|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | + |
| 9 | +import {visitAll} from '@angular/compiler'; |
| 10 | + |
| 11 | +import {ElementCollector, ElementToMigrate, MigrateError, Result} from './types'; |
| 12 | +import {calculateNesting, getMainBlock, getOriginals, hasLineBreaks, parseTemplate, reduceNestingOffset} from './util'; |
| 13 | + |
| 14 | +export const ngfor = '*ngFor'; |
| 15 | +export const commaSeparatedSyntax = new Map([ |
| 16 | + ['(', ')'], |
| 17 | + ['{', '}'], |
| 18 | + ['[', ']'], |
| 19 | +]); |
| 20 | +export const stringPairs = new Map([ |
| 21 | + [`"`, `"`], |
| 22 | + [`'`, `'`], |
| 23 | +]); |
| 24 | + |
| 25 | +/** |
| 26 | + * Replaces structural directive ngFor instances with new for. |
| 27 | + * Returns null if the migration failed (e.g. there was a syntax error). |
| 28 | + */ |
| 29 | +export function migrateFor(template: string): {migrated: string, errors: MigrateError[]} { |
| 30 | + let errors: MigrateError[] = []; |
| 31 | + let parsed = parseTemplate(template); |
| 32 | + if (parsed === null) { |
| 33 | + return {migrated: template, errors}; |
| 34 | + } |
| 35 | + |
| 36 | + let result = template; |
| 37 | + const visitor = new ElementCollector([ngfor]); |
| 38 | + visitAll(visitor, parsed.rootNodes); |
| 39 | + calculateNesting(visitor, hasLineBreaks(template)); |
| 40 | + |
| 41 | + // this tracks the character shift from different lengths of blocks from |
| 42 | + // the prior directives so as to adjust for nested block replacement during |
| 43 | + // migration. Each block calculates length differences and passes that offset |
| 44 | + // to the next migrating block to adjust character offsets properly. |
| 45 | + let offset = 0; |
| 46 | + let nestLevel = -1; |
| 47 | + let postOffsets: number[] = []; |
| 48 | + for (const el of visitor.elements) { |
| 49 | + let migrateResult: Result = {tmpl: result, offsets: {pre: 0, post: 0}}; |
| 50 | + // applies the post offsets after closing |
| 51 | + offset = reduceNestingOffset(el, nestLevel, offset, postOffsets); |
| 52 | + |
| 53 | + try { |
| 54 | + migrateResult = migrateNgFor(el, result, offset); |
| 55 | + } catch (error: unknown) { |
| 56 | + errors.push({type: ngfor, error}); |
| 57 | + } |
| 58 | + |
| 59 | + result = migrateResult.tmpl; |
| 60 | + offset += migrateResult.offsets.pre; |
| 61 | + postOffsets.push(migrateResult.offsets.post); |
| 62 | + nestLevel = el.nestCount; |
| 63 | + } |
| 64 | + |
| 65 | + return {migrated: result, errors}; |
| 66 | +} |
| 67 | + |
| 68 | + |
| 69 | +function migrateNgFor(etm: ElementToMigrate, tmpl: string, offset: number): Result { |
| 70 | + const aliasWithEqualRegexp = /=\s*(count|index|first|last|even|odd)/gm; |
| 71 | + const aliasWithAsRegexp = /(count|index|first|last|even|odd)\s+as/gm; |
| 72 | + const aliases = []; |
| 73 | + const lbString = etm.hasLineBreaks ? '\n' : ''; |
| 74 | + const lbSpaces = etm.hasLineBreaks ? `\n ` : ''; |
| 75 | + const parts = getNgForParts(etm.attr.value); |
| 76 | + |
| 77 | + const originals = getOriginals(etm, tmpl, offset); |
| 78 | + |
| 79 | + // first portion should always be the loop definition prefixed with `let` |
| 80 | + const condition = parts[0].replace('let ', ''); |
| 81 | + const loopVar = condition.split(' of ')[0]; |
| 82 | + let trackBy = loopVar; |
| 83 | + let aliasedIndex: string|null = null; |
| 84 | + for (let i = 1; i < parts.length; i++) { |
| 85 | + const part = parts[i].trim(); |
| 86 | + |
| 87 | + if (part.startsWith('trackBy:')) { |
| 88 | + // build trackby value |
| 89 | + const trackByFn = part.replace('trackBy:', '').trim(); |
| 90 | + trackBy = `${trackByFn}($index, ${loopVar})`; |
| 91 | + } |
| 92 | + // aliases |
| 93 | + // declared with `let myIndex = index` |
| 94 | + if (part.match(aliasWithEqualRegexp)) { |
| 95 | + // 'let myIndex = index' -> ['let myIndex', 'index'] |
| 96 | + const aliasParts = part.split('='); |
| 97 | + // -> 'let myIndex = $index' |
| 98 | + aliases.push(` ${aliasParts[0].trim()} = $${aliasParts[1].trim()}`); |
| 99 | + // if the aliased variable is the index, then we store it |
| 100 | + if (aliasParts[1].trim() === 'index') { |
| 101 | + // 'let myIndex' -> 'myIndex' |
| 102 | + aliasedIndex = aliasParts[0].replace('let', '').trim(); |
| 103 | + } |
| 104 | + } |
| 105 | + // declared with `index as myIndex` |
| 106 | + if (part.match(aliasWithAsRegexp)) { |
| 107 | + // 'index as myIndex' -> ['index', 'myIndex'] |
| 108 | + const aliasParts = part.split(/\s+as\s+/); |
| 109 | + // -> 'let myIndex = $index' |
| 110 | + aliases.push(` let ${aliasParts[1].trim()} = $${aliasParts[0].trim()}`); |
| 111 | + // if the aliased variable is the index, then we store it |
| 112 | + if (aliasParts[0].trim() === 'index') { |
| 113 | + aliasedIndex = aliasParts[1].trim(); |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + // if an alias has been defined for the index, then the trackBy function must use it |
| 118 | + if (aliasedIndex !== null && trackBy !== loopVar) { |
| 119 | + // byId($index, user) -> byId(i, user) |
| 120 | + trackBy = trackBy.replace('$index', aliasedIndex); |
| 121 | + } |
| 122 | + |
| 123 | + const aliasStr = (aliases.length > 0) ? `;${aliases.join(';')}` : ''; |
| 124 | + |
| 125 | + const {start, middle, end} = getMainBlock(etm, tmpl, offset); |
| 126 | + const startBlock = `@for (${condition}; track ${trackBy}${aliasStr}) {${lbSpaces}${start}`; |
| 127 | + |
| 128 | + const endBlock = `${end}${lbString}}`; |
| 129 | + const forBlock = startBlock + middle + endBlock; |
| 130 | + |
| 131 | + const updatedTmpl = tmpl.slice(0, etm.start(offset)) + forBlock + tmpl.slice(etm.end(offset)); |
| 132 | + |
| 133 | + const pre = originals.start.length - startBlock.length; |
| 134 | + const post = originals.end.length - endBlock.length; |
| 135 | + |
| 136 | + return {tmpl: updatedTmpl, offsets: {pre, post}}; |
| 137 | +} |
| 138 | + |
| 139 | +function getNgForParts(expression: string): string[] { |
| 140 | + const parts: string[] = []; |
| 141 | + const commaSeparatedStack: string[] = []; |
| 142 | + const stringStack: string[] = []; |
| 143 | + let current = ''; |
| 144 | + |
| 145 | + for (let i = 0; i < expression.length; i++) { |
| 146 | + const char = expression[i]; |
| 147 | + const isInString = stringStack.length === 0; |
| 148 | + const isInCommaSeparated = commaSeparatedStack.length === 0; |
| 149 | + |
| 150 | + // Any semicolon is a delimiter, as well as any comma outside |
| 151 | + // of comma-separated syntax, as long as they're outside of a string. |
| 152 | + if (isInString && current.length > 0 && |
| 153 | + (char === ';' || (char === ',' && isInCommaSeparated))) { |
| 154 | + parts.push(current); |
| 155 | + current = ''; |
| 156 | + continue; |
| 157 | + } |
| 158 | + |
| 159 | + if (stringPairs.has(char)) { |
| 160 | + stringStack.push(stringPairs.get(char)!); |
| 161 | + } else if (stringStack.length > 0 && stringStack[stringStack.length - 1] === char) { |
| 162 | + stringStack.pop(); |
| 163 | + } |
| 164 | + |
| 165 | + if (commaSeparatedSyntax.has(char)) { |
| 166 | + commaSeparatedStack.push(commaSeparatedSyntax.get(char)!); |
| 167 | + } else if ( |
| 168 | + commaSeparatedStack.length > 0 && |
| 169 | + commaSeparatedStack[commaSeparatedStack.length - 1] === char) { |
| 170 | + commaSeparatedStack.pop(); |
| 171 | + } |
| 172 | + |
| 173 | + current += char; |
| 174 | + } |
| 175 | + |
| 176 | + if (current.length > 0) { |
| 177 | + parts.push(current); |
| 178 | + } |
| 179 | + |
| 180 | + return parts; |
| 181 | +} |
0 commit comments