_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/benchpress/src/reporter/text_reporter_base.ts_0_2209
/** * @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 {InjectionToken} from '@angular/core'; import {MeasureValues} from '../measure_values'; import {SampleDescription} from '../sample_description'; import {formatNum, formatStats, sortedProps} from './util'; export const COLUMN_WIDTH = new InjectionToken<number>('TextReporterBase.columnWidth'); export const defaultColumnWidth = 18; export class TextReporterBase { private _metricNames: string[]; constructor( private _columnWidth: number, private _sampleDescription: SampleDescription, ) { this._metricNames = sortedProps(_sampleDescription.metrics); } description(): string { let text = `BENCHMARK ${this._sampleDescription.id}\n`; text += 'Description:\n'; const props = sortedProps(this._sampleDescription.description); props.forEach((prop) => { text += `- ${prop}: ${this._sampleDescription.description[prop]}\n`; }); text += 'Metrics:\n'; this._metricNames.forEach((metricName) => { text += `- ${metricName}: ${this._sampleDescription.metrics[metricName]}\n`; }); text += '\n'; text += `${this.metricsHeader()}\n`; text += `${this._stringRow( this._metricNames.map((_) => ''), '-', )}\n`; return text; } metricsHeader(): string { return this._stringRow(this._metricNames); } sampleMetrics(measureValues: MeasureValues): string { const formattedValues = this._metricNames.map((metricName) => { const value = measureValues.values[metricName]; return formatNum(value); }); return this._stringRow(formattedValues); } separator(): string { return this._stringRow( this._metricNames.map((_) => ''), '=', ); } sampleStats(validSamples: MeasureValues[]): string { return this._stringRow( this._metricNames.map((metricName) => formatStats(validSamples, metricName)), ); } private _stringRow(parts: string[], fill = ' ') { return parts.map((part) => part.padStart(this._columnWidth, fill)).join(' | '); } }
{ "end_byte": 2209, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/reporter/text_reporter_base.ts" }
angular/packages/benchpress/src/reporter/json_file_reporter.ts_0_2584
/** * @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 {Inject, Injectable, InjectionToken} from '@angular/core'; import {Options} from '../common_options'; import {MeasureValues} from '../measure_values'; import {Reporter} from '../reporter'; import {SampleDescription} from '../sample_description'; import {JsonReport} from './json_file_reporter_types'; import {COLUMN_WIDTH, defaultColumnWidth, TextReporterBase} from './text_reporter_base'; import {formatStats, sortedProps} from './util'; /** * A reporter that writes results into a json file. */ @Injectable() export class JsonFileReporter extends Reporter { static PATH = new InjectionToken('JsonFileReporter.path'); static PROVIDERS = [ { provide: JsonFileReporter, deps: [ SampleDescription, COLUMN_WIDTH, JsonFileReporter.PATH, Options.WRITE_FILE, Options.NOW, ], }, {provide: COLUMN_WIDTH, useValue: defaultColumnWidth}, {provide: JsonFileReporter.PATH, useValue: '.'}, ]; constructor( private _description: SampleDescription, @Inject(COLUMN_WIDTH) private _columnWidth: number, @Inject(JsonFileReporter.PATH) private _path: string, @Inject(Options.WRITE_FILE) private _writeFile: Function, @Inject(Options.NOW) private _now: Function, ) { super(); } private textReporter = new TextReporterBase(this._columnWidth, this._description); override reportMeasureValues(measureValues: MeasureValues): Promise<any> { return Promise.resolve(null); } override reportSample( completeSample: MeasureValues[], validSample: MeasureValues[], ): Promise<any> { const stats: {[key: string]: string} = {}; sortedProps(this._description.metrics).forEach((metricName) => { stats[metricName] = formatStats(validSample, metricName); }); const content = JSON.stringify( <JsonReport>{ 'description': this._description, 'metricsText': this.textReporter.metricsHeader(), 'stats': stats, 'statsText': this.textReporter.sampleStats(validSample), 'validSampleTexts': validSample.map((s) => this.textReporter.sampleMetrics(s)), 'completeSample': completeSample, 'validSample': validSample, }, null, 2, ); const filePath = `${this._path}/${this._description.id}_${this._now().getTime()}.json`; return this._writeFile(filePath, content); } }
{ "end_byte": 2584, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/reporter/json_file_reporter.ts" }
angular/packages/benchpress/src/webdriver/ios_driver_extension.ts_0_4477
/** * @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 {Injectable} from '@angular/core'; import {WebDriverAdapter} from '../web_driver_adapter'; import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension'; @Injectable() export class IOsDriverExtension extends WebDriverExtension { static PROVIDERS = [{provide: IOsDriverExtension, deps: [WebDriverAdapter]}]; constructor(private _driver: WebDriverAdapter) { super(); } override gc(): Promise<any> { throw new Error('Force GC is not supported on iOS'); } override timeBegin(name: string): Promise<any> { return this._driver.executeScript(`console.time('${name}');`); } override timeEnd(name: string, restartName: string | null = null): Promise<any> { let script = `console.timeEnd('${name}');`; if (restartName != null) { script += `console.time('${restartName}');`; } return this._driver.executeScript(script); } // See https://github.com/WebKit/webkit/tree/master/Source/WebInspectorUI/Versions override readPerfLog() { // TODO(tbosch): Bug in IOsDriver: Need to execute at least one command // so that the browser logs can be read out! return this._driver .executeScript('1+1') .then((_) => this._driver.logs('performance')) .then((entries) => { const records: any[] = []; entries.forEach((entry: any) => { const message = ( JSON.parse(entry['message']) as {message: {method: string; params: PerfLogEvent}} )['message']; if (message['method'] === 'Timeline.eventRecorded') { records.push(message['params']['record']); } }); return this._convertPerfRecordsToEvents(records); }); } /** @internal */ private _convertPerfRecordsToEvents(records: any[], events: PerfLogEvent[] | null = null) { if (!events) { events = []; } records.forEach((record) => { let endEvent: PerfLogEvent | null = null; const type = record['type']; const data = record['data']; const startTime = record['startTime']; const endTime = record['endTime']; if (type === 'FunctionCall' && (data == null || data['scriptName'] !== 'InjectedScript')) { events!.push(createStartEvent('script', startTime)); endEvent = createEndEvent('script', endTime); } else if (type === 'Time') { events!.push(createMarkStartEvent(data['message'], startTime)); } else if (type === 'TimeEnd') { events!.push(createMarkEndEvent(data['message'], startTime)); } else if ( type === 'RecalculateStyles' || type === 'Layout' || type === 'UpdateLayerTree' || type === 'Paint' || type === 'Rasterize' || type === 'CompositeLayers' ) { events!.push(createStartEvent('render', startTime)); endEvent = createEndEvent('render', endTime); } // Note: ios used to support GCEvent up until iOS 6 :-( if (record['children'] != null) { this._convertPerfRecordsToEvents(record['children'], events); } if (endEvent != null) { events!.push(endEvent); } }); return events; } override perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true}); } override supports(capabilities: {[key: string]: any}): boolean { return capabilities['browserName'].toLowerCase() === 'safari'; } } function createEvent( ph: 'X' | 'B' | 'E' | 'B' | 'E', name: string, time: number, args: any = null, ) { const result: PerfLogEvent = { 'cat': 'timeline', 'name': name, 'ts': time, 'ph': ph, // The ios protocol does not support the notions of multiple processes in // the perflog... 'pid': 'pid0', }; if (args != null) { result['args'] = args; } return result; } function createStartEvent(name: string, time: number, args: any = null) { return createEvent('B', name, time, args); } function createEndEvent(name: string, time: number, args: any = null) { return createEvent('E', name, time, args); } function createMarkStartEvent(name: string, time: number) { return createEvent('B', name, time); } function createMarkEndEvent(name: string, time: number) { return createEvent('E', name, time); }
{ "end_byte": 4477, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/webdriver/ios_driver_extension.ts" }
angular/packages/benchpress/src/webdriver/firefox_driver_extension.ts_0_1739
/** * @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 {Injectable} from '@angular/core'; import {WebDriverAdapter} from '../web_driver_adapter'; import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension'; @Injectable() export class FirefoxDriverExtension extends WebDriverExtension { static PROVIDERS = [{provide: FirefoxDriverExtension, deps: [WebDriverAdapter]}]; private _profilerStarted: boolean; constructor(private _driver: WebDriverAdapter) { super(); this._profilerStarted = false; } override gc() { return this._driver.executeScript('window.forceGC()'); } override timeBegin(name: string): Promise<any> { if (!this._profilerStarted) { this._profilerStarted = true; this._driver.executeScript('window.startProfiler();'); } return this._driver.executeScript('window.markStart("' + name + '");'); } override timeEnd(name: string, restartName: string | null = null): Promise<any> { let script = 'window.markEnd("' + name + '");'; if (restartName != null) { script += 'window.markStart("' + restartName + '");'; } return this._driver.executeScript(script); } override readPerfLog(): Promise<PerfLogEvent[]> { return this._driver.executeAsyncScript('var cb = arguments[0]; window.getProfile(cb);'); } override perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true, gc: true}); } override supports(capabilities: {[key: string]: any}): boolean { return capabilities['browserName'].toLowerCase() === 'firefox'; } }
{ "end_byte": 1739, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/webdriver/firefox_driver_extension.ts" }
angular/packages/benchpress/src/webdriver/selenium_webdriver_adapter.ts_0_2261
/** * @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 {StaticProvider} from '@angular/core'; import {WebDriverAdapter} from '../web_driver_adapter'; /** * Adapter for the selenium-webdriver. */ export class SeleniumWebDriverAdapter extends WebDriverAdapter { static PROTRACTOR_PROVIDERS = <StaticProvider[]>[ { provide: WebDriverAdapter, useFactory: () => new SeleniumWebDriverAdapter((<any>global).browser), deps: [], }, ]; constructor(private _driver: any) { super(); } override waitFor(callback: () => any): Promise<any> { return this._driver.call(callback); } override executeScript(script: string): Promise<any> { return this._driver.executeScript(script); } override executeAsyncScript(script: string): Promise<any> { return this._driver.executeAsyncScript(script); } override capabilities(): Promise<{[key: string]: any}> { return this._driver.getCapabilities().then((capsObject: any) => { const localData: {[key: string]: any} = {}; for (const key of Array.from((<Map<string, any>>capsObject).keys())) { localData[key] = capsObject.get(key); } return localData; }); } override logs(type: string): Promise<any> { // Needed as selenium-webdriver does not forward // performance logs in the correct way via manage().logs return this._driver.schedule( new Command('getLog').setParameter('type', type), 'WebDriver.manage().logs().get(' + type + ')', ); } } /** * Copy of the `Command` class of webdriver as * it is not exposed via index.js in selenium-webdriver. */ class Command { private parameters_: {[key: string]: any} = {}; constructor(private name_: string) {} getName() { return this.name_; } setParameter(name: string, value: any) { this.parameters_[name] = value; return this; } setParameters(parameters: {[key: string]: any}) { this.parameters_ = parameters; return this; } getParameter(key: string) { return this.parameters_[key]; } getParameters() { return this.parameters_; } }
{ "end_byte": 2261, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/webdriver/selenium_webdriver_adapter.ts" }
angular/packages/benchpress/src/webdriver/chrome_driver_extension.ts_0_756
/** * @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 {Inject, Injectable, StaticProvider} from '@angular/core'; import * as fs from 'fs'; import {Options} from '../common_options'; import {WebDriverAdapter} from '../web_driver_adapter'; import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension'; /** * Set the following 'traceCategories' to collect metrics in Chrome: * 'v8,blink.console,disabled-by-default-devtools.timeline,devtools.timeline,blink.user_timing' * * In order to collect the frame rate related metrics, add 'benchmark' * to the list above. */
{ "end_byte": 756, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/webdriver/chrome_driver_extension.ts" }
angular/packages/benchpress/src/webdriver/chrome_driver_extension.ts_757_8696
@Injectable() export class ChromeDriverExtension extends WebDriverExtension { static PROVIDERS = <StaticProvider>[ { provide: ChromeDriverExtension, deps: [WebDriverAdapter, Options.USER_AGENT, Options.RAW_PERFLOG_PATH], }, ]; private _majorChromeVersion: number; private _firstRun = true; private _rawPerflogPath: string | null; constructor( private driver: WebDriverAdapter, @Inject(Options.USER_AGENT) userAgent: string, @Inject(Options.RAW_PERFLOG_PATH) rawPerflogPath: string | null, ) { super(); this._majorChromeVersion = this._parseChromeVersion(userAgent); this._rawPerflogPath = rawPerflogPath; } private _parseChromeVersion(userAgent: string): number { if (!userAgent) { return -1; } let v = userAgent.split(/Chrom(e|ium)\//g)[2]; if (!v) { return -1; } v = v.split('.')[0]; if (!v) { return -1; } return parseInt(v, 10); } override gc() { return this.driver.executeScript('window.gc()'); } override async timeBegin(name: string): Promise<any> { if (this._firstRun) { this._firstRun = false; // Before the first run, read out the existing performance logs // so that the chrome buffer does not fill up. await this.driver.logs('performance'); } return this.driver.executeScript(`performance.mark('${name}-bpstart');`); } override timeEnd(name: string, restartName: string | null = null): Promise<any> { let script = `performance.mark('${name}-bpend');`; if (restartName) { script += `performance.mark('${restartName}-bpstart');`; } return this.driver.executeScript(script); } // See [Chrome Trace Event // Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit) override readPerfLog(): Promise<PerfLogEvent[]> { // TODO(tbosch): Chromedriver bug https://code.google.com/p/chromedriver/issues/detail?id=1098 // Need to execute at least one command so that the browser logs can be read out! return this.driver .executeScript('1+1') .then((_) => this.driver.logs('performance')) .then((entries) => { const events: PerfLogEvent[] = []; entries.forEach((entry: any) => { const message = ( JSON.parse(entry['message']) as {message: {method: string; params: PerfLogEvent}} )['message']; if (message['method'] === 'Tracing.dataCollected') { events.push(message['params']); } if (message['method'] === 'Tracing.bufferUsage') { throw new Error('The DevTools trace buffer filled during the test!'); } }); if (this._rawPerflogPath && events.length) { fs.appendFileSync(this._rawPerflogPath, JSON.stringify(events)); } return this._convertPerfRecordsToEvents(events); }); } private _convertPerfRecordsToEvents( chromeEvents: Array<{[key: string]: any}>, normalizedEvents: PerfLogEvent[] | null = null, ) { if (!normalizedEvents) { normalizedEvents = []; } chromeEvents.forEach((event) => { const categories = this._parseCategories(event['cat']); const normalizedEvent = this._convertEvent(event, categories); if (normalizedEvent != null) normalizedEvents!.push(normalizedEvent); }); return normalizedEvents; } private _convertEvent(event: {[key: string]: any}, categories: string[]) { const name = event['name']; const args = event['args']; if (this._isEvent(categories, name, ['blink.console'])) { return normalizeEvent(event, {'name': name}); } else if (this._isEvent(categories, name, ['blink.user_timing'])) { return normalizeEvent(event, {'name': name}); } else if ( this._isEvent( categories, name, ['benchmark'], 'BenchmarkInstrumentation::ImplThreadRenderingStats', ) ) { // TODO(goderbauer): Instead of BenchmarkInstrumentation::ImplThreadRenderingStats the // following events should be used (if available) for more accurate measurements: // 1st choice: vsync_before - ground truth on Android // 2nd choice: BenchmarkInstrumentation::DisplayRenderingStats - available on systems with // new surfaces framework (not broadly enabled yet) // 3rd choice: BenchmarkInstrumentation::ImplThreadRenderingStats - fallback event that is // always available if something is rendered const frameCount = event['args']['data']['frame_count']; if (frameCount > 1) { throw new Error('multi-frame render stats not supported'); } if (frameCount == 1) { return normalizeEvent(event, {'name': 'frame'}); } } else if ( this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'Rasterize') || this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'CompositeLayers') ) { return normalizeEvent(event, {'name': 'render'}); } else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MajorGC')) { return normalizeGCEvent(event, true); } else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MinorGC')) { return normalizeGCEvent(event, false); } else if ( this._isEvent(categories, name, ['devtools.timeline'], 'FunctionCall') && (!args || !args['data'] || (args['data']['scriptName'] !== 'InjectedScript' && args['data']['scriptName'] !== '')) ) { return normalizeEvent(event, {'name': 'script'}); } else if (this._isEvent(categories, name, ['devtools.timeline'], 'EvaluateScript')) { return normalizeEvent(event, {'name': 'script'}); } else if ( this._isEvent(categories, name, ['devtools.timeline', 'blink'], 'UpdateLayoutTree') ) { return normalizeEvent(event, {'name': 'render'}); } else if ( this._isEvent(categories, name, ['devtools.timeline'], 'UpdateLayerTree') || this._isEvent(categories, name, ['devtools.timeline'], 'Layout') || this._isEvent(categories, name, ['devtools.timeline'], 'Paint') ) { return normalizeEvent(event, {'name': 'render'}); } else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceReceivedData')) { const normArgs = {'encodedDataLength': args['data']['encodedDataLength']}; return normalizeEvent(event, {'name': 'receivedData', 'args': normArgs}); } else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceSendRequest')) { const data = args['data']; const normArgs = {'url': data['url'], 'method': data['requestMethod']}; return normalizeEvent(event, {'name': 'sendRequest', 'args': normArgs}); } else if (this._isEvent(categories, name, ['blink.user_timing'], 'navigationStart')) { return normalizeEvent(event, {'name': 'navigationStart'}); } return null; // nothing useful in this event } private _parseCategories(categories: string): string[] { return categories.split(','); } private _isEvent( eventCategories: string[], eventName: string, expectedCategories: string[], expectedName: string | null = null, ): boolean { const hasCategories = expectedCategories.reduce( (value, cat) => value && eventCategories.indexOf(cat) !== -1, true, ); return !expectedName ? hasCategories : hasCategories && eventName === expectedName; } override perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true}); } override supports(capabilities: {[key: string]: any}): boolean { const browserName = capabilities['browserName'].toLowerCase(); return ( this._majorChromeVersion >= 44 && (browserName === 'chrome' || browserName === 'chrome-headless-shell') ); } }
{ "end_byte": 8696, "start_byte": 757, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/webdriver/chrome_driver_extension.ts" }
angular/packages/benchpress/src/webdriver/chrome_driver_extension.ts_8698_10669
function normalizeEvent(chromeEvent: {[key: string]: any}, data: PerfLogEvent): PerfLogEvent { let ph = chromeEvent['ph'].toUpperCase(); if (ph === 'S') { ph = 'B'; } else if (ph === 'F') { ph = 'E'; } else if (ph === 'R') { // mark events from navigation timing ph = 'I'; // Chrome 65+ doesn't allow user timing measurements across page loads. // Instead, we use performance marks with special names. if (chromeEvent['name'].match(/-bpstart/)) { data['name'] = chromeEvent['name'].slice(0, -8); ph = 'B'; } else if (chromeEvent['name'].match(/-bpend$/)) { data['name'] = chromeEvent['name'].slice(0, -6); ph = 'E'; } } const result: {[key: string]: any} = { 'pid': chromeEvent['pid'], 'ph': ph, 'cat': 'timeline', 'ts': chromeEvent['ts'] / 1000, }; if (ph === 'X') { let dur = chromeEvent['dur']; if (dur === undefined) { dur = chromeEvent['tdur']; } result['dur'] = !dur ? 0.0 : dur / 1000; } for (const prop in data) { result[prop] = data[prop]; } return result; } function normalizeGCEvent(chromeEvent: {[key: string]: any}, majorGc: boolean) { const args = chromeEvent['args']; const heapSizeBefore = args['usedHeapSizeBefore']; const heapSizeAfter = args['usedHeapSizeAfter']; if (heapSizeBefore === undefined && heapSizeAfter === undefined) { throw new Error( `GC event didn't specify heap size to calculate amount of collected memory. Expected one of usedHeapSizeBefore / usedHeapSizeAfter arguments but got ${JSON.stringify( args, )}`, ); } const normalizedArgs = { 'majorGc': majorGc, 'usedHeapSize': heapSizeAfter !== undefined ? heapSizeAfter : heapSizeBefore, 'gcAmount': heapSizeBefore !== undefined && heapSizeAfter !== undefined ? heapSizeBefore - heapSizeAfter : 0, }; return normalizeEvent(chromeEvent, {'name': 'gc', 'args': normalizedArgs}); }
{ "end_byte": 10669, "start_byte": 8698, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/webdriver/chrome_driver_extension.ts" }
angular/packages/benchpress/src/metric/multi_metric.ts_0_1860
/** * @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 {InjectionToken, Injector} from '@angular/core'; import {Metric} from '../metric'; export class MultiMetric extends Metric { static provideWith(childTokens: any[]): any[] { return [ { provide: _CHILDREN, useFactory: (injector: Injector) => childTokens.map((token) => injector.get(token)), deps: [Injector], }, { provide: MultiMetric, useFactory: (children: Metric[]) => new MultiMetric(children), deps: [_CHILDREN], }, ]; } constructor(private _metrics: Metric[]) { super(); } /** * Starts measuring */ override beginMeasure(): Promise<any> { return Promise.all(this._metrics.map((metric) => metric.beginMeasure())); } /** * Ends measuring and reports the data * since the begin call. * @param restart: Whether to restart right after this. */ override endMeasure(restart: boolean): Promise<{[key: string]: any}> { return Promise.all(this._metrics.map((metric) => metric.endMeasure(restart))).then((values) => mergeStringMaps(<any>values), ); } /** * Describes the metrics provided by this metric implementation. * (e.g. units, ...) */ override describe(): {[key: string]: any} { return mergeStringMaps(this._metrics.map((metric) => metric.describe())); } } function mergeStringMaps(maps: {[key: string]: string}[]): {[key: string]: string} { const result: {[key: string]: string} = {}; maps.forEach((map) => { Object.keys(map).forEach((prop) => { result[prop] = map[prop]; }); }); return result; } const _CHILDREN = new InjectionToken('MultiMetric.children');
{ "end_byte": 1860, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/metric/multi_metric.ts" }
angular/packages/benchpress/src/metric/user_metric.ts_0_2219
/** * @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 {Inject, Injectable, StaticProvider} from '@angular/core'; import {Options} from '../common_options'; import {Metric} from '../metric'; import {WebDriverAdapter} from '../web_driver_adapter'; @Injectable() export class UserMetric extends Metric { static PROVIDERS = <StaticProvider[]>[ {provide: UserMetric, deps: [Options.USER_METRICS, WebDriverAdapter]}, ]; constructor( @Inject(Options.USER_METRICS) private _userMetrics: {[key: string]: string}, private _wdAdapter: WebDriverAdapter, ) { super(); } /** * Starts measuring */ override beginMeasure(): Promise<any> { return Promise.resolve(true); } /** * Ends measuring. */ override endMeasure(restart: boolean): Promise<{[key: string]: any}> { let resolve: (result: any) => void; let reject: (error: any) => void; const promise = new Promise<{[key: string]: any}>((res, rej) => { resolve = res; reject = rej; }); const adapter = this._wdAdapter; const names = Object.keys(this._userMetrics); function getAndClearValues() { Promise.all(names.map((name) => adapter.executeScript(`return window.${name}`))).then( (values: any[]) => { if (values.every((v) => typeof v === 'number')) { Promise.all(names.map((name) => adapter.executeScript(`delete window.${name}`))).then( (_: any[]) => { const map: {[k: string]: any} = {}; for (let i = 0, n = names.length; i < n; i++) { map[names[i]] = values[i]; } resolve(map); }, reject, ); } else { <any>setTimeout(getAndClearValues, 100); } }, reject, ); } getAndClearValues(); return promise; } /** * Describes the metrics provided by this metric implementation. * (e.g. units, ...) */ override describe(): {[key: string]: any} { return this._userMetrics; } }
{ "end_byte": 2219, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/metric/user_metric.ts" }
angular/packages/benchpress/src/metric/perflog_metric.ts_0_494
/** * @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 {Inject, Injectable, InjectionToken} from '@angular/core'; import {Options} from '../common_options'; import {Metric} from '../metric'; import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension'; /** * A metric that reads out the performance log */
{ "end_byte": 494, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/metric/perflog_metric.ts" }
angular/packages/benchpress/src/metric/perflog_metric.ts_495_7937
@Injectable() export class PerflogMetric extends Metric { static SET_TIMEOUT = new InjectionToken('PerflogMetric.setTimeout'); static IGNORE_NAVIGATION = new InjectionToken('PerflogMetric.ignoreNavigation'); static PROVIDERS = [ { provide: PerflogMetric, deps: [ WebDriverExtension, PerflogMetric.SET_TIMEOUT, Options.MICRO_METRICS, Options.FORCE_GC, Options.CAPTURE_FRAMES, Options.RECEIVED_DATA, Options.REQUEST_COUNT, PerflogMetric.IGNORE_NAVIGATION, ], }, { provide: PerflogMetric.SET_TIMEOUT, useValue: (fn: Function, millis: number) => <any>setTimeout(fn, millis), }, {provide: PerflogMetric.IGNORE_NAVIGATION, useValue: false}, ]; private _remainingEvents: PerfLogEvent[]; private _measureCount: number; private _perfLogFeatures: PerfLogFeatures; /** * @param driverExtension * @param setTimeout * @param microMetrics Name and description of metrics provided via console.time / console.timeEnd * @param ignoreNavigation If true, don't measure from navigationStart events. These events are * usually triggered by a page load, but can also be triggered when adding iframes to the DOM. **/ constructor( private _driverExtension: WebDriverExtension, @Inject(PerflogMetric.SET_TIMEOUT) private _setTimeout: Function, @Inject(Options.MICRO_METRICS) private _microMetrics: {[key: string]: string}, @Inject(Options.FORCE_GC) private _forceGc: boolean, @Inject(Options.CAPTURE_FRAMES) private _captureFrames: boolean, @Inject(Options.RECEIVED_DATA) private _receivedData: boolean, @Inject(Options.REQUEST_COUNT) private _requestCount: boolean, @Inject(PerflogMetric.IGNORE_NAVIGATION) private _ignoreNavigation: boolean, ) { super(); this._remainingEvents = []; this._measureCount = 0; this._perfLogFeatures = _driverExtension.perfLogFeatures(); if (!this._perfLogFeatures.userTiming) { // User timing is needed for navigationStart. this._receivedData = false; this._requestCount = false; } } override describe(): {[key: string]: string} { const res: {[key: string]: any} = { 'scriptTime': 'script execution time in ms, including gc and render', 'pureScriptTime': 'script execution time in ms, without gc nor render', }; if (this._perfLogFeatures.render) { res['renderTime'] = 'render time in ms'; res['renderTimeInScript'] = 'render time in ms while executing script (usually means reflow)'; } if (this._perfLogFeatures.gc) { res['gcTime'] = 'gc time in ms'; res['gcTimeInScript'] = 'gc time in ms while executing scripts'; res['gcAmount'] = 'gc amount in kbytes'; res['majorGcTime'] = 'time of major gcs in ms'; if (this._forceGc) { res['forcedGcTime'] = 'forced gc time in ms'; res['forcedGcAmount'] = 'forced gc amount in kbytes'; } } if (this._receivedData) { res['receivedData'] = 'encoded bytes received since navigationStart'; } if (this._requestCount) { res['requestCount'] = 'count of requests sent since navigationStart'; } if (this._captureFrames) { if (!this._perfLogFeatures.frameCapture) { const warningMsg = 'WARNING: Metric requested, but not supported by driver'; // using dot syntax for metric name to keep them grouped together in console reporter res['frameTime.mean'] = warningMsg; res['frameTime.worst'] = warningMsg; res['frameTime.best'] = warningMsg; res['frameTime.smooth'] = warningMsg; } else { res['frameTime.mean'] = 'mean frame time in ms (target: 16.6ms for 60fps)'; res['frameTime.worst'] = 'worst frame time in ms'; res['frameTime.best'] = 'best frame time in ms'; res['frameTime.smooth'] = 'percentage of frames that hit 60fps'; } } for (const name in this._microMetrics) { res[name] = this._microMetrics[name]; } return res; } override beginMeasure(): Promise<any> { let resultPromise = Promise.resolve(null); if (this._forceGc) { resultPromise = resultPromise.then((_) => this._driverExtension.gc()); } return resultPromise.then((_) => this._beginMeasure()); } override endMeasure(restart: boolean): Promise<{[key: string]: number}> { if (this._forceGc) { return this._endPlainMeasureAndMeasureForceGc(restart); } else { return this._endMeasure(restart); } } /** @internal */ private _endPlainMeasureAndMeasureForceGc(restartMeasure: boolean) { return this._endMeasure(true).then((measureValues) => { // disable frame capture for measurements during forced gc const originalFrameCaptureValue = this._captureFrames; this._captureFrames = false; return this._driverExtension .gc() .then((_) => this._endMeasure(restartMeasure)) .then((forceGcMeasureValues) => { this._captureFrames = originalFrameCaptureValue; measureValues['forcedGcTime'] = forceGcMeasureValues['gcTime']; measureValues['forcedGcAmount'] = forceGcMeasureValues['gcAmount']; return measureValues; }); }); } private _beginMeasure(): Promise<any> { return this._driverExtension.timeBegin(this._markName(this._measureCount++)); } private _endMeasure(restart: boolean): Promise<{[key: string]: number}> { const markName = this._markName(this._measureCount - 1); const nextMarkName = restart ? this._markName(this._measureCount++) : null; return this._driverExtension .timeEnd(markName, nextMarkName) .then((_: any) => this._readUntilEndMark(markName)); } private _readUntilEndMark( markName: string, loopCount: number = 0, startEvent: PerfLogEvent | null = null, ) { if (loopCount > _MAX_RETRY_COUNT) { throw new Error(`Tried too often to get the ending mark: ${loopCount}`); } return this._driverExtension.readPerfLog().then((events) => { this._addEvents(events); const result = this._aggregateEvents(this._remainingEvents, markName); if (result) { this._remainingEvents = events; return result; } let resolve: (result: any) => void; const promise = new Promise<{[key: string]: number}>((res) => { resolve = res; }); this._setTimeout(() => resolve(this._readUntilEndMark(markName, loopCount + 1)), 100); return promise; }); } private _addEvents(events: PerfLogEvent[]) { let needSort = false; events.forEach((event) => { if (event['ph'] === 'X') { needSort = true; const startEvent: PerfLogEvent = {}; const endEvent: PerfLogEvent = {}; for (const prop in event) { startEvent[prop] = event[prop]; endEvent[prop] = event[prop]; } startEvent['ph'] = 'B'; endEvent['ph'] = 'E'; endEvent['ts'] = startEvent['ts']! + startEvent['dur']!; this._remainingEvents.push(startEvent); this._remainingEvents.push(endEvent); } else { this._remainingEvents.push(event); } }); if (needSort) { // Need to sort because of the ph==='X' events this._remainingEvents.sort((a, b) => { const diff = a['ts']! - b['ts']!; return diff > 0 ? 1 : diff < 0 ? -1 : 0; }); } }
{ "end_byte": 7937, "start_byte": 495, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/metric/perflog_metric.ts" }
angular/packages/benchpress/src/metric/perflog_metric.ts_7941_15625
private _aggregateEvents( events: PerfLogEvent[], markName: string, ): {[key: string]: number} | null { const result: {[key: string]: number} = {'scriptTime': 0, 'pureScriptTime': 0}; if (this._perfLogFeatures.gc) { result['gcTime'] = 0; result['majorGcTime'] = 0; result['gcAmount'] = 0; } if (this._perfLogFeatures.render) { result['renderTime'] = 0; } if (this._captureFrames) { result['frameTime.mean'] = 0; result['frameTime.best'] = 0; result['frameTime.worst'] = 0; result['frameTime.smooth'] = 0; } for (const name in this._microMetrics) { result[name] = 0; } if (this._receivedData) { result['receivedData'] = 0; } if (this._requestCount) { result['requestCount'] = 0; } let markStartEvent: PerfLogEvent = null!; let markEndEvent: PerfLogEvent = null!; events.forEach((event) => { const ph = event['ph']; const name = event['name']; // Here we are determining if this is the event signaling the start or end of our performance // testing (this is triggered by us calling #timeBegin and #timeEnd). // // Previously, this was done by checking that the event name matched our mark name and that // the phase was either "B" or "E" ("begin" or "end"). However, since Chrome v90 this is // showing up as "-bpstart" and "-bpend" ("benchpress start/end"), which is what one would // actually expect since that is the mark name used in ChromeDriverExtension - see the // #timeBegin and #timeEnd implementations in chrome_driver_extension.ts. For // backwards-compatibility with Chrome v89 (and older), we do both checks: the phase-based // one ("B" or "E") and event name-based (the "-bp(start/end)" suffix). const isStartEvent = (ph === 'B' && name === markName) || name === markName + '-bpstart'; const isEndEvent = (ph === 'E' && name === markName) || name === markName + '-bpend'; if (isStartEvent) { markStartEvent = event; } else if (ph === 'I' && name === 'navigationStart' && !this._ignoreNavigation) { // if a benchmark measures reload of a page, use the last // navigationStart as begin event markStartEvent = event; } else if (isEndEvent) { markEndEvent = event; } }); if (!markStartEvent || !markEndEvent) { // not all events have been received, no further processing for now return null; } if (markStartEvent.pid !== markEndEvent.pid) { result['invalid'] = 1; } let gcTimeInScript = 0; let renderTimeInScript = 0; const frameTimestamps: number[] = []; const frameTimes: number[] = []; let frameCaptureStartEvent: PerfLogEvent | null = null; let frameCaptureEndEvent: PerfLogEvent | null = null; const intervalStarts: {[key: string]: PerfLogEvent} = {}; const intervalStartCount: {[key: string]: number} = {}; let inMeasureRange = false; events.forEach((event) => { const ph = event['ph']; let name = event['name']!; let microIterations = 1; const microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX); if (microIterationsMatch) { name = microIterationsMatch[1]; microIterations = parseInt(microIterationsMatch[2], 10); } if (event === markStartEvent) { inMeasureRange = true; } else if (event === markEndEvent) { inMeasureRange = false; } if (!inMeasureRange || event['pid'] !== markStartEvent['pid']) { return; } if (this._requestCount && name === 'sendRequest') { result['requestCount'] += 1; } else if (this._receivedData && name === 'receivedData' && ph === 'I') { result['receivedData'] += event['args']!['encodedDataLength']!; } if (ph === 'B' && name === _MARK_NAME_FRAME_CAPTURE) { if (frameCaptureStartEvent) { throw new Error('can capture frames only once per benchmark run'); } if (!this._captureFrames) { throw new Error( 'found start event for frame capture, but frame capture was not requested in benchpress', ); } frameCaptureStartEvent = event; } else if (ph === 'E' && name === _MARK_NAME_FRAME_CAPTURE) { if (!frameCaptureStartEvent) { throw new Error('missing start event for frame capture'); } frameCaptureEndEvent = event; } if (ph === 'I' && frameCaptureStartEvent && !frameCaptureEndEvent && name === 'frame') { frameTimestamps.push(event['ts']!); if (frameTimestamps.length >= 2) { frameTimes.push( frameTimestamps[frameTimestamps.length - 1] - frameTimestamps[frameTimestamps.length - 2], ); } } if (ph === 'B') { if (!intervalStarts[name]) { intervalStartCount[name] = 1; intervalStarts[name] = event; } else { intervalStartCount[name]++; } } else if (ph === 'E' && intervalStarts[name]) { intervalStartCount[name]--; if (intervalStartCount[name] === 0) { const startEvent = intervalStarts[name]; const duration = event['ts']! - startEvent['ts']!; intervalStarts[name] = null!; if (name === 'gc') { result['gcTime'] += duration; const gcAmount = event['args']?.['gcAmount'] ?? 0; const amount = gcAmount > 0 ? gcAmount : startEvent['args']!['usedHeapSize']! - event['args']!['usedHeapSize']!; result['gcAmount'] += amount / 1000; const majorGc = event['args']!['majorGc']; if (majorGc && majorGc) { result['majorGcTime'] += duration; } if (intervalStarts['script']) { gcTimeInScript += duration; } } else if (name === 'render') { result['renderTime'] += duration; if (intervalStarts['script']) { renderTimeInScript += duration; } } else if (name === 'script') { result['scriptTime'] += duration; } else if (this._microMetrics[name]) { (<any>result)[name] += duration / microIterations; } } } }); if (frameCaptureStartEvent && !frameCaptureEndEvent) { throw new Error('missing end event for frame capture'); } if (this._captureFrames && !frameCaptureStartEvent) { throw new Error('frame capture requested in benchpress, but no start event was found'); } if (frameTimes.length > 0) { this._addFrameMetrics(result, frameTimes); } result['renderTimeInScript'] = renderTimeInScript; result['gcTimeInScript'] = gcTimeInScript; result['pureScriptTime'] = result['scriptTime'] - gcTimeInScript - renderTimeInScript; return result; } private _addFrameMetrics(result: {[key: string]: number}, frameTimes: any[]) { result['frameTime.mean'] = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length; const firstFrame = frameTimes[0]; result['frameTime.worst'] = frameTimes.reduce((a, b) => (a > b ? a : b), firstFrame); result['frameTime.best'] = frameTimes.reduce((a, b) => (a < b ? a : b), firstFrame); result['frameTime.smooth'] = frameTimes.filter((t) => t < _FRAME_TIME_SMOOTH_THRESHOLD).length / frameTimes.length; } private _markName(index: number) { return `${_MARK_NAME_PREFIX}${index}`; } } const _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/; const _MAX_RETRY_COUNT = 20;
{ "end_byte": 15625, "start_byte": 7941, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/metric/perflog_metric.ts" }
angular/packages/benchpress/src/metric/perflog_metric.ts_15626_15823
const _MARK_NAME_PREFIX = 'benchpress'; const _MARK_NAME_FRAME_CAPTURE = 'frameCapture'; // using 17ms as a somewhat looser threshold, instead of 16.6666ms const _FRAME_TIME_SMOOTH_THRESHOLD = 17;
{ "end_byte": 15823, "start_byte": 15626, "url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/metric/perflog_metric.ts" }
angular/packages/compiler/BUILD.bazel_0_1006
load("//tools:defaults.bzl", "ng_package", "ts_library", "tsec_test") package(default_visibility = ["//visibility:public"]) ts_library( name = "compiler", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), ) tsec_test( name = "tsec_test", target = "compiler", tsconfig = "//packages:tsec_config", ) ng_package( name = "npm_package", 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/language-service/test:__pkg__", ], deps = [ ":compiler", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]), )
{ "end_byte": 1006, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/BUILD.bazel" }
angular/packages/compiler/index.ts_0_479
/** * @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 './compiler';
{ "end_byte": 479, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/index.ts" }
angular/packages/compiler/compiler.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/compiler/compiler.ts" }
angular/packages/compiler/public_api.ts_0_399
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/compiler'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 399, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/public_api.ts" }
angular/packages/compiler/design/separate_compilation.md_0_5006
# DESIGN DOC (Ivy): Separate Compilation AUTHOR: chuckj@ ## Background ### Angular 5 (Renderer2) In 5.0 and prior versions of Angular the compiler performs whole program analysis and generates template and injector definitions that use this global knowledge to flatten injector scope definitions, inline directives into the component, pre-calculate queries, pre-calculate content projection, etc. This global knowledge requires that module and component factories are generated as the final global step when compiling a module. If any of the transitive information changed, then all factories need to be regenerated. Separate component and module compilation is supported only at the module definition level and only from the source. That is, npm packages must contain the metadata necessary to generate the factories. They cannot contain, themselves, the generated factories. This is because if any of their dependencies change, their factories would be invalid, preventing them from using version ranges in their dependencies. To support producing factories from compiled source (already translated by TypeScript into JavaScript) libraries include metadata that describe the content of the Angular decorators. This document refers to this style of code generation as Renderer2 (after the name of the renderer class it uses at runtime). ### Angular Ivy In Ivy, the runtime is crafted in a way that allows for separate compilation by performing at runtime much of what was previously pre-calculated by the compiler. This allows the definition of components to change without requiring modules and components that depend on them to be recompiled. The mental model of Ivy is that the decorator is the compiler. That is, the decorator can be thought of as parameters to a class transformer that transforms the class by generating definitions based on the decorator parameters. A `@Component` decorator transforms the class by adding an `ɵcmp` static property, `@Directive` adds `ɵdir`, `@Pipe` adds `ɵpipe`, etc. In most cases the values supplied to the decorator are sufficient to generate the definition. However, in the case of interpreting the template, the compiler needs to know the selector defined for each component, directive and pipe that are in the scope of the template. The purpose of this document is to define the information that is needed by the compiler, and how that information is serialized to be discovered and used by subsequent calls to `ngc`. This document refers to this style of code generation as Ivy (after the code name of the project to create it). It would be more consistent to refer to it as Renderer3, but that looks too similar to Renderer2. ## Information needed The information available across compilations in Angular 5 is represented in the compiler by a summary description. For example, components and directives are represented by the [`CompileDirectiveSummary`](https://github.com/angular/angular/blob/d3827a0017fd5ff5ac0f6de8a19692ce47bf91b4/packages/compiler/src/compile_metadata.ts#L257). The following table shows where this information ends up in an ivy compiled class: ### `CompileDirectiveSummary` | field | destination | |---------------------|-----------------------| | `type` | implicit | | `isComponent` | `ɵcmp` | | `selector` | `ngModuleScope` | | `exportAs` | `ɵdir` | | `inputs` | `ɵdir` | | `outputs` | `ɵdir` | | `hostListeners` | `ɵdir` | | `hostProperties` | `ɵdir` | | `hostAttributes` | `ɵdir` | | `providers` | `ɵinj` | | `viewProviders` | `ɵcmp` | | `queries` | `ɵdir` | | `guards` | not used | | `viewQueries` | `ɵcmp` | | `changeDetection` | `ɵcmp` | | `template` | `ɵcmp` | | `componentViewType` | not used | | `renderType` | not used | | `componentFactory` | not used | Only one definition is generated per class. All components are directives so a `ɵcmp` contains all the `ɵdir` information. All directives are injectable so `ɵcmp` and `ɵdir` contain `ɵprov` information. For `CompilePipeSummary` the table looks like: #### `CompilePipeSummary` | field | destination | |---------------------|-----------------------| | `type` | implicit | | `name` | `ngModuleScope` | | `pure` | `ɵpipe` | The only pieces of information that are not generated into the definition are the directive selector and the pipe name as they go into the module scope. The information needed to build an `ngModuleScope` needs to be communicated from the directive and pipe to the module that declares them. ## Metadata ### Angul
{ "end_byte": 5006, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/separate_compilation.md" }
angular/packages/compiler/design/separate_compilation.md_5006_11863
ar 5 Angular 5 uses `.metadata.json` files to store information that is directly inferred from the `.ts` files and include value information that is not included in the `.d.ts` file produced by TypeScript. Because only exports for types are included in `.d.ts` files and might not include the exports necessary for values, the metadata includes export clauses from the `.ts` file. When a module is flattened into a FESM (Flat ECMAScript Module), a flat metadata file is also produced which is the metadata for all symbols exported from the module index. The metadata represents what the `.metadata.json` file would look like if all the symbols were declared in the index instead of reexported from the index. ### Angular Ivy The metadata for a class in ivy is transformed to be what the metadata of the transformed .js file produced by the Ivy compiler would be. For example, a component's `@Component` is removed by the compiler and replaced by a `ɵcmp`. The `.metadata.json` file is similarly transformed but the content of the value assigned is elided (e.g. `"ɵcmp": {}`). The compiler doesn't record the selector declared for a component but it is needed to produce the `ngModuleScope` so the information is recorded as if a static field `ngSelector` was declared on class with the value of the `selector` field from the `@Component` or `@Directive` decorator. The following transformations are performed: #### `@Component` The metadata for a component is transformed by: 1. Removing the `@Component` directive. 2. Add `"ɵcmp": {}` static field. 3. Add `"ngSelector": <selector-value>` static field. ##### Example *my.component.ts* ```ts @Component({ selector: 'my-comp', template: `<h1>Hello, {{name}}!</h1>` }) export class MyComponent { @Input() name: string; } ``` *my.component.js* ```js export class MyComponent { name: string; static ɵcmp = ɵɵdefineComponent({...}); } ``` *my.component.metadata.json* ```json { "__symbolic": "module", "version": 4, "metadata": { "MyComponent": { "__symbolic": "class", "statics": { "ɵcmp": {}, "ngSelector": "my-comp" } } } } ``` Note that this is exactly what is produced if the transform had been done manually or by some other compiler before `ngc` compiler is invoked. That is why this model has the advantage that there is no magic introduced by the compiler, as it treats classes annotated by `@Component` identically to those produced manually. #### `@Directive` The metadata for a directive is transformed by: 1. Removing the `@Directive` directive. 2. Add `"ɵdir": {}` static field. 3. Add `"ngSelector": <selector-value>` static field. ##### example *my.directive.ts* ```ts @Directive({selector: '[my-dir]'}) export class MyDirective { @HostBinding('id') dirId = 'some id'; } ``` *my.directive.js* ```js export class MyDirective { constructor() { this.dirId = 'some id'; } static ɵdir = ɵɵdefineDirective({...}); } ``` *my.directive.metadata.json* ```json { "__symbolic": "module", "version": 4, "metadata": { "MyDirective": { "__symbolic": "class", "statics": { "ɵdir": {}, "ngSelector": "[my-dir]" } } } } ``` #### `@Pipe` The metadata for a pipe is transformed by: 1. Removing the `@Pipe` directive. 2. Add `"ɵpipe": {}` static field. 3. Add `"ngSelector": <name-value>` static field. ##### example *my.pipe.ts* ```ts @Pipe({name: 'myPipe'}) export class MyPipe implements PipeTransform { transform(...) ... } ``` *my.pipe.js* ```js export class MyPipe { transform(...) ... static ɵpipe = ɵɵdefinePipe({...}); } ``` *my.pipe.metadata.json* ```json { "__symbolic": "module", "version": 4, "metadata": { "MyPipe": { "__symbolic": "class", "statics": { "ɵpipe": {}, "ngSelector": "myPipe" } } } } ``` #### `@NgModule` The metadata for a module is transformed by: 1. Remove the `@NgModule` directive. 2. Add `"ɵinj": {}` static field. 3. Add `"ngModuleScope": <module-scope>` static field. The scope value is an array the following type: ```ts export type ModuleScope = ModuleScopeEntry[]; export interface ModuleDirectiveEntry { type: Type; selector: string; } export interface ModulePipeEntry { type: Type; name: string; isPipe: true; } export interface ModuleExportEntry { type: Type; isModule: true; } type ModuleScopeEntry = ModuleDirectiveEntry | ModulePipeEntry | ModuleExportEntry; ``` where the `type` values are generated as references. ##### example *my.module.ts* ```ts @NgModule({ imports: [CommonModule, UtilityModule], declarations: [MyComponent, MyDirective, MyPipe], exports: [MyComponent, MyDirective, MyPipe, UtilityModule], providers: [{ provide: Service, useClass: ServiceImpl }] }) export class MyModule {} ``` *my.module.js* ```js export class MyModule { static ɵinj = ɵɵdefineInjector(...); } ``` *my.module.metadata.json* ```json { "__symbolic": "module", "version": 4, "metadata": { "MyModule": { "__symbolic": "class", "statics": { "ɵinj": {}, "ngModuleScope": [ { "type": { "__symbolic": "reference", "module": "./my.component", "name": "MyComponent" }, "selector": "my-comp" }, { "type": { "__symbolic": "reference", "module": "./my.directive", "name": "MyDirective" }, "selector": "[my-dir]" }, { "type": { "__symbolic": "reference", "module": "./my.pipe", "name": "MyPipe" }, "name": "myPipe", "isPipe": true }, { "type": { "__symbolic": "reference", "module": "./utility.module", "name": "UtilityModule" }, "isModule": true } ] } } } } ``` Note that this is identical to what would have been generated if the this was manually written as: ```ts export class MyModule { static ɵinj = ɵɵdefineInjector({ providers: [{ provide: Service, useClass: ServiceImpl }], imports: [CommonModule, UtilityModule] }); static ngModuleScope = [{ type: MyComponent, selector: 'my-comp' }, { type: MyDirective, selector: '[my-dir]' }, { type: MyPipe, name: 'myPipe' }, { type: UtilityModule, isModule: true }]; } ``` except for the call to `ɵɵdefineInjector` would generate a `{ __symbolic: 'error' }` value which is ignored by the ivy compiler. This allows the system to ignore the difference between manually and mechanically created module definitions. ## `ngc` output (non-Bazel) The cases that `ngc`
{ "end_byte": 11863, "start_byte": 5006, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/separate_compilation.md" }
angular/packages/compiler/design/separate_compilation.md_11863_17366
handle are producing an application and producing a reusable library used in an application. ### Application output The output of the Ivy compiler only optionally generates the factories generated by the Renderer2 style output of Angular 5.0. In Ivy, the information that was generated in factories is now generated in Angular as a definition that is generated as a static field in the Angular decorated class. Renderer2 requires that, when building the final application, all factories for all libraries also be generated. In Ivy, the definitions are generated when the library is compiled. The Ivy compile can adapt Renderer2 target libraries by generating the factories for them and back-patching, at runtime, the static property into the class. #### Back-patching module (`"renderer2BackPatching"`) When an application contains Renderer2 target libraries the Ivy definitions need to be back-patch onto the component, directive, module, pipe, and injectable classes. If the Angular compiler option `"renderer2BackPatching"` is enabled, the compiler will generate an `angular.back-patch` module into the root output directory of the project. If `"generateRenderer2Factories"` is set to `true` then the default value for `"renderer2BackPatching"` is `true` and it is an error for it to be `false`. `"renderer2BackPatching"` is ignored if `"enableIvy"` is `false`. `angular.back-patch` exports a function per `@NgModule` for the entire application, including previously compiled libraries. The name of the function is determined by name of the imported module with all non alphanumeric character, including '`/`' and '`.`', replaced by '`_`'. The back-patch functions will call the back-patch function of any module they import. This means that only the application's module and lazy loaded modules back-patching functions need to be called. If using the Renderer2 module factory instances, this is performed automatically when the first application module instance is created. #### Renderer2 Factories (`"generateRenderer2Factories"`) `ngc` can generate an implementation of `NgModuleFactory` in the same location that Angular 5.0 would generate it. This implementation of `NgModuleFactory` will back-patch the Renderer2 style classes when the first module instance is created by calling the correct back-patching function generated in the`angular.back-patch` module. Renderer2 style factories are created when the `"generateRenderer2Factories"` Angular compiler option is `true`. Setting `"generateRenderer2Factories"` implies `"renderer2BackPatching"` is also `true` and it is an error to explicitly set it to `false`. `"generateRenderer2Factories"` is ignored if `"enableIvy"` is `false`. When this option is `true` a factory module is created with the same public API at the same location as Angular 5.0 whenever Angular 5.0 would have generated a factory. ### Recommended options The recommended options for producing an ivy application are | option | value | | |--------------------------------|----------|-------------| | `"enableIvy"` | `true` | required | | `"generateRenderer2Factories"` | `true` | implied | | `"renderer2BackPatching"` | `true` | implied | | `"generateCodeForLibraries"` | `true` | default | | `"annotationsAs"` | `remove` | implied | | `"preserveWhitespaces"` | `false` | default | | `"skipMetadataEmit"` | `true` | default | | `"strictMetadataEmit"` | `false` | implied | | `"skipTemplateCodegen"` | | ignored | The options marked "implied" are implied by other options having the recommended value and do not need to be explicitly set. Options marked "default" also do not need to be set explicitly. ## Library output Building an Ivy library with `ngc` differs from Renderer2 in that the declarations are included in the generated output and should be included in the package published to `npm`. The `.metadata.json` files still need to be included but they are transformed as described below. ### Transforming metadata As described above, when the compiler adds the declaration to the class it will also transform the `.metadata.json` file to reflect the new static fields added to the class. Once the static fields are added to the metadata, the Ivy compiler no longer needs the information in the decorator. When `"enableIvy"` is `true` this information is removed from the `.metadata.json` file. ### Recommended options The recommended options for producing a ivy library are: | option | value | | |--------------------------------|----------|-------------| | `"enableIvy"` | `true` | required | | `"generateRenderer2Factories"` | `false` | | | `"renderer2BackPatching"` | `false` | default | | `"generateCodeForLibraries"` | `false` | | | `"annotationsAs"` | `remove` | implied | | `"preserveWhitespaces"` | `false` | default | | `"skipMetadataEmit"` | `false` | | | `"strictMetadataEmit"` | `true ` | | | `"skipTemplateCodegen"` | | ignored | The options marked "implied" are implied by other options having the recommended value and do not need to be explicitly set. Options marked "default" also do not need to be set explicitly. ## Simplified options The default Angular Compil
{ "end_byte": 17366, "start_byte": 11863, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/separate_compilation.md" }
angular/packages/compiler/design/separate_compilation.md_17366_25537
er options default to, mostly, the recommended set of options but the options necessary to set for specific targets are not clear and mixing them can produce nonsensical results. The `"target"` option can be used to simplify the setting of the compiler options to the recommended values depending on the target: | target | option | value | | |-------------------|--------------------------------|--------------|-------------| | `"application"` | `"generateRenderer2Factories"` | `true` | enforced | | | `"renderer2BackPatching"` | `true` | enforced | | | `"generateCodeForLibraries"` | `true` | | | | `"annotationsAs"` | `remove` | | | | `"preserveWhitespaces"` | `false` | | | | `"skipMetadataEmit"` | `false` | | | | `"strictMetadataEmit"` | `true` | | | | `"skipTemplateCodegen"` | `false` | | | | `"fullTemplateTypeCheck"` | `true` | | | | | | | | `"library"` | `"generateRenderer2Factories"` | `false` | enforced | | | `"renderer2BackPatching"` | `false` | enforced | | | `"generateCodeForLibraries"` | `false` | enforced | | | `"annotationsAs"` | `decorators` | | | | `"preserveWhitespaces"` | `false` | | | | `"skipMetadataEmit"` | `false` | enforced | | | `"strictMetadataEmit"` | `true` | | | | `"skipTemplateCodegen"` | `false` | enforced | | | `"fullTemplateTypeCheck"` | `true` | | | | | | | | `"package"` | `"flatModuleOutFile"` | | required | | | `"flatModuleId"` | | required | | | `"enableIvy"` | `false` | enforced | | | `"generateRenderer2Factories"` | `false` | enforced | | | `"renderer2BackPatching"` | `false` | enforced | | | `"generateCodeForLibraries"` | `false` | enforced | | | `"annotationsAs"` | `remove` | | | | `"preserveWhitespaces"` | `false` | | | | `"skipMetadataEmit"` | `false` | enforced | | | `"strictMetadataEmit"` | `true` | | | | `"skipTemplateCodegen"` | `false` | enforced | | | `"fullTemplateTypeCheck"` | `true` | | Options that are marked "enforced" are reported as an error if they are explicitly set to a value different from what is specified here. The options marked "required" are required to be set and an error message is displayed if no value is supplied but no default is provided. The purpose of the "application" target is for the options used when the `ngc` invocation contains the root application module. Lazy loaded modules should also be considered "application" targets. The purpose of the "library" target is for are all `ngc` invocations that do not contain the root application module or a lazy loaded module. The purpose of the "package" target is to produce a library package that will be an entry point for an npm package. Each entry point should be separately compiled using a "package" target. ##### Example - application To produce a Renderer2 application the options would look like, ```json { "compileOptions": { ... }, "angularCompilerOptions": { "target": "application" } } ``` alternately, since the recommended `"application"` options are the default values, the `"angularCompilerOptions"` can be out. ##### Example - library To produce a Renderer2 library the options would look like, ```json { "compileOptions": { ... }, "angularCompilerOptions": { "target": "library" } } ``` ##### Example - package To produce a Renderer2 package the options would look like, ```json { "compileOptions": { ... }, "angularCompilerOptions": { "target": "package" } } ``` ##### Example - Ivy application To produce an Ivy application the options would look like, ```json { "compileOptions": { ... }, "angularCompilerOptions": { "target": "application", "enableIvy": true } } ``` ##### Example - Ivy library To produce an Ivy library the options would look like, ```json { "compileOptions": { ... }, "angularCompilerOptions": { "target": "library", "enableIvy": true } } ``` ##### Example - Ivy package Ivy packages are not supported in Angular 6.0 as they are not recommended in npm packages as they would only be usable if inside Ivy applications. Ivy applications support Renderer2 libraries so npm packages should all be Renderer2 libraries. ## `ng_module` output (Bazel) The `ng_module` rule describes the source necessary to produce a Angular library that is reusable and composable into an application. ### Angular 5.0 The `ng_module` rule invokes `ngc`[<sup>1<sup>](#ngc_wrapped) to produce the Angular output. However, `ng_module` uses a feature, the `.ngsummary.json` file, not normally used and is often difficult to configure correctly. The `.ngsummary.json` describes all the information that is necessary for the compiler to use a generated factory. It is produced by actions defined in the `ng_module` rule and is consumed by actions defined by `ng_module` rules that depend on other `ng_module` rules. ### Angular Ivy The `ng_module` rule will still use `ngc` to produce the Angular output but, when producing ivy output, it no longer will need the `.ngsummary.json` file. #### `ng_experimental_ivy_srcs` The `ng_experimental_ivy_srcs` can be used as use to cause the ivy versions of files to be generated. It is intended the sole dependency of a `ts_dev_server` rule and the `ts_dev_server` sources move to `ng_experimental_iv_srcs`. #### `ng_module` Ivy output The `ng_module` is able to provide the Ivy version of the `.js` files which will be generated with as `.ivy.js` for the development sources and `.ivy.mjs` for the production sources. The `ng_module` rule will also generate a `angular.back_patch.js` and `.mjs` files and a `module_scope.json` file. The type of the `module_scope.json` file will be: ```ts interface ModuleScopeSummary { [moduleName: string]: ModuleScopeEntry[]; } ``` where `moduleName` is the name of the as it would appear in an import statement in a `.ts` file at the same relative location in the source tree. All the references in this file are also relative to this location. ##### Example The following is a typical Angular application build in bazel: *src/BUILD.bazel* ```py ng_module( name = "src", srcs = glob(["*.ts"]), deps= ["//common/component"], ) ts_dev_server( name = "server", srcs = ":src", ) ``` To use produce an Ivy version you would add: ```py ng_experimental_ivy_srcs( name = "ivy_srcs", srcs = ":src", ) ts_dev_server( name = "server_ivy", srcs = [":ivy_srcs"] ) ``` To serve the Renderer2 version, you would run: ```sh bazel run :server ``` to serve the Ivy version you would run ```sh bazel run :server_ivy ``` The `ng_experimental_ivy_srcs` rule is only needed when Ivy is experimental. Once Ivy is released, the `ng_experimental_ivy_srcs` dependent rules can be removed. --- <a name="myfootnote1"><sup>1</sup></a> More correctly, it calls `performCompilation` from the `@angular/compiler-cli` which is what `ngc` does too.
{ "end_byte": 25537, "start_byte": 17366, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/separate_compilation.md" }
angular/packages/compiler/design/architecture.md_0_2710
# DESIGN DOC(Ivy): Compiler Architecture AUTHOR: arick@, chuckj@ Status: Draft ## Overview This document details the new architecture of the Angular compiler in a post-Ivy world, as well as the compatibility functionality needed for the ecosystem to gradually migrate to Ivy without breaking changes. This compatibility ensures Ivy and non-Ivy libraries can coexist during the migration period. ### The Ivy Compilation Model Broadly speaking, The Ivy model is that Angular decorators (`@Injectable`, etc) are compiled to static properties on the classes (`ɵprov`). This operation must take place without global program knowledge, and in most cases only with knowledge of that single decorator. The one exception is `@Component`, which requires knowledge of the metadata from the `@NgModule` which declares the component in order to properly generate the component def (`ɵcmp`). In particular, the selectors which are applicable during compilation of a component template are determined by the module that declares that component, and the transitive closure of the exports of that module's imports. Going forward, this will be the model by which Angular code will be compiled, shipped to NPM, and eventually bundled into applications. ### Existing code on NPM Existing Angular libraries exist on NPM today and are distributed in the Angular Package Format, which details the artifacts shipped. Today this includes compiled `.js` files in both ES2015 and ESM (ES5 + ES2015 modules) flavors, `.d.ts` files, and `.metadata.json` files. The `.js` files have the Angular decorator information removed, and the `.metadata.json` files preserve the decorator metadata in an alternate format. ### High Level Proposal We will produce two compiler entry-points, `ngtsc` and `ngcc`. `ngtsc` will be a Typescript-to-Javascript transpiler that reifies Angular decorators into static properties. It is a minimal wrapper around `tsc` which includes a set of Angular transforms. While Ivy is experimental, `ngc` operates as `ngtsc` when the `angularCompilerOption` `enableIvy` flag is set to `true` in the `tsconfig.json` file for the project. `ngcc` (which stands for Angular compatibility compiler) is designed to process code coming from NPM and produce the equivalent Ivy version, as if the code was compiled with `ngtsc`. It will operate given a `node_modules` directory and a set of packages to compile, and will produce an equivalent directory from which the Ivy equivalents of those modules can be read. `ngcc` is a separate script entry point to `@angular/compiler-cli`. `ngcc` can also be run as part of a code loader (e.g. for Webpack) to transpile packages being read from `node_modules` on-demand. ##
{ "end_byte": 2710, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/architecture.md" }
angular/packages/compiler/design/architecture.md_2710_11628
Detailed Design ### Ivy Compilation Model The overall architecture of `ngtsc` it is a set of transformers that adjust what is emitted by TypeScript for a TypeScript program. Angular transforms both the `.js` files and the `.d.ts` files to reflect the content of Angular decorators that are then erased. This transformation is done file by file with no global knowledge except during the type-checking and for reference inversion discussed below. For example, the following class declaration: ```ts import {Component, Input} from '@angular/core'; @Component({ selector: 'greet', template: '<div> Hello, {{name}}! </div>' }) export class GreetComponent { @Input() name: string; } ``` will normally be translated into something like this: ```js const tslib_1 = require("tslib"); const core_1 = require("@angular/core"); let GreetComponent = class GreetComponent { }; tslib_1.__decorate([ core_1.Input(), tslib_1.__metadata("design:type", String) ], GreetComponent.prototype, "name", void 0); GreetComponent = tslib_1.__decorate([ core_1.Component({ selector: 'greet', template: '<div> Hello, {{name}}! </div>' }) ], GreetComponent); ``` which translates the decorator into a form that is executed at runtime. A `.d.ts` file is also emitted that might look something like ```ts export class GreetComponent { name: string; } ``` In `ngtsc` this is instead emitted as, ```js const i0 = require("@angular/core"); class GreetComponent {} GreetComponent.ɵcmp = i0.ɵɵdefineComponent({ type: GreetComponent, tag: 'greet', factory: () => new GreetComponent(), template: function (rf, ctx) { if (rf & RenderFlags.Create) { i0.ɵɵelementStart(0, 'div'); i0.ɵɵtext(1); i0.ɵɵelementEnd(); } if (rf & RenderFlags.Update) { i0.ɵɵadvance(); i0.ɵɵtextInterpolate1('Hello ', ctx.name, '!'); } } }); ``` and the `.d.ts` contains: ```ts import * as i0 from '@angular/core'; export class GreetComponent { static ɵcmp: i0.NgComponentDef< GreetComponent, 'greet', {input: 'input'} >; } ``` The information needed by reference inversion and type-checking is included in the type declaration of the `ɵcmp` in the `.d.ts`. #### TypeScript architecture The overall architecture of TypeScript is: |------------| |----------------------------------> | TypeScript | | | .d.ts | | |------------| | |------------| |-----| |-----| |------------| | TypeScript | -parse-> | AST | ->transform-> | AST | ->print-> | JavaScript | | source | | |-----| | |-----| | source | |------------| | | | |------------| | type-check | | | | | v | | |--------| | |--> | errors | <---| |--------| The parse step is a traditional recursive descent parser, augmented to support incremental parsing, that emits an abstract syntax tree (AST). The type-checker construct a symbol table and then performs type analysis of every expression in the file, reporting errors it finds. This process is not extended or modified by `ngtsc`. The transform step is a set of AST to AST transformations that perform various tasks such as, removing type declarations, lowering module and class declarations to ES5, converting `async` methods to state-machines, etc. #### Extension points TypeScript supports the following extension points to alter its output. You can, 1. Modify the TypeScript source it sees (`CompilerHost.getSourceFile`) 2. Alter the list of transforms (`CustomTransformers`) 3. Intercept the output before it is written (`WriteFileCallback`) It is not recommended to alter the source code as this complicates the managing of source maps, makes it difficult to support incremental parsing, and is not supported by TypeScript's language service plug-in model. #### Angular Extensions Angular transforms the `.js` output by adding Angular specific transforms to the list of transforms executed by TypeScript. As of TypeScript 2.7, there is no similar transformer pipe-line for `.d.ts` files so the .d.ts files will be altered during the `WriteFileCallback`. #### Decorator Reification Angular supports the following class decorators: - `@Component` - `@Directive` - `@Injectable` - `@NgModule` - `@Pipe` There are also a list of helper decorators that make the `@Component` and `@Directive` easier to use such as `@Input`, `@Output`, etc.; as well as a set of decorators that help `@Injectable` classes customize the injector such as `@Inject` and `@SkipSelf`. Each of the class decorators can be thought of as class transformers that take the declared class and transform it, possibly using information from the helper decorators, to produce an Angular class. The JIT compiler performs this transformation at runtime. The AOT compiler performs this transformation at compile time. Each of the class decorators' class transformer creates a corresponding static member on the class that describes to the runtime how to use the class. For example, the `@Component` decorator creates a `ɵcmp` static member, `@Directive` create a `ɵdir`, etc. Internally, these class transformers are called a "Compiler". Most of the compilers are straight forward translations of the metadata specified in the decorator to the information provided in the corresponding definition and, therefore, do not require anything outside the source file to perform the conversion. However, the component, during production builds and for type checking a template require the module scope of the component which requires information from other files in the program. #### Compiler design Each "Compiler" which transforms a single decorator into a static field will operate as a "pure function". Given input metadata about a particular type and decorator, it will produce an object describing the field to be added to the type, as well as the initializer value for that field (in Output AST format). A Compiler must not depend on any inputs not directly passed to it (for example, it must not scan sources or metadata for other symbols). This restriction is important for two reasons: 1. It helps to enforce the Ivy locality principle, since all inputs to the Compiler will be visible. 2. It protects against incorrect builds during `--watch` mode, since the dependencies between files will be easily traceable. Compilers will also not take Typescript nodes directly as input, but will operate against information extracted from TS sources by the transformer. In addition to helping enforce the rules above, this restriction also enables Compilers to run at runtime during JIT mode. For example, the input to the `@Component` compiler will be: * A reference to the class of the component. * The template and style resources of the component. * The selector of the component. * A selector map for the module to which the component belongs. #### Need for static value resolution During some parts of compilation, the compiler will need to statically interpret particular values in the AST, especially values from the decorator metadata. This is a complex problem. For example, while this form of a component is common: ```javascript @Component({ selector: 'foo-cmp', templateUrl: 'templates/foo.html', }) export class Foo {} ``` The following is also permitted: ```javascript export const TEMPLATE_BASE = 'templates/'; export function getTemplateUrl(cmp: string): string { return TEMPLATE_BASE + cmp + '.html'; } export const FOO_SELECTOR = 'foo-cmp'; export const FOO_TEMPLATE_URL = getTemplateUrl('foo'); @Component({ selector: FOO_SELECTOR, templateUrl: FOO_TEMPLATE_URL, }) export class Foo {} ``` `ngc` has a metadata system which attempts to statically understand the "value side" of a program. This allowed it to follow the references and evaluate the expressions required to understand that `FOO_TEMPLATE_URL` evaluates statically to `templates/foo.html`. `ngtsc` will need a similar capability, though the design will be different. The `ngtsc` metadata evaluator will be built as a partial Typescript interpreter, which visits Typescript nodes and evaluates expressions statically. This allows metadata evaluation to happen on demand. It will have some restrictions that aren't present in the `ngc` model - in particular, evaluation will not cross `node_module` boundaries. #### Compiling a te
{ "end_byte": 11628, "start_byte": 2710, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/architecture.md" }
angular/packages/compiler/design/architecture.md_11628_19599
mplate A template is compiled in `TemplateCompiler` by performing the following: 1. Tokenizes the template 2. Parses the tokens into an HTML AST 3. Converts the HTML AST into an Angular Template AST. 4. Translates the Angular Template AST to a template function The Angular Template AST transformed and annotated version of the HTML AST that does the following: 1. Converts Angular template syntax short-cuts such as `*ngFor` and `[name]` into the their canonical versions, (<ng-template> and `bind-name`). 2. Collects references (`#` attribute) and variables (`let-` attributes). 3. Parses and converts binding expressions in the binding expression AST using the variables and references collected As part of this conversion an exhaustive list of selector targets is also produced that describes the potential targets of the selectors of any component, directive or pipe. For the purpose of this document, the name of the pipe is treated as a pipe selector and the expression reference in a binding expression is a potential target of that selector. This list is used in reference inversion discussed below. The `TemplateCompiler` can produce a template function from a string without additional information. However, correct interpretation of that string requires a selector scope discussed below. The selector scope is built at runtime allowing the runtime to use a function built from just a string as long as it is given a selector scope (e.g. an NgModule) to use during instantiation. #### The selector problem To interpret the content of a template, the runtime needs to know what component and directives to apply to the element and what pipes are referenced by binding expressions. The list of candidate components, directives, and pipes are determined by the `NgModule` in which the component is declared. Since the module and component are in separate source files, mapping which components, directives, and pipes referenced is left to the runtime. Unfortunately, this leads to a tree-shaking problem. Since there no direct link between the component and types the component references then all components, directives, and pipes declared in the module, and any module imported from the module, must be available at runtime or risk the template failing to be interpreted correctly. Including everything can lead to a very large program which contains many components the application doesn't actually use. The process of removing unused code is traditionally referred to as "tree-shaking". To determine what codes is necessary to include, a tree-shakers produces the transitive closure of all the code referenced by the bootstrap function. If the bootstrap code references a module then the tree-shaker will include everything imported or declared into the module. This problem can be avoided if the component would contain a list of the components, directives, and pipes on which it depends allowing the module to be ignored altogether. The program then need only contain the types the initial component rendered depends on and on any types those dependencies require. The process of determining this list is called reference inversion because it inverts the link from the module (which hold the dependencies) to component into a link from the component to its dependencies. ##### Reference inversion in practice The View Compiler will optionally be able to perform the step of "reference inversion". If this option is elected (likely with a command-line option), the View Compiler must receive as input the selector scope for the component, indicating all of the directives and pipes that are in scope for the component. It scans the component's template, and filters the list of all directives and pipes in scope down to those which match elements in the template. This list is then reified into an instruction call which will patch it onto the component's definition. #### Flowing module & selector metadata via types (reference inversion) Reference inversion is an optional step of the compiler that can be used during production builds that prepares the Angular classes for tree-shaking. The process of reference inversion is to turn the list of selector targets produced by the template compiler to the list of types on which it depends. This mapping requires a selector scope which contains a mapping of CSS selectors declared in components, directives, and pipe names and their corresponding class. To produce this list for a module you do the following, 1. Add all the type declared in the `declarations` field. 2. For each module that is imported. - Add the exported components, directives, and pipes - Repeat these sub-steps for with each exported module For each type in the list produced above, parse the selector and convert them all into a selector matcher that, given a target, produces the type that matches the selector. This is referred to as the selector scope. Given a selector scope, a dependency list is formed by producing the set of types that are matched in selector scope from the selector target list produced by the template compiler. ##### Finding a components module. A component's module can be found by using the TypeScript language service's `findReferences`. If one of the references is to a class declaration with an `@NgModule` annotation, process the class as described above to produce the selector scope. If the class is the declaration list of the `@NgModule` then use the scope produced for that module. When processing the `@NgModule` class, the type references can be found using the program's `checker` `getSymbolAtLocation` (potentially calling `getAliasedSymbol` if it is an alias symbol, `SymbolFlags.Alias`) and then using `Symbol`'s `declarations` field to get the list of declarations nodes (there should only be one for a `class`, there can be several for an `interface`). ##### DTS modification As mentioned, TypeScript has no built in transformation pipeline for .d.ts files. Transformers can process the parsed AST and add/delete/modify nodes, but the type information emitted in the .d.ts files is purely from the initial AST, not the transformed AST. Thus, if the changes made by transformers are to be reflected in the .d.ts output, this must happen via some other mechanism. This leaves option 3 from above (`WriteFileCallback`) as the only point where .d.ts modification is possible. We will parse the .d.ts file as it's written and use the indices in the AST to coordinate insertion and deletion operations to fix up the generated types. #### Type checking a template A model very similar to the Renderer2 style of code generation can be used to generate type-check blocks for every template declared in a module. The module for type-checking can be similar to that used in `type_check_compiler.ts` for the Renderer2 AST. `type_check_compiler.ts` just emits all the binding expressions in a way that can be type-checked, calculating the correct implicit target and guarded by the correct type guards. Global type information is required for calculating type guards and for determining pipe calls. Type guards require determining which directives apply to an element to determine if any have a type guard. Correctly typing an expression that includes a pipe requires determining the result type of the `transform` method of the type. Additionally, more advanced type-checking also requires determining the types of the directives that apply to an element as well as how the attributes map to the properties of the directives. The types of directives can be found using a selector scope as described for reference inversion. Once a selector scope is produced, the component and directives that apply to an element can be determined from the selector scope. The `.d.ts` changes described above also includes the attribute to property maps. The `TypeGuard`s are recorded as static fields that are included in the `.d.ts` file of the directive. #### Overall ngtsc
{ "end_byte": 19599, "start_byte": 11628, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/architecture.md" }
angular/packages/compiler/design/architecture.md_19599_24811
architecture ##### Compilation flow When `ngtsc` starts running, it first parses the `tsconfig.json` file and then creates a `ts.Program`. Several things need to happen before the transforms described above can run: * Metadata must be collected for input source files which contain decorators. * Resource files listed in `@Component` decorators must be resolved asynchronously. The CLI, for example, may wish to run Webpack to produce the `.css` input to the `styleUrls` property of an `@Component`. * Diagnostics must be run, which creates the `TypeChecker` and touches every node in the program (a decently expensive operation). Because resource loading is asynchronous (and in particular, may actually be concurrent via subprocesses), it's desirable to kick off as much resource loading as possible before doing anything expensive. Thus, the compiler flow looks like: 1. Create the `ts.Program` 2. Scan source files for top-level declarations which have trivially detectable `@Component` annotations. This avoids creating the `TypeChecker`. * For each such declaration that has a `templateUrl` or `styleUrls`, kick off resource loading for that URL and add the `Promise` to a queue. 3. Get diagnostics and report any initial error messages. At this point, the `TypeChecker` is primed. 4. Do a thorough scan for `@Component` annotations, using the `TypeChecker` and the metadata system to resolve any complex expressions. 5. Wait on all resources to be resolved. 6. Calculate the set of transforms which need to be applied. 7. Kick off Tsickle emit, which runs the transforms. 8. During the emit callback for .d.ts files, re-parse the emitted .d.ts and merge in any requested changes from the Angular compiler. ##### Resource loading Before the transformers can run, `templateUrl` and `styleUrls` need to be asynchronously resolved to their string contents. This resolution will happen via a Host interface which the compiler will expect to be implemented. ```javascript interface NgtscCompilerHost extends ts.CompilerHost { loadResource(path: string): Promise<string>; } ``` In the `ngtsc` CLI, this interface will be implemented using a plain read from the filesystem. Another consumer of the `ngtsc` API may wish to implement custom resource loading. For example, `@angular/cli` will invoke webpack on the resource paths to produce the result. ##### Tsickle ###### Special design considerations Currently, the design of Tsickle necessitates special consideration for its integration into `ngtsc`. Tsickle masquerades as a set of transformers, and has a particular API for triggering emit. As a transformer, Tsickle expects to be able to serialize the AST it's given to code strings (that is, it expects to be able to call `.getText()` on any given input node). This restriction means that transformers which run before Tsickle cannot introduce new synthetic nodes in the AST (for example, they cannot create new static properties on classes). Tsickle also currently converts `ts.Decorator` nodes into static properties on a class, an operation known as decorator down-leveling. ###### Plan for Tsickle Because of the serialization restriction, Tsickle must run first, before the Angular transformer. However, the Angular transformer will operate against `ts.Decorator` nodes, not Tsickle's downleveled format. The Angular transformer will also remove the decorator nodes during compilation, so there is no need for Tsickle decorator downleveling. Thus, Tsickle's downlevel can be disabled for `ngtsc`. So the Angular transformer will run after the Tsickle transforms, but before the Typescript transforms. ##### Watch mode `ngtsc` will support TypeScript's `--watch` mode for incremental compilation. Internally, watch mode is implemented via reuse of a `ts.Program` from the previous compile. When a `ts.Program` is reused, TypeScript determines which source files need to be re-typechecked and re-emitted, and performs those operations. This mode works for the Angular transformer and most of the decorator compilers, because they operate only using the metadata from one particular file. The exception is the `@Component` decorator, which requires the selector scope for the module in which the component is declared in. Effectively, this means that all components within a selector scope must be recompiled together, as any changes to the component selectors or type names, for example, will invalidate the compilation of all templates of all components in the scope. Since TypeScript will not track these changes, it's the responsibility of `ngtsc` to ensure the re-compilation of the right set of files. `ngtsc` will do this by tracking the set of source files included in each module scope within its `ts.Program`. When an old `ts.Program` is reused, the previous program's selector scope records can be used to determine whether any of the included files have changed, and thus whether re-compilation of components in the scope is necessary. In the future, this tracking can be improved to reduce the number of false positives by tracking the specific data which would trigger recompiles instead of conservatively triggering on any file modifications. ### The compatibili
{ "end_byte": 24811, "start_byte": 19599, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/architecture.md" }
angular/packages/compiler/design/architecture.md_24811_34082
ty compiler #### The compatibility problem Not all Angular code is compiled at the same time. Applications have dependencies on shared libraries, and those libraries are published on NPM in their compiled form and not as Typescript source code. Even if an application is built using `ngtsc`, its dependencies may not have been. If a particular library was not compiled with `ngtsc`, it does not have reified decorator properties in its `.js` distribution as described above. Linking it against a dependency that was not compiled in the same way will fail at runtime. #### Converting pre-Ivy code Since Ivy code can only be linked against other Ivy code, to build the application all pre-Ivy dependencies from NPM must be converted to Ivy dependencies. This transformation must happen as a precursor to running `ngtsc` on the application, and future compilation and linking operations need to be made against this transformed version of the dependencies. It is possible to transpile non-Ivy code in the Angular Package Format (v6) into Ivy code, even though the `.js` files no longer contain the decorator information. This works because the Angular Package Format includes `.metadata.json` files for each `.js` file. These metadata files contain information that was present in the Typescript source but was removed during transpilation to Javascript, and this information is sufficient to generate patched `.js` files which add the Ivy static properties to decorated classes. #### Metadata from APF The `.metadata.json` files currently being shipped to NPM includes, among other information, the arguments to the Angular decorators which `ngtsc` downlevels to static properties. For example, the `.metadata.json` file for `CommonModule` contains the information for its `NgModule` decorator which was originally present in the Typescript source: ```json "CommonModule": { "__symbolic": "class", "decorators": [{ "__symbolic": "call", "expression": { "__symbolic": "reference", "module": "@angular/core", "name": "NgModule", "line": 22, "character": 1 }, "arguments": [{ "declarations": [...], "exports": [...], "providers": [...] }] }] } ``` #### ngcc operation `ngcc` will by default scan `node_modules` and produce Ivy-compatible versions of every package it discovers built using Angular Package Format (APF). It detects the APF by looking for the presence of a `.metadata.json` file alongside the package's `module` entrypoint. Alternatively, `ngcc` can be initiated by passing the name of a single NPM package. It will begin converting that package, and recurse into any dependencies of that package that it discovers which have not yet been converted. The output of `ngcc` is a directory called `ngcc_node_modules` by default, but can be renamed based on an option. Its structure mirrors that of `node_modules`, and the packages that are converted have the non-transpiled files copied verbatim - `package.json`, etc are all preserved in the output. Only the `.js` and `.d.ts` files are changed, and the `.metadata.json` files are removed. An example directory layout would be: ``` # input node_modules/ ng-dep/ package.json index.js (pre-ivy) index.d.ts (pre-ivy) index.metadata.json other.js # output ngcc_node_modules ng-dep/ package.json index.js (ivy compatible) index.d.ts (ivy-compatible) other.js (copied verbatim) ``` #### Operation as a loader `ngcc` can be called as a standalone entrypoint, but it can also be integrated into the dependency loading operation of a bundler such as Rollup or Webpack. In this mode, the `ngcc` API can be used to read a file originally in `node_modules`. If the file is from a package which has not yet been converted, `ngcc` will convert the package and its dependencies before returning the file's contents. In this mode, the on-disk `ngcc_node_modules` directory functions as a cache. If the file being requested has previously been converted, its contents will be read from `ngcc_node_modules`. #### Compilation Model `ngtsc` operates using a pipeline of different transformations, each one processing a different Angular decorator and converting it into a static property on the type being decorated. `ngcc` is architected to reuse as much of that process as possible. Compiling a package in `ngcc` involves the following steps: 1. Parse the JS files of the package with the Typescript parser. 2. Invoke the `StaticReflector` system from the legacy `@angular/compiler` to parse the `.metadata.json` files. 3. Run through each Angular decorator in the Ivy system and compile: 1. Use the JS AST plus the information from the `StaticReflector` to construct the input to the annotation's Compiler. 2. Run the annotation's Compiler which will produce a partial class and its type declaration. 3. Extract the static property definition from the partial class. 4. Combine the compiler outputs with the JS AST to produce the resulting `.js` and `.d.ts` files, and write them to disk. 5. Copy over all other files. #### Merging with JS output At first glance it is desirable for each Compiler's output to be patched into the AST for the modules being compiled, and then to generate the resulting JS code and sourcemaps using Typescript's emit on the AST. This is undesirable for several reasons: * The round-trip through the Typescript parser and emitter might subtly change the input JS code - dropping comments, reformatting code, etc. This is not ideal, as users expect the input code to remain as unchanged as possible. * It isn't possible in Typescript to directly emit without going through any of Typescript's own transformations. This may cause expressions to be reformatted, code to be downleveled, and requires configuration of an output module system into which the code will be transformed. For these reasons, `ngcc` will not use the TS emitter to produce the final patched `.js` files. Instead, the JS text will be manipulated directly, with the help of the `magic-string` or similar library to ensure the changes are reflected in the output sourcemaps. The AST which is parsed from the JS files contains position information of all the types in the JS source, and this information can be used to determine the correct insertion points for the Ivy static fields. Similarly, the `.d.ts` files will be parsed by the TS parser, and the information used to determine the insertion points of typing information that needs to be added to individual types (as well as associated imports). ##### Module systems The Angular Package Format includes more than one copy of a package's code. At minimum, it includes one ESM5 (ES5 code in ES Modules) entrypoint, one ES2015 entrypoint, and one UMD entrypoint. Some libraries _not_ following the package format may still work in the Angular CLI, if they export code that can be loaded by Webpack. Thus, `ngcc` will have two approaches for dealing with packages on NPM. 1. APF Path: libraries following the Angular package format will have their source code updated to contain Ivy definitions. This ensures tree-shaking will work properly. 2. Compatibility Path: libraries where `ngcc` cannot determine how to safely modify the existing code will have a patching operation applied. This patching operation produces a "wrapper" file for each file containing an Angular entity, which re-exports patched versions of the Angular entities. This is not compatible with tree-shaking, but will work for libraries which `ngcc` cannot otherwise understand. A warning will be printed to notify the user they should update the version of the library if possible. For example, if a library ships with commonjs-only code or a UMD bundle that `ngcc` isn't able to patch directly, it can generate patching wrappers instead of modifying the input code. ### Language Service The `@angular/language-service` is mostly out of scope for this document, and will be treated in a separate design document. However, it's worth a consideration here as the architecture of the compiler impacts the language service's design. A Language Service is an analysis engine that integrates into an IDE such as Visual Studio Code. It processes code and provides static analysis information regarding that code, as well as enables specific IDE operations such as code completion, tracing of references, and refactoring. The `@angular/language-service` is a wrapper around the Typescript language service (much as `ngtsc` wraps `tsc`) and extends the analysis of Typescript with a specific understanding of Angular concepts. In particular, it also understands the Angular Template Syntax and can bridge between the component class in Typescript and expressions in the templates. To provide code completion and other intelligence around template contents, the Angular Language Service must have a similar understanding of the template contents as the `ngtsc` compiler - it must know the selector map associated with the component, and the metadata of each directive or pipe used in the template. Whether the language service consumes the output of `ngcc` or reuses its metadata transformation logic, the data it needs will be available.
{ "end_byte": 34082, "start_byte": 24811, "url": "https://github.com/angular/angular/blob/main/packages/compiler/design/architecture.md" }
angular/packages/compiler/test/integration_spec.ts_0_2061
/** * @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 {Component, Directive, Input} from '@angular/core'; import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('integration tests', () => { let fixture: ComponentFixture<TestComponent>; describe('directives', () => { it('should support dotted selectors', waitForAsync(() => { @Directive({ selector: '[dot.name]', standalone: false, }) class MyDir { @Input('dot.name') value!: string; } TestBed.configureTestingModule({ declarations: [MyDir, TestComponent], }); const template = `<div [dot.name]="'foo'"></div>`; fixture = createTestComponent(template); fixture.detectChanges(); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); expect(myDir.value).toEqual('foo'); })); }); describe('ng-container', () => { it('should work regardless the namespace', waitForAsync(() => { @Component({ selector: 'comp', template: '<svg><ng-container *ngIf="1"><rect x="10" y="10" width="30" height="30"></rect></ng-container></svg>', standalone: false, }) class MyCmp {} const f = TestBed.configureTestingModule({declarations: [MyCmp]}).createComponent(MyCmp); f.detectChanges(); expect(f.nativeElement.children[0].children[0].tagName).toEqual('rect'); })); }); }); @Component({ selector: 'test-cmp', template: '', standalone: false, }) class TestComponent {} function createTestComponent(template: string): ComponentFixture<TestComponent> { return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent( TestComponent, ); }
{ "end_byte": 2061, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/integration_spec.ts" }
angular/packages/compiler/test/style_url_resolver_spec.ts_0_1031
/** * @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 {isStyleUrlResolvable} from '@angular/compiler/src/style_url_resolver'; describe('isStyleUrlResolvable', () => { it('should resolve relative urls', () => { expect(isStyleUrlResolvable('someUrl.css')).toBe(true); }); it('should resolve package: urls', () => { expect(isStyleUrlResolvable('package:someUrl.css')).toBe(true); }); it('should not resolve empty urls', () => { expect(isStyleUrlResolvable(null)).toBe(false); expect(isStyleUrlResolvable('')).toBe(false); }); it('should not resolve urls with other schema', () => { expect(isStyleUrlResolvable('http://otherurl')).toBe(false); }); it('should not resolve urls with absolute paths', () => { expect(isStyleUrlResolvable('/otherurl')).toBe(false); expect(isStyleUrlResolvable('//otherurl')).toBe(false); }); });
{ "end_byte": 1031, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/style_url_resolver_spec.ts" }
angular/packages/compiler/test/util_spec.ts_0_3478
/** * @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 {escapeRegExp, partitionArray, splitAtColon, stringify, utf8Encode} from '../src/util'; describe('util', () => { describe('splitAtColon', () => { it('should split when a single ":" is present', () => { expect(splitAtColon('a:b', [])).toEqual(['a', 'b']); }); it('should trim parts', () => { expect(splitAtColon(' a : b ', [])).toEqual(['a', 'b']); }); it('should support multiple ":"', () => { expect(splitAtColon('a:b:c', [])).toEqual(['a', 'b:c']); }); it('should use the default value when no ":" is present', () => { expect(splitAtColon('ab', ['c', 'd'])).toEqual(['c', 'd']); }); }); describe('RegExp', () => { it('should escape regexp', () => { expect(new RegExp(escapeRegExp('b')).exec('abc')).toBeTruthy(); expect(new RegExp(escapeRegExp('b')).exec('adc')).toBeFalsy(); expect(new RegExp(escapeRegExp('a.b')).exec('a.b')).toBeTruthy(); expect(new RegExp(escapeRegExp('a.b')).exec('axb')).toBeFalsy(); }); }); describe('utf8encode', () => { // tests from https://github.com/mathiasbynens/wtf-8 it('should encode to utf8', () => { const tests = [ ['abc', 'abc'], // // 1-byte ['\0', '\0'], // // 2-byte ['\u0080', '\xc2\x80'], ['\u05ca', '\xd7\x8a'], ['\u07ff', '\xdf\xbf'], // // 3-byte ['\u0800', '\xe0\xa0\x80'], ['\u2c3c', '\xe2\xb0\xbc'], ['\uffff', '\xef\xbf\xbf'], // //4-byte ['\uD800\uDC00', '\xF0\x90\x80\x80'], ['\uD834\uDF06', '\xF0\x9D\x8C\x86'], ['\uDBFF\uDFFF', '\xF4\x8F\xBF\xBF'], // unmatched surrogate halves // high surrogates: 0xD800 to 0xDBFF ['\uD800', '\xED\xA0\x80'], ['\uD800\uD800', '\xED\xA0\x80\xED\xA0\x80'], ['\uD800A', '\xED\xA0\x80A'], ['\uD800\uD834\uDF06\uD800', '\xED\xA0\x80\xF0\x9D\x8C\x86\xED\xA0\x80'], ['\uD9AF', '\xED\xA6\xAF'], ['\uDBFF', '\xED\xAF\xBF'], // low surrogates: 0xDC00 to 0xDFFF ['\uDC00', '\xED\xB0\x80'], ['\uDC00\uDC00', '\xED\xB0\x80\xED\xB0\x80'], ['\uDC00A', '\xED\xB0\x80A'], ['\uDC00\uD834\uDF06\uDC00', '\xED\xB0\x80\xF0\x9D\x8C\x86\xED\xB0\x80'], ['\uDEEE', '\xED\xBB\xAE'], ['\uDFFF', '\xED\xBF\xBF'], ]; tests.forEach(([input, output]) => { expect( utf8Encode(input) .map((byte) => String.fromCharCode(byte)) .join(''), ).toEqual(output); }); }); }); describe('stringify()', () => { it('should handle objects with no prototype.', () => { expect(stringify(Object.create(null))).toEqual('object'); }); }); describe('partitionArray()', () => { it('should handle empty arrays', () => { expect(partitionArray([], () => true)).toEqual([[], []]); }); it('should handle arrays with primitive type values', () => { expect(partitionArray([1, 2, 3], (el: number) => el < 2)).toEqual([[1], [2, 3]]); }); it('should handle arrays of objects', () => { expect(partitionArray([{id: 1}, {id: 2}, {id: 3}], (el: any) => el.id < 2)).toEqual([ [{id: 1}], [{id: 2}, {id: 3}], ]); }); }); });
{ "end_byte": 3478, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/util_spec.ts" }
angular/packages/compiler/test/BUILD.bazel_0_1613
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") # Test that should only be run in node NODE_ONLY = [ "**/*_node_only_spec.ts", "aot/**/*.ts", ] circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/compiler/index.mjs", deps = ["//packages/compiler"], ) ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.ts"], exclude = NODE_ONLY, ), deps = [ "//packages:types", "//packages/common", "//packages/compiler", "//packages/compiler/test/expression_parser/utils", "//packages/compiler/test/ml_parser/util", "//packages/core", "//packages/core/src/compiler", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/testing", "@npm//source-map", ], ) ts_library( name = "test_node_only_lib", testonly = True, srcs = glob( NODE_ONLY, ), deps = [ ":test_lib", "//packages/compiler", "//packages/compiler/test/expression_parser/utils", "//packages/core", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ":test_node_only_lib", "@npm//source-map", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
{ "end_byte": 1613, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/BUILD.bazel" }
angular/packages/compiler/test/compiler_facade_interface_spec.ts_0_7076
/** * @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 core from '../../core/src/compiler/compiler_facade_interface'; import {FactoryTarget} from '../public_api'; import * as compiler from '../src/compiler_facade_interface'; /** * This file is compiler level file which asserts that the set of interfaces in `@angular/core` and * `@angular/compiler` match. (Build time failure.) * * If this file fails to compile it means these two files when out of sync: * - packages/compiler/src/compiler_facade_interface.ts (master) * - packages/core/src/render3/jit/compiler_facade_interface.ts (copy) * * Please ensure that the two files are in sync using this command: * ``` * cp packages/compiler/src/compiler_facade_interface.ts \ * packages/core/src/render3/jit/compiler_facade_interface.ts * ``` */ const coreExportedCompilerFacade1: core.ExportedCompilerFacade = null! as compiler.ExportedCompilerFacade; const compilerExportedCompilerFacade2: compiler.ExportedCompilerFacade = null! as core.ExportedCompilerFacade; const coreCompilerFacade: core.CompilerFacade = null! as compiler.CompilerFacade; const compilerCompilerFacade: compiler.CompilerFacade = null! as core.CompilerFacade; const coreCoreEnvironment: core.CoreEnvironment = null! as compiler.CoreEnvironment; const compilerCoreEnvironment: compiler.CoreEnvironment = null! as core.CoreEnvironment; const coreResourceLoader: core.ResourceLoader = null! as compiler.ResourceLoader; const compilerResourceLoader: compiler.ResourceLoader = null! as core.ResourceLoader; const coreProvider: core.Provider = null! as compiler.Provider; const compilerProvider: compiler.Provider = null! as core.Provider; const coreR3FactoryTarget: core.FactoryTarget = null! as compiler.FactoryTarget; const compilerR3FactoryTarget: compiler.FactoryTarget = null! as core.FactoryTarget; const coreR3FactoryTarget2: FactoryTarget = null! as core.FactoryTarget; const compilerR3FactoryTarget2: FactoryTarget = null! as core.FactoryTarget; const coreR3FactoryTarget3: core.FactoryTarget = null! as FactoryTarget; const compilerR3FactoryTarget3: compiler.FactoryTarget = null! as FactoryTarget; const coreR3DependencyMetadataFacade: core.R3DependencyMetadataFacade = null! as compiler.R3DependencyMetadataFacade; const compilerR3DependencyMetadataFacade: compiler.R3DependencyMetadataFacade = null! as core.R3DependencyMetadataFacade; const coreR3DeclareDependencyMetadataFacade: core.R3DeclareDependencyMetadataFacade = null! as compiler.R3DeclareDependencyMetadataFacade; const compilerR3DeclareDependencyMetadataFacade: compiler.R3DeclareDependencyMetadataFacade = null! as core.R3DeclareDependencyMetadataFacade; const coreR3PipeMetadataFacade: core.R3PipeMetadataFacade = null! as compiler.R3PipeMetadataFacade; const compilerR3PipeMetadataFacade: compiler.R3PipeMetadataFacade = null! as core.R3PipeMetadataFacade; const coreR3DeclarePipeFacade: core.R3DeclarePipeFacade = null! as compiler.R3DeclarePipeFacade; const compilerR3DeclarePipeFacade: compiler.R3DeclarePipeFacade = null! as core.R3DeclarePipeFacade; const coreR3InjectableMetadataFacade: core.R3InjectableMetadataFacade = null! as compiler.R3InjectableMetadataFacade; const compilerR3InjectableMetadataFacade: compiler.R3InjectableMetadataFacade = null! as core.R3InjectableMetadataFacade; const coreR3DeclareInjectableFacade: core.R3DeclareInjectableFacade = null! as compiler.R3DeclareInjectableFacade; const compilerR3DeclareInjectableFacade: compiler.R3DeclareInjectableFacade = null! as core.R3DeclareInjectableFacade; const coreR3NgModuleMetadataFacade: core.R3NgModuleMetadataFacade = null! as compiler.R3NgModuleMetadataFacade; const compilerR3NgModuleMetadataFacade: compiler.R3NgModuleMetadataFacade = null! as core.R3NgModuleMetadataFacade; const coreR3DeclareNgModuleFacade: core.R3DeclareNgModuleFacade = null! as compiler.R3DeclareNgModuleFacade; const compilerR3DeclareNgModuleFacade: compiler.R3DeclareNgModuleFacade = null! as core.R3DeclareNgModuleFacade; const coreR3InjectorMetadataFacade: core.R3InjectorMetadataFacade = null! as compiler.R3InjectorMetadataFacade; const compilerR3InjectorMetadataFacade: compiler.R3InjectorMetadataFacade = null! as core.R3InjectorMetadataFacade; const coreR3DeclareInjectorFacade: core.R3DeclareInjectorFacade = null! as compiler.R3DeclareInjectorFacade; const compilerR3DeclareInjectorFacade: compiler.R3DeclareInjectorFacade = null! as core.R3DeclareInjectorFacade; const coreR3DirectiveMetadataFacade: core.R3DirectiveMetadataFacade = null! as compiler.R3DirectiveMetadataFacade; const compilerR3DirectiveMetadataFacade: compiler.R3DirectiveMetadataFacade = null! as core.R3DirectiveMetadataFacade; const coreR3DeclareDirectiveFacade: core.R3DeclareDirectiveFacade = null! as compiler.R3DeclareDirectiveFacade; const compilerR3DeclareDirectiveFacade: compiler.R3DeclareDirectiveFacade = null! as core.R3DeclareDirectiveFacade; const coreR3ComponentMetadataFacade: core.R3ComponentMetadataFacade = null! as compiler.R3ComponentMetadataFacade; const compilerR3ComponentMetadataFacade: compiler.R3ComponentMetadataFacade = null! as core.R3ComponentMetadataFacade; const coreR3DeclareComponentFacade: core.R3DeclareComponentFacade = null! as compiler.R3DeclareComponentFacade; const compilerR3DeclareComponentFacade: compiler.R3DeclareComponentFacade = null! as core.R3DeclareComponentFacade; const coreR3DeclareDirectiveDependencyFacade: core.R3DeclareDirectiveDependencyFacade = null! as compiler.R3DeclareDirectiveDependencyFacade; const compilerR3DeclareDirectiveDependencyFacade: compiler.R3DeclareDirectiveDependencyFacade = null! as core.R3DeclareDirectiveDependencyFacade; const coreR3DeclarePipeDependencyFacade: core.R3DeclarePipeDependencyFacade = null! as compiler.R3DeclarePipeDependencyFacade; const compilerR3DeclarePipeDependencyFacade: compiler.R3DeclarePipeDependencyFacade = null! as core.R3DeclarePipeDependencyFacade; const coreR3TemplateDependencyFacade: core.R3TemplateDependencyFacade = null! as compiler.R3TemplateDependencyFacade; const compiler3TemplateDependencyFacade: compiler.R3TemplateDependencyFacade = null! as core.R3TemplateDependencyFacade; const coreViewEncapsulation: core.ViewEncapsulation = null! as compiler.ViewEncapsulation; const compilerViewEncapsulation: compiler.ViewEncapsulation = null! as core.ViewEncapsulation; const coreR3QueryMetadataFacade: core.R3QueryMetadataFacade = null! as compiler.R3QueryMetadataFacade; const compilerR3QueryMetadataFacade: compiler.R3QueryMetadataFacade = null! as core.R3QueryMetadataFacade; const coreR3DeclareQueryMetadataFacade: core.R3DeclareQueryMetadataFacade = null! as compiler.R3DeclareQueryMetadataFacade; const compilerR3DeclareQueryMetadataFacade: compiler.R3DeclareQueryMetadataFacade = null! as core.R3DeclareQueryMetadataFacade;
{ "end_byte": 7076, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/compiler_facade_interface_spec.ts" }
angular/packages/compiler/test/security_spec.ts_0_1224
/** * @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 {IFRAME_SECURITY_SENSITIVE_ATTRS, SECURITY_SCHEMA} from '../src/schema/dom_security_schema'; describe('security-related tests', () => { it('should have no overlap between `IFRAME_SECURITY_SENSITIVE_ATTRS` and `SECURITY_SCHEMA`', () => { // The `IFRAME_SECURITY_SENSITIVE_ATTRS` and `SECURITY_SCHEMA` tokens configure sanitization // and validation rules and used to pick the right sanitizer function. // This test verifies that there is no overlap between two sets of rules to flag // a situation when 2 sanitizer functions may be needed at the same time (in which // case, compiler logic should be extended to support that). const schema = new Set(); Object.keys(SECURITY_SCHEMA()).forEach((key: string) => schema.add(key.toLowerCase())); let hasOverlap = false; IFRAME_SECURITY_SENSITIVE_ATTRS.forEach((attr) => { if (schema.has('*|' + attr) || schema.has('iframe|' + attr)) { hasOverlap = true; } }); expect(hasOverlap).toBeFalse(); }); });
{ "end_byte": 1224, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/security_spec.ts" }
angular/packages/compiler/test/selector/selector_spec.ts_0_351
/** * @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 {CssSelector, SelectorMatcher} from '@angular/compiler/src/selector'; import {el} from '@angular/platform-browser/testing/src/browser_util';
{ "end_byte": 351, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/selector/selector_spec.ts" }
angular/packages/compiler/test/selector/selector_spec.ts_353_8045
describe('SelectorMatcher', () => { let matcher: SelectorMatcher; let selectableCollector: (selector: CssSelector, context: any) => void; let s1: any[], s2: any[], s3: any[], s4: any[]; let matched: any[]; function reset() { matched = []; } beforeEach(() => { reset(); s1 = s2 = s3 = s4 = null!; selectableCollector = (selector: CssSelector, context: any) => { matched.push(selector, context); }; matcher = new SelectorMatcher(); }); it('should select by element name case sensitive', () => { matcher.addSelectables((s1 = CssSelector.parse('someTag')), 1); expect(matcher.match(getSelectorFor({tag: 'SOMEOTHERTAG'}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); expect(matcher.match(getSelectorFor({tag: 'SOMETAG'}), selectableCollector)).toEqual(false); expect(matched).toEqual([]); expect(matcher.match(getSelectorFor({tag: 'someTag'}), selectableCollector)).toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should select by class name case insensitive', () => { matcher.addSelectables((s1 = CssSelector.parse('.someClass')), 1); matcher.addSelectables((s2 = CssSelector.parse('.someClass.class2')), 2); expect(matcher.match(getSelectorFor({classes: 'SOMEOTHERCLASS'}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); expect(matcher.match(getSelectorFor({classes: 'SOMECLASS'}), selectableCollector)).toEqual( true, ); expect(matched).toEqual([s1[0], 1]); reset(); expect( matcher.match(getSelectorFor({classes: 'someClass class2'}), selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); }); it('should not throw for class name "constructor"', () => { expect(matcher.match(getSelectorFor({classes: 'constructor'}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); }); it('should select by attr name case sensitive independent of the value', () => { matcher.addSelectables((s1 = CssSelector.parse('[someAttr]')), 1); matcher.addSelectables((s2 = CssSelector.parse('[someAttr][someAttr2]')), 2); expect( matcher.match(getSelectorFor({attrs: [['SOMEOTHERATTR', '']]}), selectableCollector), ).toEqual(false); expect(matched).toEqual([]); expect(matcher.match(getSelectorFor({attrs: [['SOMEATTR', '']]}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); expect( matcher.match(getSelectorFor({attrs: [['SOMEATTR', 'someValue']]}), selectableCollector), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match( getSelectorFor({ attrs: [ ['someAttr', ''], ['someAttr2', ''], ], }), selectableCollector, ), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect( matcher.match( getSelectorFor({ attrs: [ ['someAttr', 'someValue'], ['someAttr2', ''], ], }), selectableCollector, ), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect( matcher.match( getSelectorFor({ attrs: [ ['someAttr2', ''], ['someAttr', 'someValue'], ], }), selectableCollector, ), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect( matcher.match( getSelectorFor({ attrs: [ ['someAttr2', 'someValue'], ['someAttr', ''], ], }), selectableCollector, ), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); }); it('should support "." in attribute names', () => { matcher.addSelectables((s1 = CssSelector.parse('[foo.bar]')), 1); expect(matcher.match(getSelectorFor({attrs: [['barfoo', '']]}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); reset(); expect(matcher.match(getSelectorFor({attrs: [['foo.bar', '']]}), selectableCollector)).toEqual( true, ); expect(matched).toEqual([s1[0], 1]); }); it('should support "$" in attribute names', () => { matcher.addSelectables((s1 = CssSelector.parse('[someAttr\\$]')), 1); expect(matcher.match(getSelectorFor({attrs: [['someAttr', '']]}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); reset(); expect( matcher.match(getSelectorFor({attrs: [['someAttr$', '']]}), selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1]); reset(); matcher.addSelectables((s1 = CssSelector.parse('[some\\$attr]')), 1); expect(matcher.match(getSelectorFor({attrs: [['someattr', '']]}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); expect( matcher.match(getSelectorFor({attrs: [['some$attr', '']]}), selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1]); reset(); matcher.addSelectables((s1 = CssSelector.parse('[\\$someAttr]')), 1); expect(matcher.match(getSelectorFor({attrs: [['someAttr', '']]}), selectableCollector)).toEqual( false, ); expect(matched).toEqual([]); expect( matcher.match(getSelectorFor({attrs: [['$someAttr', '']]}), selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1]); reset(); matcher.addSelectables((s1 = CssSelector.parse('[some-\\$Attr]')), 1); matcher.addSelectables((s2 = CssSelector.parse('[some-\\$Attr][some-\\$-attr]')), 2); expect( matcher.match(getSelectorFor({attrs: [['some\\$Attr', '']]}), selectableCollector), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match( getSelectorFor({ attrs: [ ['some-$-attr', 'someValue'], ['some-$Attr', ''], ], }), selectableCollector, ), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect( matcher.match(getSelectorFor({attrs: [['someattr$', '']]}), selectableCollector), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match(getSelectorFor({attrs: [['some-simple-attr', '']]}), selectableCollector), ).toEqual(false); expect(matched).toEqual([]); reset(); }); it('should select by attr name only once if the value is from the DOM', () => { matcher.addSelectables((s1 = CssSelector.parse('[some-decor]')), 1); const elementSelector = new CssSelector(); const element = el('<div attr></div>'); const empty = element.getAttribute('attr')!; elementSelector.addAttribute('some-decor', empty); matcher.match(elementSelector, selectableCollector); expect(matched).toEqual([s1[0], 1]); }); it('should select by attr name case sensitive and value case insensitive', () => { matcher.addSelectables((s1 = CssSelector.parse('[someAttr=someValue]')), 1); expect( matcher.match(getSelectorFor({attrs: [['SOMEATTR', 'SOMEOTHERATTR']]}), selectableCollector), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match(getSelectorFor({attrs: [['SOMEATTR', 'SOMEVALUE']]}), selectableCollector), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match(getSelectorFor({attrs: [['someAttr', 'SOMEVALUE']]}), selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1]); });
{ "end_byte": 8045, "start_byte": 353, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/selector/selector_spec.ts" }
angular/packages/compiler/test/selector/selector_spec.ts_8049_13845
it('should select by element name, class name and attribute name with value', () => { matcher.addSelectables((s1 = CssSelector.parse('someTag.someClass[someAttr=someValue]')), 1); expect( matcher.match( getSelectorFor({ tag: 'someOtherTag', classes: 'someOtherClass', attrs: [['someOtherAttr', '']], }), selectableCollector, ), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match( getSelectorFor({tag: 'someTag', classes: 'someOtherClass', attrs: [['someOtherAttr', '']]}), selectableCollector, ), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match( getSelectorFor({tag: 'someTag', classes: 'someClass', attrs: [['someOtherAttr', '']]}), selectableCollector, ), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match( getSelectorFor({tag: 'someTag', classes: 'someClass', attrs: [['someAttr', '']]}), selectableCollector, ), ).toEqual(false); expect(matched).toEqual([]); expect( matcher.match( getSelectorFor({tag: 'someTag', classes: 'someClass', attrs: [['someAttr', 'someValue']]}), selectableCollector, ), ).toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should select by many attributes and independent of the value', () => { matcher.addSelectables((s1 = CssSelector.parse('input[type=text][control]')), 1); const cssSelector = new CssSelector(); cssSelector.setElement('input'); cssSelector.addAttribute('type', 'text'); cssSelector.addAttribute('control', 'one'); expect(matcher.match(cssSelector, selectableCollector)).toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should select independent of the order in the css selector', () => { matcher.addSelectables((s1 = CssSelector.parse('[someAttr].someClass')), 1); matcher.addSelectables((s2 = CssSelector.parse('.someClass[someAttr]')), 2); matcher.addSelectables((s3 = CssSelector.parse('.class1.class2')), 3); matcher.addSelectables((s4 = CssSelector.parse('.class2.class1')), 4); expect( matcher.match(CssSelector.parse('[someAttr].someClass')[0], selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect( matcher.match(CssSelector.parse('.someClass[someAttr]')[0], selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2]); reset(); expect(matcher.match(CssSelector.parse('.class1.class2')[0], selectableCollector)).toEqual( true, ); expect(matched).toEqual([s3[0], 3, s4[0], 4]); reset(); expect(matcher.match(CssSelector.parse('.class2.class1')[0], selectableCollector)).toEqual( true, ); expect(matched).toEqual([s4[0], 4, s3[0], 3]); }); it('should not select with a matching :not selector', () => { matcher.addSelectables(CssSelector.parse('p:not(.someClass)'), 1); matcher.addSelectables(CssSelector.parse('p:not([someAttr])'), 2); matcher.addSelectables(CssSelector.parse(':not(.someClass)'), 3); matcher.addSelectables(CssSelector.parse(':not(p)'), 4); matcher.addSelectables(CssSelector.parse(':not(p[someAttr])'), 5); expect( matcher.match( getSelectorFor({tag: 'p', classes: 'someClass', attrs: [['someAttr', '']]}), selectableCollector, ), ).toEqual(false); expect(matched).toEqual([]); }); it('should select with a non matching :not selector', () => { matcher.addSelectables((s1 = CssSelector.parse('p:not(.someClass)')), 1); matcher.addSelectables((s2 = CssSelector.parse('p:not(.someOtherClass[someAttr])')), 2); matcher.addSelectables((s3 = CssSelector.parse(':not(.someClass)')), 3); matcher.addSelectables((s4 = CssSelector.parse(':not(.someOtherClass[someAttr])')), 4); expect( matcher.match( getSelectorFor({tag: 'p', attrs: [['someOtherAttr', '']], classes: 'someOtherClass'}), selectableCollector, ), ).toEqual(true); expect(matched).toEqual([s1[0], 1, s2[0], 2, s3[0], 3, s4[0], 4]); }); it('should match * with :not selector', () => { matcher.addSelectables(CssSelector.parse(':not([a])'), 1); expect(matcher.match(getSelectorFor({tag: 'div'}), () => {})).toEqual(true); }); it('should match with multiple :not selectors', () => { matcher.addSelectables((s1 = CssSelector.parse('div:not([a]):not([b])')), 1); expect( matcher.match(getSelectorFor({tag: 'div', attrs: [['a', '']]}), selectableCollector), ).toBe(false); expect( matcher.match(getSelectorFor({tag: 'div', attrs: [['b', '']]}), selectableCollector), ).toBe(false); expect( matcher.match(getSelectorFor({tag: 'div', attrs: [['c', '']]}), selectableCollector), ).toBe(true); }); it('should select with one match in a list', () => { matcher.addSelectables((s1 = CssSelector.parse('input[type=text], textbox')), 1); expect(matcher.match(getSelectorFor({tag: 'textbox'}), selectableCollector)).toEqual(true); expect(matched).toEqual([s1[1], 1]); reset(); expect( matcher.match(getSelectorFor({tag: 'input', attrs: [['type', 'text']]}), selectableCollector), ).toEqual(true); expect(matched).toEqual([s1[0], 1]); }); it('should not select twice with two matches in a list', () => { matcher.addSelectables((s1 = CssSelector.parse('input, .someClass')), 1); expect( matcher.match(getSelectorFor({tag: 'input', classes: 'someclass'}), selectableCollector), ).toEqual(true); expect(matched.length).toEqual(2); expect(matched).toEqual([s1[0], 1]); }); });
{ "end_byte": 13845, "start_byte": 8049, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/selector/selector_spec.ts" }
angular/packages/compiler/test/selector/selector_spec.ts_13847_20620
describe('CssSelector.parse', () => { it('should detect element names', () => { const cssSelector = CssSelector.parse('sometag')[0]; expect(cssSelector.element).toEqual('sometag'); expect(cssSelector.toString()).toEqual('sometag'); }); it('should detect attr names with escaped $', () => { let cssSelector = CssSelector.parse('[attrname\\$]')[0]; expect(cssSelector.attrs).toEqual(['attrname$', '']); expect(cssSelector.toString()).toEqual('[attrname\\$]'); cssSelector = CssSelector.parse('[\\$attrname]')[0]; expect(cssSelector.attrs).toEqual(['$attrname', '']); expect(cssSelector.toString()).toEqual('[\\$attrname]'); cssSelector = CssSelector.parse('[foo\\$bar]')[0]; expect(cssSelector.attrs).toEqual(['foo$bar', '']); expect(cssSelector.toString()).toEqual('[foo\\$bar]'); }); it('should error on attr names with unescaped $', () => { expect(() => CssSelector.parse('[attrname$]')).toThrowError( 'Error in attribute selector "attrname$". Unescaped "$" is not supported. Please escape with "\\$".', ); expect(() => CssSelector.parse('[$attrname]')).toThrowError( 'Error in attribute selector "$attrname". Unescaped "$" is not supported. Please escape with "\\$".', ); expect(() => CssSelector.parse('[foo$bar]')).toThrowError( 'Error in attribute selector "foo$bar". Unescaped "$" is not supported. Please escape with "\\$".', ); expect(() => CssSelector.parse('[foo\\$bar$]')).toThrowError( 'Error in attribute selector "foo\\$bar$". Unescaped "$" is not supported. Please escape with "\\$".', ); }); it('should detect class names', () => { const cssSelector = CssSelector.parse('.someClass')[0]; expect(cssSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('.someclass'); }); it('should detect attr names', () => { const cssSelector = CssSelector.parse('[attrname]')[0]; expect(cssSelector.attrs).toEqual(['attrname', '']); expect(cssSelector.toString()).toEqual('[attrname]'); }); it('should detect attr values', () => { const cssSelector = CssSelector.parse('[attrname=attrvalue]')[0]; expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelector.toString()).toEqual('[attrname=attrvalue]'); }); it('should detect attr values with double quotes', () => { const cssSelector = CssSelector.parse('[attrname="attrvalue"]')[0]; expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelector.toString()).toEqual('[attrname=attrvalue]'); }); it('should detect #some-value syntax and treat as attribute', () => { const cssSelector = CssSelector.parse('#some-value')[0]; expect(cssSelector.attrs).toEqual(['id', 'some-value']); expect(cssSelector.toString()).toEqual('[id=some-value]'); }); it('should detect attr values with single quotes', () => { const cssSelector = CssSelector.parse("[attrname='attrvalue']")[0]; expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelector.toString()).toEqual('[attrname=attrvalue]'); }); it('should detect multiple parts', () => { const cssSelector = CssSelector.parse('sometag[attrname=attrvalue].someclass')[0]; expect(cssSelector.element).toEqual('sometag'); expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('sometag.someclass[attrname=attrvalue]'); }); it('should detect multiple attributes', () => { const cssSelector = CssSelector.parse('input[type=text][control]')[0]; expect(cssSelector.element).toEqual('input'); expect(cssSelector.attrs).toEqual(['type', 'text', 'control', '']); expect(cssSelector.toString()).toEqual('input[type=text][control]'); }); it('should detect :not', () => { const cssSelector = CssSelector.parse('sometag:not([attrname=attrvalue].someclass)')[0]; expect(cssSelector.element).toEqual('sometag'); expect(cssSelector.attrs.length).toEqual(0); expect(cssSelector.classNames.length).toEqual(0); const notSelector = cssSelector.notSelectors[0]; expect(notSelector.element).toEqual(null); expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(notSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('sometag:not(.someclass[attrname=attrvalue])'); }); it('should detect :not without truthy', () => { const cssSelector = CssSelector.parse(':not([attrname=attrvalue].someclass)')[0]; expect(cssSelector.element).toEqual('*'); const notSelector = cssSelector.notSelectors[0]; expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']); expect(notSelector.classNames).toEqual(['someclass']); expect(cssSelector.toString()).toEqual('*:not(.someclass[attrname=attrvalue])'); }); it('should throw when nested :not', () => { expect(() => { CssSelector.parse('sometag:not(:not([attrname=attrvalue].someclass))')[0]; }).toThrowError('Nesting :not in a selector is not allowed'); }); it('should throw when multiple selectors in :not', () => { expect(() => { CssSelector.parse('sometag:not(a,b)'); }).toThrowError('Multiple selectors in :not are not supported'); }); it('should detect lists of selectors', () => { const cssSelectors = CssSelector.parse('.someclass,[attrname=attrvalue], sometag'); expect(cssSelectors.length).toEqual(3); expect(cssSelectors[0].classNames).toEqual(['someclass']); expect(cssSelectors[1].attrs).toEqual(['attrname', 'attrvalue']); expect(cssSelectors[2].element).toEqual('sometag'); }); it('should detect lists of selectors with :not', () => { const cssSelectors = CssSelector.parse( 'input[type=text], :not(textarea), textbox:not(.special)', ); expect(cssSelectors.length).toEqual(3); expect(cssSelectors[0].element).toEqual('input'); expect(cssSelectors[0].attrs).toEqual(['type', 'text']); expect(cssSelectors[1].element).toEqual('*'); expect(cssSelectors[1].notSelectors[0].element).toEqual('textarea'); expect(cssSelectors[2].element).toEqual('textbox'); expect(cssSelectors[2].notSelectors[0].classNames).toEqual(['special']); }); }); function getSelectorFor({ tag = '', attrs = [], classes = '', }: {tag?: string; attrs?: any[]; classes?: string} = {}): CssSelector { const selector = new CssSelector(); selector.setElement(tag); attrs.forEach((nameValue) => { selector.addAttribute(nameValue[0], nameValue[1]); }); classes .trim() .split(/\s+/g) .forEach((cName) => { selector.addClassName(cName); }); return selector; }
{ "end_byte": 20620, "start_byte": 13847, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/selector/selector_spec.ts" }
angular/packages/compiler/test/selector/BUILD.bazel_0_536
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") ts_library( name = "selector_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages:types", "//packages/compiler", "//packages/platform-browser/testing", ], ) jasmine_node_test( name = "selector", bootstrap = ["//tools/testing:node"], deps = [ ":selector_lib", ], ) karma_web_test_suite( name = "selector_web", deps = [ ":selector_lib", ], )
{ "end_byte": 536, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/selector/BUILD.bazel" }
angular/packages/compiler/test/output/abstract_emitter_spec.ts_0_1580
/** * @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 {escapeIdentifier} from '@angular/compiler/src/output/abstract_emitter'; describe('AbstractEmitter', () => { describe('escapeIdentifier', () => { it('should escape single quotes', () => { expect(escapeIdentifier(`'`, false)).toEqual(`'\\''`); }); it('should escape backslash', () => { expect(escapeIdentifier('\\', false)).toEqual(`'\\\\'`); }); it('should escape newlines', () => { expect(escapeIdentifier('\n', false)).toEqual(`'\\n'`); }); it('should escape carriage returns', () => { expect(escapeIdentifier('\r', false)).toEqual(`'\\r'`); }); it('should escape $', () => { expect(escapeIdentifier('$', true)).toEqual(`'\\$'`); }); it('should not escape $', () => { expect(escapeIdentifier('$', false)).toEqual(`'$'`); }); it('should add quotes for non-identifiers', () => { expect(escapeIdentifier('==', false, false)).toEqual(`'=='`); }); it('does not escape class (but it probably should)', () => { expect(escapeIdentifier('class', false, false)).toEqual('class'); }); }); }); export function stripSourceMapAndNewLine(source: string): string { if (source.endsWith('\n')) { source = source.substring(0, source.length - 1); } const smi = source.lastIndexOf('\n//#'); if (smi == -1) return source; return source.slice(0, smi); }
{ "end_byte": 1580, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/output/abstract_emitter_spec.ts" }
angular/packages/compiler/test/output/abstract_emitter_node_only_spec.ts_0_4892
/** * @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 {ParseLocation, ParseSourceFile, ParseSourceSpan} from '@angular/compiler'; import {EmitterVisitorContext} from '@angular/compiler/src/output/abstract_emitter'; import {originalPositionFor} from './source_map_util'; describe('AbstractEmitter', () => { describe('EmitterVisitorContext', () => { const fileA = new ParseSourceFile('a0a1a2a3a4a5a6a7a8a9', 'a.js'); const fileB = new ParseSourceFile('b0b1b2b3b4b5b6b7b8b9', 'b.js'); let ctx: EmitterVisitorContext; beforeEach(() => { ctx = EmitterVisitorContext.createRoot(); }); it('should add source files to the source map', () => { ctx.print(createSourceSpan(fileA, 0), 'o0'); ctx.print(createSourceSpan(fileA, 1), 'o1'); ctx.print(createSourceSpan(fileB, 0), 'o2'); ctx.print(createSourceSpan(fileB, 1), 'o3'); const sm = ctx.toSourceMapGenerator('o.ts').toJSON()!; expect(sm.sources).toEqual([fileA.url, fileB.url]); expect(sm.sourcesContent).toEqual([fileA.content, fileB.content]); }); it('should generate a valid mapping', () => { ctx.print(createSourceSpan(fileA, 0), 'fileA-0'); ctx.println(createSourceSpan(fileB, 1), 'fileB-1'); ctx.print(createSourceSpan(fileA, 2), 'fileA-2'); expectMap(ctx, 0, 0, 'a.js', 0, 0); expectMap(ctx, 0, 7, 'b.js', 0, 2); expectMap(ctx, 1, 0, 'a.js', 0, 4); }); it('should be able to shift the content', async () => { ctx.print(createSourceSpan(fileA, 0), 'fileA-0'); const sm = ctx.toSourceMapGenerator('o.ts', 10).toJSON()!; expect(await originalPositionFor(sm, {line: 11, column: 0})).toEqual({ line: 1, column: 0, source: 'a.js', }); }); it('should use the default source file for the first character', () => { ctx.print(null, 'fileA-0'); expectMap(ctx, 0, 0, 'o.ts', 0, 0); }); it('should use an explicit mapping for the first character', () => { ctx.print(createSourceSpan(fileA, 0), 'fileA-0'); expectMap(ctx, 0, 0, 'a.js', 0, 0); }); it('should map leading segment without span', () => { ctx.print(null, '....'); ctx.print(createSourceSpan(fileA, 0), 'fileA-0'); expectMap(ctx, 0, 0, 'o.ts', 0, 0); expectMap(ctx, 0, 4, 'a.js', 0, 0); expect(nbSegmentsPerLine(ctx)).toEqual([2]); }); it('should handle indent', () => { ctx.incIndent(); ctx.println(createSourceSpan(fileA, 0), 'fileA-0'); ctx.incIndent(); ctx.println(createSourceSpan(fileA, 1), 'fileA-1'); ctx.decIndent(); ctx.println(createSourceSpan(fileA, 2), 'fileA-2'); expectMap(ctx, 0, 0, 'o.ts', 0, 0); expectMap(ctx, 0, 2, 'a.js', 0, 0); expectMap(ctx, 1, 0); expectMap(ctx, 1, 2); expectMap(ctx, 1, 4, 'a.js', 0, 2); expectMap(ctx, 2, 0); expectMap(ctx, 2, 2, 'a.js', 0, 4); expect(nbSegmentsPerLine(ctx)).toEqual([2, 1, 1]); }); it('should coalesce identical span', () => { const span = createSourceSpan(fileA, 0); ctx.print(span, 'fileA-0'); ctx.print(null, '...'); ctx.print(span, 'fileA-0'); ctx.print(createSourceSpan(fileB, 0), 'fileB-0'); expectMap(ctx, 0, 0, 'a.js', 0, 0); expectMap(ctx, 0, 7, 'a.js', 0, 0); expectMap(ctx, 0, 10, 'a.js', 0, 0); expectMap(ctx, 0, 17, 'b.js', 0, 0); expect(nbSegmentsPerLine(ctx)).toEqual([2]); }); }); }); // All lines / columns indexes are 0-based // Note: source-map line indexes are 1-based, column 0-based async function expectMap( ctx: EmitterVisitorContext, genLine: number, genCol: number, source: string | null = null, srcLine: number | null = null, srcCol: number | null = null, ) { const sm = ctx.toSourceMapGenerator('o.ts').toJSON()!; const genPosition = {line: genLine + 1, column: genCol}; const origPosition = await originalPositionFor(sm, genPosition); expect(origPosition.source).toEqual(source); expect(origPosition.line).toEqual(srcLine === null ? null : srcLine + 1); expect(origPosition.column).toEqual(srcCol); } // returns the number of segments per line function nbSegmentsPerLine(ctx: EmitterVisitorContext) { const sm = ctx.toSourceMapGenerator('o.ts').toJSON()!; const lines = sm.mappings.split(';'); return lines.map((l) => { const m = l.match(/,/g); return m === null ? 1 : m.length + 1; }); } function createSourceSpan(file: ParseSourceFile, idx: number) { const col = 2 * idx; const start = new ParseLocation(file, col, 0, col); const end = new ParseLocation(file, col + 2, 0, col + 2); const sourceSpan = new ParseSourceSpan(start, end); return {sourceSpan}; }
{ "end_byte": 4892, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/output/abstract_emitter_node_only_spec.ts" }
angular/packages/compiler/test/output/output_jit_spec.ts_0_2484
/** * @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 {EmitterVisitorContext} from '@angular/compiler/src/output/abstract_emitter'; import * as o from '@angular/compiler/src/output/output_ast'; import {JitEmitterVisitor, JitEvaluator} from '@angular/compiler/src/output/output_jit'; import {R3JitReflector} from '@angular/compiler/src/render3/r3_jit'; import {newArray} from '@angular/compiler/src/util'; describe('Output JIT', () => { describe('regression', () => { it('should generate unique argument names', () => { const externalIds = newArray(10, 1).map( (_, index) => new o.ExternalReference('@angular/core', `id_${index}_`, {name: `id_${index}_`}), ); const externalIds1 = newArray(10, 1).map( (_, index) => new o.ExternalReference('@angular/core', `id_${index}_1`, {name: `id_${index}_1`}), ); const ctx = EmitterVisitorContext.createRoot(); const reflectorContext: {[key: string]: string} = {}; for (const {name} of externalIds) { reflectorContext[name!] = name!; } for (const {name} of externalIds1) { reflectorContext[name!] = name!; } const converter = new JitEmitterVisitor(new R3JitReflector(reflectorContext)); converter.visitAllStatements( [o.literalArr([...externalIds1, ...externalIds].map((id) => o.importExpr(id))).toStmt()], ctx, ); const args = converter.getArgs(); expect(Object.keys(args).length).toBe(20); }); }); it('should use strict mode', () => { const evaluator = new JitEvaluator(); expect(() => { evaluator.evaluateStatements( 'http://angular.io/something.ts', [ // Set an undeclared variable // foo = "bar"; o.variable('foo').equals(o.literal('bar')).toStmt(), ], new R3JitReflector({}), false, ); }).toThrowError(); }); it('should not add more than one strict mode statement if there is already one present', () => { const converter = new JitEmitterVisitor(new R3JitReflector({})); const ctx = EmitterVisitorContext.createRoot(); converter.visitAllStatements([o.literal('use strict').toStmt()], ctx); const matches = ctx.toSource().match(/'use strict';/g)!; expect(matches.length).toBe(1); }); });
{ "end_byte": 2484, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/output/output_jit_spec.ts" }
angular/packages/compiler/test/output/source_map_spec.ts_0_4944
/** * @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 {SourceMapGenerator, toBase64String} from '@angular/compiler/src/output/source_map'; describe('source map generation', () => { describe('generation', () => { it('should generate a valid source map', () => { const map = new SourceMapGenerator('out.js') .addSource('a.js', null) .addLine() .addMapping(0, 'a.js', 0, 0) .addMapping(4, 'a.js', 0, 6) .addMapping(5, 'a.js', 0, 7) .addMapping(8, 'a.js', 0, 22) .addMapping(9, 'a.js', 0, 23) .addMapping(10, 'a.js', 0, 24) .addLine() .addMapping(0, 'a.js', 1, 0) .addMapping(4, 'a.js', 1, 6) .addMapping(5, 'a.js', 1, 7) .addMapping(8, 'a.js', 1, 10) .addMapping(9, 'a.js', 1, 11) .addMapping(10, 'a.js', 1, 12) .addLine() .addMapping(0, 'a.js', 3, 0) .addMapping(2, 'a.js', 3, 2) .addMapping(3, 'a.js', 3, 3) .addMapping(10, 'a.js', 3, 10) .addMapping(11, 'a.js', 3, 11) .addMapping(21, 'a.js', 3, 11) .addMapping(22, 'a.js', 3, 12) .addLine() .addMapping(4, 'a.js', 4, 4) .addMapping(11, 'a.js', 4, 11) .addMapping(12, 'a.js', 4, 12) .addMapping(15, 'a.js', 4, 15) .addMapping(16, 'a.js', 4, 16) .addMapping(21, 'a.js', 4, 21) .addMapping(22, 'a.js', 4, 22) .addMapping(23, 'a.js', 4, 23) .addLine() .addMapping(0, 'a.js', 5, 0) .addMapping(1, 'a.js', 5, 1) .addMapping(2, 'a.js', 5, 2) .addMapping(3, 'a.js', 5, 2); // Generated with https://sokra.github.io/source-map-visualization using a TS source map expect(map.toJSON()!.mappings).toEqual( 'AAAA,IAAM,CAAC,GAAe,CAAC,CAAC;AACxB,IAAM,CAAC,GAAG,CAAC,CAAC;AAEZ,EAAE,CAAC,OAAO,CAAC,UAAA,CAAC;IACR,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC,CAAC,CAAA', ); }); it('should include the files and their contents', () => { const map = new SourceMapGenerator('out.js') .addSource('inline.ts', 'inline') .addSource('inline.ts', 'inline') // make sur the sources are dedup .addSource('url.ts', null) .addLine() .addMapping(0, 'inline.ts', 0, 0) .toJSON()!; expect(map.file).toEqual('out.js'); expect(map.sources).toEqual(['inline.ts', 'url.ts']); expect(map.sourcesContent).toEqual(['inline', null]); }); it('should not generate source maps when there is no mapping', () => { const smg = new SourceMapGenerator('out.js').addSource('inline.ts', 'inline').addLine(); expect(smg.toJSON()).toEqual(null); expect(smg.toJsComment()).toEqual(''); }); }); describe('encodeB64String', () => { it('should return the b64 encoded value', () => { [ ['', ''], ['a', 'YQ=='], ['Foo', 'Rm9v'], ['Foo1', 'Rm9vMQ=='], ['Foo12', 'Rm9vMTI='], ['Foo123', 'Rm9vMTIz'], ].forEach(([src, b64]) => expect(toBase64String(src)).toEqual(b64)); }); }); describe('errors', () => { it('should throw when mappings are added out of order', () => { expect(() => { new SourceMapGenerator('out.js') .addSource('in.js') .addLine() .addMapping(10, 'in.js', 0, 0) .addMapping(0, 'in.js', 0, 0); }).toThrowError('Mapping should be added in output order'); }); it('should throw when adding segments before any line is created', () => { expect(() => { new SourceMapGenerator('out.js').addSource('in.js').addMapping(0, 'in.js', 0, 0); }).toThrowError('A line must be added before mappings can be added'); }); it('should throw when adding segments referencing unknown sources', () => { expect(() => { new SourceMapGenerator('out.js').addSource('in.js').addLine().addMapping(0, 'in_.js', 0, 0); }).toThrowError('Unknown source file "in_.js"'); }); it('should throw when adding segments without column', () => { expect(() => { new SourceMapGenerator('out.js').addSource('in.js').addLine().addMapping(null!); }).toThrowError('The column in the generated code must be provided'); }); it('should throw when adding segments with a source url but no position', () => { expect(() => { new SourceMapGenerator('out.js').addSource('in.js').addLine().addMapping(0, 'in.js'); }).toThrowError('The source location must be provided when a source url is provided'); expect(() => { new SourceMapGenerator('out.js').addSource('in.js').addLine().addMapping(0, 'in.js', 0); }).toThrowError('The source location must be provided when a source url is provided'); }); }); });
{ "end_byte": 4944, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/output/source_map_spec.ts" }
angular/packages/compiler/test/output/source_map_util.ts_0_1429
/** * @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 {SourceMap} from '@angular/compiler'; import {SourceMapConsumer} from 'source-map'; export interface SourceLocation { line: number | null; column: number | null; source: string | null; } export async function originalPositionFor( sourceMap: SourceMap, genPosition: {line: number; column: number}, ): Promise<SourceLocation> { // Note: The `SourceMap` type from the compiler is different to `RawSourceMap` // from the `source-map` package, but the method we rely on works as expected. const smc = await new SourceMapConsumer(sourceMap as any); // Note: We don't return the original object as it also contains a `name` property // which is always null and we don't want to include that in our assertions... const {line, column, source} = smc.originalPositionFor(genPosition); return {line, column, source}; } export function extractSourceMap(source: string): SourceMap | null { let idx = source.lastIndexOf('\n//#'); if (idx == -1) return null; const smComment = source.slice(idx).split('\n', 2)[1].trim(); const smB64 = smComment.split('sourceMappingURL=data:application/json;base64,')[1]; return smB64 ? (JSON.parse(Buffer.from(smB64, 'base64').toString()) as SourceMap) : null; }
{ "end_byte": 1429, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/output/source_map_util.ts" }
angular/packages/compiler/test/shadow_css/shadow_css_spec.ts_0_5186
/** * @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 {shim} from './utils'; describe('ShadowCss', () => { it('should handle empty string', () => { expect(shim('', 'contenta')).toEqualCss(''); }); it('should add an attribute to every rule', () => { const css = 'one {color: red;}two {color: red;}'; const expected = 'one[contenta] {color:red;}two[contenta] {color:red;}'; expect(shim(css, 'contenta')).toEqualCss(expected); }); it('should handle invalid css', () => { const css = 'one {color: red;}garbage'; const expected = 'one[contenta] {color:red;}garbage'; expect(shim(css, 'contenta')).toEqualCss(expected); }); it('should add an attribute to every selector', () => { const css = 'one, two {color: red;}'; const expected = 'one[contenta], two[contenta] {color:red;}'; expect(shim(css, 'contenta')).toEqualCss(expected); }); it('should support newlines in the selector and content ', () => { const css = ` one, two { color: red; } `; const expected = ` one[contenta], two[contenta] { color: red; } `; expect(shim(css, 'contenta')).toEqualCss(expected); }); it('should handle complicated selectors', () => { expect(shim('one::before {}', 'contenta')).toEqualCss('one[contenta]::before {}'); expect(shim('one two {}', 'contenta')).toEqualCss('one[contenta] two[contenta] {}'); expect(shim('one > two {}', 'contenta')).toEqualCss('one[contenta] > two[contenta] {}'); expect(shim('one + two {}', 'contenta')).toEqualCss('one[contenta] + two[contenta] {}'); expect(shim('one ~ two {}', 'contenta')).toEqualCss('one[contenta] ~ two[contenta] {}'); expect(shim('.one.two > three {}', 'contenta')).toEqualCss( '.one.two[contenta] > three[contenta] {}', ); expect(shim('one[attr="value"] {}', 'contenta')).toEqualCss('one[attr="value"][contenta] {}'); expect(shim('one[attr=value] {}', 'contenta')).toEqualCss('one[attr=value][contenta] {}'); expect(shim('one[attr^="value"] {}', 'contenta')).toEqualCss('one[attr^="value"][contenta] {}'); expect(shim('one[attr$="value"] {}', 'contenta')).toEqualCss('one[attr$="value"][contenta] {}'); expect(shim('one[attr*="value"] {}', 'contenta')).toEqualCss('one[attr*="value"][contenta] {}'); expect(shim('one[attr|="value"] {}', 'contenta')).toEqualCss('one[attr|="value"][contenta] {}'); expect(shim('one[attr~="value"] {}', 'contenta')).toEqualCss('one[attr~="value"][contenta] {}'); expect(shim('one[attr="va lue"] {}', 'contenta')).toEqualCss('one[attr="va lue"][contenta] {}'); expect(shim('one[attr] {}', 'contenta')).toEqualCss('one[attr][contenta] {}'); expect(shim('[is="one"] {}', 'contenta')).toEqualCss('[is="one"][contenta] {}'); expect(shim('[attr] {}', 'contenta')).toEqualCss('[attr][contenta] {}'); }); it('should transform :host with attributes', () => { expect(shim(':host [attr] {}', 'contenta', 'hosta')).toEqualCss('[hosta] [attr][contenta] {}'); expect(shim(':host(create-first-project) {}', 'contenta', 'hosta')).toEqualCss( 'create-first-project[hosta] {}', ); expect(shim(':host[attr] {}', 'contenta', 'hosta')).toEqualCss('[attr][hosta] {}'); expect(shim(':host[attr]:where(:not(.cm-button)) {}', 'contenta', 'hosta')).toEqualCss( '[attr][hosta]:where(:not(.cm-button)) {}', ); }); it('should handle escaped sequences in selectors', () => { expect(shim('one\\/two {}', 'contenta')).toEqualCss('one\\/two[contenta] {}'); expect(shim('one\\:two {}', 'contenta')).toEqualCss('one\\:two[contenta] {}'); expect(shim('one\\\\:two {}', 'contenta')).toEqualCss('one\\\\[contenta]:two {}'); expect(shim('.one\\:two {}', 'contenta')).toEqualCss('.one\\:two[contenta] {}'); expect(shim('.one\\:\\fc ber {}', 'contenta')).toEqualCss('.one\\:\\fc ber[contenta] {}'); expect(shim('.one\\:two .three\\:four {}', 'contenta')).toEqualCss( '.one\\:two[contenta] .three\\:four[contenta] {}', ); expect(shim('div:where(.one) {}', 'contenta', 'hosta')).toEqualCss( 'div[contenta]:where(.one) {}', ); expect(shim('div:where() {}', 'contenta', 'hosta')).toEqualCss('div[contenta]:where() {}'); // See `xit('should parse concatenated pseudo selectors'` expect(shim(':where(a):where(b) {}', 'contenta', 'hosta')).toEqualCss( ':where(a)[contenta]:where(b) {}', ); expect(shim('*:where(.one) {}', 'contenta', 'hosta')).toEqualCss('*[contenta]:where(.one) {}'); expect(shim('*:where(.one) ::ng-deep .foo {}', 'contenta', 'hosta')).toEqualCss( '*[contenta]:where(.one) .foo {}', ); }); xit('should parse concatenated pseudo selectors', () => { // Current logic leads to a result with an outer scope // It could be changed, to not increase specificity // Requires a more complex parsing expect(shim(':where(a):where(b) {}', 'contenta', 'hosta')).toEqualCss( ':where(a[contenta]):where(b[contenta]) {}', ); });
{ "end_byte": 5186, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/shadow_css_spec.ts" }
angular/packages/compiler/test/shadow_css/shadow_css_spec.ts_5190_10589
it('should handle pseudo functions correctly', () => { // :where() expect(shim(':where(.one) {}', 'contenta', 'hosta')).toEqualCss(':where(.one[contenta]) {}'); expect(shim(':where(div.one span.two) {}', 'contenta', 'hosta')).toEqualCss( ':where(div.one[contenta] span.two[contenta]) {}', ); expect(shim(':where(.one) .two {}', 'contenta', 'hosta')).toEqualCss( ':where(.one[contenta]) .two[contenta] {}', ); expect(shim(':where(:host) {}', 'contenta', 'hosta')).toEqualCss(':where([hosta]) {}'); expect(shim(':where(:host) .one {}', 'contenta', 'hosta')).toEqualCss( ':where([hosta]) .one[contenta] {}', ); expect(shim(':where(.one) :where(:host) {}', 'contenta', 'hosta')).toEqualCss( ':where(.one) :where([hosta]) {}', ); expect(shim(':where(.one :host) {}', 'contenta', 'hosta')).toEqualCss( ':where(.one [hosta]) {}', ); expect(shim('div :where(.one) {}', 'contenta', 'hosta')).toEqualCss( 'div[contenta] :where(.one[contenta]) {}', ); expect(shim(':host :where(.one .two) {}', 'contenta', 'hosta')).toEqualCss( '[hosta] :where(.one[contenta] .two[contenta]) {}', ); expect(shim(':where(.one, .two) {}', 'contenta', 'hosta')).toEqualCss( ':where(.one[contenta], .two[contenta]) {}', ); expect(shim(':where(.one > .two) {}', 'contenta', 'hosta')).toEqualCss( ':where(.one[contenta] > .two[contenta]) {}', ); expect(shim(':where(> .one) {}', 'contenta', 'hosta')).toEqualCss( ':where( > .one[contenta]) {}', ); expect(shim(':where(:not(.one) ~ .two) {}', 'contenta', 'hosta')).toEqualCss( ':where([contenta]:not(.one) ~ .two[contenta]) {}', ); expect(shim(':where([foo]) {}', 'contenta', 'hosta')).toEqualCss(':where([foo][contenta]) {}'); // :is() expect(shim('div:is(.foo) {}', 'contenta', 'a-host')).toEqualCss('div[contenta]:is(.foo) {}'); expect(shim(':is(.dark :host) {}', 'contenta', 'a-host')).toEqualCss(':is(.dark [a-host]) {}'); expect(shim(':is(.dark) :is(:host) {}', 'contenta', 'a-host')).toEqualCss( ':is(.dark) :is([a-host]) {}', ); expect(shim(':host:is(.foo) {}', 'contenta', 'a-host')).toEqualCss('[a-host]:is(.foo) {}'); expect(shim(':is(.foo) {}', 'contenta', 'a-host')).toEqualCss(':is(.foo[contenta]) {}'); expect(shim(':is(.foo, .bar, .baz) {}', 'contenta', 'a-host')).toEqualCss( ':is(.foo[contenta], .bar[contenta], .baz[contenta]) {}', ); expect(shim(':is(.foo, .bar) :host {}', 'contenta', 'a-host')).toEqualCss( ':is(.foo, .bar) [a-host] {}', ); // :is() and :where() expect( shim( ':is(.foo, .bar) :is(.baz) :where(.one, .two) :host :where(.three:first-child) {}', 'contenta', 'a-host', ), ).toEqualCss( ':is(.foo, .bar) :is(.baz) :where(.one, .two) [a-host] :where(.three[contenta]:first-child) {}', ); expect(shim(':where(:is(a)) {}', 'contenta', 'hosta')).toEqualCss( ':where(:is(a[contenta])) {}', ); expect(shim(':where(:is(a, b)) {}', 'contenta', 'hosta')).toEqualCss( ':where(:is(a[contenta], b[contenta])) {}', ); expect(shim(':where(:host:is(.one, .two)) {}', 'contenta', 'hosta')).toEqualCss( ':where([hosta]:is(.one, .two)) {}', ); expect(shim(':where(:host :is(.one, .two)) {}', 'contenta', 'hosta')).toEqualCss( ':where([hosta] :is(.one[contenta], .two[contenta])) {}', ); expect(shim(':where(:is(a, b) :is(.one, .two)) {}', 'contenta', 'hosta')).toEqualCss( ':where(:is(a[contenta], b[contenta]) :is(.one[contenta], .two[contenta])) {}', ); expect( shim( ':where(:where(a:has(.foo), b) :is(.one, .two:where(.foo > .bar))) {}', 'contenta', 'hosta', ), ).toEqualCss( ':where(:where(a[contenta]:has(.foo), b[contenta]) :is(.one[contenta], .two[contenta]:where(.foo > .bar))) {}', ); // complex selectors expect(shim(':host:is([foo],[foo-2])>div.example-2 {}', 'contenta', 'a-host')).toEqualCss( '[a-host]:is([foo],[foo-2]) > div.example-2[contenta] {}', ); expect(shim(':host:is([foo], [foo-2]) > div.example-2 {}', 'contenta', 'a-host')).toEqualCss( '[a-host]:is([foo], [foo-2]) > div.example-2[contenta] {}', ); expect(shim(':host:has([foo],[foo-2])>div.example-2 {}', 'contenta', 'a-host')).toEqualCss( '[a-host]:has([foo],[foo-2]) > div.example-2[contenta] {}', ); // :has() expect(shim('div:has(a) {}', 'contenta', 'hosta')).toEqualCss('div[contenta]:has(a) {}'); expect(shim('div:has(a) :host {}', 'contenta', 'hosta')).toEqualCss('div:has(a) [hosta] {}'); expect(shim(':has(a) :host :has(b) {}', 'contenta', 'hosta')).toEqualCss( ':has(a) [hosta] [contenta]:has(b) {}', ); expect(shim('div:has(~ .one) {}', 'contenta', 'hosta')).toEqualCss( 'div[contenta]:has(~ .one) {}', ); // Unlike `:is()` or `:where()` the attribute selector isn't placed inside // of `:has()`. That is deliberate, `[contenta]:has(a)` would select all // `[contenta]` with `a` inside, while `:has(a[contenta])` would select // everything that contains `a[contenta]`, targeting elements outside of // encapsulated scope. expect(shim(':has(a) :has(b) {}', 'contenta', 'hosta')).toEqualCss( '[contenta]:has(a) [contenta]:has(b) {}', ); });
{ "end_byte": 10589, "start_byte": 5190, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/shadow_css_spec.ts" }
angular/packages/compiler/test/shadow_css/shadow_css_spec.ts_10593_15053
it('should handle :host inclusions inside pseudo-selectors selectors', () => { expect(shim('.header:not(.admin) {}', 'contenta', 'hosta')).toEqualCss( '.header[contenta]:not(.admin) {}', ); expect(shim('.header:is(:host > .toolbar, :host ~ .panel) {}', 'contenta', 'hosta')).toEqualCss( '.header[contenta]:is([hosta] > .toolbar, [hosta] ~ .panel) {}', ); expect( shim('.header:where(:host > .toolbar, :host ~ .panel) {}', 'contenta', 'hosta'), ).toEqualCss('.header[contenta]:where([hosta] > .toolbar, [hosta] ~ .panel) {}'); expect(shim('.header:not(.admin, :host.super .header) {}', 'contenta', 'hosta')).toEqualCss( '.header[contenta]:not(.admin, .super[hosta] .header) {}', ); expect( shim('.header:not(.admin, :host.super .header, :host.mega .header) {}', 'contenta', 'hosta'), ).toEqualCss('.header[contenta]:not(.admin, .super[hosta] .header, .mega[hosta] .header) {}'); expect(shim('.one :where(.two, :host) {}', 'contenta', 'hosta')).toEqualCss( '.one :where(.two[contenta], [hosta]) {}', ); expect(shim('.one :where(:host, .two) {}', 'contenta', 'hosta')).toEqualCss( '.one :where([hosta], .two[contenta]) {}', ); }); it('should handle escaped selector with space (if followed by a hex char)', () => { // When esbuild runs with optimization.minify // selectors are escaped: .über becomes .\fc ber. // The space here isn't a separator between 2 selectors expect(shim('.\\fc ber {}', 'contenta')).toEqual('.\\fc ber[contenta] {}'); expect(shim('.\\fc ker {}', 'contenta')).toEqual('.\\fc[contenta] ker[contenta] {}'); expect(shim('.pr\\fc fung {}', 'contenta')).toEqual('.pr\\fc fung[contenta] {}'); }); it('should handle ::shadow', () => { const css = shim('x::shadow > y {}', 'contenta'); expect(css).toEqualCss('x[contenta] > y[contenta] {}'); }); it('should leave calc() unchanged', () => { const styleStr = 'div {height:calc(100% - 55px);}'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss('div[contenta] {height:calc(100% - 55px);}'); }); it('should shim rules with quoted content', () => { const styleStr = 'div {background-image: url("a.jpg"); color: red;}'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss('div[contenta] {background-image:url("a.jpg"); color:red;}'); }); it('should shim rules with an escaped quote inside quoted content', () => { const styleStr = 'div::after { content: "\\"" }'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss('div[contenta]::after { content:"\\""}'); }); it('should shim rules with curly braces inside quoted content', () => { const styleStr = 'div::after { content: "{}" }'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss('div[contenta]::after { content:"{}"}'); }); it('should keep retain multiline selectors', () => { // This is needed as shifting in line number will cause sourcemaps to break. const styleStr = '.foo,\n.bar { color: red;}'; const css = shim(styleStr, 'contenta'); expect(css).toEqual('.foo[contenta], \n.bar[contenta] { color: red;}'); }); describe('comments', () => { // Comments should be kept in the same position as otherwise inline sourcemaps break due to // shift in lines. it('should replace multiline comments with newline', () => { expect(shim('/* b {c} */ b {c}', 'contenta')).toBe('\n b[contenta] {c}'); }); it('should replace multiline comments with newline in the original position', () => { expect(shim('/* b {c}\n */ b {c}', 'contenta')).toBe('\n\n b[contenta] {c}'); }); it('should replace comments with newline in the original position', () => { expect(shim('/* b {c} */ b {c} /* a {c} */ a {c}', 'contenta')).toBe( '\n b[contenta] {c} \n a[contenta] {c}', ); }); it('should keep sourceMappingURL comments', () => { expect(shim('b {c} /*# sourceMappingURL=data:x */', 'contenta')).toBe( 'b[contenta] {c} /*# sourceMappingURL=data:x */', ); expect(shim('b {c}/* #sourceMappingURL=data:x */', 'contenta')).toBe( 'b[contenta] {c}/* #sourceMappingURL=data:x */', ); }); it('should handle adjacent comments', () => { expect(shim('/* comment 1 */ /* comment 2 */ b {c}', 'contenta')).toBe( '\n \n b[contenta] {c}', ); }); }); });
{ "end_byte": 15053, "start_byte": 10593, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/shadow_css_spec.ts" }
angular/packages/compiler/test/shadow_css/host_and_host_context_spec.ts_0_4482
/** * @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 {shim} from './utils'; describe('ShadowCss, :host and :host-context', () => { describe(':host', () => { it('should handle no context', () => { expect(shim(':host {}', 'contenta', 'a-host')).toEqualCss('[a-host] {}'); }); it('should handle tag selector', () => { expect(shim(':host(ul) {}', 'contenta', 'a-host')).toEqualCss('ul[a-host] {}'); }); it('should handle class selector', () => { expect(shim(':host(.x) {}', 'contenta', 'a-host')).toEqualCss('.x[a-host] {}'); }); it('should handle attribute selector', () => { expect(shim(':host([a="b"]) {}', 'contenta', 'a-host')).toEqualCss('[a="b"][a-host] {}'); expect(shim(':host([a=b]) {}', 'contenta', 'a-host')).toEqualCss('[a=b][a-host] {}'); }); it('should handle attribute and next operator without spaces', () => { expect(shim(':host[foo]>div {}', 'contenta', 'a-host')).toEqualCss( '[foo][a-host] > div[contenta] {}', ); }); // we know that the following test doesn't pass // the host attribute is added before the space // We advise to a more simple class name that doesn't require escaping xit('should handle host with escaped class selector', () => { // here we're looking to shim :host.prüfung (an escaped ü is replaced by "\\fc ") expect(shim(':host.pr\\fc fung {}', 'contenta', 'a-host')).toEqual('.pr\\fc fung[a-host] {}'); }); it('should handle multiple tag selectors', () => { expect(shim(':host(ul,li) {}', 'contenta', 'a-host')).toEqualCss('ul[a-host], li[a-host] {}'); expect(shim(':host(ul,li) > .z {}', 'contenta', 'a-host')).toEqualCss( 'ul[a-host] > .z[contenta], li[a-host] > .z[contenta] {}', ); }); it('should handle compound class selectors', () => { expect(shim(':host(.a.b) {}', 'contenta', 'a-host')).toEqualCss('.a.b[a-host] {}'); }); it('should handle multiple class selectors', () => { expect(shim(':host(.x,.y) {}', 'contenta', 'a-host')).toEqualCss('.x[a-host], .y[a-host] {}'); expect(shim(':host(.x,.y) > .z {}', 'contenta', 'a-host')).toEqualCss( '.x[a-host] > .z[contenta], .y[a-host] > .z[contenta] {}', ); }); it('should handle multiple attribute selectors', () => { expect(shim(':host([a="b"],[c=d]) {}', 'contenta', 'a-host')).toEqualCss( '[a="b"][a-host], [c=d][a-host] {}', ); }); it('should handle pseudo selectors', () => { expect(shim(':host(:before) {}', 'contenta', 'a-host')).toEqualCss('[a-host]:before {}'); expect(shim(':host:before {}', 'contenta', 'a-host')).toEqualCss('[a-host]:before {}'); expect(shim(':host:nth-child(8n+1) {}', 'contenta', 'a-host')).toEqualCss( '[a-host]:nth-child(8n+1) {}', ); expect(shim(':host:nth-of-type(8n+1) {}', 'contenta', 'a-host')).toEqualCss( '[a-host]:nth-of-type(8n+1) {}', ); expect(shim(':host(.class):before {}', 'contenta', 'a-host')).toEqualCss( '.class[a-host]:before {}', ); expect(shim(':host.class:before {}', 'contenta', 'a-host')).toEqualCss( '.class[a-host]:before {}', ); expect(shim(':host(:not(p)):before {}', 'contenta', 'a-host')).toEqualCss( '[a-host]:not(p):before {}', ); }); // see b/63672152 it('should handle unexpected selectors in the most reasonable way', () => { expect(shim('cmp:host {}', 'contenta', 'a-host')).toEqualCss('cmp[a-host] {}'); expect(shim('cmp:host >>> {}', 'contenta', 'a-host')).toEqualCss('cmp[a-host] {}'); expect(shim('cmp:host child {}', 'contenta', 'a-host')).toEqualCss( 'cmp[a-host] child[contenta] {}', ); expect(shim('cmp:host >>> child {}', 'contenta', 'a-host')).toEqualCss( 'cmp[a-host] child {}', ); expect(shim('cmp :host {}', 'contenta', 'a-host')).toEqualCss('cmp [a-host] {}'); expect(shim('cmp :host >>> {}', 'contenta', 'a-host')).toEqualCss('cmp [a-host] {}'); expect(shim('cmp :host child {}', 'contenta', 'a-host')).toEqualCss( 'cmp [a-host] child[contenta] {}', ); expect(shim('cmp :host >>> child {}', 'contenta', 'a-host')).toEqualCss( 'cmp [a-host] child {}', ); }); });
{ "end_byte": 4482, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/host_and_host_context_spec.ts" }
angular/packages/compiler/test/shadow_css/host_and_host_context_spec.ts_4486_11079
scribe(':host-context', () => { it('should transform :host-context with pseudo selectors', () => { expect( shim(':host-context(backdrop:not(.borderless)) .backdrop {}', 'contenta', 'hosta'), ).toEqualCss( 'backdrop:not(.borderless)[hosta] .backdrop[contenta], backdrop:not(.borderless) [hosta] .backdrop[contenta] {}', ); expect(shim(':where(:host-context(backdrop)) {}', 'contenta', 'hosta')).toEqualCss( ':where(backdrop[hosta]), :where(backdrop [hosta]) {}', ); expect(shim(':where(:host-context(outer1)) :host(bar) {}', 'contenta', 'hosta')).toEqualCss( ':where(outer1) bar[hosta] {}', ); expect( shim(':where(:host-context(.one)) :where(:host-context(.two)) {}', 'contenta', 'a-host'), ).toEqualCss( ':where(.one.two[a-host]), ' + // `one` and `two` both on the host ':where(.one.two [a-host]), ' + // `one` and `two` are both on the same ancestor ':where(.one .two[a-host]), ' + // `one` is an ancestor and `two` is on the host ':where(.one .two [a-host]), ' + // `one` and `two` are both ancestors (in that order) ':where(.two .one[a-host]), ' + // `two` is an ancestor and `one` is on the host ':where(.two .one [a-host])' + // `two` and `one` are both ancestors (in that order) ' {}', ); expect( shim(':where(:host-context(backdrop)) .foo ~ .bar {}', 'contenta', 'hosta'), ).toEqualCss( ':where(backdrop[hosta]) .foo[contenta] ~ .bar[contenta], :where(backdrop [hosta]) .foo[contenta] ~ .bar[contenta] {}', ); expect(shim(':where(:host-context(backdrop)) :host {}', 'contenta', 'hosta')).toEqualCss( ':where(backdrop) [hosta] {}', ); expect(shim('div:where(:host-context(backdrop)) :host {}', 'contenta', 'hosta')).toEqualCss( 'div:where(backdrop) [hosta] {}', ); }); it('should handle tag selector', () => { expect(shim(':host-context(div) {}', 'contenta', 'a-host')).toEqualCss( 'div[a-host], div [a-host] {}', ); expect(shim(':host-context(ul) > .y {}', 'contenta', 'a-host')).toEqualCss( 'ul[a-host] > .y[contenta], ul [a-host] > .y[contenta] {}', ); }); it('should handle class selector', () => { expect(shim(':host-context(.x) {}', 'contenta', 'a-host')).toEqualCss( '.x[a-host], .x [a-host] {}', ); expect(shim(':host-context(.x) > .y {}', 'contenta', 'a-host')).toEqualCss( '.x[a-host] > .y[contenta], .x [a-host] > .y[contenta] {}', ); }); it('should handle attribute selector', () => { expect(shim(':host-context([a="b"]) {}', 'contenta', 'a-host')).toEqualCss( '[a="b"][a-host], [a="b"] [a-host] {}', ); expect(shim(':host-context([a=b]) {}', 'contenta', 'a-host')).toEqualCss( '[a=b][a-host], [a=b] [a-host] {}', ); }); it('should handle multiple :host-context() selectors', () => { expect(shim(':host-context(.one):host-context(.two) {}', 'contenta', 'a-host')).toEqualCss( '.one.two[a-host], ' + // `one` and `two` both on the host '.one.two [a-host], ' + // `one` and `two` are both on the same ancestor '.one .two[a-host], ' + // `one` is an ancestor and `two` is on the host '.one .two [a-host], ' + // `one` and `two` are both ancestors (in that order) '.two .one[a-host], ' + // `two` is an ancestor and `one` is on the host '.two .one [a-host]' + // `two` and `one` are both ancestors (in that order) ' {}', ); expect( shim(':host-context(.X):host-context(.Y):host-context(.Z) {}', 'contenta', 'a-host'), ).toEqualCss( '.X.Y.Z[a-host], ' + '.X.Y.Z [a-host], ' + '.X.Y .Z[a-host], ' + '.X.Y .Z [a-host], ' + '.X.Z .Y[a-host], ' + '.X.Z .Y [a-host], ' + '.X .Y.Z[a-host], ' + '.X .Y.Z [a-host], ' + '.X .Y .Z[a-host], ' + '.X .Y .Z [a-host], ' + '.X .Z .Y[a-host], ' + '.X .Z .Y [a-host], ' + '.Y.Z .X[a-host], ' + '.Y.Z .X [a-host], ' + '.Y .Z .X[a-host], ' + '.Y .Z .X [a-host], ' + '.Z .Y .X[a-host], ' + '.Z .Y .X [a-host] ' + '{}', ); }); // It is not clear what the behavior should be for a `:host-context` with no selectors. // This test is checking that the result is backward compatible with previous behavior. // Arguably it should actually be an error that should be reported. it('should handle :host-context with no ancestor selectors', () => { expect(shim(':host-context .inner {}', 'contenta', 'a-host')).toEqualCss( '[a-host] .inner[contenta] {}', ); expect(shim(':host-context() .inner {}', 'contenta', 'a-host')).toEqualCss( '[a-host] .inner[contenta] {}', ); }); // More than one selector such as this is not valid as part of the :host-context spec. // This test is checking that the result is backward compatible with previous behavior. // Arguably it should actually be an error that should be reported. it('should handle selectors', () => { expect(shim(':host-context(.one,.two) .inner {}', 'contenta', 'a-host')).toEqualCss( '.one[a-host] .inner[contenta], ' + '.one [a-host] .inner[contenta], ' + '.two[a-host] .inner[contenta], ' + '.two [a-host] .inner[contenta] ' + '{}', ); }); }); describe(':host-context and :host combination selector', () => { it('should handle selectors on the same element', () => { expect(shim(':host-context(div):host(.x) > .y {}', 'contenta', 'a-host')).toEqualCss( 'div.x[a-host] > .y[contenta] {}', ); }); it('should handle selectors on different elements', () => { expect(shim(':host-context(div) :host(.x) > .y {}', 'contenta', 'a-host')).toEqualCss( 'div .x[a-host] > .y[contenta] {}', ); expect(shim(':host-context(div) > :host(.x) > .y {}', 'contenta', 'a-host')).toEqualCss( 'div > .x[a-host] > .y[contenta] {}', ); }); it('should parse multiple rules containing :host-context and :host', () => { const input = ` :host-context(outer1) :host(bar) {} :host-context(outer2) :host(foo) {} `; expect(shim(input, 'contenta', 'a-host')).toEqualCss( 'outer1 bar[a-host] {} ' + 'outer2 foo[a-host] {}', ); }); }); });
{ "end_byte": 11079, "start_byte": 4486, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/host_and_host_context_spec.ts" }
angular/packages/compiler/test/shadow_css/utils.ts_0_1636
/** * @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 {ShadowCss} from '@angular/compiler/src/shadow_css'; export function shim(css: string, contentAttr: string, hostAttr: string = '') { const shadowCss = new ShadowCss(); return shadowCss.shimCssText(css, contentAttr, hostAttr); } const shadowCssMatchers: jasmine.CustomMatcherFactories = { toEqualCss: function (): jasmine.CustomMatcher { return { compare: function (actual: string, expected: string): jasmine.CustomMatcherResult { const actualCss = extractCssContent(actual); const expectedCss = extractCssContent(expected); const passes = actualCss === expectedCss; return { pass: passes, message: passes ? 'CSS equals as expected' : `Expected '${actualCss}' to equal '${expectedCss}'`, }; }, }; }, }; function extractCssContent(css: string): string { return css .replace(/^\n\s+/, '') .replace(/\n\s+$/, '') .replace(/\s+/g, ' ') .replace(/:\s/g, ':') .replace(/ }/g, '}'); } beforeEach(function () { jasmine.addMatchers(shadowCssMatchers); }); declare global { module jasmine { interface Matchers<T> { /** * Expect the actual css value to be equal to the expected css, * for this comparison extra spacing and newlines are ignored so * that only the core css content is being compared. */ toEqualCss(expected: string): void; } } }
{ "end_byte": 1636, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/utils.ts" }
angular/packages/compiler/test/shadow_css/ng_deep_spec.ts_0_1099
/** * @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 {shim} from './utils'; describe('ShadowCss, ng-deep', () => { it('should handle /deep/', () => { const css = shim('x /deep/ y {}', 'contenta'); expect(css).toEqualCss('x[contenta] y {}'); }); it('should handle >>>', () => { const css = shim('x >>> y {}', 'contenta'); expect(css).toEqualCss('x[contenta] y {}'); }); it('should handle ::ng-deep', () => { let css = '::ng-deep y {}'; expect(shim(css, 'contenta')).toEqualCss('y {}'); css = 'x ::ng-deep y {}'; expect(shim(css, 'contenta')).toEqualCss('x[contenta] y {}'); css = ':host > ::ng-deep .x {}'; expect(shim(css, 'contenta', 'h')).toEqualCss('[h] > .x {}'); css = ':host ::ng-deep > .x {}'; expect(shim(css, 'contenta', 'h')).toEqualCss('[h] > .x {}'); css = ':host > ::ng-deep > .x {}'; expect(shim(css, 'contenta', 'h')).toEqualCss('[h] > > .x {}'); }); });
{ "end_byte": 1099, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/ng_deep_spec.ts" }
angular/packages/compiler/test/shadow_css/repeat_groups_spec.ts_0_1386
/** * @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 {repeatGroups} from '@angular/compiler/src/shadow_css'; describe('ShadowCss, repeatGroups()', () => { it('should do nothing if `multiples` is 0', () => { const groups = [ ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ]; repeatGroups(groups, 0); expect(groups).toEqual([ ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ]); }); it('should do nothing if `multiples` is 1', () => { const groups = [ ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ]; repeatGroups(groups, 1); expect(groups).toEqual([ ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ]); }); it('should add clones of the original groups if `multiples` is greater than 1', () => { const group1 = ['a1', 'b1', 'c1']; const group2 = ['a2', 'b2', 'c2']; const groups = [group1, group2]; repeatGroups(groups, 3); expect(groups).toEqual([group1, group2, group1, group2, group1, group2]); expect(groups[0]).toBe(group1); expect(groups[1]).toBe(group2); expect(groups[2]).not.toBe(group1); expect(groups[3]).not.toBe(group2); expect(groups[4]).not.toBe(group1); expect(groups[5]).not.toBe(group2); }); });
{ "end_byte": 1386, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/repeat_groups_spec.ts" }
angular/packages/compiler/test/shadow_css/process_rules_spec.ts_0_1962
/** * @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 {CssRule, processRules} from '@angular/compiler/src/shadow_css'; describe('ShadowCss, processRules', () => { describe('parse rules', () => { function captureRules(input: string): CssRule[] { const result: CssRule[] = []; processRules(input, (cssRule) => { result.push(cssRule); return cssRule; }); return result; } it('should work with empty css', () => { expect(captureRules('')).toEqual([]); }); it('should capture a rule without body', () => { expect(captureRules('a;')).toEqual([new CssRule('a', '')]); }); it('should capture css rules with body', () => { expect(captureRules('a {b}')).toEqual([new CssRule('a', 'b')]); }); it('should capture css rules with nested rules', () => { expect(captureRules('a {b {c}} d {e}')).toEqual([ new CssRule('a', 'b {c}'), new CssRule('d', 'e'), ]); }); it('should capture multiple rules where some have no body', () => { expect(captureRules('@import a ; b {c}')).toEqual([ new CssRule('@import a', ''), new CssRule('b', 'c'), ]); }); }); describe('modify rules', () => { it('should allow to change the selector while preserving whitespaces', () => { expect( processRules( '@import a; b {c {d}} e {f}', (cssRule: CssRule) => new CssRule(cssRule.selector + '2', cssRule.content), ), ).toEqual('@import a2; b2 {c {d}} e2 {f}'); }); it('should allow to change the content', () => { expect( processRules( 'a {b}', (cssRule: CssRule) => new CssRule(cssRule.selector, cssRule.content + '2'), ), ).toEqual('a {b2}'); }); }); });
{ "end_byte": 1962, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/process_rules_spec.ts" }
angular/packages/compiler/test/shadow_css/at_rules_spec.ts_0_233
/** * @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 {shim} from './utils';
{ "end_byte": 233, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/at_rules_spec.ts" }
angular/packages/compiler/test/shadow_css/at_rules_spec.ts_235_7778
describe('ShadowCss, at-rules', () => { describe('@media', () => { it('should handle media rules with simple rules', () => { const css = '@media screen and (max-width: 800px) {div {font-size: 50px;}} div {}'; const expected = '@media screen and (max-width:800px) {div[contenta] {font-size:50px;}} div[contenta] {}'; expect(shim(css, 'contenta')).toEqualCss(expected); }); it('should handle media rules with both width and height', () => { const css = '@media screen and (max-width:800px, max-height:100%) {div {font-size:50px;}}'; const expected = '@media screen and (max-width:800px, max-height:100%) {div[contenta] {font-size:50px;}}'; expect(shim(css, 'contenta')).toEqualCss(expected); }); }); describe('@page', () => { // @page rules use a special set of at-rules and selectors and they can't be scoped. // See: https://www.w3.org/TR/css-page-3 it('should preserve @page rules', () => { const contentAttr = 'contenta'; const css = ` @page { margin-right: 4in; @top-left { content: "Hamlet"; } @top-right { content: "Page " counter(page); } } @page main { margin-left: 4in; } @page :left { margin-left: 3cm; margin-right: 4cm; } @page :right { margin-left: 4cm; margin-right: 3cm; } `; const result = shim(css, contentAttr); expect(result).toEqualCss(css); expect(result).not.toContain(contentAttr); }); it('should strip ::ng-deep and :host from within @page rules', () => { expect(shim('@page { margin-right: 4in; }', 'contenta', 'h')).toEqualCss( '@page { margin-right:4in;}', ); expect( shim('@page { ::ng-deep @top-left { content: "Hamlet";}}', 'contenta', 'h'), ).toEqualCss('@page { @top-left { content:"Hamlet";}}'); expect( shim('@page { :host ::ng-deep @top-left { content:"Hamlet";}}', 'contenta', 'h'), ).toEqualCss('@page { @top-left { content:"Hamlet";}}'); }); }); describe('@supports', () => { it('should handle support rules', () => { const css = '@supports (display: flex) {section {display: flex;}}'; const expected = '@supports (display:flex) {section[contenta] {display:flex;}}'; expect(shim(css, 'contenta')).toEqualCss(expected); }); it('should strip ::ng-deep and :host from within @supports', () => { expect( shim( '@supports (display: flex) { @font-face { :host ::ng-deep font-family{} } }', 'contenta', 'h', ), ).toEqualCss('@supports (display:flex) { @font-face { font-family{}}}'); }); }); describe('@font-face', () => { it('should strip ::ng-deep and :host from within @font-face', () => { expect(shim('@font-face { font-family {} }', 'contenta', 'h')).toEqualCss( '@font-face { font-family {}}', ); expect(shim('@font-face { ::ng-deep font-family{} }', 'contenta', 'h')).toEqualCss( '@font-face { font-family{}}', ); expect(shim('@font-face { :host ::ng-deep font-family{} }', 'contenta', 'h')).toEqualCss( '@font-face { font-family{}}', ); }); }); describe('@import', () => { it('should pass through @import directives', () => { const styleStr = '@import url("https://fonts.googleapis.com/css?family=Roboto");'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss(styleStr); }); it('should shim rules after @import', () => { const styleStr = '@import url("a"); div {}'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss('@import url("a"); div[contenta] {}'); }); it('should shim rules with quoted content after @import', () => { const styleStr = '@import url("a"); div {background-image: url("a.jpg"); color: red;}'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss( '@import url("a"); div[contenta] {background-image:url("a.jpg"); color:red;}', ); }); it('should pass through @import directives whose URL contains colons and semicolons', () => { const styleStr = '@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap");'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss(styleStr); }); it('should shim rules after @import with colons and semicolons', () => { const styleStr = '@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap"); div {}'; const css = shim(styleStr, 'contenta'); expect(css).toEqualCss( '@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap"); div[contenta] {}', ); }); }); describe('@container', () => { it('should scope normal selectors inside an unnamed container rules', () => { const css = `@container max(max-width: 500px) { .item { color: red; } }`; const result = shim(css, 'host-a'); expect(result).toEqualCss(` @container max(max-width: 500px) { .item[host-a] { color: red; } }`); }); it('should scope normal selectors inside a named container rules', () => { const css = ` @container container max(max-width: 500px) { .item { color: red; } }`; const result = shim(css, 'host-a'); // Note that for the time being we are not scoping the container name itself, // this is something that may or may not be done in the future depending // on how the css specs evolve. Currently as of Chrome 107 it looks like shadowDom // boundaries don't effect container queries (thus the scoping wouldn't be needed) // and this aspect of container queries seems to be still under active discussion: // https://github.com/w3c/csswg-drafts/issues/5984 expect(result).toEqualCss(` @container container max(max-width: 500px) { .item[host-a] { color: red; } }`); }); }); describe('@scope', () => { it('should scope normal selectors inside a scope rule with scoping limits', () => { const css = ` @scope (.media-object) to (.content > *) { img { border-radius: 50%; } .content { padding: 1em; } }`; const result = shim(css, 'host-a'); expect(result).toEqualCss(` @scope (.media-object) to (.content > *) { img[host-a] { border-radius: 50%; } .content[host-a] { padding: 1em; } }`); }); it('should scope normal selectors inside a scope rule', () => { const css = ` @scope (.light-scheme) { a { color: darkmagenta; } }`; const result = shim(css, 'host-a'); expect(result).toEqualCss(` @scope (.light-scheme) { a[host-a] { color: darkmagenta; } }`); }); }); describe('@document', () => { it('should handle document rules', () => { const css = '@document url(http://www.w3.org/) {div {font-size:50px;}}'; const expected = '@document url(http://www.w3.org/) {div[contenta] {font-size:50px;}}'; expect(shim(css, 'contenta')).toEqualCss(expected); }); });
{ "end_byte": 7778, "start_byte": 235, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/at_rules_spec.ts" }
angular/packages/compiler/test/shadow_css/at_rules_spec.ts_7782_8553
describe('@layer', () => { it('should handle layer rules', () => { const css = '@layer utilities {section {display: flex;}}'; const expected = '@layer utilities {section[contenta] {display:flex;}}'; expect(shim(css, 'contenta')).toEqualCss(expected); }); }); describe('@starting-style', () => { it('should scope normal selectors inside a starting-style rule', () => { const css = ` @starting-style { img { border-radius: 50%; } .content { padding: 1em; } }`; const result = shim(css, 'host-a'); expect(result).toEqualCss(` @starting-style { img[host-a] { border-radius: 50%; } .content[host-a] { padding: 1em; } }`); }); }); });
{ "end_byte": 8553, "start_byte": 7782, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/at_rules_spec.ts" }
angular/packages/compiler/test/shadow_css/keyframes_spec.ts_0_233
/** * @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 {shim} from './utils';
{ "end_byte": 233, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/keyframes_spec.ts" }
angular/packages/compiler/test/shadow_css/keyframes_spec.ts_235_7837
describe('ShadowCss, keyframes and animations', () => { it('should scope keyframes rules', () => { const css = '@keyframes foo {0% {transform:translate(-50%) scaleX(0);}}'; const expected = '@keyframes host-a_foo {0% {transform:translate(-50%) scaleX(0);}}'; expect(shim(css, 'host-a')).toEqual(expected); }); it('should scope -webkit-keyframes rules', () => { const css = '@-webkit-keyframes foo {0% {-webkit-transform:translate(-50%) scaleX(0);}} '; const expected = '@-webkit-keyframes host-a_foo {0% {-webkit-transform:translate(-50%) scaleX(0);}}'; expect(shim(css, 'host-a')).toEqual(expected); }); it('should scope animations using local keyframes identifiers', () => { const css = ` button { animation: foo 10s ease; } @keyframes foo { 0% { transform: translate(-50%) scaleX(0); } } `; const result = shim(css, 'host-a'); expect(result).toContain('animation: host-a_foo 10s ease;'); }); it('should not scope animations using non-local keyframes identifiers', () => { const css = ` button { animation: foo 10s ease; } `; const result = shim(css, 'host-a'); expect(result).toContain('animation: foo 10s ease;'); }); it('should scope animation-names using local keyframes identifiers', () => { const css = ` button { animation-name: foo; } @keyframes foo { 0% { transform: translate(-50%) scaleX(0); } } `; const result = shim(css, 'host-a'); expect(result).toContain('animation-name: host-a_foo;'); }); it('should not scope animation-names using non-local keyframes identifiers', () => { const css = ` button { animation-name: foo; } `; const result = shim(css, 'host-a'); expect(result).toContain('animation-name: foo;'); }); it('should handle (scope or not) multiple animation-names', () => { const css = ` button { animation-name: foo, bar,baz, qux , quux ,corge ,grault ,garply, waldo; } @keyframes foo {} @keyframes baz {} @keyframes quux {} @keyframes grault {} @keyframes waldo {}`; const result = shim(css, 'host-a'); const animationNames = [ 'host-a_foo', ' bar', 'host-a_baz', ' qux ', ' host-a_quux ', 'corge ', 'host-a_grault ', 'garply', ' host-a_waldo', ]; const expected = `animation-name: ${animationNames.join(',')};`; expect(result).toContain(expected); }); it('should handle (scope or not) multiple animation-names defined over multiple lines', () => { const css = ` button { animation-name: foo, bar,baz, qux , quux , grault, garply, waldo; } @keyframes foo {} @keyframes baz {} @keyframes quux {} @keyframes grault {}`; const result = shim(css, 'host-a'); ['foo', 'baz', 'quux', 'grault'].forEach((scoped) => expect(result).toContain(`host-a_${scoped}`), ); ['bar', 'qux', 'garply', 'waldo'].forEach((nonScoped) => { expect(result).toContain(nonScoped); expect(result).not.toContain(`host-a_${nonScoped}`); }); }); it('should handle (scope or not) animation definition containing some names which do not have a preceding space', () => { const COMPONENT_VARIABLE = '%COMP%'; const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`; const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`; const css = `.test { animation:my-anim 1s,my-anim2 2s, my-anim3 3s,my-anim4 4s; } @keyframes my-anim { 0% {color: red} 100% {color: blue} } @keyframes my-anim2 { 0% {font-size: 1em} 100% {font-size: 1.2em} } `; const result = shim(css, CONTENT_ATTR, HOST_ATTR); const animationLineMatch = result.match(/animation:[^;]+;/); let animationLine = ''; if (animationLineMatch) { animationLine = animationLineMatch[0]; } ['my-anim', 'my-anim2'].forEach((scoped) => expect(animationLine).toContain(`_ngcontent-%COMP%_${scoped}`), ); ['my-anim3', 'my-anim4'].forEach((nonScoped) => { expect(animationLine).toContain(nonScoped); expect(animationLine).not.toContain(`_ngcontent-%COMP%_${nonScoped}`); }); }); it('should handle (scope or not) animation definitions preceded by an erroneous comma', () => { const COMPONENT_VARIABLE = '%COMP%'; const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`; const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`; const css = `.test { animation:, my-anim 1s,my-anim2 2s, my-anim3 3s,my-anim4 4s; } @keyframes my-anim { 0% {color: red} 100% {color: blue} } @keyframes my-anim2 { 0% {font-size: 1em} 100% {font-size: 1.2em} } `; const result = shim(css, CONTENT_ATTR, HOST_ATTR); const animationLineMatch = result.match(/animation:[^;]+;/); let animationLine = ''; if (animationLineMatch) { animationLine = animationLineMatch[0]; } expect(result).not.toContain('animation:,'); ['my-anim', 'my-anim2'].forEach((scoped) => expect(animationLine).toContain(`_ngcontent-%COMP%_${scoped}`), ); ['my-anim3', 'my-anim4'].forEach((nonScoped) => { expect(animationLine).toContain(nonScoped); expect(animationLine).not.toContain(`_ngcontent-%COMP%_${nonScoped}`); }); }); it('should handle (scope or not) multiple animation definitions in a single declaration', () => { const css = ` div { animation: 1s ease foo, 2s bar infinite, forwards baz 3s; } p { animation: 1s "foo", 2s "bar"; } span { animation: .5s ease 'quux', 1s foo infinite, forwards "baz'" 1.5s, 2s bar; } button { animation: .5s bar, 1s foo 0.3s, 2s quux; } @keyframes bar {} @keyframes quux {} @keyframes "baz'" {}`; const result = shim(css, 'host-a'); expect(result).toContain('animation: 1s ease foo, 2s host-a_bar infinite, forwards baz 3s;'); expect(result).toContain('animation: 1s "foo", 2s "host-a_bar";'); expect(result).toContain(` animation: .5s host-a_bar, 1s foo 0.3s, 2s host-a_quux;`); expect(result).toContain(` animation: .5s ease 'host-a_quux', 1s foo infinite, forwards "host-a_baz'" 1.5s, 2s host-a_bar;`); }); it(`should not modify css variables ending with 'animation' even if they reference a local keyframes identifier`, () => { const css = ` button { --variable-animation: foo; } @keyframes foo {}`; const result = shim(css, 'host-a'); expect(result).toContain('--variable-animation: foo;'); }); it(`should not modify css variables ending with 'animation-name' even if they reference a local keyframes identifier`, () => { const css = ` button { --variable-animation-name: foo; } @keyframes foo {}`; const result = shim(css, 'host-a'); expect(result).toContain('--variable-animation-name: foo;'); });
{ "end_byte": 7837, "start_byte": 235, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/keyframes_spec.ts" }
angular/packages/compiler/test/shadow_css/keyframes_spec.ts_7841_14555
it('should maintain the spacing when handling (scoping or not) keyframes and animations', () => { const css = ` div { animation-name : foo; animation: 5s bar 1s backwards; animation : 3s baz ; animation-name:foobar ; animation:1s "foo" , 2s "bar",3s "quux"; } @-webkit-keyframes bar {} @keyframes foobar {} @keyframes quux {} `; const result = shim(css, 'host-a'); expect(result).toContain('animation-name : foo;'); expect(result).toContain('animation: 5s host-a_bar 1s backwards;'); expect(result).toContain('animation : 3s baz ;'); expect(result).toContain('animation-name:host-a_foobar ;'); expect(result).toContain('@-webkit-keyframes host-a_bar {}'); expect(result).toContain('@keyframes host-a_foobar {}'); expect(result).toContain('animation:1s "foo" , 2s "host-a_bar",3s "host-a_quux"'); }); it('should correctly process animations defined without any prefixed space', () => { let css = '.test{display: flex;animation:foo 1s forwards;} @keyframes foo {}'; let expected = '.test[host-a]{display: flex;animation:host-a_foo 1s forwards;} @keyframes host-a_foo {}'; expect(shim(css, 'host-a')).toEqual(expected); css = '.test{animation:foo 2s forwards;} @keyframes foo {}'; expected = '.test[host-a]{animation:host-a_foo 2s forwards;} @keyframes host-a_foo {}'; expect(shim(css, 'host-a')).toEqual(expected); css = 'button {display: block;animation-name: foobar;} @keyframes foobar {}'; expected = 'button[host-a] {display: block;animation-name: host-a_foobar;} @keyframes host-a_foobar {}'; expect(shim(css, 'host-a')).toEqual(expected); }); it('should correctly process keyframes defined without any prefixed space', () => { let css = '.test{display: flex;animation:bar 1s forwards;}@keyframes bar {}'; let expected = '.test[host-a]{display: flex;animation:host-a_bar 1s forwards;}@keyframes host-a_bar {}'; expect(shim(css, 'host-a')).toEqual(expected); css = '.test{animation:bar 2s forwards;}@-webkit-keyframes bar {}'; expected = '.test[host-a]{animation:host-a_bar 2s forwards;}@-webkit-keyframes host-a_bar {}'; expect(shim(css, 'host-a')).toEqual(expected); }); it('should ignore keywords values when scoping local animations', () => { const css = ` div { animation: inherit; animation: unset; animation: 3s ease reverse foo; animation: 5s foo 1s backwards; animation: none 1s foo; animation: .5s foo paused; animation: 1s running foo; animation: 3s linear 1s infinite running foo; animation: 5s foo ease; animation: 3s .5s infinite steps(3,end) foo; animation: 5s steps(9, jump-start) jump .5s; animation: 1s step-end steps; } @keyframes foo {} @keyframes inherit {} @keyframes unset {} @keyframes ease {} @keyframes reverse {} @keyframes backwards {} @keyframes none {} @keyframes paused {} @keyframes linear {} @keyframes running {} @keyframes end {} @keyframes jump {} @keyframes start {} @keyframes steps {} `; const result = shim(css, 'host-a'); expect(result).toContain('animation: inherit;'); expect(result).toContain('animation: unset;'); expect(result).toContain('animation: 3s ease reverse host-a_foo;'); expect(result).toContain('animation: 5s host-a_foo 1s backwards;'); expect(result).toContain('animation: none 1s host-a_foo;'); expect(result).toContain('animation: .5s host-a_foo paused;'); expect(result).toContain('animation: 1s running host-a_foo;'); expect(result).toContain('animation: 3s linear 1s infinite running host-a_foo;'); expect(result).toContain('animation: 5s host-a_foo ease;'); expect(result).toContain('animation: 3s .5s infinite steps(3,end) host-a_foo;'); expect(result).toContain('animation: 5s steps(9, jump-start) host-a_jump .5s;'); expect(result).toContain('animation: 1s step-end host-a_steps;'); }); it('should handle the usage of quotes', () => { const css = ` div { animation: 1.5s foo; } p { animation: 1s 'foz bar'; } @keyframes 'foo' {} @keyframes "foz bar" {} @keyframes bar {} @keyframes baz {} @keyframes qux {} @keyframes quux {} `; const result = shim(css, 'host-a'); expect(result).toContain("@keyframes 'host-a_foo' {}"); expect(result).toContain('@keyframes "host-a_foz bar" {}'); expect(result).toContain('animation: 1.5s host-a_foo;'); expect(result).toContain("animation: 1s 'host-a_foz bar';"); }); it('should handle the usage of quotes containing escaped quotes', () => { const css = ` div { animation: 1.5s "foo\\"bar"; } p { animation: 1s 'bar\\' \\'baz'; } button { animation-name: 'foz " baz'; } @keyframes "foo\\"bar" {} @keyframes "bar' 'baz" {} @keyframes "foz \\" baz" {} `; const result = shim(css, 'host-a'); expect(result).toContain('@keyframes "host-a_foo\\"bar" {}'); expect(result).toContain(`@keyframes "host-a_bar' 'baz" {}`); expect(result).toContain('@keyframes "host-a_foz \\" baz" {}'); expect(result).toContain('animation: 1.5s "host-a_foo\\"bar";'); expect(result).toContain("animation: 1s 'host-a_bar\\' \\'baz';"); expect(result).toContain(`animation-name: 'host-a_foz " baz';`); }); it('should handle the usage of commas in multiple animation definitions in a single declaration', () => { const css = ` button { animation: 1s "foo bar, baz", 2s 'qux quux'; } div { animation: 500ms foo, 1s 'bar, baz', 1500ms bar; } p { animation: 3s "bar, baz", 3s 'foo, bar' 1s, 3s "qux quux"; } @keyframes "qux quux" {} @keyframes "bar, baz" {} `; const result = shim(css, 'host-a'); expect(result).toContain('@keyframes "host-a_qux quux" {}'); expect(result).toContain('@keyframes "host-a_bar, baz" {}'); expect(result).toContain(`animation: 1s "foo bar, baz", 2s 'host-a_qux quux';`); expect(result).toContain("animation: 500ms foo, 1s 'host-a_bar, baz', 1500ms bar;"); expect(result).toContain( `animation: 3s "host-a_bar, baz", 3s 'foo, bar' 1s, 3s "host-a_qux quux";`, ); });
{ "end_byte": 14555, "start_byte": 7841, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/keyframes_spec.ts" }
angular/packages/compiler/test/shadow_css/keyframes_spec.ts_14559_20309
it('should handle the usage of double quotes escaping in multiple animation definitions in a single declaration', () => { const css = ` div { animation: 1s "foo", 1.5s "bar"; animation: 2s "fo\\"o", 2.5s "bar"; animation: 3s "foo\\"", 3.5s "bar", 3.7s "ba\\"r"; animation: 4s "foo\\\\", 4.5s "bar", 4.7s "baz\\""; animation: 5s "fo\\\\\\"o", 5.5s "bar", 5.7s "baz\\""; } @keyframes "foo" {} @keyframes "fo\\"o" {} @keyframes 'foo"' {} @keyframes 'foo\\\\' {} @keyframes bar {} @keyframes "ba\\"r" {} @keyframes "fo\\\\\\"o" {} `; const result = shim(css, 'host-a'); expect(result).toContain('@keyframes "host-a_foo" {}'); expect(result).toContain('@keyframes "host-a_fo\\"o" {}'); expect(result).toContain(`@keyframes 'host-a_foo"' {}`); expect(result).toContain("@keyframes 'host-a_foo\\\\' {}"); expect(result).toContain('@keyframes host-a_bar {}'); expect(result).toContain('@keyframes "host-a_ba\\"r" {}'); expect(result).toContain('@keyframes "host-a_fo\\\\\\"o"'); expect(result).toContain('animation: 1s "host-a_foo", 1.5s "host-a_bar";'); expect(result).toContain('animation: 2s "host-a_fo\\"o", 2.5s "host-a_bar";'); expect(result).toContain( 'animation: 3s "host-a_foo\\"", 3.5s "host-a_bar", 3.7s "host-a_ba\\"r";', ); expect(result).toContain('animation: 4s "host-a_foo\\\\", 4.5s "host-a_bar", 4.7s "baz\\"";'); expect(result).toContain( 'animation: 5s "host-a_fo\\\\\\"o", 5.5s "host-a_bar", 5.7s "baz\\"";', ); }); it('should handle the usage of single quotes escaping in multiple animation definitions in a single declaration', () => { const css = ` div { animation: 1s 'foo', 1.5s 'bar'; animation: 2s 'fo\\'o', 2.5s 'bar'; animation: 3s 'foo\\'', 3.5s 'bar', 3.7s 'ba\\'r'; animation: 4s 'foo\\\\', 4.5s 'bar', 4.7s 'baz\\''; animation: 5s 'fo\\\\\\'o', 5.5s 'bar', 5.7s 'baz\\''; } @keyframes foo {} @keyframes 'fo\\'o' {} @keyframes 'foo'' {} @keyframes 'foo\\\\' {} @keyframes "bar" {} @keyframes 'ba\\'r' {} @keyframes "fo\\\\\\'o" {} `; const result = shim(css, 'host-a'); expect(result).toContain('@keyframes host-a_foo {}'); expect(result).toContain("@keyframes 'host-a_fo\\'o' {}"); expect(result).toContain("@keyframes 'host-a_foo'' {}"); expect(result).toContain("@keyframes 'host-a_foo\\\\' {}"); expect(result).toContain('@keyframes "host-a_bar" {}'); expect(result).toContain("@keyframes 'host-a_ba\\'r' {}"); expect(result).toContain(`@keyframes "host-a_fo\\\\\\'o" {}`); expect(result).toContain("animation: 1s 'host-a_foo', 1.5s 'host-a_bar';"); expect(result).toContain("animation: 2s 'host-a_fo\\'o', 2.5s 'host-a_bar';"); expect(result).toContain( "animation: 3s 'host-a_foo\\'', 3.5s 'host-a_bar', 3.7s 'host-a_ba\\'r';", ); expect(result).toContain("animation: 4s 'host-a_foo\\\\', 4.5s 'host-a_bar', 4.7s 'baz\\'';"); expect(result).toContain("animation: 5s 'host-a_fo\\\\\\'o', 5.5s 'host-a_bar', 5.7s 'baz\\''"); }); it('should handle the usage of mixed single and double quotes escaping in multiple animation definitions in a single declaration', () => { const css = ` div { animation: 1s 'f\\"oo', 1.5s "ba\\'r"; animation: 2s "fo\\"\\"o", 2.5s 'b\\\\"ar'; animation: 3s 'foo\\\\', 3.5s "b\\\\\\"ar", 3.7s 'ba\\'\\"\\'r'; animation: 4s 'fo\\'o', 4.5s 'b\\"ar\\"', 4.7s "baz\\'"; } @keyframes 'f"oo' {} @keyframes 'fo""o' {} @keyframes 'foo\\\\' {} @keyframes 'fo\\'o' {} @keyframes 'ba\\'r' {} @keyframes 'b\\\\"ar' {} @keyframes 'b\\\\\\"ar' {} @keyframes 'b"ar"' {} @keyframes 'ba\\'\\"\\'r' {} `; const result = shim(css, 'host-a'); expect(result).toContain(`@keyframes 'host-a_f"oo' {}`); expect(result).toContain(`@keyframes 'host-a_fo""o' {}`); expect(result).toContain("@keyframes 'host-a_foo\\\\' {}"); expect(result).toContain("@keyframes 'host-a_fo\\'o' {}"); expect(result).toContain("@keyframes 'host-a_ba\\'r' {}"); expect(result).toContain(`@keyframes 'host-a_b\\\\"ar' {}`); expect(result).toContain(`@keyframes 'host-a_b\\\\\\"ar' {}`); expect(result).toContain(`@keyframes 'host-a_b"ar"' {}`); expect(result).toContain(`@keyframes 'host-a_ba\\'\\"\\'r' {}`); expect(result).toContain(`animation: 1s 'host-a_f\\"oo', 1.5s "host-a_ba\\'r";`); expect(result).toContain(`animation: 2s "host-a_fo\\"\\"o", 2.5s 'host-a_b\\\\"ar';`); expect(result).toContain( `animation: 3s 'host-a_foo\\\\', 3.5s "host-a_b\\\\\\"ar", 3.7s 'host-a_ba\\'\\"\\'r';`, ); expect(result).toContain( `animation: 4s 'host-a_fo\\'o', 4.5s 'host-a_b\\"ar\\"', 4.7s "baz\\'";`, ); }); it('should handle the usage of commas inside quotes', () => { const css = ` div { animation: 3s 'bar,, baz'; } p { animation-name: "bar,, baz", foo,'ease, linear , inherit', bar; } @keyframes 'foo' {} @keyframes 'bar,, baz' {} @keyframes 'ease, linear , inherit' {} `; const result = shim(css, 'host-a'); expect(result).toContain("@keyframes 'host-a_bar,, baz' {}"); expect(result).toContain("animation: 3s 'host-a_bar,, baz';"); expect(result).toContain( `animation-name: "host-a_bar,, baz", host-a_foo,'host-a_ease, linear , inherit', bar;`, ); });
{ "end_byte": 20309, "start_byte": 14559, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/keyframes_spec.ts" }
angular/packages/compiler/test/shadow_css/keyframes_spec.ts_20313_21651
it('should not ignore animation keywords when they are inside quotes', () => { const css = ` div { animation: 3s 'unset'; } button { animation: 5s "forwards" 1s forwards; } @keyframes unset {} @keyframes forwards {} `; const result = shim(css, 'host-a'); expect(result).toContain('@keyframes host-a_unset {}'); expect(result).toContain('@keyframes host-a_forwards {}'); expect(result).toContain("animation: 3s 'host-a_unset';"); expect(result).toContain('animation: 5s "host-a_forwards" 1s forwards;'); }); it('should handle css functions correctly', () => { const css = ` div { animation: foo 0.5s alternate infinite cubic-bezier(.17, .67, .83, .67); } button { animation: calc(2s / 2) calc; } @keyframes foo {} @keyframes cubic-bezier {} @keyframes calc {} `; const result = shim(css, 'host-a'); expect(result).toContain('@keyframes host-a_cubic-bezier {}'); expect(result).toContain('@keyframes host-a_calc {}'); expect(result).toContain( 'animation: host-a_foo 0.5s alternate infinite cubic-bezier(.17, .67, .83, .67);', ); expect(result).toContain('animation: calc(2s / 2) host-a_calc;'); }); });
{ "end_byte": 21651, "start_byte": 20313, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/keyframes_spec.ts" }
angular/packages/compiler/test/shadow_css/polyfills_spec.ts_0_2195
/** * @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 {shim} from './utils'; describe('ShadowCss, polyfills', () => { it('should support polyfill-next-selector', () => { let css = shim("polyfill-next-selector {content: 'x > y'} z {}", 'contenta'); expect(css).toEqualCss('x[contenta] > y[contenta]{}'); css = shim('polyfill-next-selector {content: "x > y"} z {}', 'contenta'); expect(css).toEqualCss('x[contenta] > y[contenta]{}'); css = shim(`polyfill-next-selector {content: 'button[priority="1"]'} z {}`, 'contenta'); expect(css).toEqualCss('button[priority="1"][contenta]{}'); }); it('should support polyfill-unscoped-rule', () => { let css = shim("polyfill-unscoped-rule {content: '#menu > .bar';color: blue;}", 'contenta'); expect(css).toContain('#menu > .bar {;color: blue;}'); css = shim('polyfill-unscoped-rule {content: "#menu > .bar";color: blue;}', 'contenta'); expect(css).toContain('#menu > .bar {;color: blue;}'); css = shim(`polyfill-unscoped-rule {content: 'button[priority="1"]'}`, 'contenta'); expect(css).toContain('button[priority="1"] {}'); }); it('should support multiple instances polyfill-unscoped-rule', () => { const css = shim( "polyfill-unscoped-rule {content: 'foo';color: blue;}" + "polyfill-unscoped-rule {content: 'bar';color: blue;}", 'contenta', ); expect(css).toContain('foo {;color: blue;}'); expect(css).toContain('bar {;color: blue;}'); }); it('should support polyfill-rule', () => { let css = shim("polyfill-rule {content: ':host.foo .bar';color: blue;}", 'contenta', 'a-host'); expect(css).toEqualCss('.foo[a-host] .bar[contenta] {;color:blue;}'); css = shim('polyfill-rule {content: ":host.foo .bar";color:blue;}', 'contenta', 'a-host'); expect(css).toEqualCss('.foo[a-host] .bar[contenta] {;color:blue;}'); css = shim(`polyfill-rule {content: 'button[priority="1"]'}`, 'contenta', 'a-host'); expect(css).toEqualCss('button[priority="1"][contenta] {}'); }); });
{ "end_byte": 2195, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/shadow_css/polyfills_spec.ts" }
angular/packages/compiler/test/schema/schema_extractor.ts_0_7356
/** * @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 SVG_PREFIX = ':svg:'; const MATH_PREFIX = ':math:'; // Element | Node interfaces // see https://developer.mozilla.org/en-US/docs/Web/API/Element // see https://developer.mozilla.org/en-US/docs/Web/API/Node const ELEMENT_IF = '[Element]'; // HTMLElement interface // see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement const HTMLELEMENT_IF = '[HTMLElement]'; const HTMLELEMENT_TAGS = 'abbr,address,article,aside,b,bdi,bdo,cite,content,code,dd,dfn,dt,em,figcaption,figure,footer,header,hgroup,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr'; const ALL_HTML_TAGS = // https://www.w3.org/TR/html5/index.html 'a,abbr,address,area,article,aside,audio,b,base,bdi,bdo,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,content,data,datalist,dd,del,dfn,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input,ins,kbd,keygen,label,legend,li,link,main,map,mark,meta,meter,nav,noscript,object,ol,optgroup,option,output,p,param,pre,progress,q,rb,rp,rt,rtc,ruby,s,samp,script,section,select,small,source,span,strong,style,sub,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr,' + // https://html.spec.whatwg.org/ 'details,summary,menu,menuitem'; // Via https://developer.mozilla.org/en-US/docs/Web/MathML const ALL_MATH_TAGS = 'math,maction,menclose,merror,mfenced,mfrac,mi,mmultiscripts,mn,mo,mover,mpadded,mphantom,mroot,mrow,ms,mspace,msqrt,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,semantics'; // Elements missing from Chrome (HtmlUnknownElement), to be manually added const MISSING_FROM_CHROME: {[el: string]: string[]} = { 'data^[HTMLElement]': ['value'], 'keygen^[HTMLElement]': ['!autofocus', 'challenge', '!disabled', 'form', 'keytype', 'name'], // TODO(vicb): Figure out why Chrome and WhatWG do not agree on the props // 'menu^[HTMLElement]': ['type', 'label'], 'menuitem^[HTMLElement]': [ 'type', 'label', 'icon', '!disabled', '!checked', 'radiogroup', '!default', ], 'summary^[HTMLElement]': [], 'time^[HTMLElement]': ['dateTime'], ':svg:cursor^:svg:': [], }; const _G: any = (typeof window != 'undefined' && window) || (typeof global != 'undefined' && global) || (typeof self != 'undefined' && self); const document: any = typeof _G['document'] == 'object' ? _G['document'] : null; export function extractSchema(): Map<string, string[]> | null { if (!document) return null; const SVGGraphicsElement = _G['SVGGraphicsElement']; if (!SVGGraphicsElement) return null; const element = document.createElement('video'); const descMap: Map<string, string[]> = new Map(); const visited: {[name: string]: boolean} = {}; // HTML top level extractProperties(Node, element, visited, descMap, ELEMENT_IF, ''); extractProperties(Element, element, visited, descMap, ELEMENT_IF, ''); extractProperties(HTMLElement, element, visited, descMap, HTMLELEMENT_IF, ELEMENT_IF); extractProperties(HTMLElement, element, visited, descMap, HTMLELEMENT_TAGS, HTMLELEMENT_IF); extractProperties(HTMLMediaElement, element, visited, descMap, 'media', HTMLELEMENT_IF); // SVG top level const svgAnimation = document.createElementNS('http://www.w3.org/2000/svg', 'set'); const svgPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); const svgFeFuncA = document.createElementNS('http://www.w3.org/2000/svg', 'feFuncA'); const svgGradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient'); const svgText = document.createElementNS('http://www.w3.org/2000/svg', 'text'); const SVGAnimationElement = _G['SVGAnimationElement']; const SVGGeometryElement = _G['SVGGeometryElement']; const SVGComponentTransferFunctionElement = _G['SVGComponentTransferFunctionElement']; const SVGGradientElement = _G['SVGGradientElement']; const SVGTextContentElement = _G['SVGTextContentElement']; const SVGTextPositioningElement = _G['SVGTextPositioningElement']; extractProperties(SVGElement, svgText, visited, descMap, SVG_PREFIX, HTMLELEMENT_IF); extractProperties( SVGGraphicsElement, svgText, visited, descMap, SVG_PREFIX + 'graphics', SVG_PREFIX, ); extractProperties( SVGAnimationElement, svgAnimation, visited, descMap, SVG_PREFIX + 'animation', SVG_PREFIX, ); extractProperties( SVGGeometryElement, svgPath, visited, descMap, SVG_PREFIX + 'geometry', SVG_PREFIX, ); extractProperties( SVGComponentTransferFunctionElement, svgFeFuncA, visited, descMap, SVG_PREFIX + 'componentTransferFunction', SVG_PREFIX, ); extractProperties( SVGGradientElement, svgGradient, visited, descMap, SVG_PREFIX + 'gradient', SVG_PREFIX, ); extractProperties( SVGTextContentElement, svgText, visited, descMap, SVG_PREFIX + 'textContent', SVG_PREFIX + 'graphics', ); extractProperties( SVGTextPositioningElement, svgText, visited, descMap, SVG_PREFIX + 'textPositioning', SVG_PREFIX + 'textContent', ); // Get all element types const types = Object.getOwnPropertyNames(window).filter((k) => /^(HTML|SVG).*?Element$/.test(k)); types.sort(); types.forEach((type) => { extractRecursiveProperties(visited, descMap, (window as any)[type]); }); // Add elements missed by Chrome auto-detection Object.keys(MISSING_FROM_CHROME).forEach((elHierarchy) => { descMap.set(elHierarchy, MISSING_FROM_CHROME[elHierarchy]); }); // Needed because we're running tests against some older Android versions. if (typeof MathMLElement !== 'undefined') { // Math top level const math = document.createElementNS('http://www.w3.org/1998/Math/MathML', 'math'); extractProperties(MathMLElement, math, visited, descMap, MATH_PREFIX, HTMLELEMENT_IF); // This script is written under the assumption that each tag has a corresponding class name, e.g. // `<circle>` -> `SVGCircleElement` however this doesn't hold for Math elements which are all // `MathMLElement`. Furthermore, they don't have special property names, but rather are // configured exclusively via attributes. Register them as plain elements that inherit from // the top-level `:math` namespace. ALL_MATH_TAGS.split(',').forEach((tag) => descMap.set(`${MATH_PREFIX}${tag}^${MATH_PREFIX}`, []), ); } assertNoMissingTags(descMap); return descMap; } function assertNoMissingTags(descMap: Map<string, string[]>): void { const extractedTags: string[] = []; Array.from(descMap.keys()).forEach((key: string) => { extractedTags.push(...key.split('|')[0].split('^')[0].split(',')); }); const missingTags = [ ...ALL_HTML_TAGS.split(','), ...(typeof MathMLElement === 'undefined' ? [] : ALL_MATH_TAGS.split(',').map((tag) => MATH_PREFIX + tag)), ].filter((tag) => !extractedTags.includes(tag)); if (missingTags.length) { throw new Error(`DOM schema misses tags: ${missingTags.join(',')}`); } }
{ "end_byte": 7356, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/schema/schema_extractor.ts" }
angular/packages/compiler/test/schema/schema_extractor.ts_7358_11999
function extractRecursiveProperties( visited: {[name: string]: boolean}, descMap: Map<string, string[]>, type: Function, ): string { const name = extractName(type)!; if (visited[name]) { return name; } let superName: string; switch (name) { case ELEMENT_IF: // ELEMENT_IF is the top most interface (Element | Node) superName = ''; break; case HTMLELEMENT_IF: superName = ELEMENT_IF; break; default: superName = extractRecursiveProperties( visited, descMap, type.prototype.__proto__.constructor, ); } let instance: HTMLElement | null = null; name.split(',').forEach((tagName) => { instance = type['name'].startsWith('SVG') ? document.createElementNS('http://www.w3.org/2000/svg', tagName.replace(SVG_PREFIX, '')) : document.createElement(tagName); let htmlType: Function; switch (tagName) { case 'cite': // <cite> interface is `HTMLQuoteElement` htmlType = HTMLElement; break; default: htmlType = type; } if (!(instance instanceof htmlType)) { throw new Error(`Tag <${tagName}> is not an instance of ${htmlType['name']}`); } }); extractProperties(type, instance, visited, descMap, name, superName); return name; } function extractProperties( type: Function, instance: any, visited: {[name: string]: boolean}, descMap: Map<string, string[]>, name: string, superName: string, ) { if (!type) return; visited[name] = true; const fullName = name + (superName ? '^' + superName : ''); const props: string[] = descMap.has(fullName) ? descMap.get(fullName)! : []; const prototype = type.prototype; const keys = Object.getOwnPropertyNames(prototype); keys.sort(); keys.forEach((name) => { if (name.startsWith('on')) { props.push('*' + name.slice(2)); } else { const typeCh = _TYPE_MNEMONICS[typeof instance[name]]; const descriptor = Object.getOwnPropertyDescriptor(prototype, name); const isSetter = descriptor && descriptor.set; if (typeCh !== void 0 && !name.startsWith('webkit') && isSetter) { props.push(typeCh + name); } } }); // There is no point in using `Node.nodeValue`, filter it out descMap.set(fullName, type === Node ? props.filter((p) => p != '%nodeValue') : props); } function extractName(type: Function): string | null { let name = type['name']; // The polyfill @webcomponents/custom-element/src/native-shim.js overrides the // window.HTMLElement and does not have the name property. Check if this is the // case and if so, set the name manually. if (name === '' && type === HTMLElement) { name = 'HTMLElement'; } switch (name) { // see https://www.w3.org/TR/html5/index.html // TODO(vicb): generate this map from all the element types case 'Element': return ELEMENT_IF; case 'HTMLElement': return HTMLELEMENT_IF; case 'HTMLImageElement': return 'img'; case 'HTMLAnchorElement': return 'a'; case 'HTMLDListElement': return 'dl'; case 'HTMLDirectoryElement': return 'dir'; case 'HTMLHeadingElement': return 'h1,h2,h3,h4,h5,h6'; case 'HTMLModElement': return 'ins,del'; case 'HTMLOListElement': return 'ol'; case 'HTMLParagraphElement': return 'p'; case 'HTMLQuoteElement': return 'q,blockquote,cite'; case 'HTMLTableCaptionElement': return 'caption'; case 'HTMLTableCellElement': return 'th,td'; case 'HTMLTableColElement': return 'col,colgroup'; case 'HTMLTableRowElement': return 'tr'; case 'HTMLTableSectionElement': return 'tfoot,thead,tbody'; case 'HTMLUListElement': return 'ul'; case 'SVGGraphicsElement': return SVG_PREFIX + 'graphics'; case 'SVGMPathElement': return SVG_PREFIX + 'mpath'; case 'SVGSVGElement': return SVG_PREFIX + 'svg'; case 'SVGTSpanElement': return SVG_PREFIX + 'tspan'; default: const isSVG = name.startsWith('SVG'); if (name.startsWith('HTML') || isSVG) { name = name.replace('HTML', '').replace('SVG', '').replace('Element', ''); if (isSVG && name.startsWith('FE')) { name = 'fe' + name.substring(2); } else if (name) { name = name.charAt(0).toLowerCase() + name.substring(1); } return isSVG ? SVG_PREFIX + name : name.toLowerCase(); } } return null; } const _TYPE_MNEMONICS: {[type: string]: string} = { 'string': '', 'number': '#', 'boolean': '!', 'object': '%', };
{ "end_byte": 11999, "start_byte": 7358, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/schema/schema_extractor.ts" }
angular/packages/compiler/test/schema/trusted_types_sinks_spec.ts_0_1211
/** * @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 {isTrustedTypesSink} from '@angular/compiler/src/schema/trusted_types_sinks'; describe('isTrustedTypesSink', () => { it('should classify Trusted Types sinks', () => { expect(isTrustedTypesSink('iframe', 'srcdoc')).toBeTrue(); expect(isTrustedTypesSink('p', 'innerHTML')).toBeTrue(); expect(isTrustedTypesSink('embed', 'src')).toBeTrue(); expect(isTrustedTypesSink('a', 'href')).toBeFalse(); expect(isTrustedTypesSink('base', 'href')).toBeFalse(); expect(isTrustedTypesSink('div', 'style')).toBeFalse(); }); it('should classify Trusted Types sinks case insensitive', () => { expect(isTrustedTypesSink('p', 'iNnErHtMl')).toBeTrue(); expect(isTrustedTypesSink('p', 'formaction')).toBeFalse(); expect(isTrustedTypesSink('p', 'formAction')).toBeFalse(); }); it('should classify attributes as Trusted Types sinks', () => { expect(isTrustedTypesSink('p', 'innerHtml')).toBeTrue(); expect(isTrustedTypesSink('p', 'formaction')).toBeFalse(); }); });
{ "end_byte": 1211, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/schema/trusted_types_sinks_spec.ts" }
angular/packages/compiler/test/schema/dom_element_schema_registry_spec.ts_0_552
/** * @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 '@angular/compiler/src/schema/dom_element_schema_registry'; import {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, SecurityContext} from '@angular/core'; import {Element} from '../../src/ml_parser/ast'; import {HtmlParser} from '../../src/ml_parser/html_parser'; import {extractSchema} from './schema_extractor';
{ "end_byte": 552, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/schema/dom_element_schema_registry_spec.ts" }
angular/packages/compiler/test/schema/dom_element_schema_registry_spec.ts_554_8989
describe('DOMElementSchema', () => { let registry: DomElementSchemaRegistry; beforeEach(() => { registry = new DomElementSchemaRegistry(); }); it('should detect elements', () => { expect(registry.hasElement('div', [])).toBeTruthy(); expect(registry.hasElement('b', [])).toBeTruthy(); expect(registry.hasElement('ng-container', [])).toBeTruthy(); expect(registry.hasElement('ng-content', [])).toBeTruthy(); expect(registry.hasElement('my-cmp', [])).toBeFalsy(); expect(registry.hasElement('abc', [])).toBeFalsy(); }); // https://github.com/angular/angular/issues/11219 it('should detect elements missing from chrome', () => { expect(registry.hasElement('data', [])).toBeTruthy(); expect(registry.hasElement('menuitem', [])).toBeTruthy(); expect(registry.hasElement('summary', [])).toBeTruthy(); expect(registry.hasElement('time', [])).toBeTruthy(); }); it('should detect properties on regular elements', () => { expect(registry.hasProperty('div', 'id', [])).toBeTruthy(); expect(registry.hasProperty('div', 'title', [])).toBeTruthy(); expect(registry.hasProperty('div', 'inert', [])).toBeTruthy(); expect(registry.hasProperty('h1', 'align', [])).toBeTruthy(); expect(registry.hasProperty('h2', 'align', [])).toBeTruthy(); expect(registry.hasProperty('h3', 'align', [])).toBeTruthy(); expect(registry.hasProperty('h4', 'align', [])).toBeTruthy(); expect(registry.hasProperty('h5', 'align', [])).toBeTruthy(); expect(registry.hasProperty('h6', 'align', [])).toBeTruthy(); expect(registry.hasProperty('h7', 'align', [])).toBeFalsy(); expect(registry.hasProperty('textarea', 'disabled', [])).toBeTruthy(); expect(registry.hasProperty('input', 'disabled', [])).toBeTruthy(); expect(registry.hasProperty('div', 'unknown', [])).toBeFalsy(); }); // https://github.com/angular/angular/issues/11219 it('should detect properties on elements missing from Chrome', () => { expect(registry.hasProperty('data', 'value', [])).toBeTruthy(); expect(registry.hasProperty('menuitem', 'type', [])).toBeTruthy(); expect(registry.hasProperty('menuitem', 'default', [])).toBeTruthy(); expect(registry.hasProperty('time', 'dateTime', [])).toBeTruthy(); }); it('should detect different kinds of types', () => { // inheritance: video => media => [HTMLElement] => [Element] expect(registry.hasProperty('video', 'className', [])).toBeTruthy(); // from [Element] expect(registry.hasProperty('video', 'id', [])).toBeTruthy(); // string expect(registry.hasProperty('video', 'scrollLeft', [])).toBeTruthy(); // number expect(registry.hasProperty('video', 'height', [])).toBeTruthy(); // number expect(registry.hasProperty('video', 'autoplay', [])).toBeTruthy(); // boolean expect(registry.hasProperty('video', 'classList', [])).toBeTruthy(); // object // from *; but events are not properties expect(registry.hasProperty('video', 'click', [])).toBeFalsy(); }); it('should treat custom elements as an unknown element by default', () => { expect(registry.hasProperty('custom-like', 'unknown', [])).toBe(false); expect(registry.hasProperty('custom-like', 'className', [])).toBeTruthy(); expect(registry.hasProperty('custom-like', 'style', [])).toBeTruthy(); expect(registry.hasProperty('custom-like', 'id', [])).toBeTruthy(); }); it('should return true for custom-like elements if the CUSTOM_ELEMENTS_SCHEMA was used', () => { expect(registry.hasProperty('custom-like', 'unknown', [CUSTOM_ELEMENTS_SCHEMA])).toBeTruthy(); expect(registry.hasElement('custom-like', [CUSTOM_ELEMENTS_SCHEMA])).toBeTruthy(); }); it('should return true for all elements if the NO_ERRORS_SCHEMA was used', () => { expect(registry.hasProperty('custom-like', 'unknown', [NO_ERRORS_SCHEMA])).toBeTruthy(); expect(registry.hasProperty('a', 'unknown', [NO_ERRORS_SCHEMA])).toBeTruthy(); expect(registry.hasElement('custom-like', [NO_ERRORS_SCHEMA])).toBeTruthy(); expect(registry.hasElement('unknown', [NO_ERRORS_SCHEMA])).toBeTruthy(); }); it('should re-map property names that are specified in DOM facade', () => { expect(registry.getMappedPropName('readonly')).toEqual('readOnly'); }); it('should not re-map property names that are not specified in DOM facade', () => { expect(registry.getMappedPropName('title')).toEqual('title'); expect(registry.getMappedPropName('exotic-unknown')).toEqual('exotic-unknown'); }); it('should return an error message when asserting event properties', () => { let report = registry.validateProperty('onClick'); expect(report.error).toBeTruthy(); expect(report.msg).toEqual( `Binding to event property 'onClick' is disallowed for security reasons, please use (Click)=... If 'onClick' is a directive input, make sure the directive is imported by the current module.`, ); report = registry.validateProperty('onAnything'); expect(report.error).toBeTruthy(); expect(report.msg).toEqual( `Binding to event property 'onAnything' is disallowed for security reasons, please use (Anything)=... If 'onAnything' is a directive input, make sure the directive is imported by the current module.`, ); }); it('should return an error message when asserting event attributes', () => { let report = registry.validateAttribute('onClick'); expect(report.error).toBeTruthy(); expect(report.msg).toEqual( `Binding to event attribute 'onClick' is disallowed for security reasons, please use (Click)=...`, ); report = registry.validateAttribute('onAnything'); expect(report.error).toBeTruthy(); expect(report.msg).toEqual( `Binding to event attribute 'onAnything' is disallowed for security reasons, please use (Anything)=...`, ); }); it('should not return an error message when asserting non-event properties or attributes', () => { let report = registry.validateProperty('title'); expect(report.error).toBeFalsy(); expect(report.msg).not.toBeDefined(); report = registry.validateProperty('exotic-unknown'); expect(report.error).toBeFalsy(); expect(report.msg).not.toBeDefined(); }); it('should return security contexts for elements', () => { expect(registry.securityContext('iframe', 'srcdoc', false)).toBe(SecurityContext.HTML); expect(registry.securityContext('p', 'innerHTML', false)).toBe(SecurityContext.HTML); expect(registry.securityContext('a', 'href', false)).toBe(SecurityContext.URL); expect(registry.securityContext('a', 'style', false)).toBe(SecurityContext.STYLE); expect(registry.securityContext('ins', 'cite', false)).toBe(SecurityContext.URL); expect(registry.securityContext('base', 'href', false)).toBe(SecurityContext.RESOURCE_URL); }); it('should detect properties on namespaced elements', () => { const htmlAst = new HtmlParser().parse('<svg:style>', 'TestComp'); const nodeName = (<Element>htmlAst.rootNodes[0]).name; expect(registry.hasProperty(nodeName, 'type', [])).toBeTruthy(); }); it('should check security contexts case insensitive', () => { expect(registry.securityContext('p', 'iNnErHtMl', false)).toBe(SecurityContext.HTML); expect(registry.securityContext('p', 'formaction', false)).toBe(SecurityContext.URL); expect(registry.securityContext('p', 'formAction', false)).toBe(SecurityContext.URL); }); it('should check security contexts for attributes', () => { expect(registry.securityContext('p', 'innerHtml', true)).toBe(SecurityContext.HTML); expect(registry.securityContext('p', 'formaction', true)).toBe(SecurityContext.URL); }); describe('Angular custom elements', () => { it('should support <ng-container>', () => { expect(registry.hasProperty('ng-container', 'id', [])).toBeFalsy(); }); it('should support <ng-content>', () => { expect(registry.hasProperty('ng-content', 'id', [])).toBeFalsy(); expect(registry.hasProperty('ng-content', 'select', [])).toBeFalsy(); }); }); if (!isNode) { it('generate a new schema', () => { let schema = '\n'; extractSchema()!.forEach((props, name) => { schema += `'${name}|${props.join(',')}',\n`; }); // Uncomment this line to see: // the generated schema which can then be pasted to the DomElementSchemaRegistry // console.log(schema); }); }
{ "end_byte": 8989, "start_byte": 554, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/schema/dom_element_schema_registry_spec.ts" }
angular/packages/compiler/test/schema/dom_element_schema_registry_spec.ts_8993_10689
describe('normalizeAnimationStyleProperty', () => { it('should normalize the given CSS property to camelCase', () => { expect(registry.normalizeAnimationStyleProperty('border-radius')).toBe('borderRadius'); expect(registry.normalizeAnimationStyleProperty('zIndex')).toBe('zIndex'); expect(registry.normalizeAnimationStyleProperty('-webkit-animation')).toBe('WebkitAnimation'); }); }); describe('normalizeAnimationStyleValue', () => { it('should normalize the given dimensional CSS style value to contain a PX value when numeric', () => { expect( registry.normalizeAnimationStyleValue('borderRadius', 'border-radius', 10)['value'], ).toBe('10px'); }); it('should not normalize any values that are of zero', () => { expect(registry.normalizeAnimationStyleValue('opacity', 'opacity', 0)['value']).toBe('0'); expect(registry.normalizeAnimationStyleValue('width', 'width', 0)['value']).toBe('0'); }); it("should retain the given dimensional CSS style value's unit if it already exists", () => { expect( registry.normalizeAnimationStyleValue('borderRadius', 'border-radius', '10em')['value'], ).toBe('10em'); }); it('should trim the provided CSS style value', () => { expect(registry.normalizeAnimationStyleValue('color', 'color', ' red ')['value']).toBe( 'red', ); }); it('should stringify all non dimensional numeric style values', () => { expect(registry.normalizeAnimationStyleValue('zIndex', 'zIndex', 10)['value']).toBe('10'); expect(registry.normalizeAnimationStyleValue('opacity', 'opacity', 0.5)['value']).toBe('0.5'); }); }); });
{ "end_byte": 10689, "start_byte": 8993, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/schema/dom_element_schema_registry_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_0_6185
/** * @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 {BindingType, ParsedEventType} from '../../src/expression_parser/ast'; import * as t from '../../src/render3/r3_ast'; import {unparse} from '../expression_parser/utils/unparser'; import {parseR3 as parse} from './view/util'; // Transform an IVY AST to a flat list of nodes to ease testing class R3AstHumanizer implements t.Visitor<void> { result: any[] = []; visitElement(element: t.Element) { this.result.push(['Element', element.name]); this.visitAll([ element.attributes, element.inputs, element.outputs, element.references, element.children, ]); } visitTemplate(template: t.Template) { this.result.push(['Template']); this.visitAll([ template.attributes, template.inputs, template.outputs, template.templateAttrs, template.references, template.variables, template.children, ]); } visitContent(content: t.Content) { this.result.push(['Content', content.selector]); this.visitAll([content.attributes, content.children]); } visitVariable(variable: t.Variable) { this.result.push(['Variable', variable.name, variable.value]); } visitReference(reference: t.Reference) { this.result.push(['Reference', reference.name, reference.value]); } visitTextAttribute(attribute: t.TextAttribute) { this.result.push(['TextAttribute', attribute.name, attribute.value]); } visitBoundAttribute(attribute: t.BoundAttribute) { this.result.push(['BoundAttribute', attribute.type, attribute.name, unparse(attribute.value)]); } visitBoundEvent(event: t.BoundEvent) { this.result.push(['BoundEvent', event.type, event.name, event.target, unparse(event.handler)]); } visitText(text: t.Text) { this.result.push(['Text', text.value]); } visitBoundText(text: t.BoundText) { this.result.push(['BoundText', unparse(text.value)]); } visitIcu(icu: t.Icu) { return null; } visitDeferredBlock(deferred: t.DeferredBlock): void { this.result.push(['DeferredBlock']); deferred.visitAll(this); } visitSwitchBlock(block: t.SwitchBlock): void { this.result.push(['SwitchBlock', unparse(block.expression)]); this.visitAll([block.cases]); } visitSwitchBlockCase(block: t.SwitchBlockCase): void { this.result.push([ 'SwitchBlockCase', block.expression === null ? null : unparse(block.expression), ]); this.visitAll([block.children]); } visitForLoopBlock(block: t.ForLoopBlock): void { const result: any[] = ['ForLoopBlock', unparse(block.expression), unparse(block.trackBy)]; this.result.push(result); this.visitAll([[block.item], block.contextVariables, block.children]); block.empty?.visit(this); } visitForLoopBlockEmpty(block: t.ForLoopBlockEmpty): void { this.result.push(['ForLoopBlockEmpty']); this.visitAll([block.children]); } visitIfBlock(block: t.IfBlock): void { this.result.push(['IfBlock']); this.visitAll([block.branches]); } visitIfBlockBranch(block: t.IfBlockBranch): void { this.result.push([ 'IfBlockBranch', block.expression === null ? null : unparse(block.expression), ]); const toVisit = [block.children]; block.expressionAlias !== null && toVisit.unshift([block.expressionAlias]); this.visitAll(toVisit); } visitDeferredTrigger(trigger: t.DeferredTrigger): void { if (trigger instanceof t.BoundDeferredTrigger) { this.result.push(['BoundDeferredTrigger', unparse(trigger.value)]); } else if (trigger instanceof t.ImmediateDeferredTrigger) { this.result.push(['ImmediateDeferredTrigger']); } else if (trigger instanceof t.HoverDeferredTrigger) { this.result.push(['HoverDeferredTrigger', trigger.reference]); } else if (trigger instanceof t.IdleDeferredTrigger) { this.result.push(['IdleDeferredTrigger']); } else if (trigger instanceof t.TimerDeferredTrigger) { this.result.push(['TimerDeferredTrigger', trigger.delay]); } else if (trigger instanceof t.InteractionDeferredTrigger) { this.result.push(['InteractionDeferredTrigger', trigger.reference]); } else if (trigger instanceof t.ViewportDeferredTrigger) { this.result.push(['ViewportDeferredTrigger', trigger.reference]); } else if (trigger instanceof t.NeverDeferredTrigger) { this.result.push(['NeverDeferredTrigger']); } else { throw new Error('Unknown trigger'); } } visitDeferredBlockPlaceholder(block: t.DeferredBlockPlaceholder): void { const result = ['DeferredBlockPlaceholder']; block.minimumTime !== null && result.push(`minimum ${block.minimumTime}ms`); this.result.push(result); this.visitAll([block.children]); } visitDeferredBlockLoading(block: t.DeferredBlockLoading): void { const result = ['DeferredBlockLoading']; block.afterTime !== null && result.push(`after ${block.afterTime}ms`); block.minimumTime !== null && result.push(`minimum ${block.minimumTime}ms`); this.result.push(result); this.visitAll([block.children]); } visitDeferredBlockError(block: t.DeferredBlockError): void { this.result.push(['DeferredBlockError']); this.visitAll([block.children]); } visitUnknownBlock(block: t.UnknownBlock): void { this.result.push(['UnknownBlock', block.name]); } visitLetDeclaration(decl: t.LetDeclaration) { this.result.push(['LetDeclaration', decl.name, unparse(decl.value)]); } private visitAll(nodes: t.Node[][]) { nodes.forEach((node) => t.visitAll(this, node)); } } function expectFromHtml(html: string, ignoreError = false) { const res = parse(html, {ignoreError}); return expectFromR3Nodes(res.nodes); } function expectFromR3Nodes(nodes: t.Node[]) { const humanizer = new R3AstHumanizer(); t.visitAll(humanizer, nodes); return expect(humanizer.result); } function expectSpanFromHtml(html: string) { const {nodes} = parse(html); return expect(nodes[0]!.sourceSpan.toString()); }
{ "end_byte": 6185, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_6187_13161
describe('R3 template transform', () => { describe('ParseSpan on nodes toString', () => { it('should create valid text span on Element with adjacent start and end tags', () => { expectSpanFromHtml('<div></div>').toBe('<div></div>'); }); }); describe('Nodes without binding', () => { it('should parse incomplete tags terminated by EOF', () => { expectFromHtml('<a', true /* ignoreError */).toEqual([['Element', 'a']]); }); it('should parse incomplete tags terminated by another tag', () => { expectFromHtml('<a <span></span>', true /* ignoreError */).toEqual([ ['Element', 'a'], ['Element', 'span'], ]); }); it('should parse text nodes', () => { expectFromHtml('a').toEqual([['Text', 'a']]); }); it('should parse elements with attributes', () => { expectFromHtml('<div a=b></div>').toEqual([ ['Element', 'div'], ['TextAttribute', 'a', 'b'], ]); }); it('should parse ngContent', () => { const res = parse('<ng-content select="a"></ng-content>'); expectFromR3Nodes(res.nodes).toEqual([ ['Content', 'a'], ['TextAttribute', 'select', 'a'], ]); }); it('should parse ngContent when it contains WS only', () => { expectFromHtml('<ng-content select="a"> \n </ng-content>').toEqual([ ['Content', 'a'], ['TextAttribute', 'select', 'a'], ]); }); it('should parse ngContent regardless the namespace', () => { expectFromHtml('<svg><ng-content select="a"></ng-content></svg>').toEqual([ ['Element', ':svg:svg'], ['Content', 'a'], ['TextAttribute', 'select', 'a'], ]); }); }); describe('Bound text nodes', () => { it('should parse bound text nodes', () => { expectFromHtml('{{a}}').toEqual([['BoundText', '{{ a }}']]); }); }); describe('Bound attributes', () => { it('should parse mixed case bound properties', () => { expectFromHtml('<div [someProp]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Property, 'someProp', 'v'], ]); }); it('should parse bound properties via bind- ', () => { expectFromHtml('<div bind-prop="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Property, 'prop', 'v'], ]); }); it('should report missing property names in bind- syntax', () => { expect(() => parse('<div bind-></div>')).toThrowError(/Property name is missing in binding/); }); it('should parse bound properties via {{...}}', () => { expectFromHtml('<div prop="{{v}}"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Property, 'prop', '{{ v }}'], ]); }); it('should parse dash case bound properties', () => { expectFromHtml('<div [some-prop]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Property, 'some-prop', 'v'], ]); }); it('should parse dotted name bound properties', () => { expectFromHtml('<div [d.ot]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Property, 'd.ot', 'v'], ]); }); it('should not normalize property names via the element schema', () => { expectFromHtml('<div [mappedAttr]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Property, 'mappedAttr', 'v'], ]); }); it('should parse mixed case bound attributes', () => { expectFromHtml('<div [attr.someAttr]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Attribute, 'someAttr', 'v'], ]); }); it('should parse and dash case bound classes', () => { expectFromHtml('<div [class.some-class]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Class, 'some-class', 'v'], ]); }); it('should parse mixed case bound classes', () => { expectFromHtml('<div [class.someClass]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Class, 'someClass', 'v'], ]); }); it('should parse mixed case bound styles', () => { expectFromHtml('<div [style.someStyle]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.Style, 'someStyle', 'v'], ]); }); }); describe('templates', () => { it('should support * directives', () => { expectFromHtml('<div *ngIf></div>').toEqual([ ['Template'], ['TextAttribute', 'ngIf', ''], ['Element', 'div'], ]); }); it('should support <ng-template>', () => { expectFromHtml('<ng-template></ng-template>').toEqual([['Template']]); }); it('should support <ng-template> regardless the namespace', () => { expectFromHtml('<svg><ng-template></ng-template></svg>').toEqual([ ['Element', ':svg:svg'], ['Template'], ]); }); it('should support <ng-template> with structural directive', () => { expectFromHtml('<ng-template *ngIf="true"></ng-template>').toEqual([ ['Template'], ['BoundAttribute', 0, 'ngIf', 'true'], ['Template'], ]); const res = parse('<ng-template *ngIf="true"></ng-template>', {ignoreError: false}); expect((res.nodes[0] as t.Template).tagName).toEqual(null); expect(((res.nodes[0] as t.Template).children[0] as t.Template).tagName).toEqual( 'ng-template', ); }); it('should support reference via #...', () => { expectFromHtml('<ng-template #a></ng-template>').toEqual([ ['Template'], ['Reference', 'a', ''], ]); }); it('should support reference via ref-...', () => { expectFromHtml('<ng-template ref-a></ng-template>').toEqual([ ['Template'], ['Reference', 'a', ''], ]); }); it('should report an error if a reference is used multiple times on the same template', () => { expect(() => parse('<ng-template #a #a></ng-template>')).toThrowError( /Reference "#a" is defined more than once/, ); }); it('should parse variables via let-...', () => { expectFromHtml('<ng-template let-a="b"></ng-template>').toEqual([ ['Template'], ['Variable', 'a', 'b'], ]); }); it('should parse attributes', () => { expectFromHtml('<ng-template k1="v1" k2="v2"></ng-template>').toEqual([ ['Template'], ['TextAttribute', 'k1', 'v1'], ['TextAttribute', 'k2', 'v2'], ]); }); it('should parse bound attributes', () => { expectFromHtml('<ng-template [k1]="v1" [k2]="v2"></ng-template>').toEqual([ ['Template'], ['BoundAttribute', BindingType.Property, 'k1', 'v1'], ['BoundAttribute', BindingType.Property, 'k2', 'v2'], ]); }); });
{ "end_byte": 13161, "start_byte": 6187, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_13165_20632
describe('inline templates', () => { it('should support attribute and bound attributes', () => { // Desugared form is // <ng-template ngFor [ngForOf]="items" let-item> // <div></div> // </ng-template> expectFromHtml('<div *ngFor="let item of items"></div>').toEqual([ ['Template'], ['TextAttribute', 'ngFor', ''], ['BoundAttribute', BindingType.Property, 'ngForOf', 'items'], ['Variable', 'item', '$implicit'], ['Element', 'div'], ]); // Note that this test exercises an *incorrect* usage of the ngFor // directive. There is a missing 'let' in the beginning of the expression // which causes the template to be desugared into // <ng-template [ngFor]="item" [ngForOf]="items"> // <div></div> // </ng-template> expectFromHtml('<div *ngFor="item of items"></div>').toEqual([ ['Template'], ['BoundAttribute', BindingType.Property, 'ngFor', 'item'], ['BoundAttribute', BindingType.Property, 'ngForOf', 'items'], ['Element', 'div'], ]); }); it('should parse variables via let ...', () => { expectFromHtml('<div *ngIf="let a=b"></div>').toEqual([ ['Template'], ['TextAttribute', 'ngIf', ''], ['Variable', 'a', 'b'], ['Element', 'div'], ]); }); it('should parse variables via as ...', () => { expectFromHtml('<div *ngIf="expr as local"></div>').toEqual([ ['Template'], ['BoundAttribute', BindingType.Property, 'ngIf', 'expr'], ['Variable', 'local', 'ngIf'], ['Element', 'div'], ]); }); }); describe('events', () => { it('should parse bound events with a target', () => { expectFromHtml('<div (window:event)="v"></div>').toEqual([ ['Element', 'div'], ['BoundEvent', ParsedEventType.Regular, 'event', 'window', 'v'], ]); }); it('should parse event names case sensitive', () => { expectFromHtml('<div (some-event)="v"></div>').toEqual([ ['Element', 'div'], ['BoundEvent', ParsedEventType.Regular, 'some-event', null, 'v'], ]); expectFromHtml('<div (someEvent)="v"></div>').toEqual([ ['Element', 'div'], ['BoundEvent', ParsedEventType.Regular, 'someEvent', null, 'v'], ]); }); it('should parse bound events via on-', () => { expectFromHtml('<div on-event="v"></div>').toEqual([ ['Element', 'div'], ['BoundEvent', ParsedEventType.Regular, 'event', null, 'v'], ]); }); it('should report missing event names in on- syntax', () => { expect(() => parse('<div on-></div>')).toThrowError(/Event name is missing in binding/); }); it('should parse bound events and properties via [(...)]', () => { expectFromHtml('<div [(prop)]="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.TwoWay, 'prop', 'v'], ['BoundEvent', ParsedEventType.TwoWay, 'propChange', null, 'v'], ]); }); it('should parse bound events and properties via bindon-', () => { expectFromHtml('<div bindon-prop="v"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.TwoWay, 'prop', 'v'], ['BoundEvent', ParsedEventType.TwoWay, 'propChange', null, 'v'], ]); }); it('should parse bound events and properties via [(...)] with non-null operator', () => { expectFromHtml('<div [(prop)]="v!"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.TwoWay, 'prop', 'v!'], ['BoundEvent', ParsedEventType.TwoWay, 'propChange', null, 'v!'], ]); }); it('should parse property reads bound via [(...)]', () => { expectFromHtml('<div [(prop)]="a.b.c"></div>').toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.TwoWay, 'prop', 'a.b.c'], ['BoundEvent', ParsedEventType.TwoWay, 'propChange', null, 'a.b.c'], ]); }); it('should parse keyed reads bound via [(...)]', () => { expectFromHtml(`<div [(prop)]="a['b']['c']"></div>`).toEqual([ ['Element', 'div'], ['BoundAttribute', BindingType.TwoWay, 'prop', `a["b"]["c"]`], ['BoundEvent', ParsedEventType.TwoWay, 'propChange', null, `a["b"]["c"]`], ]); }); it('should report assignments in two-way bindings', () => { expect(() => parse(`<div [(prop)]="v = 1"></div>`)).toThrowError( /Bindings cannot contain assignments/, ); }); it('should report pipes in two-way bindings', () => { expect(() => parse(`<div [(prop)]="v | pipe"></div>`)).toThrowError( /Cannot have a pipe in an action expression/, ); }); it('should report unsupported expressions in two-way bindings', () => { const unsupportedExpressions = [ 'v + 1', 'foo.bar?.baz', `foo.bar?.['baz']`, 'true', '123', 'a.b()', 'v()', '[1, 2, 3]', '{a: 1, b: 2, c: 3}', 'v === 1', 'a || b', 'a && b', 'a ?? b', '!a', '!!a', 'a ? b : c', ]; for (const expression of unsupportedExpressions) { expect(() => parse(`<div [(prop)]="${expression}"></div>`)) .withContext(expression) .toThrowError(/Unsupported expression in a two-way binding/); } }); it('should report an error for assignments into non-null asserted expressions', () => { // TODO(joost): this syntax is allowed in TypeScript. Consider changing the grammar to // allow this syntax, or improve the error message. // See https://github.com/angular/angular/pull/37809 expect(() => parse('<div (prop)="v! = $event"></div>')).toThrowError( /Unexpected token '=' at column 4/, ); }); it('should report missing property names in bindon- syntax', () => { expect(() => parse('<div bindon-></div>')).toThrowError( /Property name is missing in binding/, ); }); it('should report an error on empty expression', () => { expect(() => parse('<div (event)="">')).toThrowError(/Empty expressions are not allowed/); expect(() => parse('<div (event)=" ">')).toThrowError(/Empty expressions are not allowed/); }); it('should parse bound animation events when event name is empty', () => { expectFromHtml('<div (@)="onAnimationEvent($event)"></div>', true).toEqual([ ['Element', 'div'], ['BoundEvent', ParsedEventType.Animation, '', null, 'onAnimationEvent($event)'], ]); expect(() => parse('<div (@)></div>')).toThrowError( /Animation event name is missing in binding/, ); }); it('should report invalid phase value of animation event', () => { expect(() => parse('<div (@event.invalidPhase)></div>')).toThrowError( /The provided animation output phase value "invalidphase" for "@event" is not supported \(use start or done\)/, ); expect(() => parse('<div (@event.)></div>')).toThrowError( /The animation trigger output event \(@event\) is missing its phase value name \(start or done are currently supported\)/, ); expect(() => parse('<div (@event)></div>')).toThrowError( /The animation trigger output event \(@event\) is missing its phase value name \(start or done are currently supported\)/, ); }); });
{ "end_byte": 20632, "start_byte": 13165, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_20636_27246
describe('variables', () => { it('should report variables not on template elements', () => { expect(() => parse('<div let-a-name="b"></div>')).toThrowError( /"let-" is only supported on ng-template elements./, ); }); it('should report missing variable names', () => { expect(() => parse('<ng-template let-><ng-template>')).toThrowError( /Variable does not have a name/, ); }); }); describe('references', () => { it('should parse references via #...', () => { expectFromHtml('<div #a></div>').toEqual([ ['Element', 'div'], ['Reference', 'a', ''], ]); }); it('should parse references via ref-', () => { expectFromHtml('<div ref-a></div>').toEqual([ ['Element', 'div'], ['Reference', 'a', ''], ]); }); it('should parse camel case references', () => { expectFromHtml('<div #someA></div>').toEqual([ ['Element', 'div'], ['Reference', 'someA', ''], ]); }); it('should report invalid reference names', () => { expect(() => parse('<div #a-b></div>')).toThrowError(/"-" is not allowed in reference names/); }); it('should report missing reference names', () => { expect(() => parse('<div #></div>')).toThrowError(/Reference does not have a name/); }); it('should report an error if a reference is used multiple times on the same element', () => { expect(() => parse('<div #a #a></div>')).toThrowError( /Reference "#a" is defined more than once/, ); }); }); describe('literal attribute', () => { it('should report missing animation trigger in @ syntax', () => { expect(() => parse('<div @></div>')).toThrowError(/Animation trigger is missing/); }); }); describe('ng-content', () => { it('should parse ngContent without selector', () => { const res = parse('<ng-content></ng-content>'); expectFromR3Nodes(res.nodes).toEqual([['Content', '*']]); }); it('should parse ngContent with a specific selector', () => { const res = parse('<ng-content select="tag[attribute]"></ng-content>'); const selectors = ['', 'tag[attribute]']; expectFromR3Nodes(res.nodes).toEqual([ ['Content', selectors[1]], ['TextAttribute', 'select', selectors[1]], ]); }); it('should parse ngContent with a selector', () => { const res = parse( '<ng-content select="a"></ng-content><ng-content></ng-content><ng-content select="b"></ng-content>', ); const selectors = ['*', 'a', 'b']; expectFromR3Nodes(res.nodes).toEqual([ ['Content', selectors[1]], ['TextAttribute', 'select', selectors[1]], ['Content', selectors[0]], ['Content', selectors[2]], ['TextAttribute', 'select', selectors[2]], ]); }); it('should parse ngProjectAs as an attribute', () => { const res = parse('<ng-content ngProjectAs="a"></ng-content>'); expectFromR3Nodes(res.nodes).toEqual([ ['Content', '*'], ['TextAttribute', 'ngProjectAs', 'a'], ]); }); it('should parse ngContent with children', () => { const res = parse( '<ng-content><section>Root <div>Parent <span>Child</span></div></section></ng-content>', ); expectFromR3Nodes(res.nodes).toEqual([ ['Content', '*'], ['Element', 'section'], ['Text', 'Root '], ['Element', 'div'], ['Text', 'Parent '], ['Element', 'span'], ['Text', 'Child'], ]); }); }); describe('Ignored elements', () => { it('should ignore <script> elements', () => { expectFromHtml('<script></script>a').toEqual([['Text', 'a']]); }); it('should ignore <style> elements', () => { expectFromHtml('<style></style>a').toEqual([['Text', 'a']]); }); }); describe('<link rel="stylesheet">', () => { it('should keep <link rel="stylesheet"> elements if they have an absolute url', () => { expectFromHtml('<link rel="stylesheet" href="http://someurl">').toEqual([ ['Element', 'link'], ['TextAttribute', 'rel', 'stylesheet'], ['TextAttribute', 'href', 'http://someurl'], ]); expectFromHtml('<link REL="stylesheet" href="http://someurl">').toEqual([ ['Element', 'link'], ['TextAttribute', 'REL', 'stylesheet'], ['TextAttribute', 'href', 'http://someurl'], ]); }); it('should keep <link rel="stylesheet"> elements if they have no uri', () => { expectFromHtml('<link rel="stylesheet">').toEqual([ ['Element', 'link'], ['TextAttribute', 'rel', 'stylesheet'], ]); expectFromHtml('<link REL="stylesheet">').toEqual([ ['Element', 'link'], ['TextAttribute', 'REL', 'stylesheet'], ]); }); it('should ignore <link rel="stylesheet"> elements if they have a relative uri', () => { expectFromHtml('<link rel="stylesheet" href="./other.css">').toEqual([]); expectFromHtml('<link REL="stylesheet" HREF="./other.css">').toEqual([]); }); }); describe('ngNonBindable', () => { it('should ignore bindings on children of elements with ngNonBindable', () => { expectFromHtml('<div ngNonBindable>{{b}}</div>').toEqual([ ['Element', 'div'], ['TextAttribute', 'ngNonBindable', ''], ['Text', '{{b}}'], ]); }); it('should keep nested children of elements with ngNonBindable', () => { expectFromHtml('<div ngNonBindable><span>{{b}}</span></div>').toEqual([ ['Element', 'div'], ['TextAttribute', 'ngNonBindable', ''], ['Element', 'span'], ['Text', '{{b}}'], ]); }); it('should ignore <script> elements inside of elements with ngNonBindable', () => { expectFromHtml('<div ngNonBindable><script></script>a</div>').toEqual([ ['Element', 'div'], ['TextAttribute', 'ngNonBindable', ''], ['Text', 'a'], ]); }); it('should ignore <style> elements inside of elements with ngNonBindable', () => { expectFromHtml('<div ngNonBindable><style></style>a</div>').toEqual([ ['Element', 'div'], ['TextAttribute', 'ngNonBindable', ''], ['Text', 'a'], ]); }); it('should ignore <link rel="stylesheet"> elements inside of elements with ngNonBindable', () => { expectFromHtml('<div ngNonBindable><link rel="stylesheet">a</div>').toEqual([ ['Element', 'div'], ['TextAttribute', 'ngNonBindable', ''], ['Text', 'a'], ]); }); });
{ "end_byte": 27246, "start_byte": 20636, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_27250_35921
describe('deferred blocks', () => { it('should parse a simple deferred block', () => { expectFromHtml('@defer{hello}').toEqual([['DeferredBlock'], ['Text', 'hello']]); }); it('should parse a deferred block with a `when` trigger', () => { expectFromHtml('@defer (when isVisible() && loaded){hello}').toEqual([ ['DeferredBlock'], ['BoundDeferredTrigger', 'isVisible() && loaded'], ['Text', 'hello'], ]); }); it('should parse a deferred block with a single `on` trigger', () => { expectFromHtml('@defer (on idle){hello}').toEqual([ ['DeferredBlock'], ['IdleDeferredTrigger'], ['Text', 'hello'], ]); }); it('should parse a deferred block with multiple `on` triggers', () => { expectFromHtml('@defer (on idle, viewport(button)){hello}').toEqual([ ['DeferredBlock'], ['IdleDeferredTrigger'], ['ViewportDeferredTrigger', 'button'], ['Text', 'hello'], ]); }); it('should parse a deferred block with a non-parenthesized trigger at the end', () => { expectFromHtml('@defer (on idle, viewport(button), immediate){hello}').toEqual([ ['DeferredBlock'], ['IdleDeferredTrigger'], ['ViewportDeferredTrigger', 'button'], ['ImmediateDeferredTrigger'], ['Text', 'hello'], ]); }); it('should parse a deferred block with `when` and `on` triggers', () => { const template = '@defer (when isVisible(); on timer(100ms), idle, viewport(button)){hello}'; expectFromHtml(template).toEqual([ ['DeferredBlock'], ['BoundDeferredTrigger', 'isVisible()'], ['TimerDeferredTrigger', 100], ['IdleDeferredTrigger'], ['ViewportDeferredTrigger', 'button'], ['Text', 'hello'], ]); }); it('should allow new line after trigger name', () => { const template = `@defer(\nwhen\nisVisible(); on\ntimer(100ms),\nidle, viewport(button)){hello}`; expectFromHtml(template).toEqual([ ['DeferredBlock'], ['BoundDeferredTrigger', 'isVisible()'], ['TimerDeferredTrigger', 100], ['IdleDeferredTrigger'], ['ViewportDeferredTrigger', 'button'], ['Text', 'hello'], ]); }); it('should parse a deferred block with a timer set in seconds', () => { expectFromHtml('@defer (on timer(10s)){hello}').toEqual([ ['DeferredBlock'], ['TimerDeferredTrigger', 10000], ['Text', 'hello'], ]); }); it('should parse a deferred block with a timer with a decimal point', () => { expectFromHtml('@defer (on timer(1.5s)){hello}').toEqual([ ['DeferredBlock'], ['TimerDeferredTrigger', 1500], ['Text', 'hello'], ]); }); it('should parse a deferred block with a timer that has no units', () => { expectFromHtml('@defer (on timer(100)){hello}').toEqual([ ['DeferredBlock'], ['TimerDeferredTrigger', 100], ['Text', 'hello'], ]); }); it('should parse a deferred block with a hover trigger', () => { expectFromHtml('@defer (on hover(button)){hello}').toEqual([ ['DeferredBlock'], ['HoverDeferredTrigger', 'button'], ['Text', 'hello'], ]); }); it('should parse a deferred block with an interaction trigger', () => { expectFromHtml('@defer (on interaction(button)){hello}').toEqual([ ['DeferredBlock'], ['InteractionDeferredTrigger', 'button'], ['Text', 'hello'], ]); }); it('should parse a deferred block with connected blocks', () => { expectFromHtml( '@defer {<calendar-cmp [date]="current"/>}' + '@loading {Loading...}' + '@placeholder {Placeholder content!}' + '@error {Loading failed :(}', ).toEqual([ ['DeferredBlock'], ['Element', 'calendar-cmp'], ['BoundAttribute', 0, 'date', 'current'], ['DeferredBlockPlaceholder'], ['Text', 'Placeholder content!'], ['DeferredBlockLoading'], ['Text', 'Loading...'], ['DeferredBlockError'], ['Text', 'Loading failed :('], ]); }); it('should parse a deferred block with comments between the connected blocks', () => { expectFromHtml( '@defer {<calendar-cmp [date]="current"/>}' + '<!-- Show this while loading --> @loading {Loading...}' + '<!-- Show this on the server --> @placeholder {Placeholder content!}' + '<!-- Show this on error --> @error {Loading failed :(}', ).toEqual([ ['DeferredBlock'], ['Element', 'calendar-cmp'], ['BoundAttribute', 0, 'date', 'current'], ['DeferredBlockPlaceholder'], ['Text', 'Placeholder content!'], ['DeferredBlockLoading'], ['Text', 'Loading...'], ['DeferredBlockError'], ['Text', 'Loading failed :('], ]); }); it( 'should parse a deferred block with connected blocks that have an arbitrary ' + 'amount of whitespace between them when preserveWhitespaces is enabled', () => { const template = '@defer {<calendar-cmp [date]="current"/>}' + ' @loading {Loading...} ' + '\n\n @placeholder {Placeholder content!} \n\n' + '@error {Loading failed :(}'; expectFromR3Nodes(parse(template, {preserveWhitespaces: true}).nodes).toEqual([ // Note: we also expect the whitespace nodes between the blocks to be ignored here. ['DeferredBlock'], ['Element', 'calendar-cmp'], ['BoundAttribute', 0, 'date', 'current'], ['DeferredBlockPlaceholder'], ['Text', 'Placeholder content!'], ['DeferredBlockLoading'], ['Text', 'Loading...'], ['DeferredBlockError'], ['Text', 'Loading failed :('], ]); }, ); it('should parse a loading block with parameters', () => { expectFromHtml( '@defer{<calendar-cmp [date]="current"/>}' + '@loading (after 100ms; minimum 1.5s){Loading...}', ).toEqual([ ['DeferredBlock'], ['Element', 'calendar-cmp'], ['BoundAttribute', 0, 'date', 'current'], ['DeferredBlockLoading', 'after 100ms', 'minimum 1500ms'], ['Text', 'Loading...'], ]); }); it('should parse a placeholder block with parameters', () => { expectFromHtml( '@defer {<calendar-cmp [date]="current"/>}' + '@placeholder (minimum 1.5s){Placeholder...}', ).toEqual([ ['DeferredBlock'], ['Element', 'calendar-cmp'], ['BoundAttribute', 0, 'date', 'current'], ['DeferredBlockPlaceholder', 'minimum 1500ms'], ['Text', 'Placeholder...'], ]); }); it('should parse a deferred block with prefetch triggers', () => { const html = '@defer (on idle; prefetch on viewport(button), hover(button); prefetch when shouldPrefetch()){hello}'; expectFromHtml(html).toEqual([ ['DeferredBlock'], ['IdleDeferredTrigger'], ['ViewportDeferredTrigger', 'button'], ['HoverDeferredTrigger', 'button'], ['BoundDeferredTrigger', 'shouldPrefetch()'], ['Text', 'hello'], ]); }); it('should allow arbitrary number of spaces after the `prefetch` keyword', () => { const html = '@defer (on idle; prefetch on viewport(button), hover(button); prefetch when shouldPrefetch()){hello}'; expectFromHtml(html).toEqual([ ['DeferredBlock'], ['IdleDeferredTrigger'], ['ViewportDeferredTrigger', 'button'], ['HoverDeferredTrigger', 'button'], ['BoundDeferredTrigger', 'shouldPrefetch()'], ['Text', 'hello'], ]); }); it('should parse the hydrate-specific `never` trigger', () => { const html = '@defer (on idle; hydrate never){hello}'; expectFromHtml(html).toEqual([ ['DeferredBlock'], ['NeverDeferredTrigger'], ['IdleDeferredTrigger'], ['Text', 'hello'], ]); }); it('should parse a deferred block with hydrate triggers', () => { const html = '@defer (on idle; hydrate on viewport, hover, timer(500); hydrate when shouldHydrate()){hello}'; expectFromHtml(html).toEqual([ ['DeferredBlock'], ['ViewportDeferredTrigger', null], ['HoverDeferredTrigger', null], ['TimerDeferredTrigger', 500], ['BoundDeferredTrigger', 'shouldHydrate()'], ['IdleDeferredTrigger'], ['Text', 'hello'], ]); });
{ "end_byte": 35921, "start_byte": 27250, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_35927_40000
it('should allow arbitrary number of spaces after the `hydrate` keyword', () => { const html = '@defer (on idle; hydrate on viewport, hover; hydrate when shouldHydrate()){hello}'; expectFromHtml(html).toEqual([ ['DeferredBlock'], ['ViewportDeferredTrigger', null], ['HoverDeferredTrigger', null], ['BoundDeferredTrigger', 'shouldHydrate()'], ['IdleDeferredTrigger'], ['Text', 'hello'], ]); }); it('should parse a complete example', () => { expectFromHtml( '@defer (when isVisible() && foo; on hover(button), timer(10s), idle, immediate, ' + 'interaction(button), viewport(container); prefetch on immediate; ' + 'prefetch when isDataLoaded(); hydrate when shouldHydrate(); hydrate on viewport){' + '<calendar-cmp [date]="current"/>}@loading (minimum 1s; after 100ms){Loading...}' + '@placeholder (minimum 500){Placeholder content!}' + '@error {Loading failed :(}', ).toEqual([ ['DeferredBlock'], ['BoundDeferredTrigger', 'shouldHydrate()'], ['ViewportDeferredTrigger', null], ['BoundDeferredTrigger', 'isVisible() && foo'], ['HoverDeferredTrigger', 'button'], ['TimerDeferredTrigger', 10000], ['IdleDeferredTrigger'], ['ImmediateDeferredTrigger'], ['InteractionDeferredTrigger', 'button'], ['ViewportDeferredTrigger', 'container'], ['ImmediateDeferredTrigger'], ['BoundDeferredTrigger', 'isDataLoaded()'], ['Element', 'calendar-cmp'], ['BoundAttribute', 0, 'date', 'current'], ['DeferredBlockPlaceholder', 'minimum 500ms'], ['Text', 'Placeholder content!'], ['DeferredBlockLoading', 'after 100ms', 'minimum 1000ms'], ['Text', 'Loading...'], ['DeferredBlockError'], ['Text', 'Loading failed :('], ]); }); it('should treat blocks as plain text inside ngNonBindable', () => { expectFromHtml( '<div ngNonBindable>' + '@defer (when isVisible() && foo; on hover(button), timer(10s), idle, immediate, ' + 'interaction(button), viewport(container); prefetch on immediate; ' + 'prefetch when isDataLoaded(); hydrate when shouldHydrate(); hydrate on viewport){' + '<calendar-cmp [date]="current"/>}@loading (minimum 1s; after 100ms){Loading...}' + '@placeholder (minimum 500){Placeholder content!}' + '@error {Loading failed :(}' + '</div>', ).toEqual([ ['Element', 'div'], ['TextAttribute', 'ngNonBindable', ''], [ 'Text', '@defer (when isVisible() && foo; on hover(button), timer(10s), idle, immediate, ' + 'interaction(button), viewport(container); prefetch on immediate; ' + 'prefetch when isDataLoaded(); hydrate when shouldHydrate(); hydrate on viewport){', ], ['Element', 'calendar-cmp'], ['TextAttribute', '[date]', 'current'], ['Text', '}'], ['Text', '@loading (minimum 1s; after 100ms){'], ['Text', 'Loading...'], ['Text', '}'], ['Text', '@placeholder (minimum 500){'], ['Text', 'Placeholder content!'], ['Text', '}'], ['Text', '@error {'], ['Text', 'Loading failed :('], ['Text', '}'], ]); }); it('should parse triggers with implied target elements', () => { expectFromHtml( '@defer (on hover, interaction, viewport; prefetch on hover, interaction, viewport) {hello}' + '@placeholder {<implied-trigger/>}', ).toEqual([ ['DeferredBlock'], ['HoverDeferredTrigger', null], ['InteractionDeferredTrigger', null], ['ViewportDeferredTrigger', null], ['HoverDeferredTrigger', null], ['InteractionDeferredTrigger', null], ['ViewportDeferredTrigger', null], ['Text', 'hello'], ['DeferredBlockPlaceholder'], ['Element', 'implied-trigger'], ]); });
{ "end_byte": 40000, "start_byte": 35927, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_40006_48510
describe('block validations', () => { it('should report syntax error in `when` trigger', () => { expect(() => parse('@defer (when isVisible#){hello}')).toThrowError( /Invalid character \[#\]/, ); }); it('should report unrecognized trigger', () => { expect(() => parse('@defer (unknown visible()){hello}')).toThrowError( /Unrecognized trigger/, ); }); it('should report content before a connected block', () => { expect(() => parse('@defer {hello} <br> @placeholder {placeholder}')).toThrowError( /@placeholder block can only be used after an @defer block/, ); }); it('should report connected defer blocks used without a defer block', () => { expect(() => parse('@placeholder {placeholder}')).toThrowError( /@placeholder block can only be used after an @defer block/, ); expect(() => parse('@loading {loading}')).toThrowError( /@loading block can only be used after an @defer block/, ); expect(() => parse('@error {error}')).toThrowError( /@error block can only be used after an @defer block/, ); }); it('should report multiple placeholder blocks', () => { expect(() => parse('@defer {hello} @placeholder {p1} @placeholder {p2}')).toThrowError( /@defer block can only have one @placeholder block/, ); }); it('should report multiple loading blocks', () => { expect(() => parse('@defer {hello} @loading {l1} @loading {l2}')).toThrowError( /@defer block can only have one @loading block/, ); }); it('should report multiple error blocks', () => { expect(() => parse('@defer {hello} @error {e1} @error {e2}')).toThrowError( /@defer block can only have one @error block/, ); }); it('should report unrecognized parameter in placeholder block', () => { expect(() => parse('@defer {hello} @placeholder (unknown 100ms) {hi}')).toThrowError( /Unrecognized parameter in @placeholder block: "unknown 100ms"/, ); }); it('should report unrecognized parameter in loading block', () => { expect(() => parse('@defer {hello} @loading (unknown 100ms) {hi}')).toThrowError( /Unrecognized parameter in @loading block: "unknown 100ms"/, ); }); it('should report any parameter usage in error block', () => { expect(() => parse('@defer {hello} @error (foo) {hi}')).toThrowError( /@error block cannot have parameters/, ); }); it('should report if minimum placeholder time cannot be parsed', () => { expect(() => parse('@defer {hello} @placeholder (minimum 123abc) {hi}')).toThrowError( /Could not parse time value of parameter "minimum"/, ); }); it('should report if minimum loading time cannot be parsed', () => { expect(() => parse('@defer {hello} @loading (minimum 123abc) {hi}')).toThrowError( /Could not parse time value of parameter "minimum"/, ); }); it('should report if after loading time cannot be parsed', () => { expect(() => parse('@defer {hello} @loading (after 123abc) {hi}')).toThrowError( /Could not parse time value of parameter "after"/, ); }); it('should report unrecognized `on` trigger', () => { expect(() => parse('@defer (on foo) {hello}')).toThrowError( /Unrecognized trigger type "foo"/, ); }); it('should report missing comma after unparametarized `on` trigger', () => { expect(() => parse('@defer (on hover idle) {hello}')).toThrowError(/Unexpected token/); }); it('should report missing comma after parametarized `on` trigger', () => { expect(() => parse('@defer (on viewport(button) idle) {hello}')).toThrowError( /Unexpected token/, ); }); it('should report mutliple commas after between `on` triggers', () => { expect(() => parse('@defer (on viewport(button), , idle) {hello}')).toThrowError( /Unexpected token/, ); }); it('should report unclosed parenthesis in `on` trigger', () => { expect(() => parse('@defer (on viewport(button) {hello}')).toThrowError( /Incomplete block "defer"/, ); }); it('should report incorrect closing parenthesis in `on` trigger', () => { expect(() => parse('@defer (on viewport(but)ton) {hello}')).toThrowError( /Unexpected token/, ); }); it('should report stray closing parenthesis in `on` trigger', () => { expect(() => parse('@defer (on idle)) {hello}')).toThrowError(/Unexpected character "EOF"/); }); it('should report non-identifier token usage in `on` trigger', () => { expect(() => parse('@defer (on 123) {hello}')).toThrowError(/Unexpected token/); }); it('should report if identifier is not followed by an opening parenthesis', () => { expect(() => parse('@defer (on viewport[]) {hello}')).toThrowError(/Unexpected token/); }); it('should report if parameters are passed to `idle` trigger', () => { expect(() => parse('@defer (on idle(1)) {hello}')).toThrowError( /"idle" trigger cannot have parameters/, ); }); it('should report if no parameters are passed into `timer` trigger', () => { expect(() => parse('@defer (on timer) {hello}')).toThrowError( /"timer" trigger must have exactly one parameter/, ); }); it('should report if `timer` trigger value cannot be parsed', () => { expect(() => parse('@defer (on timer(123abc)) {hello}')).toThrowError( /Could not parse time value of trigger "timer"/, ); }); it('should report if `interaction` trigger has more than one parameter', () => { expect(() => parse('@defer (on interaction(a, b)) {hello}')).toThrowError( /"interaction" trigger can only have zero or one parameters/, ); }); it('should report if parameters are passed to `immediate` trigger', () => { expect(() => parse('@defer (on immediate(1)) {hello}')).toThrowError( /"immediate" trigger cannot have parameters/, ); }); it('should report if `hover` trigger has more than one parameter', () => { expect(() => parse('@defer (on hover(a, b)) {hello}')).toThrowError( /"hover" trigger can only have zero or one parameters/, ); }); it('should report if `viewport` trigger has more than one parameter', () => { expect(() => parse('@defer (on viewport(a, b)) {hello}')).toThrowError( /"viewport" trigger can only have zero or one parameters/, ); }); it('should report duplicate when triggers', () => { expect(() => parse('@defer (when isVisible(); when somethingElse()) {hello}')).toThrowError( /Duplicate "when" trigger is not allowed/, ); }); it('should report duplicate on triggers', () => { expect(() => parse('@defer (on idle; when isVisible(); on timer(10), idle) {hello}'), ).toThrowError(/Duplicate "idle" trigger is not allowed/); }); it('should report duplicate prefetch when triggers', () => { expect(() => parse('@defer (prefetch when isVisible(); prefetch when somethingElse()) {hello}'), ).toThrowError(/Duplicate "when" trigger is not allowed/); }); it('should report duplicate prefetch on triggers', () => { expect(() => parse( '@defer (prefetch on idle; prefetch when isVisible(); prefetch on timer(10), idle) {hello}', ), ).toThrowError(/Duplicate "idle" trigger is not allowed/); }); it('should report multiple minimum parameters on a placeholder block', () => { expect(() => parse('@defer {hello} @placeholder (minimum 1s; minimum 500ms) {placeholder}'), ).toThrowError(/@placeholder block can only have one "minimum" parameter/); }); it('should report multiple minimum parameters on a loading block', () => { expect(() => parse('@defer {hello} @loading (minimum 1s; minimum 500ms) {loading}'), ).toThrowError(/@loading block can only have one "minimum" parameter/); });
{ "end_byte": 48510, "start_byte": 40006, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_48518_53527
it('should report multiple after parameters on a loading block', () => { expect(() => parse('@defer {hello} @loading (after 1s; after 500ms) {loading}'), ).toThrowError(/@loading block can only have one "after" parameter/); }); it('should report if reference-based trigger has no reference and there is no placeholder block', () => { expect(() => parse('@defer (on viewport) {hello}')).toThrowError( /"viewport" trigger with no parameters can only be placed on an @defer that has a @placeholder block/, ); }); it('should report if reference-based trigger has no reference and the placeholder is empty', () => { expect(() => parse('@defer (on viewport) {hello} @placeholder {}')).toThrowError( /"viewport" trigger with no parameters can only be placed on an @defer that has a @placeholder block with exactly one root element node/, ); }); it('should report if reference-based trigger has no reference and the placeholder with text at the root', () => { expect(() => parse('@defer (on viewport) {hello} @placeholder {placeholder}')).toThrowError( /"viewport" trigger with no parameters can only be placed on an @defer that has a @placeholder block with exactly one root element node/, ); }); it('should report if reference-based trigger has no reference and the placeholder has multiple root elements', () => { expect(() => parse('@defer (on viewport) {hello} @placeholder {<div></div><span></span>}'), ).toThrowError( /"viewport" trigger with no parameters can only be placed on an @defer that has a @placeholder block with exactly one root element node/, ); }); it('should report parameter passed to hydrate trigger with reference-based equivalent', () => { expect(() => parse('@defer (on interaction(button); hydrate on interaction(button)) {hello}'), ).toThrowError(/Hydration trigger "interaction" cannot have parameters/); }); it('should not report missing reference on hydrate trigger', () => { expect(() => parse('@defer (on immediate; hydrate on viewport) {hello}')).not.toThrow(); }); it('should report if reference-based trigger has no reference and there is no placeholder block but a hydrate trigger exists', () => { expect(() => parse('@defer (on viewport; hydrate on immediate) {hello}')).toThrowError( /"viewport" trigger with no parameters can only be placed on an @defer that has a @placeholder block/, ); }); it('should report if reference-based trigger has no reference and there is no placeholder block but a hydrate trigger exists and it is also viewport', () => { expect(() => parse('@defer (on viewport; hydrate on viewport) {hello}')).toThrowError( /"viewport" trigger with no parameters can only be placed on an @defer that has a @placeholder block/, ); }); it('should report never trigger used without `hydrate`', () => { expect(() => parse('@defer (on immediate; never) {hello}')).toThrowError( /Unrecognized trigger/, ); expect(() => parse('@defer (on immediate; prefetch never) {hello}')).toThrowError( /Unrecognized trigger/, ); }); it('should report `hydrate never` used with additonal characters', () => { expect(() => parse('@defer (hydrate never, and thank you) {hello}')).toThrowError( /Unrecognized trigger/, ); }); it('should not report an error when `hydrate never` is used with additonal blocks', () => { expect(() => parse('@defer (hydrate never; on idle;) {hello}')).not.toThrowError( /Unrecognized trigger/, ); }); it('should not report an error when `hydrate never` is used with spaces', () => { expect(() => parse('@defer(hydrate never ; on idle ;) {hello}')).not.toThrowError( /Unrecognized trigger/, ); }); it('should not report an error when `hydrate never` is used after another block', () => { expect(() => parse(`@defer( on idle; hydrate never) {hello}`), ).not.toThrowError(/Unrecognized trigger/); }); it('should report when `hydrate never` is used together with another `hydrate` trigger', () => { // Extra trigger after `hydrate never`. expect(() => parse('@defer (hydrate never; hydrate when shouldHydrate()) {hello}'), ).toThrowError( /Cannot specify additional `hydrate` triggers if `hydrate never` is present/, ); // Extra trigger before `hydrate never`. expect(() => parse('@defer (hydrate when shouldHydrate(); hydrate never) {hello}'), ).toThrowError( /Cannot specify additional `hydrate` triggers if `hydrate never` is present/, ); }); }); });
{ "end_byte": 53527, "start_byte": 48518, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_53531_61736
describe('switch blocks', () => { it('should parse a switch block', () => { expectFromHtml(` @switch (cond.kind) { @case (x()) { X case } @case ('hello') {<button>Y case</button>} @case (42) { Z case } @default { No case matched } } `).toEqual([ ['SwitchBlock', 'cond.kind'], ['SwitchBlockCase', 'x()'], ['Text', ' X case '], ['SwitchBlockCase', '"hello"'], ['Element', 'button'], ['Text', 'Y case'], ['SwitchBlockCase', '42'], ['Text', ' Z case '], ['SwitchBlockCase', null], ['Text', ' No case matched '], ]); }); // This is a special case for `switch` blocks, because `preserveWhitespaces` will cause // some text nodes with whitespace to be preserve in the primary block. it('should parse a switch block when preserveWhitespaces is enabled', () => { const template = ` @switch (cond.kind) { @case (x()) { X case } @case ('hello') { <button>Y case</button> } @case (42) { Z case } @default { No case matched } } `; expectFromR3Nodes(parse(template, {preserveWhitespaces: true}).nodes).toEqual([ ['Text', '\n '], ['SwitchBlock', 'cond.kind'], ['SwitchBlockCase', 'x()'], ['Text', '\n X case\n '], ['SwitchBlockCase', '"hello"'], ['Text', '\n '], ['Element', 'button'], ['Text', 'Y case'], ['Text', '\n '], ['SwitchBlockCase', '42'], ['Text', '\n Z case\n '], ['SwitchBlockCase', null], ['Text', '\n No case matched\n '], ['Text', '\n '], ]); }); it('should parse a switch block with optional parentheses', () => { expectFromHtml(` @switch ((cond.kind)) { @case ((x())) { X case } @case (('hello')) {<button>Y case</button>} @case ((42)) { Z case } @default { No case matched } } `).toEqual([ ['SwitchBlock', 'cond.kind'], ['SwitchBlockCase', 'x()'], ['Text', ' X case '], ['SwitchBlockCase', '"hello"'], ['Element', 'button'], ['Text', 'Y case'], ['SwitchBlockCase', '42'], ['Text', ' Z case '], ['SwitchBlockCase', null], ['Text', ' No case matched '], ]); }); it('should parse a nested switch block', () => { expectFromHtml(` @switch (cond) { @case ('a') { @switch (innerCond) { @case ('innerA') { Inner A } @case ('innerB') { Inner B } } } @case ('b') {<button>Y case</button>} @case ('c') { Z case } @default { @switch (innerCond) { @case ('innerC') { Inner C } @case ('innerD') { Inner D } @default { @switch (innerInnerCond) { @case ('innerInnerA') { Inner inner A } @case ('innerInnerA') { Inner inner B } } } } } } `).toEqual([ ['SwitchBlock', 'cond'], ['SwitchBlockCase', '"a"'], ['SwitchBlock', 'innerCond'], ['SwitchBlockCase', '"innerA"'], ['Text', ' Inner A '], ['SwitchBlockCase', '"innerB"'], ['Text', ' Inner B '], ['SwitchBlockCase', '"b"'], ['Element', 'button'], ['Text', 'Y case'], ['SwitchBlockCase', '"c"'], ['Text', ' Z case '], ['SwitchBlockCase', null], ['SwitchBlock', 'innerCond'], ['SwitchBlockCase', '"innerC"'], ['Text', ' Inner C '], ['SwitchBlockCase', '"innerD"'], ['Text', ' Inner D '], ['SwitchBlockCase', null], ['SwitchBlock', 'innerInnerCond'], ['SwitchBlockCase', '"innerInnerA"'], ['Text', ' Inner inner A '], ['SwitchBlockCase', '"innerInnerA"'], ['Text', ' Inner inner B '], ]); }); it('should parse a switch block containing comments', () => { expectFromHtml(` @switch (cond.kind) { <!-- X case --> @case (x) { X case } <!-- default case --> @default { No case matched } } `).toEqual([ ['SwitchBlock', 'cond.kind'], ['SwitchBlockCase', 'x'], ['Text', ' X case '], ['SwitchBlockCase', null], ['Text', ' No case matched '], ]); }); describe('validations', () => { it('should report syntax error in switch expression', () => { expect(() => parse(` @switch (cond/.kind) { @case (x()) {X case} @default {No case matched} } `), ).toThrowError(/Parser Error: Unexpected token \./); }); it('should report syntax error in case expression', () => { expect(() => parse(` @switch (cond) { @case (x/.y) {X case} } `), ).toThrowError(/Parser Error: Unexpected token \./); }); it('should report if a block different from "case" and "default" is used in a switch', () => { const result = parse( ` @switch (cond) { @case (x()) {X case} @foo {Foo} } `, {ignoreError: true}, ); const switchNode = result.nodes[0] as t.SwitchBlock; expect(result.errors.map((e) => e.msg)).toEqual([ '@switch block can only contain @case and @default blocks', ]); expect(switchNode.unknownBlocks.map((b) => b.name)).toEqual(['foo']); }); it('should report if @case or @default is used outside of a switch block', () => { expect(() => parse(`@case (foo) {}`)).toThrowError(/Unrecognized block @case/); expect(() => parse(`@default {}`)).toThrowError(/Unrecognized block @default/); }); it('should report if a switch has no parameters', () => { expect(() => parse(` @switch { @case (1) {case} } `), ).toThrowError(/@switch block must have exactly one parameter/); }); it('should report if a switch has more than one parameter', () => { expect(() => parse(` @switch (foo; bar) { @case (1) {case} } `), ).toThrowError(/@switch block must have exactly one parameter/); }); it('should report if a case has no parameters', () => { expect(() => parse(` @switch (cond) { @case {case} } `), ).toThrowError(/@case block must have exactly one parameter/); expect(() => parse(` @switch (cond) { @case ( ) {case} } `), ).toThrowError(/@case block must have exactly one parameter/); }); it('should report if a case has more than one parameter', () => { expect(() => parse(` @switch (cond) { @case (foo; bar) {case} } `), ).toThrowError(/@case block must have exactly one parameter/); }); it('should report if a switch has multiple default blocks', () => { expect(() => parse(` @switch (cond) { @case (foo) {foo} @default {one} @default {two} } `), ).toThrowError(/@switch block can only have one @default block/); }); it('should report if a default block has parameters', () => { expect(() => parse(` @switch (cond) { @case (foo) {foo} @default (bar) {bar} } `), ).toThrowError(/@default block cannot have parameters/); }); }); });
{ "end_byte": 61736, "start_byte": 53531, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_61740_69329
describe('for loop blocks', () => { it('should parse a for loop block', () => { expectFromHtml(` @for (item of items.foo.bar; track item.id) { {{ item }} } @empty { There were no items in the list. } `).toEqual([ ['ForLoopBlock', 'items.foo.bar', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', ' {{ item }} '], ['ForLoopBlockEmpty'], ['Text', ' There were no items in the list. '], ]); }); it('should parse a for loop block with optional parentheses', () => { expectFromHtml(` @for ((item of items.foo.bar); track item.id){ {{ item }} } `).toEqual([ ['ForLoopBlock', 'items.foo.bar', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', ' {{ item }} '], ]); expectFromHtml(` @for ((item of items.foo.bar()); track item.id) { {{ item }} } `).toEqual([ ['ForLoopBlock', 'items.foo.bar()', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', ' {{ item }} '], ]); expectFromHtml(` @for (( ( (item of items.foo.bar()) ) ); track item.id) { {{ item }} } `).toEqual([ ['ForLoopBlock', 'items.foo.bar()', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', ' {{ item }} '], ]); }); it('should parse a for loop block with let parameters', () => { expectFromHtml(` @for (item of items.foo.bar; track item.id; let idx = $index, f = $first, c = $count; let l = $last, ev = $even, od = $odd) { {{ item }} } `).toEqual([ ['ForLoopBlock', 'items.foo.bar', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['Variable', 'idx', '$index'], ['Variable', 'f', '$first'], ['Variable', 'c', '$count'], ['Variable', 'l', '$last'], ['Variable', 'ev', '$even'], ['Variable', 'od', '$odd'], ['BoundText', ' {{ item }} '], ]); }); it('should parse a for loop block with newlines in its let parameters', () => { expectFromHtml(` @for (item of items.foo.bar; track item.id; let\nidx = $index,\nf = $first,\nc = $count,\nl = $last,\nev = $even,\nod = $odd) { {{ item }} } `).toEqual([ ['ForLoopBlock', 'items.foo.bar', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['Variable', 'idx', '$index'], ['Variable', 'f', '$first'], ['Variable', 'c', '$count'], ['Variable', 'l', '$last'], ['Variable', 'ev', '$even'], ['Variable', 'od', '$odd'], ['BoundText', ' {{ item }} '], ]); }); it('should parse nested for loop blocks', () => { expectFromHtml(` @for (item of items.foo.bar; track item.id) { {{ item }} <div> @for (subitem of item.items; track subitem.id) {<h1>{{subitem}}</h1>} </div> } @empty { There were no items in the list. } `).toEqual([ ['ForLoopBlock', 'items.foo.bar', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', ' {{ item }} '], ['Element', 'div'], ['ForLoopBlock', 'item.items', 'subitem.id'], ['Variable', 'subitem', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['Element', 'h1'], ['BoundText', '{{ subitem }}'], ['ForLoopBlockEmpty'], ['Text', ' There were no items in the list. '], ]); }); it('should parse a for loop block with a function call in the `track` expression', () => { expectFromHtml(` @for (item of items.foo.bar; track trackBy(item.id, 123)) { {{ item }} } `).toEqual([ ['ForLoopBlock', 'items.foo.bar', 'trackBy(item.id, 123)'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', ' {{ item }} '], ]); }); it('should parse a for loop block with newlines in its expression', () => { const expectedResult = [ ['ForLoopBlock', 'items.foo.bar', 'item.id + foo'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', '{{ item }}'], ]; expectFromHtml(` @for (item\nof\nitems.foo.bar; track item.id +\nfoo) {{{ item }}} `).toEqual(expectedResult); expectFromHtml(` @for ((item\nof\nitems.foo.bar); track (item.id +\nfoo)) {{{ item }}} `).toEqual(expectedResult); }); it('should parse for loop block expression containing new lines', () => { expectFromHtml(` @for (item of [ { id: 1 }, { id: 2 } ]; track item.id) { {{ item }} } `).toEqual([ ['ForLoopBlock', '[{id: 1}, {id: 2}]', 'item.id'], ['Variable', 'item', '$implicit'], ['Variable', '$index', '$index'], ['Variable', '$first', '$first'], ['Variable', '$last', '$last'], ['Variable', '$even', '$even'], ['Variable', '$odd', '$odd'], ['Variable', '$count', '$count'], ['BoundText', ' {{ item }} '], ]); });
{ "end_byte": 69329, "start_byte": 61740, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_69335_74948
describe('validations', () => { it('should report if for loop does not have an expression', () => { expect(() => parse(`@for {hello}`)).toThrowError(/@for loop does not have an expression/); }); it('should report if for loop does not have a tracking expression', () => { expect(() => parse(`@for (a of b) {hello}`)).toThrowError( /@for loop must have a "track" expression/, ); expect(() => parse(`@for (a of b; track ) {hello}`)).toThrowError( /@for loop must have a "track" expression/, ); }); it('should report mismatching optional parentheses around for loop expression', () => { expect(() => parse(`@for ((a of b; track c) {hello}`)).toThrowError( /Unclosed parentheses in expression/, ); expect(() => parse(`@for ((a of b(); track c) {hello}`)).toThrowError( /Unexpected end of expression: b\(/, ); expect(() => parse(`@for (a of b); track c) {hello}`)).toThrowError( /Unexpected character "EOF"/, ); }); it('should report unrecognized for loop parameters', () => { expect(() => parse(`@for (a of b; foo bar) {hello}`)).toThrowError( /Unrecognized @for loop paramater "foo bar"/, ); }); it('should report multiple `track` parameters', () => { expect(() => parse(`@for (a of b; track c; track d) {hello}`)).toThrowError( /@for loop can only have one "track" expression/, ); }); it('should report invalid for loop expression', () => { const errorPattern = /Cannot parse expression\. @for loop expression must match the pattern "<identifier> of <expression>"/; expect(() => parse(`@for (//invalid of items) {hello}`)).toThrowError(errorPattern); expect(() => parse(`@for (item) {hello}`)).toThrowError(errorPattern); expect(() => parse(`@for (item in items) {hello}`)).toThrowError(errorPattern); expect(() => parse(`@for (item of ) {hello}`)).toThrowError(errorPattern); }); it('should report syntax error in for loop expression', () => { expect(() => parse(`@for (item of items..foo) {hello}`)).toThrowError( /Unexpected token \./, ); }); it('should report for loop with multiple `empty` blocks', () => { expect(() => parse(` @for (a of b; track a) { Main } @empty { Empty one } @empty { Empty two } `), ).toThrowError(/@for loop can only have one @empty block/); }); it('should report empty block with parameters', () => { expect(() => parse(` @for (a of b; track a) { main } @empty (foo) { empty } `), ).toThrowError(/@empty block cannot have parameters/); }); it('should content between @for and @empty blocks', () => { expect(() => parse(` @for (a of b; track a) { main } <div></div> @empty { empty } `), ).toThrowError(/@empty block can only be used after an @for block/); }); it('should report an empty block used without a @for loop block', () => { expect(() => parse(`@empty {hello}`)).toThrowError( /@empty block can only be used after an @for block/, ); }); it('should report an empty `let` parameter', () => { expect(() => parse(`@for (item of items.foo.bar; track item.id; let ) {}`)).toThrowError( /Invalid @for loop "let" parameter. Parameter should match the pattern "<name> = <variable name>"/, ); }); it('should report an invalid `let` parameter', () => { expect(() => parse(`@for (item of items.foo.bar; track item.id; let i = $index, $odd) {}`), ).toThrowError( /Invalid @for loop "let" parameter\. Parameter should match the pattern "<name> = <variable name>"/, ); }); it('should an unknown variable in a `let` parameter', () => { expect(() => parse(`@for (item of items.foo.bar; track item.id; let foo = $foo) {}`), ).toThrowError(/Unknown "let" parameter variable "\$foo"\. The allowed variables are:/); }); it('should report duplicate `let` parameter variables', () => { expect(() => parse( `@for (item of items.foo.bar; track item.id; let i = $index, f = $first, i = $index) {}`, ), ).toThrowError(/Duplicate "let" parameter variable "\$index"/); expect(() => parse(`@for (item of items.foo.bar; track item.id; let $index = $index) {}`), ).toThrowError(/Duplicate "let" parameter variable "\$index"/); }); it('should report an item name that conflicts with the implicit context variables', () => { ['$index', '$count', '$first', '$last', '$even', '$odd'].forEach((varName) => { expect(() => parse(`@for (${varName} of items; track $index) {}`)).toThrowError( /@for loop item name cannot be one of \$index, \$first, \$last, \$even, \$odd, \$count/, ); }); }); it('should report a context variable alias that is the same as the variable name', () => { expect(() => parse(`@for (item of items; let item = $index; track $index) {}`), ).toThrowError(/Invalid @for loop "let" parameter. Variable cannot be called "item"/); }); }); });
{ "end_byte": 74948, "start_byte": 69335, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_74952_82442
describe('if blocks', () => { it('should parse an if block', () => { expectFromHtml(` @if (cond.expr; as foo) { Main case was true! } @else if (other.expr) { Extra case was true! } @else { False case! } `).toEqual([ ['IfBlock'], ['IfBlockBranch', 'cond.expr'], ['Variable', 'foo', 'foo'], ['Text', ' Main case was true! '], ['IfBlockBranch', 'other.expr'], ['Text', ' Extra case was true! '], ['IfBlockBranch', null], ['Text', ' False case! '], ]); }); it('should parse an if block with optional parentheses', () => { expectFromHtml(` @if ((cond.expr)) { Main case was true! } @else if ((other.expr)) { Extra case was true! } @else { False case! } `).toEqual([ ['IfBlock'], ['IfBlockBranch', 'cond.expr'], ['Text', ' Main case was true! '], ['IfBlockBranch', 'other.expr'], ['Text', ' Extra case was true! '], ['IfBlockBranch', null], ['Text', ' False case! '], ]); }); it('should parse nested if blocks', () => { expectFromHtml(` @if (a) { @if (a1) { a1 } @else { b1 } } @else if (b) { b } @else { @if (c1) { c1 } @else if (c2) { c2 } @else { c3 } } `).toEqual([ ['IfBlock'], ['IfBlockBranch', 'a'], ['IfBlock'], ['IfBlockBranch', 'a1'], ['Text', ' a1 '], ['IfBlockBranch', null], ['Text', ' b1 '], ['IfBlockBranch', 'b'], ['Text', ' b '], ['IfBlockBranch', null], ['IfBlock'], ['IfBlockBranch', 'c1'], ['Text', ' c1 '], ['IfBlockBranch', 'c2'], ['Text', ' c2 '], ['IfBlockBranch', null], ['Text', ' c3 '], ]); }); it('should parse an else if block with multiple spaces', () => { expectFromHtml(` @if (cond.expr; as foo) { Main case was true! } @else if (other.expr) { Other case was true! } `).toEqual([ ['IfBlock'], ['IfBlockBranch', 'cond.expr'], ['Variable', 'foo', 'foo'], ['Text', ' Main case was true! '], ['IfBlockBranch', 'other.expr'], ['Text', ' Other case was true! '], ]); }); it('should parse an else if block with a tab between `else` and `if`', () => { expectFromHtml(` @if (cond.expr; as foo) { Main case was true! } @else\tif (other.expr) { Other case was true! } `).toEqual([ ['IfBlock'], ['IfBlockBranch', 'cond.expr'], ['Variable', 'foo', 'foo'], ['Text', ' Main case was true! '], ['IfBlockBranch', 'other.expr'], ['Text', ' Other case was true! '], ]); }); it('should parse an if block containing comments between the branches', () => { expectFromHtml(` @if (cond.expr; as foo) { Main case was true! } <!-- Extra case --> @else if (other.expr) { Extra case was true! } <!-- False case --> @else { False case! } `).toEqual([ ['IfBlock'], ['IfBlockBranch', 'cond.expr'], ['Variable', 'foo', 'foo'], ['Text', ' Main case was true! '], ['IfBlockBranch', 'other.expr'], ['Text', ' Extra case was true! '], ['IfBlockBranch', null], ['Text', ' False case! '], ]); }); describe('validations', () => { it('should report an if block without a condition', () => { expect(() => parse(` @if {hello} `), ).toThrowError(/Conditional block does not have an expression/); expect(() => parse(` @if ( ) {hello} `), ).toThrowError(/Conditional block does not have an expression/); }); it('should report an unknown parameter in an if block', () => { expect(() => parse(` @if (foo; bar) {hello} `), ).toThrowError(/Unrecognized conditional paramater "bar"/); }); it('should report an unknown parameter in an else if block', () => { expect(() => parse(` @if (foo) {hello} @else if (bar; baz) {goodbye} `), ).toThrowError(/Unrecognized conditional paramater "baz"/); }); it('should report an if block that has multiple `as` expressions', () => { expect(() => parse(` @if (foo; as foo; as bar) {hello} `), ).toThrowError(/Conditional can only have one "as" expression/); }); it('should report an else if block with a newline in the name', () => { expect(() => parse(` @if (foo) {hello} @else\nif (bar) {goodbye} `), ).toThrowError(/Unrecognized block @else\nif/); }); it('should report an else if block that has an `as` expression', () => { expect(() => parse(` @if (foo) {hello} @else if (bar; as alias) {goodbye} `), ).toThrowError(/"as" expression is only allowed on the primary @if block/); }); it('should report an @else if block used without an @if block', () => { expect(() => parse(`@else if (foo) {hello}`)).toThrowError( /@else if block can only be used after an @if or @else if block/, ); }); it('should report an @else block used without an @if block', () => { expect(() => parse(`@else (foo) {hello}`)).toThrowError( /@else block can only be used after an @if or @else if block/, ); }); it('should report content between an @if and @else if block', () => { expect(() => parse(`@if (foo) {hello} <div></div> @else if (bar) {goodbye}`)).toThrowError( /@else if block can only be used after an @if or @else if block/, ); }); it('should report content between an @if and @else block', () => { expect(() => parse(`@if (foo) {hello} <div></div> @else {goodbye}`)).toThrowError( /@else block can only be used after an @if or @else if block/, ); }); it('should report an else block with parameters', () => { expect(() => parse(` @if (foo) {hello} @else (bar) {goodbye} `), ).toThrowError(/@else block cannot have parameters/); }); it('should report a conditional with multiple else blocks', () => { expect(() => parse(` @if (foo) {hello} @else {goodbye} @else {goodbye again} `), ).toThrowError(/Conditional can only have one @else block/); }); it('should report an else if block after an else block', () => { expect(() => parse(` @if (foo) {hello} @else {goodbye} @else (if bar) {goodbye again} `), ).toThrowError(/@else block must be last inside the conditional/); }); }); }); describe('unknown blocks', () => { it('should parse unknown blocks', () => { expectFromHtml('@unknown {}', true /* ignoreError */).toEqual([['UnknownBlock', 'unknown']]); }); });
{ "end_byte": 82442, "start_byte": 74952, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/r3_template_transform_spec.ts_82446_83351
describe('@let declarations', () => { it('should parse a let declaration', () => { expectFromHtml('@let foo = 123 + 456;').toEqual([['LetDeclaration', 'foo', '123 + 456']]); }); it('should report syntax errors in the let declaration value', () => { expect(() => parse('@let foo = {one: 1;')).toThrowError( /Parser Error: Missing expected } at the end of the expression \[\{one: 1]/, ); }); it('should report a let declaration with no value', () => { expect(() => parse('@let foo = ;')).toThrowError(/@let declaration value cannot be empty/); }); it('should produce a text node when @let is used inside ngNonBindable', () => { expectFromHtml('<div ngNonBindable>@let foo = 123;</div>').toEqual([ ['Element', 'div'], ['TextAttribute', 'ngNonBindable', ''], ['Text', '@let foo = 123;'], ]); }); }); });
{ "end_byte": 83351, "start_byte": 82446, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_template_transform_spec.ts" }
angular/packages/compiler/test/render3/style_parser_spec.ts_0_3211
/** * @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 { hyphenate, parse as parseStyle, } from '../../src/template/pipeline/src/phases/parse_extracted_styles'; describe('style parsing', () => { it('should parse empty or blank strings', () => { const result1 = parseStyle(''); expect(result1).toEqual([]); const result2 = parseStyle(' '); expect(result2).toEqual([]); }); it('should parse a string into a key/value map', () => { const result = parseStyle('width:100px;height:200px;opacity:0'); expect(result).toEqual(['width', '100px', 'height', '200px', 'opacity', '0']); }); it('should allow empty values', () => { const result = parseStyle('width:;height: ;'); expect(result).toEqual(['width', '', 'height', '']); }); it('should trim values and properties', () => { const result = parseStyle('width :333px ; height:666px ; opacity: 0.5;'); expect(result).toEqual(['width', '333px', 'height', '666px', 'opacity', '0.5']); }); it('should not mess up with quoted strings that contain [:;] values', () => { const result = parseStyle('content: "foo; man: guy"; width: 100px'); expect(result).toEqual(['content', '"foo; man: guy"', 'width', '100px']); }); it('should not mess up with quoted strings that contain inner quote values', () => { const quoteStr = '"one \'two\' three "four" five"'; const result = parseStyle(`content: ${quoteStr}; width: 123px`); expect(result).toEqual(['content', quoteStr, 'width', '123px']); }); it('should respect parenthesis that are placed within a style', () => { const result = parseStyle('background-image: url("foo.jpg")'); expect(result).toEqual(['background-image', 'url("foo.jpg")']); }); it('should respect multi-level parenthesis that contain special [:;] characters', () => { const result = parseStyle('color: rgba(calc(50 * 4), var(--cool), :5;); height: 100px;'); expect(result).toEqual(['color', 'rgba(calc(50 * 4), var(--cool), :5;)', 'height', '100px']); }); it('should hyphenate style properties from camel case', () => { const result = parseStyle('borderWidth: 200px'); expect(result).toEqual(['border-width', '200px']); }); describe('should not remove quotes', () => { it('from string data types', () => { const result = parseStyle('content: "foo"'); expect(result).toEqual(['content', '"foo"']); }); it('that changes the value context from invalid to valid', () => { const result = parseStyle('width: "1px"'); expect(result).toEqual(['width', '"1px"']); }); }); describe('camelCasing => hyphenation', () => { it('should convert a camel-cased value to a hyphenated value', () => { expect(hyphenate('fooBar')).toEqual('foo-bar'); expect(hyphenate('fooBarMan')).toEqual('foo-bar-man'); expect(hyphenate('-fooBar-man')).toEqual('-foo-bar-man'); }); it('should make everything lowercase', () => { expect(hyphenate('-WebkitAnimation')).toEqual('-webkit-animation'); }); }); });
{ "end_byte": 3211, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/style_parser_spec.ts" }
angular/packages/compiler/test/render3/r3_ast_spans_spec.ts_0_7816
/** * @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 '../../src/parse_util'; import * as t from '../../src/render3/r3_ast'; import {parseR3 as parse} from './view/util'; class R3AstSourceSpans implements t.Visitor<void> { result: any[] = []; visitElement(element: t.Element) { this.result.push([ 'Element', humanizeSpan(element.sourceSpan), humanizeSpan(element.startSourceSpan), humanizeSpan(element.endSourceSpan), ]); this.visitAll([ element.attributes, element.inputs, element.outputs, element.references, element.children, ]); } visitTemplate(template: t.Template) { this.result.push([ 'Template', humanizeSpan(template.sourceSpan), humanizeSpan(template.startSourceSpan), humanizeSpan(template.endSourceSpan), ]); this.visitAll([ template.attributes, template.inputs, template.outputs, template.templateAttrs, template.references, template.variables, template.children, ]); } visitContent(content: t.Content) { this.result.push(['Content', humanizeSpan(content.sourceSpan)]); this.visitAll([content.attributes, content.children]); } visitVariable(variable: t.Variable) { this.result.push([ 'Variable', humanizeSpan(variable.sourceSpan), humanizeSpan(variable.keySpan), humanizeSpan(variable.valueSpan), ]); } visitReference(reference: t.Reference) { this.result.push([ 'Reference', humanizeSpan(reference.sourceSpan), humanizeSpan(reference.keySpan), humanizeSpan(reference.valueSpan), ]); } visitTextAttribute(attribute: t.TextAttribute) { this.result.push([ 'TextAttribute', humanizeSpan(attribute.sourceSpan), humanizeSpan(attribute.keySpan), humanizeSpan(attribute.valueSpan), ]); } visitBoundAttribute(attribute: t.BoundAttribute) { this.result.push([ 'BoundAttribute', humanizeSpan(attribute.sourceSpan), humanizeSpan(attribute.keySpan), humanizeSpan(attribute.valueSpan), ]); } visitBoundEvent(event: t.BoundEvent) { this.result.push([ 'BoundEvent', humanizeSpan(event.sourceSpan), humanizeSpan(event.keySpan), humanizeSpan(event.handlerSpan), ]); } visitText(text: t.Text) { this.result.push(['Text', humanizeSpan(text.sourceSpan)]); } visitBoundText(text: t.BoundText) { this.result.push(['BoundText', humanizeSpan(text.sourceSpan)]); } visitIcu(icu: t.Icu) { this.result.push(['Icu', humanizeSpan(icu.sourceSpan)]); for (const key of Object.keys(icu.vars)) { this.result.push(['Icu:Var', humanizeSpan(icu.vars[key].sourceSpan)]); } for (const key of Object.keys(icu.placeholders)) { this.result.push(['Icu:Placeholder', humanizeSpan(icu.placeholders[key].sourceSpan)]); } } visitDeferredBlock(deferred: t.DeferredBlock): void { this.result.push([ 'DeferredBlock', humanizeSpan(deferred.sourceSpan), humanizeSpan(deferred.startSourceSpan), humanizeSpan(deferred.endSourceSpan), ]); deferred.visitAll(this); } visitSwitchBlock(block: t.SwitchBlock): void { this.result.push([ 'SwitchBlock', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), humanizeSpan(block.endSourceSpan), ]); this.visitAll([block.cases]); } visitSwitchBlockCase(block: t.SwitchBlockCase): void { this.result.push([ 'SwitchBlockCase', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), ]); this.visitAll([block.children]); } visitForLoopBlock(block: t.ForLoopBlock): void { this.result.push([ 'ForLoopBlock', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), humanizeSpan(block.endSourceSpan), ]); this.visitVariable(block.item); this.visitAll([block.contextVariables]); this.visitAll([block.children]); block.empty?.visit(this); } visitForLoopBlockEmpty(block: t.ForLoopBlockEmpty): void { this.result.push([ 'ForLoopBlockEmpty', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), ]); this.visitAll([block.children]); } visitIfBlock(block: t.IfBlock): void { this.result.push([ 'IfBlock', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), humanizeSpan(block.endSourceSpan), ]); this.visitAll([block.branches]); } visitIfBlockBranch(block: t.IfBlockBranch): void { this.result.push([ 'IfBlockBranch', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), ]); if (block.expressionAlias) { this.visitVariable(block.expressionAlias); } this.visitAll([block.children]); } visitDeferredTrigger(trigger: t.DeferredTrigger): void { let name: string; if (trigger instanceof t.BoundDeferredTrigger) { name = 'BoundDeferredTrigger'; } else if (trigger instanceof t.ImmediateDeferredTrigger) { name = 'ImmediateDeferredTrigger'; } else if (trigger instanceof t.HoverDeferredTrigger) { name = 'HoverDeferredTrigger'; } else if (trigger instanceof t.IdleDeferredTrigger) { name = 'IdleDeferredTrigger'; } else if (trigger instanceof t.TimerDeferredTrigger) { name = 'TimerDeferredTrigger'; } else if (trigger instanceof t.InteractionDeferredTrigger) { name = 'InteractionDeferredTrigger'; } else if (trigger instanceof t.ViewportDeferredTrigger) { name = 'ViewportDeferredTrigger'; } else if (trigger instanceof t.NeverDeferredTrigger) { name = 'NeverDeferredTrigger'; } else { throw new Error('Unknown trigger'); } this.result.push([name, humanizeSpan(trigger.sourceSpan)]); } visitDeferredBlockPlaceholder(block: t.DeferredBlockPlaceholder): void { this.result.push([ 'DeferredBlockPlaceholder', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), humanizeSpan(block.endSourceSpan), ]); this.visitAll([block.children]); } visitDeferredBlockError(block: t.DeferredBlockError): void { this.result.push([ 'DeferredBlockError', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), humanizeSpan(block.endSourceSpan), ]); this.visitAll([block.children]); } visitDeferredBlockLoading(block: t.DeferredBlockLoading): void { this.result.push([ 'DeferredBlockLoading', humanizeSpan(block.sourceSpan), humanizeSpan(block.startSourceSpan), humanizeSpan(block.endSourceSpan), ]); this.visitAll([block.children]); } visitUnknownBlock(block: t.UnknownBlock): void { this.result.push(['UnknownBlock', humanizeSpan(block.sourceSpan)]); } visitLetDeclaration(decl: t.LetDeclaration): void { this.result.push([ 'LetDeclaration', humanizeSpan(decl.sourceSpan), humanizeSpan(decl.nameSpan), humanizeSpan(decl.valueSpan), ]); } private visitAll(nodes: t.Node[][]) { nodes.forEach((node) => t.visitAll(this, node)); } } function humanizeSpan(span: ParseSourceSpan | null | undefined): string { if (span === null || span === undefined) { return `<empty>`; } return span.toString(); } function expectFromHtml(html: string) { return expectFromR3Nodes(parse(html).nodes); } function expectFromR3Nodes(nodes: t.Node[]) { const humanizer = new R3AstSourceSpans(); t.visitAll(humanizer, nodes); return expect(humanizer.result); }
{ "end_byte": 7816, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_spans_spec.ts" }
angular/packages/compiler/test/render3/r3_ast_spans_spec.ts_7818_14739
describe('R3 AST source spans', () => { describe('nodes without binding', () => { it('is correct for text nodes', () => { expectFromHtml('a').toEqual([['Text', 'a']]); }); it('is correct for elements with attributes', () => { expectFromHtml('<div a="b"></div>').toEqual([ ['Element', '<div a="b"></div>', '<div a="b">', '</div>'], ['TextAttribute', 'a="b"', 'a', 'b'], ]); }); it('is correct for elements with attributes without value', () => { expectFromHtml('<div a></div>').toEqual([ ['Element', '<div a></div>', '<div a>', '</div>'], ['TextAttribute', 'a', 'a', '<empty>'], ]); }); it('is correct for self-closing elements with trailing whitespace', () => { expectFromHtml('<input />\n <span>\n</span>').toEqual([ ['Element', '<input />', '<input />', '<input />'], ['Element', '<span>\n</span>', '<span>', '</span>'], ]); }); }); describe('bound text nodes', () => { it('is correct for bound text nodes', () => { expectFromHtml('{{a}}').toEqual([['BoundText', '{{a}}']]); }); }); describe('bound attributes', () => { it('is correct for bound properties', () => { expectFromHtml('<div [someProp]="v"></div>').toEqual([ ['Element', '<div [someProp]="v"></div>', '<div [someProp]="v">', '</div>'], ['BoundAttribute', '[someProp]="v"', 'someProp', 'v'], ]); }); it('is correct for bound properties without value', () => { expectFromHtml('<div [someProp]></div>').toEqual([ ['Element', '<div [someProp]></div>', '<div [someProp]>', '</div>'], ['BoundAttribute', '[someProp]', 'someProp', '<empty>'], ]); }); it('is correct for bound properties via bind- ', () => { expectFromHtml('<div bind-prop="v"></div>').toEqual([ ['Element', '<div bind-prop="v"></div>', '<div bind-prop="v">', '</div>'], ['BoundAttribute', 'bind-prop="v"', 'prop', 'v'], ]); }); it('is correct for bound properties via {{...}}', () => { expectFromHtml('<div prop="{{v}}"></div>').toEqual([ ['Element', '<div prop="{{v}}"></div>', '<div prop="{{v}}">', '</div>'], ['BoundAttribute', 'prop="{{v}}"', 'prop', '{{v}}'], ]); }); it('is correct for bound properties via data-', () => { expectFromHtml('<div data-prop="{{v}}"></div>').toEqual([ ['Element', '<div data-prop="{{v}}"></div>', '<div data-prop="{{v}}">', '</div>'], ['BoundAttribute', 'data-prop="{{v}}"', 'prop', '{{v}}'], ]); }); it('is correct for bound properties via @', () => { expectFromHtml('<div bind-@animation="v"></div>').toEqual([ ['Element', '<div bind-@animation="v"></div>', '<div bind-@animation="v">', '</div>'], ['BoundAttribute', 'bind-@animation="v"', 'animation', 'v'], ]); }); it('is correct for bound properties via animation-', () => { expectFromHtml('<div bind-animate-animationName="v"></div>').toEqual([ [ 'Element', '<div bind-animate-animationName="v"></div>', '<div bind-animate-animationName="v">', '</div>', ], ['BoundAttribute', 'bind-animate-animationName="v"', 'animationName', 'v'], ]); }); it('is correct for bound properties via @ without value', () => { expectFromHtml('<div @animation></div>').toEqual([ ['Element', '<div @animation></div>', '<div @animation>', '</div>'], ['BoundAttribute', '@animation', 'animation', '<empty>'], ]); }); }); describe('templates', () => { it('is correct for * directives', () => { expectFromHtml('<div *ngIf></div>').toEqual([ ['Template', '<div *ngIf></div>', '<div *ngIf>', '</div>'], ['TextAttribute', 'ngIf', 'ngIf', '<empty>'], ['Element', '<div *ngIf></div>', '<div *ngIf>', '</div>'], ]); }); it('is correct for <ng-template>', () => { expectFromHtml('<ng-template></ng-template>').toEqual([ ['Template', '<ng-template></ng-template>', '<ng-template>', '</ng-template>'], ]); }); it('is correct for reference via #...', () => { expectFromHtml('<ng-template #a></ng-template>').toEqual([ ['Template', '<ng-template #a></ng-template>', '<ng-template #a>', '</ng-template>'], ['Reference', '#a', 'a', '<empty>'], ]); }); it('is correct for reference with name', () => { expectFromHtml('<ng-template #a="b"></ng-template>').toEqual([ [ 'Template', '<ng-template #a="b"></ng-template>', '<ng-template #a="b">', '</ng-template>', ], ['Reference', '#a="b"', 'a', 'b'], ]); }); it('is correct for reference via ref-...', () => { expectFromHtml('<ng-template ref-a></ng-template>').toEqual([ ['Template', '<ng-template ref-a></ng-template>', '<ng-template ref-a>', '</ng-template>'], ['Reference', 'ref-a', 'a', '<empty>'], ]); }); it('is correct for reference via data-ref-...', () => { expectFromHtml('<ng-template data-ref-a></ng-template>').toEqual([ [ 'Template', '<ng-template data-ref-a></ng-template>', '<ng-template data-ref-a>', '</ng-template>', ], ['Reference', 'data-ref-a', 'a', '<empty>'], ]); }); it('is correct for variables via let-...', () => { expectFromHtml('<ng-template let-a="b"></ng-template>').toEqual([ [ 'Template', '<ng-template let-a="b"></ng-template>', '<ng-template let-a="b">', '</ng-template>', ], ['Variable', 'let-a="b"', 'a', 'b'], ]); }); it('is correct for variables via data-let-...', () => { expectFromHtml('<ng-template data-let-a="b"></ng-template>').toEqual([ [ 'Template', '<ng-template data-let-a="b"></ng-template>', '<ng-template data-let-a="b">', '</ng-template>', ], ['Variable', 'data-let-a="b"', 'a', 'b'], ]); }); it('is correct for attributes', () => { expectFromHtml('<ng-template k1="v1"></ng-template>').toEqual([ [ 'Template', '<ng-template k1="v1"></ng-template>', '<ng-template k1="v1">', '</ng-template>', ], ['TextAttribute', 'k1="v1"', 'k1', 'v1'], ]); }); it('is correct for bound attributes', () => { expectFromHtml('<ng-template [k1]="v1"></ng-template>').toEqual([ [ 'Template', '<ng-template [k1]="v1"></ng-template>', '<ng-template [k1]="v1">', '</ng-template>', ], ['BoundAttribute', '[k1]="v1"', 'k1', 'v1'], ]); }); }); // TODO(joost): improve spans of nodes extracted from macrosyntax
{ "end_byte": 14739, "start_byte": 7818, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_spans_spec.ts" }
angular/packages/compiler/test/render3/r3_ast_spans_spec.ts_14742_21173
describe('inline templates', () => { it('is correct for attribute and bound attributes', () => { // Desugared form is // <ng-template ngFor [ngForOf]="items" let-item> // <div></div> // </ng-template> expectFromHtml('<div *ngFor="let item of items"></div>').toEqual([ [ 'Template', '<div *ngFor="let item of items"></div>', '<div *ngFor="let item of items">', '</div>', ], ['TextAttribute', 'ngFor', 'ngFor', '<empty>'], ['BoundAttribute', 'of items', 'of', 'items'], ['Variable', 'let item ', 'item', '<empty>'], [ 'Element', '<div *ngFor="let item of items"></div>', '<div *ngFor="let item of items">', '</div>', ], ]); // Note that this test exercises an *incorrect* usage of the ngFor // directive. There is a missing 'let' in the beginning of the expression // which causes the template to be desugared into // <ng-template [ngFor]="item" [ngForOf]="items"> // <div></div> // </ng-template> expectFromHtml('<div *ngFor="item of items"></div>').toEqual([ [ 'Template', '<div *ngFor="item of items"></div>', '<div *ngFor="item of items">', '</div>', ], ['BoundAttribute', 'ngFor="item ', 'ngFor', 'item'], ['BoundAttribute', 'of items', 'of', 'items'], ['Element', '<div *ngFor="item of items"></div>', '<div *ngFor="item of items">', '</div>'], ]); expectFromHtml('<div *ngFor="let item of items; trackBy: trackByFn"></div>').toEqual([ [ 'Template', '<div *ngFor="let item of items; trackBy: trackByFn"></div>', '<div *ngFor="let item of items; trackBy: trackByFn">', '</div>', ], ['TextAttribute', 'ngFor', 'ngFor', '<empty>'], ['BoundAttribute', 'of items; ', 'of', 'items'], ['BoundAttribute', 'trackBy: trackByFn', 'trackBy', 'trackByFn'], ['Variable', 'let item ', 'item', '<empty>'], [ 'Element', '<div *ngFor="let item of items; trackBy: trackByFn"></div>', '<div *ngFor="let item of items; trackBy: trackByFn">', '</div>', ], ]); }); it('is correct for variables via let ...', () => { expectFromHtml('<div *ngIf="let a=b"></div>').toEqual([ ['Template', '<div *ngIf="let a=b"></div>', '<div *ngIf="let a=b">', '</div>'], ['TextAttribute', 'ngIf', 'ngIf', '<empty>'], ['Variable', 'let a=b', 'a', 'b'], ['Element', '<div *ngIf="let a=b"></div>', '<div *ngIf="let a=b">', '</div>'], ]); }); it('is correct for variables via as ...', () => { expectFromHtml('<div *ngIf="expr as local"></div>').toEqual([ ['Template', '<div *ngIf="expr as local"></div>', '<div *ngIf="expr as local">', '</div>'], ['BoundAttribute', 'ngIf="expr ', 'ngIf', 'expr'], ['Variable', 'ngIf="expr as local', 'local', 'ngIf'], ['Element', '<div *ngIf="expr as local"></div>', '<div *ngIf="expr as local">', '</div>'], ]); }); }); describe('events', () => { it('is correct for event names case sensitive', () => { expectFromHtml('<div (someEvent)="v"></div>').toEqual([ ['Element', '<div (someEvent)="v"></div>', '<div (someEvent)="v">', '</div>'], ['BoundEvent', '(someEvent)="v"', 'someEvent', 'v'], ]); }); it('is correct for bound events via on-', () => { expectFromHtml('<div on-event="v"></div>').toEqual([ ['Element', '<div on-event="v"></div>', '<div on-event="v">', '</div>'], ['BoundEvent', 'on-event="v"', 'event', 'v'], ]); }); it('is correct for bound events via data-on-', () => { expectFromHtml('<div data-on-event="v"></div>').toEqual([ ['Element', '<div data-on-event="v"></div>', '<div data-on-event="v">', '</div>'], ['BoundEvent', 'data-on-event="v"', 'event', 'v'], ]); }); it('is correct for bound events and properties via [(...)]', () => { expectFromHtml('<div [(prop)]="v"></div>').toEqual([ ['Element', '<div [(prop)]="v"></div>', '<div [(prop)]="v">', '</div>'], ['BoundAttribute', '[(prop)]="v"', 'prop', 'v'], ['BoundEvent', '[(prop)]="v"', 'prop', 'v'], ]); }); it('is correct for bound events and properties via bindon-', () => { expectFromHtml('<div bindon-prop="v"></div>').toEqual([ ['Element', '<div bindon-prop="v"></div>', '<div bindon-prop="v">', '</div>'], ['BoundAttribute', 'bindon-prop="v"', 'prop', 'v'], ['BoundEvent', 'bindon-prop="v"', 'prop', 'v'], ]); }); it('is correct for bound events and properties via data-bindon-', () => { expectFromHtml('<div data-bindon-prop="v"></div>').toEqual([ ['Element', '<div data-bindon-prop="v"></div>', '<div data-bindon-prop="v">', '</div>'], ['BoundAttribute', 'data-bindon-prop="v"', 'prop', 'v'], ['BoundEvent', 'data-bindon-prop="v"', 'prop', 'v'], ]); }); it('is correct for bound events via @', () => { expectFromHtml('<div (@name.done)="v"></div>').toEqual([ ['Element', '<div (@name.done)="v"></div>', '<div (@name.done)="v">', '</div>'], ['BoundEvent', '(@name.done)="v"', 'name.done', 'v'], ]); }); }); describe('references', () => { it('is correct for references via #...', () => { expectFromHtml('<div #a></div>').toEqual([ ['Element', '<div #a></div>', '<div #a>', '</div>'], ['Reference', '#a', 'a', '<empty>'], ]); }); it('is correct for references with name', () => { expectFromHtml('<div #a="b"></div>').toEqual([ ['Element', '<div #a="b"></div>', '<div #a="b">', '</div>'], ['Reference', '#a="b"', 'a', 'b'], ]); }); it('is correct for references via ref-', () => { expectFromHtml('<div ref-a></div>').toEqual([ ['Element', '<div ref-a></div>', '<div ref-a>', '</div>'], ['Reference', 'ref-a', 'a', '<empty>'], ]); }); it('is correct for references via data-ref-', () => { expectFromHtml('<div ref-a></div>').toEqual([ ['Element', '<div ref-a></div>', '<div ref-a>', '</div>'], ['Reference', 'ref-a', 'a', '<empty>'], ]); }); });
{ "end_byte": 21173, "start_byte": 14742, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_spans_spec.ts" }
angular/packages/compiler/test/render3/r3_ast_spans_spec.ts_21177_28740
describe('ICU expressions', () => { it('is correct for variables and placeholders', () => { expectFromHtml( '<span i18n>{item.var, plural, other { {{item.placeholder}} items } }</span>', ).toEqual([ [ 'Element', '<span i18n>{item.var, plural, other { {{item.placeholder}} items } }</span>', '<span i18n>', '</span>', ], ['Icu', '{item.var, plural, other { {{item.placeholder}} items } }'], ['Icu:Var', 'item.var'], ['Icu:Placeholder', '{{item.placeholder}}'], ]); }); it('is correct for nested ICUs', () => { expectFromHtml( '<span i18n>{item.var, plural, other { {{item.placeholder}} {nestedVar, plural, other { {{nestedPlaceholder}} }}} }</span>', ).toEqual([ [ 'Element', '<span i18n>{item.var, plural, other { {{item.placeholder}} {nestedVar, plural, other { {{nestedPlaceholder}} }}} }</span>', '<span i18n>', '</span>', ], [ 'Icu', '{item.var, plural, other { {{item.placeholder}} {nestedVar, plural, other { {{nestedPlaceholder}} }}} }', ], ['Icu:Var', 'nestedVar'], ['Icu:Var', 'item.var'], ['Icu:Placeholder', '{{item.placeholder}}'], ['Icu:Placeholder', '{{nestedPlaceholder}}'], ]); }); }); describe('deferred blocks', () => { it('is correct for deferred blocks', () => { const html = '@defer (when isVisible() && foo; on hover(button), timer(10s), idle, immediate, ' + 'interaction(button), viewport(container); prefetch on immediate; ' + 'prefetch when isDataLoaded(); hydrate on interaction; hydrate when isVisible(); hydrate on timer(1200)) {<calendar-cmp [date]="current"/>}' + '@loading (minimum 1s; after 100ms) {Loading...}' + '@placeholder (minimum 500) {Placeholder content!}' + '@error {Loading failed :(}'; expectFromHtml(html).toEqual([ [ 'DeferredBlock', '@defer (when isVisible() && foo; on hover(button), timer(10s), idle, immediate, interaction(button), viewport(container); prefetch on immediate; prefetch when isDataLoaded(); hydrate on interaction; hydrate when isVisible(); hydrate on timer(1200)) {<calendar-cmp [date]="current"/>}@loading (minimum 1s; after 100ms) {Loading...}@placeholder (minimum 500) {Placeholder content!}@error {Loading failed :(}', '@defer (when isVisible() && foo; on hover(button), timer(10s), idle, immediate, interaction(button), viewport(container); prefetch on immediate; prefetch when isDataLoaded(); hydrate on interaction; hydrate when isVisible(); hydrate on timer(1200)) {', '}', ], ['InteractionDeferredTrigger', 'hydrate on interaction'], ['BoundDeferredTrigger', 'hydrate when isVisible()'], ['TimerDeferredTrigger', 'hydrate on timer(1200)'], ['BoundDeferredTrigger', 'when isVisible() && foo'], ['HoverDeferredTrigger', 'on hover(button)'], ['TimerDeferredTrigger', 'timer(10s)'], ['IdleDeferredTrigger', 'idle'], ['ImmediateDeferredTrigger', 'immediate'], ['InteractionDeferredTrigger', 'interaction(button)'], ['ViewportDeferredTrigger', 'viewport(container)'], ['ImmediateDeferredTrigger', 'prefetch on immediate'], ['BoundDeferredTrigger', 'prefetch when isDataLoaded()'], [ 'Element', '<calendar-cmp [date]="current"/>', '<calendar-cmp [date]="current"/>', '<calendar-cmp [date]="current"/>', ], ['BoundAttribute', '[date]="current"', 'date', 'current'], [ 'DeferredBlockPlaceholder', '@placeholder (minimum 500) {Placeholder content!}', '@placeholder (minimum 500) {', '}', ], ['Text', 'Placeholder content!'], [ 'DeferredBlockLoading', '@loading (minimum 1s; after 100ms) {Loading...}', '@loading (minimum 1s; after 100ms) {', '}', ], ['Text', 'Loading...'], ['DeferredBlockError', '@error {Loading failed :(}', '@error {', '}'], ['Text', 'Loading failed :('], ]); }); }); describe('switch blocks', () => { it('is correct for switch blocks', () => { const html = `@switch (cond.kind) {` + `@case (x()) {X case}` + `@case ('hello') {Y case}` + `@case (42) {Z case}` + `@default {No case matched}` + `}`; expectFromHtml(html).toEqual([ [ 'SwitchBlock', "@switch (cond.kind) {@case (x()) {X case}@case ('hello') {Y case}@case (42) {Z case}@default {No case matched}}", '@switch (cond.kind) {', '}', ], ['SwitchBlockCase', '@case (x()) {X case}', '@case (x()) {'], ['Text', 'X case'], ['SwitchBlockCase', "@case ('hello') {Y case}", "@case ('hello') {"], ['Text', 'Y case'], ['SwitchBlockCase', '@case (42) {Z case}', '@case (42) {'], ['Text', 'Z case'], ['SwitchBlockCase', '@default {No case matched}', '@default {'], ['Text', 'No case matched'], ]); }); }); describe('for loop blocks', () => { it('is correct for loop blocks', () => { const html = `@for (item of items.foo.bar; track item.id; let i = $index, _o_d_d_ = $odd) {<h1>{{ item }}</h1>}` + `@empty {There were no items in the list.}`; expectFromHtml(html).toEqual([ [ 'ForLoopBlock', '@for (item of items.foo.bar; track item.id; let i = $index, _o_d_d_ = $odd) {<h1>{{ item }}</h1>}@empty {There were no items in the list.}', '@for (item of items.foo.bar; track item.id; let i = $index, _o_d_d_ = $odd) {', '}', ], ['Variable', 'item', 'item', '<empty>'], ['Variable', '', '', '<empty>'], ['Variable', '', '', '<empty>'], ['Variable', '', '', '<empty>'], ['Variable', '', '', '<empty>'], ['Variable', '', '', '<empty>'], ['Variable', '', '', '<empty>'], ['Variable', 'i = $index', 'i', '$index'], ['Variable', '_o_d_d_ = $odd', '_o_d_d_', '$odd'], ['Element', '<h1>{{ item }}</h1>', '<h1>', '</h1>'], ['BoundText', '{{ item }}'], ['ForLoopBlockEmpty', '@empty {There were no items in the list.}', '@empty {'], ['Text', 'There were no items in the list.'], ]); }); }); describe('if blocks', () => { it('is correct for if blocks', () => { const html = `@if (cond.expr; as foo) {Main case was true!}` + `@else if (other.expr) {Extra case was true!}` + `@else {False case!}`; expectFromHtml(html).toEqual([ [ 'IfBlock', '@if (cond.expr; as foo) {Main case was true!}@else if (other.expr) {Extra case was true!}@else {False case!}', '@if (cond.expr; as foo) {', '}', ], [ 'IfBlockBranch', '@if (cond.expr; as foo) {Main case was true!}', '@if (cond.expr; as foo) {', ], ['Variable', 'foo', 'foo', '<empty>'], ['Text', 'Main case was true!'], [ 'IfBlockBranch', '@else if (other.expr) {Extra case was true!}', '@else if (other.expr) {', ], ['Text', 'Extra case was true!'], ['IfBlockBranch', '@else {False case!}', '@else {'], ['Text', 'False case!'], ]); }); });
{ "end_byte": 28740, "start_byte": 21177, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_spans_spec.ts" }
angular/packages/compiler/test/render3/r3_ast_spans_spec.ts_28744_28969
describe('@let declaration', () => { it('is correct for a let declaration', () => { expectFromHtml('@let foo = 123;').toEqual([ ['LetDeclaration', '@let foo = 123', 'foo', '123'], ]); }); }); });
{ "end_byte": 28969, "start_byte": 28744, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_spans_spec.ts" }
angular/packages/compiler/test/render3/README.md_0_86
Tests in this directory are excluded from running in the browser and only run in node.
{ "end_byte": 86, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/README.md" }
angular/packages/compiler/test/render3/BUILD.bazel_0_458
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.ts"], ), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler/test/expression_parser/utils", "//packages/core", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], )
{ "end_byte": 458, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/BUILD.bazel" }
angular/packages/compiler/test/render3/r3_ast_absolute_span_spec.ts_0_8079
/** * @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 {AbsoluteSourceSpan} from '@angular/compiler'; import {humanizeExpressionSource} from './util/expression'; import {parseR3 as parse} from './view/util'; describe('expression AST absolute source spans', () => { it('should handle comment in interpolation', () => { expect( humanizeExpressionSource(parse('{{foo // comment}}', {preserveWhitespaces: true}).nodes), ).toContain(['foo', new AbsoluteSourceSpan(2, 5)]); }); it('should handle whitespace in interpolation', () => { expect( humanizeExpressionSource(parse('{{ foo }}', {preserveWhitespaces: true}).nodes), ).toContain(['foo', new AbsoluteSourceSpan(4, 7)]); }); it('should handle whitespace and comment in interpolation', () => { expect( humanizeExpressionSource(parse('{{ foo // comment }}', {preserveWhitespaces: true}).nodes), ).toContain(['foo', new AbsoluteSourceSpan(4, 7)]); }); it('should handle comment in an action binding', () => { expect( humanizeExpressionSource( parse('<button (click)="foo = true // comment">Save</button>', { preserveWhitespaces: true, }).nodes, ), ).toContain(['foo = true', new AbsoluteSourceSpan(17, 27)]); }); // TODO(ayazhafiz): duplicate this test without `preserveWhitespaces` once whitespace rewriting is // moved to post-R3AST generation. it('should provide absolute offsets with arbitrary whitespace', () => { expect( humanizeExpressionSource( parse('<div>\n \n{{foo}}</div>', {preserveWhitespaces: true}).nodes, ), ).toContain(['\n \n{{ foo }}', new AbsoluteSourceSpan(5, 16)]); }); it('should provide absolute offsets of an expression in a bound text', () => { expect(humanizeExpressionSource(parse('<div>{{foo}}</div>').nodes)).toContain([ '{{ foo }}', new AbsoluteSourceSpan(5, 12), ]); }); it('should provide absolute offsets of an expression in a bound event', () => { expect(humanizeExpressionSource(parse('<div (click)="foo();bar();"></div>').nodes)).toContain([ 'foo(); bar();', new AbsoluteSourceSpan(14, 26), ]); expect(humanizeExpressionSource(parse('<div on-click="foo();bar();"></div>').nodes)).toContain([ 'foo(); bar();', new AbsoluteSourceSpan(15, 27), ]); }); it('should provide absolute offsets of an expression in a bound attribute', () => { expect( humanizeExpressionSource(parse('<input [disabled]="condition ? true : false" />').nodes), ).toContain(['condition ? true : false', new AbsoluteSourceSpan(19, 43)]); expect( humanizeExpressionSource(parse('<input bind-disabled="condition ? true : false" />').nodes), ).toContain(['condition ? true : false', new AbsoluteSourceSpan(22, 46)]); }); it('should provide absolute offsets of an expression in a template attribute', () => { expect(humanizeExpressionSource(parse('<div *ngIf="value | async"></div>').nodes)).toContain([ '(value | async)', new AbsoluteSourceSpan(12, 25), ]); }); describe('binary expression', () => { it('should provide absolute offsets of a binary expression', () => { expect(humanizeExpressionSource(parse('<div>{{1 + 2}}<div>').nodes)).toContain([ '1 + 2', new AbsoluteSourceSpan(7, 12), ]); }); it('should provide absolute offsets of expressions in a binary expression', () => { expect(humanizeExpressionSource(parse('<div>{{1 + 2}}<div>').nodes)).toEqual( jasmine.arrayContaining([ ['1', new AbsoluteSourceSpan(7, 8)], ['2', new AbsoluteSourceSpan(11, 12)], ]), ); }); }); describe('conditional', () => { it('should provide absolute offsets of a conditional', () => { expect(humanizeExpressionSource(parse('<div>{{bool ? 1 : 0}}<div>').nodes)).toContain([ 'bool ? 1 : 0', new AbsoluteSourceSpan(7, 19), ]); }); it('should provide absolute offsets of expressions in a conditional', () => { expect(humanizeExpressionSource(parse('<div>{{bool ? 1 : 0}}<div>').nodes)).toEqual( jasmine.arrayContaining([ ['bool', new AbsoluteSourceSpan(7, 11)], ['1', new AbsoluteSourceSpan(14, 15)], ['0', new AbsoluteSourceSpan(18, 19)], ]), ); }); }); describe('chain', () => { it('should provide absolute offsets of a chain', () => { expect(humanizeExpressionSource(parse('<div (click)="a(); b();"><div>').nodes)).toContain([ 'a(); b();', new AbsoluteSourceSpan(14, 23), ]); }); it('should provide absolute offsets of expressions in a chain', () => { expect(humanizeExpressionSource(parse('<div (click)="a(); b();"><div>').nodes)).toEqual( jasmine.arrayContaining([ ['a()', new AbsoluteSourceSpan(14, 17)], ['b()', new AbsoluteSourceSpan(19, 22)], ]), ); }); }); describe('function call', () => { it('should provide absolute offsets of a function call', () => { expect(humanizeExpressionSource(parse('<div>{{fn()()}}<div>').nodes)).toContain([ 'fn()()', new AbsoluteSourceSpan(7, 13), ]); }); it('should provide absolute offsets of expressions in a function call', () => { expect(humanizeExpressionSource(parse('<div>{{fn()(param)}}<div>').nodes)).toContain([ 'param', new AbsoluteSourceSpan(12, 17), ]); }); }); it('should provide absolute offsets of an implicit receiver', () => { expect(humanizeExpressionSource(parse('<div>{{a.b}}<div>').nodes)).toContain([ '', new AbsoluteSourceSpan(7, 7), ]); }); describe('interpolation', () => { it('should provide absolute offsets of an interpolation', () => { expect(humanizeExpressionSource(parse('<div>{{1 + foo.length}}<div>').nodes)).toContain([ '{{ 1 + foo.length }}', new AbsoluteSourceSpan(5, 23), ]); }); it('should provide absolute offsets of expressions in an interpolation', () => { expect(humanizeExpressionSource(parse('<div>{{1 + 2}}<div>').nodes)).toEqual( jasmine.arrayContaining([ ['1', new AbsoluteSourceSpan(7, 8)], ['2', new AbsoluteSourceSpan(11, 12)], ]), ); }); it('should handle HTML entity before interpolation', () => { expect(humanizeExpressionSource(parse('&nbsp;{{abc}}').nodes)).toEqual( jasmine.arrayContaining([['abc', new AbsoluteSourceSpan(8, 11)]]), ); }); it('should handle many HTML entities and many interpolations', () => { expect( humanizeExpressionSource(parse('&quot;{{abc}}&quot;{{def}}&nbsp;{{ghi}}').nodes), ).toEqual( jasmine.arrayContaining([ ['abc', new AbsoluteSourceSpan(8, 11)], ['def', new AbsoluteSourceSpan(21, 24)], ['ghi', new AbsoluteSourceSpan(34, 37)], ]), ); }); it('should handle interpolation in attribute', () => { expect(humanizeExpressionSource(parse('<div class="{{abc}}"><div>').nodes)).toEqual( jasmine.arrayContaining([['abc', new AbsoluteSourceSpan(14, 17)]]), ); }); it('should handle interpolation preceded by HTML entity in attribute', () => { expect(humanizeExpressionSource(parse('<div class="&nbsp;{{abc}}"><div>').nodes)).toEqual( jasmine.arrayContaining([['abc', new AbsoluteSourceSpan(20, 23)]]), ); }); it('should handle many interpolation with HTML entities in attribute', () => { expect( humanizeExpressionSource( parse('<div class="&quot;{{abc}}&quot;&nbsp;{{def}}"><div>').nodes, ), ).toEqual( jasmine.arrayContaining([ ['abc', new AbsoluteSourceSpan(20, 23)], ['def', new AbsoluteSourceSpan(39, 42)], ]), ); }); });
{ "end_byte": 8079, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_absolute_span_spec.ts" }
angular/packages/compiler/test/render3/r3_ast_absolute_span_spec.ts_8083_15778
describe('keyed read', () => { it('should provide absolute offsets of a keyed read', () => { expect(humanizeExpressionSource(parse('<div>{{obj[key]}}<div>').nodes)).toContain([ 'obj[key]', new AbsoluteSourceSpan(7, 15), ]); }); it('should provide absolute offsets of expressions in a keyed read', () => { expect(humanizeExpressionSource(parse('<div>{{obj[key]}}<div>').nodes)).toContain([ 'key', new AbsoluteSourceSpan(11, 14), ]); }); }); describe('keyed write', () => { it('should provide absolute offsets of a keyed write', () => { expect(humanizeExpressionSource(parse('<div>{{obj[key] = 0}}<div>').nodes)).toContain([ 'obj[key] = 0', new AbsoluteSourceSpan(7, 19), ]); }); it('should provide absolute offsets of expressions in a keyed write', () => { expect(humanizeExpressionSource(parse('<div>{{obj[key] = 0}}<div>').nodes)).toEqual( jasmine.arrayContaining([ ['key', new AbsoluteSourceSpan(11, 14)], ['0', new AbsoluteSourceSpan(18, 19)], ]), ); }); }); it('should provide absolute offsets of a literal primitive', () => { expect(humanizeExpressionSource(parse('<div>{{100}}<div>').nodes)).toContain([ '100', new AbsoluteSourceSpan(7, 10), ]); }); describe('literal array', () => { it('should provide absolute offsets of a literal array', () => { expect(humanizeExpressionSource(parse('<div>{{[0, 1, 2]}}<div>').nodes)).toContain([ '[0, 1, 2]', new AbsoluteSourceSpan(7, 16), ]); }); it('should provide absolute offsets of expressions in a literal array', () => { expect(humanizeExpressionSource(parse('<div>{{[0, 1, 2]}}<div>').nodes)).toEqual( jasmine.arrayContaining([ ['0', new AbsoluteSourceSpan(8, 9)], ['1', new AbsoluteSourceSpan(11, 12)], ['2', new AbsoluteSourceSpan(14, 15)], ]), ); }); }); describe('literal map', () => { it('should provide absolute offsets of a literal map', () => { expect(humanizeExpressionSource(parse('<div>{{ {a: 0} }}<div>').nodes)).toContain([ '{a: 0}', new AbsoluteSourceSpan(8, 14), ]); }); it('should provide absolute offsets of expressions in a literal map', () => { expect(humanizeExpressionSource(parse('<div>{{ {a: 0} }}<div>').nodes)).toEqual( jasmine.arrayContaining([['0', new AbsoluteSourceSpan(12, 13)]]), ); }); }); describe('method call', () => { it('should provide absolute offsets of a method call', () => { expect(humanizeExpressionSource(parse('<div>{{method()}}</div>').nodes)).toContain([ 'method()', new AbsoluteSourceSpan(7, 15), ]); }); it('should provide absolute offsets of expressions in a method call', () => { expect(humanizeExpressionSource(parse('<div>{{method(param)}}<div>').nodes)).toContain([ 'param', new AbsoluteSourceSpan(14, 19), ]); }); }); describe('non-null assert', () => { it('should provide absolute offsets of a non-null assert', () => { expect(humanizeExpressionSource(parse('<div>{{prop!}}</div>').nodes)).toContain([ 'prop!', new AbsoluteSourceSpan(7, 12), ]); }); it('should provide absolute offsets of expressions in a non-null assert', () => { expect(humanizeExpressionSource(parse('<div>{{prop!}}<div>').nodes)).toContain([ 'prop', new AbsoluteSourceSpan(7, 11), ]); }); }); describe('pipe', () => { it('should provide absolute offsets of a pipe', () => { expect(humanizeExpressionSource(parse('<div>{{prop | pipe}}<div>').nodes)).toContain([ '(prop | pipe)', new AbsoluteSourceSpan(7, 18), ]); }); it('should provide absolute offsets expressions in a pipe', () => { expect(humanizeExpressionSource(parse('<div>{{prop | pipe}}<div>').nodes)).toContain([ 'prop', new AbsoluteSourceSpan(7, 11), ]); }); }); describe('property read', () => { it('should provide absolute offsets of a property read', () => { expect(humanizeExpressionSource(parse('<div>{{prop.obj}}<div>').nodes)).toContain([ 'prop.obj', new AbsoluteSourceSpan(7, 15), ]); }); it('should provide absolute offsets of expressions in a property read', () => { expect(humanizeExpressionSource(parse('<div>{{prop.obj}}<div>').nodes)).toContain([ 'prop', new AbsoluteSourceSpan(7, 11), ]); }); }); describe('property write', () => { it('should provide absolute offsets of a property write', () => { expect(humanizeExpressionSource(parse('<div (click)="prop = 0"></div>').nodes)).toContain([ 'prop = 0', new AbsoluteSourceSpan(14, 22), ]); }); it('should provide absolute offsets of an accessed property write', () => { expect( humanizeExpressionSource(parse('<div (click)="prop.inner = 0"></div>').nodes), ).toContain(['prop.inner = 0', new AbsoluteSourceSpan(14, 28)]); }); it('should provide absolute offsets of expressions in a property write', () => { expect(humanizeExpressionSource(parse('<div (click)="prop = 0"></div>').nodes)).toContain([ '0', new AbsoluteSourceSpan(21, 22), ]); }); }); describe('"not" prefix', () => { it('should provide absolute offsets of a "not" prefix', () => { expect(humanizeExpressionSource(parse('<div>{{!prop}}</div>').nodes)).toContain([ '!prop', new AbsoluteSourceSpan(7, 12), ]); }); it('should provide absolute offsets of expressions in a "not" prefix', () => { expect(humanizeExpressionSource(parse('<div>{{!prop}}<div>').nodes)).toContain([ 'prop', new AbsoluteSourceSpan(8, 12), ]); }); }); describe('safe method call', () => { it('should provide absolute offsets of a safe method call', () => { expect(humanizeExpressionSource(parse('<div>{{prop?.safe()}}<div>').nodes)).toContain([ 'prop?.safe()', new AbsoluteSourceSpan(7, 19), ]); }); it('should provide absolute offsets of expressions in safe method call', () => { expect(humanizeExpressionSource(parse('<div>{{prop?.safe()}}<div>').nodes)).toContain([ 'prop', new AbsoluteSourceSpan(7, 11), ]); }); }); describe('safe property read', () => { it('should provide absolute offsets of a safe property read', () => { expect(humanizeExpressionSource(parse('<div>{{prop?.safe}}<div>').nodes)).toContain([ 'prop?.safe', new AbsoluteSourceSpan(7, 17), ]); }); it('should provide absolute offsets of expressions in safe property read', () => { expect(humanizeExpressionSource(parse('<div>{{prop?.safe}}<div>').nodes)).toContain([ 'prop', new AbsoluteSourceSpan(7, 11), ]); }); }); describe('absolute offsets for template expressions', () => { it('should work for simple cases', () => { expect( humanizeExpressionSource(parse('<div *ngFor="let item of items">{{item}}</div>').nodes), ).toContain(['items', new AbsoluteSourceSpan(25, 30)]); }); it('should work with multiple bindings', () => { expect( humanizeExpressionSource(parse('<div *ngFor="let a of As; let b of Bs"></div>').nodes), ).toEqual( jasmine.arrayContaining([ ['As', new AbsoluteSourceSpan(22, 24)], ['Bs', new AbsoluteSourceSpan(35, 37)], ]), ); }); });
{ "end_byte": 15778, "start_byte": 8083, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_absolute_span_spec.ts" }
angular/packages/compiler/test/render3/r3_ast_absolute_span_spec.ts_15782_17336
describe('ICU expressions', () => { it('is correct for variables and placeholders', () => { const spans = humanizeExpressionSource( parse('<span i18n>{item.var, plural, other { {{item.placeholder}} items } }</span>').nodes, ); expect(spans).toContain(['item.var', new AbsoluteSourceSpan(12, 20)]); expect(spans).toContain(['item.placeholder', new AbsoluteSourceSpan(40, 56)]); }); it('is correct for variables and placeholders', () => { const spans = humanizeExpressionSource( parse( '<span i18n>{item.var, plural, other { {{item.placeholder}} {nestedVar, plural, other { {{nestedPlaceholder}} }}} }</span>', ).nodes, ); expect(spans).toContain(['item.var', new AbsoluteSourceSpan(12, 20)]); expect(spans).toContain(['item.placeholder', new AbsoluteSourceSpan(40, 56)]); expect(spans).toContain(['nestedVar', new AbsoluteSourceSpan(60, 69)]); expect(spans).toContain(['nestedPlaceholder', new AbsoluteSourceSpan(89, 106)]); }); }); describe('object literal', () => { it('is correct for object literals with shorthand property declarations', () => { const spans = humanizeExpressionSource( parse('<div (click)="test({a: 1, b, c: 3, foo})"></div>').nodes, ); expect(spans).toContain(['{a: 1, b: b, c: 3, foo: foo}', new AbsoluteSourceSpan(19, 39)]); expect(spans).toContain(['b', new AbsoluteSourceSpan(26, 27)]); expect(spans).toContain(['foo', new AbsoluteSourceSpan(35, 38)]); }); }); });
{ "end_byte": 17336, "start_byte": 15782, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/r3_ast_absolute_span_spec.ts" }
angular/packages/compiler/test/render3/util/expression.ts_0_6451
/** * @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 {AbsoluteSourceSpan} from '@angular/compiler'; import * as e from '../../../src/expression_parser/ast'; import * as t from '../../../src/render3/r3_ast'; import {unparse} from '../../expression_parser/utils/unparser'; type HumanizedExpressionSource = [string, AbsoluteSourceSpan]; class ExpressionSourceHumanizer extends e.RecursiveAstVisitor implements t.Visitor { result: HumanizedExpressionSource[] = []; private recordAst(ast: e.AST) { this.result.push([unparse(ast), ast.sourceSpan]); } // This method is defined to reconcile the type of ExpressionSourceHumanizer // since both RecursiveAstVisitor and Visitor define the visit() method in // their interfaces. override visit(node: e.AST | t.Node, context?: any) { if (node instanceof e.AST) { node.visit(this, context); } else { node.visit(this); } } visitASTWithSource(ast: e.ASTWithSource) { this.recordAst(ast); this.visitAll([ast.ast], null); } override visitBinary(ast: e.Binary) { this.recordAst(ast); super.visitBinary(ast, null); } override visitChain(ast: e.Chain) { this.recordAst(ast); super.visitChain(ast, null); } override visitConditional(ast: e.Conditional) { this.recordAst(ast); super.visitConditional(ast, null); } override visitImplicitReceiver(ast: e.ImplicitReceiver) { this.recordAst(ast); super.visitImplicitReceiver(ast, null); } override visitInterpolation(ast: e.Interpolation) { this.recordAst(ast); super.visitInterpolation(ast, null); } override visitKeyedRead(ast: e.KeyedRead) { this.recordAst(ast); super.visitKeyedRead(ast, null); } override visitKeyedWrite(ast: e.KeyedWrite) { this.recordAst(ast); super.visitKeyedWrite(ast, null); } override visitLiteralPrimitive(ast: e.LiteralPrimitive) { this.recordAst(ast); super.visitLiteralPrimitive(ast, null); } override visitLiteralArray(ast: e.LiteralArray) { this.recordAst(ast); super.visitLiteralArray(ast, null); } override visitLiteralMap(ast: e.LiteralMap) { this.recordAst(ast); super.visitLiteralMap(ast, null); } override visitNonNullAssert(ast: e.NonNullAssert) { this.recordAst(ast); super.visitNonNullAssert(ast, null); } override visitPipe(ast: e.BindingPipe) { this.recordAst(ast); super.visitPipe(ast, null); } override visitPrefixNot(ast: e.PrefixNot) { this.recordAst(ast); super.visitPrefixNot(ast, null); } override visitTypeofExpresion(ast: e.TypeofExpression) { this.recordAst(ast); super.visitTypeofExpresion(ast, null); } override visitPropertyRead(ast: e.PropertyRead) { this.recordAst(ast); super.visitPropertyRead(ast, null); } override visitPropertyWrite(ast: e.PropertyWrite) { this.recordAst(ast); super.visitPropertyWrite(ast, null); } override visitSafePropertyRead(ast: e.SafePropertyRead) { this.recordAst(ast); super.visitSafePropertyRead(ast, null); } override visitSafeKeyedRead(ast: e.SafeKeyedRead) { this.recordAst(ast); super.visitSafeKeyedRead(ast, null); } override visitCall(ast: e.Call) { this.recordAst(ast); super.visitCall(ast, null); } override visitSafeCall(ast: e.SafeCall) { this.recordAst(ast); super.visitSafeCall(ast, null); } visitTemplate(ast: t.Template) { t.visitAll(this, ast.children); t.visitAll(this, ast.templateAttrs); } visitElement(ast: t.Element) { t.visitAll(this, ast.children); t.visitAll(this, ast.inputs); t.visitAll(this, ast.outputs); } visitReference(ast: t.Reference) {} visitVariable(ast: t.Variable) {} visitEvent(ast: t.BoundEvent) { ast.handler.visit(this); } visitTextAttribute(ast: t.TextAttribute) {} visitBoundAttribute(ast: t.BoundAttribute) { ast.value.visit(this); } visitBoundEvent(ast: t.BoundEvent) { ast.handler.visit(this); } visitBoundText(ast: t.BoundText) { ast.value.visit(this); } visitContent(ast: t.Content) { t.visitAll(this, ast.children); } visitText(ast: t.Text) {} visitUnknownBlock(block: t.UnknownBlock) {} visitIcu(ast: t.Icu) { for (const key of Object.keys(ast.vars)) { ast.vars[key].visit(this); } for (const key of Object.keys(ast.placeholders)) { ast.placeholders[key].visit(this); } } visitDeferredBlock(deferred: t.DeferredBlock) { deferred.visitAll(this); } visitDeferredTrigger(trigger: t.DeferredTrigger): void { if (trigger instanceof t.BoundDeferredTrigger) { this.recordAst(trigger.value); } } visitDeferredBlockPlaceholder(block: t.DeferredBlockPlaceholder) { t.visitAll(this, block.children); } visitDeferredBlockError(block: t.DeferredBlockError) { t.visitAll(this, block.children); } visitDeferredBlockLoading(block: t.DeferredBlockLoading) { t.visitAll(this, block.children); } visitSwitchBlock(block: t.SwitchBlock) { block.expression.visit(this); t.visitAll(this, block.cases); } visitSwitchBlockCase(block: t.SwitchBlockCase) { block.expression?.visit(this); t.visitAll(this, block.children); } visitForLoopBlock(block: t.ForLoopBlock) { block.item.visit(this); t.visitAll(this, block.contextVariables); block.expression.visit(this); t.visitAll(this, block.children); block.empty?.visit(this); } visitForLoopBlockEmpty(block: t.ForLoopBlockEmpty) { t.visitAll(this, block.children); } visitIfBlock(block: t.IfBlock) { t.visitAll(this, block.branches); } visitIfBlockBranch(block: t.IfBlockBranch) { block.expression?.visit(this); block.expressionAlias?.visit(this); t.visitAll(this, block.children); } visitLetDeclaration(decl: t.LetDeclaration) { decl.value.visit(this); } } /** * Humanizes expression AST source spans in a template by returning an array of tuples * [unparsed AST, AST source span] * for each expression in the template. * @param templateAsts template AST to humanize */ export function humanizeExpressionSource(templateAsts: t.Node[]): HumanizedExpressionSource[] { const humanizer = new ExpressionSourceHumanizer(); t.visitAll(humanizer, templateAsts); return humanizer.result; }
{ "end_byte": 6451, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/util/expression.ts" }
angular/packages/compiler/test/render3/view/binding_spec.ts_0_7551
/** * @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 e from '../../../src/expression_parser/ast'; import * as a from '../../../src/render3/r3_ast'; import {DirectiveMeta, InputOutputPropertySet} from '../../../src/render3/view/t2_api'; import {findMatchingDirectivesAndPipes, R3TargetBinder} from '../../../src/render3/view/t2_binder'; import {parseTemplate} from '../../../src/render3/view/template'; import {CssSelector, SelectorMatcher} from '../../../src/selector'; import {findExpression} from './util'; /** * A `InputOutputPropertySet` which only uses an identity mapping for fields and properties. */ class IdentityInputMapping implements InputOutputPropertySet { private names: Set<string>; constructor(names: string[]) { this.names = new Set(names); } hasBindingPropertyName(propertyName: string): boolean { return this.names.has(propertyName); } } function makeSelectorMatcher(): SelectorMatcher<DirectiveMeta[]> { const matcher = new SelectorMatcher<DirectiveMeta[]>(); matcher.addSelectables(CssSelector.parse('[ngFor][ngForOf]'), [ { name: 'NgFor', exportAs: null, inputs: new IdentityInputMapping(['ngForOf']), outputs: new IdentityInputMapping([]), isComponent: false, isStructural: true, selector: '[ngFor][ngForOf]', animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); matcher.addSelectables(CssSelector.parse('[dir]'), [ { name: 'Dir', exportAs: ['dir'], inputs: new IdentityInputMapping([]), outputs: new IdentityInputMapping([]), isComponent: false, isStructural: false, selector: '[dir]', animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); matcher.addSelectables(CssSelector.parse('[hasOutput]'), [ { name: 'HasOutput', exportAs: null, inputs: new IdentityInputMapping([]), outputs: new IdentityInputMapping(['outputBinding']), isComponent: false, isStructural: false, selector: '[hasOutput]', animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); matcher.addSelectables(CssSelector.parse('[hasInput]'), [ { name: 'HasInput', exportAs: null, inputs: new IdentityInputMapping(['inputBinding']), outputs: new IdentityInputMapping([]), isComponent: false, isStructural: false, selector: '[hasInput]', animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); matcher.addSelectables(CssSelector.parse('[sameSelectorAsInput]'), [ { name: 'SameSelectorAsInput', exportAs: null, inputs: new IdentityInputMapping(['sameSelectorAsInput']), outputs: new IdentityInputMapping([]), isComponent: false, isStructural: false, selector: '[sameSelectorAsInput]', animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); matcher.addSelectables(CssSelector.parse('comp'), [ { name: 'Comp', exportAs: null, inputs: new IdentityInputMapping([]), outputs: new IdentityInputMapping([]), isComponent: true, isStructural: false, selector: 'comp', animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); const simpleDirectives = ['a', 'b', 'c', 'd', 'e', 'f']; const deferBlockDirectives = ['loading', 'error', 'placeholder']; for (const dir of [...simpleDirectives, ...deferBlockDirectives]) { const name = dir[0].toUpperCase() + dir.slice(1).toLowerCase(); matcher.addSelectables(CssSelector.parse(`[${dir}]`), [ { name: `Dir${name}`, exportAs: null, inputs: new IdentityInputMapping([]), outputs: new IdentityInputMapping([]), isComponent: false, isStructural: true, selector: `[${dir}]`, animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); } return matcher; } describe('findMatchingDirectivesAndPipes', () => { it('should match directives and detect pipes in eager and deferrable parts of a template', () => { const template = ` <div [title]="abc | uppercase"></div> @defer { <my-defer-cmp [label]="abc | lowercase" /> } @placeholder {} `; const directiveSelectors = ['[title]', 'my-defer-cmp', 'not-matching']; const result = findMatchingDirectivesAndPipes(template, directiveSelectors); expect(result).toEqual({ directives: { regular: ['[title]'], deferCandidates: ['my-defer-cmp'], }, pipes: { regular: ['uppercase'], deferCandidates: ['lowercase'], }, }); }); it('should return empty directive list if no selectors are provided', () => { const template = ` <div [title]="abc | uppercase"></div> @defer { <my-defer-cmp [label]="abc | lowercase" /> } @placeholder {} `; const directiveSelectors: string[] = []; const result = findMatchingDirectivesAndPipes(template, directiveSelectors); expect(result).toEqual({ directives: { regular: [], deferCandidates: [], }, // Expect pipes to be present still. pipes: { regular: ['uppercase'], deferCandidates: ['lowercase'], }, }); }); it('should return a directive and a pipe only once (either as a regular or deferrable)', () => { const template = ` <my-defer-cmp [label]="abc | lowercase" [title]="abc | uppercase" /> @defer { <my-defer-cmp [label]="abc | lowercase" [title]="abc | uppercase" /> } @placeholder {} `; const directiveSelectors = ['[title]', 'my-defer-cmp', 'not-matching']; const result = findMatchingDirectivesAndPipes(template, directiveSelectors); expect(result).toEqual({ directives: { regular: ['my-defer-cmp', '[title]'], // All directives/components are used eagerly. deferCandidates: [], }, pipes: { regular: ['lowercase', 'uppercase'], // All pipes are used eagerly. deferCandidates: [], }, }); }); it('should handle directives on elements with local refs', () => { const template = ` <input [(ngModel)]="name" #ctrl="ngModel" required /> @defer { <my-defer-cmp [label]="abc | lowercase" [title]="abc | uppercase" /> <input [(ngModel)]="name" #ctrl="ngModel" required /> } @placeholder {} `; const directiveSelectors = [ '[ngModel]:not([formControlName]):not([formControl])', '[title]', 'my-defer-cmp', 'not-matching', ]; const result = findMatchingDirectivesAndPipes(template, directiveSelectors); expect(result).toEqual({ directives: { // `ngModel` is used both eagerly and in a defer block, thus it's located // in the "regular" (eager) bucket. regular: ['[ngModel]:not([formControlName]):not([formControl])'], deferCandidates: ['my-defer-cmp', '[title]'], }, pipes: { regular: [], deferCandidates: ['lowercase', 'uppercase'], }, }); }); });
{ "end_byte": 7551, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/binding_spec.ts" }
angular/packages/compiler/test/render3/view/binding_spec.ts_7553_15593
describe('t2 binding', () => { it('should bind a simple template', () => { const template = parseTemplate('<div *ngFor="let item of items">{{item.name}}</div>', '', {}); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const itemBinding = (findExpression(template.nodes, '{{item.name}}')! as e.Interpolation) .expressions[0] as e.PropertyRead; const item = itemBinding.receiver; const itemTarget = res.getExpressionTarget(item); if (!(itemTarget instanceof a.Variable)) { return fail('Expected item to point to a Variable'); } expect(itemTarget.value).toBe('$implicit'); const itemTemplate = res.getDefinitionNodeOfSymbol(itemTarget); expect(itemTemplate).not.toBeNull(); expect(res.getNestingLevel(itemTemplate!)).toBe(1); }); it('should match directives when binding a simple template', () => { const template = parseTemplate('<div *ngFor="let item of items">{{item.name}}</div>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const tmpl = template.nodes[0] as a.Template; const directives = res.getDirectivesOfNode(tmpl)!; expect(directives).not.toBeNull(); expect(directives.length).toBe(1); expect(directives[0].name).toBe('NgFor'); }); it('should match directives on namespaced elements', () => { const template = parseTemplate('<svg><text dir>SVG</text></svg>', '', {}); const matcher = new SelectorMatcher<DirectiveMeta[]>(); matcher.addSelectables(CssSelector.parse('text[dir]'), [ { name: 'Dir', exportAs: null, inputs: new IdentityInputMapping([]), outputs: new IdentityInputMapping([]), isComponent: false, isStructural: false, selector: 'text[dir]', animationTriggerNames: null, ngContentSelectors: null, preserveWhitespaces: false, }, ]); const binder = new R3TargetBinder(matcher); const res = binder.bind({template: template.nodes}); const svgNode = template.nodes[0] as a.Element; const textNode = svgNode.children[0] as a.Element; const directives = res.getDirectivesOfNode(textNode)!; expect(directives).not.toBeNull(); expect(directives.length).toBe(1); expect(directives[0].name).toBe('Dir'); }); it('should not match directives intended for an element on a microsyntax template', () => { const template = parseTemplate('<div *ngFor="let item of items" dir></div>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const tmpl = template.nodes[0] as a.Template; const tmplDirectives = res.getDirectivesOfNode(tmpl)!; expect(tmplDirectives).not.toBeNull(); expect(tmplDirectives.length).toBe(1); expect(tmplDirectives[0].name).toBe('NgFor'); const elDirectives = res.getDirectivesOfNode(tmpl.children[0] as a.Element)!; expect(elDirectives).not.toBeNull(); expect(elDirectives.length).toBe(1); expect(elDirectives[0].name).toBe('Dir'); }); it('should get @let declarations when resolving entities at the root', () => { const template = parseTemplate( ` @let one = 1; @let two = 2; @let sum = one + two; `, '', ); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const entities = Array.from(res.getEntitiesInScope(null)); expect(entities.map((entity) => entity.name)).toEqual(['one', 'two', 'sum']); }); it('should scope @let declarations to their current view', () => { const template = parseTemplate( ` @let one = 1; @if (true) { @let two = 2; } @if (true) { @let three = 3; } `, '', ); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const rootEntities = Array.from(res.getEntitiesInScope(null)); const firstBranchEntities = Array.from( res.getEntitiesInScope((template.nodes[1] as a.IfBlock).branches[0]), ); const secondBranchEntities = Array.from( res.getEntitiesInScope((template.nodes[2] as a.IfBlock).branches[0]), ); expect(rootEntities.map((entity) => entity.name)).toEqual(['one']); expect(firstBranchEntities.map((entity) => entity.name)).toEqual(['one', 'two']); expect(secondBranchEntities.map((entity) => entity.name)).toEqual(['one', 'three']); }); it('should resolve expressions to an @let declaration', () => { const template = parseTemplate( ` @let value = 1; {{value}} `, '', ); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const interpolationWrapper = (template.nodes[1] as a.BoundText).value as e.ASTWithSource; const propertyRead = (interpolationWrapper.ast as e.Interpolation).expressions[0]; const target = res.getExpressionTarget(propertyRead); expect(target instanceof a.LetDeclaration).toBe(true); expect((target as a.LetDeclaration)?.name).toBe('value'); }); it('should not resolve a `this` access to a template reference', () => { const template = parseTemplate( ` <input #value> {{this.value}} `, '', ); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const interpolationWrapper = (template.nodes[1] as a.BoundText).value as e.ASTWithSource; const propertyRead = (interpolationWrapper.ast as e.Interpolation).expressions[0]; const target = res.getExpressionTarget(propertyRead); expect(target).toBe(null); }); it('should not resolve a `this` access to a template variable', () => { const template = parseTemplate(`<ng-template let-value>{{this.value}}</ng-template>`, ''); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const templateNode = template.nodes[0] as a.Template; const interpolationWrapper = (templateNode.children[0] as a.BoundText).value as e.ASTWithSource; const propertyRead = (interpolationWrapper.ast as e.Interpolation).expressions[0]; const target = res.getExpressionTarget(propertyRead); expect(target).toBe(null); }); it('should not resolve a `this` access to a `@let` declaration', () => { const template = parseTemplate( ` @let value = 1; {{this.value}} `, '', ); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const interpolationWrapper = (template.nodes[1] as a.BoundText).value as e.ASTWithSource; const propertyRead = (interpolationWrapper.ast as e.Interpolation).expressions[0]; const target = res.getExpressionTarget(propertyRead); expect(target).toBe(null); }); it('should resolve the definition node of let declarations', () => { const template = parseTemplate( ` @if (true) { @let one = 1; } @if (true) { @let two = 2; } `, '', ); const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>()); const res = binder.bind({template: template.nodes}); const firstBranch = (template.nodes[0] as a.IfBlock).branches[0]; const firstLet = firstBranch.children[0] as a.LetDeclaration; const secondBranch = (template.nodes[1] as a.IfBlock).branches[0]; const secondLet = secondBranch.children[0] as a.LetDeclaration; expect(res.getDefinitionNodeOfSymbol(firstLet)).toBe(firstBranch); expect(res.getDefinitionNodeOfSymbol(secondLet)).toBe(secondBranch); });
{ "end_byte": 15593, "start_byte": 7553, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/binding_spec.ts" }
angular/packages/compiler/test/render3/view/binding_spec.ts_15597_19267
describe('matching inputs to consuming directives', () => { it('should work for bound attributes', () => { const template = parseTemplate('<div hasInput [inputBinding]="myValue"></div>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const el = template.nodes[0] as a.Element; const attr = el.inputs[0]; const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta; expect(consumer.name).toBe('HasInput'); }); it('should work for text attributes on elements', () => { const template = parseTemplate('<div hasInput inputBinding="text"></div>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const el = template.nodes[0] as a.Element; const attr = el.attributes[1]; const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta; expect(consumer.name).toBe('HasInput'); }); it('should work for text attributes on templates', () => { const template = parseTemplate( '<ng-template hasInput inputBinding="text"></ng-template>', '', {}, ); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const el = template.nodes[0] as a.Element; const attr = el.attributes[1]; const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta; expect(consumer.name).toBe('HasInput'); }); it('should not match directives on attribute bindings with the same name as an input', () => { const template = parseTemplate( '<ng-template [attr.sameSelectorAsInput]="123"></ng-template>', '', {}, ); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const el = template.nodes[0] as a.Element; const input = el.inputs[0]; const consumer = res.getConsumerOfBinding(input); expect(consumer).toEqual(el); }); it('should bind to the encompassing node when no directive input is matched', () => { const template = parseTemplate('<span dir></span>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const el = template.nodes[0] as a.Element; const attr = el.attributes[0]; const consumer = res.getConsumerOfBinding(attr); expect(consumer).toEqual(el); }); }); describe('matching outputs to consuming directives', () => { it('should work for bound events', () => { const template = parseTemplate( '<div hasOutput (outputBinding)="myHandler($event)"></div>', '', {}, ); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const el = template.nodes[0] as a.Element; const attr = el.outputs[0]; const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta; expect(consumer.name).toBe('HasOutput'); }); it('should bind to the encompassing node when no directive output is matched', () => { const template = parseTemplate('<span dir (fakeOutput)="myHandler($event)"></span>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); const el = template.nodes[0] as a.Element; const attr = el.outputs[0]; const consumer = res.getConsumerOfBinding(attr); expect(consumer).toEqual(el); }); });
{ "end_byte": 19267, "start_byte": 15597, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/binding_spec.ts" }
angular/packages/compiler/test/render3/view/binding_spec.ts_19271_28068
describe('extracting defer blocks info', () => { it('should extract top-level defer blocks', () => { const template = parseTemplate( ` @defer {<cmp-a />} @defer {<cmp-b />} <cmp-c /> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const deferBlocks = bound.getDeferBlocks(); expect(deferBlocks.length).toBe(2); }); it('should extract nested defer blocks and associated pipes', () => { const template = parseTemplate( ` @defer { {{ name | pipeA }} @defer { {{ name | pipeB }} } } @loading { @defer { {{ name | pipeC }} } {{ name | loading }} } @placeholder { @defer { {{ name | pipeD }} } {{ name | placeholder }} } @error { @defer { {{ name | pipeE }} } {{ name | error }} } {{ name | pipeF }} `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const deferBlocks = bound.getDeferBlocks(); expect(deferBlocks.length).toBe(5); // Record all pipes used within :placeholder, :loading and :error sub-blocks, // also record pipes used outside of any defer blocks. expect(bound.getEagerlyUsedPipes()).toEqual(['placeholder', 'loading', 'error', 'pipeF']); // Record *all* pipes from the template, including the ones from defer blocks. expect(bound.getUsedPipes()).toEqual([ 'pipeA', 'pipeB', 'pipeD', 'placeholder', 'pipeC', 'loading', 'pipeE', 'error', 'pipeF', ]); }); it('should identify pipes used after a nested defer block as being lazy', () => { const template = parseTemplate( ` @defer { {{ name | pipeA }} @defer { {{ name | pipeB }} } {{ name | pipeC }} } `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); expect(bound.getUsedPipes()).toEqual(['pipeA', 'pipeB', 'pipeC']); expect(bound.getEagerlyUsedPipes()).toEqual([]); }); it('should extract nested defer blocks and associated directives', () => { const template = parseTemplate( ` @defer { <img *a /> @defer { <img *b /> } } @loading { @defer { <img *c /> } <img *loading /> } @placeholder { @defer { <img *d /> } <img *placeholder /> } @error { @defer { <img *e /> } <img *error /> } <img *f /> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const deferBlocks = bound.getDeferBlocks(); expect(deferBlocks.length).toBe(5); // Record all directives used within placeholder, loading and error sub-blocks, // also record directives used outside of any defer blocks. const eagerDirs = bound.getEagerlyUsedDirectives(); expect(eagerDirs.length).toBe(4); expect(eagerDirs.map((dir) => dir.name)).toEqual([ 'DirPlaceholder', 'DirLoading', 'DirError', 'DirF', ]); // Record *all* directives from the template, including the ones from defer blocks. const allDirs = bound.getUsedDirectives(); expect(allDirs.length).toBe(9); expect(allDirs.map((dir) => dir.name)).toEqual([ 'DirA', 'DirB', 'DirD', 'DirPlaceholder', 'DirC', 'DirLoading', 'DirE', 'DirError', 'DirF', ]); }); it('should identify directives used after a nested defer block as being lazy', () => { const template = parseTemplate( ` @defer { <img *a /> @defer {<img *b />} <img *c /> } `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const allDirs = bound.getUsedDirectives().map((dir) => dir.name); const eagerDirs = bound.getEagerlyUsedDirectives().map((dir) => dir.name); expect(allDirs).toEqual(['DirA', 'DirB', 'DirC']); expect(eagerDirs).toEqual([]); }); it('should identify a trigger element that is a parent of the deferred block', () => { const template = parseTemplate( ` <div #trigger> @defer (on viewport(trigger)) {} </div> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('div'); }); it('should identify a trigger element outside of the deferred block', () => { const template = parseTemplate( ` <div> @defer (on viewport(trigger)) {} </div> <div> <div> <button #trigger></button> </div> </div> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('button'); }); it('should identify a trigger element in a parent embedded view', () => { const template = parseTemplate( ` <div *ngFor="let item of items"> <button #trigger></button> <div *ngFor="let child of item.children"> <div *ngFor="let grandchild of child.children"> @defer (on viewport(trigger)) {} </div> </div> </div> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('button'); }); it('should identify a trigger element inside the placeholder', () => { const template = parseTemplate( ` @defer (on viewport(trigger)) { main } @placeholder { <button #trigger></button> } `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('button'); }); it('should not identify a trigger inside the main content block', () => { const template = parseTemplate( ` @defer (on viewport(trigger)) {<button #trigger></button>} `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); it('should identify a trigger element on a component', () => { const template = parseTemplate( ` @defer (on viewport(trigger)) {} <comp #trigger/> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('comp'); });
{ "end_byte": 28068, "start_byte": 19271, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/binding_spec.ts" }
angular/packages/compiler/test/render3/view/binding_spec.ts_28074_35830
it('should identify a trigger element on a directive', () => { const template = parseTemplate( ` @defer (on viewport(trigger)) {} <button dir #trigger="dir"></button> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('button'); }); it('should identify an implicit trigger inside the placeholder block', () => { const template = parseTemplate( ` <div #trigger> @defer (on viewport) {} @placeholder {<button></button>} </div> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('button'); }); it('should identify an implicit trigger inside the placeholder block with comments', () => { const template = parseTemplate( ` @defer (on viewport) { main } @placeholder { <!-- before --> <button #trigger></button> <!-- after --> } `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl?.name).toBe('button'); }); it('should not identify an implicit trigger if the placeholder has multiple root nodes', () => { const template = parseTemplate( ` <div #trigger> @defer (on viewport) {} @placeholder {<button></button><div></div>} </div> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); it('should not identify an implicit trigger if there is no placeholder', () => { const template = parseTemplate( ` <div #trigger> @defer (on viewport) {} <button></button> </div> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); it('should not identify an implicit trigger if the placeholder has a single root text node', () => { const template = parseTemplate( ` <div #trigger> @defer (on viewport) {} @placeholder {hello} </div> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); it('should not identify a trigger inside a sibling embedded view', () => { const template = parseTemplate( ` <div *ngIf="cond"> <button #trigger></button> </div> @defer (on viewport(trigger)) {} `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); it('should not identify a trigger element in an embedded view inside the placeholder', () => { const template = parseTemplate( ` @defer (on viewport(trigger)) { main } @placeholder { <div *ngIf="cond"><button #trigger></button></div> } `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); it('should not identify a trigger element inside the a deferred block within the placeholder', () => { const template = parseTemplate( ` @defer (on viewport(trigger)) { main } @placeholder { @defer { <button #trigger></button> } } `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); it('should not identify a trigger element on a template', () => { const template = parseTemplate( ` @defer (on viewport(trigger)) {} <ng-template #trigger></ng-template> `, '', ); const binder = new R3TargetBinder(makeSelectorMatcher()); const bound = binder.bind({template: template.nodes}); const block = Array.from(bound.getDeferBlocks())[0]; const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!); expect(triggerEl).toBeNull(); }); }); describe('used pipes', () => { it('should record pipes used in interpolations', () => { const template = parseTemplate('{{value|date}}', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); expect(res.getUsedPipes()).toEqual(['date']); }); it('should record pipes used in bound attributes', () => { const template = parseTemplate('<person [age]="age|number"></person>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); expect(res.getUsedPipes()).toEqual(['number']); }); it('should record pipes used in bound template attributes', () => { const template = parseTemplate('<ng-template [ngIf]="obs|async"></ng-template>', '', {}); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); expect(res.getUsedPipes()).toEqual(['async']); }); it('should record pipes used in ICUs', () => { const template = parseTemplate( `<span i18n>{count|number, plural, =1 { {{value|date}} } }</span>`, '', {}, ); const binder = new R3TargetBinder(makeSelectorMatcher()); const res = binder.bind({template: template.nodes}); expect(res.getUsedPipes()).toEqual(['number', 'date']); }); }); });
{ "end_byte": 35830, "start_byte": 28074, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/binding_spec.ts" }
angular/packages/compiler/test/render3/view/i18n_spec.ts_0_969
/** * @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 i18n from '../../../src/i18n/i18n_ast'; import * as o from '../../../src/output/output_ast'; import {ParseSourceSpan} from '../../../src/parse_util'; import * as t from '../../../src/render3/r3_ast'; import {serializeI18nMessageForGetMsg} from '../../../src/render3/view/i18n/get_msg_utils'; import {serializeIcuNode} from '../../../src/render3/view/i18n/icu_serializer'; import {serializeI18nMessageForLocalize} from '../../../src/render3/view/i18n/localize_utils'; import {I18nMeta, i18nMetaToJSDoc, parseI18nMeta} from '../../../src/render3/view/i18n/meta'; import {formatI18nPlaceholderName} from '../../../src/render3/view/i18n/util'; import {LEADING_TRIVIA_CHARS} from '../../../src/render3/view/template'; import {parseR3 as parse} from './util';
{ "end_byte": 969, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/i18n_spec.ts" }
angular/packages/compiler/test/render3/view/i18n_spec.ts_971_8842
describe('Utils', () => { it('formatI18nPlaceholderName', () => { const cases = [ // input, output ['', ''], ['ICU', 'icu'], ['ICU_1', 'icu_1'], ['ICU_1000', 'icu_1000'], ['START_TAG_NG-CONTAINER', 'startTagNgContainer'], ['START_TAG_NG-CONTAINER_1', 'startTagNgContainer_1'], ['CLOSE_TAG_ITALIC', 'closeTagItalic'], ['CLOSE_TAG_BOLD_1', 'closeTagBold_1'], ]; cases.forEach(([input, output]) => { expect(formatI18nPlaceholderName(input)).toEqual(output); }); }); describe('metadata serialization', () => { it('parseI18nMeta()', () => { expect(parseI18nMeta('')).toEqual(meta()); expect(parseI18nMeta('desc')).toEqual(meta('', '', 'desc')); expect(parseI18nMeta('desc@@id')).toEqual(meta('id', '', 'desc')); expect(parseI18nMeta('meaning|desc')).toEqual(meta('', 'meaning', 'desc')); expect(parseI18nMeta('meaning|desc@@id')).toEqual(meta('id', 'meaning', 'desc')); expect(parseI18nMeta('@@id')).toEqual(meta('id', '', '')); expect(parseI18nMeta('\n ')).toEqual(meta()); expect(parseI18nMeta('\n desc\n ')).toEqual(meta('', '', 'desc')); expect(parseI18nMeta('\n desc@@id\n ')).toEqual(meta('id', '', 'desc')); expect(parseI18nMeta('\n meaning|desc\n ')).toEqual(meta('', 'meaning', 'desc')); expect(parseI18nMeta('\n meaning|desc@@id\n ')).toEqual(meta('id', 'meaning', 'desc')); expect(parseI18nMeta('\n @@id\n ')).toEqual(meta('id', '', '')); }); it('serializeI18nHead()', () => { expect(o.localizedString(meta(), [literal('')], [], []).serializeI18nHead()).toEqual({ cooked: '', raw: '', range: jasmine.any(ParseSourceSpan), }); expect( o.localizedString(meta('', '', 'desc'), [literal('')], [], []).serializeI18nHead(), ).toEqual({cooked: ':desc:', raw: ':desc:', range: jasmine.any(ParseSourceSpan)}); expect( o.localizedString(meta('id', '', 'desc'), [literal('')], [], []).serializeI18nHead(), ).toEqual({cooked: ':desc@@id:', raw: ':desc@@id:', range: jasmine.any(ParseSourceSpan)}); expect( o.localizedString(meta('', 'meaning', 'desc'), [literal('')], [], []).serializeI18nHead(), ).toEqual({ cooked: ':meaning|desc:', raw: ':meaning|desc:', range: jasmine.any(ParseSourceSpan), }); expect( o.localizedString(meta('id', 'meaning', 'desc'), [literal('')], [], []).serializeI18nHead(), ).toEqual({ cooked: ':meaning|desc@@id:', raw: ':meaning|desc@@id:', range: jasmine.any(ParseSourceSpan), }); expect( o.localizedString(meta('id', '', ''), [literal('')], [], []).serializeI18nHead(), ).toEqual({cooked: ':@@id:', raw: ':@@id:', range: jasmine.any(ParseSourceSpan)}); // Escaping colons (block markers) expect( o .localizedString(meta('id:sub_id', 'meaning', 'desc'), [literal('')], [], []) .serializeI18nHead(), ).toEqual({ cooked: ':meaning|desc@@id:sub_id:', raw: ':meaning|desc@@id\\:sub_id:', range: jasmine.any(ParseSourceSpan), }); expect( o .localizedString(meta('id', 'meaning:sub_meaning', 'desc'), [literal('')], [], []) .serializeI18nHead(), ).toEqual({ cooked: ':meaning:sub_meaning|desc@@id:', raw: ':meaning\\:sub_meaning|desc@@id:', range: jasmine.any(ParseSourceSpan), }); expect( o .localizedString(meta('id', 'meaning', 'desc:sub_desc'), [literal('')], [], []) .serializeI18nHead(), ).toEqual({ cooked: ':meaning|desc:sub_desc@@id:', raw: ':meaning|desc\\:sub_desc@@id:', range: jasmine.any(ParseSourceSpan), }); expect( o .localizedString(meta('id', 'meaning', 'desc'), [literal('message source')], [], []) .serializeI18nHead(), ).toEqual({ cooked: ':meaning|desc@@id:message source', raw: ':meaning|desc@@id:message source', range: jasmine.any(ParseSourceSpan), }); expect( o .localizedString(meta('id', 'meaning', 'desc'), [literal(':message source')], [], []) .serializeI18nHead(), ).toEqual({ cooked: ':meaning|desc@@id::message source', raw: ':meaning|desc@@id::message source', range: jasmine.any(ParseSourceSpan), }); expect( o .localizedString(meta('', '', ''), [literal('message source')], [], []) .serializeI18nHead(), ).toEqual({ cooked: 'message source', raw: 'message source', range: jasmine.any(ParseSourceSpan), }); expect( o .localizedString(meta('', '', ''), [literal(':message source')], [], []) .serializeI18nHead(), ).toEqual({ cooked: ':message source', raw: '\\:message source', range: jasmine.any(ParseSourceSpan), }); }); it('serializeI18nPlaceholderBlock()', () => { expect( o .localizedString(meta('', '', ''), [literal(''), literal('')], [literal('')], []) .serializeI18nTemplatePart(1), ).toEqual({cooked: '', raw: '', range: jasmine.any(ParseSourceSpan)}); expect( o .localizedString( meta('', '', ''), [literal(''), literal('')], [new o.LiteralPiece('abc', {} as any)], [], ) .serializeI18nTemplatePart(1), ).toEqual({cooked: ':abc:', raw: ':abc:', range: jasmine.any(ParseSourceSpan)}); expect( o .localizedString(meta('', '', ''), [literal(''), literal('message')], [literal('')], []) .serializeI18nTemplatePart(1), ).toEqual({cooked: 'message', raw: 'message', range: jasmine.any(ParseSourceSpan)}); expect( o .localizedString( meta('', '', ''), [literal(''), literal('message')], [literal('abc')], [], ) .serializeI18nTemplatePart(1), ).toEqual({cooked: ':abc:message', raw: ':abc:message', range: jasmine.any(ParseSourceSpan)}); expect( o .localizedString(meta('', '', ''), [literal(''), literal(':message')], [literal('')], []) .serializeI18nTemplatePart(1), ).toEqual({cooked: ':message', raw: '\\:message', range: jasmine.any(ParseSourceSpan)}); expect( o .localizedString( meta('', '', ''), [literal(''), literal(':message')], [literal('abc')], [], ) .serializeI18nTemplatePart(1), ).toEqual({ cooked: ':abc::message', raw: ':abc::message', range: jasmine.any(ParseSourceSpan), }); }); }); describe('jsdoc generation', () => { it('generates with description', () => { const docComment = i18nMetaToJSDoc(meta('', '', 'desc')); expect(docComment.tags.length).toBe(1); expect(docComment.tags[0]).toEqual({tagName: o.JSDocTagName.Desc, text: 'desc'}); }); it('generates with no description suppressed', () => { const docComment = i18nMetaToJSDoc(meta('', '', '')); expect(docComment.tags.length).toBe(1); expect(docComment.tags[0]).toEqual({ tagName: o.JSDocTagName.Suppress, text: '{msgDescriptions}', }); }); it('generates with description and meaning', () => { const docComment = i18nMetaToJSDoc(meta('', 'meaning', '')); expect(docComment.tags).toContain({tagName: o.JSDocTagName.Meaning, text: 'meaning'}); }); }); function meta(customId?: string, meaning?: string, description?: string): I18nMeta { return {customId, meaning, description}; } });
{ "end_byte": 8842, "start_byte": 971, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/i18n_spec.ts" }
angular/packages/compiler/test/render3/view/i18n_spec.ts_8844_11049
describe('serializeI18nMessageForGetMsg', () => { const serialize = (input: string): string => { const tree = parse(`<div i18n>${input}</div>`); const root = tree.nodes[0] as t.Element; return serializeI18nMessageForGetMsg(root.i18n as i18n.Message); }; it('should serialize plain text for `GetMsg()`', () => { expect(serialize('Some text')).toEqual('Some text'); }); it('should serialize text with interpolation for `GetMsg()`', () => { expect(serialize('Some text {{ valueA }} and {{ valueB + valueC }}')).toEqual( 'Some text {$interpolation} and {$interpolation_1}', ); }); it('should serialize interpolation with named placeholder for `GetMsg()`', () => { expect(serialize('{{ valueB + valueC // i18n(ph="PLACEHOLDER NAME") }}')).toEqual( '{$placeholderName}', ); }); it('should serialize content with HTML tags for `GetMsg()`', () => { expect(serialize('A <span>B<div>C</div></span> D')).toEqual( 'A {$startTagSpan}B{$startTagDiv}C{$closeTagDiv}{$closeTagSpan} D', ); }); it('should serialize simple ICU for `GetMsg()`', () => { expect(serialize('{age, plural, 10 {ten} other {other}}')).toEqual( '{VAR_PLURAL, plural, 10 {ten} other {other}}', ); }); it('should serialize nested ICUs for `GetMsg()`', () => { expect( serialize('{age, plural, 10 {ten {size, select, 1 {one} 2 {two} other {2+}}} other {other}}'), ).toEqual( '{VAR_PLURAL, plural, 10 {ten {VAR_SELECT, select, 1 {one} 2 {two} other {2+}}} other {other}}', ); }); it('should serialize ICU with nested HTML for `GetMsg()`', () => { expect(serialize('{age, plural, 10 {<b>ten</b>} other {<div class="A">other</div>}}')).toEqual( '{VAR_PLURAL, plural, 10 {{START_BOLD_TEXT}ten{CLOSE_BOLD_TEXT}} other {{START_TAG_DIV}other{CLOSE_TAG_DIV}}}', ); }); it('should serialize ICU with nested HTML containing further ICUs for `GetMsg()`', () => { expect( serialize( '{gender, select, male {male} female {female} other {other}}<div>{gender, select, male {male} female {female} other {other}}</div>', ), ).toEqual('{$icu}{$startTagDiv}{$icu}{$closeTagDiv}'); }); });
{ "end_byte": 11049, "start_byte": 8844, "url": "https://github.com/angular/angular/blob/main/packages/compiler/test/render3/view/i18n_spec.ts" }