forked from huang12zheng/Dart-Data-Class-Generator
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathextension.js
More file actions
2641 lines (2262 loc) · 80.3 KB
/
extension.js
File metadata and controls
2641 lines (2262 loc) · 80.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
var projectName = '';
var isFlutter = false;
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
context.subscriptions.push(
vscode.commands.registerCommand(
'dart_data_class.generate.from_props',
generateDataClass
)
);
context.subscriptions.push(
vscode.commands.registerCommand(
'dart_data_class.generate.from_json',
generateJsonDataClass
)
);
context.subscriptions.push(vscode.languages.registerCodeActionsProvider({
language: 'dart',
scheme: 'file'
}, new DataClassCodeActions(), {
providedCodeActionKinds: [
vscode.CodeActionKind.QuickFix
],
}));
findProjectName();
}
async function findProjectName() {
const pubspecs = await vscode.workspace.findFiles('pubspec.yaml');
if (pubspecs != null && pubspecs.length > 0) {
const pubspec = pubspecs[0];
const content = fs.readFileSync(pubspec.fsPath, 'utf8');
if (content != null && content.includes('name: ')) {
isFlutter = content.includes('flutter:') && content.includes('sdk: flutter');
for (const line of content.split('\n')) {
if (line.startsWith('name: ')) {
projectName = line.replace('name:', '').trim();
break;
}
}
}
}
}
async function generateJsonDataClass() {
let langId = getLangId();
if (langId == 'dart') {
let document = getDocText();
const name = await vscode.window.showInputBox({
placeHolder: 'Please type in a class name.'
});
if (name == null || name.length == 0) {
return;
}
let reader = new JsonReader(document, name);
let seperate = true;
if (await reader.error == null) {
if (reader.files.length >= 2) {
const setting = readSetting('json.seperate');
if (setting == 'ask') {
const r = await vscode.window.showQuickPick(['Yes', 'No'], {
canPickMany: false,
placeHolder: 'Do you wish to seperate the JSON into multiple files?'
});
if (r != null) {
seperate = r == 'Yes';
} else {
return;
}
} else {
seperate = setting == 'seperate';
}
}
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
cancellable: false
}, async function (progress, token) {
progress.report({ increment: 0, message: 'Generating Data Classes...' });
scrollTo(0);
await reader.commitJson(progress, seperate);
clearSelection();
});
} else {
showError(await reader.error);
}
} else if (langId == 'json') {
showError('Please paste the JSON directly into an empty .dart file and then try again!');
} else {
showError('Make sure that you\'re editing a dart file and then try again!');
}
}
async function generateDataClass(text = getDocText()) {
if (getLangId() == 'dart') {
const generator = new DataClassGenerator(text);
let clazzes = generator.clazzes;
if (clazzes.length == 0) {
showError('No convertable dart classes were detected!');
return null;
} else if (clazzes.length >= 2) {
// Show a prompt if there is more than one class in the current editor.
clazzes = await showClassChooser(clazzes);
if (clazzes == null) {
showInfo('No classes selected!');
return;
}
}
for (let clazz of clazzes) {
if (clazz.isValid && clazz.toReplace.length > 0) {
if (readSetting('override.manual')) {
// When manual overriding is activated ask for every override.
let result = [];
for (let replacement of clazz.toReplace) {
const r = await vscode.window.showQuickPick(['Yes', 'No'], {
placeHolder: `Do you want to override ${replacement.name}?`,
canPickMany: false
});
if (r == null) {
showInfo('Canceled!');
return;
} else if ('Yes' == r) result.push(replacement);
}
clazz.toReplace = result;
}
}
}
console.log(clazzes);
const edit = getReplaceEdit(clazzes, generator.imports, true);
await vscode.workspace.applyEdit(edit);
clearSelection();
return clazzes;
} else {
showError('Make sure that you\'re editing a dart file and then try again!');
return null;
}
}
/**
* @param {DartClass[]} clazzez
*/
async function showClassChooser(clazzez) {
const values = clazzez.map((v) => v.name);
const r = await vscode.window.showQuickPick(values, {
placeHolder: 'Please select the classes you want to generate data classes of.',
canPickMany: true,
});
let result = [];
if (r != null && r.length > 0) {
for (let c of r) {
for (let clazz of clazzez) {
if (clazz.name == c)
result.push(clazz);
}
}
} else return null;
return result;
}
class DartClass {
constructor() {
/** @type {string} */
this.name = null;
/** @type {string} */
this.fullGenericType = '';
/** @type {string} */
this.superclass = null;
/** @type {string[]} */
this.interfaces = [];
/** @type {string[]} */
this.mixins = [];
/** @type {string} */
this.constr = null;
/** @type {ClassField[]} */
this.properties = [];
/** @type {number} */
this.startsAtLine = null;
/** @type {number} */
this.endsAtLine = null;
/** @type {number} */
this.constrStartsAtLine = null;
/** @type {number} */
this.constrEndsAtLine = null;
this.constrDifferent = false;
this.isArray = false;
this.classContent = '';
this.toInsert = '';
/** @type {ClassPart[]} */
this.toReplace = [];
this.isLastInFile = false;
}
get type() {
return this.name + this.genericType;
}
get genericType() {
const parts = this.fullGenericType.split(',');
return parts.map((type) => {
let part = type.trim();
if (part.includes('extends')) {
part = part.substring(0, part.indexOf('extends')).trim();
if (type === parts[parts.length - 1]) {
part += '>';
}
}
return part;
}).join(', ');
}
get propsEndAtLine() {
if (this.properties.length > 0) {
return this.properties[this.properties.length - 1].line;
} else {
return -1;
}
}
get hasSuperclass() {
return this.superclass != null;
}
get classDetected() {
return this.startsAtLine != null;
}
get didChange() {
return this.toInsert.length > 0 || this.toReplace.length > 0 || this.constrDifferent;
}
get hasNamedConstructor() {
if (this.constr != null) {
return this.constr.replace('const', '').trimLeft().startsWith(this.name + '({');
}
return true;
}
get hasConstructor() {
return this.constrStartsAtLine != null && this.constrEndsAtLine != null && this.constr != null;
}
get hasMixins() {
return this.mixins != null && this.mixins.length > 0;
}
get hasInterfaces() {
return this.interfaces != null && this.interfaces.length > 0;
}
get hasEnding() {
return this.endsAtLine != null;
}
get hasProperties() {
return this.properties.length > 0;
}
get fewProps() {
return this.properties.length <= 3;
}
get isValid() {
return this.classDetected && this.hasEnding && this.hasProperties && this.uniquePropNames;
}
get isWidget() {
return this.superclass != null && (this.superclass == 'StatelessWidget' || this.superclass == 'StatefulWidget');
}
get isStatelessWidget() {
return this.isWidget && this.superclass != null && this.superclass == 'StatelessWidget';
}
get isState() {
return !this.isWidget && this.superclass != null && this.superclass.startsWith('State<');
}
get isAbstract() {
return this.classContent.trimLeft().startsWith('abstract class');
}
get usesEquatable() {
return (this.hasSuperclass && this.superclass == 'Equatable') || (this.hasMixins && this.mixins.includes('EquatableMixin'));
}
get issue() {
const def = this.name + ' couldn\'t be converted to a data class: '
let msg = def;
if (!this.hasProperties) {
msg += 'Class must have at least one property!';
} else if (!this.hasEnding) {
msg += 'Class has no ending!';
} else if (!this.uniquePropNames) {
msg += 'Class doesn\'t have unique property names!';
} else {
msg = removeEnd(msg, ': ') + '.';
}
return msg;
}
get uniquePropNames() {
let props = [];
for (let p of this.properties) {
const n = p.name;
if (props.includes(n))
return false;
props.push(n);
}
return true;
}
/**
* @param {number} line
*/
replacementAtLine(line) {
for (let part of this.toReplace) {
if (part.startsAt <= line && part.endsAt >= line) {
return part.replacement;
}
}
return null;
}
generateClassReplacement() {
let replacement = '';
let lines = this.classContent.split('\n');
for (let i = this.endsAtLine - this.startsAtLine; i >= 0; i--) {
let line = lines[i] + '\n';
let l = this.startsAtLine + i;
if (i == 0) {
const classType = this.isAbstract ? 'abstract class' : 'class';
let classDeclaration = classType + ' ' + this.name + this.fullGenericType;
if (this.superclass != null) {
classDeclaration += ' extends ' + this.superclass;
}
/**
* @param {string[]} list
* @param {string} keyword
*/
function addSuperTypes(list, keyword) {
if (list.length == 0) return;
const length = list.length;
classDeclaration += ` ${keyword} `;
for (let x = 0; x < length; x++) {
const isLast = x == length - 1;
const type = list[x];
classDeclaration += type;
if (!isLast) {
classDeclaration += ', ';
}
}
}
addSuperTypes(this.mixins, 'with');
addSuperTypes(this.interfaces, 'implements');
classDeclaration += ' {\n';
replacement = classDeclaration + replacement;
} else if (l == this.propsEndAtLine && this.constr != null && !this.hasConstructor) {
replacement = this.constr + replacement;
replacement = line + replacement;
} else if (l == this.endsAtLine && this.isValid) {
replacement = line + replacement;
replacement = this.toInsert + replacement;
} else {
let rp = this.replacementAtLine(l);
if (rp != null) {
if (!replacement.includes(rp))
replacement = rp + '\n' + replacement;
} else {
replacement = line + replacement;
}
}
}
return removeEnd(replacement, '\n');
}
}
class Imports {
/**
* @param {string} text
*/
constructor(text) {
/** @type {string[]} */
this.values = [];
/** @type {number} */
this.startAtLine = null;
/** @type {number} */
this.endAtLine = null;
/** @type {string} */
this.rawImports = null;
this.text = text;
this.readImports();
}
get hasImports() {
return this.values != null && this.values.length > 0;
}
get hasExportDeclaration() {
return /^export /m.test(this.formatted);
}
get hasImportDeclaration() {
return /^import /m.test(this.formatted);
}
get hasPreviousImports() {
return this.startAtLine != null && this.endAtLine != null;
}
get didChange() {
return !areStrictEqual(this.rawImports, this.formatted);
}
get range() {
return new vscode.Range(
new vscode.Position(this.startAtLine - 1, 0),
new vscode.Position(this.endAtLine, 1),
);
}
readImports() {
this.rawImports = '';
const lines = this.text.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
const isLast = i == lines.length - 1;
if (line.startsWith('import') || line.startsWith('export') || line.startsWith('part')) {
this.values.push(line);
this.rawImports += `${line}\n`;
if (this.startAtLine == null) {
this.startAtLine = i + 1;
}
if (isLast) {
this.endAtLine = i + 1;
break;
}
} else {
const isLicenseComment = line.startsWith('//') && this.values.length == 0;
const didEnd = !(isBlank(line) || line.startsWith('library') || isLicenseComment);
if (isLast || didEnd) {
if (this.startAtLine != null) {
if (i > 0 && isBlank(lines[i - 1])) {
this.endAtLine = i - 1;
} else {
this.endAtLine = i;
}
}
break;
}
}
}
}
get formatted() {
if (!this.hasImports) return '';
let workspace = projectName;
if (workspace == null || workspace.length == 0) {
const file = getEditor().document.uri;
if (file.scheme === 'file') {
const folder = vscode.workspace.getWorkspaceFolder(file);
if (folder) {
workspace = path.basename(folder.uri.fsPath).replace('-', '_');
}
}
}
const dartImports = [];
const packageImports = [];
const packageLocalImports = [];
const relativeImports = [];
const partStatements = [];
const exports = [];
for (let imp of this.values) {
if (imp.startsWith('export')) {
exports.push(imp);
} else if (imp.startsWith('part')) {
partStatements.push(imp);
} else if (imp.includes('dart:')) {
dartImports.push(imp);
} else if (workspace != null && imp.includes(`package:${workspace}`)) {
packageLocalImports.push(imp);
} else if (imp.includes('package:')) {
packageImports.push(imp);
} else {
relativeImports.push(imp);
}
}
let imps = '';
/**
* @param {any[]} imports
*/
function addImports(imports) {
imports.sort();
for (let i = 0; i < imports.length; i++) {
const isLast = i == imports.length - 1;
const imp = imports[i];
imps += imp + '\n';
if (isLast) {
imps += '\n';
}
}
}
addImports(dartImports);
addImports(packageImports);
addImports(packageLocalImports);
addImports(relativeImports);
addImports(exports);
addImports(partStatements);
return removeEnd(imps, '\n');
}
/**
* @param {string} imp
*/
includes(imp) {
return this.values.includes(imp);
}
/**
* @param {string} imp
*/
push(imp) {
return this.values.push(imp);
}
/**
* @param {string[]} imps
*/
hastAtLeastOneImport(imps) {
for (let imp of imps) {
const impt = `import '${imp}';`;
if (this.text.includes(impt) || this.includes(impt))
return true;
}
return false;
}
/**
* @param {string} imp
* @param {string[]} validOverrides
*/
requiresImport(imp, validOverrides = []) {
const formattedImport = !imp.startsWith('import') ? "import '" + imp + "';" : imp;
if (!this.includes(formattedImport) && !this.hastAtLeastOneImport(validOverrides)) {
this.values.push(formattedImport);
}
}
}
class ClassField {
/**
* @param {String} type
* @param {String} name
* @param {number} line
* @param {boolean} isFinal
* @param {boolean} isConst
*/
constructor(type, name, line = 1, isFinal = true, isConst = false, json = false) {
this.rawType = type;
this.name = toVarName(name);
this.key = json ? name : varToKey(this.name);
if (readSetting('capitalize.enabled')) this.key = capitalize(this.key);
this.line = line;
this.isFinal = isFinal;
this.isConst = isConst;
this.isEnum = false;
this.isCollectionType = (/** @type {string} */ type) => this.rawType == type || this.rawType.startsWith(type + '<');
}
get type() {
return this.isNullable ? removeEnd(this.rawType, '?') : this.rawType;
}
get isNullable() {
return this.rawType.endsWith('?');
}
get isList() {
return this.isCollectionType('List');
}
get isMap() {
return this.isCollectionType('Map');
}
get isSet() {
return this.isCollectionType('Set');
}
get isCollection() {
return this.isList || this.isMap || this.isSet;
}
get collectionType() {
if (this.isList || this.isSet) {
const collection = this.isSet ? 'Set' : 'List';
const type = this.rawType == collection ? 'dynamic' : this.rawType.replace(collection + '<', '').replace('>', '');
return new ClassField(type, this.name, this.line, this.isFinal);
}
return this;
}
get isPrimitive() {
let t = this.collectionType.type;
return t == 'String' || t == 'num' || t == 'dynamic' || t == 'bool' || this.isDouble || this.isInt || this.isMap;
}
get isPrivate() {
return this.name.startsWith('_');
}
get defValue() {
if (this.isList) {
return 'const []';
} else if (this.isMap || this.isSet) {
return 'const {}';
} else {
switch (this.type) {
case 'String': return "''";
case 'num':
case 'int': return "0";
case 'double': return "0.0";
case 'bool': return 'false';
case 'dynamic': return "null";
default: return `${this.type}()`;
}
}
}
get isInt() {
return this.collectionType.type == 'int';
}
get isDouble() {
return this.collectionType.type == 'double';
}
}
class ClassPart {
/**
* @param {string} name
* @param {number} startsAt
* @param {number} endsAt
* @param {string} current
* @param {string} replacement
*/
constructor(name, startsAt = null, endsAt = null, current = null, replacement = null) {
this.name = name;
this.startsAt = startsAt;
this.endsAt = endsAt;
this.current = current;
this.replacement = replacement;
}
get isValid() {
return this.startsAt != null && this.endsAt != null && this.current != null;
}
get startPos() {
return new vscode.Position(this.startsAt, 0);
}
get endPos() {
return new vscode.Position(this.endsAt, 0);
}
}
class DataClassGenerator {
/**
* @param {String} text
* @param {DartClass[]} clazzes
* @param {boolean} fromJSON
* @param {string} part
*/
constructor(text, clazzes = null, fromJSON = false, part = null) {
this.text = text;
this.fromJSON = fromJSON;
this.clazzes = clazzes == null ? this.parseAndReadClasses() : clazzes;
this.imports = new Imports(text);
this.part = part;
this.generateDataClazzes();
this.clazz = null;
}
get hasImports() {
return this.imports.hasImports;
}
/**
* @param {string} imp
* @param {string[]} validOverrides
*/
requiresImport(imp, validOverrides = []) {
this.imports.requiresImport(imp, validOverrides);
}
/**
* @param {string} part
*/
isPartSelected(part) {
return this.part == null || this.part == part;
}
generateDataClazzes() {
const insertConstructor = readSetting('constructor.enabled') && this.isPartSelected('constructor');
for (let clazz of this.clazzes) {
this.clazz = clazz;
if (insertConstructor)
this.insertConstructor(clazz);
if (!clazz.isWidget) {
if (!clazz.isAbstract) {
if (readSetting('copyWith.enabled') && this.isPartSelected('copyWith'))
this.insertCopyWith(clazz);
if (readSetting('toMap.enabled') && this.isPartSelected('serialization'))
this.insertToMap(clazz, readSetting('toMap.hideNull'));
if (readSetting('fromMap.enabled') && this.isPartSelected('serialization'))
this.insertFromMap(clazz);
if (readSetting('toJson.enabled') && this.isPartSelected('serialization'))
this.insertToJson(clazz);
if (readSetting('fromJson.enabled') && this.isPartSelected('serialization'))
this.insertFromJson(clazz);
}
if (readSetting('toString.enabled') && this.isPartSelected('toString'))
this.insertToString(clazz);
if ((clazz.usesEquatable || readSetting('useEquatable')) && this.isPartSelected('useEquatable')) {
this.insertEquatable(clazz);
} else {
if (readSetting('equality.enabled') && this.isPartSelected('equality'))
this.insertEquality(clazz);
if (readSetting('hashCode.enabled') && this.isPartSelected('equality'))
this.insertHash(clazz);
}
}
}
}
/**
* @param {string} name
* @param {string} finder
* @param {DartClass} clazz
*/
findPart(name, finder, clazz) {
const normalize = (/** @type {string} */ src) => {
let result = '';
let generics = 0;
let prevChar = '';
for (const char of src) {
if (char == '<') generics++;
if (char != ' ' && generics == 0) {
result += char;
}
if (prevChar != '=' && char == '>') generics--;
prevChar = char;
}
return result;
}
const finderString = normalize(finder);
const lines = clazz.classContent.split('\n');
const part = new ClassPart(name);
let curlies = 0;
let singleLine = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineNum = clazz.startsAtLine + i;
curlies += count(line, '{');
curlies -= count(line, '}');
if (part.startsAt == null && normalize(line).startsWith(finderString)) {
if (line.includes('=>')) singleLine = true;
if (curlies == 2 || singleLine) {
part.startsAt = lineNum;
part.current = line + '\n';
}
} else if (part.startsAt != null && part.endsAt == null && (curlies >= 2 || singleLine)) {
part.current += line + '\n';
} else if (part.startsAt != null && part.endsAt == null && curlies == 1) {
part.endsAt = lineNum;
part.current += line;
}
// Detect the end of a single line function by searching for the ';' because
// a single line function doesn't necessarily only have one single line.
if (singleLine && part.startsAt != null && part.endsAt == null && line.trimRight().endsWith(';')) {
part.endsAt = lineNum;
}
}
return part.isValid ? part : null;
}
/**
* If class already exists and has a constructor with the parameter, reuse that parameter.
* E.g. when the dev changed the parameter from this.x to this.x = y the generator inserts
* this.x = y. This way the generator can preserve changes made in the constructor.
* @param {ClassField | string} prop
* @param {{ "name": string; "text": string; "isThis": boolean; }[]} oldProps
*/
findConstrParameter(prop, oldProps) {
const name = typeof prop === 'string' ? prop : prop.name;
for (let oldProp of oldProps) {
if (name === oldProp.name) {
return oldProp;
}
}
return null;
}
/**
* @param {DartClass} clazz
*/
findOldConstrProperties(clazz) {
if (!clazz.hasConstructor || clazz.constrStartsAtLine == clazz.constrEndsAtLine) {
return [];
}
let oldConstr = '';
let brackets = 0;
let didFindConstr = false;
for (let c of clazz.constr) {
if (c == '(') {
if (didFindConstr) oldConstr += c;
brackets++;
didFindConstr = true;
continue;
} else if (c == ')') {
brackets--;
if (didFindConstr && brackets == 0)
break;
}
if (brackets >= 1)
oldConstr += c;
}
oldConstr = removeStart(oldConstr, ['{', '[']);
oldConstr = removeEnd(oldConstr, ['}', ']']);
let oldArguments = oldConstr.split('\n');
const oldProperties = [];
for (let arg of oldArguments) {
let formatted = arg.replace('required', '').trim();
if (formatted.indexOf('=') != -1) {
formatted = formatted.substring(0, formatted.indexOf('=')).trim();
}
let name = null;
let isThis = false;
if (formatted.startsWith('this.')) {
name = formatted.replace('this.', '');
isThis = true;
} else {
const words = formatted.split(' ');
if (words.length >= 1) {
const w = words[1];
if (!isBlank(w)) name = w;
}
}
if (name != null) {
oldProperties.push({
"name": removeEnd(name.trim(), ','),
"text": arg.trim() + '\n',
"isThis": isThis,
});
}
}
return oldProperties;
}
/**
* @param {DartClass} clazz
*/
insertConstructor(clazz) {
const withDefaults = readSetting('constructor.default_values');
let constr = '';
let startBracket = '({';
let endBracket = '})';
if (clazz.constr != null) {
if (clazz.constr.trimLeft().startsWith('const'))
constr += 'const ';
// Detect custom constructor brackets and preserve them.
const fConstr = clazz.constr.replace('const', '').trimLeft();
if (fConstr.startsWith(clazz.name + '([')) startBracket = '([';
else if (fConstr.startsWith(clazz.name + '({')) startBracket = '({';
else startBracket = '(';
if (fConstr.includes('])')) endBracket = '])';
else if (fConstr.includes('})')) endBracket = '})';
else endBracket = ')';
} else {
if (clazz.isWidget)
constr += 'const ';
}
constr += clazz.name + startBracket + '\n';
// Add 'Key key,' for widgets in constructor.
if (clazz.isWidget) {
let hasKey = false;
let clazzConstr = clazz.constr || '';
for (let line of clazzConstr.split('\n')) {
if (line.trim().startsWith('Key? key')) {
hasKey = true;
break;
}
}
if (!hasKey)
constr += ' Key? key,\n';
}
const oldProperties = this.findOldConstrProperties(clazz);
for (let prop of oldProperties) {
if (!prop.isThis) {
constr += ' ' + prop.text;
}
}
for (let prop of clazz.properties) {
const oldProperty = this.findConstrParameter(prop, oldProperties);
if (oldProperty != null) {
if (oldProperty.isThis)
constr += ' ' + oldProperty.text;
continue;
}
const parameter = `this.${prop.name}`
constr += ' ';
if (!prop.isNullable) {
const hasDefault = withDefaults && ((prop.isPrimitive || prop.isCollection) && prop.rawType != 'dynamic');
const isNamedConstr = startBracket == '({' && endBracket == '})';