/
types.ts
399 lines (349 loc) Β· 11.2 KB
/
types.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Attribute, Element, RecursiveVisitor, Text} from '@angular/compiler';
import ts from 'typescript';
export const ngtemplate = 'ng-template';
export const boundngifelse = '[ngIfElse]';
export const boundngifthenelse = '[ngIfThenElse]';
export const boundngifthen = '[ngIfThen]';
export const nakedngfor = 'ngFor';
function allFormsOf(selector: string): string[] {
return [
selector,
`*${selector}`,
`[${selector}]`,
];
}
const commonModuleDirectives = new Set([
...allFormsOf('ngComponentOutlet'),
...allFormsOf('ngTemplateOutlet'),
...allFormsOf('ngClass'),
...allFormsOf('ngPlural'),
...allFormsOf('ngPluralCase'),
...allFormsOf('ngStyle'),
...allFormsOf('ngTemplateOutlet'),
...allFormsOf('ngComponentOutlet'),
'[NgForOf]',
'[NgForTrackBy]',
'[ngIfElse]',
'[ngIfThenElse]',
]);
function pipeMatchRegExpFor(name: string): RegExp {
return new RegExp(`\\|\\s*${name}`);
}
const commonModulePipes = [
'date',
'async',
'currency',
'number',
'i18nPlural',
'i18nSelect',
'json',
'keyvalue',
'slice',
'lowercase',
'uppercase',
'titlecase',
'percent',
'titlecase',
].map(name => pipeMatchRegExpFor(name));
/**
* Represents a range of text within a file. Omitting the end
* means that it's until the end of the file.
*/
type Range = {
start: number,
end?: number, node: ts.Node, type: string,
};
export type Offsets = {
pre: number,
post: number,
};
export type Result = {
tmpl: string,
offsets: Offsets,
};
export interface ForAttributes {
forOf: string;
trackBy: string;
}
export interface AliasAttributes {
item: string;
aliases: Map<string, string>;
}
/**
* Represents an error that happened during migration
*/
export type MigrateError = {
type: string,
error: unknown,
};
/**
* Represents an element with a migratable attribute
*/
export class ElementToMigrate {
el: Element;
attr: Attribute;
elseAttr: Attribute|undefined;
thenAttr: Attribute|undefined;
forAttrs: ForAttributes|undefined;
aliasAttrs: AliasAttributes|undefined;
nestCount = 0;
hasLineBreaks = false;
constructor(
el: Element, attr: Attribute, elseAttr: Attribute|undefined = undefined,
thenAttr: Attribute|undefined = undefined, forAttrs: ForAttributes|undefined = undefined,
aliasAttrs: AliasAttributes|undefined = undefined) {
this.el = el;
this.attr = attr;
this.elseAttr = elseAttr;
this.thenAttr = thenAttr;
this.forAttrs = forAttrs;
this.aliasAttrs = aliasAttrs;
}
getCondition(): string {
const chunks = this.attr.value.split(';');
let condition = chunks[0];
// checks for case of no usage of `;` in if else / if then else
const elseIx = condition.indexOf(' else ');
const thenIx = condition.indexOf(' then ');
if (thenIx > -1) {
condition = condition.slice(0, thenIx);
} else if (elseIx > -1) {
condition = condition.slice(0, elseIx);
}
let letVar = chunks.find(c => c.search(/\s*let\s/) > -1);
return condition + (letVar ? ';' + letVar : '');
}
getTemplateName(targetStr: string, secondStr?: string): string {
const targetLocation = this.attr.value.indexOf(targetStr);
const secondTargetLocation = secondStr ? this.attr.value.indexOf(secondStr) : undefined;
let templateName =
this.attr.value.slice(targetLocation + targetStr.length, secondTargetLocation);
if (templateName.startsWith(':')) {
templateName = templateName.slice(1).trim();
}
return templateName.split(';')[0].trim();
}
getValueEnd(offset: number): number {
return (this.attr.valueSpan ? (this.attr.valueSpan.end.offset + 1) :
this.attr.keySpan!.end.offset) -
offset;
}
hasChildren(): boolean {
return this.el.children.length > 0;
}
getChildSpan(offset: number): {childStart: number, childEnd: number} {
const childStart = this.el.children[0].sourceSpan.start.offset - offset;
const childEnd = this.el.children[this.el.children.length - 1].sourceSpan.end.offset - offset;
return {childStart, childEnd};
}
shouldRemoveElseAttr(): boolean {
return (this.el.name === 'ng-template' || this.el.name === 'ng-container') &&
this.elseAttr !== undefined;
}
getElseAttrStr(): string {
if (this.elseAttr !== undefined) {
const elseValStr = this.elseAttr.value !== '' ? `="${this.elseAttr.value}"` : '';
return `${this.elseAttr.name}${elseValStr}`;
}
return '';
}
start(offset: number): number {
return this.el.sourceSpan?.start.offset - offset;
}
end(offset: number): number {
return this.el.sourceSpan?.end.offset - offset;
}
length(): number {
return this.el.sourceSpan?.end.offset - this.el.sourceSpan?.start.offset;
}
}
/**
* Represents an ng-template inside a template being migrated to new control flow
*/
export class Template {
el: Element;
name: string;
count: number = 0;
contents: string = '';
children: string = '';
i18n: Attribute|null = null;
attributes: Attribute[];
constructor(el: Element, name: string, i18n: Attribute|null) {
this.el = el;
this.name = name;
this.attributes = el.attrs;
this.i18n = i18n;
}
get isNgTemplateOutlet() {
return this.attributes.find(attr => attr.name === '*ngTemplateOutlet') !== undefined;
}
get outletContext() {
const letVar = this.attributes.find(attr => attr.name.startsWith('let-'));
return letVar ? `; context: {$implicit: ${letVar.name.split('-')[1]}}` : '';
}
generateTemplateOutlet() {
const attr = this.attributes.find(attr => attr.name === '*ngTemplateOutlet');
const outletValue = attr?.value ?? this.name.slice(1);
return `<ng-container *ngTemplateOutlet="${outletValue}${this.outletContext}"></ng-container>`;
}
generateContents(tmpl: string) {
this.contents = tmpl.slice(this.el.sourceSpan.start.offset, this.el.sourceSpan.end.offset);
this.children = '';
if (this.el.children.length > 0) {
this.children = tmpl.slice(
this.el.children[0].sourceSpan.start.offset,
this.el.children[this.el.children.length - 1].sourceSpan.end.offset);
}
}
}
/** Represents a file that was analyzed by the migration. */
export class AnalyzedFile {
private ranges: Range[] = [];
removeCommonModule = false;
canRemoveImports = false;
sourceFilePath: string = '';
/** Returns the ranges in the order in which they should be migrated. */
getSortedRanges(): Range[] {
// templates first for checking on whether certain imports can be safely removed
const templateRanges = this.ranges.slice()
.filter(x => x.type !== 'import')
.sort((aStart, bStart) => bStart.start - aStart.start);
const importRanges = this.ranges.slice()
.filter(x => x.type === 'import')
.sort((aStart, bStart) => bStart.start - aStart.start);
return [...templateRanges, ...importRanges];
}
/**
* Adds a text range to an `AnalyzedFile`.
* @param path Path of the file.
* @param analyzedFiles Map keeping track of all the analyzed files.
* @param range Range to be added.
*/
static addRange(
path: string, sourceFilePath: string, analyzedFiles: Map<string, AnalyzedFile>,
range: Range): void {
let analysis = analyzedFiles.get(path);
if (!analysis) {
analysis = new AnalyzedFile();
analysis.sourceFilePath = sourceFilePath;
analyzedFiles.set(path, analysis);
}
const duplicate =
analysis.ranges.find(current => current.start === range.start && current.end === range.end);
if (!duplicate) {
analysis.ranges.push(range);
}
}
}
/** Finds all non-control flow elements from common module. */
export class CommonCollector extends RecursiveVisitor {
count = 0;
override visitElement(el: Element): void {
if (el.attrs.length > 0) {
for (const attr of el.attrs) {
if (this.hasDirectives(attr.name) || this.hasPipes(attr.value)) {
this.count++;
}
}
}
super.visitElement(el, null);
}
override visitText(ast: Text) {
if (this.hasPipes(ast.value)) {
this.count++;
}
}
private hasDirectives(input: string): boolean {
return commonModuleDirectives.has(input);
}
private hasPipes(input: string): boolean {
return commonModulePipes.some(regexp => regexp.test(input));
}
}
/** Finds all elements with ngif structural directives. */
export class ElementCollector extends RecursiveVisitor {
readonly elements: ElementToMigrate[] = [];
constructor(private _attributes: string[] = []) {
super();
}
override visitElement(el: Element): void {
if (el.attrs.length > 0) {
for (const attr of el.attrs) {
if (this._attributes.includes(attr.name)) {
const elseAttr = el.attrs.find(x => x.name === boundngifelse);
const thenAttr =
el.attrs.find(x => x.name === boundngifthenelse || x.name === boundngifthen);
const forAttrs = attr.name === nakedngfor ? this.getForAttrs(el) : undefined;
const aliasAttrs = this.getAliasAttrs(el);
this.elements.push(
new ElementToMigrate(el, attr, elseAttr, thenAttr, forAttrs, aliasAttrs));
}
}
}
super.visitElement(el, null);
}
private getForAttrs(el: Element): ForAttributes {
let trackBy = '';
let forOf = '';
for (const attr of el.attrs) {
if (attr.name === '[ngForTrackBy]') {
trackBy = attr.value;
}
if (attr.name === '[ngForOf]') {
forOf = attr.value;
}
}
return {forOf, trackBy};
}
private getAliasAttrs(el: Element): AliasAttributes {
const aliases = new Map<string, string>();
let item = '';
for (const attr of el.attrs) {
if (attr.name.startsWith('let-')) {
if (attr.value === '') {
// item
item = attr.name.replace('let-', '');
} else {
// alias
aliases.set(attr.name.replace('let-', ''), attr.value);
}
}
}
return {item, aliases};
}
}
/** Finds all elements with ngif structural directives. */
export class TemplateCollector extends RecursiveVisitor {
readonly elements: ElementToMigrate[] = [];
readonly templates: Map<string, Template> = new Map();
override visitElement(el: Element): void {
if (el.name === ngtemplate) {
let i18n = null;
let templateAttr = null;
for (const attr of el.attrs) {
if (attr.name === 'i18n') {
i18n = attr;
}
if (attr.name.startsWith('#')) {
templateAttr = attr;
}
}
if (templateAttr !== null && !this.templates.has(templateAttr.name)) {
this.templates.set(templateAttr.name, new Template(el, templateAttr.name, i18n));
this.elements.push(new ElementToMigrate(el, templateAttr));
} else if (templateAttr !== null) {
throw new Error(
`A duplicate ng-template name "${templateAttr.name}" was found. ` +
`The control flow migration requires unique ng-template names within a component.`);
}
}
super.visitElement(el, null);
}
}