_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler/src/i18n/serializers/placeholder.ts_0_4910 | /**
* @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.dev/license
*/
const TAG_TO_PLACEHOLDER_NAMES: {[k: string]: string} = {
'A': 'LINK',
'B': 'BOLD_TEXT',
'BR': 'LINE_BREAK',
'EM': 'EMPHASISED_TEXT',
'H1': 'HEADING_LEVEL1',
'H2': 'HEADING_LEVEL2',
'H3': 'HEADING_LEVEL3',
'H4': 'HEADING_LEVEL4',
'H5': 'HEADING_LEVEL5',
'H6': 'HEADING_LEVEL6',
'HR': 'HORIZONTAL_RULE',
'I': 'ITALIC_TEXT',
'LI': 'LIST_ITEM',
'LINK': 'MEDIA_LINK',
'OL': 'ORDERED_LIST',
'P': 'PARAGRAPH',
'Q': 'QUOTATION',
'S': 'STRIKETHROUGH_TEXT',
'SMALL': 'SMALL_TEXT',
'SUB': 'SUBSTRIPT',
'SUP': 'SUPERSCRIPT',
'TBODY': 'TABLE_BODY',
'TD': 'TABLE_CELL',
'TFOOT': 'TABLE_FOOTER',
'TH': 'TABLE_HEADER_CELL',
'THEAD': 'TABLE_HEADER',
'TR': 'TABLE_ROW',
'TT': 'MONOSPACED_TEXT',
'U': 'UNDERLINED_TEXT',
'UL': 'UNORDERED_LIST',
};
/**
* Creates unique names for placeholder with different content.
*
* Returns the same placeholder name when the content is identical.
*/
export class PlaceholderRegistry {
// Count the occurrence of the base name top generate a unique name
private _placeHolderNameCounts: {[k: string]: number} = {};
// Maps signature to placeholder names
private _signatureToName: {[k: string]: string} = {};
getStartTagPlaceholderName(tag: string, attrs: {[k: string]: string}, isVoid: boolean): string {
const signature = this._hashTag(tag, attrs, isVoid);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const upperTag = tag.toUpperCase();
const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
const name = this._generateUniqueName(isVoid ? baseName : `START_${baseName}`);
this._signatureToName[signature] = name;
return name;
}
getCloseTagPlaceholderName(tag: string): string {
const signature = this._hashClosingTag(tag);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const upperTag = tag.toUpperCase();
const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
const name = this._generateUniqueName(`CLOSE_${baseName}`);
this._signatureToName[signature] = name;
return name;
}
getPlaceholderName(name: string, content: string): string {
const upperName = name.toUpperCase();
const signature = `PH: ${upperName}=${content}`;
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const uniqueName = this._generateUniqueName(upperName);
this._signatureToName[signature] = uniqueName;
return uniqueName;
}
getUniquePlaceholder(name: string): string {
return this._generateUniqueName(name.toUpperCase());
}
getStartBlockPlaceholderName(name: string, parameters: string[]): string {
const signature = this._hashBlock(name, parameters);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const placeholder = this._generateUniqueName(`START_BLOCK_${this._toSnakeCase(name)}`);
this._signatureToName[signature] = placeholder;
return placeholder;
}
getCloseBlockPlaceholderName(name: string): string {
const signature = this._hashClosingBlock(name);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const placeholder = this._generateUniqueName(`CLOSE_BLOCK_${this._toSnakeCase(name)}`);
this._signatureToName[signature] = placeholder;
return placeholder;
}
// Generate a hash for a tag - does not take attribute order into account
private _hashTag(tag: string, attrs: {[k: string]: string}, isVoid: boolean): string {
const start = `<${tag}`;
const strAttrs = Object.keys(attrs)
.sort()
.map((name) => ` ${name}=${attrs[name]}`)
.join('');
const end = isVoid ? '/>' : `></${tag}>`;
return start + strAttrs + end;
}
private _hashClosingTag(tag: string): string {
return this._hashTag(`/${tag}`, {}, false);
}
private _hashBlock(name: string, parameters: string[]): string {
const params = parameters.length === 0 ? '' : ` (${parameters.sort().join('; ')})`;
return `@${name}${params} {}`;
}
private _hashClosingBlock(name: string): string {
return this._hashBlock(`close_${name}`, []);
}
private _toSnakeCase(name: string) {
return name.toUpperCase().replace(/[^A-Z0-9]/g, '_');
}
private _generateUniqueName(base: string): string {
const seen = this._placeHolderNameCounts.hasOwnProperty(base);
if (!seen) {
this._placeHolderNameCounts[base] = 1;
return base;
}
const id = this._placeHolderNameCounts[base];
this._placeHolderNameCounts[base] = id + 1;
return `${base}_${id}`;
}
}
| {
"end_byte": 4910,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/placeholder.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_0_553 | /**
* @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.dev/license
*/
// Mapping between all HTML entity names and their unicode representation.
// Generated from https://html.spec.whatwg.org/multipage/entities.json by stripping
// the `&` and `;` from the keys and removing the duplicates.
// see https://www.w3.org/TR/html51/syntax.html#named-character-references
export const NAMED_ENTITIES: Record<string, string> = | {
"end_byte": 553,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_554_4907 | {
'AElig': '\u00C6',
'AMP': '\u0026',
'amp': '\u0026',
'Aacute': '\u00C1',
'Abreve': '\u0102',
'Acirc': '\u00C2',
'Acy': '\u0410',
'Afr': '\uD835\uDD04',
'Agrave': '\u00C0',
'Alpha': '\u0391',
'Amacr': '\u0100',
'And': '\u2A53',
'Aogon': '\u0104',
'Aopf': '\uD835\uDD38',
'ApplyFunction': '\u2061',
'af': '\u2061',
'Aring': '\u00C5',
'angst': '\u00C5',
'Ascr': '\uD835\uDC9C',
'Assign': '\u2254',
'colone': '\u2254',
'coloneq': '\u2254',
'Atilde': '\u00C3',
'Auml': '\u00C4',
'Backslash': '\u2216',
'setminus': '\u2216',
'setmn': '\u2216',
'smallsetminus': '\u2216',
'ssetmn': '\u2216',
'Barv': '\u2AE7',
'Barwed': '\u2306',
'doublebarwedge': '\u2306',
'Bcy': '\u0411',
'Because': '\u2235',
'becaus': '\u2235',
'because': '\u2235',
'Bernoullis': '\u212C',
'Bscr': '\u212C',
'bernou': '\u212C',
'Beta': '\u0392',
'Bfr': '\uD835\uDD05',
'Bopf': '\uD835\uDD39',
'Breve': '\u02D8',
'breve': '\u02D8',
'Bumpeq': '\u224E',
'HumpDownHump': '\u224E',
'bump': '\u224E',
'CHcy': '\u0427',
'COPY': '\u00A9',
'copy': '\u00A9',
'Cacute': '\u0106',
'Cap': '\u22D2',
'CapitalDifferentialD': '\u2145',
'DD': '\u2145',
'Cayleys': '\u212D',
'Cfr': '\u212D',
'Ccaron': '\u010C',
'Ccedil': '\u00C7',
'Ccirc': '\u0108',
'Cconint': '\u2230',
'Cdot': '\u010A',
'Cedilla': '\u00B8',
'cedil': '\u00B8',
'CenterDot': '\u00B7',
'centerdot': '\u00B7',
'middot': '\u00B7',
'Chi': '\u03A7',
'CircleDot': '\u2299',
'odot': '\u2299',
'CircleMinus': '\u2296',
'ominus': '\u2296',
'CirclePlus': '\u2295',
'oplus': '\u2295',
'CircleTimes': '\u2297',
'otimes': '\u2297',
'ClockwiseContourIntegral': '\u2232',
'cwconint': '\u2232',
'CloseCurlyDoubleQuote': '\u201D',
'rdquo': '\u201D',
'rdquor': '\u201D',
'CloseCurlyQuote': '\u2019',
'rsquo': '\u2019',
'rsquor': '\u2019',
'Colon': '\u2237',
'Proportion': '\u2237',
'Colone': '\u2A74',
'Congruent': '\u2261',
'equiv': '\u2261',
'Conint': '\u222F',
'DoubleContourIntegral': '\u222F',
'ContourIntegral': '\u222E',
'conint': '\u222E',
'oint': '\u222E',
'Copf': '\u2102',
'complexes': '\u2102',
'Coproduct': '\u2210',
'coprod': '\u2210',
'CounterClockwiseContourIntegral': '\u2233',
'awconint': '\u2233',
'Cross': '\u2A2F',
'Cscr': '\uD835\uDC9E',
'Cup': '\u22D3',
'CupCap': '\u224D',
'asympeq': '\u224D',
'DDotrahd': '\u2911',
'DJcy': '\u0402',
'DScy': '\u0405',
'DZcy': '\u040F',
'Dagger': '\u2021',
'ddagger': '\u2021',
'Darr': '\u21A1',
'Dashv': '\u2AE4',
'DoubleLeftTee': '\u2AE4',
'Dcaron': '\u010E',
'Dcy': '\u0414',
'Del': '\u2207',
'nabla': '\u2207',
'Delta': '\u0394',
'Dfr': '\uD835\uDD07',
'DiacriticalAcute': '\u00B4',
'acute': '\u00B4',
'DiacriticalDot': '\u02D9',
'dot': '\u02D9',
'DiacriticalDoubleAcute': '\u02DD',
'dblac': '\u02DD',
'DiacriticalGrave': '\u0060',
'grave': '\u0060',
'DiacriticalTilde': '\u02DC',
'tilde': '\u02DC',
'Diamond': '\u22C4',
'diam': '\u22C4',
'diamond': '\u22C4',
'DifferentialD': '\u2146',
'dd': '\u2146',
'Dopf': '\uD835\uDD3B',
'Dot': '\u00A8',
'DoubleDot': '\u00A8',
'die': '\u00A8',
'uml': '\u00A8',
'DotDot': '\u20DC',
'DotEqual': '\u2250',
'doteq': '\u2250',
'esdot': '\u2250',
'DoubleDownArrow': '\u21D3',
'Downarrow': '\u21D3',
'dArr': '\u21D3',
'DoubleLeftArrow': '\u21D0',
'Leftarrow': '\u21D0',
'lArr': '\u21D0',
'DoubleLeftRightArrow': '\u21D4',
'Leftrightarrow': '\u21D4',
'hArr': '\u21D4',
'iff': '\u21D4',
'DoubleLongLeftArrow': '\u27F8',
'Longleftarrow': '\u27F8',
'xlArr': '\u27F8',
'DoubleLongLeftRightArrow': '\u27FA',
'Longleftrightarrow': '\u27FA',
'xhArr': '\u27FA',
'DoubleLongRightArrow': '\u27F9',
'Longrightarrow': '\u27F9',
'xrArr': '\u27F9',
'DoubleRightArrow': '\u21D2',
'Implies': '\u21D2',
'Rightarrow': '\u21D2',
'rArr': '\u21D2',
'DoubleRightTee': '\u22A8',
'vDash': '\u22A8',
'DoubleUpArrow': '\u21D1',
'Uparrow': '\u21D1',
'uArr': '\u21D1',
'DoubleUpDownArrow': '\u21D5',
'Updownarrow': '\u21D5',
'vArr': '\u21D5',
'DoubleVerticalBar': '\u2225',
'par': '\u2225',
'parallel': '\u2225',
'shortparallel': '\u2225',
'spar': '\u2225',
'DownArrow': '\u2193',
'ShortDownArrow': '\u2193',
'darr': '\u2193', | {
"end_byte": 4907,
"start_byte": 554,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_4910_9206 | 'downarrow': '\u2193',
'DownArrowBar': '\u2913',
'DownArrowUpArrow': '\u21F5',
'duarr': '\u21F5',
'DownBreve': '\u0311',
'DownLeftRightVector': '\u2950',
'DownLeftTeeVector': '\u295E',
'DownLeftVector': '\u21BD',
'leftharpoondown': '\u21BD',
'lhard': '\u21BD',
'DownLeftVectorBar': '\u2956',
'DownRightTeeVector': '\u295F',
'DownRightVector': '\u21C1',
'rhard': '\u21C1',
'rightharpoondown': '\u21C1',
'DownRightVectorBar': '\u2957',
'DownTee': '\u22A4',
'top': '\u22A4',
'DownTeeArrow': '\u21A7',
'mapstodown': '\u21A7',
'Dscr': '\uD835\uDC9F',
'Dstrok': '\u0110',
'ENG': '\u014A',
'ETH': '\u00D0',
'Eacute': '\u00C9',
'Ecaron': '\u011A',
'Ecirc': '\u00CA',
'Ecy': '\u042D',
'Edot': '\u0116',
'Efr': '\uD835\uDD08',
'Egrave': '\u00C8',
'Element': '\u2208',
'in': '\u2208',
'isin': '\u2208',
'isinv': '\u2208',
'Emacr': '\u0112',
'EmptySmallSquare': '\u25FB',
'EmptyVerySmallSquare': '\u25AB',
'Eogon': '\u0118',
'Eopf': '\uD835\uDD3C',
'Epsilon': '\u0395',
'Equal': '\u2A75',
'EqualTilde': '\u2242',
'eqsim': '\u2242',
'esim': '\u2242',
'Equilibrium': '\u21CC',
'rightleftharpoons': '\u21CC',
'rlhar': '\u21CC',
'Escr': '\u2130',
'expectation': '\u2130',
'Esim': '\u2A73',
'Eta': '\u0397',
'Euml': '\u00CB',
'Exists': '\u2203',
'exist': '\u2203',
'ExponentialE': '\u2147',
'ee': '\u2147',
'exponentiale': '\u2147',
'Fcy': '\u0424',
'Ffr': '\uD835\uDD09',
'FilledSmallSquare': '\u25FC',
'FilledVerySmallSquare': '\u25AA',
'blacksquare': '\u25AA',
'squarf': '\u25AA',
'squf': '\u25AA',
'Fopf': '\uD835\uDD3D',
'ForAll': '\u2200',
'forall': '\u2200',
'Fouriertrf': '\u2131',
'Fscr': '\u2131',
'GJcy': '\u0403',
'GT': '\u003E',
'gt': '\u003E',
'Gamma': '\u0393',
'Gammad': '\u03DC',
'Gbreve': '\u011E',
'Gcedil': '\u0122',
'Gcirc': '\u011C',
'Gcy': '\u0413',
'Gdot': '\u0120',
'Gfr': '\uD835\uDD0A',
'Gg': '\u22D9',
'ggg': '\u22D9',
'Gopf': '\uD835\uDD3E',
'GreaterEqual': '\u2265',
'ge': '\u2265',
'geq': '\u2265',
'GreaterEqualLess': '\u22DB',
'gel': '\u22DB',
'gtreqless': '\u22DB',
'GreaterFullEqual': '\u2267',
'gE': '\u2267',
'geqq': '\u2267',
'GreaterGreater': '\u2AA2',
'GreaterLess': '\u2277',
'gl': '\u2277',
'gtrless': '\u2277',
'GreaterSlantEqual': '\u2A7E',
'geqslant': '\u2A7E',
'ges': '\u2A7E',
'GreaterTilde': '\u2273',
'gsim': '\u2273',
'gtrsim': '\u2273',
'Gscr': '\uD835\uDCA2',
'Gt': '\u226B',
'NestedGreaterGreater': '\u226B',
'gg': '\u226B',
'HARDcy': '\u042A',
'Hacek': '\u02C7',
'caron': '\u02C7',
'Hat': '\u005E',
'Hcirc': '\u0124',
'Hfr': '\u210C',
'Poincareplane': '\u210C',
'HilbertSpace': '\u210B',
'Hscr': '\u210B',
'hamilt': '\u210B',
'Hopf': '\u210D',
'quaternions': '\u210D',
'HorizontalLine': '\u2500',
'boxh': '\u2500',
'Hstrok': '\u0126',
'HumpEqual': '\u224F',
'bumpe': '\u224F',
'bumpeq': '\u224F',
'IEcy': '\u0415',
'IJlig': '\u0132',
'IOcy': '\u0401',
'Iacute': '\u00CD',
'Icirc': '\u00CE',
'Icy': '\u0418',
'Idot': '\u0130',
'Ifr': '\u2111',
'Im': '\u2111',
'image': '\u2111',
'imagpart': '\u2111',
'Igrave': '\u00CC',
'Imacr': '\u012A',
'ImaginaryI': '\u2148',
'ii': '\u2148',
'Int': '\u222C',
'Integral': '\u222B',
'int': '\u222B',
'Intersection': '\u22C2',
'bigcap': '\u22C2',
'xcap': '\u22C2',
'InvisibleComma': '\u2063',
'ic': '\u2063',
'InvisibleTimes': '\u2062',
'it': '\u2062',
'Iogon': '\u012E',
'Iopf': '\uD835\uDD40',
'Iota': '\u0399',
'Iscr': '\u2110',
'imagline': '\u2110',
'Itilde': '\u0128',
'Iukcy': '\u0406',
'Iuml': '\u00CF',
'Jcirc': '\u0134',
'Jcy': '\u0419',
'Jfr': '\uD835\uDD0D',
'Jopf': '\uD835\uDD41',
'Jscr': '\uD835\uDCA5',
'Jsercy': '\u0408',
'Jukcy': '\u0404',
'KHcy': '\u0425',
'KJcy': '\u040C',
'Kappa': '\u039A',
'Kcedil': '\u0136',
'Kcy': '\u041A',
'Kfr': '\uD835\uDD0E',
'Kopf': '\uD835\uDD42',
'Kscr': '\uD835\uDCA6',
'LJcy': '\u0409',
'LT': '\u003C',
'lt': '\u003C',
'Lacute': '\u0139',
'Lambda': '\u039B',
'Lang': '\u27EA',
'Laplacetrf': '\u2112',
'Lscr': '\u2112',
'lagran': '\u2112',
'Larr': '\u219E',
'twoheadleftarrow': '\u219E',
'Lcaron': '\u013D', | {
"end_byte": 9206,
"start_byte": 4910,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_9209_13721 | 'Lcedil': '\u013B',
'Lcy': '\u041B',
'LeftAngleBracket': '\u27E8',
'lang': '\u27E8',
'langle': '\u27E8',
'LeftArrow': '\u2190',
'ShortLeftArrow': '\u2190',
'larr': '\u2190',
'leftarrow': '\u2190',
'slarr': '\u2190',
'LeftArrowBar': '\u21E4',
'larrb': '\u21E4',
'LeftArrowRightArrow': '\u21C6',
'leftrightarrows': '\u21C6',
'lrarr': '\u21C6',
'LeftCeiling': '\u2308',
'lceil': '\u2308',
'LeftDoubleBracket': '\u27E6',
'lobrk': '\u27E6',
'LeftDownTeeVector': '\u2961',
'LeftDownVector': '\u21C3',
'dharl': '\u21C3',
'downharpoonleft': '\u21C3',
'LeftDownVectorBar': '\u2959',
'LeftFloor': '\u230A',
'lfloor': '\u230A',
'LeftRightArrow': '\u2194',
'harr': '\u2194',
'leftrightarrow': '\u2194',
'LeftRightVector': '\u294E',
'LeftTee': '\u22A3',
'dashv': '\u22A3',
'LeftTeeArrow': '\u21A4',
'mapstoleft': '\u21A4',
'LeftTeeVector': '\u295A',
'LeftTriangle': '\u22B2',
'vartriangleleft': '\u22B2',
'vltri': '\u22B2',
'LeftTriangleBar': '\u29CF',
'LeftTriangleEqual': '\u22B4',
'ltrie': '\u22B4',
'trianglelefteq': '\u22B4',
'LeftUpDownVector': '\u2951',
'LeftUpTeeVector': '\u2960',
'LeftUpVector': '\u21BF',
'uharl': '\u21BF',
'upharpoonleft': '\u21BF',
'LeftUpVectorBar': '\u2958',
'LeftVector': '\u21BC',
'leftharpoonup': '\u21BC',
'lharu': '\u21BC',
'LeftVectorBar': '\u2952',
'LessEqualGreater': '\u22DA',
'leg': '\u22DA',
'lesseqgtr': '\u22DA',
'LessFullEqual': '\u2266',
'lE': '\u2266',
'leqq': '\u2266',
'LessGreater': '\u2276',
'lessgtr': '\u2276',
'lg': '\u2276',
'LessLess': '\u2AA1',
'LessSlantEqual': '\u2A7D',
'leqslant': '\u2A7D',
'les': '\u2A7D',
'LessTilde': '\u2272',
'lesssim': '\u2272',
'lsim': '\u2272',
'Lfr': '\uD835\uDD0F',
'Ll': '\u22D8',
'Lleftarrow': '\u21DA',
'lAarr': '\u21DA',
'Lmidot': '\u013F',
'LongLeftArrow': '\u27F5',
'longleftarrow': '\u27F5',
'xlarr': '\u27F5',
'LongLeftRightArrow': '\u27F7',
'longleftrightarrow': '\u27F7',
'xharr': '\u27F7',
'LongRightArrow': '\u27F6',
'longrightarrow': '\u27F6',
'xrarr': '\u27F6',
'Lopf': '\uD835\uDD43',
'LowerLeftArrow': '\u2199',
'swarr': '\u2199',
'swarrow': '\u2199',
'LowerRightArrow': '\u2198',
'searr': '\u2198',
'searrow': '\u2198',
'Lsh': '\u21B0',
'lsh': '\u21B0',
'Lstrok': '\u0141',
'Lt': '\u226A',
'NestedLessLess': '\u226A',
'll': '\u226A',
'Map': '\u2905',
'Mcy': '\u041C',
'MediumSpace': '\u205F',
'Mellintrf': '\u2133',
'Mscr': '\u2133',
'phmmat': '\u2133',
'Mfr': '\uD835\uDD10',
'MinusPlus': '\u2213',
'mnplus': '\u2213',
'mp': '\u2213',
'Mopf': '\uD835\uDD44',
'Mu': '\u039C',
'NJcy': '\u040A',
'Nacute': '\u0143',
'Ncaron': '\u0147',
'Ncedil': '\u0145',
'Ncy': '\u041D',
'NegativeMediumSpace': '\u200B',
'NegativeThickSpace': '\u200B',
'NegativeThinSpace': '\u200B',
'NegativeVeryThinSpace': '\u200B',
'ZeroWidthSpace': '\u200B',
'NewLine': '\u000A',
'Nfr': '\uD835\uDD11',
'NoBreak': '\u2060',
'NonBreakingSpace': '\u00A0',
'nbsp': '\u00A0',
'Nopf': '\u2115',
'naturals': '\u2115',
'Not': '\u2AEC',
'NotCongruent': '\u2262',
'nequiv': '\u2262',
'NotCupCap': '\u226D',
'NotDoubleVerticalBar': '\u2226',
'npar': '\u2226',
'nparallel': '\u2226',
'nshortparallel': '\u2226',
'nspar': '\u2226',
'NotElement': '\u2209',
'notin': '\u2209',
'notinva': '\u2209',
'NotEqual': '\u2260',
'ne': '\u2260',
'NotEqualTilde': '\u2242\u0338',
'nesim': '\u2242\u0338',
'NotExists': '\u2204',
'nexist': '\u2204',
'nexists': '\u2204',
'NotGreater': '\u226F',
'ngt': '\u226F',
'ngtr': '\u226F',
'NotGreaterEqual': '\u2271',
'nge': '\u2271',
'ngeq': '\u2271',
'NotGreaterFullEqual': '\u2267\u0338',
'ngE': '\u2267\u0338',
'ngeqq': '\u2267\u0338',
'NotGreaterGreater': '\u226B\u0338',
'nGtv': '\u226B\u0338',
'NotGreaterLess': '\u2279',
'ntgl': '\u2279',
'NotGreaterSlantEqual': '\u2A7E\u0338',
'ngeqslant': '\u2A7E\u0338',
'nges': '\u2A7E\u0338',
'NotGreaterTilde': '\u2275',
'ngsim': '\u2275',
'NotHumpDownHump': '\u224E\u0338',
'nbump': '\u224E\u0338',
'NotHumpEqual': '\u224F\u0338',
'nbumpe': '\u224F\u0338',
'NotLeftTriangle': '\u22EA',
'nltri': '\u22EA',
'ntriangleleft': '\u22EA',
'NotLeftTriangleBar': '\u29CF\u0338',
'NotLeftTriangleEqual': '\u22EC',
'nltrie': '\u22EC',
'ntrianglelefteq': '\u22EC',
'NotLess': '\u226E',
'nless': '\u226E',
'nlt': '\u226E',
'NotLessEqual': '\u2270', | {
"end_byte": 13721,
"start_byte": 9209,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_13724_18038 | 'nle': '\u2270',
'nleq': '\u2270',
'NotLessGreater': '\u2278',
'ntlg': '\u2278',
'NotLessLess': '\u226A\u0338',
'nLtv': '\u226A\u0338',
'NotLessSlantEqual': '\u2A7D\u0338',
'nleqslant': '\u2A7D\u0338',
'nles': '\u2A7D\u0338',
'NotLessTilde': '\u2274',
'nlsim': '\u2274',
'NotNestedGreaterGreater': '\u2AA2\u0338',
'NotNestedLessLess': '\u2AA1\u0338',
'NotPrecedes': '\u2280',
'npr': '\u2280',
'nprec': '\u2280',
'NotPrecedesEqual': '\u2AAF\u0338',
'npre': '\u2AAF\u0338',
'npreceq': '\u2AAF\u0338',
'NotPrecedesSlantEqual': '\u22E0',
'nprcue': '\u22E0',
'NotReverseElement': '\u220C',
'notni': '\u220C',
'notniva': '\u220C',
'NotRightTriangle': '\u22EB',
'nrtri': '\u22EB',
'ntriangleright': '\u22EB',
'NotRightTriangleBar': '\u29D0\u0338',
'NotRightTriangleEqual': '\u22ED',
'nrtrie': '\u22ED',
'ntrianglerighteq': '\u22ED',
'NotSquareSubset': '\u228F\u0338',
'NotSquareSubsetEqual': '\u22E2',
'nsqsube': '\u22E2',
'NotSquareSuperset': '\u2290\u0338',
'NotSquareSupersetEqual': '\u22E3',
'nsqsupe': '\u22E3',
'NotSubset': '\u2282\u20D2',
'nsubset': '\u2282\u20D2',
'vnsub': '\u2282\u20D2',
'NotSubsetEqual': '\u2288',
'nsube': '\u2288',
'nsubseteq': '\u2288',
'NotSucceeds': '\u2281',
'nsc': '\u2281',
'nsucc': '\u2281',
'NotSucceedsEqual': '\u2AB0\u0338',
'nsce': '\u2AB0\u0338',
'nsucceq': '\u2AB0\u0338',
'NotSucceedsSlantEqual': '\u22E1',
'nsccue': '\u22E1',
'NotSucceedsTilde': '\u227F\u0338',
'NotSuperset': '\u2283\u20D2',
'nsupset': '\u2283\u20D2',
'vnsup': '\u2283\u20D2',
'NotSupersetEqual': '\u2289',
'nsupe': '\u2289',
'nsupseteq': '\u2289',
'NotTilde': '\u2241',
'nsim': '\u2241',
'NotTildeEqual': '\u2244',
'nsime': '\u2244',
'nsimeq': '\u2244',
'NotTildeFullEqual': '\u2247',
'ncong': '\u2247',
'NotTildeTilde': '\u2249',
'nap': '\u2249',
'napprox': '\u2249',
'NotVerticalBar': '\u2224',
'nmid': '\u2224',
'nshortmid': '\u2224',
'nsmid': '\u2224',
'Nscr': '\uD835\uDCA9',
'Ntilde': '\u00D1',
'Nu': '\u039D',
'OElig': '\u0152',
'Oacute': '\u00D3',
'Ocirc': '\u00D4',
'Ocy': '\u041E',
'Odblac': '\u0150',
'Ofr': '\uD835\uDD12',
'Ograve': '\u00D2',
'Omacr': '\u014C',
'Omega': '\u03A9',
'ohm': '\u03A9',
'Omicron': '\u039F',
'Oopf': '\uD835\uDD46',
'OpenCurlyDoubleQuote': '\u201C',
'ldquo': '\u201C',
'OpenCurlyQuote': '\u2018',
'lsquo': '\u2018',
'Or': '\u2A54',
'Oscr': '\uD835\uDCAA',
'Oslash': '\u00D8',
'Otilde': '\u00D5',
'Otimes': '\u2A37',
'Ouml': '\u00D6',
'OverBar': '\u203E',
'oline': '\u203E',
'OverBrace': '\u23DE',
'OverBracket': '\u23B4',
'tbrk': '\u23B4',
'OverParenthesis': '\u23DC',
'PartialD': '\u2202',
'part': '\u2202',
'Pcy': '\u041F',
'Pfr': '\uD835\uDD13',
'Phi': '\u03A6',
'Pi': '\u03A0',
'PlusMinus': '\u00B1',
'plusmn': '\u00B1',
'pm': '\u00B1',
'Popf': '\u2119',
'primes': '\u2119',
'Pr': '\u2ABB',
'Precedes': '\u227A',
'pr': '\u227A',
'prec': '\u227A',
'PrecedesEqual': '\u2AAF',
'pre': '\u2AAF',
'preceq': '\u2AAF',
'PrecedesSlantEqual': '\u227C',
'prcue': '\u227C',
'preccurlyeq': '\u227C',
'PrecedesTilde': '\u227E',
'precsim': '\u227E',
'prsim': '\u227E',
'Prime': '\u2033',
'Product': '\u220F',
'prod': '\u220F',
'Proportional': '\u221D',
'prop': '\u221D',
'propto': '\u221D',
'varpropto': '\u221D',
'vprop': '\u221D',
'Pscr': '\uD835\uDCAB',
'Psi': '\u03A8',
'QUOT': '\u0022',
'quot': '\u0022',
'Qfr': '\uD835\uDD14',
'Qopf': '\u211A',
'rationals': '\u211A',
'Qscr': '\uD835\uDCAC',
'RBarr': '\u2910',
'drbkarow': '\u2910',
'REG': '\u00AE',
'circledR': '\u00AE',
'reg': '\u00AE',
'Racute': '\u0154',
'Rang': '\u27EB',
'Rarr': '\u21A0',
'twoheadrightarrow': '\u21A0',
'Rarrtl': '\u2916',
'Rcaron': '\u0158',
'Rcedil': '\u0156',
'Rcy': '\u0420',
'Re': '\u211C',
'Rfr': '\u211C',
'real': '\u211C',
'realpart': '\u211C',
'ReverseElement': '\u220B',
'SuchThat': '\u220B',
'ni': '\u220B',
'niv': '\u220B',
'ReverseEquilibrium': '\u21CB',
'leftrightharpoons': '\u21CB',
'lrhar': '\u21CB',
'ReverseUpEquilibrium': '\u296F',
'duhar': '\u296F',
'Rho': '\u03A1',
'RightAngleBracket': '\u27E9',
'rang': '\u27E9',
'rangle': '\u27E9', | {
"end_byte": 18038,
"start_byte": 13724,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_18041_22423 | 'RightArrow': '\u2192',
'ShortRightArrow': '\u2192',
'rarr': '\u2192',
'rightarrow': '\u2192',
'srarr': '\u2192',
'RightArrowBar': '\u21E5',
'rarrb': '\u21E5',
'RightArrowLeftArrow': '\u21C4',
'rightleftarrows': '\u21C4',
'rlarr': '\u21C4',
'RightCeiling': '\u2309',
'rceil': '\u2309',
'RightDoubleBracket': '\u27E7',
'robrk': '\u27E7',
'RightDownTeeVector': '\u295D',
'RightDownVector': '\u21C2',
'dharr': '\u21C2',
'downharpoonright': '\u21C2',
'RightDownVectorBar': '\u2955',
'RightFloor': '\u230B',
'rfloor': '\u230B',
'RightTee': '\u22A2',
'vdash': '\u22A2',
'RightTeeArrow': '\u21A6',
'map': '\u21A6',
'mapsto': '\u21A6',
'RightTeeVector': '\u295B',
'RightTriangle': '\u22B3',
'vartriangleright': '\u22B3',
'vrtri': '\u22B3',
'RightTriangleBar': '\u29D0',
'RightTriangleEqual': '\u22B5',
'rtrie': '\u22B5',
'trianglerighteq': '\u22B5',
'RightUpDownVector': '\u294F',
'RightUpTeeVector': '\u295C',
'RightUpVector': '\u21BE',
'uharr': '\u21BE',
'upharpoonright': '\u21BE',
'RightUpVectorBar': '\u2954',
'RightVector': '\u21C0',
'rharu': '\u21C0',
'rightharpoonup': '\u21C0',
'RightVectorBar': '\u2953',
'Ropf': '\u211D',
'reals': '\u211D',
'RoundImplies': '\u2970',
'Rrightarrow': '\u21DB',
'rAarr': '\u21DB',
'Rscr': '\u211B',
'realine': '\u211B',
'Rsh': '\u21B1',
'rsh': '\u21B1',
'RuleDelayed': '\u29F4',
'SHCHcy': '\u0429',
'SHcy': '\u0428',
'SOFTcy': '\u042C',
'Sacute': '\u015A',
'Sc': '\u2ABC',
'Scaron': '\u0160',
'Scedil': '\u015E',
'Scirc': '\u015C',
'Scy': '\u0421',
'Sfr': '\uD835\uDD16',
'ShortUpArrow': '\u2191',
'UpArrow': '\u2191',
'uarr': '\u2191',
'uparrow': '\u2191',
'Sigma': '\u03A3',
'SmallCircle': '\u2218',
'compfn': '\u2218',
'Sopf': '\uD835\uDD4A',
'Sqrt': '\u221A',
'radic': '\u221A',
'Square': '\u25A1',
'squ': '\u25A1',
'square': '\u25A1',
'SquareIntersection': '\u2293',
'sqcap': '\u2293',
'SquareSubset': '\u228F',
'sqsub': '\u228F',
'sqsubset': '\u228F',
'SquareSubsetEqual': '\u2291',
'sqsube': '\u2291',
'sqsubseteq': '\u2291',
'SquareSuperset': '\u2290',
'sqsup': '\u2290',
'sqsupset': '\u2290',
'SquareSupersetEqual': '\u2292',
'sqsupe': '\u2292',
'sqsupseteq': '\u2292',
'SquareUnion': '\u2294',
'sqcup': '\u2294',
'Sscr': '\uD835\uDCAE',
'Star': '\u22C6',
'sstarf': '\u22C6',
'Sub': '\u22D0',
'Subset': '\u22D0',
'SubsetEqual': '\u2286',
'sube': '\u2286',
'subseteq': '\u2286',
'Succeeds': '\u227B',
'sc': '\u227B',
'succ': '\u227B',
'SucceedsEqual': '\u2AB0',
'sce': '\u2AB0',
'succeq': '\u2AB0',
'SucceedsSlantEqual': '\u227D',
'sccue': '\u227D',
'succcurlyeq': '\u227D',
'SucceedsTilde': '\u227F',
'scsim': '\u227F',
'succsim': '\u227F',
'Sum': '\u2211',
'sum': '\u2211',
'Sup': '\u22D1',
'Supset': '\u22D1',
'Superset': '\u2283',
'sup': '\u2283',
'supset': '\u2283',
'SupersetEqual': '\u2287',
'supe': '\u2287',
'supseteq': '\u2287',
'THORN': '\u00DE',
'TRADE': '\u2122',
'trade': '\u2122',
'TSHcy': '\u040B',
'TScy': '\u0426',
'Tab': '\u0009',
'Tau': '\u03A4',
'Tcaron': '\u0164',
'Tcedil': '\u0162',
'Tcy': '\u0422',
'Tfr': '\uD835\uDD17',
'Therefore': '\u2234',
'there4': '\u2234',
'therefore': '\u2234',
'Theta': '\u0398',
'ThickSpace': '\u205F\u200A',
'ThinSpace': '\u2009',
'thinsp': '\u2009',
'Tilde': '\u223C',
'sim': '\u223C',
'thicksim': '\u223C',
'thksim': '\u223C',
'TildeEqual': '\u2243',
'sime': '\u2243',
'simeq': '\u2243',
'TildeFullEqual': '\u2245',
'cong': '\u2245',
'TildeTilde': '\u2248',
'ap': '\u2248',
'approx': '\u2248',
'asymp': '\u2248',
'thickapprox': '\u2248',
'thkap': '\u2248',
'Topf': '\uD835\uDD4B',
'TripleDot': '\u20DB',
'tdot': '\u20DB',
'Tscr': '\uD835\uDCAF',
'Tstrok': '\u0166',
'Uacute': '\u00DA',
'Uarr': '\u219F',
'Uarrocir': '\u2949',
'Ubrcy': '\u040E',
'Ubreve': '\u016C',
'Ucirc': '\u00DB',
'Ucy': '\u0423',
'Udblac': '\u0170',
'Ufr': '\uD835\uDD18',
'Ugrave': '\u00D9',
'Umacr': '\u016A',
'UnderBar': '\u005F',
'lowbar': '\u005F',
'UnderBrace': '\u23DF',
'UnderBracket': '\u23B5',
'bbrk': '\u23B5',
'UnderParenthesis': '\u23DD',
'Union': '\u22C3',
'bigcup': '\u22C3',
'xcup': '\u22C3',
'UnionPlus': '\u228E',
'uplus': '\u228E', | {
"end_byte": 22423,
"start_byte": 18041,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_22426_26502 | 'Uogon': '\u0172',
'Uopf': '\uD835\uDD4C',
'UpArrowBar': '\u2912',
'UpArrowDownArrow': '\u21C5',
'udarr': '\u21C5',
'UpDownArrow': '\u2195',
'updownarrow': '\u2195',
'varr': '\u2195',
'UpEquilibrium': '\u296E',
'udhar': '\u296E',
'UpTee': '\u22A5',
'bot': '\u22A5',
'bottom': '\u22A5',
'perp': '\u22A5',
'UpTeeArrow': '\u21A5',
'mapstoup': '\u21A5',
'UpperLeftArrow': '\u2196',
'nwarr': '\u2196',
'nwarrow': '\u2196',
'UpperRightArrow': '\u2197',
'nearr': '\u2197',
'nearrow': '\u2197',
'Upsi': '\u03D2',
'upsih': '\u03D2',
'Upsilon': '\u03A5',
'Uring': '\u016E',
'Uscr': '\uD835\uDCB0',
'Utilde': '\u0168',
'Uuml': '\u00DC',
'VDash': '\u22AB',
'Vbar': '\u2AEB',
'Vcy': '\u0412',
'Vdash': '\u22A9',
'Vdashl': '\u2AE6',
'Vee': '\u22C1',
'bigvee': '\u22C1',
'xvee': '\u22C1',
'Verbar': '\u2016',
'Vert': '\u2016',
'VerticalBar': '\u2223',
'mid': '\u2223',
'shortmid': '\u2223',
'smid': '\u2223',
'VerticalLine': '\u007C',
'verbar': '\u007C',
'vert': '\u007C',
'VerticalSeparator': '\u2758',
'VerticalTilde': '\u2240',
'wr': '\u2240',
'wreath': '\u2240',
'VeryThinSpace': '\u200A',
'hairsp': '\u200A',
'Vfr': '\uD835\uDD19',
'Vopf': '\uD835\uDD4D',
'Vscr': '\uD835\uDCB1',
'Vvdash': '\u22AA',
'Wcirc': '\u0174',
'Wedge': '\u22C0',
'bigwedge': '\u22C0',
'xwedge': '\u22C0',
'Wfr': '\uD835\uDD1A',
'Wopf': '\uD835\uDD4E',
'Wscr': '\uD835\uDCB2',
'Xfr': '\uD835\uDD1B',
'Xi': '\u039E',
'Xopf': '\uD835\uDD4F',
'Xscr': '\uD835\uDCB3',
'YAcy': '\u042F',
'YIcy': '\u0407',
'YUcy': '\u042E',
'Yacute': '\u00DD',
'Ycirc': '\u0176',
'Ycy': '\u042B',
'Yfr': '\uD835\uDD1C',
'Yopf': '\uD835\uDD50',
'Yscr': '\uD835\uDCB4',
'Yuml': '\u0178',
'ZHcy': '\u0416',
'Zacute': '\u0179',
'Zcaron': '\u017D',
'Zcy': '\u0417',
'Zdot': '\u017B',
'Zeta': '\u0396',
'Zfr': '\u2128',
'zeetrf': '\u2128',
'Zopf': '\u2124',
'integers': '\u2124',
'Zscr': '\uD835\uDCB5',
'aacute': '\u00E1',
'abreve': '\u0103',
'ac': '\u223E',
'mstpos': '\u223E',
'acE': '\u223E\u0333',
'acd': '\u223F',
'acirc': '\u00E2',
'acy': '\u0430',
'aelig': '\u00E6',
'afr': '\uD835\uDD1E',
'agrave': '\u00E0',
'alefsym': '\u2135',
'aleph': '\u2135',
'alpha': '\u03B1',
'amacr': '\u0101',
'amalg': '\u2A3F',
'and': '\u2227',
'wedge': '\u2227',
'andand': '\u2A55',
'andd': '\u2A5C',
'andslope': '\u2A58',
'andv': '\u2A5A',
'ang': '\u2220',
'angle': '\u2220',
'ange': '\u29A4',
'angmsd': '\u2221',
'measuredangle': '\u2221',
'angmsdaa': '\u29A8',
'angmsdab': '\u29A9',
'angmsdac': '\u29AA',
'angmsdad': '\u29AB',
'angmsdae': '\u29AC',
'angmsdaf': '\u29AD',
'angmsdag': '\u29AE',
'angmsdah': '\u29AF',
'angrt': '\u221F',
'angrtvb': '\u22BE',
'angrtvbd': '\u299D',
'angsph': '\u2222',
'angzarr': '\u237C',
'aogon': '\u0105',
'aopf': '\uD835\uDD52',
'apE': '\u2A70',
'apacir': '\u2A6F',
'ape': '\u224A',
'approxeq': '\u224A',
'apid': '\u224B',
'apos': '\u0027',
'aring': '\u00E5',
'ascr': '\uD835\uDCB6',
'ast': '\u002A',
'midast': '\u002A',
'atilde': '\u00E3',
'auml': '\u00E4',
'awint': '\u2A11',
'bNot': '\u2AED',
'backcong': '\u224C',
'bcong': '\u224C',
'backepsilon': '\u03F6',
'bepsi': '\u03F6',
'backprime': '\u2035',
'bprime': '\u2035',
'backsim': '\u223D',
'bsim': '\u223D',
'backsimeq': '\u22CD',
'bsime': '\u22CD',
'barvee': '\u22BD',
'barwed': '\u2305',
'barwedge': '\u2305',
'bbrktbrk': '\u23B6',
'bcy': '\u0431',
'bdquo': '\u201E',
'ldquor': '\u201E',
'bemptyv': '\u29B0',
'beta': '\u03B2',
'beth': '\u2136',
'between': '\u226C',
'twixt': '\u226C',
'bfr': '\uD835\uDD1F',
'bigcirc': '\u25EF',
'xcirc': '\u25EF',
'bigodot': '\u2A00',
'xodot': '\u2A00',
'bigoplus': '\u2A01',
'xoplus': '\u2A01',
'bigotimes': '\u2A02',
'xotime': '\u2A02',
'bigsqcup': '\u2A06',
'xsqcup': '\u2A06',
'bigstar': '\u2605',
'starf': '\u2605',
'bigtriangledown': '\u25BD',
'xdtri': '\u25BD' | {
"end_byte": 26502,
"start_byte": 22426,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_26502_30570 | ,
'bigtriangleup': '\u25B3',
'xutri': '\u25B3',
'biguplus': '\u2A04',
'xuplus': '\u2A04',
'bkarow': '\u290D',
'rbarr': '\u290D',
'blacklozenge': '\u29EB',
'lozf': '\u29EB',
'blacktriangle': '\u25B4',
'utrif': '\u25B4',
'blacktriangledown': '\u25BE',
'dtrif': '\u25BE',
'blacktriangleleft': '\u25C2',
'ltrif': '\u25C2',
'blacktriangleright': '\u25B8',
'rtrif': '\u25B8',
'blank': '\u2423',
'blk12': '\u2592',
'blk14': '\u2591',
'blk34': '\u2593',
'block': '\u2588',
'bne': '\u003D\u20E5',
'bnequiv': '\u2261\u20E5',
'bnot': '\u2310',
'bopf': '\uD835\uDD53',
'bowtie': '\u22C8',
'boxDL': '\u2557',
'boxDR': '\u2554',
'boxDl': '\u2556',
'boxDr': '\u2553',
'boxH': '\u2550',
'boxHD': '\u2566',
'boxHU': '\u2569',
'boxHd': '\u2564',
'boxHu': '\u2567',
'boxUL': '\u255D',
'boxUR': '\u255A',
'boxUl': '\u255C',
'boxUr': '\u2559',
'boxV': '\u2551',
'boxVH': '\u256C',
'boxVL': '\u2563',
'boxVR': '\u2560',
'boxVh': '\u256B',
'boxVl': '\u2562',
'boxVr': '\u255F',
'boxbox': '\u29C9',
'boxdL': '\u2555',
'boxdR': '\u2552',
'boxdl': '\u2510',
'boxdr': '\u250C',
'boxhD': '\u2565',
'boxhU': '\u2568',
'boxhd': '\u252C',
'boxhu': '\u2534',
'boxminus': '\u229F',
'minusb': '\u229F',
'boxplus': '\u229E',
'plusb': '\u229E',
'boxtimes': '\u22A0',
'timesb': '\u22A0',
'boxuL': '\u255B',
'boxuR': '\u2558',
'boxul': '\u2518',
'boxur': '\u2514',
'boxv': '\u2502',
'boxvH': '\u256A',
'boxvL': '\u2561',
'boxvR': '\u255E',
'boxvh': '\u253C',
'boxvl': '\u2524',
'boxvr': '\u251C',
'brvbar': '\u00A6',
'bscr': '\uD835\uDCB7',
'bsemi': '\u204F',
'bsol': '\u005C',
'bsolb': '\u29C5',
'bsolhsub': '\u27C8',
'bull': '\u2022',
'bullet': '\u2022',
'bumpE': '\u2AAE',
'cacute': '\u0107',
'cap': '\u2229',
'capand': '\u2A44',
'capbrcup': '\u2A49',
'capcap': '\u2A4B',
'capcup': '\u2A47',
'capdot': '\u2A40',
'caps': '\u2229\uFE00',
'caret': '\u2041',
'ccaps': '\u2A4D',
'ccaron': '\u010D',
'ccedil': '\u00E7',
'ccirc': '\u0109',
'ccups': '\u2A4C',
'ccupssm': '\u2A50',
'cdot': '\u010B',
'cemptyv': '\u29B2',
'cent': '\u00A2',
'cfr': '\uD835\uDD20',
'chcy': '\u0447',
'check': '\u2713',
'checkmark': '\u2713',
'chi': '\u03C7',
'cir': '\u25CB',
'cirE': '\u29C3',
'circ': '\u02C6',
'circeq': '\u2257',
'cire': '\u2257',
'circlearrowleft': '\u21BA',
'olarr': '\u21BA',
'circlearrowright': '\u21BB',
'orarr': '\u21BB',
'circledS': '\u24C8',
'oS': '\u24C8',
'circledast': '\u229B',
'oast': '\u229B',
'circledcirc': '\u229A',
'ocir': '\u229A',
'circleddash': '\u229D',
'odash': '\u229D',
'cirfnint': '\u2A10',
'cirmid': '\u2AEF',
'cirscir': '\u29C2',
'clubs': '\u2663',
'clubsuit': '\u2663',
'colon': '\u003A',
'comma': '\u002C',
'commat': '\u0040',
'comp': '\u2201',
'complement': '\u2201',
'congdot': '\u2A6D',
'copf': '\uD835\uDD54',
'copysr': '\u2117',
'crarr': '\u21B5',
'cross': '\u2717',
'cscr': '\uD835\uDCB8',
'csub': '\u2ACF',
'csube': '\u2AD1',
'csup': '\u2AD0',
'csupe': '\u2AD2',
'ctdot': '\u22EF',
'cudarrl': '\u2938',
'cudarrr': '\u2935',
'cuepr': '\u22DE',
'curlyeqprec': '\u22DE',
'cuesc': '\u22DF',
'curlyeqsucc': '\u22DF',
'cularr': '\u21B6',
'curvearrowleft': '\u21B6',
'cularrp': '\u293D',
'cup': '\u222A',
'cupbrcap': '\u2A48',
'cupcap': '\u2A46',
'cupcup': '\u2A4A',
'cupdot': '\u228D',
'cupor': '\u2A45',
'cups': '\u222A\uFE00',
'curarr': '\u21B7',
'curvearrowright': '\u21B7',
'curarrm': '\u293C',
'curlyvee': '\u22CE',
'cuvee': '\u22CE',
'curlywedge': '\u22CF',
'cuwed': '\u22CF',
'curren': '\u00A4',
'cwint': '\u2231',
'cylcty': '\u232D',
'dHar': '\u2965',
'dagger': '\u2020',
'daleth': '\u2138',
'dash': '\u2010',
'hyphen': '\u2010',
'dbkarow': '\u290F',
'rBarr': '\u290F',
'dcaron': '\u010F',
'dcy': '\u0434',
'ddarr': '\u21CA',
'downdownarrows': '\u21CA',
'ddotseq': '\u2A77',
'eDDot': '\u2A77',
'deg': '\u00B0', | {
"end_byte": 30570,
"start_byte": 26502,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_30573_34624 | 'delta': '\u03B4',
'demptyv': '\u29B1',
'dfisht': '\u297F',
'dfr': '\uD835\uDD21',
'diamondsuit': '\u2666',
'diams': '\u2666',
'digamma': '\u03DD',
'gammad': '\u03DD',
'disin': '\u22F2',
'div': '\u00F7',
'divide': '\u00F7',
'divideontimes': '\u22C7',
'divonx': '\u22C7',
'djcy': '\u0452',
'dlcorn': '\u231E',
'llcorner': '\u231E',
'dlcrop': '\u230D',
'dollar': '\u0024',
'dopf': '\uD835\uDD55',
'doteqdot': '\u2251',
'eDot': '\u2251',
'dotminus': '\u2238',
'minusd': '\u2238',
'dotplus': '\u2214',
'plusdo': '\u2214',
'dotsquare': '\u22A1',
'sdotb': '\u22A1',
'drcorn': '\u231F',
'lrcorner': '\u231F',
'drcrop': '\u230C',
'dscr': '\uD835\uDCB9',
'dscy': '\u0455',
'dsol': '\u29F6',
'dstrok': '\u0111',
'dtdot': '\u22F1',
'dtri': '\u25BF',
'triangledown': '\u25BF',
'dwangle': '\u29A6',
'dzcy': '\u045F',
'dzigrarr': '\u27FF',
'eacute': '\u00E9',
'easter': '\u2A6E',
'ecaron': '\u011B',
'ecir': '\u2256',
'eqcirc': '\u2256',
'ecirc': '\u00EA',
'ecolon': '\u2255',
'eqcolon': '\u2255',
'ecy': '\u044D',
'edot': '\u0117',
'efDot': '\u2252',
'fallingdotseq': '\u2252',
'efr': '\uD835\uDD22',
'eg': '\u2A9A',
'egrave': '\u00E8',
'egs': '\u2A96',
'eqslantgtr': '\u2A96',
'egsdot': '\u2A98',
'el': '\u2A99',
'elinters': '\u23E7',
'ell': '\u2113',
'els': '\u2A95',
'eqslantless': '\u2A95',
'elsdot': '\u2A97',
'emacr': '\u0113',
'empty': '\u2205',
'emptyset': '\u2205',
'emptyv': '\u2205',
'varnothing': '\u2205',
'emsp13': '\u2004',
'emsp14': '\u2005',
'emsp': '\u2003',
'eng': '\u014B',
'ensp': '\u2002',
'eogon': '\u0119',
'eopf': '\uD835\uDD56',
'epar': '\u22D5',
'eparsl': '\u29E3',
'eplus': '\u2A71',
'epsi': '\u03B5',
'epsilon': '\u03B5',
'epsiv': '\u03F5',
'straightepsilon': '\u03F5',
'varepsilon': '\u03F5',
'equals': '\u003D',
'equest': '\u225F',
'questeq': '\u225F',
'equivDD': '\u2A78',
'eqvparsl': '\u29E5',
'erDot': '\u2253',
'risingdotseq': '\u2253',
'erarr': '\u2971',
'escr': '\u212F',
'eta': '\u03B7',
'eth': '\u00F0',
'euml': '\u00EB',
'euro': '\u20AC',
'excl': '\u0021',
'fcy': '\u0444',
'female': '\u2640',
'ffilig': '\uFB03',
'fflig': '\uFB00',
'ffllig': '\uFB04',
'ffr': '\uD835\uDD23',
'filig': '\uFB01',
'fjlig': '\u0066\u006A',
'flat': '\u266D',
'fllig': '\uFB02',
'fltns': '\u25B1',
'fnof': '\u0192',
'fopf': '\uD835\uDD57',
'fork': '\u22D4',
'pitchfork': '\u22D4',
'forkv': '\u2AD9',
'fpartint': '\u2A0D',
'frac12': '\u00BD',
'half': '\u00BD',
'frac13': '\u2153',
'frac14': '\u00BC',
'frac15': '\u2155',
'frac16': '\u2159',
'frac18': '\u215B',
'frac23': '\u2154',
'frac25': '\u2156',
'frac34': '\u00BE',
'frac35': '\u2157',
'frac38': '\u215C',
'frac45': '\u2158',
'frac56': '\u215A',
'frac58': '\u215D',
'frac78': '\u215E',
'frasl': '\u2044',
'frown': '\u2322',
'sfrown': '\u2322',
'fscr': '\uD835\uDCBB',
'gEl': '\u2A8C',
'gtreqqless': '\u2A8C',
'gacute': '\u01F5',
'gamma': '\u03B3',
'gap': '\u2A86',
'gtrapprox': '\u2A86',
'gbreve': '\u011F',
'gcirc': '\u011D',
'gcy': '\u0433',
'gdot': '\u0121',
'gescc': '\u2AA9',
'gesdot': '\u2A80',
'gesdoto': '\u2A82',
'gesdotol': '\u2A84',
'gesl': '\u22DB\uFE00',
'gesles': '\u2A94',
'gfr': '\uD835\uDD24',
'gimel': '\u2137',
'gjcy': '\u0453',
'glE': '\u2A92',
'gla': '\u2AA5',
'glj': '\u2AA4',
'gnE': '\u2269',
'gneqq': '\u2269',
'gnap': '\u2A8A',
'gnapprox': '\u2A8A',
'gne': '\u2A88',
'gneq': '\u2A88',
'gnsim': '\u22E7',
'gopf': '\uD835\uDD58',
'gscr': '\u210A',
'gsime': '\u2A8E',
'gsiml': '\u2A90',
'gtcc': '\u2AA7',
'gtcir': '\u2A7A',
'gtdot': '\u22D7',
'gtrdot': '\u22D7',
'gtlPar': '\u2995',
'gtquest': '\u2A7C',
'gtrarr': '\u2978',
'gvertneqq': '\u2269\uFE00',
'gvnE': '\u2269\uFE00',
'hardcy': '\u044A',
'harrcir': '\u2948',
'harrw': '\u21AD',
'leftrightsquigarrow': '\u21AD',
'hbar': '\u210F',
'hslash': '\u210F' | {
"end_byte": 34624,
"start_byte": 30573,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_34624_38647 | ,
'planck': '\u210F',
'plankv': '\u210F',
'hcirc': '\u0125',
'hearts': '\u2665',
'heartsuit': '\u2665',
'hellip': '\u2026',
'mldr': '\u2026',
'hercon': '\u22B9',
'hfr': '\uD835\uDD25',
'hksearow': '\u2925',
'searhk': '\u2925',
'hkswarow': '\u2926',
'swarhk': '\u2926',
'hoarr': '\u21FF',
'homtht': '\u223B',
'hookleftarrow': '\u21A9',
'larrhk': '\u21A9',
'hookrightarrow': '\u21AA',
'rarrhk': '\u21AA',
'hopf': '\uD835\uDD59',
'horbar': '\u2015',
'hscr': '\uD835\uDCBD',
'hstrok': '\u0127',
'hybull': '\u2043',
'iacute': '\u00ED',
'icirc': '\u00EE',
'icy': '\u0438',
'iecy': '\u0435',
'iexcl': '\u00A1',
'ifr': '\uD835\uDD26',
'igrave': '\u00EC',
'iiiint': '\u2A0C',
'qint': '\u2A0C',
'iiint': '\u222D',
'tint': '\u222D',
'iinfin': '\u29DC',
'iiota': '\u2129',
'ijlig': '\u0133',
'imacr': '\u012B',
'imath': '\u0131',
'inodot': '\u0131',
'imof': '\u22B7',
'imped': '\u01B5',
'incare': '\u2105',
'infin': '\u221E',
'infintie': '\u29DD',
'intcal': '\u22BA',
'intercal': '\u22BA',
'intlarhk': '\u2A17',
'intprod': '\u2A3C',
'iprod': '\u2A3C',
'iocy': '\u0451',
'iogon': '\u012F',
'iopf': '\uD835\uDD5A',
'iota': '\u03B9',
'iquest': '\u00BF',
'iscr': '\uD835\uDCBE',
'isinE': '\u22F9',
'isindot': '\u22F5',
'isins': '\u22F4',
'isinsv': '\u22F3',
'itilde': '\u0129',
'iukcy': '\u0456',
'iuml': '\u00EF',
'jcirc': '\u0135',
'jcy': '\u0439',
'jfr': '\uD835\uDD27',
'jmath': '\u0237',
'jopf': '\uD835\uDD5B',
'jscr': '\uD835\uDCBF',
'jsercy': '\u0458',
'jukcy': '\u0454',
'kappa': '\u03BA',
'kappav': '\u03F0',
'varkappa': '\u03F0',
'kcedil': '\u0137',
'kcy': '\u043A',
'kfr': '\uD835\uDD28',
'kgreen': '\u0138',
'khcy': '\u0445',
'kjcy': '\u045C',
'kopf': '\uD835\uDD5C',
'kscr': '\uD835\uDCC0',
'lAtail': '\u291B',
'lBarr': '\u290E',
'lEg': '\u2A8B',
'lesseqqgtr': '\u2A8B',
'lHar': '\u2962',
'lacute': '\u013A',
'laemptyv': '\u29B4',
'lambda': '\u03BB',
'langd': '\u2991',
'lap': '\u2A85',
'lessapprox': '\u2A85',
'laquo': '\u00AB',
'larrbfs': '\u291F',
'larrfs': '\u291D',
'larrlp': '\u21AB',
'looparrowleft': '\u21AB',
'larrpl': '\u2939',
'larrsim': '\u2973',
'larrtl': '\u21A2',
'leftarrowtail': '\u21A2',
'lat': '\u2AAB',
'latail': '\u2919',
'late': '\u2AAD',
'lates': '\u2AAD\uFE00',
'lbarr': '\u290C',
'lbbrk': '\u2772',
'lbrace': '\u007B',
'lcub': '\u007B',
'lbrack': '\u005B',
'lsqb': '\u005B',
'lbrke': '\u298B',
'lbrksld': '\u298F',
'lbrkslu': '\u298D',
'lcaron': '\u013E',
'lcedil': '\u013C',
'lcy': '\u043B',
'ldca': '\u2936',
'ldrdhar': '\u2967',
'ldrushar': '\u294B',
'ldsh': '\u21B2',
'le': '\u2264',
'leq': '\u2264',
'leftleftarrows': '\u21C7',
'llarr': '\u21C7',
'leftthreetimes': '\u22CB',
'lthree': '\u22CB',
'lescc': '\u2AA8',
'lesdot': '\u2A7F',
'lesdoto': '\u2A81',
'lesdotor': '\u2A83',
'lesg': '\u22DA\uFE00',
'lesges': '\u2A93',
'lessdot': '\u22D6',
'ltdot': '\u22D6',
'lfisht': '\u297C',
'lfr': '\uD835\uDD29',
'lgE': '\u2A91',
'lharul': '\u296A',
'lhblk': '\u2584',
'ljcy': '\u0459',
'llhard': '\u296B',
'lltri': '\u25FA',
'lmidot': '\u0140',
'lmoust': '\u23B0',
'lmoustache': '\u23B0',
'lnE': '\u2268',
'lneqq': '\u2268',
'lnap': '\u2A89',
'lnapprox': '\u2A89',
'lne': '\u2A87',
'lneq': '\u2A87',
'lnsim': '\u22E6',
'loang': '\u27EC',
'loarr': '\u21FD',
'longmapsto': '\u27FC',
'xmap': '\u27FC',
'looparrowright': '\u21AC',
'rarrlp': '\u21AC',
'lopar': '\u2985',
'lopf': '\uD835\uDD5D',
'loplus': '\u2A2D',
'lotimes': '\u2A34',
'lowast': '\u2217',
'loz': '\u25CA',
'lozenge': '\u25CA',
'lpar': '\u0028',
'lparlt': '\u2993',
'lrhard': '\u296D',
'lrm': '\u200E',
'lrtri': '\u22BF',
'lsaquo': '\u2039',
'lscr': '\uD835\uDCC1',
'lsime': '\u2A8D',
'lsimg': '\u2A8F',
'lsquor': '\u201A',
'sbquo': '\u201A',
'lstrok': '\u0142',
'ltcc': '\u2AA6', | {
"end_byte": 38647,
"start_byte": 34624,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_38650_42628 | 'ltcir': '\u2A79',
'ltimes': '\u22C9',
'ltlarr': '\u2976',
'ltquest': '\u2A7B',
'ltrPar': '\u2996',
'ltri': '\u25C3',
'triangleleft': '\u25C3',
'lurdshar': '\u294A',
'luruhar': '\u2966',
'lvertneqq': '\u2268\uFE00',
'lvnE': '\u2268\uFE00',
'mDDot': '\u223A',
'macr': '\u00AF',
'strns': '\u00AF',
'male': '\u2642',
'malt': '\u2720',
'maltese': '\u2720',
'marker': '\u25AE',
'mcomma': '\u2A29',
'mcy': '\u043C',
'mdash': '\u2014',
'mfr': '\uD835\uDD2A',
'mho': '\u2127',
'micro': '\u00B5',
'midcir': '\u2AF0',
'minus': '\u2212',
'minusdu': '\u2A2A',
'mlcp': '\u2ADB',
'models': '\u22A7',
'mopf': '\uD835\uDD5E',
'mscr': '\uD835\uDCC2',
'mu': '\u03BC',
'multimap': '\u22B8',
'mumap': '\u22B8',
'nGg': '\u22D9\u0338',
'nGt': '\u226B\u20D2',
'nLeftarrow': '\u21CD',
'nlArr': '\u21CD',
'nLeftrightarrow': '\u21CE',
'nhArr': '\u21CE',
'nLl': '\u22D8\u0338',
'nLt': '\u226A\u20D2',
'nRightarrow': '\u21CF',
'nrArr': '\u21CF',
'nVDash': '\u22AF',
'nVdash': '\u22AE',
'nacute': '\u0144',
'nang': '\u2220\u20D2',
'napE': '\u2A70\u0338',
'napid': '\u224B\u0338',
'napos': '\u0149',
'natur': '\u266E',
'natural': '\u266E',
'ncap': '\u2A43',
'ncaron': '\u0148',
'ncedil': '\u0146',
'ncongdot': '\u2A6D\u0338',
'ncup': '\u2A42',
'ncy': '\u043D',
'ndash': '\u2013',
'neArr': '\u21D7',
'nearhk': '\u2924',
'nedot': '\u2250\u0338',
'nesear': '\u2928',
'toea': '\u2928',
'nfr': '\uD835\uDD2B',
'nharr': '\u21AE',
'nleftrightarrow': '\u21AE',
'nhpar': '\u2AF2',
'nis': '\u22FC',
'nisd': '\u22FA',
'njcy': '\u045A',
'nlE': '\u2266\u0338',
'nleqq': '\u2266\u0338',
'nlarr': '\u219A',
'nleftarrow': '\u219A',
'nldr': '\u2025',
'nopf': '\uD835\uDD5F',
'not': '\u00AC',
'notinE': '\u22F9\u0338',
'notindot': '\u22F5\u0338',
'notinvb': '\u22F7',
'notinvc': '\u22F6',
'notnivb': '\u22FE',
'notnivc': '\u22FD',
'nparsl': '\u2AFD\u20E5',
'npart': '\u2202\u0338',
'npolint': '\u2A14',
'nrarr': '\u219B',
'nrightarrow': '\u219B',
'nrarrc': '\u2933\u0338',
'nrarrw': '\u219D\u0338',
'nscr': '\uD835\uDCC3',
'nsub': '\u2284',
'nsubE': '\u2AC5\u0338',
'nsubseteqq': '\u2AC5\u0338',
'nsup': '\u2285',
'nsupE': '\u2AC6\u0338',
'nsupseteqq': '\u2AC6\u0338',
'ntilde': '\u00F1',
'nu': '\u03BD',
'num': '\u0023',
'numero': '\u2116',
'numsp': '\u2007',
'nvDash': '\u22AD',
'nvHarr': '\u2904',
'nvap': '\u224D\u20D2',
'nvdash': '\u22AC',
'nvge': '\u2265\u20D2',
'nvgt': '\u003E\u20D2',
'nvinfin': '\u29DE',
'nvlArr': '\u2902',
'nvle': '\u2264\u20D2',
'nvlt': '\u003C\u20D2',
'nvltrie': '\u22B4\u20D2',
'nvrArr': '\u2903',
'nvrtrie': '\u22B5\u20D2',
'nvsim': '\u223C\u20D2',
'nwArr': '\u21D6',
'nwarhk': '\u2923',
'nwnear': '\u2927',
'oacute': '\u00F3',
'ocirc': '\u00F4',
'ocy': '\u043E',
'odblac': '\u0151',
'odiv': '\u2A38',
'odsold': '\u29BC',
'oelig': '\u0153',
'ofcir': '\u29BF',
'ofr': '\uD835\uDD2C',
'ogon': '\u02DB',
'ograve': '\u00F2',
'ogt': '\u29C1',
'ohbar': '\u29B5',
'olcir': '\u29BE',
'olcross': '\u29BB',
'olt': '\u29C0',
'omacr': '\u014D',
'omega': '\u03C9',
'omicron': '\u03BF',
'omid': '\u29B6',
'oopf': '\uD835\uDD60',
'opar': '\u29B7',
'operp': '\u29B9',
'or': '\u2228',
'vee': '\u2228',
'ord': '\u2A5D',
'order': '\u2134',
'orderof': '\u2134',
'oscr': '\u2134',
'ordf': '\u00AA',
'ordm': '\u00BA',
'origof': '\u22B6',
'oror': '\u2A56',
'orslope': '\u2A57',
'orv': '\u2A5B',
'oslash': '\u00F8',
'osol': '\u2298',
'otilde': '\u00F5',
'otimesas': '\u2A36',
'ouml': '\u00F6',
'ovbar': '\u233D',
'para': '\u00B6',
'parsim': '\u2AF3',
'parsl': '\u2AFD',
'pcy': '\u043F',
'percnt': '\u0025',
'period': '\u002E',
'permil': '\u2030',
'pertenk': '\u2031',
'pfr': '\uD835\uDD2D',
'phi': '\u03C6',
'phiv': '\u03D5',
'straightphi': '\u03D5',
'varphi': '\u03D5', | {
"end_byte": 42628,
"start_byte": 38650,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_42631_46644 | 'phone': '\u260E',
'pi': '\u03C0',
'piv': '\u03D6',
'varpi': '\u03D6',
'planckh': '\u210E',
'plus': '\u002B',
'plusacir': '\u2A23',
'pluscir': '\u2A22',
'plusdu': '\u2A25',
'pluse': '\u2A72',
'plussim': '\u2A26',
'plustwo': '\u2A27',
'pointint': '\u2A15',
'popf': '\uD835\uDD61',
'pound': '\u00A3',
'prE': '\u2AB3',
'prap': '\u2AB7',
'precapprox': '\u2AB7',
'precnapprox': '\u2AB9',
'prnap': '\u2AB9',
'precneqq': '\u2AB5',
'prnE': '\u2AB5',
'precnsim': '\u22E8',
'prnsim': '\u22E8',
'prime': '\u2032',
'profalar': '\u232E',
'profline': '\u2312',
'profsurf': '\u2313',
'prurel': '\u22B0',
'pscr': '\uD835\uDCC5',
'psi': '\u03C8',
'puncsp': '\u2008',
'qfr': '\uD835\uDD2E',
'qopf': '\uD835\uDD62',
'qprime': '\u2057',
'qscr': '\uD835\uDCC6',
'quatint': '\u2A16',
'quest': '\u003F',
'rAtail': '\u291C',
'rHar': '\u2964',
'race': '\u223D\u0331',
'racute': '\u0155',
'raemptyv': '\u29B3',
'rangd': '\u2992',
'range': '\u29A5',
'raquo': '\u00BB',
'rarrap': '\u2975',
'rarrbfs': '\u2920',
'rarrc': '\u2933',
'rarrfs': '\u291E',
'rarrpl': '\u2945',
'rarrsim': '\u2974',
'rarrtl': '\u21A3',
'rightarrowtail': '\u21A3',
'rarrw': '\u219D',
'rightsquigarrow': '\u219D',
'ratail': '\u291A',
'ratio': '\u2236',
'rbbrk': '\u2773',
'rbrace': '\u007D',
'rcub': '\u007D',
'rbrack': '\u005D',
'rsqb': '\u005D',
'rbrke': '\u298C',
'rbrksld': '\u298E',
'rbrkslu': '\u2990',
'rcaron': '\u0159',
'rcedil': '\u0157',
'rcy': '\u0440',
'rdca': '\u2937',
'rdldhar': '\u2969',
'rdsh': '\u21B3',
'rect': '\u25AD',
'rfisht': '\u297D',
'rfr': '\uD835\uDD2F',
'rharul': '\u296C',
'rho': '\u03C1',
'rhov': '\u03F1',
'varrho': '\u03F1',
'rightrightarrows': '\u21C9',
'rrarr': '\u21C9',
'rightthreetimes': '\u22CC',
'rthree': '\u22CC',
'ring': '\u02DA',
'rlm': '\u200F',
'rmoust': '\u23B1',
'rmoustache': '\u23B1',
'rnmid': '\u2AEE',
'roang': '\u27ED',
'roarr': '\u21FE',
'ropar': '\u2986',
'ropf': '\uD835\uDD63',
'roplus': '\u2A2E',
'rotimes': '\u2A35',
'rpar': '\u0029',
'rpargt': '\u2994',
'rppolint': '\u2A12',
'rsaquo': '\u203A',
'rscr': '\uD835\uDCC7',
'rtimes': '\u22CA',
'rtri': '\u25B9',
'triangleright': '\u25B9',
'rtriltri': '\u29CE',
'ruluhar': '\u2968',
'rx': '\u211E',
'sacute': '\u015B',
'scE': '\u2AB4',
'scap': '\u2AB8',
'succapprox': '\u2AB8',
'scaron': '\u0161',
'scedil': '\u015F',
'scirc': '\u015D',
'scnE': '\u2AB6',
'succneqq': '\u2AB6',
'scnap': '\u2ABA',
'succnapprox': '\u2ABA',
'scnsim': '\u22E9',
'succnsim': '\u22E9',
'scpolint': '\u2A13',
'scy': '\u0441',
'sdot': '\u22C5',
'sdote': '\u2A66',
'seArr': '\u21D8',
'sect': '\u00A7',
'semi': '\u003B',
'seswar': '\u2929',
'tosa': '\u2929',
'sext': '\u2736',
'sfr': '\uD835\uDD30',
'sharp': '\u266F',
'shchcy': '\u0449',
'shcy': '\u0448',
'shy': '\u00AD',
'sigma': '\u03C3',
'sigmaf': '\u03C2',
'sigmav': '\u03C2',
'varsigma': '\u03C2',
'simdot': '\u2A6A',
'simg': '\u2A9E',
'simgE': '\u2AA0',
'siml': '\u2A9D',
'simlE': '\u2A9F',
'simne': '\u2246',
'simplus': '\u2A24',
'simrarr': '\u2972',
'smashp': '\u2A33',
'smeparsl': '\u29E4',
'smile': '\u2323',
'ssmile': '\u2323',
'smt': '\u2AAA',
'smte': '\u2AAC',
'smtes': '\u2AAC\uFE00',
'softcy': '\u044C',
'sol': '\u002F',
'solb': '\u29C4',
'solbar': '\u233F',
'sopf': '\uD835\uDD64',
'spades': '\u2660',
'spadesuit': '\u2660',
'sqcaps': '\u2293\uFE00',
'sqcups': '\u2294\uFE00',
'sscr': '\uD835\uDCC8',
'star': '\u2606',
'sub': '\u2282',
'subset': '\u2282',
'subE': '\u2AC5',
'subseteqq': '\u2AC5',
'subdot': '\u2ABD',
'subedot': '\u2AC3',
'submult': '\u2AC1',
'subnE': '\u2ACB',
'subsetneqq': '\u2ACB',
'subne': '\u228A',
'subsetneq': '\u228A',
'subplus': '\u2ABF',
'subrarr': '\u2979',
'subsim': '\u2AC7',
'subsub': '\u2AD5',
'subsup': '\u2AD3',
'sung': '\u266A', | {
"end_byte": 46644,
"start_byte": 42631,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/entities.ts_46647_50159 | 'sup1': '\u00B9',
'sup2': '\u00B2',
'sup3': '\u00B3',
'supE': '\u2AC6',
'supseteqq': '\u2AC6',
'supdot': '\u2ABE',
'supdsub': '\u2AD8',
'supedot': '\u2AC4',
'suphsol': '\u27C9',
'suphsub': '\u2AD7',
'suplarr': '\u297B',
'supmult': '\u2AC2',
'supnE': '\u2ACC',
'supsetneqq': '\u2ACC',
'supne': '\u228B',
'supsetneq': '\u228B',
'supplus': '\u2AC0',
'supsim': '\u2AC8',
'supsub': '\u2AD4',
'supsup': '\u2AD6',
'swArr': '\u21D9',
'swnwar': '\u292A',
'szlig': '\u00DF',
'target': '\u2316',
'tau': '\u03C4',
'tcaron': '\u0165',
'tcedil': '\u0163',
'tcy': '\u0442',
'telrec': '\u2315',
'tfr': '\uD835\uDD31',
'theta': '\u03B8',
'thetasym': '\u03D1',
'thetav': '\u03D1',
'vartheta': '\u03D1',
'thorn': '\u00FE',
'times': '\u00D7',
'timesbar': '\u2A31',
'timesd': '\u2A30',
'topbot': '\u2336',
'topcir': '\u2AF1',
'topf': '\uD835\uDD65',
'topfork': '\u2ADA',
'tprime': '\u2034',
'triangle': '\u25B5',
'utri': '\u25B5',
'triangleq': '\u225C',
'trie': '\u225C',
'tridot': '\u25EC',
'triminus': '\u2A3A',
'triplus': '\u2A39',
'trisb': '\u29CD',
'tritime': '\u2A3B',
'trpezium': '\u23E2',
'tscr': '\uD835\uDCC9',
'tscy': '\u0446',
'tshcy': '\u045B',
'tstrok': '\u0167',
'uHar': '\u2963',
'uacute': '\u00FA',
'ubrcy': '\u045E',
'ubreve': '\u016D',
'ucirc': '\u00FB',
'ucy': '\u0443',
'udblac': '\u0171',
'ufisht': '\u297E',
'ufr': '\uD835\uDD32',
'ugrave': '\u00F9',
'uhblk': '\u2580',
'ulcorn': '\u231C',
'ulcorner': '\u231C',
'ulcrop': '\u230F',
'ultri': '\u25F8',
'umacr': '\u016B',
'uogon': '\u0173',
'uopf': '\uD835\uDD66',
'upsi': '\u03C5',
'upsilon': '\u03C5',
'upuparrows': '\u21C8',
'uuarr': '\u21C8',
'urcorn': '\u231D',
'urcorner': '\u231D',
'urcrop': '\u230E',
'uring': '\u016F',
'urtri': '\u25F9',
'uscr': '\uD835\uDCCA',
'utdot': '\u22F0',
'utilde': '\u0169',
'uuml': '\u00FC',
'uwangle': '\u29A7',
'vBar': '\u2AE8',
'vBarv': '\u2AE9',
'vangrt': '\u299C',
'varsubsetneq': '\u228A\uFE00',
'vsubne': '\u228A\uFE00',
'varsubsetneqq': '\u2ACB\uFE00',
'vsubnE': '\u2ACB\uFE00',
'varsupsetneq': '\u228B\uFE00',
'vsupne': '\u228B\uFE00',
'varsupsetneqq': '\u2ACC\uFE00',
'vsupnE': '\u2ACC\uFE00',
'vcy': '\u0432',
'veebar': '\u22BB',
'veeeq': '\u225A',
'vellip': '\u22EE',
'vfr': '\uD835\uDD33',
'vopf': '\uD835\uDD67',
'vscr': '\uD835\uDCCB',
'vzigzag': '\u299A',
'wcirc': '\u0175',
'wedbar': '\u2A5F',
'wedgeq': '\u2259',
'weierp': '\u2118',
'wp': '\u2118',
'wfr': '\uD835\uDD34',
'wopf': '\uD835\uDD68',
'wscr': '\uD835\uDCCC',
'xfr': '\uD835\uDD35',
'xi': '\u03BE',
'xnis': '\u22FB',
'xopf': '\uD835\uDD69',
'xscr': '\uD835\uDCCD',
'yacute': '\u00FD',
'yacy': '\u044F',
'ycirc': '\u0177',
'ycy': '\u044B',
'yen': '\u00A5',
'yfr': '\uD835\uDD36',
'yicy': '\u0457',
'yopf': '\uD835\uDD6A',
'yscr': '\uD835\uDCCE',
'yucy': '\u044E',
'yuml': '\u00FF',
'zacute': '\u017A',
'zcaron': '\u017E',
'zcy': '\u0437',
'zdot': '\u017C',
'zeta': '\u03B6',
'zfr': '\uD835\uDD37',
'zhcy': '\u0436',
'zigrarr': '\u21DD',
'zopf': '\uD835\uDD6B',
'zscr': '\uD835\uDCCF',
'zwj': '\u200D',
'zwnj': '\u200C',
};
// The &ngsp; pseudo-entity is denoting a space.
// 0xE500 is a PUA (Private Use Areas) unicode character
// This is inspired by the Angular Dart implementation.
export const NGSP_UNICODE = '\uE500';
NAMED_ENTITIES['ngsp'] = NGSP_UNICODE; | {
"end_byte": 50159,
"start_byte": 46647,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/entities.ts"
} |
angular/packages/compiler/src/ml_parser/html_whitespaces.ts_0_8648 | /**
* @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.dev/license
*/
import * as html from './ast';
import {NGSP_UNICODE} from './entities';
import {ParseTreeResult} from './parser';
import {InterpolatedTextToken, TextToken, TokenType} from './tokens';
export const PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
const SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
// Equivalent to \s with \u00a0 (non-breaking space) excluded.
// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
const WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
const NO_WS_REGEXP = new RegExp(`[^${WS_CHARS}]`);
const WS_REPLACE_REGEXP = new RegExp(`[${WS_CHARS}]{2,}`, 'g');
function hasPreserveWhitespacesAttr(attrs: html.Attribute[]): boolean {
return attrs.some((attr: html.Attribute) => attr.name === PRESERVE_WS_ATTR_NAME);
}
/**
* &ngsp; is a placeholder for non-removable space
* &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
* and later on replaced by a space.
*/
export function replaceNgsp(value: string): string {
// lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
}
/**
* This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
* - consider spaces, tabs and new lines as whitespace characters;
* - drop text nodes consisting of whitespace characters only;
* - for all other text nodes replace consecutive whitespace characters with one space;
* - convert &ngsp; pseudo-entity to a single space;
*
* Removal and trimming of whitespaces have positive performance impact (less code to generate
* while compiling templates, faster view creation). At the same time it can be "destructive"
* in some cases (whitespaces can influence layout). Because of the potential of breaking layout
* this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
* whitespace removal. The default option for whitespace removal will be revisited in Angular 6
* and might be changed to "on" by default.
*
* If `originalNodeMap` is provided, the transformed nodes will be mapped back to their original
* inputs. Any output nodes not in the map were not transformed. This supports correlating and
* porting information between the trimmed nodes and original nodes (such as `i18n` properties)
* such that trimming whitespace does not does not drop required information from the node.
*/
export class WhitespaceVisitor implements html.Visitor {
// How many ICU expansions which are currently being visited. ICUs can be nested, so this
// tracks the current depth of nesting. If this depth is greater than 0, then this visitor is
// currently processing content inside an ICU expansion.
private icuExpansionDepth = 0;
constructor(
private readonly preserveSignificantWhitespace: boolean,
private readonly originalNodeMap?: Map<html.Node, html.Node>,
private readonly requireContext = true,
) {}
visitElement(element: html.Element, context: any): any {
if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
// don't descent into elements where we need to preserve whitespaces
// but still visit all attributes to eliminate one used as a market to preserve WS
const newElement = new html.Element(
element.name,
visitAllWithSiblings(this, element.attrs),
element.children,
element.sourceSpan,
element.startSourceSpan,
element.endSourceSpan,
element.i18n,
);
this.originalNodeMap?.set(newElement, element);
return newElement;
}
const newElement = new html.Element(
element.name,
element.attrs,
visitAllWithSiblings(this, element.children),
element.sourceSpan,
element.startSourceSpan,
element.endSourceSpan,
element.i18n,
);
this.originalNodeMap?.set(newElement, element);
return newElement;
}
visitAttribute(attribute: html.Attribute, context: any): any {
return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
}
visitText(text: html.Text, context: SiblingVisitorContext | null): any {
const isNotBlank = text.value.match(NO_WS_REGEXP);
const hasExpansionSibling =
context && (context.prev instanceof html.Expansion || context.next instanceof html.Expansion);
// Do not trim whitespace within ICU expansions when preserving significant whitespace.
// Historically, ICU whitespace was never trimmed and this is really a bug. However fixing it
// would change message IDs which we can't easily do. Instead we only trim ICU whitespace within
// ICU expansions when not preserving significant whitespace, which is the new behavior where it
// most matters.
const inIcuExpansion = this.icuExpansionDepth > 0;
if (inIcuExpansion && this.preserveSignificantWhitespace) return text;
if (isNotBlank || hasExpansionSibling) {
// Process the whitespace in the tokens of this Text node
const tokens = text.tokens.map((token) =>
token.type === TokenType.TEXT ? createWhitespaceProcessedTextToken(token) : token,
);
// Fully trim message when significant whitespace is not preserved.
if (!this.preserveSignificantWhitespace && tokens.length > 0) {
// The first token should only call `.trimStart()` and the last token
// should only call `.trimEnd()`, but there might be only one token which
// needs to call both.
const firstToken = tokens[0]!;
tokens.splice(0, 1, trimLeadingWhitespace(firstToken, context));
const lastToken = tokens[tokens.length - 1]; // Could be the same as the first token.
tokens.splice(tokens.length - 1, 1, trimTrailingWhitespace(lastToken, context));
}
// Process the whitespace of the value of this Text node. Also trim the leading/trailing
// whitespace when we don't need to preserve significant whitespace.
const processed = processWhitespace(text.value);
const value = this.preserveSignificantWhitespace
? processed
: trimLeadingAndTrailingWhitespace(processed, context);
const result = new html.Text(value, text.sourceSpan, tokens, text.i18n);
this.originalNodeMap?.set(result, text);
return result;
}
return null;
}
visitComment(comment: html.Comment, context: any): any {
return comment;
}
visitExpansion(expansion: html.Expansion, context: any): any {
this.icuExpansionDepth++;
let newExpansion: html.Expansion;
try {
newExpansion = new html.Expansion(
expansion.switchValue,
expansion.type,
visitAllWithSiblings(this, expansion.cases),
expansion.sourceSpan,
expansion.switchValueSourceSpan,
expansion.i18n,
);
} finally {
this.icuExpansionDepth--;
}
this.originalNodeMap?.set(newExpansion, expansion);
return newExpansion;
}
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any {
const newExpansionCase = new html.ExpansionCase(
expansionCase.value,
visitAllWithSiblings(this, expansionCase.expression),
expansionCase.sourceSpan,
expansionCase.valueSourceSpan,
expansionCase.expSourceSpan,
);
this.originalNodeMap?.set(newExpansionCase, expansionCase);
return newExpansionCase;
}
visitBlock(block: html.Block, context: any): any {
const newBlock = new html.Block(
block.name,
block.parameters,
visitAllWithSiblings(this, block.children),
block.sourceSpan,
block.nameSpan,
block.startSourceSpan,
block.endSourceSpan,
);
this.originalNodeMap?.set(newBlock, block);
return newBlock;
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {
return parameter;
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
return decl;
}
visit(_node: html.Node, context: any) {
// `visitAllWithSiblings` provides context necessary for ICU messages to be handled correctly.
// Prefer that over calling `html.visitAll` directly on this visitor.
if (this.requireContext && !context) {
throw new Error(
`WhitespaceVisitor requires context. Visit via \`visitAllWithSiblings\` to get this context.`,
);
}
return false;
}
} | {
"end_byte": 8648,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/html_whitespaces.ts"
} |
angular/packages/compiler/src/ml_parser/html_whitespaces.ts_8650_11079 | function trimLeadingWhitespace(
token: InterpolatedTextToken,
context: SiblingVisitorContext | null,
): InterpolatedTextToken {
if (token.type !== TokenType.TEXT) return token;
const isFirstTokenInTag = !context?.prev;
if (!isFirstTokenInTag) return token;
return transformTextToken(token, (text) => text.trimStart());
}
function trimTrailingWhitespace(
token: InterpolatedTextToken,
context: SiblingVisitorContext | null,
): InterpolatedTextToken {
if (token.type !== TokenType.TEXT) return token;
const isLastTokenInTag = !context?.next;
if (!isLastTokenInTag) return token;
return transformTextToken(token, (text) => text.trimEnd());
}
function trimLeadingAndTrailingWhitespace(
text: string,
context: SiblingVisitorContext | null,
): string {
const isFirstTokenInTag = !context?.prev;
const isLastTokenInTag = !context?.next;
const maybeTrimmedStart = isFirstTokenInTag ? text.trimStart() : text;
const maybeTrimmed = isLastTokenInTag ? maybeTrimmedStart.trimEnd() : maybeTrimmedStart;
return maybeTrimmed;
}
function createWhitespaceProcessedTextToken({type, parts, sourceSpan}: TextToken): TextToken {
return {type, parts: [processWhitespace(parts[0])], sourceSpan};
}
function transformTextToken(
{type, parts, sourceSpan}: TextToken,
transform: (parts: string) => string,
): TextToken {
// `TextToken` only ever has one part as defined in its type, so we just transform the first element.
return {type, parts: [transform(parts[0])], sourceSpan};
}
function processWhitespace(text: string): string {
return replaceNgsp(text).replace(WS_REPLACE_REGEXP, ' ');
}
export function removeWhitespaces(
htmlAstWithErrors: ParseTreeResult,
preserveSignificantWhitespace: boolean,
): ParseTreeResult {
return new ParseTreeResult(
visitAllWithSiblings(
new WhitespaceVisitor(preserveSignificantWhitespace),
htmlAstWithErrors.rootNodes,
),
htmlAstWithErrors.errors,
);
}
interface SiblingVisitorContext {
prev: html.Node | undefined;
next: html.Node | undefined;
}
export function visitAllWithSiblings(visitor: WhitespaceVisitor, nodes: html.Node[]): any[] {
const result: any[] = [];
nodes.forEach((ast, i) => {
const context: SiblingVisitorContext = {prev: nodes[i - 1], next: nodes[i + 1]};
const astResult = ast.visit(visitor, context);
if (astResult) {
result.push(astResult);
}
});
return result;
} | {
"end_byte": 11079,
"start_byte": 8650,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/html_whitespaces.ts"
} |
angular/packages/compiler/src/ml_parser/defaults.ts_0_813 | /**
* @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.dev/license
*/
import {assertInterpolationSymbols} from '../assertions';
export class InterpolationConfig {
static fromArray(markers: [string, string] | null): InterpolationConfig {
if (!markers) {
return DEFAULT_INTERPOLATION_CONFIG;
}
assertInterpolationSymbols('interpolation', markers);
return new InterpolationConfig(markers[0], markers[1]);
}
constructor(
public start: string,
public end: string,
) {}
}
export const DEFAULT_INTERPOLATION_CONFIG: InterpolationConfig = new InterpolationConfig(
'{{',
'}}',
);
export const DEFAULT_CONTAINER_BLOCKS = new Set(['switch']);
| {
"end_byte": 813,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/defaults.ts"
} |
angular/packages/compiler/src/ml_parser/lexer.ts_0_4573 | /**
* @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.dev/license
*/
import * as chars from '../chars';
import {ParseError, ParseLocation, ParseSourceFile, ParseSourceSpan} from '../parse_util';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from './defaults';
import {NAMED_ENTITIES} from './entities';
import {TagContentType, TagDefinition} from './tags';
import {IncompleteTagOpenToken, TagOpenStartToken, Token, TokenType} from './tokens';
export class TokenError extends ParseError {
constructor(
errorMsg: string,
public tokenType: TokenType | null,
span: ParseSourceSpan,
) {
super(span, errorMsg);
}
}
export class TokenizeResult {
constructor(
public tokens: Token[],
public errors: TokenError[],
public nonNormalizedIcuExpressions: Token[],
) {}
}
export interface LexerRange {
startPos: number;
startLine: number;
startCol: number;
endPos: number;
}
/**
* Options that modify how the text is tokenized.
*/
export interface TokenizeOptions {
/** Whether to tokenize ICU messages (considered as text nodes when false). */
tokenizeExpansionForms?: boolean;
/** How to tokenize interpolation markers. */
interpolationConfig?: InterpolationConfig;
/**
* The start and end point of the text to parse within the `source` string.
* The entire `source` string is parsed if this is not provided.
* */
range?: LexerRange;
/**
* If this text is stored in a JavaScript string, then we have to deal with escape sequences.
*
* **Example 1:**
*
* ```
* "abc\"def\nghi"
* ```
*
* - The `\"` must be converted to `"`.
* - The `\n` must be converted to a new line character in a token,
* but it should not increment the current line for source mapping.
*
* **Example 2:**
*
* ```
* "abc\
* def"
* ```
*
* The line continuation (`\` followed by a newline) should be removed from a token
* but the new line should increment the current line for source mapping.
*/
escapedString?: boolean;
/**
* If this text is stored in an external template (e.g. via `templateUrl`) then we need to decide
* whether or not to normalize the line-endings (from `\r\n` to `\n`) when processing ICU
* expressions.
*
* If `true` then we will normalize ICU expression line endings.
* The default is `false`, but this will be switched in a future major release.
*/
i18nNormalizeLineEndingsInICUs?: boolean;
/**
* An array of characters that should be considered as leading trivia.
* Leading trivia are characters that are not important to the developer, and so should not be
* included in source-map segments. A common example is whitespace.
*/
leadingTriviaChars?: string[];
/**
* If true, do not convert CRLF to LF.
*/
preserveLineEndings?: boolean;
/**
* Whether to tokenize @ block syntax. Otherwise considered text,
* or ICU tokens if `tokenizeExpansionForms` is enabled.
*/
tokenizeBlocks?: boolean;
/**
* Whether to tokenize the `@let` syntax. Otherwise will be considered either
* text or an incomplete block, depending on whether `tokenizeBlocks` is enabled.
*/
tokenizeLet?: boolean;
}
export function tokenize(
source: string,
url: string,
getTagDefinition: (tagName: string) => TagDefinition,
options: TokenizeOptions = {},
): TokenizeResult {
const tokenizer = new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options);
tokenizer.tokenize();
return new TokenizeResult(
mergeTextTokens(tokenizer.tokens),
tokenizer.errors,
tokenizer.nonNormalizedIcuExpressions,
);
}
const _CR_OR_CRLF_REGEXP = /\r\n?/g;
function _unexpectedCharacterErrorMsg(charCode: number): string {
const char = charCode === chars.$EOF ? 'EOF' : String.fromCharCode(charCode);
return `Unexpected character "${char}"`;
}
function _unknownEntityErrorMsg(entitySrc: string): string {
return `Unknown entity "${entitySrc}" - use the "&#<decimal>;" or "&#x<hex>;" syntax`;
}
function _unparsableEntityErrorMsg(type: CharacterReferenceType, entityStr: string): string {
return `Unable to parse entity "${entityStr}" - ${type} character reference entities must end with ";"`;
}
enum CharacterReferenceType {
HEX = 'hexadecimal',
DEC = 'decimal',
}
class _ControlFlowError {
constructor(public error: TokenError) {}
}
// See https://www.w3.org/TR/html51/syntax.html#writing-html-documents | {
"end_byte": 4573,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/lexer.ts"
} |
angular/packages/compiler/src/ml_parser/lexer.ts_4574_12105 | class _Tokenizer {
private _cursor: CharacterCursor;
private _tokenizeIcu: boolean;
private _interpolationConfig: InterpolationConfig;
private _leadingTriviaCodePoints: number[] | undefined;
private _currentTokenStart: CharacterCursor | null = null;
private _currentTokenType: TokenType | null = null;
private _expansionCaseStack: TokenType[] = [];
private _inInterpolation: boolean = false;
private readonly _preserveLineEndings: boolean;
private readonly _i18nNormalizeLineEndingsInICUs: boolean;
private readonly _tokenizeBlocks: boolean;
private readonly _tokenizeLet: boolean;
tokens: Token[] = [];
errors: TokenError[] = [];
nonNormalizedIcuExpressions: Token[] = [];
/**
* @param _file The html source file being tokenized.
* @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
* @param options Configuration of the tokenization.
*/
constructor(
_file: ParseSourceFile,
private _getTagDefinition: (tagName: string) => TagDefinition,
options: TokenizeOptions,
) {
this._tokenizeIcu = options.tokenizeExpansionForms || false;
this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
this._leadingTriviaCodePoints =
options.leadingTriviaChars && options.leadingTriviaChars.map((c) => c.codePointAt(0) || 0);
const range = options.range || {
endPos: _file.content.length,
startPos: 0,
startLine: 0,
startCol: 0,
};
this._cursor = options.escapedString
? new EscapedCharacterCursor(_file, range)
: new PlainCharacterCursor(_file, range);
this._preserveLineEndings = options.preserveLineEndings || false;
this._i18nNormalizeLineEndingsInICUs = options.i18nNormalizeLineEndingsInICUs || false;
this._tokenizeBlocks = options.tokenizeBlocks ?? true;
this._tokenizeLet = options.tokenizeLet ?? true;
try {
this._cursor.init();
} catch (e) {
this.handleError(e);
}
}
private _processCarriageReturns(content: string): string {
if (this._preserveLineEndings) {
return content;
}
// https://www.w3.org/TR/html51/syntax.html#preprocessing-the-input-stream
// In order to keep the original position in the source, we can not
// pre-process it.
// Instead CRs are processed right before instantiating the tokens.
return content.replace(_CR_OR_CRLF_REGEXP, '\n');
}
tokenize(): void {
while (this._cursor.peek() !== chars.$EOF) {
const start = this._cursor.clone();
try {
if (this._attemptCharCode(chars.$LT)) {
if (this._attemptCharCode(chars.$BANG)) {
if (this._attemptCharCode(chars.$LBRACKET)) {
this._consumeCdata(start);
} else if (this._attemptCharCode(chars.$MINUS)) {
this._consumeComment(start);
} else {
this._consumeDocType(start);
}
} else if (this._attemptCharCode(chars.$SLASH)) {
this._consumeTagClose(start);
} else {
this._consumeTagOpen(start);
}
} else if (
this._tokenizeLet &&
// Use `peek` instead of `attempCharCode` since we
// don't want to advance in case it's not `@let`.
this._cursor.peek() === chars.$AT &&
!this._inInterpolation &&
this._attemptStr('@let')
) {
this._consumeLetDeclaration(start);
} else if (this._tokenizeBlocks && this._attemptCharCode(chars.$AT)) {
this._consumeBlockStart(start);
} else if (
this._tokenizeBlocks &&
!this._inInterpolation &&
!this._isInExpansionCase() &&
!this._isInExpansionForm() &&
this._attemptCharCode(chars.$RBRACE)
) {
this._consumeBlockEnd(start);
} else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
// In (possibly interpolated) text the end of the text is given by `isTextEnd()`, while
// the premature end of an interpolation is given by the start of a new HTML element.
this._consumeWithInterpolation(
TokenType.TEXT,
TokenType.INTERPOLATION,
() => this._isTextEnd(),
() => this._isTagStart(),
);
}
} catch (e) {
this.handleError(e);
}
}
this._beginToken(TokenType.EOF);
this._endToken([]);
}
private _getBlockName(): string {
// This allows us to capture up something like `@else if`, but not `@ if`.
let spacesInNameAllowed = false;
const nameCursor = this._cursor.clone();
this._attemptCharCodeUntilFn((code) => {
if (chars.isWhitespace(code)) {
return !spacesInNameAllowed;
}
if (isBlockNameChar(code)) {
spacesInNameAllowed = true;
return false;
}
return true;
});
return this._cursor.getChars(nameCursor).trim();
}
private _consumeBlockStart(start: CharacterCursor) {
this._beginToken(TokenType.BLOCK_OPEN_START, start);
const startToken = this._endToken([this._getBlockName()]);
if (this._cursor.peek() === chars.$LPAREN) {
// Advance past the opening paren.
this._cursor.advance();
// Capture the parameters.
this._consumeBlockParameters();
// Allow spaces before the closing paren.
this._attemptCharCodeUntilFn(isNotWhitespace);
if (this._attemptCharCode(chars.$RPAREN)) {
// Allow spaces after the paren.
this._attemptCharCodeUntilFn(isNotWhitespace);
} else {
startToken.type = TokenType.INCOMPLETE_BLOCK_OPEN;
return;
}
}
if (this._attemptCharCode(chars.$LBRACE)) {
this._beginToken(TokenType.BLOCK_OPEN_END);
this._endToken([]);
} else {
startToken.type = TokenType.INCOMPLETE_BLOCK_OPEN;
}
}
private _consumeBlockEnd(start: CharacterCursor) {
this._beginToken(TokenType.BLOCK_CLOSE, start);
this._endToken([]);
}
private _consumeBlockParameters() {
// Trim the whitespace until the first parameter.
this._attemptCharCodeUntilFn(isBlockParameterChar);
while (this._cursor.peek() !== chars.$RPAREN && this._cursor.peek() !== chars.$EOF) {
this._beginToken(TokenType.BLOCK_PARAMETER);
const start = this._cursor.clone();
let inQuote: number | null = null;
let openParens = 0;
// Consume the parameter until the next semicolon or brace.
// Note that we skip over semicolons/braces inside of strings.
while (
(this._cursor.peek() !== chars.$SEMICOLON && this._cursor.peek() !== chars.$EOF) ||
inQuote !== null
) {
const char = this._cursor.peek();
// Skip to the next character if it was escaped.
if (char === chars.$BACKSLASH) {
this._cursor.advance();
} else if (char === inQuote) {
inQuote = null;
} else if (inQuote === null && chars.isQuote(char)) {
inQuote = char;
} else if (char === chars.$LPAREN && inQuote === null) {
openParens++;
} else if (char === chars.$RPAREN && inQuote === null) {
if (openParens === 0) {
break;
} else if (openParens > 0) {
openParens--;
}
}
this._cursor.advance();
}
this._endToken([this._cursor.getChars(start)]);
// Skip to the next parameter.
this._attemptCharCodeUntilFn(isBlockParameterChar);
}
} | {
"end_byte": 12105,
"start_byte": 4574,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/lexer.ts"
} |
angular/packages/compiler/src/ml_parser/lexer.ts_12109_19770 | private _consumeLetDeclaration(start: CharacterCursor) {
this._beginToken(TokenType.LET_START, start);
// Require at least one white space after the `@let`.
if (chars.isWhitespace(this._cursor.peek())) {
this._attemptCharCodeUntilFn(isNotWhitespace);
} else {
const token = this._endToken([this._cursor.getChars(start)]);
token.type = TokenType.INCOMPLETE_LET;
return;
}
const startToken = this._endToken([this._getLetDeclarationName()]);
// Skip over white space before the equals character.
this._attemptCharCodeUntilFn(isNotWhitespace);
// Expect an equals sign.
if (!this._attemptCharCode(chars.$EQ)) {
startToken.type = TokenType.INCOMPLETE_LET;
return;
}
// Skip spaces after the equals.
this._attemptCharCodeUntilFn((code) => isNotWhitespace(code) && !chars.isNewLine(code));
this._consumeLetDeclarationValue();
// Terminate the `@let` with a semicolon.
const endChar = this._cursor.peek();
if (endChar === chars.$SEMICOLON) {
this._beginToken(TokenType.LET_END);
this._endToken([]);
this._cursor.advance();
} else {
startToken.type = TokenType.INCOMPLETE_LET;
startToken.sourceSpan = this._cursor.getSpan(start);
}
}
private _getLetDeclarationName(): string {
const nameCursor = this._cursor.clone();
let allowDigit = false;
this._attemptCharCodeUntilFn((code) => {
if (
chars.isAsciiLetter(code) ||
code === chars.$$ ||
code === chars.$_ ||
// `@let` names can't start with a digit, but digits are valid anywhere else in the name.
(allowDigit && chars.isDigit(code))
) {
allowDigit = true;
return false;
}
return true;
});
return this._cursor.getChars(nameCursor).trim();
}
private _consumeLetDeclarationValue(): void {
const start = this._cursor.clone();
this._beginToken(TokenType.LET_VALUE, start);
while (this._cursor.peek() !== chars.$EOF) {
const char = this._cursor.peek();
// `@let` declarations terminate with a semicolon.
if (char === chars.$SEMICOLON) {
break;
}
// If we hit a quote, skip over its content since we don't care what's inside.
if (chars.isQuote(char)) {
this._cursor.advance();
this._attemptCharCodeUntilFn((inner) => {
if (inner === chars.$BACKSLASH) {
this._cursor.advance();
return false;
}
return inner === char;
});
}
this._cursor.advance();
}
this._endToken([this._cursor.getChars(start)]);
}
/**
* @returns whether an ICU token has been created
* @internal
*/
private _tokenizeExpansionForm(): boolean {
if (this.isExpansionFormStart()) {
this._consumeExpansionFormStart();
return true;
}
if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
this._consumeExpansionCaseStart();
return true;
}
if (this._cursor.peek() === chars.$RBRACE) {
if (this._isInExpansionCase()) {
this._consumeExpansionCaseEnd();
return true;
}
if (this._isInExpansionForm()) {
this._consumeExpansionFormEnd();
return true;
}
}
return false;
}
private _beginToken(type: TokenType, start = this._cursor.clone()) {
this._currentTokenStart = start;
this._currentTokenType = type;
}
private _endToken(parts: string[], end?: CharacterCursor): Token {
if (this._currentTokenStart === null) {
throw new TokenError(
'Programming error - attempted to end a token when there was no start to the token',
this._currentTokenType,
this._cursor.getSpan(end),
);
}
if (this._currentTokenType === null) {
throw new TokenError(
'Programming error - attempted to end a token which has no token type',
null,
this._cursor.getSpan(this._currentTokenStart),
);
}
const token = {
type: this._currentTokenType,
parts,
sourceSpan: (end ?? this._cursor).getSpan(
this._currentTokenStart,
this._leadingTriviaCodePoints,
),
} as Token;
this.tokens.push(token);
this._currentTokenStart = null;
this._currentTokenType = null;
return token;
}
private _createError(msg: string, span: ParseSourceSpan): _ControlFlowError {
if (this._isInExpansionForm()) {
msg += ` (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`;
}
const error = new TokenError(msg, this._currentTokenType, span);
this._currentTokenStart = null;
this._currentTokenType = null;
return new _ControlFlowError(error);
}
private handleError(e: any) {
if (e instanceof CursorError) {
e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
}
if (e instanceof _ControlFlowError) {
this.errors.push(e.error);
} else {
throw e;
}
}
private _attemptCharCode(charCode: number): boolean {
if (this._cursor.peek() === charCode) {
this._cursor.advance();
return true;
}
return false;
}
private _attemptCharCodeCaseInsensitive(charCode: number): boolean {
if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
this._cursor.advance();
return true;
}
return false;
}
private _requireCharCode(charCode: number) {
const location = this._cursor.clone();
if (!this._attemptCharCode(charCode)) {
throw this._createError(
_unexpectedCharacterErrorMsg(this._cursor.peek()),
this._cursor.getSpan(location),
);
}
}
private _attemptStr(chars: string): boolean {
const len = chars.length;
if (this._cursor.charsLeft() < len) {
return false;
}
const initialPosition = this._cursor.clone();
for (let i = 0; i < len; i++) {
if (!this._attemptCharCode(chars.charCodeAt(i))) {
// If attempting to parse the string fails, we want to reset the parser
// to where it was before the attempt
this._cursor = initialPosition;
return false;
}
}
return true;
}
private _attemptStrCaseInsensitive(chars: string): boolean {
for (let i = 0; i < chars.length; i++) {
if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
return false;
}
}
return true;
}
private _requireStr(chars: string) {
const location = this._cursor.clone();
if (!this._attemptStr(chars)) {
throw this._createError(
_unexpectedCharacterErrorMsg(this._cursor.peek()),
this._cursor.getSpan(location),
);
}
}
private _attemptCharCodeUntilFn(predicate: (code: number) => boolean) {
while (!predicate(this._cursor.peek())) {
this._cursor.advance();
}
}
private _requireCharCodeUntilFn(predicate: (code: number) => boolean, len: number) {
const start = this._cursor.clone();
this._attemptCharCodeUntilFn(predicate);
if (this._cursor.diff(start) < len) {
throw this._createError(
_unexpectedCharacterErrorMsg(this._cursor.peek()),
this._cursor.getSpan(start),
);
}
}
private _attemptUntilChar(char: number) {
while (this._cursor.peek() !== char) {
this._cursor.advance();
}
}
private _readChar(): string {
// Don't rely upon reading directly from `_input` as the actual char value
// may have been generated from an escape sequence.
const char = String.fromCodePoint(this._cursor.peek());
this._cursor.advance();
return char;
} | {
"end_byte": 19770,
"start_byte": 12109,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/lexer.ts"
} |
angular/packages/compiler/src/ml_parser/lexer.ts_19774_27628 | private _consumeEntity(textTokenType: TokenType): void {
this._beginToken(TokenType.ENCODED_ENTITY);
const start = this._cursor.clone();
this._cursor.advance();
if (this._attemptCharCode(chars.$HASH)) {
const isHex = this._attemptCharCode(chars.$x) || this._attemptCharCode(chars.$X);
const codeStart = this._cursor.clone();
this._attemptCharCodeUntilFn(isDigitEntityEnd);
if (this._cursor.peek() != chars.$SEMICOLON) {
// Advance cursor to include the peeked character in the string provided to the error
// message.
this._cursor.advance();
const entityType = isHex ? CharacterReferenceType.HEX : CharacterReferenceType.DEC;
throw this._createError(
_unparsableEntityErrorMsg(entityType, this._cursor.getChars(start)),
this._cursor.getSpan(),
);
}
const strNum = this._cursor.getChars(codeStart);
this._cursor.advance();
try {
const charCode = parseInt(strNum, isHex ? 16 : 10);
this._endToken([String.fromCharCode(charCode), this._cursor.getChars(start)]);
} catch {
throw this._createError(
_unknownEntityErrorMsg(this._cursor.getChars(start)),
this._cursor.getSpan(),
);
}
} else {
const nameStart = this._cursor.clone();
this._attemptCharCodeUntilFn(isNamedEntityEnd);
if (this._cursor.peek() != chars.$SEMICOLON) {
// No semicolon was found so abort the encoded entity token that was in progress, and treat
// this as a text token
this._beginToken(textTokenType, start);
this._cursor = nameStart;
this._endToken(['&']);
} else {
const name = this._cursor.getChars(nameStart);
this._cursor.advance();
const char = NAMED_ENTITIES[name];
if (!char) {
throw this._createError(_unknownEntityErrorMsg(name), this._cursor.getSpan(start));
}
this._endToken([char, `&${name};`]);
}
}
}
private _consumeRawText(consumeEntities: boolean, endMarkerPredicate: () => boolean): void {
this._beginToken(consumeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
const parts: string[] = [];
while (true) {
const tagCloseStart = this._cursor.clone();
const foundEndMarker = endMarkerPredicate();
this._cursor = tagCloseStart;
if (foundEndMarker) {
break;
}
if (consumeEntities && this._cursor.peek() === chars.$AMPERSAND) {
this._endToken([this._processCarriageReturns(parts.join(''))]);
parts.length = 0;
this._consumeEntity(TokenType.ESCAPABLE_RAW_TEXT);
this._beginToken(TokenType.ESCAPABLE_RAW_TEXT);
} else {
parts.push(this._readChar());
}
}
this._endToken([this._processCarriageReturns(parts.join(''))]);
}
private _consumeComment(start: CharacterCursor) {
this._beginToken(TokenType.COMMENT_START, start);
this._requireCharCode(chars.$MINUS);
this._endToken([]);
this._consumeRawText(false, () => this._attemptStr('-->'));
this._beginToken(TokenType.COMMENT_END);
this._requireStr('-->');
this._endToken([]);
}
private _consumeCdata(start: CharacterCursor) {
this._beginToken(TokenType.CDATA_START, start);
this._requireStr('CDATA[');
this._endToken([]);
this._consumeRawText(false, () => this._attemptStr(']]>'));
this._beginToken(TokenType.CDATA_END);
this._requireStr(']]>');
this._endToken([]);
}
private _consumeDocType(start: CharacterCursor) {
this._beginToken(TokenType.DOC_TYPE, start);
const contentStart = this._cursor.clone();
this._attemptUntilChar(chars.$GT);
const content = this._cursor.getChars(contentStart);
this._cursor.advance();
this._endToken([content]);
}
private _consumePrefixAndName(): string[] {
const nameOrPrefixStart = this._cursor.clone();
let prefix: string = '';
while (this._cursor.peek() !== chars.$COLON && !isPrefixEnd(this._cursor.peek())) {
this._cursor.advance();
}
let nameStart: CharacterCursor;
if (this._cursor.peek() === chars.$COLON) {
prefix = this._cursor.getChars(nameOrPrefixStart);
this._cursor.advance();
nameStart = this._cursor.clone();
} else {
nameStart = nameOrPrefixStart;
}
this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
const name = this._cursor.getChars(nameStart);
return [prefix, name];
}
private _consumeTagOpen(start: CharacterCursor) {
let tagName: string;
let prefix: string;
let openTagToken: TagOpenStartToken | IncompleteTagOpenToken | undefined;
try {
if (!chars.isAsciiLetter(this._cursor.peek())) {
throw this._createError(
_unexpectedCharacterErrorMsg(this._cursor.peek()),
this._cursor.getSpan(start),
);
}
openTagToken = this._consumeTagOpenStart(start);
prefix = openTagToken.parts[0];
tagName = openTagToken.parts[1];
this._attemptCharCodeUntilFn(isNotWhitespace);
while (
this._cursor.peek() !== chars.$SLASH &&
this._cursor.peek() !== chars.$GT &&
this._cursor.peek() !== chars.$LT &&
this._cursor.peek() !== chars.$EOF
) {
this._consumeAttributeName();
this._attemptCharCodeUntilFn(isNotWhitespace);
if (this._attemptCharCode(chars.$EQ)) {
this._attemptCharCodeUntilFn(isNotWhitespace);
this._consumeAttributeValue();
}
this._attemptCharCodeUntilFn(isNotWhitespace);
}
this._consumeTagOpenEnd();
} catch (e) {
if (e instanceof _ControlFlowError) {
if (openTagToken) {
// We errored before we could close the opening tag, so it is incomplete.
openTagToken.type = TokenType.INCOMPLETE_TAG_OPEN;
} else {
// When the start tag is invalid, assume we want a "<" as text.
// Back to back text tokens are merged at the end.
this._beginToken(TokenType.TEXT, start);
this._endToken(['<']);
}
return;
}
throw e;
}
const contentTokenType = this._getTagDefinition(tagName).getContentType(prefix);
if (contentTokenType === TagContentType.RAW_TEXT) {
this._consumeRawTextWithTagClose(prefix, tagName, false);
} else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
this._consumeRawTextWithTagClose(prefix, tagName, true);
}
}
private _consumeRawTextWithTagClose(prefix: string, tagName: string, consumeEntities: boolean) {
this._consumeRawText(consumeEntities, () => {
if (!this._attemptCharCode(chars.$LT)) return false;
if (!this._attemptCharCode(chars.$SLASH)) return false;
this._attemptCharCodeUntilFn(isNotWhitespace);
if (!this._attemptStrCaseInsensitive(tagName)) return false;
this._attemptCharCodeUntilFn(isNotWhitespace);
return this._attemptCharCode(chars.$GT);
});
this._beginToken(TokenType.TAG_CLOSE);
this._requireCharCodeUntilFn((code) => code === chars.$GT, 3);
this._cursor.advance(); // Consume the `>`
this._endToken([prefix, tagName]);
}
private _consumeTagOpenStart(start: CharacterCursor): TagOpenStartToken {
this._beginToken(TokenType.TAG_OPEN_START, start);
const parts = this._consumePrefixAndName();
return this._endToken(parts) as TagOpenStartToken;
}
private _consumeAttributeName() {
const attrNameStart = this._cursor.peek();
if (attrNameStart === chars.$SQ || attrNameStart === chars.$DQ) {
throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
}
this._beginToken(TokenType.ATTR_NAME);
const prefixAndName = this._consumePrefixAndName();
this._endToken(prefixAndName);
} | {
"end_byte": 27628,
"start_byte": 19774,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/lexer.ts"
} |
angular/packages/compiler/src/ml_parser/lexer.ts_27632_36267 | private _consumeAttributeValue() {
if (this._cursor.peek() === chars.$SQ || this._cursor.peek() === chars.$DQ) {
const quoteChar = this._cursor.peek();
this._consumeQuote(quoteChar);
// In an attribute then end of the attribute value and the premature end to an interpolation
// are both triggered by the `quoteChar`.
const endPredicate = () => this._cursor.peek() === quoteChar;
this._consumeWithInterpolation(
TokenType.ATTR_VALUE_TEXT,
TokenType.ATTR_VALUE_INTERPOLATION,
endPredicate,
endPredicate,
);
this._consumeQuote(quoteChar);
} else {
const endPredicate = () => isNameEnd(this._cursor.peek());
this._consumeWithInterpolation(
TokenType.ATTR_VALUE_TEXT,
TokenType.ATTR_VALUE_INTERPOLATION,
endPredicate,
endPredicate,
);
}
}
private _consumeQuote(quoteChar: number) {
this._beginToken(TokenType.ATTR_QUOTE);
this._requireCharCode(quoteChar);
this._endToken([String.fromCodePoint(quoteChar)]);
}
private _consumeTagOpenEnd() {
const tokenType = this._attemptCharCode(chars.$SLASH)
? TokenType.TAG_OPEN_END_VOID
: TokenType.TAG_OPEN_END;
this._beginToken(tokenType);
this._requireCharCode(chars.$GT);
this._endToken([]);
}
private _consumeTagClose(start: CharacterCursor) {
this._beginToken(TokenType.TAG_CLOSE, start);
this._attemptCharCodeUntilFn(isNotWhitespace);
const prefixAndName = this._consumePrefixAndName();
this._attemptCharCodeUntilFn(isNotWhitespace);
this._requireCharCode(chars.$GT);
this._endToken(prefixAndName);
}
private _consumeExpansionFormStart() {
this._beginToken(TokenType.EXPANSION_FORM_START);
this._requireCharCode(chars.$LBRACE);
this._endToken([]);
this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
this._beginToken(TokenType.RAW_TEXT);
const condition = this._readUntil(chars.$COMMA);
const normalizedCondition = this._processCarriageReturns(condition);
if (this._i18nNormalizeLineEndingsInICUs) {
// We explicitly want to normalize line endings for this text.
this._endToken([normalizedCondition]);
} else {
// We are not normalizing line endings.
const conditionToken = this._endToken([condition]);
if (normalizedCondition !== condition) {
this.nonNormalizedIcuExpressions.push(conditionToken);
}
}
this._requireCharCode(chars.$COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(TokenType.RAW_TEXT);
const type = this._readUntil(chars.$COMMA);
this._endToken([type]);
this._requireCharCode(chars.$COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
}
private _consumeExpansionCaseStart() {
this._beginToken(TokenType.EXPANSION_CASE_VALUE);
const value = this._readUntil(chars.$LBRACE).trim();
this._endToken([value]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
this._requireCharCode(chars.$LBRACE);
this._endToken([]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
}
private _consumeExpansionCaseEnd() {
this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
this._requireCharCode(chars.$RBRACE);
this._endToken([]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.pop();
}
private _consumeExpansionFormEnd() {
this._beginToken(TokenType.EXPANSION_FORM_END);
this._requireCharCode(chars.$RBRACE);
this._endToken([]);
this._expansionCaseStack.pop();
}
/**
* Consume a string that may contain interpolation expressions.
*
* The first token consumed will be of `tokenType` and then there will be alternating
* `interpolationTokenType` and `tokenType` tokens until the `endPredicate()` returns true.
*
* If an interpolation token ends prematurely it will have no end marker in its `parts` array.
*
* @param textTokenType the kind of tokens to interleave around interpolation tokens.
* @param interpolationTokenType the kind of tokens that contain interpolation.
* @param endPredicate a function that should return true when we should stop consuming.
* @param endInterpolation a function that should return true if there is a premature end to an
* interpolation expression - i.e. before we get to the normal interpolation closing marker.
*/
private _consumeWithInterpolation(
textTokenType: TokenType,
interpolationTokenType: TokenType,
endPredicate: () => boolean,
endInterpolation: () => boolean,
) {
this._beginToken(textTokenType);
const parts: string[] = [];
while (!endPredicate()) {
const current = this._cursor.clone();
if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
this._endToken([this._processCarriageReturns(parts.join(''))], current);
parts.length = 0;
this._consumeInterpolation(interpolationTokenType, current, endInterpolation);
this._beginToken(textTokenType);
} else if (this._cursor.peek() === chars.$AMPERSAND) {
this._endToken([this._processCarriageReturns(parts.join(''))]);
parts.length = 0;
this._consumeEntity(textTokenType);
this._beginToken(textTokenType);
} else {
parts.push(this._readChar());
}
}
// It is possible that an interpolation was started but not ended inside this text token.
// Make sure that we reset the state of the lexer correctly.
this._inInterpolation = false;
this._endToken([this._processCarriageReturns(parts.join(''))]);
}
/**
* Consume a block of text that has been interpreted as an Angular interpolation.
*
* @param interpolationTokenType the type of the interpolation token to generate.
* @param interpolationStart a cursor that points to the start of this interpolation.
* @param prematureEndPredicate a function that should return true if the next characters indicate
* an end to the interpolation before its normal closing marker.
*/
private _consumeInterpolation(
interpolationTokenType: TokenType,
interpolationStart: CharacterCursor,
prematureEndPredicate: (() => boolean) | null,
): void {
const parts: string[] = [];
this._beginToken(interpolationTokenType, interpolationStart);
parts.push(this._interpolationConfig.start);
// Find the end of the interpolation, ignoring content inside quotes.
const expressionStart = this._cursor.clone();
let inQuote: number | null = null;
let inComment = false;
while (
this._cursor.peek() !== chars.$EOF &&
(prematureEndPredicate === null || !prematureEndPredicate())
) {
const current = this._cursor.clone();
if (this._isTagStart()) {
// We are starting what looks like an HTML element in the middle of this interpolation.
// Reset the cursor to before the `<` character and end the interpolation token.
// (This is actually wrong but here for backward compatibility).
this._cursor = current;
parts.push(this._getProcessedChars(expressionStart, current));
this._endToken(parts);
return;
}
if (inQuote === null) {
if (this._attemptStr(this._interpolationConfig.end)) {
// We are not in a string, and we hit the end interpolation marker
parts.push(this._getProcessedChars(expressionStart, current));
parts.push(this._interpolationConfig.end);
this._endToken(parts);
return;
} else if (this._attemptStr('//')) {
// Once we are in a comment we ignore any quotes
inComment = true;
}
}
const char = this._cursor.peek();
this._cursor.advance();
if (char === chars.$BACKSLASH) {
// Skip the next character because it was escaped.
this._cursor.advance();
} else if (char === inQuote) {
// Exiting the current quoted string
inQuote = null;
} else if (!inComment && inQuote === null && chars.isQuote(char)) {
// Entering a new quoted string
inQuote = char;
}
}
// We hit EOF without finding a closing interpolation marker
parts.push(this._getProcessedChars(expressionStart, this._cursor));
this._endToken(parts);
}
private _getProcessedChars(start: CharacterCursor, end: CharacterCursor): string {
return this._processCarriageReturns(end.getChars(start));
} | {
"end_byte": 36267,
"start_byte": 27632,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/lexer.ts"
} |
angular/packages/compiler/src/ml_parser/lexer.ts_36271_42003 | private _isTextEnd(): boolean {
if (this._isTagStart() || this._cursor.peek() === chars.$EOF) {
return true;
}
if (this._tokenizeIcu && !this._inInterpolation) {
if (this.isExpansionFormStart()) {
// start of an expansion form
return true;
}
if (this._cursor.peek() === chars.$RBRACE && this._isInExpansionCase()) {
// end of and expansion case
return true;
}
}
if (
this._tokenizeBlocks &&
!this._inInterpolation &&
!this._isInExpansion() &&
(this._cursor.peek() === chars.$AT || this._cursor.peek() === chars.$RBRACE)
) {
return true;
}
return false;
}
/**
* Returns true if the current cursor is pointing to the start of a tag
* (opening/closing/comments/cdata/etc).
*/
private _isTagStart(): boolean {
if (this._cursor.peek() === chars.$LT) {
// We assume that `<` followed by whitespace is not the start of an HTML element.
const tmp = this._cursor.clone();
tmp.advance();
// If the next character is alphabetic, ! nor / then it is a tag start
const code = tmp.peek();
if (
(chars.$a <= code && code <= chars.$z) ||
(chars.$A <= code && code <= chars.$Z) ||
code === chars.$SLASH ||
code === chars.$BANG
) {
return true;
}
}
return false;
}
private _readUntil(char: number): string {
const start = this._cursor.clone();
this._attemptUntilChar(char);
return this._cursor.getChars(start);
}
private _isInExpansion(): boolean {
return this._isInExpansionCase() || this._isInExpansionForm();
}
private _isInExpansionCase(): boolean {
return (
this._expansionCaseStack.length > 0 &&
this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
TokenType.EXPANSION_CASE_EXP_START
);
}
private _isInExpansionForm(): boolean {
return (
this._expansionCaseStack.length > 0 &&
this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
TokenType.EXPANSION_FORM_START
);
}
private isExpansionFormStart(): boolean {
if (this._cursor.peek() !== chars.$LBRACE) {
return false;
}
if (this._interpolationConfig) {
const start = this._cursor.clone();
const isInterpolation = this._attemptStr(this._interpolationConfig.start);
this._cursor = start;
return !isInterpolation;
}
return true;
}
}
function isNotWhitespace(code: number): boolean {
return !chars.isWhitespace(code) || code === chars.$EOF;
}
function isNameEnd(code: number): boolean {
return (
chars.isWhitespace(code) ||
code === chars.$GT ||
code === chars.$LT ||
code === chars.$SLASH ||
code === chars.$SQ ||
code === chars.$DQ ||
code === chars.$EQ ||
code === chars.$EOF
);
}
function isPrefixEnd(code: number): boolean {
return (
(code < chars.$a || chars.$z < code) &&
(code < chars.$A || chars.$Z < code) &&
(code < chars.$0 || code > chars.$9)
);
}
function isDigitEntityEnd(code: number): boolean {
return code === chars.$SEMICOLON || code === chars.$EOF || !chars.isAsciiHexDigit(code);
}
function isNamedEntityEnd(code: number): boolean {
return code === chars.$SEMICOLON || code === chars.$EOF || !chars.isAsciiLetter(code);
}
function isExpansionCaseStart(peek: number): boolean {
return peek !== chars.$RBRACE;
}
function compareCharCodeCaseInsensitive(code1: number, code2: number): boolean {
return toUpperCaseCharCode(code1) === toUpperCaseCharCode(code2);
}
function toUpperCaseCharCode(code: number): number {
return code >= chars.$a && code <= chars.$z ? code - chars.$a + chars.$A : code;
}
function isBlockNameChar(code: number): boolean {
return chars.isAsciiLetter(code) || chars.isDigit(code) || code === chars.$_;
}
function isBlockParameterChar(code: number): boolean {
return code !== chars.$SEMICOLON && isNotWhitespace(code);
}
function mergeTextTokens(srcTokens: Token[]): Token[] {
const dstTokens: Token[] = [];
let lastDstToken: Token | undefined = undefined;
for (let i = 0; i < srcTokens.length; i++) {
const token = srcTokens[i];
if (
(lastDstToken && lastDstToken.type === TokenType.TEXT && token.type === TokenType.TEXT) ||
(lastDstToken &&
lastDstToken.type === TokenType.ATTR_VALUE_TEXT &&
token.type === TokenType.ATTR_VALUE_TEXT)
) {
lastDstToken.parts[0]! += token.parts[0];
lastDstToken.sourceSpan.end = token.sourceSpan.end;
} else {
lastDstToken = token;
dstTokens.push(lastDstToken);
}
}
return dstTokens;
}
/**
* The _Tokenizer uses objects of this type to move through the input text,
* extracting "parsed characters". These could be more than one actual character
* if the text contains escape sequences.
*/
interface CharacterCursor {
/** Initialize the cursor. */
init(): void;
/** The parsed character at the current cursor position. */
peek(): number;
/** Advance the cursor by one parsed character. */
advance(): void;
/** Get a span from the marked start point to the current point. */
getSpan(start?: this, leadingTriviaCodePoints?: number[]): ParseSourceSpan;
/** Get the parsed characters from the marked start point to the current point. */
getChars(start: this): string;
/** The number of characters left before the end of the cursor. */
charsLeft(): number;
/** The number of characters between `this` cursor and `other` cursor. */
diff(other: this): number;
/** Make a copy of this cursor */
clone(): CharacterCursor;
}
interface CursorState {
peek: number;
offset: number;
line: number;
column: number;
} | {
"end_byte": 42003,
"start_byte": 36271,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/lexer.ts"
} |
angular/packages/compiler/src/ml_parser/lexer.ts_42005_50698 | class PlainCharacterCursor implements CharacterCursor {
protected state: CursorState;
protected file: ParseSourceFile;
protected input: string;
protected end: number;
constructor(fileOrCursor: PlainCharacterCursor);
constructor(fileOrCursor: ParseSourceFile, range: LexerRange);
constructor(fileOrCursor: ParseSourceFile | PlainCharacterCursor, range?: LexerRange) {
if (fileOrCursor instanceof PlainCharacterCursor) {
this.file = fileOrCursor.file;
this.input = fileOrCursor.input;
this.end = fileOrCursor.end;
const state = fileOrCursor.state;
// Note: avoid using `{...fileOrCursor.state}` here as that has a severe performance penalty.
// In ES5 bundles the object spread operator is translated into the `__assign` helper, which
// is not optimized by VMs as efficiently as a raw object literal. Since this constructor is
// called in tight loops, this difference matters.
this.state = {
peek: state.peek,
offset: state.offset,
line: state.line,
column: state.column,
};
} else {
if (!range) {
throw new Error(
'Programming error: the range argument must be provided with a file argument.',
);
}
this.file = fileOrCursor;
this.input = fileOrCursor.content;
this.end = range.endPos;
this.state = {
peek: -1,
offset: range.startPos,
line: range.startLine,
column: range.startCol,
};
}
}
clone(): PlainCharacterCursor {
return new PlainCharacterCursor(this);
}
peek() {
return this.state.peek;
}
charsLeft() {
return this.end - this.state.offset;
}
diff(other: this) {
return this.state.offset - other.state.offset;
}
advance(): void {
this.advanceState(this.state);
}
init(): void {
this.updatePeek(this.state);
}
getSpan(start?: this, leadingTriviaCodePoints?: number[]): ParseSourceSpan {
start = start || this;
let fullStart = start;
if (leadingTriviaCodePoints) {
while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
if (fullStart === start) {
start = start.clone() as this;
}
start.advance();
}
}
const startLocation = this.locationFromCursor(start);
const endLocation = this.locationFromCursor(this);
const fullStartLocation =
fullStart !== start ? this.locationFromCursor(fullStart) : startLocation;
return new ParseSourceSpan(startLocation, endLocation, fullStartLocation);
}
getChars(start: this): string {
return this.input.substring(start.state.offset, this.state.offset);
}
charAt(pos: number): number {
return this.input.charCodeAt(pos);
}
protected advanceState(state: CursorState) {
if (state.offset >= this.end) {
this.state = state;
throw new CursorError('Unexpected character "EOF"', this);
}
const currentChar = this.charAt(state.offset);
if (currentChar === chars.$LF) {
state.line++;
state.column = 0;
} else if (!chars.isNewLine(currentChar)) {
state.column++;
}
state.offset++;
this.updatePeek(state);
}
protected updatePeek(state: CursorState): void {
state.peek = state.offset >= this.end ? chars.$EOF : this.charAt(state.offset);
}
private locationFromCursor(cursor: this): ParseLocation {
return new ParseLocation(
cursor.file,
cursor.state.offset,
cursor.state.line,
cursor.state.column,
);
}
}
class EscapedCharacterCursor extends PlainCharacterCursor {
protected internalState: CursorState;
constructor(fileOrCursor: EscapedCharacterCursor);
constructor(fileOrCursor: ParseSourceFile, range: LexerRange);
constructor(fileOrCursor: ParseSourceFile | EscapedCharacterCursor, range?: LexerRange) {
if (fileOrCursor instanceof EscapedCharacterCursor) {
super(fileOrCursor);
this.internalState = {...fileOrCursor.internalState};
} else {
super(fileOrCursor, range!);
this.internalState = this.state;
}
}
override advance(): void {
this.state = this.internalState;
super.advance();
this.processEscapeSequence();
}
override init(): void {
super.init();
this.processEscapeSequence();
}
override clone(): EscapedCharacterCursor {
return new EscapedCharacterCursor(this);
}
override getChars(start: this): string {
const cursor = start.clone();
let chars = '';
while (cursor.internalState.offset < this.internalState.offset) {
chars += String.fromCodePoint(cursor.peek());
cursor.advance();
}
return chars;
}
/**
* Process the escape sequence that starts at the current position in the text.
*
* This method is called to ensure that `peek` has the unescaped value of escape sequences.
*/
protected processEscapeSequence(): void {
const peek = () => this.internalState.peek;
if (peek() === chars.$BACKSLASH) {
// We have hit an escape sequence so we need the internal state to become independent
// of the external state.
this.internalState = {...this.state};
// Move past the backslash
this.advanceState(this.internalState);
// First check for standard control char sequences
if (peek() === chars.$n) {
this.state.peek = chars.$LF;
} else if (peek() === chars.$r) {
this.state.peek = chars.$CR;
} else if (peek() === chars.$v) {
this.state.peek = chars.$VTAB;
} else if (peek() === chars.$t) {
this.state.peek = chars.$TAB;
} else if (peek() === chars.$b) {
this.state.peek = chars.$BSPACE;
} else if (peek() === chars.$f) {
this.state.peek = chars.$FF;
}
// Now consider more complex sequences
else if (peek() === chars.$u) {
// Unicode code-point sequence
this.advanceState(this.internalState); // advance past the `u` char
if (peek() === chars.$LBRACE) {
// Variable length Unicode, e.g. `\x{123}`
this.advanceState(this.internalState); // advance past the `{` char
// Advance past the variable number of hex digits until we hit a `}` char
const digitStart = this.clone();
let length = 0;
while (peek() !== chars.$RBRACE) {
this.advanceState(this.internalState);
length++;
}
this.state.peek = this.decodeHexDigits(digitStart, length);
} else {
// Fixed length Unicode, e.g. `\u1234`
const digitStart = this.clone();
this.advanceState(this.internalState);
this.advanceState(this.internalState);
this.advanceState(this.internalState);
this.state.peek = this.decodeHexDigits(digitStart, 4);
}
} else if (peek() === chars.$x) {
// Hex char code, e.g. `\x2F`
this.advanceState(this.internalState); // advance past the `x` char
const digitStart = this.clone();
this.advanceState(this.internalState);
this.state.peek = this.decodeHexDigits(digitStart, 2);
} else if (chars.isOctalDigit(peek())) {
// Octal char code, e.g. `\012`,
let octal = '';
let length = 0;
let previous = this.clone();
while (chars.isOctalDigit(peek()) && length < 3) {
previous = this.clone();
octal += String.fromCodePoint(peek());
this.advanceState(this.internalState);
length++;
}
this.state.peek = parseInt(octal, 8);
// Backup one char
this.internalState = previous.internalState;
} else if (chars.isNewLine(this.internalState.peek)) {
// Line continuation `\` followed by a new line
this.advanceState(this.internalState); // advance over the newline
this.state = this.internalState;
} else {
// If none of the `if` blocks were executed then we just have an escaped normal character.
// In that case we just, effectively, skip the backslash from the character.
this.state.peek = this.internalState.peek;
}
}
}
protected decodeHexDigits(start: EscapedCharacterCursor, length: number): number {
const hex = this.input.slice(start.internalState.offset, start.internalState.offset + length);
const charCode = parseInt(hex, 16);
if (!isNaN(charCode)) {
return charCode;
} else {
start.state = start.internalState;
throw new CursorError('Invalid hexadecimal escape sequence', start);
}
}
}
export class CursorError {
constructor(
public msg: string,
public cursor: CharacterCursor,
) {}
} | {
"end_byte": 50698,
"start_byte": 42005,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/lexer.ts"
} |
angular/packages/compiler/src/ml_parser/ast.ts_0_6683 | /**
* @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.dev/license
*/
import {I18nMeta} from '../i18n/i18n_ast';
import {ParseSourceSpan} from '../parse_util';
import {InterpolatedAttributeToken, InterpolatedTextToken} from './tokens';
interface BaseNode {
sourceSpan: ParseSourceSpan;
visit(visitor: Visitor, context: any): any;
}
export type Node =
| Attribute
| Comment
| Element
| Expansion
| ExpansionCase
| Text
| Block
| BlockParameter;
export abstract class NodeWithI18n implements BaseNode {
constructor(
public sourceSpan: ParseSourceSpan,
public i18n?: I18nMeta,
) {}
abstract visit(visitor: Visitor, context: any): any;
}
export class Text extends NodeWithI18n {
constructor(
public value: string,
sourceSpan: ParseSourceSpan,
public tokens: InterpolatedTextToken[],
i18n?: I18nMeta,
) {
super(sourceSpan, i18n);
}
override visit(visitor: Visitor, context: any): any {
return visitor.visitText(this, context);
}
}
export class Expansion extends NodeWithI18n {
constructor(
public switchValue: string,
public type: string,
public cases: ExpansionCase[],
sourceSpan: ParseSourceSpan,
public switchValueSourceSpan: ParseSourceSpan,
i18n?: I18nMeta,
) {
super(sourceSpan, i18n);
}
override visit(visitor: Visitor, context: any): any {
return visitor.visitExpansion(this, context);
}
}
export class ExpansionCase implements BaseNode {
constructor(
public value: string,
public expression: Node[],
public sourceSpan: ParseSourceSpan,
public valueSourceSpan: ParseSourceSpan,
public expSourceSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context: any): any {
return visitor.visitExpansionCase(this, context);
}
}
export class Attribute extends NodeWithI18n {
constructor(
public name: string,
public value: string,
sourceSpan: ParseSourceSpan,
readonly keySpan: ParseSourceSpan | undefined,
public valueSpan: ParseSourceSpan | undefined,
public valueTokens: InterpolatedAttributeToken[] | undefined,
i18n: I18nMeta | undefined,
) {
super(sourceSpan, i18n);
}
override visit(visitor: Visitor, context: any): any {
return visitor.visitAttribute(this, context);
}
}
export class Element extends NodeWithI18n {
constructor(
public name: string,
public attrs: Attribute[],
public children: Node[],
sourceSpan: ParseSourceSpan,
public startSourceSpan: ParseSourceSpan,
public endSourceSpan: ParseSourceSpan | null = null,
i18n?: I18nMeta,
) {
super(sourceSpan, i18n);
}
override visit(visitor: Visitor, context: any): any {
return visitor.visitElement(this, context);
}
}
export class Comment implements BaseNode {
constructor(
public value: string | null,
public sourceSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context: any): any {
return visitor.visitComment(this, context);
}
}
export class Block extends NodeWithI18n {
constructor(
public name: string,
public parameters: BlockParameter[],
public children: Node[],
sourceSpan: ParseSourceSpan,
public nameSpan: ParseSourceSpan,
public startSourceSpan: ParseSourceSpan,
public endSourceSpan: ParseSourceSpan | null = null,
i18n?: I18nMeta,
) {
super(sourceSpan, i18n);
}
override visit(visitor: Visitor, context: any) {
return visitor.visitBlock(this, context);
}
}
export class BlockParameter implements BaseNode {
constructor(
public expression: string,
public sourceSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context: any): any {
return visitor.visitBlockParameter(this, context);
}
}
export class LetDeclaration implements BaseNode {
constructor(
public name: string,
public value: string,
public sourceSpan: ParseSourceSpan,
readonly nameSpan: ParseSourceSpan,
public valueSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context: any): any {
return visitor.visitLetDeclaration(this, context);
}
}
export interface Visitor {
// Returning a truthy value from `visit()` will prevent `visitAll()` from the call to the typed
// method and result returned will become the result included in `visitAll()`s result array.
visit?(node: Node, context: any): any;
visitElement(element: Element, context: any): any;
visitAttribute(attribute: Attribute, context: any): any;
visitText(text: Text, context: any): any;
visitComment(comment: Comment, context: any): any;
visitExpansion(expansion: Expansion, context: any): any;
visitExpansionCase(expansionCase: ExpansionCase, context: any): any;
visitBlock(block: Block, context: any): any;
visitBlockParameter(parameter: BlockParameter, context: any): any;
visitLetDeclaration(decl: LetDeclaration, context: any): any;
}
export function visitAll(visitor: Visitor, nodes: Node[], context: any = null): any[] {
const result: any[] = [];
const visit = visitor.visit
? (ast: Node) => visitor.visit!(ast, context) || ast.visit(visitor, context)
: (ast: Node) => ast.visit(visitor, context);
nodes.forEach((ast) => {
const astResult = visit(ast);
if (astResult) {
result.push(astResult);
}
});
return result;
}
export class RecursiveVisitor implements Visitor {
constructor() {}
visitElement(ast: Element, context: any): any {
this.visitChildren(context, (visit) => {
visit(ast.attrs);
visit(ast.children);
});
}
visitAttribute(ast: Attribute, context: any): any {}
visitText(ast: Text, context: any): any {}
visitComment(ast: Comment, context: any): any {}
visitExpansion(ast: Expansion, context: any): any {
return this.visitChildren(context, (visit) => {
visit(ast.cases);
});
}
visitExpansionCase(ast: ExpansionCase, context: any): any {}
visitBlock(block: Block, context: any): any {
this.visitChildren(context, (visit) => {
visit(block.parameters);
visit(block.children);
});
}
visitBlockParameter(ast: BlockParameter, context: any): any {}
visitLetDeclaration(decl: LetDeclaration, context: any) {}
private visitChildren<T extends Node>(
context: any,
cb: (visit: <V extends Node>(children: V[] | undefined) => void) => void,
) {
let results: any[][] = [];
let t = this;
function visit<T extends Node>(children: T[] | undefined) {
if (children) results.push(visitAll(t, children, context));
}
cb(visit);
return Array.prototype.concat.apply([], results);
}
}
| {
"end_byte": 6683,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/ast.ts"
} |
angular/packages/compiler/src/ml_parser/icu_ast_expander.ts_0_5933 | /**
* @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.dev/license
*/
import {ParseError, ParseSourceSpan} from '../parse_util';
import * as html from './ast';
// http://cldr.unicode.org/index/cldr-spec/plural-rules
const PLURAL_CASES: string[] = ['zero', 'one', 'two', 'few', 'many', 'other'];
/**
* Expands special forms into elements.
*
* For example,
*
* ```
* { messages.length, plural,
* =0 {zero}
* =1 {one}
* other {more than one}
* }
* ```
*
* will be expanded into
*
* ```
* <ng-container [ngPlural]="messages.length">
* <ng-template ngPluralCase="=0">zero</ng-template>
* <ng-template ngPluralCase="=1">one</ng-template>
* <ng-template ngPluralCase="other">more than one</ng-template>
* </ng-container>
* ```
*/
export function expandNodes(nodes: html.Node[]): ExpansionResult {
const expander = new _Expander();
return new ExpansionResult(html.visitAll(expander, nodes), expander.isExpanded, expander.errors);
}
export class ExpansionResult {
constructor(
public nodes: html.Node[],
public expanded: boolean,
public errors: ParseError[],
) {}
}
export class ExpansionError extends ParseError {
constructor(span: ParseSourceSpan, errorMsg: string) {
super(span, errorMsg);
}
}
/**
* Expand expansion forms (plural, select) to directives
*
* @internal
*/
class _Expander implements html.Visitor {
isExpanded: boolean = false;
errors: ParseError[] = [];
visitElement(element: html.Element, context: any): any {
return new html.Element(
element.name,
element.attrs,
html.visitAll(this, element.children),
element.sourceSpan,
element.startSourceSpan,
element.endSourceSpan,
);
}
visitAttribute(attribute: html.Attribute, context: any): any {
return attribute;
}
visitText(text: html.Text, context: any): any {
return text;
}
visitComment(comment: html.Comment, context: any): any {
return comment;
}
visitExpansion(icu: html.Expansion, context: any): any {
this.isExpanded = true;
return icu.type === 'plural'
? _expandPluralForm(icu, this.errors)
: _expandDefaultForm(icu, this.errors);
}
visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {
throw new Error('Should not be reached');
}
visitBlock(block: html.Block, context: any) {
return new html.Block(
block.name,
block.parameters,
html.visitAll(this, block.children),
block.sourceSpan,
block.nameSpan,
block.startSourceSpan,
block.endSourceSpan,
);
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {
return parameter;
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
return decl;
}
}
// Plural forms are expanded to `NgPlural` and `NgPluralCase`s
function _expandPluralForm(ast: html.Expansion, errors: ParseError[]): html.Element {
const children = ast.cases.map((c) => {
if (PLURAL_CASES.indexOf(c.value) === -1 && !c.value.match(/^=\d+$/)) {
errors.push(
new ExpansionError(
c.valueSourceSpan,
`Plural cases should be "=<number>" or one of ${PLURAL_CASES.join(', ')}`,
),
);
}
const expansionResult = expandNodes(c.expression);
errors.push(...expansionResult.errors);
return new html.Element(
`ng-template`,
[
new html.Attribute(
'ngPluralCase',
`${c.value}`,
c.valueSourceSpan,
undefined /* keySpan */,
undefined /* valueSpan */,
undefined /* valueTokens */,
undefined /* i18n */,
),
],
expansionResult.nodes,
c.sourceSpan,
c.sourceSpan,
c.sourceSpan,
);
});
const switchAttr = new html.Attribute(
'[ngPlural]',
ast.switchValue,
ast.switchValueSourceSpan,
undefined /* keySpan */,
undefined /* valueSpan */,
undefined /* valueTokens */,
undefined /* i18n */,
);
return new html.Element(
'ng-container',
[switchAttr],
children,
ast.sourceSpan,
ast.sourceSpan,
ast.sourceSpan,
);
}
// ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
function _expandDefaultForm(ast: html.Expansion, errors: ParseError[]): html.Element {
const children = ast.cases.map((c) => {
const expansionResult = expandNodes(c.expression);
errors.push(...expansionResult.errors);
if (c.value === 'other') {
// other is the default case when no values match
return new html.Element(
`ng-template`,
[
new html.Attribute(
'ngSwitchDefault',
'',
c.valueSourceSpan,
undefined /* keySpan */,
undefined /* valueSpan */,
undefined /* valueTokens */,
undefined /* i18n */,
),
],
expansionResult.nodes,
c.sourceSpan,
c.sourceSpan,
c.sourceSpan,
);
}
return new html.Element(
`ng-template`,
[
new html.Attribute(
'ngSwitchCase',
`${c.value}`,
c.valueSourceSpan,
undefined /* keySpan */,
undefined /* valueSpan */,
undefined /* valueTokens */,
undefined /* i18n */,
),
],
expansionResult.nodes,
c.sourceSpan,
c.sourceSpan,
c.sourceSpan,
);
});
const switchAttr = new html.Attribute(
'[ngSwitch]',
ast.switchValue,
ast.switchValueSourceSpan,
undefined /* keySpan */,
undefined /* valueSpan */,
undefined /* valueTokens */,
undefined /* i18n */,
);
return new html.Element(
'ng-container',
[switchAttr],
children,
ast.sourceSpan,
ast.sourceSpan,
ast.sourceSpan,
);
}
| {
"end_byte": 5933,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/icu_ast_expander.ts"
} |
angular/packages/compiler/src/ml_parser/xml_tags.ts_0_921 | /**
* @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.dev/license
*/
import {TagContentType, TagDefinition} from './tags';
export class XmlTagDefinition implements TagDefinition {
closedByParent: boolean = false;
implicitNamespacePrefix: string | null = null;
isVoid: boolean = false;
ignoreFirstLf: boolean = false;
canSelfClose: boolean = true;
preventNamespaceInheritance: boolean = false;
requireExtraParent(currentParent: string): boolean {
return false;
}
isClosedByChild(name: string): boolean {
return false;
}
getContentType(): TagContentType {
return TagContentType.PARSABLE_DATA;
}
}
const _TAG_DEFINITION = new XmlTagDefinition();
export function getXmlTagDefinition(tagName: string): XmlTagDefinition {
return _TAG_DEFINITION;
}
| {
"end_byte": 921,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/xml_tags.ts"
} |
angular/packages/compiler/src/ml_parser/parser.ts_0_2236 | /**
* @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.dev/license
*/
import {ParseError, ParseLocation, ParseSourceSpan} from '../parse_util';
import * as html from './ast';
import {NAMED_ENTITIES} from './entities';
import {tokenize, TokenizeOptions} from './lexer';
import {getNsPrefix, mergeNsAndName, splitNsName, TagDefinition} from './tags';
import {
AttributeNameToken,
AttributeQuoteToken,
BlockCloseToken,
BlockOpenStartToken,
BlockParameterToken,
CdataStartToken,
CommentStartToken,
ExpansionCaseExpressionEndToken,
ExpansionCaseExpressionStartToken,
ExpansionCaseValueToken,
ExpansionFormStartToken,
IncompleteBlockOpenToken,
IncompleteLetToken,
IncompleteTagOpenToken,
InterpolatedAttributeToken,
InterpolatedTextToken,
LetEndToken,
LetStartToken,
LetValueToken,
TagCloseToken,
TagOpenStartToken,
TextToken,
Token,
TokenType,
} from './tokens';
/** Nodes that can contain other nodes. */
type NodeContainer = html.Element | html.Block;
/** Class that can construct a `NodeContainer`. */
interface NodeContainerConstructor extends Function {
new (...args: any[]): NodeContainer;
}
export class TreeError extends ParseError {
static create(elementName: string | null, span: ParseSourceSpan, msg: string): TreeError {
return new TreeError(elementName, span, msg);
}
constructor(
public elementName: string | null,
span: ParseSourceSpan,
msg: string,
) {
super(span, msg);
}
}
export class ParseTreeResult {
constructor(
public rootNodes: html.Node[],
public errors: ParseError[],
) {}
}
export class Parser {
constructor(public getTagDefinition: (tagName: string) => TagDefinition) {}
parse(source: string, url: string, options?: TokenizeOptions): ParseTreeResult {
const tokenizeResult = tokenize(source, url, this.getTagDefinition, options);
const parser = new _TreeBuilder(tokenizeResult.tokens, this.getTagDefinition);
parser.build();
return new ParseTreeResult(
parser.rootNodes,
(tokenizeResult.errors as ParseError[]).concat(parser.errors),
);
}
} | {
"end_byte": 2236,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/parser.ts"
} |
angular/packages/compiler/src/ml_parser/parser.ts_2238_9940 | class _TreeBuilder {
private _index: number = -1;
// `_peek` will be initialized by the call to `_advance()` in the constructor.
private _peek!: Token;
private _containerStack: NodeContainer[] = [];
rootNodes: html.Node[] = [];
errors: TreeError[] = [];
constructor(
private tokens: Token[],
private getTagDefinition: (tagName: string) => TagDefinition,
) {
this._advance();
}
build(): void {
while (this._peek.type !== TokenType.EOF) {
if (
this._peek.type === TokenType.TAG_OPEN_START ||
this._peek.type === TokenType.INCOMPLETE_TAG_OPEN
) {
this._consumeStartTag(this._advance());
} else if (this._peek.type === TokenType.TAG_CLOSE) {
this._consumeEndTag(this._advance());
} else if (this._peek.type === TokenType.CDATA_START) {
this._closeVoidElement();
this._consumeCdata(this._advance());
} else if (this._peek.type === TokenType.COMMENT_START) {
this._closeVoidElement();
this._consumeComment(this._advance());
} else if (
this._peek.type === TokenType.TEXT ||
this._peek.type === TokenType.RAW_TEXT ||
this._peek.type === TokenType.ESCAPABLE_RAW_TEXT
) {
this._closeVoidElement();
this._consumeText(this._advance());
} else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
this._consumeExpansion(this._advance());
} else if (this._peek.type === TokenType.BLOCK_OPEN_START) {
this._closeVoidElement();
this._consumeBlockOpen(this._advance());
} else if (this._peek.type === TokenType.BLOCK_CLOSE) {
this._closeVoidElement();
this._consumeBlockClose(this._advance());
} else if (this._peek.type === TokenType.INCOMPLETE_BLOCK_OPEN) {
this._closeVoidElement();
this._consumeIncompleteBlock(this._advance());
} else if (this._peek.type === TokenType.LET_START) {
this._closeVoidElement();
this._consumeLet(this._advance());
} else if (this._peek.type === TokenType.INCOMPLETE_LET) {
this._closeVoidElement();
this._consumeIncompleteLet(this._advance());
} else {
// Skip all other tokens...
this._advance();
}
}
for (const leftoverContainer of this._containerStack) {
// Unlike HTML elements, blocks aren't closed implicitly by the end of the file.
if (leftoverContainer instanceof html.Block) {
this.errors.push(
TreeError.create(
leftoverContainer.name,
leftoverContainer.sourceSpan,
`Unclosed block "${leftoverContainer.name}"`,
),
);
}
}
}
private _advance<T extends Token>(): T {
const prev = this._peek;
if (this._index < this.tokens.length - 1) {
// Note: there is always an EOF token at the end
this._index++;
}
this._peek = this.tokens[this._index];
return prev as T;
}
private _advanceIf<T extends TokenType>(type: T): (Token & {type: T}) | null {
if (this._peek.type === type) {
return this._advance<Token & {type: T}>();
}
return null;
}
private _consumeCdata(_startToken: CdataStartToken) {
this._consumeText(this._advance<TextToken>());
this._advanceIf(TokenType.CDATA_END);
}
private _consumeComment(token: CommentStartToken) {
const text = this._advanceIf(TokenType.RAW_TEXT);
const endToken = this._advanceIf(TokenType.COMMENT_END);
const value = text != null ? text.parts[0].trim() : null;
const sourceSpan =
endToken == null
? token.sourceSpan
: new ParseSourceSpan(
token.sourceSpan.start,
endToken.sourceSpan.end,
token.sourceSpan.fullStart,
);
this._addToParent(new html.Comment(value, sourceSpan));
}
private _consumeExpansion(token: ExpansionFormStartToken) {
const switchValue = this._advance<TextToken>();
const type = this._advance<TextToken>();
const cases: html.ExpansionCase[] = [];
// read =
while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
const expCase = this._parseExpansionCase();
if (!expCase) return; // error
cases.push(expCase);
}
// read the final }
if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
this.errors.push(
TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '}'.`),
);
return;
}
const sourceSpan = new ParseSourceSpan(
token.sourceSpan.start,
this._peek.sourceSpan.end,
token.sourceSpan.fullStart,
);
this._addToParent(
new html.Expansion(
switchValue.parts[0],
type.parts[0],
cases,
sourceSpan,
switchValue.sourceSpan,
),
);
this._advance();
}
private _parseExpansionCase(): html.ExpansionCase | null {
const value = this._advance<ExpansionCaseValueToken>();
// read {
if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
this.errors.push(
TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '{'.`),
);
return null;
}
// read until }
const start = this._advance<ExpansionCaseExpressionStartToken>();
const exp = this._collectExpansionExpTokens(start);
if (!exp) return null;
const end = this._advance<ExpansionCaseExpressionEndToken>();
exp.push({type: TokenType.EOF, parts: [], sourceSpan: end.sourceSpan});
// parse everything in between { and }
const expansionCaseParser = new _TreeBuilder(exp, this.getTagDefinition);
expansionCaseParser.build();
if (expansionCaseParser.errors.length > 0) {
this.errors = this.errors.concat(expansionCaseParser.errors);
return null;
}
const sourceSpan = new ParseSourceSpan(
value.sourceSpan.start,
end.sourceSpan.end,
value.sourceSpan.fullStart,
);
const expSourceSpan = new ParseSourceSpan(
start.sourceSpan.start,
end.sourceSpan.end,
start.sourceSpan.fullStart,
);
return new html.ExpansionCase(
value.parts[0],
expansionCaseParser.rootNodes,
sourceSpan,
value.sourceSpan,
expSourceSpan,
);
}
private _collectExpansionExpTokens(start: Token): Token[] | null {
const exp: Token[] = [];
const expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
while (true) {
if (
this._peek.type === TokenType.EXPANSION_FORM_START ||
this._peek.type === TokenType.EXPANSION_CASE_EXP_START
) {
expansionFormStack.push(this._peek.type);
}
if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
expansionFormStack.pop();
if (expansionFormStack.length === 0) return exp;
} else {
this.errors.push(
TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`),
);
return null;
}
}
if (this._peek.type === TokenType.EXPANSION_FORM_END) {
if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
expansionFormStack.pop();
} else {
this.errors.push(
TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`),
);
return null;
}
}
if (this._peek.type === TokenType.EOF) {
this.errors.push(
TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`),
);
return null;
}
exp.push(this._advance());
}
} | {
"end_byte": 9940,
"start_byte": 2238,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/parser.ts"
} |
angular/packages/compiler/src/ml_parser/parser.ts_9944_17211 | private _consumeText(token: InterpolatedTextToken) {
const tokens = [token];
const startSpan = token.sourceSpan;
let text = token.parts[0];
if (text.length > 0 && text[0] === '\n') {
const parent = this._getContainer();
if (
parent != null &&
parent.children.length === 0 &&
this.getTagDefinition(parent.name).ignoreFirstLf
) {
text = text.substring(1);
tokens[0] = {type: token.type, sourceSpan: token.sourceSpan, parts: [text]} as typeof token;
}
}
while (
this._peek.type === TokenType.INTERPOLATION ||
this._peek.type === TokenType.TEXT ||
this._peek.type === TokenType.ENCODED_ENTITY
) {
token = this._advance();
tokens.push(token);
if (token.type === TokenType.INTERPOLATION) {
// For backward compatibility we decode HTML entities that appear in interpolation
// expressions. This is arguably a bug, but it could be a considerable breaking change to
// fix it. It should be addressed in a larger project to refactor the entire parser/lexer
// chain after View Engine has been removed.
text += token.parts.join('').replace(/&([^;]+);/g, decodeEntity);
} else if (token.type === TokenType.ENCODED_ENTITY) {
text += token.parts[0];
} else {
text += token.parts.join('');
}
}
if (text.length > 0) {
const endSpan = token.sourceSpan;
this._addToParent(
new html.Text(
text,
new ParseSourceSpan(startSpan.start, endSpan.end, startSpan.fullStart, startSpan.details),
tokens,
),
);
}
}
private _closeVoidElement(): void {
const el = this._getContainer();
if (el instanceof html.Element && this.getTagDefinition(el.name).isVoid) {
this._containerStack.pop();
}
}
private _consumeStartTag(startTagToken: TagOpenStartToken | IncompleteTagOpenToken) {
const [prefix, name] = startTagToken.parts;
const attrs: html.Attribute[] = [];
while (this._peek.type === TokenType.ATTR_NAME) {
attrs.push(this._consumeAttr(this._advance<AttributeNameToken>()));
}
const fullName = this._getElementFullName(prefix, name, this._getClosestParentElement());
let selfClosing = false;
// Note: There could have been a tokenizer error
// so that we don't get a token for the end tag...
if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
this._advance();
selfClosing = true;
const tagDef = this.getTagDefinition(fullName);
if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
this.errors.push(
TreeError.create(
fullName,
startTagToken.sourceSpan,
`Only void, custom and foreign elements can be self closed "${startTagToken.parts[1]}"`,
),
);
}
} else if (this._peek.type === TokenType.TAG_OPEN_END) {
this._advance();
selfClosing = false;
}
const end = this._peek.sourceSpan.fullStart;
const span = new ParseSourceSpan(
startTagToken.sourceSpan.start,
end,
startTagToken.sourceSpan.fullStart,
);
// Create a separate `startSpan` because `span` will be modified when there is an `end` span.
const startSpan = new ParseSourceSpan(
startTagToken.sourceSpan.start,
end,
startTagToken.sourceSpan.fullStart,
);
const el = new html.Element(fullName, attrs, [], span, startSpan, undefined);
const parentEl = this._getContainer();
this._pushContainer(
el,
parentEl instanceof html.Element &&
this.getTagDefinition(parentEl.name).isClosedByChild(el.name),
);
if (selfClosing) {
// Elements that are self-closed have their `endSourceSpan` set to the full span, as the
// element start tag also represents the end tag.
this._popContainer(fullName, html.Element, span);
} else if (startTagToken.type === TokenType.INCOMPLETE_TAG_OPEN) {
// We already know the opening tag is not complete, so it is unlikely it has a corresponding
// close tag. Let's optimistically parse it as a full element and emit an error.
this._popContainer(fullName, html.Element, null);
this.errors.push(
TreeError.create(fullName, span, `Opening tag "${fullName}" not terminated.`),
);
}
}
private _pushContainer(node: NodeContainer, isClosedByChild: boolean) {
if (isClosedByChild) {
this._containerStack.pop();
}
this._addToParent(node);
this._containerStack.push(node);
}
private _consumeEndTag(endTagToken: TagCloseToken) {
const fullName = this._getElementFullName(
endTagToken.parts[0],
endTagToken.parts[1],
this._getClosestParentElement(),
);
if (this.getTagDefinition(fullName).isVoid) {
this.errors.push(
TreeError.create(
fullName,
endTagToken.sourceSpan,
`Void elements do not have end tags "${endTagToken.parts[1]}"`,
),
);
} else if (!this._popContainer(fullName, html.Element, endTagToken.sourceSpan)) {
const errMsg = `Unexpected closing tag "${fullName}". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags`;
this.errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
}
}
/**
* Closes the nearest element with the tag name `fullName` in the parse tree.
* `endSourceSpan` is the span of the closing tag, or null if the element does
* not have a closing tag (for example, this happens when an incomplete
* opening tag is recovered).
*/
private _popContainer(
expectedName: string | null,
expectedType: NodeContainerConstructor,
endSourceSpan: ParseSourceSpan | null,
): boolean {
let unexpectedCloseTagDetected = false;
for (let stackIndex = this._containerStack.length - 1; stackIndex >= 0; stackIndex--) {
const node = this._containerStack[stackIndex];
if ((node.name === expectedName || expectedName === null) && node instanceof expectedType) {
// Record the parse span with the element that is being closed. Any elements that are
// removed from the element stack at this point are closed implicitly, so they won't get
// an end source span (as there is no explicit closing element).
node.endSourceSpan = endSourceSpan;
node.sourceSpan.end = endSourceSpan !== null ? endSourceSpan.end : node.sourceSpan.end;
this._containerStack.splice(stackIndex, this._containerStack.length - stackIndex);
return !unexpectedCloseTagDetected;
}
// Blocks and most elements are not self closing.
if (
node instanceof html.Block ||
(node instanceof html.Element && !this.getTagDefinition(node.name).closedByParent)
) {
// Note that we encountered an unexpected close tag but continue processing the element
// stack so we can assign an `endSourceSpan` if there is a corresponding start tag for this
// end tag in the stack.
unexpectedCloseTagDetected = true;
}
}
return false;
} | {
"end_byte": 17211,
"start_byte": 9944,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/parser.ts"
} |
angular/packages/compiler/src/ml_parser/parser.ts_17215_25745 | private _consumeAttr(attrName: AttributeNameToken): html.Attribute {
const fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
let attrEnd = attrName.sourceSpan.end;
// Consume any quote
if (this._peek.type === TokenType.ATTR_QUOTE) {
this._advance();
}
// Consume the attribute value
let value = '';
const valueTokens: InterpolatedAttributeToken[] = [];
let valueStartSpan: ParseSourceSpan | undefined = undefined;
let valueEnd: ParseLocation | undefined = undefined;
// NOTE: We need to use a new variable `nextTokenType` here to hide the actual type of
// `_peek.type` from TS. Otherwise TS will narrow the type of `_peek.type` preventing it from
// being able to consider `ATTR_VALUE_INTERPOLATION` as an option. This is because TS is not
// able to see that `_advance()` will actually mutate `_peek`.
const nextTokenType = this._peek.type as TokenType;
if (nextTokenType === TokenType.ATTR_VALUE_TEXT) {
valueStartSpan = this._peek.sourceSpan;
valueEnd = this._peek.sourceSpan.end;
while (
this._peek.type === TokenType.ATTR_VALUE_TEXT ||
this._peek.type === TokenType.ATTR_VALUE_INTERPOLATION ||
this._peek.type === TokenType.ENCODED_ENTITY
) {
const valueToken = this._advance<InterpolatedAttributeToken>();
valueTokens.push(valueToken);
if (valueToken.type === TokenType.ATTR_VALUE_INTERPOLATION) {
// For backward compatibility we decode HTML entities that appear in interpolation
// expressions. This is arguably a bug, but it could be a considerable breaking change to
// fix it. It should be addressed in a larger project to refactor the entire parser/lexer
// chain after View Engine has been removed.
value += valueToken.parts.join('').replace(/&([^;]+);/g, decodeEntity);
} else if (valueToken.type === TokenType.ENCODED_ENTITY) {
value += valueToken.parts[0];
} else {
value += valueToken.parts.join('');
}
valueEnd = attrEnd = valueToken.sourceSpan.end;
}
}
// Consume any quote
if (this._peek.type === TokenType.ATTR_QUOTE) {
const quoteToken = this._advance<AttributeQuoteToken>();
attrEnd = quoteToken.sourceSpan.end;
}
const valueSpan =
valueStartSpan &&
valueEnd &&
new ParseSourceSpan(valueStartSpan.start, valueEnd, valueStartSpan.fullStart);
return new html.Attribute(
fullName,
value,
new ParseSourceSpan(attrName.sourceSpan.start, attrEnd, attrName.sourceSpan.fullStart),
attrName.sourceSpan,
valueSpan,
valueTokens.length > 0 ? valueTokens : undefined,
undefined,
);
}
private _consumeBlockOpen(token: BlockOpenStartToken) {
const parameters: html.BlockParameter[] = [];
while (this._peek.type === TokenType.BLOCK_PARAMETER) {
const paramToken = this._advance<BlockParameterToken>();
parameters.push(new html.BlockParameter(paramToken.parts[0], paramToken.sourceSpan));
}
if (this._peek.type === TokenType.BLOCK_OPEN_END) {
this._advance();
}
const end = this._peek.sourceSpan.fullStart;
const span = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
// Create a separate `startSpan` because `span` will be modified when there is an `end` span.
const startSpan = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
const block = new html.Block(token.parts[0], parameters, [], span, token.sourceSpan, startSpan);
this._pushContainer(block, false);
}
private _consumeBlockClose(token: BlockCloseToken) {
if (!this._popContainer(null, html.Block, token.sourceSpan)) {
this.errors.push(
TreeError.create(
null,
token.sourceSpan,
`Unexpected closing block. The block may have been closed earlier. ` +
`If you meant to write the } character, you should use the "}" ` +
`HTML entity instead.`,
),
);
}
}
private _consumeIncompleteBlock(token: IncompleteBlockOpenToken) {
const parameters: html.BlockParameter[] = [];
while (this._peek.type === TokenType.BLOCK_PARAMETER) {
const paramToken = this._advance<BlockParameterToken>();
parameters.push(new html.BlockParameter(paramToken.parts[0], paramToken.sourceSpan));
}
const end = this._peek.sourceSpan.fullStart;
const span = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
// Create a separate `startSpan` because `span` will be modified when there is an `end` span.
const startSpan = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
const block = new html.Block(token.parts[0], parameters, [], span, token.sourceSpan, startSpan);
this._pushContainer(block, false);
// Incomplete blocks don't have children so we close them immediately and report an error.
this._popContainer(null, html.Block, null);
this.errors.push(
TreeError.create(
token.parts[0],
span,
`Incomplete block "${token.parts[0]}". If you meant to write the @ character, ` +
`you should use the "@" HTML entity instead.`,
),
);
}
private _consumeLet(startToken: LetStartToken) {
const name = startToken.parts[0];
let valueToken: LetValueToken;
let endToken: LetEndToken;
if (this._peek.type !== TokenType.LET_VALUE) {
this.errors.push(
TreeError.create(
startToken.parts[0],
startToken.sourceSpan,
`Invalid @let declaration "${name}". Declaration must have a value.`,
),
);
return;
} else {
valueToken = this._advance();
}
// Type cast is necessary here since TS narrowed the type of `peek` above.
if ((this._peek as Token).type !== TokenType.LET_END) {
this.errors.push(
TreeError.create(
startToken.parts[0],
startToken.sourceSpan,
`Unterminated @let declaration "${name}". Declaration must be terminated with a semicolon.`,
),
);
return;
} else {
endToken = this._advance();
}
const end = endToken.sourceSpan.fullStart;
const span = new ParseSourceSpan(
startToken.sourceSpan.start,
end,
startToken.sourceSpan.fullStart,
);
// The start token usually captures the `@let`. Construct a name span by
// offsetting the start by the length of any text before the name.
const startOffset = startToken.sourceSpan.toString().lastIndexOf(name);
const nameStart = startToken.sourceSpan.start.moveBy(startOffset);
const nameSpan = new ParseSourceSpan(nameStart, startToken.sourceSpan.end);
const node = new html.LetDeclaration(
name,
valueToken.parts[0],
span,
nameSpan,
valueToken.sourceSpan,
);
this._addToParent(node);
}
private _consumeIncompleteLet(token: IncompleteLetToken) {
// Incomplete `@let` declaration may end up with an empty name.
const name = token.parts[0] ?? '';
const nameString = name ? ` "${name}"` : '';
// If there's at least a name, we can salvage an AST node that can be used for completions.
if (name.length > 0) {
const startOffset = token.sourceSpan.toString().lastIndexOf(name);
const nameStart = token.sourceSpan.start.moveBy(startOffset);
const nameSpan = new ParseSourceSpan(nameStart, token.sourceSpan.end);
const valueSpan = new ParseSourceSpan(
token.sourceSpan.start,
token.sourceSpan.start.moveBy(0),
);
const node = new html.LetDeclaration(name, '', token.sourceSpan, nameSpan, valueSpan);
this._addToParent(node);
}
this.errors.push(
TreeError.create(
token.parts[0],
token.sourceSpan,
`Incomplete @let declaration${nameString}. ` +
`@let declarations must be written as \`@let <name> = <value>;\``,
),
);
}
private _getContainer(): NodeContainer | null {
return this._containerStack.length > 0
? this._containerStack[this._containerStack.length - 1]
: null;
}
private _getClosestParentElement(): html.Element | null {
for (let i = this._containerStack.length - 1; i > -1; i--) {
if (this._containerStack[i] instanceof html.Element) {
return this._containerStack[i] as html.Element;
}
}
return null;
} | {
"end_byte": 25745,
"start_byte": 17215,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/parser.ts"
} |
angular/packages/compiler/src/ml_parser/parser.ts_25749_27270 | private _addToParent(node: html.Node) {
const parent = this._getContainer();
if (parent === null) {
this.rootNodes.push(node);
} else {
parent.children.push(node);
}
}
private _getElementFullName(
prefix: string,
localName: string,
parentElement: html.Element | null,
): string {
if (prefix === '') {
prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
if (prefix === '' && parentElement != null) {
const parentTagName = splitNsName(parentElement.name)[1];
const parentTagDefinition = this.getTagDefinition(parentTagName);
if (!parentTagDefinition.preventNamespaceInheritance) {
prefix = getNsPrefix(parentElement.name);
}
}
}
return mergeNsAndName(prefix, localName);
}
}
function lastOnStack(stack: any[], element: any): boolean {
return stack.length > 0 && stack[stack.length - 1] === element;
}
/**
* Decode the `entity` string, which we believe is the contents of an HTML entity.
*
* If the string is not actually a valid/known entity then just return the original `match` string.
*/
function decodeEntity(match: string, entity: string): string {
if (NAMED_ENTITIES[entity] !== undefined) {
return NAMED_ENTITIES[entity] || match;
}
if (/^#x[a-f0-9]+$/i.test(entity)) {
return String.fromCodePoint(parseInt(entity.slice(2), 16));
}
if (/^#\d+$/.test(entity)) {
return String.fromCodePoint(parseInt(entity.slice(1), 10));
}
return match;
} | {
"end_byte": 27270,
"start_byte": 25749,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/parser.ts"
} |
angular/packages/compiler/src/ml_parser/tokens.ts_0_5934 | /**
* @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.dev/license
*/
import {ParseSourceSpan} from '../parse_util';
export const enum TokenType {
TAG_OPEN_START,
TAG_OPEN_END,
TAG_OPEN_END_VOID,
TAG_CLOSE,
INCOMPLETE_TAG_OPEN,
TEXT,
ESCAPABLE_RAW_TEXT,
RAW_TEXT,
INTERPOLATION,
ENCODED_ENTITY,
COMMENT_START,
COMMENT_END,
CDATA_START,
CDATA_END,
ATTR_NAME,
ATTR_QUOTE,
ATTR_VALUE_TEXT,
ATTR_VALUE_INTERPOLATION,
DOC_TYPE,
EXPANSION_FORM_START,
EXPANSION_CASE_VALUE,
EXPANSION_CASE_EXP_START,
EXPANSION_CASE_EXP_END,
EXPANSION_FORM_END,
BLOCK_OPEN_START,
BLOCK_OPEN_END,
BLOCK_CLOSE,
BLOCK_PARAMETER,
INCOMPLETE_BLOCK_OPEN,
LET_START,
LET_VALUE,
LET_END,
INCOMPLETE_LET,
EOF,
}
export type Token =
| TagOpenStartToken
| TagOpenEndToken
| TagOpenEndVoidToken
| TagCloseToken
| IncompleteTagOpenToken
| TextToken
| InterpolationToken
| EncodedEntityToken
| CommentStartToken
| CommentEndToken
| CdataStartToken
| CdataEndToken
| AttributeNameToken
| AttributeQuoteToken
| AttributeValueTextToken
| AttributeValueInterpolationToken
| DocTypeToken
| ExpansionFormStartToken
| ExpansionCaseValueToken
| ExpansionCaseExpressionStartToken
| ExpansionCaseExpressionEndToken
| ExpansionFormEndToken
| EndOfFileToken
| BlockParameterToken
| BlockOpenStartToken
| BlockOpenEndToken
| BlockCloseToken
| IncompleteBlockOpenToken
| LetStartToken
| LetValueToken
| LetEndToken
| IncompleteLetToken;
export type InterpolatedTextToken = TextToken | InterpolationToken | EncodedEntityToken;
export type InterpolatedAttributeToken =
| AttributeValueTextToken
| AttributeValueInterpolationToken
| EncodedEntityToken;
export interface TokenBase {
type: TokenType;
parts: string[];
sourceSpan: ParseSourceSpan;
}
export interface TagOpenStartToken extends TokenBase {
type: TokenType.TAG_OPEN_START;
parts: [prefix: string, name: string];
}
export interface TagOpenEndToken extends TokenBase {
type: TokenType.TAG_OPEN_END;
parts: [];
}
export interface TagOpenEndVoidToken extends TokenBase {
type: TokenType.TAG_OPEN_END_VOID;
parts: [];
}
export interface TagCloseToken extends TokenBase {
type: TokenType.TAG_CLOSE;
parts: [prefix: string, name: string];
}
export interface IncompleteTagOpenToken extends TokenBase {
type: TokenType.INCOMPLETE_TAG_OPEN;
parts: [prefix: string, name: string];
}
export interface TextToken extends TokenBase {
type: TokenType.TEXT | TokenType.ESCAPABLE_RAW_TEXT | TokenType.RAW_TEXT;
parts: [text: string];
}
export interface InterpolationToken extends TokenBase {
type: TokenType.INTERPOLATION;
parts:
| [startMarker: string, expression: string, endMarker: string]
| [startMarker: string, expression: string];
}
export interface EncodedEntityToken extends TokenBase {
type: TokenType.ENCODED_ENTITY;
parts: [decoded: string, encoded: string];
}
export interface CommentStartToken extends TokenBase {
type: TokenType.COMMENT_START;
parts: [];
}
export interface CommentEndToken extends TokenBase {
type: TokenType.COMMENT_END;
parts: [];
}
export interface CdataStartToken extends TokenBase {
type: TokenType.CDATA_START;
parts: [];
}
export interface CdataEndToken extends TokenBase {
type: TokenType.CDATA_END;
parts: [];
}
export interface AttributeNameToken extends TokenBase {
type: TokenType.ATTR_NAME;
parts: [prefix: string, name: string];
}
export interface AttributeQuoteToken extends TokenBase {
type: TokenType.ATTR_QUOTE;
parts: [quote: "'" | '"'];
}
export interface AttributeValueTextToken extends TokenBase {
type: TokenType.ATTR_VALUE_TEXT;
parts: [value: string];
}
export interface AttributeValueInterpolationToken extends TokenBase {
type: TokenType.ATTR_VALUE_INTERPOLATION;
parts:
| [startMarker: string, expression: string, endMarker: string]
| [startMarker: string, expression: string];
}
export interface DocTypeToken extends TokenBase {
type: TokenType.DOC_TYPE;
parts: [content: string];
}
export interface ExpansionFormStartToken extends TokenBase {
type: TokenType.EXPANSION_FORM_START;
parts: [];
}
export interface ExpansionCaseValueToken extends TokenBase {
type: TokenType.EXPANSION_CASE_VALUE;
parts: [value: string];
}
export interface ExpansionCaseExpressionStartToken extends TokenBase {
type: TokenType.EXPANSION_CASE_EXP_START;
parts: [];
}
export interface ExpansionCaseExpressionEndToken extends TokenBase {
type: TokenType.EXPANSION_CASE_EXP_END;
parts: [];
}
export interface ExpansionFormEndToken extends TokenBase {
type: TokenType.EXPANSION_FORM_END;
parts: [];
}
export interface EndOfFileToken extends TokenBase {
type: TokenType.EOF;
parts: [];
}
export interface BlockParameterToken extends TokenBase {
type: TokenType.BLOCK_PARAMETER;
parts: [expression: string];
}
export interface BlockOpenStartToken extends TokenBase {
type: TokenType.BLOCK_OPEN_START;
parts: [name: string];
}
export interface BlockOpenEndToken extends TokenBase {
type: TokenType.BLOCK_OPEN_END;
parts: [];
}
export interface BlockCloseToken extends TokenBase {
type: TokenType.BLOCK_CLOSE;
parts: [];
}
export interface IncompleteBlockOpenToken extends TokenBase {
type: TokenType.INCOMPLETE_BLOCK_OPEN;
parts: [name: string];
}
export interface LetStartToken extends TokenBase {
type: TokenType.LET_START;
parts: [name: string];
}
export interface LetValueToken extends TokenBase {
type: TokenType.LET_VALUE;
parts: [value: string];
}
export interface LetEndToken extends TokenBase {
type: TokenType.LET_END;
parts: [];
}
export interface IncompleteLetToken extends TokenBase {
type: TokenType.INCOMPLETE_LET;
parts: [name: string];
}
| {
"end_byte": 5934,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/tokens.ts"
} |
angular/packages/compiler/src/ml_parser/xml_parser.ts_0_706 | /**
* @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.dev/license
*/
import {TokenizeOptions} from './lexer';
import {Parser, ParseTreeResult} from './parser';
import {getXmlTagDefinition} from './xml_tags';
export class XmlParser extends Parser {
constructor() {
super(getXmlTagDefinition);
}
override parse(source: string, url: string, options: TokenizeOptions = {}): ParseTreeResult {
// Blocks and let declarations aren't supported in an XML context.
return super.parse(source, url, {...options, tokenizeBlocks: false, tokenizeLet: false});
}
}
| {
"end_byte": 706,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/xml_parser.ts"
} |
angular/packages/compiler/src/ml_parser/html_tags.ts_0_7789 | /**
* @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.dev/license
*/
import {DomElementSchemaRegistry} from '../schema/dom_element_schema_registry';
import {getNsPrefix, TagContentType, TagDefinition} from './tags';
export class HtmlTagDefinition implements TagDefinition {
private closedByChildren: {[key: string]: boolean} = {};
private contentType:
| TagContentType
| {default: TagContentType; [namespace: string]: TagContentType};
closedByParent = false;
implicitNamespacePrefix: string | null;
isVoid: boolean;
ignoreFirstLf: boolean;
canSelfClose: boolean;
preventNamespaceInheritance: boolean;
constructor({
closedByChildren,
implicitNamespacePrefix,
contentType = TagContentType.PARSABLE_DATA,
closedByParent = false,
isVoid = false,
ignoreFirstLf = false,
preventNamespaceInheritance = false,
canSelfClose = false,
}: {
closedByChildren?: string[];
closedByParent?: boolean;
implicitNamespacePrefix?: string;
contentType?: TagContentType | {default: TagContentType; [namespace: string]: TagContentType};
isVoid?: boolean;
ignoreFirstLf?: boolean;
preventNamespaceInheritance?: boolean;
canSelfClose?: boolean;
} = {}) {
if (closedByChildren && closedByChildren.length > 0) {
closedByChildren.forEach((tagName) => (this.closedByChildren[tagName] = true));
}
this.isVoid = isVoid;
this.closedByParent = closedByParent || isVoid;
this.implicitNamespacePrefix = implicitNamespacePrefix || null;
this.contentType = contentType;
this.ignoreFirstLf = ignoreFirstLf;
this.preventNamespaceInheritance = preventNamespaceInheritance;
this.canSelfClose = canSelfClose ?? isVoid;
}
isClosedByChild(name: string): boolean {
return this.isVoid || name.toLowerCase() in this.closedByChildren;
}
getContentType(prefix?: string): TagContentType {
if (typeof this.contentType === 'object') {
const overrideType = prefix === undefined ? undefined : this.contentType[prefix];
return overrideType ?? this.contentType.default;
}
return this.contentType;
}
}
let DEFAULT_TAG_DEFINITION!: HtmlTagDefinition;
// see https://www.w3.org/TR/html51/syntax.html#optional-tags
// This implementation does not fully conform to the HTML5 spec.
let TAG_DEFINITIONS!: {[key: string]: HtmlTagDefinition};
export function getHtmlTagDefinition(tagName: string): HtmlTagDefinition {
if (!TAG_DEFINITIONS) {
DEFAULT_TAG_DEFINITION = new HtmlTagDefinition({canSelfClose: true});
TAG_DEFINITIONS = Object.assign(Object.create(null), {
'base': new HtmlTagDefinition({isVoid: true}),
'meta': new HtmlTagDefinition({isVoid: true}),
'area': new HtmlTagDefinition({isVoid: true}),
'embed': new HtmlTagDefinition({isVoid: true}),
'link': new HtmlTagDefinition({isVoid: true}),
'img': new HtmlTagDefinition({isVoid: true}),
'input': new HtmlTagDefinition({isVoid: true}),
'param': new HtmlTagDefinition({isVoid: true}),
'hr': new HtmlTagDefinition({isVoid: true}),
'br': new HtmlTagDefinition({isVoid: true}),
'source': new HtmlTagDefinition({isVoid: true}),
'track': new HtmlTagDefinition({isVoid: true}),
'wbr': new HtmlTagDefinition({isVoid: true}),
'p': new HtmlTagDefinition({
closedByChildren: [
'address',
'article',
'aside',
'blockquote',
'div',
'dl',
'fieldset',
'footer',
'form',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'header',
'hgroup',
'hr',
'main',
'nav',
'ol',
'p',
'pre',
'section',
'table',
'ul',
],
closedByParent: true,
}),
'thead': new HtmlTagDefinition({closedByChildren: ['tbody', 'tfoot']}),
'tbody': new HtmlTagDefinition({closedByChildren: ['tbody', 'tfoot'], closedByParent: true}),
'tfoot': new HtmlTagDefinition({closedByChildren: ['tbody'], closedByParent: true}),
'tr': new HtmlTagDefinition({closedByChildren: ['tr'], closedByParent: true}),
'td': new HtmlTagDefinition({closedByChildren: ['td', 'th'], closedByParent: true}),
'th': new HtmlTagDefinition({closedByChildren: ['td', 'th'], closedByParent: true}),
'col': new HtmlTagDefinition({isVoid: true}),
'svg': new HtmlTagDefinition({implicitNamespacePrefix: 'svg'}),
'foreignObject': new HtmlTagDefinition({
// Usually the implicit namespace here would be redundant since it will be inherited from
// the parent `svg`, but we have to do it for `foreignObject`, because the way the parser
// works is that the parent node of an end tag is its own start tag which means that
// the `preventNamespaceInheritance` on `foreignObject` would have it default to the
// implicit namespace which is `html`, unless specified otherwise.
implicitNamespacePrefix: 'svg',
// We want to prevent children of foreignObject from inheriting its namespace, because
// the point of the element is to allow nodes from other namespaces to be inserted.
preventNamespaceInheritance: true,
}),
'math': new HtmlTagDefinition({implicitNamespacePrefix: 'math'}),
'li': new HtmlTagDefinition({closedByChildren: ['li'], closedByParent: true}),
'dt': new HtmlTagDefinition({closedByChildren: ['dt', 'dd']}),
'dd': new HtmlTagDefinition({closedByChildren: ['dt', 'dd'], closedByParent: true}),
'rb': new HtmlTagDefinition({
closedByChildren: ['rb', 'rt', 'rtc', 'rp'],
closedByParent: true,
}),
'rt': new HtmlTagDefinition({
closedByChildren: ['rb', 'rt', 'rtc', 'rp'],
closedByParent: true,
}),
'rtc': new HtmlTagDefinition({closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true}),
'rp': new HtmlTagDefinition({
closedByChildren: ['rb', 'rt', 'rtc', 'rp'],
closedByParent: true,
}),
'optgroup': new HtmlTagDefinition({closedByChildren: ['optgroup'], closedByParent: true}),
'option': new HtmlTagDefinition({
closedByChildren: ['option', 'optgroup'],
closedByParent: true,
}),
'pre': new HtmlTagDefinition({ignoreFirstLf: true}),
'listing': new HtmlTagDefinition({ignoreFirstLf: true}),
'style': new HtmlTagDefinition({contentType: TagContentType.RAW_TEXT}),
'script': new HtmlTagDefinition({contentType: TagContentType.RAW_TEXT}),
'title': new HtmlTagDefinition({
// The browser supports two separate `title` tags which have to use
// a different content type: `HTMLTitleElement` and `SVGTitleElement`
contentType: {
default: TagContentType.ESCAPABLE_RAW_TEXT,
svg: TagContentType.PARSABLE_DATA,
},
}),
'textarea': new HtmlTagDefinition({
contentType: TagContentType.ESCAPABLE_RAW_TEXT,
ignoreFirstLf: true,
}),
});
new DomElementSchemaRegistry().allKnownElementNames().forEach((knownTagName) => {
if (!TAG_DEFINITIONS[knownTagName] && getNsPrefix(knownTagName) === null) {
TAG_DEFINITIONS[knownTagName] = new HtmlTagDefinition({canSelfClose: false});
}
});
}
// We have to make both a case-sensitive and a case-insensitive lookup, because
// HTML tag names are case insensitive, whereas some SVG tags are case sensitive.
return (
TAG_DEFINITIONS[tagName] ?? TAG_DEFINITIONS[tagName.toLowerCase()] ?? DEFAULT_TAG_DEFINITION
);
}
| {
"end_byte": 7789,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/html_tags.ts"
} |
angular/packages/compiler/src/ml_parser/html_parser.ts_0_587 | /**
* @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.dev/license
*/
import {getHtmlTagDefinition} from './html_tags';
import {TokenizeOptions} from './lexer';
import {Parser, ParseTreeResult} from './parser';
export class HtmlParser extends Parser {
constructor() {
super(getHtmlTagDefinition);
}
override parse(source: string, url: string, options?: TokenizeOptions): ParseTreeResult {
return super.parse(source, url, options);
}
}
| {
"end_byte": 587,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/html_parser.ts"
} |
angular/packages/compiler/src/ml_parser/tags.ts_0_1990 | /**
* @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.dev/license
*/
export enum TagContentType {
RAW_TEXT,
ESCAPABLE_RAW_TEXT,
PARSABLE_DATA,
}
export interface TagDefinition {
closedByParent: boolean;
implicitNamespacePrefix: string | null;
isVoid: boolean;
ignoreFirstLf: boolean;
canSelfClose: boolean;
preventNamespaceInheritance: boolean;
isClosedByChild(name: string): boolean;
getContentType(prefix?: string): TagContentType;
}
export function splitNsName(elementName: string, fatal: boolean = true): [string | null, string] {
if (elementName[0] != ':') {
return [null, elementName];
}
const colonIndex = elementName.indexOf(':', 1);
if (colonIndex === -1) {
if (fatal) {
throw new Error(`Unsupported format "${elementName}" expecting ":namespace:name"`);
} else {
return [null, elementName];
}
}
return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
}
// `<ng-container>` tags work the same regardless the namespace
export function isNgContainer(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-container';
}
// `<ng-content>` tags work the same regardless the namespace
export function isNgContent(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-content';
}
// `<ng-template>` tags work the same regardless the namespace
export function isNgTemplate(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-template';
}
export function getNsPrefix(fullName: string): string;
export function getNsPrefix(fullName: null): null;
export function getNsPrefix(fullName: string | null): string | null {
return fullName === null ? null : splitNsName(fullName)[0];
}
export function mergeNsAndName(prefix: string, localName: string): string {
return prefix ? `:${prefix}:${localName}` : localName;
}
| {
"end_byte": 1990,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/ml_parser/tags.ts"
} |
angular/packages/animations/PACKAGE.md_0_1858 | Implements a domain-specific language (DSL) for defining web animation sequences for HTML elements as
multiple transformations over time.
Use this API to define how an HTML element can move, change color, grow or shrink, fade, or slide off
the page. These changes can occur simultaneously or sequentially. You can control the timing of each
of these transformations. The function calls generate the data structures and metadata that enable Angular
to integrate animations into templates and run them based on application states.
Animation definitions are linked to components through the `{@link Component.animations animations}`
property in the `@Component` metadata, typically in the component file of the HTML element to be animated.
The `trigger()` function encapsulates a named animation, with all other function calls nested within. Use
the trigger name to bind the named animation to a specific triggering element in the HTML template.
Angular animations are based on CSS web transition functionality, so anything that can be styled or
transformed in CSS can be animated the same way in Angular. Angular animations allow you to:
* Set animation timings, styles, keyframes, and transitions.
* Animate HTML elements in complex sequences and choreographies.
* Animate HTML elements as they are inserted and removed from the DOM, including responsive real-time
filtering.
* Create reusable animations.
* Animate parent and child elements.
Additional animation functionality is provided in other Angular modules for animation testing, for
route-based animations, and for programmatic animation controls that allow an end user to fast forward
and reverse an animation sequence.
@see Find out more in the [animations guide](guide/animations).
@see See what polyfills you might need in the [browser support guide](reference/versions#browser-support).
| {
"end_byte": 1858,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/PACKAGE.md"
} |
angular/packages/animations/BUILD.bazel_0_2018 | load("//tools:defaults.bzl", "api_golden_test", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "animations",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/common",
"//packages/core",
],
)
ng_package(
name = "npm_package",
package_name = "@angular/animations",
srcs = [
"package.json",
],
tags = [
"release-with-framework",
],
# Do not add more to this list.
# Dependencies on the full npm_package cause long re-builds.
visibility = [
"//adev:__pkg__",
"//integration:__subpackages__",
"//modules/ssr-benchmarks:__subpackages__",
"//packages/compiler-cli/integrationtest:__pkg__",
"//packages/compiler/test:__pkg__",
],
deps = [
":animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
],
)
api_golden_test_npm_package(
name = "animations_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular/goldens/public-api/animations",
npm_package = "angular/packages/animations/npm_package",
)
api_golden_test(
name = "animations_errors",
data = [
"//goldens:public-api",
"//packages/animations",
"//packages/animations/browser",
],
entry_point = "angular/packages/animations/src/errors.d.ts",
golden = "angular/goldens/public-api/animations/errors.api.md",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "animations_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
"//packages/common:files_for_docgen",
],
entry_point = ":index.ts",
module_name = "@angular/animations",
)
| {
"end_byte": 2018,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/BUILD.bazel"
} |
angular/packages/animations/index.ts_0_481 | /**
* @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.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/index.ts"
} |
angular/packages/animations/public_api.ts_0_325 | /**
* @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.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/animations';
| {
"end_byte": 325,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/public_api.ts"
} |
angular/packages/animations/test/animation_group_player_spec.ts_0_1445 | /**
* @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.dev/license
*/
import {fakeAsync} from '@angular/core/testing';
import {NoopAnimationPlayer} from '../src/animations';
import {AnimationGroupPlayer} from '../src/players/animation_group_player';
describe('AnimationGroupPlayer', () => {
it('should getPosition of an empty group', fakeAsync(() => {
const players: NoopAnimationPlayer[] = [];
const groupPlayer = new AnimationGroupPlayer(players);
expect(groupPlayer.getPosition()).toBe(0);
}));
it('should getPosition of a single player in a group', fakeAsync(() => {
const player = new NoopAnimationPlayer(5, 5);
player.setPosition(0.2);
const players = [player];
const groupPlayer = new AnimationGroupPlayer(players);
expect(groupPlayer.getPosition()).toBe(0.2);
}));
it('should getPosition based on the longest player in the group', fakeAsync(() => {
const longestPlayer = new NoopAnimationPlayer(5, 5);
longestPlayer.setPosition(0.2);
const players = [
new NoopAnimationPlayer(1, 4),
new NoopAnimationPlayer(4, 1),
new NoopAnimationPlayer(7, 0),
longestPlayer,
new NoopAnimationPlayer(1, 1),
];
const groupPlayer = new AnimationGroupPlayer(players);
expect(groupPlayer.getPosition()).toBe(0.2);
}));
});
| {
"end_byte": 1445,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/test/animation_group_player_spec.ts"
} |
angular/packages/animations/test/browser_animation_builder_spec.ts_0_8511 | /**
* @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.dev/license
*/
import {
animate,
AnimationBuilder,
style,
ɵBrowserAnimationBuilder as BrowserAnimationBuilder,
} from '@angular/animations';
import {AnimationDriver} from '@angular/animations/browser';
import {MockAnimationDriver} from '@angular/animations/browser/testing';
import {DOCUMENT} from '@angular/common';
import {Component, NgZone, RendererFactory2, ViewChild} from '@angular/core';
import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing';
import {ɵDomRendererFactory2 as DomRendererFactory2} from '@angular/platform-browser';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {ɵAsyncAnimationRendererFactory as AsyncAnimationRendererFactory} from '@angular/platform-browser/animations/async';
describe('BrowserAnimationBuilder', () => {
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}],
});
});
it('should inject AnimationBuilder into a component', () => {
@Component({
selector: 'ani-cmp',
template: '...',
standalone: false,
})
class Cmp {
constructor(public builder: AnimationBuilder) {}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
expect(cmp.builder instanceof BrowserAnimationBuilder).toBeTruthy();
});
it("should listen on start and done on the animation builder's player after it has been reset", fakeAsync(() => {
@Component({
selector: 'ani-cmp',
template: '...',
standalone: false,
})
class Cmp {
@ViewChild('target') public target: any;
constructor(public builder: AnimationBuilder) {}
build() {
const definition = this.builder.build([
style({opacity: 0}),
animate(1000, style({opacity: 1})),
]);
return definition.create(this.target);
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
const player = cmp.build();
let startedCount = 0;
player.onStart(() => startedCount++);
let finishedCount = 0;
player.onDone(() => finishedCount++);
player.init();
flushMicrotasks();
expect(startedCount).toEqual(0);
expect(finishedCount).toEqual(0);
player.play();
flushMicrotasks();
expect(startedCount).toEqual(1);
expect(finishedCount).toEqual(0);
player.finish();
flushMicrotasks();
expect(startedCount).toEqual(1);
expect(finishedCount).toEqual(1);
player.play();
player.finish();
flushMicrotasks();
expect(startedCount).toEqual(1);
expect(finishedCount).toEqual(1);
[0, 1, 2, 3].forEach((i) => {
player.reset();
player.play();
flushMicrotasks();
expect(startedCount).toEqual(i + 2);
expect(finishedCount).toEqual(i + 1);
player.finish();
flushMicrotasks();
expect(startedCount).toEqual(i + 2);
expect(finishedCount).toEqual(i + 2);
});
}));
it("should listen on start and done on the animation builder's player", fakeAsync(() => {
@Component({
selector: 'ani-cmp',
template: '...',
standalone: false,
})
class Cmp {
@ViewChild('target') public target: any;
constructor(public builder: AnimationBuilder) {}
build() {
const definition = this.builder.build([
style({opacity: 0}),
animate(1000, style({opacity: 1})),
]);
return definition.create(this.target);
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
const player = cmp.build();
let started = false;
player.onStart(() => (started = true));
let finished = false;
player.onDone(() => (finished = true));
let destroyed = false;
player.onDestroy(() => (destroyed = true));
player.init();
flushMicrotasks();
expect(started).toBeFalsy();
expect(finished).toBeFalsy();
expect(destroyed).toBeFalsy();
player.play();
flushMicrotasks();
expect(started).toBeTruthy();
expect(finished).toBeFalsy();
expect(destroyed).toBeFalsy();
player.finish();
flushMicrotasks();
expect(started).toBeTruthy();
expect(finished).toBeTruthy();
expect(destroyed).toBeFalsy();
player.destroy();
flushMicrotasks();
expect(started).toBeTruthy();
expect(finished).toBeTruthy();
expect(destroyed).toBeTruthy();
}));
it('should update `hasStarted()` on `play()` and `reset()`', fakeAsync(() => {
@Component({
selector: 'ani-another-cmp',
template: '...',
standalone: false,
})
class CmpAnother {
@ViewChild('target') public target: any;
constructor(public builder: AnimationBuilder) {}
build() {
const definition = this.builder.build([
style({opacity: 0}),
animate(1000, style({opacity: 1})),
]);
return definition.create(this.target);
}
}
TestBed.configureTestingModule({declarations: [CmpAnother]});
const fixture = TestBed.createComponent(CmpAnother);
const cmp = fixture.componentInstance;
fixture.detectChanges();
const player = cmp.build();
expect(player.hasStarted()).toBeFalsy();
flushMicrotasks();
player.play();
flushMicrotasks();
expect(player.hasStarted()).toBeTruthy();
player.reset();
flushMicrotasks();
expect(player.hasStarted()).toBeFalsy();
}));
describe('without Animations enabled', () => {
beforeEach(() => {
// We need to reset the test environment because
// browser_tests.init.ts inits the environment with the NoopAnimationsModule
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment([BrowserDynamicTestingModule], platformBrowserDynamicTesting());
});
it('should throw an error when injecting AnimationBuilder without animation providers set', () => {
expect(() => TestBed.inject(AnimationBuilder)).toThrowError(
/Angular detected that the `AnimationBuilder` was injected/,
);
});
afterEach(() => {
// We're reset the test environment to their default values, cf browser_tests.init.ts
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(
[BrowserDynamicTestingModule, NoopAnimationsModule],
platformBrowserDynamicTesting(),
);
});
});
describe('with Animations async', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: RendererFactory2,
useFactory: (doc: Document, renderer: DomRendererFactory2, zone: NgZone) => {
// Using a empty promise to prevent switching to the delegate to AnimationRenderer
return new AsyncAnimationRendererFactory(
doc,
renderer,
zone,
'noop',
new Promise<any>(() => {}),
);
},
deps: [DOCUMENT, DomRendererFactory2, NgZone],
},
],
});
});
it('should be able to build', () => {
@Component({
selector: 'ani-cmp',
template: '...',
standalone: false,
})
class Cmp {
@ViewChild('target') public target: any;
constructor(public builder: AnimationBuilder) {}
build() {
const definition = this.builder.build([style({'transform': `rotate(0deg)`})]);
return definition.create(this.target);
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
cmp.build();
});
});
});
| {
"end_byte": 8511,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/test/browser_animation_builder_spec.ts"
} |
angular/packages/animations/test/util_spec.ts_0_513 | /**
* @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.dev/license
*/
describe('util', () => {
it('should schedule a microtask and not call an async timeout', (done) => {
let count = 0;
queueMicrotask(() => count++);
expect(count).toEqual(0);
queueMicrotask(() => {
expect(count).toEqual(1);
done();
});
expect(count).toEqual(0);
});
});
| {
"end_byte": 513,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/test/util_spec.ts"
} |
angular/packages/animations/test/BUILD.bazel_0_1152 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/animations/index.mjs",
deps = [
"//packages/animations",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
"//packages/common",
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-browser-dynamic/testing",
"//packages/platform-browser/animations",
"//packages/platform-browser/animations/async",
"//packages/platform-browser/testing",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
| {
"end_byte": 1152,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/test/BUILD.bazel"
} |
angular/packages/animations/test/animation_player_spec.ts_0_2371 | /**
* @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.dev/license
*/
import {fakeAsync} from '@angular/core/testing';
import {flushMicrotasks} from '../../core/testing/src/fake_async';
import {NoopAnimationPlayer} from '../src/players/animation_player';
describe('NoopAnimationPlayer', () => {
it('should finish after the next microtask once started', fakeAsync(() => {
const log: string[] = [];
const player = new NoopAnimationPlayer();
player.onStart(() => log.push('started'));
player.onDone(() => log.push('done'));
flushMicrotasks();
expect(log).toEqual([]);
player.play();
expect(log).toEqual(['started']);
flushMicrotasks();
expect(log).toEqual(['started', 'done']);
}));
it('should fire all callbacks when destroyed', () => {
const log: string[] = [];
const player = new NoopAnimationPlayer();
player.onStart(() => log.push('started'));
player.onDone(() => log.push('done'));
player.onDestroy(() => log.push('destroy'));
expect(log).toEqual([]);
player.destroy();
expect(log).toEqual(['started', 'done', 'destroy']);
});
it('should fire start/done callbacks manually when called directly', fakeAsync(() => {
const log: string[] = [];
const player = new NoopAnimationPlayer();
player.onStart(() => log.push('started'));
player.onDone(() => log.push('done'));
flushMicrotasks();
(player as any).triggerCallback('start');
expect(log).toEqual(['started']);
player.play();
expect(log).toEqual(['started']);
(player as any).triggerCallback('done');
expect(log).toEqual(['started', 'done']);
player.finish();
expect(log).toEqual(['started', 'done']);
flushMicrotasks();
expect(log).toEqual(['started', 'done']);
}));
it('should fire off start callbacks before triggering the finish callback', fakeAsync(() => {
const log: string[] = [];
const player = new NoopAnimationPlayer();
player.onStart(() => {
queueMicrotask(() => log.push('started'));
});
player.onDone(() => log.push('done'));
expect(log).toEqual([]);
player.play();
expect(log).toEqual([]);
flushMicrotasks();
expect(log).toEqual(['started', 'done']);
}));
});
| {
"end_byte": 2371,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/test/animation_player_spec.ts"
} |
angular/packages/animations/browser/PACKAGE.md_0_80 | Provides infrastructure for cross-platform rendering of animations in a browser. | {
"end_byte": 80,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/PACKAGE.md"
} |
angular/packages/animations/browser/BUILD.bazel_0_778 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "browser",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/animations",
"//packages/core",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "animations_browser_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
"//packages/animations:files_for_docgen",
],
entry_point = ":index.ts",
module_name = "@angular/animations/browser",
)
| {
"end_byte": 778,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/BUILD.bazel"
} |
angular/packages/animations/browser/index.ts_0_481 | /**
* @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.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/index.ts"
} |
angular/packages/animations/browser/public_api.ts_0_322 | /**
* @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.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/browser';
| {
"end_byte": 322,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/public_api.ts"
} |
angular/packages/animations/browser/test/shared.ts_0_1345 | /**
* @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.dev/license
*/
import {trigger} from '@angular/animations';
import {TriggerAst} from '../src/dsl/animation_ast';
import {buildAnimationAst} from '../src/dsl/animation_ast_builder';
import {AnimationTrigger, buildTrigger} from '../src/dsl/animation_trigger';
import {NoopAnimationStyleNormalizer} from '../src/dsl/style_normalization/animation_style_normalizer';
import {triggerParsingFailed} from '../src/error_helpers';
import {triggerParsingWarnings} from '../src/warning_helpers';
import {MockAnimationDriver} from '../testing/src/mock_animation_driver';
export function makeTrigger(
name: string,
steps: any,
skipErrors: boolean = false,
): AnimationTrigger {
const driver = new MockAnimationDriver();
const errors: Error[] = [];
const warnings: string[] = [];
const triggerData = trigger(name, steps);
const triggerAst = buildAnimationAst(driver, triggerData, errors, warnings) as TriggerAst;
if (!skipErrors && errors.length) {
throw triggerParsingFailed(name, errors);
}
if (warnings.length) {
triggerParsingWarnings(name, warnings);
}
return buildTrigger(name, triggerAst, new NoopAnimationStyleNormalizer());
}
| {
"end_byte": 1345,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/shared.ts"
} |
angular/packages/animations/browser/test/BUILD.bazel_0_1123 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/animations/browser/index.mjs",
deps = ["//packages/animations/browser"],
)
circular_dependency_test(
name = "testing_circular_deps_test",
entry_point = "angular/packages/animations/browser/testing/index.mjs",
deps = ["//packages/animations/browser/testing"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser/testing",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
| {
"end_byte": 1123,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/BUILD.bazel"
} |
angular/packages/animations/browser/test/render/timeline_animation_engine_spec.ts_0_4549 | /**
* @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.dev/license
*/
import {animate, AnimationMetadata, style} from '@angular/animations';
import {
AnimationStyleNormalizer,
NoopAnimationStyleNormalizer,
} from '../../src/dsl/style_normalization/animation_style_normalizer';
import {AnimationDriver} from '../../src/render/animation_driver';
import {getBodyNode} from '../../src/render/shared';
import {TimelineAnimationEngine} from '../../src/render/timeline_animation_engine';
import {MockAnimationDriver, MockAnimationPlayer} from '../../testing/src/mock_animation_driver';
(function () {
const defaultDriver = new MockAnimationDriver();
function makeEngine(body: any, driver?: AnimationDriver, normalizer?: AnimationStyleNormalizer) {
return new TimelineAnimationEngine(
body,
driver || defaultDriver,
normalizer || new NoopAnimationStyleNormalizer(),
);
}
// these tests are only meant to be run within the DOM
if (isNode) return;
describe('TimelineAnimationEngine', () => {
let element: any;
beforeEach(() => {
MockAnimationDriver.log = [];
element = document.createElement('div');
document.body.appendChild(element);
});
afterEach(() => element.remove());
it('should animate a timeline', () => {
const engine = makeEngine(getBodyNode());
const steps = [style({height: 100}), animate(1000, style({height: 0}))];
expect(MockAnimationDriver.log.length).toEqual(0);
invokeAnimation(engine, element, steps);
expect(MockAnimationDriver.log.length).toEqual(1);
});
it('should not destroy timeline-based animations after they have finished', () => {
const engine = makeEngine(getBodyNode());
const log: string[] = [];
function capture(value: string) {
return () => {
log.push(value);
};
}
const steps = [style({height: 0}), animate(1000, style({height: 500}))];
const player = invokeAnimation(engine, element, steps);
player.onDone(capture('done'));
player.onDestroy(capture('destroy'));
expect(log).toEqual([]);
player.finish();
expect(log).toEqual(['done']);
player.destroy();
expect(log).toEqual(['done', 'destroy']);
});
it('should normalize the style values that are animateTransitioned within an a timeline animation', () => {
const engine = makeEngine(getBodyNode(), defaultDriver, new SuffixNormalizer('-normalized'));
const steps = [style({width: '333px'}), animate(1000, style({width: '999px'}))];
const player = invokeAnimation(engine, element, steps) as MockAnimationPlayer;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['width-normalized', '333px-normalized'],
['offset', 0],
]),
new Map<string, string | number>([
['width-normalized', '999px-normalized'],
['offset', 1],
]),
]);
});
it('should normalize `*` values', () => {
const driver = new SuperMockDriver();
const engine = makeEngine(getBodyNode(), driver);
const steps = [style({width: '*'}), animate(1000, style({width: '999px'}))];
const player = invokeAnimation(engine, element, steps) as MockAnimationPlayer;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['width', '*star*'],
['offset', 0],
]),
new Map<string, string | number>([
['width', '999px'],
['offset', 1],
]),
]);
});
});
})();
function invokeAnimation(
engine: TimelineAnimationEngine,
element: any,
steps: AnimationMetadata | AnimationMetadata[],
id: string = 'id',
) {
engine.register(id, steps);
return engine.create(id, element);
}
class SuffixNormalizer extends AnimationStyleNormalizer {
constructor(private _suffix: string) {
super();
}
override normalizePropertyName(propertyName: string, errors: Error[]): string {
return propertyName + this._suffix;
}
override normalizeStyleValue(
userProvidedProperty: string,
normalizedProperty: string,
value: string | number,
errors: Error[],
): string {
return value + this._suffix;
}
}
class SuperMockDriver extends MockAnimationDriver {
override computeStyle(element: any, prop: string, defaultValue?: string): string {
return '*star*';
}
}
| {
"end_byte": 4549,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/render/timeline_animation_engine_spec.ts"
} |
angular/packages/animations/browser/test/render/transition_animation_engine_spec.ts_0_7690 | /**
* @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.dev/license
*/
import {
animate,
AnimationEvent,
AnimationMetadata,
AnimationTriggerMetadata,
NoopAnimationPlayer,
state,
style,
transition,
trigger,
} from '@angular/animations';
import {TriggerAst} from '../../src/dsl/animation_ast';
import {buildAnimationAst} from '../../src/dsl/animation_ast_builder';
import {buildTrigger} from '../../src/dsl/animation_trigger';
import {
AnimationStyleNormalizer,
NoopAnimationStyleNormalizer,
} from '../../src/dsl/style_normalization/animation_style_normalizer';
import {getBodyNode} from '../../src/render/shared';
import {
TransitionAnimationEngine,
TransitionAnimationPlayer,
} from '../../src/render/transition_animation_engine';
import {MockAnimationDriver, MockAnimationPlayer} from '../../testing/src/mock_animation_driver';
const DEFAULT_NAMESPACE_ID = 'id';
(function () {
const driver = new MockAnimationDriver();
// these tests are only meant to be run within the DOM
if (isNode) return;
describe('TransitionAnimationEngine', () => {
let element: any;
beforeEach(() => {
MockAnimationDriver.log = [];
element = document.createElement('div');
document.body.appendChild(element);
});
afterEach(() => {
element.remove();
});
function makeEngine(normalizer?: AnimationStyleNormalizer) {
const engine = new TransitionAnimationEngine(
getBodyNode(),
driver,
normalizer || new NoopAnimationStyleNormalizer(),
);
engine.createNamespace(DEFAULT_NAMESPACE_ID, element);
return engine;
}
describe('trigger registration', () => {
it('should ignore and not throw an error if the same trigger is registered twice', () => {
// TODO (matsko): ask why this is avoided
const engine = makeEngine();
registerTrigger(element, engine, trigger('trig', []));
expect(() => {
registerTrigger(element, engine, trigger('trig', []));
}).not.toThrow();
});
});
describe('property setting', () => {
it('should invoke a transition based on a property change', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, 'myTrigger', 'value');
engine.flush();
expect(engine.players.length).toEqual(1);
const player = MockAnimationDriver.log.pop() as MockAnimationPlayer;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['height', '0px'],
['offset', 0],
]),
new Map<string, string | number>([
['height', '100px'],
['offset', 1],
]),
]);
});
it('should not queue an animation if the property value has not changed at all', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
registerTrigger(element, engine, trig);
engine.flush();
expect(engine.players.length).toEqual(0);
setProperty(element, engine, 'myTrigger', 'abc');
engine.flush();
expect(engine.players.length).toEqual(1);
setProperty(element, engine, 'myTrigger', 'abc');
engine.flush();
expect(engine.players.length).toEqual(1);
});
it('should throw an error if an animation property without a matching trigger is changed', () => {
const engine = makeEngine();
expect(() => {
setProperty(element, engine, 'myTrigger', 'no');
}).toThrowError(/The provided animation trigger "myTrigger" has not been registered!/);
});
});
describe('removal operations', () => {
it("should cleanup all inner state that's tied to an element once removed", () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition(':leave', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, 'myTrigger', 'value');
engine.flush();
expect(engine.statesByElement.has(element)).toBe(
true,
'Expected element data to be defined.',
);
expect(engine.playersByElement.has(element)).toBe(
true,
'Expected element data to be defined.',
);
engine.destroy(DEFAULT_NAMESPACE_ID, null);
engine.removeNode(DEFAULT_NAMESPACE_ID, element, true);
engine.flush();
engine.players[0].finish();
expect(engine.statesByElement.has(element)).toBe(
false,
'Expected element data to be undefined.',
);
expect(engine.playersByElement.has(element)).toBe(
false,
'Expected element data to be undefined.',
);
});
it('should create and recreate a namespace for a host element with the same component source', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition('* => *', animate(1234, style({color: 'red'}))),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, 'myTrigger', 'value');
engine.flush();
expect(
((engine.players[0] as TransitionAnimationPlayer).getRealPlayer() as MockAnimationPlayer)
.duration,
).toEqual(1234);
engine.destroy(DEFAULT_NAMESPACE_ID, null);
registerTrigger(element, engine, trig);
setProperty(element, engine, 'myTrigger', 'value2');
engine.flush();
expect(
((engine.players[0] as TransitionAnimationPlayer).getRealPlayer() as MockAnimationPlayer)
.duration,
).toEqual(1234);
});
it('should clear child node data when a parent node with leave transition is removed', () => {
const engine = makeEngine();
const child = document.createElement('div');
const parentTrigger = trigger('parent', [
transition(':leave', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
const childTrigger = trigger('child', [
transition(':enter', [style({opacity: '0'}), animate(1000, style({opacity: '1'}))]),
]);
registerTrigger(element, engine, parentTrigger);
registerTrigger(child, engine, childTrigger);
element.appendChild(child);
engine.insertNode(DEFAULT_NAMESPACE_ID, child, element, true);
setProperty(element, engine, 'parent', 'value');
setProperty(child, engine, 'child', 'visible');
engine.flush();
expect(engine.statesByElement.has(element)).toBe(
true,
'Expected parent data to be defined.',
);
expect(engine.statesByElement.has(child)).toBe(true, 'Expected child data to be defined.');
engine.removeNode(DEFAULT_NAMESPACE_ID, element, true);
engine.flush();
engine.players[0].finish();
expect(engine.statesByElement.has(element)).toBe(
false,
'Expected parent data to be cleared.',
);
expect(engine.statesByElement.has(child)).toBe(false, 'Expected child data to be cleared.');
});
}); | {
"end_byte": 7690,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/render/transition_animation_engine_spec.ts"
} |
angular/packages/animations/browser/test/render/transition_animation_engine_spec.ts_7696_14096 | describe('event listeners', () => {
it('should listen to the onStart operation for the animation', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
let count = 0;
registerTrigger(element, engine, trig);
listen(element, engine, 'myTrigger', 'start', () => count++);
setProperty(element, engine, 'myTrigger', 'value');
expect(count).toEqual(0);
engine.flush();
expect(count).toEqual(1);
});
it('should listen to the onDone operation for the animation', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
let count = 0;
registerTrigger(element, engine, trig);
listen(element, engine, 'myTrigger', 'done', () => count++);
setProperty(element, engine, 'myTrigger', 'value');
expect(count).toEqual(0);
engine.flush();
expect(count).toEqual(0);
engine.players[0].finish();
expect(count).toEqual(1);
});
it("should throw an error when an event is listened to that isn't supported", () => {
const engine = makeEngine();
const trig = trigger('myTrigger', []);
registerTrigger(element, engine, trig);
expect(() => {
listen(element, engine, 'myTrigger', 'explode', () => {});
}).toThrowError(
/The provided animation trigger event "explode" for the animation trigger "myTrigger" is not supported!/,
);
});
it("should throw an error when an event is listened for a trigger that doesn't exist", () => {
const engine = makeEngine();
expect(() => {
listen(element, engine, 'myTrigger', 'explode', () => {});
}).toThrowError(
/Unable to listen on the animation trigger event "explode" because the animation trigger "myTrigger" doesn\'t exist!/,
);
});
it('should throw an error when an undefined event is listened for', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', []);
registerTrigger(element, engine, trig);
expect(() => {
listen(element, engine, 'myTrigger', '', () => {});
}).toThrowError(
/Unable to listen on the animation trigger "myTrigger" because the provided event is undefined!/,
);
});
it('should retain event listeners and call them for successive animation state changes', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
registerTrigger(element, engine, trig);
let count = 0;
listen(element, engine, 'myTrigger', 'start', () => count++);
setProperty(element, engine, 'myTrigger', '123');
engine.flush();
expect(count).toEqual(1);
setProperty(element, engine, 'myTrigger', '456');
engine.flush();
expect(count).toEqual(2);
});
it('should only fire event listener changes for when the corresponding trigger changes state', () => {
const engine = makeEngine();
const trig1 = trigger('myTrigger1', [
transition('* => 123', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
registerTrigger(element, engine, trig1);
const trig2 = trigger('myTrigger2', [
transition('* => 123', [style({width: '0px'}), animate(1000, style({width: '100px'}))]),
]);
registerTrigger(element, engine, trig2);
let count = 0;
listen(element, engine, 'myTrigger1', 'start', () => count++);
setProperty(element, engine, 'myTrigger1', '123');
engine.flush();
expect(count).toEqual(1);
setProperty(element, engine, 'myTrigger2', '123');
engine.flush();
expect(count).toEqual(1);
});
it('should allow a listener to be deregistered, but only after a flush occurs', () => {
const engine = makeEngine();
const trig = trigger('myTrigger', [
transition('* => 123', [style({height: '0px'}), animate(1000, style({height: '100px'}))]),
]);
registerTrigger(element, engine, trig);
let count = 0;
const deregisterFn = listen(element, engine, 'myTrigger', 'start', () => count++);
setProperty(element, engine, 'myTrigger', '123');
engine.flush();
expect(count).toEqual(1);
deregisterFn();
engine.flush();
setProperty(element, engine, 'myTrigger', '456');
engine.flush();
expect(count).toEqual(1);
});
it('should trigger a listener callback with an AnimationEvent argument', () => {
const engine = makeEngine();
registerTrigger(
element,
engine,
trigger('myTrigger', [
transition('* => *', [style({height: '0px'}), animate(1234, style({height: '100px'}))]),
]),
);
// we do this so that the next transition has a starting value that isn't null
setProperty(element, engine, 'myTrigger', '123');
engine.flush();
let capture: AnimationEvent = null!;
listen(element, engine, 'myTrigger', 'start', (e) => (capture = e));
listen(element, engine, 'myTrigger', 'done', (e) => (capture = e));
setProperty(element, engine, 'myTrigger', '456');
engine.flush();
delete (capture as any)['_data'];
expect(capture).toEqual({
element,
triggerName: 'myTrigger',
phaseName: 'start',
fromState: '123',
toState: '456',
totalTime: 1234,
disabled: false,
});
capture = null!;
const player = engine.players.pop()!;
player.finish();
delete (capture as any)['_data'];
expect(capture).toEqual({
element,
triggerName: 'myTrigger',
phaseName: 'done',
fromState: '123',
toState: '456',
totalTime: 1234,
disabled: false,
});
});
}); | {
"end_byte": 14096,
"start_byte": 7696,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/render/transition_animation_engine_spec.ts"
} |
angular/packages/animations/browser/test/render/transition_animation_engine_spec.ts_14102_22446 | describe('transition operations', () => {
it('should persist the styles on the element as actual styles once the animation is complete', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('on', style({height: '100px'})),
state('off', style({height: '0px'})),
transition('on => off', animate(9876)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'on');
setProperty(element, engine, trig.name, 'off');
engine.flush();
expect(element.style.height).not.toEqual('0px');
engine.players[0].finish();
expect(element.style.height).toEqual('0px');
});
it('should remove all existing state styling from an element when a follow-up transition occurs on the same trigger', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('a', style({height: '100px'})),
state('b', style({height: '500px'})),
state('c', style({width: '200px'})),
transition('* => *', animate(9876)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'a');
setProperty(element, engine, trig.name, 'b');
engine.flush();
const player1 = engine.players[0];
player1.finish();
expect(element.style.height).toEqual('500px');
setProperty(element, engine, trig.name, 'c');
engine.flush();
const player2 = engine.players[0];
expect(element.style.height).not.toEqual('500px');
player2.finish();
expect(element.style.width).toEqual('200px');
expect(element.style.height).not.toEqual('500px');
});
it('should allow two animation transitions with different triggers to animate in parallel', () => {
const engine = makeEngine();
const trig1 = trigger('something1', [
state('a', style({width: '100px'})),
state('b', style({width: '200px'})),
transition('* => *', animate(1000)),
]);
const trig2 = trigger('something2', [
state('x', style({height: '500px'})),
state('y', style({height: '1000px'})),
transition('* => *', animate(2000)),
]);
registerTrigger(element, engine, trig1);
registerTrigger(element, engine, trig2);
let doneCount = 0;
function doneCallback() {
doneCount++;
}
setProperty(element, engine, trig1.name, 'a');
setProperty(element, engine, trig1.name, 'b');
setProperty(element, engine, trig2.name, 'x');
setProperty(element, engine, trig2.name, 'y');
engine.flush();
const player1 = engine.players[0]!;
player1.onDone(doneCallback);
expect(doneCount).toEqual(0);
const player2 = engine.players[1]!;
player2.onDone(doneCallback);
expect(doneCount).toEqual(0);
player1.finish();
expect(doneCount).toEqual(1);
player2.finish();
expect(doneCount).toEqual(2);
expect(element.style.width).toEqual('200px');
expect(element.style.height).toEqual('1000px');
});
it('should cancel a previously running animation when a follow-up transition kicks off on the same trigger', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('x', style({opacity: 0})),
state('y', style({opacity: 0.5})),
state('z', style({opacity: 1})),
transition('* => *', animate(1000)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'x');
setProperty(element, engine, trig.name, 'y');
engine.flush();
expect(parseFloat(element.style.opacity)).not.toEqual(0.5);
const player1 = engine.players[0];
setProperty(element, engine, trig.name, 'z');
engine.flush();
const player2 = engine.players[0];
expect(parseFloat(element.style.opacity)).not.toEqual(0.5);
player2.finish();
expect(parseFloat(element.style.opacity)).toEqual(1);
player1.finish();
expect(parseFloat(element.style.opacity)).toEqual(1);
});
it('should pass in the previously running players into the follow-up transition player when cancelled', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('x', style({opacity: 0})),
state('y', style({opacity: 0.5})),
state('z', style({opacity: 1})),
transition('* => *', animate(1000)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'x');
setProperty(element, engine, trig.name, 'y');
engine.flush();
const player1 = MockAnimationDriver.log.pop()! as MockAnimationPlayer;
player1.setPosition(0.5);
setProperty(element, engine, trig.name, 'z');
engine.flush();
const player2 = MockAnimationDriver.log.pop()! as MockAnimationPlayer;
expect(player2.previousPlayers).toEqual([player1]);
player2.finish();
setProperty(element, engine, trig.name, 'x');
engine.flush();
const player3 = MockAnimationDriver.log.pop()! as MockAnimationPlayer;
expect(player3.previousPlayers).toEqual([]);
});
it('should cancel all existing players if a removal animation is set to occur', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('m', style({opacity: 0})),
state('n', style({opacity: 1})),
transition('* => *', animate(1000)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'm');
setProperty(element, engine, trig.name, 'n');
engine.flush();
let doneCount = 0;
function doneCallback() {
doneCount++;
}
const player1 = engine.players[0];
player1.onDone(doneCallback);
expect(doneCount).toEqual(0);
setProperty(element, engine, trig.name, 'void');
engine.flush();
expect(doneCount).toEqual(1);
});
it('should only persist styles that exist in the final state styles and not the last keyframe', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('0', style({width: '0px'})),
state('1', style({width: '100px'})),
transition('* => *', [animate(1000, style({height: '200px'}))]),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, '0');
setProperty(element, engine, trig.name, '1');
engine.flush();
const player = engine.players[0]!;
expect(element.style.width).not.toEqual('100px');
player.finish();
expect(element.style.height).not.toEqual('200px');
expect(element.style.width).toEqual('100px');
});
it('should default to using styling from the `*` state if a matching state is not found', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('a', style({opacity: 0})),
state('*', style({opacity: 0.5})),
transition('* => *', animate(1000)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'a');
setProperty(element, engine, trig.name, 'z');
engine.flush();
engine.players[0].finish();
expect(parseFloat(element.style.opacity)).toEqual(0.5);
});
it('should treat `void` as `void`', () => {
const engine = makeEngine();
const trig = trigger('something', [
state('a', style({opacity: 0})),
state('void', style({opacity: 0.8})),
transition('* => *', animate(1000)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'a');
setProperty(element, engine, trig.name, 'void');
engine.flush();
engine.players[0].finish();
expect(parseFloat(element.style.opacity)).toEqual(0.8);
});
}); | {
"end_byte": 22446,
"start_byte": 14102,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/render/transition_animation_engine_spec.ts"
} |
angular/packages/animations/browser/test/render/transition_animation_engine_spec.ts_22452_28478 | describe('style normalizer', () => {
it('should normalize the style values that are animateTransitioned within an a transition animation', () => {
const engine = makeEngine(new SuffixNormalizer('-normalized'));
const trig = trigger('something', [
state('on', style({height: 100})),
state('off', style({height: 0})),
transition('on => off', animate(9876)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'on');
setProperty(element, engine, trig.name, 'off');
engine.flush();
const player = MockAnimationDriver.log.pop() as MockAnimationPlayer;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['height-normalized', '100-normalized'],
['offset', 0],
]),
new Map<string, string | number>([
['height-normalized', '0-normalized'],
['offset', 1],
]),
]);
});
it('should throw an error when normalization fails within a transition animation', () => {
const engine = makeEngine(new ExactCssValueNormalizer({left: '100px'}));
const trig = trigger('something', [
state('a', style({left: '0px', width: '200px'})),
state('b', style({left: '100px', width: '100px'})),
transition('a => b', animate(9876)),
]);
registerTrigger(element, engine, trig);
setProperty(element, engine, trig.name, 'a');
setProperty(element, engine, trig.name, 'b');
let errorMessage = '';
try {
engine.flush();
} catch (e) {
errorMessage = (e as Error).toString();
}
expect(errorMessage).toMatch(/Unable to animate due to the following errors:/);
expect(errorMessage).toMatch(/- The CSS property `left` is not allowed to be `0px`/);
expect(errorMessage).toMatch(/- The CSS property `width` is not allowed/);
});
});
describe('view operations', () => {
it('should perform insert operations immediately ', () => {
const engine = makeEngine();
const child1 = document.createElement('div');
const child2 = document.createElement('div');
element.appendChild(child1);
element.appendChild(child2);
element.appendChild(child1);
engine.insertNode(DEFAULT_NAMESPACE_ID, child1, element, true);
element.appendChild(child2);
engine.insertNode(DEFAULT_NAMESPACE_ID, child2, element, true);
expect(element.contains(child1)).toBe(true);
expect(element.contains(child2)).toBe(true);
});
it('should not throw an error if a missing namespace is used', () => {
const engine = makeEngine();
const ID = 'foo';
const TRIGGER = 'fooTrigger';
expect(() => {
engine.trigger(ID, element, TRIGGER, 'something');
}).not.toThrow();
});
it('should still apply state-styling to an element even if it is not yet inserted into the DOM', () => {
const engine = makeEngine();
const orphanElement = document.createElement('div');
orphanElement.classList.add('orphan');
registerTrigger(
orphanElement,
engine,
trigger('trig', [
state('go', style({opacity: 0.5})),
transition('* => go', animate(1000)),
]),
);
setProperty(orphanElement, engine, 'trig', 'go');
engine.flush();
expect(engine.players.length).toEqual(0);
expect(orphanElement.style.opacity).toEqual('0.5');
});
});
});
})();
class SuffixNormalizer extends AnimationStyleNormalizer {
constructor(private _suffix: string) {
super();
}
override normalizePropertyName(propertyName: string, errors: Error[]): string {
return propertyName + this._suffix;
}
override normalizeStyleValue(
userProvidedProperty: string,
normalizedProperty: string,
value: string | number,
errors: Error[],
): string {
return value + this._suffix;
}
}
class ExactCssValueNormalizer extends AnimationStyleNormalizer {
constructor(private _allowedValues: {[propName: string]: any}) {
super();
}
override normalizePropertyName(propertyName: string, errors: Error[]): string {
if (!this._allowedValues[propertyName]) {
errors.push(new Error(`The CSS property \`${propertyName}\` is not allowed`));
}
return propertyName;
}
override normalizeStyleValue(
userProvidedProperty: string,
normalizedProperty: string,
value: string | number,
errors: Error[],
): string {
const expectedValue = this._allowedValues[userProvidedProperty];
if (expectedValue != value) {
errors.push(
new Error(`The CSS property \`${userProvidedProperty}\` is not allowed to be \`${value}\``),
);
}
return expectedValue;
}
}
function registerTrigger(
element: any,
engine: TransitionAnimationEngine,
metadata: AnimationTriggerMetadata,
id: string = DEFAULT_NAMESPACE_ID,
) {
const errors: Error[] = [];
const warnings: string[] = [];
const driver = new MockAnimationDriver();
const name = metadata.name;
const ast = buildAnimationAst(
driver,
metadata as AnimationMetadata,
errors,
warnings,
) as TriggerAst;
if (errors.length) {
}
const trigger = buildTrigger(name, ast, new NoopAnimationStyleNormalizer());
engine.register(id, element);
engine.registerTrigger(id, name, trigger);
}
function setProperty(
element: any,
engine: TransitionAnimationEngine,
property: string,
value: any,
id: string = DEFAULT_NAMESPACE_ID,
) {
engine.trigger(id, element, property, value);
}
function listen(
element: any,
engine: TransitionAnimationEngine,
eventName: string,
phaseName: string,
callback: (event: any) => any,
id: string = DEFAULT_NAMESPACE_ID,
) {
return engine.listen(id, element, eventName, phaseName, callback);
} | {
"end_byte": 28478,
"start_byte": 22452,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/render/transition_animation_engine_spec.ts"
} |
angular/packages/animations/browser/test/render/web_animations/web_animations_player_spec.ts_0_5145 | /**
* @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.dev/license
*/
import {WebAnimationsPlayer} from '../../../src/render/web_animations/web_animations_player';
describe('WebAnimationsPlayer tests', () => {
let element: any;
let innerPlayer: MockDomAnimation | null = null;
beforeEach(() => {
element = {};
element['animate'] = () => {
return (innerPlayer = new MockDomAnimation());
};
});
it('should automatically pause the player when created and initialized', () => {
const keyframes = [
new Map<string, string | number>([
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
];
const player = new WebAnimationsPlayer(element, keyframes, {duration: 1000});
player.init();
const p = innerPlayer!;
expect(p.log).toEqual(['pause']);
player.play();
expect(p.log).toEqual(['pause', 'play']);
});
it('should not pause the player if created and started before initialized', () => {
const keyframes = [
new Map<string, string | number>([
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
];
const player = new WebAnimationsPlayer(element, keyframes, {duration: 1000});
player.play();
const p = innerPlayer!;
expect(p.log).toEqual(['play']);
});
it('should fire start/done callbacks manually when called directly', () => {
const log: string[] = [];
const player = new WebAnimationsPlayer(element, [], {duration: 1000});
player.onStart(() => log.push('started'));
player.onDone(() => log.push('done'));
(player as any).triggerCallback('start');
expect(log).toEqual(['started']);
player.play();
expect(log).toEqual(['started']);
(player as any).triggerCallback('done');
expect(log).toEqual(['started', 'done']);
player.finish();
expect(log).toEqual(['started', 'done']);
});
it('should allow setting position before animation is started', () => {
const player = new WebAnimationsPlayer(element, [], {duration: 1000});
player.setPosition(0.5);
const p = innerPlayer!;
expect(p.log).toEqual(['pause']);
expect(p.currentTime).toEqual(500);
});
it('should continue playing animations from setPosition', () => {
const player = new WebAnimationsPlayer(element, [], {duration: 1000});
player.play();
const p = innerPlayer!;
expect(p.log).toEqual(['play']);
player.setPosition(0.5);
expect(p.currentTime).toEqual(500);
expect(p.log).toEqual(['play']);
});
});
class MockDomAnimation implements Animation {
log: string[] = [];
cancel(): void {
this.log.push('cancel');
}
play(): void {
this.log.push('play');
}
pause(): void {
this.log.push('pause');
}
finish(): void {
this.log.push('finish');
}
currentTime: number = 0;
// Other properties to ensure conformance to interface
effect: AnimationEffect | null = null;
finished: Promise<Animation> = Promise.resolve({} as any);
id: string = '';
oncancel: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null = null;
onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null = null;
onremove: ((this: Animation, ev: Event) => any) | null = null;
pending: boolean = false;
playState: AnimationPlayState = 'running';
playbackRate: number = 0;
ready: Promise<Animation> = Promise.resolve({} as any);
replaceState: AnimationReplaceState = 'active';
startTime: number | null = null;
timeline: AnimationTimeline | null = null;
commitStyles(): void {
throw new Error('Method not implemented.');
}
persist(): void {
throw new Error('Method not implemented.');
}
reverse(): void {
throw new Error('Method not implemented.');
}
updatePlaybackRate(playbackRate: number): void {
throw new Error('Method not implemented.');
}
removeEventListener<K extends keyof AnimationEventMap>(
type: K,
listener: (this: Animation, ev: AnimationEventMap[K]) => any,
options?: boolean | EventListenerOptions | undefined,
): void;
removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions | undefined,
): void;
removeEventListener(type: unknown, listener: unknown, options?: unknown): void {
throw new Error('Method not implemented.');
}
dispatchEvent(event: Event): boolean;
dispatchEvent(event: Event): boolean;
dispatchEvent(event: unknown): boolean {
throw new Error('Method not implemented.');
}
removeAllListeners?(eventName?: string | undefined): void {
throw new Error('Method not implemented.');
}
eventListeners?(eventName?: string | undefined): EventListenerOrEventListenerObject[] {
throw new Error('Method not implemented.');
}
addEventListener(eventName: string, handler: (event: any) => any): any {}
}
| {
"end_byte": 5145,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/render/web_animations/web_animations_player_spec.ts"
} |
angular/packages/animations/browser/test/render/web_animations/web_animations_driver_spec.ts_0_1637 | /**
* @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.dev/license
*/
import {WebAnimationsDriver} from '../../../src/render/web_animations/web_animations_driver';
import {WebAnimationsPlayer} from '../../../src/render/web_animations/web_animations_player';
describe('WebAnimationsDriver', () => {
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
describe('when web-animations are supported natively', () => {
it('should return an instance of a WebAnimationsPlayer if scrubbing is not requested', () => {
const element = createElement();
const driver = makeDriver();
const player = driver.animate(element, [], 1000, 1000, '', []);
expect(player instanceof WebAnimationsPlayer).toBeTruthy();
});
});
describe('when animation is inside a shadow DOM', () => {
it('should consider an element inside the shadow DOM to be contained by the document body', () => {
const hostElement = createElement();
const shadowRoot = hostElement.attachShadow({mode: 'open'});
const elementToAnimate = createElement();
shadowRoot.appendChild(elementToAnimate);
document.body.appendChild(hostElement);
const animator = new WebAnimationsDriver();
expect(animator.containsElement(document.body, elementToAnimate)).toBeTrue();
});
});
});
function makeDriver() {
return new WebAnimationsDriver();
}
function createElement() {
return document.createElement('div');
}
| {
"end_byte": 1637,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/render/web_animations/web_animations_driver_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_ast_builder_spec.ts_0_1889 | /**
* @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.dev/license
*/
import {AnimationMetadata, AnimationMetadataType} from '@angular/animations';
import {buildAnimationAst} from '../../src/dsl/animation_ast_builder';
import {MockAnimationDriver} from '../../testing';
describe('buildAnimationAst', () => {
it('should build the AST without any errors and warnings', () => {
const driver = new MockAnimationDriver();
const errors: Error[] = [];
const warnings: string[] = [];
const animationAst = buildAnimationAst(
driver,
<AnimationMetadata>{
animation: [
{
styles: {
offset: null,
styles: {backgroundColor: '#000'},
type: AnimationMetadataType.Style,
},
timings: {delay: 0, duration: 1000, easing: 'ease-in-out'},
type: AnimationMetadataType.Animate,
},
],
options: null,
selector: 'body',
type: AnimationMetadataType.Query,
},
errors,
warnings,
);
expect(errors).toEqual([]);
expect(warnings).toEqual([]);
expect(animationAst).toEqual(<ReturnType<typeof buildAnimationAst>>{
type: 11,
selector: 'body',
limit: 0,
optional: false,
includeSelf: false,
animation: {
type: 4,
timings: {delay: 0, duration: 1000, easing: 'ease-in-out'},
style: {
type: 6,
styles: [new Map([['backgroundColor', '#000']])],
easing: null,
offset: null,
containsDynamicStyles: false,
options: null,
isEmptyStep: false,
},
options: null,
},
originalSelector: 'body',
options: {},
});
});
});
| {
"end_byte": 1889,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_ast_builder_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_0_1460 | /**
* @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.dev/license
*/
import {
animate,
animation,
AnimationMetadata,
AnimationMetadataType,
AnimationOptions,
AUTO_STYLE,
group,
keyframes,
query,
sequence,
state,
style,
transition,
trigger,
useAnimation,
ɵStyleDataMap,
} from '@angular/animations';
import {Animation} from '../../src/dsl/animation';
import {buildAnimationAst} from '../../src/dsl/animation_ast_builder';
import {AnimationTimelineInstruction} from '../../src/dsl/animation_timeline_instruction';
import {ElementInstructionMap} from '../../src/dsl/element_instruction_map';
import {MockAnimationDriver} from '../../testing';
function createDiv() {
return document.createElement('div');
}
describe('Animation', () => {
// these tests are only meant to be run within the DOM (for now)
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
let rootElement: any;
let subElement1: any;
let subElement2: any;
beforeEach(() => {
rootElement = createDiv();
subElement1 = createDiv();
subElement2 = createDiv();
document.body.appendChild(rootElement);
rootElement.appendChild(subElement1);
rootElement.appendChild(subElement2);
});
afterEach(() => {
rootElement.remove();
});
| {
"end_byte": 1460,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_1464_9461 | escribe('validation', () => {
it('should throw an error if one or more but not all keyframes() styles contain offsets', () => {
const steps = animate(1000, keyframes([style({opacity: 0}), style({opacity: 1, offset: 1})]));
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/Not all style\(\) steps within the declared keyframes\(\) contain offsets/);
});
it('should throw an error if not all offsets are between 0 and 1', () => {
let steps = animate(
1000,
keyframes([style({opacity: 0, offset: -1}), style({opacity: 1, offset: 1})]),
);
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/Please ensure that all keyframe offsets are between 0 and 1/);
steps = animate(
1000,
keyframes([style({opacity: 0, offset: 0}), style({opacity: 1, offset: 1.1})]),
);
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/Please ensure that all keyframe offsets are between 0 and 1/);
});
it('should throw an error if a smaller offset shows up after a bigger one', () => {
let steps = animate(
1000,
keyframes([style({opacity: 0, offset: 1}), style({opacity: 1, offset: 0})]),
);
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/Please ensure that all keyframe offsets are in order/);
});
it('should throw an error if any styles overlap during parallel animations', () => {
const steps = group([
sequence([
// 0 -> 2000ms
style({opacity: 0}),
animate('500ms', style({opacity: 0.25})),
animate('500ms', style({opacity: 0.5})),
animate('500ms', style({opacity: 0.75})),
animate('500ms', style({opacity: 1})),
]),
animate(
'1s 500ms',
keyframes([
// 0 -> 1500ms
style({width: 0}),
style({opacity: 1, width: 1000}),
]),
),
]);
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(
/The CSS property "opacity" that exists between the times of "0ms" and "2000ms" is also being animated in a parallel animation between the times of "0ms" and "1500ms"/,
);
});
it('should not throw an error if animations overlap in different query levels within different transitions', () => {
const steps = trigger('myAnimation', [
transition(
'a => b',
group([
query('h1', animate('1s', style({opacity: 0}))),
query('h2', animate('1s', style({opacity: 1}))),
]),
),
transition(
'b => a',
group([
query('h1', animate('1s', style({opacity: 0}))),
query('h2', animate('1s', style({opacity: 1}))),
]),
),
]);
expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow();
});
it('should not allow triggers to be defined with a prefixed `@` symbol', () => {
const steps = trigger('@foo', []);
expect(() => validateAndThrowAnimationSequence(steps)).toThrowError(
/animation triggers cannot be prefixed with an `@` sign \(e\.g\. trigger\('@foo', \[...\]\)\)/,
);
});
it('should throw an error if an animation time is invalid', () => {
const steps = [animate('500xs', style({opacity: 1}))];
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/The provided timing value "500xs" is invalid/);
const steps2 = [animate('500ms 500ms 500ms ease-out', style({opacity: 1}))];
expect(() => {
validateAndThrowAnimationSequence(steps2);
}).toThrowError(/The provided timing value "500ms 500ms 500ms ease-out" is invalid/);
});
it('should throw if negative durations are used', () => {
const steps = [animate(-1000, style({opacity: 1}))];
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/Duration values below 0 are not allowed for this animation step/);
const steps2 = [animate('-1s', style({opacity: 1}))];
expect(() => {
validateAndThrowAnimationSequence(steps2);
}).toThrowError(/Duration values below 0 are not allowed for this animation step/);
});
it('should throw if negative delays are used', () => {
const steps = [animate('1s -500ms', style({opacity: 1}))];
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/Delay values below 0 are not allowed for this animation step/);
const steps2 = [animate('1s -0.5s', style({opacity: 1}))];
expect(() => {
validateAndThrowAnimationSequence(steps2);
}).toThrowError(/Delay values below 0 are not allowed for this animation step/);
});
it('should throw if keyframes() is not used inside of animate()', () => {
const steps = [keyframes([])];
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(/keyframes\(\) must be placed inside of a call to animate\(\)/);
const steps2 = [group([keyframes([])])];
expect(() => {
validateAndThrowAnimationSequence(steps2);
}).toThrowError(/keyframes\(\) must be placed inside of a call to animate\(\)/);
});
it('should throw if dynamic style substitutions are used without defaults within state() definitions', () => {
const steps = [
state(
'final',
style({
'width': '{{ one }}px',
'borderRadius': '{{ two }}px {{ three }}px',
}),
),
];
expect(() => {
validateAndThrowAnimationSequence(steps);
}).toThrowError(
/state\("final", ...\) must define default values for all the following style substitutions: one, two, three/,
);
const steps2 = [
state(
'panfinal',
style({
'color': '{{ greyColor }}',
'borderColor': '1px solid {{ greyColor }}',
'backgroundColor': '{{ redColor }}',
}),
{params: {redColor: 'maroon'}},
),
];
expect(() => {
validateAndThrowAnimationSequence(steps2);
}).toThrowError(
/state\("panfinal", ...\) must define default values for all the following style substitutions: greyColor/,
);
});
it('should provide a warning if an invalid CSS property is used in the animation', () => {
const steps = [animate(1000, style({abc: '500px'}))];
expect(getValidationWarningsForAnimationSequence(steps)).toEqual([
'The following provided properties are not recognized: abc',
]);
});
it('should provide a warning if multiple invalid CSS properties are used in the animation', () => {
const steps = [
state(
'state',
style({
'123': '100px',
}),
),
style({abc: '200px'}),
animate(1000, style({xyz: '300px'})),
];
expect(getValidationWarningsForAnimationSequence(steps)).toEqual([
'The following provided properties are not recognized: 123, abc, xyz',
]);
});
it('should allow a vendor-prefixed property to be used in an animation sequence without throwing an error', () => {
const steps = [
style({webkitTransform: 'translateX(0px)'}),
animate(1000, style({webkitTransform: 'translateX(100px)'})),
];
expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow();
});
it('should allow for old CSS properties (like transform) to be auto-prefixed by webkit', () => {
const steps = [
style({transform: 'translateX(-100px)'}),
animate(1000, style({transform: 'translateX(500px)'})),
];
expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow();
});
});
| {
"end_byte": 9461,
"start_byte": 1464,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_9465_13596 | escribe('keyframe building', () => {
describe('style() / animate()', () => {
it('should produce a balanced series of keyframes given a sequence of animate steps', () => {
const steps = [
style({width: 0}),
animate(1000, style({height: 50})),
animate(1000, style({width: 100})),
animate(1000, style({height: 150})),
animate(1000, style({width: 200})),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['height', AUTO_STYLE],
['width', 0],
['offset', 0],
]),
new Map<string, string | number>([
['height', 50],
['width', 0],
['offset', 0.25],
]),
new Map<string, string | number>([
['height', 50],
['width', 100],
['offset', 0.5],
]),
new Map<string, string | number>([
['height', 150],
['width', 100],
['offset', 0.75],
]),
new Map<string, string | number>([
['height', 150],
['width', 200],
['offset', 1],
]),
]);
});
it('should fill in missing starting steps when a starting `style()` value is not used', () => {
const steps = [animate(1000, style({width: 999}))];
const players = invokeAnimationSequence(rootElement, steps);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['width', AUTO_STYLE],
['offset', 0],
]),
new Map<string, string | number>([
['width', 999],
['offset', 1],
]),
]);
});
it('should merge successive style() calls together before an animate() call', () => {
const steps = [
style({width: 0}),
style({height: 0}),
style({width: 200}),
style({opacity: 0}),
animate(1000, style({width: 100, height: 400, opacity: 1})),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['width', 200],
['height', 0],
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['width', 100],
['height', 400],
['opacity', 1],
['offset', 1],
]),
]);
});
it('should not merge in successive style() calls to the previous animate() keyframe', () => {
const steps = [
style({opacity: 0}),
animate(1000, style({opacity: 0.5})),
style({opacity: 0.6}),
animate(1000, style({opacity: 1})),
];
const players = invokeAnimationSequence(rootElement, steps);
const keyframes = humanizeOffsets(players[0].keyframes, 4);
expect(keyframes).toEqual([
new Map<string, string | number>([
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0.5],
['offset', 0.4998],
]),
new Map<string, string | number>([
['opacity', 0.6],
['offset', 0.5002],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
});
it('should support an easing value that uses cubic-bezier(...)', () => {
const steps = [
style({opacity: 0}),
animate('1s cubic-bezier(.29, .55 ,.53 ,1.53)', style({opacity: 1})),
];
const player = invokeAnimationSequence(rootElement, steps)[0];
const firstKeyframe = player.keyframes[0];
const firstKeyframeEasing = firstKeyframe.get('easing') as string;
expect(firstKeyframeEasing.replace(/\s+/g, '')).toEqual('cubic-bezier(.29,.55,.53,1.53)');
});
});
| {
"end_byte": 13596,
"start_byte": 9465,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_13602_18207 | escribe('sequence()', () => {
it('should not produce extra timelines when multiple sequences are used within each other', () => {
const steps = [
style({width: 0}),
animate(1000, style({width: 100})),
sequence([
animate(1000, style({width: 200})),
sequence([animate(1000, style({width: 300}))]),
]),
animate(1000, style({width: 400})),
sequence([animate(1000, style({width: 500}))]),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
const player = players[0];
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['width', 0],
['offset', 0],
]),
new Map<string, string | number>([
['width', 100],
['offset', 0.2],
]),
new Map<string, string | number>([
['width', 200],
['offset', 0.4],
]),
new Map<string, string | number>([
['width', 300],
['offset', 0.6],
]),
new Map<string, string | number>([
['width', 400],
['offset', 0.8],
]),
new Map<string, string | number>([
['width', 500],
['offset', 1],
]),
]);
});
it('should create a new timeline after a sequence if group() or keyframe() commands are used within', () => {
const steps = [
style({width: 100, height: 100}),
animate(1000, style({width: 150, height: 150})),
sequence([
group([animate(1000, style({height: 200}))]),
animate(1000, keyframes([style({width: 180}), style({width: 200})])),
]),
animate(1000, style({width: 500, height: 500})),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(4);
const finalPlayer = players[players.length - 1];
expect(finalPlayer.keyframes).toEqual([
new Map<string, string | number>([
['width', 200],
['height', 200],
['offset', 0],
]),
new Map<string, string | number>([
['width', 500],
['height', 500],
['offset', 1],
]),
]);
});
it('should push the start of a sequence if a delay option is provided', () => {
const steps = [
style({width: '0px'}),
animate(1000, style({width: '100px'})),
sequence([animate(1000, style({width: '200px'}))], {delay: 500}),
];
const players = invokeAnimationSequence(rootElement, steps);
const finalPlayer = players[players.length - 1];
expect(finalPlayer.keyframes).toEqual([
new Map<string, string | number>([
['width', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['width', '200px'],
['offset', 1],
]),
]);
expect(finalPlayer.delay).toEqual(1500);
});
it('should allow a float-based delay value to be used', () => {
let steps: any[] = [animate('.75s 0.75s', style({width: '300px'}))];
let players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
let p1 = players.pop()!;
expect(p1.duration).toEqual(1500);
expect(p1.keyframes).toEqual([
new Map<string, string | number>([
['width', '*'],
['offset', 0],
]),
new Map<string, string | number>([
['width', '*'],
['offset', 0.5],
]),
new Map<string, string | number>([
['width', '300px'],
['offset', 1],
]),
]);
steps = [style({width: '100px'}), animate('.5s .5s', style({width: '200px'}))];
players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
p1 = players.pop()!;
expect(p1.duration).toEqual(1000);
expect(p1.keyframes).toEqual([
new Map<string, string | number>([
['width', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['width', '100px'],
['offset', 0.5],
]),
new Map<string, string | number>([
['width', '200px'],
['offset', 1],
]),
]);
});
});
| {
"end_byte": 18207,
"start_byte": 13602,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_18213_23808 | escribe('substitutions', () => {
it('should allow params to be substituted even if they are not defaulted in a reusable animation', () => {
const myAnimation = animation([
style({left: '{{ start }}'}),
animate(1000, style({left: '{{ end }}'})),
]);
const steps = [useAnimation(myAnimation, {params: {start: '0px', end: '100px'}})];
const players = invokeAnimationSequence(rootElement, steps, {});
expect(players.length).toEqual(1);
const player = players[0];
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['left', '0px'],
['offset', 0],
]),
new Map<string, string | number>([
['left', '100px'],
['offset', 1],
]),
]);
});
it('should substitute in timing values', () => {
function makeAnimation(exp: string, options: {[key: string]: any}) {
const steps = [style({opacity: 0}), animate(exp, style({opacity: 1}))];
return invokeAnimationSequence(rootElement, steps, options);
}
let players = makeAnimation('{{ duration }}', buildParams({duration: '1234ms'}));
expect(players[0].duration).toEqual(1234);
players = makeAnimation('{{ duration }}', buildParams({duration: '9s 2s'}));
expect(players[0].duration).toEqual(11000);
players = makeAnimation('{{ duration }} 1s', buildParams({duration: '1.5s'}));
expect(players[0].duration).toEqual(2500);
players = makeAnimation(
'{{ duration }} {{ delay }}',
buildParams({duration: '1s', delay: '2s'}),
);
expect(players[0].duration).toEqual(3000);
});
it('should allow multiple substitutions to occur within the same style value', () => {
const steps = [
style({borderRadius: '100px 100px'}),
animate(1000, style({borderRadius: '{{ one }}px {{ two }}'})),
];
const players = invokeAnimationSequence(
rootElement,
steps,
buildParams({one: '200', two: '400px'}),
);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['borderRadius', '100px 100px'],
]),
new Map<string, string | number>([
['offset', 1],
['borderRadius', '200px 400px'],
]),
]);
});
it('should substitute in values that are defined as parameters for inner areas of a sequence', () => {
const steps = sequence(
[
sequence(
[
sequence(
[style({height: '{{ x0 }}px'}), animate(1000, style({height: '{{ x2 }}px'}))],
buildParams({x2: '{{ x1 }}3'}),
),
],
buildParams({x1: '{{ x0 }}2'}),
),
],
buildParams({x0: '1'}),
);
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
const [player] = players;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['height', '1px'],
]),
new Map<string, string | number>([
['offset', 1],
['height', '123px'],
]),
]);
});
it('should substitute in values that are defined as parameters for reusable animations', () => {
const anim = animation([
style({height: '{{ start }}'}),
animate(1000, style({height: '{{ end }}'})),
]);
const steps = sequence(
[
sequence(
[useAnimation(anim, buildParams({start: '{{ a }}', end: '{{ b }}'}))],
buildParams({a: '100px', b: '200px'}),
),
],
buildParams({a: '0px'}),
);
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
const [player] = players;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['height', '100px'],
]),
new Map<string, string | number>([
['offset', 1],
['height', '200px'],
]),
]);
});
it('should throw an error when an input variable is not provided when invoked and is not a default value', () => {
expect(() =>
invokeAnimationSequence(rootElement, [style({color: '{{ color }}'})]),
).toThrowError(/Please provide a value for the animation param color/);
expect(() =>
invokeAnimationSequence(
rootElement,
[style({color: '{{ start }}'}), animate('{{ time }}', style({color: '{{ end }}'}))],
buildParams({start: 'blue', end: 'red'}),
),
).toThrowError(/Please provide a value for the animation param time/);
expect(() =>
invokeAnimationSequence(
rootElement,
[style({color: '{{ color }}'})],
buildParams({color: undefined}),
),
).toThrowError(/Please provide a value for the animation param color/);
expect(() =>
invokeAnimationSequence(
rootElement,
[style({color: '{{ color }}'})],
buildParams({color: null}),
),
).toThrowError(/Please provide a value for the animation param color/);
});
});
| {
"end_byte": 23808,
"start_byte": 18213,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_23814_31419 | escribe('keyframes()', () => {
it('should produce a sub timeline when `keyframes()` is used within a sequence', () => {
const steps = [
animate(1000, style({opacity: 0.5})),
animate(1000, style({opacity: 1})),
animate(1000, keyframes([style({height: 0}), style({height: 100}), style({height: 50})])),
animate(1000, style({height: 0, opacity: 0})),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(3);
const player0 = players[0];
expect(player0.delay).toEqual(0);
expect(player0.keyframes).toEqual([
new Map<string, string | number>([
['opacity', AUTO_STYLE],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0.5],
['offset', 0.5],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
const subPlayer = players[1];
expect(subPlayer.delay).toEqual(2000);
expect(subPlayer.keyframes).toEqual([
new Map<string, string | number>([
['height', 0],
['offset', 0],
]),
new Map<string, string | number>([
['height', 100],
['offset', 0.5],
]),
new Map<string, string | number>([
['height', 50],
['offset', 1],
]),
]);
const player1 = players[2];
expect(player1.delay).toEqual(3000);
expect(player1.keyframes).toEqual([
new Map<string, string | number>([
['opacity', 1],
['height', 50],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0],
['height', 0],
['offset', 1],
]),
]);
});
it('should propagate inner keyframe style data to the parent timeline if used afterwards', () => {
const steps = [
style({opacity: 0}),
animate(1000, style({opacity: 0.5})),
animate(1000, style({opacity: 1})),
animate(1000, keyframes([style({color: 'red'}), style({color: 'blue'})])),
animate(1000, style({color: 'green', opacity: 0})),
];
const players = invokeAnimationSequence(rootElement, steps);
const finalPlayer = players[players.length - 1];
expect(finalPlayer.keyframes).toEqual([
new Map<string, string | number>([
['opacity', 1],
['color', 'blue'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0],
['color', 'green'],
['offset', 1],
]),
]);
});
it('should feed in starting data into inner keyframes if used in an style step beforehand', () => {
const steps = [
animate(1000, style({opacity: 0.5})),
animate(
1000,
keyframes([style({opacity: 0.8, offset: 0.5}), style({opacity: 1, offset: 1})]),
),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(2);
const topPlayer = players[0];
expect(topPlayer.keyframes).toEqual([
new Map<string, string | number>([
['opacity', AUTO_STYLE],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0.5],
['offset', 1],
]),
]);
const subPlayer = players[1];
expect(subPlayer.keyframes).toEqual([
new Map<string, string | number>([
['opacity', 0.5],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0.8],
['offset', 0.5],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
});
it('should set the easing value as an easing value for the entire timeline', () => {
const steps = [
style({opacity: 0}),
animate(1000, style({opacity: 0.5})),
animate(
'1s ease-out',
keyframes([style({opacity: 0.8, offset: 0.5}), style({opacity: 1, offset: 1})]),
),
];
const player = invokeAnimationSequence(rootElement, steps)[1];
expect(player.easing).toEqual('ease-out');
});
it('should combine the starting time + the given delay as the delay value for the animated keyframes', () => {
const steps = [
style({opacity: 0}),
animate(500, style({opacity: 0.5})),
animate(
'1s 2s ease-out',
keyframes([style({opacity: 0.8, offset: 0.5}), style({opacity: 1, offset: 1})]),
),
];
const player = invokeAnimationSequence(rootElement, steps)[1];
expect(player.delay).toEqual(2500);
});
it('should not leak in additional styles used later on after keyframe styles have already been declared', () => {
const steps = [
animate(1000, style({height: '50px'})),
animate(
2000,
keyframes([
style({left: '0', top: '0', offset: 0}),
style({left: '40%', top: '50%', offset: 0.33}),
style({left: '60%', top: '80%', offset: 0.66}),
style({left: 'calc(100% - 100px)', top: '100%', offset: 1}),
]),
),
group([animate('2s', style({width: '200px'}))]),
animate('2s', style({height: '300px'})),
group([animate('2s', style({height: '500px', width: '500px'}))]),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(5);
const firstPlayerKeyframes = players[0].keyframes;
expect(firstPlayerKeyframes[0].get('width')).toBeFalsy();
expect(firstPlayerKeyframes[1].get('width')).toBeFalsy();
expect(firstPlayerKeyframes[0].get('height')).toEqual(AUTO_STYLE);
expect(firstPlayerKeyframes[1].get('height')).toEqual('50px');
const keyframePlayerKeyframes = players[1].keyframes;
expect(keyframePlayerKeyframes[0].get('width')).toBeFalsy();
expect(keyframePlayerKeyframes[0].get('height')).toBeFalsy();
const groupPlayerKeyframes = players[2].keyframes;
expect(groupPlayerKeyframes[0].get('width')).toEqual(AUTO_STYLE);
expect(groupPlayerKeyframes[1].get('width')).toEqual('200px');
expect(groupPlayerKeyframes[0].get('height')).toBeFalsy();
expect(groupPlayerKeyframes[1].get('height')).toBeFalsy();
const secondToFinalAnimatePlayerKeyframes = players[3].keyframes;
expect(secondToFinalAnimatePlayerKeyframes[0].get('width')).toBeFalsy();
expect(secondToFinalAnimatePlayerKeyframes[1].get('width')).toBeFalsy();
expect(secondToFinalAnimatePlayerKeyframes[0].get('height')).toEqual('50px');
expect(secondToFinalAnimatePlayerKeyframes[1].get('height')).toEqual('300px');
const finalAnimatePlayerKeyframes = players[4].keyframes;
expect(finalAnimatePlayerKeyframes[0].get('width')).toEqual('200px');
expect(finalAnimatePlayerKeyframes[1].get('width')).toEqual('500px');
expect(finalAnimatePlayerKeyframes[0].get('height')).toEqual('300px');
expect(finalAnimatePlayerKeyframes[1].get('height')).toEqual('500px');
});
| {
"end_byte": 31419,
"start_byte": 23814,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_31427_33304 | t('should respect offsets if provided directly within the style data', () => {
const steps = animate(
1000,
keyframes([
style({opacity: 0, offset: 0}),
style({opacity: 0.6, offset: 0.6}),
style({opacity: 1, offset: 1}),
]),
);
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
const player = players[0];
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0.6],
['offset', 0.6],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
});
it('should respect offsets if provided directly within the style metadata type', () => {
const steps = animate(
1000,
keyframes([
{type: AnimationMetadataType.Style, offset: 0, styles: {opacity: 0}},
{type: AnimationMetadataType.Style, offset: 0.4, styles: {opacity: 0.4}},
{type: AnimationMetadataType.Style, offset: 1, styles: {opacity: 1}},
]),
);
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
const player = players[0];
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0.4],
['offset', 0.4],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
});
});
| {
"end_byte": 33304,
"start_byte": 31427,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_33310_40066 | escribe('group()', () => {
it('should properly tally style data within a group() for use in a follow-up animate() step', () => {
const steps = [
style({width: 0, height: 0}),
animate(1000, style({width: 20, height: 50})),
group([animate('1s 1s', style({width: 200})), animate('1s', style({height: 500}))]),
animate(1000, style({width: 1000, height: 1000})),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(4);
const player0 = players[0];
expect(player0.duration).toEqual(1000);
expect(player0.keyframes).toEqual([
new Map<string, string | number>([
['width', 0],
['height', 0],
['offset', 0],
]),
new Map<string, string | number>([
['width', 20],
['height', 50],
['offset', 1],
]),
]);
const gPlayer1 = players[1];
expect(gPlayer1.duration).toEqual(2000);
expect(gPlayer1.delay).toEqual(1000);
expect(gPlayer1.keyframes).toEqual([
new Map<string, string | number>([
['width', 20],
['offset', 0],
]),
new Map<string, string | number>([
['width', 20],
['offset', 0.5],
]),
new Map<string, string | number>([
['width', 200],
['offset', 1],
]),
]);
const gPlayer2 = players[2];
expect(gPlayer2.duration).toEqual(1000);
expect(gPlayer2.delay).toEqual(1000);
expect(gPlayer2.keyframes).toEqual([
new Map<string, string | number>([
['height', 50],
['offset', 0],
]),
new Map<string, string | number>([
['height', 500],
['offset', 1],
]),
]);
const player1 = players[3];
expect(player1.duration).toEqual(1000);
expect(player1.delay).toEqual(3000);
expect(player1.keyframes).toEqual([
new Map<string, string | number>([
['width', 200],
['height', 500],
['offset', 0],
]),
new Map<string, string | number>([
['width', 1000],
['height', 1000],
['offset', 1],
]),
]);
});
it('should support groups with nested sequences', () => {
const steps = [
group([
sequence([style({opacity: 0}), animate(1000, style({opacity: 1}))]),
sequence([style({width: 0}), animate(1000, style({width: 200}))]),
]),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(2);
const gPlayer1 = players[0];
expect(gPlayer1.delay).toEqual(0);
expect(gPlayer1.keyframes).toEqual([
new Map<string, string | number>([
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
const gPlayer2 = players[1];
expect(gPlayer1.delay).toEqual(0);
expect(gPlayer2.keyframes).toEqual([
new Map<string, string | number>([
['width', 0],
['offset', 0],
]),
new Map<string, string | number>([
['width', 200],
['offset', 1],
]),
]);
});
it('should respect delays after group entries', () => {
const steps = [
style({width: 0, height: 0}),
animate(1000, style({width: 50, height: 50})),
group([animate(1000, style({width: 100})), animate(1000, style({height: 100}))]),
animate('1s 1s', style({height: 200, width: 200})),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(4);
const finalPlayer = players[players.length - 1];
expect(finalPlayer.delay).toEqual(2000);
expect(finalPlayer.duration).toEqual(2000);
expect(finalPlayer.keyframes).toEqual([
new Map<string, string | number>([
['width', 100],
['height', 100],
['offset', 0],
]),
new Map<string, string | number>([
['width', 100],
['height', 100],
['offset', 0.5],
]),
new Map<string, string | number>([
['width', 200],
['height', 200],
['offset', 1],
]),
]);
});
it('should respect delays after multiple calls to group()', () => {
const steps = [
group([animate('2s', style({opacity: 1})), animate('2s', style({width: '100px'}))]),
animate(2000, style({width: 0, opacity: 0})),
group([animate('2s', style({opacity: 1})), animate('2s', style({width: '200px'}))]),
animate(2000, style({width: 0, opacity: 0})),
];
const players = invokeAnimationSequence(rootElement, steps);
const middlePlayer = players[2];
expect(middlePlayer.delay).toEqual(2000);
expect(middlePlayer.duration).toEqual(2000);
const finalPlayer = players[players.length - 1];
expect(finalPlayer.delay).toEqual(6000);
expect(finalPlayer.duration).toEqual(2000);
});
it('should push the start of a group if a delay option is provided', () => {
const steps = [
style({width: '0px', height: '0px'}),
animate(1500, style({width: '100px', height: '100px'})),
group([animate(1000, style({width: '200px'})), animate(2000, style({height: '200px'}))], {
delay: 300,
}),
];
const players = invokeAnimationSequence(rootElement, steps);
const finalWidthPlayer = players[players.length - 2];
const finalHeightPlayer = players[players.length - 1];
expect(finalWidthPlayer.delay).toEqual(1800);
expect(finalWidthPlayer.keyframes).toEqual([
new Map<string, string | number>([
['width', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['width', '200px'],
['offset', 1],
]),
]);
expect(finalHeightPlayer.delay).toEqual(1800);
expect(finalHeightPlayer.keyframes).toEqual([
new Map<string, string | number>([
['height', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['height', '200px'],
['offset', 1],
]),
]);
});
});
| {
"end_byte": 40066,
"start_byte": 33310,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_40072_45968 | escribe('query()', () => {
it('should delay the query operation if a delay option is provided', () => {
const steps = [
style({opacity: 0}),
animate(1000, style({opacity: 1})),
query('div', [style({width: 0}), animate(500, style({width: 200}))], {delay: 200}),
];
const players = invokeAnimationSequence(rootElement, steps);
const finalPlayer = players[players.length - 1];
expect(finalPlayer.delay).toEqual(1200);
});
it('should throw an error when an animation query returns zero elements', () => {
const steps = [
query('somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
];
expect(() => {
invokeAnimationSequence(rootElement, steps);
}).toThrowError(
/`query\("somethingFake"\)` returned zero elements\. \(Use `query\("somethingFake", \{ optional: true \}\)` if you wish to allow this\.\)/,
);
});
it('should allow a query to be skipped if it is set as optional and returns zero elements', () => {
const steps = [
query('somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {
optional: true,
}),
];
expect(() => {
invokeAnimationSequence(rootElement, steps);
}).not.toThrow();
const steps2 = [
query('fakeSomethings', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {
optional: true,
}),
];
expect(() => {
invokeAnimationSequence(rootElement, steps2);
}).not.toThrow();
});
it('should delay the query operation if a delay option is provided', () => {
const steps = [
style({opacity: 0}),
animate(1300, style({opacity: 1})),
query('div', [style({width: 0}), animate(500, style({width: 200}))], {delay: 300}),
];
const players = invokeAnimationSequence(rootElement, steps);
const fp1 = players[players.length - 2];
const fp2 = players[players.length - 1];
expect(fp1.delay).toEqual(1600);
expect(fp2.delay).toEqual(1600);
});
});
describe('timing values', () => {
it('should properly combine an easing value with a delay into a set of three keyframes', () => {
const steps: AnimationMetadata[] = [
style({opacity: 0}),
animate('3s 1s ease-out', style({opacity: 1})),
];
const player = invokeAnimationSequence(rootElement, steps)[0];
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', 0],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 0],
['offset', 0.25],
['easing', 'ease-out'],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
});
it('should allow easing values to exist for each animate() step', () => {
const steps: AnimationMetadata[] = [
style({width: 0}),
animate('1s linear', style({width: 10})),
animate('2s ease-out', style({width: 20})),
animate('1s ease-in', style({width: 30})),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players.length).toEqual(1);
const player = players[0];
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['width', 0],
['offset', 0],
['easing', 'linear'],
]),
new Map<string, string | number>([
['width', 10],
['offset', 0.25],
['easing', 'ease-out'],
]),
new Map<string, string | number>([
['width', 20],
['offset', 0.75],
['easing', 'ease-in'],
]),
new Map<string, string | number>([
['width', 30],
['offset', 1],
]),
]);
});
it('should produce a top-level timeline only for the duration that is set as before a group kicks in', () => {
const steps: AnimationMetadata[] = [
style({width: 0, height: 0, opacity: 0}),
animate('1s', style({width: 100, height: 100, opacity: 0.2})),
group([
animate('500ms 1s', style({width: 500})),
animate('1s', style({height: 500})),
sequence([
animate(500, style({opacity: 0.5})),
animate(500, style({opacity: 0.6})),
animate(500, style({opacity: 0.7})),
animate(500, style({opacity: 1})),
]),
]),
];
const player = invokeAnimationSequence(rootElement, steps)[0];
expect(player.duration).toEqual(1000);
expect(player.delay).toEqual(0);
});
it('should offset group() and keyframe() timelines with a delay which is the current time of the previous player when called', () => {
const steps: AnimationMetadata[] = [
style({width: 0, height: 0}),
animate('1500ms linear', style({width: 10, height: 10})),
group([
animate(1000, style({width: 500, height: 500})),
animate(2000, style({width: 500, height: 500})),
]),
animate(1000, keyframes([style({width: 200}), style({width: 500})])),
];
const players = invokeAnimationSequence(rootElement, steps);
expect(players[0].delay).toEqual(0); // top-level animation
expect(players[1].delay).toEqual(1500); // first entry in group()
expect(players[2].delay).toEqual(1500); // second entry in group()
expect(players[3].delay).toEqual(3500); // animate(...keyframes())
});
});
| {
"end_byte": 45968,
"start_byte": 40072,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_spec.ts_45974_50055 | escribe('state based data', () => {
it('should create an empty animation if there are zero animation steps', () => {
const steps: AnimationMetadata[] = [];
const fromStyles: Array<ɵStyleDataMap> = [
new Map<string, string | number>([
['background', 'blue'],
['height', 100],
]),
];
const toStyles: Array<ɵStyleDataMap> = [
new Map<string, string | number>([['background', 'red']]),
];
const player = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles)[0];
expect(player.duration).toEqual(0);
expect(player.keyframes).toEqual([]);
});
it('should produce an animation from start to end between the to and from styles if there are animate steps in between', () => {
const steps: AnimationMetadata[] = [animate(1000)];
const fromStyles: Array<ɵStyleDataMap> = [
new Map<string, string | number>([
['background', 'blue'],
['height', 100],
]),
];
const toStyles: Array<ɵStyleDataMap> = [
new Map<string, string | number>([['background', 'red']]),
];
const players = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['background', 'blue'],
['height', 100],
['offset', 0],
]),
new Map<string, string | number>([
['background', 'red'],
['height', AUTO_STYLE],
['offset', 1],
]),
]);
});
it('should produce an animation from start to end between the to and from styles if there are animate steps in between with an easing value', () => {
const steps: AnimationMetadata[] = [animate('1s ease-out')];
const fromStyles: Array<ɵStyleDataMap> = [
new Map<string, string | number>([['background', 'blue']]),
];
const toStyles: Array<ɵStyleDataMap> = [
new Map<string, string | number>([['background', 'red']]),
];
const players = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['background', 'blue'],
['offset', 0],
['easing', 'ease-out'],
]),
new Map<string, string | number>([
['background', 'red'],
['offset', 1],
]),
]);
});
});
});
});
function humanizeOffsets(
keyframes: Array<ɵStyleDataMap>,
digits: number = 3,
): Array<ɵStyleDataMap> {
return keyframes.map((keyframe) => {
keyframe.set('offset', Number(parseFloat(<any>keyframe.get('offset')).toFixed(digits)));
return keyframe;
});
}
function invokeAnimationSequence(
element: any,
steps: AnimationMetadata | AnimationMetadata[],
locals: {[key: string]: any} = {},
startingStyles: Array<ɵStyleDataMap> = [],
destinationStyles: Array<ɵStyleDataMap> = [],
subInstructions?: ElementInstructionMap,
): AnimationTimelineInstruction[] {
const driver = new MockAnimationDriver();
return new Animation(driver, steps).buildTimelines(
element,
startingStyles,
destinationStyles,
locals,
subInstructions,
);
}
function validateAndThrowAnimationSequence(steps: AnimationMetadata | AnimationMetadata[]) {
const driver = new MockAnimationDriver();
const errors: Error[] = [];
const ast = buildAnimationAst(driver, steps, errors, []);
if (errors.length) {
throw new Error(errors.join('\n'));
}
}
function getValidationWarningsForAnimationSequence(
steps: AnimationMetadata | AnimationMetadata[],
): string[] {
const driver = new MockAnimationDriver();
const warnings: string[] = [];
buildAnimationAst(driver, steps, [], warnings);
return warnings;
}
function buildParams(params: {[name: string]: any}): AnimationOptions {
return <AnimationOptions>{params};
}
| {
"end_byte": 50055,
"start_byte": 45974,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_trigger_spec.ts_0_2001 | /**
* @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.dev/license
*/
import {animate, AnimationOptions, state, style, transition} from '@angular/animations';
import {AnimationTransitionInstruction} from '@angular/animations/browser/src/dsl/animation_transition_instruction';
import {AnimationTrigger} from '@angular/animations/browser/src/dsl/animation_trigger';
import {ENTER_CLASSNAME, LEAVE_CLASSNAME} from '../../src/util';
import {MockAnimationDriver} from '../../testing';
import {makeTrigger} from '../shared';
describe('AnimationTrigger', () => {
// these tests are only meant to be run within the DOM (for now)
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
let element: any;
beforeEach(() => {
element = document.createElement('div');
document.body.appendChild(element);
});
afterEach(() => {
element.remove();
});
describe('trigger validation', () => {
it('should group errors together for an animation trigger', () => {
expect(() => {
makeTrigger('myTrigger', [transition('12345', animate(3333))]);
}).toThrowError(/NG03403: Animation parsing for the myTrigger trigger have failed/);
});
it('should throw an error when a transition within a trigger contains an invalid expression', () => {
expect(() => {
makeTrigger('name', [transition('somethingThatIsWrong', animate(3333))]);
}).toThrowError(
/- NG03015: The provided transition expression "somethingThatIsWrong" is not supported/,
);
});
it('should throw an error if an animation alias is used that is not yet supported', () => {
expect(() => {
makeTrigger('name', [transition(':angular', animate(3333))]);
}).toThrowError(/- NG03016: The transition alias value ":angular" is not supported/);
});
}); | {
"end_byte": 2001,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_trigger_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_trigger_spec.ts_2005_9618 | describe('trigger usage', () => {
it('should construct a trigger based on the states and transition data', () => {
const result = makeTrigger('name', [
state('on', style({width: 0})),
state('off', style({width: 100})),
transition('on => off', animate(1000)),
transition('off => on', animate(1000)),
]);
expect(result.states.get('on')!.buildStyles({}, [])).toEqual(
new Map<string, string | number>([['width', 0]]),
);
expect(result.states.get('off')!.buildStyles({}, [])).toEqual(
new Map<string, string | number>([['width', 100]]),
);
expect(result.transitionFactories.length).toEqual(2);
});
it('should allow multiple state values to use the same styles', () => {
const result = makeTrigger('name', [
state('on, off', style({width: 50})),
transition('on => off', animate(1000)),
transition('off => on', animate(1000)),
]);
expect(result.states.get('on')!.buildStyles({}, [])).toEqual(
new Map<string, string | number>([['width', 50]]),
);
expect(result.states.get('off')!.buildStyles({}, [])).toEqual(
new Map<string, string | number>([['width', 50]]),
);
});
it('should find the first transition that matches', () => {
const result = makeTrigger('name', [
transition('a => b', animate(1234)),
transition('b => c', animate(5678)),
]);
const trans = buildTransition(result, element, 'b', 'c')!;
expect(trans.timelines.length).toEqual(1);
const timeline = trans.timelines[0];
expect(timeline.duration).toEqual(5678);
});
it('should find a transition with a `*` value', () => {
const result = makeTrigger('name', [
transition('* => b', animate(1234)),
transition('b => *', animate(5678)),
transition('* => *', animate(9999)),
]);
let trans = buildTransition(result, element, 'b', 'c')!;
expect(trans.timelines[0].duration).toEqual(5678);
trans = buildTransition(result, element, 'a', 'b')!;
expect(trans.timelines[0].duration).toEqual(1234);
trans = buildTransition(result, element, 'c', 'c')!;
expect(trans.timelines[0].duration).toEqual(9999);
});
it('should null when no results are found', () => {
const result = makeTrigger('name', [transition('a => b', animate(1111))]);
const trigger = result.matchTransition('b', 'a', {}, {});
expect(trigger).toBeFalsy();
});
it('should support bi-directional transition expressions', () => {
const result = makeTrigger('name', [transition('a <=> b', animate(2222))]);
const t1 = buildTransition(result, element, 'a', 'b')!;
expect(t1.timelines[0].duration).toEqual(2222);
const t2 = buildTransition(result, element, 'b', 'a')!;
expect(t2.timelines[0].duration).toEqual(2222);
});
it('should support multiple transition statements in one string', () => {
const result = makeTrigger('name', [transition('a => b, b => a, c => *', animate(1234))]);
const t1 = buildTransition(result, element, 'a', 'b')!;
expect(t1.timelines[0].duration).toEqual(1234);
const t2 = buildTransition(result, element, 'b', 'a')!;
expect(t2.timelines[0].duration).toEqual(1234);
const t3 = buildTransition(result, element, 'c', 'a')!;
expect(t3.timelines[0].duration).toEqual(1234);
});
describe('params', () => {
it('should support transition-level animation variable params', () => {
const result = makeTrigger('name', [
transition(
'a => b',
[style({height: '{{ a }}'}), animate(1000, style({height: '{{ b }}'}))],
buildParams({a: '100px', b: '200px'}),
),
]);
const trans = buildTransition(result, element, 'a', 'b')!;
const keyframes = trans.timelines[0].keyframes;
expect(keyframes).toEqual([
new Map<string, string | number>([
['height', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['height', '200px'],
['offset', 1],
]),
]);
});
it('should substitute variable params provided directly within the transition match', () => {
const result = makeTrigger('name', [
transition(
'a => b',
[style({height: '{{ a }}'}), animate(1000, style({height: '{{ b }}'}))],
buildParams({a: '100px', b: '200px'}),
),
]);
const trans = buildTransition(result, element, 'a', 'b', {}, buildParams({a: '300px'}))!;
const keyframes = trans.timelines[0].keyframes;
expect(keyframes).toEqual([
new Map<string, string | number>([
['height', '300px'],
['offset', 0],
]),
new Map<string, string | number>([
['height', '200px'],
['offset', 1],
]),
]);
});
});
it('should match `true` and `false` given boolean values', () => {
const result = makeTrigger('name', [
state('false', style({color: 'red'})),
state('true', style({color: 'green'})),
transition('true <=> false', animate(1234)),
]);
const trans = buildTransition(result, element, false, true)!;
expect(trans.timelines[0].duration).toEqual(1234);
});
it('should match `1` and `0` given boolean values', () => {
const result = makeTrigger('name', [
state('0', style({color: 'red'})),
state('1', style({color: 'green'})),
transition('1 <=> 0', animate(4567)),
]);
const trans = buildTransition(result, element, false, true)!;
expect(trans.timelines[0].duration).toEqual(4567);
});
it('should match `true` and `false` state styles on a `1 <=> 0` boolean transition given boolean values', () => {
const result = makeTrigger('name', [
state('false', style({color: 'red'})),
state('true', style({color: 'green'})),
transition('1 <=> 0', animate(4567)),
]);
const trans = buildTransition(result, element, false, true)!;
expect(trans.timelines[0].keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['color', 'red'],
]),
new Map<string, string | number>([
['offset', 1],
['color', 'green'],
]),
]);
});
it('should match `1` and `0` state styles on a `true <=> false` boolean transition given boolean values', () => {
const result = makeTrigger('name', [
state('0', style({color: 'orange'})),
state('1', style({color: 'blue'})),
transition('true <=> false', animate(4567)),
]);
const trans = buildTransition(result, element, false, true)!;
expect(trans.timelines[0].keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['color', 'orange'],
]),
new Map<string, string | number>([
['offset', 1],
['color', 'blue'],
]),
]);
});
it('should treat numeric values (disguised as strings) as proper state values', () => {
const result = makeTrigger('name', [
state(1 as any as string, style({opacity: 0})),
state(0 as any as string, style({opacity: 0})),
transition('* => *', animate(1000)),
]);
expect(() => {
const trans = buildTransition(result, element, false, true)!;
}).not.toThrow();
}); | {
"end_byte": 9618,
"start_byte": 2005,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_trigger_spec.ts"
} |
angular/packages/animations/browser/test/dsl/animation_trigger_spec.ts_9624_10987 | describe('aliases', () => {
it('should alias the :enter transition as void => *', () => {
const result = makeTrigger('name', [transition(':enter', animate(3333))]);
const trans = buildTransition(result, element, 'void', 'something')!;
expect(trans.timelines[0].duration).toEqual(3333);
});
it('should alias the :leave transition as * => void', () => {
const result = makeTrigger('name', [transition(':leave', animate(3333))]);
const trans = buildTransition(result, element, 'something', 'void')!;
expect(trans.timelines[0].duration).toEqual(3333);
});
});
});
});
function buildTransition(
trigger: AnimationTrigger,
element: any,
fromState: any,
toState: any,
fromOptions?: AnimationOptions,
toOptions?: AnimationOptions,
): AnimationTransitionInstruction | null {
const params = (toOptions && toOptions.params) || {};
const trans = trigger.matchTransition(fromState, toState, element, params)!;
if (trans) {
const driver = new MockAnimationDriver();
return trans.build(
driver,
element,
fromState,
toState,
ENTER_CLASSNAME,
LEAVE_CLASSNAME,
fromOptions,
toOptions,
)!;
}
return null;
}
function buildParams(params: {[name: string]: any}): AnimationOptions {
return <AnimationOptions>{params};
} | {
"end_byte": 10987,
"start_byte": 9624,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/animation_trigger_spec.ts"
} |
angular/packages/animations/browser/test/dsl/style_normalizer/web_animations_style_normalizer_spec.ts_0_2765 | /**
* @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.dev/license
*/
import {WebAnimationsStyleNormalizer} from '../../../src/dsl/style_normalization/web_animations_style_normalizer';
describe('WebAnimationsStyleNormalizer', () => {
const normalizer = new WebAnimationsStyleNormalizer();
describe('normalizePropertyName', () => {
it('should normalize CSS property values to camel-case', () => {
expect(normalizer.normalizePropertyName('width', [])).toEqual('width');
expect(normalizer.normalizePropertyName('border-width', [])).toEqual('borderWidth');
expect(normalizer.normalizePropertyName('borderHeight', [])).toEqual('borderHeight');
expect(normalizer.normalizePropertyName('-webkit-animation', [])).toEqual('WebkitAnimation');
});
});
describe('normalizeStyleValue', () => {
function normalize(prop: string, val: string | number): string {
const errors: Error[] = [];
const result = normalizer.normalizeStyleValue(prop, prop, val, errors);
if (errors.length) {
throw new Error(errors.join('\n'));
}
return result;
}
it('should normalize number-based dimensional properties to use a `px` suffix if missing', () => {
expect(normalize('width', 10)).toEqual('10px');
expect(normalize('height', 20)).toEqual('20px');
});
it('should report an error when a string-based dimensional value does not contain a suffix at all', () => {
expect(() => {
normalize('width', '50');
}).toThrowError(/Please provide a CSS unit value for width:50/);
});
it('should not normalize non-dimensional properties with `px` values, but only convert them to string', () => {
expect(normalize('opacity', 0)).toEqual('0');
expect(normalize('opacity', '1')).toEqual('1');
expect(normalize('color', 'red')).toEqual('red');
expect(normalize('fontWeight', '100')).toEqual('100');
});
it('should not normalize dimensional-based values that already contain a dimensional suffix or a non dimensional value', () => {
expect(normalize('width', '50em')).toEqual('50em');
expect(normalize('height', '500pt')).toEqual('500pt');
expect(normalize('borderWidth', 'inherit')).toEqual('inherit');
expect(normalize('paddingTop', 'calc(500px + 200px)')).toEqual('calc(500px + 200px)');
});
it('should allow `perspective` to be a numerical property', () => {
expect(normalize('perspective', 10)).toEqual('10px');
expect(normalize('perspective', '100pt')).toEqual('100pt');
expect(normalize('perspective', 'none')).toEqual('none');
});
});
});
| {
"end_byte": 2765,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/test/dsl/style_normalizer/web_animations_style_normalizer_spec.ts"
} |
angular/packages/animations/browser/testing/PACKAGE.md_0_72 | Provides infrastructure for testing of the Animations browser subsystem. | {
"end_byte": 72,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/testing/PACKAGE.md"
} |
angular/packages/animations/browser/testing/BUILD.bazel_0_696 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "testing",
srcs = glob(["**/*.ts"]),
deps = [
"//packages/animations",
"//packages/animations/browser",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "animations_browser_testing_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/animations/browser/testing",
)
| {
"end_byte": 696,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/testing/BUILD.bazel"
} |
angular/packages/animations/browser/testing/index.ts_0_480 | /**
* @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.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verifcation. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 480,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/testing/index.ts"
} |
angular/packages/animations/browser/testing/public_api.ts_0_322 | /**
* @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.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/testing';
| {
"end_byte": 322,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/testing/public_api.ts"
} |
angular/packages/animations/browser/testing/src/mock_animation_driver.ts_0_4147 | /**
* @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.dev/license
*/
import {AnimationPlayer, AUTO_STYLE, NoopAnimationPlayer, ɵStyleDataMap} from '@angular/animations';
import {
AnimationDriver,
ɵallowPreviousPlayerStylesMerge as allowPreviousPlayerStylesMerge,
ɵcamelCaseToDashCase,
ɵcontainsElement as containsElement,
ɵgetParentElement as getParentElement,
ɵinvokeQuery as invokeQuery,
ɵnormalizeKeyframes as normalizeKeyframes,
ɵvalidateStyleProperty as validateStyleProperty,
ɵvalidateWebAnimatableStyleProperty,
} from '@angular/animations/browser';
/**
* @publicApi
*/
export class MockAnimationDriver implements AnimationDriver {
static log: AnimationPlayer[] = [];
validateStyleProperty(prop: string): boolean {
return validateStyleProperty(prop);
}
validateAnimatableStyleProperty(prop: string): boolean {
const cssProp = ɵcamelCaseToDashCase(prop);
return ɵvalidateWebAnimatableStyleProperty(cssProp);
}
containsElement(elm1: any, elm2: any): boolean {
return containsElement(elm1, elm2);
}
getParentElement(element: unknown): unknown {
return getParentElement(element);
}
query(element: any, selector: string, multi: boolean): any[] {
return invokeQuery(element, selector, multi);
}
computeStyle(element: any, prop: string, defaultValue?: string): string {
return defaultValue || '';
}
animate(
element: any,
keyframes: Array<ɵStyleDataMap>,
duration: number,
delay: number,
easing: string,
previousPlayers: any[] = [],
): MockAnimationPlayer {
const player = new MockAnimationPlayer(
element,
keyframes,
duration,
delay,
easing,
previousPlayers,
);
MockAnimationDriver.log.push(<AnimationPlayer>player);
return player;
}
}
/**
* @publicApi
*/
export class MockAnimationPlayer extends NoopAnimationPlayer {
private __finished = false;
private __started = false;
public previousStyles: ɵStyleDataMap = new Map();
private _onInitFns: (() => any)[] = [];
public currentSnapshot: ɵStyleDataMap = new Map();
private _keyframes: Array<ɵStyleDataMap> = [];
constructor(
public element: any,
public keyframes: Array<ɵStyleDataMap>,
public duration: number,
public delay: number,
public easing: string,
public previousPlayers: any[],
) {
super(duration, delay);
this._keyframes = normalizeKeyframes(keyframes);
if (allowPreviousPlayerStylesMerge(duration, delay)) {
previousPlayers.forEach((player) => {
if (player instanceof MockAnimationPlayer) {
const styles = player.currentSnapshot;
styles.forEach((val, prop) => this.previousStyles.set(prop, val));
}
});
}
}
/** @internal */
onInit(fn: () => any) {
this._onInitFns.push(fn);
}
/** @internal */
override init() {
super.init();
this._onInitFns.forEach((fn) => fn());
this._onInitFns = [];
}
override reset() {
super.reset();
this.__started = false;
}
override finish(): void {
super.finish();
this.__finished = true;
}
override destroy(): void {
super.destroy();
this.__finished = true;
}
/** @internal */
triggerMicrotask() {}
override play(): void {
super.play();
this.__started = true;
}
override hasStarted() {
return this.__started;
}
beforeDestroy() {
const captures: ɵStyleDataMap = new Map();
this.previousStyles.forEach((val, prop) => captures.set(prop, val));
if (this.hasStarted()) {
// when assembling the captured styles, it's important that
// we build the keyframe styles in the following order:
// {other styles within keyframes, ... previousStyles }
this._keyframes.forEach((kf) => {
for (let [prop, val] of kf) {
if (prop !== 'offset') {
captures.set(prop, this.__finished ? val : AUTO_STYLE);
}
}
});
}
this.currentSnapshot = captures;
}
}
| {
"end_byte": 4147,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/testing/src/mock_animation_driver.ts"
} |
angular/packages/animations/browser/testing/src/testing.ts_0_285 | /**
* @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.dev/license
*/
export {MockAnimationDriver, MockAnimationPlayer} from './mock_animation_driver';
| {
"end_byte": 285,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/testing/src/testing.ts"
} |
angular/packages/animations/browser/src/private_export.ts_0_1662 | /**
* @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.dev/license
*/
export {createEngine as ɵcreateEngine} from './create_engine';
export {Animation as ɵAnimation} from './dsl/animation';
export {
AnimationStyleNormalizer as ɵAnimationStyleNormalizer,
NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer,
} from './dsl/style_normalization/animation_style_normalizer';
export {WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer} from './dsl/style_normalization/web_animations_style_normalizer';
export {AnimationEngine as ɵAnimationEngine} from './render/animation_engine_next';
export {AnimationRendererFactory as ɵAnimationRendererFactory} from './render/animation_renderer';
export {
AnimationRenderer as ɵAnimationRenderer,
BaseAnimationRenderer as ɵBaseAnimationRenderer,
} from './render/renderer';
export {
containsElement as ɵcontainsElement,
getParentElement as ɵgetParentElement,
invokeQuery as ɵinvokeQuery,
validateStyleProperty as ɵvalidateStyleProperty,
validateWebAnimatableStyleProperty as ɵvalidateWebAnimatableStyleProperty,
} from './render/shared';
export {WebAnimationsDriver as ɵWebAnimationsDriver} from './render/web_animations/web_animations_driver';
export {WebAnimationsPlayer as ɵWebAnimationsPlayer} from './render/web_animations/web_animations_player';
export {
allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge,
camelCaseToDashCase as ɵcamelCaseToDashCase,
normalizeKeyframes as ɵnormalizeKeyframes,
} from './util';
| {
"end_byte": 1662,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/private_export.ts"
} |
angular/packages/animations/browser/src/browser.ts_0_425 | /**
* @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.dev/license
*/
/**
* @module
* @description
* Entry point for all animation APIs of the animation browser package.
*/
export {AnimationDriver, NoopAnimationDriver} from './render/animation_driver';
export * from './private_export';
| {
"end_byte": 425,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/browser.ts"
} |
angular/packages/animations/browser/src/warning_helpers.ts_0_1621 | /**
* @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.dev/license
*/
function createListOfWarnings(warnings: string[]): string {
const LINE_START = '\n - ';
return `${LINE_START}${warnings
.filter(Boolean)
.map((warning) => warning)
.join(LINE_START)}`;
}
export function warnValidation(warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);
}
export function warnTriggerBuild(name: string, warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(
`The animation trigger "${name}" has built with the following warnings:${createListOfWarnings(
warnings,
)}`,
);
}
export function warnRegister(warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);
}
export function triggerParsingWarnings(name: string, warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
console.warn(
`Animation parsing for the ${name} trigger presents the following warnings:${createListOfWarnings(
warnings,
)}`,
);
}
export function pushUnrecognizedPropertiesWarning(warnings: string[], props: string[]): void {
if (props.length) {
warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);
}
}
| {
"end_byte": 1621,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/warning_helpers.ts"
} |
angular/packages/animations/browser/src/create_engine.ts_0_990 | /**
* @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.dev/license
*/
import {NoopAnimationStyleNormalizer} from './dsl/style_normalization/animation_style_normalizer';
import {WebAnimationsStyleNormalizer} from './dsl/style_normalization/web_animations_style_normalizer';
import {NoopAnimationDriver} from './render/animation_driver';
import {AnimationEngine} from './render/animation_engine_next';
import {WebAnimationsDriver} from './render/web_animations/web_animations_driver';
export function createEngine(type: 'animations' | 'noop', doc: Document): AnimationEngine {
// TODO: find a way to make this tree shakable.
if (type === 'noop') {
return new AnimationEngine(doc, new NoopAnimationDriver(), new NoopAnimationStyleNormalizer());
}
return new AnimationEngine(doc, new WebAnimationsDriver(), new WebAnimationsStyleNormalizer());
}
| {
"end_byte": 990,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/create_engine.ts"
} |
angular/packages/animations/browser/src/util.ts_0_7229 | /**
* @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.dev/license
*/
import {
AnimateTimings,
AnimationMetadata,
AnimationMetadataType,
AnimationOptions,
sequence,
ɵStyleData,
ɵStyleDataMap,
} from '@angular/animations';
import {Ast as AnimationAst, AstVisitor as AnimationAstVisitor} from './dsl/animation_ast';
import {AnimationDslVisitor} from './dsl/animation_dsl_visitor';
import {
invalidNodeType,
invalidParamValue,
invalidStyleParams,
invalidTimingValue,
negativeDelayValue,
negativeStepValue,
} from './error_helpers';
const ONE_SECOND = 1000;
export const SUBSTITUTION_EXPR_START = '{{';
export const SUBSTITUTION_EXPR_END = '}}';
export const ENTER_CLASSNAME = 'ng-enter';
export const LEAVE_CLASSNAME = 'ng-leave';
export const NG_TRIGGER_CLASSNAME = 'ng-trigger';
export const NG_TRIGGER_SELECTOR = '.ng-trigger';
export const NG_ANIMATING_CLASSNAME = 'ng-animating';
export const NG_ANIMATING_SELECTOR = '.ng-animating';
export function resolveTimingValue(value: string | number) {
if (typeof value == 'number') return value;
const matches = value.match(/^(-?[\.\d]+)(m?s)/);
if (!matches || matches.length < 2) return 0;
return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
}
function _convertTimeValueToMS(value: number, unit: string): number {
switch (unit) {
case 's':
return value * ONE_SECOND;
default: // ms or something else
return value;
}
}
export function resolveTiming(
timings: string | number | AnimateTimings,
errors: Error[],
allowNegativeValues?: boolean,
) {
return timings.hasOwnProperty('duration')
? <AnimateTimings>timings
: parseTimeExpression(<string | number>timings, errors, allowNegativeValues);
}
function parseTimeExpression(
exp: string | number,
errors: Error[],
allowNegativeValues?: boolean,
): AnimateTimings {
const regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i;
let duration: number;
let delay: number = 0;
let easing: string = '';
if (typeof exp === 'string') {
const matches = exp.match(regex);
if (matches === null) {
errors.push(invalidTimingValue(exp));
return {duration: 0, delay: 0, easing: ''};
}
duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
const delayMatch = matches[3];
if (delayMatch != null) {
delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);
}
const easingVal = matches[5];
if (easingVal) {
easing = easingVal;
}
} else {
duration = exp;
}
if (!allowNegativeValues) {
let containsErrors = false;
let startIndex = errors.length;
if (duration < 0) {
errors.push(negativeStepValue());
containsErrors = true;
}
if (delay < 0) {
errors.push(negativeDelayValue());
containsErrors = true;
}
if (containsErrors) {
errors.splice(startIndex, 0, invalidTimingValue(exp));
}
}
return {duration, delay, easing};
}
export function normalizeKeyframes(
keyframes: Array<ɵStyleData> | Array<ɵStyleDataMap>,
): Array<ɵStyleDataMap> {
if (!keyframes.length) {
return [];
}
if (keyframes[0] instanceof Map) {
return keyframes as Array<ɵStyleDataMap>;
}
return keyframes.map((kf) => new Map(Object.entries(kf)));
}
export function normalizeStyles(styles: ɵStyleDataMap | Array<ɵStyleDataMap>): ɵStyleDataMap {
return Array.isArray(styles) ? new Map(...styles) : new Map(styles);
}
export function setStyles(element: any, styles: ɵStyleDataMap, formerStyles?: ɵStyleDataMap) {
styles.forEach((val, prop) => {
const camelProp = dashCaseToCamelCase(prop);
if (formerStyles && !formerStyles.has(prop)) {
formerStyles.set(prop, element.style[camelProp]);
}
element.style[camelProp] = val;
});
}
export function eraseStyles(element: any, styles: ɵStyleDataMap) {
styles.forEach((_, prop) => {
const camelProp = dashCaseToCamelCase(prop);
element.style[camelProp] = '';
});
}
export function normalizeAnimationEntry(
steps: AnimationMetadata | AnimationMetadata[],
): AnimationMetadata {
if (Array.isArray(steps)) {
if (steps.length == 1) return steps[0];
return sequence(steps);
}
return steps as AnimationMetadata;
}
export function validateStyleParams(
value: string | number | null | undefined,
options: AnimationOptions,
errors: Error[],
) {
const params = options.params || {};
const matches = extractStyleParams(value);
if (matches.length) {
matches.forEach((varName) => {
if (!params.hasOwnProperty(varName)) {
errors.push(invalidStyleParams(varName));
}
});
}
}
const PARAM_REGEX = new RegExp(
`${SUBSTITUTION_EXPR_START}\\s*(.+?)\\s*${SUBSTITUTION_EXPR_END}`,
'g',
);
export function extractStyleParams(value: string | number | null | undefined): string[] {
let params: string[] = [];
if (typeof value === 'string') {
let match: any;
while ((match = PARAM_REGEX.exec(value))) {
params.push(match[1] as string);
}
PARAM_REGEX.lastIndex = 0;
}
return params;
}
export function interpolateParams(
value: string | number,
params: {[name: string]: any},
errors: Error[],
): string | number {
const original = `${value}`;
const str = original.replace(PARAM_REGEX, (_, varName) => {
let localVal = params[varName];
// this means that the value was never overridden by the data passed in by the user
if (localVal == null) {
errors.push(invalidParamValue(varName));
localVal = '';
}
return localVal.toString();
});
// we do this to assert that numeric values stay as they are
return str == original ? value : str;
}
const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
export function dashCaseToCamelCase(input: string): string {
return input.replace(DASH_CASE_REGEXP, (...m: any[]) => m[1].toUpperCase());
}
export function camelCaseToDashCase(input: string): string {
return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
export function allowPreviousPlayerStylesMerge(duration: number, delay: number) {
return duration === 0 || delay === 0;
}
export function balancePreviousStylesIntoKeyframes(
element: any,
keyframes: Array<ɵStyleDataMap>,
previousStyles: ɵStyleDataMap,
) {
if (previousStyles.size && keyframes.length) {
let startingKeyframe = keyframes[0];
let missingStyleProps: string[] = [];
previousStyles.forEach((val, prop) => {
if (!startingKeyframe.has(prop)) {
missingStyleProps.push(prop);
}
startingKeyframe.set(prop, val);
});
if (missingStyleProps.length) {
for (let i = 1; i < keyframes.length; i++) {
let kf = keyframes[i];
missingStyleProps.forEach((prop) => kf.set(prop, computeStyle(element, prop)));
}
}
}
return keyframes;
}
export function visitDslNode(
visitor: AnimationDslVisitor,
node: AnimationMetadata,
context: any,
): any;
export function visitDslNode(
visitor: AnimationAstVisitor,
node: AnimationAst<AnimationMetadataType>,
context: any,
): any;
export functi | {
"end_byte": 7229,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/util.ts"
} |
angular/packages/animations/browser/src/util.ts_7230_8698 | n visitDslNode(visitor: any, node: any, context: any): any {
switch (node.type) {
case AnimationMetadataType.Trigger:
return visitor.visitTrigger(node, context);
case AnimationMetadataType.State:
return visitor.visitState(node, context);
case AnimationMetadataType.Transition:
return visitor.visitTransition(node, context);
case AnimationMetadataType.Sequence:
return visitor.visitSequence(node, context);
case AnimationMetadataType.Group:
return visitor.visitGroup(node, context);
case AnimationMetadataType.Animate:
return visitor.visitAnimate(node, context);
case AnimationMetadataType.Keyframes:
return visitor.visitKeyframes(node, context);
case AnimationMetadataType.Style:
return visitor.visitStyle(node, context);
case AnimationMetadataType.Reference:
return visitor.visitReference(node, context);
case AnimationMetadataType.AnimateChild:
return visitor.visitAnimateChild(node, context);
case AnimationMetadataType.AnimateRef:
return visitor.visitAnimateRef(node, context);
case AnimationMetadataType.Query:
return visitor.visitQuery(node, context);
case AnimationMetadataType.Stagger:
return visitor.visitStagger(node, context);
default:
throw invalidNodeType(node.type);
}
}
export function computeStyle(element: any, prop: string): string {
return (<any>window.getComputedStyle(element))[prop];
}
| {
"end_byte": 8698,
"start_byte": 7230,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/util.ts"
} |
angular/packages/animations/browser/src/error_helpers.ts_0_9346 | /**
* @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.dev/license
*/
import {ɵRuntimeErrorCode as RuntimeErrorCode} from '@angular/animations';
import {ɵRuntimeError as RuntimeError} from '@angular/core';
const LINE_START = '\n - ';
export function invalidTimingValue(exp: string | number): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_TIMING_VALUE,
ngDevMode && `The provided timing value "${exp}" is invalid.`,
);
}
export function negativeStepValue(): Error {
return new RuntimeError(
RuntimeErrorCode.NEGATIVE_STEP_VALUE,
ngDevMode && 'Duration values below 0 are not allowed for this animation step.',
);
}
export function negativeDelayValue(): Error {
return new RuntimeError(
RuntimeErrorCode.NEGATIVE_DELAY_VALUE,
ngDevMode && 'Delay values below 0 are not allowed for this animation step.',
);
}
export function invalidStyleParams(varName: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_STYLE_PARAMS,
ngDevMode &&
`Unable to resolve the local animation param ${varName} in the given list of values`,
);
}
export function invalidParamValue(varName: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_PARAM_VALUE,
ngDevMode && `Please provide a value for the animation param ${varName}`,
);
}
export function invalidNodeType(nodeType: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_NODE_TYPE,
ngDevMode && `Unable to resolve animation metadata node #${nodeType}`,
);
}
export function invalidCssUnitValue(userProvidedProperty: string, value: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_CSS_UNIT_VALUE,
ngDevMode && `Please provide a CSS unit value for ${userProvidedProperty}:${value}`,
);
}
export function invalidTrigger(): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_TRIGGER,
ngDevMode &&
"animation triggers cannot be prefixed with an `@` sign (e.g. trigger('@foo', [...]))",
);
}
export function invalidDefinition(): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_DEFINITION,
ngDevMode && 'only state() and transition() definitions can sit inside of a trigger()',
);
}
export function invalidState(metadataName: string, missingSubs: string[]): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_STATE,
ngDevMode &&
`state("${metadataName}", ...) must define default values for all the following style substitutions: ${missingSubs.join(
', ',
)}`,
);
}
export function invalidStyleValue(value: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_STYLE_VALUE,
ngDevMode && `The provided style string value ${value} is not allowed.`,
);
}
export function invalidProperty(prop: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_PROPERTY,
ngDevMode &&
`The provided animation property "${prop}" is not a supported CSS property for animations`,
);
}
export function invalidParallelAnimation(
prop: string,
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_PARALLEL_ANIMATION,
ngDevMode &&
`The CSS property "${prop}" that exists between the times of "${firstStart}ms" and "${firstEnd}ms" is also being animated in a parallel animation between the times of "${secondStart}ms" and "${secondEnd}ms"`,
);
}
export function invalidKeyframes(): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_KEYFRAMES,
ngDevMode && `keyframes() must be placed inside of a call to animate()`,
);
}
export function invalidOffset(): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_OFFSET,
ngDevMode && `Please ensure that all keyframe offsets are between 0 and 1`,
);
}
export function keyframeOffsetsOutOfOrder(): Error {
return new RuntimeError(
RuntimeErrorCode.KEYFRAME_OFFSETS_OUT_OF_ORDER,
ngDevMode && `Please ensure that all keyframe offsets are in order`,
);
}
export function keyframesMissingOffsets(): Error {
return new RuntimeError(
RuntimeErrorCode.KEYFRAMES_MISSING_OFFSETS,
ngDevMode && `Not all style() steps within the declared keyframes() contain offsets`,
);
}
export function invalidStagger(): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_STAGGER,
ngDevMode && `stagger() can only be used inside of query()`,
);
}
export function invalidQuery(selector: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_QUERY,
ngDevMode &&
`\`query("${selector}")\` returned zero elements. (Use \`query("${selector}", { optional: true })\` if you wish to allow this.)`,
);
}
export function invalidExpression(expr: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_EXPRESSION,
ngDevMode && `The provided transition expression "${expr}" is not supported`,
);
}
export function invalidTransitionAlias(alias: string): Error {
return new RuntimeError(
RuntimeErrorCode.INVALID_TRANSITION_ALIAS,
ngDevMode && `The transition alias value "${alias}" is not supported`,
);
}
export function validationFailed(errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.VALIDATION_FAILED,
ngDevMode && `animation validation failed:\n${errors.map((err) => err.message).join('\n')}`,
);
}
export function buildingFailed(errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.BUILDING_FAILED,
ngDevMode && `animation building failed:\n${errors.map((err) => err.message).join('\n')}`,
);
}
export function triggerBuildFailed(name: string, errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.TRIGGER_BUILD_FAILED,
ngDevMode &&
`The animation trigger "${name}" has failed to build due to the following errors:\n - ${errors
.map((err) => err.message)
.join('\n - ')}`,
);
}
export function animationFailed(errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.ANIMATION_FAILED,
ngDevMode &&
`Unable to animate due to the following errors:${LINE_START}${errors
.map((err) => err.message)
.join(LINE_START)}`,
);
}
export function registerFailed(errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.REGISTRATION_FAILED,
ngDevMode &&
`Unable to build the animation due to the following errors: ${errors
.map((err) => err.message)
.join('\n')}`,
);
}
export function missingOrDestroyedAnimation(): Error {
return new RuntimeError(
RuntimeErrorCode.MISSING_OR_DESTROYED_ANIMATION,
ngDevMode && "The requested animation doesn't exist or has already been destroyed",
);
}
export function createAnimationFailed(errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.CREATE_ANIMATION_FAILED,
ngDevMode &&
`Unable to create the animation due to the following errors:${errors
.map((err) => err.message)
.join('\n')}`,
);
}
export function missingPlayer(id: string): Error {
return new RuntimeError(
RuntimeErrorCode.MISSING_PLAYER,
ngDevMode && `Unable to find the timeline player referenced by ${id}`,
);
}
export function missingTrigger(phase: string, name: string): Error {
return new RuntimeError(
RuntimeErrorCode.MISSING_TRIGGER,
ngDevMode &&
`Unable to listen on the animation trigger event "${phase}" because the animation trigger "${name}" doesn\'t exist!`,
);
}
export function missingEvent(name: string): Error {
return new RuntimeError(
RuntimeErrorCode.MISSING_EVENT,
ngDevMode &&
`Unable to listen on the animation trigger "${name}" because the provided event is undefined!`,
);
}
export function unsupportedTriggerEvent(phase: string, name: string): Error {
return new RuntimeError(
RuntimeErrorCode.UNSUPPORTED_TRIGGER_EVENT,
ngDevMode &&
`The provided animation trigger event "${phase}" for the animation trigger "${name}" is not supported!`,
);
}
export function unregisteredTrigger(name: string): Error {
return new RuntimeError(
RuntimeErrorCode.UNREGISTERED_TRIGGER,
ngDevMode && `The provided animation trigger "${name}" has not been registered!`,
);
}
export function triggerTransitionsFailed(errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.TRIGGER_TRANSITIONS_FAILED,
ngDevMode &&
`Unable to process animations due to the following failed trigger transitions\n ${errors
.map((err) => err.message)
.join('\n')}`,
);
}
export function triggerParsingFailed(name: string, errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.TRIGGER_PARSING_FAILED,
ngDevMode &&
`Animation parsing for the ${name} trigger have failed:${LINE_START}${errors
.map((err) => err.message)
.join(LINE_START)}`,
);
}
export function transitionFailed(name: string, errors: Error[]): Error {
return new RuntimeError(
RuntimeErrorCode.TRANSITION_FAILED,
ngDevMode && `@${name} has failed due to:\n ${errors.map((err) => err.message).join('\n- ')}`,
);
}
| {
"end_byte": 9346,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/error_helpers.ts"
} |
angular/packages/animations/browser/src/render/timeline_animation_engine.ts_0_5673 | /**
* @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.dev/license
*/
import {
AnimationMetadata,
AnimationMetadataType,
AnimationOptions,
AnimationPlayer,
AUTO_STYLE,
ɵStyleDataMap,
} from '@angular/animations';
import {Ast} from '../dsl/animation_ast';
import {buildAnimationAst} from '../dsl/animation_ast_builder';
import {buildAnimationTimelines} from '../dsl/animation_timeline_builder';
import {AnimationTimelineInstruction} from '../dsl/animation_timeline_instruction';
import {ElementInstructionMap} from '../dsl/element_instruction_map';
import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer';
import {
createAnimationFailed,
missingOrDestroyedAnimation,
missingPlayer,
registerFailed,
} from '../error_helpers';
import {ENTER_CLASSNAME, LEAVE_CLASSNAME} from '../util';
import {warnRegister} from '../warning_helpers';
import {AnimationDriver} from './animation_driver';
import {
getOrSetDefaultValue,
listenOnPlayer,
makeAnimationEvent,
normalizeKeyframes,
optimizeGroupPlayer,
} from './shared';
const EMPTY_INSTRUCTION_MAP = new ElementInstructionMap();
export class TimelineAnimationEngine {
private _animations = new Map<string, Ast<AnimationMetadataType>>();
private _playersById = new Map<string, AnimationPlayer>();
public players: AnimationPlayer[] = [];
constructor(
public bodyNode: any,
private _driver: AnimationDriver,
private _normalizer: AnimationStyleNormalizer,
) {}
register(id: string, metadata: AnimationMetadata | AnimationMetadata[]) {
const errors: Error[] = [];
const warnings: string[] = [];
const ast = buildAnimationAst(this._driver, metadata, errors, warnings);
if (errors.length) {
throw registerFailed(errors);
} else {
if (warnings.length) {
warnRegister(warnings);
}
this._animations.set(id, ast);
}
}
private _buildPlayer(
i: AnimationTimelineInstruction,
preStyles: ɵStyleDataMap,
postStyles?: ɵStyleDataMap,
): AnimationPlayer {
const element = i.element;
const keyframes = normalizeKeyframes(this._normalizer, i.keyframes, preStyles, postStyles);
return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);
}
create(id: string, element: any, options: AnimationOptions = {}): AnimationPlayer {
const errors: Error[] = [];
const ast = this._animations.get(id);
let instructions: AnimationTimelineInstruction[];
const autoStylesMap = new Map<any, ɵStyleDataMap>();
if (ast) {
instructions = buildAnimationTimelines(
this._driver,
element,
ast,
ENTER_CLASSNAME,
LEAVE_CLASSNAME,
new Map(),
new Map(),
options,
EMPTY_INSTRUCTION_MAP,
errors,
);
instructions.forEach((inst) => {
const styles = getOrSetDefaultValue(
autoStylesMap,
inst.element,
new Map<string, string | number | null>(),
);
inst.postStyleProps.forEach((prop) => styles.set(prop, null));
});
} else {
errors.push(missingOrDestroyedAnimation());
instructions = [];
}
if (errors.length) {
throw createAnimationFailed(errors);
}
autoStylesMap.forEach((styles, element) => {
styles.forEach((_, prop) => {
styles.set(prop, this._driver.computeStyle(element, prop, AUTO_STYLE));
});
});
const players = instructions.map((i) => {
const styles = autoStylesMap.get(i.element);
return this._buildPlayer(i, new Map(), styles);
});
const player = optimizeGroupPlayer(players);
this._playersById.set(id, player);
player.onDestroy(() => this.destroy(id));
this.players.push(player);
return player;
}
destroy(id: string) {
const player = this._getPlayer(id);
player.destroy();
this._playersById.delete(id);
const index = this.players.indexOf(player);
if (index >= 0) {
this.players.splice(index, 1);
}
}
private _getPlayer(id: string): AnimationPlayer {
const player = this._playersById.get(id);
if (!player) {
throw missingPlayer(id);
}
return player;
}
listen(
id: string,
element: string,
eventName: string,
callback: (event: any) => any,
): () => void {
// triggerName, fromState, toState are all ignored for timeline animations
const baseEvent = makeAnimationEvent(element, '', '', '');
listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);
return () => {};
}
command(id: string, element: any, command: string, args: any[]): void {
if (command == 'register') {
this.register(id, args[0] as AnimationMetadata | AnimationMetadata[]);
return;
}
if (command == 'create') {
const options = (args[0] || {}) as AnimationOptions;
this.create(id, element, options);
return;
}
const player = this._getPlayer(id);
switch (command) {
case 'play':
player.play();
break;
case 'pause':
player.pause();
break;
case 'reset':
player.reset();
break;
case 'restart':
player.restart();
break;
case 'finish':
player.finish();
break;
case 'init':
player.init();
break;
case 'setPosition':
player.setPosition(parseFloat(args[0] as string));
break;
case 'destroy':
this.destroy(id);
break;
}
}
}
| {
"end_byte": 5673,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/timeline_animation_engine.ts"
} |
angular/packages/animations/browser/src/render/special_cased_styles.ts_0_4701 | /**
* @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.dev/license
*/
import {ɵStyleDataMap} from '@angular/animations';
import {eraseStyles, setStyles} from '../util';
/**
* Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are
* detected.
*
* In CSS there exist properties that cannot be animated within a keyframe animation
* (whether it be via CSS keyframes or web-animations) and the animation implementation
* will ignore them. This function is designed to detect those special cased styles and
* return a container that will be executed at the start and end of the animation.
*
* @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`
*/
export function packageNonAnimatableStyles(
element: any,
styles: ɵStyleDataMap | Array<ɵStyleDataMap>,
): SpecialCasedStyles | null {
let startStyles: ɵStyleDataMap | null = null;
let endStyles: ɵStyleDataMap | null = null;
if (Array.isArray(styles) && styles.length) {
startStyles = filterNonAnimatableStyles(styles[0]);
if (styles.length > 1) {
endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);
}
} else if (styles instanceof Map) {
startStyles = filterNonAnimatableStyles(styles);
}
return startStyles || endStyles ? new SpecialCasedStyles(element, startStyles, endStyles) : null;
}
/**
* Designed to be executed during a keyframe-based animation to apply any special-cased styles.
*
* When started (when the `start()` method is run) then the provided `startStyles`
* will be applied. When finished (when the `finish()` method is called) the
* `endStyles` will be applied as well any any starting styles. Finally when
* `destroy()` is called then all styles will be removed.
*/
export class SpecialCasedStyles {
static initialStylesByElement = /* @__PURE__ */ new WeakMap<any, ɵStyleDataMap>();
private _state = SpecialCasedStylesState.Pending;
private _initialStyles!: ɵStyleDataMap;
constructor(
private _element: any,
private _startStyles: ɵStyleDataMap | null,
private _endStyles: ɵStyleDataMap | null,
) {
let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);
if (!initialStyles) {
SpecialCasedStyles.initialStylesByElement.set(_element, (initialStyles = new Map()));
}
this._initialStyles = initialStyles;
}
start() {
if (this._state < SpecialCasedStylesState.Started) {
if (this._startStyles) {
setStyles(this._element, this._startStyles, this._initialStyles);
}
this._state = SpecialCasedStylesState.Started;
}
}
finish() {
this.start();
if (this._state < SpecialCasedStylesState.Finished) {
setStyles(this._element, this._initialStyles);
if (this._endStyles) {
setStyles(this._element, this._endStyles);
this._endStyles = null;
}
this._state = SpecialCasedStylesState.Started;
}
}
destroy() {
this.finish();
if (this._state < SpecialCasedStylesState.Destroyed) {
SpecialCasedStyles.initialStylesByElement.delete(this._element);
if (this._startStyles) {
eraseStyles(this._element, this._startStyles);
this._endStyles = null;
}
if (this._endStyles) {
eraseStyles(this._element, this._endStyles);
this._endStyles = null;
}
setStyles(this._element, this._initialStyles);
this._state = SpecialCasedStylesState.Destroyed;
}
}
}
/**
* An enum of states reflective of what the status of `SpecialCasedStyles` is.
*
* Depending on how `SpecialCasedStyles` is interacted with, the start and end
* styles may not be applied in the same way. This enum ensures that if and when
* the ending styles are applied then the starting styles are applied. It is
* also used to reflect what the current status of the special cased styles are
* which helps prevent the starting/ending styles not be applied twice. It is
* also used to cleanup the styles once `SpecialCasedStyles` is destroyed.
*/
const enum SpecialCasedStylesState {
Pending = 0,
Started = 1,
Finished = 2,
Destroyed = 3,
}
function filterNonAnimatableStyles(styles: ɵStyleDataMap): ɵStyleDataMap | null {
let result: ɵStyleDataMap | null = null;
styles.forEach((val, prop) => {
if (isNonAnimatableStyle(prop)) {
result = result || new Map();
result.set(prop, val);
}
});
return result;
}
function isNonAnimatableStyle(prop: string) {
return prop === 'display' || prop === 'position';
}
| {
"end_byte": 4701,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/special_cased_styles.ts"
} |
angular/packages/animations/browser/src/render/animation_driver.ts_0_2823 | /**
* @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.dev/license
*/
import {AnimationPlayer, NoopAnimationPlayer} from '@angular/animations';
import {Injectable} from '@angular/core';
import {containsElement, getParentElement, invokeQuery, validateStyleProperty} from './shared';
/**
* @publicApi
*
* `AnimationDriver` implentation for Noop animations
*/
@Injectable()
export class NoopAnimationDriver implements AnimationDriver {
/**
* @returns Whether `prop` is a valid CSS property
*/
validateStyleProperty(prop: string): boolean {
return validateStyleProperty(prop);
}
/**
*
* @returns Whether elm1 contains elm2.
*/
containsElement(elm1: any, elm2: any): boolean {
return containsElement(elm1, elm2);
}
/**
* @returns Rhe parent of the given element or `null` if the element is the `document`
*/
getParentElement(element: unknown): unknown {
return getParentElement(element);
}
/**
* @returns The result of the query selector on the element. The array will contain up to 1 item
* if `multi` is `false`.
*/
query(element: any, selector: string, multi: boolean): any[] {
return invokeQuery(element, selector, multi);
}
/**
* @returns The `defaultValue` or empty string
*/
computeStyle(element: any, prop: string, defaultValue?: string): string {
return defaultValue || '';
}
/**
* @returns An `NoopAnimationPlayer`
*/
animate(
element: any,
keyframes: Array<Map<string, string | number>>,
duration: number,
delay: number,
easing: string,
previousPlayers: any[] = [],
scrubberAccessRequested?: boolean,
): AnimationPlayer {
return new NoopAnimationPlayer(duration, delay);
}
}
/**
* @publicApi
*/
export abstract class AnimationDriver {
/**
* @deprecated Use the NoopAnimationDriver class.
*/
static NOOP: AnimationDriver = /* @__PURE__ */ new NoopAnimationDriver();
abstract validateStyleProperty(prop: string): boolean;
abstract validateAnimatableStyleProperty?: (prop: string) => boolean;
abstract containsElement(elm1: any, elm2: any): boolean;
/**
* Obtains the parent element, if any. `null` is returned if the element does not have a parent.
*/
abstract getParentElement(element: unknown): unknown;
abstract query(element: any, selector: string, multi: boolean): any[];
abstract computeStyle(element: any, prop: string, defaultValue?: string): string;
abstract animate(
element: any,
keyframes: Array<Map<string, string | number>>,
duration: number,
delay: number,
easing?: string | null,
previousPlayers?: any[],
scrubberAccessRequested?: boolean,
): any;
}
| {
"end_byte": 2823,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/animation_driver.ts"
} |
angular/packages/animations/browser/src/render/animation_engine_instruction.ts_0_397 | /**
* @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.dev/license
*/
export const enum AnimationTransitionInstructionType {
TransitionAnimation,
TimelineAnimation,
}
export interface AnimationEngineInstruction {
type: AnimationTransitionInstructionType;
}
| {
"end_byte": 397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/animation_engine_instruction.ts"
} |
angular/packages/animations/browser/src/render/shared.ts_0_6521 | /**
* @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.dev/license
*/
import {
AnimationEvent,
AnimationPlayer,
AUTO_STYLE,
NoopAnimationPlayer,
ɵAnimationGroupPlayer,
ɵPRE_STYLE as PRE_STYLE,
ɵStyleDataMap,
} from '@angular/animations';
import {AnimationStyleNormalizer} from '../../src/dsl/style_normalization/animation_style_normalizer';
import {animationFailed} from '../error_helpers';
import {ANIMATABLE_PROP_SET} from './web_animations/animatable_props_set';
export function optimizeGroupPlayer(players: AnimationPlayer[]): AnimationPlayer {
switch (players.length) {
case 0:
return new NoopAnimationPlayer();
case 1:
return players[0];
default:
return new ɵAnimationGroupPlayer(players);
}
}
export function normalizeKeyframes(
normalizer: AnimationStyleNormalizer,
keyframes: Array<ɵStyleDataMap>,
preStyles: ɵStyleDataMap = new Map(),
postStyles: ɵStyleDataMap = new Map(),
): Array<ɵStyleDataMap> {
const errors: Error[] = [];
const normalizedKeyframes: Array<ɵStyleDataMap> = [];
let previousOffset = -1;
let previousKeyframe: ɵStyleDataMap | null = null;
keyframes.forEach((kf) => {
const offset = kf.get('offset') as number;
const isSameOffset = offset == previousOffset;
const normalizedKeyframe: ɵStyleDataMap = (isSameOffset && previousKeyframe) || new Map();
kf.forEach((val, prop) => {
let normalizedProp = prop;
let normalizedValue = val;
if (prop !== 'offset') {
normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);
switch (normalizedValue) {
case PRE_STYLE:
normalizedValue = preStyles.get(prop)!;
break;
case AUTO_STYLE:
normalizedValue = postStyles.get(prop)!;
break;
default:
normalizedValue = normalizer.normalizeStyleValue(
prop,
normalizedProp,
normalizedValue,
errors,
);
break;
}
}
normalizedKeyframe.set(normalizedProp, normalizedValue);
});
if (!isSameOffset) {
normalizedKeyframes.push(normalizedKeyframe);
}
previousKeyframe = normalizedKeyframe;
previousOffset = offset;
});
if (errors.length) {
throw animationFailed(errors);
}
return normalizedKeyframes;
}
export function listenOnPlayer(
player: AnimationPlayer,
eventName: string,
event: AnimationEvent | undefined,
callback: (event: any) => any,
) {
switch (eventName) {
case 'start':
player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));
break;
case 'done':
player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));
break;
case 'destroy':
player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));
break;
}
}
export function copyAnimationEvent(
e: AnimationEvent,
phaseName: string,
player: AnimationPlayer,
): AnimationEvent {
const totalTime = player.totalTime;
const disabled = (player as any).disabled ? true : false;
const event = makeAnimationEvent(
e.element,
e.triggerName,
e.fromState,
e.toState,
phaseName || e.phaseName,
totalTime == undefined ? e.totalTime : totalTime,
disabled,
);
const data = (e as any)['_data'];
if (data != null) {
(event as any)['_data'] = data;
}
return event;
}
export function makeAnimationEvent(
element: any,
triggerName: string,
fromState: string,
toState: string,
phaseName: string = '',
totalTime: number = 0,
disabled?: boolean,
): AnimationEvent {
return {element, triggerName, fromState, toState, phaseName, totalTime, disabled: !!disabled};
}
export function getOrSetDefaultValue<T, V>(map: Map<T, V>, key: T, defaultValue: V) {
let value = map.get(key);
if (!value) {
map.set(key, (value = defaultValue));
}
return value;
}
export function parseTimelineCommand(command: string): [string, string] {
const separatorPos = command.indexOf(':');
const id = command.substring(1, separatorPos);
const action = command.slice(separatorPos + 1);
return [id, action];
}
const documentElement: HTMLElement | null = /* @__PURE__ */ (() =>
typeof document === 'undefined' ? null : document.documentElement)();
export function getParentElement(element: any): unknown | null {
const parent = element.parentNode || element.host || null; // consider host to support shadow DOM
if (parent === documentElement) {
return null;
}
return parent;
}
function containsVendorPrefix(prop: string): boolean {
// Webkit is the only real popular vendor prefix nowadays
// cc: http://shouldiprefix.com/
return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit
}
let _CACHED_BODY: {style: any} | null = null;
let _IS_WEBKIT = false;
export function validateStyleProperty(prop: string): boolean {
if (!_CACHED_BODY) {
_CACHED_BODY = getBodyNode() || {};
_IS_WEBKIT = _CACHED_BODY!.style ? 'WebkitAppearance' in _CACHED_BODY!.style : false;
}
let result = true;
if (_CACHED_BODY!.style && !containsVendorPrefix(prop)) {
result = prop in _CACHED_BODY!.style;
if (!result && _IS_WEBKIT) {
const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.slice(1);
result = camelProp in _CACHED_BODY!.style;
}
}
return result;
}
export function validateWebAnimatableStyleProperty(prop: string): boolean {
return ANIMATABLE_PROP_SET.has(prop);
}
export function getBodyNode(): any | null {
if (typeof document != 'undefined') {
return document.body;
}
return null;
}
export function containsElement(elm1: any, elm2: any): boolean {
while (elm2) {
if (elm2 === elm1) {
return true;
}
elm2 = getParentElement(elm2);
}
return false;
}
export function invokeQuery(element: any, selector: string, multi: boolean): any[] {
if (multi) {
return Array.from(element.querySelectorAll(selector));
}
const elem = element.querySelector(selector);
return elem ? [elem] : [];
}
export function hypenatePropsKeys(original: ɵStyleDataMap): ɵStyleDataMap {
const newMap: ɵStyleDataMap = new Map();
original.forEach((val, prop) => {
const newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');
newMap.set(newProp, val);
});
return newMap;
}
| {
"end_byte": 6521,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/shared.ts"
} |
angular/packages/animations/browser/src/render/animation_engine_next.ts_0_4507 | /**
* @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.dev/license
*/
import {AnimationMetadata, AnimationPlayer, AnimationTriggerMetadata} from '@angular/animations';
import {TriggerAst} from '../dsl/animation_ast';
import {buildAnimationAst} from '../dsl/animation_ast_builder';
import {AnimationTrigger, buildTrigger} from '../dsl/animation_trigger';
import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer';
import {triggerBuildFailed} from '../error_helpers';
import {warnTriggerBuild} from '../warning_helpers';
import {AnimationDriver} from './animation_driver';
import {parseTimelineCommand} from './shared';
import {TimelineAnimationEngine} from './timeline_animation_engine';
import {TransitionAnimationEngine} from './transition_animation_engine';
export class AnimationEngine {
private _transitionEngine: TransitionAnimationEngine;
private _timelineEngine: TimelineAnimationEngine;
private _triggerCache: {[key: string]: AnimationTrigger} = {};
// this method is designed to be overridden by the code that uses this engine
public onRemovalComplete = (element: any, context: any) => {};
constructor(
doc: Document,
private _driver: AnimationDriver,
private _normalizer: AnimationStyleNormalizer,
) {
this._transitionEngine = new TransitionAnimationEngine(doc.body, _driver, _normalizer);
this._timelineEngine = new TimelineAnimationEngine(doc.body, _driver, _normalizer);
this._transitionEngine.onRemovalComplete = (element: any, context: any) =>
this.onRemovalComplete(element, context);
}
registerTrigger(
componentId: string,
namespaceId: string,
hostElement: any,
name: string,
metadata: AnimationTriggerMetadata,
): void {
const cacheKey = componentId + '-' + name;
let trigger = this._triggerCache[cacheKey];
if (!trigger) {
const errors: Error[] = [];
const warnings: string[] = [];
const ast = buildAnimationAst(
this._driver,
metadata as AnimationMetadata,
errors,
warnings,
) as TriggerAst;
if (errors.length) {
throw triggerBuildFailed(name, errors);
}
if (warnings.length) {
warnTriggerBuild(name, warnings);
}
trigger = buildTrigger(name, ast, this._normalizer);
this._triggerCache[cacheKey] = trigger;
}
this._transitionEngine.registerTrigger(namespaceId, name, trigger);
}
register(namespaceId: string, hostElement: any) {
this._transitionEngine.register(namespaceId, hostElement);
}
destroy(namespaceId: string, context: any) {
this._transitionEngine.destroy(namespaceId, context);
}
onInsert(namespaceId: string, element: any, parent: any, insertBefore: boolean): void {
this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);
}
onRemove(namespaceId: string, element: any, context: any): void {
this._transitionEngine.removeNode(namespaceId, element, context);
}
disableAnimations(element: any, disable: boolean) {
this._transitionEngine.markElementAsDisabled(element, disable);
}
process(namespaceId: string, element: any, property: string, value: any) {
if (property.charAt(0) == '@') {
const [id, action] = parseTimelineCommand(property);
const args = value as any[];
this._timelineEngine.command(id, element, action, args);
} else {
this._transitionEngine.trigger(namespaceId, element, property, value);
}
}
listen(
namespaceId: string,
element: any,
eventName: string,
eventPhase: string,
callback: (event: any) => any,
): () => any {
// @@listen
if (eventName.charAt(0) == '@') {
const [id, action] = parseTimelineCommand(eventName);
return this._timelineEngine.listen(id, element, action, callback);
}
return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);
}
flush(microtaskId: number = -1): void {
this._transitionEngine.flush(microtaskId);
}
get players(): AnimationPlayer[] {
return [...this._transitionEngine.players, ...this._timelineEngine.players];
}
whenRenderingDone(): Promise<any> {
return this._transitionEngine.whenRenderingDone();
}
afterFlushAnimationsDone(cb: VoidFunction): void {
this._transitionEngine.afterFlushAnimationsDone(cb);
}
}
| {
"end_byte": 4507,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/animation_engine_next.ts"
} |
angular/packages/animations/browser/src/render/animation_renderer.ts_0_4533 | /**
* @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.dev/license
*/
import {AnimationTriggerMetadata} from '@angular/animations';
import type {NgZone, Renderer2, RendererFactory2, RendererType2} from '@angular/core';
import {AnimationEngine} from './animation_engine_next';
import {AnimationRenderer, BaseAnimationRenderer} from './renderer';
// Define a recursive type to allow for nested arrays of `AnimationTriggerMetadata`. Note that an
// interface declaration is used as TypeScript prior to 3.7 does not support recursive type
// references, see https://github.com/microsoft/TypeScript/pull/33050 for details.
type NestedAnimationTriggerMetadata = AnimationTriggerMetadata | RecursiveAnimationTriggerMetadata;
interface RecursiveAnimationTriggerMetadata extends Array<NestedAnimationTriggerMetadata> {}
export class AnimationRendererFactory implements RendererFactory2 {
private _currentId: number = 0;
private _microtaskId: number = 1;
private _animationCallbacksBuffer: [(e: any) => any, any][] = [];
private _rendererCache = new Map<Renderer2, BaseAnimationRenderer>();
private _cdRecurDepth = 0;
constructor(
private delegate: RendererFactory2,
private engine: AnimationEngine,
private _zone: NgZone,
) {
engine.onRemovalComplete = (element: any, delegate: Renderer2 | null) => {
delegate?.removeChild(null, element);
};
}
createRenderer(hostElement: any, type: RendererType2): BaseAnimationRenderer {
const EMPTY_NAMESPACE_ID = '';
// cache the delegates to find out which cached delegate can
// be used by which cached renderer
const delegate = this.delegate.createRenderer(hostElement, type);
if (!hostElement || !type?.data?.['animation']) {
const cache = this._rendererCache;
let renderer: BaseAnimationRenderer | undefined = cache.get(delegate);
if (!renderer) {
// Ensure that the renderer is removed from the cache on destroy
// since it may contain references to detached DOM nodes.
const onRendererDestroy = () => cache.delete(delegate);
renderer = new BaseAnimationRenderer(
EMPTY_NAMESPACE_ID,
delegate,
this.engine,
onRendererDestroy,
);
// only cache this result when the base renderer is used
cache.set(delegate, renderer);
}
return renderer;
}
const componentId = type.id;
const namespaceId = type.id + '-' + this._currentId;
this._currentId++;
this.engine.register(namespaceId, hostElement);
const registerTrigger = (trigger: NestedAnimationTriggerMetadata) => {
if (Array.isArray(trigger)) {
trigger.forEach(registerTrigger);
} else {
this.engine.registerTrigger(componentId, namespaceId, hostElement, trigger.name, trigger);
}
};
const animationTriggers = type.data['animation'] as NestedAnimationTriggerMetadata[];
animationTriggers.forEach(registerTrigger);
return new AnimationRenderer(this, namespaceId, delegate, this.engine);
}
begin() {
this._cdRecurDepth++;
if (this.delegate.begin) {
this.delegate.begin();
}
}
private _scheduleCountTask() {
queueMicrotask(() => {
this._microtaskId++;
});
}
/** @internal */
scheduleListenerCallback(count: number, fn: (e: any) => any, data: any) {
if (count >= 0 && count < this._microtaskId) {
this._zone.run(() => fn(data));
return;
}
const animationCallbacksBuffer = this._animationCallbacksBuffer;
if (animationCallbacksBuffer.length == 0) {
queueMicrotask(() => {
this._zone.run(() => {
animationCallbacksBuffer.forEach((tuple) => {
const [fn, data] = tuple;
fn(data);
});
this._animationCallbacksBuffer = [];
});
});
}
animationCallbacksBuffer.push([fn, data]);
}
end() {
this._cdRecurDepth--;
// this is to prevent animations from running twice when an inner
// component does CD when a parent component instead has inserted it
if (this._cdRecurDepth == 0) {
this._zone.runOutsideAngular(() => {
this._scheduleCountTask();
this.engine.flush(this._microtaskId);
});
}
if (this.delegate.end) {
this.delegate.end();
}
}
whenRenderingDone(): Promise<any> {
return this.engine.whenRenderingDone();
}
}
| {
"end_byte": 4533,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/animation_renderer.ts"
} |
angular/packages/animations/browser/src/render/transition_animation_engine.ts_0_3854 | /**
* @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.dev/license
*/
import {
AnimationOptions,
AnimationPlayer,
AUTO_STYLE,
NoopAnimationPlayer,
ɵAnimationGroupPlayer as AnimationGroupPlayer,
ɵPRE_STYLE as PRE_STYLE,
ɵStyleDataMap,
} from '@angular/animations';
import {ɵWritable as Writable} from '@angular/core';
import {AnimationTimelineInstruction} from '../dsl/animation_timeline_instruction';
import {AnimationTransitionFactory} from '../dsl/animation_transition_factory';
import {AnimationTransitionInstruction} from '../dsl/animation_transition_instruction';
import {AnimationTrigger} from '../dsl/animation_trigger';
import {ElementInstructionMap} from '../dsl/element_instruction_map';
import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer';
import {
missingEvent,
missingTrigger,
transitionFailed,
triggerTransitionsFailed,
unregisteredTrigger,
unsupportedTriggerEvent,
} from '../error_helpers';
import {
ENTER_CLASSNAME,
eraseStyles,
LEAVE_CLASSNAME,
NG_ANIMATING_CLASSNAME,
NG_ANIMATING_SELECTOR,
NG_TRIGGER_CLASSNAME,
NG_TRIGGER_SELECTOR,
setStyles,
} from '../util';
import {AnimationDriver} from './animation_driver';
import {
getOrSetDefaultValue,
listenOnPlayer,
makeAnimationEvent,
normalizeKeyframes,
optimizeGroupPlayer,
} from './shared';
const QUEUED_CLASSNAME = 'ng-animate-queued';
const QUEUED_SELECTOR = '.ng-animate-queued';
const DISABLED_CLASSNAME = 'ng-animate-disabled';
const DISABLED_SELECTOR = '.ng-animate-disabled';
const STAR_CLASSNAME = 'ng-star-inserted';
const STAR_SELECTOR = '.ng-star-inserted';
const EMPTY_PLAYER_ARRAY: TransitionAnimationPlayer[] = [];
const NULL_REMOVAL_STATE: ElementAnimationState = {
namespaceId: '',
setForRemoval: false,
setForMove: false,
hasAnimation: false,
removedBeforeQueried: false,
};
const NULL_REMOVED_QUERIED_STATE: ElementAnimationState = {
namespaceId: '',
setForMove: false,
setForRemoval: false,
hasAnimation: false,
removedBeforeQueried: true,
};
interface TriggerListener {
name: string;
phase: string;
callback: (event: any) => any;
}
interface QueueInstruction {
element: any;
triggerName: string;
fromState: StateValue;
toState: StateValue;
transition: AnimationTransitionFactory;
player: TransitionAnimationPlayer;
isFallbackTransition: boolean;
}
const REMOVAL_FLAG = '__ng_removed';
interface ElementAnimationState {
setForRemoval: boolean;
setForMove: boolean;
hasAnimation: boolean;
namespaceId: string;
removedBeforeQueried: boolean;
previousTriggersValues?: Map<string, string>;
}
class StateValue {
public value: string;
public options: AnimationOptions;
get params(): {[key: string]: any} {
return this.options.params as {[key: string]: any};
}
constructor(
input: any,
public namespaceId: string = '',
) {
const isObj = input && input.hasOwnProperty('value');
const value = isObj ? input['value'] : input;
this.value = normalizeTriggerValue(value);
if (isObj) {
// we drop the value property from options.
const {value, ...options} = input;
this.options = options as AnimationOptions;
} else {
this.options = {};
}
if (!this.options.params) {
this.options.params = {};
}
}
absorbOptions(options: AnimationOptions) {
const newParams = options.params;
if (newParams) {
const oldParams = this.options.params!;
Object.keys(newParams).forEach((prop) => {
if (oldParams[prop] == null) {
oldParams[prop] = newParams[prop];
}
});
}
}
}
const VOID_VALUE = 'void';
const DEFAULT_STATE_VALUE = new StateValue(VOID_VALUE);
cl | {
"end_byte": 3854,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts"
} |
angular/packages/animations/browser/src/render/transition_animation_engine.ts_3856_12012 | s AnimationTransitionNamespace {
public players: TransitionAnimationPlayer[] = [];
private _triggers = new Map<string, AnimationTrigger>();
private _queue: QueueInstruction[] = [];
private _elementListeners = new Map<any, TriggerListener[]>();
private _hostClassName: string;
constructor(
public id: string,
public hostElement: any,
private _engine: TransitionAnimationEngine,
) {
this._hostClassName = 'ng-tns-' + id;
addClass(hostElement, this._hostClassName);
}
listen(element: any, name: string, phase: string, callback: (event: any) => boolean): () => any {
if (!this._triggers.has(name)) {
throw missingTrigger(phase, name);
}
if (phase == null || phase.length == 0) {
throw missingEvent(name);
}
if (!isTriggerEventValid(phase)) {
throw unsupportedTriggerEvent(phase, name);
}
const listeners = getOrSetDefaultValue(this._elementListeners, element, []);
const data = {name, phase, callback};
listeners.push(data);
const triggersWithStates = getOrSetDefaultValue(
this._engine.statesByElement,
element,
new Map<string, StateValue>(),
);
if (!triggersWithStates.has(name)) {
addClass(element, NG_TRIGGER_CLASSNAME);
addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);
triggersWithStates.set(name, DEFAULT_STATE_VALUE);
}
return () => {
// the event listener is removed AFTER the flush has occurred such
// that leave animations callbacks can fire (otherwise if the node
// is removed in between then the listeners would be deregistered)
this._engine.afterFlush(() => {
const index = listeners.indexOf(data);
if (index >= 0) {
listeners.splice(index, 1);
}
if (!this._triggers.has(name)) {
triggersWithStates.delete(name);
}
});
};
}
register(name: string, ast: AnimationTrigger): boolean {
if (this._triggers.has(name)) {
// throw
return false;
} else {
this._triggers.set(name, ast);
return true;
}
}
private _getTrigger(name: string) {
const trigger = this._triggers.get(name);
if (!trigger) {
throw unregisteredTrigger(name);
}
return trigger;
}
trigger(
element: any,
triggerName: string,
value: any,
defaultToFallback: boolean = true,
): TransitionAnimationPlayer | undefined {
const trigger = this._getTrigger(triggerName);
const player = new TransitionAnimationPlayer(this.id, triggerName, element);
let triggersWithStates = this._engine.statesByElement.get(element);
if (!triggersWithStates) {
addClass(element, NG_TRIGGER_CLASSNAME);
addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);
this._engine.statesByElement.set(
element,
(triggersWithStates = new Map<string, StateValue>()),
);
}
let fromState = triggersWithStates.get(triggerName);
const toState = new StateValue(value, this.id);
const isObj = value && value.hasOwnProperty('value');
if (!isObj && fromState) {
toState.absorbOptions(fromState.options);
}
triggersWithStates.set(triggerName, toState);
if (!fromState) {
fromState = DEFAULT_STATE_VALUE;
}
const isRemoval = toState.value === VOID_VALUE;
// normally this isn't reached by here, however, if an object expression
// is passed in then it may be a new object each time. Comparing the value
// is important since that will stay the same despite there being a new object.
// The removal arc here is special cased because the same element is triggered
// twice in the event that it contains animations on the outer/inner portions
// of the host container
if (!isRemoval && fromState.value === toState.value) {
// this means that despite the value not changing, some inner params
// have changed which means that the animation final styles need to be applied
if (!objEquals(fromState.params, toState.params)) {
const errors: Error[] = [];
const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);
const toStyles = trigger.matchStyles(toState.value, toState.params, errors);
if (errors.length) {
this._engine.reportError(errors);
} else {
this._engine.afterFlush(() => {
eraseStyles(element, fromStyles);
setStyles(element, toStyles);
});
}
}
return;
}
const playersOnElement: TransitionAnimationPlayer[] = getOrSetDefaultValue(
this._engine.playersByElement,
element,
[],
);
playersOnElement.forEach((player) => {
// only remove the player if it is queued on the EXACT same trigger/namespace
// we only also deal with queued players here because if the animation has
// started then we want to keep the player alive until the flush happens
// (which is where the previousPlayers are passed into the new player)
if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {
player.destroy();
}
});
let transition = trigger.matchTransition(
fromState.value,
toState.value,
element,
toState.params,
);
let isFallbackTransition = false;
if (!transition) {
if (!defaultToFallback) return;
transition = trigger.fallbackTransition;
isFallbackTransition = true;
}
this._engine.totalQueuedPlayers++;
this._queue.push({
element,
triggerName,
transition,
fromState,
toState,
player,
isFallbackTransition,
});
if (!isFallbackTransition) {
addClass(element, QUEUED_CLASSNAME);
player.onStart(() => {
removeClass(element, QUEUED_CLASSNAME);
});
}
player.onDone(() => {
let index = this.players.indexOf(player);
if (index >= 0) {
this.players.splice(index, 1);
}
const players = this._engine.playersByElement.get(element);
if (players) {
let index = players.indexOf(player);
if (index >= 0) {
players.splice(index, 1);
}
}
});
this.players.push(player);
playersOnElement.push(player);
return player;
}
deregister(name: string) {
this._triggers.delete(name);
this._engine.statesByElement.forEach((stateMap) => stateMap.delete(name));
this._elementListeners.forEach((listeners, element) => {
this._elementListeners.set(
element,
listeners.filter((entry) => {
return entry.name != name;
}),
);
});
}
clearElementCache(element: any) {
this._engine.statesByElement.delete(element);
this._elementListeners.delete(element);
const elementPlayers = this._engine.playersByElement.get(element);
if (elementPlayers) {
elementPlayers.forEach((player) => player.destroy());
this._engine.playersByElement.delete(element);
}
}
private _signalRemovalForInnerTriggers(rootElement: any, context: any) {
const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);
// emulate a leave animation for all inner nodes within this node.
// If there are no animations found for any of the nodes then clear the cache
// for the element.
elements.forEach((elm) => {
// this means that an inner remove() operation has already kicked off
// the animation on this element...
if (elm[REMOVAL_FLAG]) return;
const namespaces = this._engine.fetchNamespacesByElement(elm);
if (namespaces.size) {
namespaces.forEach((ns) => ns.triggerLeaveAnimation(elm, context, false, true));
} else {
this.clearElementCache(elm);
}
});
// If the child elements were removed along with the parent, their animations might not
// have completed. Clear all the elements from the cache so we don't end up with a memory leak.
this._engine.afterFlushAnimationsDone(() =>
elements.forEach((elm) => this.clearElementCache(elm)),
);
}
| {
"end_byte": 12012,
"start_byte": 3856,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts"
} |
angular/packages/animations/browser/src/render/transition_animation_engine.ts_12016_18664 | gerLeaveAnimation(
element: any,
context: any,
destroyAfterComplete?: boolean,
defaultToFallback?: boolean,
): boolean {
const triggerStates = this._engine.statesByElement.get(element);
const previousTriggersValues = new Map<string, string>();
if (triggerStates) {
const players: TransitionAnimationPlayer[] = [];
triggerStates.forEach((state, triggerName) => {
previousTriggersValues.set(triggerName, state.value);
// this check is here in the event that an element is removed
// twice (both on the host level and the component level)
if (this._triggers.has(triggerName)) {
const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);
if (player) {
players.push(player);
}
}
});
if (players.length) {
this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);
if (destroyAfterComplete) {
optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));
}
return true;
}
}
return false;
}
prepareLeaveAnimationListeners(element: any) {
const listeners = this._elementListeners.get(element);
const elementStates = this._engine.statesByElement.get(element);
// if this statement fails then it means that the element was picked up
// by an earlier flush (or there are no listeners at all to track the leave).
if (listeners && elementStates) {
const visitedTriggers = new Set<string>();
listeners.forEach((listener) => {
const triggerName = listener.name;
if (visitedTriggers.has(triggerName)) return;
visitedTriggers.add(triggerName);
const trigger = this._triggers.get(triggerName)!;
const transition = trigger.fallbackTransition;
const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;
const toState = new StateValue(VOID_VALUE);
const player = new TransitionAnimationPlayer(this.id, triggerName, element);
this._engine.totalQueuedPlayers++;
this._queue.push({
element,
triggerName,
transition,
fromState,
toState,
player,
isFallbackTransition: true,
});
});
}
}
removeNode(element: any, context: any): void {
const engine = this._engine;
if (element.childElementCount) {
this._signalRemovalForInnerTriggers(element, context);
}
// this means that a * => VOID animation was detected and kicked off
if (this.triggerLeaveAnimation(element, context, true)) return;
// find the player that is animating and make sure that the
// removal is delayed until that player has completed
let containsPotentialParentTransition = false;
if (engine.totalAnimations) {
const currentPlayers = engine.players.length
? engine.playersByQueriedElement.get(element)
: [];
// when this `if statement` does not continue forward it means that
// a previous animation query has selected the current element and
// is animating it. In this situation want to continue forwards and
// allow the element to be queued up for animation later.
if (currentPlayers && currentPlayers.length) {
containsPotentialParentTransition = true;
} else {
let parent = element;
while ((parent = parent.parentNode)) {
const triggers = engine.statesByElement.get(parent);
if (triggers) {
containsPotentialParentTransition = true;
break;
}
}
}
}
// at this stage we know that the element will either get removed
// during flush or will be picked up by a parent query. Either way
// we need to fire the listeners for this element when it DOES get
// removed (once the query parent animation is done or after flush)
this.prepareLeaveAnimationListeners(element);
// whether or not a parent has an animation we need to delay the deferral of the leave
// operation until we have more information (which we do after flush() has been called)
if (containsPotentialParentTransition) {
engine.markElementAsRemoved(this.id, element, false, context);
} else {
const removalFlag = element[REMOVAL_FLAG];
if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {
// we do this after the flush has occurred such
// that the callbacks can be fired
engine.afterFlush(() => this.clearElementCache(element));
engine.destroyInnerAnimations(element);
engine._onRemovalComplete(element, context);
}
}
}
insertNode(element: any, parent: any): void {
addClass(element, this._hostClassName);
}
drainQueuedTransitions(microtaskId: number): QueueInstruction[] {
const instructions: QueueInstruction[] = [];
this._queue.forEach((entry) => {
const player = entry.player;
if (player.destroyed) return;
const element = entry.element;
const listeners = this._elementListeners.get(element);
if (listeners) {
listeners.forEach((listener: TriggerListener) => {
if (listener.name == entry.triggerName) {
const baseEvent = makeAnimationEvent(
element,
entry.triggerName,
entry.fromState.value,
entry.toState.value,
);
(baseEvent as any)['_data'] = microtaskId;
listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);
}
});
}
if (player.markedForDestroy) {
this._engine.afterFlush(() => {
// now we can destroy the element properly since the event listeners have
// been bound to the player
player.destroy();
});
} else {
instructions.push(entry);
}
});
this._queue = [];
return instructions.sort((a, b) => {
// if depCount == 0 them move to front
// otherwise if a contains b then move back
const d0 = a.transition.ast.depCount;
const d1 = b.transition.ast.depCount;
if (d0 == 0 || d1 == 0) {
return d0 - d1;
}
return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;
});
}
destroy(context: any) {
this.players.forEach((p) => p.destroy());
this._signalRemovalForInnerTriggers(this.hostElement, context);
}
}
interface QueuedTransition {
element: any;
instruction: AnimationTransitionInstruction;
player: TransitionAnimationPlayer;
}
ex | {
"end_byte": 18664,
"start_byte": 12016,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts"
} |
angular/packages/animations/browser/src/render/transition_animation_engine.ts_18666_27403 | rt class TransitionAnimationEngine {
public players: TransitionAnimationPlayer[] = [];
public newHostElements = new Map<any, AnimationTransitionNamespace>();
public playersByElement = new Map<any, TransitionAnimationPlayer[]>();
public playersByQueriedElement = new Map<any, TransitionAnimationPlayer[]>();
public statesByElement = new Map<any, Map<string, StateValue>>();
public disabledNodes = new Set<any>();
public totalAnimations = 0;
public totalQueuedPlayers = 0;
private _namespaceLookup: {[id: string]: AnimationTransitionNamespace} = {};
private _namespaceList: AnimationTransitionNamespace[] = [];
private _flushFns: (() => any)[] = [];
private _whenQuietFns: (() => any)[] = [];
public namespacesByHostElement = new Map<any, AnimationTransitionNamespace>();
public collectedEnterElements: any[] = [];
public collectedLeaveElements: any[] = [];
// this method is designed to be overridden by the code that uses this engine
public onRemovalComplete = (element: any, context: any) => {};
/** @internal */
_onRemovalComplete(element: any, context: any) {
this.onRemovalComplete(element, context);
}
constructor(
public bodyNode: any,
public driver: AnimationDriver,
private _normalizer: AnimationStyleNormalizer,
) {}
get queuedPlayers(): TransitionAnimationPlayer[] {
const players: TransitionAnimationPlayer[] = [];
this._namespaceList.forEach((ns) => {
ns.players.forEach((player) => {
if (player.queued) {
players.push(player);
}
});
});
return players;
}
createNamespace(namespaceId: string, hostElement: any) {
const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);
if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {
this._balanceNamespaceList(ns, hostElement);
} else {
// defer this later until flush during when the host element has
// been inserted so that we know exactly where to place it in
// the namespace list
this.newHostElements.set(hostElement, ns);
// given that this host element is a part of the animation code, it
// may or may not be inserted by a parent node that is of an
// animation renderer type. If this happens then we can still have
// access to this item when we query for :enter nodes. If the parent
// is a renderer then the set data-structure will normalize the entry
this.collectEnterElement(hostElement);
}
return (this._namespaceLookup[namespaceId] = ns);
}
private _balanceNamespaceList(ns: AnimationTransitionNamespace, hostElement: any) {
const namespaceList = this._namespaceList;
const namespacesByHostElement = this.namespacesByHostElement;
const limit = namespaceList.length - 1;
if (limit >= 0) {
let found = false;
// Find the closest ancestor with an existing namespace so we can then insert `ns` after it,
// establishing a top-down ordering of namespaces in `this._namespaceList`.
let ancestor = this.driver.getParentElement(hostElement);
while (ancestor) {
const ancestorNs = namespacesByHostElement.get(ancestor);
if (ancestorNs) {
// An animation namespace has been registered for this ancestor, so we insert `ns`
// right after it to establish top-down ordering of animation namespaces.
const index = namespaceList.indexOf(ancestorNs);
namespaceList.splice(index + 1, 0, ns);
found = true;
break;
}
ancestor = this.driver.getParentElement(ancestor);
}
if (!found) {
// No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to
// ensure that any existing descendants are ordered after `ns`, retaining the desired
// top-down ordering.
namespaceList.unshift(ns);
}
} else {
namespaceList.push(ns);
}
namespacesByHostElement.set(hostElement, ns);
return ns;
}
register(namespaceId: string, hostElement: any) {
let ns = this._namespaceLookup[namespaceId];
if (!ns) {
ns = this.createNamespace(namespaceId, hostElement);
}
return ns;
}
registerTrigger(namespaceId: string, name: string, trigger: AnimationTrigger) {
let ns = this._namespaceLookup[namespaceId];
if (ns && ns.register(name, trigger)) {
this.totalAnimations++;
}
}
destroy(namespaceId: string, context: any) {
if (!namespaceId) return;
this.afterFlush(() => {});
this.afterFlushAnimationsDone(() => {
const ns = this._fetchNamespace(namespaceId);
this.namespacesByHostElement.delete(ns.hostElement);
const index = this._namespaceList.indexOf(ns);
if (index >= 0) {
this._namespaceList.splice(index, 1);
}
ns.destroy(context);
delete this._namespaceLookup[namespaceId];
});
}
private _fetchNamespace(id: string) {
return this._namespaceLookup[id];
}
fetchNamespacesByElement(element: any): Set<AnimationTransitionNamespace> {
// normally there should only be one namespace per element, however
// if @triggers are placed on both the component element and then
// its host element (within the component code) then there will be
// two namespaces returned. We use a set here to simply deduplicate
// the namespaces in case (for the reason described above) there are multiple triggers
const namespaces = new Set<AnimationTransitionNamespace>();
const elementStates = this.statesByElement.get(element);
if (elementStates) {
for (let stateValue of elementStates.values()) {
if (stateValue.namespaceId) {
const ns = this._fetchNamespace(stateValue.namespaceId);
if (ns) {
namespaces.add(ns);
}
}
}
}
return namespaces;
}
trigger(namespaceId: string, element: any, name: string, value: any): boolean {
if (isElementNode(element)) {
const ns = this._fetchNamespace(namespaceId);
if (ns) {
ns.trigger(element, name, value);
return true;
}
}
return false;
}
insertNode(namespaceId: string, element: any, parent: any, insertBefore: boolean): void {
if (!isElementNode(element)) return;
// special case for when an element is removed and reinserted (move operation)
// when this occurs we do not want to use the element for deletion later
const details = element[REMOVAL_FLAG] as ElementAnimationState;
if (details && details.setForRemoval) {
details.setForRemoval = false;
details.setForMove = true;
const index = this.collectedLeaveElements.indexOf(element);
if (index >= 0) {
this.collectedLeaveElements.splice(index, 1);
}
}
// in the event that the namespaceId is blank then the caller
// code does not contain any animation code in it, but it is
// just being called so that the node is marked as being inserted
if (namespaceId) {
const ns = this._fetchNamespace(namespaceId);
// This if-statement is a workaround for router issue #21947.
// The router sometimes hits a race condition where while a route
// is being instantiated a new navigation arrives, triggering leave
// animation of DOM that has not been fully initialized, until this
// is resolved, we need to handle the scenario when DOM is not in a
// consistent state during the animation.
if (ns) {
ns.insertNode(element, parent);
}
}
// only *directives and host elements are inserted before
if (insertBefore) {
this.collectEnterElement(element);
}
}
collectEnterElement(element: any) {
this.collectedEnterElements.push(element);
}
markElementAsDisabled(element: any, value: boolean) {
if (value) {
if (!this.disabledNodes.has(element)) {
this.disabledNodes.add(element);
addClass(element, DISABLED_CLASSNAME);
}
} else if (this.disabledNodes.has(element)) {
this.disabledNodes.delete(element);
removeClass(element, DISABLED_CLASSNAME);
}
}
removeNode(namespaceId: string, element: any, context: any): void {
if (isElementNode(element)) {
const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;
if (ns) {
ns.removeNode(element, context);
} else {
this.markElementAsRemoved(namespaceId, element, false, context);
}
const hostNS = this.namespacesByHostElement.get(element);
if (hostNS && hostNS.id !== namespaceId) {
hostNS.removeNode(element, context);
}
} else {
this._onRemovalComplete(element, context);
}
}
| {
"end_byte": 27403,
"start_byte": 18666,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts"
} |
angular/packages/animations/browser/src/render/transition_animation_engine.ts_27407_32728 | ElementAsRemoved(
namespaceId: string,
element: any,
hasAnimation?: boolean,
context?: any,
previousTriggersValues?: Map<string, string>,
) {
this.collectedLeaveElements.push(element);
element[REMOVAL_FLAG] = {
namespaceId,
setForRemoval: context,
hasAnimation,
removedBeforeQueried: false,
previousTriggersValues,
};
}
listen(
namespaceId: string,
element: any,
name: string,
phase: string,
callback: (event: any) => boolean,
): () => any {
if (isElementNode(element)) {
return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);
}
return () => {};
}
private _buildInstruction(
entry: QueueInstruction,
subTimelines: ElementInstructionMap,
enterClassName: string,
leaveClassName: string,
skipBuildAst?: boolean,
) {
return entry.transition.build(
this.driver,
entry.element,
entry.fromState.value,
entry.toState.value,
enterClassName,
leaveClassName,
entry.fromState.options,
entry.toState.options,
subTimelines,
skipBuildAst,
);
}
destroyInnerAnimations(containerElement: any) {
let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);
elements.forEach((element) => this.destroyActiveAnimationsForElement(element));
if (this.playersByQueriedElement.size == 0) return;
elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);
elements.forEach((element) => this.finishActiveQueriedAnimationOnElement(element));
}
destroyActiveAnimationsForElement(element: any) {
const players = this.playersByElement.get(element);
if (players) {
players.forEach((player) => {
// special case for when an element is set for destruction, but hasn't started.
// in this situation we want to delay the destruction until the flush occurs
// so that any event listeners attached to the player are triggered.
if (player.queued) {
player.markedForDestroy = true;
} else {
player.destroy();
}
});
}
}
finishActiveQueriedAnimationOnElement(element: any) {
const players = this.playersByQueriedElement.get(element);
if (players) {
players.forEach((player) => player.finish());
}
}
whenRenderingDone(): Promise<any> {
return new Promise<void>((resolve) => {
if (this.players.length) {
return optimizeGroupPlayer(this.players).onDone(() => resolve());
} else {
resolve();
}
});
}
processLeaveNode(element: any) {
const details = element[REMOVAL_FLAG] as ElementAnimationState;
if (details && details.setForRemoval) {
// this will prevent it from removing it twice
element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;
if (details.namespaceId) {
this.destroyInnerAnimations(element);
const ns = this._fetchNamespace(details.namespaceId);
if (ns) {
ns.clearElementCache(element);
}
}
this._onRemovalComplete(element, details.setForRemoval);
}
if (element.classList?.contains(DISABLED_CLASSNAME)) {
this.markElementAsDisabled(element, false);
}
this.driver.query(element, DISABLED_SELECTOR, true).forEach((node) => {
this.markElementAsDisabled(node, false);
});
}
flush(microtaskId: number = -1) {
let players: AnimationPlayer[] = [];
if (this.newHostElements.size) {
this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));
this.newHostElements.clear();
}
if (this.totalAnimations && this.collectedEnterElements.length) {
for (let i = 0; i < this.collectedEnterElements.length; i++) {
const elm = this.collectedEnterElements[i];
addClass(elm, STAR_CLASSNAME);
}
}
if (
this._namespaceList.length &&
(this.totalQueuedPlayers || this.collectedLeaveElements.length)
) {
const cleanupFns: Function[] = [];
try {
players = this._flushAnimations(cleanupFns, microtaskId);
} finally {
for (let i = 0; i < cleanupFns.length; i++) {
cleanupFns[i]();
}
}
} else {
for (let i = 0; i < this.collectedLeaveElements.length; i++) {
const element = this.collectedLeaveElements[i];
this.processLeaveNode(element);
}
}
this.totalQueuedPlayers = 0;
this.collectedEnterElements.length = 0;
this.collectedLeaveElements.length = 0;
this._flushFns.forEach((fn) => fn());
this._flushFns = [];
if (this._whenQuietFns.length) {
// we move these over to a variable so that
// if any new callbacks are registered in another
// flush they do not populate the existing set
const quietFns = this._whenQuietFns;
this._whenQuietFns = [];
if (players.length) {
optimizeGroupPlayer(players).onDone(() => {
quietFns.forEach((fn) => fn());
});
} else {
quietFns.forEach((fn) => fn());
}
}
}
reportError(errors: Error[]) {
throw triggerTransitionsFailed(errors);
}
private _flushAnimations(
cleanupFns: Function[],
microtaskId: number,
): TransitionAnimationPlayer[] {
| {
"end_byte": 32728,
"start_byte": 27407,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts"
} |
angular/packages/animations/browser/src/render/transition_animation_engine.ts_32729_42251 | const subTimelines = new ElementInstructionMap();
const skippedPlayers: TransitionAnimationPlayer[] = [];
const skippedPlayersMap = new Map<any, AnimationPlayer[]>();
const queuedInstructions: QueuedTransition[] = [];
const queriedElements = new Map<any, TransitionAnimationPlayer[]>();
const allPreStyleElements = new Map<any, Set<string>>();
const allPostStyleElements = new Map<any, Set<string>>();
const disabledElementsSet = new Set<any>();
this.disabledNodes.forEach((node) => {
disabledElementsSet.add(node);
const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);
for (let i = 0; i < nodesThatAreDisabled.length; i++) {
disabledElementsSet.add(nodesThatAreDisabled[i]);
}
});
const bodyNode = this.bodyNode;
const allTriggerElements = Array.from(this.statesByElement.keys());
const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);
// this must occur before the instructions are built below such that
// the :enter queries match the elements (since the timeline queries
// are fired during instruction building).
const enterNodeMapIds = new Map<any, string>();
let i = 0;
enterNodeMap.forEach((nodes, root) => {
const className = ENTER_CLASSNAME + i++;
enterNodeMapIds.set(root, className);
nodes.forEach((node) => addClass(node, className));
});
const allLeaveNodes: any[] = [];
const mergedLeaveNodes = new Set<any>();
const leaveNodesWithoutAnimations = new Set<any>();
for (let i = 0; i < this.collectedLeaveElements.length; i++) {
const element = this.collectedLeaveElements[i];
const details = element[REMOVAL_FLAG] as ElementAnimationState;
if (details && details.setForRemoval) {
allLeaveNodes.push(element);
mergedLeaveNodes.add(element);
if (details.hasAnimation) {
this.driver
.query(element, STAR_SELECTOR, true)
.forEach((elm) => mergedLeaveNodes.add(elm));
} else {
leaveNodesWithoutAnimations.add(element);
}
}
}
const leaveNodeMapIds = new Map<any, string>();
const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));
leaveNodeMap.forEach((nodes, root) => {
const className = LEAVE_CLASSNAME + i++;
leaveNodeMapIds.set(root, className);
nodes.forEach((node) => addClass(node, className));
});
cleanupFns.push(() => {
enterNodeMap.forEach((nodes, root) => {
const className = enterNodeMapIds.get(root)!;
nodes.forEach((node) => removeClass(node, className));
});
leaveNodeMap.forEach((nodes, root) => {
const className = leaveNodeMapIds.get(root)!;
nodes.forEach((node) => removeClass(node, className));
});
allLeaveNodes.forEach((element) => {
this.processLeaveNode(element);
});
});
const allPlayers: TransitionAnimationPlayer[] = [];
const erroneousTransitions: AnimationTransitionInstruction[] = [];
for (let i = this._namespaceList.length - 1; i >= 0; i--) {
const ns = this._namespaceList[i];
ns.drainQueuedTransitions(microtaskId).forEach((entry) => {
const player = entry.player;
const element = entry.element;
allPlayers.push(player);
if (this.collectedEnterElements.length) {
const details = element[REMOVAL_FLAG] as ElementAnimationState;
// animations for move operations (elements being removed and reinserted,
// e.g. when the order of an *ngFor list changes) are currently not supported
if (details && details.setForMove) {
if (
details.previousTriggersValues &&
details.previousTriggersValues.has(entry.triggerName)
) {
const previousValue = details.previousTriggersValues.get(entry.triggerName) as string;
// we need to restore the previous trigger value since the element has
// only been moved and hasn't actually left the DOM
const triggersWithStates = this.statesByElement.get(entry.element);
if (triggersWithStates && triggersWithStates.has(entry.triggerName)) {
const state = triggersWithStates.get(entry.triggerName)!;
state.value = previousValue;
triggersWithStates.set(entry.triggerName, state);
}
}
player.destroy();
return;
}
}
const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);
const leaveClassName = leaveNodeMapIds.get(element)!;
const enterClassName = enterNodeMapIds.get(element)!;
const instruction = this._buildInstruction(
entry,
subTimelines,
enterClassName,
leaveClassName,
nodeIsOrphaned,
)!;
if (instruction.errors && instruction.errors.length) {
erroneousTransitions.push(instruction);
return;
}
// even though the element may not be in the DOM, it may still
// be added at a later point (due to the mechanics of content
// projection and/or dynamic component insertion) therefore it's
// important to still style the element.
if (nodeIsOrphaned) {
player.onStart(() => eraseStyles(element, instruction.fromStyles));
player.onDestroy(() => setStyles(element, instruction.toStyles));
skippedPlayers.push(player);
return;
}
// if an unmatched transition is queued and ready to go
// then it SHOULD NOT render an animation and cancel the
// previously running animations.
if (entry.isFallbackTransition) {
player.onStart(() => eraseStyles(element, instruction.fromStyles));
player.onDestroy(() => setStyles(element, instruction.toStyles));
skippedPlayers.push(player);
return;
}
// this means that if a parent animation uses this animation as a sub-trigger
// then it will instruct the timeline builder not to add a player delay, but
// instead stretch the first keyframe gap until the animation starts. This is
// important in order to prevent extra initialization styles from being
// required by the user for the animation.
const timelines: AnimationTimelineInstruction[] = [];
instruction.timelines.forEach((tl) => {
tl.stretchStartingKeyframe = true;
if (!this.disabledNodes.has(tl.element)) {
timelines.push(tl);
}
});
instruction.timelines = timelines;
subTimelines.append(element, instruction.timelines);
const tuple = {instruction, player, element};
queuedInstructions.push(tuple);
instruction.queriedElements.forEach((element) =>
getOrSetDefaultValue(queriedElements, element, []).push(player),
);
instruction.preStyleProps.forEach((stringMap, element) => {
if (stringMap.size) {
let setVal: Set<string> = allPreStyleElements.get(element)!;
if (!setVal) {
allPreStyleElements.set(element, (setVal = new Set<string>()));
}
stringMap.forEach((_, prop) => setVal.add(prop));
}
});
instruction.postStyleProps.forEach((stringMap, element) => {
let setVal: Set<string> = allPostStyleElements.get(element)!;
if (!setVal) {
allPostStyleElements.set(element, (setVal = new Set<string>()));
}
stringMap.forEach((_, prop) => setVal.add(prop));
});
});
}
if (erroneousTransitions.length) {
const errors: Error[] = [];
erroneousTransitions.forEach((instruction) => {
errors.push(transitionFailed(instruction.triggerName, instruction.errors!));
});
allPlayers.forEach((player) => player.destroy());
this.reportError(errors);
}
const allPreviousPlayersMap = new Map<any, TransitionAnimationPlayer[]>();
// this map tells us which element in the DOM tree is contained by
// which animation. Further down this map will get populated once
// the players are built and in doing so we can use it to efficiently
// figure out if a sub player is skipped due to a parent player having priority.
const animationElementMap = new Map<any, any>();
queuedInstructions.forEach((entry) => {
const element = entry.element;
if (subTimelines.has(element)) {
animationElementMap.set(element, element);
this._beforeAnimationBuild(
entry.player.namespaceId,
entry.instruction,
allPreviousPlayersMap,
);
}
});
skippedPlayers.forEach((player) => {
const element = player.element;
const previousPlayers = this._getPreviousPlayers(
element,
false,
player.namespaceId,
player.triggerName,
null,
);
previousPlayers.forEach((prevPlayer) => {
getOrSetDefaultValue(allPreviousPlayersMap, element, []).push(prevPlayer);
prevPlayer.destroy();
});
});
// this is a special case for nodes that will be removed either by
// having their own leave animations or by being queried in a container
// that will be removed once a parent animation is complete. The idea
| {
"end_byte": 42251,
"start_byte": 32729,
"url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.