forked from angular/angular
/
ifs.ts
262 lines (212 loc) · 9.98 KB
/
ifs.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
/**
* @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 {visitAll} from '@angular/compiler';
import {ElementCollector, ElementToMigrate, MigrateError, Result} from './types';
import {calculateNesting, getMainBlock, getOriginals, hasLineBreaks, parseTemplate, reduceNestingOffset} from './util';
export const ngif = '*ngIf';
export const boundngif = '[ngIf]';
export const nakedngif = 'ngIf';
const ifs = [
ngif,
nakedngif,
boundngif,
];
/**
* Replaces structural directive ngif instances with new if.
* Returns null if the migration failed (e.g. there was a syntax error).
*/
export function migrateIf(template: string):
{migrated: string, errors: MigrateError[], changed: boolean} {
let errors: MigrateError[] = [];
let parsed = parseTemplate(template);
if (parsed === null) {
return {migrated: template, errors, changed: false};
}
let result = template;
const visitor = new ElementCollector(ifs);
visitAll(visitor, parsed.rootNodes);
calculateNesting(visitor, hasLineBreaks(template));
// this tracks the character shift from different lengths of blocks from
// the prior directives so as to adjust for nested block replacement during
// migration. Each block calculates length differences and passes that offset
// to the next migrating block to adjust character offsets properly.
let offset = 0;
let nestLevel = -1;
let postOffsets: number[] = [];
for (const el of visitor.elements) {
let migrateResult: Result = {tmpl: result, offsets: {pre: 0, post: 0}};
// applies the post offsets after closing
offset = reduceNestingOffset(el, nestLevel, offset, postOffsets);
try {
migrateResult = migrateNgIf(el, result, offset);
} catch (error: unknown) {
errors.push({type: ngif, error});
}
result = migrateResult.tmpl;
offset += migrateResult.offsets.pre;
postOffsets.push(migrateResult.offsets.post);
nestLevel = el.nestCount;
}
const changed = visitor.elements.length > 0;
return {migrated: result, errors, changed};
}
function migrateNgIf(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const matchThen = etm.attr.value.match(/[^\w\d];?\s*then/gm);
const matchElse = etm.attr.value.match(/[^\w\d];?\s*else/gm);
if (etm.thenAttr !== undefined || etm.elseAttr !== undefined) {
// bound if then / if then else
return buildBoundIfElseBlock(etm, tmpl, offset);
} else if (matchThen && matchThen.length > 0 && matchElse && matchElse.length > 0) {
// then else
return buildStandardIfThenElseBlock(etm, tmpl, matchThen[0], matchElse![0], offset);
} else if (matchThen && matchThen.length > 0) {
// just then
return buildStandardIfThenBlock(etm, tmpl, matchThen[0], offset);
} else if ((matchElse && matchElse.length > 0)) {
// just else
return buildStandardIfElseBlock(etm, tmpl, matchElse![0], offset);
}
return buildIfBlock(etm, tmpl, offset);
}
function buildIfBlock(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const aliasAttrs = etm.aliasAttrs!;
const aliases = [...aliasAttrs.aliases.keys()];
if (aliasAttrs.item) {
aliases.push(aliasAttrs.item);
}
// includes the mandatory semicolon before as
const lbString = etm.hasLineBreaks ? '\n' : '';
let condition = etm.attr.value
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
if (aliases.length > 1 || (aliases.length === 1 && condition.indexOf('; as') > -1)) {
// only 1 alias allowed
throw new Error(
'Found more than one alias on your ngIf. Remove one of them and re-run the migration.');
} else if (aliases.length === 1) {
condition += `; as ${aliases[0]}`;
}
const originals = getOriginals(etm, tmpl, offset);
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `@if (${condition}) {${lbString}${start}`;
const endBlock = `${end}${lbString}}`;
const ifBlock = startBlock + middle + endBlock;
const updatedTmpl = tmpl.slice(0, etm.start(offset)) + ifBlock + tmpl.slice(etm.end(offset));
// this should be the difference between the starting element up to the start of the closing
// element and the mainblock sans }
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - endBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
function buildStandardIfElseBlock(
etm: ElementToMigrate, tmpl: string, elseString: string, offset: number): Result {
// includes the mandatory semicolon before as
const condition = etm.getCondition()
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
const elsePlaceholder = `θ${etm.getTemplateName(elseString)}δ`;
return buildIfElseBlock(etm, tmpl, condition, elsePlaceholder, offset);
}
function buildBoundIfElseBlock(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const aliasAttrs = etm.aliasAttrs!;
const aliases = [...aliasAttrs.aliases.keys()];
if (aliasAttrs.item) {
aliases.push(aliasAttrs.item);
}
// includes the mandatory semicolon before as
let condition = etm.attr.value.replace(' as ', '; as ');
if (aliases.length > 1 || (aliases.length === 1 && condition.indexOf('; as') > -1)) {
// only 1 alias allowed
throw new Error(
'Found more than one alias on your ngIf. Remove one of them and re-run the migration.');
} else if (aliases.length === 1) {
condition += `; as ${aliases[0]}`;
}
const elsePlaceholder = `θ${etm.elseAttr!.value.trim()}δ`;
if (etm.thenAttr !== undefined) {
const thenPlaceholder = `θ${etm.thenAttr!.value.trim()}δ`;
return buildIfThenElseBlock(etm, tmpl, condition, thenPlaceholder, elsePlaceholder, offset);
}
return buildIfElseBlock(etm, tmpl, condition, elsePlaceholder, offset);
}
function buildIfElseBlock(
etm: ElementToMigrate, tmpl: string, condition: string, elsePlaceholder: string,
offset: number): Result {
const lbString = etm.hasLineBreaks ? '\n' : '';
const originals = getOriginals(etm, tmpl, offset);
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `@if (${condition}) {${lbString}${start}`;
const elseBlock = `${end}${lbString}} @else {${lbString}`;
const postBlock = elseBlock + elsePlaceholder + `${lbString}}`;
const ifElseBlock = startBlock + middle + postBlock;
const tmplStart = tmpl.slice(0, etm.start(offset));
const tmplEnd = tmpl.slice(etm.end(offset));
const updatedTmpl = tmplStart + ifElseBlock + tmplEnd;
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - postBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
function buildStandardIfThenElseBlock(
etm: ElementToMigrate, tmpl: string, thenString: string, elseString: string,
offset: number): Result {
// includes the mandatory semicolon before as
const condition = etm.getCondition()
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
const thenPlaceholder = `θ${etm.getTemplateName(thenString, elseString)}δ`;
const elsePlaceholder = `θ${etm.getTemplateName(elseString)}δ`;
return buildIfThenElseBlock(etm, tmpl, condition, thenPlaceholder, elsePlaceholder, offset);
}
function buildStandardIfThenBlock(
etm: ElementToMigrate, tmpl: string, thenString: string, offset: number): Result {
// includes the mandatory semicolon before as
const condition = etm.getCondition()
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
const thenPlaceholder = `θ${etm.getTemplateName(thenString)}δ`;
return buildIfThenBlock(etm, tmpl, condition, thenPlaceholder, offset);
}
function buildIfThenElseBlock(
etm: ElementToMigrate, tmpl: string, condition: string, thenPlaceholder: string,
elsePlaceholder: string, offset: number): Result {
const lbString = etm.hasLineBreaks ? '\n' : '';
const originals = getOriginals(etm, tmpl, offset);
const startBlock = `@if (${condition}) {${lbString}`;
const elseBlock = `${lbString}} @else {${lbString}`;
const postBlock = thenPlaceholder + elseBlock + elsePlaceholder + `${lbString}}`;
const ifThenElseBlock = startBlock + postBlock;
const tmplStart = tmpl.slice(0, etm.start(offset));
const tmplEnd = tmpl.slice(etm.end(offset));
const updatedTmpl = tmplStart + ifThenElseBlock + tmplEnd;
// We ignore the contents of the element on if then else.
// If there's anything there, we need to account for the length in the offset.
const pre = originals.start.length + originals.childLength - startBlock.length;
const post = originals.end.length - postBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
function buildIfThenBlock(
etm: ElementToMigrate, tmpl: string, condition: string, thenPlaceholder: string,
offset: number): Result {
const lbString = etm.hasLineBreaks ? '\n' : '';
const originals = getOriginals(etm, tmpl, offset);
const startBlock = `@if (${condition}) {${lbString}`;
const postBlock = thenPlaceholder + `${lbString}}`;
const ifThenBlock = startBlock + postBlock;
const tmplStart = tmpl.slice(0, etm.start(offset));
const tmplEnd = tmpl.slice(etm.end(offset));
const updatedTmpl = tmplStart + ifThenBlock + tmplEnd;
// We ignore the contents of the element on if then else.
// If there's anything there, we need to account for the length in the offset.
const pre = originals.start.length + originals.childLength - startBlock.length;
const post = originals.end.length - postBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}