diff --git a/dev-infra/ts-circular-dependencies/analyzer.ts b/dev-infra/ts-circular-dependencies/analyzer.ts index 76aa7ab0d324f..079602bebabe2 100644 --- a/dev-infra/ts-circular-dependencies/analyzer.ts +++ b/dev-infra/ts-circular-dependencies/analyzer.ts @@ -13,7 +13,7 @@ import * as ts from 'typescript'; import {getFileStatus} from './file_system'; import {getModuleReferences} from './parser'; -export type ModuleResolver = (specifier: string) => string | null; +export type ModuleResolver = (specifier: string) => string|null; /** * Reference chains describe a sequence of source files which are connected through imports. @@ -69,7 +69,7 @@ export class Analyzer { getSourceFile(filePath: string): ts.SourceFile { const resolvedPath = resolve(filePath); if (this._sourceFileCache.has(resolvedPath)) { - return this._sourceFileCache.get(resolvedPath) !; + return this._sourceFileCache.get(resolvedPath)!; } const fileContent = readFileSync(resolvedPath, 'utf8'); const sourceFile = @@ -105,7 +105,7 @@ export class Analyzer { if (!this.unresolvedFiles.has(originFilePath)) { this.unresolvedFiles.set(originFilePath, [specifier]); } - this.unresolvedFiles.get(originFilePath) !.push(specifier); + this.unresolvedFiles.get(originFilePath)!.push(specifier); } /** Resolves the given import specifier to the corresponding source file. */ diff --git a/dev-infra/utils/config.ts b/dev-infra/utils/config.ts index 78b165d223419..d3893d404c556 100644 --- a/dev-infra/utils/config.ts +++ b/dev-infra/utils/config.ts @@ -44,4 +44,6 @@ export function getAngularDevConfig(): DevInfraConfig { * Interface exressing the expected structure of the DevInfraConfig. * Allows for providing a typing for a part of the config to read. */ -export interface DevInfraConfig { [K: string]: T; } +export interface DevInfraConfig { + [K: string]: T; +} diff --git a/goldens/public-api/core/core.d.ts b/goldens/public-api/core/core.d.ts index bdb2bf34df06f..b123b36d35284 100644 --- a/goldens/public-api/core/core.d.ts +++ b/goldens/public-api/core/core.d.ts @@ -1064,7 +1064,7 @@ export declare function ɵɵstyleSanitizer(sanitizer: StyleSanitizeFn | null): v export declare function ɵɵtemplate(index: number, templateFn: ComponentTemplate | null, decls: number, vars: number, tagName?: string | null, attrsIndex?: number | null, localRefsIndex?: number | null, localRefExtractor?: LocalRefExtractor): void; -export declare function ɵɵtemplateRefExtractor(tNode: TNode, currentView: ɵangular_packages_core_core_bp): TemplateRef | null; +export declare function ɵɵtemplateRefExtractor(tNode: TNode, currentView: ɵangular_packages_core_core_bo): TemplateRef | null; export declare function ɵɵtext(index: number, value?: string): void; diff --git a/modules/benchmarks/src/bootstrap_ng2.ts b/modules/benchmarks/src/bootstrap_ng2.ts index ff8eb4d105ff6..5bd0a5c803424 100644 --- a/modules/benchmarks/src/bootstrap_ng2.ts +++ b/modules/benchmarks/src/bootstrap_ng2.ts @@ -8,77 +8,79 @@ (function(global: any) { - writeScriptTag('/all/benchmarks/vendor/core.js'); - writeScriptTag('/all/benchmarks/vendor/zone.js'); - writeScriptTag('/all/benchmarks/vendor/long-stack-trace-zone.js'); - writeScriptTag('/all/benchmarks/vendor/system.src.js'); - writeScriptTag('/all/benchmarks/vendor/Reflect.js', 'benchmarksBootstrap()'); +writeScriptTag('/all/benchmarks/vendor/core.js'); +writeScriptTag('/all/benchmarks/vendor/zone.js'); +writeScriptTag('/all/benchmarks/vendor/long-stack-trace-zone.js'); +writeScriptTag('/all/benchmarks/vendor/system.src.js'); +writeScriptTag('/all/benchmarks/vendor/Reflect.js', 'benchmarksBootstrap()'); - (global).benchmarksBootstrap = benchmarksBootstrap; +(global).benchmarksBootstrap = benchmarksBootstrap; - function benchmarksBootstrap() { - // check query param - const useBundles = location.search.indexOf('bundles=false') == -1; - if (useBundles) { - System.config({ - defaultJSExtensions: true, - map: { - '@angular/core': '/packages-dist/core/bundles/core.umd.js', - '@angular/animations': '/packages-dist/common/bundles/animations.umd.js', - '@angular/platform-browser/animations': - '/packages-dist/platform-browser/bundles/platform-browser-animations.umd.js', - '@angular/common': '/packages-dist/common/bundles/common.umd.js', - '@angular/forms': '/packages-dist/forms/bundles/forms.umd.js', - '@angular/compiler': '/packages-dist/compiler/bundles/compiler.umd.js', - '@angular/platform-browser': - '/packages-dist/platform-browser/bundles/platform-browser.umd.js', - '@angular/platform-browser-dynamic': - '/packages-dist/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', - '@angular/http': '/packages-dist/http/bundles/http.umd.js', - '@angular/upgrade': '/packages-dist/upgrade/bundles/upgrade.umd.js', - '@angular/router': '/packages-dist/router/bundles/router.umd.js', - 'rxjs': '/all/benchmarks/vendor/rxjs', - }, - packages: { - 'rxjs/ajax': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs/operators': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs/testing': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs/websocket': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs': {main: 'index.js', defaultExtension: 'js'}, - } - }); - } else { - console.warn( - 'Not using the Angular bundles. Don\'t use this configuration for e2e/performance tests!'); +function benchmarksBootstrap() { + // check query param + const useBundles = location.search.indexOf('bundles=false') == -1; + if (useBundles) { + System.config({ + defaultJSExtensions: true, + map: { + '@angular/core': '/packages-dist/core/bundles/core.umd.js', + '@angular/animations': '/packages-dist/common/bundles/animations.umd.js', + '@angular/platform-browser/animations': + '/packages-dist/platform-browser/bundles/platform-browser-animations.umd.js', + '@angular/common': '/packages-dist/common/bundles/common.umd.js', + '@angular/forms': '/packages-dist/forms/bundles/forms.umd.js', + '@angular/compiler': '/packages-dist/compiler/bundles/compiler.umd.js', + '@angular/platform-browser': + '/packages-dist/platform-browser/bundles/platform-browser.umd.js', + '@angular/platform-browser-dynamic': + '/packages-dist/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', + '@angular/http': '/packages-dist/http/bundles/http.umd.js', + '@angular/upgrade': '/packages-dist/upgrade/bundles/upgrade.umd.js', + '@angular/router': '/packages-dist/router/bundles/router.umd.js', + 'rxjs': '/all/benchmarks/vendor/rxjs', + }, + packages: { + 'rxjs/ajax': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs/operators': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs/testing': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs/websocket': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs': {main: 'index.js', defaultExtension: 'js'}, + } + }); + } else { + console.warn( + 'Not using the Angular bundles. Don\'t use this configuration for e2e/performance tests!'); - System.config({ - defaultJSExtensions: true, - map: {'@angular': '/all/@angular', 'rxjs': '/all/benchmarks/vendor/rxjs'}, - packages: { - '@angular/core': {main: 'index.js', defaultExtension: 'js'}, - '@angular/animations': {main: 'index.js', defaultExtension: 'js'}, - '@angular/platform-browser/animations': {main: 'index.js', defaultExtension: 'js'}, - '@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, - '@angular/router': {main: 'index.js', defaultExtension: 'js'}, - '@angular/common': {main: 'index.js', defaultExtension: 'js'}, - '@angular/forms': {main: 'index.js', defaultExtension: 'js'}, - '@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'}, - '@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'}, - '@angular/upgrade': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs/ajax': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs/operators': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs/testing': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs/websocket': {main: 'index.js', defaultExtension: 'js'}, - 'rxjs': {main: 'index.js', defaultExtension: 'js'}, - } - }); - } - - // BOOTSTRAP the app! - System.import('index').then(function(m: any) { m.main(); }, console.error.bind(console)); + System.config({ + defaultJSExtensions: true, + map: {'@angular': '/all/@angular', 'rxjs': '/all/benchmarks/vendor/rxjs'}, + packages: { + '@angular/core': {main: 'index.js', defaultExtension: 'js'}, + '@angular/animations': {main: 'index.js', defaultExtension: 'js'}, + '@angular/platform-browser/animations': {main: 'index.js', defaultExtension: 'js'}, + '@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, + '@angular/router': {main: 'index.js', defaultExtension: 'js'}, + '@angular/common': {main: 'index.js', defaultExtension: 'js'}, + '@angular/forms': {main: 'index.js', defaultExtension: 'js'}, + '@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'}, + '@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'}, + '@angular/upgrade': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs/ajax': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs/operators': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs/testing': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs/websocket': {main: 'index.js', defaultExtension: 'js'}, + 'rxjs': {main: 'index.js', defaultExtension: 'js'}, + } + }); } - function writeScriptTag(scriptUrl: string, onload?: string) { - document.write(``); - } + // BOOTSTRAP the app! + System.import('index').then(function(m: any) { + m.main(); + }, console.error.bind(console)); +} + +function writeScriptTag(scriptUrl: string, onload?: string) { + document.write(``); +} }(window)); diff --git a/modules/benchmarks/src/bootstrap_plain.ts b/modules/benchmarks/src/bootstrap_plain.ts index b2c62c53ae679..dcc711f93273c 100644 --- a/modules/benchmarks/src/bootstrap_plain.ts +++ b/modules/benchmarks/src/bootstrap_plain.ts @@ -8,24 +8,24 @@ (function(global: any) { - writeScriptTag('/all/benchmarks/vendor/core.js'); - writeScriptTag('/all/benchmarks/vendor/system.src.js', 'benchmarksBootstrap()'); +writeScriptTag('/all/benchmarks/vendor/core.js'); +writeScriptTag('/all/benchmarks/vendor/system.src.js', 'benchmarksBootstrap()'); - (global).benchmarksBootstrap = benchmarksBootstrap; +(global).benchmarksBootstrap = benchmarksBootstrap; - function benchmarksBootstrap() { - System.config({ - defaultJSExtensions: true, - map: {'incremental-dom': '/all/benchmarks/vendor/incremental-dom-cjs.js'} - }); +function benchmarksBootstrap() { + System.config({ + defaultJSExtensions: true, + map: {'incremental-dom': '/all/benchmarks/vendor/incremental-dom-cjs.js'} + }); - // BOOTSTRAP the app! - System.import('index').then(function(m: any) { - m.main && m.main(); - }, console.error.bind(console)); - } + // BOOTSTRAP the app! + System.import('index').then(function(m: any) { + m.main && m.main(); + }, console.error.bind(console)); +} - function writeScriptTag(scriptUrl: string, onload?: string) { - document.write(``); - } +function writeScriptTag(scriptUrl: string, onload?: string) { + document.write(``); +} }(window)); diff --git a/modules/benchmarks/src/change_detection/change_detection.e2e-spec.ts b/modules/benchmarks/src/change_detection/change_detection.e2e-spec.ts index 4872bfee5352a..33ba44bce599f 100644 --- a/modules/benchmarks/src/change_detection/change_detection.e2e-spec.ts +++ b/modules/benchmarks/src/change_detection/change_detection.e2e-spec.ts @@ -13,7 +13,7 @@ import {openBrowser, verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('change detection benchmark', () => { afterEach(verifyNoBrowserErrors); - it(`should render and update`, async() => { + it(`should render and update`, async () => { openBrowser({ url: '', ignoreBrowserSynchronization: true, diff --git a/modules/benchmarks/src/change_detection/change_detection.perf-spec.ts b/modules/benchmarks/src/change_detection/change_detection.perf-spec.ts index 6251659446592..f450dc5bc8e1c 100644 --- a/modules/benchmarks/src/change_detection/change_detection.perf-spec.ts +++ b/modules/benchmarks/src/change_detection/change_detection.perf-spec.ts @@ -31,15 +31,14 @@ const UpdateWorker: Worker = { // name. We determine the name of the Bazel package where this test runs from the current test // target. The Bazel target // looks like: "//modules/benchmarks/src/change_detection/{pkg_name}:{target_name}". -const testPackageName = process.env['BAZEL_TARGET'] !.split(':')[0].split('/').pop(); +const testPackageName = process.env['BAZEL_TARGET']!.split(':')[0].split('/').pop(); describe('change detection benchmark perf', () => { - afterEach(verifyNoBrowserErrors); [UpdateWorker].forEach((worker) => { describe(worker.id, () => { - it(`should run benchmark for ${testPackageName}`, async() => { + it(`should run benchmark for ${testPackageName}`, async () => { await runChangeDetectionBenchmark({ id: `change_detection.${testPackageName}.${worker.id}`, url: '/', diff --git a/modules/benchmarks/src/change_detection/transplanted_views/init.ts b/modules/benchmarks/src/change_detection/transplanted_views/init.ts index 600d862438194..53b6ef336a004 100644 --- a/modules/benchmarks/src/change_detection/transplanted_views/init.ts +++ b/modules/benchmarks/src/change_detection/transplanted_views/init.ts @@ -35,7 +35,9 @@ export function init(moduleRef: NgModuleRef) { appRef.tick(); } - function detectChanges() { appRef.tick(); } + function detectChanges() { + appRef.tick(); + } function noop() {} } diff --git a/modules/benchmarks/src/change_detection/transplanted_views/transplanted_views.ts b/modules/benchmarks/src/change_detection/transplanted_views/transplanted_views.ts index b74e47b8c7089..da7746640c267 100644 --- a/modules/benchmarks/src/change_detection/transplanted_views/transplanted_views.ts +++ b/modules/benchmarks/src/change_detection/transplanted_views/transplanted_views.ts @@ -40,10 +40,14 @@ export class InsertionComponent { @Input() template !: TemplateRef<{}>; views: any[] = []; @Input() - set viewCount(n: number) { this.views = n > 0 ? newArray(n) : []; } + set viewCount(n: number) { + this.views = n > 0 ? newArray(n) : []; + } // use trackBy to ensure profile isn't affected by the cost to refresh ngFor. - trackByIndex(index: number, item: any) { return index; } + trackByIndex(index: number, item: any) { + return index; + } } @NgModule({ diff --git a/modules/benchmarks/src/change_detection/util.ts b/modules/benchmarks/src/change_detection/util.ts index 7205f7245479d..25944f727c16c 100644 --- a/modules/benchmarks/src/change_detection/util.ts +++ b/modules/benchmarks/src/change_detection/util.ts @@ -15,7 +15,7 @@ export function newArray(size: number, value: T): T[]; export function newArray(size: number, value?: T): T[] { const list: T[] = []; for (let i = 0; i < size; i++) { - list.push(value !); + list.push(value!); } return list; } diff --git a/modules/benchmarks/src/class_bindings/app.component.ts b/modules/benchmarks/src/class_bindings/app.component.ts index 73ffcaae3b077..27aa5e20f9521 100644 --- a/modules/benchmarks/src/class_bindings/app.component.ts +++ b/modules/benchmarks/src/class_bindings/app.component.ts @@ -27,12 +27,16 @@ export class AppComponent { } } - create() { this.show = true; } + create() { + this.show = true; + } update() { this.msg = this.msg === 'hello' ? 'bye' : 'hello'; this.list[0].text = this.msg; } - destroy() { this.show = false; } + destroy() { + this.show = false; + } } diff --git a/modules/benchmarks/src/class_bindings/class_bindings.perf-spec.ts b/modules/benchmarks/src/class_bindings/class_bindings.perf-spec.ts index 41486c5ce64ac..e21d27dadf2a8 100644 --- a/modules/benchmarks/src/class_bindings/class_bindings.perf-spec.ts +++ b/modules/benchmarks/src/class_bindings/class_bindings.perf-spec.ts @@ -10,8 +10,7 @@ import {$, browser} from 'protractor'; import {runBenchmark} from '../../../e2e_util/perf_util'; describe('class bindings perf', () => { - - it('should work for update', async() => { + it('should work for update', async () => { browser.rootEl = '#root'; await runBenchmark({ id: 'create', @@ -23,7 +22,7 @@ describe('class bindings perf', () => { }); }); - it('should work for update', async() => { + it('should work for update', async () => { browser.rootEl = '#root'; await runBenchmark({ id: 'update', @@ -34,5 +33,4 @@ describe('class bindings perf', () => { work: () => $('#update').click() }); }); - }); diff --git a/modules/benchmarks/src/expanding_rows/benchmark.ts b/modules/benchmarks/src/expanding_rows/benchmark.ts index 2fc9492f0a8a7..df18ff4a28a70 100644 --- a/modules/benchmarks/src/expanding_rows/benchmark.ts +++ b/modules/benchmarks/src/expanding_rows/benchmark.ts @@ -31,23 +31,32 @@ import {BenchmarkableExpandingRowModule} from './benchmarkable_expanding_row_mod `, }) export class InitializationRoot implements AfterViewInit { - @ViewChild(BenchmarkableExpandingRow, {static: true}) - expandingRow !: BenchmarkableExpandingRow; + @ViewChild(BenchmarkableExpandingRow, {static: true}) expandingRow!: BenchmarkableExpandingRow; ngAfterViewInit() {} - reset() { this.expandingRow.reset(); } + reset() { + this.expandingRow.reset(); + } - init() { this.expandingRow.init(); } + init() { + this.expandingRow.init(); + } async runAll() { - await execTimed('initialization_benchmark', async() => { await this.doInit(); }); + await execTimed('initialization_benchmark', async () => { + await this.doInit(); + }); } - async handleInitClick() { await this.doInit(); } + async handleInitClick() { + await this.doInit(); + } private async doInit() { - await execTimed('initial_load', async() => { this.expandingRow.init(); }); + await execTimed('initial_load', async () => { + this.expandingRow.init(); + }); } } @@ -74,5 +83,9 @@ export async function execTimed(description: string, func: () => Promise) } export async function nextTick(delay = 1) { - return new Promise((res, rej) => { setTimeout(() => { res(); }, delay); }); + return new Promise((res, rej) => { + setTimeout(() => { + res(); + }, delay); + }); } diff --git a/modules/benchmarks/src/expanding_rows/benchmark_module.ts b/modules/benchmarks/src/expanding_rows/benchmark_module.ts index 6f13981f6067d..6a51767018b12 100644 --- a/modules/benchmarks/src/expanding_rows/benchmark_module.ts +++ b/modules/benchmarks/src/expanding_rows/benchmark_module.ts @@ -26,7 +26,9 @@ import {Component, ErrorHandler, Injectable, NgModule} from '@angular/core'; export class BenchmarkArea { } -declare interface ExtendedWindow extends Window { benchmarkErrors?: string[]; } +declare interface ExtendedWindow extends Window { + benchmarkErrors?: string[]; +} const extendedWindow = window as ExtendedWindow; @Injectable({providedIn: 'root'}) diff --git a/modules/benchmarks/src/expanding_rows/benchmarkable_expanding_row.ts b/modules/benchmarks/src/expanding_rows/benchmarkable_expanding_row.ts index 8c70934388bbc..a677ef152e4f3 100644 --- a/modules/benchmarks/src/expanding_rows/benchmarkable_expanding_row.ts +++ b/modules/benchmarks/src/expanding_rows/benchmarkable_expanding_row.ts @@ -44,12 +44,12 @@ export interface MlbTeam { }) export class BenchmarkableExpandingRow { // TODO(b/109816955): remove '!', see go/strict-prop-init-fix. - showExpandingRow !: boolean; + showExpandingRow!: boolean; // TODO(b/109816955): remove '!', see go/strict-prop-init-fix. - teams !: MlbTeam[]; + teams!: MlbTeam[]; // TODO(b/109816955): remove '!', see go/strict-prop-init-fix. - private fakeTeams !: MlbTeam[]; + private fakeTeams!: MlbTeam[]; init(): void { this.teams = this.fakeTeams; diff --git a/modules/benchmarks/src/expanding_rows/expanding_row.ts b/modules/benchmarks/src/expanding_rows/expanding_row.ts index da6da38bb8543..aadfded4e639a 100644 --- a/modules/benchmarks/src/expanding_rows/expanding_row.ts +++ b/modules/benchmarks/src/expanding_rows/expanding_row.ts @@ -112,15 +112,14 @@ export class ExpandingRow { * The identifier for this node provided by the user code. We need this * while we are emitting onToggle event. */ - @Input() rowId !: string; + @Input() rowId!: string; /** * An ElementRef to the main element in this component. We need a reference * to this element to compute the height. The height of cfc-expanding-row * is used in [cfcExpandingRowHost] directive for scroll adjustments. */ - @ViewChild('expandingRowMainElement', {static: true}) - expandingRowMainElement !: ElementRef; + @ViewChild('expandingRowMainElement', {static: true}) expandingRowMainElement!: ElementRef; /** * This @Output event emitter will be triggered when the user expands or @@ -145,7 +144,9 @@ export class ExpandingRow { } /** TS getter for isExpanded property. */ - get isExpanded(): boolean { return this.isExpandedInternal; } + get isExpanded(): boolean { + return this.isExpandedInternal; + } /** Triggered when isExpanded property changes. */ isExpandedChange = new EventEmitter(); @@ -164,7 +165,9 @@ export class ExpandingRow { } /** TS getter for isFocused property. */ - get isFocused(): boolean { return this.isFocusedInternal; } + get isFocused(): boolean { + return this.isFocusedInternal; + } /** The index of the row in the context of the entire collection. */ set index(value: number) { @@ -178,7 +181,9 @@ export class ExpandingRow { } /** TS getter for index property. */ - get index(): number { return this.indexInternal; } + get index(): number { + return this.indexInternal; + } /** * We should probably rename this to summaryContentChild. Because technically @@ -188,7 +193,7 @@ export class ExpandingRow { * component is not in the same file as ExpandingRow. */ // TODO(b/109816955): remove '!', see go/strict-prop-init-fix. - summaryViewChild !: ExpandingRowSummary; + summaryViewChild!: ExpandingRowSummary; /** * We compute the collapsed height (which is just height of @@ -205,7 +210,7 @@ export class ExpandingRow { /** Internal storage for index public property. */ // TODO(b/109816955): remove '!', see go/strict-prop-init-fix. - private indexInternal !: number; + private indexInternal!: number; /** * This holds a reference to [cfcExpandingRowHost] directive. We need @@ -233,7 +238,9 @@ export class ExpandingRow { * When user tabs into child cfc-expanding-row-summary component. This method * will make sure we focuse on this row, and blur on previously focused row. */ - handleSummaryFocus(): void { this.focus(); } + handleSummaryFocus(): void { + this.focus(); + } /** * cfc-expanding-row-details-caption component will call this function to @@ -256,7 +263,9 @@ export class ExpandingRow { * Gets the height of this component. This height is used in parent * [cfcExpandingRowHost] directive to compute scroll adjustment. */ - getHeight(): number { return this.expandingRowMainElement.nativeElement.offsetHeight; } + getHeight(): number { + return this.expandingRowMainElement.nativeElement.offsetHeight; + } /** * Expands this row. This will notify the host so that it can collapse @@ -268,7 +277,9 @@ export class ExpandingRow { this.expandingRowHost.handleRowExpand(this); // setTimeout here makes sure we scroll this row into view after animation. - setTimeout(() => { this.expandingRowMainElement.nativeElement.focus(); }); + setTimeout(() => { + this.expandingRowMainElement.nativeElement.focus(); + }); this.onToggle.emit({rowId: this.rowId, isExpand: true}); } @@ -305,7 +316,9 @@ export class ExpandingRow { // Summary child is not present currently. We need to NG2 to update the // template. - setTimeout(() => { this.summaryViewChild.focus(); }); + setTimeout(() => { + this.summaryViewChild.focus(); + }); } /** diff --git a/modules/benchmarks/src/expanding_rows/expanding_row_details_caption.ts b/modules/benchmarks/src/expanding_rows/expanding_row_details_caption.ts index 15f77c95db13b..00cbe534fa5e9 100644 --- a/modules/benchmarks/src/expanding_rows/expanding_row_details_caption.ts +++ b/modules/benchmarks/src/expanding_rows/expanding_row_details_caption.ts @@ -49,5 +49,7 @@ export class ExpandingRowDetailsCaption implements OnDestroy { } /** When component is destroyed, unlisten to isExpanded. */ - ngOnDestroy(): void { this.onDestroy.next(); } + ngOnDestroy(): void { + this.onDestroy.next(); + } } diff --git a/modules/benchmarks/src/expanding_rows/expanding_row_details_content.ts b/modules/benchmarks/src/expanding_rows/expanding_row_details_content.ts index 2ab182a39ca3f..557f6f2731966 100644 --- a/modules/benchmarks/src/expanding_rows/expanding_row_details_content.ts +++ b/modules/benchmarks/src/expanding_rows/expanding_row_details_content.ts @@ -35,10 +35,13 @@ export class ExpandingRowDetailsContent implements OnDestroy { * hide this component if the row is collapsed. */ constructor(@Host() public expandingRow: ExpandingRow, changeDetectorRef: ChangeDetectorRef) { - this.isExpandedChangeSubscription = - this.expandingRow.isExpandedChange.subscribe(() => { changeDetectorRef.markForCheck(); }); + this.isExpandedChangeSubscription = this.expandingRow.isExpandedChange.subscribe(() => { + changeDetectorRef.markForCheck(); + }); } /** Unsubscribe from changes in parent isExpanded property. */ - ngOnDestroy(): void { this.isExpandedChangeSubscription.unsubscribe(); } + ngOnDestroy(): void { + this.isExpandedChangeSubscription.unsubscribe(); + } } diff --git a/modules/benchmarks/src/expanding_rows/expanding_row_host.ts b/modules/benchmarks/src/expanding_rows/expanding_row_host.ts index 52bf88ecb8f52..195013c43004a 100644 --- a/modules/benchmarks/src/expanding_rows/expanding_row_host.ts +++ b/modules/benchmarks/src/expanding_rows/expanding_row_host.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {AfterContentInit, AfterViewInit, ChangeDetectionStrategy, Component, ContentChildren, ElementRef, EventEmitter, HostListener, Input, OnDestroy, Output, QueryList, ViewChild, forwardRef} from '@angular/core'; +import {AfterContentInit, AfterViewInit, ChangeDetectionStrategy, Component, ContentChildren, ElementRef, EventEmitter, forwardRef, HostListener, Input, OnDestroy, Output, QueryList, ViewChild} from '@angular/core'; import {Subscription} from 'rxjs'; import {EXPANDING_ROW_HOST_INJECTION_TOKEN, ExpandingRow, ExpandingRowHostBase} from './expanding_row'; @@ -26,7 +26,7 @@ export const EXPANDING_ROW_KEYPRESS_THORTTLE_MS = 50; * This type union is created to make arguments of handleUpOrDownPress* * methods in ExpandingRowHost class more readable. */ -type UpOrDown = 'up' | 'down'; +type UpOrDown = 'up'|'down'; /** * This is the wrapper directive for the cfc-expanding-row components. Note that @@ -48,8 +48,7 @@ type UpOrDown = 'up' | 'down'; changeDetection: ChangeDetectionStrategy.OnPush, providers: [{provide: EXPANDING_ROW_HOST_INJECTION_TOKEN, useExisting: ExpandingRowHost}], }) -export class ExpandingRowHost implements AfterViewInit, - OnDestroy, ExpandingRowHostBase { +export class ExpandingRowHost implements AfterViewInit, OnDestroy, ExpandingRowHostBase { /** * An HTML selector (e.g. "body") for the scroll element. We need this to * make some scroll adjustments. @@ -71,11 +70,10 @@ export class ExpandingRowHost implements AfterViewInit, @Output() onPrepend = new EventEmitter(); /** A reference to the last focusable element in list of expanding rows. */ - @ViewChild('lastFocusable', {static: true}) lastFocusableElement !: ElementRef; + @ViewChild('lastFocusable', {static: true}) lastFocusableElement!: ElementRef; /** A reference to the first focusable element in list of expanding rows. */ - @ViewChild('firstFocusable', {static: true}) - firstFocusableElement !: ElementRef; + @ViewChild('firstFocusable', {static: true}) firstFocusableElement!: ElementRef; /** * A reference to all child cfc-expanding-row elements. We will need for @@ -83,7 +81,7 @@ export class ExpandingRowHost implements AfterViewInit, * which row is previous row when user presses "left arrow" on a focused row. */ @ContentChildren(forwardRef(() => ExpandingRow), {descendants: true}) - contentRows !: QueryList; + contentRows!: QueryList; /** * Keeps track of the last row that had focus before focus left the list @@ -122,7 +120,7 @@ export class ExpandingRowHost implements AfterViewInit, /** Subscription to changes in the expanding rows. */ // TODO(b/109816955): remove '!', see go/strict-prop-init-fix. - private rowChangeSubscription !: Subscription; + private rowChangeSubscription!: Subscription; /** * When component initializes we need to attach click listener to the root @@ -138,8 +136,9 @@ export class ExpandingRowHost implements AfterViewInit, clickRootElement.addEventListener('mouseup', this.handleRootMouseUpBound); - this.rowChangeSubscription = - this.contentRows.changes.subscribe(() => { this.recalcRowIndexes(); }); + this.rowChangeSubscription = this.contentRows.changes.subscribe(() => { + this.recalcRowIndexes(); + }); this.recalcRowIndexes(); } @@ -256,13 +255,17 @@ export class ExpandingRowHost implements AfterViewInit, * Function that is called by expanding row summary to focus on the last * focusable element before the list of expanding rows. */ - focusOnPreviousFocusableElement(): void { this.lastFocusedRow = this.focusedRow; } + focusOnPreviousFocusableElement(): void { + this.lastFocusedRow = this.focusedRow; + } /** * Function that is called by expanding row summary to focus on the next * focusable element after the list of expanding rows. */ - focusOnNextFocusableElement(): void { this.lastFocusedRow = this.focusedRow; } + focusOnNextFocusableElement(): void { + this.lastFocusedRow = this.focusedRow; + } /** * Handles keydown event on the host. We are just concerned with up, @@ -275,7 +278,8 @@ export class ExpandingRowHost implements AfterViewInit, * - Enter: Expands the focused row. */ @HostListener('keydown', ['$event']) - handleKeyDown(event: KeyboardEvent) {} + handleKeyDown(event: KeyboardEvent) { + } /** * Recursively returns true if target HTMLElement is within a @@ -491,7 +495,10 @@ export class ExpandingRowHost implements AfterViewInit, // Updates all of the rows with their new index. private recalcRowIndexes() { let index = 0; - setTimeout( - () => { this.contentRows.forEach((row: ExpandingRow) => { row.index = index++; }); }); + setTimeout(() => { + this.contentRows.forEach((row: ExpandingRow) => { + row.index = index++; + }); + }); } } diff --git a/modules/benchmarks/src/expanding_rows/expanding_row_summary.ts b/modules/benchmarks/src/expanding_rows/expanding_row_summary.ts index e8ffb31534aa1..673e796271fc5 100644 --- a/modules/benchmarks/src/expanding_rows/expanding_row_summary.ts +++ b/modules/benchmarks/src/expanding_rows/expanding_row_summary.ts @@ -48,8 +48,7 @@ export class ExpandingRowSummary implements OnDestroy { * reference to compute collapsed height of the row. We also use this * reference for focus and blur methods below. */ - @ViewChild('expandingRowSummaryMainElement') - mainElementRef !: ElementRef; + @ViewChild('expandingRowSummaryMainElement') mainElementRef!: ElementRef; /** Subscription for changes in parent isExpanded property. */ private isExpandedSubscription: Subscription; @@ -65,11 +64,13 @@ export class ExpandingRowSummary implements OnDestroy { */ constructor(@Host() public expandingRow: ExpandingRow, changeDetectorRef: ChangeDetectorRef) { this.expandingRow.summaryViewChild = this; - this.isExpandedSubscription = - this.expandingRow.isExpandedChange.subscribe(() => { changeDetectorRef.markForCheck(); }); + this.isExpandedSubscription = this.expandingRow.isExpandedChange.subscribe(() => { + changeDetectorRef.markForCheck(); + }); - this.indexSubscription = - this.expandingRow.indexChange.subscribe(() => { changeDetectorRef.markForCheck(); }); + this.indexSubscription = this.expandingRow.indexChange.subscribe(() => { + changeDetectorRef.markForCheck(); + }); } @@ -203,5 +204,7 @@ export class ExpandingRowSummary implements OnDestroy { } /** Returns array of focusable elements within this component. */ - private getFocusableChildren(): HTMLElement[] { return []; } + private getFocusableChildren(): HTMLElement[] { + return []; + } } diff --git a/modules/benchmarks/src/expanding_rows/expanding_rows.perf-spec.ts b/modules/benchmarks/src/expanding_rows/expanding_rows.perf-spec.ts index ee4bab2193c83..316de6c5abd49 100644 --- a/modules/benchmarks/src/expanding_rows/expanding_rows.perf-spec.ts +++ b/modules/benchmarks/src/expanding_rows/expanding_rows.perf-spec.ts @@ -10,8 +10,7 @@ import {$, browser} from 'protractor'; import {runBenchmark} from '../../../e2e_util/perf_util'; describe('benchmarks', () => { - - it('should work for create', async() => { + it('should work for create', async () => { browser.rootEl = '#root'; await runBenchmark({ id: 'create', @@ -22,5 +21,4 @@ describe('benchmarks', () => { work: () => $('#init').click() }); }); - }); diff --git a/modules/benchmarks/src/expanding_rows/index_aot.ts b/modules/benchmarks/src/expanding_rows/index_aot.ts index d2318d8818f59..367e8753327cc 100644 --- a/modules/benchmarks/src/expanding_rows/index_aot.ts +++ b/modules/benchmarks/src/expanding_rows/index_aot.ts @@ -18,5 +18,5 @@ enableProdMode(); platformBrowser().bootstrapModuleFactory(ExpandingRowBenchmarkModuleNgFactory); function setMode(name: string): void { - document.querySelector('#rendererMode') !.textContent = `Render Mode: ${name}`; + document.querySelector('#rendererMode')!.textContent = `Render Mode: ${name}`; } diff --git a/modules/benchmarks/src/js-web-frameworks/js-web-frameworks.perf-spec.ts b/modules/benchmarks/src/js-web-frameworks/js-web-frameworks.perf-spec.ts index 0ed6859aa6fb0..200590588e9bd 100644 --- a/modules/benchmarks/src/js-web-frameworks/js-web-frameworks.perf-spec.ts +++ b/modules/benchmarks/src/js-web-frameworks/js-web-frameworks.perf-spec.ts @@ -24,19 +24,25 @@ const Create1KWorker: Worker = { const Delete1KWorker: Worker = { id: 'delete1K', prepare: () => $('#create1KRows').click(), - work: () => { $('#deleteAll').click(); } + work: () => { + $('#deleteAll').click(); + } }; const UpdateWorker: Worker = { id: 'update', prepare: () => $('#create1KRows').click(), - work: () => { $('#update').click(); } + work: () => { + $('#update').click(); + } }; const SwapWorker: Worker = { id: 'swap', prepare: () => $('#create1KRows').click(), - work: () => { $('#swap').click(); } + work: () => { + $('#swap').click(); + } }; // In order to make sure that we don't change the ids of the benchmarks, we need to @@ -45,15 +51,14 @@ const SwapWorker: Worker = { // name. e.g. "largeTable.ng2_switch.createDestroy". We determine the name of the // Bazel package where this test runs from the current test target. The Bazel target // looks like: "//modules/benchmarks/src/largetable/{pkg_name}:{target_name}". -const testPackageName = process.env['BAZEL_TARGET'] !.split(':')[0].split('/').pop(); +const testPackageName = process.env['BAZEL_TARGET']!.split(':')[0].split('/').pop(); describe('js-web-frameworks benchmark perf', () => { - afterEach(verifyNoBrowserErrors); [Create1KWorker, Delete1KWorker, UpdateWorker, SwapWorker].forEach((worker) => { describe(worker.id, () => { - it(`should run benchmark for ${testPackageName}`, async() => { + it(`should run benchmark for ${testPackageName}`, async () => { await runTableBenchmark({ id: `js-web-frameworks.${testPackageName}.${worker.id}`, url: '/', diff --git a/modules/benchmarks/src/js-web-frameworks/ng2/rows.ts b/modules/benchmarks/src/js-web-frameworks/ng2/rows.ts index 655c2385cddc0..e691da507c131 100644 --- a/modules/benchmarks/src/js-web-frameworks/ng2/rows.ts +++ b/modules/benchmarks/src/js-web-frameworks/ng2/rows.ts @@ -42,14 +42,16 @@ export class JsWebFrameworksComponent { constructor(private _appRef: ApplicationRef) {} - itemById(index: number, item: RowData) { return item.id; } + itemById(index: number, item: RowData) { + return item.id; + } select(itemId: number) { this.selected = itemId; this._appRef.tick(); } - delete (itemId: number) { + delete(itemId: number) { const data = this.data; for (let i = 0, l = data.length; i < l; i++) { if (data[i].id === itemId) { diff --git a/modules/benchmarks/src/largeform/largeform.e2e-spec.ts b/modules/benchmarks/src/largeform/largeform.e2e-spec.ts index 5cd7516a27689..de55e1600263a 100644 --- a/modules/benchmarks/src/largeform/largeform.e2e-spec.ts +++ b/modules/benchmarks/src/largeform/largeform.e2e-spec.ts @@ -11,10 +11,9 @@ import {$, By, element} from 'protractor'; import {openBrowser, verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('largeform benchmark', () => { - afterEach(verifyNoBrowserErrors); - it('should work for ng2', async() => { + it('should work for ng2', async () => { openBrowser({ url: '/', params: [{name: 'copies', value: 1}], diff --git a/modules/benchmarks/src/largeform/largeform.perf-spec.ts b/modules/benchmarks/src/largeform/largeform.perf-spec.ts index fe06cd8ef361a..ccab69f06521d 100644 --- a/modules/benchmarks/src/largeform/largeform.perf-spec.ts +++ b/modules/benchmarks/src/largeform/largeform.perf-spec.ts @@ -26,12 +26,11 @@ const CreateAndDestroyWorker = { }; describe('largeform benchmark spec', () => { - afterEach(verifyNoBrowserErrors); [CreateAndDestroyWorker].forEach((worker) => { describe(worker.id, () => { - it('should run for ng2', async() => { + it('should run for ng2', async () => { await runLargeFormBenchmark({url: '/', id: `largeform.ng2.${worker.id}`, worker: worker}); }); }); diff --git a/modules/benchmarks/src/largetable/incremental_dom/table.ts b/modules/benchmarks/src/largetable/incremental_dom/table.ts index 7d50f8ff2731a..6a9e60024d985 100644 --- a/modules/benchmarks/src/largetable/incremental_dom/table.ts +++ b/modules/benchmarks/src/largetable/incremental_dom/table.ts @@ -17,7 +17,9 @@ const {patch, elementOpen, elementClose, elementOpenStart, elementOpenEnd, attr, export class TableComponent { constructor(private _rootEl: any) {} - set data(data: TableCell[][]) { patch(this._rootEl, () => this._render(data)); } + set data(data: TableCell[][]) { + patch(this._rootEl, () => this._render(data)); + } private _render(data: TableCell[][]) { elementOpen('table'); diff --git a/modules/benchmarks/src/largetable/largetable.e2e-spec.ts b/modules/benchmarks/src/largetable/largetable.e2e-spec.ts index 0068b33b2a521..3b6da53085fa0 100644 --- a/modules/benchmarks/src/largetable/largetable.e2e-spec.ts +++ b/modules/benchmarks/src/largetable/largetable.e2e-spec.ts @@ -13,7 +13,7 @@ import {openBrowser, verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('largetable benchmark', () => { afterEach(verifyNoBrowserErrors); - it(`should render the table`, async() => { + it(`should render the table`, async () => { openBrowser({ url: '', ignoreBrowserSynchronization: true, diff --git a/modules/benchmarks/src/largetable/largetable.perf-spec.ts b/modules/benchmarks/src/largetable/largetable.perf-spec.ts index b78931a009f96..ffd96ece13c65 100644 --- a/modules/benchmarks/src/largetable/largetable.perf-spec.ts +++ b/modules/benchmarks/src/largetable/largetable.perf-spec.ts @@ -40,15 +40,14 @@ const UpdateWorker: Worker = { // name. e.g. "largeTable.ng2_switch.createDestroy". We determine the name of the // Bazel package where this test runs from the current test target. The Bazel target // looks like: "//modules/benchmarks/src/largetable/{pkg_name}:{target_name}". -const testPackageName = process.env['BAZEL_TARGET'] !.split(':')[0].split('/').pop(); +const testPackageName = process.env['BAZEL_TARGET']!.split(':')[0].split('/').pop(); describe('largetable benchmark perf', () => { - afterEach(verifyNoBrowserErrors); [CreateOnlyWorker, CreateAndDestroyWorker, UpdateWorker].forEach((worker) => { describe(worker.id, () => { - it(`should run benchmark for ${testPackageName}`, async() => { + it(`should run benchmark for ${testPackageName}`, async () => { await runTableBenchmark({ id: `largeTable.${testPackageName}.${worker.id}`, url: '/', diff --git a/modules/benchmarks/src/largetable/ng2/table.ts b/modules/benchmarks/src/largetable/ng2/table.ts index 55028bf29a3f4..d00f811563312 100644 --- a/modules/benchmarks/src/largetable/ng2/table.ts +++ b/modules/benchmarks/src/largetable/ng2/table.ts @@ -9,7 +9,7 @@ import {Component, Input, NgModule} from '@angular/core'; import {BrowserModule, DomSanitizer, SafeStyle} from '@angular/platform-browser'; -import {TableCell, emptyTable} from '../util'; +import {emptyTable, TableCell} from '../util'; let trustedEmptyColor: SafeStyle; let trustedGreyColor: SafeStyle; @@ -25,12 +25,15 @@ let trustedGreyColor: SafeStyle; `, }) export class TableComponent { - @Input() - data: TableCell[][] = emptyTable; + @Input() data: TableCell[][] = emptyTable; - trackByIndex(index: number, item: any) { return index; } + trackByIndex(index: number, item: any) { + return index; + } - getColor(row: number) { return row % 2 ? trustedEmptyColor : trustedGreyColor; } + getColor(row: number) { + return row % 2 ? trustedEmptyColor : trustedGreyColor; + } } @NgModule({imports: [BrowserModule], bootstrap: [TableComponent], declarations: [TableComponent]}) diff --git a/modules/benchmarks/src/largetable/ng2_switch/table.ts b/modules/benchmarks/src/largetable/ng2_switch/table.ts index 10b73f6539be0..8e1c5a7fe2bfd 100644 --- a/modules/benchmarks/src/largetable/ng2_switch/table.ts +++ b/modules/benchmarks/src/largetable/ng2_switch/table.ts @@ -9,7 +9,7 @@ import {Component, Input, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; -import {TableCell, emptyTable} from '../util'; +import {emptyTable, TableCell} from '../util'; @Component({ selector: 'largetable', @@ -22,10 +22,11 @@ import {TableCell, emptyTable} from '../util'; ` }) export class TableComponent { - @Input() - data: TableCell[][] = emptyTable; + @Input() data: TableCell[][] = emptyTable; - trackByIndex(index: number, item: any) { return index; } + trackByIndex(index: number, item: any) { + return index; + } } @NgModule({imports: [BrowserModule], bootstrap: [TableComponent], declarations: [TableComponent]}) diff --git a/modules/benchmarks/src/largetable/render3/index_aot.ts b/modules/benchmarks/src/largetable/render3/index_aot.ts index 77c3c8610dc89..6abeee67421bb 100644 --- a/modules/benchmarks/src/largetable/render3/index_aot.ts +++ b/modules/benchmarks/src/largetable/render3/index_aot.ts @@ -9,7 +9,7 @@ import {ɵrenderComponent as renderComponent} from '@angular/core'; import {bindAction, profile} from '../../util'; -import {LargeTableComponent, createDom, destroyDom} from './table'; +import {createDom, destroyDom, LargeTableComponent} from './table'; function noop() {} diff --git a/modules/benchmarks/src/largetable/render3/table.ts b/modules/benchmarks/src/largetable/render3/table.ts index 5634f68f375f7..85339a976e935 100644 --- a/modules/benchmarks/src/largetable/render3/table.ts +++ b/modules/benchmarks/src/largetable/render3/table.ts @@ -9,7 +9,7 @@ import {CommonModule} from '@angular/common'; import {Component, Input, NgModule, ɵdetectChanges} from '@angular/core'; -import {TableCell, buildTable, emptyTable} from '../util'; +import {buildTable, emptyTable, TableCell} from '../util'; @Component({ selector: 'largetable', @@ -26,12 +26,15 @@ import {TableCell, buildTable, emptyTable} from '../util'; `, }) export class LargeTableComponent { - @Input() - data: TableCell[][] = emptyTable; + @Input() data: TableCell[][] = emptyTable; - trackByIndex(index: number, item: any) { return index; } + trackByIndex(index: number, item: any) { + return index; + } - getColor(row: number) { return row % 2 ? '' : 'grey'; } + getColor(row: number) { + return row % 2 ? '' : 'grey'; + } } @NgModule({declarations: [LargeTableComponent], imports: [CommonModule]}) diff --git a/modules/benchmarks/src/old/compiler/compiler_benchmark.ts b/modules/benchmarks/src/old/compiler/compiler_benchmark.ts index 51cf1d0ffab45..9dd4572bc84b2 100644 --- a/modules/benchmarks/src/old/compiler/compiler_benchmark.ts +++ b/modules/benchmarks/src/old/compiler/compiler_benchmark.ts @@ -6,28 +6,23 @@ * found in the LICENSE file at https://angular.io/license */ +import {CompilerConfig, DirectiveResolver} from '@angular/compiler'; +import {Component, ComponentResolver, Directive, ViewContainerRef,} from '@angular/core'; +import {ViewMetadata} from '@angular/core/src/metadata/view'; import {PromiseWrapper} from '@angular/facade/src/async'; -import {Type, print} from '@angular/facade/src/lang'; +import {print, Type} from '@angular/facade/src/lang'; import {bootstrap} from '@angular/platform-browser'; import {BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter'; import {DOM} from '@angular/platform-browser/src/dom/dom_adapter'; - -import {ComponentResolver, Component, Directive, ViewContainerRef,} from '@angular/core'; - -import {ViewMetadata} from '@angular/core/src/metadata/view'; - -import {CompilerConfig, DirectiveResolver} from '@angular/compiler'; - -import {getIntParameter, bindAction} from '@angular/testing/src/benchmark_util'; +import {bindAction, getIntParameter} from '@angular/testing/src/benchmark_util'; function _createBindings(): any[] { const multiplyTemplatesBy = getIntParameter('elements'); return [ { provide: DirectiveResolver, - useFactory: - () => new MultiplyDirectiveResolver( - multiplyTemplatesBy, [BenchmarkComponentNoBindings, BenchmarkComponentWithBindings]), + useFactory: () => new MultiplyDirectiveResolver( + multiplyTemplatesBy, [BenchmarkComponentNoBindings, BenchmarkComponentWithBindings]), deps: [] }, // Use interpretative mode as Dart does not support JIT and @@ -57,7 +52,9 @@ function measureWrapper(func, desc) { const elapsedMs = new Date().getTime() - begin.getTime(); print(`[${desc}] ...done, took ${elapsedMs} ms`); }; - const onError = function(e) { DOM.logError(e); }; + const onError = function(e) { + DOM.logError(e); + }; PromiseWrapper.then(func(), onSuccess, onError); }; } diff --git a/modules/benchmarks/src/old/compiler/selector_benchmark.ts b/modules/benchmarks/src/old/compiler/selector_benchmark.ts index d1812a2d6d20d..028728eaa6eef 100644 --- a/modules/benchmarks/src/old/compiler/selector_benchmark.ts +++ b/modules/benchmarks/src/old/compiler/selector_benchmark.ts @@ -47,7 +47,9 @@ export function main() { function match() { let matchCount = 0; for (let i = 0; i < count; i++) { - fixedMatcher.match(fixedSelectors[i][0], (selector, selected) => { matchCount += selected; }); + fixedMatcher.match(fixedSelectors[i][0], (selector, selected) => { + matchCount += selected; + }); } return matchCount; } diff --git a/modules/benchmarks/src/old/costs/index.ts b/modules/benchmarks/src/old/costs/index.ts index 74023d5610766..2d3929b8fb492 100644 --- a/modules/benchmarks/src/old/costs/index.ts +++ b/modules/benchmarks/src/old/costs/index.ts @@ -10,7 +10,7 @@ import {NgFor, NgIf} from '@angular/common'; import {Component, Directive, DynamicComponentLoader, ViewContainerRef} from '@angular/core'; import {ApplicationRef} from '@angular/core/src/application_ref'; import {ListWrapper} from '@angular/facade/src/lang'; -import {BrowserModule, bootstrap} from '@angular/platform-browser'; +import {bootstrap, BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {bindAction, getIntParameter} from '@angular/testing/src/benchmark_util'; @@ -89,7 +89,9 @@ class AppComponent { testingWithDirectives: boolean; testingDynamicComponents: boolean; - constructor() { this.reset(); } + constructor() { + this.reset(); + } reset(): void { this.list = []; diff --git a/modules/benchmarks/src/old/di/di_benchmark.ts b/modules/benchmarks/src/old/di/di_benchmark.ts index 6d1e8fcc48752..ca00d579639af 100644 --- a/modules/benchmarks/src/old/di/di_benchmark.ts +++ b/modules/benchmarks/src/old/di/di_benchmark.ts @@ -98,30 +98,42 @@ export function main() { @Injectable() class A { - constructor() { count++; } + constructor() { + count++; + } } @Injectable() class B { - constructor(a: A) { count++; } + constructor(a: A) { + count++; + } } @Injectable() class C { - constructor(b: B) { count++; } + constructor(b: B) { + count++; + } } @Injectable() class D { - constructor(c: C, b: B) { count++; } + constructor(c: C, b: B) { + count++; + } } @Injectable() class E { - constructor(d: D, c: C) { count++; } + constructor(d: D, c: C) { + count++; + } } @Injectable() class F { - constructor(e: E, d: D) { count++; } + constructor(e: E, d: D) { + count++; + } } diff --git a/modules/benchmarks/src/old/naive_infinite_scroll/app.ts b/modules/benchmarks/src/old/naive_infinite_scroll/app.ts index 4456bf3fe1c99..8d4297d7b5113 100644 --- a/modules/benchmarks/src/old/naive_infinite_scroll/app.ts +++ b/modules/benchmarks/src/old/naive_infinite_scroll/app.ts @@ -45,7 +45,9 @@ export class App { for (let i = 0; i < appSize; i++) { this.scrollAreas.push(i); } - bindAction('#run-btn', () => { this.runBenchmark(); }); + bindAction('#run-btn', () => { + this.runBenchmark(); + }); bindAction('#reset-btn', () => { this._getScrollDiv().scrollTop = 0; const existingMarker = this._locateFinishedMarker(); @@ -88,7 +90,11 @@ export class App { }, 0); } - private _locateFinishedMarker() { return DOM.querySelector(document.body, '#done'); } + private _locateFinishedMarker() { + return DOM.querySelector(document.body, '#done'); + } - private _getScrollDiv() { return DOM.query('body /deep/ #scrollDiv'); } + private _getScrollDiv() { + return DOM.query('body /deep/ #scrollDiv'); + } } diff --git a/modules/benchmarks/src/old/naive_infinite_scroll/cells.ts b/modules/benchmarks/src/old/naive_infinite_scroll/cells.ts index 747ff2fd2a205..1f4de9cb6f102 100644 --- a/modules/benchmarks/src/old/naive_infinite_scroll/cells.ts +++ b/modules/benchmarks/src/old/naive_infinite_scroll/cells.ts @@ -16,7 +16,9 @@ export class HasStyle { constructor() {} - set width(w: number) { this.cellWidth = w; } + set width(w: number) { + this.cellWidth = w; + } } @Component({ @@ -74,7 +76,9 @@ export class StageButtonsComponent extends HasStyle { private _offering: Offering; stages: Stage[]; - get offering(): Offering { return this._offering; } + get offering(): Offering { + return this._offering; + } set offering(offering: Offering) { this._offering = offering; diff --git a/modules/benchmarks/src/old/naive_infinite_scroll/common.ts b/modules/benchmarks/src/old/naive_infinite_scroll/common.ts index 4d0a269a051ec..2279def26466d 100644 --- a/modules/benchmarks/src/old/naive_infinite_scroll/common.ts +++ b/modules/benchmarks/src/old/naive_infinite_scroll/common.ts @@ -56,13 +56,17 @@ export class CustomDate { return new CustomDate(newYear, newMonth, newDay); } - static now(): CustomDate { return new CustomDate(2014, 1, 28); } + static now(): CustomDate { + return new CustomDate(2014, 1, 28); + } } export class RawEntity { private _data: Map; - constructor() { this._data = new Map(); } + constructor() { + this._data = new Map(); + } get(key: string) { if (key.indexOf('.') == -1) { @@ -114,51 +118,107 @@ export class RawEntity { } export class Company extends RawEntity { - get name(): string { return this.get('name'); } - set name(val: string) { this.set('name', val); } + get name(): string { + return this.get('name'); + } + set name(val: string) { + this.set('name', val); + } } export class Offering extends RawEntity { - get name(): string { return this.get('name'); } - set name(val: string) { this.set('name', val); } + get name(): string { + return this.get('name'); + } + set name(val: string) { + this.set('name', val); + } - get company(): Company { return this.get('company'); } - set company(val: Company) { this.set('company', val); } + get company(): Company { + return this.get('company'); + } + set company(val: Company) { + this.set('company', val); + } - get opportunity(): Opportunity { return this.get('opportunity'); } - set opportunity(val: Opportunity) { this.set('opportunity', val); } + get opportunity(): Opportunity { + return this.get('opportunity'); + } + set opportunity(val: Opportunity) { + this.set('opportunity', val); + } - get account(): Account { return this.get('account'); } - set account(val: Account) { this.set('account', val); } + get account(): Account { + return this.get('account'); + } + set account(val: Account) { + this.set('account', val); + } - get basePoints(): number { return this.get('basePoints'); } - set basePoints(val: number) { this.set('basePoints', val); } + get basePoints(): number { + return this.get('basePoints'); + } + set basePoints(val: number) { + this.set('basePoints', val); + } - get kickerPoints(): number { return this.get('kickerPoints'); } - set kickerPoints(val: number) { this.set('kickerPoints', val); } + get kickerPoints(): number { + return this.get('kickerPoints'); + } + set kickerPoints(val: number) { + this.set('kickerPoints', val); + } - get status(): string { return this.get('status'); } - set status(val: string) { this.set('status', val); } + get status(): string { + return this.get('status'); + } + set status(val: string) { + this.set('status', val); + } - get bundles(): string { return this.get('bundles'); } - set bundles(val: string) { this.set('bundles', val); } + get bundles(): string { + return this.get('bundles'); + } + set bundles(val: string) { + this.set('bundles', val); + } - get dueDate(): CustomDate { return this.get('dueDate'); } - set dueDate(val: CustomDate) { this.set('dueDate', val); } + get dueDate(): CustomDate { + return this.get('dueDate'); + } + set dueDate(val: CustomDate) { + this.set('dueDate', val); + } - get endDate(): CustomDate { return this.get('endDate'); } - set endDate(val: CustomDate) { this.set('endDate', val); } + get endDate(): CustomDate { + return this.get('endDate'); + } + set endDate(val: CustomDate) { + this.set('endDate', val); + } - get aatStatus(): string { return this.get('aatStatus'); } - set aatStatus(val: string) { this.set('aatStatus', val); } + get aatStatus(): string { + return this.get('aatStatus'); + } + set aatStatus(val: string) { + this.set('aatStatus', val); + } } export class Opportunity extends RawEntity { - get name(): string { return this.get('name'); } - set name(val: string) { this.set('name', val); } + get name(): string { + return this.get('name'); + } + set name(val: string) { + this.set('name', val); + } } export class Account extends RawEntity { - get accountId(): number { return this.get('accountId'); } - set accountId(val: number) { this.set('accountId', val); } + get accountId(): number { + return this.get('accountId'); + } + set accountId(val: number) { + this.set('accountId', val); + } } diff --git a/modules/benchmarks/src/old/naive_infinite_scroll/scroll_area.ts b/modules/benchmarks/src/old/naive_infinite_scroll/scroll_area.ts index f0b71725d3ced..807c29a166563 100644 --- a/modules/benchmarks/src/old/naive_infinite_scroll/scroll_area.ts +++ b/modules/benchmarks/src/old/naive_infinite_scroll/scroll_area.ts @@ -9,7 +9,7 @@ import {NgFor} from '@angular/common'; import {Component, Directive} from '@angular/core'; -import {HEIGHT, ITEMS, ITEM_HEIGHT, Offering, ROW_WIDTH, VIEW_PORT_HEIGHT, VISIBLE_ITEMS} from './common'; +import {HEIGHT, ITEM_HEIGHT, ITEMS, Offering, ROW_WIDTH, VIEW_PORT_HEIGHT, VISIBLE_ITEMS} from './common'; import {generateOfferings} from './random_data'; import {ScrollItemComponent} from './scroll_item'; diff --git a/modules/benchmarks/src/old/naive_infinite_scroll/scroll_item.ts b/modules/benchmarks/src/old/naive_infinite_scroll/scroll_item.ts index b88862454449c..4604384676a67 100644 --- a/modules/benchmarks/src/old/naive_infinite_scroll/scroll_item.ts +++ b/modules/benchmarks/src/old/naive_infinite_scroll/scroll_item.ts @@ -9,7 +9,7 @@ import {Component, Directive} from '@angular/core'; import {AccountCellComponent, CompanyNameComponent, FormattedCellComponent, OfferingNameComponent, OpportunityNameComponent, StageButtonsComponent} from './cells'; -import {AAT_STATUS_WIDTH, ACCOUNT_CELL_WIDTH, BASE_POINTS_WIDTH, BUNDLES_WIDTH, COMPANY_NAME_WIDTH, DUE_DATE_WIDTH, END_DATE_WIDTH, ITEM_HEIGHT, KICKER_POINTS_WIDTH, OFFERING_NAME_WIDTH, OPPORTUNITY_NAME_WIDTH, Offering, STAGE_BUTTONS_WIDTH} from './common'; +import {AAT_STATUS_WIDTH, ACCOUNT_CELL_WIDTH, BASE_POINTS_WIDTH, BUNDLES_WIDTH, COMPANY_NAME_WIDTH, DUE_DATE_WIDTH, END_DATE_WIDTH, ITEM_HEIGHT, KICKER_POINTS_WIDTH, Offering, OFFERING_NAME_WIDTH, OPPORTUNITY_NAME_WIDTH, STAGE_BUTTONS_WIDTH} from './common'; @Component({ selector: 'scroll-item', @@ -63,17 +63,41 @@ export class ScrollItemComponent { itemHeight: number; - constructor() { this.itemHeight = ITEM_HEIGHT; } + constructor() { + this.itemHeight = ITEM_HEIGHT; + } - get companyNameWidth() { return COMPANY_NAME_WIDTH; } - get opportunityNameWidth() { return OPPORTUNITY_NAME_WIDTH; } - get offeringNameWidth() { return OFFERING_NAME_WIDTH; } - get accountCellWidth() { return ACCOUNT_CELL_WIDTH; } - get basePointsWidth() { return BASE_POINTS_WIDTH; } - get kickerPointsWidth() { return KICKER_POINTS_WIDTH; } - get stageButtonsWidth() { return STAGE_BUTTONS_WIDTH; } - get bundlesWidth() { return BUNDLES_WIDTH; } - get dueDateWidth() { return DUE_DATE_WIDTH; } - get endDateWidth() { return END_DATE_WIDTH; } - get aatStatusWidth() { return AAT_STATUS_WIDTH; } + get companyNameWidth() { + return COMPANY_NAME_WIDTH; + } + get opportunityNameWidth() { + return OPPORTUNITY_NAME_WIDTH; + } + get offeringNameWidth() { + return OFFERING_NAME_WIDTH; + } + get accountCellWidth() { + return ACCOUNT_CELL_WIDTH; + } + get basePointsWidth() { + return BASE_POINTS_WIDTH; + } + get kickerPointsWidth() { + return KICKER_POINTS_WIDTH; + } + get stageButtonsWidth() { + return STAGE_BUTTONS_WIDTH; + } + get bundlesWidth() { + return BUNDLES_WIDTH; + } + get dueDateWidth() { + return DUE_DATE_WIDTH; + } + get endDateWidth() { + return END_DATE_WIDTH; + } + get aatStatusWidth() { + return AAT_STATUS_WIDTH; + } } diff --git a/modules/benchmarks/src/styling/ng2/init.ts b/modules/benchmarks/src/styling/ng2/init.ts index e7816d80f8cd4..b697223019c09 100644 --- a/modules/benchmarks/src/styling/ng2/init.ts +++ b/modules/benchmarks/src/styling/ng2/init.ts @@ -23,7 +23,7 @@ export function init(moduleRef: NgModuleRef) { const componentRef = appRef.components[0]; const component = componentRef.instance; const componentHostEl = componentRef.location.nativeElement; - const select = document.querySelector('#scenario-select') !as HTMLSelectElement; + const select = document.querySelector('#scenario-select')! as HTMLSelectElement; function create(tplRefIdx: number) { component.tplRefIdx = tplRefIdx; @@ -41,7 +41,9 @@ export function init(moduleRef: NgModuleRef) { appRef.tick(); } - function detectChanges() { appRef.tick(); } + function detectChanges() { + appRef.tick(); + } function modifyExternally() { const buttonEls = componentHostEl.querySelectorAll('button') as HTMLButtonElement[]; diff --git a/modules/benchmarks/src/styling/ng2/styling.ts b/modules/benchmarks/src/styling/ng2/styling.ts index b669654ae7f05..87c65829f99df 100644 --- a/modules/benchmarks/src/styling/ng2/styling.ts +++ b/modules/benchmarks/src/styling/ng2/styling.ts @@ -35,7 +35,9 @@ export class StylingComponent { tplRefIdx: number = 0; staticStyle = {width: '10px'}; - getTplRef(...tplRefs): TemplateRef { return tplRefs[this.tplRefIdx]; } + getTplRef(...tplRefs): TemplateRef { + return tplRefs[this.tplRefIdx]; + } } @NgModule({ diff --git a/modules/benchmarks/src/styling/styling_perf.spec.ts b/modules/benchmarks/src/styling/styling_perf.spec.ts index edf69fd43d4bd..779ef33bf8c70 100644 --- a/modules/benchmarks/src/styling/styling_perf.spec.ts +++ b/modules/benchmarks/src/styling/styling_perf.spec.ts @@ -28,7 +28,7 @@ const SCENARIOS = [ describe('styling benchmark spec', () => { afterEach(verifyNoBrowserErrors); - it('should render and interact to update and detect changes', async() => { + it('should render and interact to update and detect changes', async () => { openBrowser({url: '/', ignoreBrowserSynchronization: true}); create(); const items = element.all(by.css('styling-bindings button')); @@ -38,7 +38,7 @@ describe('styling benchmark spec', () => { expect(await items.first().getAttribute('title')).toBe('baz'); }); - it('should render and run noop change detection', async() => { + it('should render and run noop change detection', async () => { openBrowser({url: '/', ignoreBrowserSynchronization: true}); create(); const items = element.all(by.css('styling-bindings button')); @@ -51,7 +51,7 @@ describe('styling benchmark spec', () => { // Create benchmarks for each possible test scenario. SCENARIOS.forEach(({optionIndex, id}) => { describe(id, () => { - it('should run create benchmark', async() => { + it('should run create benchmark', async () => { await runStylingBenchmark(`styling.${id}.create`, { work: () => create(), prepare: () => { @@ -61,7 +61,7 @@ describe('styling benchmark spec', () => { }); }); - it('should run update benchmark', async() => { + it('should run update benchmark', async () => { await runStylingBenchmark(`styling.${id}.update`, { work: () => update(), prepare: () => { @@ -71,7 +71,7 @@ describe('styling benchmark spec', () => { }); }); - it('should run detect changes benchmark', async() => { + it('should run detect changes benchmark', async () => { await runStylingBenchmark(`styling.${id}.noop_cd`, { work: () => detectChanges(), prepare: () => { diff --git a/modules/benchmarks/src/tree/baseline/tree.ts b/modules/benchmarks/src/tree/baseline/tree.ts index 8350018a600c1..c1a97ba99cfbb 100644 --- a/modules/benchmarks/src/tree/baseline/tree.ts +++ b/modules/benchmarks/src/tree/baseline/tree.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {TreeNode, newArray} from '../util'; +import {newArray, TreeNode} from '../util'; export class TreeComponent { private _renderNodes: any[]; diff --git a/modules/benchmarks/src/tree/incremental_dom/tree.ts b/modules/benchmarks/src/tree/incremental_dom/tree.ts index 0a5a23ab6bafe..c241f4ab5b1b1 100644 --- a/modules/benchmarks/src/tree/incremental_dom/tree.ts +++ b/modules/benchmarks/src/tree/incremental_dom/tree.ts @@ -17,7 +17,9 @@ const {patch, elementOpen, elementClose, elementOpenStart, elementOpenEnd, text, export class TreeComponent { constructor(private _rootEl: any) {} - set data(data: TreeNode) { patch(this._rootEl, () => this._render(data)); } + set data(data: TreeNode) { + patch(this._rootEl, () => this._render(data)); + } private _render(data: TreeNode) { elementOpenStart('span', '', null); diff --git a/modules/benchmarks/src/tree/ng1/index.ts b/modules/benchmarks/src/tree/ng1/index.ts index d4dd3c80ae2ae..40348ed4aaebe 100644 --- a/modules/benchmarks/src/tree/ng1/index.ts +++ b/modules/benchmarks/src/tree/ng1/index.ts @@ -15,7 +15,7 @@ declare var angular: any; function init() { let detectChangesRuns = 0; - const numberOfChecksEl = document.getElementById('numberOfChecks') !; + const numberOfChecksEl = document.getElementById('numberOfChecks')!; addTreeToModule(angular.module('app', [])).run([ '$rootScope', @@ -31,11 +31,15 @@ function init() { function noop() {} function destroyDom() { - $rootScope.$apply(() => { $rootScope.initData = emptyTree; }); + $rootScope.$apply(() => { + $rootScope.initData = emptyTree; + }); } function createDom() { - $rootScope.$apply(() => { $rootScope.initData = buildTree(); }); + $rootScope.$apply(() => { + $rootScope.initData = buildTree(); + }); } bindAction('#destroyDom', destroyDom); diff --git a/modules/benchmarks/src/tree/ng1/tree.ts b/modules/benchmarks/src/tree/ng1/tree.ts index d914fa9b7b1bb..a212febb9819e 100644 --- a/modules/benchmarks/src/tree/ng1/tree.ts +++ b/modules/benchmarks/src/tree/ng1/tree.ts @@ -41,7 +41,6 @@ export function addTreeToModule(mod: any): any { } let childElement: any, childScope: any; $scope.$watch($attr.data, function ngIfWatchAction(value: any) { - if (value) { if (!childScope) { childScope = $scope.$new(); @@ -67,6 +66,8 @@ export function addTreeToModule(mod: any): any { ]) .config([ '$compileProvider', - function($compileProvider: any) { $compileProvider.debugInfoEnabled(false); } + function($compileProvider: any) { + $compileProvider.debugInfoEnabled(false); + } ]); } diff --git a/modules/benchmarks/src/tree/ng2/init.ts b/modules/benchmarks/src/tree/ng2/init.ts index 06d5b861283bf..1f45f7cb0f2f6 100644 --- a/modules/benchmarks/src/tree/ng2/init.ts +++ b/modules/benchmarks/src/tree/ng2/init.ts @@ -40,7 +40,7 @@ export function init(moduleRef: NgModuleRef) { const injector = moduleRef.injector; appRef = injector.get(ApplicationRef); - const numberOfChecksEl = document.getElementById('numberOfChecks') !; + const numberOfChecksEl = document.getElementById('numberOfChecks')!; tree = appRef.components[0].instance; diff --git a/modules/benchmarks/src/tree/ng2/tree.ts b/modules/benchmarks/src/tree/ng2/tree.ts index eea897e5cb6a0..199f33355cc4c 100644 --- a/modules/benchmarks/src/tree/ng2/tree.ts +++ b/modules/benchmarks/src/tree/ng2/tree.ts @@ -9,7 +9,7 @@ import {Component, NgModule} from '@angular/core'; import {BrowserModule, DomSanitizer, SafeStyle} from '@angular/platform-browser'; -import {TreeNode, emptyTree} from '../util'; +import {emptyTree, TreeNode} from '../util'; let trustedEmptyColor: SafeStyle; let trustedGreyColor: SafeStyle; @@ -22,7 +22,9 @@ let trustedGreyColor: SafeStyle; }) export class TreeComponent { data: TreeNode = emptyTree; - get bgColor() { return this.data.depth % 2 ? trustedEmptyColor : trustedGreyColor; } + get bgColor() { + return this.data.depth % 2 ? trustedEmptyColor : trustedGreyColor; + } } @NgModule({imports: [BrowserModule], bootstrap: [TreeComponent], declarations: [TreeComponent]}) diff --git a/modules/benchmarks/src/tree/ng2_next/tree.ts b/modules/benchmarks/src/tree/ng2_next/tree.ts index 6ded8e33d64ae..31a28a9e3f82d 100644 --- a/modules/benchmarks/src/tree/ng2_next/tree.ts +++ b/modules/benchmarks/src/tree/ng2_next/tree.ts @@ -7,17 +7,19 @@ */ import {NgIf} from '@angular/common'; -import {ComponentFactory, ComponentFactoryResolver, ComponentRef, ErrorHandler, Injector, NgModuleRef, RendererFactory2, Sanitizer, TemplateRef, ViewContainerRef, ɵArgumentType as ArgumentType, ɵBindingFlags as BindingFlags, ɵNodeFlags as NodeFlags, ɵViewDefinition as ViewDefinition, ɵViewFlags as ViewFlags, ɵand as anchorDef, ɵccf as createComponentFactory, ɵdid as directiveDef, ɵeld as elementDef, ɵinitServicesIfNeeded as initServicesIfNeeded, ɵted as textDef, ɵvid as viewDef} from '@angular/core'; +import {ComponentFactory, ComponentFactoryResolver, ComponentRef, ErrorHandler, Injector, NgModuleRef, RendererFactory2, Sanitizer, TemplateRef, ViewContainerRef, ɵand as anchorDef, ɵArgumentType as ArgumentType, ɵBindingFlags as BindingFlags, ɵccf as createComponentFactory, ɵdid as directiveDef, ɵeld as elementDef, ɵinitServicesIfNeeded as initServicesIfNeeded, ɵNodeFlags as NodeFlags, ɵted as textDef, ɵvid as viewDef, ɵViewDefinition as ViewDefinition, ɵViewFlags as ViewFlags} from '@angular/core'; import {SafeStyle, ɵDomRendererFactory2 as DomRendererFactory2, ɵDomSanitizerImpl as DomSanitizerImpl} from '@angular/platform-browser'; -import {TreeNode, emptyTree} from '../util'; +import {emptyTree, TreeNode} from '../util'; let trustedEmptyColor: SafeStyle; let trustedGreyColor: SafeStyle; export class TreeComponent { data: TreeNode = emptyTree; - get bgColor() { return this.data.depth % 2 ? trustedEmptyColor : trustedGreyColor; } + get bgColor() { + return this.data.depth % 2 ? trustedEmptyColor : trustedGreyColor; + } } let viewFlags = ViewFlags.None; @@ -120,11 +122,19 @@ export class AppModule implements Injector, NgModuleRef { this.componentFactory.create(Injector.NULL, [], this.componentFactory.selector, this); } - tick() { this.componentRef.changeDetectorRef.detectChanges(); } + tick() { + this.componentRef.changeDetectorRef.detectChanges(); + } - get injector() { return this; } - get componentFactoryResolver(): ComponentFactoryResolver { return null; } - get instance() { return this; } + get injector() { + return this; + } + get componentFactoryResolver(): ComponentFactoryResolver { + return null; + } + get instance() { + return this; + } destroy() {} onDestroy(callback: () => void) {} } diff --git a/modules/benchmarks/src/tree/ng2_static/tree.ts b/modules/benchmarks/src/tree/ng2_static/tree.ts index 2ca2adaf1d184..cf0af17d51230 100644 --- a/modules/benchmarks/src/tree/ng2_static/tree.ts +++ b/modules/benchmarks/src/tree/ng2_static/tree.ts @@ -9,24 +9,25 @@ import {Component, Input, NgModule} from '@angular/core'; import {BrowserModule, DomSanitizer, SafeStyle} from '@angular/platform-browser'; -import {TreeNode, emptyTree, getMaxDepth} from '../util'; +import {emptyTree, getMaxDepth, TreeNode} from '../util'; let trustedEmptyColor: SafeStyle; let trustedGreyColor: SafeStyle; function createTreeComponent(level: number, isLeaf: boolean) { - const nextTreeEl = `tree${level+1}`; + const nextTreeEl = `tree${level + 1}`; let template = ` {{data.value}} `; if (!isLeaf) { - template += - `<${nextTreeEl} [data]='data.right'><${nextTreeEl} [data]='data.left'>`; + template += `<${nextTreeEl} [data]='data.right'><${ + nextTreeEl} [data]='data.left'>`; } @Component({selector: `tree${level}`, template: template}) class TreeComponent { - @Input() - data: TreeNode; - get bgColor() { return this.data.depth % 2 ? trustedEmptyColor : trustedGreyColor; } + @Input() data: TreeNode; + get bgColor() { + return this.data.depth % 2 ? trustedEmptyColor : trustedGreyColor; + } } return TreeComponent; @@ -34,8 +35,7 @@ function createTreeComponent(level: number, isLeaf: boolean) { @Component({selector: 'tree', template: ``}) export class RootTreeComponent { - @Input() - data: TreeNode = emptyTree; + @Input() data: TreeNode = emptyTree; } function createModule(): any { diff --git a/modules/benchmarks/src/tree/ng2_switch/tree.ts b/modules/benchmarks/src/tree/ng2_switch/tree.ts index 42164490744a9..24ec4c6df9abd 100644 --- a/modules/benchmarks/src/tree/ng2_switch/tree.ts +++ b/modules/benchmarks/src/tree/ng2_switch/tree.ts @@ -9,7 +9,7 @@ import {Component, Input, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; -import {TreeNode, emptyTree} from '../util'; +import {emptyTree, TreeNode} from '../util'; @Component({ selector: 'tree', @@ -19,8 +19,7 @@ import {TreeNode, emptyTree} from '../util'; ` }) export class TreeComponent { - @Input() - data: TreeNode = emptyTree; + @Input() data: TreeNode = emptyTree; } @NgModule({ diff --git a/modules/benchmarks/src/tree/render3/index_aot.ts b/modules/benchmarks/src/tree/render3/index_aot.ts index b9235143140d6..797ccc7ff3976 100644 --- a/modules/benchmarks/src/tree/render3/index_aot.ts +++ b/modules/benchmarks/src/tree/render3/index_aot.ts @@ -7,8 +7,10 @@ */ import {ɵrenderComponent as renderComponent} from '@angular/core'; + import {bindAction, profile} from '../../util'; -import {TreeComponent, createDom, destroyDom, detectChanges} from './tree'; + +import {createDom, destroyDom, detectChanges, TreeComponent} from './tree'; function noop() {} diff --git a/modules/benchmarks/src/tree/render3/tree.ts b/modules/benchmarks/src/tree/render3/tree.ts index a6c77591cefd5..8fa337963d8e8 100644 --- a/modules/benchmarks/src/tree/render3/tree.ts +++ b/modules/benchmarks/src/tree/render3/tree.ts @@ -21,7 +21,7 @@ export function createDom(component: TreeComponent) { ɵdetectChanges(component); } -const numberOfChecksEl = document.getElementById('numberOfChecks') !; +const numberOfChecksEl = document.getElementById('numberOfChecks')!; let detectChangesRuns = 0; export function detectChanges(component: TreeComponent) { for (let i = 0; i < 10; i++) { @@ -42,7 +42,9 @@ export function detectChanges(component: TreeComponent) { }) export class TreeComponent { data: any = emptyTree; - get bgColor() { return this.data.depth % 2 ? '' : 'grey'; } + get bgColor() { + return this.data.depth % 2 ? '' : 'grey'; + } } @NgModule({declarations: [TreeComponent], imports: [CommonModule]}) diff --git a/modules/benchmarks/src/tree/render3_function/index.ts b/modules/benchmarks/src/tree/render3_function/index.ts index 32be3be0b8608..8afd56308d3b4 100644 --- a/modules/benchmarks/src/tree/render3_function/index.ts +++ b/modules/benchmarks/src/tree/render3_function/index.ts @@ -6,11 +6,11 @@ * found in the LICENSE file at https://angular.io/license */ -import {ɵRenderFlags, ɵrenderComponent as renderComponent, ɵɵadvance, ɵɵcontainer, ɵɵcontainerRefreshEnd, ɵɵcontainerRefreshStart, ɵɵdefineComponent, ɵɵelementEnd, ɵɵelementStart, ɵɵembeddedViewEnd, ɵɵembeddedViewStart, ɵɵstyleProp, ɵɵtext, ɵɵtextInterpolate1} from '@angular/core'; +import {ɵrenderComponent as renderComponent, ɵRenderFlags, ɵɵadvance, ɵɵcontainer, ɵɵcontainerRefreshEnd, ɵɵcontainerRefreshStart, ɵɵdefineComponent, ɵɵelementEnd, ɵɵelementStart, ɵɵembeddedViewEnd, ɵɵembeddedViewStart, ɵɵstyleProp, ɵɵtext, ɵɵtextInterpolate1} from '@angular/core'; import {bindAction, profile} from '../../util'; import {createDom, destroyDom, detectChanges} from '../render3/tree'; -import {TreeNode, emptyTree} from '../util'; +import {emptyTree, TreeNode} from '../util'; function noop() {} @@ -26,15 +26,16 @@ export class TreeFunction { selectors: [['tree']], decls: 5, vars: 2, - template: function(rf: ɵRenderFlags, ctx: TreeFunction) { - // bit of a hack - TreeTpl(rf, ctx.data); - }, + template: + function(rf: ɵRenderFlags, ctx: TreeFunction) { + // bit of a hack + TreeTpl(rf, ctx.data); + }, inputs: {data: 'data'} }); } -const TreeFunctionCmpDef = TreeFunction.ɵcmp as{decls: number, vars: number}; +const TreeFunctionCmpDef = TreeFunction.ɵcmp as {decls: number, vars: number}; export function TreeTpl(rf: ɵRenderFlags, ctx: TreeNode) { if (rf & ɵRenderFlags.Create) { ɵɵelementStart(0, 'tree'); diff --git a/modules/benchmarks/src/tree/tree.e2e-spec.ts b/modules/benchmarks/src/tree/tree.e2e-spec.ts index f86a822568f05..8f9ecfb3d5fa9 100644 --- a/modules/benchmarks/src/tree/tree.e2e-spec.ts +++ b/modules/benchmarks/src/tree/tree.e2e-spec.ts @@ -11,7 +11,7 @@ import {$} from 'protractor'; import {openTreeBenchmark} from './test_utils'; describe('tree benchmark', () => { - it('should work for createDestroy', async() => { + it('should work for createDestroy', async () => { openTreeBenchmark(); await $('#createDom').click(); expect($('#root').getText()).toContain('1'); @@ -19,7 +19,7 @@ describe('tree benchmark', () => { expect(await $('#root').getText()).toEqual(''); }); - it('should work for update', async() => { + it('should work for update', async () => { openTreeBenchmark(); await $('#createDom').click(); await $('#createDom').click(); diff --git a/modules/benchmarks/src/tree/tree.perf-spec.ts b/modules/benchmarks/src/tree/tree.perf-spec.ts index 2e52a2fae88f3..dc703a061826b 100644 --- a/modules/benchmarks/src/tree/tree.perf-spec.ts +++ b/modules/benchmarks/src/tree/tree.perf-spec.ts @@ -10,7 +10,7 @@ import {$} from 'protractor'; import {runTreeBenchmark} from './test_utils'; describe('tree benchmark perf', () => { - it('should work for createOnly', async() => { + it('should work for createOnly', async () => { await runTreeBenchmark({ // This cannot be called "createOnly" because the actual destroy benchmark // has the "createOnly" id already. See: https://github.com/angular/angular/pull/21503 @@ -20,7 +20,7 @@ describe('tree benchmark perf', () => { }); }); - it('should work for destroy', async() => { + it('should work for destroy', async () => { await runTreeBenchmark({ // This is actually a benchmark for destroying the dom, but it has been accidentally // named "createOnly". See https://github.com/angular/angular/pull/21503. @@ -30,7 +30,7 @@ describe('tree benchmark perf', () => { }); }); - it('should work for createDestroy', async() => { + it('should work for createDestroy', async () => { await runTreeBenchmark({ id: 'createDestroy', work: () => { @@ -40,7 +40,7 @@ describe('tree benchmark perf', () => { }); }); - it('should work for update', async() => { + it('should work for update', async () => { await runTreeBenchmark({ id: 'update', work: () => $('#createDom').click(), diff --git a/modules/benchmarks/src/tree/tree_detect_changes.e2e-spec.ts b/modules/benchmarks/src/tree/tree_detect_changes.e2e-spec.ts index d75539af1340f..d6f61653e2385 100644 --- a/modules/benchmarks/src/tree/tree_detect_changes.e2e-spec.ts +++ b/modules/benchmarks/src/tree/tree_detect_changes.e2e-spec.ts @@ -11,7 +11,7 @@ import {$} from 'protractor'; import {openTreeBenchmark} from './test_utils'; describe('tree benchmark detect changes', () => { - it('should work for detectChanges', async() => { + it('should work for detectChanges', async () => { openTreeBenchmark(); await $('#detectChanges').click(); expect($('#numberOfChecks').getText()).toContain('10'); diff --git a/modules/benchmarks/src/tree/tree_detect_changes.perf-spec.ts b/modules/benchmarks/src/tree/tree_detect_changes.perf-spec.ts index 822491e6193fe..49a391f476205 100644 --- a/modules/benchmarks/src/tree/tree_detect_changes.perf-spec.ts +++ b/modules/benchmarks/src/tree/tree_detect_changes.perf-spec.ts @@ -10,7 +10,7 @@ import {$} from 'protractor'; import {runTreeBenchmark} from './test_utils'; describe('tree benchmark detect changes perf', () => { - it('should work for detectChanges', async() => { + it('should work for detectChanges', async () => { await runTreeBenchmark({ id: 'detectChanges', work: () => $('#detectChanges').click(), diff --git a/modules/benchmarks/src/tree/util.ts b/modules/benchmarks/src/tree/util.ts index 4c9dc197898fa..519945df508e3 100644 --- a/modules/benchmarks/src/tree/util.ts +++ b/modules/benchmarks/src/tree/util.ts @@ -16,12 +16,14 @@ export class TreeNode { public value: string, public depth: number, public maxDepth: number, public left: TreeNode|null, public right: TreeNode|null) { this.transitiveChildCount = Math.pow(2, (this.maxDepth - this.depth + 1)) - 1; - this.children = this.left ? [this.left, this.right !] : []; + this.children = this.left ? [this.left, this.right!] : []; } // Needed for Polymer as it does not support ternary nor modulo operator // in expressions - get style(): string { return this.depth % 2 === 0 ? 'background-color: grey' : ''; } + get style(): string { + return this.depth % 2 === 0 ? 'background-color: grey' : ''; + } } let treeCreateCount: number; @@ -78,7 +80,7 @@ export function newArray(size: number, value: T): T[]; export function newArray(size: number, value?: T): T[] { const list: T[] = []; for (let i = 0; i < size; i++) { - list.push(value !); + list.push(value!); } return list; } diff --git a/modules/benchmarks/src/util.ts b/modules/benchmarks/src/util.ts index 099be1664c68b..e5937a64a1fb1 100644 --- a/modules/benchmarks/src/util.ts +++ b/modules/benchmarks/src/util.ts @@ -35,7 +35,7 @@ export function getStringParameter(name: string) { } export function bindAction(selector: string, callback: () => void) { - document.querySelector(selector) !.addEventListener('click', callback); + document.querySelector(selector)!.addEventListener('click', callback); } @@ -66,7 +66,8 @@ function reportProfileResults(durations: number[], count: number) { Number.MAX_SAFE_INTEGER) .toFixed(2); window.console.log( - `Iterations: ${count}; cold time: ${durations[0].toFixed(2)} ms; average time: ${avgDuration} ms / iteration; best time: ${minDuration} ms`); + `Iterations: ${count}; cold time: ${durations[0].toFixed(2)} ms; average time: ${ + avgDuration} ms / iteration; best time: ${minDuration} ms`); } // helper script that will read out the url parameters diff --git a/modules/benchmarks/src/views/views-benchmark.ts b/modules/benchmarks/src/views/views-benchmark.ts index 5984d34480b6e..d6d807c1a629b 100644 --- a/modules/benchmarks/src/views/views-benchmark.ts +++ b/modules/benchmarks/src/views/views-benchmark.ts @@ -20,7 +20,9 @@ export class ViewManipulationDirective { } } - clear() { this._vcRef.clear(); } + clear() { + this._vcRef.clear(); + } } @Component({ @@ -44,9 +46,13 @@ export class ViewsBenchmark { constructor(private _cdRef: ChangeDetectorRef) {} - create(vm: ViewManipulationDirective) { vm.create(1000); } + create(vm: ViewManipulationDirective) { + vm.create(1000); + } - destroy(vm: ViewManipulationDirective) { vm.clear(); } + destroy(vm: ViewManipulationDirective) { + vm.clear(); + } check() { for (let i = 0; i < 10000; i++) { diff --git a/modules/playground/e2e_test/hello_world/hello_world_spec.ts b/modules/playground/e2e_test/hello_world/hello_world_spec.ts index 7e20b09b742f3..2d167fec7436b 100644 --- a/modules/playground/e2e_test/hello_world/hello_world_spec.ts +++ b/modules/playground/e2e_test/hello_world/hello_world_spec.ts @@ -11,7 +11,6 @@ import {browser} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('hello world', function() { - afterEach(verifyNoBrowserErrors); describe('hello world app', function() { @@ -30,7 +29,6 @@ describe('hello world', function() { expect(getComponentText('hello-app', '.greeting')).toEqual('howdy world!'); }); }); - }); function getComponentText(selector: string, innerSelector: string) { diff --git a/modules/playground/e2e_test/http/http_spec.ts b/modules/playground/e2e_test/http/http_spec.ts index 58d4ecb0db8e6..f5a5618b3f198 100644 --- a/modules/playground/e2e_test/http/http_spec.ts +++ b/modules/playground/e2e_test/http/http_spec.ts @@ -11,7 +11,6 @@ import {browser} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('http', function() { - afterEach(verifyNoBrowserErrors); describe('fetching', function() { @@ -25,6 +24,6 @@ describe('http', function() { }); function getComponentText(selector: string, innerSelector: string) { - return browser.executeScript( - `return document.querySelector("${selector}").querySelector("${innerSelector}").textContent.trim()`); + return browser.executeScript(`return document.querySelector("${selector}").querySelector("${ + innerSelector}").textContent.trim()`); } diff --git a/modules/playground/e2e_test/jsonp/jsonp_spec.ts b/modules/playground/e2e_test/jsonp/jsonp_spec.ts index 71c6734ea4ba9..72f1003a5fffd 100644 --- a/modules/playground/e2e_test/jsonp/jsonp_spec.ts +++ b/modules/playground/e2e_test/jsonp/jsonp_spec.ts @@ -11,7 +11,6 @@ import {browser} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('jsonp', function() { - afterEach(verifyNoBrowserErrors); describe('fetching', function() { @@ -25,6 +24,6 @@ describe('jsonp', function() { }); function getComponentText(selector: string, innerSelector: string) { - return browser.executeScript( - `return document.querySelector("${selector}").querySelector("${innerSelector}").textContent.trim()`); + return browser.executeScript(`return document.querySelector("${selector}").querySelector("${ + innerSelector}").textContent.trim()`); } diff --git a/modules/playground/e2e_test/key_events/key_events_spec.ts b/modules/playground/e2e_test/key_events/key_events_spec.ts index f98d087df49c1..898950d8c5036 100644 --- a/modules/playground/e2e_test/key_events/key_events_spec.ts +++ b/modules/playground/e2e_test/key_events/key_events_spec.ts @@ -13,11 +13,12 @@ import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; const Key = protractor.Key; describe('key_events', function() { - const URL = '/'; afterEach(verifyNoBrowserErrors); - beforeEach(() => { browser.get(URL); }); + beforeEach(() => { + browser.get(URL); + }); it('should display correct key names', function() { const firstArea = element.all(by.css('.sample-area')).get(0); @@ -78,5 +79,4 @@ describe('key_events', function() { secondArea.sendKeys(Key.CONTROL, Key.SHIFT, Key.ENTER); expect(secondArea.getText()).toEqual(''); }); - }); diff --git a/modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.ts b/modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.ts index 8fd35bea15aed..25c96ee92c0af 100644 --- a/modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.ts +++ b/modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.ts @@ -11,7 +11,6 @@ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('Model-Driven Forms', function() { - afterEach(verifyNoBrowserErrors); const URL = '/'; diff --git a/modules/playground/e2e_test/relative_assets/assets_spec.ts b/modules/playground/e2e_test/relative_assets/assets_spec.ts index 1b777c6d2d0a1..eb57cfe5c3323 100644 --- a/modules/playground/e2e_test/relative_assets/assets_spec.ts +++ b/modules/playground/e2e_test/relative_assets/assets_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {$, ExpectedConditions, browser, by, element} from 'protractor'; +import {$, browser, by, element, ExpectedConditions} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; @@ -16,7 +16,6 @@ function waitForElement(selector: string) { } describe('relative assets relative-app', () => { - afterEach(verifyNoBrowserErrors); const URL = '/'; diff --git a/modules/playground/e2e_test/routing/routing_spec.ts b/modules/playground/e2e_test/routing/routing_spec.ts index 9e28ba0d41752..f71e7eed8cf5f 100644 --- a/modules/playground/e2e_test/routing/routing_spec.ts +++ b/modules/playground/e2e_test/routing/routing_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {$, ExpectedConditions, browser, by, element} from 'protractor'; +import {$, browser, by, element, ExpectedConditions} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; @@ -16,7 +16,6 @@ function waitForElement(selector: string) { } describe('routing inbox-app', () => { - afterEach(verifyNoBrowserErrors); describe('index view', () => { diff --git a/modules/playground/e2e_test/svg/svg_spec.ts b/modules/playground/e2e_test/svg/svg_spec.ts index 0c58cab353616..7cbeb29b98b50 100644 --- a/modules/playground/e2e_test/svg/svg_spec.ts +++ b/modules/playground/e2e_test/svg/svg_spec.ts @@ -11,15 +11,15 @@ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('SVG', function() { - const URL = '/'; afterEach(verifyNoBrowserErrors); - beforeEach(() => { browser.get(URL); }); + beforeEach(() => { + browser.get(URL); + }); it('should display SVG component contents', function() { const svgText = element.all(by.css('g text')).get(0); expect(svgText.getText()).toEqual('Hello'); }); - }); diff --git a/modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.ts b/modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.ts index b822ad49cd2aa..96f0efc869c05 100644 --- a/modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.ts +++ b/modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.ts @@ -11,7 +11,6 @@ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('Template-Driven Forms', function() { - afterEach(verifyNoBrowserErrors); const URL = '/'; diff --git a/modules/playground/e2e_test/web_workers/input/input_spec.ts b/modules/playground/e2e_test/web_workers/input/input_spec.ts index 0659ba5adf8d8..bd73b09ccf81f 100644 --- a/modules/playground/e2e_test/web_workers/input/input_spec.ts +++ b/modules/playground/e2e_test/web_workers/input/input_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {ExpectedConditions, browser, by, element, protractor} from 'protractor'; +import {browser, by, element, ExpectedConditions, protractor} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../e2e_util/e2e_util'; diff --git a/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts b/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts index a271f82ce5277..ecb474a84f486 100644 --- a/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts +++ b/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {ExpectedConditions, browser, by, element, protractor} from 'protractor'; +import {browser, by, element, ExpectedConditions, protractor} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../e2e_util/e2e_util'; @@ -27,7 +27,6 @@ describe('WebWorkers Kitchen Sink', function() { const elem = element(by.css(selector)); browser.wait(ExpectedConditions.textToBePresentInElement(elem, 'hello world!'), 5000); expect(elem.getText()).toEqual('hello world!'); - }); it('should change greeting', () => { diff --git a/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts b/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts index d5c1ec34ca878..23d59484addad 100644 --- a/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts +++ b/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts @@ -6,14 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ -import {ExpectedConditions, browser, by, element, protractor} from 'protractor'; +import {browser, by, element, ExpectedConditions, protractor} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../e2e_util/e2e_util'; const URL = '/'; describe('MessageBroker', function() { - afterEach(() => { verifyNoBrowserErrors(); browser.ignoreSynchronization = false; diff --git a/modules/playground/e2e_test/web_workers/router/router_spec.ts b/modules/playground/e2e_test/web_workers/router/router_spec.ts index 736e01fc54283..752687c20c9dd 100644 --- a/modules/playground/e2e_test/web_workers/router/router_spec.ts +++ b/modules/playground/e2e_test/web_workers/router/router_spec.ts @@ -69,7 +69,9 @@ describe('WebWorker Router', () => { browser.wait(() => { const deferred = protractor.promise.defer(); const elem = element(by.css(contentSelector)); - elem.getText().then((text: string) => { return deferred.fulfill(text === expected); }); + elem.getText().then((text: string) => { + return deferred.fulfill(text === expected); + }); return deferred.promise; }, 5000); } @@ -77,8 +79,9 @@ describe('WebWorker Router', () => { function waitForUrl(regex: RegExp): void { browser.wait(() => { const deferred = protractor.promise.defer(); - browser.getCurrentUrl().then( - (url: string) => { return deferred.fulfill(url.match(regex) !== null); }); + browser.getCurrentUrl().then((url: string) => { + return deferred.fulfill(url.match(regex) !== null); + }); return deferred.promise; }, 5000); } diff --git a/modules/playground/e2e_test/web_workers/todo/todo_spec.ts b/modules/playground/e2e_test/web_workers/todo/todo_spec.ts index f1a54158663db..2af60cf400fe2 100644 --- a/modules/playground/e2e_test/web_workers/todo/todo_spec.ts +++ b/modules/playground/e2e_test/web_workers/todo/todo_spec.ts @@ -26,7 +26,6 @@ describe('WebWorkers Todo', function() { waitForBootstrap(); expect(element(by.css('#todoapp header')).getText()).toEqual('todos'); }); - }); function waitForBootstrap(): void { diff --git a/modules/playground/e2e_test/zippy_component/zippy_spec.ts b/modules/playground/e2e_test/zippy_component/zippy_spec.ts index e3d7f25043564..6e66e4049be7f 100644 --- a/modules/playground/e2e_test/zippy_component/zippy_spec.ts +++ b/modules/playground/e2e_test/zippy_component/zippy_spec.ts @@ -11,13 +11,14 @@ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../e2e_util/e2e_util'; describe('Zippy Component', function() { - afterEach(verifyNoBrowserErrors); describe('zippy', function() { const URL = '/'; - beforeEach(function() { browser.get(URL); }); + beforeEach(function() { + browser.get(URL); + }); it('should change the zippy title depending on it\'s state', function() { const zippyTitle = element(by.css('.zippy__title')); diff --git a/modules/playground/src/animate/app/animate-app.ts b/modules/playground/src/animate/app/animate-app.ts index 273fa5441563a..14f55429b46a8 100644 --- a/modules/playground/src/animate/app/animate-app.ts +++ b/modules/playground/src/animate/app/animate-app.ts @@ -87,7 +87,9 @@ export class AnimateApp { alert(`backgroundAnimation has ${phase} from ${data['fromState']} to ${data['toState']}`); } - get state() { return this._state; } + get state() { + return this._state; + } set state(s) { this._state = s; if (s == 'void') { diff --git a/modules/playground/src/async/index.ts b/modules/playground/src/async/index.ts index d3405212e02c8..5036c61f5e0a0 100644 --- a/modules/playground/src/async/index.ts +++ b/modules/playground/src/async/index.ts @@ -43,7 +43,9 @@ class AsyncApplication { multiTimeoutId: any = null; intervalId: any = null; - increment(): void { this.val1++; } + increment(): void { + this.val1++; + } delayedIncrement(): void { this.cancelDelayedIncrement(); diff --git a/modules/playground/src/gestures/index.ts b/modules/playground/src/gestures/index.ts index 2dbc531eb68ce..56f3c1c21b6cd 100644 --- a/modules/playground/src/gestures/index.ts +++ b/modules/playground/src/gestures/index.ts @@ -16,11 +16,17 @@ class GesturesCmp { pinchScale: number = 1; rotateAngle: number = 0; - onSwipe(event: HammerInput): void { this.swipeDirection = event.deltaX > 0 ? 'right' : 'left'; } + onSwipe(event: HammerInput): void { + this.swipeDirection = event.deltaX > 0 ? 'right' : 'left'; + } - onPinch(event: HammerInput): void { this.pinchScale = event.scale; } + onPinch(event: HammerInput): void { + this.pinchScale = event.scale; + } - onRotate(event: HammerInput): void { this.rotateAngle = event.rotation; } + onRotate(event: HammerInput): void { + this.rotateAngle = event.rotation; + } } @NgModule({declarations: [GesturesCmp], bootstrap: [GesturesCmp], imports: [BrowserModule]}) diff --git a/modules/playground/src/hello_world/index.ts b/modules/playground/src/hello_world/index.ts index 5a449f7f3ec09..c0a37bded689c 100644 --- a/modules/playground/src/hello_world/index.ts +++ b/modules/playground/src/hello_world/index.ts @@ -48,9 +48,13 @@ export class RedDec { export class HelloCmp { greeting: string; - constructor(service: GreetingService) { this.greeting = service.greeting; } + constructor(service: GreetingService) { + this.greeting = service.greeting; + } - changeGreeting(): void { this.greeting = 'howdy'; } + changeGreeting(): void { + this.greeting = 'howdy'; + } } @NgModule({declarations: [HelloCmp, RedDec], bootstrap: [HelloCmp], imports: [BrowserModule]}) diff --git a/modules/playground/src/key_events/index.ts b/modules/playground/src/key_events/index.ts index e73aaf437b14e..ed4c34bf67683 100644 --- a/modules/playground/src/key_events/index.ts +++ b/modules/playground/src/key_events/index.ts @@ -36,7 +36,9 @@ export class KeyEventsApp { event.preventDefault(); } - resetShiftEnter(): void { this.shiftEnter = false; } + resetShiftEnter(): void { + this.shiftEnter = false; + } /** * Get a more readable version of current pressed keys. diff --git a/modules/playground/src/model_driven_forms/index.ts b/modules/playground/src/model_driven_forms/index.ts index b71d22cf76bda..94138296a5b59 100644 --- a/modules/playground/src/model_driven_forms/index.ts +++ b/modules/playground/src/model_driven_forms/index.ts @@ -52,7 +52,9 @@ export class ShowError { controlPath: string; errorTypes: string[]; - constructor(@Host() formDir: FormGroupDirective) { this.formDir = formDir; } + constructor(@Host() formDir: FormGroupDirective) { + this.formDir = formDir; + } get errorMessage(): string { const form: FormGroup = this.formDir.form; diff --git a/modules/playground/src/order_management/index.ts b/modules/playground/src/order_management/index.ts index b83b10b9f1fea..10d933702f668 100644 --- a/modules/playground/src/order_management/index.ts +++ b/modules/playground/src/order_management/index.ts @@ -23,7 +23,9 @@ class OrderItem { public orderItemId: number, public orderId: number, public productName: string, public qty: number, public unitPrice: number) {} - get total(): number { return this.qty * this.unitPrice; } + get total(): number { + return this.qty * this.unitPrice; + } } class Order { @@ -31,8 +33,12 @@ class Order { public orderId: number, public customerName: string, public limit: number, private _dataService: DataService) {} - get items(): OrderItem[] { return this._dataService.itemsFor(this); } - get total(): number { return this.items.map(i => i.total).reduce((a, b) => a + b, 0); } + get items(): OrderItem[] { + return this._dataService.itemsFor(this); + } + get total(): number { + return this.items.map(i => i.total).reduce((a, b) => a + b, 0); + } } @@ -69,7 +75,9 @@ export class DataService { this.orderItems.push(new OrderItem(_nextId++, order.orderId, '', 0, 0)); } - deleteItem(item: OrderItem): void { this.orderItems.splice(this.orderItems.indexOf(item), 1); } + deleteItem(item: OrderItem): void { + this.orderItems.splice(this.orderItems.indexOf(item), 1); + } } @@ -107,8 +115,12 @@ export class DataService { export class OrderListComponent { orders: Order[]; - constructor(private _service: DataService) { this.orders = _service.orders; } - select(order: Order): void { this._service.currentOrder = order; } + constructor(private _service: DataService) { + this.orders = _service.orders; + } + select(order: Order): void { + this._service.currentOrder = order; + } } @@ -141,7 +153,9 @@ export class OrderItemComponent { @Input() item: OrderItem; @Output() delete = new EventEmitter(); - onDelete(): void { this.delete.emit(this.item); } + onDelete(): void { + this.delete.emit(this.item); + } } @Component({ @@ -176,11 +190,17 @@ export class OrderItemComponent { export class OrderDetailsComponent { constructor(private _service: DataService) {} - get order(): Order { return this._service.currentOrder; } + get order(): Order { + return this._service.currentOrder; + } - deleteItem(item: OrderItem): void { this._service.deleteItem(item); } + deleteItem(item: OrderItem): void { + this._service.deleteItem(item); + } - addItem(): void { this._service.addItemForOrder(this.order); } + addItem(): void { + this._service.addItemForOrder(this.order); + } } @Component({ diff --git a/modules/playground/src/person_management/index.ts b/modules/playground/src/person_management/index.ts index d981acad14575..e660952e1b294 100644 --- a/modules/playground/src/person_management/index.ts +++ b/modules/playground/src/person_management/index.ts @@ -35,9 +35,15 @@ class Person { this.personId = _nextId++; } - get age(): number { return 2015 - this.yearOfBirth; } - get fullName(): string { return `${this.firstName} ${this.lastName}`; } - get friendNames(): string { return this.friends.map(f => f.fullName).join(', '); } + get age(): number { + return 2015 - this.yearOfBirth; + } + get fullName(): string { + return `${this.firstName} ${this.lastName}`; + } + get friendNames(): string { + return this.friends.map(f => f.fullName).join(', '); + } } @@ -106,7 +112,9 @@ export class DataService { }) export class FullNameComponent { constructor(private _service: DataService) {} - get person(): Person { return this._service.currentPerson; } + get person(): Person { + return this._service.currentPerson; + } } @Component({ @@ -158,7 +166,9 @@ export class FullNameComponent { }) export class PersonsDetailComponent { constructor(private _service: DataService) {} - get person(): Person { return this._service.currentPerson; } + get person(): Person { + return this._service.currentPerson; + } } @Component({ @@ -179,9 +189,13 @@ export class PersonsDetailComponent { export class PersonsComponent { persons: Person[]; - constructor(private _service: DataService) { this.persons = _service.persons; } + constructor(private _service: DataService) { + this.persons = _service.persons; + } - select(person: Person): void { this._service.currentPerson = person; } + select(person: Person): void { + this._service.currentPerson = person; + } } @@ -199,8 +213,12 @@ export class PersonsComponent { export class PersonManagementApplication { mode: string; - switchToEditName(): void { this.mode = 'editName'; } - switchToPersonList(): void { this.mode = 'personList'; } + switchToEditName(): void { + this.mode = 'editName'; + } + switchToPersonList(): void { + this.mode = 'personList'; + } } @NgModule({ diff --git a/modules/playground/src/routing/app/inbox-app.ts b/modules/playground/src/routing/app/inbox-app.ts index 2d87ef3719da6..4e06ab860192f 100644 --- a/modules/playground/src/routing/app/inbox-app.ts +++ b/modules/playground/src/routing/app/inbox-app.ts @@ -29,7 +29,8 @@ export class InboxRecord { email: string, firstName: string, lastName: string, - date: string, draft?: boolean + date: string, + draft?: boolean } = null) { if (data) { this.setData(data); @@ -43,7 +44,8 @@ export class InboxRecord { email: string, firstName: string, lastName: string, - date: string, draft?: boolean + date: string, + draft?: boolean }) { this.id = record.id; this.subject = record.subject; diff --git a/modules/playground/src/routing/app/inbox-detail.ts b/modules/playground/src/routing/app/inbox-detail.ts index d59ccd0e0c1ab..9b95cadcf0a9d 100644 --- a/modules/playground/src/routing/app/inbox-detail.ts +++ b/modules/playground/src/routing/app/inbox-detail.ts @@ -17,8 +17,11 @@ export class InboxDetailCmp { private ready: boolean = false; constructor(db: DbService, route: ActivatedRoute) { - route.paramMap.forEach( - p => { db.email(p.get('id')).then((data) => { this.record.setData(data); }); }); + route.paramMap.forEach(p => { + db.email(p.get('id')).then((data) => { + this.record.setData(data); + }); + }); } } diff --git a/modules/playground/src/sourcemap/index.ts b/modules/playground/src/sourcemap/index.ts index 2a0622683da9d..80e3b844588d4 100644 --- a/modules/playground/src/sourcemap/index.ts +++ b/modules/playground/src/sourcemap/index.ts @@ -16,7 +16,9 @@ import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; ` }) export class ErrorComponent { - createError(): void { throw new Error('Sourcemap test'); } + createError(): void { + throw new Error('Sourcemap test'); + } } @NgModule({declarations: [ErrorComponent], bootstrap: [ErrorComponent], imports: [BrowserModule]}) diff --git a/modules/playground/src/template_driven_forms/index.ts b/modules/playground/src/template_driven_forms/index.ts index e5c316370ba66..59f3f25080a91 100644 --- a/modules/playground/src/template_driven_forms/index.ts +++ b/modules/playground/src/template_driven_forms/index.ts @@ -78,7 +78,9 @@ export class ShowError { controlPath: string; errorTypes: string[]; - constructor(@Host() formDir: NgForm) { this.formDir = formDir; } + constructor(@Host() formDir: NgForm) { + this.formDir = formDir; + } get errorMessage(): string { const form: FormGroup = this.formDir.form; diff --git a/modules/playground/src/todo/app/TodoStore.ts b/modules/playground/src/todo/app/TodoStore.ts index e8bde62ae16ae..5938b9674ca2c 100644 --- a/modules/playground/src/todo/app/TodoStore.ts +++ b/modules/playground/src/todo/app/TodoStore.ts @@ -14,14 +14,18 @@ export abstract class KeyModel { } export class Todo extends KeyModel { - constructor(key: number, public title: string, public completed: boolean) { super(key); } + constructor(key: number, public title: string, public completed: boolean) { + super(key); + } } @Injectable() export class TodoFactory { private _uid: number = 0; - nextUid(): number { return ++this._uid; } + nextUid(): number { + return ++this._uid; + } create(title: string, isCompleted: boolean): Todo { return new Todo(this.nextUid(), title, isCompleted); @@ -33,9 +37,13 @@ export class TodoFactory { export class Store { list: T[] = []; - add(record: T): void { this.list.push(record); } + add(record: T): void { + this.list.push(record); + } - remove(record: T): void { this.removeBy((item) => item === record); } + remove(record: T): void { + this.removeBy((item) => item === record); + } removeBy(callback: (record: T) => boolean): void { this.list = this.list.filter((record) => !callback(record)); diff --git a/modules/playground/src/todo/index.ts b/modules/playground/src/todo/index.ts index 3e6526cf9488a..04a1d55fabf5e 100644 --- a/modules/playground/src/todo/index.ts +++ b/modules/playground/src/todo/index.ts @@ -23,7 +23,9 @@ export class TodoApp { inputElement.value = ''; } - editTodo(todo: Todo): void { this.todoEdit = todo; } + editTodo(todo: Todo): void { + this.todoEdit = todo; + } doneEditing($event: KeyboardEvent, todo: Todo): void { const which = $event.which; @@ -37,18 +39,28 @@ export class TodoApp { } } - addTodo(newTitle: string): void { this.todoStore.add(this.factory.create(newTitle, false)); } + addTodo(newTitle: string): void { + this.todoStore.add(this.factory.create(newTitle, false)); + } - completeMe(todo: Todo): void { todo.completed = !todo.completed; } + completeMe(todo: Todo): void { + todo.completed = !todo.completed; + } - deleteMe(todo: Todo): void { this.todoStore.remove(todo); } + deleteMe(todo: Todo): void { + this.todoStore.remove(todo); + } toggleAll($event: MouseEvent): void { const isComplete = ($event.target as HTMLInputElement).checked; - this.todoStore.list.forEach((todo: Todo) => { todo.completed = isComplete; }); + this.todoStore.list.forEach((todo: Todo) => { + todo.completed = isComplete; + }); } - clearCompleted(): void { this.todoStore.removeBy((todo: Todo) => todo.completed); } + clearCompleted(): void { + this.todoStore.removeBy((todo: Todo) => todo.completed); + } } @NgModule({declarations: [TodoApp], bootstrap: [TodoApp], imports: [BrowserModule]}) diff --git a/modules/playground/src/upgrade/index.ts b/modules/playground/src/upgrade/index.ts index 7b737ebeab7cb..6a336abc9cc18 100644 --- a/modules/playground/src/upgrade/index.ts +++ b/modules/playground/src/upgrade/index.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Component, EventEmitter, Input, NgModule, Output, forwardRef} from '@angular/core'; +import {Component, EventEmitter, forwardRef, Input, NgModule, Output} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {UpgradeAdapter} from '@angular/upgrade'; @@ -30,7 +30,9 @@ const styles = [` const adapter = new UpgradeAdapter(forwardRef(() => Ng2AppModule)); const ng1module = angular.module('myExample', []); -ng1module.controller('Index', function($scope: any) { $scope.name = 'World'; }); +ng1module.controller('Index', function($scope: any) { + $scope.name = 'World'; +}); ng1module.directive('ng1User', function() { return { diff --git a/modules/playground/src/web_workers/input/index_common.ts b/modules/playground/src/web_workers/input/index_common.ts index 6ac81ce050a92..f820e28e52fd0 100644 --- a/modules/playground/src/web_workers/input/index_common.ts +++ b/modules/playground/src/web_workers/input/index_common.ts @@ -26,7 +26,11 @@ export class InputCmp { inputVal = ''; textareaVal = ''; - inputChanged(e: Event) { this.inputVal = (e.target as HTMLInputElement).value; } + inputChanged(e: Event) { + this.inputVal = (e.target as HTMLInputElement).value; + } - textAreaChanged(e: Event) { this.textareaVal = (e.target as HTMLTextAreaElement).value; } + textAreaChanged(e: Event) { + this.textareaVal = (e.target as HTMLTextAreaElement).value; + } } diff --git a/modules/playground/src/web_workers/kitchen_sink/index_common.ts b/modules/playground/src/web_workers/kitchen_sink/index_common.ts index 387c95d5995cf..53d3d5a508298 100644 --- a/modules/playground/src/web_workers/kitchen_sink/index_common.ts +++ b/modules/playground/src/web_workers/kitchen_sink/index_common.ts @@ -49,9 +49,15 @@ export class HelloCmp { greeting: string; lastKey: string = '(none)'; - constructor(service: GreetingService) { this.greeting = service.greeting; } + constructor(service: GreetingService) { + this.greeting = service.greeting; + } - changeGreeting(): void { this.greeting = 'howdy'; } + changeGreeting(): void { + this.greeting = 'howdy'; + } - onKeyDown(event: KeyboardEvent): void { this.lastKey = String.fromCharCode(event.keyCode); } + onKeyDown(event: KeyboardEvent): void { + this.lastKey = String.fromCharCode(event.keyCode); + } } diff --git a/modules/playground/src/web_workers/message_broker/index.ts b/modules/playground/src/web_workers/message_broker/index.ts index 0f6979eecea1c..c00828e9e77a5 100644 --- a/modules/playground/src/web_workers/message_broker/index.ts +++ b/modules/playground/src/web_workers/message_broker/index.ts @@ -7,7 +7,7 @@ */ import {PlatformRef} from '@angular/core'; -import {ClientMessageBrokerFactory, FnArg, SerializerTypes, UiArguments, bootstrapWorkerUi} from '@angular/platform-webworker'; +import {bootstrapWorkerUi, ClientMessageBrokerFactory, FnArg, SerializerTypes, UiArguments} from '@angular/platform-webworker'; const ECHO_CHANNEL = 'ECHO'; diff --git a/modules/playground/src/web_workers/message_broker/index_common.ts b/modules/playground/src/web_workers/message_broker/index_common.ts index 181b5811669c6..b451fcc8df41c 100644 --- a/modules/playground/src/web_workers/message_broker/index_common.ts +++ b/modules/playground/src/web_workers/message_broker/index_common.ts @@ -19,5 +19,7 @@ export class App { 'echo', [SerializerTypes.PRIMITIVE], this._echo, SerializerTypes.PRIMITIVE); } - private _echo(val: string) { return new Promise((res) => res(val)); } + private _echo(val: string) { + return new Promise((res) => res(val)); + } } diff --git a/modules/playground/src/web_workers/router/index.ts b/modules/playground/src/web_workers/router/index.ts index 788553247276a..50e4244c3fe6a 100644 --- a/modules/playground/src/web_workers/router/index.ts +++ b/modules/playground/src/web_workers/router/index.ts @@ -6,6 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -import {WORKER_UI_LOCATION_PROVIDERS, bootstrapWorkerUi} from '@angular/platform-webworker'; +import {bootstrapWorkerUi, WORKER_UI_LOCATION_PROVIDERS} from '@angular/platform-webworker'; bootstrapWorkerUi('loader.js', WORKER_UI_LOCATION_PROVIDERS); diff --git a/modules/playground/src/web_workers/todo/index_common.ts b/modules/playground/src/web_workers/todo/index_common.ts index 584ae61e86ee4..443557f9b8cc7 100644 --- a/modules/playground/src/web_workers/todo/index_common.ts +++ b/modules/playground/src/web_workers/todo/index_common.ts @@ -36,11 +36,17 @@ export class TodoApp { } } - editTodo(todo: Todo): void { this.todoEdit = todo; } + editTodo(todo: Todo): void { + this.todoEdit = todo; + } - addTodo(newTitle: string): void { this.todoStore.add(this.factory.create(newTitle, false)); } + addTodo(newTitle: string): void { + this.todoStore.add(this.factory.create(newTitle, false)); + } - completeMe(todo: Todo): void { todo.completed = !todo.completed; } + completeMe(todo: Todo): void { + todo.completed = !todo.completed; + } toggleCompleted(): void { this.hideActive = !this.hideActive; @@ -57,12 +63,18 @@ export class TodoApp { this.hideActive = false; } - deleteMe(todo: Todo): void { this.todoStore.remove(todo); } + deleteMe(todo: Todo): void { + this.todoStore.remove(todo); + } toggleAll($event: MouseEvent): void { this.isComplete = !this.isComplete; - this.todoStore.list.forEach((todo: Todo) => { todo.completed = this.isComplete; }); + this.todoStore.list.forEach((todo: Todo) => { + todo.completed = this.isComplete; + }); } - clearCompleted(): void { this.todoStore.removeBy((todo: Todo) => todo.completed); } + clearCompleted(): void { + this.todoStore.removeBy((todo: Todo) => todo.completed); + } } diff --git a/modules/playground/src/web_workers/todo/services/TodoStore.ts b/modules/playground/src/web_workers/todo/services/TodoStore.ts index c889788eb83b8..3486fe7fc131d 100644 --- a/modules/playground/src/web_workers/todo/services/TodoStore.ts +++ b/modules/playground/src/web_workers/todo/services/TodoStore.ts @@ -25,7 +25,9 @@ export class Todo extends KeyModel { export class TodoFactory { private _uid: number = 0; - nextUid(): number { return ++this._uid; } + nextUid(): number { + return ++this._uid; + } create(title: string, isCompleted: boolean): Todo { return new Todo(this.nextUid(), title, isCompleted); @@ -37,9 +39,13 @@ export class TodoFactory { export class Store { list: T[] = []; - add(record: T): void { this.list.push(record); } + add(record: T): void { + this.list.push(record); + } - remove(record: T): void { this.removeBy((item) => item === record); } + remove(record: T): void { + this.removeBy((item) => item === record); + } removeBy(callback: (record: T) => boolean): void { this.list = this.list.filter((record) => !callback(record)); diff --git a/modules/playground/src/zippy_component/index.ts b/modules/playground/src/zippy_component/index.ts index 00ede4cd6cae4..9d1b5706db338 100644 --- a/modules/playground/src/zippy_component/index.ts +++ b/modules/playground/src/zippy_component/index.ts @@ -26,7 +26,9 @@ import {Zippy} from './app/zippy'; export class ZippyApp { logs: string[] = []; - pushLog(log: string) { this.logs.push(log); } + pushLog(log: string) { + this.logs.push(log); + } } @NgModule({declarations: [ZippyApp, Zippy], bootstrap: [ZippyApp], imports: [BrowserModule]}) diff --git a/packages/animations/browser/src/dsl/animation.ts b/packages/animations/browser/src/dsl/animation.ts index e21494a980a86..a9ba429ca0048 100644 --- a/packages/animations/browser/src/dsl/animation.ts +++ b/packages/animations/browser/src/dsl/animation.ts @@ -22,7 +22,7 @@ export class Animation { const errors: any[] = []; const ast = buildAnimationAst(_driver, input, errors); if (errors.length) { - const errorMessage = `animation validation failed:\n${errors.join("\n")}`; + const errorMessage = `animation validation failed:\n${errors.join('\n')}`; throw new Error(errorMessage); } this._animationAst = ast; @@ -42,7 +42,7 @@ export class Animation { this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors); if (errors.length) { - const errorMessage = `animation building failed:\n${errors.join("\n")}`; + const errorMessage = `animation building failed:\n${errors.join('\n')}`; throw new Error(errorMessage); } return result; diff --git a/packages/animations/browser/src/dsl/animation_ast.ts b/packages/animations/browser/src/dsl/animation_ast.ts index dd5a46363becc..8d57c09f0a5e3 100644 --- a/packages/animations/browser/src/dsl/animation_ast.ts +++ b/packages/animations/browser/src/dsl/animation_ast.ts @@ -74,7 +74,9 @@ export interface StyleAst extends Ast { isEmptyStep?: boolean; } -export interface KeyframesAst extends Ast { styles: StyleAst[]; } +export interface KeyframesAst extends Ast { + styles: StyleAst[]; +} export interface ReferenceAst extends Ast { animation: Ast; diff --git a/packages/animations/browser/src/dsl/animation_ast_builder.ts b/packages/animations/browser/src/dsl/animation_ast_builder.ts index e883eb742e065..5184e74589d5d 100644 --- a/packages/animations/browser/src/dsl/animation_ast_builder.ts +++ b/packages/animations/browser/src/dsl/animation_ast_builder.ts @@ -5,11 +5,11 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimateTimings, AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationQueryMetadata, AnimationQueryOptions, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, style, ɵStyleData} from '@angular/animations'; +import {AnimateTimings, AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationQueryMetadata, AnimationQueryOptions, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, AUTO_STYLE, style, ɵStyleData} from '@angular/animations'; import {AnimationDriver} from '../render/animation_driver'; import {getOrSetAsInMap} from '../render/shared'; -import {ENTER_SELECTOR, LEAVE_SELECTOR, NG_ANIMATING_SELECTOR, NG_TRIGGER_SELECTOR, SUBSTITUTION_EXPR_START, copyObj, extractStyleParams, iteratorToArray, normalizeAnimationEntry, resolveTiming, validateStyleParams, visitDslNode} from '../util'; +import {copyObj, ENTER_SELECTOR, extractStyleParams, iteratorToArray, LEAVE_SELECTOR, NG_ANIMATING_SELECTOR, NG_TRIGGER_SELECTOR, normalizeAnimationEntry, resolveTiming, SUBSTITUTION_EXPR_START, validateStyleParams, visitDslNode} from '../util'; import {AnimateAst, AnimateChildAst, AnimateRefAst, Ast, DynamicTimingAst, GroupAst, KeyframesAst, QueryAst, ReferenceAst, SequenceAst, StaggerAst, StateAst, StyleAst, TimingAst, TransitionAst, TriggerAst} from './animation_ast'; import {AnimationDslVisitor} from './animation_dsl_visitor'; @@ -55,7 +55,7 @@ const SELF_TOKEN_REGEX = new RegExp(`\s*${SELF_TOKEN}\s*,?`, 'g'); * Otherwise an error will be thrown. */ export function buildAnimationAst( - driver: AnimationDriver, metadata: AnimationMetadata | AnimationMetadata[], + driver: AnimationDriver, metadata: AnimationMetadata|AnimationMetadata[], errors: any[]): Ast { return new AnimationAstBuilderVisitor(driver).build(metadata, errors); } @@ -114,7 +114,11 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { return { type: AnimationMetadataType.Trigger, - name: metadata.name, states, transitions, queryCount, depCount, + name: metadata.name, + states, + transitions, + queryCount, + depCount, options: null }; } @@ -139,8 +143,10 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { }); if (missingSubs.size) { const missingSubsArr = iteratorToArray(missingSubs.values()); - context.errors.push( - `state("${metadata.name}", ...) must define default values for all the following style substitutions: ${missingSubsArr.join(', ')}`); + context.errors.push(`state("${ + metadata + .name}", ...) must define default values for all the following style substitutions: ${ + missingSubsArr.join(', ')}`); } } @@ -210,7 +216,7 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { let isEmpty = false; if (!styleMetadata) { isEmpty = true; - const newStyleData: {[prop: string]: string | number} = {}; + const newStyleData: {[prop: string]: string|number} = {}; if (timingAst.easing) { newStyleData['easing'] = timingAst.easing; } @@ -239,9 +245,9 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { private _makeStyleAst(metadata: AnimationStyleMetadata, context: AnimationAstBuilderContext): StyleAst { - const styles: (ɵStyleData | string)[] = []; + const styles: (ɵStyleData|string)[] = []; if (Array.isArray(metadata.styles)) { - (metadata.styles as(ɵStyleData | string)[]).forEach(styleTuple => { + (metadata.styles as (ɵStyleData | string)[]).forEach(styleTuple => { if (typeof styleTuple == 'string') { if (styleTuple == AUTO_STYLE) { styles.push(styleTuple); @@ -282,7 +288,8 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { type: AnimationMetadataType.Style, styles, easing: collectedEasing, - offset: metadata.offset, containsDynamicStyles, + offset: metadata.offset, + containsDynamicStyles, options: null }; } @@ -300,19 +307,22 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { Object.keys(tuple).forEach(prop => { if (!this._driver.validateStyleProperty(prop)) { - context.errors.push( - `The provided animation property "${prop}" is not a supported CSS property for animations`); + context.errors.push(`The provided animation property "${ + prop}" is not a supported CSS property for animations`); return; } - const collectedStyles = context.collectedStyles[context.currentQuerySelector !]; + const collectedStyles = context.collectedStyles[context.currentQuerySelector!]; const collectedEntry = collectedStyles[prop]; let updateCollectedStyle = true; if (collectedEntry) { if (startTime != endTime && startTime >= collectedEntry.startTime && endTime <= collectedEntry.endTime) { - context.errors.push( - `The CSS property "${prop}" that exists between the times of "${collectedEntry.startTime}ms" and "${collectedEntry.endTime}ms" is also being animated in a parallel animation between the times of "${startTime}ms" and "${endTime}ms"`); + context.errors.push(`The CSS property "${prop}" that exists between the times of "${ + collectedEntry.startTime}ms" and "${ + collectedEntry + .endTime}ms" is also being animated in a parallel animation between the times of "${ + startTime}ms" and "${endTime}ms"`); updateCollectedStyle = false; } @@ -383,7 +393,7 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { const limit = length - 1; const currentTime = context.currentTime; - const currentAnimateTimings = context.currentAnimateTimings !; + const currentAnimateTimings = context.currentAnimateTimings!; const animateDuration = currentAnimateTimings.duration; keyframes.forEach((kf, i) => { const offset = generatedOffset > 0 ? (i == limit ? 1 : (generatedOffset * i)) : offsets[i]; @@ -427,7 +437,7 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { } visitQuery(metadata: AnimationQueryMetadata, context: AnimationAstBuilderContext): QueryAst { - const parentSelector = context.currentQuerySelector !; + const parentSelector = context.currentQuerySelector!; const options = (metadata.options || {}) as AnimationQueryOptions; context.queryCount++; @@ -445,7 +455,9 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { type: AnimationMetadataType.Query, selector, limit: options.limit || 0, - optional: !!options.optional, includeSelf, animation, + optional: !!options.optional, + includeSelf, + animation, originalSelector: metadata.selector, options: normalizeAnimationOptions(metadata.options) }; @@ -462,7 +474,8 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor { return { type: AnimationMetadataType.Stagger, - animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context), timings, + animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context), + timings, options: null }; } @@ -483,7 +496,7 @@ function normalizeSelector(selector: string): [string, boolean] { } -function normalizeParams(obj: {[key: string]: any} | any): {[key: string]: any}|null { +function normalizeParams(obj: {[key: string]: any}|any): {[key: string]: any}|null { return obj ? copyObj(obj) : null; } @@ -504,7 +517,7 @@ export class AnimationAstBuilderContext { constructor(public errors: any[]) {} } -function consumeOffset(styles: ɵStyleData | string | (ɵStyleData | string)[]): number|null { +function consumeOffset(styles: ɵStyleData|string|(ɵStyleData | string)[]): number|null { if (typeof styles == 'string') return null; let offset: number|null = null; @@ -529,7 +542,7 @@ function isObject(value: any): boolean { return !Array.isArray(value) && typeof value == 'object'; } -function constructTimingAst(value: string | number | AnimateTimings, errors: any[]) { +function constructTimingAst(value: string|number|AnimateTimings, errors: any[]) { let timings: AnimateTimings|null = null; if (value.hasOwnProperty('duration')) { timings = value as AnimateTimings; @@ -551,11 +564,11 @@ function constructTimingAst(value: string | number | AnimateTimings, errors: any return makeTimingAst(timings.duration, timings.delay, timings.easing); } -function normalizeAnimationOptions(options: AnimationOptions | null): AnimationOptions { +function normalizeAnimationOptions(options: AnimationOptions|null): AnimationOptions { if (options) { options = copyObj(options); if (options['params']) { - options['params'] = normalizeParams(options['params']) !; + options['params'] = normalizeParams(options['params'])!; } } else { options = {}; @@ -563,6 +576,6 @@ function normalizeAnimationOptions(options: AnimationOptions | null): AnimationO return options; } -function makeTimingAst(duration: number, delay: number, easing: string | null): TimingAst { +function makeTimingAst(duration: number, delay: number, easing: string|null): TimingAst { return {duration, delay, easing}; } diff --git a/packages/animations/browser/src/dsl/animation_timeline_builder.ts b/packages/animations/browser/src/dsl/animation_timeline_builder.ts index b9bc5b09202df..7995610117a4a 100644 --- a/packages/animations/browser/src/dsl/animation_timeline_builder.ts +++ b/packages/animations/browser/src/dsl/animation_timeline_builder.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimateChildOptions, AnimateTimings, AnimationMetadataType, AnimationOptions, AnimationQueryOptions, ɵPRE_STYLE as PRE_STYLE, ɵStyleData} from '@angular/animations'; +import {AnimateChildOptions, AnimateTimings, AnimationMetadataType, AnimationOptions, AnimationQueryOptions, AUTO_STYLE, ɵPRE_STYLE as PRE_STYLE, ɵStyleData} from '@angular/animations'; import {AnimationDriver} from '../render/animation_driver'; import {copyObj, copyStyles, interpolateParams, iteratorToArray, resolveTiming, resolveTimingValue, visitDslNode} from '../util'; @@ -301,7 +301,7 @@ export class AnimationTimelineBuilderVisitor implements AstVisitor { visitStyle(ast: StyleAst, context: AnimationTimelineContext) { const timeline = context.currentTimeline; - const timings = context.currentAnimateTimings !; + const timings = context.currentAnimateTimings!; // this is a special case for when a style() call // directly follows an animate() call (but not inside of an animate() call) @@ -320,8 +320,8 @@ export class AnimationTimelineBuilderVisitor implements AstVisitor { } visitKeyframes(ast: KeyframesAst, context: AnimationTimelineContext) { - const currentAnimateTimings = context.currentAnimateTimings !; - const startTime = (context.currentTimeline !).duration; + const currentAnimateTimings = context.currentAnimateTimings!; + const startTime = (context.currentTimeline!).duration; const duration = currentAnimateTimings.duration; const innerContext = context.createSubContext(); const innerTimeline = innerContext.currentTimeline; @@ -351,8 +351,9 @@ export class AnimationTimelineBuilderVisitor implements AstVisitor { const options = (ast.options || {}) as AnimationQueryOptions; const delay = options.delay ? resolveTimingValue(options.delay) : 0; - if (delay && (context.previousNode.type === AnimationMetadataType.Style || - (startTime == 0 && context.currentTimeline.getCurrentStyleProperties().length))) { + if (delay && + (context.previousNode.type === AnimationMetadataType.Style || + (startTime == 0 && context.currentTimeline.getCurrentStyleProperties().length))) { context.currentTimeline.snapshotCurrentStyles(); context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; } @@ -365,7 +366,6 @@ export class AnimationTimelineBuilderVisitor implements AstVisitor { context.currentQueryTotal = elms.length; let sameElementTimeline: TimelineBuilder|null = null; elms.forEach((element, i) => { - context.currentQueryIndex = i; const innerContext = context.createSubContext(ast.options, element); if (delay) { @@ -400,7 +400,7 @@ export class AnimationTimelineBuilderVisitor implements AstVisitor { } visitStagger(ast: StaggerAst, context: AnimationTimelineContext) { - const parentContext = context.parentContext !; + const parentContext = context.parentContext!; const tl = context.currentTimeline; const timings = ast.timings; const duration = Math.abs(timings.duration); @@ -460,7 +460,9 @@ export class AnimationTimelineContext { timelines.push(this.currentTimeline); } - get params() { return this.options.params; } + get params() { + return this.options.params; + } updateOptions(options: AnimationOptions|null, skipIfExists?: boolean) { if (!options) return; @@ -479,7 +481,7 @@ export class AnimationTimelineContext { const newParams = newOptions.params; if (newParams) { - let paramsToUpdate: {[name: string]: any} = optionsToUpdate.params !; + let paramsToUpdate: {[name: string]: any} = optionsToUpdate.params!; if (!paramsToUpdate) { paramsToUpdate = this.options.params = {}; } @@ -498,7 +500,9 @@ export class AnimationTimelineContext { const oldParams = this.options.params; if (oldParams) { const params: {[name: string]: any} = options['params'] = {}; - Object.keys(oldParams).forEach(name => { params[name] = oldParams[name]; }); + Object.keys(oldParams).forEach(name => { + params[name] = oldParams[name]; + }); } } return options; @@ -576,8 +580,8 @@ export class AnimationTimelineContext { } if (!optional && results.length == 0) { - errors.push( - `\`query("${originalSelector}")\` returned zero elements. (Use \`query("${originalSelector}", { optional: true })\` if you wish to allow this.)`); + errors.push(`\`query("${originalSelector}")\` returned zero elements. (Use \`query("${ + originalSelector}", { optional: true })\` if you wish to allow this.)`); } return results; } @@ -587,7 +591,7 @@ export class AnimationTimelineContext { export class TimelineBuilder { public duration: number = 0; // TODO(issue/24571): remove '!'. - public easing !: string | null; + public easing!: string|null; private _previousKeyframe: ɵStyleData = {}; private _currentKeyframe: ɵStyleData = {}; private _keyframes = new Map(); @@ -606,7 +610,7 @@ export class TimelineBuilder { } this._localTimelineStyles = Object.create(this._backFill, {}); - this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element) !; + this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element)!; if (!this._globalTimelineStyles) { this._globalTimelineStyles = this._localTimelineStyles; this._elementTimelineStylesLookup.set(element, this._localTimelineStyles); @@ -625,9 +629,13 @@ export class TimelineBuilder { } } - getCurrentStyleProperties(): string[] { return Object.keys(this._currentKeyframe); } + getCurrentStyleProperties(): string[] { + return Object.keys(this._currentKeyframe); + } - get currentTime() { return this.startTime + this.duration; } + get currentTime() { + return this.startTime + this.duration; + } delayNextStep(delay: number) { // in the event that a style() step is placed right before a stagger() @@ -656,7 +664,7 @@ export class TimelineBuilder { if (this._currentKeyframe) { this._previousKeyframe = this._currentKeyframe; } - this._currentKeyframe = this._keyframes.get(this.duration) !; + this._currentKeyframe = this._keyframes.get(this.duration)!; if (!this._currentKeyframe) { this._currentKeyframe = Object.create(this._backFill, {}); this._keyframes.set(this.duration, this._currentKeyframe); @@ -680,7 +688,9 @@ export class TimelineBuilder { this._styleSummary[prop] = {time: this.currentTime, value}; } - allowOnlyTimelineStyles() { return this._currentEmptyStepKeyframe !== this._currentKeyframe; } + allowOnlyTimelineStyles() { + return this._currentEmptyStepKeyframe !== this._currentKeyframe; + } applyEmptyStep(easing: string|null) { if (easing) { @@ -748,7 +758,9 @@ export class TimelineBuilder { }); } - getFinalKeyframe() { return this._keyframes.get(this.duration); } + getFinalKeyframe() { + return this._keyframes.get(this.duration); + } get properties() { const properties: string[] = []; @@ -820,7 +832,9 @@ class SubTimelineBuilder extends TimelineBuilder { this.timings = {duration: timings.duration, delay: timings.delay, easing: timings.easing}; } - containsAnimation(): boolean { return this.keyframes.length > 1; } + containsAnimation(): boolean { + return this.keyframes.length > 1; + } buildKeyframes(): AnimationTimelineInstruction { let keyframes = this.keyframes; @@ -883,13 +897,15 @@ function roundOffset(offset: number, decimalPoints = 3): number { return Math.round(offset * mult) / mult; } -function flattenStyles(input: (ɵStyleData | string)[], allStyles: ɵStyleData) { +function flattenStyles(input: (ɵStyleData|string)[], allStyles: ɵStyleData) { const styles: ɵStyleData = {}; let allProperties: string[]; input.forEach(token => { if (token === '*') { allProperties = allProperties || Object.keys(allStyles); - allProperties.forEach(prop => { styles[prop] = AUTO_STYLE; }); + allProperties.forEach(prop => { + styles[prop] = AUTO_STYLE; + }); } else { copyStyles(token as ɵStyleData, false, styles); } diff --git a/packages/animations/browser/src/dsl/animation_timeline_instruction.ts b/packages/animations/browser/src/dsl/animation_timeline_instruction.ts index 4c10d69a3dfd9..13e4cc4d01c4f 100644 --- a/packages/animations/browser/src/dsl/animation_timeline_instruction.ts +++ b/packages/animations/browser/src/dsl/animation_timeline_instruction.ts @@ -23,7 +23,7 @@ export interface AnimationTimelineInstruction extends AnimationEngineInstruction export function createTimelineInstruction( element: any, keyframes: ɵStyleData[], preStyleProps: string[], postStyleProps: string[], - duration: number, delay: number, easing: string | null = null, + duration: number, delay: number, easing: string|null = null, subTimeline: boolean = false): AnimationTimelineInstruction { return { type: AnimationTransitionInstructionType.TimelineAnimation, @@ -33,6 +33,8 @@ export function createTimelineInstruction( postStyleProps, duration, delay, - totalTime: duration + delay, easing, subTimeline + totalTime: duration + delay, + easing, + subTimeline }; } diff --git a/packages/animations/browser/src/dsl/animation_transition_expr.ts b/packages/animations/browser/src/dsl/animation_transition_expr.ts index 120e97bd2b1cd..9fe58d271a3a6 100644 --- a/packages/animations/browser/src/dsl/animation_transition_expr.ts +++ b/packages/animations/browser/src/dsl/animation_transition_expr.ts @@ -10,7 +10,7 @@ export declare type TransitionMatcherFn = (fromState: any, toState: any, element: any, params: {[key: string]: any}) => boolean; export function parseTransitionExpr( - transitionValue: string | TransitionMatcherFn, errors: string[]): TransitionMatcherFn[] { + transitionValue: string|TransitionMatcherFn, errors: string[]): TransitionMatcherFn[] { const expressions: TransitionMatcherFn[] = []; if (typeof transitionValue == 'string') { transitionValue.split(/\s*,\s*/).forEach( diff --git a/packages/animations/browser/src/dsl/animation_transition_factory.ts b/packages/animations/browser/src/dsl/animation_transition_factory.ts index f1499e862b6a8..ab7729fe6b6d6 100644 --- a/packages/animations/browser/src/dsl/animation_transition_factory.ts +++ b/packages/animations/browser/src/dsl/animation_transition_factory.ts @@ -55,13 +55,16 @@ export class AnimationTransitionFactory { const animationOptions = {params: {...transitionAnimationParams, ...nextAnimationParams}}; - const timelines = skipAstBuild ? [] : buildAnimationTimelines( - driver, element, this.ast.animation, enterClassName, - leaveClassName, currentStateStyles, nextStateStyles, - animationOptions, subInstructions, errors); + const timelines = skipAstBuild ? + [] : + buildAnimationTimelines( + driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, + nextStateStyles, animationOptions, subInstructions, errors); let totalTime = 0; - timelines.forEach(tl => { totalTime = Math.max(tl.duration + tl.delay, totalTime); }); + timelines.forEach(tl => { + totalTime = Math.max(tl.duration + tl.delay, totalTime); + }); if (errors.length) { return createTransitionInstruction( diff --git a/packages/animations/browser/src/dsl/animation_trigger.ts b/packages/animations/browser/src/dsl/animation_trigger.ts index 79d948af9c06b..5e307adc88776 100644 --- a/packages/animations/browser/src/dsl/animation_trigger.ts +++ b/packages/animations/browser/src/dsl/animation_trigger.ts @@ -22,8 +22,8 @@ export function buildTrigger(name: string, ast: TriggerAst): AnimationTrigger { } /** -* @publicApi -*/ + * @publicApi + */ export class AnimationTrigger { public transitionFactories: AnimationTransitionFactory[] = []; public fallbackTransition: AnimationTransitionFactory; @@ -45,7 +45,9 @@ export class AnimationTrigger { this.fallbackTransition = createFallbackTransition(name, this.states); } - get containsQueries() { return this.ast.queryCount > 0; } + get containsQueries() { + return this.ast.queryCount > 0; + } matchTransition(currentState: any, nextState: any, element: any, params: {[key: string]: any}): AnimationTransitionFactory|null { diff --git a/packages/animations/browser/src/dsl/element_instruction_map.ts b/packages/animations/browser/src/dsl/element_instruction_map.ts index ad61a5f35ee39..7d5ca8baac211 100644 --- a/packages/animations/browser/src/dsl/element_instruction_map.ts +++ b/packages/animations/browser/src/dsl/element_instruction_map.ts @@ -28,7 +28,11 @@ export class ElementInstructionMap { existingInstructions.push(...instructions); } - has(element: any): boolean { return this._map.has(element); } + has(element: any): boolean { + return this._map.has(element); + } - clear() { this._map.clear(); } + clear() { + this._map.clear(); + } } diff --git a/packages/animations/browser/src/dsl/style_normalization/animation_style_normalizer.ts b/packages/animations/browser/src/dsl/style_normalization/animation_style_normalizer.ts index ea0161b90810b..3ab5f062575e8 100644 --- a/packages/animations/browser/src/dsl/style_normalization/animation_style_normalizer.ts +++ b/packages/animations/browser/src/dsl/style_normalization/animation_style_normalizer.ts @@ -20,7 +20,9 @@ export abstract class AnimationStyleNormalizer { * @publicApi */ export class NoopAnimationStyleNormalizer { - normalizePropertyName(propertyName: string, errors: string[]): string { return propertyName; } + normalizePropertyName(propertyName: string, errors: string[]): string { + return propertyName; + } normalizeStyleValue( userProvidedProperty: string, normalizedProperty: string, value: string|number, diff --git a/packages/animations/browser/src/private_export.ts b/packages/animations/browser/src/private_export.ts index bcce822afca9d..3773ef5348807 100644 --- a/packages/animations/browser/src/private_export.ts +++ b/packages/animations/browser/src/private_export.ts @@ -13,6 +13,6 @@ export {AnimationEngine as ɵAnimationEngine} from './render/animation_engine_ne export {CssKeyframesDriver as ɵCssKeyframesDriver} from './render/css_keyframes/css_keyframes_driver'; export {CssKeyframesPlayer as ɵCssKeyframesPlayer} from './render/css_keyframes/css_keyframes_player'; export {containsElement as ɵcontainsElement, invokeQuery as ɵinvokeQuery, matchesElement as ɵmatchesElement, validateStyleProperty as ɵvalidateStyleProperty} from './render/shared'; -export {WebAnimationsDriver as ɵWebAnimationsDriver, supportsWebAnimations as ɵsupportsWebAnimations} from './render/web_animations/web_animations_driver'; +export {supportsWebAnimations as ɵsupportsWebAnimations, WebAnimationsDriver as ɵWebAnimationsDriver} from './render/web_animations/web_animations_driver'; export {WebAnimationsPlayer as ɵWebAnimationsPlayer} from './render/web_animations/web_animations_player'; export {allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge} from './util'; diff --git a/packages/animations/browser/src/render/animation_driver.ts b/packages/animations/browser/src/render/animation_driver.ts index 2302b4f40349d..84085e18656b7 100644 --- a/packages/animations/browser/src/render/animation_driver.ts +++ b/packages/animations/browser/src/render/animation_driver.ts @@ -15,13 +15,17 @@ import {containsElement, invokeQuery, matchesElement, validateStyleProperty} fro */ @Injectable() export class NoopAnimationDriver implements AnimationDriver { - validateStyleProperty(prop: string): boolean { return validateStyleProperty(prop); } + validateStyleProperty(prop: string): boolean { + return validateStyleProperty(prop); + } matchesElement(element: any, selector: string): boolean { return matchesElement(element, selector); } - containsElement(elm1: any, elm2: any): boolean { return containsElement(elm1, elm2); } + containsElement(elm1: any, elm2: any): boolean { + return containsElement(elm1, elm2); + } query(element: any, selector: string, multi: boolean): any[] { return invokeQuery(element, selector, multi); @@ -32,7 +36,7 @@ export class NoopAnimationDriver implements AnimationDriver { } animate( - element: any, keyframes: {[key: string]: string | number}[], duration: number, delay: number, + element: any, keyframes: {[key: string]: string|number}[], duration: number, delay: number, easing: string, previousPlayers: any[] = [], scrubberAccessRequested?: boolean): AnimationPlayer { return new NoopAnimationPlayer(duration, delay); @@ -56,6 +60,6 @@ export abstract class AnimationDriver { abstract computeStyle(element: any, prop: string, defaultValue?: string): string; abstract animate( - element: any, keyframes: {[key: string]: string | number}[], duration: number, delay: number, + element: any, keyframes: {[key: string]: string|number}[], duration: number, delay: number, easing?: string|null, previousPlayers?: any[], scrubberAccessRequested?: boolean): any; } diff --git a/packages/animations/browser/src/render/animation_engine_instruction.ts b/packages/animations/browser/src/render/animation_engine_instruction.ts index 43c9fcd773ef2..d263df4ffde83 100644 --- a/packages/animations/browser/src/render/animation_engine_instruction.ts +++ b/packages/animations/browser/src/render/animation_engine_instruction.ts @@ -5,6 +5,11 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -export const enum AnimationTransitionInstructionType {TransitionAnimation, TimelineAnimation} +export const enum AnimationTransitionInstructionType { + TransitionAnimation, + TimelineAnimation +} -export interface AnimationEngineInstruction { type: AnimationTransitionInstructionType; } +export interface AnimationEngineInstruction { + type: AnimationTransitionInstructionType; +} diff --git a/packages/animations/browser/src/render/animation_engine_next.ts b/packages/animations/browser/src/render/animation_engine_next.ts index fe458b7611772..fa5ec2b5b966a 100644 --- a/packages/animations/browser/src/render/animation_engine_next.ts +++ b/packages/animations/browser/src/render/animation_engine_next.ts @@ -45,8 +45,8 @@ export class AnimationEngine { const ast = buildAnimationAst(this._driver, metadata as AnimationMetadata, errors) as TriggerAst; if (errors.length) { - throw new Error( - `The animation trigger "${name}" has failed to build due to the following errors:\n - ${errors.join("\n - ")}`); + throw new Error(`The animation trigger "${ + name}" has failed to build due to the following errors:\n - ${errors.join('\n - ')}`); } trigger = buildTrigger(name, ast); this._triggerCache[cacheKey] = trigger; @@ -95,12 +95,16 @@ export class AnimationEngine { return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback); } - flush(microtaskId: number = -1): void { this._transitionEngine.flush(microtaskId); } + flush(microtaskId: number = -1): void { + this._transitionEngine.flush(microtaskId); + } get players(): AnimationPlayer[] { return (this._transitionEngine.players as AnimationPlayer[]) .concat(this._timelineEngine.players as AnimationPlayer[]); } - whenRenderingDone(): Promise { return this._transitionEngine.whenRenderingDone(); } + whenRenderingDone(): Promise { + return this._transitionEngine.whenRenderingDone(); + } } diff --git a/packages/animations/browser/src/render/css_keyframes/css_keyframes_driver.ts b/packages/animations/browser/src/render/css_keyframes/css_keyframes_driver.ts index c69ee499c922c..a849111dfb6e5 100644 --- a/packages/animations/browser/src/render/css_keyframes/css_keyframes_driver.ts +++ b/packages/animations/browser/src/render/css_keyframes/css_keyframes_driver.ts @@ -23,13 +23,17 @@ export class CssKeyframesDriver implements AnimationDriver { private readonly _head: any = document.querySelector('head'); private _warningIssued = false; - validateStyleProperty(prop: string): boolean { return validateStyleProperty(prop); } + validateStyleProperty(prop: string): boolean { + return validateStyleProperty(prop); + } matchesElement(element: any, selector: string): boolean { return matchesElement(element, selector); } - containsElement(elm1: any, elm2: any): boolean { return containsElement(elm1, elm2); } + containsElement(elm1: any, elm2: any): boolean { + return containsElement(elm1, elm2); + } query(element: any, selector: string, multi: boolean): any[] { return invokeQuery(element, selector, multi); @@ -104,7 +108,7 @@ export class CssKeyframesDriver implements AnimationDriver { const animationName = `${KEYFRAMES_NAME_PREFIX}${this._count++}`; const kfElm = this.buildKeyframeElement(element, animationName, keyframes); - document.querySelector('head') !.appendChild(kfElm); + document.querySelector('head')!.appendChild(kfElm); const specialStyles = packageNonAnimatableStyles(element, keyframes); const player = new CssKeyframesPlayer( @@ -124,8 +128,8 @@ export class CssKeyframesDriver implements AnimationDriver { } } -function flattenKeyframesIntoStyles( - keyframes: null | {[key: string]: any} | {[key: string]: any}[]): {[key: string]: any} { +function flattenKeyframesIntoStyles(keyframes: null|{[key: string]: any}| + {[key: string]: any}[]): {[key: string]: any} { let flatKeyframes: {[key: string]: any} = {}; if (keyframes) { const kfs = Array.isArray(keyframes) ? keyframes : [keyframes]; diff --git a/packages/animations/browser/src/render/css_keyframes/css_keyframes_player.ts b/packages/animations/browser/src/render/css_keyframes/css_keyframes_player.ts index 1a6f302b043f3..114929a8e3038 100644 --- a/packages/animations/browser/src/render/css_keyframes/css_keyframes_player.ts +++ b/packages/animations/browser/src/render/css_keyframes/css_keyframes_player.ts @@ -14,7 +14,12 @@ import {ElementAnimationStyleHandler} from './element_animation_style_handler'; const DEFAULT_FILL_MODE = 'forwards'; const DEFAULT_EASING = 'linear'; -export const enum AnimatorControlState {INITIALIZED = 1, STARTED = 2, FINISHED = 3, DESTROYED = 4} +export const enum AnimatorControlState { + INITIALIZED = 1, + STARTED = 2, + FINISHED = 3, + DESTROYED = 4 +} export class CssKeyframesPlayer implements AnimationPlayer { private _onDoneFns: Function[] = []; @@ -23,10 +28,10 @@ export class CssKeyframesPlayer implements AnimationPlayer { private _started = false; // TODO(issue/24571): remove '!'. - private _styler !: ElementAnimationStyleHandler; + private _styler!: ElementAnimationStyleHandler; // TODO(issue/24571): remove '!'. - public parentPlayer !: AnimationPlayer; + public parentPlayer!: AnimationPlayer; public readonly totalTime: number; public readonly easing: string; public currentSnapshot: {[key: string]: string} = {}; @@ -34,7 +39,7 @@ export class CssKeyframesPlayer implements AnimationPlayer { private _state: AnimatorControlState = 0; constructor( - public readonly element: any, public readonly keyframes: {[key: string]: string | number}[], + public readonly element: any, public readonly keyframes: {[key: string]: string|number}[], public readonly animationName: string, private readonly _duration: number, private readonly _delay: number, easing: string, private readonly _finalStyles: {[key: string]: any}, @@ -44,11 +49,17 @@ export class CssKeyframesPlayer implements AnimationPlayer { this._buildStyler(); } - onStart(fn: () => void): void { this._onStartFns.push(fn); } + onStart(fn: () => void): void { + this._onStartFns.push(fn); + } - onDone(fn: () => void): void { this._onDoneFns.push(fn); } + onDone(fn: () => void): void { + this._onDoneFns.push(fn); + } - onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } + onDestroy(fn: () => void): void { + this._onDestroyFns.push(fn); + } destroy() { this.init(); @@ -86,11 +97,17 @@ export class CssKeyframesPlayer implements AnimationPlayer { this._flushDoneFns(); } - setPosition(value: number) { this._styler.setPosition(value); } + setPosition(value: number) { + this._styler.setPosition(value); + } - getPosition(): number { return this._styler.getPosition(); } + getPosition(): number { + return this._styler.getPosition(); + } - hasStarted(): boolean { return this._state >= AnimatorControlState.STARTED; } + hasStarted(): boolean { + return this._state >= AnimatorControlState.STARTED; + } init(): void { if (this._state >= AnimatorControlState.INITIALIZED) return; this._state = AnimatorControlState.INITIALIZED; diff --git a/packages/animations/browser/src/render/css_keyframes/direct_style_player.ts b/packages/animations/browser/src/render/css_keyframes/direct_style_player.ts index f4c092d27eb88..6a7ff3a453eec 100644 --- a/packages/animations/browser/src/render/css_keyframes/direct_style_player.ts +++ b/packages/animations/browser/src/render/css_keyframes/direct_style_player.ts @@ -22,7 +22,7 @@ export class DirectStylePlayer extends NoopAnimationPlayer { if (this.__initialized || !this._startingStyles) return; this.__initialized = true; Object.keys(this._styles).forEach(prop => { - this._startingStyles ![prop] = this.element.style[prop]; + this._startingStyles![prop] = this.element.style[prop]; }); super.init(); } @@ -38,7 +38,7 @@ export class DirectStylePlayer extends NoopAnimationPlayer { destroy() { if (!this._startingStyles) return; Object.keys(this._startingStyles).forEach(prop => { - const value = this._startingStyles ![prop]; + const value = this._startingStyles![prop]; if (value) { this.element.style.setProperty(prop, value); } else { diff --git a/packages/animations/browser/src/render/css_keyframes/element_animation_style_handler.ts b/packages/animations/browser/src/render/css_keyframes/element_animation_style_handler.ts index 03e06889d30b2..095c726a38f84 100644 --- a/packages/animations/browser/src/render/css_keyframes/element_animation_style_handler.ts +++ b/packages/animations/browser/src/render/css_keyframes/element_animation_style_handler.ts @@ -28,14 +28,19 @@ export class ElementAnimationStyleHandler { apply() { applyKeyframeAnimation( this._element, - `${this._duration}ms ${this._easing} ${this._delay}ms 1 normal ${this._fillMode} ${this._name}`); + `${this._duration}ms ${this._easing} ${this._delay}ms 1 normal ${this._fillMode} ${ + this._name}`); addRemoveAnimationEvent(this._element, this._eventFn, false); this._startTime = Date.now(); } - pause() { playPauseAnimation(this._element, this._name, 'paused'); } + pause() { + playPauseAnimation(this._element, this._name, 'paused'); + } - resume() { playPauseAnimation(this._element, this._name, 'running'); } + resume() { + playPauseAnimation(this._element, this._name, 'running'); + } setPosition(position: number) { const index = findIndexForAnimation(this._element, this._name); @@ -43,7 +48,9 @@ export class ElementAnimationStyleHandler { setAnimationStyle(this._element, 'Delay', `-${this._position}ms`, index); } - getPosition() { return this._position; } + getPosition() { + return this._position; + } private _handleCallback(event: any) { const timestamp = event._ngTestManualTimestamp || Date.now(); @@ -70,7 +77,7 @@ export class ElementAnimationStyleHandler { } } -function playPauseAnimation(element: any, name: string, status: 'running' | 'paused') { +function playPauseAnimation(element: any, name: string, status: 'running'|'paused') { const index = findIndexForAnimation(element, name); setAnimationStyle(element, 'PlayState', status, index); } diff --git a/packages/animations/browser/src/render/shared.ts b/packages/animations/browser/src/render/shared.ts index e3d6119fad1c0..c8cbe83ddab71 100644 --- a/packages/animations/browser/src/render/shared.ts +++ b/packages/animations/browser/src/render/shared.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimationEvent, AnimationPlayer, NoopAnimationPlayer, ɵAnimationGroupPlayer, ɵPRE_STYLE as PRE_STYLE, ɵStyleData} from '@angular/animations'; +import {AnimationEvent, AnimationPlayer, AUTO_STYLE, NoopAnimationPlayer, ɵAnimationGroupPlayer, ɵPRE_STYLE as PRE_STYLE, ɵStyleData} from '@angular/animations'; import {AnimationStyleNormalizer} from '../../src/dsl/style_normalization/animation_style_normalizer'; import {AnimationDriver} from '../../src/render/animation_driver'; @@ -89,7 +89,7 @@ export function normalizeKeyframes( } export function listenOnPlayer( - player: AnimationPlayer, eventName: string, event: AnimationEvent | undefined, + player: AnimationPlayer, eventName: string, event: AnimationEvent|undefined, callback: (event: any) => any) { switch (eventName) { case 'start': @@ -125,7 +125,7 @@ export function makeAnimationEvent( } export function getOrSetAsInMap( - map: Map| {[key: string]: any}, key: any, defaultValue: any) { + map: Map|{[key: string]: any}, key: any, defaultValue: any) { let value: any; if (map instanceof Map) { value = map.get(key); @@ -161,7 +161,9 @@ let _query: (element: any, selector: string, multi: boolean) => any[] = const _isNode = isNode(); if (_isNode || typeof Element !== 'undefined') { // this is well supported in all browsers - _contains = (elm1: any, elm2: any) => { return elm1.contains(elm2) as boolean; }; + _contains = (elm1: any, elm2: any) => { + return elm1.contains(elm2) as boolean; + }; _matches = (() => { if (_isNode || Element.prototype.matches) { @@ -203,15 +205,15 @@ let _IS_WEBKIT = false; export function validateStyleProperty(prop: string): boolean { if (!_CACHED_BODY) { _CACHED_BODY = getBodyNode() || {}; - _IS_WEBKIT = _CACHED_BODY !.style ? ('WebkitAppearance' in _CACHED_BODY !.style) : false; + _IS_WEBKIT = _CACHED_BODY!.style ? ('WebkitAppearance' in _CACHED_BODY!.style) : false; } let result = true; - if (_CACHED_BODY !.style && !containsVendorPrefix(prop)) { - result = prop in _CACHED_BODY !.style; + if (_CACHED_BODY!.style && !containsVendorPrefix(prop)) { + result = prop in _CACHED_BODY!.style; if (!result && _IS_WEBKIT) { const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.substr(1); - result = camelProp in _CACHED_BODY !.style; + result = camelProp in _CACHED_BODY!.style; } } diff --git a/packages/animations/browser/src/render/special_cased_styles.ts b/packages/animations/browser/src/render/special_cased_styles.ts index 546c3df5e8943..e97aadbc855b4 100644 --- a/packages/animations/browser/src/render/special_cased_styles.ts +++ b/packages/animations/browser/src/render/special_cased_styles.ts @@ -19,7 +19,7 @@ import {eraseStyles, setStyles} from '../util'; * @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null` */ export function packageNonAnimatableStyles( - element: any, styles: {[key: string]: any} | {[key: string]: any}[]): SpecialCasedStyles|null { + element: any, styles: {[key: string]: any}|{[key: string]: any}[]): SpecialCasedStyles|null { let startStyles: {[key: string]: any}|null = null; let endStyles: {[key: string]: any}|null = null; if (Array.isArray(styles) && styles.length) { @@ -47,7 +47,7 @@ export class SpecialCasedStyles { static initialStylesByElement = new WeakMap(); private _state = SpecialCasedStylesState.Pending; - private _initialStyles !: {[key: string]: any}; + private _initialStyles!: {[key: string]: any}; constructor( private _element: any, private _startStyles: {[key: string]: any}|null, diff --git a/packages/animations/browser/src/render/timeline_animation_engine.ts b/packages/animations/browser/src/render/timeline_animation_engine.ts index d83ad50223207..df26094c0a74c 100644 --- a/packages/animations/browser/src/render/timeline_animation_engine.ts +++ b/packages/animations/browser/src/render/timeline_animation_engine.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationPlayer, ɵStyleData} from '@angular/animations'; +import {AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationPlayer, AUTO_STYLE, ɵStyleData} from '@angular/animations'; import {Ast} from '../dsl/animation_ast'; import {buildAnimationAst} from '../dsl/animation_ast_builder'; @@ -34,7 +34,7 @@ export class TimelineAnimationEngine { const ast = buildAnimationAst(this._driver, metadata, errors); if (errors.length) { throw new Error( - `Unable to build the animation due to the following errors: ${errors.join("\n")}`); + `Unable to build the animation due to the following errors: ${errors.join('\n')}`); } else { this._animations[id] = ast; } @@ -71,12 +71,13 @@ export class TimelineAnimationEngine { if (errors.length) { throw new Error( - `Unable to create the animation due to the following errors: ${errors.join("\n")}`); + `Unable to create the animation due to the following errors: ${errors.join('\n')}`); } autoStylesMap.forEach((styles, element) => { - Object.keys(styles).forEach( - prop => { styles[prop] = this._driver.computeStyle(element, prop, AUTO_STYLE); }); + Object.keys(styles).forEach(prop => { + styles[prop] = this._driver.computeStyle(element, prop, AUTO_STYLE); + }); }); const players = instructions.map(i => { diff --git a/packages/animations/browser/src/render/transition_animation_engine.ts b/packages/animations/browser/src/render/transition_animation_engine.ts index f3ef0f80bc098..236f1e31808eb 100644 --- a/packages/animations/browser/src/render/transition_animation_engine.ts +++ b/packages/animations/browser/src/render/transition_animation_engine.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimationOptions, AnimationPlayer, NoopAnimationPlayer, ɵAnimationGroupPlayer as AnimationGroupPlayer, ɵPRE_STYLE as PRE_STYLE, ɵStyleData} from '@angular/animations'; +import {AnimationOptions, AnimationPlayer, AUTO_STYLE, NoopAnimationPlayer, ɵAnimationGroupPlayer as AnimationGroupPlayer, ɵPRE_STYLE as PRE_STYLE, ɵStyleData} from '@angular/animations'; import {AnimationTimelineInstruction} from '../dsl/animation_timeline_instruction'; import {AnimationTransitionFactory} from '../dsl/animation_transition_factory'; @@ -13,7 +13,7 @@ import {AnimationTransitionInstruction} from '../dsl/animation_transition_instru import {AnimationTrigger} from '../dsl/animation_trigger'; import {ElementInstructionMap} from '../dsl/element_instruction_map'; import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer'; -import {ENTER_CLASSNAME, LEAVE_CLASSNAME, NG_ANIMATING_CLASSNAME, NG_ANIMATING_SELECTOR, NG_TRIGGER_CLASSNAME, NG_TRIGGER_SELECTOR, copyObj, eraseStyles, iteratorToArray, setStyles} from '../util'; +import {copyObj, ENTER_CLASSNAME, eraseStyles, iteratorToArray, LEAVE_CLASSNAME, NG_ANIMATING_CLASSNAME, NG_ANIMATING_SELECTOR, NG_TRIGGER_CLASSNAME, NG_TRIGGER_SELECTOR, setStyles} from '../util'; import {AnimationDriver} from './animation_driver'; import {getOrSetAsInMap, listenOnPlayer, makeAnimationEvent, normalizeKeyframes, optimizeGroupPlayer} from './shared'; @@ -71,7 +71,9 @@ export class StateValue { public value: string; public options: AnimationOptions; - get params(): {[key: string]: any} { return this.options.params as{[key: string]: any}; } + get params(): {[key: string]: any} { + return this.options.params as {[key: string]: any}; + } constructor(input: any, public namespaceId: string = '') { const isObj = input && input.hasOwnProperty('value'); @@ -92,7 +94,7 @@ export class StateValue { absorbOptions(options: AnimationOptions) { const newParams = options.params; if (newParams) { - const oldParams = this.options.params !; + const oldParams = this.options.params!; Object.keys(newParams).forEach(prop => { if (oldParams[prop] == null) { oldParams[prop] = newParams[prop]; @@ -263,7 +265,9 @@ export class AnimationTransitionNamespace { if (!isFallbackTransition) { addClass(element, QUEUED_CLASSNAME); - player.onStart(() => { removeClass(element, QUEUED_CLASSNAME); }); + player.onStart(() => { + removeClass(element, QUEUED_CLASSNAME); + }); } player.onDone(() => { @@ -290,11 +294,14 @@ export class AnimationTransitionNamespace { deregister(name: string) { delete this._triggers[name]; - this._engine.statesByElement.forEach((stateMap, element) => { delete stateMap[name]; }); + this._engine.statesByElement.forEach((stateMap, element) => { + delete stateMap[name]; + }); this._elementListeners.forEach((listeners, element) => { - this._elementListeners.set( - element, listeners.filter(entry => { return entry.name != name; })); + this._elementListeners.set(element, listeners.filter(entry => { + return entry.name != name; + })); }); } @@ -372,7 +379,7 @@ export class AnimationTransitionNamespace { const trigger = this._triggers[triggerName]; const transition = trigger.fallbackTransition; - const elementStates = this._engine.statesByElement.get(element) !; + const elementStates = this._engine.statesByElement.get(element)!; const fromState = elementStates[triggerName] || DEFAULT_STATE_VALUE; const toState = new StateValue(VOID_VALUE); const player = new TransitionAnimationPlayer(this.id, triggerName, element); @@ -448,7 +455,9 @@ export class AnimationTransitionNamespace { } } - insertNode(element: any, parent: any): void { addClass(element, this._hostClassName); } + insertNode(element: any, parent: any): void { + addClass(element, this._hostClassName); + } drainQueuedTransitions(microtaskId: number): QueueInstruction[] { const instructions: QueueInstruction[] = []; @@ -538,7 +547,9 @@ export class TransitionAnimationEngine { public onRemovalComplete = (element: any, context: any) => {}; /** @internal */ - _onRemovalComplete(element: any, context: any) { this.onRemovalComplete(element, context); } + _onRemovalComplete(element: any, context: any) { + this.onRemovalComplete(element, context); + } constructor( public bodyNode: any, public driver: AnimationDriver, @@ -631,7 +642,9 @@ export class TransitionAnimationEngine { this.afterFlushAnimationsDone(() => ns.destroy(context)); } - private _fetchNamespace(id: string) { return this._namespaceLookup[id]; } + private _fetchNamespace(id: string) { + return this._namespaceLookup[id]; + } fetchNamespacesByElement(element: any): Set { // normally there should only be one namespace per element, however @@ -704,7 +717,9 @@ export class TransitionAnimationEngine { } } - collectEnterElement(element: any) { this.collectedEnterElements.push(element); } + collectEnterElement(element: any) { + this.collectedEnterElements.push(element); + } markElementAsDisabled(element: any, value: boolean) { if (value) { @@ -740,11 +755,8 @@ export class TransitionAnimationEngine { markElementAsRemoved(namespaceId: string, element: any, hasAnimation?: boolean, context?: any) { this.collectedLeaveElements.push(element); - element[REMOVAL_FLAG] = { - namespaceId, - setForRemoval: context, hasAnimation, - removedBeforeQueried: false - }; + element[REMOVAL_FLAG] = + {namespaceId, setForRemoval: context, hasAnimation, removedBeforeQueried: false}; } listen( @@ -876,7 +888,9 @@ export class TransitionAnimationEngine { this._whenQuietFns = []; if (players.length) { - optimizeGroupPlayer(players).onDone(() => { quietFns.forEach(fn => fn()); }); + optimizeGroupPlayer(players).onDone(() => { + quietFns.forEach(fn => fn()); + }); } else { quietFns.forEach(fn => fn()); } @@ -950,16 +964,18 @@ export class TransitionAnimationEngine { cleanupFns.push(() => { enterNodeMap.forEach((nodes, root) => { - const className = enterNodeMapIds.get(root) !; + const className = enterNodeMapIds.get(root)!; nodes.forEach(node => removeClass(node, className)); }); leaveNodeMap.forEach((nodes, root) => { - const className = leaveNodeMapIds.get(root) !; + const className = leaveNodeMapIds.get(root)!; nodes.forEach(node => removeClass(node, className)); }); - allLeaveNodes.forEach(element => { this.processLeaveNode(element); }); + allLeaveNodes.forEach(element => { + this.processLeaveNode(element); + }); }); const allPlayers: TransitionAnimationPlayer[] = []; @@ -981,10 +997,10 @@ export class TransitionAnimationEngine { } const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element); - const leaveClassName = leaveNodeMapIds.get(element) !; - const enterClassName = enterNodeMapIds.get(element) !; + const leaveClassName = leaveNodeMapIds.get(element)!; + const enterClassName = enterNodeMapIds.get(element)!; const instruction = this._buildInstruction( - entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned) !; + entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned)!; if (instruction.errors && instruction.errors.length) { erroneousTransitions.push(instruction); return; @@ -1029,7 +1045,7 @@ export class TransitionAnimationEngine { instruction.preStyleProps.forEach((stringMap, element) => { const props = Object.keys(stringMap); if (props.length) { - let setVal: Set = allPreStyleElements.get(element) !; + let setVal: Set = allPreStyleElements.get(element)!; if (!setVal) { allPreStyleElements.set(element, setVal = new Set()); } @@ -1039,7 +1055,7 @@ export class TransitionAnimationEngine { instruction.postStyleProps.forEach((stringMap, element) => { const props = Object.keys(stringMap); - let setVal: Set = allPostStyleElements.get(element) !; + let setVal: Set = allPostStyleElements.get(element)!; if (!setVal) { allPostStyleElements.set(element, setVal = new Set()); } @@ -1052,7 +1068,7 @@ export class TransitionAnimationEngine { const errors: string[] = []; erroneousTransitions.forEach(instruction => { errors.push(`@${instruction.triggerName} has failed due to:\n`); - instruction.errors !.forEach(error => errors.push(`- ${error}\n`)); + instruction.errors!.forEach(error => errors.push(`- ${error}\n`)); }); allPlayers.forEach(player => player.destroy()); @@ -1116,7 +1132,7 @@ export class TransitionAnimationEngine { replaceNodes.forEach(node => { const post = postStylesMap.get(node); const pre = preStylesMap.get(node); - postStylesMap.set(node, { ...post, ...pre } as any); + postStylesMap.set(node, {...post, ...pre} as any); }); const rootPlayers: TransitionAnimationPlayer[] = []; @@ -1274,9 +1290,13 @@ export class TransitionAnimationEngine { return this._fetchNamespace(namespaceId).elementContainsData(element) || containsData; } - afterFlush(callback: () => any) { this._flushFns.push(callback); } + afterFlush(callback: () => any) { + this._flushFns.push(callback); + } - afterFlushAnimationsDone(callback: () => any) { this._whenQuietFns.push(callback); } + afterFlushAnimationsDone(callback: () => any) { + this._whenQuietFns.push(callback); + } private _getPreviousPlayers( element: string, isQueriedElement: boolean, namespaceId?: string, triggerName?: string, @@ -1413,8 +1433,9 @@ export class TransitionAnimationEngine { // this basically makes all of the callbacks for sub element animations // be dependent on the upper players for when they finish - allSubElements.forEach( - element => { getOrSetAsInMap(skippedPlayersMap, element, []).push(player); }); + allSubElements.forEach(element => { + getOrSetAsInMap(skippedPlayersMap, element, []).push(player); + }); return player; } @@ -1441,7 +1462,7 @@ export class TransitionAnimationPlayer implements AnimationPlayer { private _queuedCallbacks: {[name: string]: (() => any)[]} = {}; public readonly destroyed = false; // TODO(issue/24571): remove '!'. - public parentPlayer !: AnimationPlayer; + public parentPlayer!: AnimationPlayer; public markedForDestroy: boolean = false; public disabled = false; @@ -1462,17 +1483,21 @@ export class TransitionAnimationPlayer implements AnimationPlayer { this._queuedCallbacks = {}; this._containsRealPlayer = true; this.overrideTotalTime(player.totalTime); - (this as{queued: boolean}).queued = false; + (this as {queued: boolean}).queued = false; } - getRealPlayer() { return this._player; } + getRealPlayer() { + return this._player; + } - overrideTotalTime(totalTime: number) { (this as any).totalTime = totalTime; } + overrideTotalTime(totalTime: number) { + (this as any).totalTime = totalTime; + } syncPlayerEvents(player: AnimationPlayer) { const p = this._player as any; if (p.triggerCallback) { - player.onStart(() => p.triggerCallback !('start')); + player.onStart(() => p.triggerCallback!('start')); } player.onDone(() => this.finish()); player.onDestroy(() => this.destroy()); @@ -1503,24 +1528,38 @@ export class TransitionAnimationPlayer implements AnimationPlayer { this._player.onDestroy(fn); } - init(): void { this._player.init(); } + init(): void { + this._player.init(); + } - hasStarted(): boolean { return this.queued ? false : this._player.hasStarted(); } + hasStarted(): boolean { + return this.queued ? false : this._player.hasStarted(); + } - play(): void { !this.queued && this._player.play(); } + play(): void { + !this.queued && this._player.play(); + } - pause(): void { !this.queued && this._player.pause(); } + pause(): void { + !this.queued && this._player.pause(); + } - restart(): void { !this.queued && this._player.restart(); } + restart(): void { + !this.queued && this._player.restart(); + } - finish(): void { this._player.finish(); } + finish(): void { + this._player.finish(); + } destroy(): void { - (this as{destroyed: boolean}).destroyed = true; + (this as {destroyed: boolean}).destroyed = true; this._player.destroy(); } - reset(): void { !this.queued && this._player.reset(); } + reset(): void { + !this.queued && this._player.reset(); + } setPosition(p: any): void { if (!this.queued) { @@ -1528,7 +1567,9 @@ export class TransitionAnimationPlayer implements AnimationPlayer { } } - getPosition(): number { return this.queued ? 0 : this._player.getPosition(); } + getPosition(): number { + return this.queued ? 0 : this._player.getPosition(); + } /** @internal */ triggerCallback(phaseName: string): void { @@ -1539,7 +1580,7 @@ export class TransitionAnimationPlayer implements AnimationPlayer { } } -function deleteOrUnsetInMap(map: Map| {[key: string]: any}, key: any, value: any) { +function deleteOrUnsetInMap(map: Map|{[key: string]: any}, key: any, value: any) { let currentValues: any[]|null|undefined; if (map instanceof Map) { currentValues = map.get(key); @@ -1661,7 +1702,7 @@ function buildRootMap(roots: any[], nodes: any[]): Map { nodes.forEach(node => { const root = getRoot(node); if (root !== NULL_NODE) { - rootMap.get(root) !.push(node); + rootMap.get(root)!.push(node); } }); @@ -1742,7 +1783,7 @@ function replacePostStylesAsPre( let preEntry = allPreStyleElements.get(element); if (preEntry) { - postEntry.forEach(data => preEntry !.add(data)); + postEntry.forEach(data => preEntry!.add(data)); } else { allPreStyleElements.set(element, postEntry); } diff --git a/packages/animations/browser/src/render/web_animations/web_animations_driver.ts b/packages/animations/browser/src/render/web_animations/web_animations_driver.ts index 29cd26e376ea2..00657d309abda 100644 --- a/packages/animations/browser/src/render/web_animations/web_animations_driver.ts +++ b/packages/animations/browser/src/render/web_animations/web_animations_driver.ts @@ -19,13 +19,17 @@ export class WebAnimationsDriver implements AnimationDriver { private _isNativeImpl = /\{\s*\[native\s+code\]\s*\}/.test(getElementAnimateFn().toString()); private _cssKeyframesDriver = new CssKeyframesDriver(); - validateStyleProperty(prop: string): boolean { return validateStyleProperty(prop); } + validateStyleProperty(prop: string): boolean { + return validateStyleProperty(prop); + } matchesElement(element: any, selector: string): boolean { return matchesElement(element, selector); } - containsElement(elm1: any, elm2: any): boolean { return containsElement(elm1, elm2); } + containsElement(elm1: any, elm2: any): boolean { + return containsElement(elm1, elm2); + } query(element: any, selector: string, multi: boolean): any[] { return invokeQuery(element, selector, multi); @@ -35,7 +39,9 @@ export class WebAnimationsDriver implements AnimationDriver { return (window.getComputedStyle(element) as any)[prop] as string; } - overrideWebAnimationsSupport(supported: boolean) { this._isNativeImpl = supported; } + overrideWebAnimationsSupport(supported: boolean) { + this._isNativeImpl = supported; + } animate( element: any, keyframes: ɵStyleData[], duration: number, delay: number, easing: string, @@ -47,7 +53,7 @@ export class WebAnimationsDriver implements AnimationDriver { } const fill = delay == 0 ? 'both' : 'forwards'; - const playerOptions: {[key: string]: string | number} = {duration, delay, fill}; + const playerOptions: {[key: string]: string|number} = {duration, delay, fill}; // we check for this to avoid having a null|undefined value be present // for the easing (which results in an error for certain browsers #9752) if (easing) { diff --git a/packages/animations/browser/src/render/web_animations/web_animations_player.ts b/packages/animations/browser/src/render/web_animations/web_animations_player.ts index 76c2cd44bed34..025fff00c490e 100644 --- a/packages/animations/browser/src/render/web_animations/web_animations_player.ts +++ b/packages/animations/browser/src/render/web_animations/web_animations_player.ts @@ -23,18 +23,18 @@ export class WebAnimationsPlayer implements AnimationPlayer { private _started = false; private _destroyed = false; // TODO(issue/24571): remove '!'. - private _finalKeyframe !: {[key: string]: string | number}; + private _finalKeyframe!: {[key: string]: string|number}; // TODO(issue/24571): remove '!'. - public readonly domPlayer !: DOMAnimation; + public readonly domPlayer!: DOMAnimation; public time = 0; public parentPlayer: AnimationPlayer|null = null; - public currentSnapshot: {[styleName: string]: string | number} = {}; + public currentSnapshot: {[styleName: string]: string|number} = {}; constructor( - public element: any, public keyframes: {[key: string]: string | number}[], - public options: {[key: string]: string | number}, + public element: any, public keyframes: {[key: string]: string|number}[], + public options: {[key: string]: string|number}, private _specialStyles?: SpecialCasedStyles|null) { this._duration = options['duration']; this._delay = options['delay'] || 0; @@ -59,7 +59,7 @@ export class WebAnimationsPlayer implements AnimationPlayer { this._initialized = true; const keyframes = this.keyframes; - (this as{domPlayer: DOMAnimation}).domPlayer = + (this as {domPlayer: DOMAnimation}).domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options); this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : {}; this.domPlayer.addEventListener('finish', () => this._onFinish()); @@ -81,11 +81,17 @@ export class WebAnimationsPlayer implements AnimationPlayer { return element['animate'](keyframes, options) as DOMAnimation; } - onStart(fn: () => void): void { this._onStartFns.push(fn); } + onStart(fn: () => void): void { + this._onStartFns.push(fn); + } - onDone(fn: () => void): void { this._onDoneFns.push(fn); } + onDone(fn: () => void): void { + this._onDoneFns.push(fn); + } - onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } + onDestroy(fn: () => void): void { + this._onDestroyFns.push(fn); + } play(): void { this._buildPlayer(); @@ -132,7 +138,9 @@ export class WebAnimationsPlayer implements AnimationPlayer { this.play(); } - hasStarted(): boolean { return this._started; } + hasStarted(): boolean { + return this._started; + } destroy(): void { if (!this._destroyed) { @@ -147,14 +155,20 @@ export class WebAnimationsPlayer implements AnimationPlayer { } } - setPosition(p: number): void { this.domPlayer.currentTime = p * this.time; } + setPosition(p: number): void { + this.domPlayer.currentTime = p * this.time; + } - getPosition(): number { return this.domPlayer.currentTime / this.time; } + getPosition(): number { + return this.domPlayer.currentTime / this.time; + } - get totalTime(): number { return this._delay + this._duration; } + get totalTime(): number { + return this._delay + this._duration; + } beforeDestroy() { - const styles: {[key: string]: string | number} = {}; + const styles: {[key: string]: string|number} = {}; if (this.hasStarted()) { Object.keys(this._finalKeyframe).forEach(prop => { if (prop != 'offset') { diff --git a/packages/animations/browser/src/util.ts b/packages/animations/browser/src/util.ts index ffcc2a7567d1d..aad7d53ae104b 100644 --- a/packages/animations/browser/src/util.ts +++ b/packages/animations/browser/src/util.ts @@ -23,7 +23,7 @@ export const NG_TRIGGER_SELECTOR = '.ng-trigger'; export const NG_ANIMATING_CLASSNAME = 'ng-animating'; export const NG_ANIMATING_SELECTOR = '.ng-animating'; -export function resolveTimingValue(value: string | number) { +export function resolveTimingValue(value: string|number) { if (typeof value == 'number') return value; const matches = value.match(/^(-?[\.\d]+)(m?s)/); @@ -42,14 +42,14 @@ function _convertTimeValueToMS(value: number, unit: string): number { } export function resolveTiming( - timings: string | number | AnimateTimings, errors: any[], allowNegativeValues?: boolean) { + timings: string|number|AnimateTimings, errors: any[], allowNegativeValues?: boolean) { return timings.hasOwnProperty('duration') ? timings : parseTimeExpression(timings, errors, allowNegativeValues); } function parseTimeExpression( - exp: string | number, errors: string[], allowNegativeValues?: boolean): AnimateTimings { + exp: string|number, errors: string[], allowNegativeValues?: boolean): AnimateTimings { const regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i; let duration: number; let delay: number = 0; @@ -97,11 +97,13 @@ function parseTimeExpression( export function copyObj( obj: {[key: string]: any}, destination: {[key: string]: any} = {}): {[key: string]: any} { - Object.keys(obj).forEach(prop => { destination[prop] = obj[prop]; }); + Object.keys(obj).forEach(prop => { + destination[prop] = obj[prop]; + }); return destination; } -export function normalizeStyles(styles: ɵStyleData | ɵStyleData[]): ɵStyleData { +export function normalizeStyles(styles: ɵStyleData|ɵStyleData[]): ɵStyleData { const normalizedStyles: ɵStyleData = {}; if (Array.isArray(styles)) { styles.forEach(data => copyStyles(data, false, normalizedStyles)); @@ -186,8 +188,8 @@ export function eraseStyles(element: any, styles: ɵStyleData) { } } -export function normalizeAnimationEntry(steps: AnimationMetadata | AnimationMetadata[]): - AnimationMetadata { +export function normalizeAnimationEntry(steps: AnimationMetadata| + AnimationMetadata[]): AnimationMetadata { if (Array.isArray(steps)) { if (steps.length == 1) return steps[0]; return sequence(steps); @@ -196,7 +198,7 @@ export function normalizeAnimationEntry(steps: AnimationMetadata | AnimationMeta } export function validateStyleParams( - value: string | number, options: AnimationOptions, errors: any[]) { + value: string|number, options: AnimationOptions, errors: any[]) { const params = options.params || {}; const matches = extractStyleParams(value); if (matches.length) { @@ -211,7 +213,7 @@ export function validateStyleParams( const PARAM_REGEX = new RegExp(`${SUBSTITUTION_EXPR_START}\\s*(.+?)\\s*${SUBSTITUTION_EXPR_END}`, 'g'); -export function extractStyleParams(value: string | number): string[] { +export function extractStyleParams(value: string|number): string[] { let params: string[] = []; if (typeof value === 'string') { let match: any; @@ -224,7 +226,7 @@ export function extractStyleParams(value: string | number): string[] { } export function interpolateParams( - value: string | number, params: {[name: string]: any}, errors: any[]): string|number { + value: string|number, params: {[name: string]: any}, errors: any[]): string|number { const original = value.toString(); const str = original.replace(PARAM_REGEX, (_, varName) => { let localVal = params[varName]; @@ -297,7 +299,9 @@ export function balancePreviousStylesIntoKeyframes( // tslint:disable-next-line for (var i = 1; i < keyframes.length; i++) { let kf = keyframes[i]; - missingStyleProps.forEach(function(prop) { kf[prop] = computeStyle(element, prop); }); + missingStyleProps.forEach(function(prop) { + kf[prop] = computeStyle(element, prop); + }); } } } diff --git a/packages/animations/browser/test/dsl/animation_spec.ts b/packages/animations/browser/test/dsl/animation_spec.ts index 4fe716c808717..5aacf1c78b734 100644 --- a/packages/animations/browser/test/dsl/animation_spec.ts +++ b/packages/animations/browser/test/dsl/animation_spec.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimationMetadata, AnimationMetadataType, AnimationOptions, animate, animation, group, keyframes, query, sequence, state, style, transition, trigger, useAnimation, ɵStyleData} from '@angular/animations'; +import {animate, animation, AnimationMetadata, AnimationMetadataType, AnimationOptions, AUTO_STYLE, group, keyframes, query, sequence, state, style, transition, trigger, useAnimation, ɵStyleData} from '@angular/animations'; import {Animation} from '../../src/dsl/animation'; import {buildAnimationAst} from '../../src/dsl/animation_ast_builder'; @@ -35,7 +35,9 @@ function createDiv() { rootElement.appendChild(subElement2); }); - afterEach(() => { document.body.removeChild(rootElement); }); + afterEach(() => { + document.body.removeChild(rootElement); + }); describe('validation', () => { it('should throw an error if one or more but not all keyframes() styles contain offsets', @@ -45,7 +47,9 @@ function createDiv() { style({opacity: 1, offset: 1}), ])); - expect(() => { validateAndThrowAnimationSequence(steps); }) + expect(() => { + validateAndThrowAnimationSequence(steps); + }) .toThrowError( /Not all style\(\) steps within the declared keyframes\(\) contain offsets/); }); @@ -96,7 +100,9 @@ function createDiv() { ])) ]); - expect(() => { validateAndThrowAnimationSequence(steps); }) + expect(() => { + validateAndThrowAnimationSequence(steps); + }) .toThrowError( /The CSS property "opacity" that exists between the times of "0ms" and "2000ms" is also being animated in a parallel animation between the times of "0ms" and "1500ms"/); }); @@ -191,7 +197,9 @@ function createDiv() { })), ]; - expect(() => { validateAndThrowAnimationSequence(steps); }) + expect(() => { + validateAndThrowAnimationSequence(steps); + }) .toThrowError( /state\("final", ...\) must define default values for all the following style substitutions: one, two, three/); @@ -203,7 +211,9 @@ function createDiv() { }), {params: {redColor: 'maroon'}})]; - expect(() => { validateAndThrowAnimationSequence(steps2); }) + expect(() => { + validateAndThrowAnimationSequence(steps2); + }) .toThrowError( /state\("panfinal", ...\) must define default values for all the following style substitutions: greyColor/); }); @@ -211,7 +221,9 @@ function createDiv() { it('should throw an error if an invalid CSS property is used in the animation', () => { const steps = [animate(1000, style({abc: '500px'}))]; - expect(() => { validateAndThrowAnimationSequence(steps); }) + expect(() => { + validateAndThrowAnimationSequence(steps); + }) .toThrowError( /The provided animation property "abc" is not a supported CSS property for animations/); }); @@ -388,7 +400,7 @@ function createDiv() { let players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); - let p1 = players.pop() !; + let p1 = players.pop()!; expect(p1.duration).toEqual(1500); expect(p1.keyframes).toEqual([ {width: '*', offset: 0}, @@ -405,7 +417,7 @@ function createDiv() { players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); - p1 = players.pop() !; + p1 = players.pop()!; expect(p1.duration).toEqual(1000); expect(p1.keyframes).toEqual([ {width: '100px', offset: 0}, @@ -876,7 +888,9 @@ function createDiv() { const steps = [query('somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))])]; - expect(() => { invokeAnimationSequence(rootElement, steps); }) + expect(() => { + invokeAnimationSequence(rootElement, steps); + }) .toThrowError( /`query\("somethingFake"\)` returned zero elements\. \(Use `query\("somethingFake", \{ optional: true \}\)` if you wish to allow this\.\)/); }); @@ -887,13 +901,17 @@ function createDiv() { 'somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {optional: true})]; - expect(() => { invokeAnimationSequence(rootElement, steps); }).not.toThrow(); + expect(() => { + invokeAnimationSequence(rootElement, steps); + }).not.toThrow(); const steps2 = [query( 'fakeSomethings', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {optional: true})]; - expect(() => { invokeAnimationSequence(rootElement, steps2); }).not.toThrow(); + expect(() => { + invokeAnimationSequence(rootElement, steps2); + }).not.toThrow(); }); it('should delay the query operation if a delay option is provided', () => { @@ -1025,8 +1043,7 @@ function createDiv() { const players = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles); expect(players[0].keyframes).toEqual([ - {background: 'blue', offset: 0, easing: 'ease-out'}, - {background: 'red', offset: 1} + {background: 'blue', offset: 0, easing: 'ease-out'}, {background: 'red', offset: 1} ]); }); }); @@ -1042,7 +1059,7 @@ function humanizeOffsets(keyframes: ɵStyleData[], digits: number = 3): ɵStyleD } function invokeAnimationSequence( - element: any, steps: AnimationMetadata | AnimationMetadata[], locals: {[key: string]: any} = {}, + element: any, steps: AnimationMetadata|AnimationMetadata[], locals: {[key: string]: any} = {}, startingStyles: ɵStyleData[] = [], destinationStyles: ɵStyleData[] = [], subInstructions?: ElementInstructionMap): AnimationTimelineInstruction[] { const driver = new MockAnimationDriver(); @@ -1050,7 +1067,7 @@ function invokeAnimationSequence( .buildTimelines(element, startingStyles, destinationStyles, locals, subInstructions); } -function validateAndThrowAnimationSequence(steps: AnimationMetadata | AnimationMetadata[]) { +function validateAndThrowAnimationSequence(steps: AnimationMetadata|AnimationMetadata[]) { const driver = new MockAnimationDriver(); const errors: any[] = []; const ast = buildAnimationAst(driver, steps, errors); diff --git a/packages/animations/browser/test/dsl/animation_trigger_spec.ts b/packages/animations/browser/test/dsl/animation_trigger_spec.ts index 5482075fc6458..f2c2e134b4e6c 100644 --- a/packages/animations/browser/test/dsl/animation_trigger_spec.ts +++ b/packages/animations/browser/test/dsl/animation_trigger_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {AnimationOptions, animate, state, style, transition} from '@angular/animations'; +import {animate, AnimationOptions, state, style, transition} from '@angular/animations'; import {AnimationTransitionInstruction} from '@angular/animations/browser/src/dsl/animation_transition_instruction'; import {AnimationTrigger} from '@angular/animations/browser/src/dsl/animation_trigger'; @@ -25,7 +25,9 @@ import {makeTrigger} from '../shared'; document.body.appendChild(element); }); - afterEach(() => { document.body.removeChild(element); }); + afterEach(() => { + document.body.removeChild(element); + }); describe('trigger validation', () => { it('should group errors together for an animation trigger', () => { @@ -36,8 +38,9 @@ import {makeTrigger} from '../shared'; it('should throw an error when a transition within a trigger contains an invalid expression', () => { - expect( - () => { makeTrigger('name', [transition('somethingThatIsWrong', animate(3333))]); }) + expect(() => { + makeTrigger('name', [transition('somethingThatIsWrong', animate(3333))]); + }) .toThrowError( /- The provided transition expression "somethingThatIsWrong" is not supported/); }); @@ -78,7 +81,7 @@ import {makeTrigger} from '../shared'; const result = makeTrigger( 'name', [transition('a => b', animate(1234)), transition('b => c', animate(5678))]); - const trans = buildTransition(result, element, 'b', 'c') !; + const trans = buildTransition(result, element, 'b', 'c')!; expect(trans.timelines.length).toEqual(1); const timeline = trans.timelines[0]; expect(timeline.duration).toEqual(5678); @@ -90,13 +93,13 @@ import {makeTrigger} from '../shared'; transition('* => *', animate(9999)) ]); - let trans = buildTransition(result, element, 'b', 'c') !; + let trans = buildTransition(result, element, 'b', 'c')!; expect(trans.timelines[0].duration).toEqual(5678); - trans = buildTransition(result, element, 'a', 'b') !; + trans = buildTransition(result, element, 'a', 'b')!; expect(trans.timelines[0].duration).toEqual(1234); - trans = buildTransition(result, element, 'c', 'c') !; + trans = buildTransition(result, element, 'c', 'c')!; expect(trans.timelines[0].duration).toEqual(9999); }); @@ -110,23 +113,23 @@ import {makeTrigger} from '../shared'; it('should support bi-directional transition expressions', () => { const result = makeTrigger('name', [transition('a <=> b', animate(2222))]); - const t1 = buildTransition(result, element, 'a', 'b') !; + const t1 = buildTransition(result, element, 'a', 'b')!; expect(t1.timelines[0].duration).toEqual(2222); - const t2 = buildTransition(result, element, 'b', 'a') !; + const t2 = buildTransition(result, element, 'b', 'a')!; expect(t2.timelines[0].duration).toEqual(2222); }); it('should support multiple transition statements in one string', () => { const result = makeTrigger('name', [transition('a => b, b => a, c => *', animate(1234))]); - const t1 = buildTransition(result, element, 'a', 'b') !; + const t1 = buildTransition(result, element, 'a', 'b')!; expect(t1.timelines[0].duration).toEqual(1234); - const t2 = buildTransition(result, element, 'b', 'a') !; + const t2 = buildTransition(result, element, 'b', 'a')!; expect(t2.timelines[0].duration).toEqual(1234); - const t3 = buildTransition(result, element, 'c', 'a') !; + const t3 = buildTransition(result, element, 'c', 'a')!; expect(t3.timelines[0].duration).toEqual(1234); }); @@ -138,7 +141,7 @@ import {makeTrigger} from '../shared'; 'a => b', [style({height: '{{ a }}'}), animate(1000, style({height: '{{ b }}'}))], buildParams({a: '100px', b: '200px'}))]); - const trans = buildTransition(result, element, 'a', 'b') !; + const trans = buildTransition(result, element, 'a', 'b')!; const keyframes = trans.timelines[0].keyframes; expect(keyframes).toEqual([{height: '100px', offset: 0}, {height: '200px', offset: 1}]); }); @@ -153,7 +156,7 @@ import {makeTrigger} from '../shared'; buildParams({a: '100px', b: '200px'}))]); const trans = - buildTransition(result, element, 'a', 'b', {}, buildParams({a: '300px'})) !; + buildTransition(result, element, 'a', 'b', {}, buildParams({a: '300px'}))!; const keyframes = trans.timelines[0].keyframes; expect(keyframes).toEqual( @@ -167,7 +170,7 @@ import {makeTrigger} from '../shared'; transition('true <=> false', animate(1234)) ]); - const trans = buildTransition(result, element, false, true) !; + const trans = buildTransition(result, element, false, true)!; expect(trans.timelines[0].duration).toEqual(1234); }); @@ -177,7 +180,7 @@ import {makeTrigger} from '../shared'; transition('1 <=> 0', animate(4567)) ]); - const trans = buildTransition(result, element, false, true) !; + const trans = buildTransition(result, element, false, true)!; expect(trans.timelines[0].duration).toEqual(4567); }); @@ -188,7 +191,7 @@ import {makeTrigger} from '../shared'; transition('1 <=> 0', animate(4567)) ]); - const trans = buildTransition(result, element, false, true) !; + const trans = buildTransition(result, element, false, true)!; expect(trans.timelines[0].keyframes).toEqual([ {offset: 0, color: 'red'}, {offset: 1, color: 'green'} ]); @@ -201,7 +204,7 @@ import {makeTrigger} from '../shared'; transition('true <=> false', animate(4567)) ]); - const trans = buildTransition(result, element, false, true) !; + const trans = buildTransition(result, element, false, true)!; expect(trans.timelines[0].keyframes).toEqual([ {offset: 0, color: 'orange'}, {offset: 1, color: 'blue'} ]); @@ -214,7 +217,7 @@ import {makeTrigger} from '../shared'; ]); expect(() => { - const trans = buildTransition(result, element, false, true) !; + const trans = buildTransition(result, element, false, true)!; }).not.toThrow(); }); @@ -222,14 +225,14 @@ import {makeTrigger} from '../shared'; it('should alias the :enter transition as void => *', () => { const result = makeTrigger('name', [transition(':enter', animate(3333))]); - const trans = buildTransition(result, element, 'void', 'something') !; + const trans = buildTransition(result, element, 'void', 'something')!; expect(trans.timelines[0].duration).toEqual(3333); }); it('should alias the :leave transition as * => void', () => { const result = makeTrigger('name', [transition(':leave', animate(3333))]); - const trans = buildTransition(result, element, 'something', 'void') !; + const trans = buildTransition(result, element, 'something', 'void')!; expect(trans.timelines[0].duration).toEqual(3333); }); }); @@ -242,12 +245,12 @@ function buildTransition( fromOptions?: AnimationOptions, toOptions?: AnimationOptions): AnimationTransitionInstruction| null { const params = toOptions && toOptions.params || {}; - const trans = trigger.matchTransition(fromState, toState, element, params) !; + const trans = trigger.matchTransition(fromState, toState, element, params)!; if (trans) { const driver = new MockAnimationDriver(); return trans.build( driver, element, fromState, toState, ENTER_CLASSNAME, LEAVE_CLASSNAME, fromOptions, - toOptions) !; + toOptions)!; } return null; } diff --git a/packages/animations/browser/test/dsl/style_normalizer/web_animations_style_normalizer_spec.ts b/packages/animations/browser/test/dsl/style_normalizer/web_animations_style_normalizer_spec.ts index 003df7678cc9a..17d5878ffe775 100644 --- a/packages/animations/browser/test/dsl/style_normalizer/web_animations_style_normalizer_spec.ts +++ b/packages/animations/browser/test/dsl/style_normalizer/web_animations_style_normalizer_spec.ts @@ -16,13 +16,13 @@ import {WebAnimationsStyleNormalizer} from '../../../src/dsl/style_normalization expect(normalizer.normalizePropertyName('width', [])).toEqual('width'); expect(normalizer.normalizePropertyName('border-width', [])).toEqual('borderWidth'); expect(normalizer.normalizePropertyName('borderHeight', [])).toEqual('borderHeight'); - expect(normalizer.normalizePropertyName('-webkit-animation', [ - ])).toEqual('WebkitAnimation'); + expect(normalizer.normalizePropertyName('-webkit-animation', [])) + .toEqual('WebkitAnimation'); }); }); describe('normalizeStyleValue', () => { - function normalize(prop: string, val: string | number): string { + function normalize(prop: string, val: string|number): string { const errors: string[] = []; const result = normalizer.normalizeStyleValue(prop, prop, val, errors); if (errors.length) { diff --git a/packages/animations/browser/test/render/css_keyframes/css_keyframes_driver_spec.ts b/packages/animations/browser/test/render/css_keyframes/css_keyframes_driver_spec.ts index 747a3895751ee..54a4a73d06d1d 100644 --- a/packages/animations/browser/test/render/css_keyframes/css_keyframes_driver_spec.ts +++ b/packages/animations/browser/test/render/css_keyframes/css_keyframes_driver_spec.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {TestBed, fakeAsync, flushMicrotasks} from '@angular/core/testing'; +import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing'; import {CssKeyframesDriver} from '../../../src/render/css_keyframes/css_keyframes_driver'; import {CssKeyframesPlayer} from '../../../src/render/css_keyframes/css_keyframes_player'; @@ -16,7 +16,7 @@ import {assertElementExistsInDom, createElement, findKeyframeDefinition, forceRe const CSS_KEYFRAME_RULE_TYPE = 7; describe('CssKeyframesDriver tests', () => { - if (isNode || typeof(window as any)['AnimationEvent'] == 'undefined') return; + if (isNode || typeof (window as any)['AnimationEvent'] == 'undefined') return; describe('building keyframes', () => { it('should build CSS keyframe style object containing the keyframe styles', () => { @@ -28,7 +28,7 @@ describe('CssKeyframesDriver tests', () => { {opacity: 1, width: '200px', offset: 1}, ]); - const head = document.querySelector('head') !; + const head = document.querySelector('head')!; head.appendChild(kfElm); forceReflow(); @@ -67,7 +67,7 @@ describe('CssKeyframesDriver tests', () => { {width: '200px', offset: 1}, ]); - const head = document.querySelector('head') !; + const head = document.querySelector('head')!; head.appendChild(kfElm); forceReflow(); @@ -261,7 +261,7 @@ describe('CssKeyframesDriver tests', () => { player.play(); player.finish(); - player.beforeDestroy !(); + player.beforeDestroy!(); expect(player.currentSnapshot).toEqual({ width: '999px', height: '999px', diff --git a/packages/animations/browser/test/render/css_keyframes/direct_style_player_spec.ts b/packages/animations/browser/test/render/css_keyframes/direct_style_player_spec.ts index c04ae07783dfe..86234018ad614 100644 --- a/packages/animations/browser/test/render/css_keyframes/direct_style_player_spec.ts +++ b/packages/animations/browser/test/render/css_keyframes/direct_style_player_spec.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {TestBed, fakeAsync, flushMicrotasks} from '@angular/core/testing'; +import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing'; import {DirectStylePlayer} from '../../../src/render/css_keyframes/direct_style_player'; diff --git a/packages/animations/browser/test/render/css_keyframes/element_animation_style_handler_spec.ts b/packages/animations/browser/test/render/css_keyframes/element_animation_style_handler_spec.ts index d5b64b5758d1b..ad5984c599add 100644 --- a/packages/animations/browser/test/render/css_keyframes/element_animation_style_handler_spec.ts +++ b/packages/animations/browser/test/render/css_keyframes/element_animation_style_handler_spec.ts @@ -13,7 +13,7 @@ import {assertStyle, createElement, makeAnimationEvent, supportsAnimationEventCr const EMPTY_FN = () => {}; { describe('ElementAnimationStyleHandler', () => { - if (isNode || typeof(window as any)['AnimationEvent'] == 'undefined') return; + if (isNode || typeof (window as any)['AnimationEvent'] == 'undefined') return; it('should add and remove an animation on to an element\'s styling', () => { const element = createElement(); diff --git a/packages/animations/browser/test/render/css_keyframes/shared.ts b/packages/animations/browser/test/render/css_keyframes/shared.ts index e60a4f50ad665..d9592ee5a0f0a 100644 --- a/packages/animations/browser/test/render/css_keyframes/shared.ts +++ b/packages/animations/browser/test/render/css_keyframes/shared.ts @@ -10,7 +10,7 @@ export function forceReflow() { } export function makeAnimationEvent( - startOrEnd: 'start' | 'end', animationName: string, elapsedTime: number, timestamp?: number) { + startOrEnd: 'start'|'end', animationName: string, elapsedTime: number, timestamp?: number) { const e = new AnimationEvent('animation' + startOrEnd, {animationName, elapsedTime}); if (timestamp) { (e as any)._ngTestManualTimestamp = timestamp; diff --git a/packages/animations/browser/test/render/timeline_animation_engine_spec.ts b/packages/animations/browser/test/render/timeline_animation_engine_spec.ts index b9471416335b9..a6fb9e873103a 100644 --- a/packages/animations/browser/test/render/timeline_animation_engine_spec.ts +++ b/packages/animations/browser/test/render/timeline_animation_engine_spec.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AnimationMetadata, animate, style} from '@angular/animations'; +import {animate, AnimationMetadata, style} from '@angular/animations'; import {AnimationStyleNormalizer, NoopAnimationStyleNormalizer} from '../../src/dsl/style_normalization/animation_style_normalizer'; import {AnimationDriver} from '../../src/render/animation_driver'; @@ -14,98 +14,101 @@ import {TimelineAnimationEngine} from '../../src/render/timeline_animation_engin import {MockAnimationDriver, MockAnimationPlayer} from '../../testing/src/mock_animation_driver'; (function() { - const defaultDriver = new MockAnimationDriver(); +const defaultDriver = new MockAnimationDriver(); - function makeEngine(body: any, driver?: AnimationDriver, normalizer?: AnimationStyleNormalizer) { - return new TimelineAnimationEngine( - body, driver || defaultDriver, normalizer || new NoopAnimationStyleNormalizer()); - } +function makeEngine(body: any, driver?: AnimationDriver, normalizer?: AnimationStyleNormalizer) { + return new TimelineAnimationEngine( + body, driver || defaultDriver, normalizer || new NoopAnimationStyleNormalizer()); +} + +// these tests are only mean't to be run within the DOM +if (isNode) return; + +describe('TimelineAnimationEngine', () => { + let element: any; + + beforeEach(() => { + MockAnimationDriver.log = []; + element = document.createElement('div'); + document.body.appendChild(element); + }); + + afterEach(() => document.body.removeChild(element)); + + it('should animate a timeline', () => { + const engine = makeEngine(getBodyNode()); + const steps = [style({height: 100}), animate(1000, style({height: 0}))]; + expect(MockAnimationDriver.log.length).toEqual(0); + invokeAnimation(engine, element, steps); + expect(MockAnimationDriver.log.length).toEqual(1); + }); - // these tests are only mean't to be run within the DOM - if (isNode) return; - - describe('TimelineAnimationEngine', () => { - let element: any; - - beforeEach(() => { - MockAnimationDriver.log = []; - element = document.createElement('div'); - document.body.appendChild(element); - }); - - afterEach(() => document.body.removeChild(element)); - - it('should animate a timeline', () => { - const engine = makeEngine(getBodyNode()); - const steps = [style({height: 100}), animate(1000, style({height: 0}))]; - expect(MockAnimationDriver.log.length).toEqual(0); - invokeAnimation(engine, element, steps); - expect(MockAnimationDriver.log.length).toEqual(1); - }); - - it('should not destroy timeline-based animations after they have finished', () => { - const engine = makeEngine(getBodyNode()); - - const log: string[] = []; - function capture(value: string) { - return () => { log.push(value); }; - } - - const steps = [style({height: 0}), animate(1000, style({height: 500}))]; - - const player = invokeAnimation(engine, element, steps); - player.onDone(capture('done')); - player.onDestroy(capture('destroy')); - expect(log).toEqual([]); - - player.finish(); - expect(log).toEqual(['done']); - - player.destroy(); - expect(log).toEqual(['done', 'destroy']); - }); - - it('should normalize the style values that are animateTransitioned within an a timeline animation', - () => { - const engine = - makeEngine(getBodyNode(), defaultDriver, new SuffixNormalizer('-normalized')); - - const steps = [ - style({width: '333px'}), - animate(1000, style({width: '999px'})), - ]; - - const player = invokeAnimation(engine, element, steps) as MockAnimationPlayer; - expect(player.keyframes).toEqual([ - {'width-normalized': '333px-normalized', offset: 0}, - {'width-normalized': '999px-normalized', offset: 1} - ]); - }); - - it('should normalize `*` values', () => { - const driver = new SuperMockDriver(); - const engine = makeEngine(getBodyNode(), driver); - - const steps = [ - style({width: '*'}), - animate(1000, style({width: '999px'})), - ]; - - const player = invokeAnimation(engine, element, steps) as MockAnimationPlayer; - expect(player.keyframes).toEqual([{width: '*star*', offset: 0}, {width: '999px', offset: 1}]); - }); + it('should not destroy timeline-based animations after they have finished', () => { + const engine = makeEngine(getBodyNode()); + + const log: string[] = []; + function capture(value: string) { + return () => { + log.push(value); + }; + } + + const steps = [style({height: 0}), animate(1000, style({height: 500}))]; + + const player = invokeAnimation(engine, element, steps); + player.onDone(capture('done')); + player.onDestroy(capture('destroy')); + expect(log).toEqual([]); + + player.finish(); + expect(log).toEqual(['done']); + + player.destroy(); + expect(log).toEqual(['done', 'destroy']); }); + + it('should normalize the style values that are animateTransitioned within an a timeline animation', + () => { + const engine = makeEngine(getBodyNode(), defaultDriver, new SuffixNormalizer('-normalized')); + + const steps = [ + style({width: '333px'}), + animate(1000, style({width: '999px'})), + ]; + + const player = invokeAnimation(engine, element, steps) as MockAnimationPlayer; + expect(player.keyframes).toEqual([ + {'width-normalized': '333px-normalized', offset: 0}, + {'width-normalized': '999px-normalized', offset: 1} + ]); + }); + + it('should normalize `*` values', () => { + const driver = new SuperMockDriver(); + const engine = makeEngine(getBodyNode(), driver); + + const steps = [ + style({width: '*'}), + animate(1000, style({width: '999px'})), + ]; + + const player = invokeAnimation(engine, element, steps) as MockAnimationPlayer; + expect(player.keyframes).toEqual([{width: '*star*', offset: 0}, {width: '999px', offset: 1}]); + }); +}); })(); function invokeAnimation( - engine: TimelineAnimationEngine, element: any, steps: AnimationMetadata | AnimationMetadata[], + engine: TimelineAnimationEngine, element: any, steps: AnimationMetadata|AnimationMetadata[], id: string = 'id') { engine.register(id, steps); return engine.create(id, element); } class SuffixNormalizer extends AnimationStyleNormalizer { - constructor(private _suffix: string) { super(); } + constructor(private _suffix: string) { + super(); + } normalizePropertyName(propertyName: string, errors: string[]): string { return propertyName + this._suffix; @@ -119,5 +122,7 @@ class SuffixNormalizer extends AnimationStyleNormalizer { } class SuperMockDriver extends MockAnimationDriver { - computeStyle(element: any, prop: string, defaultValue?: string): string { return '*star*'; } + computeStyle(element: any, prop: string, defaultValue?: string): string { + return '*star*'; + } } diff --git a/packages/animations/browser/test/render/transition_animation_engine_spec.ts b/packages/animations/browser/test/render/transition_animation_engine_spec.ts index 98d80c294d6c4..21502489e9587 100644 --- a/packages/animations/browser/test/render/transition_animation_engine_spec.ts +++ b/packages/animations/browser/test/render/transition_animation_engine_spec.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AnimationEvent, AnimationMetadata, AnimationTriggerMetadata, NoopAnimationPlayer, animate, state, style, transition, trigger} from '@angular/animations'; +import {animate, AnimationEvent, AnimationMetadata, AnimationTriggerMetadata, NoopAnimationPlayer, state, style, transition, trigger} from '@angular/animations'; import {TriggerAst} from '../../src/dsl/animation_ast'; import {buildAnimationAst} from '../../src/dsl/animation_ast_builder'; @@ -18,673 +18,680 @@ import {MockAnimationDriver, MockAnimationPlayer} from '../../testing/src/mock_a const DEFAULT_NAMESPACE_ID = 'id'; (function() { - const driver = new MockAnimationDriver(); +const driver = new MockAnimationDriver(); - // these tests are only mean't to be run within the DOM - if (isNode) return; +// these tests are only mean't to be run within the DOM +if (isNode) return; - describe('TransitionAnimationEngine', () => { - let element: any; +describe('TransitionAnimationEngine', () => { + let element: any; - beforeEach(() => { - MockAnimationDriver.log = []; - element = document.createElement('div'); - document.body.appendChild(element); - }); + beforeEach(() => { + MockAnimationDriver.log = []; + element = document.createElement('div'); + document.body.appendChild(element); + }); - afterEach(() => { document.body.removeChild(element); }); + afterEach(() => { + document.body.removeChild(element); + }); - function makeEngine(normalizer?: AnimationStyleNormalizer) { - const engine = new TransitionAnimationEngine( - getBodyNode(), driver, normalizer || new NoopAnimationStyleNormalizer()); - engine.createNamespace(DEFAULT_NAMESPACE_ID, element); - return engine; - } + function makeEngine(normalizer?: AnimationStyleNormalizer) { + const engine = new TransitionAnimationEngine( + getBodyNode(), driver, normalizer || new NoopAnimationStyleNormalizer()); + engine.createNamespace(DEFAULT_NAMESPACE_ID, element); + return engine; + } - describe('trigger registration', () => { - it('should ignore and not throw an error if the same trigger is registered twice', () => { - // TODO (matsko): ask why this is avoided - const engine = makeEngine(); + describe('trigger registration', () => { + it('should ignore and not throw an error if the same trigger is registered twice', () => { + // TODO (matsko): ask why this is avoided + const engine = makeEngine(); + registerTrigger(element, engine, trigger('trig', [])); + expect(() => { registerTrigger(element, engine, trigger('trig', [])); - expect(() => { registerTrigger(element, engine, trigger('trig', [])); }).not.toThrow(); - }); + }).not.toThrow(); }); + }); - describe('property setting', () => { - it('should invoke a transition based on a property change', () => { - const engine = makeEngine(); - const trig = trigger('myTrigger', [ - transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) - ]); + describe('property setting', () => { + it('should invoke a transition based on a property change', () => { + const engine = makeEngine(); + const trig = trigger('myTrigger', [ + transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); - registerTrigger(element, engine, trig); - setProperty(element, engine, 'myTrigger', 'value'); - engine.flush(); - expect(engine.players.length).toEqual(1); + registerTrigger(element, engine, trig); + setProperty(element, engine, 'myTrigger', 'value'); + engine.flush(); + expect(engine.players.length).toEqual(1); - const player = MockAnimationDriver.log.pop() as MockAnimationPlayer; - expect(player.keyframes).toEqual([ - {height: '0px', offset: 0}, {height: '100px', offset: 1} - ]); - }); - - it('should not queue an animation if the property value has not changed at all', () => { - const engine = makeEngine(); + const player = MockAnimationDriver.log.pop() as MockAnimationPlayer; + expect(player.keyframes).toEqual([{height: '0px', offset: 0}, {height: '100px', offset: 1}]); + }); - const trig = trigger('myTrigger', [ - transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) - ]); + it('should not queue an animation if the property value has not changed at all', () => { + const engine = makeEngine(); - registerTrigger(element, engine, trig); - engine.flush(); - expect(engine.players.length).toEqual(0); + const trig = trigger('myTrigger', [ + transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); - setProperty(element, engine, 'myTrigger', 'abc'); - engine.flush(); - expect(engine.players.length).toEqual(1); + registerTrigger(element, engine, trig); + engine.flush(); + expect(engine.players.length).toEqual(0); - setProperty(element, engine, 'myTrigger', 'abc'); - engine.flush(); - expect(engine.players.length).toEqual(1); - }); + setProperty(element, engine, 'myTrigger', 'abc'); + engine.flush(); + expect(engine.players.length).toEqual(1); - it('should throw an error if an animation property without a matching trigger is changed', - () => { - const engine = makeEngine(); - expect(() => { - setProperty(element, engine, 'myTrigger', 'no'); - }).toThrowError(/The provided animation trigger "myTrigger" has not been registered!/); - }); + setProperty(element, engine, 'myTrigger', 'abc'); + engine.flush(); + expect(engine.players.length).toEqual(1); }); - describe('removal operations', () => { - it('should cleanup all inner state that\'s tied to an element once removed', () => { - const engine = makeEngine(); + it('should throw an error if an animation property without a matching trigger is changed', + () => { + const engine = makeEngine(); + expect(() => { + setProperty(element, engine, 'myTrigger', 'no'); + }).toThrowError(/The provided animation trigger "myTrigger" has not been registered!/); + }); + }); + + describe('removal operations', () => { + it('should cleanup all inner state that\'s tied to an element once removed', () => { + const engine = makeEngine(); - const trig = trigger('myTrigger', [ - transition(':leave', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) - ]); + const trig = trigger('myTrigger', [ + transition(':leave', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); - registerTrigger(element, engine, trig); - setProperty(element, engine, 'myTrigger', 'value'); - engine.flush(); + registerTrigger(element, engine, trig); + setProperty(element, engine, 'myTrigger', 'value'); + engine.flush(); - expect(engine.elementContainsData(DEFAULT_NAMESPACE_ID, element)).toBeTruthy(); + expect(engine.elementContainsData(DEFAULT_NAMESPACE_ID, element)).toBeTruthy(); - engine.removeNode(DEFAULT_NAMESPACE_ID, element, true, true); - engine.flush(); + engine.removeNode(DEFAULT_NAMESPACE_ID, element, true, true); + engine.flush(); - expect(engine.elementContainsData(DEFAULT_NAMESPACE_ID, element)).toBeTruthy(); - }); + expect(engine.elementContainsData(DEFAULT_NAMESPACE_ID, element)).toBeTruthy(); + }); - it('should create and recreate a namespace for a host element with the same component source', - () => { - const engine = makeEngine(); - - const trig = - trigger('myTrigger', [transition('* => *', animate(1234, style({color: 'red'})))]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, 'myTrigger', 'value'); - engine.flush(); - expect(((engine.players[0] as TransitionAnimationPlayer) - .getRealPlayer() as MockAnimationPlayer) - .duration) - .toEqual(1234); - - engine.destroy(DEFAULT_NAMESPACE_ID, null); - - registerTrigger(element, engine, trig); - setProperty(element, engine, 'myTrigger', 'value2'); - engine.flush(); - expect(((engine.players[0] as TransitionAnimationPlayer) - .getRealPlayer() as MockAnimationPlayer) - .duration) - .toEqual(1234); - }); - - it('should clear child node data when a parent node with leave transition is removed', () => { - const engine = makeEngine(); - const child = document.createElement('div'); - const parentTrigger = trigger('parent', [ - transition(':leave', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) - ]); - const childTrigger = trigger( - 'child', - [transition(':enter', [style({opacity: '0'}), animate(1000, style({opacity: '1'}))])]); - - registerTrigger(element, engine, parentTrigger); - registerTrigger(child, engine, childTrigger); - - element.appendChild(child); - engine.insertNode(DEFAULT_NAMESPACE_ID, child, element, true); - - setProperty(element, engine, 'parent', 'value'); - setProperty(child, engine, 'child', 'visible'); - engine.flush(); + it('should create and recreate a namespace for a host element with the same component source', + () => { + const engine = makeEngine(); + + const trig = + trigger('myTrigger', [transition('* => *', animate(1234, style({color: 'red'})))]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, 'myTrigger', 'value'); + engine.flush(); + expect(((engine.players[0] as TransitionAnimationPlayer).getRealPlayer() as + MockAnimationPlayer) + .duration) + .toEqual(1234); + + engine.destroy(DEFAULT_NAMESPACE_ID, null); + + registerTrigger(element, engine, trig); + setProperty(element, engine, 'myTrigger', 'value2'); + engine.flush(); + expect(((engine.players[0] as TransitionAnimationPlayer).getRealPlayer() as + MockAnimationPlayer) + .duration) + .toEqual(1234); + }); + + it('should clear child node data when a parent node with leave transition is removed', () => { + const engine = makeEngine(); + const child = document.createElement('div'); + const parentTrigger = trigger('parent', [ + transition(':leave', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); + const childTrigger = trigger( + 'child', + [transition(':enter', [style({opacity: '0'}), animate(1000, style({opacity: '1'}))])]); + + registerTrigger(element, engine, parentTrigger); + registerTrigger(child, engine, childTrigger); + + element.appendChild(child); + engine.insertNode(DEFAULT_NAMESPACE_ID, child, element, true); + + setProperty(element, engine, 'parent', 'value'); + setProperty(child, engine, 'child', 'visible'); + engine.flush(); + + expect(engine.statesByElement.has(element)).toBe(true, 'Expected parent data to be defined.'); + expect(engine.statesByElement.has(child)).toBe(true, 'Expected child data to be defined.'); + + engine.removeNode(DEFAULT_NAMESPACE_ID, element, true, true); + engine.flush(); + engine.players[0].finish(); + + expect(engine.statesByElement.has(element)) + .toBe(false, 'Expected parent data to be cleared.'); + expect(engine.statesByElement.has(child)).toBe(false, 'Expected child data to be cleared.'); + }); + }); - expect(engine.statesByElement.has(element)) - .toBe(true, 'Expected parent data to be defined.'); - expect(engine.statesByElement.has(child)).toBe(true, 'Expected child data to be defined.'); + describe('event listeners', () => { + it('should listen to the onStart operation for the animation', () => { + const engine = makeEngine(); - engine.removeNode(DEFAULT_NAMESPACE_ID, element, true, true); - engine.flush(); - engine.players[0].finish(); + const trig = trigger('myTrigger', [ + transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); - expect(engine.statesByElement.has(element)) - .toBe(false, 'Expected parent data to be cleared.'); - expect(engine.statesByElement.has(child)).toBe(false, 'Expected child data to be cleared.'); - }); + let count = 0; + registerTrigger(element, engine, trig); + listen(element, engine, 'myTrigger', 'start', () => count++); + setProperty(element, engine, 'myTrigger', 'value'); + expect(count).toEqual(0); + engine.flush(); + expect(count).toEqual(1); }); - describe('event listeners', () => { - it('should listen to the onStart operation for the animation', () => { - const engine = makeEngine(); + it('should listen to the onDone operation for the animation', () => { + const engine = makeEngine(); - const trig = trigger('myTrigger', [ - transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) - ]); + const trig = trigger('myTrigger', [ + transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); - let count = 0; - registerTrigger(element, engine, trig); - listen(element, engine, 'myTrigger', 'start', () => count++); - setProperty(element, engine, 'myTrigger', 'value'); - expect(count).toEqual(0); + let count = 0; + registerTrigger(element, engine, trig); + listen(element, engine, 'myTrigger', 'done', () => count++); + setProperty(element, engine, 'myTrigger', 'value'); + expect(count).toEqual(0); - engine.flush(); - expect(count).toEqual(1); - }); + engine.flush(); + expect(count).toEqual(0); - it('should listen to the onDone operation for the animation', () => { - const engine = makeEngine(); + engine.players[0].finish(); + expect(count).toEqual(1); + }); - const trig = trigger('myTrigger', [ - transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) - ]); + it('should throw an error when an event is listened to that isn\'t supported', () => { + const engine = makeEngine(); + const trig = trigger('myTrigger', []); + registerTrigger(element, engine, trig); - let count = 0; - registerTrigger(element, engine, trig); - listen(element, engine, 'myTrigger', 'done', () => count++); - setProperty(element, engine, 'myTrigger', 'value'); - expect(count).toEqual(0); + expect(() => { + listen(element, engine, 'myTrigger', 'explode', () => {}); + }) + .toThrowError( + /The provided animation trigger event "explode" for the animation trigger "myTrigger" is not supported!/); + }); - engine.flush(); - expect(count).toEqual(0); + it('should throw an error when an event is listened for a trigger that doesn\'t exist', () => { + const engine = makeEngine(); + expect(() => { + listen(element, engine, 'myTrigger', 'explode', () => {}); + }) + .toThrowError( + /Unable to listen on the animation trigger event "explode" because the animation trigger "myTrigger" doesn\'t exist!/); + }); - engine.players[0].finish(); - expect(count).toEqual(1); - }); + it('should throw an error when an undefined event is listened for', () => { + const engine = makeEngine(); + const trig = trigger('myTrigger', []); + registerTrigger(element, engine, trig); + expect(() => { + listen(element, engine, 'myTrigger', '', () => {}); + }) + .toThrowError( + /Unable to listen on the animation trigger "myTrigger" because the provided event is undefined!/); + }); - it('should throw an error when an event is listened to that isn\'t supported', () => { - const engine = makeEngine(); - const trig = trigger('myTrigger', []); - registerTrigger(element, engine, trig); + it('should retain event listeners and call them for successive animation state changes', () => { + const engine = makeEngine(); + const trig = trigger('myTrigger', [ + transition('* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); - expect(() => { listen(element, engine, 'myTrigger', 'explode', () => {}); }) - .toThrowError( - /The provided animation trigger event "explode" for the animation trigger "myTrigger" is not supported!/); - }); + registerTrigger(element, engine, trig); - it('should throw an error when an event is listened for a trigger that doesn\'t exist', () => { - const engine = makeEngine(); - expect(() => { listen(element, engine, 'myTrigger', 'explode', () => {}); }) - .toThrowError( - /Unable to listen on the animation trigger event "explode" because the animation trigger "myTrigger" doesn\'t exist!/); - }); + let count = 0; + listen(element, engine, 'myTrigger', 'start', () => count++); - it('should throw an error when an undefined event is listened for', () => { - const engine = makeEngine(); - const trig = trigger('myTrigger', []); - registerTrigger(element, engine, trig); - expect(() => { listen(element, engine, 'myTrigger', '', () => {}); }) - .toThrowError( - /Unable to listen on the animation trigger "myTrigger" because the provided event is undefined!/); - }); + setProperty(element, engine, 'myTrigger', '123'); + engine.flush(); + expect(count).toEqual(1); - it('should retain event listeners and call them for successive animation state changes', - () => { - const engine = makeEngine(); - const trig = trigger( - 'myTrigger', - [transition( - '* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))])]); - - registerTrigger(element, engine, trig); - - let count = 0; - listen(element, engine, 'myTrigger', 'start', () => count++); - - setProperty(element, engine, 'myTrigger', '123'); - engine.flush(); - expect(count).toEqual(1); - - setProperty(element, engine, 'myTrigger', '456'); - engine.flush(); - expect(count).toEqual(2); - }); - - it('should only fire event listener changes for when the corresponding trigger changes state', - () => { - const engine = makeEngine(); - const trig1 = trigger( - 'myTrigger1', - [transition( - '* => 123', [style({height: '0px'}), animate(1000, style({height: '100px'}))])]); - registerTrigger(element, engine, trig1); - - const trig2 = trigger( - 'myTrigger2', - [transition( - '* => 123', [style({width: '0px'}), animate(1000, style({width: '100px'}))])]); - registerTrigger(element, engine, trig2); - - let count = 0; - listen(element, engine, 'myTrigger1', 'start', () => count++); - - setProperty(element, engine, 'myTrigger1', '123'); - engine.flush(); - expect(count).toEqual(1); - - setProperty(element, engine, 'myTrigger2', '123'); - engine.flush(); - expect(count).toEqual(1); - }); - - it('should allow a listener to be deregistered, but only after a flush occurs', () => { - const engine = makeEngine(); - const trig = trigger( - 'myTrigger', - [transition( - '* => 123', [style({height: '0px'}), animate(1000, style({height: '100px'}))])]); - registerTrigger(element, engine, trig); - - let count = 0; - const deregisterFn = listen(element, engine, 'myTrigger', 'start', () => count++); - setProperty(element, engine, 'myTrigger', '123'); - engine.flush(); - expect(count).toEqual(1); + setProperty(element, engine, 'myTrigger', '456'); + engine.flush(); + expect(count).toEqual(2); + }); - deregisterFn(); - engine.flush(); + it('should only fire event listener changes for when the corresponding trigger changes state', + () => { + const engine = makeEngine(); + const trig1 = trigger('myTrigger1', [ + transition('* => 123', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); + registerTrigger(element, engine, trig1); + + const trig2 = trigger('myTrigger2', [ + transition('* => 123', [style({width: '0px'}), animate(1000, style({width: '100px'}))]) + ]); + registerTrigger(element, engine, trig2); + + let count = 0; + listen(element, engine, 'myTrigger1', 'start', () => count++); + + setProperty(element, engine, 'myTrigger1', '123'); + engine.flush(); + expect(count).toEqual(1); + + setProperty(element, engine, 'myTrigger2', '123'); + engine.flush(); + expect(count).toEqual(1); + }); + + it('should allow a listener to be deregistered, but only after a flush occurs', () => { + const engine = makeEngine(); + const trig = trigger('myTrigger', [ + transition('* => 123', [style({height: '0px'}), animate(1000, style({height: '100px'}))]) + ]); + registerTrigger(element, engine, trig); + + let count = 0; + const deregisterFn = listen(element, engine, 'myTrigger', 'start', () => count++); + setProperty(element, engine, 'myTrigger', '123'); + engine.flush(); + expect(count).toEqual(1); + + deregisterFn(); + engine.flush(); + + setProperty(element, engine, 'myTrigger', '456'); + engine.flush(); + expect(count).toEqual(1); + }); - setProperty(element, engine, 'myTrigger', '456'); - engine.flush(); - expect(count).toEqual(1); + it('should trigger a listener callback with an AnimationEvent argument', () => { + const engine = makeEngine(); + registerTrigger( + element, engine, trigger('myTrigger', [ + transition('* => *', [style({height: '0px'}), animate(1234, style({height: '100px'}))]) + ])); + + // we do this so that the next transition has a starting value that isn't null + setProperty(element, engine, 'myTrigger', '123'); + engine.flush(); + + let capture: AnimationEvent = null!; + listen(element, engine, 'myTrigger', 'start', e => capture = e); + listen(element, engine, 'myTrigger', 'done', e => capture = e); + setProperty(element, engine, 'myTrigger', '456'); + engine.flush(); + + delete (capture as any)['_data']; + expect(capture).toEqual({ + element, + triggerName: 'myTrigger', + phaseName: 'start', + fromState: '123', + toState: '456', + totalTime: 1234, + disabled: false }); - it('should trigger a listener callback with an AnimationEvent argument', () => { - const engine = makeEngine(); - registerTrigger( - element, engine, trigger('myTrigger', [ - transition( - '* => *', [style({height: '0px'}), animate(1234, style({height: '100px'}))]) - ])); - - // we do this so that the next transition has a starting value that isn't null - setProperty(element, engine, 'myTrigger', '123'); - engine.flush(); - - let capture: AnimationEvent = null !; - listen(element, engine, 'myTrigger', 'start', e => capture = e); - listen(element, engine, 'myTrigger', 'done', e => capture = e); - setProperty(element, engine, 'myTrigger', '456'); - engine.flush(); - - delete (capture as any)['_data']; - expect(capture).toEqual({ - element, - triggerName: 'myTrigger', - phaseName: 'start', - fromState: '123', - toState: '456', - totalTime: 1234, - disabled: false - }); - - capture = null !; - const player = engine.players.pop() !; - player.finish(); - - delete (capture as any)['_data']; - expect(capture).toEqual({ - element, - triggerName: 'myTrigger', - phaseName: 'done', - fromState: '123', - toState: '456', - totalTime: 1234, - disabled: false - }); + capture = null!; + const player = engine.players.pop()!; + player.finish(); + + delete (capture as any)['_data']; + expect(capture).toEqual({ + element, + triggerName: 'myTrigger', + phaseName: 'done', + fromState: '123', + toState: '456', + totalTime: 1234, + disabled: false }); }); + }); - describe('transition operations', () => { - it('should persist the styles on the element as actual styles once the animation is complete', - () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('on', style({height: '100px'})), state('off', style({height: '0px'})), - transition('on => off', animate(9876)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'on'); - setProperty(element, engine, trig.name, 'off'); - engine.flush(); - - expect(element.style.height).not.toEqual('0px'); - engine.players[0].finish(); - expect(element.style.height).toEqual('0px'); - }); - - it('should remove all existing state styling from an element when a follow-up transition occurs on the same trigger', - () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('a', style({height: '100px'})), state('b', style({height: '500px'})), - state('c', style({width: '200px'})), transition('* => *', animate(9876)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'a'); - setProperty(element, engine, trig.name, 'b'); - engine.flush(); - - const player1 = engine.players[0]; - player1.finish(); - expect(element.style.height).toEqual('500px'); - - setProperty(element, engine, trig.name, 'c'); - engine.flush(); - - const player2 = engine.players[0]; - expect(element.style.height).not.toEqual('500px'); - player2.finish(); - expect(element.style.width).toEqual('200px'); - expect(element.style.height).not.toEqual('500px'); - }); - - it('should allow two animation transitions with different triggers to animate in parallel', - () => { - const engine = makeEngine(); - const trig1 = trigger('something1', [ - state('a', style({width: '100px'})), state('b', style({width: '200px'})), - transition('* => *', animate(1000)) - ]); - - const trig2 = trigger('something2', [ - state('x', style({height: '500px'})), state('y', style({height: '1000px'})), - transition('* => *', animate(2000)) - ]); - - registerTrigger(element, engine, trig1); - registerTrigger(element, engine, trig2); - - let doneCount = 0; - function doneCallback() { doneCount++; } - - setProperty(element, engine, trig1.name, 'a'); - setProperty(element, engine, trig1.name, 'b'); - setProperty(element, engine, trig2.name, 'x'); - setProperty(element, engine, trig2.name, 'y'); - engine.flush(); - - const player1 = engine.players[0] !; - player1.onDone(doneCallback); - expect(doneCount).toEqual(0); - - const player2 = engine.players[1] !; - player2.onDone(doneCallback); - expect(doneCount).toEqual(0); - - player1.finish(); - expect(doneCount).toEqual(1); - - player2.finish(); - expect(doneCount).toEqual(2); - - expect(element.style.width).toEqual('200px'); - expect(element.style.height).toEqual('1000px'); - }); - - it('should cancel a previously running animation when a follow-up transition kicks off on the same trigger', - () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('x', style({opacity: 0})), - state('y', style({opacity: .5})), - state('z', style({opacity: 1})), - transition('* => *', animate(1000)), - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'x'); - setProperty(element, engine, trig.name, 'y'); - engine.flush(); - - expect(parseFloat(element.style.opacity)).not.toEqual(.5); - - const player1 = engine.players[0]; - setProperty(element, engine, trig.name, 'z'); - engine.flush(); - - const player2 = engine.players[0]; - - expect(parseFloat(element.style.opacity)).not.toEqual(.5); - - player2.finish(); - expect(parseFloat(element.style.opacity)).toEqual(1); - - player1.finish(); - expect(parseFloat(element.style.opacity)).toEqual(1); - }); - - it('should pass in the previously running players into the follow-up transition player when cancelled', - () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('x', style({opacity: 0})), state('y', style({opacity: .5})), - state('z', style({opacity: 1})), transition('* => *', animate(1000)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'x'); - setProperty(element, engine, trig.name, 'y'); - engine.flush(); - - const player1 = MockAnimationDriver.log.pop() !as MockAnimationPlayer; - player1.setPosition(0.5); - - setProperty(element, engine, trig.name, 'z'); - engine.flush(); - - const player2 = MockAnimationDriver.log.pop() !as MockAnimationPlayer; - expect(player2.previousPlayers).toEqual([player1]); - player2.finish(); - - setProperty(element, engine, trig.name, 'x'); - engine.flush(); - - const player3 = MockAnimationDriver.log.pop() !as MockAnimationPlayer; - expect(player3.previousPlayers).toEqual([]); - }); - - it('should cancel all existing players if a removal animation is set to occur', () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('m', style({opacity: 0})), state('n', style({opacity: 1})), - transition('* => *', animate(1000)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'm'); - setProperty(element, engine, trig.name, 'n'); - engine.flush(); + describe('transition operations', () => { + it('should persist the styles on the element as actual styles once the animation is complete', + () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('on', style({height: '100px'})), state('off', style({height: '0px'})), + transition('on => off', animate(9876)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'on'); + setProperty(element, engine, trig.name, 'off'); + engine.flush(); + + expect(element.style.height).not.toEqual('0px'); + engine.players[0].finish(); + expect(element.style.height).toEqual('0px'); + }); + + it('should remove all existing state styling from an element when a follow-up transition occurs on the same trigger', + () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('a', style({height: '100px'})), state('b', style({height: '500px'})), + state('c', style({width: '200px'})), transition('* => *', animate(9876)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'a'); + setProperty(element, engine, trig.name, 'b'); + engine.flush(); + + const player1 = engine.players[0]; + player1.finish(); + expect(element.style.height).toEqual('500px'); + + setProperty(element, engine, trig.name, 'c'); + engine.flush(); + + const player2 = engine.players[0]; + expect(element.style.height).not.toEqual('500px'); + player2.finish(); + expect(element.style.width).toEqual('200px'); + expect(element.style.height).not.toEqual('500px'); + }); + + it('should allow two animation transitions with different triggers to animate in parallel', + () => { + const engine = makeEngine(); + const trig1 = trigger('something1', [ + state('a', style({width: '100px'})), state('b', style({width: '200px'})), + transition('* => *', animate(1000)) + ]); + + const trig2 = trigger('something2', [ + state('x', style({height: '500px'})), state('y', style({height: '1000px'})), + transition('* => *', animate(2000)) + ]); + + registerTrigger(element, engine, trig1); + registerTrigger(element, engine, trig2); + + let doneCount = 0; + function doneCallback() { + doneCount++; + } + + setProperty(element, engine, trig1.name, 'a'); + setProperty(element, engine, trig1.name, 'b'); + setProperty(element, engine, trig2.name, 'x'); + setProperty(element, engine, trig2.name, 'y'); + engine.flush(); + + const player1 = engine.players[0]!; + player1.onDone(doneCallback); + expect(doneCount).toEqual(0); + + const player2 = engine.players[1]!; + player2.onDone(doneCallback); + expect(doneCount).toEqual(0); + + player1.finish(); + expect(doneCount).toEqual(1); + + player2.finish(); + expect(doneCount).toEqual(2); + + expect(element.style.width).toEqual('200px'); + expect(element.style.height).toEqual('1000px'); + }); + + it('should cancel a previously running animation when a follow-up transition kicks off on the same trigger', + () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('x', style({opacity: 0})), + state('y', style({opacity: .5})), + state('z', style({opacity: 1})), + transition('* => *', animate(1000)), + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'x'); + setProperty(element, engine, trig.name, 'y'); + engine.flush(); + + expect(parseFloat(element.style.opacity)).not.toEqual(.5); + + const player1 = engine.players[0]; + setProperty(element, engine, trig.name, 'z'); + engine.flush(); + + const player2 = engine.players[0]; + + expect(parseFloat(element.style.opacity)).not.toEqual(.5); + + player2.finish(); + expect(parseFloat(element.style.opacity)).toEqual(1); + + player1.finish(); + expect(parseFloat(element.style.opacity)).toEqual(1); + }); + + it('should pass in the previously running players into the follow-up transition player when cancelled', + () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('x', style({opacity: 0})), state('y', style({opacity: .5})), + state('z', style({opacity: 1})), transition('* => *', animate(1000)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'x'); + setProperty(element, engine, trig.name, 'y'); + engine.flush(); + + const player1 = MockAnimationDriver.log.pop()! as MockAnimationPlayer; + player1.setPosition(0.5); + + setProperty(element, engine, trig.name, 'z'); + engine.flush(); + + const player2 = MockAnimationDriver.log.pop()! as MockAnimationPlayer; + expect(player2.previousPlayers).toEqual([player1]); + player2.finish(); + + setProperty(element, engine, trig.name, 'x'); + engine.flush(); + + const player3 = MockAnimationDriver.log.pop()! as MockAnimationPlayer; + expect(player3.previousPlayers).toEqual([]); + }); - let doneCount = 0; - function doneCallback() { doneCount++; } + it('should cancel all existing players if a removal animation is set to occur', () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('m', style({opacity: 0})), state('n', style({opacity: 1})), + transition('* => *', animate(1000)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'm'); + setProperty(element, engine, trig.name, 'n'); + engine.flush(); - const player1 = engine.players[0]; - player1.onDone(doneCallback); + let doneCount = 0; + function doneCallback() { + doneCount++; + } - expect(doneCount).toEqual(0); + const player1 = engine.players[0]; + player1.onDone(doneCallback); - setProperty(element, engine, trig.name, 'void'); - engine.flush(); + expect(doneCount).toEqual(0); - expect(doneCount).toEqual(1); - }); - - it('should only persist styles that exist in the final state styles and not the last keyframe', - () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('0', style({width: '0px'})), state('1', style({width: '100px'})), - transition('* => *', [animate(1000, style({height: '200px'}))]) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, '0'); - setProperty(element, engine, trig.name, '1'); - engine.flush(); - - const player = engine.players[0] !; - expect(element.style.width).not.toEqual('100px'); - - player.finish(); - expect(element.style.height).not.toEqual('200px'); - expect(element.style.width).toEqual('100px'); - }); - - it('should default to using styling from the `*` state if a matching state is not found', - () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('a', style({opacity: 0})), state('*', style({opacity: .5})), - transition('* => *', animate(1000)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'a'); - setProperty(element, engine, trig.name, 'z'); - engine.flush(); - - engine.players[0].finish(); - expect(parseFloat(element.style.opacity)).toEqual(.5); - }); - - it('should treat `void` as `void`', () => { - const engine = makeEngine(); - const trig = trigger('something', [ - state('a', style({opacity: 0})), state('void', style({opacity: .8})), - transition('* => *', animate(1000)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'a'); - setProperty(element, engine, trig.name, 'void'); - engine.flush(); + setProperty(element, engine, trig.name, 'void'); + engine.flush(); - engine.players[0].finish(); - expect(parseFloat(element.style.opacity)).toEqual(.8); - }); + expect(doneCount).toEqual(1); }); - describe('style normalizer', () => { - it('should normalize the style values that are animateTransitioned within an a transition animation', - () => { - const engine = makeEngine(new SuffixNormalizer('-normalized')); - - const trig = trigger('something', [ - state('on', style({height: 100})), state('off', style({height: 0})), - transition('on => off', animate(9876)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'on'); - setProperty(element, engine, trig.name, 'off'); - engine.flush(); - - const player = MockAnimationDriver.log.pop() as MockAnimationPlayer; - expect(player.keyframes).toEqual([ - {'height-normalized': '100-normalized', offset: 0}, - {'height-normalized': '0-normalized', offset: 1} - ]); - }); - - it('should throw an error when normalization fails within a transition animation', () => { - const engine = makeEngine(new ExactCssValueNormalizer({left: '100px'})); - - const trig = trigger('something', [ - state('a', style({left: '0px', width: '200px'})), - state('b', style({left: '100px', width: '100px'})), transition('a => b', animate(9876)) - ]); - - registerTrigger(element, engine, trig); - setProperty(element, engine, trig.name, 'a'); - setProperty(element, engine, trig.name, 'b'); - - let errorMessage = ''; - try { - engine.flush(); - } catch (e) { - errorMessage = e.toString(); - } - - expect(errorMessage).toMatch(/Unable to animate due to the following errors:/); - expect(errorMessage).toMatch(/- The CSS property `left` is not allowed to be `0px`/); - expect(errorMessage).toMatch(/- The CSS property `width` is not allowed/); - }); + it('should only persist styles that exist in the final state styles and not the last keyframe', + () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('0', style({width: '0px'})), state('1', style({width: '100px'})), + transition('* => *', [animate(1000, style({height: '200px'}))]) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, '0'); + setProperty(element, engine, trig.name, '1'); + engine.flush(); + + const player = engine.players[0]!; + expect(element.style.width).not.toEqual('100px'); + + player.finish(); + expect(element.style.height).not.toEqual('200px'); + expect(element.style.width).toEqual('100px'); + }); + + it('should default to using styling from the `*` state if a matching state is not found', + () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('a', style({opacity: 0})), state('*', style({opacity: .5})), + transition('* => *', animate(1000)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'a'); + setProperty(element, engine, trig.name, 'z'); + engine.flush(); + + engine.players[0].finish(); + expect(parseFloat(element.style.opacity)).toEqual(.5); + }); + + it('should treat `void` as `void`', () => { + const engine = makeEngine(); + const trig = trigger('something', [ + state('a', style({opacity: 0})), state('void', style({opacity: .8})), + transition('* => *', animate(1000)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'a'); + setProperty(element, engine, trig.name, 'void'); + engine.flush(); + + engine.players[0].finish(); + expect(parseFloat(element.style.opacity)).toEqual(.8); }); + }); + + describe('style normalizer', () => { + it('should normalize the style values that are animateTransitioned within an a transition animation', + () => { + const engine = makeEngine(new SuffixNormalizer('-normalized')); + + const trig = trigger('something', [ + state('on', style({height: 100})), state('off', style({height: 0})), + transition('on => off', animate(9876)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'on'); + setProperty(element, engine, trig.name, 'off'); + engine.flush(); + + const player = MockAnimationDriver.log.pop() as MockAnimationPlayer; + expect(player.keyframes).toEqual([ + {'height-normalized': '100-normalized', offset: 0}, + {'height-normalized': '0-normalized', offset: 1} + ]); + }); + + it('should throw an error when normalization fails within a transition animation', () => { + const engine = makeEngine(new ExactCssValueNormalizer({left: '100px'})); + + const trig = trigger('something', [ + state('a', style({left: '0px', width: '200px'})), + state('b', style({left: '100px', width: '100px'})), transition('a => b', animate(9876)) + ]); + + registerTrigger(element, engine, trig); + setProperty(element, engine, trig.name, 'a'); + setProperty(element, engine, trig.name, 'b'); + + let errorMessage = ''; + try { + engine.flush(); + } catch (e) { + errorMessage = e.toString(); + } - describe('view operations', () => { - it('should perform insert operations immediately ', () => { - const engine = makeEngine(); + expect(errorMessage).toMatch(/Unable to animate due to the following errors:/); + expect(errorMessage).toMatch(/- The CSS property `left` is not allowed to be `0px`/); + expect(errorMessage).toMatch(/- The CSS property `width` is not allowed/); + }); + }); - const child1 = document.createElement('div'); - const child2 = document.createElement('div'); - element.appendChild(child1); - element.appendChild(child2); + describe('view operations', () => { + it('should perform insert operations immediately ', () => { + const engine = makeEngine(); - element.appendChild(child1); - engine.insertNode(DEFAULT_NAMESPACE_ID, child1, element, true); - element.appendChild(child2); - engine.insertNode(DEFAULT_NAMESPACE_ID, child2, element, true); + const child1 = document.createElement('div'); + const child2 = document.createElement('div'); + element.appendChild(child1); + element.appendChild(child2); - expect(element.contains(child1)).toBe(true); - expect(element.contains(child2)).toBe(true); - }); + element.appendChild(child1); + engine.insertNode(DEFAULT_NAMESPACE_ID, child1, element, true); + element.appendChild(child2); + engine.insertNode(DEFAULT_NAMESPACE_ID, child2, element, true); - it('should not throw an error if a missing namespace is used', () => { - const engine = makeEngine(); - const ID = 'foo'; - const TRIGGER = 'fooTrigger'; - expect(() => { engine.trigger(ID, element, TRIGGER, 'something'); }).not.toThrow(); - }); + expect(element.contains(child1)).toBe(true); + expect(element.contains(child2)).toBe(true); + }); - it('should still apply state-styling to an element even if it is not yet inserted into the DOM', - () => { - const engine = makeEngine(); - const orphanElement = document.createElement('div'); - orphanElement.classList.add('orphan'); - - registerTrigger( - orphanElement, engine, trigger('trig', [ - state('go', style({opacity: 0.5})), transition('* => go', animate(1000)) - ])); - - setProperty(orphanElement, engine, 'trig', 'go'); - engine.flush(); - expect(engine.players.length).toEqual(0); - expect(orphanElement.style.opacity).toEqual('0.5'); - }); + it('should not throw an error if a missing namespace is used', () => { + const engine = makeEngine(); + const ID = 'foo'; + const TRIGGER = 'fooTrigger'; + expect(() => { + engine.trigger(ID, element, TRIGGER, 'something'); + }).not.toThrow(); }); + + it('should still apply state-styling to an element even if it is not yet inserted into the DOM', + () => { + const engine = makeEngine(); + const orphanElement = document.createElement('div'); + orphanElement.classList.add('orphan'); + + registerTrigger(orphanElement, engine, trigger('trig', [ + state('go', style({opacity: 0.5})), transition('* => go', animate(1000)) + ])); + + setProperty(orphanElement, engine, 'trig', 'go'); + engine.flush(); + expect(engine.players.length).toEqual(0); + expect(orphanElement.style.opacity).toEqual('0.5'); + }); }); +}); })(); class SuffixNormalizer extends AnimationStyleNormalizer { - constructor(private _suffix: string) { super(); } + constructor(private _suffix: string) { + super(); + } normalizePropertyName(propertyName: string, errors: string[]): string { return propertyName + this._suffix; @@ -698,7 +705,9 @@ class SuffixNormalizer extends AnimationStyleNormalizer { } class ExactCssValueNormalizer extends AnimationStyleNormalizer { - constructor(private _allowedValues: {[propName: string]: any}) { super(); } + constructor(private _allowedValues: {[propName: string]: any}) { + super(); + } normalizePropertyName(propertyName: string, errors: string[]): string { if (!this._allowedValues[propertyName]) { diff --git a/packages/animations/browser/test/render/web_animations/web_animations_player_spec.ts b/packages/animations/browser/test/render/web_animations/web_animations_player_spec.ts index c8e44bc11ca83..cbcdceda78f63 100644 --- a/packages/animations/browser/test/render/web_animations/web_animations_player_spec.ts +++ b/packages/animations/browser/test/render/web_animations/web_animations_player_spec.ts @@ -13,7 +13,9 @@ import {WebAnimationsPlayer} from '../../../src/render/web_animations/web_animat let innerPlayer: MockDomAnimation|null = null; beforeEach(() => { element = {}; - element['animate'] = () => { return innerPlayer = new MockDomAnimation(); }; + element['animate'] = () => { + return innerPlayer = new MockDomAnimation(); + }; }); describe('WebAnimationsPlayer tests', () => { @@ -26,7 +28,7 @@ import {WebAnimationsPlayer} from '../../../src/render/web_animations/web_animat const player = new WebAnimationsPlayer(element, keyframes, {duration: 1000}); player.init(); - const p = innerPlayer !; + const p = innerPlayer!; expect(p.log).toEqual(['pause']); player.play(); @@ -42,7 +44,7 @@ import {WebAnimationsPlayer} from '../../../src/render/web_animations/web_animat const player = new WebAnimationsPlayer(element, keyframes, {duration: 1000}); player.play(); - const p = innerPlayer !; + const p = innerPlayer!; expect(p.log).toEqual(['play']); }); @@ -70,10 +72,18 @@ import {WebAnimationsPlayer} from '../../../src/render/web_animations/web_animat class MockDomAnimation implements DOMAnimation { log: string[] = []; - cancel(): void { this.log.push('cancel'); } - play(): void { this.log.push('play'); } - pause(): void { this.log.push('pause'); } - finish(): void { this.log.push('finish'); } + cancel(): void { + this.log.push('cancel'); + } + play(): void { + this.log.push('play'); + } + pause(): void { + this.log.push('pause'); + } + finish(): void { + this.log.push('finish'); + } onfinish: Function = () => {}; position: number = 0; currentTime: number = 0; diff --git a/packages/animations/browser/test/shared.ts b/packages/animations/browser/test/shared.ts index 12904ef157232..f89b4ddf79341 100644 --- a/packages/animations/browser/test/shared.ts +++ b/packages/animations/browser/test/shared.ts @@ -21,8 +21,8 @@ export function makeTrigger( const triggerAst = buildAnimationAst(driver, triggerData, errors) as TriggerAst; if (!skipErrors && errors.length) { const LINE_START = '\n - '; - throw new Error( - `Animation parsing for the ${name} trigger have failed:${LINE_START}${errors.join(LINE_START)}`); + throw new Error(`Animation parsing for the ${name} trigger have failed:${LINE_START}${ + errors.join(LINE_START)}`); } return buildTrigger(name, triggerAst); } diff --git a/packages/animations/browser/testing/src/mock_animation_driver.ts b/packages/animations/browser/testing/src/mock_animation_driver.ts index 367d9e4a0128f..d21fc192d3e40 100644 --- a/packages/animations/browser/testing/src/mock_animation_driver.ts +++ b/packages/animations/browser/testing/src/mock_animation_driver.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimationPlayer, NoopAnimationPlayer, ɵStyleData} from '@angular/animations'; +import {AnimationPlayer, AUTO_STYLE, NoopAnimationPlayer, ɵStyleData} from '@angular/animations'; import {AnimationDriver, ɵallowPreviousPlayerStylesMerge as allowPreviousPlayerStylesMerge, ɵcontainsElement as containsElement, ɵinvokeQuery as invokeQuery, ɵmatchesElement as matchesElement, ɵvalidateStyleProperty as validateStyleProperty} from '@angular/animations/browser'; @@ -15,13 +15,17 @@ import {AnimationDriver, ɵallowPreviousPlayerStylesMerge as allowPreviousPlayer export class MockAnimationDriver implements AnimationDriver { static log: AnimationPlayer[] = []; - validateStyleProperty(prop: string): boolean { return validateStyleProperty(prop); } + validateStyleProperty(prop: string): boolean { + return validateStyleProperty(prop); + } matchesElement(element: any, selector: string): boolean { return matchesElement(element, selector); } - containsElement(elm1: any, elm2: any): boolean { return containsElement(elm1, elm2); } + containsElement(elm1: any, elm2: any): boolean { + return containsElement(elm1, elm2); + } query(element: any, selector: string, multi: boolean): any[] { return invokeQuery(element, selector, multi); @@ -32,7 +36,7 @@ export class MockAnimationDriver implements AnimationDriver { } animate( - element: any, keyframes: {[key: string]: string | number}[], duration: number, delay: number, + element: any, keyframes: {[key: string]: string|number}[], duration: number, delay: number, easing: string, previousPlayers: any[] = []): MockAnimationPlayer { const player = new MockAnimationPlayer(element, keyframes, duration, delay, easing, previousPlayers); @@ -47,12 +51,12 @@ export class MockAnimationDriver implements AnimationDriver { export class MockAnimationPlayer extends NoopAnimationPlayer { private __finished = false; private __started = false; - public previousStyles: {[key: string]: string | number} = {}; + public previousStyles: {[key: string]: string|number} = {}; private _onInitFns: (() => any)[] = []; public currentSnapshot: ɵStyleData = {}; constructor( - public element: any, public keyframes: {[key: string]: string | number}[], + public element: any, public keyframes: {[key: string]: string|number}[], public duration: number, public delay: number, public easing: string, public previousPlayers: any[]) { super(duration, delay); @@ -68,7 +72,9 @@ export class MockAnimationPlayer extends NoopAnimationPlayer { } /* @internal */ - onInit(fn: () => any) { this._onInitFns.push(fn); } + onInit(fn: () => any) { + this._onInitFns.push(fn); + } /* @internal */ init() { @@ -95,7 +101,9 @@ export class MockAnimationPlayer extends NoopAnimationPlayer { this.__started = true; } - hasStarted() { return this.__started; } + hasStarted() { + return this.__started; + } beforeDestroy() { const captures: ɵStyleData = {}; diff --git a/packages/animations/src/animation_metadata.ts b/packages/animations/src/animation_metadata.ts index 89492cf68845e..079744bf7391f 100755 --- a/packages/animations/src/animation_metadata.ts +++ b/packages/animations/src/animation_metadata.ts @@ -9,7 +9,9 @@ /** * Represents a set of CSS styles for use in an animation style. */ -export interface ɵStyleData { [key: string]: string|number; } +export interface ɵStyleData { + [key: string]: string|number; +} /** * Represents animation-step timing parameters for an animation step. @@ -67,10 +69,10 @@ export declare interface AnimationOptions { */ delay?: number|string; /** - * A set of developer-defined parameters that modify styling and timing - * when an animation action starts. An array of key-value pairs, where the provided value - * is used as a default. - */ + * A set of developer-defined parameters that modify styling and timing + * when an animation action starts. An array of key-value pairs, where the provided value + * is used as a default. + */ params?: {[name: string]: any}; } @@ -81,7 +83,9 @@ export declare interface AnimationOptions { * * @publicApi */ -export declare interface AnimateChildOptions extends AnimationOptions { duration?: number|string; } +export declare interface AnimateChildOptions extends AnimationOptions { + duration?: number|string; +} /** * @description Constants for the categories of parameters that can be defined for animations. @@ -171,7 +175,9 @@ export const AUTO_STYLE = '*'; * * @publicApi */ -export interface AnimationMetadata { type: AnimationMetadataType; } +export interface AnimationMetadata { + type: AnimationMetadataType; +} /** * Contains an animation trigger. Instantiated and returned by the @@ -181,8 +187,8 @@ export interface AnimationMetadata { type: AnimationMetadataType; } */ export interface AnimationTriggerMetadata extends AnimationMetadata { /** - * The trigger name, used to associate it with an element. Unique within the component. - */ + * The trigger name, used to associate it with an element. Unique within the component. + */ name: string; /** * An animation definition object, containing an array of state and transition declarations. @@ -654,8 +660,9 @@ export function trigger(name: string, definitions: AnimationMetadata[]): Animati * @publicApi */ export function animate( - timings: string | number, styles: AnimationStyleMetadata | AnimationKeyframesSequenceMetadata | - null = null): AnimationAnimateMetadata { + timings: string|number, + styles: AnimationStyleMetadata|AnimationKeyframesSequenceMetadata|null = + null): AnimationAnimateMetadata { return {type: AnimationMetadataType.Animate, styles, timings}; } @@ -693,7 +700,7 @@ export function animate( * @publicApi */ export function group( - steps: AnimationMetadata[], options: AnimationOptions | null = null): AnimationGroupMetadata { + steps: AnimationMetadata[], options: AnimationOptions|null = null): AnimationGroupMetadata { return {type: AnimationMetadataType.Group, steps, options}; } @@ -721,7 +728,8 @@ export function group( * @usageNotes * When you pass an array of steps to a * `transition()` call, the steps run sequentially by default. - * Compare this to the `{@link animations/group group()}` call, which runs animation steps in parallel. + * Compare this to the `{@link animations/group group()}` call, which runs animation steps in + *parallel. * * When a sequence is used within a `{@link animations/group group()}` or a `transition()` call, * execution continues to the next instruction only after each of the inner animation @@ -729,8 +737,8 @@ export function group( * * @publicApi **/ -export function sequence(steps: AnimationMetadata[], options: AnimationOptions | null = null): - AnimationSequenceMetadata { +export function sequence( + steps: AnimationMetadata[], options: AnimationOptions|null = null): AnimationSequenceMetadata { return {type: AnimationMetadataType.Sequence, steps, options}; } @@ -773,9 +781,8 @@ export function sequence(steps: AnimationMetadata[], options: AnimationOptions | * * @publicApi **/ -export function style( - tokens: '*' | {[key: string]: string | number} | - Array<'*'|{[key: string]: string | number}>): AnimationStyleMetadata { +export function style(tokens: '*'|{[key: string]: string | number}| + Array<'*'|{[key: string]: string | number}>): AnimationStyleMetadata { return {type: AnimationMetadataType.Style, styles: tokens, offset: null}; } @@ -1032,10 +1039,10 @@ export function keyframes(steps: AnimationStyleMetadata[]): AnimationKeyframesSe * @publicApi **/ export function transition( - stateChangeExpr: string | ((fromState: string, toState: string, element?: any, - params?: {[key: string]: any}) => boolean), - steps: AnimationMetadata | AnimationMetadata[], - options: AnimationOptions | null = null): AnimationTransitionMetadata { + stateChangeExpr: string| + ((fromState: string, toState: string, element?: any, params?: {[key: string]: any}) => boolean), + steps: AnimationMetadata|AnimationMetadata[], + options: AnimationOptions|null = null): AnimationTransitionMetadata { return {type: AnimationMetadataType.Transition, expr: stateChangeExpr, animation: steps, options}; } @@ -1085,8 +1092,8 @@ export function transition( * @publicApi */ export function animation( - steps: AnimationMetadata | AnimationMetadata[], - options: AnimationOptions | null = null): AnimationReferenceMetadata { + steps: AnimationMetadata|AnimationMetadata[], + options: AnimationOptions|null = null): AnimationReferenceMetadata { return {type: AnimationMetadataType.Reference, animation: steps, options}; } @@ -1109,7 +1116,7 @@ export function animation( * * @publicApi */ -export function animateChild(options: AnimateChildOptions | null = null): +export function animateChild(options: AnimateChildOptions|null = null): AnimationAnimateChildMetadata { return {type: AnimationMetadataType.AnimateChild, options}; } @@ -1126,7 +1133,7 @@ export function animateChild(options: AnimateChildOptions | null = null): */ export function useAnimation( animation: AnimationReferenceMetadata, - options: AnimationOptions | null = null): AnimationAnimateRefMetadata { + options: AnimationOptions|null = null): AnimationAnimateRefMetadata { return {type: AnimationMetadataType.AnimateRef, animation, options}; } @@ -1179,7 +1186,7 @@ export function useAnimation( * ### Usage Example * * The following example queries for inner elements and animates them - * individually using `animate()`. + * individually using `animate()`. * * ```typescript * @Component({ @@ -1218,8 +1225,8 @@ export function useAnimation( * @publicApi */ export function query( - selector: string, animation: AnimationMetadata | AnimationMetadata[], - options: AnimationQueryOptions | null = null): AnimationQueryMetadata { + selector: string, animation: AnimationMetadata|AnimationMetadata[], + options: AnimationQueryOptions|null = null): AnimationQueryMetadata { return {type: AnimationMetadataType.Query, selector, animation, options}; } @@ -1303,8 +1310,7 @@ export function query( * * @publicApi */ -export function stagger( - timings: string | number, - animation: AnimationMetadata | AnimationMetadata[]): AnimationStaggerMetadata { +export function stagger(timings: string|number, animation: AnimationMetadata|AnimationMetadata[]): + AnimationStaggerMetadata { return {type: AnimationMetadataType.Stagger, timings, animation}; } diff --git a/packages/animations/src/animations.ts b/packages/animations/src/animations.ts index 7f8acfadc9c2d..66482a0d79fc1 100644 --- a/packages/animations/src/animations.ts +++ b/packages/animations/src/animations.ts @@ -13,7 +13,7 @@ */ export {AnimationBuilder, AnimationFactory} from './animation_builder'; export {AnimationEvent} from './animation_event'; -export {AUTO_STYLE, AnimateChildOptions, AnimateTimings, AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationQueryMetadata, AnimationQueryOptions, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, animate, animateChild, animation, group, keyframes, query, sequence, stagger, state, style, transition, trigger, useAnimation, ɵStyleData} from './animation_metadata'; +export {animate, animateChild, AnimateChildOptions, AnimateTimings, animation, AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationQueryMetadata, AnimationQueryOptions, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, AUTO_STYLE, group, keyframes, query, sequence, stagger, state, style, transition, trigger, useAnimation, ɵStyleData} from './animation_metadata'; export {AnimationPlayer, NoopAnimationPlayer} from './players/animation_player'; export * from './private_export'; diff --git a/packages/animations/src/players/animation_group_player.ts b/packages/animations/src/players/animation_group_player.ts index c1f6a40c23aba..79f6611735411 100644 --- a/packages/animations/src/players/animation_group_player.ts +++ b/packages/animations/src/players/animation_group_player.ts @@ -69,9 +69,13 @@ export class AnimationGroupPlayer implements AnimationPlayer { } } - init(): void { this.players.forEach(player => player.init()); } + init(): void { + this.players.forEach(player => player.init()); + } - onStart(fn: () => void): void { this._onStartFns.push(fn); } + onStart(fn: () => void): void { + this._onStartFns.push(fn); + } private _onStart() { if (!this.hasStarted()) { @@ -81,11 +85,17 @@ export class AnimationGroupPlayer implements AnimationPlayer { } } - onDone(fn: () => void): void { this._onDoneFns.push(fn); } + onDone(fn: () => void): void { + this._onDoneFns.push(fn); + } - onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } + onDestroy(fn: () => void): void { + this._onDestroyFns.push(fn); + } - hasStarted() { return this._started; } + hasStarted() { + return this._started; + } play() { if (!this.parentPlayer) { @@ -95,16 +105,22 @@ export class AnimationGroupPlayer implements AnimationPlayer { this.players.forEach(player => player.play()); } - pause(): void { this.players.forEach(player => player.pause()); } + pause(): void { + this.players.forEach(player => player.pause()); + } - restart(): void { this.players.forEach(player => player.restart()); } + restart(): void { + this.players.forEach(player => player.restart()); + } finish(): void { this._onFinish(); this.players.forEach(player => player.finish()); } - destroy(): void { this._onDestroy(); } + destroy(): void { + this._onDestroy(); + } private _onDestroy() { if (!this._destroyed) { diff --git a/packages/animations/src/players/animation_player.ts b/packages/animations/src/players/animation_player.ts index 3a183db7c2012..6ec35d6b81c39 100644 --- a/packages/animations/src/players/animation_player.ts +++ b/packages/animations/src/players/animation_player.ts @@ -94,11 +94,13 @@ export interface AnimationPlayer { * Provides a callback to invoke before the animation is destroyed. */ beforeDestroy?: () => any; - /** @internal + /** + * @internal * Internal */ triggerCallback?: (phaseName: string) => void; - /** @internal + /** + * @internal * Internal */ disabled?: boolean; @@ -124,7 +126,9 @@ export class NoopAnimationPlayer implements AnimationPlayer { private _finished = false; public parentPlayer: AnimationPlayer|null = null; public readonly totalTime: number; - constructor(duration: number = 0, delay: number = 0) { this.totalTime = duration + delay; } + constructor(duration: number = 0, delay: number = 0) { + this.totalTime = duration + delay; + } private _onFinish() { if (!this._finished) { this._finished = true; @@ -132,10 +136,18 @@ export class NoopAnimationPlayer implements AnimationPlayer { this._onDoneFns = []; } } - onStart(fn: () => void): void { this._onStartFns.push(fn); } - onDone(fn: () => void): void { this._onDoneFns.push(fn); } - onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } - hasStarted(): boolean { return this._started; } + onStart(fn: () => void): void { + this._onStartFns.push(fn); + } + onDone(fn: () => void): void { + this._onDoneFns.push(fn); + } + onDestroy(fn: () => void): void { + this._onDestroyFns.push(fn); + } + hasStarted(): boolean { + return this._started; + } init(): void {} play(): void { if (!this.hasStarted()) { @@ -146,7 +158,9 @@ export class NoopAnimationPlayer implements AnimationPlayer { } /** @internal */ - triggerMicrotask() { scheduleMicroTask(() => this._onFinish()); } + triggerMicrotask() { + scheduleMicroTask(() => this._onFinish()); + } private _onStart() { this._onStartFns.forEach(fn => fn()); @@ -155,7 +169,9 @@ export class NoopAnimationPlayer implements AnimationPlayer { pause(): void {} restart(): void {} - finish(): void { this._onFinish(); } + finish(): void { + this._onFinish(); + } destroy(): void { if (!this._destroyed) { this._destroyed = true; @@ -169,7 +185,9 @@ export class NoopAnimationPlayer implements AnimationPlayer { } reset(): void {} setPosition(position: number): void {} - getPosition(): number { return 0; } + getPosition(): number { + return 0; + } /** @internal */ triggerCallback(phaseName: string): void { diff --git a/packages/animations/test/animation_player_spec.ts b/packages/animations/test/animation_player_spec.ts index 7ad7152d6018f..2bf205fcbb9cc 100644 --- a/packages/animations/test/animation_player_spec.ts +++ b/packages/animations/test/animation_player_spec.ts @@ -69,7 +69,9 @@ import {scheduleMicroTask} from '../src/util'; const log: string[] = []; const player = new NoopAnimationPlayer(); - player.onStart(() => { scheduleMicroTask(() => log.push('started')); }); + player.onStart(() => { + scheduleMicroTask(() => log.push('started')); + }); player.onDone(() => log.push('done')); expect(log).toEqual([]); diff --git a/packages/bazel/src/api-extractor/index.ts b/packages/bazel/src/api-extractor/index.ts index 71e46ca72c148..b89304cfe8998 100644 --- a/packages/bazel/src/api-extractor/index.ts +++ b/packages/bazel/src/api-extractor/index.ts @@ -38,7 +38,7 @@ export function runMain( // API extractor doesn't always support the version of TypeScript used in the repo // example: at the moment it is not compatable with 3.2 // to use the internal TypeScript we shall not create a program but rather pass a parsed tsConfig. - const parsedTsConfig = parsedConfig !.config as any; + const parsedTsConfig = parsedConfig!.config as any; const compilerOptions = parsedTsConfig.compilerOptions; for (const [key, values] of Object.entries(compilerOptions.paths)) { if (key === '*') { @@ -113,8 +113,8 @@ api-extractor: running with const dtsBundleOuts = dtsBundleOut.split(','); if (entryPoints.length !== entryPoints.length) { - throw new Error( - `Entry points count (${entryPoints.length}) does not match Bundle out count (${dtsBundleOuts.length})`); + throw new Error(`Entry points count (${entryPoints.length}) does not match Bundle out count (${ + dtsBundleOuts.length})`); } for (let i = 0; i < entryPoints.length; i++) { diff --git a/packages/bazel/src/builders/bazel.ts b/packages/bazel/src/builders/bazel.ts index e2dd5cb82f624..b737c9c969ed6 100644 --- a/packages/bazel/src/builders/bazel.ts +++ b/packages/bazel/src/builders/bazel.ts @@ -9,12 +9,12 @@ /// import {spawn} from 'child_process'; -import {copyFileSync, existsSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync} from 'fs'; +import {copyFileSync, existsSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync} from 'fs'; import {platform} from 'os'; import {dirname, join, normalize} from 'path'; -export type Executable = 'bazel' | 'ibazel'; -export type Command = 'build' | 'test' | 'run' | 'coverage' | 'query'; +export type Executable = 'bazel'|'ibazel'; +export type Command = 'build'|'test'|'run'|'coverage'|'query'; /** * Spawn the Bazel process. Trap SINGINT to make sure Bazel process is killed. diff --git a/packages/bazel/src/builders/index.ts b/packages/bazel/src/builders/index.ts index 99d6549f5f989..54ac7e90a485b 100644 --- a/packages/bazel/src/builders/index.ts +++ b/packages/bazel/src/builders/index.ts @@ -13,27 +13,29 @@ import {JsonObject} from '@angular-devkit/core'; import {checkInstallation, copyBazelFiles, deleteBazelFiles, getTemplateDir, runBazel} from './bazel'; import {Schema} from './schema'; -async function _bazelBuilder(options: JsonObject & Schema, context: BuilderContext, ): - Promise { - const {logger, workspaceRoot} = context; - const {bazelCommand, leaveBazelFilesOnDisk, targetLabel, watch} = options; - const executable = watch ? 'ibazel' : 'bazel'; - const binary = checkInstallation(executable, workspaceRoot); - const templateDir = getTemplateDir(workspaceRoot); - const bazelFiles = copyBazelFiles(workspaceRoot, templateDir); +async function _bazelBuilder( + options: JsonObject&Schema, + context: BuilderContext, + ): Promise { + const {logger, workspaceRoot} = context; + const {bazelCommand, leaveBazelFilesOnDisk, targetLabel, watch} = options; + const executable = watch ? 'ibazel' : 'bazel'; + const binary = checkInstallation(executable, workspaceRoot); + const templateDir = getTemplateDir(workspaceRoot); + const bazelFiles = copyBazelFiles(workspaceRoot, templateDir); - try { - const flags: string[] = []; - await runBazel(workspaceRoot, binary, bazelCommand, targetLabel, flags); - return {success: true}; - } catch (err) { - logger.error(err.message); - return {success: false}; - } finally { - if (!leaveBazelFilesOnDisk) { - deleteBazelFiles(bazelFiles); // this will never throw - } - } + try { + const flags: string[] = []; + await runBazel(workspaceRoot, binary, bazelCommand, targetLabel, flags); + return {success: true}; + } catch (err) { + logger.error(err.message); + return {success: false}; + } finally { + if (!leaveBazelFilesOnDisk) { + deleteBazelFiles(bazelFiles); // this will never throw } + } +} export default createBuilder(_bazelBuilder); diff --git a/packages/bazel/src/ng_package/packager.ts b/packages/bazel/src/ng_package/packager.ts index c4f17fb77f22c..10d269e0c5360 100644 --- a/packages/bazel/src/ng_package/packager.ts +++ b/packages/bazel/src/ng_package/packager.ts @@ -22,7 +22,9 @@ function main(args: string[]): number { const paramFilePath = args[0]; // Bazel params may be surrounded with quotes - function unquoteParameter(s: string) { return s.replace(/^'(.*)'$/, '$1'); } + function unquoteParameter(s: string) { + return s.replace(/^'(.*)'$/, '$1'); + } // Parameters are specified in the file one per line. const params = fs.readFileSync(paramFilePath, 'utf-8').split('\n').map(unquoteParameter); @@ -109,7 +111,7 @@ function main(args: string[]): number { * @param inputPath Path to the file in the input tree. * @param fileContent Content of the file. */ - function writeFileFromInputPath(inputPath: string, fileContent: string | Buffer) { + function writeFileFromInputPath(inputPath: string, fileContent: string|Buffer) { // We want the relative path from the given file to its ancestor "root" directory. // This root depends on whether the file lives in the source tree (srcDir) as a basic file // input to ng_package, the bin output tree (binDir) as the output of another rule, or @@ -164,9 +166,15 @@ function main(args: string[]): number { esm2015.forEach(file => writeEsmFile(file, '', 'esm2015')); esm5.forEach(file => writeEsmFile(file, '.esm5', 'esm5')); - bundles.forEach(bundle => { copyFile(bundle, out, 'bundles'); }); - fesm2015.forEach(file => { copyFile(file, out, 'fesm2015'); }); - fesm5.forEach(file => { copyFile(file, out, 'fesm5'); }); + bundles.forEach(bundle => { + copyFile(bundle, out, 'bundles'); + }); + fesm2015.forEach(file => { + copyFile(file, out, 'fesm2015'); + }); + fesm5.forEach(file => { + copyFile(file, out, 'fesm5'); + }); // Copy all type definitions into the package. This is necessary so that developers can use // the package with type definitions. @@ -419,14 +427,16 @@ export * from '${srcDirRelative(inputPath, typingsFile.replace(/\.d\.tsx?$/, '') * Normalizes the specified path by replacing backslash separators with Posix * forward slash separators. */ - function normalizeSeparators(path: string): string { return path.replace(/\\/g, '/'); } + function normalizeSeparators(path: string): string { + return path.replace(/\\/g, '/'); + } /** - * Rewires metadata to point to the flattened dts file. - * - * @param metadataPath the metadata file path - * @param typingsPath the typings bundle entrypoint - */ + * Rewires metadata to point to the flattened dts file. + * + * @param metadataPath the metadata file path + * @param typingsPath the typings bundle entrypoint + */ function rewireMetadata(metadataPath: string, typingsPath: string): string { const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf-8')); @@ -470,7 +480,7 @@ export function newArray(size: number, value: T): T[]; export function newArray(size: number, value?: T): T[] { const list: T[] = []; for (let i = 0; i < size; i++) { - list.push(value !); + list.push(value!); } return list; } diff --git a/packages/bazel/src/ngc-wrapped/index.ts b/packages/bazel/src/ngc-wrapped/index.ts index e78b1064548f4..a80c00cd846db 100644 --- a/packages/bazel/src/ngc-wrapped/index.ts +++ b/packages/bazel/src/ngc-wrapped/index.ts @@ -7,7 +7,7 @@ */ import * as ng from '@angular/compiler-cli'; -import {BazelOptions, CachedFileLoader, CompilerHost, FileCache, FileLoader, UncachedFileLoader, constructManifest, debug, parseTsconfig, resolveNormalizedPath, runAsWorker, runWorkerLoop} from '@bazel/typescript'; +import {BazelOptions, CachedFileLoader, CompilerHost, constructManifest, debug, FileCache, FileLoader, parseTsconfig, resolveNormalizedPath, runAsWorker, runWorkerLoop, UncachedFileLoader} from '@bazel/typescript'; import * as fs from 'fs'; import * as path from 'path'; import * as tsickle from 'tsickle'; @@ -123,7 +123,12 @@ export function runOneBuild(args: string[], inputs?: {[path: string]: string}): const {diagnostics} = compile({ allDepsCompiledWithBazel: ALL_DEPS_COMPILED_WITH_BAZEL, useManifestPathsAsModuleName: _useManifestPathsAsModuleName, - expectedOuts: expectedOut, compilerOpts, tsHost, bazelOpts, files, inputs, + expectedOuts: expectedOut, + compilerOpts, + tsHost, + bazelOpts, + files, + inputs, }); if (diagnostics.length) { console.error(ng.formatDiagnostics(diagnostics)); @@ -142,16 +147,24 @@ export function relativeToRootDirs(filePath: string, rootDirs: string[]): string return filePath; } -export function compile({allDepsCompiledWithBazel = true, useManifestPathsAsModuleName, - compilerOpts, tsHost, bazelOpts, files, inputs, expectedOuts, - gatherDiagnostics, bazelHost}: { +export function compile({ + allDepsCompiledWithBazel = true, + useManifestPathsAsModuleName, + compilerOpts, + tsHost, + bazelOpts, + files, + inputs, + expectedOuts, + gatherDiagnostics, + bazelHost +}: { allDepsCompiledWithBazel?: boolean, - useManifestPathsAsModuleName?: boolean, - compilerOpts: ng.CompilerOptions, - tsHost: ts.CompilerHost, inputs?: {[path: string]: string}, - bazelOpts: BazelOptions, - files: string[], - expectedOuts: string[], + useManifestPathsAsModuleName?: boolean, compilerOpts: ng.CompilerOptions, tsHost: ts.CompilerHost, + inputs?: {[path: string]: string}, + bazelOpts: BazelOptions, + files: string[], + expectedOuts: string[], gatherDiagnostics?: (program: ng.Program) => ng.Diagnostics, bazelHost?: CompilerHost, }): {diagnostics: ng.Diagnostics, program: ng.Program} { @@ -362,7 +375,7 @@ export function compile({allDepsCompiledWithBazel = true, useManifestPathsAsModu if ((compilerOpts.module === ts.ModuleKind.UMD || compilerOpts.module === ts.ModuleKind.AMD) && ngHost.amdModuleName) { - return ngHost.amdModuleName({ fileName: importedFilePath } as ts.SourceFile); + return ngHost.amdModuleName({fileName: importedFilePath} as ts.SourceFile); } // If no AMD module name has been set for the source file by the `@bazel/typescript` compiler @@ -434,8 +447,10 @@ export function compile({allDepsCompiledWithBazel = true, useManifestPathsAsModu const {diagnostics, emitResult, program} = ng.performCompilation({ rootNames: files, options: compilerOpts, - host: ngHost, emitCallback, - mergeEmitResultsCallback: tsickle.mergeEmitResults, gatherDiagnostics + host: ngHost, + emitCallback, + mergeEmitResultsCallback: tsickle.mergeEmitResults, + gatherDiagnostics }); const tsickleEmitResult = emitResult as tsickle.EmitResult; let externs = '/** @externs */\n'; @@ -512,9 +527,9 @@ function convertToForwardSlashPath(filePath: string): string { function gatherDiagnosticsForInputsOnly( options: ng.CompilerOptions, bazelOpts: BazelOptions, - ngProgram: ng.Program): (ng.Diagnostic | ts.Diagnostic)[] { + ngProgram: ng.Program): (ng.Diagnostic|ts.Diagnostic)[] { const tsProgram = ngProgram.getTsProgram(); - const diagnostics: (ng.Diagnostic | ts.Diagnostic)[] = []; + const diagnostics: (ng.Diagnostic|ts.Diagnostic)[] = []; // These checks mirror ts.getPreEmitDiagnostics, with the important // exception of avoiding b/30708240, which is that if you call // program.getDeclarationDiagnostics() it somehow corrupts the emit. diff --git a/packages/bazel/src/schematics/ng-add/index.ts b/packages/bazel/src/schematics/ng-add/index.ts index 5b72330363cfd..8eb6809b9dd80 100644 --- a/packages/bazel/src/schematics/ng-add/index.ts +++ b/packages/bazel/src/schematics/ng-add/index.ts @@ -9,10 +9,10 @@ */ import {JsonAstObject, parseJsonAst} from '@angular-devkit/core'; -import {Rule, SchematicContext, SchematicsException, Tree, apply, applyTemplates, chain, mergeWith, url} from '@angular-devkit/schematics'; +import {apply, applyTemplates, chain, mergeWith, Rule, SchematicContext, SchematicsException, Tree, url} from '@angular-devkit/schematics'; import {NodePackageInstallTask} from '@angular-devkit/schematics/tasks'; import {getWorkspace, getWorkspacePath} from '@schematics/angular/utility/config'; -import {NodeDependencyType, addPackageJsonDependency, getPackageJsonDependency, removePackageJsonDependency} from '@schematics/angular/utility/dependencies'; +import {addPackageJsonDependency, getPackageJsonDependency, NodeDependencyType, removePackageJsonDependency} from '@schematics/angular/utility/dependencies'; import {findPropertyInAstObject, insertPropertyInAstObjectInOrder} from '@schematics/angular/utility/json-utils'; import {validateProjectName} from '@schematics/angular/utility/validation'; @@ -137,7 +137,7 @@ function updateGitignore() { */ function updateAngularJsonToUseBazelBuilder(options: Schema): Rule { return (host: Tree) => { - const name = options.name !; + const name = options.name!; const workspacePath = getWorkspacePath(host); if (!workspacePath) { throw new Error('Could not find angular.json'); @@ -235,7 +235,8 @@ function backupAngularJson(): Rule { return; } host.create( - `${workspacePath}.bak`, '// This is a backup file of the original angular.json. ' + + `${workspacePath}.bak`, + '// This is a backup file of the original angular.json. ' + 'This file is needed in case you want to revert to the workflow without Bazel.\n\n' + host.read(workspacePath)); }; diff --git a/packages/bazel/src/schematics/ng-add/index_spec.ts b/packages/bazel/src/schematics/ng-add/index_spec.ts index 133584ac9e109..7dc0f7ca58fdf 100644 --- a/packages/bazel/src/schematics/ng-add/index_spec.ts +++ b/packages/bazel/src/schematics/ng-add/index_spec.ts @@ -10,7 +10,6 @@ import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; describe('ng-add schematic', () => { - const defaultOptions = {name: 'demo'}; let host: UnitTestTree; let schematicRunner: SchematicTestRunner; @@ -61,7 +60,7 @@ describe('ng-add schematic', () => { new SchematicTestRunner('@angular/bazel', require.resolve('../collection.json')); }); - it('throws if package.json is not found', async() => { + it('throws if package.json is not found', async () => { expect(host.files).toContain('/package.json'); host.delete('/package.json'); @@ -76,7 +75,7 @@ describe('ng-add schematic', () => { expect(message).toBe('Could not read package.json.'); }); - it('throws if angular.json is not found', async() => { + it('throws if angular.json is not found', async () => { expect(host.files).toContain('/angular.json'); host.delete('/angular.json'); @@ -91,7 +90,7 @@ describe('ng-add schematic', () => { expect(message).toBe('Could not find angular.json'); }); - it('should add @angular/bazel to package.json dependencies', async() => { + it('should add @angular/bazel to package.json dependencies', async () => { host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const {files} = host; expect(files).toContain('/package.json'); @@ -106,7 +105,7 @@ describe('ng-add schematic', () => { expect(Object.keys(json.devDependencies)).toContain(bazel); }); - it('should add @bazel/* dev dependencies', async() => { + it('should add @bazel/* dev dependencies', async () => { host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const content = host.readContent('/package.json'); const json = JSON.parse(content); @@ -118,7 +117,7 @@ describe('ng-add schematic', () => { expect(devDeps).toContain('@bazel/typescript'); }); - it('should replace an existing dev dependency', async() => { + it('should replace an existing dev dependency', async () => { expect(host.files).toContain('/package.json'); const packageJson = JSON.parse(host.readContent('/package.json')); packageJson.devDependencies['@angular/bazel'] = '4.2.42'; @@ -126,12 +125,12 @@ describe('ng-add schematic', () => { host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const content = host.readContent('/package.json'); // It is possible that a dep gets added twice if the package already exists. - expect(content.match(/@angular\/bazel/g) !.length).toEqual(1); + expect(content.match(/@angular\/bazel/g)!.length).toEqual(1); const json = JSON.parse(content); expect(json.devDependencies['@angular/bazel']).toBe('1.2.3'); }); - it('should remove an existing dependency', async() => { + it('should remove an existing dependency', async () => { expect(host.files).toContain('/package.json'); const packageJson = JSON.parse(host.readContent('/package.json')); packageJson.dependencies['@angular/bazel'] = '4.2.42'; @@ -144,7 +143,7 @@ describe('ng-add schematic', () => { expect(json.devDependencies['@angular/bazel']).toBe('1.2.3'); }); - it('should remove unneeded dependencies', async() => { + it('should remove unneeded dependencies', async () => { const packageJson = JSON.parse(host.readContent('/package.json')); packageJson.devDependencies['@angular-devkit/build-angular'] = '1.2.3'; host.overwrite('/package.json', JSON.stringify(packageJson)); @@ -154,7 +153,7 @@ describe('ng-add schematic', () => { expect(json.devDependencies['angular-devkit/build-angular']).toBeUndefined(); }); - it('should append to scripts.postinstall if it already exists', async() => { + it('should append to scripts.postinstall if it already exists', async () => { const packageJson = JSON.parse(host.readContent('/package.json')); packageJson['scripts'] = { postinstall: 'angular rocks', @@ -167,7 +166,7 @@ describe('ng-add schematic', () => { .toBe('angular rocks; ngcc --properties es2015 browser module main'); }); - it('should update ngcc in scripts.postinstall if it already exists', async() => { + it('should update ngcc in scripts.postinstall if it already exists', async () => { const packageJson = JSON.parse(host.readContent('/package.json')); packageJson['scripts'] = { postinstall: @@ -180,14 +179,14 @@ describe('ng-add schematic', () => { expect(json.scripts['postinstall']).toBe('ngcc --properties es2015 browser module main'); }); - it('should not create Bazel workspace file', async() => { + it('should not create Bazel workspace file', async () => { host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const {files} = host; expect(files).not.toContain('/WORKSPACE'); expect(files).not.toContain('/BUILD.bazel'); }); - it('should produce main.dev.ts and main.prod.ts for AOT', async() => { + it('should produce main.dev.ts and main.prod.ts for AOT', async () => { host.create('/src/main.ts', 'generated by CLI'); host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const {files} = host; @@ -199,7 +198,7 @@ describe('ng-add schematic', () => { expect(files).toContain('/src/main.ts'); }); - it('should not overwrite index.html with script tags', async() => { + it('should not overwrite index.html with script tags', async () => { host.create('/src/index.html', 'Hello World'); host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const {files} = host; @@ -209,14 +208,14 @@ describe('ng-add schematic', () => { expect(content).not.toMatch(''); }); - it('should generate main.dev.ts and main.prod.ts', async() => { + it('should generate main.dev.ts and main.prod.ts', async () => { host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const {files} = host; expect(files).toContain('/src/main.dev.ts'); expect(files).toContain('/src/main.prod.ts'); }); - it('should overwrite .gitignore for bazel-out directory', async() => { + it('should overwrite .gitignore for bazel-out directory', async () => { host.create('.gitignore', '\n# compiled output\n'); host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const {files} = host; @@ -225,7 +224,7 @@ describe('ng-add schematic', () => { expect(content).toMatch('\n# compiled output\n/bazel-out\n'); }); - it('should create a backup for original angular.json', async() => { + it('should create a backup for original angular.json', async () => { expect(host.files).toContain('/angular.json'); const original = host.readContent('/angular.json'); host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); @@ -235,7 +234,7 @@ describe('ng-add schematic', () => { expect(content).toMatch(original); }); - it('should update angular.json to use Bazel builder', async() => { + it('should update angular.json to use Bazel builder', async () => { host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); const {files} = host; expect(files).toContain('/angular.json'); @@ -256,7 +255,7 @@ describe('ng-add schematic', () => { expect(lint.builder).toBe('@angular-devkit/build-angular:tslint'); }); - it('should get defaultProject if name is not provided', async() => { + it('should get defaultProject if name is not provided', async () => { const options = {}; host = await schematicRunner.runSchematicAsync('ng-add', options, host).toPromise(); const content = host.readContent('/angular.json'); @@ -281,7 +280,7 @@ describe('ng-add schematic', () => { ['~7.0.1', false], ]; for (const [version, upgrade] of cases) { - it(`should ${upgrade ? '' : 'not '}upgrade v${version}')`, async() => { + it(`should ${upgrade ? '' : 'not '}upgrade v${version}')`, async () => { host.overwrite('package.json', JSON.stringify({ name: 'demo', dependencies: { @@ -305,7 +304,7 @@ describe('ng-add schematic', () => { } }); - it('should add a postinstall step to package.json', async() => { + it('should add a postinstall step to package.json', async () => { host = await schematicRunner.runSchematicAsync('ng-add', defaultOptions, host).toPromise(); expect(host.files).toContain('/package.json'); const content = host.readContent('/package.json'); @@ -313,7 +312,7 @@ describe('ng-add schematic', () => { expect(json.scripts.postinstall).toBe('ngcc --properties es2015 browser module main'); }); - it('should work when run on a minimal project (without test and e2e targets)', async() => { + it('should work when run on a minimal project (without test and e2e targets)', async () => { host.overwrite('angular.json', JSON.stringify({ projects: { 'demo': { @@ -338,5 +337,4 @@ describe('ng-add schematic', () => { expect(error).toBeNull(); }); - }); diff --git a/packages/bazel/src/schematics/ng-new/index.ts b/packages/bazel/src/schematics/ng-new/index.ts index 94a3826399ca1..51e52e5051f82 100644 --- a/packages/bazel/src/schematics/ng-new/index.ts +++ b/packages/bazel/src/schematics/ng-new/index.ts @@ -8,8 +8,9 @@ * @fileoverview Schematics for ng-new project that builds with Bazel. */ -import {Rule, Tree, chain, externalSchematic, schematic} from '@angular-devkit/schematics'; +import {chain, externalSchematic, Rule, schematic, Tree} from '@angular-devkit/schematics'; import {validateProjectName} from '@schematics/angular/utility/validation'; + import {Schema} from './schema'; export default function(options: Schema): Rule { diff --git a/packages/bazel/src/schematics/ng-new/index_spec.ts b/packages/bazel/src/schematics/ng-new/index_spec.ts index 3d1fef16bf787..1da740b925f36 100644 --- a/packages/bazel/src/schematics/ng-new/index_spec.ts +++ b/packages/bazel/src/schematics/ng-new/index_spec.ts @@ -9,14 +9,16 @@ import {SchematicTestRunner} from '@angular-devkit/schematics/testing'; describe('ng-new schematic', () => { - const schematicRunner = - new SchematicTestRunner('@angular/bazel', require.resolve('../collection.json'), ); + const schematicRunner = new SchematicTestRunner( + '@angular/bazel', + require.resolve('../collection.json'), + ); const defaultOptions = { name: 'demo', version: '7.0.0', }; - it('should call external @schematics/angular', async() => { + it('should call external @schematics/angular', async () => { const options = {...defaultOptions}; const host = await schematicRunner.runSchematicAsync('ng-new', options).toPromise(); const {files} = host; @@ -25,7 +27,7 @@ describe('ng-new schematic', () => { expect(files).toContain('/demo/package.json'); }); - it('should call ng-add to generate additional files needed by Bazel', async() => { + it('should call ng-add to generate additional files needed by Bazel', async () => { const options = {...defaultOptions}; const host = await schematicRunner.runSchematicAsync('ng-new', options).toPromise(); const {files} = host; diff --git a/packages/bazel/src/schematics/ng-new/schema.d.ts b/packages/bazel/src/schematics/ng-new/schema.d.ts index 9cf013db9e82f..913cf2bc26622 100644 --- a/packages/bazel/src/schematics/ng-new/schema.d.ts +++ b/packages/bazel/src/schematics/ng-new/schema.d.ts @@ -86,8 +86,8 @@ export interface Schema { viewEncapsulation?: ViewEncapsulation; } /** -* Initial git repository commit information. -*/ + * Initial git repository commit information. + */ export declare type CommitUnion = boolean | CommitObject; export interface CommitObject { email: string; @@ -95,16 +95,16 @@ export interface CommitObject { name: string; } /** -* The file extension or preprocessor to use for style files. -*/ + * The file extension or preprocessor to use for style files. + */ export declare enum Style { Css = 'css', Sass = 'sass', Scss = 'scss', } /** -* The view encapsulation strategy to use in the initial project. -*/ + * The view encapsulation strategy to use in the initial project. + */ export declare enum ViewEncapsulation { Emulated = 'Emulated', Native = 'Native', diff --git a/packages/bazel/src/schematics/utility/json-utils.ts b/packages/bazel/src/schematics/utility/json-utils.ts index 0c42716dbdba1..449ea6d62a573 100644 --- a/packages/bazel/src/schematics/utility/json-utils.ts +++ b/packages/bazel/src/schematics/utility/json-utils.ts @@ -42,7 +42,7 @@ export function removeKeyValueInAstObject( let length = end - start; const match = content.slice(end).match(/^[,\s]+/); if (match) { - length += match.pop() !.length; + length += match.pop()!.length; } recorder.remove(start, length); if (i === node.properties.length - 1) { // last property @@ -60,6 +60,6 @@ export function removeKeyValueInAstObject( /** * Returns true if the specified 'node' is a JsonAstObject, false otherwise. */ -export function isJsonAstObject(node: JsonAstNode | null): node is JsonAstObject { +export function isJsonAstObject(node: JsonAstNode|null): node is JsonAstObject { return !!node && node.kind === 'object'; } diff --git a/packages/bazel/src/schematics/utility/json-utils_spec.ts b/packages/bazel/src/schematics/utility/json-utils_spec.ts index 0f7e2d24aa902..4341d083459ed 100644 --- a/packages/bazel/src/schematics/utility/json-utils_spec.ts +++ b/packages/bazel/src/schematics/utility/json-utils_spec.ts @@ -12,9 +12,10 @@ import {UnitTestTree} from '@angular-devkit/schematics/testing'; import {isJsonAstObject, removeKeyValueInAstObject, replacePropertyInAstObject} from './json-utils'; describe('JsonUtils', () => { - let tree: UnitTestTree; - beforeEach(() => { tree = new UnitTestTree(new HostTree()); }); + beforeEach(() => { + tree = new UnitTestTree(new HostTree()); + }); describe('replacePropertyInAstObject', () => { it('should replace property', () => { diff --git a/packages/bazel/test/ng_package/common_package.spec.ts b/packages/bazel/test/ng_package/common_package.spec.ts index 5966ae1f248a0..cfe1144e234e4 100644 --- a/packages/bazel/test/ng_package/common_package.spec.ts +++ b/packages/bazel/test/ng_package/common_package.spec.ts @@ -30,8 +30,9 @@ describe('@angular/common ng_package', () => { }); // regression test for https://github.com/angular/angular/issues/23217 // Note, we don't have an e2e test that covers this - it('doesn\'t pass require in a way that breaks webpack static analysis', - () => { expect(shx.cat('locales/fr.js')).not.toContain('factory(require, exports)'); }); + it('doesn\'t pass require in a way that breaks webpack static analysis', () => { + expect(shx.cat('locales/fr.js')).not.toContain('factory(require, exports)'); + }); }); it('should have right bundle files', () => { @@ -59,8 +60,9 @@ describe('@angular/common ng_package', () => { ]); }); - it('should reference core using global symbol in umd', - () => { expect(shx.cat('bundles/common.umd.js')).toContain('global.ng.core'); }); + it('should reference core using global symbol in umd', () => { + expect(shx.cat('bundles/common.umd.js')).toContain('global.ng.core'); + }); it('should have right fesm files', () => { const expected = [ diff --git a/packages/bazel/test/ng_package/core_package.spec.ts b/packages/bazel/test/ng_package/core_package.spec.ts index bbfe3594acf9b..0f6bda62c5235 100644 --- a/packages/bazel/test/ng_package/core_package.spec.ts +++ b/packages/bazel/test/ng_package/core_package.spec.ts @@ -41,8 +41,9 @@ describe('@angular/core ng_package', () => { describe('package.json', () => { const packageJson = 'package.json'; - it('should have a package.json file', - () => { expect(shx.grep('"name":', packageJson)).toContain(`@angular/core`); }); + it('should have a package.json file', () => { + expect(shx.grep('"name":', packageJson)).toContain(`@angular/core`); + }); it('should contain correct version number with the PLACEHOLDER string replaced', () => { expect(shx.grep('"version":', packageJson)).toMatch(/\d+\.\d+\.\d+(?!-PLACEHOLDER)/); @@ -66,16 +67,20 @@ describe('@angular/core ng_package', () => { describe('typescript support', () => { if (ivyEnabled) { - it('should have an index d.ts file', - () => { expect(shx.cat('core.d.ts')).toContain(`export *`); }); + it('should have an index d.ts file', () => { + expect(shx.cat('core.d.ts')).toContain(`export *`); + }); - it('should not have amd module names', - () => { expect(shx.cat('public_api.d.ts')).not.toContain(' { + expect(shx.cat('public_api.d.ts')).not.toContain(' { expect(shx.cat('core.d.ts')).toContain('export declare'); }); - it('should have an r3_symbols d.ts file', - () => { expect(shx.cat('src/r3_symbols.d.ts')).toContain('export declare'); }); + it('should have an index d.ts file', () => { + expect(shx.cat('core.d.ts')).toContain('export declare'); + }); + it('should have an r3_symbols d.ts file', () => { + expect(shx.cat('src/r3_symbols.d.ts')).toContain('export declare'); + }); } }); @@ -87,15 +92,18 @@ describe('@angular/core ng_package', () => { obsoleteInIvy('metadata files are no longer needed or produced in Ivy') .describe('angular metadata', () => { - it('should have metadata.json files', - () => { expect(shx.cat('core.metadata.json')).toContain(`"__symbolic":"module"`); }); - it('should not have self-references in metadata.json', - () => { expect(shx.cat('core.metadata.json')).not.toContain(`"from":"./core"`); }); + it('should have metadata.json files', () => { + expect(shx.cat('core.metadata.json')).toContain(`"__symbolic":"module"`); + }); + it('should not have self-references in metadata.json', () => { + expect(shx.cat('core.metadata.json')).not.toContain(`"from":"./core"`); + }); }); describe('fesm2015', () => { - it('should have a fesm15 file in the /fesm2015 directory', - () => { expect(shx.cat('fesm2015/core.js')).toContain(`export {`); }); + it('should have a fesm15 file in the /fesm2015 directory', () => { + expect(shx.cat('fesm2015/core.js')).toContain(`export {`); + }); it('should have a source map', () => { expect(shx.cat('fesm2015/core.js.map')) @@ -114,8 +122,9 @@ describe('@angular/core ng_package', () => { }); describe('fesm5', () => { - it('should have a fesm5 file in the /fesm5 directory', - () => { expect(shx.cat('fesm5/core.js')).toContain(`export {`); }); + it('should have a fesm5 file in the /fesm5 directory', () => { + expect(shx.cat('fesm5/core.js')).toContain(`export {`); + }); it('should have a source map', () => { expect(shx.cat('fesm5/core.js.map')).toContain(`{"version":3,"file":"core.js","sources":`); @@ -131,12 +140,14 @@ describe('@angular/core ng_package', () => { expect(shx.cat('fesm5/core.js')).toContain('.ɵprov = '); }); } else { - it('should have decorators', - () => { expect(shx.cat('fesm5/core.js')).toContain('__decorate'); }); + it('should have decorators', () => { + expect(shx.cat('fesm5/core.js')).toContain('__decorate'); + }); // See: https://github.com/angular/angular/pull/32069 - it('should retain access to const', - () => { expect(shx.cat('fesm5/core.js')).toContain('!ivyEnabled'); }); + it('should retain access to const', () => { + expect(shx.cat('fesm5/core.js')).toContain('!ivyEnabled'); + }); } it('should load tslib from external bundle', () => { @@ -145,8 +156,9 @@ describe('@angular/core ng_package', () => { }); obsoleteInIvy('we no longer need to export private symbols') - .it('should have been built from the generated bundle index', - () => { expect(shx.cat('fesm5/core.js')).toMatch('export {.*makeParamDecorator'); }); + .it('should have been built from the generated bundle index', () => { + expect(shx.cat('fesm5/core.js')).toMatch('export {.*makeParamDecorator'); + }); }); describe('esm2015', () => { @@ -160,25 +172,31 @@ describe('@angular/core ng_package', () => { }); describe('esm5', () => { - it('should not contain any *.ngfactory.js files', - () => { expect(shx.find('esm5').filter(f => f.endsWith('.ngfactory.js'))).toEqual([]); }); + it('should not contain any *.ngfactory.js files', () => { + expect(shx.find('esm5').filter(f => f.endsWith('.ngfactory.js'))).toEqual([]); + }); - it('should not contain any *.ngsummary.js files', - () => { expect(shx.find('esm5').filter(f => f.endsWith('.ngsummary.js'))).toEqual([]); }); + it('should not contain any *.ngsummary.js files', () => { + expect(shx.find('esm5').filter(f => f.endsWith('.ngsummary.js'))).toEqual([]); + }); }); describe('umd', () => { - it('should have a umd file in the /bundles directory', - () => { expect(shx.ls('bundles/core.umd.js').length).toBe(1, 'File not found'); }); + it('should have a umd file in the /bundles directory', () => { + expect(shx.ls('bundles/core.umd.js').length).toBe(1, 'File not found'); + }); - it('should have a source map next to the umd file', - () => { expect(shx.ls('bundles/core.umd.js.map').length).toBe(1, 'File not found'); }); + it('should have a source map next to the umd file', () => { + expect(shx.ls('bundles/core.umd.js.map').length).toBe(1, 'File not found'); + }); - it('should have a minified umd file in the /bundles directory', - () => { expect(shx.ls('bundles/core.umd.min.js').length).toBe(1, 'File not found'); }); + it('should have a minified umd file in the /bundles directory', () => { + expect(shx.ls('bundles/core.umd.min.js').length).toBe(1, 'File not found'); + }); - it('should have a source map next to the minified umd file', - () => { expect(shx.ls('bundles/core.umd.min.js.map').length).toBe(1, 'File not found'); }); + it('should have a source map next to the minified umd file', () => { + expect(shx.ls('bundles/core.umd.min.js.map').length).toBe(1, 'File not found'); + }); it('should have the version info in the header', () => { expect(shx.cat('bundles/core.umd.js')) @@ -189,22 +207,25 @@ describe('@angular/core ng_package', () => { expect(shx.cat('bundles/core.umd.js')).toContain('function __extends'); expect(shx.cat('bundles/core.umd.js')).not.toContain('undefined.__extends'); }); - it('should have an AMD name', - () => { expect(shx.cat('bundles/core.umd.js')).toContain('define(\'@angular/core\''); }); - it('should define ng global symbols', - () => { expect(shx.cat('bundles/core.umd.js')).toContain('global.ng.core = {}'); }); + it('should have an AMD name', () => { + expect(shx.cat('bundles/core.umd.js')).toContain('define(\'@angular/core\''); + }); + it('should define ng global symbols', () => { + expect(shx.cat('bundles/core.umd.js')).toContain('global.ng.core = {}'); + }); }); }); describe('secondary entry-point', () => { describe('package.json', () => { - const packageJson = p `testing/package.json`; + const packageJson = p`testing/package.json`; - it('should have a package.json file', - () => { expect(shx.grep('"name":', packageJson)).toContain(`@angular/core/testing`); }); + it('should have a package.json file', () => { + expect(shx.grep('"name":', packageJson)).toContain(`@angular/core/testing`); + }); it('should have its module resolution mappings defined in the nested package.json', () => { - const packageJson = p `testing/package.json`; + const packageJson = p`testing/package.json`; expect(shx.grep('"main":', packageJson)).toContain(`../bundles/core-testing.umd.js`); expect(shx.grep('"module":', packageJson)).toContain(`../fesm5/testing.js`); expect(shx.grep('"es2015":', packageJson)).toContain(`../fesm2015/testing.js`); @@ -216,13 +237,15 @@ describe('@angular/core ng_package', () => { describe('typings', () => { if (ivyEnabled) { - const typingsFile = p `testing/index.d.ts`; - it('should have a typings file', - () => { expect(shx.cat(typingsFile)).toContain(`export * from './public_api';`); }); + const typingsFile = p`testing/index.d.ts`; + it('should have a typings file', () => { + expect(shx.cat(typingsFile)).toContain(`export * from './public_api';`); + }); } else { - const typingsFile = p `testing/testing.d.ts`; - it('should have a typings file', - () => { expect(shx.cat(typingsFile)).toContain('export declare'); }); + const typingsFile = p`testing/testing.d.ts`; + it('should have a typings file', () => { + expect(shx.cat(typingsFile)).toContain('export declare'); + }); } obsoleteInIvy( @@ -242,8 +265,9 @@ describe('@angular/core ng_package', () => { }); describe('fesm2015', () => { - it('should have a fesm15 file in the /fesm2015 directory', - () => { expect(shx.cat('fesm2015/testing.js')).toContain(`export {`); }); + it('should have a fesm15 file in the /fesm2015 directory', () => { + expect(shx.cat('fesm2015/testing.js')).toContain(`export {`); + }); it('should have a source map', () => { expect(shx.cat('fesm2015/testing.js.map')) @@ -257,8 +281,9 @@ describe('@angular/core ng_package', () => { }); describe('fesm5', () => { - it('should have a fesm5 file in the /fesm5 directory', - () => { expect(shx.cat('fesm5/testing.js')).toContain(`export {`); }); + it('should have a fesm5 file in the /fesm5 directory', () => { + expect(shx.cat('fesm5/testing.js')).toContain(`export {`); + }); it('should have a source map', () => { expect(shx.cat('fesm5/testing.js.map')) @@ -267,8 +292,9 @@ describe('@angular/core ng_package', () => { }); describe('umd', () => { - it('should have a umd file in the /bundles directory', - () => { expect(shx.ls('bundles/core-testing.umd.js').length).toBe(1, 'File not found'); }); + it('should have a umd file in the /bundles directory', () => { + expect(shx.ls('bundles/core-testing.umd.js').length).toBe(1, 'File not found'); + }); it('should have a source map next to the umd file', () => { expect(shx.ls('bundles/core-testing.umd.js.map').length).toBe(1, 'File not found'); diff --git a/packages/bazel/test/ngc-wrapped/flat_module_test.ts b/packages/bazel/test/ngc-wrapped/flat_module_test.ts index b7fdec9b79d63..664a4e736f55e 100644 --- a/packages/bazel/test/ngc-wrapped/flat_module_test.ts +++ b/packages/bazel/test/ngc-wrapped/flat_module_test.ts @@ -11,7 +11,6 @@ import {existsSync, readFileSync} from 'fs'; import {dirname, join} from 'path'; describe('flat_module ng_module', () => { - let packageOutput: string; let flatModuleOutFile: string; @@ -21,11 +20,11 @@ describe('flat_module ng_module', () => { flatModuleOutFile = join(packageOutput, 'flat_module.js'); }); - it('should have a flat module out file', - () => { expect(existsSync(flatModuleOutFile)).toBe(true); }); + it('should have a flat module out file', () => { + expect(existsSync(flatModuleOutFile)).toBe(true); + }); describe('flat module out file', () => { - obsoleteInIvy('Ngtsc computes the AMD module name differently than NGC') .it('should have a proper AMD module name', () => { expect(readFileSync(flatModuleOutFile, 'utf8')) diff --git a/packages/bazel/test/ngc-wrapped/index_test.ts b/packages/bazel/test/ngc-wrapped/index_test.ts index 5c22cc2d7bb05..3932730149b8c 100644 --- a/packages/bazel/test/ngc-wrapped/index_test.ts +++ b/packages/bazel/test/ngc-wrapped/index_test.ts @@ -11,7 +11,6 @@ import * as path from 'path'; import {setup} from './test_support'; describe('ngc_wrapped', () => { - it('should work', () => { const {read, write, runOneBuild, writeConfig, shouldExist, basePath, typesRoots} = setup(); diff --git a/packages/bazel/test/ngc-wrapped/test_support.ts b/packages/bazel/test/ngc-wrapped/test_support.ts index 9f0dc054a8d24..69098ba0538bc 100644 --- a/packages/bazel/test/ngc-wrapped/test_support.ts +++ b/packages/bazel/test/ngc-wrapped/test_support.ts @@ -19,7 +19,9 @@ export interface TestSupport { angularCorePath: string; typesRoots: string; writeConfig({ - srcTargetPath, depPaths, pathMapping, + srcTargetPath, + depPaths, + pathMapping, }: { srcTargetPath: string, depPaths?: string[], @@ -33,13 +35,13 @@ export interface TestSupport { runOneBuild(): boolean; } -export function setup( - { - bazelBin = 'bazel-bin', tsconfig = 'tsconfig.json', - }: { - bazelBin?: string, - tsconfig?: string, - } = {}): TestSupport { +export function setup({ + bazelBin = 'bazel-bin', + tsconfig = 'tsconfig.json', +}: { + bazelBin?: string, + tsconfig?: string, +} = {}): TestSupport { const runfilesPath = process.env['TEST_SRCDIR']; const basePath = makeTempDir(runfilesPath); @@ -93,12 +95,17 @@ export function setup( } function writeFiles(...mockDirs: {[fileName: string]: string}[]) { - mockDirs.forEach( - (dir) => { Object.keys(dir).forEach((fileName) => { write(fileName, dir[fileName]); }); }); + mockDirs.forEach((dir) => { + Object.keys(dir).forEach((fileName) => { + write(fileName, dir[fileName]); + }); + }); } function writeConfig({ - srcTargetPath, depPaths = [], pathMapping = [], + srcTargetPath, + depPaths = [], + pathMapping = [], }: { srcTargetPath: string, depPaths?: string[], @@ -133,7 +140,8 @@ export function setup( defaultTsConfig: emptyTsConfig.config, rootDir: basePath, target: target, - outDir: bazelBinPath, compilationTargetSrc, + outDir: bazelBinPath, + compilationTargetSrc, files: files, pathMapping: pathMappingObj, }); @@ -153,7 +161,9 @@ export function setup( } } - function runOneBuildImpl(): boolean { return runOneBuild(['@' + tsConfigJsonPath]); } + function runOneBuildImpl(): boolean { + return runOneBuild(['@' + tsConfigJsonPath]); + } } function makeTempDir(baseDir: string): string { diff --git a/packages/benchpress/index.ts b/packages/benchpress/index.ts index 716714669c7e6..0808d5f55f77a 100644 --- a/packages/benchpress/index.ts +++ b/packages/benchpress/index.ts @@ -24,7 +24,7 @@ export {JsonFileReporter} from './src/reporter/json_file_reporter'; export {MultiReporter} from './src/reporter/multi_reporter'; export {Runner} from './src/runner'; export {SampleDescription} from './src/sample_description'; -export {SampleState, Sampler} from './src/sampler'; +export {Sampler, SampleState} from './src/sampler'; export {Validator} from './src/validator'; export {RegressionSlopeValidator} from './src/validator/regression_slope_validator'; export {SizeValidator} from './src/validator/size_validator'; diff --git a/packages/benchpress/src/metric.ts b/packages/benchpress/src/metric.ts index 60fb0a8f0bcb5..228282ff1a2fc 100644 --- a/packages/benchpress/src/metric.ts +++ b/packages/benchpress/src/metric.ts @@ -14,18 +14,24 @@ export abstract class Metric { /** * Starts measuring */ - beginMeasure(): Promise { throw new Error('NYI'); } + beginMeasure(): Promise { + throw new Error('NYI'); + } /** * Ends measuring and reports the data * since the begin call. * @param restart: Whether to restart right after this. */ - endMeasure(restart: boolean): Promise<{[key: string]: any}> { throw new Error('NYI'); } + endMeasure(restart: boolean): Promise<{[key: string]: any}> { + throw new Error('NYI'); + } /** * Describes the metrics provided by this metric implementation. * (e.g. units, ...) */ - describe(): {[key: string]: string} { throw new Error('NYI'); } + describe(): {[key: string]: string} { + throw new Error('NYI'); + } } diff --git a/packages/benchpress/src/metric/multi_metric.ts b/packages/benchpress/src/metric/multi_metric.ts index 47310e74835cf..05994585d4813 100644 --- a/packages/benchpress/src/metric/multi_metric.ts +++ b/packages/benchpress/src/metric/multi_metric.ts @@ -26,7 +26,9 @@ export class MultiMetric extends Metric { ]; } - constructor(private _metrics: Metric[]) { super(); } + constructor(private _metrics: Metric[]) { + super(); + } /** * Starts measuring @@ -56,7 +58,11 @@ export class MultiMetric extends Metric { 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]; }); }); + maps.forEach(map => { + Object.keys(map).forEach(prop => { + result[prop] = map[prop]; + }); + }); return result; } diff --git a/packages/benchpress/src/metric/perflog_metric.ts b/packages/benchpress/src/metric/perflog_metric.ts index ac285e7a959e7..7a1dbd99a7203 100644 --- a/packages/benchpress/src/metric/perflog_metric.ts +++ b/packages/benchpress/src/metric/perflog_metric.ts @@ -23,11 +23,12 @@ export class PerflogMetric extends Metric { 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 - ] + 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, @@ -169,7 +170,9 @@ export class PerflogMetric extends Metric { return result; } let resolve: (result: any) => void; - const promise = new Promise<{[key: string]: number}>(res => { resolve = res; }); + const promise = new Promise<{[key: string]: number}>(res => { + resolve = res; + }); this._setTimeout(() => resolve(this._readUntilEndMark(markName, loopCount + 1)), 100); return promise; }); @@ -188,7 +191,7 @@ export class PerflogMetric extends Metric { } startEvent['ph'] = 'B'; endEvent['ph'] = 'E'; - endEvent['ts'] = startEvent['ts'] ! + startEvent['dur'] !; + endEvent['ts'] = startEvent['ts']! + startEvent['dur']!; this._remainingEvents.push(startEvent); this._remainingEvents.push(endEvent); } else { @@ -198,7 +201,7 @@ export class PerflogMetric extends Metric { if (needSort) { // Need to sort because of the ph==='X' events this._remainingEvents.sort((a, b) => { - const diff = a['ts'] ! - b['ts'] !; + const diff = a['ts']! - b['ts']!; return diff > 0 ? 1 : diff < 0 ? -1 : 0; }); } @@ -230,8 +233,8 @@ export class PerflogMetric extends Metric { result['requestCount'] = 0; } - let markStartEvent: PerfLogEvent = null !; - let markEndEvent: PerfLogEvent = null !; + let markStartEvent: PerfLogEvent = null!; + let markEndEvent: PerfLogEvent = null!; events.forEach((event) => { const ph = event['ph']; const name = event['name']; @@ -267,7 +270,7 @@ export class PerflogMetric extends Metric { let inMeasureRange = false; events.forEach((event) => { const ph = event['ph']; - let name = event['name'] !; + let name = event['name']!; let microIterations = 1; const microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX); if (microIterationsMatch) { @@ -286,7 +289,7 @@ export class PerflogMetric extends Metric { if (this._requestCount && name === 'sendRequest') { result['requestCount'] += 1; } else if (this._receivedData && name === 'receivedData' && ph === 'I') { - result['receivedData'] += event['args'] !['encodedDataLength'] !; + result['receivedData'] += event['args']!['encodedDataLength']!; } if (ph === 'B' && name === _MARK_NAME_FRAME_CAPTURE) { if (frameCaptureStartEvent) { @@ -305,7 +308,7 @@ export class PerflogMetric extends Metric { } if (ph === 'I' && frameCaptureStartEvent && !frameCaptureEndEvent && name === 'frame') { - frameTimestamps.push(event['ts'] !); + frameTimestamps.push(event['ts']!); if (frameTimestamps.length >= 2) { frameTimes.push( frameTimestamps[frameTimestamps.length - 1] - @@ -324,14 +327,14 @@ export class PerflogMetric extends Metric { intervalStartCount[name]--; if (intervalStartCount[name] === 0) { const startEvent = intervalStarts[name]; - const duration = (event['ts'] ! - startEvent['ts'] !); - intervalStarts[name] = null !; + const duration = (event['ts']! - startEvent['ts']!); + intervalStarts[name] = null!; if (name === 'gc') { result['gcTime'] += duration; const amount = - (startEvent['args'] !['usedHeapSize'] ! - event['args'] !['usedHeapSize'] !) / 1000; + (startEvent['args']!['usedHeapSize']! - event['args']!['usedHeapSize']!) / 1000; result['gcAmount'] += amount; - const majorGc = event['args'] !['majorGc']; + const majorGc = event['args']!['majorGc']; if (majorGc && majorGc) { result['majorGcTime'] += duration; } @@ -374,7 +377,9 @@ export class PerflogMetric extends Metric { frameTimes.filter(t => t < _FRAME_TIME_SMOOTH_THRESHOLD).length / frameTimes.length; } - private _markName(index: number) { return `${_MARK_NAME_PREFIX}${index}`; } + private _markName(index: number) { + return `${_MARK_NAME_PREFIX}${index}`; + } } const _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/; diff --git a/packages/benchpress/src/metric/user_metric.ts b/packages/benchpress/src/metric/user_metric.ts index 0adf2f08ef6ae..d08964a75f6b4 100644 --- a/packages/benchpress/src/metric/user_metric.ts +++ b/packages/benchpress/src/metric/user_metric.ts @@ -26,7 +26,9 @@ export class UserMetric extends Metric { /** * Starts measuring */ - beginMeasure(): Promise { return Promise.resolve(true); } + beginMeasure(): Promise { + return Promise.resolve(true); + } /** * Ends measuring. @@ -34,8 +36,7 @@ export class UserMetric extends Metric { 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) => { + const promise = new Promise<{[key: string]: any;}>((res, rej) => { resolve = res; reject = rej; }); @@ -67,5 +68,7 @@ export class UserMetric extends Metric { * Describes the metrics provided by this metric implementation. * (e.g. units, ...) */ - describe(): {[key: string]: any} { return this._userMetrics; } + describe(): {[key: string]: any} { + return this._userMetrics; + } } diff --git a/packages/benchpress/src/reporter.ts b/packages/benchpress/src/reporter.ts index 0a75e79614a57..842fd31d89d92 100644 --- a/packages/benchpress/src/reporter.ts +++ b/packages/benchpress/src/reporter.ts @@ -12,7 +12,9 @@ import {MeasureValues} from './measure_values'; * A reporter reports measure values and the valid sample. */ export abstract class Reporter { - reportMeasureValues(values: MeasureValues): Promise { throw new Error('NYI'); } + reportMeasureValues(values: MeasureValues): Promise { + throw new Error('NYI'); + } reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise { throw new Error('NYI'); diff --git a/packages/benchpress/src/reporter/console_reporter.ts b/packages/benchpress/src/reporter/console_reporter.ts index 1659640010591..e2dc0e519c386 100644 --- a/packages/benchpress/src/reporter/console_reporter.ts +++ b/packages/benchpress/src/reporter/console_reporter.ts @@ -28,10 +28,11 @@ export class ConsoleReporter extends Reporter { }, {provide: ConsoleReporter.COLUMN_WIDTH, useValue: 18}, { provide: ConsoleReporter.PRINT, - useValue: function(v: any) { - // tslint:disable-next-line:no-console - console.log(v); - } + useValue: + function(v: any) { + // tslint:disable-next-line:no-console + console.log(v); + } } ]; @@ -58,7 +59,9 @@ export class ConsoleReporter extends Reporter { this._print(`BENCHMARK ${sampleDescription.id}`); this._print('Description:'); const props = sortedProps(sampleDescription.description); - props.forEach((prop) => { this._print(`- ${prop}: ${sampleDescription.description[prop]}`); }); + props.forEach((prop) => { + this._print(`- ${prop}: ${sampleDescription.description[prop]}`); + }); this._print('Metrics:'); this._metricNames.forEach((metricName) => { this._print(`- ${metricName}: ${sampleDescription.metrics[metricName]}`); diff --git a/packages/benchpress/src/reporter/json_file_reporter.ts b/packages/benchpress/src/reporter/json_file_reporter.ts index aaca71e9164ad..702b94ca5d695 100644 --- a/packages/benchpress/src/reporter/json_file_reporter.ts +++ b/packages/benchpress/src/reporter/json_file_reporter.ts @@ -37,7 +37,9 @@ export class JsonFileReporter extends Reporter { super(); } - reportMeasureValues(measureValues: MeasureValues): Promise { return Promise.resolve(null); } + reportMeasureValues(measureValues: MeasureValues): Promise { + return Promise.resolve(null); + } reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise { const stats: {[key: string]: string} = {}; diff --git a/packages/benchpress/src/reporter/multi_reporter.ts b/packages/benchpress/src/reporter/multi_reporter.ts index 07b507148ac24..355ef4482f12f 100644 --- a/packages/benchpress/src/reporter/multi_reporter.ts +++ b/packages/benchpress/src/reporter/multi_reporter.ts @@ -27,7 +27,9 @@ export class MultiReporter extends Reporter { ]; } - constructor(private _reporters: Reporter[]) { super(); } + constructor(private _reporters: Reporter[]) { + super(); + } reportMeasureValues(values: MeasureValues): Promise { return Promise.all(this._reporters.map(reporter => reporter.reportMeasureValues(values))); diff --git a/packages/benchpress/src/runner.ts b/packages/benchpress/src/runner.ts index 7ba28dbf8a330..2b6e2f65fc270 100644 --- a/packages/benchpress/src/runner.ts +++ b/packages/benchpress/src/runner.ts @@ -17,7 +17,7 @@ import {Reporter} from './reporter'; import {ConsoleReporter} from './reporter/console_reporter'; import {MultiReporter} from './reporter/multi_reporter'; import {SampleDescription} from './sample_description'; -import {SampleState, Sampler} from './sampler'; +import {Sampler, SampleState} from './sampler'; import {Validator} from './validator'; import {RegressionSlopeValidator} from './validator/regression_slope_validator'; import {SizeValidator} from './validator/size_validator'; diff --git a/packages/benchpress/src/sample_description.ts b/packages/benchpress/src/sample_description.ts index ccecf159b5754..c99d65f902dbb 100644 --- a/packages/benchpress/src/sample_description.ts +++ b/packages/benchpress/src/sample_description.ts @@ -29,10 +29,11 @@ export class SampleDescription { userDesc ], metric.describe()), - deps: [ - Metric, Options.SAMPLE_ID, Options.FORCE_GC, Options.USER_AGENT, Validator, - Options.DEFAULT_DESCRIPTION, Options.SAMPLE_DESCRIPTION - ] + deps: + [ + Metric, Options.SAMPLE_ID, Options.FORCE_GC, Options.USER_AGENT, Validator, + Options.DEFAULT_DESCRIPTION, Options.SAMPLE_DESCRIPTION + ] }]; description: {[key: string]: any}; @@ -41,9 +42,13 @@ export class SampleDescription { public metrics: {[key: string]: any}) { this.description = {}; descriptions.forEach(description => { - Object.keys(description).forEach(prop => { this.description[prop] = description[prop]; }); + Object.keys(description).forEach(prop => { + this.description[prop] = description[prop]; + }); }); } - toJson() { return {'id': this.id, 'description': this.description, 'metrics': this.metrics}; } + toJson() { + return {'id': this.id, 'description': this.description, 'metrics': this.metrics}; + } } diff --git a/packages/benchpress/src/sampler.ts b/packages/benchpress/src/sampler.ts index 720fe621a5355..1d3999682b2fc 100644 --- a/packages/benchpress/src/sampler.ts +++ b/packages/benchpress/src/sampler.ts @@ -28,9 +28,11 @@ import {WebDriverAdapter} from './web_driver_adapter'; export class Sampler { static PROVIDERS = [{ provide: Sampler, - deps: [ - WebDriverAdapter, Metric, Reporter, Validator, Options.PREPARE, Options.EXECUTE, Options.NOW - ] + deps: + [ + WebDriverAdapter, Metric, Reporter, Validator, Options.PREPARE, Options.EXECUTE, + Options.NOW + ] }]; constructor( private _driver: WebDriverAdapter, private _metric: Metric, private _reporter: Reporter, diff --git a/packages/benchpress/src/validator.ts b/packages/benchpress/src/validator.ts index 536c22949d6e0..8838af7a2f772 100644 --- a/packages/benchpress/src/validator.ts +++ b/packages/benchpress/src/validator.ts @@ -17,11 +17,15 @@ export abstract class Validator { /** * Calculates a valid sample out of the complete sample */ - validate(completeSample: MeasureValues[]): MeasureValues[]|null { throw new Error('NYI'); } + validate(completeSample: MeasureValues[]): MeasureValues[]|null { + throw new Error('NYI'); + } /** * Returns a Map that describes the properties of the validator * (e.g. sample size, ...) */ - describe(): {[key: string]: any} { throw new Error('NYI'); } + describe(): {[key: string]: any} { + throw new Error('NYI'); + } } diff --git a/packages/benchpress/src/validator/size_validator.ts b/packages/benchpress/src/validator/size_validator.ts index 7d546c186a436..61e6c8cf71914 100644 --- a/packages/benchpress/src/validator/size_validator.ts +++ b/packages/benchpress/src/validator/size_validator.ts @@ -22,9 +22,13 @@ export class SizeValidator extends Validator { {provide: SizeValidator.SAMPLE_SIZE, useValue: 10} ]; - constructor(@Inject(SizeValidator.SAMPLE_SIZE) private _sampleSize: number) { super(); } + constructor(@Inject(SizeValidator.SAMPLE_SIZE) private _sampleSize: number) { + super(); + } - describe(): {[key: string]: any} { return {'sampleSize': this._sampleSize}; } + describe(): {[key: string]: any} { + return {'sampleSize': this._sampleSize}; + } validate(completeSample: MeasureValues[]): MeasureValues[]|null { if (completeSample.length >= this._sampleSize) { diff --git a/packages/benchpress/src/web_driver_adapter.ts b/packages/benchpress/src/web_driver_adapter.ts index d43e022f0e477..7e671a59ad89c 100644 --- a/packages/benchpress/src/web_driver_adapter.ts +++ b/packages/benchpress/src/web_driver_adapter.ts @@ -14,9 +14,19 @@ * Needs one implementation for every supported WebDriver client. */ export abstract class WebDriverAdapter { - waitFor(callback: Function): Promise { throw new Error('NYI'); } - executeScript(script: string): Promise { throw new Error('NYI'); } - executeAsyncScript(script: string): Promise { throw new Error('NYI'); } - capabilities(): Promise<{[key: string]: any}> { throw new Error('NYI'); } - logs(type: string): Promise { throw new Error('NYI'); } + waitFor(callback: Function): Promise { + throw new Error('NYI'); + } + executeScript(script: string): Promise { + throw new Error('NYI'); + } + executeAsyncScript(script: string): Promise { + throw new Error('NYI'); + } + capabilities(): Promise<{[key: string]: any}> { + throw new Error('NYI'); + } + logs(type: string): Promise { + throw new Error('NYI'); + } } diff --git a/packages/benchpress/src/web_driver_extension.ts b/packages/benchpress/src/web_driver_extension.ts index f5d1739763811..87e83c29bdb1c 100644 --- a/packages/benchpress/src/web_driver_extension.ts +++ b/packages/benchpress/src/web_driver_extension.ts @@ -12,7 +12,7 @@ import {Options} from './common_options'; export type PerfLogEvent = { [key: string]: any -} & { +}&{ ph?: 'X' | 'B' | 'E' | 'I', ts?: number, dur?: number, @@ -43,7 +43,7 @@ export abstract class WebDriverExtension { { provide: WebDriverExtension, useFactory: (children: WebDriverExtension[], capabilities: {[key: string]: any}) => { - let delegate: WebDriverExtension = undefined !; + let delegate: WebDriverExtension = undefined!; children.forEach(extension => { if (extension.supports(capabilities)) { delegate = extension; @@ -60,11 +60,17 @@ export abstract class WebDriverExtension { return res; } - gc(): Promise { throw new Error('NYI'); } + gc(): Promise { + throw new Error('NYI'); + } - timeBegin(name: string): Promise { throw new Error('NYI'); } + timeBegin(name: string): Promise { + throw new Error('NYI'); + } - timeEnd(name: string, restartName: string|null): Promise { throw new Error('NYI'); } + timeEnd(name: string, restartName: string|null): Promise { + throw new Error('NYI'); + } /** * Format: @@ -78,11 +84,17 @@ export abstract class WebDriverExtension { * Based on [Chrome Trace Event *Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit) **/ - readPerfLog(): Promise { throw new Error('NYI'); } + readPerfLog(): Promise { + throw new Error('NYI'); + } - perfLogFeatures(): PerfLogFeatures { throw new Error('NYI'); } + perfLogFeatures(): PerfLogFeatures { + throw new Error('NYI'); + } - supports(capabilities: {[key: string]: any}): boolean { return true; } + supports(capabilities: {[key: string]: any}): boolean { + return true; + } } export class PerfLogFeatures { diff --git a/packages/benchpress/src/webdriver/chrome_driver_extension.ts b/packages/benchpress/src/webdriver/chrome_driver_extension.ts index 9dba35fb28cbe..649c8f925082e 100644 --- a/packages/benchpress/src/webdriver/chrome_driver_extension.ts +++ b/packages/benchpress/src/webdriver/chrome_driver_extension.ts @@ -54,7 +54,9 @@ export class ChromeDriverExtension extends WebDriverExtension { return parseInt(v, 10); } - gc() { return this.driver.executeScript('window.gc()'); } + gc() { + return this.driver.executeScript('window.gc()'); + } async timeBegin(name: string): Promise { if (this._firstRun) { @@ -108,7 +110,7 @@ export class ChromeDriverExtension extends WebDriverExtension { chromeEvents.forEach((event) => { const categories = this._parseCategories(event['cat']); const normalizedEvent = this._convertEvent(event, categories); - if (normalizedEvent != null) normalizedEvents !.push(normalizedEvent); + if (normalizedEvent != null) normalizedEvents!.push(normalizedEvent); }); return normalizedEvents; } @@ -184,7 +186,9 @@ export class ChromeDriverExtension extends WebDriverExtension { return null; // nothing useful in this event } - private _parseCategories(categories: string): string[] { return categories.split(','); } + private _parseCategories(categories: string): string[] { + return categories.split(','); + } private _isEvent( eventCategories: string[], eventName: string, expectedCategories: string[], diff --git a/packages/benchpress/src/webdriver/firefox_driver_extension.ts b/packages/benchpress/src/webdriver/firefox_driver_extension.ts index 2d34742505618..796eaef34d0d8 100644 --- a/packages/benchpress/src/webdriver/firefox_driver_extension.ts +++ b/packages/benchpress/src/webdriver/firefox_driver_extension.ts @@ -22,7 +22,9 @@ export class FirefoxDriverExtension extends WebDriverExtension { this._profilerStarted = false; } - gc() { return this._driver.executeScript('window.forceGC()'); } + gc() { + return this._driver.executeScript('window.forceGC()'); + } timeBegin(name: string): Promise { if (!this._profilerStarted) { @@ -44,7 +46,9 @@ export class FirefoxDriverExtension extends WebDriverExtension { return this._driver.executeAsyncScript('var cb = arguments[0]; window.getProfile(cb);'); } - perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true, gc: true}); } + perfLogFeatures(): PerfLogFeatures { + return new PerfLogFeatures({render: true, gc: true}); + } supports(capabilities: {[key: string]: any}): boolean { return capabilities['browserName'].toLowerCase() === 'firefox'; diff --git a/packages/benchpress/src/webdriver/ios_driver_extension.ts b/packages/benchpress/src/webdriver/ios_driver_extension.ts index fefef6314c006..5200ee57e614f 100644 --- a/packages/benchpress/src/webdriver/ios_driver_extension.ts +++ b/packages/benchpress/src/webdriver/ios_driver_extension.ts @@ -15,9 +15,13 @@ import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_e export class IOsDriverExtension extends WebDriverExtension { static PROVIDERS = [{provide: IOsDriverExtension, deps: [WebDriverAdapter]}]; - constructor(private _driver: WebDriverAdapter) { super(); } + constructor(private _driver: WebDriverAdapter) { + super(); + } - gc(): Promise { throw new Error('Force GC is not supported on iOS'); } + gc(): Promise { + throw new Error('Force GC is not supported on iOS'); + } timeBegin(name: string): Promise { return this._driver.executeScript(`console.time('${name}');`); @@ -62,16 +66,16 @@ export class IOsDriverExtension extends WebDriverExtension { const endTime = record['endTime']; if (type === 'FunctionCall' && (data == null || data['scriptName'] !== 'InjectedScript')) { - events !.push(createStartEvent('script', startTime)); + events!.push(createStartEvent('script', startTime)); endEvent = createEndEvent('script', endTime); } else if (type === 'Time') { - events !.push(createMarkStartEvent(data['message'], startTime)); + events!.push(createMarkStartEvent(data['message'], startTime)); } else if (type === 'TimeEnd') { - events !.push(createMarkEndEvent(data['message'], startTime)); + 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)); + events!.push(createStartEvent('render', startTime)); endEvent = createEndEvent('render', endTime); } // Note: ios used to support GCEvent up until iOS 6 :-( @@ -79,21 +83,22 @@ export class IOsDriverExtension extends WebDriverExtension { this._convertPerfRecordsToEvents(record['children'], events); } if (endEvent != null) { - events !.push(endEvent); + events!.push(endEvent); } }); return events; } - perfLogFeatures(): PerfLogFeatures { return new PerfLogFeatures({render: true}); } + perfLogFeatures(): PerfLogFeatures { + return new PerfLogFeatures({render: true}); + } 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) { +function createEvent(ph: 'X'|'B'|'E'|'B'|'E', name: string, time: number, args: any = null) { const result: PerfLogEvent = { 'cat': 'timeline', 'name': name, diff --git a/packages/benchpress/src/webdriver/selenium_webdriver_adapter.ts b/packages/benchpress/src/webdriver/selenium_webdriver_adapter.ts index 3f7f7c4aa1fd7..74cc405dd3ff0 100644 --- a/packages/benchpress/src/webdriver/selenium_webdriver_adapter.ts +++ b/packages/benchpress/src/webdriver/selenium_webdriver_adapter.ts @@ -21,11 +21,17 @@ export class SeleniumWebDriverAdapter extends WebDriverAdapter { deps: [] }]; - constructor(private _driver: any) { super(); } + constructor(private _driver: any) { + super(); + } - waitFor(callback: () => any): Promise { return this._driver.call(callback); } + waitFor(callback: () => any): Promise { + return this._driver.call(callback); + } - executeScript(script: string): Promise { return this._driver.executeScript(script); } + executeScript(script: string): Promise { + return this._driver.executeScript(script); + } executeAsyncScript(script: string): Promise { return this._driver.executeAsyncScript(script); @@ -58,7 +64,9 @@ class Command { private parameters_: {[key: string]: any} = {}; constructor(private name_: string) {} - getName() { return this.name_; } + getName() { + return this.name_; + } setParameter(name: string, value: any) { this.parameters_[name] = value; @@ -70,7 +78,11 @@ class Command { return this; } - getParameter(key: string) { return this.parameters_[key]; } + getParameter(key: string) { + return this.parameters_[key]; + } - getParameters() { return this.parameters_; } + getParameters() { + return this.parameters_; + } } diff --git a/packages/benchpress/test/metric/multi_metric_spec.ts b/packages/benchpress/test/metric/multi_metric_spec.ts index 1eb8bda5bc8b2..16335f7fcd676 100644 --- a/packages/benchpress/test/metric/multi_metric_spec.ts +++ b/packages/benchpress/test/metric/multi_metric_spec.ts @@ -11,50 +11,52 @@ import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/te import {Injector, Metric, MultiMetric} from '../../index'; (function() { - function createMetric(ids: any[]) { - const m = Injector - .create([ - ids.map(id => ({provide: id, useValue: new MockMetric(id)})), - MultiMetric.provideWith(ids) - ]) - .get(MultiMetric); - return Promise.resolve(m); - } +function createMetric(ids: any[]) { + const m = Injector + .create([ + ids.map(id => ({provide: id, useValue: new MockMetric(id)})), + MultiMetric.provideWith(ids) + ]) + .get(MultiMetric); + return Promise.resolve(m); +} - describe('multi metric', () => { - it('should merge descriptions', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createMetric(['m1', 'm2']).then((m) => { - expect(m.describe()).toEqual({'m1': 'describe', 'm2': 'describe'}); - async.done(); - }); - })); +describe('multi metric', () => { + it('should merge descriptions', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + createMetric(['m1', 'm2']).then((m) => { + expect(m.describe()).toEqual({'m1': 'describe', 'm2': 'describe'}); + async.done(); + }); + })); - it('should merge all beginMeasure calls', + it('should merge all beginMeasure calls', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + createMetric(['m1', 'm2']).then((m) => m.beginMeasure()).then((values) => { + expect(values).toEqual(['m1_beginMeasure', 'm2_beginMeasure']); + async.done(); + }); + })); + + [false, true].forEach((restartFlag) => { + it(`should merge all endMeasure calls for restart=${restartFlag}`, inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createMetric(['m1', 'm2']).then((m) => m.beginMeasure()).then((values) => { - expect(values).toEqual(['m1_beginMeasure', 'm2_beginMeasure']); + createMetric(['m1', 'm2']).then((m) => m.endMeasure(restartFlag)).then((values) => { + expect(values).toEqual({'m1': {'restart': restartFlag}, 'm2': {'restart': restartFlag}}); async.done(); }); })); - - [false, true].forEach((restartFlag) => { - it(`should merge all endMeasure calls for restart=${restartFlag}`, - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createMetric(['m1', 'm2']).then((m) => m.endMeasure(restartFlag)).then((values) => { - expect(values).toEqual( - {'m1': {'restart': restartFlag}, 'm2': {'restart': restartFlag}}); - async.done(); - }); - })); - }); - }); +}); })(); class MockMetric extends Metric { - constructor(private _id: string) { super(); } + constructor(private _id: string) { + super(); + } - beginMeasure(): Promise { return Promise.resolve(`${this._id}_beginMeasure`); } + beginMeasure(): Promise { + return Promise.resolve(`${this._id}_beginMeasure`); + } endMeasure(restart: boolean): Promise<{[key: string]: any}> { const result: {[key: string]: any} = {}; diff --git a/packages/benchpress/test/metric/perflog_metric_spec.ts b/packages/benchpress/test/metric/perflog_metric_spec.ts index 7c068403a7de6..0133ff65db3f8 100644 --- a/packages/benchpress/test/metric/perflog_metric_spec.ts +++ b/packages/benchpress/test/metric/perflog_metric_spec.ts @@ -13,691 +13,677 @@ import {Injector, Metric, Options, PerfLogEvent, PerfLogFeatures, PerflogMetric, import {TraceEventFactory} from '../trace_event_factory'; (function() { - let commandLog: any[]; - const eventFactory = new TraceEventFactory('timeline', 'pid0'); - - function createMetric( - perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, - {microMetrics, forceGc, captureFrames, receivedData, requestCount, ignoreNavigation}: { - microMetrics?: {[key: string]: string}, - forceGc?: boolean, - captureFrames?: boolean, - receivedData?: boolean, - requestCount?: boolean, - ignoreNavigation?: boolean - } = {}): Metric { - commandLog = []; - if (!perfLogFeatures) { - perfLogFeatures = - new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true}); - } - if (!microMetrics) { - microMetrics = {}; - } - const providers: StaticProvider[] = [ - Options.DEFAULT_PROVIDERS, PerflogMetric.PROVIDERS, - {provide: Options.MICRO_METRICS, useValue: microMetrics}, { - provide: PerflogMetric.SET_TIMEOUT, - useValue: (fn: Function, millis: number) => { - commandLog.push(['setTimeout', millis]); - fn(); - }, +let commandLog: any[]; +const eventFactory = new TraceEventFactory('timeline', 'pid0'); + +function createMetric( + perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, + {microMetrics, forceGc, captureFrames, receivedData, requestCount, ignoreNavigation}: { + microMetrics?: {[key: string]: string}, + forceGc?: boolean, + captureFrames?: boolean, + receivedData?: boolean, + requestCount?: boolean, + ignoreNavigation?: boolean + } = {}): Metric { + commandLog = []; + if (!perfLogFeatures) { + perfLogFeatures = + new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true}); + } + if (!microMetrics) { + microMetrics = {}; + } + const providers: StaticProvider[] = [ + Options.DEFAULT_PROVIDERS, PerflogMetric.PROVIDERS, + {provide: Options.MICRO_METRICS, useValue: microMetrics}, { + provide: PerflogMetric.SET_TIMEOUT, + useValue: (fn: Function, millis: number) => { + commandLog.push(['setTimeout', millis]); + fn(); }, - { - provide: WebDriverExtension, - useValue: new MockDriverExtension(perfLogs, commandLog, perfLogFeatures) - } - ]; - if (forceGc != null) { - providers.push({provide: Options.FORCE_GC, useValue: forceGc}); - } - if (captureFrames != null) { - providers.push({provide: Options.CAPTURE_FRAMES, useValue: captureFrames}); - } - if (receivedData != null) { - providers.push({provide: Options.RECEIVED_DATA, useValue: receivedData}); + }, + { + provide: WebDriverExtension, + useValue: new MockDriverExtension(perfLogs, commandLog, perfLogFeatures) } - if (requestCount != null) { - providers.push({provide: Options.REQUEST_COUNT, useValue: requestCount}); - } - if (ignoreNavigation != null) { - providers.push({provide: PerflogMetric.IGNORE_NAVIGATION, useValue: ignoreNavigation}); - } - return Injector.create(providers).get(PerflogMetric); + ]; + if (forceGc != null) { + providers.push({provide: Options.FORCE_GC, useValue: forceGc}); } + if (captureFrames != null) { + providers.push({provide: Options.CAPTURE_FRAMES, useValue: captureFrames}); + } + if (receivedData != null) { + providers.push({provide: Options.RECEIVED_DATA, useValue: receivedData}); + } + if (requestCount != null) { + providers.push({provide: Options.REQUEST_COUNT, useValue: requestCount}); + } + if (ignoreNavigation != null) { + providers.push({provide: PerflogMetric.IGNORE_NAVIGATION, useValue: ignoreNavigation}); + } + return Injector.create(providers).get(PerflogMetric); +} - describe('perflog metric', () => { - - function sortedKeys(stringMap: {[key: string]: any}) { - const res: string[] = []; - res.push(...Object.keys(stringMap)); - res.sort(); - return res; - } - - it('should describe itself based on the perfLogFeatrues', () => { - expect(sortedKeys(createMetric([[]], new PerfLogFeatures()).describe())).toEqual([ - 'pureScriptTime', 'scriptTime' - ]); - - expect( - sortedKeys(createMetric([[]], new PerfLogFeatures({render: true, gc: false})).describe())) - .toEqual(['pureScriptTime', 'renderTime', 'scriptTime']); - - expect(sortedKeys(createMetric([[]], null !).describe())).toEqual([ - 'gcAmount', 'gcTime', 'majorGcTime', 'pureScriptTime', 'renderTime', 'scriptTime' - ]); - - expect(sortedKeys(createMetric([[]], new PerfLogFeatures({render: true, gc: true}), { - forceGc: true - }).describe())) - .toEqual([ - 'forcedGcAmount', 'forcedGcTime', 'gcAmount', 'gcTime', 'majorGcTime', 'pureScriptTime', - 'renderTime', 'scriptTime' - ]); - - - expect(sortedKeys(createMetric([[]], new PerfLogFeatures({userTiming: true}), { - receivedData: true, - requestCount: true - }).describe())) - .toEqual(['pureScriptTime', 'receivedData', 'requestCount', 'scriptTime']); - }); - - it('should describe itself based on micro metrics', () => { - const description = - createMetric([[]], null !, {microMetrics: {'myMicroMetric': 'someDesc'}}).describe(); - expect(description['myMicroMetric']).toEqual('someDesc'); - }); - - it('should describe itself if frame capture is requested and available', () => { - const description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), { - captureFrames: true - }).describe(); - expect(description['frameTime.mean']).not.toContain('WARNING'); - expect(description['frameTime.best']).not.toContain('WARNING'); - expect(description['frameTime.worst']).not.toContain('WARNING'); - expect(description['frameTime.smooth']).not.toContain('WARNING'); - }); +describe('perflog metric', () => { + function sortedKeys(stringMap: {[key: string]: any}) { + const res: string[] = []; + res.push(...Object.keys(stringMap)); + res.sort(); + return res; + } - it('should describe itself if frame capture is requested and not available', () => { - const description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), { - captureFrames: true - }).describe(); - expect(description['frameTime.mean']).toContain('WARNING'); - expect(description['frameTime.best']).toContain('WARNING'); - expect(description['frameTime.worst']).toContain('WARNING'); - expect(description['frameTime.smooth']).toContain('WARNING'); - }); + it('should describe itself based on the perfLogFeatrues', () => { + expect(sortedKeys(createMetric([[]], new PerfLogFeatures()).describe())).toEqual([ + 'pureScriptTime', 'scriptTime' + ]); + + expect( + sortedKeys(createMetric([[]], new PerfLogFeatures({render: true, gc: false})).describe())) + .toEqual(['pureScriptTime', 'renderTime', 'scriptTime']); + + expect(sortedKeys(createMetric([[]], null!).describe())).toEqual([ + 'gcAmount', 'gcTime', 'majorGcTime', 'pureScriptTime', 'renderTime', 'scriptTime' + ]); + + expect(sortedKeys(createMetric([[]], new PerfLogFeatures({render: true, gc: true}), { + forceGc: true + }).describe())) + .toEqual([ + 'forcedGcAmount', 'forcedGcTime', 'gcAmount', 'gcTime', 'majorGcTime', 'pureScriptTime', + 'renderTime', 'scriptTime' + ]); + + + expect(sortedKeys(createMetric([[]], new PerfLogFeatures({userTiming: true}), { + receivedData: true, + requestCount: true + }).describe())) + .toEqual(['pureScriptTime', 'receivedData', 'requestCount', 'scriptTime']); + }); - describe('beginMeasure', () => { + it('should describe itself based on micro metrics', () => { + const description = + createMetric([[]], null!, {microMetrics: {'myMicroMetric': 'someDesc'}}).describe(); + expect(description['myMicroMetric']).toEqual('someDesc'); + }); - it('should not force gc and mark the timeline', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const metric = createMetric([[]], null !); - metric.beginMeasure().then((_) => { - expect(commandLog).toEqual([['timeBegin', 'benchpress0']]); + it('should describe itself if frame capture is requested and available', () => { + const description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), { + captureFrames: true + }).describe(); + expect(description['frameTime.mean']).not.toContain('WARNING'); + expect(description['frameTime.best']).not.toContain('WARNING'); + expect(description['frameTime.worst']).not.toContain('WARNING'); + expect(description['frameTime.smooth']).not.toContain('WARNING'); + }); - async.done(); - }); - })); + it('should describe itself if frame capture is requested and not available', () => { + const description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), { + captureFrames: true + }).describe(); + expect(description['frameTime.mean']).toContain('WARNING'); + expect(description['frameTime.best']).toContain('WARNING'); + expect(description['frameTime.worst']).toContain('WARNING'); + expect(description['frameTime.smooth']).toContain('WARNING'); + }); - it('should force gc and mark the timeline', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const metric = createMetric([[]], null !, {forceGc: true}); - metric.beginMeasure().then((_) => { - expect(commandLog).toEqual([['gc'], ['timeBegin', 'benchpress0']]); + describe('beginMeasure', () => { + it('should not force gc and mark the timeline', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const metric = createMetric([[]], null!); + metric.beginMeasure().then((_) => { + expect(commandLog).toEqual([['timeBegin', 'benchpress0']]); + + async.done(); + }); + })); + + it('should force gc and mark the timeline', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const metric = createMetric([[]], null!, {forceGc: true}); + metric.beginMeasure().then((_) => { + expect(commandLog).toEqual([['gc'], ['timeBegin', 'benchpress0']]); + + async.done(); + }); + })); + }); - async.done(); - }); - })); + describe('endMeasure', () => { + it('should mark and aggregate events in between the marks', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const events = [[ + eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), + eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10) + ]]; + const metric = createMetric(events, null!); + metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { + expect(commandLog).toEqual([ + ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog' + ]); + expect(data['scriptTime']).toBe(2); + + async.done(); + }); + })); + + it('should mark and aggregate events since navigationStart', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const events = [[ + eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), + eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7), + eventFactory.start('script', 8), eventFactory.end('script', 9), + eventFactory.markEnd('benchpress0', 10) + ]]; + const metric = createMetric(events, null!); + metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { + expect(data['scriptTime']).toBe(1); + + async.done(); + }); + })); + + it('should ignore navigationStart if ignoreNavigation is set', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const events = [[ + eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), + eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7), + eventFactory.start('script', 8), eventFactory.end('script', 9), + eventFactory.markEnd('benchpress0', 10) + ]]; + const metric = createMetric(events, null!, {ignoreNavigation: true}); + metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { + expect(data['scriptTime']).toBe(3); + + async.done(); + }); + })); + + it('should restart timing', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const events = [ + [ + eventFactory.markStart('benchpress0', 0), + eventFactory.markEnd('benchpress0', 1), + eventFactory.markStart('benchpress1', 2), + ], + [eventFactory.markEnd('benchpress1', 3)] + ]; + const metric = createMetric(events, null!); + metric.beginMeasure() + .then((_) => metric.endMeasure(true)) + .then((_) => metric.endMeasure(true)) + .then((_) => { + expect(commandLog).toEqual([ + ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], + 'readPerfLog', ['timeEnd', 'benchpress1', 'benchpress2'], 'readPerfLog' + ]); - }); + async.done(); + }); + })); + + it('should loop and aggregate until the end mark is present', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const events = [ + [eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)], + [eventFactory.end('script', 2)], + [ + eventFactory.start('script', 3), eventFactory.end('script', 5), + eventFactory.markEnd('benchpress0', 10) + ] + ]; + const metric = createMetric(events, null!); + metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { + expect(commandLog).toEqual([ + ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog', + ['setTimeout', 100], 'readPerfLog', ['setTimeout', 100], 'readPerfLog' + ]); + expect(data['scriptTime']).toBe(3); + + async.done(); + }); + })); + + it('should store events after the end mark for the next call', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const events = [ + [ + eventFactory.markStart('benchpress0', 0), eventFactory.markEnd('benchpress0', 1), + eventFactory.markStart('benchpress1', 1), eventFactory.start('script', 1), + eventFactory.end('script', 2) + ], + [ + eventFactory.start('script', 3), eventFactory.end('script', 5), + eventFactory.markEnd('benchpress1', 6) + ] + ]; + const metric = createMetric(events, null!); + metric.beginMeasure() + .then((_) => metric.endMeasure(true)) + .then((data) => { + expect(data['scriptTime']).toBe(0); + return metric.endMeasure(true); + }) + .then((data) => { + expect(commandLog).toEqual([ + ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], + 'readPerfLog', ['timeEnd', 'benchpress1', 'benchpress2'], 'readPerfLog' + ]); + expect(data['scriptTime']).toBe(3); - describe('endMeasure', () => { + async.done(); + }); + })); + + describe('with forced gc', () => { + let events: PerfLogEvent[][]; + beforeEach(() => { + events = [[ + eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), + eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10), + eventFactory.markStart('benchpress1', 11), + eventFactory.start('gc', 12, {'usedHeapSize': 2500}), + eventFactory.end('gc', 15, {'usedHeapSize': 1000}), + eventFactory.markEnd('benchpress1', 20) + ]]; + }); - it('should mark and aggregate events in between the marks', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const events = [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), - eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10) - ]]; - const metric = createMetric(events, null !); + it('should measure forced gc', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const metric = createMetric(events, null!, {forceGc: true}); metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog' + ['gc'], ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], + 'readPerfLog', ['gc'], ['timeEnd', 'benchpress1', null], 'readPerfLog' ]); - expect(data['scriptTime']).toBe(2); + expect(data['forcedGcTime']).toBe(3); + expect(data['forcedGcAmount']).toBe(1.5); async.done(); }); })); - it('should mark and aggregate events since navigationStart', + it('should restart after the forced gc if needed', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const events = [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), - eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7), - eventFactory.start('script', 8), eventFactory.end('script', 9), - eventFactory.markEnd('benchpress0', 10) - ]]; - const metric = createMetric(events, null !); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(data['scriptTime']).toBe(1); - - async.done(); - }); - })); - - it('should ignore navigationStart if ignoreNavigation is set', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const events = [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), - eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7), - eventFactory.start('script', 8), eventFactory.end('script', 9), - eventFactory.markEnd('benchpress0', 10) - ]]; - const metric = createMetric(events, null !, {ignoreNavigation: true}); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(data['scriptTime']).toBe(3); + const metric = createMetric(events, null!, {forceGc: true}); + metric.beginMeasure().then((_) => metric.endMeasure(true)).then((data) => { + expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']); async.done(); }); })); + }); + }); - it('should restart timing', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const events = [ - [ - eventFactory.markStart('benchpress0', 0), - eventFactory.markEnd('benchpress0', 1), - eventFactory.markStart('benchpress1', 2), - ], - [eventFactory.markEnd('benchpress1', 3)] - ]; - const metric = createMetric(events, null !); - metric.beginMeasure() - .then((_) => metric.endMeasure(true)) - .then((_) => metric.endMeasure(true)) - .then((_) => { - expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], - 'readPerfLog', ['timeEnd', 'benchpress1', 'benchpress2'], 'readPerfLog' - ]); + describe('aggregation', () => { + function aggregate(events: any[], {microMetrics, captureFrames, receivedData, requestCount}: { + microMetrics?: {[key: string]: string}, + captureFrames?: boolean, + receivedData?: boolean, + requestCount?: boolean + } = {}) { + events.unshift(eventFactory.markStart('benchpress0', 0)); + events.push(eventFactory.markEnd('benchpress0', 10)); + const metric = createMetric([events], null!, { + microMetrics: microMetrics, + captureFrames: captureFrames, + receivedData: receivedData, + requestCount: requestCount + }); + return metric.beginMeasure().then((_) => metric.endMeasure(false)); + } + describe('frame metrics', () => { + it('should calculate mean frame time', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate( + [ + eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), + eventFactory.instant('frame', 3), eventFactory.instant('frame', 4), + eventFactory.markEnd('frameCapture', 5) + ], + {captureFrames: true}) + .then((data) => { + expect(data['frameTime.mean']).toBe(((3 - 1) + (4 - 3)) / 2); async.done(); }); })); - it('should loop and aggregate until the end mark is present', + it('should throw if no start event', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const events = [ - [eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)], - [eventFactory.end('script', 2)], - [ - eventFactory.start('script', 3), eventFactory.end('script', 5), - eventFactory.markEnd('benchpress0', 10) - ] - ]; - const metric = createMetric(events, null !); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog', - ['setTimeout', 100], 'readPerfLog', ['setTimeout', 100], 'readPerfLog' - ]); - expect(data['scriptTime']).toBe(3); - + aggregate([eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)], { + captureFrames: true + }).catch((err): any => { + expect(() => { + throw err; + }).toThrowError('missing start event for frame capture'); async.done(); }); })); - it('should store events after the end mark for the next call', + it('should throw if no end event', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const events = [ - [ - eventFactory.markStart('benchpress0', 0), eventFactory.markEnd('benchpress0', 1), - eventFactory.markStart('benchpress1', 1), eventFactory.start('script', 1), - eventFactory.end('script', 2) - ], - [ - eventFactory.start('script', 3), eventFactory.end('script', 5), - eventFactory.markEnd('benchpress1', 6) - ] - ]; - const metric = createMetric(events, null !); - metric.beginMeasure() - .then((_) => metric.endMeasure(true)) - .then((data) => { - expect(data['scriptTime']).toBe(0); - return metric.endMeasure(true); - }) - .then((data) => { - expect(commandLog).toEqual([ - ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], - 'readPerfLog', ['timeEnd', 'benchpress1', 'benchpress2'], 'readPerfLog' - ]); - expect(data['scriptTime']).toBe(3); - + aggregate( + [eventFactory.markStart('frameCapture', 3), eventFactory.instant('frame', 4)], + {captureFrames: true}) + .catch((err): any => { + expect(() => { + throw err; + }).toThrowError('missing end event for frame capture'); async.done(); }); })); - describe('with forced gc', () => { - let events: PerfLogEvent[][]; - beforeEach(() => { - events = [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), - eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10), - eventFactory.markStart('benchpress1', 11), - eventFactory.start('gc', 12, {'usedHeapSize': 2500}), - eventFactory.end('gc', 15, {'usedHeapSize': 1000}), - eventFactory.markEnd('benchpress1', 20) - ]]; - }); - - it('should measure forced gc', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const metric = createMetric(events, null !, {forceGc: true}); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(commandLog).toEqual([ - ['gc'], ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], - 'readPerfLog', ['gc'], ['timeEnd', 'benchpress1', null], 'readPerfLog' - ]); - expect(data['forcedGcTime']).toBe(3); - expect(data['forcedGcAmount']).toBe(1.5); - - async.done(); - }); - })); - - it('should restart after the forced gc if needed', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const metric = createMetric(events, null !, {forceGc: true}); - metric.beginMeasure().then((_) => metric.endMeasure(true)).then((data) => { - expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']); - - async.done(); - }); - })); - - }); - - }); - - describe('aggregation', () => { - - function aggregate(events: any[], {microMetrics, captureFrames, receivedData, requestCount}: { - microMetrics?: {[key: string]: string}, - captureFrames?: boolean, - receivedData?: boolean, - requestCount?: boolean - } = {}) { - events.unshift(eventFactory.markStart('benchpress0', 0)); - events.push(eventFactory.markEnd('benchpress0', 10)); - const metric = createMetric([events], null !, { - microMetrics: microMetrics, - captureFrames: captureFrames, - receivedData: receivedData, - requestCount: requestCount - }); - return metric.beginMeasure().then((_) => metric.endMeasure(false)); - } - - describe('frame metrics', () => { - it('should calculate mean frame time', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 3), eventFactory.instant('frame', 4), - eventFactory.markEnd('frameCapture', 5) - ], - {captureFrames: true}) - .then((data) => { - expect(data['frameTime.mean']).toBe(((3 - 1) + (4 - 3)) / 2); - async.done(); - }); - })); - - it('should throw if no start event', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - - aggregate( - [eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)], - {captureFrames: true}) - .catch((err): any => { - expect(() => { - throw err; - }).toThrowError('missing start event for frame capture'); - async.done(); - }); - })); - - it('should throw if no end event', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - - aggregate( - [eventFactory.markStart('frameCapture', 3), eventFactory.instant('frame', 4)], - {captureFrames: true}) - .catch((err): any => { - expect(() => { throw err; }).toThrowError('missing end event for frame capture'); - async.done(); - }); - })); - - it('should throw if trying to capture twice', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - - aggregate( - [ - eventFactory.markStart('frameCapture', 3), - eventFactory.markStart('frameCapture', 4) - ], - {captureFrames: true}) - .catch((err): any => { - expect(() => { - throw err; - }).toThrowError('can capture frames only once per benchmark run'); - async.done(); - }); - })); - - it('should throw if trying to capture when frame capture is disabled', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([eventFactory.markStart('frameCapture', 3)]).catch((err) => { - expect(() => { throw err; }) - .toThrowError( - 'found start event for frame capture, but frame capture was not requested in benchpress'); - async.done(); - return null; - }); - })); - - it('should throw if frame capture is enabled, but nothing is captured', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([], {captureFrames: true}).catch((err): any => { - expect(() => { throw err; }) - .toThrowError( - 'frame capture requested in benchpress, but no start event was found'); - async.done(); - }); - })); - - it('should calculate best and worst frame time', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 9), eventFactory.instant('frame', 15), - eventFactory.instant('frame', 18), eventFactory.instant('frame', 28), - eventFactory.instant('frame', 32), eventFactory.markEnd('frameCapture', 10) - ], - {captureFrames: true}) - .then((data) => { - expect(data['frameTime.worst']).toBe(10); - expect(data['frameTime.best']).toBe(3); - async.done(); - }); - })); - - it('should calculate percentage of smoothness to be good', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 2), eventFactory.instant('frame', 3), - eventFactory.markEnd('frameCapture', 4) - ], - {captureFrames: true}) - .then((data) => { - expect(data['frameTime.smooth']).toBe(1.0); - async.done(); - }); - })); - - it('should calculate percentage of smoothness to be bad', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), - eventFactory.instant('frame', 2), eventFactory.instant('frame', 22), - eventFactory.instant('frame', 23), eventFactory.instant('frame', 24), - eventFactory.markEnd('frameCapture', 4) - ], - {captureFrames: true}) - .then((data) => { - expect(data['frameTime.smooth']).toBe(0.75); - async.done(); - }); - })); - - }); - - it('should report a single interval', + it('should throw if trying to capture twice', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.start('script', 0), eventFactory.end('script', 5) - ]).then((data) => { - expect(data['scriptTime']).toBe(5); - async.done(); - }); - })); - - it('should sum up multiple intervals', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.start('script', 0), eventFactory.end('script', 5), - eventFactory.start('script', 10), eventFactory.end('script', 17) - ]).then((data) => { - expect(data['scriptTime']).toBe(12); - async.done(); - }); + aggregate( + [ + eventFactory.markStart('frameCapture', 3), + eventFactory.markStart('frameCapture', 4) + ], + {captureFrames: true}) + .catch((err): any => { + expect(() => { + throw err; + }).toThrowError('can capture frames only once per benchmark run'); + async.done(); + }); })); - it('should ignore not started intervals', + it('should throw if trying to capture when frame capture is disabled', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([eventFactory.end('script', 10)]).then((data) => { - expect(data['scriptTime']).toBe(0); + aggregate([eventFactory.markStart('frameCapture', 3)]).catch((err) => { + expect(() => { + throw err; + }) + .toThrowError( + 'found start event for frame capture, but frame capture was not requested in benchpress'); async.done(); + return null; }); })); - it('should ignore not ended intervals', + it('should throw if frame capture is enabled, but nothing is captured', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([eventFactory.start('script', 10)]).then((data) => { - expect(data['scriptTime']).toBe(0); + aggregate([], {captureFrames: true}).catch((err): any => { + expect(() => { + throw err; + }).toThrowError('frame capture requested in benchpress, but no start event was found'); async.done(); }); })); - it('should ignore nested intervals', + it('should calculate best and worst frame time', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.start('script', 0), eventFactory.start('script', 5), - eventFactory.end('script', 10), eventFactory.end('script', 17) - ]).then((data) => { - expect(data['scriptTime']).toBe(17); - async.done(); - }); + aggregate( + [ + eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), + eventFactory.instant('frame', 9), eventFactory.instant('frame', 15), + eventFactory.instant('frame', 18), eventFactory.instant('frame', 28), + eventFactory.instant('frame', 32), eventFactory.markEnd('frameCapture', 10) + ], + {captureFrames: true}) + .then((data) => { + expect(data['frameTime.worst']).toBe(10); + expect(data['frameTime.best']).toBe(3); + async.done(); + }); })); - it('should ignore events from different processed as the start mark', + it('should calculate percentage of smoothness to be good', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1'); - const metric = createMetric( - [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null), - eventFactory.end('script', 5, null), - otherProcessEventFactory.start('script', 10, null), - otherProcessEventFactory.end('script', 17, null), - eventFactory.markEnd('benchpress0', 20) - ]], - null !); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(data['scriptTime']).toBe(5); - async.done(); - }); + aggregate( + [ + eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), + eventFactory.instant('frame', 2), eventFactory.instant('frame', 3), + eventFactory.markEnd('frameCapture', 4) + ], + {captureFrames: true}) + .then((data) => { + expect(data['frameTime.smooth']).toBe(1.0); + async.done(); + }); })); - it('should mark a run as invalid if the start and end marks are different', + it('should calculate percentage of smoothness to be bad', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1'); - const metric = createMetric( - [[ - eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null), - eventFactory.end('script', 5, null), - otherProcessEventFactory.start('script', 10, null), - otherProcessEventFactory.end('script', 17, null), - otherProcessEventFactory.markEnd('benchpress0', 20) - ]], - null !); - metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { - expect(data['invalid']).toBe(1); - async.done(); - }); + aggregate( + [ + eventFactory.markStart('frameCapture', 0), eventFactory.instant('frame', 1), + eventFactory.instant('frame', 2), eventFactory.instant('frame', 22), + eventFactory.instant('frame', 23), eventFactory.instant('frame', 24), + eventFactory.markEnd('frameCapture', 4) + ], + {captureFrames: true}) + .then((data) => { + expect(data['frameTime.smooth']).toBe(0.75); + async.done(); + }); })); + }); - it('should support scriptTime metric', + it('should report a single interval', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('script', 0), eventFactory.end('script', 5) + ]).then((data) => { + expect(data['scriptTime']).toBe(5); + async.done(); + }); + })); + + it('should sum up multiple intervals', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('script', 0), eventFactory.end('script', 5), + eventFactory.start('script', 10), eventFactory.end('script', 17) + ]).then((data) => { + expect(data['scriptTime']).toBe(12); + async.done(); + }); + })); + + it('should ignore not started intervals', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([eventFactory.end('script', 10)]).then((data) => { + expect(data['scriptTime']).toBe(0); + async.done(); + }); + })); + + it('should ignore not ended intervals', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([eventFactory.start('script', 10)]).then((data) => { + expect(data['scriptTime']).toBe(0); + async.done(); + }); + })); + + it('should ignore nested intervals', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('script', 0), eventFactory.start('script', 5), + eventFactory.end('script', 10), eventFactory.end('script', 17) + ]).then((data) => { + expect(data['scriptTime']).toBe(17); + async.done(); + }); + })); + + it('should ignore events from different processed as the start mark', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1'); + const metric = createMetric( + [[ + eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null), + eventFactory.end('script', 5, null), + otherProcessEventFactory.start('script', 10, null), + otherProcessEventFactory.end('script', 17, null), + eventFactory.markEnd('benchpress0', 20) + ]], + null!); + metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { + expect(data['scriptTime']).toBe(5); + async.done(); + }); + })); + + it('should mark a run as invalid if the start and end marks are different', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1'); + const metric = createMetric( + [[ + eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null), + eventFactory.end('script', 5, null), + otherProcessEventFactory.start('script', 10, null), + otherProcessEventFactory.end('script', 17, null), + otherProcessEventFactory.markEnd('benchpress0', 20) + ]], + null!); + metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { + expect(data['invalid']).toBe(1); + async.done(); + }); + })); + + it('should support scriptTime metric', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('script', 0), eventFactory.end('script', 5) + ]).then((data) => { + expect(data['scriptTime']).toBe(5); + async.done(); + }); + })); + + it('should support renderTime metric', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('render', 0), eventFactory.end('render', 5) + ]).then((data) => { + expect(data['renderTime']).toBe(5); + async.done(); + }); + })); + + it('should support gcTime/gcAmount metric', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('gc', 0, {'usedHeapSize': 2500}), + eventFactory.end('gc', 5, {'usedHeapSize': 1000}) + ]).then((data) => { + expect(data['gcTime']).toBe(5); + expect(data['gcAmount']).toBe(1.5); + expect(data['majorGcTime']).toBe(0); + async.done(); + }); + })); + + it('should support majorGcTime metric', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('gc', 0, {'usedHeapSize': 2500}), + eventFactory.end('gc', 5, {'usedHeapSize': 1000, 'majorGc': true}) + ]).then((data) => { + expect(data['gcTime']).toBe(5); + expect(data['majorGcTime']).toBe(5); + async.done(); + }); + })); + + it('should support pureScriptTime = scriptTime-gcTime-renderTime', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + aggregate([ + eventFactory.start('script', 0), eventFactory.start('gc', 1, {'usedHeapSize': 1000}), + eventFactory.end('gc', 4, {'usedHeapSize': 0}), eventFactory.start('render', 4), + eventFactory.end('render', 5), eventFactory.end('script', 6) + ]).then((data) => { + expect(data['scriptTime']).toBe(6); + expect(data['pureScriptTime']).toBe(2); + async.done(); + }); + })); + + describe('receivedData', () => { + it('should report received data since last navigationStart', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.start('script', 0), eventFactory.end('script', 5) - ]).then((data) => { - expect(data['scriptTime']).toBe(5); - async.done(); - }); + aggregate( + [ + eventFactory.instant('receivedData', 0, {'encodedDataLength': 1}), + eventFactory.instant('navigationStart', 1), + eventFactory.instant('receivedData', 2, {'encodedDataLength': 2}), + eventFactory.instant('navigationStart', 3), + eventFactory.instant('receivedData', 4, {'encodedDataLength': 4}), + eventFactory.instant('receivedData', 5, {'encodedDataLength': 8}) + ], + {receivedData: true}) + .then((data) => { + expect(data['receivedData']).toBe(12); + async.done(); + }); })); + }); - it('should support renderTime metric', + describe('requestCount', () => { + it('should report count of requests sent since last navigationStart', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.start('render', 0), eventFactory.end('render', 5) - ]).then((data) => { - expect(data['renderTime']).toBe(5); - async.done(); - }); + aggregate( + [ + eventFactory.instant('sendRequest', 0), eventFactory.instant('navigationStart', 1), + eventFactory.instant('sendRequest', 2), eventFactory.instant('navigationStart', 3), + eventFactory.instant('sendRequest', 4), eventFactory.instant('sendRequest', 5) + ], + {requestCount: true}) + .then((data) => { + expect(data['requestCount']).toBe(2); + async.done(); + }); })); + }); - it('should support gcTime/gcAmount metric', + describe('microMetrics', () => { + it('should report micro metrics', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.start('gc', 0, {'usedHeapSize': 2500}), - eventFactory.end('gc', 5, {'usedHeapSize': 1000}) - ]).then((data) => { - expect(data['gcTime']).toBe(5); - expect(data['gcAmount']).toBe(1.5); - expect(data['majorGcTime']).toBe(0); - async.done(); - }); + aggregate( + [ + eventFactory.markStart('mm1', 0), + eventFactory.markEnd('mm1', 5), + ], + {microMetrics: {'mm1': 'micro metric 1'}}) + .then((data) => { + expect(data['mm1']).toBe(5.0); + async.done(); + }); })); - it('should support majorGcTime metric', + it('should ignore micro metrics that were not specified', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { aggregate([ - eventFactory.start('gc', 0, {'usedHeapSize': 2500}), - eventFactory.end('gc', 5, {'usedHeapSize': 1000, 'majorGc': true}) + eventFactory.markStart('mm1', 0), + eventFactory.markEnd('mm1', 5), ]).then((data) => { - expect(data['gcTime']).toBe(5); - expect(data['majorGcTime']).toBe(5); + expect(data['mm1']).toBeFalsy(); async.done(); }); })); - it('should support pureScriptTime = scriptTime-gcTime-renderTime', + it('should report micro metric averages', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.start('script', 0), eventFactory.start('gc', 1, {'usedHeapSize': 1000}), - eventFactory.end('gc', 4, {'usedHeapSize': 0}), eventFactory.start('render', 4), - eventFactory.end('render', 5), eventFactory.end('script', 6) - ]).then((data) => { - expect(data['scriptTime']).toBe(6); - expect(data['pureScriptTime']).toBe(2); - async.done(); - }); + aggregate( + [ + eventFactory.markStart('mm1*20', 0), + eventFactory.markEnd('mm1*20', 5), + ], + {microMetrics: {'mm1': 'micro metric 1'}}) + .then((data) => { + expect(data['mm1']).toBe(5 / 20); + async.done(); + }); })); - - describe('receivedData', () => { - it('should report received data since last navigationStart', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.instant('receivedData', 0, {'encodedDataLength': 1}), - eventFactory.instant('navigationStart', 1), - eventFactory.instant('receivedData', 2, {'encodedDataLength': 2}), - eventFactory.instant('navigationStart', 3), - eventFactory.instant('receivedData', 4, {'encodedDataLength': 4}), - eventFactory.instant('receivedData', 5, {'encodedDataLength': 8}) - ], - {receivedData: true}) - .then((data) => { - expect(data['receivedData']).toBe(12); - async.done(); - }); - })); - }); - - describe('requestCount', () => { - it('should report count of requests sent since last navigationStart', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.instant('sendRequest', 0), - eventFactory.instant('navigationStart', 1), - eventFactory.instant('sendRequest', 2), - eventFactory.instant('navigationStart', 3), - eventFactory.instant('sendRequest', 4), eventFactory.instant('sendRequest', 5) - ], - {requestCount: true}) - .then((data) => { - expect(data['requestCount']).toBe(2); - async.done(); - }); - })); - }); - - describe('microMetrics', () => { - - it('should report micro metrics', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.markStart('mm1', 0), - eventFactory.markEnd('mm1', 5), - ], - {microMetrics: {'mm1': 'micro metric 1'}}) - .then((data) => { - expect(data['mm1']).toBe(5.0); - async.done(); - }); - })); - - it('should ignore micro metrics that were not specified', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate([ - eventFactory.markStart('mm1', 0), - eventFactory.markEnd('mm1', 5), - ]).then((data) => { - expect(data['mm1']).toBeFalsy(); - async.done(); - }); - })); - - it('should report micro metric averages', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - aggregate( - [ - eventFactory.markStart('mm1*20', 0), - eventFactory.markEnd('mm1*20', 5), - ], - {microMetrics: {'mm1': 'micro metric 1'}}) - .then((data) => { - expect(data['mm1']).toBe(5 / 20); - async.done(); - }); - })); - - }); - }); - }); +}); })(); class MockDriverExtension extends WebDriverExtension { @@ -717,7 +703,9 @@ class MockDriverExtension extends WebDriverExtension { return Promise.resolve(null); } - perfLogFeatures(): PerfLogFeatures { return this._perfLogFeatures; } + perfLogFeatures(): PerfLogFeatures { + return this._perfLogFeatures; + } readPerfLog(): Promise { this._commandLog.push('readPerfLog'); diff --git a/packages/benchpress/test/metric/user_metric_spec.ts b/packages/benchpress/test/metric/user_metric_spec.ts index 0225154a585f5..0f551c3184c2e 100644 --- a/packages/benchpress/test/metric/user_metric_spec.ts +++ b/packages/benchpress/test/metric/user_metric_spec.ts @@ -12,55 +12,55 @@ import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/te import {Options, PerfLogEvent, PerfLogFeatures, UserMetric, WebDriverAdapter} from '../../index'; (function() { - let wdAdapter: MockDriverAdapter; +let wdAdapter: MockDriverAdapter; - function createMetric( - perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, - {userMetrics}: {userMetrics?: {[key: string]: string}} = {}): UserMetric { - if (!perfLogFeatures) { - perfLogFeatures = - new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true}); - } - if (!userMetrics) { - userMetrics = {}; - } - wdAdapter = new MockDriverAdapter(); - const providers: StaticProvider[] = [ - Options.DEFAULT_PROVIDERS, UserMetric.PROVIDERS, - {provide: Options.USER_METRICS, useValue: userMetrics}, - {provide: WebDriverAdapter, useValue: wdAdapter} - ]; - return Injector.create(providers).get(UserMetric); +function createMetric( + perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, + {userMetrics}: {userMetrics?: {[key: string]: string}} = {}): UserMetric { + if (!perfLogFeatures) { + perfLogFeatures = + new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true}); } + if (!userMetrics) { + userMetrics = {}; + } + wdAdapter = new MockDriverAdapter(); + const providers: StaticProvider[] = [ + Options.DEFAULT_PROVIDERS, UserMetric.PROVIDERS, + {provide: Options.USER_METRICS, useValue: userMetrics}, + {provide: WebDriverAdapter, useValue: wdAdapter} + ]; + return Injector.create(providers).get(UserMetric); +} - describe('user metric', () => { - - it('should describe itself based on userMetrics', () => { - expect(createMetric([[]], new PerfLogFeatures(), { - userMetrics: {'loadTime': 'time to load'} - }).describe()) - .toEqual({'loadTime': 'time to load'}); - }); - - describe('endMeasure', () => { - it('should stop measuring when all properties have numeric values', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const metric = createMetric( - [[]], new PerfLogFeatures(), - {userMetrics: {'loadTime': 'time to load', 'content': 'time to see content'}}); - metric.beginMeasure().then(() => metric.endMeasure(true)).then(values => { - expect(values['loadTime']).toBe(25); - expect(values['content']).toBe(250); - async.done(); - }); +describe('user metric', () => { + it('should describe itself based on userMetrics', () => { + expect(createMetric([[]], new PerfLogFeatures(), { + userMetrics: {'loadTime': 'time to load'} + }).describe()) + .toEqual({'loadTime': 'time to load'}); + }); - wdAdapter.data['loadTime'] = 25; - // Wait before setting 2nd property. - setTimeout(() => { wdAdapter.data['content'] = 250; }, 50); + describe('endMeasure', () => { + it('should stop measuring when all properties have numeric values', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const metric = createMetric( + [[]], new PerfLogFeatures(), + {userMetrics: {'loadTime': 'time to load', 'content': 'time to see content'}}); + metric.beginMeasure().then(() => metric.endMeasure(true)).then(values => { + expect(values['loadTime']).toBe(25); + expect(values['content']).toBe(250); + async.done(); + }); - }), 600); - }); + wdAdapter.data['loadTime'] = 25; + // Wait before setting 2nd property. + setTimeout(() => { + wdAdapter.data['content'] = 250; + }, 50); + }), 600); }); +}); })(); class MockDriverAdapter extends WebDriverAdapter { diff --git a/packages/benchpress/test/reporter/console_reporter_spec.ts b/packages/benchpress/test/reporter/console_reporter_spec.ts index 0181382b11f2d..ac1397a82caa1 100644 --- a/packages/benchpress/test/reporter/console_reporter_spec.ts +++ b/packages/benchpress/test/reporter/console_reporter_spec.ts @@ -18,10 +18,10 @@ import {ConsoleReporter, Injector, MeasureValues, SampleDescription} from '../.. function createReporter( {columnWidth = null, sampleId = null, descriptions = null, metrics = null}: { - columnWidth?: number | null, - sampleId?: string | null, - descriptions?: {[key: string]: any}[] | null, - metrics?: {[key: string]: any} | null + columnWidth?: number|null, + sampleId?: string|null, + descriptions?: {[key: string]: any}[]|null, + metrics?: {[key: string]: any}|null }) { log = []; if (!descriptions) { @@ -33,7 +33,7 @@ import {ConsoleReporter, Injector, MeasureValues, SampleDescription} from '../.. const providers: StaticProvider[] = [ ConsoleReporter.PROVIDERS, { provide: SampleDescription, - useValue: new SampleDescription(sampleId, descriptions, metrics !) + useValue: new SampleDescription(sampleId, descriptions, metrics!) }, {provide: ConsoleReporter.PRINT, useValue: (line: string) => log.push(line)} ]; @@ -84,7 +84,6 @@ import {ConsoleReporter, Injector, MeasureValues, SampleDescription} from '../.. reporter.reportSample([], [mv(0, 0, {'a': 3, 'b': 0}), mv(1, 1, {'a': 5, 'b': 0})]); expect(log).toEqual(['======== | ========', '4.00+-25% | 0.00']); }); - }); } diff --git a/packages/benchpress/test/reporter/json_file_reporter_spec.ts b/packages/benchpress/test/reporter/json_file_reporter_spec.ts index 2ca147f2379d4..3ade0b9a27f1d 100644 --- a/packages/benchpress/test/reporter/json_file_reporter_spec.ts +++ b/packages/benchpress/test/reporter/json_file_reporter_spec.ts @@ -62,16 +62,12 @@ import {Injector, JsonFileReporter, MeasureValues, Options, SampleDescription} f {'timeStamp': '1970-01-01T00:00:00.000Z', 'runIndex': 0, 'values': {'a': 3, 'b': 6}} ], 'validSample': [ - {'timeStamp': '1970-01-01T00:00:00.000Z', 'runIndex': 0, 'values': {'a': 3, 'b': 6}}, { - 'timeStamp': '1970-01-01T00:00:00.001Z', - 'runIndex': 1, - 'values': {'a': 5, 'b': 9} - } + {'timeStamp': '1970-01-01T00:00:00.000Z', 'runIndex': 0, 'values': {'a': 3, 'b': 6}}, + {'timeStamp': '1970-01-01T00:00:00.001Z', 'runIndex': 1, 'values': {'a': 5, 'b': 9}} ] }); async.done(); })); - }); } diff --git a/packages/benchpress/test/reporter/multi_reporter_spec.ts b/packages/benchpress/test/reporter/multi_reporter_spec.ts index 4bfeb5ff82282..96045b5a1f79c 100644 --- a/packages/benchpress/test/reporter/multi_reporter_spec.ts +++ b/packages/benchpress/test/reporter/multi_reporter_spec.ts @@ -11,50 +11,48 @@ import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/te import {Injector, MeasureValues, MultiReporter, Reporter} from '../../index'; (function() { - function createReporters(ids: any[]) { - const r = Injector - .create([ - ids.map(id => ({provide: id, useValue: new MockReporter(id)})), - MultiReporter.provideWith(ids) - ]) - .get(MultiReporter); - return Promise.resolve(r); - } - - describe('multi reporter', () => { - - it('should reportMeasureValues to all', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const mv = new MeasureValues(0, new Date(), {}); - createReporters(['m1', 'm2']).then((r) => r.reportMeasureValues(mv)).then((values) => { - - expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]); - async.done(); - }); - })); - - it('should reportSample to call', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - const completeSample = - [new MeasureValues(0, new Date(), {}), new MeasureValues(1, new Date(), {})]; - const validSample = [completeSample[1]]; +function createReporters(ids: any[]) { + const r = Injector + .create([ + ids.map(id => ({provide: id, useValue: new MockReporter(id)})), + MultiReporter.provideWith(ids) + ]) + .get(MultiReporter); + return Promise.resolve(r); +} - createReporters(['m1', 'm2']) - .then((r) => r.reportSample(completeSample, validSample)) - .then((values) => { +describe('multi reporter', () => { + it('should reportMeasureValues to all', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const mv = new MeasureValues(0, new Date(), {}); + createReporters(['m1', 'm2']).then((r) => r.reportMeasureValues(mv)).then((values) => { + expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]); + async.done(); + }); + })); - expect(values).toEqual([ - {'id': 'm1', 'completeSample': completeSample, 'validSample': validSample}, - {'id': 'm2', 'completeSample': completeSample, 'validSample': validSample} - ]); - async.done(); - }); - })); + it('should reportSample to call', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + const completeSample = + [new MeasureValues(0, new Date(), {}), new MeasureValues(1, new Date(), {})]; + const validSample = [completeSample[1]]; - }); + createReporters(['m1', 'm2']) + .then((r) => r.reportSample(completeSample, validSample)) + .then((values) => { + expect(values).toEqual([ + {'id': 'm1', 'completeSample': completeSample, 'validSample': validSample}, + {'id': 'm2', 'completeSample': completeSample, 'validSample': validSample} + ]); + async.done(); + }); + })); +}); })(); class MockReporter extends Reporter { - constructor(private _id: string) { super(); } + constructor(private _id: string) { + super(); + } reportMeasureValues(values: MeasureValues): Promise<{[key: string]: any}> { return Promise.resolve({'id': this._id, 'values': values}); diff --git a/packages/benchpress/test/runner_spec.ts b/packages/benchpress/test/runner_spec.ts index 3487b5988eb52..87cd2710c952f 100644 --- a/packages/benchpress/test/runner_spec.ts +++ b/packages/benchpress/test/runner_spec.ts @@ -8,7 +8,7 @@ import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal'; -import {Injector, Metric, Options, Runner, SampleDescription, SampleState, Sampler, Validator, WebDriverAdapter} from '../index'; +import {Injector, Metric, Options, Runner, SampleDescription, Sampler, SampleState, Validator, WebDriverAdapter} from '../index'; { describe('runner', () => { @@ -68,7 +68,6 @@ import {Injector, Metric, Options, Runner, SampleDescription, SampleState, Sampl .sample({id: 'someId'}) .then((_) => injector.get(SampleDescription)) .then((desc) => { - expect(desc.metrics).toEqual({'m1': 'some metric'}); async.done(); }); @@ -109,32 +108,45 @@ import {Injector, Metric, Options, Runner, SampleDescription, SampleState, Sampl }) .then((_) => injector.get(SampleDescription)) .then((desc) => { - expect(desc.description['a']).toBe(2); async.done(); }); - })); - }); } class MockWebDriverAdapter extends WebDriverAdapter { - executeScript(script: string): Promise { return Promise.resolve('someUserAgent'); } - capabilities(): Promise> { return null !; } + executeScript(script: string): Promise { + return Promise.resolve('someUserAgent'); + } + capabilities(): Promise> { + return null!; + } } class MockValidator extends Validator { - constructor() { super(); } - describe() { return {'v': 11}; } + constructor() { + super(); + } + describe() { + return {'v': 11}; + } } class MockMetric extends Metric { - constructor() { super(); } - describe() { return {'m1': 'some metric'}; } + constructor() { + super(); + } + describe() { + return {'m1': 'some metric'}; + } } class MockSampler extends Sampler { - constructor() { super(null !, null !, null !, null !, null !, null !, null !); } - sample(): Promise { return Promise.resolve(new SampleState([], [])); } + constructor() { + super(null!, null!, null!, null!, null!, null!, null!); + } + sample(): Promise { + return Promise.resolve(new SampleState([], [])); + } } diff --git a/packages/benchpress/test/sampler_spec.ts b/packages/benchpress/test/sampler_spec.ts index 9b1b7864e38d6..ec416c8d0f468 100644 --- a/packages/benchpress/test/sampler_spec.ts +++ b/packages/benchpress/test/sampler_spec.ts @@ -67,7 +67,6 @@ import {Injector, MeasureValues, Metric, Options, Reporter, Sampler, Validator, expect(log).toEqual([0, 1, 2, 3]); async.done(); }); - })); it('should call prepare, beginMeasure, execute, endMeasure for every iteration', @@ -77,8 +76,12 @@ import {Injector, MeasureValues, Metric, Options, Reporter, Sampler, Validator, createSampler({ metric: createCountingMetric(log), validator: createCountingValidator(2), - prepare: () => { log.push(`p${workCount++}`); }, - execute: () => { log.push(`w${workCount++}`); } + prepare: () => { + log.push(`p${workCount++}`); + }, + execute: () => { + log.push(`w${workCount++}`); + } }); sampler.sample().then((_) => { expect(log).toEqual([ @@ -102,7 +105,9 @@ import {Injector, MeasureValues, Metric, Options, Reporter, Sampler, Validator, createSampler({ metric: createCountingMetric(log), validator: createCountingValidator(2), - execute: () => { log.push(`w${workCount++}`); }, + execute: () => { + log.push(`w${workCount++}`); + }, prepare: null }); sampler.sample().then((_) => { @@ -130,7 +135,9 @@ import {Injector, MeasureValues, Metric, Options, Reporter, Sampler, Validator, scriptTime = 0; return result; }), - prepare: () => { scriptTime = 1 * iterationCount; }, + prepare: () => { + scriptTime = 1 * iterationCount; + }, execute: () => { scriptTime = 10 * iterationCount; iterationCount++; @@ -147,7 +154,7 @@ import {Injector, MeasureValues, Metric, Options, Reporter, Sampler, Validator, it('should call the validator for every execution and store the valid sample', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const log: any[] = []; - const validSample = [mv(null !, null !, {})]; + const validSample = [mv(null!, null!, {})]; createSampler({ metric: createCountingMetric(), @@ -174,7 +181,7 @@ import {Injector, MeasureValues, Metric, Options, Reporter, Sampler, Validator, it('should report the metric values', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const log: any[] = []; - const validSample = [mv(null !, null !, {})]; + const validSample = [mv(null!, null!, {})]; createSampler({ validator: createCountingValidator(2, validSample), metric: createCountingMetric(), @@ -198,7 +205,6 @@ import {Injector, MeasureValues, Metric, Options, Reporter, Sampler, Validator, async.done(); }); })); - }); } @@ -223,7 +229,9 @@ function createCountingMetric(log: any[] = []) { } class MockDriverAdapter extends WebDriverAdapter { - constructor(private _log: any[] = [], private _waitFor: Function|null = null) { super(); } + constructor(private _log: any[] = [], private _waitFor: Function|null = null) { + super(); + } waitFor(callback: Function): Promise { if (this._waitFor != null) { return this._waitFor(callback); @@ -235,7 +243,9 @@ class MockDriverAdapter extends WebDriverAdapter { class MockValidator extends Validator { - constructor(private _log: any[] = [], private _validate: Function|null = null) { super(); } + constructor(private _log: any[] = [], private _validate: Function|null = null) { + super(); + } validate(completeSample: MeasureValues[]): MeasureValues[] { const stableSample = this._validate != null ? this._validate(completeSample) : completeSample; this._log.push(['validate', completeSample, stableSample]); @@ -244,7 +254,9 @@ class MockValidator extends Validator { } class MockMetric extends Metric { - constructor(private _log: any[] = [], private _endMeasure: Function|null = null) { super(); } + constructor(private _log: any[] = [], private _endMeasure: Function|null = null) { + super(); + } beginMeasure() { this._log.push(['beginMeasure']); return Promise.resolve(null); @@ -257,7 +269,9 @@ class MockMetric extends Metric { } class MockReporter extends Reporter { - constructor(private _log: any[] = []) { super(); } + constructor(private _log: any[] = []) { + super(); + } reportMeasureValues(values: MeasureValues): Promise { this._log.push(['reportMeasureValues', values]); return Promise.resolve(null); diff --git a/packages/benchpress/test/statistic_spec.ts b/packages/benchpress/test/statistic_spec.ts index efbeaa8766723..9f8a90b5cadc0 100644 --- a/packages/benchpress/test/statistic_spec.ts +++ b/packages/benchpress/test/statistic_spec.ts @@ -11,7 +11,6 @@ import {Statistic} from '../src/statistic'; { describe('statistic', () => { - it('should calculate the mean', () => { expect(Statistic.calculateMean([])).toBeNaN(); expect(Statistic.calculateMean([1, 2, 3])).toBe(2.0); @@ -34,6 +33,5 @@ import {Statistic} from '../src/statistic'; expect(Statistic.calculateRegressionSlope([1], 1, [2], 2)).toBeNaN(); expect(Statistic.calculateRegressionSlope([1, 2], 1.5, [2, 4], 3)).toBe(2.0); }); - }); } diff --git a/packages/benchpress/test/trace_event_factory.ts b/packages/benchpress/test/trace_event_factory.ts index 11ce4c0b53151..e687f2b0a2092 100644 --- a/packages/benchpress/test/trace_event_factory.ts +++ b/packages/benchpress/test/trace_event_factory.ts @@ -20,13 +20,21 @@ export class TraceEventFactory { return res; } - markStart(name: string, time: number) { return this.create('B', name, time); } + markStart(name: string, time: number) { + return this.create('B', name, time); + } - markEnd(name: string, time: number) { return this.create('E', name, time); } + markEnd(name: string, time: number) { + return this.create('E', name, time); + } - start(name: string, time: number, args: any = null) { return this.create('B', name, time, args); } + start(name: string, time: number, args: any = null) { + return this.create('B', name, time, args); + } - end(name: string, time: number, args: any = null) { return this.create('E', name, time, args); } + end(name: string, time: number, args: any = null) { + return this.create('E', name, time, args); + } instant(name: string, time: number, args: any = null) { return this.create('I', name, time, args); diff --git a/packages/benchpress/test/validator/regression_slope_validator_spec.ts b/packages/benchpress/test/validator/regression_slope_validator_spec.ts index 07cc120cc906d..ceafcca4e3b22 100644 --- a/packages/benchpress/test/validator/regression_slope_validator_spec.ts +++ b/packages/benchpress/test/validator/regression_slope_validator_spec.ts @@ -53,7 +53,6 @@ import {Injector, MeasureValues, RegressionSlopeValidator} from '../../index'; expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3)); }); - }); } diff --git a/packages/benchpress/test/validator/size_validator_spec.ts b/packages/benchpress/test/validator/size_validator_spec.ts index 782b36ab1f250..aa809412bfe91 100644 --- a/packages/benchpress/test/validator/size_validator_spec.ts +++ b/packages/benchpress/test/validator/size_validator_spec.ts @@ -39,7 +39,6 @@ import {Injector, MeasureValues, SizeValidator} from '../../index'; expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3)); }); - }); } diff --git a/packages/benchpress/test/web_driver_extension_spec.ts b/packages/benchpress/test/web_driver_extension_spec.ts index 907c464eaad5c..8ec00b4355276 100644 --- a/packages/benchpress/test/web_driver_extension_spec.ts +++ b/packages/benchpress/test/web_driver_extension_spec.ts @@ -11,44 +11,45 @@ import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/te import {Injector, Options, WebDriverExtension} from '../index'; (function() { - function createExtension(ids: any[], caps: any) { - return new Promise((res, rej) => { - try { - res(Injector - .create([ - ids.map((id) => ({provide: id, useValue: new MockExtension(id)})), - {provide: Options.CAPABILITIES, useValue: caps}, - WebDriverExtension.provideFirstSupported(ids) - ]) - .get(WebDriverExtension)); - } catch (e) { - rej(e); - } - }); - } - - describe('WebDriverExtension.provideFirstSupported', () => { - - it('should provide the extension that matches the capabilities', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createExtension(['m1', 'm2', 'm3'], {'browser': 'm2'}).then((m) => { - expect(m.id).toEqual('m2'); - async.done(); - }); - })); - - it('should throw if there is no match', - inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createExtension(['m1'], {'browser': 'm2'}).catch((err) => { - expect(err != null).toBe(true); - async.done(); - }); - })); +function createExtension(ids: any[], caps: any) { + return new Promise((res, rej) => { + try { + res(Injector + .create([ + ids.map((id) => ({provide: id, useValue: new MockExtension(id)})), + {provide: Options.CAPABILITIES, useValue: caps}, + WebDriverExtension.provideFirstSupported(ids) + ]) + .get(WebDriverExtension)); + } catch (e) { + rej(e); + } }); +} + +describe('WebDriverExtension.provideFirstSupported', () => { + it('should provide the extension that matches the capabilities', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + createExtension(['m1', 'm2', 'm3'], {'browser': 'm2'}).then((m) => { + expect(m.id).toEqual('m2'); + async.done(); + }); + })); + + it('should throw if there is no match', + inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { + createExtension(['m1'], {'browser': 'm2'}).catch((err) => { + expect(err != null).toBe(true); + async.done(); + }); + })); +}); })(); class MockExtension extends WebDriverExtension { - constructor(public id: string) { super(); } + constructor(public id: string) { + super(); + } supports(capabilities: {[key: string]: any}): boolean { return capabilities['browser'] === this.id; diff --git a/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts b/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts index 988352345cdd2..1e353a05b257e 100644 --- a/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts +++ b/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts @@ -32,7 +32,7 @@ import {TraceEventFactory} from '../trace_event_factory'; const normEvents = new TraceEventFactory('timeline', 'pid0'); function createExtension( - perfRecords: any[] | null = null, userAgent: string | null = null, + perfRecords: any[]|null = null, userAgent: string|null = null, messageMethod = 'Tracing.dataCollected'): WebDriverExtension { if (!perfRecords) { perfRecords = []; @@ -97,9 +97,9 @@ import {TraceEventFactory} from '../trace_event_factory'; it('should mark the timeline via performance.mark() with start and end of a test', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { createExtension().timeEnd('name1', 'name2').then((_) => { - expect(log).toEqual([[ - 'executeScript', `performance.mark('name1-bpend');performance.mark('name2-bpstart');` - ]]); + expect(log).toEqual([ + ['executeScript', `performance.mark('name1-bpend');performance.mark('name2-bpstart');`] + ]); async.done(); }); })); @@ -173,7 +173,8 @@ import {TraceEventFactory} from '../trace_event_factory'; [ chromeTimelineV8Events.start('MajorGC', 1000, {'usedHeapSizeBefore': 1000}), chromeTimelineV8Events.end('MajorGC', 2000, {'usedHeapSizeAfter': 0}), - ], ) + ], + ) .readPerfLog() .then((events) => { expect(events.length).toEqual(2); @@ -192,7 +193,8 @@ import {TraceEventFactory} from '../trace_event_factory'; [ chrome45TimelineEvents.start(recordType, 1234), chrome45TimelineEvents.end(recordType, 2345) - ], ) + ], + ) .readPerfLog() .then((events) => { expect(events).toEqual([ @@ -210,7 +212,8 @@ import {TraceEventFactory} from '../trace_event_factory'; [ chromeBlinkTimelineEvents.start('UpdateLayoutTree', 1234), chromeBlinkTimelineEvents.end('UpdateLayoutTree', 2345) - ], ) + ], + ) .readPerfLog() .then((events) => { expect(events).toEqual([ @@ -254,8 +257,10 @@ import {TraceEventFactory} from '../trace_event_factory'; })); it('should report receivedData', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createExtension([chrome45TimelineEvents.instant( - 'ResourceReceivedData', 1234, {'data': {'encodedDataLength': 987}})], ) + createExtension( + [chrome45TimelineEvents.instant( + 'ResourceReceivedData', 1234, {'data': {'encodedDataLength': 987}})], + ) .readPerfLog() .then((events) => { expect(events).toEqual( @@ -265,9 +270,11 @@ import {TraceEventFactory} from '../trace_event_factory'; })); it('should report sendRequest', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createExtension([chrome45TimelineEvents.instant( - 'ResourceSendRequest', 1234, - {'data': {'url': 'http://here', 'requestMethod': 'GET'}})], ) + createExtension( + [chrome45TimelineEvents.instant( + 'ResourceSendRequest', 1234, + {'data': {'url': 'http://here', 'requestMethod': 'GET'}})], + ) .readPerfLog() .then((events) => { expect(events).toEqual([normEvents.instant( @@ -277,7 +284,6 @@ import {TraceEventFactory} from '../trace_event_factory'; })); describe('readPerfLog (common)', () => { - it('should execute a dummy script before reading them', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { // TODO(tbosch): This seems to be a bug in ChromeDriver: @@ -296,7 +302,8 @@ import {TraceEventFactory} from '../trace_event_factory'; [ chromeTimelineEvents.start(recordType, 1234), chromeTimelineEvents.end(recordType, 2345) - ], ) + ], + ) .readPerfLog() .then((events) => { expect(events).toEqual([ @@ -337,7 +344,6 @@ import {TraceEventFactory} from '../trace_event_factory'; it('should throw when ImplThreadRenderingStats contains more than one frame', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createExtension([benchmarkEvents.instant( 'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {'data': {'frame_count': 2}})]) @@ -349,7 +355,6 @@ import {TraceEventFactory} from '../trace_event_factory'; async.done(); }); })); - }); it('should report begin timestamps', @@ -374,7 +379,6 @@ import {TraceEventFactory} from '../trace_event_factory'; it('should throw an error on buffer overflow', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { - createExtension( [ chromeTimelineEvents.start('FunctionCall', 1234), @@ -394,9 +398,7 @@ import {TraceEventFactory} from '../trace_event_factory'; expect(createExtension().supports({'browserName': 'Chrome'})).toBe(true); }); - }); - }); } @@ -419,7 +421,7 @@ class MockDriverAdapter extends WebDriverAdapter { {'message': {'method': this._messageMethod, 'params': event}}, null, 2) }))); } else { - return null !; + return null!; } } } diff --git a/packages/benchpress/test/webdriver/ios_driver_extension_spec.ts b/packages/benchpress/test/webdriver/ios_driver_extension_spec.ts index f2edbc774015f..6e7e6de0289f1 100644 --- a/packages/benchpress/test/webdriver/ios_driver_extension_spec.ts +++ b/packages/benchpress/test/webdriver/ios_driver_extension_spec.ts @@ -8,7 +8,7 @@ import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal'; -import {IOsDriverExtension, Injector, WebDriverAdapter, WebDriverExtension} from '../../index'; +import {Injector, IOsDriverExtension, WebDriverAdapter, WebDriverExtension} from '../../index'; import {TraceEventFactory} from '../trace_event_factory'; { @@ -18,7 +18,7 @@ import {TraceEventFactory} from '../trace_event_factory'; const normEvents = new TraceEventFactory('timeline', 'pid0'); - function createExtension(perfRecords: any[] | null = null): WebDriverExtension { + function createExtension(perfRecords: any[]|null = null): WebDriverExtension { if (!perfRecords) { perfRecords = []; } @@ -63,7 +63,6 @@ import {TraceEventFactory} from '../trace_event_factory'; })); describe('readPerfLog', () => { - it('should execute a dummy script before reading them', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { // TODO(tbosch): This seems to be a bug in ChromeDriver: @@ -140,9 +139,7 @@ import {TraceEventFactory} from '../trace_event_factory'; expect(createExtension().supports({'browserName': 'Safari'})).toBe(true); }); - }); - }); } @@ -155,7 +152,7 @@ function timeEndRecord(name: string, time: number) { } function durationRecord( - type: string, startTime: number, endTime: number, children: any[] | null = null) { + type: string, startTime: number, endTime: number, children: any[]|null = null) { if (!children) { children = []; } @@ -172,7 +169,9 @@ function internalScriptRecord(startTime: number, endTime: number) { } class MockDriverAdapter extends WebDriverAdapter { - constructor(private _log: any[], private _perfRecords: any[]) { super(); } + constructor(private _log: any[], private _perfRecords: any[]) { + super(); + } executeScript(script: string) { this._log.push(['executeScript', script]); @@ -190,7 +189,7 @@ class MockDriverAdapter extends WebDriverAdapter { }; })); } else { - return null !; + return null!; } } } diff --git a/packages/common/http/src/client.ts b/packages/common/http/src/client.ts index 275fc69a77508..6814034f8b46e 100644 --- a/packages/common/http/src/client.ts +++ b/packages/common/http/src/client.ts @@ -7,7 +7,7 @@ */ import {Injectable} from '@angular/core'; -import {Observable, of } from 'rxjs'; +import {Observable, of} from 'rxjs'; import {concatMap, filter, map} from 'rxjs/operators'; import {HttpHandler} from './backend'; @@ -29,14 +29,14 @@ import {HttpEvent, HttpResponse} from './response'; */ function addBody( options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, - params?: HttpParams | {[param: string]: string | string[]}, + params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, - responseType?: 'arraybuffer' | 'blob' | 'json' | 'text', + responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean, }, - body: T | null): any { + body: T|null): any { return { body, headers: options.headers, @@ -48,7 +48,7 @@ function addBody( }; } -export type HttpObserve = 'body' | 'events' | 'response'; +export type HttpObserve = 'body'|'events'|'response'; /** * Performs HTTP requests. @@ -108,8 +108,8 @@ export class HttpClient { request(req: HttpRequest): Observable>; /** - * Constructs a request that interprets the body as an `ArrayBuffer` and returns the response in an - * `ArrayBuffer`. + * Constructs a request that interprets the body as an `ArrayBuffer` and returns the response in + * an `ArrayBuffer`. * * @param method The HTTP method. * @param url The endpoint URL. @@ -123,8 +123,8 @@ export class HttpClient { headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; /** @@ -142,8 +142,8 @@ export class HttpClient { headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -161,8 +161,8 @@ export class HttpClient { headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -173,15 +173,16 @@ export class HttpClient { * @param url The endpoint URL. * @param options The HTTP options to send with the request. * - * @return An `Observable` of the response, with the response body as an array of `HTTPEvents` for the + * @return An `Observable` of the response, with the response body as an array of `HTTPEvents` for + * the * request. */ request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, - params?: HttpParams|{[param: string]: string | string[]}, - observe: 'events', reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + params?: HttpParams|{[param: string]: string | string[]}, observe: 'events', + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -197,15 +198,15 @@ export class HttpClient { */ request(method: string, url: string, options: { body?: any, - headers?: HttpHeaders|{[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** - * Constructs a request which interprets the body as a text string and returns the full event stream. + * Constructs a request which interprets the body as a text string and returns the full event + * stream. * * @param method The HTTP method. * @param url The endpoint URL. @@ -216,15 +217,15 @@ export class HttpClient { */ request(method: string, url: string, options: { body?: any, - headers?: HttpHeaders|{[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** - * Constructs a request which interprets the body as a JSON object and returns the full event stream. + * Constructs a request which interprets the body as a JSON object and returns the full event + * stream. * * @param method The HTTP method. * @param url The endpoint URL. @@ -236,15 +237,15 @@ export class HttpClient { request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, - reportProgress?: boolean, - observe: 'events', + reportProgress?: boolean, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, responseType?: 'json', withCredentials?: boolean, }): Observable>; /** - * Constructs a request which interprets the body as a JSON object and returns the full event stream. + * Constructs a request which interprets the body as a JSON object and returns the full event + * stream. * * @param method The HTTP method. * @param url The endpoint URL. @@ -256,8 +257,7 @@ export class HttpClient { request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, - reportProgress?: boolean, - observe: 'events', + reportProgress?: boolean, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, responseType?: 'json', withCredentials?: boolean, @@ -275,11 +275,10 @@ export class HttpClient { */ request(method: string, url: string, options: { body?: any, - headers?: HttpHeaders|{[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -293,15 +292,15 @@ export class HttpClient { */ request(method: string, url: string, options: { body?: any, - headers?: HttpHeaders|{[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** - * Constructs a request which interprets the body as a text stream and returns the full `HTTPResponse`. + * Constructs a request which interprets the body as a text stream and returns the full + * `HTTPResponse`. * * @param method The HTTP method. * @param url The endpoint URL. @@ -311,15 +310,15 @@ export class HttpClient { */ request(method: string, url: string, options: { body?: any, - headers?: HttpHeaders|{[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** - * Constructs a request which interprets the body as a JSON object and returns the full `HTTPResponse`. + * Constructs a request which interprets the body as a JSON object and returns the full + * `HTTPResponse`. * * @param method The HTTP method. * @param url The endpoint URL. @@ -331,8 +330,7 @@ export class HttpClient { request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, - reportProgress?: boolean, - observe: 'response', + reportProgress?: boolean, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, responseType?: 'json', withCredentials?: boolean, @@ -351,8 +349,7 @@ export class HttpClient { request(method: string, url: string, options: { body?: any, headers?: HttpHeaders|{[header: string]: string | string[]}, - reportProgress?: boolean, - observe: 'response', + reportProgress?: boolean, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, responseType?: 'json', withCredentials?: boolean, @@ -477,12 +474,12 @@ export class HttpClient { if (options.params instanceof HttpParams) { params = options.params; } else { - params = new HttpParams({ fromObject: options.params } as HttpParamsOptions); + params = new HttpParams({fromObject: options.params} as HttpParamsOptions); } } // Construct the request. - req = new HttpRequest(first, url !, (options.body !== undefined ? options.body : null), { + req = new HttpRequest(first, url!, (options.body !== undefined ? options.body : null), { headers, params, reportProgress: options.reportProgress, @@ -497,7 +494,7 @@ export class HttpClient { // inside an Observable chain, which causes interceptors to be re-run on every // subscription (this also makes retries re-run the handler, including interceptors). const events$: Observable> = - of (req).pipe(concatMap((req: HttpRequest) => this.handler.handle(req))); + of(req).pipe(concatMap((req: HttpRequest) => this.handler.handle(req))); // If coming via the API signature which accepts a previously constructed HttpRequest, // the only option is to get the event stream. Otherwise, return the event stream if @@ -568,12 +565,12 @@ export class HttpClient { * * @return An `Observable` of the response body as an `ArrayBuffer`. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; @@ -586,12 +583,12 @@ export class HttpClient { * * @return An `Observable` of the response body as a `Blob`. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -603,12 +600,12 @@ export class HttpClient { * * @return An `Observable` of the response, with the response body of type string. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -621,12 +618,11 @@ export class HttpClient { * @return An `Observable` of all `HTTPEvents` for the request, * with response body as an `ArrayBuffer`. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -639,12 +635,11 @@ export class HttpClient { * @return An `Observable` of all the `HTTPEvents` for the request, with the response body as a * `Blob`. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -657,12 +652,11 @@ export class HttpClient { * @return An `Observable` of all `HTTPEvents` for the request, with the response * body of type string. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -675,9 +669,8 @@ export class HttpClient { * @return An `Observable` of all `HTTPEvents` for the request, with response body of * type `Object`. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -695,8 +688,7 @@ export class HttpClient { * body in the requested type. */ delete(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -712,12 +704,11 @@ export class HttpClient { * * @return An `Observable` of the full `HTTPResponse`, with the response body as an `ArrayBuffer`. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -729,12 +720,11 @@ export class HttpClient { * * @return An `Observable` of the `HTTPResponse`, with the response body of type `Blob`. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -746,12 +736,11 @@ export class HttpClient { * * @return An `Observable` of the full `HTTPResponse`, with the response body of type string. */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -764,9 +753,8 @@ export class HttpClient { * @return An `Observable` of the `HTTPResponse`, with the response body of type `Object`. * */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -783,8 +771,7 @@ export class HttpClient { * @return An `Observable` of the `HTTPResponse`, with the response body of the requested type. */ delete(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -800,8 +787,8 @@ export class HttpClient { * * @return An `Observable` of the response, with the response body of type `Object`. */ - delete (url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + delete(url: string, options?: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -819,7 +806,7 @@ export class HttpClient { * @return An `Observable` of the `HTTPResponse`, with response body in the requested type. */ delete(url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -836,8 +823,8 @@ export class HttpClient { * @param options The HTTP options to send with the request. * */ - delete (url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + delete(url: string, options: { + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -849,8 +836,8 @@ export class HttpClient { /** - * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the response in - * an `ArrayBuffer`. + * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the + * response in an `ArrayBuffer`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. @@ -858,11 +845,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; /** @@ -875,11 +862,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a `Blob`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -892,11 +879,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body of type string. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -910,11 +897,10 @@ export class HttpClient { * body as an `ArrayBuffer`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -927,11 +913,10 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a `Blob`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -944,11 +929,10 @@ export class HttpClient { * @return An `Observable` of the response, with the response body of type string. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -961,8 +945,7 @@ export class HttpClient { * @return An `Observable` of the response, with the response body of type `Object`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -970,7 +953,8 @@ export class HttpClient { }): Observable>; /** - * Constructs a `GET` request that interprets the body as a JSON object and returns the full event stream. + * Constructs a `GET` request that interprets the body as a JSON object and returns the full event + * stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. @@ -978,8 +962,7 @@ export class HttpClient { * @return An `Observable` of the response, with a response body in the requested type. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -997,11 +980,10 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -1015,11 +997,10 @@ export class HttpClient { * with the response body as a `Blob`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -1033,11 +1014,10 @@ export class HttpClient { * with the response body of type string. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -1051,8 +1031,7 @@ export class HttpClient { * with the response body of type `Object`. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1070,8 +1049,7 @@ export class HttpClient { * with a response body in the requested type. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1089,7 +1067,7 @@ export class HttpClient { * @return An `Observable` of the response body as a JSON object. */ get(url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1107,7 +1085,7 @@ export class HttpClient { * @return An `Observable` of the `HTTPResponse`, with a response body in the requested type. */ get(url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1121,7 +1099,7 @@ export class HttpClient { * details on the return type. */ get(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1142,11 +1120,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; /** @@ -1160,11 +1138,11 @@ export class HttpClient { */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -1177,11 +1155,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body of type string. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -1195,11 +1173,10 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -1213,11 +1190,10 @@ export class HttpClient { * with the response body as a `Blob`. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -1227,14 +1203,14 @@ export class HttpClient { * @param url The endpoint URL. * @param options The HTTP options to send with the request. * - * @return An `Observable` of all HttpEvents for the request, with the response body of type string. + * @return An `Observable` of all HttpEvents for the request, with the response body of type + * string. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -1248,8 +1224,7 @@ export class HttpClient { * type `Object`. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1267,8 +1242,7 @@ export class HttpClient { * @param options The HTTP options to send with the request. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1286,11 +1260,10 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -1304,11 +1277,10 @@ export class HttpClient { * with the response body as a blob. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -1322,11 +1294,10 @@ export class HttpClient { * with the response body of type string. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -1340,8 +1311,7 @@ export class HttpClient { * with the response body of type `Object`. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1359,8 +1329,7 @@ export class HttpClient { * with a responmse body of the requested type. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1377,7 +1346,7 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a JSON object. */ head(url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1396,7 +1365,7 @@ export class HttpClient { * with a response body of the given type. */ head(url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1412,7 +1381,7 @@ export class HttpClient { * details on the return type. */ head(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1482,11 +1451,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; /** @@ -1499,11 +1468,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a `Blob`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -1516,11 +1485,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body of type string. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -1534,11 +1503,10 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -1552,11 +1520,10 @@ export class HttpClient { * with the response body as a `Blob`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -1570,11 +1537,10 @@ export class HttpClient { * with the response body of type string. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -1588,8 +1554,7 @@ export class HttpClient { * body of type `Object`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1607,8 +1572,7 @@ export class HttpClient { * with a response body in the requested type. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1626,11 +1590,10 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -1644,11 +1607,10 @@ export class HttpClient { * with the response body as a `Blob`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -1662,11 +1624,10 @@ export class HttpClient { * with the response body of type string. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -1680,8 +1641,7 @@ export class HttpClient { * with the response body of type `Object`. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1699,8 +1659,7 @@ export class HttpClient { * with a response body in the requested type. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1708,8 +1667,8 @@ export class HttpClient { }): Observable>; /** - * Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the response - * body as a JSON object. + * Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the + * response body as a JSON object. * * @param url The endpoint URL. * @param options HTTP options. @@ -1717,7 +1676,7 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a JSON object. */ options(url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1726,8 +1685,8 @@ export class HttpClient { }): Observable; /** - * Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the response - * in a given type. + * Constructs an `OPTIONS` request that interprets the body as a JSON object and returns the + * response in a given type. * * @param url The endpoint URL. * @param options HTTP options. @@ -1735,7 +1694,7 @@ export class HttpClient { * @return An `Observable` of the `HTTPResponse`, with a response body of the given type. */ options(url: string, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1751,7 +1710,7 @@ export class HttpClient { * details on the return type. */ options(url: string, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -1772,11 +1731,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; /** @@ -1790,11 +1749,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a `Blob`. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -1808,11 +1767,11 @@ export class HttpClient { * @return An `Observable` of the response, with a response body of type string. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -1828,11 +1787,10 @@ export class HttpClient { */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -1847,11 +1805,10 @@ export class HttpClient { * response body as `Blob`. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -1866,11 +1823,10 @@ export class HttpClient { * response body of type string. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -1885,8 +1841,7 @@ export class HttpClient { * with a response body of type `Object`. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1905,8 +1860,7 @@ export class HttpClient { * with a response body in the requested type. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -1925,11 +1879,10 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -1944,11 +1897,10 @@ export class HttpClient { * with the response body as a `Blob`. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -1963,11 +1915,10 @@ export class HttpClient { * with a response body of type string. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -1982,8 +1933,7 @@ export class HttpClient { * with a response body in the requested type. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2002,8 +1952,7 @@ export class HttpClient { * with a response body in the given type. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2021,7 +1970,7 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a JSON object. */ patch(url: string, body: any|null, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2041,7 +1990,7 @@ export class HttpClient { * with a response body in the given type. */ patch(url: string, body: any|null, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2055,7 +2004,7 @@ export class HttpClient { * details on the return type. */ patch(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2076,11 +2025,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; /** @@ -2094,11 +2043,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a `Blob`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -2112,11 +2061,11 @@ export class HttpClient { * @return An `Observable` of the response, with a response body of type string. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -2131,11 +2080,10 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -2149,15 +2097,15 @@ export class HttpClient { * @return An `Observable` of all `HttpEvents` for the request, with the response body as `Blob`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** - * Constructs a `POST` request that interprets the body as a text string and returns the full event stream. + * Constructs a `POST` request that interprets the body as a text string and returns the full + * event stream. * * @param url The endpoint URL. * @param body The content to replace with. @@ -2167,15 +2115,15 @@ export class HttpClient { * with a response body of type string. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** - * Constructs a POST request that interprets the body as a JSON object and returns the full event stream. + * Constructs a POST request that interprets the body as a JSON object and returns the full event + * stream. * * @param url The endpoint URL. * @param body The content to replace with. @@ -2185,8 +2133,7 @@ export class HttpClient { * with a response body of type `Object`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2194,7 +2141,8 @@ export class HttpClient { }): Observable>; /** - * Constructs a POST request that interprets the body as a JSON object and returns the full event stream. + * Constructs a POST request that interprets the body as a JSON object and returns the full event + * stream. * * @param url The endpoint URL. * @param body The content to replace with. @@ -2204,8 +2152,7 @@ export class HttpClient { * with a response body in the requested type. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2220,14 +2167,14 @@ export class HttpClient { * @param body The content to replace with. * @param options HTTP options * - * @return An `Observable` of the `HTTPResponse` for the request, with the response body as an `ArrayBuffer`. + * @return An `Observable` of the `HTTPResponse` for the request, with the response body as an + * `ArrayBuffer`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -2242,11 +2189,10 @@ export class HttpClient { * with the response body as a `Blob`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -2261,11 +2207,10 @@ export class HttpClient { * with a response body of type string. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** @@ -2280,8 +2225,7 @@ export class HttpClient { * `Object`. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2297,11 +2241,11 @@ export class HttpClient { * @param body The content to replace with. * @param options HTTP options * - * @return An `Observable` of the `HTTPResponse` for the request, with a response body in the requested type. + * @return An `Observable` of the `HTTPResponse` for the request, with a response body in the + * requested type. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2319,7 +2263,7 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a JSON object. */ post(url: string, body: any|null, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2335,10 +2279,11 @@ export class HttpClient { * @param body The content to replace with. * @param options HTTP options * - * @return An `Observable` of the `HTTPResponse` for the request, with a response body in the requested type. + * @return An `Observable` of the `HTTPResponse` for the request, with a response body in the + * requested type. */ post(url: string, body: any|null, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2353,7 +2298,7 @@ export class HttpClient { * details on the return type. */ post(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2374,11 +2319,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable; /** @@ -2392,11 +2337,11 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a `Blob`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable; /** @@ -2410,11 +2355,11 @@ export class HttpClient { * @return An `Observable` of the response, with a response body of type string. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable; /** @@ -2429,15 +2374,15 @@ export class HttpClient { * with the response body as an `ArrayBuffer`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** - * Constructs a `PUT` request that interprets the body as a `Blob` and returns the full event stream. + * Constructs a `PUT` request that interprets the body as a `Blob` and returns the full event + * stream. * * @param url The endpoint URL. * @param body The resources to add/update. @@ -2447,15 +2392,15 @@ export class HttpClient { * with the response body as a `Blob`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** - * Constructs a `PUT` request that interprets the body as a text string and returns the full event stream. + * Constructs a `PUT` request that interprets the body as a text string and returns the full event + * stream. * * @param url The endpoint URL. * @param body The resources to add/update. @@ -2465,15 +2410,15 @@ export class HttpClient { * of type string. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** - * Constructs a `PUT` request that interprets the body as a JSON object and returns the full event stream. + * Constructs a `PUT` request that interprets the body as a JSON object and returns the full event + * stream. * * @param url The endpoint URL. * @param body The resources to add/update. @@ -2483,8 +2428,7 @@ export class HttpClient { * type `Object`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2503,8 +2447,9 @@ export class HttpClient { * with a response body in the requested type. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'events', responseType?: 'json', withCredentials?: boolean, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events', + responseType?: 'json', + withCredentials?: boolean, }): Observable>; /** @@ -2515,14 +2460,14 @@ export class HttpClient { * @param body The resources to add/update. * @param options HTTP options * - * @return An `Observable` of the `HTTPResponse` for the request, with the response body as an `ArrayBuffer`. + * @return An `Observable` of the `HTTPResponse` for the request, with the response body as an + * `ArrayBuffer`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'arraybuffer', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'arraybuffer', + withCredentials?: boolean, }): Observable>; /** @@ -2537,11 +2482,10 @@ export class HttpClient { * with the response body as a `Blob`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'blob', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'blob', + withCredentials?: boolean, }): Observable>; /** @@ -2552,18 +2496,19 @@ export class HttpClient { * @param body The resources to add/update. * @param options HTTP options * - * @return An `Observable` of the `HTTPResponse` for the request, with a response body of type string. + * @return An `Observable` of the `HTTPResponse` for the request, with a response body of type + * string. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, - reportProgress?: boolean, - responseType: 'text', withCredentials?: boolean, + reportProgress?: boolean, responseType: 'text', + withCredentials?: boolean, }): Observable>; /** - * Constructs a `PUT` request that interprets the body as a JSON object and returns the full HTTP response. + * Constructs a `PUT` request that interprets the body as a JSON object and returns the full HTTP + * response. * * @param url The endpoint URL. * @param body The resources to add/update. @@ -2573,8 +2518,7 @@ export class HttpClient { * of type 'Object`. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2582,7 +2526,8 @@ export class HttpClient { }): Observable>; /** - * Constructs a `PUT` request that interprets the body as a JSON object and returns the full HTTP response. + * Constructs a `PUT` request that interprets the body as a JSON object and returns the full HTTP + * response. * * @param url The endpoint URL. * @param body The resources to add/update. @@ -2592,8 +2537,7 @@ export class HttpClient { * with a response body in the requested type. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, - observe: 'response', + headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'response', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, responseType?: 'json', @@ -2611,7 +2555,7 @@ export class HttpClient { * @return An `Observable` of the response, with the response body as a JSON object. */ put(url: string, body: any|null, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2627,10 +2571,11 @@ export class HttpClient { * @param body The resources to add/update. * @param options HTTP options * - * @return An `Observable` of the `HTTPResponse` for the request, with a response body in the requested type. + * @return An `Observable` of the `HTTPResponse` for the request, with a response body in the + * requested type. */ put(url: string, body: any|null, options?: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: 'body', params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, @@ -2645,7 +2590,7 @@ export class HttpClient { * See the individual overloads for details on the return type. */ put(url: string, body: any|null, options: { - headers?: HttpHeaders | {[header: string]: string | string[]}, + headers?: HttpHeaders|{[header: string]: string | string[]}, observe?: HttpObserve, params?: HttpParams|{[param: string]: string | string[]}, reportProgress?: boolean, diff --git a/packages/common/http/src/headers.ts b/packages/common/http/src/headers.ts index a8a006d467e7b..6e187c3adabf7 100755 --- a/packages/common/http/src/headers.ts +++ b/packages/common/http/src/headers.ts @@ -24,7 +24,7 @@ export class HttpHeaders { * Internal map of lowercase header names to values. */ // TODO(issue/24571): remove '!'. - private headers !: Map; + private headers!: Map; /** @@ -36,7 +36,7 @@ export class HttpHeaders { /** * Complete the lazy initialization of this object (needed before reading). */ - private lazyInit !: HttpHeaders | Function | null; + private lazyInit!: HttpHeaders|Function|null; /** * Queued updates to be materialized the next initialization. @@ -59,7 +59,7 @@ export class HttpHeaders { const value = line.slice(index + 1).trim(); this.maybeSetNormalizedName(name, key); if (this.headers.has(key)) { - this.headers.get(key) !.push(value); + this.headers.get(key)!.push(value); } else { this.headers.set(key, [value]); } @@ -169,7 +169,7 @@ export class HttpHeaders { * * @returns A clone of the HTTP headers object with the given value deleted. */ - delete (name: string, value?: string|string[]): HttpHeaders { + delete(name: string, value?: string|string[]): HttpHeaders { return this.clone({name, value, op: 'd'}); } @@ -197,8 +197,8 @@ export class HttpHeaders { private copyFrom(other: HttpHeaders) { other.init(); Array.from(other.headers.keys()).forEach(key => { - this.headers.set(key, other.headers.get(key) !); - this.normalizedNames.set(key, other.normalizedNames.get(key) !); + this.headers.set(key, other.headers.get(key)!); + this.normalizedNames.set(key, other.normalizedNames.get(key)!); }); } @@ -215,7 +215,7 @@ export class HttpHeaders { switch (update.op) { case 'a': case 's': - let value = update.value !; + let value = update.value!; if (typeof value === 'string') { value = [value]; } @@ -255,6 +255,6 @@ export class HttpHeaders { forEach(fn: (name: string, values: string[]) => void) { this.init(); Array.from(this.normalizedNames.keys()) - .forEach(key => fn(this.normalizedNames.get(key) !, this.headers.get(key) !)); + .forEach(key => fn(this.normalizedNames.get(key)!, this.headers.get(key)!)); } } diff --git a/packages/common/http/src/interceptor.ts b/packages/common/http/src/interceptor.ts index 0f71d46eb44b2..5f83c1421230e 100644 --- a/packages/common/http/src/interceptor.ts +++ b/packages/common/http/src/interceptor.ts @@ -38,8 +38,8 @@ import {HttpEvent} from './response'; * To use the same instance of `HttpInterceptors` for the entire app, import the `HttpClientModule` * only in your `AppModule`, and add the interceptors to the root application injector . * If you import `HttpClientModule` multiple times across different modules (for example, in lazy - * loading modules), each import creates a new copy of the `HttpClientModule`, which overwrites the interceptors - * provided in the root module. + * loading modules), each import creates a new copy of the `HttpClientModule`, which overwrites the + * interceptors provided in the root module. * */ export interface HttpInterceptor { diff --git a/packages/common/http/src/jsonp.ts b/packages/common/http/src/jsonp.ts index b613434039a8e..7a6c9311e4775 100644 --- a/packages/common/http/src/jsonp.ts +++ b/packages/common/http/src/jsonp.ts @@ -36,7 +36,9 @@ export const JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json respo * * */ -export abstract class JsonpCallbackContext { [key: string]: (data: any) => void; } +export abstract class JsonpCallbackContext { + [key: string]: (data: any) => void; +} /** * Processes an `HttpRequest` with the JSONP method, @@ -53,7 +55,9 @@ export class JsonpClientBackend implements HttpBackend { /** * Get the name of the next callback method, by incrementing the global `nextRequestId`. */ - private nextCallback(): string { return `ng_jsonp_callback_${nextRequestId++}`; } + private nextCallback(): string { + return `ng_jsonp_callback_${nextRequestId++}`; + } /** * Processes a JSONP request and returns an event stream of the results. @@ -157,7 +161,8 @@ export class JsonpClientBackend implements HttpBackend { observer.next(new HttpResponse({ body, status: 200, - statusText: 'OK', url, + statusText: 'OK', + url, })); // Complete the stream, the response is over. @@ -178,7 +183,8 @@ export class JsonpClientBackend implements HttpBackend { observer.error(new HttpErrorResponse({ error, status: 0, - statusText: 'JSONP Error', url, + statusText: 'JSONP Error', + url, })); }; diff --git a/packages/common/http/src/module.ts b/packages/common/http/src/module.ts index 9225814ac66ae..33460638ef5e8 100644 --- a/packages/common/http/src/module.ts +++ b/packages/common/http/src/module.ts @@ -52,7 +52,7 @@ export class HttpInterceptingHandler implements HttpHandler { * */ export function interceptingHandler( - backend: HttpBackend, interceptors: HttpInterceptor[] | null = []): HttpHandler { + backend: HttpBackend, interceptors: HttpInterceptor[]|null = []): HttpHandler { if (!interceptors) { return backend; } diff --git a/packages/common/http/src/params.ts b/packages/common/http/src/params.ts index 30caa33cdec79..1e0ab81e9f4bb 100755 --- a/packages/common/http/src/params.ts +++ b/packages/common/http/src/params.ts @@ -37,28 +37,36 @@ export class HttpUrlEncodingCodec implements HttpParameterCodec { * @param key The key name. * @returns The encoded key name. */ - encodeKey(key: string): string { return standardEncoding(key); } + encodeKey(key: string): string { + return standardEncoding(key); + } /** * Encodes the value of a URL parameter or query-string. * @param value The value. * @returns The encoded value. */ - encodeValue(value: string): string { return standardEncoding(value); } + encodeValue(value: string): string { + return standardEncoding(value); + } /** * Decodes an encoded URL parameter or query-string key. * @param key The encoded key name. * @returns The decoded key name. */ - decodeKey(key: string): string { return decodeURIComponent(key); } + decodeKey(key: string): string { + return decodeURIComponent(key); + } /** * Decodes an encoded URL parameter or query-string value. * @param value The encoded value. * @returns The decoded value. */ - decodeValue(value: string) { return decodeURIComponent(value); } + decodeValue(value: string) { + return decodeURIComponent(value); + } } @@ -97,7 +105,8 @@ interface Update { op: 'a'|'d'|'s'; } -/** Options used to construct an `HttpParams` instance. +/** + * Options used to construct an `HttpParams` instance. * * @publicApi */ @@ -109,7 +118,7 @@ export interface HttpParamsOptions { fromString?: string; /** Object map of the HTTP parameters. Mutually exclusive with `fromString`. */ - fromObject?: {[param: string]: string | ReadonlyArray}; + fromObject?: {[param: string]: string|ReadonlyArray}; /** Encoding codec used to parse and serialize the parameters. */ encoder?: HttpParameterCodec; @@ -140,7 +149,7 @@ export class HttpParams { this.map = new Map(); Object.keys(options.fromObject).forEach(key => { const value = (options.fromObject as any)[key]; - this.map !.set(key, Array.isArray(value) ? value : [value]); + this.map!.set(key, Array.isArray(value) ? value : [value]); }); } else { this.map = null; @@ -155,7 +164,7 @@ export class HttpParams { */ has(param: string): boolean { this.init(); - return this.map !.has(param); + return this.map!.has(param); } /** @@ -166,7 +175,7 @@ export class HttpParams { */ get(param: string): string|null { this.init(); - const res = this.map !.get(param); + const res = this.map!.get(param); return !!res ? res[0] : null; } @@ -178,7 +187,7 @@ export class HttpParams { */ getAll(param: string): string[]|null { this.init(); - return this.map !.get(param) || null; + return this.map!.get(param) || null; } /** @@ -187,7 +196,7 @@ export class HttpParams { */ keys(): string[] { this.init(); - return Array.from(this.map !.keys()); + return Array.from(this.map!.keys()); } /** @@ -196,7 +205,9 @@ export class HttpParams { * @param value The new value to add. * @return A new body with the appended value. */ - append(param: string, value: string): HttpParams { return this.clone({param, value, op: 'a'}); } + append(param: string, value: string): HttpParams { + return this.clone({param, value, op: 'a'}); + } /** * Replaces the value for a parameter. @@ -204,7 +215,9 @@ export class HttpParams { * @param value The new value. * @return A new body with the new value. */ - set(param: string, value: string): HttpParams { return this.clone({param, value, op: 's'}); } + set(param: string, value: string): HttpParams { + return this.clone({param, value, op: 's'}); + } /** * Removes a given value or all values from a parameter. @@ -213,7 +226,9 @@ export class HttpParams { * @return A new body with the given value removed, or with all values * removed if no value is specified. */ - delete (param: string, value?: string): HttpParams { return this.clone({param, value, op: 'd'}); } + delete(param: string, value?: string): HttpParams { + return this.clone({param, value, op: 'd'}); + } /** * Serializes the body to an encoded string, where key-value pairs (separated by `=`) are @@ -227,7 +242,7 @@ export class HttpParams { // `a: ['1']` produces `'a=1'` // `b: []` produces `''` // `c: ['1', '2']` produces `'c=1&c=2'` - return this.map !.get(key) !.map(value => eKey + '=' + this.encoder.encodeValue(value)) + return this.map!.get(key)!.map(value => eKey + '=' + this.encoder.encodeValue(value)) .join('&'); }) // filter out empty values because `b: []` produces `''` @@ -237,7 +252,7 @@ export class HttpParams { } private clone(update: Update): HttpParams { - const clone = new HttpParams({ encoder: this.encoder } as HttpParamsOptions); + const clone = new HttpParams({encoder: this.encoder} as HttpParamsOptions); clone.cloneFrom = this.cloneFrom || this; clone.updates = (this.updates || []).concat([update]); return clone; @@ -249,29 +264,29 @@ export class HttpParams { } if (this.cloneFrom !== null) { this.cloneFrom.init(); - this.cloneFrom.keys().forEach(key => this.map !.set(key, this.cloneFrom !.map !.get(key) !)); - this.updates !.forEach(update => { + this.cloneFrom.keys().forEach(key => this.map!.set(key, this.cloneFrom!.map!.get(key)!)); + this.updates!.forEach(update => { switch (update.op) { case 'a': case 's': - const base = (update.op === 'a' ? this.map !.get(update.param) : undefined) || []; - base.push(update.value !); - this.map !.set(update.param, base); + const base = (update.op === 'a' ? this.map!.get(update.param) : undefined) || []; + base.push(update.value!); + this.map!.set(update.param, base); break; case 'd': if (update.value !== undefined) { - let base = this.map !.get(update.param) || []; + let base = this.map!.get(update.param) || []; const idx = base.indexOf(update.value); if (idx !== -1) { base.splice(idx, 1); } if (base.length > 0) { - this.map !.set(update.param, base); + this.map!.set(update.param, base); } else { - this.map !.delete(update.param); + this.map!.delete(update.param); } } else { - this.map !.delete(update.param); + this.map!.delete(update.param); break; } } diff --git a/packages/common/http/src/request.ts b/packages/common/http/src/request.ts index b641daad9b4a0..12409680ce357 100644 --- a/packages/common/http/src/request.ts +++ b/packages/common/http/src/request.ts @@ -89,7 +89,7 @@ export class HttpRequest { * Outgoing headers for this request. */ // TODO(issue/24571): remove '!'. - readonly headers !: HttpHeaders; + readonly headers!: HttpHeaders; /** * Whether this request should be made in a way that exposes progress events. @@ -121,7 +121,7 @@ export class HttpRequest { * Outgoing URL parameters. */ // TODO(issue/24571): remove '!'. - readonly params !: HttpParams; + readonly params!: HttpParams; /** * The outgoing URL with all URL parameters set. @@ -312,7 +312,7 @@ export class HttpRequest { body?: T|null, method?: string, url?: string, - setHeaders?: {[name: string]: string | string[]}, + setHeaders?: {[name: string]: string|string[]}, setParams?: {[param: string]: string}, }): HttpRequest; clone(update: { @@ -324,7 +324,7 @@ export class HttpRequest { body?: V|null, method?: string, url?: string, - setHeaders?: {[name: string]: string | string[]}, + setHeaders?: {[name: string]: string|string[]}, setParams?: {[param: string]: string}, }): HttpRequest; clone(update: { @@ -336,7 +336,7 @@ export class HttpRequest { body?: any|null, method?: string, url?: string, - setHeaders?: {[name: string]: string | string[]}, + setHeaders?: {[name: string]: string|string[]}, setParams?: {[param: string]: string}; } = {}): HttpRequest { // For method, url, and responseType, take the current value unless @@ -368,20 +368,23 @@ export class HttpRequest { // Set every requested header. headers = Object.keys(update.setHeaders) - .reduce((headers, name) => headers.set(name, update.setHeaders ![name]), headers); + .reduce((headers, name) => headers.set(name, update.setHeaders![name]), headers); } // Check whether the caller has asked to set params. if (update.setParams) { // Set every requested param. params = Object.keys(update.setParams) - .reduce((params, param) => params.set(param, update.setParams ![param]), params); + .reduce((params, param) => params.set(param, update.setParams![param]), params); } // Finally, construct the new HttpRequest using the pieces from above. - return new HttpRequest( - method, url, body, { - params, headers, reportProgress, responseType, withCredentials, - }); + return new HttpRequest(method, url, body, { + params, + headers, + reportProgress, + responseType, + withCredentials, + }); } } diff --git a/packages/common/http/src/response.ts b/packages/common/http/src/response.ts index 35af00813d524..d41d7aeef7a89 100644 --- a/packages/common/http/src/response.ts +++ b/packages/common/http/src/response.ts @@ -100,7 +100,9 @@ export interface HttpUploadProgressEvent extends HttpProgressEvent { * * @publicApi */ -export interface HttpSentEvent { type: HttpEventType.Sent; } +export interface HttpSentEvent { + type: HttpEventType.Sent; +} /** * A user-defined event. @@ -110,7 +112,9 @@ export interface HttpSentEvent { type: HttpEventType.Sent; } * * @publicApi */ -export interface HttpUserEvent { type: HttpEventType.User; } +export interface HttpUserEvent { + type: HttpEventType.User; +} /** * An error that represents a failed attempt to JSON.parse text coming back @@ -133,7 +137,7 @@ export interface HttpJsonParseError { * @publicApi */ export type HttpEvent = - HttpSentEvent | HttpHeaderResponse | HttpResponse| HttpProgressEvent | HttpUserEvent; + HttpSentEvent|HttpHeaderResponse|HttpResponse|HttpProgressEvent|HttpUserEvent; /** * Base class for both `HttpResponse` and `HttpHeaderResponse`. @@ -172,7 +176,7 @@ export abstract class HttpResponseBase { * Type of the response, narrowed to either the full response or the header. */ // TODO(issue/24571): remove '!'. - readonly type !: HttpEventType.Response | HttpEventType.ResponseHeader; + readonly type!: HttpEventType.Response|HttpEventType.ResponseHeader; /** * Super-constructor for all responses. @@ -260,7 +264,11 @@ export class HttpResponse extends HttpResponseBase { * Construct a new `HttpResponse`. */ constructor(init: { - body?: T | null, headers?: HttpHeaders; status?: number; statusText?: string; url?: string; + body?: T|null, + headers?: HttpHeaders; + status?: number; + statusText?: string; + url?: string; } = {}) { super(init); this.body = init.body !== undefined ? init.body : null; @@ -272,10 +280,18 @@ export class HttpResponse extends HttpResponseBase { clone(update: {headers?: HttpHeaders; status?: number; statusText?: string; url?: string;}): HttpResponse; clone(update: { - body?: V | null, headers?: HttpHeaders; status?: number; statusText?: string; url?: string; + body?: V|null, + headers?: HttpHeaders; + status?: number; + statusText?: string; + url?: string; }): HttpResponse; clone(update: { - body?: any | null; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; + body?: any|null; + headers?: HttpHeaders; + status?: number; + statusText?: string; + url?: string; } = {}): HttpResponse { return new HttpResponse({ body: (update.body !== undefined) ? update.body : this.body, @@ -311,7 +327,11 @@ export class HttpErrorResponse extends HttpResponseBase implements Error { readonly ok = false; constructor(init: { - error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; + error?: any; + headers?: HttpHeaders; + status?: number; + statusText?: string; + url?: string; }) { // Initialize with a default status of 0 / Unknown Error. super(init, 0, 'Unknown Error'); @@ -322,8 +342,8 @@ export class HttpErrorResponse extends HttpResponseBase implements Error { if (this.status >= 200 && this.status < 300) { this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`; } else { - this.message = - `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${init.statusText}`; + this.message = `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${ + init.statusText}`; } this.error = init.error || null; } diff --git a/packages/common/http/src/xhr.ts b/packages/common/http/src/xhr.ts index b1c00e3249903..f0e4eb9a81860 100644 --- a/packages/common/http/src/xhr.ts +++ b/packages/common/http/src/xhr.ts @@ -35,7 +35,9 @@ function getResponseUrl(xhr: any): string|null { * * @publicApi */ -export abstract class XhrFactory { abstract build(): XMLHttpRequest; } +export abstract class XhrFactory { + abstract build(): XMLHttpRequest; +} /** * A factory for `HttpXhrBackend` that uses the `XMLHttpRequest` browser API. @@ -44,7 +46,9 @@ export abstract class XhrFactory { abstract build(): XMLHttpRequest; } @Injectable() export class BrowserXhr implements XhrFactory { constructor() {} - build(): any { return (new XMLHttpRequest()); } + build(): any { + return (new XMLHttpRequest()); + } } /** @@ -200,7 +204,7 @@ export class HttpXhrBackend implements HttpBackend { // Even though the response status was 2xx, this is still an error. ok = false; // The parse error contains the text of the body that failed to parse. - body = { error, text: body } as HttpJsonParseError; + body = {error, text: body} as HttpJsonParseError; } } } @@ -318,7 +322,7 @@ export class HttpXhrBackend implements HttpBackend { } // Fire the request, and notify the event stream that it was fired. - xhr.send(reqBody !); + xhr.send(reqBody!); observer.next({type: HttpEventType.Sent}); // This is the return from the Observable function, which is the diff --git a/packages/common/http/test/client_spec.ts b/packages/common/http/test/client_spec.ts index bed29df8eb351..d84925c2d0d55 100644 --- a/packages/common/http/test/client_spec.ts +++ b/packages/common/http/test/client_spec.ts @@ -14,13 +14,15 @@ import {toArray} from 'rxjs/operators'; { describe('HttpClient', () => { - let client: HttpClient = null !; - let backend: HttpClientTestingBackend = null !; + let client: HttpClient = null!; + let backend: HttpClientTestingBackend = null!; beforeEach(() => { backend = new HttpClientTestingBackend(); client = new HttpClient(backend); }); - afterEach(() => { backend.verify(); }); + afterEach(() => { + backend.verify(); + }); describe('makes a basic request', () => { it('for JSON data', done => { client.get('/test').subscribe(res => { diff --git a/packages/common/http/test/headers_spec.ts b/packages/common/http/test/headers_spec.ts index c7e23e2b2c4bc..49554a52015a4 100644 --- a/packages/common/http/test/headers_spec.ts +++ b/packages/common/http/test/headers_spec.ts @@ -10,7 +10,6 @@ import {HttpHeaders} from '@angular/common/http/src/headers'; { describe('HttpHeaders', () => { - describe('initialization', () => { it('should conform to spec', () => { const httpHeaders = { diff --git a/packages/common/http/test/jsonp_mock.ts b/packages/common/http/test/jsonp_mock.ts index 7b2345d7c3494..b05f25672dae7 100644 --- a/packages/common/http/test/jsonp_mock.ts +++ b/packages/common/http/test/jsonp_mock.ts @@ -18,19 +18,23 @@ export class MockScriptElement { this.listeners[event] = handler as any; } - removeEventListener(event: 'load'|'error'): void { delete this.listeners[event]; } + removeEventListener(event: 'load'|'error'): void { + delete this.listeners[event]; + } } export class MockDocument { // TODO(issue/24571): remove '!'. - mock !: MockScriptElement | null; + mock!: MockScriptElement|null; readonly body: any = this; createElement(tag: 'script'): HTMLScriptElement { return new MockScriptElement() as any as HTMLScriptElement; } - appendChild(node: any): void { this.mock = node; } + appendChild(node: any): void { + this.mock = node; + } removeNode(node: any): void { if (this.mock === node) { @@ -38,7 +42,11 @@ export class MockDocument { } } - mockLoad(): void { this.mock !.listeners.load !(null as any); } + mockLoad(): void { + this.mock!.listeners.load!(null as any); + } - mockError(err: Error) { this.mock !.listeners.error !(err); } + mockError(err: Error) { + this.mock!.listeners.error!(err); + } } diff --git a/packages/common/http/test/module_spec.ts b/packages/common/http/test/module_spec.ts index a6a66440f3cb2..4841de7b496f9 100644 --- a/packages/common/http/test/module_spec.ts +++ b/packages/common/http/test/module_spec.ts @@ -38,11 +38,15 @@ class TestInterceptor implements HttpInterceptor { } class InterceptorA extends TestInterceptor { - constructor() { super('A'); } + constructor() { + super('A'); + } } class InterceptorB extends TestInterceptor { - constructor() { super('B'); } + constructor() { + super('B'); + } } @Injectable() @@ -98,7 +102,9 @@ class ReentrantInterceptor implements HttpInterceptor { {provide: HTTP_INTERCEPTORS, useClass: ReentrantInterceptor, multi: true}, ], }); - injector.get(HttpClient).get('/test').subscribe(() => { done(); }); + injector.get(HttpClient).get('/test').subscribe(() => { + done(); + }); injector.get(HttpTestingController).expectOne('/test').flush('ok!'); }); }); diff --git a/packages/common/http/test/request_spec.ts b/packages/common/http/test/request_spec.ts index af17f0f7887e6..4c4f74d4a36df 100644 --- a/packages/common/http/test/request_spec.ts +++ b/packages/common/http/test/request_spec.ts @@ -80,16 +80,21 @@ const TEST_STRING = `I'm a body!`; expect(clone.headers).toBe(headers); expect(clone.headers.get('Test')).toBe('Test header'); }); - it('and updates the url', - () => { expect(req.clone({url: '/changed'}).url).toBe('/changed'); }); - it('and updates the method', - () => { expect(req.clone({method: 'PUT'}).method).toBe('PUT'); }); - it('and updates the body', - () => { expect(req.clone({body: 'changed body'}).body).toBe('changed body'); }); + it('and updates the url', () => { + expect(req.clone({url: '/changed'}).url).toBe('/changed'); + }); + it('and updates the method', () => { + expect(req.clone({method: 'PUT'}).method).toBe('PUT'); + }); + it('and updates the body', () => { + expect(req.clone({body: 'changed body'}).body).toBe('changed body'); + }); }); describe('content type detection', () => { const baseReq = new HttpRequest('POST', '/test', null); - it('handles a null body', () => { expect(baseReq.detectContentTypeHeader()).toBeNull(); }); + it('handles a null body', () => { + expect(baseReq.detectContentTypeHeader()).toBeNull(); + }); it('doesn\'t associate a content type with ArrayBuffers', () => { const req = baseReq.clone({body: new ArrayBuffer(4)}); expect(req.detectContentTypeHeader()).toBeNull(); @@ -113,7 +118,9 @@ const TEST_STRING = `I'm a body!`; }); describe('body serialization', () => { const baseReq = new HttpRequest('POST', '/test', null); - it('handles a null body', () => { expect(baseReq.serializeBody()).toBeNull(); }); + it('handles a null body', () => { + expect(baseReq.serializeBody()).toBeNull(); + }); it('passes ArrayBuffers through', () => { const body = new ArrayBuffer(4); expect(baseReq.clone({body}).serializeBody()).toBe(body); @@ -125,8 +132,9 @@ const TEST_STRING = `I'm a body!`; it('serializes arrays as json', () => { expect(baseReq.clone({body: ['a', 'b']}).serializeBody()).toBe('["a","b"]'); }); - it('handles numbers as json', - () => { expect(baseReq.clone({body: 314159}).serializeBody()).toBe('314159'); }); + it('handles numbers as json', () => { + expect(baseReq.clone({body: 314159}).serializeBody()).toBe('314159'); + }); it('handles objects as json', () => { const req = baseReq.clone({body: {data: 'test data'}}); expect(req.serializeBody()).toBe('{"data":"test data"}'); diff --git a/packages/common/http/test/xhr_mock.ts b/packages/common/http/test/xhr_mock.ts index bfac036991ba8..3634293726e6d 100644 --- a/packages/common/http/test/xhr_mock.ts +++ b/packages/common/http/test/xhr_mock.ts @@ -11,9 +11,11 @@ import {XhrFactory} from '@angular/common/http/src/xhr'; export class MockXhrFactory implements XhrFactory { // TODO(issue/24571): remove '!'. - mock !: MockXMLHttpRequest; + mock!: MockXMLHttpRequest; - build(): XMLHttpRequest { return (this.mock = new MockXMLHttpRequest()) as any; } + build(): XMLHttpRequest { + return (this.mock = new MockXMLHttpRequest()) as any; + } } export class MockXMLHttpRequestUpload { @@ -32,9 +34,9 @@ export class MockXMLHttpRequest { // Set by method calls. body: any; // TODO(issue/24571): remove '!'. - method !: string; + method!: string; // TODO(issue/24571): remove '!'. - url !: string; + url!: string; mockHeaders: {[key: string]: string} = {}; mockAborted: boolean = false; @@ -64,7 +66,9 @@ export class MockXMLHttpRequest { this.url = url; } - send(body: any): void { this.body = body; } + send(body: any): void { + this.body = body; + } addEventListener(event: 'error'|'load'|'progress'|'uploadProgress', handler: Function): void { this.listeners[event] = handler as any; @@ -74,9 +78,13 @@ export class MockXMLHttpRequest { delete this.listeners[event]; } - setRequestHeader(name: string, value: string): void { this.mockHeaders[name] = value; } + setRequestHeader(name: string, value: string): void { + this.mockHeaders[name] = value; + } - getAllResponseHeaders(): string { return this.mockResponseHeaders; } + getAllResponseHeaders(): string { + return this.mockResponseHeaders; + } getResponseHeader(header: string): string|null { return new HttpHeaders(this.mockResponseHeaders).get(header); @@ -95,14 +103,17 @@ export class MockXMLHttpRequest { mockDownloadProgressEvent(loaded: number, total?: number): void { if (this.listeners.progress) { - this.listeners.progress({ lengthComputable: total !== undefined, loaded, total } as any); + this.listeners.progress({lengthComputable: total !== undefined, loaded, total} as any); } } mockUploadProgressEvent(loaded: number, total?: number) { if (this.listeners.uploadProgress) { - this.listeners.uploadProgress( - { lengthComputable: total !== undefined, loaded, total, } as any); + this.listeners.uploadProgress({ + lengthComputable: total !== undefined, + loaded, + total, + } as any); } } @@ -118,5 +129,7 @@ export class MockXMLHttpRequest { } } - abort() { this.mockAborted = true; } + abort() { + this.mockAborted = true; + } } diff --git a/packages/common/http/test/xsrf_spec.ts b/packages/common/http/test/xsrf_spec.ts index 252b0032b6fcc..bf588b2fab9cc 100644 --- a/packages/common/http/test/xsrf_spec.ts +++ b/packages/common/http/test/xsrf_spec.ts @@ -13,16 +13,22 @@ import {HttpXsrfCookieExtractor, HttpXsrfInterceptor, HttpXsrfTokenExtractor} fr import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend'; class SampleTokenExtractor extends HttpXsrfTokenExtractor { - constructor(private token: string|null) { super(); } + constructor(private token: string|null) { + super(); + } - getToken(): string|null { return this.token; } + getToken(): string|null { + return this.token; + } } { describe('HttpXsrfInterceptor', () => { let backend: HttpClientTestingBackend; const interceptor = new HttpXsrfInterceptor(new SampleTokenExtractor('test'), 'X-XSRF-TOKEN'); - beforeEach(() => { backend = new HttpClientTestingBackend(); }); + beforeEach(() => { + backend = new HttpClientTestingBackend(); + }); it('applies XSRF protection to outgoing requests', () => { interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe(); const req = backend.expectOne('/test'); @@ -59,7 +65,9 @@ class SampleTokenExtractor extends HttpXsrfTokenExtractor { expect(req.request.headers.has('X-XSRF-TOKEN')).toEqual(false); req.flush({}); }); - afterEach(() => { backend.verify(); }); + afterEach(() => { + backend.verify(); + }); }); describe('HttpXsrfCookieExtractor', () => { let document: {[key: string]: string}; @@ -70,8 +78,9 @@ class SampleTokenExtractor extends HttpXsrfTokenExtractor { }; extractor = new HttpXsrfCookieExtractor(document, 'browser', 'XSRF-TOKEN'); }); - it('parses the cookie from document.cookie', - () => { expect(extractor.getToken()).toEqual('test'); }); + it('parses the cookie from document.cookie', () => { + expect(extractor.getToken()).toEqual('test'); + }); it('does not re-parse if document.cookie has not changed', () => { expect(extractor.getToken()).toEqual('test'); expect(extractor.getToken()).toEqual('test'); diff --git a/packages/common/http/testing/src/backend.ts b/packages/common/http/testing/src/backend.ts index 75a32389b8dff..b01dc0dc353c0 100644 --- a/packages/common/http/testing/src/backend.ts +++ b/packages/common/http/testing/src/backend.ts @@ -39,8 +39,10 @@ export class HttpClientTestingBackend implements HttpBackend, HttpTestingControl return new Observable((observer: Observer) => { const testReq = new TestRequest(req, observer); this.open.push(testReq); - observer.next({ type: HttpEventType.Sent } as HttpEvent); - return () => { testReq._cancelled = true; }; + observer.next({type: HttpEventType.Sent} as HttpEvent); + return () => { + testReq._cancelled = true; + }; }); } @@ -86,8 +88,8 @@ export class HttpClientTestingBackend implements HttpBackend, HttpTestingControl description = description || this.descriptionFromMatcher(match); const matches = this.match(match); if (matches.length > 1) { - throw new Error( - `Expected one matching request for criteria "${description}", found ${matches.length} requests.`); + throw new Error(`Expected one matching request for criteria "${description}", found ${ + matches.length} requests.`); } if (matches.length === 0) { let message = `Expected one matching request for criteria "${description}", found none.`; @@ -116,8 +118,8 @@ export class HttpClientTestingBackend implements HttpBackend, HttpTestingControl description = description || this.descriptionFromMatcher(match); const matches = this.match(match); if (matches.length > 0) { - throw new Error( - `Expected zero matching requests for criteria "${description}", found ${matches.length}.`); + throw new Error(`Expected zero matching requests for criteria "${description}", found ${ + matches.length}.`); } } diff --git a/packages/common/http/testing/src/request.ts b/packages/common/http/testing/src/request.ts index 022cf77e19be1..9f240be590785 100644 --- a/packages/common/http/testing/src/request.ts +++ b/packages/common/http/testing/src/request.ts @@ -21,7 +21,9 @@ export class TestRequest { /** * Whether the request was cancelled after it was sent. */ - get cancelled(): boolean { return this._cancelled; } + get cancelled(): boolean { + return this._cancelled; + } /** * @internal set by `HttpClientTestingBackend` @@ -39,7 +41,7 @@ export class TestRequest { * Both successful and unsuccessful responses can be delivered via `flush()`. */ flush(body: ArrayBuffer|Blob|string|number|Object|(string|number|Object|null)[]|null, opts: { - headers?: HttpHeaders | {[name: string]: string | string[]}, + headers?: HttpHeaders|{[name: string]: string | string[]}, status?: number, statusText?: string, } = {}): void { @@ -75,7 +77,7 @@ export class TestRequest { * Resolve the request by returning an `ErrorEvent` (e.g. simulating a network failure). */ error(error: ErrorEvent, opts: { - headers?: HttpHeaders | {[name: string]: string | string[]}, + headers?: HttpHeaders|{[name: string]: string | string[]}, status?: number, statusText?: string, } = {}): void { @@ -112,9 +114,8 @@ export class TestRequest { /** * Helper function to convert a response body to an ArrayBuffer. */ -function _toArrayBufferBody( - body: ArrayBuffer | Blob | string | number | Object | - (string | number | Object | null)[]): ArrayBuffer { +function _toArrayBufferBody(body: ArrayBuffer|Blob|string|number|Object| + (string | number | Object | null)[]): ArrayBuffer { if (typeof ArrayBuffer === 'undefined') { throw new Error('ArrayBuffer responses are not supported on this platform.'); } @@ -127,9 +128,8 @@ function _toArrayBufferBody( /** * Helper function to convert a response body to a Blob. */ -function _toBlob( - body: ArrayBuffer | Blob | string | number | Object | - (string | number | Object | null)[]): Blob { +function _toBlob(body: ArrayBuffer|Blob|string|number|Object| + (string | number | Object | null)[]): Blob { if (typeof Blob === 'undefined') { throw new Error('Blob responses are not supported on this platform.'); } @@ -146,7 +146,7 @@ function _toBlob( * Helper function to convert a response body to JSON data. */ function _toJsonBody( - body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[], + body: ArrayBuffer|Blob|string|number|Object|(string | number | Object | null)[], format: string = 'JSON'): Object|string|number|(Object | string | number)[] { if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) { throw new Error(`Automatic conversion to ${format} is not supported for ArrayBuffers.`); @@ -164,9 +164,8 @@ function _toJsonBody( /** * Helper function to convert a response body to a string. */ -function _toTextBody( - body: ArrayBuffer | Blob | string | number | Object | - (string | number | Object | null)[]): string { +function _toTextBody(body: ArrayBuffer|Blob|string|number|Object| + (string | number | Object | null)[]): string { if (typeof body === 'string') { return body; } @@ -183,9 +182,9 @@ function _toTextBody( * Convert a response body to the requested type. */ function _maybeConvertBody( - responseType: string, body: ArrayBuffer | Blob | string | number | Object | - (string | number | Object | null)[] | null): ArrayBuffer|Blob|string|number|Object| - (string | number | Object | null)[]|null { + responseType: string, + body: ArrayBuffer|Blob|string|number|Object|(string | number | Object | null)[]| + null): ArrayBuffer|Blob|string|number|Object|(string | number | Object | null)[]|null { if (body === null) { return null; } diff --git a/packages/common/http/testing/test/request_spec.ts b/packages/common/http/testing/test/request_spec.ts index 92d78399d29d7..5c4092a52d2c3 100644 --- a/packages/common/http/testing/test/request_spec.ts +++ b/packages/common/http/testing/test/request_spec.ts @@ -15,7 +15,9 @@ describe('HttpClient TestRequest', () => { const client = new HttpClient(mock); let resp: any; - client.post('/some-url', {test: 'test'}).subscribe(body => { resp = body; }); + client.post('/some-url', {test: 'test'}).subscribe(body => { + resp = body; + }); const req = mock.expectOne('/some-url'); req.flush(null); @@ -28,7 +30,9 @@ describe('HttpClient TestRequest', () => { const client = new HttpClient(mock); let resp: any; - client.get('/some-other-url').subscribe(body => { resp = body; }); + client.get('/some-other-url').subscribe(body => { + resp = body; + }); try { // expect different URL @@ -48,7 +52,9 @@ describe('HttpClient TestRequest', () => { let resp: any; const params = {query: 'hello'}; - client.get('/some-url', {params}).subscribe(body => { resp = body; }); + client.get('/some-url', {params}).subscribe(body => { + resp = body; + }); try { // expect different query parameters @@ -67,8 +73,12 @@ describe('HttpClient TestRequest', () => { const client = new HttpClient(mock); let resp: any; - client.get('/some-other-url?query=world').subscribe(body => { resp = body; }); - client.post('/and-another-url', {}).subscribe(body => { resp = body; }); + client.get('/some-other-url?query=world').subscribe(body => { + resp = body; + }); + client.post('/and-another-url', {}).subscribe(body => { + resp = body; + }); try { // expect different URL diff --git a/packages/common/src/directives/ng_class.ts b/packages/common/src/directives/ng_class.ts index 63ddbe198e422..d24e4dfae7796 100644 --- a/packages/common/src/directives/ng_class.ts +++ b/packages/common/src/directives/ng_class.ts @@ -7,7 +7,7 @@ */ import {Directive, DoCheck, ElementRef, Input, IterableChanges, IterableDiffer, IterableDiffers, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2, ɵisListLikeIterable as isListLikeIterable, ɵstringify as stringify} from '@angular/core'; -type NgClassSupportedTypes = string[] | Set| {[klass: string]: any} | null | undefined; +type NgClassSupportedTypes = string[]|Set|{[klass: string]: any}|null|undefined; /** * @ngModule CommonModule @@ -83,7 +83,7 @@ export class NgClass implements DoCheck { this._applyIterableChanges(iterableChanges); } } else if (this._keyValueDiffer) { - const keyValueChanges = this._keyValueDiffer.diff(this._rawClass as{[k: string]: any}); + const keyValueChanges = this._keyValueDiffer.diff(this._rawClass as {[k: string]: any}); if (keyValueChanges) { this._applyKeyValueChanges(keyValueChanges); } @@ -105,8 +105,8 @@ export class NgClass implements DoCheck { if (typeof record.item === 'string') { this._toggleClass(record.item, true); } else { - throw new Error( - `NgClass can only toggle CSS classes expressed as strings, got ${stringify(record.item)}`); + throw new Error(`NgClass can only toggle CSS classes expressed as strings, got ${ + stringify(record.item)}`); } }); diff --git a/packages/common/src/directives/ng_component_outlet.ts b/packages/common/src/directives/ng_component_outlet.ts index 23f2b856a482d..6c601b6442043 100644 --- a/packages/common/src/directives/ng_component_outlet.ts +++ b/packages/common/src/directives/ng_component_outlet.ts @@ -67,13 +67,13 @@ import {ComponentFactoryResolver, ComponentRef, Directive, Injector, Input, NgMo @Directive({selector: '[ngComponentOutlet]'}) export class NgComponentOutlet implements OnChanges, OnDestroy { // TODO(issue/24571): remove '!'. - @Input() ngComponentOutlet !: Type; + @Input() ngComponentOutlet!: Type; // TODO(issue/24571): remove '!'. - @Input() ngComponentOutletInjector !: Injector; + @Input() ngComponentOutletInjector!: Injector; // TODO(issue/24571): remove '!'. - @Input() ngComponentOutletContent !: any[][]; + @Input() ngComponentOutletContent!: any[][]; // TODO(issue/24571): remove '!'. - @Input() ngComponentOutletNgModuleFactory !: NgModuleFactory; + @Input() ngComponentOutletNgModuleFactory!: NgModuleFactory; private _componentRef: ComponentRef|null = null; private _moduleRef: NgModuleRef|null = null; diff --git a/packages/common/src/directives/ng_for_of.ts b/packages/common/src/directives/ng_for_of.ts index 02d8243690c99..dc176145abe3e 100644 --- a/packages/common/src/directives/ng_for_of.ts +++ b/packages/common/src/directives/ng_for_of.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef, isDevMode} from '@angular/core'; +import {Directive, DoCheck, EmbeddedViewRef, Input, isDevMode, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core'; /** * @publicApi @@ -14,13 +14,21 @@ import {Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, Iterab export class NgForOfContext = NgIterable> { constructor(public $implicit: T, public ngForOf: U, public index: number, public count: number) {} - get first(): boolean { return this.index === 0; } + get first(): boolean { + return this.index === 0; + } - get last(): boolean { return this.index === this.count - 1; } + get last(): boolean { + return this.index === this.count - 1; + } - get even(): boolean { return this.index % 2 === 0; } + get even(): boolean { + return this.index % 2 === 0; + } - get odd(): boolean { return !this.even; } + get odd(): boolean { + return !this.even; + } } /** @@ -162,13 +170,15 @@ export class NgForOf = NgIterable> implements DoCh this._trackByFn = fn; } - get ngForTrackBy(): TrackByFunction { return this._trackByFn; } + get ngForTrackBy(): TrackByFunction { + return this._trackByFn; + } private _ngForOf: U|undefined|null = null; private _ngForOfDirty: boolean = true; private _differ: IterableDiffer|null = null; // TODO(issue/24571): remove '!'. - private _trackByFn !: TrackByFunction; + private _trackByFn!: TrackByFunction; constructor( private _viewContainer: ViewContainerRef, @@ -200,8 +210,8 @@ export class NgForOf = NgIterable> implements DoCh try { this._differ = this._differs.find(value).create(this.ngForTrackBy); } catch { - throw new Error( - `Cannot find a differ supporting object '${value}' of type '${getTypeName(value)}'. NgFor only supports binding to Iterables such as Arrays.`); + throw new Error(`Cannot find a differ supporting object '${value}' of type '${ + getTypeName(value)}'. NgFor only supports binding to Iterables such as Arrays.`); } } } @@ -214,14 +224,14 @@ export class NgForOf = NgIterable> implements DoCh private _applyChanges(changes: IterableChanges) { const insertTuples: RecordViewTuple[] = []; changes.forEachOperation( - (item: IterableChangeRecord, adjustedPreviousIndex: number | null, - currentIndex: number | null) => { + (item: IterableChangeRecord, adjustedPreviousIndex: number|null, + currentIndex: number|null) => { if (item.previousIndex == null) { // NgForOf is never "null" or "undefined" here because the differ detected // that a new item needs to be inserted from the iterable. This implies that // there is an iterable value for "_ngForOf". const view = this._viewContainer.createEmbeddedView( - this._template, new NgForOfContext(null !, this._ngForOf !, -1, -1), + this._template, new NgForOfContext(null!, this._ngForOf!, -1, -1), currentIndex === null ? undefined : currentIndex); const tuple = new RecordViewTuple(item, view); insertTuples.push(tuple); @@ -229,7 +239,7 @@ export class NgForOf = NgIterable> implements DoCh this._viewContainer.remove( adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex); } else if (adjustedPreviousIndex !== null) { - const view = this._viewContainer.get(adjustedPreviousIndex) !; + const view = this._viewContainer.get(adjustedPreviousIndex)!; this._viewContainer.move(view, currentIndex); const tuple = new RecordViewTuple(item, >>view); insertTuples.push(tuple); @@ -244,7 +254,7 @@ export class NgForOf = NgIterable> implements DoCh const viewRef = >>this._viewContainer.get(i); viewRef.context.index = i; viewRef.context.count = ilen; - viewRef.context.ngForOf = this._ngForOf !; + viewRef.context.ngForOf = this._ngForOf!; } changes.forEachIdentityChange((record: any) => { diff --git a/packages/common/src/directives/ng_if.ts b/packages/common/src/directives/ng_if.ts index e9cb89227e4c0..2868055a973e0 100644 --- a/packages/common/src/directives/ng_if.ts +++ b/packages/common/src/directives/ng_if.ts @@ -241,11 +241,11 @@ export class NgIf { * @publicApi */ export class NgIfContext { - public $implicit: T = null !; - public ngIf: T = null !; + public $implicit: T = null!; + public ngIf: T = null!; } -function assertTemplate(property: string, templateRef: TemplateRef| null): void { +function assertTemplate(property: string, templateRef: TemplateRef|null): void { const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView); if (!isTemplateRefOrNull) { throw new Error(`${property} must be a TemplateRef, but received '${stringify(templateRef)}'.`); diff --git a/packages/common/src/directives/ng_plural.ts b/packages/common/src/directives/ng_plural.ts index 1cc7de97c4633..52158f9347c4a 100644 --- a/packages/common/src/directives/ng_plural.ts +++ b/packages/common/src/directives/ng_plural.ts @@ -8,7 +8,7 @@ import {Attribute, Directive, Host, Input, TemplateRef, ViewContainerRef} from '@angular/core'; -import {NgLocalization, getPluralCategory} from '../i18n/localization'; +import {getPluralCategory, NgLocalization} from '../i18n/localization'; import {SwitchView} from './ng_switch'; @@ -47,9 +47,9 @@ import {SwitchView} from './ng_switch'; @Directive({selector: '[ngPlural]'}) export class NgPlural { // TODO(issue/24571): remove '!'. - private _switchValue !: number; + private _switchValue!: number; // TODO(issue/24571): remove '!'. - private _activeView !: SwitchView; + private _activeView!: SwitchView; private _caseViews: {[k: string]: SwitchView} = {}; constructor(private _localization: NgLocalization) {} @@ -60,7 +60,9 @@ export class NgPlural { this._updateView(); } - addCase(value: string, switchView: SwitchView): void { this._caseViews[value] = switchView; } + addCase(value: string, switchView: SwitchView): void { + this._caseViews[value] = switchView; + } private _updateView(): void { this._clearViews(); diff --git a/packages/common/src/directives/ng_style.ts b/packages/common/src/directives/ng_style.ts index 73dab1a154bb4..f13a93e6dc988 100644 --- a/packages/common/src/directives/ng_style.ts +++ b/packages/common/src/directives/ng_style.ts @@ -62,7 +62,7 @@ export class NgStyle implements DoCheck { ngDoCheck() { if (this._differ) { - const changes = this._differ.diff(this._ngStyle !); + const changes = this._differ.diff(this._ngStyle!); if (changes) { this._applyChanges(changes); } diff --git a/packages/common/src/directives/ng_switch.ts b/packages/common/src/directives/ng_switch.ts index 11c0fc8aef19c..e964491e93078 100644 --- a/packages/common/src/directives/ng_switch.ts +++ b/packages/common/src/directives/ng_switch.ts @@ -104,7 +104,7 @@ export class SwitchView { @Directive({selector: '[ngSwitch]'}) export class NgSwitch { // TODO(issue/24571): remove '!'. - private _defaultViews !: SwitchView[]; + private _defaultViews!: SwitchView[]; private _defaultUsed = false; private _caseCount = 0; private _lastCaseCheckIndex = 0; @@ -120,7 +120,9 @@ export class NgSwitch { } /** @internal */ - _addCase(): number { return this._caseCount++; } + _addCase(): number { + return this._caseCount++; + } /** @internal */ _addDefault(view: SwitchView) { @@ -193,8 +195,7 @@ export class NgSwitchCase implements DoCheck { /** * Stores the HTML template to be selected on match. */ - @Input() - ngSwitchCase: any; + @Input() ngSwitchCase: any; constructor( viewContainer: ViewContainerRef, templateRef: TemplateRef, @@ -206,7 +207,9 @@ export class NgSwitchCase implements DoCheck { /** * Performs case matching. For internal use only. */ - ngDoCheck() { this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase)); } + ngDoCheck() { + this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase)); + } } /** diff --git a/packages/common/src/directives/ng_template_outlet.ts b/packages/common/src/directives/ng_template_outlet.ts index 69662161e7b9c..4256313edc548 100644 --- a/packages/common/src/directives/ng_template_outlet.ts +++ b/packages/common/src/directives/ng_template_outlet.ts @@ -101,7 +101,7 @@ export class NgTemplateOutlet implements OnChanges { private _updateExistingContext(ctx: Object): void { for (let propName of Object.keys(ctx)) { - (this._viewRef !.context)[propName] = (this.ngTemplateOutletContext)[propName]; + (this._viewRef!.context)[propName] = (this.ngTemplateOutletContext)[propName]; } } } diff --git a/packages/common/src/dom_adapter.ts b/packages/common/src/dom_adapter.ts index ea8ba85defbf7..5b715ff982b78 100644 --- a/packages/common/src/dom_adapter.ts +++ b/packages/common/src/dom_adapter.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -let _DOM: DomAdapter = null !; +let _DOM: DomAdapter = null!; export function getDOM(): DomAdapter { return _DOM; diff --git a/packages/common/src/i18n/format_date.ts b/packages/common/src/i18n/format_date.ts index b5df8175b377f..06ad7ab760f8c 100644 --- a/packages/common/src/i18n/format_date.ts +++ b/packages/common/src/i18n/format_date.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {FormStyle, FormatWidth, NumberSymbol, Time, TranslationWidth, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleDayNames, getLocaleDayPeriods, getLocaleEraNames, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocaleId, getLocaleMonthNames, getLocaleNumberSymbol, getLocaleTimeFormat} from './locale_data_api'; +import {FormatWidth, FormStyle, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleDayNames, getLocaleDayPeriods, getLocaleEraNames, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocaleId, getLocaleMonthNames, getLocaleNumberSymbol, getLocaleTimeFormat, NumberSymbol, Time, TranslationWidth} from './locale_data_api'; export const ISO8601_DATE_REGEX = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; @@ -62,7 +62,7 @@ enum TranslationType { * @publicApi */ export function formatDate( - value: string | number | Date, format: string, locale: string, timezone?: string): string { + value: string|number|Date, format: string, locale: string, timezone?: string): string { let date = toDate(value); const namedFormat = getNamedFormat(locale, format); format = namedFormat || format; @@ -278,7 +278,7 @@ function getDateTranslation( const rules = getLocaleExtraDayPeriodRules(locale); const dayPeriods = getLocaleExtraDayPeriods(locale, form, width); let result; - rules.forEach((rule: Time | [Time, Time], index: number) => { + rules.forEach((rule: Time|[Time, Time], index: number) => { if (Array.isArray(rule)) { // morning, afternoon, evening, night const {hours: hoursFrom, minutes: minutesFrom} = rule[0]; @@ -652,7 +652,7 @@ function convertTimezoneToLocal(date: Date, timezone: string, reverse: boolean): * * Throws if unable to convert to a date. */ -export function toDate(value: string | number | Date): Date { +export function toDate(value: string|number|Date): Date { if (isDate(value)) { return value; } diff --git a/packages/common/src/i18n/format_number.ts b/packages/common/src/i18n/format_number.ts index 770b55032d09e..ba4e358e8dbdf 100644 --- a/packages/common/src/i18n/format_number.ts +++ b/packages/common/src/i18n/format_number.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {NumberFormatStyle, NumberSymbol, getLocaleNumberFormat, getLocaleNumberSymbol, getNumberOfCurrencyDigits} from './locale_data_api'; +import {getLocaleNumberFormat, getLocaleNumberSymbol, getNumberOfCurrencyDigits, NumberFormatStyle, NumberSymbol} from './locale_data_api'; export const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/; const MAX_DIGITS = 22; @@ -153,7 +153,7 @@ export function formatCurrency( const format = getLocaleNumberFormat(locale, NumberFormatStyle.Currency); const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); - pattern.minFrac = getNumberOfCurrencyDigits(currencyCode !); + pattern.minFrac = getNumberOfCurrencyDigits(currencyCode!); pattern.maxFrac = pattern.minFrac; const res = formatNumberToLocaleString( @@ -392,8 +392,8 @@ function parseNumber(num: number): ParsedNumber { */ function roundNumber(parsedNumber: ParsedNumber, minFrac: number, maxFrac: number) { if (minFrac > maxFrac) { - throw new Error( - `The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`); + throw new Error(`The minimum number of digits after fraction (${ + minFrac}) is higher than the maximum (${maxFrac}).`); } let digits = parsedNumber.digits; diff --git a/packages/common/src/i18n/locale_data.ts b/packages/common/src/i18n/locale_data.ts index cfbdee94d916b..c2355c8a5d333 100644 --- a/packages/common/src/i18n/locale_data.ts +++ b/packages/common/src/i18n/locale_data.ts @@ -16,6 +16,6 @@ import {ɵregisterLocaleData} from '@angular/core'; * * @publicApi */ -export function registerLocaleData(data: any, localeId?: string | any, extraData?: any): void { +export function registerLocaleData(data: any, localeId?: string|any, extraData?: any): void { return ɵregisterLocaleData(data, localeId, extraData); } diff --git a/packages/common/src/i18n/locale_data_api.ts b/packages/common/src/i18n/locale_data_api.ts index 2354580d434ab..94bbb3fabc9be 100644 --- a/packages/common/src/i18n/locale_data_api.ts +++ b/packages/common/src/i18n/locale_data_api.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {ɵCurrencyIndex, ɵExtraLocaleDataIndex, ɵLocaleDataIndex, ɵfindLocaleData, ɵgetLocaleCurrencyCode, ɵgetLocalePluralCase} from '@angular/core'; +import {ɵCurrencyIndex, ɵExtraLocaleDataIndex, ɵfindLocaleData, ɵgetLocaleCurrencyCode, ɵgetLocalePluralCase, ɵLocaleDataIndex} from '@angular/core'; import {CURRENCIES_EN, CurrenciesSymbols} from './currencies'; @@ -235,9 +235,9 @@ export function getLocaleId(locale: string): string { export function getLocaleDayPeriods( locale: string, formStyle: FormStyle, width: TranslationWidth): [string, string] { const data = ɵfindLocaleData(locale); - const amPmData = <[ - string, string - ][][]>[data[ɵLocaleDataIndex.DayPeriodsFormat], data[ɵLocaleDataIndex.DayPeriodsStandalone]]; + const amPmData = <[string, string][][]>[ + data[ɵLocaleDataIndex.DayPeriodsFormat], data[ɵLocaleDataIndex.DayPeriodsStandalone] + ]; const amPm = getLastDefinedValue(amPmData, formStyle); return getLastDefinedValue(amPm, width); } @@ -509,8 +509,9 @@ export const getLocalePluralCase: (locale: string) => ((value: number) => Plural function checkFullData(data: any) { if (!data[ɵLocaleDataIndex.ExtraData]) { - throw new Error( - `Missing extra locale data for the locale "${data[ɵLocaleDataIndex.LocaleId]}". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`); + throw new Error(`Missing extra locale data for the locale "${ + data[ɵLocaleDataIndex + .LocaleId]}". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`); } } @@ -536,11 +537,11 @@ function checkFullData(data: any) { * * @publicApi */ -export function getLocaleExtraDayPeriodRules(locale: string): (Time | [Time, Time])[] { +export function getLocaleExtraDayPeriodRules(locale: string): (Time|[Time, Time])[] { const data = ɵfindLocaleData(locale); checkFullData(data); const rules = data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodsRules] || []; - return rules.map((rule: string | [string, string]) => { + return rules.map((rule: string|[string, string]) => { if (typeof rule === 'string') { return extractTime(rule); } @@ -570,8 +571,8 @@ export function getLocaleExtraDayPeriods( const data = ɵfindLocaleData(locale); checkFullData(data); const dayPeriodsData = [ - data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodFormats], - data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodStandalone] + data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodFormats], + data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodStandalone] ]; const dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || []; return getLastDefinedValue(dayPeriods, width) || []; @@ -646,7 +647,7 @@ function extractTime(time: string): Time { * * @publicApi */ -export function getCurrencySymbol(code: string, format: 'wide' | 'narrow', locale = 'en'): string { +export function getCurrencySymbol(code: string, format: 'wide'|'narrow', locale = 'en'): string { const currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || []; const symbolNarrow = currency[ɵCurrencyIndex.SymbolNarrow]; diff --git a/packages/common/src/i18n/localization.ts b/packages/common/src/i18n/localization.ts index 64227fbcbdadf..b213aae529d83 100644 --- a/packages/common/src/i18n/localization.ts +++ b/packages/common/src/i18n/localization.ts @@ -7,7 +7,8 @@ */ import {Inject, Injectable, LOCALE_ID} from '@angular/core'; -import {Plural, getLocalePluralCase} from './locale_data_api'; + +import {getLocalePluralCase, Plural} from './locale_data_api'; /** @@ -51,7 +52,9 @@ export function getPluralCategory( */ @Injectable() export class NgLocaleLocalization extends NgLocalization { - constructor(@Inject(LOCALE_ID) protected locale: string) { super(); } + constructor(@Inject(LOCALE_ID) protected locale: string) { + super(); + } getPluralCategory(value: any, locale?: string): string { const plural = getLocalePluralCase(locale || this.locale)(value); diff --git a/packages/common/src/location/hash_location_strategy.ts b/packages/common/src/location/hash_location_strategy.ts index b25601127e320..4c17e30cbe9da 100644 --- a/packages/common/src/location/hash_location_strategy.ts +++ b/packages/common/src/location/hash_location_strategy.ts @@ -48,7 +48,9 @@ export class HashLocationStrategy extends LocationStrategy { this._platformLocation.onHashChange(fn); } - getBaseHref(): string { return this._baseHref; } + getBaseHref(): string { + return this._baseHref; + } path(includeHash: boolean = false): string { // the hash value is always prefixed with a `#` @@ -80,7 +82,11 @@ export class HashLocationStrategy extends LocationStrategy { this._platformLocation.replaceState(state, title, url); } - forward(): void { this._platformLocation.forward(); } + forward(): void { + this._platformLocation.forward(); + } - back(): void { this._platformLocation.back(); } + back(): void { + this._platformLocation.back(); + } } diff --git a/packages/common/src/location/location.ts b/packages/common/src/location/location.ts index a161654e6d6ea..415852cc2c147 100644 --- a/packages/common/src/location/location.ts +++ b/packages/common/src/location/location.ts @@ -97,7 +97,9 @@ export class Location { * Reports the current state of the location history. * @returns The current value of the `history.state` object. */ - getState(): unknown { return this._platformLocation.getState(); } + getState(): unknown { + return this._platformLocation.getState(); + } /** * Normalizes the given path and compares to the current normalized path. @@ -173,12 +175,16 @@ export class Location { /** * Navigates forward in the platform's history. */ - forward(): void { this._platformStrategy.forward(); } + forward(): void { + this._platformStrategy.forward(); + } /** * Navigates back in the platform's history. */ - back(): void { this._platformStrategy.back(); } + back(): void { + this._platformStrategy.back(); + } /** * Registers a URL change listener. Use to catch updates performed by the Angular @@ -188,7 +194,9 @@ export class Location { */ onUrlChange(fn: (url: string, state: unknown) => void) { this._urlChangeListeners.push(fn); - this.subscribe(v => { this._notifyUrlChangeListeners(v.url, v.state); }); + this.subscribe(v => { + this._notifyUrlChangeListeners(v.url, v.state); + }); } /** @internal */ diff --git a/packages/common/src/location/location_strategy.ts b/packages/common/src/location/location_strategy.ts index a4e732c20ad8d..6e3fc8bbb1772 100644 --- a/packages/common/src/location/location_strategy.ts +++ b/packages/common/src/location/location_strategy.ts @@ -126,9 +126,13 @@ export class PathLocationStrategy extends LocationStrategy { this._platformLocation.onHashChange(fn); } - getBaseHref(): string { return this._baseHref; } + getBaseHref(): string { + return this._baseHref; + } - prepareExternalUrl(internal: string): string { return joinWithSlash(this._baseHref, internal); } + prepareExternalUrl(internal: string): string { + return joinWithSlash(this._baseHref, internal); + } path(includeHash: boolean = false): string { const pathname = @@ -147,7 +151,11 @@ export class PathLocationStrategy extends LocationStrategy { this._platformLocation.replaceState(state, title, externalUrl); } - forward(): void { this._platformLocation.forward(); } + forward(): void { + this._platformLocation.forward(); + } - back(): void { this._platformLocation.back(); } + back(): void { + this._platformLocation.back(); + } } diff --git a/packages/common/src/location/platform_location.ts b/packages/common/src/location/platform_location.ts index 4139d768153c1..8470161f7174d 100644 --- a/packages/common/src/location/platform_location.ts +++ b/packages/common/src/location/platform_location.ts @@ -86,7 +86,9 @@ export interface LocationChangeEvent { /** * @publicApi */ -export interface LocationChangeListener { (event: LocationChangeEvent): any; } +export interface LocationChangeListener { + (event: LocationChangeEvent): any; +} @@ -101,8 +103,8 @@ export interface LocationChangeListener { (event: LocationChangeEvent): any; } useFactory: createBrowserPlatformLocation, }) export class BrowserPlatformLocation extends PlatformLocation { - public readonly location !: Location; - private _history !: History; + public readonly location!: Location; + private _history!: History; constructor(@Inject(DOCUMENT) private _doc: any) { super(); @@ -112,11 +114,13 @@ export class BrowserPlatformLocation extends PlatformLocation { // This is moved to its own method so that `MockPlatformLocationStrategy` can overwrite it /** @internal */ _init() { - (this as{location: Location}).location = getDOM().getLocation(); + (this as {location: Location}).location = getDOM().getLocation(); this._history = getDOM().getHistory(); } - getBaseHrefFromDOM(): string { return getDOM().getBaseHref(this._doc) !; } + getBaseHrefFromDOM(): string { + return getDOM().getBaseHref(this._doc)!; + } onPopState(fn: LocationChangeListener): void { getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('popstate', fn, false); @@ -126,14 +130,30 @@ export class BrowserPlatformLocation extends PlatformLocation { getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('hashchange', fn, false); } - get href(): string { return this.location.href; } - get protocol(): string { return this.location.protocol; } - get hostname(): string { return this.location.hostname; } - get port(): string { return this.location.port; } - get pathname(): string { return this.location.pathname; } - get search(): string { return this.location.search; } - get hash(): string { return this.location.hash; } - set pathname(newPath: string) { this.location.pathname = newPath; } + get href(): string { + return this.location.href; + } + get protocol(): string { + return this.location.protocol; + } + get hostname(): string { + return this.location.hostname; + } + get port(): string { + return this.location.port; + } + get pathname(): string { + return this.location.pathname; + } + get search(): string { + return this.location.search; + } + get hash(): string { + return this.location.hash; + } + set pathname(newPath: string) { + this.location.pathname = newPath; + } pushState(state: any, title: string, url: string): void { if (supportsState()) { @@ -151,11 +171,17 @@ export class BrowserPlatformLocation extends PlatformLocation { } } - forward(): void { this._history.forward(); } + forward(): void { + this._history.forward(); + } - back(): void { this._history.back(); } + back(): void { + this._history.back(); + } - getState(): unknown { return this._history.state; } + getState(): unknown { + return this._history.state; + } } export function supportsState(): boolean { diff --git a/packages/common/src/pipes/async_pipe.ts b/packages/common/src/pipes/async_pipe.ts index 40d565d2f18d3..54a62d69031ef 100644 --- a/packages/common/src/pipes/async_pipe.ts +++ b/packages/common/src/pipes/async_pipe.ts @@ -19,17 +19,28 @@ interface SubscriptionStrategy { class ObservableStrategy implements SubscriptionStrategy { createSubscription(async: Observable, updateLatestValue: any): SubscriptionLike { - return async.subscribe({next: updateLatestValue, error: (e: any) => { throw e; }}); + return async.subscribe({ + next: updateLatestValue, + error: (e: any) => { + throw e; + } + }); } - dispose(subscription: SubscriptionLike): void { subscription.unsubscribe(); } + dispose(subscription: SubscriptionLike): void { + subscription.unsubscribe(); + } - onDestroy(subscription: SubscriptionLike): void { subscription.unsubscribe(); } + onDestroy(subscription: SubscriptionLike): void { + subscription.unsubscribe(); + } } class PromiseStrategy implements SubscriptionStrategy { createSubscription(async: Promise, updateLatestValue: (v: any) => any): Promise { - return async.then(updateLatestValue, e => { throw e; }); + return async.then(updateLatestValue, e => { + throw e; + }); } dispose(subscription: Promise): void {} @@ -74,7 +85,7 @@ export class AsyncPipe implements OnDestroy, PipeTransform { private _subscription: SubscriptionLike|Promise|null = null; private _obj: Observable|Promise|EventEmitter|null = null; - private _strategy: SubscriptionStrategy = null !; + private _strategy: SubscriptionStrategy = null!; constructor(private _ref: ChangeDetectorRef) {} @@ -130,7 +141,7 @@ export class AsyncPipe implements OnDestroy, PipeTransform { } private _dispose(): void { - this._strategy.dispose(this._subscription !); + this._strategy.dispose(this._subscription!); this._latestValue = null; this._latestReturnedValue = null; this._subscription = null; diff --git a/packages/common/src/pipes/i18n_plural_pipe.ts b/packages/common/src/pipes/i18n_plural_pipe.ts index 0a4fa6a030ebd..e8500d86bd867 100644 --- a/packages/common/src/pipes/i18n_plural_pipe.ts +++ b/packages/common/src/pipes/i18n_plural_pipe.ts @@ -7,7 +7,9 @@ */ import {Pipe, PipeTransform} from '@angular/core'; -import {NgLocalization, getPluralCategory} from '../i18n/localization'; + +import {getPluralCategory, NgLocalization} from '../i18n/localization'; + import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; const _INTERPOLATION_REGEXP: RegExp = /#/g; diff --git a/packages/common/src/pipes/index.ts b/packages/common/src/pipes/index.ts index 9dc1e8d10a296..708b67f49ad05 100644 --- a/packages/common/src/pipes/index.ts +++ b/packages/common/src/pipes/index.ts @@ -26,11 +26,11 @@ export { CurrencyPipe, DatePipe, DecimalPipe, - KeyValue, - KeyValuePipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, + KeyValue, + KeyValuePipe, LowerCasePipe, PercentPipe, SlicePipe, diff --git a/packages/common/src/pipes/json_pipe.ts b/packages/common/src/pipes/json_pipe.ts index 7ecbdddbe370b..4bae1ec2a055e 100644 --- a/packages/common/src/pipes/json_pipe.ts +++ b/packages/common/src/pipes/json_pipe.ts @@ -28,5 +28,7 @@ export class JsonPipe implements PipeTransform { /** * @param value A value of any type to convert into a JSON-format string. */ - transform(value: any): string { return JSON.stringify(value, null, 2); } + transform(value: any): string { + return JSON.stringify(value, null, 2); + } } diff --git a/packages/common/src/pipes/keyvalue_pipe.ts b/packages/common/src/pipes/keyvalue_pipe.ts index 592e57f95849a..a0e56be48a75d 100644 --- a/packages/common/src/pipes/keyvalue_pipe.ts +++ b/packages/common/src/pipes/keyvalue_pipe.ts @@ -47,7 +47,7 @@ export interface KeyValue { export class KeyValuePipe implements PipeTransform { constructor(private readonly differs: KeyValueDiffers) {} - private differ !: KeyValueDiffer; + private differ!: KeyValueDiffer; private keyValues: Array> = []; transform(input: null, compareFn?: (a: KeyValue, b: KeyValue) => number): null; @@ -90,7 +90,7 @@ export class KeyValuePipe implements PipeTransform { if (differChanges) { this.keyValues = []; differChanges.forEachItem((r: KeyValueChangeRecord) => { - this.keyValues.push(makeKeyValuePair(r.key, r.currentValue !)); + this.keyValues.push(makeKeyValuePair(r.key, r.currentValue!)); }); this.keyValues.sort(compareFn); } diff --git a/packages/common/src/pipes/number_pipe.ts b/packages/common/src/pipes/number_pipe.ts index db8c6546faf67..e681f27803c59 100644 --- a/packages/common/src/pipes/number_pipe.ts +++ b/packages/common/src/pipes/number_pipe.ts @@ -253,7 +253,7 @@ function isEmpty(value: any): boolean { /** * Transforms a string into a number (if needed). */ -function strToNumber(value: number | string): number { +function strToNumber(value: number|string): number { // Convert strings to numbers if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) { return Number(value); diff --git a/packages/common/src/pipes/slice_pipe.ts b/packages/common/src/pipes/slice_pipe.ts index 13f57fc2ae7cb..59fd55da63fe2 100644 --- a/packages/common/src/pipes/slice_pipe.ts +++ b/packages/common/src/pipes/slice_pipe.ts @@ -75,5 +75,7 @@ export class SlicePipe implements PipeTransform { return value.slice(start, end); } - private supports(obj: any): boolean { return typeof obj === 'string' || Array.isArray(obj); } + private supports(obj: any): boolean { + return typeof obj === 'string' || Array.isArray(obj); + } } diff --git a/packages/common/src/viewport_scroller.ts b/packages/common/src/viewport_scroller.ts index 39044f51d93ca..9462a709a327b 100644 --- a/packages/common/src/viewport_scroller.ts +++ b/packages/common/src/viewport_scroller.ts @@ -186,7 +186,9 @@ export class NullViewportScroller implements ViewportScroller { /** * Empty implementation */ - getScrollPosition(): [number, number] { return [0, 0]; } + getScrollPosition(): [number, number] { + return [0, 0]; + } /** * Empty implementation diff --git a/packages/common/test/cookie_spec.ts b/packages/common/test/cookie_spec.ts index 36b10c0e35328..0fa17ba5ab1d6 100644 --- a/packages/common/test/cookie_spec.ts +++ b/packages/common/test/cookie_spec.ts @@ -9,12 +9,12 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {parseCookieValue} from '@angular/common/src/cookie'; import {describe, expect, it} from '@angular/core/testing/src/testing_internal'; diff --git a/packages/common/test/directives/ng_class_spec.ts b/packages/common/test/directives/ng_class_spec.ts index d31771932de40..419b443f8370d 100644 --- a/packages/common/test/directives/ng_class_spec.ts +++ b/packages/common/test/directives/ng_class_spec.ts @@ -7,7 +7,7 @@ */ import {Component} from '@angular/core'; -import {ComponentFixture, TestBed, async} from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; { describe('binding to CSS class list', () => { @@ -18,14 +18,18 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; } function detectChangesAndExpectClassName(classes: string): void { - fixture !.detectChanges(); - let nonNormalizedClassName = fixture !.debugElement.children[0].nativeElement.className; + fixture!.detectChanges(); + let nonNormalizedClassName = fixture!.debugElement.children[0].nativeElement.className; expect(normalizeClassNames(nonNormalizedClassName)).toEqual(normalizeClassNames(classes)); } - function getComponent(): TestComponent { return fixture !.debugElement.componentInstance; } + function getComponent(): TestComponent { + return fixture!.debugElement.componentInstance; + } - afterEach(() => { fixture = null; }); + afterEach(() => { + fixture = null; + }); beforeEach(() => { TestBed.configureTestingModule({ @@ -43,7 +47,6 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; })); describe('expressions evaluating to objects', () => { - it('should add classes specified in an object literal', async(() => { fixture = createTestComponent('
'); @@ -74,13 +77,13 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; detectChangesAndExpectClassName('foo'); - objExpr !['bar'] = true; + objExpr!['bar'] = true; detectChangesAndExpectClassName('foo bar'); - objExpr !['baz'] = true; + objExpr!['baz'] = true; detectChangesAndExpectClassName('foo bar baz'); - delete (objExpr !['bar']); + delete (objExpr!['bar']); detectChangesAndExpectClassName('foo baz'); })); @@ -129,7 +132,6 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; }); describe('expressions evaluating to lists', () => { - it('should add classes specified in a list literal', async(() => { fixture = createTestComponent(`
`); @@ -194,14 +196,13 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; it('should throw with descriptive error message when CSS class is not a string', () => { fixture = createTestComponent(`
`); - expect(() => fixture !.detectChanges()) + expect(() => fixture!.detectChanges()) .toThrowError( /NgClass can only toggle CSS classes expressed as strings, got \[object Object\]/); }); }); describe('expressions evaluating to sets', () => { - it('should add and remove classes if the set instance changed', async(() => { fixture = createTestComponent('
'); let setExpr = new Set(); @@ -217,7 +218,6 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; }); describe('expressions evaluating to string', () => { - it('should add classes specified in a string literal', async(() => { fixture = createTestComponent(`
`); detectChangesAndExpectClassName('foo bar foo-bar fooBar'); @@ -257,19 +257,17 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; getComponent().strExpr = ''; detectChangesAndExpectClassName('foo'); })); - }); describe('cooperation with other class-changing constructs', () => { - it('should co-operate with the class attribute', async(() => { fixture = createTestComponent('
'); const objExpr = getComponent().objExpr; - objExpr !['bar'] = true; + objExpr!['bar'] = true; detectChangesAndExpectClassName('init foo bar'); - objExpr !['foo'] = false; + objExpr!['foo'] = false; detectChangesAndExpectClassName('init bar'); getComponent().objExpr = null; @@ -280,10 +278,10 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; fixture = createTestComponent(`
`); const objExpr = getComponent().objExpr; - objExpr !['bar'] = true; + objExpr!['bar'] = true; detectChangesAndExpectClassName(`init foo bar`); - objExpr !['foo'] = false; + objExpr!['foo'] = false; detectChangesAndExpectClassName(`init bar`); getComponent().objExpr = null; @@ -306,10 +304,10 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; createTestComponent(`
`); const objExpr = getComponent().objExpr; - objExpr !['bar'] = true; + objExpr!['bar'] = true; detectChangesAndExpectClassName(`init foo bar`); - objExpr !['foo'] = false; + objExpr!['foo'] = false; detectChangesAndExpectClassName(`init bar`); getComponent().objExpr = null; @@ -324,10 +322,10 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; detectChangesAndExpectClassName('init foo baz'); - objExpr !['bar'] = true; + objExpr!['bar'] = true; detectChangesAndExpectClassName('init foo baz bar'); - objExpr !['foo'] = false; + objExpr!['foo'] = false; detectChangesAndExpectClassName('init baz bar'); getComponent().condition = false; @@ -342,7 +340,7 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; detectChangesAndExpectClassName('init foo'); - cmp.objExpr !['bar'] = true; + cmp.objExpr!['bar'] = true; detectChangesAndExpectClassName('init foo bar'); cmp.strExpr = 'baz'; @@ -354,7 +352,6 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; }); describe('prevent regressions', () => { - // https://github.com/angular/angular/issues/34336 it('should not write to the native node unless the bound expression has changed', () => { fixture = createTestComponent(`
`); @@ -392,7 +389,6 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; expect(leading.className).toBe('foo'); expect(trailing.className).toBe('foo'); }); - }); }); } @@ -406,7 +402,9 @@ class TestComponent { objExpr: {[klass: string]: any}|null = {'foo': true, 'bar': false}; strExpr: string|null = 'foo'; - constructor() { this.setExpr.add('foo'); } + constructor() { + this.setExpr.add('foo'); + } } function createTestComponent(template: string): ComponentFixture { diff --git a/packages/common/test/directives/ng_component_outlet_spec.ts b/packages/common/test/directives/ng_component_outlet_spec.ts index b00c2e8efe46d..e5ddc9d63b796 100644 --- a/packages/common/test/directives/ng_component_outlet_spec.ts +++ b/packages/common/test/directives/ng_component_outlet_spec.ts @@ -8,13 +8,14 @@ import {CommonModule} from '@angular/common'; import {NgComponentOutlet} from '@angular/common/src/directives/ng_component_outlet'; -import {Compiler, Component, ComponentRef, Inject, InjectionToken, Injector, NO_ERRORS_SCHEMA, NgModule, NgModuleFactory, Optional, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef} from '@angular/core'; -import {TestBed, async} from '@angular/core/testing'; +import {Compiler, Component, ComponentRef, Inject, InjectionToken, Injector, NgModule, NgModuleFactory, NO_ERRORS_SCHEMA, Optional, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef} from '@angular/core'; +import {async, TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('insert/remove', () => { - - beforeEach(() => { TestBed.configureTestingModule({imports: [TestModule]}); }); + beforeEach(() => { + TestBed.configureTestingModule({imports: [TestModule]}); + }); it('should do nothing if component is null', async(() => { const template = ``; @@ -51,7 +52,7 @@ describe('insert/remove', () => { fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('foo'); expect(fixture.componentInstance.cmpRef).toBeAnInstanceOf(ComponentRef); - expect(fixture.componentInstance.cmpRef !.instance).toBeAnInstanceOf(InjectedComponent); + expect(fixture.componentInstance.cmpRef!.instance).toBeAnInstanceOf(InjectedComponent); })); @@ -99,11 +100,10 @@ describe('insert/remove', () => { [{provide: TEST_TOKEN, useValue: uniqueValue}], fixture.componentRef.injector); fixture.detectChanges(); - let cmpRef: ComponentRef = fixture.componentInstance.cmpRef !; + let cmpRef: ComponentRef = fixture.componentInstance.cmpRef!; expect(cmpRef).toBeAnInstanceOf(ComponentRef); expect(cmpRef.instance).toBeAnInstanceOf(InjectedComponent); expect(cmpRef.instance.testToken).toBe(uniqueValue); - })); @@ -114,7 +114,7 @@ describe('insert/remove', () => { fixture.componentInstance.cmpRef = null; fixture.componentInstance.currentComponent = InjectedComponent; fixture.detectChanges(); - let cmpRef: ComponentRef = fixture.componentInstance.cmpRef !; + let cmpRef: ComponentRef = fixture.componentInstance.cmpRef!; expect(cmpRef).toBeAnInstanceOf(ComponentRef); expect(cmpRef.instance).toBeAnInstanceOf(InjectedComponent); expect(cmpRef.instance.testToken).toBeNull(); @@ -166,7 +166,7 @@ describe('insert/remove', () => { fixture.componentInstance.currentComponent = Module2InjectedComponent; fixture.detectChanges(); - const moduleRef = fixture.componentInstance.ngComponentOutlet['_moduleRef'] !; + const moduleRef = fixture.componentInstance.ngComponentOutlet['_moduleRef']!; spyOn(moduleRef, 'destroy').and.callThrough(); expect(moduleRef.destroy).not.toHaveBeenCalled(); @@ -224,21 +224,25 @@ const TEST_CMP_TEMPLATE = @Component({selector: 'test-cmp', template: TEST_CMP_TEMPLATE}) class TestComponent { // TODO(issue/24571): remove '!'. - currentComponent !: Type| null; + currentComponent!: Type|null; // TODO(issue/24571): remove '!'. - injector !: Injector; + injector!: Injector; // TODO(issue/24571): remove '!'. - projectables !: any[][]; + projectables!: any[][]; // TODO(issue/24571): remove '!'. - module !: NgModuleFactory; + module!: NgModuleFactory; - get cmpRef(): ComponentRef|null { return this.ngComponentOutlet['_componentRef']; } - set cmpRef(value: ComponentRef|null) { this.ngComponentOutlet['_componentRef'] = value; } + get cmpRef(): ComponentRef|null { + return this.ngComponentOutlet['_componentRef']; + } + set cmpRef(value: ComponentRef|null) { + this.ngComponentOutlet['_componentRef'] = value; + } // TODO(issue/24571): remove '!'. - @ViewChildren(TemplateRef) tplRefs !: QueryList>; + @ViewChildren(TemplateRef) tplRefs!: QueryList>; // TODO(issue/24571): remove '!'. - @ViewChild(NgComponentOutlet, {static: true}) ngComponentOutlet !: NgComponentOutlet; + @ViewChild(NgComponentOutlet, {static: true}) ngComponentOutlet!: NgComponentOutlet; constructor(public vcRef: ViewContainerRef) {} } diff --git a/packages/common/test/directives/ng_for_spec.ts b/packages/common/test/directives/ng_for_spec.ts index fef7e67976573..6ce561de1221a 100644 --- a/packages/common/test/directives/ng_for_spec.ts +++ b/packages/common/test/directives/ng_for_spec.ts @@ -8,7 +8,7 @@ import {CommonModule} from '@angular/common'; import {Component} from '@angular/core'; -import {ComponentFixture, TestBed, async} from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {expect} from '@angular/platform-browser/testing/src/matchers'; @@ -18,14 +18,18 @@ let thisArg: any; describe('ngFor', () => { let fixture: ComponentFixture; - function getComponent(): TestComponent { return fixture.componentInstance; } + function getComponent(): TestComponent { + return fixture.componentInstance; + } function detectChangesAndExpectText(text: string): void { fixture.detectChanges(); expect(fixture.nativeElement).toHaveText(text); } - afterEach(() => { fixture = null as any; }); + afterEach(() => { + fixture = null as any; + }); beforeEach(() => { TestBed.configureTestingModule({ @@ -103,7 +107,7 @@ let thisArg: any; detectChangesAndExpectText('1;2;'); - getComponent().items = null !; + getComponent().items = null!; detectChangesAndExpectText(''); getComponent().items = [1, 2, 3]; @@ -377,16 +381,24 @@ let thisArg: any; } class Foo { - toString() { return 'foo'; } + toString() { + return 'foo'; + } } @Component({selector: 'test-cmp', template: ''}) class TestComponent { value: any; items: any[] = [1, 2]; - trackById(index: number, item: any): string { return item['id']; } - trackByIndex(index: number, item: any): number { return index; } - trackByContext(): void { thisArg = this; } + trackById(index: number, item: any): string { + return item['id']; + } + trackByIndex(index: number, item: any): number { + return index; + } + trackByContext(): void { + thisArg = this; + } } const TEMPLATE = '
{{item.toString()}};
'; diff --git a/packages/common/test/directives/ng_if_spec.ts b/packages/common/test/directives/ng_if_spec.ts index 84b73b4ce1436..2e9cd74069a71 100644 --- a/packages/common/test/directives/ng_if_spec.ts +++ b/packages/common/test/directives/ng_if_spec.ts @@ -8,7 +8,7 @@ import {CommonModule, ɵgetDOM as getDOM} from '@angular/common'; import {Component} from '@angular/core'; -import {ComponentFixture, TestBed, async} from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {expect} from '@angular/platform-browser/testing/src/matchers'; @@ -16,9 +16,13 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('ngIf directive', () => { let fixture: ComponentFixture; - function getComponent(): TestComponent { return fixture.componentInstance; } + function getComponent(): TestComponent { + return fixture.componentInstance; + } - afterEach(() => { fixture = null !; }); + afterEach(() => { + fixture = null!; + }); beforeEach(() => { TestBed.configureTestingModule({ diff --git a/packages/common/test/directives/ng_plural_spec.ts b/packages/common/test/directives/ng_plural_spec.ts index 07e6e66740b7f..9a5a30bb983d2 100644 --- a/packages/common/test/directives/ng_plural_spec.ts +++ b/packages/common/test/directives/ng_plural_spec.ts @@ -8,21 +8,25 @@ import {CommonModule, NgLocalization} from '@angular/common'; import {Component, Injectable} from '@angular/core'; -import {ComponentFixture, TestBed, async} from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; { describe('ngPlural', () => { let fixture: ComponentFixture; - function getComponent(): TestComponent { return fixture.componentInstance; } + function getComponent(): TestComponent { + return fixture.componentInstance; + } function detectChangesAndExpectText(text: string): void { fixture.detectChanges(); expect(fixture.nativeElement).toHaveText(text); } - afterEach(() => { fixture = null !; }); + afterEach(() => { + fixture = null!; + }); beforeEach(() => { TestBed.configureTestingModule({ diff --git a/packages/common/test/directives/ng_style_spec.ts b/packages/common/test/directives/ng_style_spec.ts index aaba40cd80e88..3ec43fa203aa4 100644 --- a/packages/common/test/directives/ng_style_spec.ts +++ b/packages/common/test/directives/ng_style_spec.ts @@ -8,19 +8,23 @@ import {CommonModule} from '@angular/common'; import {Component} from '@angular/core'; -import {ComponentFixture, TestBed, async} from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; { describe('NgStyle', () => { let fixture: ComponentFixture; - function getComponent(): TestComponent { return fixture.componentInstance; } + function getComponent(): TestComponent { + return fixture.componentInstance; + } function expectNativeEl(fixture: ComponentFixture): any { return expect(fixture.debugElement.children[0].nativeElement); } - afterEach(() => { fixture = null !; }); + afterEach(() => { + fixture = null!; + }); beforeEach(() => { TestBed.configureTestingModule({declarations: [TestComponent], imports: [CommonModule]}); @@ -159,7 +163,6 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; })); it('should not write to the native node unless the bound expression has changed', () => { - const template = `
`; fixture = createTestComponent(template); @@ -189,7 +192,6 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing'; fixture.detectChanges(); expectNativeEl(fixture).toHaveCssStyle({'width': '400px'}); }); - }); } diff --git a/packages/common/test/directives/ng_switch_spec.ts b/packages/common/test/directives/ng_switch_spec.ts index 436d8ad36bb18..0dbeab3acef4d 100644 --- a/packages/common/test/directives/ng_switch_spec.ts +++ b/packages/common/test/directives/ng_switch_spec.ts @@ -15,14 +15,18 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('NgSwitch', () => { let fixture: ComponentFixture; - function getComponent(): TestComponent { return fixture.componentInstance; } + function getComponent(): TestComponent { + return fixture.componentInstance; + } function detectChangesAndExpectText(text: string): void { fixture.detectChanges(); expect(fixture.nativeElement).toHaveText(text); } - afterEach(() => { fixture = null !; }); + afterEach(() => { + fixture = null!; + }); beforeEach(() => { TestBed.configureTestingModule({ @@ -118,13 +122,14 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; }); describe('corner cases', () => { - it('should not create the default case if another case matches', () => { const log: string[] = []; @Directive({selector: '[test]'}) class TestDirective { - constructor(@Attribute('test') test: string) { log.push(test); } + constructor(@Attribute('test') test: string) { + log.push(test); + } } const template = '
' + @@ -149,7 +154,6 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; fixture = createTestComponent(template); detectChangesAndExpectText('when default1;when default2;'); - }); it('should allow defaults before cases', () => { @@ -223,8 +227,8 @@ class TestComponent { ` }) class ComplexComponent { - @ViewChild('foo', {static: true}) foo !: TemplateRef; - @ViewChild('bar', {static: true}) bar !: TemplateRef; + @ViewChild('foo', {static: true}) foo!: TemplateRef; + @ViewChild('bar', {static: true}) bar!: TemplateRef; state: string = 'case1'; } diff --git a/packages/common/test/directives/ng_template_outlet_spec.ts b/packages/common/test/directives/ng_template_outlet_spec.ts index 57ee45b50976b..b6f6776806e1f 100644 --- a/packages/common/test/directives/ng_template_outlet_spec.ts +++ b/packages/common/test/directives/ng_template_outlet_spec.ts @@ -8,20 +8,24 @@ import {CommonModule} from '@angular/common'; import {Component, ContentChildren, Directive, Injectable, NO_ERRORS_SCHEMA, OnDestroy, QueryList, TemplateRef} from '@angular/core'; -import {ComponentFixture, TestBed, async} from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('NgTemplateOutlet', () => { let fixture: ComponentFixture; - function setTplRef(value: any): void { fixture.componentInstance.currentTplRef = value; } + function setTplRef(value: any): void { + fixture.componentInstance.currentTplRef = value; + } function detectChangesAndExpectText(text: string): void { fixture.detectChanges(); expect(fixture.debugElement.nativeElement).toHaveText(text); } - afterEach(() => { fixture = null as any; }); + afterEach(() => { + fixture = null as any; + }); beforeEach(() => { TestBed.configureTestingModule({ @@ -58,7 +62,7 @@ describe('NgTemplateOutlet', () => { ``; fixture = createTestComponent(template); fixture.detectChanges(); - const refs = fixture.debugElement.children[0].references !['refs']; + const refs = fixture.debugElement.children[0].references!['refs']; setTplRef(refs.tplRefs.first); detectChangesAndExpectText('foo'); @@ -74,7 +78,7 @@ describe('NgTemplateOutlet', () => { fixture = createTestComponent(template); fixture.detectChanges(); - const refs = fixture.debugElement.children[0].references !['refs']; + const refs = fixture.debugElement.children[0].references!['refs']; setTplRef(refs.tplRefs.first); detectChangesAndExpectText('foo'); @@ -223,7 +227,7 @@ describe('NgTemplateOutlet', () => { ``; fixture = createTestComponent(template); fixture.detectChanges(); - const refs = fixture.debugElement.children[0].references !['refs']; + const refs = fixture.debugElement.children[0].references!['refs']; setTplRef(refs.tplRefs.first); detectChangesAndExpectText('foo'); @@ -236,7 +240,6 @@ describe('NgTemplateOutlet', () => { detectChangesAndExpectText('foo'); }).not.toThrow(); })); - }); @Injectable() @@ -248,19 +251,21 @@ class DestroyedSpyService { class DestroyableCmpt implements OnDestroy { constructor(private _spyService: DestroyedSpyService) {} - ngOnDestroy(): void { this._spyService.destroyed = true; } + ngOnDestroy(): void { + this._spyService.destroyed = true; + } } @Directive({selector: 'tpl-refs', exportAs: 'tplRefs'}) class CaptureTplRefs { // TODO(issue/24571): remove '!'. - @ContentChildren(TemplateRef) tplRefs !: QueryList>; + @ContentChildren(TemplateRef) tplRefs!: QueryList>; } @Component({selector: 'test-cmp', template: ''}) class TestComponent { // TODO(issue/24571): remove '!'. - currentTplRef !: TemplateRef; + currentTplRef!: TemplateRef; context: any = {foo: 'bar'}; value = 'bar'; } diff --git a/packages/common/test/directives/non_bindable_spec.ts b/packages/common/test/directives/non_bindable_spec.ts index d77194450cb54..ceda2fb42fd95 100644 --- a/packages/common/test/directives/non_bindable_spec.ts +++ b/packages/common/test/directives/non_bindable_spec.ts @@ -9,13 +9,12 @@ import {ɵgetDOM as getDOM} from '@angular/common'; import {Component, Directive} from '@angular/core'; import {ElementRef} from '@angular/core/src/linker/element_ref'; -import {ComponentFixture, TestBed, async} from '@angular/core/testing'; +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {hasClass} from '@angular/platform-browser/testing/src/browser_util'; import {expect} from '@angular/platform-browser/testing/src/matchers'; { describe('non-bindable', () => { - beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestComponent, TestDirective], @@ -53,13 +52,17 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; @Directive({selector: '[test-dec]'}) class TestDirective { - constructor(el: ElementRef) { el.nativeElement.classList.add('compiled'); } + constructor(el: ElementRef) { + el.nativeElement.classList.add('compiled'); + } } @Component({selector: 'test-cmp', template: ''}) class TestComponent { text: string; - constructor() { this.text = 'foo'; } + constructor() { + this.text = 'foo'; + } } function createTestComponent(template: string): ComponentFixture { diff --git a/packages/common/test/i18n/format_date_spec.ts b/packages/common/test/i18n/format_date_spec.ts index 7bbe33938888a..cd1b6dfcae4fe 100644 --- a/packages/common/test/i18n/format_date_spec.ts +++ b/packages/common/test/i18n/format_date_spec.ts @@ -12,35 +12,50 @@ import localeEnExtra from '@angular/common/locales/extra/en'; import localeHu from '@angular/common/locales/hu'; import localeSr from '@angular/common/locales/sr'; import localeTh from '@angular/common/locales/th'; -import {isDate, toDate, formatDate} from '@angular/common/src/i18n/format_date'; -import {ɵDEFAULT_LOCALE_ID, ɵunregisterLocaleData, ɵregisterLocaleData} from '@angular/core'; +import {formatDate, isDate, toDate} from '@angular/common/src/i18n/format_date'; +import {ɵDEFAULT_LOCALE_ID, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; describe('Format date', () => { describe('toDate', () => { - it('should support date', () => { expect(isDate(toDate(new Date()))).toBeTruthy(); }); + it('should support date', () => { + expect(isDate(toDate(new Date()))).toBeTruthy(); + }); - it('should support int', () => { expect(isDate(toDate(123456789))).toBeTruthy(); }); + it('should support int', () => { + expect(isDate(toDate(123456789))).toBeTruthy(); + }); - it('should support numeric strings', - () => { expect(isDate(toDate('123456789'))).toBeTruthy(); }); + it('should support numeric strings', () => { + expect(isDate(toDate('123456789'))).toBeTruthy(); + }); - it('should support decimal strings', - () => { expect(isDate(toDate('123456789.11'))).toBeTruthy(); }); + it('should support decimal strings', () => { + expect(isDate(toDate('123456789.11'))).toBeTruthy(); + }); - it('should support ISO string', - () => { expect(isDate(toDate('2015-06-15T21:43:11Z'))).toBeTruthy(); }); + it('should support ISO string', () => { + expect(isDate(toDate('2015-06-15T21:43:11Z'))).toBeTruthy(); + }); - it('should throw for empty string', () => { expect(() => toDate('')).toThrow(); }); + it('should throw for empty string', () => { + expect(() => toDate('')).toThrow(); + }); - it('should throw for alpha numeric strings', - () => { expect(() => toDate('123456789 hello')).toThrow(); }); + it('should throw for alpha numeric strings', () => { + expect(() => toDate('123456789 hello')).toThrow(); + }); - it('should throw for NaN', () => { expect(() => toDate(Number.NaN)).toThrow(); }); + it('should throw for NaN', () => { + expect(() => toDate(Number.NaN)).toThrow(); + }); - it('should support ISO string without time', - () => { expect(isDate(toDate('2015-01-01'))).toBeTruthy(); }); + it('should support ISO string without time', () => { + expect(isDate(toDate('2015-01-01'))).toBeTruthy(); + }); - it('should throw for objects', () => { expect(() => toDate({} as any)).toThrow(); }); + it('should throw for objects', () => { + expect(() => toDate({} as any)).toThrow(); + }); }); describe('formatDate', () => { @@ -49,7 +64,7 @@ describe('Format date', () => { let date: Date; // Check the transformation of a date into a pattern - function expectDateFormatAs(date: Date | string, pattern: any, output: string): void { + function expectDateFormatAs(date: Date|string, pattern: any, output: string): void { expect(formatDate(date, pattern, ɵDEFAULT_LOCALE_ID)) .toEqual(output, `pattern: "${pattern}"`); } @@ -65,7 +80,9 @@ describe('Format date', () => { afterAll(() => ɵunregisterLocaleData()); - beforeEach(() => { date = new Date(2015, 5, 15, 9, 3, 1, 550); }); + beforeEach(() => { + date = new Date(2015, 5, 15, 9, 3, 1, 550); + }); it('should format each component correctly', () => { const dateFixtures: any = { @@ -293,7 +310,7 @@ describe('Format date', () => { }); it('should remove bidi control characters', - () => expect(formatDate(date, 'MM/dd/yyyy', ɵDEFAULT_LOCALE_ID) !.length).toEqual(10)); + () => expect(formatDate(date, 'MM/dd/yyyy', ɵDEFAULT_LOCALE_ID)!.length).toEqual(10)); it(`should format the date correctly in various locales`, () => { expect(formatDate(date, 'short', 'de')).toEqual('15.06.15, 09:03'); diff --git a/packages/common/test/i18n/format_number_spec.ts b/packages/common/test/i18n/format_number_spec.ts index c6f384095398b..f16cb9ec1731a 100644 --- a/packages/common/test/i18n/format_number_spec.ts +++ b/packages/common/test/i18n/format_number_spec.ts @@ -6,13 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ +import {formatCurrency, formatNumber, formatPercent} from '@angular/common'; +import localeAr from '@angular/common/locales/ar'; import localeEn from '@angular/common/locales/en'; import localeEsUS from '@angular/common/locales/es-US'; import localeFr from '@angular/common/locales/fr'; -import localeAr from '@angular/common/locales/ar'; -import {formatCurrency, formatNumber, formatPercent} from '@angular/common'; +import {ɵDEFAULT_LOCALE_ID, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; import {describe, expect, it} from '@angular/core/testing/src/testing_internal'; -import {ɵDEFAULT_LOCALE_ID, ɵunregisterLocaleData, ɵregisterLocaleData} from '@angular/core'; describe('Format number', () => { beforeAll(() => { @@ -44,8 +44,9 @@ describe('Format number', () => { }); describe('transform with custom locales', () => { - it('should return the correct format for es-US', - () => { expect(formatNumber(9999999.99, 'es-US', '1.2-2')).toEqual('9,999,999.99'); }); + it('should return the correct format for es-US', () => { + expect(formatNumber(9999999.99, 'es-US', '1.2-2')).toEqual('9,999,999.99'); + }); }); }); diff --git a/packages/common/test/i18n/locale_data_api_spec.ts b/packages/common/test/i18n/locale_data_api_spec.ts index c4cb78d6f002b..74eb1914e765a 100644 --- a/packages/common/test/i18n/locale_data_api_spec.ts +++ b/packages/common/test/i18n/locale_data_api_spec.ts @@ -6,14 +6,14 @@ * found in the LICENSE file at https://angular.io/license */ -import {ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; - import localeEn from '@angular/common/locales/en'; -import localeFr from '@angular/common/locales/fr'; -import localeZh from '@angular/common/locales/zh'; import localeEnAU from '@angular/common/locales/en-AU'; +import localeFr from '@angular/common/locales/fr'; import localeHe from '@angular/common/locales/he'; -import {getCurrencySymbol, getLocaleDateFormat, FormatWidth, getNumberOfCurrencyDigits, getLocaleDirection} from '../../src/i18n/locale_data_api'; +import localeZh from '@angular/common/locales/zh'; +import {ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; + +import {FormatWidth, getCurrencySymbol, getLocaleDateFormat, getLocaleDirection, getNumberOfCurrencyDigits} from '../../src/i18n/locale_data_api'; { describe('locale data api', () => { @@ -25,7 +25,9 @@ import {getCurrencySymbol, getLocaleDateFormat, FormatWidth, getNumberOfCurrency ɵregisterLocaleData(localeHe); }); - afterAll(() => { ɵunregisterLocaleData(); }); + afterAll(() => { + ɵunregisterLocaleData(); + }); describe('getting currency symbol', () => { it('should return the correct symbol', () => { @@ -55,16 +57,19 @@ import {getCurrencySymbol, getLocaleDateFormat, FormatWidth, getNumberOfCurrency }); describe('getLastDefinedValue', () => { - it('should find the last defined date format when format not defined', - () => { expect(getLocaleDateFormat('zh', FormatWidth.Long)).toEqual('y年M月d日'); }); + it('should find the last defined date format when format not defined', () => { + expect(getLocaleDateFormat('zh', FormatWidth.Long)).toEqual('y年M月d日'); + }); }); describe('getDirectionality', () => { - it('should have correct direction for rtl languages', - () => { expect(getLocaleDirection('he')).toEqual('rtl'); }); + it('should have correct direction for rtl languages', () => { + expect(getLocaleDirection('he')).toEqual('rtl'); + }); - it('should have correct direction for ltr languages', - () => { expect(getLocaleDirection('en')).toEqual('ltr'); }); + it('should have correct direction for ltr languages', () => { + expect(getLocaleDirection('en')).toEqual('ltr'); + }); }); }); } diff --git a/packages/common/test/i18n/localization_spec.ts b/packages/common/test/i18n/localization_spec.ts index dd078c6d89c4d..01c22b4e6c7d1 100644 --- a/packages/common/test/i18n/localization_spec.ts +++ b/packages/common/test/i18n/localization_spec.ts @@ -6,13 +6,13 @@ * found in the LICENSE file at https://angular.io/license */ +import localeFr from '@angular/common/locales/fr'; import localeRo from '@angular/common/locales/ro'; import localeSr from '@angular/common/locales/sr'; import localeZgh from '@angular/common/locales/zgh'; -import localeFr from '@angular/common/locales/fr'; -import {LOCALE_ID, ɵunregisterLocaleData, ɵregisterLocaleData} from '@angular/core'; -import {TestBed, inject} from '@angular/core/testing'; -import {NgLocaleLocalization, NgLocalization, getPluralCategory} from '@angular/common/src/i18n/localization'; +import {getPluralCategory, NgLocaleLocalization, NgLocalization} from '@angular/common/src/i18n/localization'; +import {LOCALE_ID, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; +import {inject, TestBed} from '@angular/core/testing'; { describe('l10n', () => { diff --git a/packages/common/test/location/location_spec.ts b/packages/common/test/location/location_spec.ts index 92b876f5f656f..9bee33fcba47f 100644 --- a/packages/common/test/location/location_spec.ts +++ b/packages/common/test/location/location_spec.ts @@ -8,7 +8,7 @@ import {CommonModule, Location, LocationStrategy, PathLocationStrategy, PlatformLocation} from '@angular/common'; import {MockPlatformLocation} from '@angular/common/testing'; -import {TestBed, inject} from '@angular/core/testing'; +import {inject, TestBed} from '@angular/core/testing'; const baseUrl = '/base'; @@ -46,14 +46,18 @@ describe('Location Class', () => { imports: [CommonModule], providers: [ {provide: LocationStrategy, useClass: PathLocationStrategy}, - {provide: PlatformLocation, useFactory: () => { return new MockPlatformLocation(); }}, + { + provide: PlatformLocation, + useFactory: () => { + return new MockPlatformLocation(); + } + }, {provide: Location, useClass: Location, deps: [LocationStrategy, PlatformLocation]}, ] }); }); it('should get the state object', inject([Location], (location: Location) => { - expect(location.getState()).toBe(null); location.go('/test', '', {foo: 'bar'}); @@ -62,7 +66,6 @@ describe('Location Class', () => { })); it('should work after using back button', inject([Location], (location: Location) => { - expect(location.getState()).toBe(null); location.go('/test1', '', {url: 'test1'}); @@ -74,7 +77,6 @@ describe('Location Class', () => { expect(location.getState()).toEqual({url: 'test1'}); })); - }); describe('location.onUrlChange()', () => { @@ -83,7 +85,12 @@ describe('Location Class', () => { imports: [CommonModule], providers: [ {provide: LocationStrategy, useClass: PathLocationStrategy}, - {provide: PlatformLocation, useFactory: () => { return new MockPlatformLocation(); }}, + { + provide: PlatformLocation, + useFactory: () => { + return new MockPlatformLocation(); + } + }, {provide: Location, useClass: Location, deps: [LocationStrategy, PlatformLocation]}, ] }); @@ -95,8 +102,9 @@ describe('Location Class', () => { it('should add registered functions to urlChangeListeners', inject([Location], (location: Location) => { - - function changeListener(url: string, state: unknown) { return undefined; } + function changeListener(url: string, state: unknown) { + return undefined; + } expect((location as any)._urlChangeListeners.length).toBe(0); @@ -104,8 +112,6 @@ describe('Location Class', () => { expect((location as any)._urlChangeListeners.length).toBe(1); expect((location as any)._urlChangeListeners[0]).toEqual(changeListener); - })); - }); }); \ No newline at end of file diff --git a/packages/common/test/pipes/async_pipe_spec.ts b/packages/common/test/pipes/async_pipe_spec.ts index 29f945ef9b86a..0d1635938c78c 100644 --- a/packages/common/test/pipes/async_pipe_spec.ts +++ b/packages/common/test/pipes/async_pipe_spec.ts @@ -15,7 +15,6 @@ import {SpyChangeDetectorRef} from '../spies'; { describe('AsyncPipe', () => { - describe('Observable', () => { let emitter: EventEmitter; let pipe: AsyncPipe; @@ -29,8 +28,9 @@ import {SpyChangeDetectorRef} from '../spies'; }); describe('transform', () => { - it('should return null when subscribing to an observable', - () => { expect(pipe.transform(emitter)).toBe(null); }); + it('should return null when subscribing to an observable', () => { + expect(pipe.transform(emitter)).toBe(null); + }); it('should return the latest available value wrapped', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @@ -96,8 +96,9 @@ import {SpyChangeDetectorRef} from '../spies'; }); describe('ngOnDestroy', () => { - it('should do nothing when no subscription', - () => { expect(() => pipe.ngOnDestroy()).not.toThrow(); }); + it('should do nothing when no subscription', () => { + expect(() => pipe.ngOnDestroy()).not.toThrow(); + }); it('should dispose of the existing subscription', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @@ -133,8 +134,9 @@ import {SpyChangeDetectorRef} from '../spies'; }); describe('transform', () => { - it('should return null when subscribing to a promise', - () => { expect(pipe.transform(promise)).toBe(null); }); + it('should return null when subscribing to a promise', () => { + expect(pipe.transform(promise)).toBe(null); + }); it('should return the latest available value', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @@ -189,8 +191,9 @@ import {SpyChangeDetectorRef} from '../spies'; })); describe('ngOnDestroy', () => { - it('should do nothing when no source', - () => { expect(() => pipe.ngOnDestroy()).not.toThrow(); }); + it('should do nothing when no source', () => { + expect(() => pipe.ngOnDestroy()).not.toThrow(); + }); it('should dispose of the existing source', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { diff --git a/packages/common/test/pipes/case_conversion_pipes_spec.ts b/packages/common/test/pipes/case_conversion_pipes_spec.ts index 22458d785508e..5584f5e468d2b 100644 --- a/packages/common/test/pipes/case_conversion_pipes_spec.ts +++ b/packages/common/test/pipes/case_conversion_pipes_spec.ts @@ -12,41 +12,55 @@ import {LowerCasePipe, TitleCasePipe, UpperCasePipe} from '@angular/common'; describe('LowerCasePipe', () => { let pipe: LowerCasePipe; - beforeEach(() => { pipe = new LowerCasePipe(); }); + beforeEach(() => { + pipe = new LowerCasePipe(); + }); - it('should return lowercase', () => { expect(pipe.transform('FOO')).toEqual('foo'); }); + it('should return lowercase', () => { + expect(pipe.transform('FOO')).toEqual('foo'); + }); it('should lowercase when there is a new value', () => { expect(pipe.transform('FOO')).toEqual('foo'); expect(pipe.transform('BAr')).toEqual('bar'); }); - it('should not support other objects', - () => { expect(() => pipe.transform({})).toThrowError(); }); + it('should not support other objects', () => { + expect(() => pipe.transform({})).toThrowError(); + }); }); describe('TitleCasePipe', () => { let pipe: TitleCasePipe; - beforeEach(() => { pipe = new TitleCasePipe(); }); + beforeEach(() => { + pipe = new TitleCasePipe(); + }); - it('should return titlecase', () => { expect(pipe.transform('foo')).toEqual('Foo'); }); + it('should return titlecase', () => { + expect(pipe.transform('foo')).toEqual('Foo'); + }); - it('should return titlecase for subsequent words', - () => { expect(pipe.transform('one TWO Three fouR')).toEqual('One Two Three Four'); }); + it('should return titlecase for subsequent words', () => { + expect(pipe.transform('one TWO Three fouR')).toEqual('One Two Three Four'); + }); - it('should support empty strings', () => { expect(pipe.transform('')).toEqual(''); }); + it('should support empty strings', () => { + expect(pipe.transform('')).toEqual(''); + }); - it('should persist whitespace', - () => { expect(pipe.transform('one two')).toEqual('One Two'); }); + it('should persist whitespace', () => { + expect(pipe.transform('one two')).toEqual('One Two'); + }); it('should titlecase when there is a new value', () => { expect(pipe.transform('bar')).toEqual('Bar'); expect(pipe.transform('foo')).toEqual('Foo'); }); - it('should not capitalize letter after the quotes', - () => { expect(pipe.transform('it\'s complicated')).toEqual('It\'s Complicated'); }); + it('should not capitalize letter after the quotes', () => { + expect(pipe.transform('it\'s complicated')).toEqual('It\'s Complicated'); + }); it('should not treat non-space character as a separator', () => { expect(pipe.transform('one,two,three')).toEqual('One,two,three'); @@ -66,23 +80,29 @@ import {LowerCasePipe, TitleCasePipe, UpperCasePipe} from '@angular/common'; expect(pipe.transform('éric')).toEqual('Éric'); }); - it('should not support other objects', - () => { expect(() => pipe.transform({})).toThrowError(); }); + it('should not support other objects', () => { + expect(() => pipe.transform({})).toThrowError(); + }); }); describe('UpperCasePipe', () => { let pipe: UpperCasePipe; - beforeEach(() => { pipe = new UpperCasePipe(); }); + beforeEach(() => { + pipe = new UpperCasePipe(); + }); - it('should return uppercase', () => { expect(pipe.transform('foo')).toEqual('FOO'); }); + it('should return uppercase', () => { + expect(pipe.transform('foo')).toEqual('FOO'); + }); it('should uppercase when there is a new value', () => { expect(pipe.transform('foo')).toEqual('FOO'); expect(pipe.transform('bar')).toEqual('BAR'); }); - it('should not support other objects', - () => { expect(() => pipe.transform({})).toThrowError(); }); + it('should not support other objects', () => { + expect(() => pipe.transform({})).toThrowError(); + }); }); } diff --git a/packages/common/test/pipes/date_pipe_spec.ts b/packages/common/test/pipes/date_pipe_spec.ts index d651ceb7d431f..c1542d60e4dbb 100644 --- a/packages/common/test/pipes/date_pipe_spec.ts +++ b/packages/common/test/pipes/date_pipe_spec.ts @@ -10,8 +10,8 @@ import {DatePipe} from '@angular/common'; import localeEn from '@angular/common/locales/en'; import localeEnExtra from '@angular/common/locales/extra/en'; import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; +import {ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_reflector'; -import {ɵunregisterLocaleData, ɵregisterLocaleData} from '@angular/core'; { let date: Date; @@ -28,33 +28,44 @@ import {ɵunregisterLocaleData, ɵregisterLocaleData} from '@angular/core'; }); it('should be marked as pure', () => { - expect(new PipeResolver(new JitReflector()).resolve(DatePipe) !.pure).toEqual(true); + expect(new PipeResolver(new JitReflector()).resolve(DatePipe)!.pure).toEqual(true); }); describe('supports', () => { - it('should support date', () => { expect(() => pipe.transform(date)).not.toThrow(); }); + it('should support date', () => { + expect(() => pipe.transform(date)).not.toThrow(); + }); - it('should support int', () => { expect(() => pipe.transform(123456789)).not.toThrow(); }); + it('should support int', () => { + expect(() => pipe.transform(123456789)).not.toThrow(); + }); - it('should support numeric strings', - () => { expect(() => pipe.transform('123456789')).not.toThrow(); }); + it('should support numeric strings', () => { + expect(() => pipe.transform('123456789')).not.toThrow(); + }); - it('should support decimal strings', - () => { expect(() => pipe.transform('123456789.11')).not.toThrow(); }); + it('should support decimal strings', () => { + expect(() => pipe.transform('123456789.11')).not.toThrow(); + }); it('should support ISO string', () => expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow()); - it('should return null for empty string', - () => { expect(pipe.transform('')).toEqual(null); }); + it('should return null for empty string', () => { + expect(pipe.transform('')).toEqual(null); + }); - it('should return null for NaN', () => { expect(pipe.transform(Number.NaN)).toEqual(null); }); + it('should return null for NaN', () => { + expect(pipe.transform(Number.NaN)).toEqual(null); + }); - it('should support ISO string without time', - () => { expect(() => pipe.transform(isoStringWithoutTime)).not.toThrow(); }); + it('should support ISO string without time', () => { + expect(() => pipe.transform(isoStringWithoutTime)).not.toThrow(); + }); - it('should not support other objects', - () => { expect(() => pipe.transform({})).toThrowError(/InvalidPipeArgument/); }); + it('should not support other objects', () => { + expect(() => pipe.transform({})).toThrowError(/InvalidPipeArgument/); + }); }); describe('transform', () => { diff --git a/packages/common/test/pipes/i18n_plural_pipe_spec.ts b/packages/common/test/pipes/i18n_plural_pipe_spec.ts index 2941584b3cf8b..104716b195d21 100644 --- a/packages/common/test/pipes/i18n_plural_pipe_spec.ts +++ b/packages/common/test/pipes/i18n_plural_pipe_spec.ts @@ -29,7 +29,7 @@ import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_refle }); it('should be marked as pure', () => { - expect(new PipeResolver(new JitReflector()).resolve(I18nPluralPipe) !.pure).toEqual(true); + expect(new PipeResolver(new JitReflector()).resolve(I18nPluralPipe)!.pure).toEqual(true); }); describe('transform', () => { @@ -54,17 +54,19 @@ import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_refle }); it('should use "" if value is undefined', () => { - const val = pipe.transform(void(0) as any, mapping); + const val = pipe.transform(void (0) as any, mapping); expect(val).toEqual(''); }); - it('should not support bad arguments', - () => { expect(() => pipe.transform(0, 'hey')).toThrowError(); }); + it('should not support bad arguments', () => { + expect(() => pipe.transform(0, 'hey')).toThrowError(); + }); }); - }); } class TestLocalization extends NgLocalization { - getPluralCategory(value: number): string { return value > 1 && value < 6 ? 'many' : 'other'; } + getPluralCategory(value: number): string { + return value > 1 && value < 6 ? 'many' : 'other'; + } } diff --git a/packages/common/test/pipes/i18n_select_pipe_spec.ts b/packages/common/test/pipes/i18n_select_pipe_spec.ts index 2d68a237d325c..998ab7fd40a19 100644 --- a/packages/common/test/pipes/i18n_select_pipe_spec.ts +++ b/packages/common/test/pipes/i18n_select_pipe_spec.ts @@ -16,7 +16,7 @@ import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_refle const mapping = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'}; it('should be marked as pure', () => { - expect(new PipeResolver(new JitReflector()).resolve(I18nSelectPipe) !.pure).toEqual(true); + expect(new PipeResolver(new JitReflector()).resolve(I18nSelectPipe)!.pure).toEqual(true); }); describe('transform', () => { @@ -30,17 +30,18 @@ import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_refle expect(val).toEqual('Invite her.'); }); - it('should return the "other" text if value is neither "male" nor "female"', - () => { expect(pipe.transform('Anything else', mapping)).toEqual('Invite them.'); }); + it('should return the "other" text if value is neither "male" nor "female"', () => { + expect(pipe.transform('Anything else', mapping)).toEqual('Invite them.'); + }); it('should return an empty text if value is null or undefined', () => { expect(pipe.transform(null, mapping)).toEqual(''); expect(pipe.transform(void 0, mapping)).toEqual(''); }); - it('should throw on bad arguments', - () => { expect(() => pipe.transform('male', 'hey')).toThrowError(); }); + it('should throw on bad arguments', () => { + expect(() => pipe.transform('male', 'hey')).toThrowError(); + }); }); - }); } diff --git a/packages/common/test/pipes/json_pipe_spec.ts b/packages/common/test/pipes/json_pipe_spec.ts index a9f5e4637d7bc..b1a9fb5bb58ec 100644 --- a/packages/common/test/pipes/json_pipe_spec.ts +++ b/packages/common/test/pipes/json_pipe_spec.ts @@ -8,7 +8,7 @@ import {CommonModule, JsonPipe} from '@angular/common'; import {Component} from '@angular/core'; -import {TestBed, async} from '@angular/core/testing'; +import {async, TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; { @@ -18,7 +18,9 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; let inceptionObjString: string; let pipe: JsonPipe; - function normalize(obj: string): string { return obj.replace(regNewLine, ''); } + function normalize(obj: string): string { + return obj.replace(regNewLine, ''); + } beforeEach(() => { inceptionObj = {dream: {dream: {dream: 'Limbo'}}}; @@ -35,8 +37,9 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; }); describe('transform', () => { - it('should return JSON-formatted string', - () => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); }); + it('should return JSON-formatted string', () => { + expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); + }); it('should return JSON-formatted string even when normalized', () => { const dream1 = normalize(pipe.transform(inceptionObj)); @@ -52,7 +55,6 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; }); describe('integration', () => { - @Component({selector: 'test-comp', template: '{{data | json}}'}) class TestComp { data: any; diff --git a/packages/common/test/pipes/keyvalue_pipe_spec.ts b/packages/common/test/pipes/keyvalue_pipe_spec.ts index 4433f9c98d052..e4af0fc130760 100644 --- a/packages/common/test/pipes/keyvalue_pipe_spec.ts +++ b/packages/common/test/pipes/keyvalue_pipe_spec.ts @@ -64,12 +64,12 @@ describe('KeyValuePipe', () => { expect(transform1 !== transform2).toEqual(true); }); it('should accept a type union of an object with string keys and null', () => { - let value !: {[key: string]: string} | null; + let value!: {[key: string]: string}|null; const pipe = new KeyValuePipe(defaultKeyValueDiffers); expect(pipe.transform(value)).toEqual(null); }); it('should accept a type union of an object with number keys and null', () => { - let value !: {[key: number]: string} | null; + let value!: {[key: number]: string}|null; const pipe = new KeyValuePipe(defaultKeyValueDiffers); expect(pipe.transform(value)).toEqual(null); }); @@ -126,7 +126,7 @@ describe('KeyValuePipe', () => { expect(transform1 !== transform2).toEqual(true); }); it('should accept a type union of a Map and null', () => { - let value !: Map| null; + let value!: Map|null; const pipe = new KeyValuePipe(defaultKeyValueDiffers); expect(pipe.transform(value)).toEqual(null); }); diff --git a/packages/common/test/pipes/number_pipe_spec.ts b/packages/common/test/pipes/number_pipe_spec.ts index c0a456451d6b9..a57690451018e 100644 --- a/packages/common/test/pipes/number_pipe_spec.ts +++ b/packages/common/test/pipes/number_pipe_spec.ts @@ -6,14 +6,14 @@ * found in the LICENSE file at https://angular.io/license */ +import {CurrencyPipe, DecimalPipe, PercentPipe} from '@angular/common'; +import localeAr from '@angular/common/locales/ar'; +import localeDa from '@angular/common/locales/da'; +import localeDeAt from '@angular/common/locales/de-AT'; import localeEn from '@angular/common/locales/en'; import localeEsUS from '@angular/common/locales/es-US'; import localeFr from '@angular/common/locales/fr'; -import localeAr from '@angular/common/locales/ar'; -import localeDeAt from '@angular/common/locales/de-AT'; -import localeDa from '@angular/common/locales/da'; -import {ɵunregisterLocaleData, ɵregisterLocaleData} from '@angular/core'; -import {CurrencyPipe, DecimalPipe, PercentPipe} from '@angular/common'; +import {ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; import {beforeEach, describe, expect, it} from '@angular/core/testing/src/testing_internal'; { @@ -32,7 +32,9 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/src/testin describe('DecimalPipe', () => { describe('transform', () => { let pipe: DecimalPipe; - beforeEach(() => { pipe = new DecimalPipe('en-US'); }); + beforeEach(() => { + pipe = new DecimalPipe('en-US'); + }); it('should return correct value for numbers', () => { expect(pipe.transform(12345)).toEqual('12,345'); @@ -68,7 +70,9 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/src/testin describe('PercentPipe', () => { let pipe: PercentPipe; - beforeEach(() => { pipe = new PercentPipe('en-US'); }); + beforeEach(() => { + pipe = new PercentPipe('en-US'); + }); describe('transform', () => { it('should return correct value for numbers', () => { @@ -89,7 +93,9 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/src/testin describe('CurrencyPipe', () => { let pipe: CurrencyPipe; - beforeEach(() => { pipe = new CurrencyPipe('en-US', 'USD'); }); + beforeEach(() => { + pipe = new CurrencyPipe('en-US', 'USD'); + }); describe('transform', () => { it('should return correct value for numbers', () => { diff --git a/packages/common/test/pipes/slice_pipe_spec.ts b/packages/common/test/pipes/slice_pipe_spec.ts index 63c79f188067a..e86edf75651a8 100644 --- a/packages/common/test/pipes/slice_pipe_spec.ts +++ b/packages/common/test/pipes/slice_pipe_spec.ts @@ -8,7 +8,7 @@ import {CommonModule, SlicePipe} from '@angular/common'; import {Component} from '@angular/core'; -import {TestBed, async} from '@angular/core/testing'; +import {async, TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; { @@ -24,24 +24,32 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; }); describe('supports', () => { - it('should support strings', () => { expect(() => pipe.transform(str, 0)).not.toThrow(); }); - it('should support lists', () => { expect(() => pipe.transform(list, 0)).not.toThrow(); }); - it('should support readonly lists', - () => { expect(() => pipe.transform(list as ReadonlyArray, 0)).not.toThrow(); }); + it('should support strings', () => { + expect(() => pipe.transform(str, 0)).not.toThrow(); + }); + it('should support lists', () => { + expect(() => pipe.transform(list, 0)).not.toThrow(); + }); + it('should support readonly lists', () => { + expect(() => pipe.transform(list as ReadonlyArray, 0)).not.toThrow(); + }); it('should not support other objects', // this would not compile // so we cast as `any` to check that it throws for unsupported objects - () => { expect(() => pipe.transform({} as any, 0)).toThrow(); }); + () => { + expect(() => pipe.transform({} as any, 0)).toThrow(); + }); }); describe('transform', () => { + it('should return null if the value is null', () => { + expect(pipe.transform(null, 1)).toBe(null); + }); - it('should return null if the value is null', - () => { expect(pipe.transform(null, 1)).toBe(null); }); - - it('should return undefined if the value is undefined', - () => { expect(pipe.transform(undefined, 1)).toBe(undefined); }); + it('should return undefined if the value is undefined', () => { + expect(pipe.transform(undefined, 1)).toBe(undefined); + }); it('should return all items after START index when START is positive and END is omitted', () => { @@ -85,11 +93,9 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; expect(pipe.transform(list, 2)).toEqual([3, 4, 5]); expect(list).toEqual([1, 2, 3, 4, 5]); }); - }); describe('integration', () => { - @Component({selector: 'test-comp', template: '{{(data | slice:1).join(",") }}'}) class TestComp { data: any; diff --git a/packages/common/test/spies.ts b/packages/common/test/spies.ts index e956a4821c474..e889b9431e49c 100644 --- a/packages/common/test/spies.ts +++ b/packages/common/test/spies.ts @@ -18,4 +18,6 @@ export class SpyChangeDetectorRef extends SpyObject { export class SpyNgControl extends SpyObject {} -export class SpyValueAccessor extends SpyObject { writeValue: any; } +export class SpyValueAccessor extends SpyObject { + writeValue: any; +} diff --git a/packages/common/test/viewport_scroller_spec.ts b/packages/common/test/viewport_scroller_spec.ts index 281ef96d37d47..fd0485546a0ea 100644 --- a/packages/common/test/viewport_scroller_spec.ts +++ b/packages/common/test/viewport_scroller_spec.ts @@ -9,12 +9,12 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {describe, expect, it} from '@angular/core/testing/src/testing_internal'; import {BrowserViewportScroller, ViewportScroller} from '../src/viewport_scroller'; @@ -25,7 +25,7 @@ import {BrowserViewportScroller, ViewportScroller} from '../src/viewport_scrolle let documentSpy: any; beforeEach(() => { documentSpy = jasmine.createSpyObj('document', ['querySelector']); - scroller = new BrowserViewportScroller(documentSpy, {scrollTo: 1}, null !); + scroller = new BrowserViewportScroller(documentSpy, {scrollTo: 1}, null!); }); it('escapes invalid characters selectors', () => { const invalidSelectorChars = `"' :.[],=`; diff --git a/packages/common/testing/src/location_mock.ts b/packages/common/testing/src/location_mock.ts index a5efc1ffb318b..b02d5e2b2fd05 100644 --- a/packages/common/testing/src/location_mock.ts +++ b/packages/common/testing/src/location_mock.ts @@ -25,19 +25,27 @@ export class SpyLocation implements Location { /** @internal */ _baseHref: string = ''; /** @internal */ - _platformStrategy: LocationStrategy = null !; + _platformStrategy: LocationStrategy = null!; /** @internal */ - _platformLocation: PlatformLocation = null !; + _platformLocation: PlatformLocation = null!; /** @internal */ _urlChangeListeners: ((url: string, state: unknown) => void)[] = []; - setInitialPath(url: string) { this._history[this._historyIndex].path = url; } + setInitialPath(url: string) { + this._history[this._historyIndex].path = url; + } - setBaseHref(url: string) { this._baseHref = url; } + setBaseHref(url: string) { + this._baseHref = url; + } - path(): string { return this._history[this._historyIndex].path; } + path(): string { + return this._history[this._historyIndex].path; + } - getState(): unknown { return this._history[this._historyIndex].state; } + getState(): unknown { + return this._history[this._historyIndex].state; + } isCurrentPathEqualTo(path: string, query: string = ''): boolean { const givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; @@ -115,7 +123,9 @@ export class SpyLocation implements Location { } onUrlChange(fn: (url: string, state: unknown) => void) { this._urlChangeListeners.push(fn); - this.subscribe(v => { this._notifyUrlChangeListeners(v.url, v.state); }); + this.subscribe(v => { + this._notifyUrlChangeListeners(v.url, v.state); + }); } /** @internal */ @@ -129,7 +139,9 @@ export class SpyLocation implements Location { return this._subject.subscribe({next: onNext, error: onThrow, complete: onReturn}); } - normalize(url: string): string { return null !; } + normalize(url: string): string { + return null!; + } } class LocationState { diff --git a/packages/common/testing/src/mock_location_strategy.ts b/packages/common/testing/src/mock_location_strategy.ts index 2c38f8d39f591..8cd329aa64f25 100644 --- a/packages/common/testing/src/mock_location_strategy.ts +++ b/packages/common/testing/src/mock_location_strategy.ts @@ -26,14 +26,18 @@ export class MockLocationStrategy extends LocationStrategy { /** @internal */ _subject: EventEmitter = new EventEmitter(); private stateChanges: any[] = []; - constructor() { super(); } + constructor() { + super(); + } simulatePopState(url: string): void { this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); } - path(includeHash: boolean = false): string { return this.internalPath; } + path(includeHash: boolean = false): string { + return this.internalPath; + } prepareExternalUrl(internal: string): string { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { @@ -68,9 +72,13 @@ export class MockLocationStrategy extends LocationStrategy { this.urlChanges.push('replace: ' + externalUrl); } - onPopState(fn: (value: any) => void): void { this._subject.subscribe({next: fn}); } + onPopState(fn: (value: any) => void): void { + this._subject.subscribe({next: fn}); + } - getBaseHref(): string { return this.internalBaseHref; } + getBaseHref(): string { + return this.internalBaseHref; + } back(): void { if (this.urlChanges.length > 0) { @@ -81,9 +89,13 @@ export class MockLocationStrategy extends LocationStrategy { } } - forward(): void { throw 'not implemented'; } + forward(): void { + throw 'not implemented'; + } - getState(): unknown { return this.stateChanges[(this.stateChanges.length || 1) - 1]; } + getState(): unknown { + return this.stateChanges[(this.stateChanges.length || 1) - 1]; + } } class _MockPopStateEvent { diff --git a/packages/common/testing/src/mock_platform_location.ts b/packages/common/testing/src/mock_platform_location.ts index 4f7c15602252f..4cbb5a677ceb9 100644 --- a/packages/common/testing/src/mock_platform_location.ts +++ b/packages/common/testing/src/mock_platform_location.ts @@ -126,23 +126,41 @@ export class MockPlatformLocation implements PlatformLocation { } } - get hostname() { return this.urlChanges[0].hostname; } - get protocol() { return this.urlChanges[0].protocol; } - get port() { return this.urlChanges[0].port; } - get pathname() { return this.urlChanges[0].pathname; } - get search() { return this.urlChanges[0].search; } - get hash() { return this.urlChanges[0].hash; } - get state() { return this.urlChanges[0].state; } + get hostname() { + return this.urlChanges[0].hostname; + } + get protocol() { + return this.urlChanges[0].protocol; + } + get port() { + return this.urlChanges[0].port; + } + get pathname() { + return this.urlChanges[0].pathname; + } + get search() { + return this.urlChanges[0].search; + } + get hash() { + return this.urlChanges[0].hash; + } + get state() { + return this.urlChanges[0].state; + } - getBaseHrefFromDOM(): string { return this.baseHref; } + getBaseHrefFromDOM(): string { + return this.baseHref; + } onPopState(fn: LocationChangeListener): void { // No-op: a state stack is not implemented, so // no events will ever come. } - onHashChange(fn: LocationChangeListener): void { this.hashUpdate.subscribe(fn); } + onHashChange(fn: LocationChangeListener): void { + this.hashUpdate.subscribe(fn); + } get href(): string { let url = `${this.protocol}//${this.hostname}${this.port ? ':' + this.port : ''}`; @@ -150,7 +168,9 @@ export class MockPlatformLocation implements PlatformLocation { return url; } - get url(): string { return `${this.pathname}${this.search}${this.hash}`; } + get url(): string { + return `${this.pathname}${this.search}${this.hash}`; + } private parseChanges(state: unknown, url: string, baseHref: string = '') { // When the `history.state` value is stored, it is always copied. @@ -169,7 +189,9 @@ export class MockPlatformLocation implements PlatformLocation { this.urlChanges.unshift({...this.urlChanges[0], pathname, search, hash, state: parsedState}); } - forward(): void { throw new Error('Not implemented'); } + forward(): void { + throw new Error('Not implemented'); + } back(): void { const oldUrl = this.url; @@ -178,13 +200,15 @@ export class MockPlatformLocation implements PlatformLocation { const newHash = this.hash; if (oldHash !== newHash) { - scheduleMicroTask(() => this.hashUpdate.next({ - type: 'hashchange', state: null, oldUrl, newUrl: this.url - } as LocationChangeEvent)); + scheduleMicroTask( + () => this.hashUpdate.next( + {type: 'hashchange', state: null, oldUrl, newUrl: this.url} as LocationChangeEvent)); } } - getState(): unknown { return this.state; } + getState(): unknown { + return this.state; + } } export function scheduleMicroTask(cb: () => any) { diff --git a/packages/common/upgrade/src/location_shim.ts b/packages/common/upgrade/src/location_shim.ts index 7f03b46c0b360..aa7d52341d765 100644 --- a/packages/common/upgrade/src/location_shim.ts +++ b/packages/common/upgrade/src/location_shim.ts @@ -88,7 +88,7 @@ export class $locationShim { return; } - let elm: (Node & ParentNode)|null = event.target; + let elm: (Node&ParentNode)|null = event.target; // traverse the DOM up to find first A tag while (elm && elm.nodeName.toLowerCase() !== 'a') { @@ -286,7 +286,9 @@ export class $locationShim { * This function emulates the $browser.state() function from AngularJS. It will cause * history.state to be cached unless changed with deep equality check. */ - private browserState(): unknown { return this.cachedState; } + private browserState(): unknown { + return this.cachedState; + } private stripBaseUrl(base: string, url: string) { if (url.startsWith(base)) { @@ -446,7 +448,9 @@ export class $locationShim { * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" * ``` */ - absUrl(): string { return this.$$absUrl; } + absUrl(): string { + return this.$$absUrl; + } /** * Retrieves the current URL, or sets a new URL. When setting a URL, @@ -488,7 +492,9 @@ export class $locationShim { * // => "http" * ``` */ - protocol(): string { return this.$$protocol; } + protocol(): string { + return this.$$protocol; + } /** * Retrieves the protocol of the current URL. @@ -509,7 +515,9 @@ export class $locationShim { * // => "example.com:8080" * ``` */ - host(): string { return this.$$host; } + host(): string { + return this.$$host; + } /** * Retrieves the port of the current URL. @@ -520,7 +528,9 @@ export class $locationShim { * // => 80 * ``` */ - port(): number|null { return this.$$port; } + port(): number|null { + return this.$$port; + } /** * Retrieves the path of the current URL, or changes the path and returns a reference to its own @@ -553,7 +563,7 @@ export class $locationShim { } /** - * Retrieves a map of the search parameters of the current URL, or changes a search + * Retrieves a map of the search parameters of the current URL, or changes a search * part and returns a reference to its own instance. * * @@ -576,7 +586,8 @@ export class $locationShim { * If the argument is a hash object containing an array of values, these values will be encoded * as duplicate search parameters in the URL. * - * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue` + * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, + * then `paramValue` * will override only a single search property. * * If `paramValue` is an array, it will override the property of the `search` component of diff --git a/packages/common/upgrade/src/location_upgrade_module.ts b/packages/common/upgrade/src/location_upgrade_module.ts index 720dd986a0125..d11f9dfd23eb2 100644 --- a/packages/common/upgrade/src/location_upgrade_module.ts +++ b/packages/common/upgrade/src/location_upgrade_module.ts @@ -55,7 +55,7 @@ const APP_BASE_HREF_RESOLVED = new InjectionToken('APP_BASE_HREF_RESOLVE /** * `NgModule` used for providing and configuring Angular's Unified Location Service for upgrading. - * + * * @see [Using the Unified Angular Location Service](guide/upgrade#using-the-unified-angular-location-service) * * @publicApi diff --git a/packages/common/upgrade/src/params.ts b/packages/common/upgrade/src/params.ts index ac9fe5f7d64b6..587816ecb0e92 100644 --- a/packages/common/upgrade/src/params.ts +++ b/packages/common/upgrade/src/params.ts @@ -152,7 +152,9 @@ export class AngularJSUrlCodec implements UrlCodec { } // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L72 - decodeSearch(search: string) { return parseKeyValue(search); } + decodeSearch(search: string) { + return parseKeyValue(search); + } // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L73 decodeHash(hash: string) { @@ -193,7 +195,9 @@ export class AngularJSUrlCodec implements UrlCodec { } } - areEqual(valA: string, valB: string) { return this.normalize(valA) === this.normalize(valB); } + areEqual(valA: string, valB: string) { + return this.normalize(valA) === this.normalize(valB); + } // https://github.com/angular/angular.js/blob/864c7f0/src/ng/urlUtils.js#L60 parse(url: string, base?: string) { diff --git a/packages/common/upgrade/src/utils.ts b/packages/common/upgrade/src/utils.ts index 48cba8e2fee97..0ce909ecda499 100644 --- a/packages/common/upgrade/src/utils.ts +++ b/packages/common/upgrade/src/utils.ts @@ -27,7 +27,7 @@ export function deepEqual(a: any, b: any): boolean { } } -export function isAnchor(el: (Node & ParentNode) | Element | null): el is HTMLAnchorElement { +export function isAnchor(el: (Node&ParentNode)|Element|null): el is HTMLAnchorElement { return (el).href !== undefined; } diff --git a/packages/common/upgrade/test/upgrade.spec.ts b/packages/common/upgrade/test/upgrade.spec.ts index cab39addc56b3..47d3af76d32aa 100644 --- a/packages/common/upgrade/test/upgrade.spec.ts +++ b/packages/common/upgrade/test/upgrade.spec.ts @@ -7,7 +7,7 @@ */ import {CommonModule, PathLocationStrategy} from '@angular/common'; -import {TestBed, inject} from '@angular/core/testing'; +import {inject, TestBed} from '@angular/core/testing'; import {UpgradeModule} from '@angular/upgrade/static'; import {$locationShim} from '../src/location_shim'; @@ -43,15 +43,26 @@ export function injectorFactory() { export class $rootScopeMock { private watchers: any[] = []; private events: {[k: string]: any[]} = {}; - runWatchers() { this.watchers.forEach(fn => fn()); } + runWatchers() { + this.watchers.forEach(fn => fn()); + } - $watch(fn: any) { this.watchers.push(fn); } + $watch(fn: any) { + this.watchers.push(fn); + } $broadcast(evt: string, ...args: any[]) { if (this.events[evt]) { - this.events[evt].forEach(fn => { fn.apply(fn, args); }); + this.events[evt].forEach(fn => { + fn.apply(fn, args); + }); } - return {defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }}; + return { + defaultPrevented: false, + preventDefault() { + this.defaultPrevented = true; + } + }; } $on(evt: string, fn: any) { @@ -61,7 +72,9 @@ export class $rootScopeMock { this.events[evt].push(fn); } - $evalAsync(fn: any) { fn(); } + $evalAsync(fn: any) { + fn(); + } } describe('LocationProvider', () => { @@ -83,7 +96,6 @@ describe('LocationProvider', () => { expect($location).toBeDefined(); expect($location instanceof $locationShim).toBe(true); })); - }); @@ -105,7 +117,9 @@ describe('LocationHtml5Url', function() { upgradeModule.$injector = {get: injectorFactory()}; }); - beforeEach(inject([$locationShim], (loc: $locationShim) => { $location = loc; })); + beforeEach(inject([$locationShim], (loc: $locationShim) => { + $location = loc; + })); it('should set the URL', () => { @@ -158,8 +172,9 @@ describe('LocationHtml5Url', function() { }).toThrow(); }); - it('should support state', - function() { expect($location.state({a: 2}).state()).toEqual({a: 2}); }); + it('should support state', function() { + expect($location.state({a: 2}).state()).toEqual({a: 2}); + }); }); @@ -180,10 +195,14 @@ describe('NewUrl', function() { upgradeModule.$injector = {get: injectorFactory()}; }); - beforeEach(inject([$locationShim], (loc: $locationShim) => { $location = loc; })); + beforeEach(inject([$locationShim], (loc: $locationShim) => { + $location = loc; + })); // Sets the default most of these tests rely on - function setupUrl(url = '/path/b?search=a&b=c&d#hash') { $location.url(url); } + function setupUrl(url = '/path/b?search=a&b=c&d#hash') { + $location.url(url); + } it('should provide common getters', function() { setupUrl(); @@ -409,7 +428,6 @@ describe('NewUrl', function() { }); describe('encoding', function() { - it('should encode special characters', function() { $location.path('/a <>#'); $location.search({'i j': '<>#'}); @@ -455,7 +473,6 @@ describe('NewUrl', function() { $location.search({'a+b': 'c+d'}); expect($location.search()).toEqual({'a+b': 'c+d'}); }); - }); it('should not preserve old properties when parsing new url', function() { @@ -486,7 +503,9 @@ describe('New URL Parsing', () => { upgradeModule.$injector = {get: injectorFactory()}; }); - beforeEach(inject([$locationShim], (loc: $locationShim) => { $location = loc; })); + beforeEach(inject([$locationShim], (loc: $locationShim) => { + $location = loc; + })); it('should prepend path with basePath', function() { $location.$$parse('http://server/base/abc?a'); @@ -496,7 +515,6 @@ describe('New URL Parsing', () => { $location.path('/new/path'); expect($location.absUrl()).toBe('http://server/base/new/path?a'); }); - }); describe('New URL Parsing', () => { @@ -516,7 +534,9 @@ describe('New URL Parsing', () => { upgradeModule.$injector = {get: injectorFactory()}; }); - beforeEach(inject([$locationShim], (loc: $locationShim) => { $location = loc; })); + beforeEach(inject([$locationShim], (loc: $locationShim) => { + $location = loc; + })); it('should parse new url', function() { $location.$$parse('http://host.com/base'); @@ -549,8 +569,9 @@ describe('New URL Parsing', () => { }); it('should throw error when invalid server url given', function() { - - expect(function() { $location.$$parse('http://other.server.org/path#/path'); }) + expect(function() { + $location.$$parse('http://other.server.org/path#/path'); + }) .toThrowError( 'Invalid url "http://other.server.org/path#/path", missing path prefix "http://host.com/".'); }); @@ -620,12 +641,10 @@ describe('New URL Parsing', () => { // After watchers have been run, location should be updated and `state` should change expect($location.state()).toBe(null); }); - }); }); describe('$location.onChange()', () => { - let $location: $locationShim; let upgradeModule: UpgradeModule; let mock$rootScope: $rootScopeMock; @@ -644,13 +663,18 @@ describe('$location.onChange()', () => { mock$rootScope = upgradeModule.$injector.get('$rootScope'); }); - beforeEach(inject([$locationShim], (loc: $locationShim) => { $location = loc; })); + beforeEach(inject([$locationShim], (loc: $locationShim) => { + $location = loc; + })); - it('should have onChange method', () => { expect(typeof $location.onChange).toBe('function'); }); + it('should have onChange method', () => { + expect(typeof $location.onChange).toBe('function'); + }); it('should add registered functions to changeListeners', () => { - - function changeListener(url: string, state: unknown) { return undefined; } + function changeListener(url: string, state: unknown) { + return undefined; + } function errorHandler(e: Error) {} expect(($location as any).$$changeListeners.length).toBe(0); @@ -663,7 +687,6 @@ describe('$location.onChange()', () => { }); it('should call changeListeners when URL is updated', () => { - const onChangeVals = {url: 'url', state: 'state' as unknown, oldUrl: 'oldUrl', oldState: 'oldState' as unknown}; @@ -688,7 +711,6 @@ describe('$location.onChange()', () => { }); it('should call changeListeners after $locationChangeSuccess', () => { - let changeListenerCalled = false; let locationChangeSuccessEmitted = false; @@ -715,13 +737,14 @@ describe('$location.onChange()', () => { }); it('should call forward errors to error handler', () => { - - let error !: Error; + let error!: Error; function changeListener(url: string, state: unknown, oldUrl: string, oldState: unknown) { throw new Error('Handle error'); } - function errorHandler(e: Error) { error = e; } + function errorHandler(e: Error) { + error = e; + } $location.onChange(changeListener, errorHandler); @@ -729,7 +752,6 @@ describe('$location.onChange()', () => { mock$rootScope.runWatchers(); expect(error.message).toBe('Handle error'); }); - }); function parseLinkAndReturn(location: $locationShim, toUrl: string, relHref?: string) { diff --git a/packages/common/upgrade/test/upgrade_location_test_module.ts b/packages/common/upgrade/test/upgrade_location_test_module.ts index efcb0ab607bd5..52f093c64d5fc 100644 --- a/packages/common/upgrade/test/upgrade_location_test_module.ts +++ b/packages/common/upgrade/test/upgrade_location_test_module.ts @@ -72,7 +72,7 @@ export class LocationUpgradeTestModule { appBaseHref: config && config.appBaseHref, useHash: config && config.useHash || false }) - .providers ! + .providers! ], }; } diff --git a/packages/compiler-cli/integrationtest/test.js b/packages/compiler-cli/integrationtest/test.js index c30bb482c6179..39e23aa4b6a1d 100644 --- a/packages/compiler-cli/integrationtest/test.js +++ b/packages/compiler-cli/integrationtest/test.js @@ -34,8 +34,8 @@ function nodejs_repository() { const nodejsBinaryExt = os.platform() === 'win32' ? '.bat' : '.sh'; const ngcBin = require.resolve(`./ngc_bin${nodejsBinaryExt}`); const xi18nBin = require.resolve(`./ng_xi18n${nodejsBinaryExt}`); -const nodeBin = require.resolve( - `${nodejs_repository()}/${(os.platform() === 'win32' ? 'bin/nodejs/node.exe' : 'bin/nodejs/bin/node')}`); +const nodeBin = require.resolve(`${nodejs_repository()}/${ + (os.platform() === 'win32' ? 'bin/nodejs/node.exe' : 'bin/nodejs/bin/node')}`); const jasmineBin = require.resolve('npm/node_modules/jasmine/bin/jasmine.js'); // Prepare the test directory before building the integration test output. This ensures that diff --git a/packages/core/schematics/migrations/google3/explicitQueryTimingRule.ts b/packages/core/schematics/migrations/google3/explicitQueryTimingRule.ts index 4a218c8aca536..895cb276dbbeb 100644 --- a/packages/core/schematics/migrations/google3/explicitQueryTimingRule.ts +++ b/packages/core/schematics/migrations/google3/explicitQueryTimingRule.ts @@ -28,7 +28,7 @@ export class Rule extends Rules.TypedRule { const typeChecker = program.getTypeChecker(); const queryVisitor = new NgQueryResolveVisitor(program.getTypeChecker()); const templateVisitor = new NgComponentTemplateVisitor(typeChecker); - const rootSourceFiles = program.getRootFileNames().map(f => program.getSourceFile(f) !); + const rootSourceFiles = program.getRootFileNames().map(f => program.getSourceFile(f)!); const printer = ts.createPrinter(); const failures: RuleFailure[] = []; @@ -44,7 +44,7 @@ export class Rule extends Rules.TypedRule { // check component templates for static query usage. templateVisitor.resolvedTemplates.forEach(template => { if (classMetadata.has(template.container)) { - classMetadata.get(template.container) !.template = template; + classMetadata.get(template.container)!.template = template; } }); diff --git a/packages/core/schematics/migrations/google3/noMissingInjectableRule.ts b/packages/core/schematics/migrations/google3/noMissingInjectableRule.ts index 5fa6511c9c483..ffb810cdac25c 100644 --- a/packages/core/schematics/migrations/google3/noMissingInjectableRule.ts +++ b/packages/core/schematics/migrations/google3/noMissingInjectableRule.ts @@ -50,7 +50,7 @@ export class Rule extends Rules.TypedRule { transformer.recordChanges(); if (updateRecorders.has(sourceFile)) { - failures.push(...updateRecorders.get(sourceFile) !.failures); + failures.push(...updateRecorders.get(sourceFile)!.failures); } return failures; @@ -58,7 +58,7 @@ export class Rule extends Rules.TypedRule { /** Gets the update recorder for the specified source file. */ function getUpdateRecorder(sourceFile: ts.SourceFile): TslintUpdateRecorder { if (updateRecorders.has(sourceFile)) { - return updateRecorders.get(sourceFile) !; + return updateRecorders.get(sourceFile)!; } const recorder = new TslintUpdateRecorder(ruleName, sourceFile); updateRecorders.set(sourceFile, recorder); diff --git a/packages/core/schematics/migrations/google3/rendererToRenderer2Rule.ts b/packages/core/schematics/migrations/google3/rendererToRenderer2Rule.ts index 767621218f6c4..c0e1108f752ae 100644 --- a/packages/core/schematics/migrations/google3/rendererToRenderer2Rule.ts +++ b/packages/core/schematics/migrations/google3/rendererToRenderer2Rule.ts @@ -9,7 +9,7 @@ import {Replacement, RuleFailure, Rules} from 'tslint'; import * as ts from 'typescript'; -import {HelperFunction, getHelper} from '../renderer-to-renderer2/helpers'; +import {getHelper, HelperFunction} from '../renderer-to-renderer2/helpers'; import {migrateExpression, replaceImport} from '../renderer-to-renderer2/migration'; import {findCoreImport, findRendererReferences} from '../renderer-to-renderer2/util'; @@ -75,7 +75,7 @@ export class Rule extends Rules.TypedRule { private _getTypedNodeFailure( node: ts.ParameterDeclaration|ts.PropertyDeclaration|ts.AsExpression, sourceFile: ts.SourceFile): RuleFailure { - const type = node.type !; + const type = node.type!; return new RuleFailure( sourceFile, type.getStart(), type.getEnd(), diff --git a/packages/core/schematics/migrations/google3/undecoratedClassesWithDecoratedFieldsRule.ts b/packages/core/schematics/migrations/google3/undecoratedClassesWithDecoratedFieldsRule.ts index 9a1150a9aad44..2b2a32836498a 100644 --- a/packages/core/schematics/migrations/google3/undecoratedClassesWithDecoratedFieldsRule.ts +++ b/packages/core/schematics/migrations/google3/undecoratedClassesWithDecoratedFieldsRule.ts @@ -32,14 +32,14 @@ export class Rule extends Rules.TypedRule { transform.recordChanges(); if (updateRecorders.has(sourceFile)) { - return updateRecorders.get(sourceFile) !.failures; + return updateRecorders.get(sourceFile)!.failures; } return []; /** Gets the update recorder for the specified source file. */ function getUpdateRecorder(sourceFile: ts.SourceFile): TslintUpdateRecorder { if (updateRecorders.has(sourceFile)) { - return updateRecorders.get(sourceFile) !; + return updateRecorders.get(sourceFile)!; } const recorder = new TslintUpdateRecorder(ruleName, sourceFile); updateRecorders.set(sourceFile, recorder); diff --git a/packages/core/schematics/migrations/missing-injectable/definition_collector.ts b/packages/core/schematics/migrations/missing-injectable/definition_collector.ts index b2d5cee32edde..abf5f5842b039 100644 --- a/packages/core/schematics/migrations/missing-injectable/definition_collector.ts +++ b/packages/core/schematics/migrations/missing-injectable/definition_collector.ts @@ -8,7 +8,7 @@ import * as ts from 'typescript'; -import {NgDecorator, getAngularDecorators} from '../../utils/ng_decorators'; +import {getAngularDecorators, NgDecorator} from '../../utils/ng_decorators'; import {getPropertyNameText} from '../../utils/typescript/property_name'; export interface ResolvedNgModule { diff --git a/packages/core/schematics/migrations/missing-injectable/google3/tslint_update_recorder.ts b/packages/core/schematics/migrations/missing-injectable/google3/tslint_update_recorder.ts index 0f3da184da8b9..195469b2688fa 100644 --- a/packages/core/schematics/migrations/missing-injectable/google3/tslint_update_recorder.ts +++ b/packages/core/schematics/migrations/missing-injectable/google3/tslint_update_recorder.ts @@ -21,7 +21,8 @@ export class TslintUpdateRecorder implements UpdateRecorder { // are handled in reverse and in case a decorator and import are inserted at // the start of the file, the class decorator should come after the import. this.failures.unshift(new RuleFailure( - this.sourceFile, node.getStart(), 0, `Class needs to be decorated with ` + + this.sourceFile, node.getStart(), 0, + `Class needs to be decorated with ` + `"${decoratorText}" because it has been provided by "${className}".`, this.ruleName, Replacement.appendText(node.getStart(), `${decoratorText}\n`))); } diff --git a/packages/core/schematics/migrations/missing-injectable/transform.ts b/packages/core/schematics/migrations/missing-injectable/transform.ts index c70e75b12dc5d..aad21c9d12ad3 100644 --- a/packages/core/schematics/migrations/missing-injectable/transform.ts +++ b/packages/core/schematics/migrations/missing-injectable/transform.ts @@ -46,7 +46,9 @@ export class MissingInjectableTransform { new TypeScriptReflectionHost(typeChecker), typeChecker, /* dependencyTracker */ null); } - recordChanges() { this.importManager.recordChanges(); } + recordChanges() { + this.importManager.recordChanges(); + } /** * Migrates all specified NgModule's by walking through referenced providers @@ -76,10 +78,9 @@ export class MissingInjectableTransform { this._migrateLiteralProviders(literals); if (!Array.isArray(resolvedValue)) { - return [{ - node: module.providersExpr, - message: 'Providers of module are not statically analyzable.' - }]; + return [ + {node: module.providersExpr, message: 'Providers of module are not statically analyzable.'} + ]; } return this._visitProviderResolvedValue(resolvedValue, module); @@ -194,8 +195,9 @@ export class MissingInjectableTransform { const sourceFile = node.getSourceFile(); const newObjectLiteral = ts.updateObjectLiteral( - node, node.properties.concat( - ts.createPropertyAssignment('useValue', ts.createIdentifier('undefined')))); + node, + node.properties.concat( + ts.createPropertyAssignment('useValue', ts.createIdentifier('undefined')))); this.getUpdateRecorder(sourceFile) .updateObjectLiteral( @@ -217,11 +219,12 @@ export class MissingInjectableTransform { // decorate the class. This is because the class is instantiated through the // specified "deps" and the class does not need a factory definition. if (value.has('provide') && value.has('useClass') && value.get('deps') == null) { - return this._visitProviderResolvedValue(value.get('useClass') !, module); + return this._visitProviderResolvedValue(value.get('useClass')!, module); } } else if (Array.isArray(value)) { - return value.reduce((res, v) => res.concat(this._visitProviderResolvedValue(v, module)), [ - ] as AnalysisFailure[]); + return value.reduce( + (res, v) => res.concat(this._visitProviderResolvedValue(v, module)), + [] as AnalysisFailure[]); } else if (value instanceof DynamicValue) { return [{node: value.node, message: `Provider is not statically analyzable.`}]; } diff --git a/packages/core/schematics/migrations/module-with-providers/collector.ts b/packages/core/schematics/migrations/module-with-providers/collector.ts index ee30d5e192ced..ebad0c3587a6c 100644 --- a/packages/core/schematics/migrations/module-with-providers/collector.ts +++ b/packages/core/schematics/migrations/module-with-providers/collector.ts @@ -8,7 +8,8 @@ import * as ts from 'typescript'; -import {NgDecorator, getAngularDecorators} from '../../utils/ng_decorators'; +import {getAngularDecorators, NgDecorator} from '../../utils/ng_decorators'; + import {isModuleWithProvidersNotGeneric} from './util'; export interface ResolvedNgModule { diff --git a/packages/core/schematics/migrations/module-with-providers/transform.ts b/packages/core/schematics/migrations/module-with-providers/transform.ts index e11d17e82088a..c4ac37e8be43a 100644 --- a/packages/core/schematics/migrations/module-with-providers/transform.ts +++ b/packages/core/schematics/migrations/module-with-providers/transform.ts @@ -35,7 +35,7 @@ export class ModuleWithProvidersTransform { /** Migrates a given NgModule by walking through the referenced providers and static methods. */ migrateModule(module: ResolvedNgModule): AnalysisFailure[] { return module.staticMethodsWithoutType.map(this._migrateStaticNgModuleMethod.bind(this)) - .filter(v => v) as AnalysisFailure[]; + .filter(v => v) as AnalysisFailure[]; } /** Migrates a ModuleWithProviders type definition that has no explicit generic type */ @@ -98,8 +98,10 @@ export class ModuleWithProvidersTransform { return ngModule && (value.size === 1 || (providers && value.size === 2)); } - /** Determine the generic type of a suspected ModuleWithProviders return type and add it - * explicitly */ + /** + * Determine the generic type of a suspected ModuleWithProviders return type and add it + * explicitly + */ private _migrateStaticNgModuleMethod(node: ts.MethodDeclaration): AnalysisFailure|null { const returnStatement = node.body && node.body.statements.find(n => ts.isReturnStatement(n)) as ts.ReturnStatement | undefined; @@ -131,7 +133,7 @@ export class ModuleWithProvidersTransform { */ private _getTypeOfResolvedValue(value: ResolvedValue): string|undefined { if (value instanceof Map && this.isModuleWithProvidersType(value)) { - const mapValue = value.get('ngModule') !; + const mapValue = value.get('ngModule')!; if (mapValue instanceof Reference && ts.isClassDeclaration(mapValue.node) && mapValue.node.name) { return mapValue.node.name.text; diff --git a/packages/core/schematics/migrations/renderer-to-renderer2/helpers.ts b/packages/core/schematics/migrations/renderer-to-renderer2/helpers.ts index b41a5c2cee95b..d7cff149c3cae 100644 --- a/packages/core/schematics/migrations/renderer-to-renderer2/helpers.ts +++ b/packages/core/schematics/migrations/renderer-to-renderer2/helpers.ts @@ -69,7 +69,7 @@ function createAnyTypeHelper(): ts.TypeAliasDeclaration { /** Creates a function parameter that is typed as `any`. */ function getAnyTypedParameter( - parameterName: string | ts.Identifier, isRequired = true): ts.ParameterDeclaration { + parameterName: string|ts.Identifier, isRequired = true): ts.ParameterDeclaration { // Declare the parameter as `any` so we don't have to add extra logic to ensure that the // generated code will pass type checking. Use our custom `any` type so people have an incentive // to clean it up afterwards and to avoid potentially introducing lint warnings in G3. @@ -153,10 +153,11 @@ function getCreationHelper( // `if (parent) { renderer.appendChild(parent, node) }`. const guardedAppendChildCall = ts.createIf( - parent, ts.createBlock( - [ts.createExpressionStatement(ts.createCall( - ts.createPropertyAccess(renderer, 'appendChild'), [], [parent, node]))], - true)); + parent, + ts.createBlock( + [ts.createExpressionStatement( + ts.createCall(ts.createPropertyAccess(renderer, 'appendChild'), [], [parent, node]))], + true)); return ts.createFunctionDeclaration( [], [], undefined, functionName, [], @@ -258,10 +259,11 @@ function getDetachViewHelper(): ts.FunctionDeclaration { // const node = rootNodes[i]; const nodeVariableStatement = ts.createVariableStatement( - undefined, ts.createVariableDeclarationList( - [ts.createVariableDeclaration( - node, undefined, ts.createElementAccess(rootNodes, incrementor))], - ts.NodeFlags.Const)); + undefined, + ts.createVariableDeclarationList( + [ts.createVariableDeclaration( + node, undefined, ts.createElementAccess(rootNodes, incrementor))], + ts.NodeFlags.Const)); // renderer.removeChild(renderer.parentNode(node), node); const removeCall = ts.createCall( ts.createPropertyAccess(renderer, 'removeChild'), [], diff --git a/packages/core/schematics/migrations/renderer-to-renderer2/migration.ts b/packages/core/schematics/migrations/renderer-to-renderer2/migration.ts index 88f29fd3e38f4..f82ab0809f49b 100644 --- a/packages/core/schematics/migrations/renderer-to-renderer2/migration.ts +++ b/packages/core/schematics/migrations/renderer-to-renderer2/migration.ts @@ -12,7 +12,7 @@ import {HelperFunction} from './helpers'; import {findImportSpecifier} from './util'; /** A call expression that is based on a property access. */ -type PropertyAccessCallExpression = ts.CallExpression & {expression: ts.PropertyAccessExpression}; +type PropertyAccessCallExpression = ts.CallExpression&{expression: ts.PropertyAccessExpression}; /** Replaces an import inside an import statement with a different one. */ export function replaceImport(node: ts.NamedImports, oldImport: string, newImport: string) { @@ -42,7 +42,7 @@ export function replaceImport(node: ts.NamedImports, oldImport: string, newImpor * Returns null if the expression should be dropped. */ export function migrateExpression(node: ts.CallExpression, typeChecker: ts.TypeChecker): - {node: ts.Node | null, requiredHelpers?: HelperFunction[]} { + {node: ts.Node|null, requiredHelpers?: HelperFunction[]} { if (isPropertyAccessCallExpression(node)) { switch (node.expression.name.getText()) { case 'setElementProperty': @@ -152,7 +152,7 @@ function migrateSetElementClass(node: PropertyAccessCallExpression): ts.Node { // Clone so we don't mutate by accident. Note that we assume that // the user's code is providing all three required arguments. const outputMethodArgs = node.arguments.slice(); - const isAddArgument = outputMethodArgs.pop() !; + const isAddArgument = outputMethodArgs.pop()!; const createRendererCall = (isAdd: boolean) => { const innerExpression = node.expression.expression; const topExpression = @@ -263,6 +263,6 @@ function migrateAnimateCall() { */ function switchToHelperCall( node: PropertyAccessCallExpression, helper: HelperFunction, - args: ts.Expression[] | ts.NodeArray): ts.Node { + args: ts.Expression[]|ts.NodeArray): ts.Node { return ts.createCall(ts.createIdentifier(helper), [], [node.expression.expression, ...args]); } diff --git a/packages/core/schematics/migrations/renderer-to-renderer2/util.ts b/packages/core/schematics/migrations/renderer-to-renderer2/util.ts index e2dc21df8aa35..993dd82aa3b08 100644 --- a/packages/core/schematics/migrations/renderer-to-renderer2/util.ts +++ b/packages/core/schematics/migrations/renderer-to-renderer2/util.ts @@ -88,8 +88,7 @@ export function findImportSpecifier( /** Checks whether a node is referring to an import spcifier. */ function isReferenceToImport( - typeChecker: ts.TypeChecker, node: ts.Node, - importSpecifier: ts.ImportSpecifier | null): boolean { + typeChecker: ts.TypeChecker, node: ts.Node, importSpecifier: ts.ImportSpecifier|null): boolean { if (importSpecifier) { const nodeSymbol = typeChecker.getTypeAtLocation(node).getSymbol(); const importSymbol = typeChecker.getTypeAtLocation(importSpecifier).getSymbol(); @@ -102,7 +101,7 @@ function isReferenceToImport( /** Finds the identifier referring to the `Renderer` inside a `forwardRef` call expression. */ function findRendererIdentifierInForwardRef( typeChecker: ts.TypeChecker, node: ts.CallExpression, - rendererImport: ts.ImportSpecifier | null): ts.Identifier|null { + rendererImport: ts.ImportSpecifier|null): ts.Identifier|null { const firstArg = node.arguments[0]; if (ts.isArrowFunction(firstArg)) { diff --git a/packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts b/packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts index fa511a964ae20..457ee8818f433 100644 --- a/packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts +++ b/packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts @@ -24,7 +24,7 @@ export function getInputNamesOfClass( } const inputDecorator = - getAngularDecorators(typeChecker, m.decorators !).find(d => d.name === 'Input'); + getAngularDecorators(typeChecker, m.decorators!).find(d => d.name === 'Input'); if (inputDecorator && hasPropertyNameText(m.name)) { resolvedInputSetters.push(m.name.text); diff --git a/packages/core/schematics/migrations/static-queries/strategies/template_strategy/template_strategy.ts b/packages/core/schematics/migrations/static-queries/strategies/template_strategy/template_strategy.ts index c614961b67332..1414809880b06 100644 --- a/packages/core/schematics/migrations/static-queries/strategies/template_strategy/template_strategy.ts +++ b/packages/core/schematics/migrations/static-queries/strategies/template_strategy/template_strategy.ts @@ -7,7 +7,7 @@ */ import {AotCompiler, CompileDirectiveMetadata, CompileMetadataResolver, CompileNgModuleMetadata, CompileStylesheetMetadata, ElementAst, EmbeddedTemplateAst, NgAnalyzedModules, QueryMatch, StaticSymbol, TemplateAst} from '@angular/compiler'; -import {Diagnostic, createProgram, readConfiguration} from '@angular/compiler-cli'; +import {createProgram, Diagnostic, readConfiguration} from '@angular/compiler-cli'; import {resolve} from 'path'; import * as ts from 'typescript'; @@ -46,17 +46,17 @@ export class QueryTemplateStrategy implements TimingStrategy { // expose the logic that is necessary to analyze the determined modules. We work around // this by just accessing the necessary private properties using the bracket notation. this.compiler = (aotProgram as any)['compiler']; - this.metadataResolver = this.compiler !['_metadataResolver']; + this.metadataResolver = this.compiler!['_metadataResolver']; // Modify the "DirectiveNormalizer" to not normalize any referenced external stylesheets. // This is necessary because in CLI projects preprocessor files are commonly referenced // and we don't want to parse them in order to extract relative style references. This // breaks the analysis of the project because we instantiate a standalone AOT compiler // program which does not contain the custom logic by the Angular CLI Webpack compiler plugin. - const directiveNormalizer = this.metadataResolver !['_directiveNormalizer']; + const directiveNormalizer = this.metadataResolver!['_directiveNormalizer']; directiveNormalizer['_normalizeStylesheet'] = function(metadata: CompileStylesheetMetadata) { return new CompileStylesheetMetadata( - {styles: metadata.styles, styleUrls: [], moduleUrl: metadata.moduleUrl !}); + {styles: metadata.styles, styleUrls: [], moduleUrl: metadata.moduleUrl!}); }; // Retrieves the analyzed modules of the current program. This data can be @@ -75,7 +75,7 @@ export class QueryTemplateStrategy implements TimingStrategy { /** Analyzes a given directive by determining the timing of all matched view queries. */ private _analyzeDirective(symbol: StaticSymbol, analyzedModules: NgAnalyzedModules) { - const metadata = this.metadataResolver !.getDirectiveMetadata(symbol); + const metadata = this.metadataResolver!.getDirectiveMetadata(symbol); const ngModule = analyzedModules.ngModuleByPipeOrDirective.get(symbol); if (!metadata.isComponent || !ngModule) { @@ -168,7 +168,7 @@ export class QueryTemplateStrategy implements TimingStrategy { const queryKey = this._getViewQueryUniqueKey(filePath, classDecl.name.text, queryName); if (this.analyzedQueries.has(queryKey)) { - return this.analyzedQueries.get(queryKey) !; + return this.analyzedQueries.get(queryKey)!; } return null; } @@ -176,7 +176,7 @@ export class QueryTemplateStrategy implements TimingStrategy { private _parseTemplate(component: CompileDirectiveMetadata, ngModule: CompileNgModuleMetadata): TemplateAst[] { return this - .compiler !['_parseTemplate'](component, ngModule, ngModule.transitiveModule.directives) + .compiler!['_parseTemplate'](component, ngModule, ngModule.transitiveModule.directives) .template; } @@ -201,11 +201,11 @@ function findStaticQueryIds( nodes.forEach((node) => { const staticQueryIds = new Set(); const dynamicQueryIds = new Set(); - let queryMatches: QueryMatch[] = undefined !; + let queryMatches: QueryMatch[] = undefined!; if (node instanceof ElementAst) { findStaticQueryIds(node.children, result); node.children.forEach((child) => { - const childData = result.get(child) !; + const childData = result.get(child)!; childData.staticQueryIds.forEach(queryId => staticQueryIds.add(queryId)); childData.dynamicQueryIds.forEach(queryId => dynamicQueryIds.add(queryId)); }); @@ -213,7 +213,7 @@ function findStaticQueryIds( } else if (node instanceof EmbeddedTemplateAst) { findStaticQueryIds(node.children, result); node.children.forEach((child) => { - const childData = result.get(child) !; + const childData = result.get(child)!; childData.staticQueryIds.forEach(queryId => dynamicQueryIds.add(queryId)); childData.dynamicQueryIds.forEach(queryId => dynamicQueryIds.add(queryId)); }); diff --git a/packages/core/schematics/migrations/static-queries/strategies/timing-strategy.ts b/packages/core/schematics/migrations/static-queries/strategies/timing-strategy.ts index b530f60055d1b..0c35f6c6e45ee 100644 --- a/packages/core/schematics/migrations/static-queries/strategies/timing-strategy.ts +++ b/packages/core/schematics/migrations/static-queries/strategies/timing-strategy.ts @@ -16,5 +16,6 @@ export interface TimingStrategy { } export type TimingResult = { - timing: QueryTiming | null; message?: string; + timing: QueryTiming|null; + message?: string; }; diff --git a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/declaration_usage_visitor.ts b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/declaration_usage_visitor.ts index f42d647005abe..269f901f2c5bb 100644 --- a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/declaration_usage_visitor.ts +++ b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/declaration_usage_visitor.ts @@ -167,7 +167,7 @@ export class DeclarationUsageVisitor { d.body && !this.visitedJumpExprNodes.has(d)) .forEach(d => { this.visitedJumpExprNodes.add(d); - this.nodeQueue.push(d.body !); + this.nodeQueue.push(d.body!); }); } @@ -212,7 +212,7 @@ export class DeclarationUsageVisitor { this.ambiguousNodeQueue = []; while (this.nodeQueue.length) { - const node = this.nodeQueue.shift() !; + const node = this.nodeQueue.shift()!; if (ts.isIdentifier(node) && this.isReferringToSymbol(node)) { return ResolvedUsage.SYNCHRONOUS; @@ -306,7 +306,7 @@ export class DeclarationUsageVisitor { } } - jumpExp.arguments !.forEach((node: ts.Node) => { + jumpExp.arguments!.forEach((node: ts.Node) => { node = this._resolveDeclarationOfNode(node); if (ts.isVariableDeclaration(node) && node.initializer) { @@ -325,7 +325,7 @@ export class DeclarationUsageVisitor { */ private _resolveNodeFromContext(node: ts.Node): ts.Node { if (this.context.has(node)) { - return this.context.get(node) !; + return this.context.get(node)!; } return node; } diff --git a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/super_class_context.ts b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/super_class_context.ts index b48589e8a112d..d8bfafeedc428 100644 --- a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/super_class_context.ts +++ b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/super_class_context.ts @@ -35,7 +35,7 @@ export function updateSuperClassAbstractMembersContext( const baseClassImpl = baseClass.members.find( baseClassMethod => !!baseClassMethod.name && getPropertyNameText(baseClassMethod.name) === - getPropertyNameText(superClassMember.name !)); + getPropertyNameText(superClassMember.name!)); if (!baseClassImpl || !isFunctionLikeDeclaration(baseClassImpl) || !baseClassImpl.body) { return; diff --git a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/template_usage_visitor.ts b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/template_usage_visitor.ts index 3cfc79c2d2974..ec7c9b27d30e3 100644 --- a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/template_usage_visitor.ts +++ b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/template_usage_visitor.ts @@ -17,7 +17,9 @@ export class TemplateUsageVisitor extends NullVisitor { private hasQueryTemplateReference = false; private expressionAstVisitor = new ExpressionAstVisitor(this.queryPropertyName); - constructor(public queryPropertyName: string) { super(); } + constructor(public queryPropertyName: string) { + super(); + } /** Checks whether the given query is statically accessed within the specified HTML nodes. */ isQueryUsedStatically(htmlNodes: Node[]): boolean { @@ -59,7 +61,9 @@ export class TemplateUsageVisitor extends NullVisitor { attribute.value.visit(this.expressionAstVisitor, attribute.sourceSpan); } - visitBoundText(text: BoundText) { text.value.visit(this.expressionAstVisitor, text.sourceSpan); } + visitBoundText(text: BoundText) { + text.value.visit(this.expressionAstVisitor, text.sourceSpan); + } visitBoundEvent(node: BoundEvent) { node.handler.visit(this.expressionAstVisitor, node.handlerSpan); @@ -73,7 +77,9 @@ export class TemplateUsageVisitor extends NullVisitor { class ExpressionAstVisitor extends RecursiveAstVisitor { hasQueryPropertyRead = false; - constructor(private queryPropertyName: string) { super(); } + constructor(private queryPropertyName: string) { + super(); + } visitPropertyRead(node: PropertyRead, span: ParseSourceSpan): any { // The receiver of the property read needs to be "implicit" as queries are accessed diff --git a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts index 81de639b5501d..6085105e9f61f 100644 --- a/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts +++ b/packages/core/schematics/migrations/static-queries/strategies/usage_strategy/usage_strategy.ts @@ -70,7 +70,7 @@ export class QueryUsageStrategy implements TimingStrategy { classDecl: ts.ClassDeclaration, query: NgQueryDefinition, knownInputNames: string[], functionCtx: FunctionContext = new Map(), visitInheritedClasses = true): ResolvedUsage { const usageVisitor = - new DeclarationUsageVisitor(query.property !, this.typeChecker, functionCtx); + new DeclarationUsageVisitor(query.property!, this.typeChecker, functionCtx); const classMetadata = this.classMetadata.get(classDecl); let usage: ResolvedUsage = ResolvedUsage.ASYNCHRONOUS; @@ -99,10 +99,10 @@ export class QueryUsageStrategy implements TimingStrategy { // In case there is a component template for the current class, we check if the // template statically accesses the current query. In case that's true, the query // can be marked as static. - if (classMetadata.template && hasPropertyNameText(query.property !.name)) { + if (classMetadata.template && hasPropertyNameText(query.property!.name)) { const template = classMetadata.template; const parsedHtml = parseHtmlGracefully(template.content, template.filePath); - const htmlVisitor = new TemplateUsageVisitor(query.property !.name.text); + const htmlVisitor = new TemplateUsageVisitor(query.property!.name.text); if (parsedHtml && htmlVisitor.isQueryUsedStatically(parsedHtml)) { return ResolvedUsage.SYNCHRONOUS; @@ -179,5 +179,5 @@ function filterQueryClassMemberNodes( } return false; }) - .map(member => member.body !); + .map(member => member.body!); } diff --git a/packages/core/schematics/migrations/static-queries/transform.ts b/packages/core/schematics/migrations/static-queries/transform.ts index f60875799aade..379e64bba89f4 100644 --- a/packages/core/schematics/migrations/static-queries/transform.ts +++ b/packages/core/schematics/migrations/static-queries/transform.ts @@ -10,7 +10,7 @@ import * as ts from 'typescript'; import {getPropertyNameText} from '../../utils/typescript/property_name'; import {NgQueryDefinition, QueryTiming} from './angular/query-definition'; -export type TransformedQueryResult = null | { +export type TransformedQueryResult = null|{ /** Transformed call expression. */ node: ts.CallExpression; /** Failure message which is set when the query could not be transformed successfully. */ @@ -25,7 +25,7 @@ const TODO_CHECK_COMMENT = 'TODO: check static flag'; * determined timing. The updated decorator call expression node will be returned. */ export function getTransformedQueryCallExpr( - query: NgQueryDefinition, timing: QueryTiming | null, + query: NgQueryDefinition, timing: QueryTiming|null, createTodo: boolean): TransformedQueryResult { const queryExpr = query.decorator.node.expression; const queryArguments = queryExpr.arguments; @@ -81,7 +81,7 @@ export function getTransformedQueryCallExpr( failureMessage, node: ts.updateCall( queryExpr, queryExpr.expression, queryExpr.typeArguments, - [queryArguments[0], newOptionsNode !]) + [queryArguments[0], newOptionsNode!]) }; } @@ -94,8 +94,7 @@ export function getTransformedQueryCallExpr( return { failureMessage: null, node: ts.updateCall( - queryExpr, queryExpr.expression, queryExpr.typeArguments, - [queryArguments[0], optionsNode]) + queryExpr, queryExpr.expression, queryExpr.typeArguments, [queryArguments[0], optionsNode]) }; } diff --git a/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/google3/tslint_update_recorder.ts b/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/google3/tslint_update_recorder.ts index 5dc825721b668..311bdb15e869f 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/google3/tslint_update_recorder.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/google3/tslint_update_recorder.ts @@ -22,7 +22,8 @@ export class TslintUpdateRecorder implements UpdateRecorder { // are handled in reverse and in case a decorator and import are inserted at // the start of the file, the class decorator should come after the import. this.failures.unshift(new RuleFailure( - this.sourceFile, node.getStart(), 0, `Class needs to be decorated with ` + + this.sourceFile, node.getStart(), 0, + `Class needs to be decorated with ` + `"${decoratorText}" because it uses Angular features.`, this.ruleName, Replacement.appendText(node.getStart(), `${decoratorText}\n`))); } diff --git a/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/transform.ts b/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/transform.ts index 159f65d6c81ed..012ff0c43a0d9 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/transform.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-decorated-fields/transform.ts @@ -7,11 +7,11 @@ */ import {PartialEvaluator} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; -import {TypeScriptReflectionHost, reflectObjectLiteral} from '@angular/compiler-cli/src/ngtsc/reflection'; +import {reflectObjectLiteral, TypeScriptReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import * as ts from 'typescript'; import {ImportManager} from '../../utils/import_manager'; -import {NgDecorator, getAngularDecorators} from '../../utils/ng_decorators'; +import {getAngularDecorators, NgDecorator} from '../../utils/ng_decorators'; import {findBaseClassDeclarations} from '../../utils/typescript/find_base_classes'; import {unwrapExpression} from '../../utils/typescript/functions'; @@ -56,7 +56,9 @@ export class UndecoratedClassesWithDecoratedFieldsTransform { } /** Records all changes that were made in the import manager. */ - recordChanges() { this.importManager.recordChanges(); } + recordChanges() { + this.importManager.recordChanges(); + } /** Finds undecorated abstract directives in the specified source files. */ private _findUndecoratedAbstractDirectives(sourceFiles: ts.SourceFile[]) { @@ -130,9 +132,9 @@ export class UndecoratedClassesWithDecoratedFieldsTransform { } /** - * Checks whether the given decorator resolves to an abstract directive. An directive is - * considered "abstract" if there is no selector specified. - */ + * Checks whether the given decorator resolves to an abstract directive. An directive is + * considered "abstract" if there is no selector specified. + */ private _isAbstractDirective({node}: NgDecorator): boolean { const metadataArgs = node.expression.arguments; if (metadataArgs.length === 0) { @@ -146,7 +148,7 @@ export class UndecoratedClassesWithDecoratedFieldsTransform { if (!metadata.has('selector')) { return false; } - const selector = this.partialEvaluator.evaluate(metadata.get('selector') !); + const selector = this.partialEvaluator.evaluate(metadata.get('selector')!); return selector == null; } diff --git a/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/convert_directive_metadata.ts b/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/convert_directive_metadata.ts index aef0570b178af..faa6ca4bf7053 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/convert_directive_metadata.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/convert_directive_metadata.ts @@ -78,7 +78,7 @@ export function convertDirectiveMetadataToExpression( /** * Gets a valid property name from the given text. If the text cannot be used * as unquoted identifier, the name will be wrapped in a string literal. -*/ + */ function getPropertyName(name: string): string|ts.StringLiteral { // Matches the most common identifiers that do not need quotes. Constructing a // regular expression that matches the ECMAScript specification in order to determine diff --git a/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/decorator_rewriter.ts b/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/decorator_rewriter.ts index fa34c27d63463..1767ccd3451b4 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/decorator_rewriter.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/decorator_rewriter.ts @@ -122,7 +122,7 @@ export class DecoratorRewriter { |null { try { return ts - .transform(prop, [ctx => this.importRewriterFactory.create(ctx, this.newSourceFile !)]) + .transform(prop, [ctx => this.importRewriterFactory.create(ctx, this.newSourceFile!)]) .transformed[0]; } catch (e) { // If the error is for an unresolved identifier, we want to return "null" because diff --git a/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/import_rewrite_visitor.ts b/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/import_rewrite_visitor.ts index 3003e9cc276a7..1cbc50aed6f1e 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/import_rewrite_visitor.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-di/decorator_rewrite/import_rewrite_visitor.ts @@ -11,11 +11,11 @@ import {dirname, resolve} from 'path'; import * as ts from 'typescript'; import {ImportManager} from '../../../utils/import_manager'; -import {Import, getImportOfIdentifier} from '../../../utils/typescript/imports'; +import {getImportOfIdentifier, Import} from '../../../utils/typescript/imports'; import {getValueSymbolOfDeclaration} from '../../../utils/typescript/symbol'; import {getPosixPath} from './path_format'; -import {ResolvedExport, getExportSymbolsOfFile} from './source_file_exports'; +import {getExportSymbolsOfFile, ResolvedExport} from './source_file_exports'; /** @@ -116,7 +116,7 @@ export class ImportRewriteTransformerFactory { */ private _getSourceFileExports(sourceFile: ts.SourceFile): ResolvedExport[] { if (this.sourceFileExports.has(sourceFile)) { - return this.sourceFileExports.get(sourceFile) !; + return this.sourceFileExports.get(sourceFile)!; } const sourceFileExports = getExportSymbolsOfFile(sourceFile, this.typeChecker); diff --git a/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts b/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts index ceef1fbc4d119..6ad2f725d9399 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-di/index.ts @@ -123,7 +123,7 @@ function runUndecoratedClassesMigration( /** Gets the update recorder for the specified source file. */ function getUpdateRecorder(sourceFile: ts.SourceFile): UpdateRecorder { if (updateRecorders.has(sourceFile)) { - return updateRecorders.get(sourceFile) !; + return updateRecorders.get(sourceFile)!; } const treeRecorder = tree.beginUpdate(relative(basePath, sourceFile.fileName)); const recorder: UpdateRecorder = { @@ -146,7 +146,9 @@ function runUndecoratedClassesMigration( treeRecorder.remove(namedBindings.getStart(), namedBindings.getWidth()); treeRecorder.insertRight(namedBindings.getStart(), newNamedBindings); }, - commitUpdate() { tree.commitUpdate(treeRecorder); } + commitUpdate() { + tree.commitUpdate(treeRecorder); + } }; updateRecorders.set(sourceFile, recorder); return recorder; diff --git a/packages/core/schematics/migrations/undecorated-classes-with-di/ng_declaration_collector.ts b/packages/core/schematics/migrations/undecorated-classes-with-di/ng_declaration_collector.ts index f0c770cbda18b..e6d569c28bed9 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-di/ng_declaration_collector.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-di/ng_declaration_collector.ts @@ -10,7 +10,7 @@ import {Reference} from '@angular/compiler-cli/src/ngtsc/imports'; import {PartialEvaluator, ResolvedValue} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; import * as ts from 'typescript'; -import {NgDecorator, getAngularDecorators} from '../../utils/ng_decorators'; +import {getAngularDecorators, NgDecorator} from '../../utils/ng_decorators'; import {getPropertyNameText} from '../../utils/typescript/property_name'; diff --git a/packages/core/schematics/migrations/undecorated-classes-with-di/transform.ts b/packages/core/schematics/migrations/undecorated-classes-with-di/transform.ts index 5ec39b6e3eb7a..f6857adde714f 100644 --- a/packages/core/schematics/migrations/undecorated-classes-with-di/transform.ts +++ b/packages/core/schematics/migrations/undecorated-classes-with-di/transform.ts @@ -17,7 +17,7 @@ import {hasExplicitConstructor} from '../../utils/typescript/class_declaration'; import {findBaseClassDeclarations} from '../../utils/typescript/find_base_classes'; import {getImportOfIdentifier} from '../../utils/typescript/imports'; -import {UnexpectedMetadataValueError, convertDirectiveMetadataToExpression} from './decorator_rewrite/convert_directive_metadata'; +import {convertDirectiveMetadataToExpression, UnexpectedMetadataValueError} from './decorator_rewrite/convert_directive_metadata'; import {DecoratorRewriter} from './decorator_rewrite/decorator_rewriter'; import {hasDirectiveDecorator, hasInjectableDecorator} from './ng_declaration_collector'; import {UpdateRecorder} from './update_recorder'; @@ -316,7 +316,9 @@ export class UndecoratedClassesTransform { } /** Records all changes that were made in the import manager. */ - recordChanges() { this.importManager.recordChanges(); } + recordChanges() { + this.importManager.recordChanges(); + } /** * Constructs a TypeScript decorator node from the specified declaration metadata. Returns diff --git a/packages/core/schematics/test/dynamic_queries_migration_spec.ts b/packages/core/schematics/test/dynamic_queries_migration_spec.ts index 19b23c951ed51..69b31fb5309ef 100644 --- a/packages/core/schematics/test/dynamic_queries_migration_spec.ts +++ b/packages/core/schematics/test/dynamic_queries_migration_spec.ts @@ -47,7 +47,7 @@ describe('dynamic queries migration', () => { }); it('should remove the options object from a dynamic ViewChild query that only has one property', - async() => { + async () => { writeFile('/index.ts', ` import { Directive, ViewChild } from '@angular/core'; @@ -62,7 +62,7 @@ describe('dynamic queries migration', () => { }); it('should remove the options object from a dynamic ContentChild query that only has one property', - async() => { + async () => { writeFile('/index.ts', ` import { Directive, ContentChild } from '@angular/core'; @@ -77,7 +77,7 @@ describe('dynamic queries migration', () => { }); it('should only remove the `static` flag from a ViewChild query if it has more than one property', - async() => { + async () => { writeFile('/index.ts', ` import { Directive, ViewChild, ElementRef } from '@angular/core'; @@ -93,7 +93,7 @@ describe('dynamic queries migration', () => { }); it('should only remove the `static` flag from a ContentChild query if it has more than one property', - async() => { + async () => { writeFile('/index.ts', ` import { Directive, ContentChild, ElementRef } from '@angular/core'; @@ -108,7 +108,7 @@ describe('dynamic queries migration', () => { .toContain(`@ContentChild('child', { read: ElementRef }) child: ElementRef;`); }); - it('should not change static ViewChild queries', async() => { + it('should not change static ViewChild queries', async () => { writeFile('/index.ts', ` import { Directive, ViewChild, ElementRef } from '@angular/core'; @@ -123,7 +123,7 @@ describe('dynamic queries migration', () => { .toContain(`@ViewChild('child', { read: ElementRef, static: true }) child: ElementRef;`); }); - it('should not change static ContentChild queries', async() => { + it('should not change static ContentChild queries', async () => { writeFile('/index.ts', ` import { Directive, ContentChild, ElementRef } from '@angular/core'; @@ -138,7 +138,7 @@ describe('dynamic queries migration', () => { .toContain(`@ContentChild('child', { static: true, read: ElementRef }) child: ElementRef;`); }); - it('should migrate dynamic queries on a setter', async() => { + it('should migrate dynamic queries on a setter', async () => { writeFile('/index.ts', ` import { Directive, ContentChild, ViewChild } from '@angular/core'; diff --git a/packages/core/schematics/test/google3/dynamic_queries_spec.ts b/packages/core/schematics/test/google3/dynamic_queries_spec.ts index 51f5a2ec8000b..16ec13d368cb3 100644 --- a/packages/core/schematics/test/google3/dynamic_queries_spec.ts +++ b/packages/core/schematics/test/google3/dynamic_queries_spec.ts @@ -17,7 +17,7 @@ describe('Google3 dynamic queries TSLint rule', () => { let tmpDir: string; beforeEach(() => { - tmpDir = join(process.env['TEST_TMPDIR'] !, 'google3-test'); + tmpDir = join(process.env['TEST_TMPDIR']!, 'google3-test'); shx.mkdir('-p', tmpDir); writeFile('tsconfig.json', JSON.stringify({compilerOptions: {module: 'es2015'}})); @@ -31,7 +31,7 @@ describe('Google3 dynamic queries TSLint rule', () => { const config = Configuration.parseConfigFile({rules: {'dynamic-queries': true}}); program.getRootFileNames().forEach(fileName => { - linter.lint(fileName, program.getSourceFile(fileName) !.getFullText(), config); + linter.lint(fileName, program.getSourceFile(fileName)!.getFullText(), config); }); return linter; @@ -41,7 +41,9 @@ describe('Google3 dynamic queries TSLint rule', () => { writeFileSync(join(tmpDir, fileName), content); } - function getFile(fileName: string) { return readFileSync(join(tmpDir, fileName), 'utf8'); } + function getFile(fileName: string) { + return readFileSync(join(tmpDir, fileName), 'utf8'); + } it('should flag dynamic queries', () => { writeFile('/index.ts', ` @@ -172,5 +174,4 @@ describe('Google3 dynamic queries TSLint rule', () => { expect(content).toContain(`@ContentChild('child') set child(c: any) {}`); expect(content).toContain(`@ViewChild('otherChild') set otherChild(c: any) {}`); }); - }); diff --git a/packages/core/schematics/test/google3/explicit_query_timing_rule_spec.ts b/packages/core/schematics/test/google3/explicit_query_timing_rule_spec.ts index 3705176b85f89..895973c728836 100644 --- a/packages/core/schematics/test/google3/explicit_query_timing_rule_spec.ts +++ b/packages/core/schematics/test/google3/explicit_query_timing_rule_spec.ts @@ -12,7 +12,6 @@ import * as shx from 'shelljs'; import {Configuration, Linter} from 'tslint'; describe('Google3 explicitQueryTiming TSLint rule', () => { - /** * Path to the static-query schematic rules directory. The path needs to be resolved through * the Bazel runfiles, because on Windows runfiles are not symlinked into the working directory. @@ -23,7 +22,7 @@ describe('Google3 explicitQueryTiming TSLint rule', () => { let tmpDir: string; beforeEach(() => { - tmpDir = join(process.env['TEST_TMPDIR'] !, 'google3-test'); + tmpDir = join(process.env['TEST_TMPDIR']!, 'google3-test'); shx.mkdir('-p', tmpDir); writeFile('tsconfig.json', JSON.stringify({compilerOptions: {module: 'es2015'}})); @@ -41,7 +40,7 @@ describe('Google3 explicitQueryTiming TSLint rule', () => { const config = Configuration.parseConfigFile({rules: {'explicit-query-timing': true}}); program.getRootFileNames().forEach(fileName => { - linter.lint(fileName, program.getSourceFile(fileName) !.getFullText(), config); + linter.lint(fileName, program.getSourceFile(fileName)!.getFullText(), config); }); return linter; diff --git a/packages/core/schematics/test/google3/missing_injectable_rule_spec.ts b/packages/core/schematics/test/google3/missing_injectable_rule_spec.ts index 87cf98a077f75..5a11ec8ad6431 100644 --- a/packages/core/schematics/test/google3/missing_injectable_rule_spec.ts +++ b/packages/core/schematics/test/google3/missing_injectable_rule_spec.ts @@ -18,7 +18,7 @@ describe('Google3 missing injectable tslint rule', () => { let tmpDir: string; beforeEach(() => { - tmpDir = join(process.env['TEST_TMPDIR'] !, 'google3-test'); + tmpDir = join(process.env['TEST_TMPDIR']!, 'google3-test'); shx.mkdir('-p', tmpDir); writeFile('tsconfig.json', JSON.stringify({compilerOptions: {module: 'es2015'}})); @@ -32,7 +32,7 @@ describe('Google3 missing injectable tslint rule', () => { const config = Configuration.parseConfigFile({rules: {'no-missing-injectable': true}}); program.getRootFileNames().forEach(fileName => { - linter.lint(fileName, program.getSourceFile(fileName) !.getFullText(), config); + linter.lint(fileName, program.getSourceFile(fileName)!.getFullText(), config); }); return linter; @@ -42,7 +42,9 @@ describe('Google3 missing injectable tslint rule', () => { writeFileSync(join(tmpDir, fileName), content); } - function getFile(fileName: string) { return readFileSync(join(tmpDir, fileName), 'utf8'); } + function getFile(fileName: string) { + return readFileSync(join(tmpDir, fileName), 'utf8'); + } describe('NgModule', () => createTests('NgModule', 'providers')); describe('Directive', () => createTests('Directive', 'providers')); @@ -77,7 +79,7 @@ describe('Google3 missing injectable tslint rule', () => { }); function createTests( - type: 'NgModule' | 'Directive' | 'Component', propName: 'providers' | 'viewProviders') { + type: 'NgModule'|'Directive'|'Component', propName: 'providers'|'viewProviders') { it('should create proper failures for missing injectable providers', () => { writeFile('index.ts', ` import { ${type} } from '@angular/core'; @@ -266,6 +268,4 @@ describe('Google3 missing injectable tslint rule', () => { .toMatch(/import { Inject, Injectable } from '@angular\/core';/); }); } - - }); diff --git a/packages/core/schematics/test/google3/no_template_variable_assignment_rule_spec.ts b/packages/core/schematics/test/google3/no_template_variable_assignment_rule_spec.ts index 66ce27f7ccbab..08ffd83ebf015 100644 --- a/packages/core/schematics/test/google3/no_template_variable_assignment_rule_spec.ts +++ b/packages/core/schematics/test/google3/no_template_variable_assignment_rule_spec.ts @@ -18,7 +18,7 @@ describe('Google3 noTemplateVariableAssignment TSLint rule', () => { let tmpDir: string; beforeEach(() => { - tmpDir = join(process.env['TEST_TMPDIR'] !, 'google3-test'); + tmpDir = join(process.env['TEST_TMPDIR']!, 'google3-test'); shx.mkdir('-p', tmpDir); writeFile('tsconfig.json', JSON.stringify({compilerOptions: {module: 'es2015'}})); @@ -34,7 +34,7 @@ describe('Google3 noTemplateVariableAssignment TSLint rule', () => { Configuration.parseConfigFile({rules: {'no-template-variable-assignment': true}}); program.getRootFileNames().forEach(fileName => { - linter.lint(fileName, program.getSourceFile(fileName) !.getFullText(), config); + linter.lint(fileName, program.getSourceFile(fileName)!.getFullText(), config); }); return linter; diff --git a/packages/core/schematics/test/google3/renderer_to_renderer2_spec.ts b/packages/core/schematics/test/google3/renderer_to_renderer2_spec.ts index f403e7a026782..ee5a452899b9f 100644 --- a/packages/core/schematics/test/google3/renderer_to_renderer2_spec.ts +++ b/packages/core/schematics/test/google3/renderer_to_renderer2_spec.ts @@ -18,7 +18,7 @@ describe('Google3 Renderer to Renderer2 TSLint rule', () => { let tmpDir: string; beforeEach(() => { - tmpDir = join(process.env['TEST_TMPDIR'] !, 'google3-test'); + tmpDir = join(process.env['TEST_TMPDIR']!, 'google3-test'); shx.mkdir('-p', tmpDir); // We need to declare the Angular symbols we're testing for, otherwise type checking won't work. @@ -46,7 +46,7 @@ describe('Google3 Renderer to Renderer2 TSLint rule', () => { const config = Configuration.parseConfigFile({rules: {'renderer-to-renderer2': true}}); program.getRootFileNames().forEach(fileName => { - linter.lint(fileName, program.getSourceFile(fileName) !.getFullText(), config); + linter.lint(fileName, program.getSourceFile(fileName)!.getFullText(), config); }); return linter; @@ -56,7 +56,9 @@ describe('Google3 Renderer to Renderer2 TSLint rule', () => { writeFileSync(join(tmpDir, fileName), content); } - function getFile(fileName: string) { return readFileSync(join(tmpDir, fileName), 'utf8'); } + function getFile(fileName: string) { + return readFileSync(join(tmpDir, fileName), 'utf8'); + } it('should flag Renderer imports and typed nodes', () => { writeFile('/index.ts', ` @@ -223,8 +225,8 @@ describe('Google3 Renderer to Renderer2 TSLint rule', () => { runTSLint(true); const content = getFile('index.ts'); - expect(content.match(/function __ngRendererCreateElementHelper\(/g) !.length).toBe(1); - expect(content.match(/function __ngRendererSetElementAttributeHelper\(/g) !.length).toBe(1); + expect(content.match(/function __ngRendererCreateElementHelper\(/g)!.length).toBe(1); + expect(content.match(/function __ngRendererSetElementAttributeHelper\(/g)!.length).toBe(1); }); it('should insert helpers after the user\'s code', () => { @@ -410,5 +412,4 @@ describe('Google3 Renderer to Renderer2 TSLint rule', () => { // Expect the `setInfo` method to only contain whitespace. expect(content).toMatch(/setInfo\(\) \{\s+\}/); }); - }); diff --git a/packages/core/schematics/test/google3/undecorated_classes_with_decorated_fields_spec.ts b/packages/core/schematics/test/google3/undecorated_classes_with_decorated_fields_spec.ts index c78cdfcad0307..a8e5764a5ef5d 100644 --- a/packages/core/schematics/test/google3/undecorated_classes_with_decorated_fields_spec.ts +++ b/packages/core/schematics/test/google3/undecorated_classes_with_decorated_fields_spec.ts @@ -18,7 +18,7 @@ describe('Google3 undecorated classes with decorated fields TSLint rule', () => let tmpDir: string; beforeEach(() => { - tmpDir = join(process.env['TEST_TMPDIR'] !, 'google3-test'); + tmpDir = join(process.env['TEST_TMPDIR']!, 'google3-test'); shx.mkdir('-p', tmpDir); writeFile('tsconfig.json', JSON.stringify({compilerOptions: {module: 'es2015'}})); }); @@ -33,7 +33,7 @@ describe('Google3 undecorated classes with decorated fields TSLint rule', () => }); program.getRootFileNames().forEach(fileName => { - linter.lint(fileName, program.getSourceFile(fileName) !.getFullText(), config); + linter.lint(fileName, program.getSourceFile(fileName)!.getFullText(), config); }); return linter; @@ -43,7 +43,9 @@ describe('Google3 undecorated classes with decorated fields TSLint rule', () => writeFileSync(join(tmpDir, fileName), content); } - function getFile(fileName: string) { return readFileSync(join(tmpDir, fileName), 'utf8'); } + function getFile(fileName: string) { + return readFileSync(join(tmpDir, fileName), 'utf8'); + } it('should flag undecorated classes with decorated fields', () => { writeFile('/index.ts', ` @@ -97,8 +99,9 @@ describe('Google3 undecorated classes with decorated fields TSLint rule', () => expect(getFile('/index.ts')).toContain(`import { Directive, Input } from '@angular/core';`); }); - it('should not generate conflicting imports there is a different `Directive` symbol', async() => { - writeFile('/index.ts', ` + it('should not generate conflicting imports there is a different `Directive` symbol', + async () => { + writeFile('/index.ts', ` import { HostBinding } from '@angular/core'; export class Directive { @@ -111,12 +114,12 @@ describe('Google3 undecorated classes with decorated fields TSLint rule', () => } `); - runTSLint(true); - const fileContent = getFile('/index.ts'); - expect(fileContent) - .toContain(`import { HostBinding, Directive as Directive_1 } from '@angular/core';`); - expect(fileContent).toMatch(/@Directive_1\(\)\s+export class MyLibrarySharedBaseClass/); - }); + runTSLint(true); + const fileContent = getFile('/index.ts'); + expect(fileContent) + .toContain(`import { HostBinding, Directive as Directive_1 } from '@angular/core';`); + expect(fileContent).toMatch(/@Directive_1\(\)\s+export class MyLibrarySharedBaseClass/); + }); it('should add @Directive to undecorated classes that have @Input', () => { writeFile('/index.ts', ` @@ -250,7 +253,7 @@ describe('Google3 undecorated classes with decorated fields TSLint rule', () => expect(getFile('/index.ts')).toContain(`@Directive()\nexport class Base {`); }); - it('should add @Directive to undecorated derived classes of a migrated class', async() => { + it('should add @Directive to undecorated derived classes of a migrated class', async () => { writeFile('/index.ts', ` import { Input, Directive, NgModule } from '@angular/core'; diff --git a/packages/core/schematics/test/line_mappings_spec.ts b/packages/core/schematics/test/line_mappings_spec.ts index a9aa66fb5bb53..17565e11d88d2 100644 --- a/packages/core/schematics/test/line_mappings_spec.ts +++ b/packages/core/schematics/test/line_mappings_spec.ts @@ -9,7 +9,6 @@ import {computeLineStartsMap, getLineAndCharacterFromPosition} from '../utils/line_mappings'; describe('line mappings', () => { - it('should properly compute line starts', () => { expect(computeLineStartsMap(` diff --git a/packages/core/schematics/test/missing_injectable_migration_spec.ts b/packages/core/schematics/test/missing_injectable_migration_spec.ts index 762989f4a8204..f07027a538a7b 100644 --- a/packages/core/schematics/test/missing_injectable_migration_spec.ts +++ b/packages/core/schematics/test/missing_injectable_migration_spec.ts @@ -76,7 +76,7 @@ describe('Missing injectable migration', () => { it('should migrate all providers defined in "viewProviders" and "providers" in the ' + 'same component', - async() => { + async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -102,8 +102,8 @@ describe('Missing injectable migration', () => { }); function createTests( - type: 'NgModule' | 'Directive' | 'Component', propName: 'providers' | 'viewProviders') { - it(`should migrate type provider in ${type}`, async() => { + type: 'NgModule'|'Directive'|'Component', propName: 'providers'|'viewProviders') { + it(`should migrate type provider in ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -121,7 +121,7 @@ describe('Missing injectable migration', () => { .toContain(`{ ${type}, Injectable } from '@angular/core`); }); - it(`should migrate object literal provider in ${type} to explicit value provider`, async() => { + it(`should migrate object literal provider in ${type} to explicit value provider`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -140,7 +140,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).toContain(`{${type}} from '@angular/core`); }); - it(`should migrate object literal provider with forwardRef in ${type}`, async() => { + it(`should migrate object literal provider with forwardRef in ${type}`, async () => { writeFile('/index.ts', ` import {${type}, forwardRef} from '@angular/core'; @@ -158,7 +158,7 @@ describe('Missing injectable migration', () => { .toContain(`{ ${type}, forwardRef, Injectable } from '@angular/core`); }); - it(`should not migrate object literal provider with "useValue" in ${type}`, async() => { + it(`should not migrate object literal provider with "useValue" in ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -174,7 +174,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).not.toContain('@Injectable'); }); - it(`should not migrate provider with "useClass" and "deps" in ${type}`, async() => { + it(`should not migrate provider with "useClass" and "deps" in ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -190,7 +190,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).not.toContain('@Injectable'); }); - it(`should not migrate object literal provider with "useFactory" in ${type}`, async() => { + it(`should not migrate object literal provider with "useFactory" in ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -206,7 +206,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).not.toContain('@Injectable'); }); - it(`should not migrate object literal provider with "useExisting" in ${type}`, async() => { + it(`should not migrate object literal provider with "useExisting" in ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -226,7 +226,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).not.toContain('@Injectable'); }); - it(`should migrate object literal provider with "useClass" in ${type}`, async() => { + it(`should migrate object literal provider with "useClass" in ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -248,7 +248,7 @@ describe('Missing injectable migration', () => { it(`should not migrate references for providers with "useExisting" in ${type}, but migrate ` + `existing token if declared in other ${type}`, - async() => { + async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -281,7 +281,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).toMatch(/MyService {}\s+export class MyToken/); }); - it('should not migrate provider which is already decorated with @Injectable', async() => { + it('should not migrate provider which is already decorated with @Injectable', async () => { writeFile('/index.ts', ` import {Injectable, ${type}} from '@angular/core'; @@ -299,7 +299,7 @@ describe('Missing injectable migration', () => { .toMatch(/@angular\/core';\s+@Injectable\(\)\s+export class MyService/); }); - it('should not migrate provider which is already decorated with @Directive', async() => { + it('should not migrate provider which is already decorated with @Directive', async () => { writeFile('/index.ts', ` import {Directive, ${type}} from '@angular/core'; @@ -316,7 +316,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).not.toContain('@Injectable'); }); - it('should not migrate provider which is already decorated with @Component', async() => { + it('should not migrate provider which is already decorated with @Component', async () => { writeFile('/index.ts', ` import {Component, ${type}} from '@angular/core'; @@ -333,7 +333,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).not.toContain('@Injectable'); }); - it('should not migrate provider which is already decorated with @Pipe', async() => { + it('should not migrate provider which is already decorated with @Pipe', async () => { writeFile('/index.ts', ` import {Pipe, ${type}} from '@angular/core'; @@ -350,7 +350,7 @@ describe('Missing injectable migration', () => { expect(tree.readContent('/index.ts')).not.toContain('@Injectable'); }); - it(`should migrate multiple providers in same ${type}`, async() => { + it(`should migrate multiple providers in same ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -370,7 +370,7 @@ describe('Missing injectable migration', () => { .toContain(`{ ${type}, Injectable } from '@angular/core`); }); - it(`should migrate multiple mixed providers in same ${type}`, async() => { + it(`should migrate multiple mixed providers in same ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -399,7 +399,7 @@ describe('Missing injectable migration', () => { .toContain(`{ provide: ServiceB, useValue: undefined },`); }); - it(`should migrate multiple nested providers in same ${type}`, async() => { + it(`should migrate multiple nested providers in same ${type}`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -433,7 +433,7 @@ describe('Missing injectable migration', () => { .toContain(`{ provide: ServiceD, useValue: undefined },`); }); - it('should migrate providers referenced through identifier', async() => { + it('should migrate providers referenced through identifier', async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -467,7 +467,7 @@ describe('Missing injectable migration', () => { .toContain(`{ provide: ServiceC, useValue: undefined },`); }); - it('should migrate providers created through static analyzable function call', async() => { + it('should migrate providers created through static analyzable function call', async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -497,7 +497,7 @@ describe('Missing injectable migration', () => { .toContain(`ServiceB, { provide: ServiceC, useValue: undefined }),`); }); - it('should migrate providers which are computed through spread operator', async() => { + it('should migrate providers which are computed through spread operator', async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -525,7 +525,7 @@ describe('Missing injectable migration', () => { .toContain(`ServiceB, { provide: ServiceC, useValue: undefined }];`); }); - it(`should migrate provider once if referenced in multiple ${type} definitions`, async() => { + it(`should migrate provider once if referenced in multiple ${type} definitions`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -559,7 +559,7 @@ describe('Missing injectable migration', () => { it(`should only migrate empty object provider literal once if referenced multiple times ` + `in ${type} definitions`, - async() => { + async () => { writeFile('/provider.ts', ` export class MyService {} @@ -592,7 +592,7 @@ describe('Missing injectable migration', () => { .toContain(`const PROVIDER = { provide: MyService, useValue: undefined };`); }); - it('should create new import for @Injectable when migrating provider', async() => { + it('should create new import for @Injectable when migrating provider', async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; import {MyService, MySecondService} from './service'; @@ -617,7 +617,7 @@ describe('Missing injectable migration', () => { }); it('should re-use existing namespace import for importing @Injectable when migrating provider', - async() => { + async () => { writeFile('/index.ts', ` import * as core from '@angular/core'; @@ -643,7 +643,7 @@ describe('Missing injectable migration', () => { .toMatch(/@core.Injectable\(\)\s+export class MyService/); }); - it('should warn if a referenced individual provider could not be resolved', async() => { + it('should warn if a referenced individual provider could not be resolved', async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -659,7 +659,7 @@ describe('Missing injectable migration', () => { expect(warnOutput[0]).toContain(`4:${providerSourceTextColumn}:`); }); - it(`should warn if ${propName} value could not be resolved`, async() => { + it(`should warn if ${propName} value could not be resolved`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -675,7 +675,7 @@ describe('Missing injectable migration', () => { expect(warnOutput[0]).toContain(`4:${propValueSourceTextColumn}:`); }); - it(`should not throw if an empty @${type} is analyzed`, async() => { + it(`should not throw if an empty @${type} is analyzed`, async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; @@ -693,7 +693,7 @@ describe('Missing injectable migration', () => { }); it('should create new import for injectable after full end of last import statement', - async() => { + async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; import {MyService} from './service'; @@ -718,7 +718,7 @@ describe('Missing injectable migration', () => { .toMatch(/'b'; \/\/ some comment\s+import { Injectable } from "@angular\/core";/); }); - it('should create new import at source file start with trailing new-line', async() => { + it('should create new import at source file start with trailing new-line', async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; import {MyService} from './service'; @@ -739,7 +739,7 @@ describe('Missing injectable migration', () => { /^import { Injectable } from "@angular\/core";\s+\/\* @license \*\/\s+@Injectable\(\)\s+export class MyService/); }); - it('should remove @Inject decorator for providers which are migrated', async() => { + it('should remove @Inject decorator for providers which are migrated', async () => { writeFile('/index.ts', ` import {${type}} from '@angular/core'; import {MyService} from './service'; @@ -766,7 +766,7 @@ describe('Missing injectable migration', () => { .toMatch(/import { Inject, Injectable } from '@angular\/core';/); }); - it('should not migrate provider classes in library type definitions', async() => { + it('should not migrate provider classes in library type definitions', async () => { writeFile('/node_modules/my-lib/index.d.ts', ` export declare class MyService {} `); diff --git a/packages/core/schematics/test/module_with_providers_migration_spec.ts b/packages/core/schematics/test/module_with_providers_migration_spec.ts index 089753a633d15..13a999e76d90e 100644 --- a/packages/core/schematics/test/module_with_providers_migration_spec.ts +++ b/packages/core/schematics/test/module_with_providers_migration_spec.ts @@ -46,7 +46,7 @@ describe('ModuleWithProviders migration', () => { shx.rm('-r', tmpDirPath); }); - it('should add generic type for function return', async() => { + it('should add generic type for function return', async () => { writeFile('/index.ts', ` import {NgModule, ModuleWithProviders} from '@angular/core'; @@ -69,7 +69,7 @@ describe('ModuleWithProviders migration', () => { expect(tree.readContent('/index.ts')).toContain(`ModuleWithProviders`); }); - it('should add generic type for function return; external file', async() => { + it('should add generic type for function return; external file', async () => { writeFile('/module.ts', ` import {NgModule} from '@angular/core'; @@ -96,7 +96,7 @@ describe('ModuleWithProviders migration', () => { expect(tree.readContent('/index.ts')).toContain(`ModuleWithProviders`); }); - it('should add generic type for function return without explicit type', async() => { + it('should add generic type for function return without explicit type', async () => { writeFile('/index.ts', ` import {NgModule} from '@angular/core'; @@ -119,7 +119,7 @@ describe('ModuleWithProviders migration', () => { expect(tree.readContent('/index.ts')).toContain(`ModuleWithProviders`); }); - it('should add generic type for const variable', async() => { + it('should add generic type for const variable', async () => { writeFile('/index.ts', ` import {ModuleWithProviders, NgModule} from '@angular/core'; @@ -140,7 +140,7 @@ describe('ModuleWithProviders migration', () => { expect(tree.readContent('/index.ts')).toContain(`ModuleWithProviders`); }); - it('should add generic type for const variable without explicit type', async() => { + it('should add generic type for const variable without explicit type', async () => { writeFile('/index.ts', ` import {NgModule} from '@angular/core'; @@ -161,7 +161,7 @@ describe('ModuleWithProviders migration', () => { expect(tree.readContent('/index.ts')).toContain(`ModuleWithProviders`); }); - it('should not add generic type for const variable with invalid base object', async() => { + it('should not add generic type for const variable with invalid base object', async () => { writeFile('/index.ts', ` import {NgModule} from '@angular/core'; @@ -182,7 +182,7 @@ describe('ModuleWithProviders migration', () => { expect(tree.readContent('/index.ts')).not.toContain(`ModuleWithProviders`); }); - it('should add generic type for const variables and functions with incomplete type', async() => { + it('should add generic type for const variables and functions with incomplete type', async () => { writeFile('/index.ts', ` import {ModuleWithProviders, NgModule} from '@angular/core'; @@ -214,7 +214,7 @@ describe('ModuleWithProviders migration', () => { expect(tree.readContent('/index.ts')).not.toContain(`ModuleWithProviders `); }); - it('should not add generic type for const variables without initialization', async() => { + it('should not add generic type for const variables without initialization', async () => { writeFile('/index.ts', ` import {ModuleWithProviders} from '@angular/core'; diff --git a/packages/core/schematics/test/move_document_migration_spec.ts b/packages/core/schematics/test/move_document_migration_spec.ts index 46aefc9e016d2..d0f252c4fc5af 100644 --- a/packages/core/schematics/test/move_document_migration_spec.ts +++ b/packages/core/schematics/test/move_document_migration_spec.ts @@ -47,7 +47,7 @@ describe('move-document migration', () => { }); describe('move-document', () => { - it('should properly apply import replacement', async() => { + it('should properly apply import replacement', async () => { writeFile('/index.ts', ` import {DOCUMENT} from '@angular/platform-browser'; `); @@ -73,7 +73,7 @@ describe('move-document migration', () => { expect(content).not.toContain(`import {DOCUMENT} from '@angular/platform-browser';`); }); - it('should properly apply import replacement with existing import', async() => { + it('should properly apply import replacement with existing import', async () => { writeFile('/index.ts', ` import {DOCUMENT} from '@angular/platform-browser'; import {someImport} from '@angular/common'; @@ -96,7 +96,7 @@ describe('move-document migration', () => { expect(contentReverse).not.toContain(`import {DOCUMENT} from '@angular/platform-browser';`); }); - it('should properly apply import replacement with existing import w/ comments', async() => { + it('should properly apply import replacement with existing import w/ comments', async () => { writeFile('/index.ts', ` /** * this is a comment @@ -115,7 +115,7 @@ describe('move-document migration', () => { expect(content).toMatch(/.*this is a comment.*/); }); - it('should properly apply import replacement with existing and redundant imports', async() => { + it('should properly apply import replacement with existing and redundant imports', async () => { writeFile('/index.ts', ` import {DOCUMENT} from '@angular/platform-browser'; import {anotherImport} from '@angular/platform-browser-dynamic'; @@ -131,7 +131,7 @@ describe('move-document migration', () => { }); it('should properly apply import replacement with existing import and leave original import', - async() => { + async () => { writeFile('/index.ts', ` import {DOCUMENT, anotherImport} from '@angular/platform-browser'; import {someImport} from '@angular/common'; @@ -145,7 +145,7 @@ describe('move-document migration', () => { expect(content).toContain(`import { anotherImport } from '@angular/platform-browser';`); }); - it('should properly apply import replacement with existing import and alias', async() => { + it('should properly apply import replacement with existing import and alias', async () => { writeFile('/index.ts', ` import {DOCUMENT as doc, anotherImport} from '@angular/platform-browser'; import {someImport} from '@angular/common'; diff --git a/packages/core/schematics/test/project_tsconfig_paths_spec.ts b/packages/core/schematics/test/project_tsconfig_paths_spec.ts index 0ebf15276debc..b9cb58b5047c8 100644 --- a/packages/core/schematics/test/project_tsconfig_paths_spec.ts +++ b/packages/core/schematics/test/project_tsconfig_paths_spec.ts @@ -13,13 +13,14 @@ import {getProjectTsConfigPaths} from '../utils/project_tsconfig_paths'; describe('project tsconfig paths', () => { let testTree: UnitTestTree; - beforeEach(() => { testTree = new UnitTestTree(new HostTree()); }); + beforeEach(() => { + testTree = new UnitTestTree(new HostTree()); + }); it('should detect build tsconfig path inside of angular.json file', () => { testTree.create('/my-custom-config.json', ''); testTree.create('/angular.json', JSON.stringify({ - projects: - {my_name: {architect: {build: {options: {tsConfig: './my-custom-config.json'}}}}} + projects: {my_name: {architect: {build: {options: {tsConfig: './my-custom-config.json'}}}}} })); expect(getProjectTsConfigPaths(testTree).buildPaths).toEqual(['my-custom-config.json']); @@ -57,8 +58,7 @@ describe('project tsconfig paths', () => { it('should detect test tsconfig path inside of .angular.json file', () => { testTree.create('/my-test-config.json', ''); testTree.create('/.angular.json', JSON.stringify({ - projects: - {with_tests: {architect: {test: {options: {tsConfig: './my-test-config.json'}}}}} + projects: {with_tests: {architect: {test: {options: {tsConfig: './my-test-config.json'}}}}} })); expect(getProjectTsConfigPaths(testTree).testPaths).toEqual(['my-test-config.json']); diff --git a/packages/core/schematics/test/renderer_to_renderer2_migration_spec.ts b/packages/core/schematics/test/renderer_to_renderer2_migration_spec.ts index c30919ea5d9c8..c818804e89cf0 100644 --- a/packages/core/schematics/test/renderer_to_renderer2_migration_spec.ts +++ b/packages/core/schematics/test/renderer_to_renderer2_migration_spec.ts @@ -52,7 +52,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('import renaming', () => { - it('should change Renderer imports to Renderer2', async() => { + it('should change Renderer imports to Renderer2', async () => { writeFile('/index.ts', ` import { Renderer, Component } from '@angular/core'; @@ -67,7 +67,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain(`import { Component, Renderer2 } from '@angular/core';`); }); - it('should change aliased Renderer imports to Renderer2', async() => { + it('should change aliased Renderer imports to Renderer2', async () => { writeFile('/index.ts', ` import { Renderer as RenamedRenderer, Component } from '@angular/core'; @@ -82,7 +82,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain(`import { Component, Renderer2 as RenamedRenderer } from '@angular/core';`); }); - it('should not change Renderer imports if they are not from @angular/core', async() => { + it('should not change Renderer imports if they are not from @angular/core', async () => { writeFile('/index.ts', ` import { Component } from '@angular/core'; import { Renderer } from './my-renderer'; @@ -102,7 +102,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('type renaming', () => { - it('should change type of constructor parameter from Renderer to Renderer2', async() => { + it('should change type of constructor parameter from Renderer to Renderer2', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -117,7 +117,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain('constructor(element: ElementRef, renderer: Renderer2)'); }); - it('should change type of method parameter from Renderer to Renderer2', async() => { + it('should change type of method parameter from Renderer to Renderer2', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -134,7 +134,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain('disable(renderer: Renderer2, element: HTMLElement, isDisabled: boolean)'); }); - it('should change type of property declarations', async() => { + it('should change type of property declarations', async () => { writeFile('/index.ts', ` import { Renderer, Component } from '@angular/core'; @@ -148,7 +148,7 @@ describe('Renderer to Renderer2 migration', () => { expect(tree.readContent('/index.ts')).toContain('public renderer: Renderer2;'); }); - it('should change type of properties initialized via the constructor', async() => { + it('should change type of properties initialized via the constructor', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -163,7 +163,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain('constructor(element: ElementRef, private _renderer: Renderer2)'); }); - it('should change the type of something that was cast to Renderer', async() => { + it('should change the type of something that was cast to Renderer', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -184,7 +184,7 @@ describe('Renderer to Renderer2 migration', () => { expect(content).toContain(`renderer.setStyle(element.nativeElement, 'color', 'red');`); }); - it('should not rename types called Renderer that do not come from Angular', async() => { + it('should not rename types called Renderer that do not come from Angular', async () => { // Write a dummy renderer file so type checking picks it up. writeFile('/my-renderer.ts', `export abstract class Renderer {}`); @@ -203,7 +203,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain('constructor(element: ElementRef, renderer: Renderer)'); }); - it('should rename inside single-line forwardRef', async() => { + it('should rename inside single-line forwardRef', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef, forwardRef, Inject } from '@angular/core'; @@ -221,7 +221,7 @@ describe('Renderer to Renderer2 migration', () => { `constructor(@Inject(forwardRef(() => Renderer2)) private _renderer: Renderer2)`); }); - it('should rename inside multi-line forwardRef', async() => { + it('should rename inside multi-line forwardRef', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef, forwardRef, Inject } from '@angular/core'; @@ -238,11 +238,10 @@ describe('Renderer to Renderer2 migration', () => { expect(content).toContain( `constructor(@Inject(forwardRef(() => { return Renderer2; })) private _renderer: Renderer2) {}`); }); - }); describe('helper insertion', () => { - it('should only declare each helper once per file', async() => { + it('should only declare each helper once per file', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -260,11 +259,11 @@ describe('Renderer to Renderer2 migration', () => { const content = tree.readContent('/index.ts'); - expect(content.match(/function __ngRendererCreateElementHelper\(/g) !.length) + expect(content.match(/function __ngRendererCreateElementHelper\(/g)!.length) .toBe(1, 'Expected exactly one helper for createElement.'); }); - it('should insert helpers after the user\'s code', async() => { + it('should insert helpers after the user\'s code', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -287,7 +286,7 @@ describe('Renderer to Renderer2 migration', () => { expect(contentAfterSeparator).toContain('function __ngRendererCreateElementHelper('); }); - it('should be able to handle multiple helpers per file', async() => { + it('should be able to handle multiple helpers per file', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -314,15 +313,15 @@ describe('Renderer to Renderer2 migration', () => { const content = tree.readContent('/index.ts'); - expect(content.match(/function __ngRendererCreateTextHelper\(/g) !.length) + expect(content.match(/function __ngRendererCreateTextHelper\(/g)!.length) .toBe(1, 'Expected exactly one helper for createElement.'); - expect(content.match(/function __ngRendererCreateElementHelper\(/g) !.length) + expect(content.match(/function __ngRendererCreateElementHelper\(/g)!.length) .toBe(1, 'Expected exactly one helper for createText.'); - expect(content.match(/function __ngRendererCreateTemplateAnchorHelper\(/g) !.length) + expect(content.match(/function __ngRendererCreateTemplateAnchorHelper\(/g)!.length) .toBe(1, 'Expected exactly one helper for createTemplateAnchor.'); }); - it('should create the __ngRendererSplitNamespaceHelper', async() => { + it('should create the __ngRendererSplitNamespaceHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -347,7 +346,7 @@ describe('Renderer to Renderer2 migration', () => { `)); }); - it('should declare our custom any type', async() => { + it('should declare our custom any type', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -365,11 +364,10 @@ describe('Renderer to Renderer2 migration', () => { type AnyDuringRendererMigration = any; `)); }); - }); describe('setElementProperty migration', () => { - it('should migrate setElementProperty calls', async() => { + it('should migrate setElementProperty calls', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -390,7 +388,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('setText migration', () => { - it('should migrate setText calls', async() => { + it('should migrate setText calls', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -412,7 +410,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('listenGlobal migration', () => { - it('should migrate listenGlobal calls', async() => { + it('should migrate listenGlobal calls', async () => { writeFile('/index.ts', ` import { Renderer, Component } from '@angular/core'; @@ -433,7 +431,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('selectRootElement migration', () => { - it('should migrate selectRootElement calls', async() => { + it('should migrate selectRootElement calls', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -454,7 +452,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('setElementClass migration', () => { - it('should migrate calls with inline isAdd value', async() => { + it('should migrate calls with inline isAdd value', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -479,7 +477,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain(`this._renderer.removeClass(this._element.nativeElement, className);`); }); - it('should migrate calls with variable isAdd value', async() => { + it('should migrate calls with variable isAdd value', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -503,7 +501,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('setElementStyle migration', () => { - it('should migrate calls with two arguments to a removeStyle call', async() => { + it('should migrate calls with two arguments to a removeStyle call', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -522,7 +520,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain(`this._renderer.removeStyle(this._element.nativeElement, 'color');`); }); - it('should migrate calls with static third arguments to a setStyle call', async() => { + it('should migrate calls with static third arguments to a setStyle call', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -552,7 +550,7 @@ describe('Renderer to Renderer2 migration', () => { }); it('should migrate calls with null or undefined value for last argument to a removeStyle call', - async() => { + async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -575,7 +573,7 @@ describe('Renderer to Renderer2 migration', () => { `this._renderer.removeStyle(this._element.nativeElement, 'background-color');`); }); - it('should migrate calls with a variable third argument', async() => { + it('should migrate calls with a variable third argument', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -597,7 +595,7 @@ describe('Renderer to Renderer2 migration', () => { }); it('should migrate calls with a variable third argument whose value can be inferred', - async() => { + async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -625,7 +623,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('setElementAttribute migration', () => { - it('should migrate to calls to the __ngRendererSetElementAttributeHelper', async() => { + it('should migrate to calls to the __ngRendererSetElementAttributeHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -651,7 +649,7 @@ describe('Renderer to Renderer2 migration', () => { '__ngRendererSetElementAttributeHelper(this._renderer, this._element.nativeElement, name);'); }); - it('should declare the __ngRendererSetElementAttributeHelper', async() => { + it('should declare the __ngRendererSetElementAttributeHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -680,12 +678,11 @@ describe('Renderer to Renderer2 migration', () => { expect(content).toContain(stripWhitespace('function __ngRendererSplitNamespaceHelper(')); }); - }); describe('invokeElementMethod migration', () => { it('should migrate calls to a direct method call if the method name and arguments are static', - async() => { + async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -710,7 +707,7 @@ describe('Renderer to Renderer2 migration', () => { }); it('should migrate calls to a property access if the method name or arguments are dynamic', - async() => { + async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -738,7 +735,7 @@ describe('Renderer to Renderer2 migration', () => { `(this._element.nativeElement as any)['otherMethod'].apply(this._element.nativeElement, args);`); }); - it('should handle calls without an `args` array', async() => { + it('should handle calls without an `args` array', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -761,7 +758,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('setBindingDebugInfo migration', () => { - it('should drop calls to setBindingDebugInfo', async() => { + it('should drop calls to setBindingDebugInfo', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -783,7 +780,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('createViewRoot migration', () => { - it('should replace createViewRoot calls with a reference to the first argument', async() => { + it('should replace createViewRoot calls with a reference to the first argument', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -806,7 +803,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('createElement migration', () => { - it('should migrate to calls to the __ngRendererCreateElementHelper', async() => { + it('should migrate to calls to the __ngRendererCreateElementHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -833,7 +830,7 @@ describe('Renderer to Renderer2 migration', () => { 'return __ngRendererCreateElementHelper(this._renderer, this._element.nativeElement, nodeName);'); }); - it('should declare the __ngRendererCreateElementHelper', async() => { + it('should declare the __ngRendererCreateElementHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -862,11 +859,10 @@ describe('Renderer to Renderer2 migration', () => { expect(content).toContain(stripWhitespace('function __ngRendererSplitNamespaceHelper(')); }); - }); describe('createText migration', () => { - it('should migrate to calls to the __ngRendererCreateTextHelper', async() => { + it('should migrate to calls to the __ngRendererCreateTextHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -893,7 +889,7 @@ describe('Renderer to Renderer2 migration', () => { 'return __ngRendererCreateTextHelper(this._renderer, this._element.nativeElement, value);'); }); - it('should declare the __ngRendererCreateTextHelper', async() => { + it('should declare the __ngRendererCreateTextHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -917,11 +913,10 @@ describe('Renderer to Renderer2 migration', () => { } `)); }); - }); describe('createTemplateAnchor migration', () => { - it('should migrate to calls to the __ngRendererCreateTemplateAnchorHelper', async() => { + it('should migrate to calls to the __ngRendererCreateTemplateAnchorHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -947,7 +942,7 @@ describe('Renderer to Renderer2 migration', () => { 'return __ngRendererCreateTemplateAnchorHelper(this._renderer, this._element.nativeElement);'); }); - it('should declare the __ngRendererCreateTemplateAnchorHelper', async() => { + it('should declare the __ngRendererCreateTemplateAnchorHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -971,11 +966,10 @@ describe('Renderer to Renderer2 migration', () => { } `)); }); - }); describe('projectNodes migration', () => { - it('should migrate to calls to the __ngRendererProjectNodesHelper', async() => { + it('should migrate to calls to the __ngRendererProjectNodesHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -997,7 +991,7 @@ describe('Renderer to Renderer2 migration', () => { '__ngRendererProjectNodesHelper(this._renderer, this._element.nativeElement, nodesToProject);'); }); - it('should declare the __ngRendererProjectNodesHelper', async() => { + it('should declare the __ngRendererProjectNodesHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -1019,11 +1013,10 @@ describe('Renderer to Renderer2 migration', () => { } `)); }); - }); describe('animate migration', () => { - it('should migrate to calls to the __ngRendererAnimateHelper', async() => { + it('should migrate to calls to the __ngRendererAnimateHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -1043,7 +1036,7 @@ describe('Renderer to Renderer2 migration', () => { expect(tree.readContent('/index.ts')).toContain('__ngRendererAnimateHelper();'); }); - it('should declare the __ngRendererAnimateHelper', async() => { + it('should declare the __ngRendererAnimateHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -1063,11 +1056,10 @@ describe('Renderer to Renderer2 migration', () => { } `)); }); - }); describe('destroyView migration', () => { - it('should migrate to calls to the __ngRendererDestroyViewHelper', async() => { + it('should migrate to calls to the __ngRendererDestroyViewHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -1088,7 +1080,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain('__ngRendererDestroyViewHelper(this._renderer, allNodes);'); }); - it('should declare the __ngRendererDestroyViewHelper', async() => { + it('should declare the __ngRendererDestroyViewHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -1116,7 +1108,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('detachView migration', () => { - it('should migrate to calls to the __ngRendererDetachViewHelper', async() => { + it('should migrate to calls to the __ngRendererDetachViewHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component } from '@angular/core'; @@ -1137,7 +1129,7 @@ describe('Renderer to Renderer2 migration', () => { .toContain('__ngRendererDetachViewHelper(this._renderer, rootNodes);'); }); - it('should declare the __ngRendererDetachViewHelper', async() => { + it('should declare the __ngRendererDetachViewHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component } from '@angular/core'; @@ -1166,7 +1158,7 @@ describe('Renderer to Renderer2 migration', () => { }); describe('attachViewAfter migration', () => { - it('should migrate to calls to the __ngRendererAttachViewAfterHelper', async() => { + it('should migrate to calls to the __ngRendererAttachViewAfterHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component, ElementRef } from '@angular/core'; @@ -1188,7 +1180,7 @@ describe('Renderer to Renderer2 migration', () => { '__ngRendererAttachViewAfterHelper(this._renderer, this._element.nativeElement, rootNodes);'); }); - it('should declare the __ngRendererAttachViewAfterHelper', async() => { + it('should declare the __ngRendererAttachViewAfterHelper', async () => { writeFile('/index.ts', ` import { Renderer, Component } from '@angular/core'; @@ -1225,5 +1217,7 @@ describe('Renderer to Renderer2 migration', () => { return runner.runSchematicAsync('migration-v9-renderer-to-renderer2', {}, tree).toPromise(); } - function stripWhitespace(contents: string) { return contents.replace(/\s/g, ''); } + function stripWhitespace(contents: string) { + return contents.replace(/\s/g, ''); + } }); diff --git a/packages/core/schematics/test/static_queries_migration_template_spec.ts b/packages/core/schematics/test/static_queries_migration_template_spec.ts index 341bb27866d54..31882e577016e 100644 --- a/packages/core/schematics/test/static_queries_migration_template_spec.ts +++ b/packages/core/schematics/test/static_queries_migration_template_spec.ts @@ -61,7 +61,9 @@ describe('static-queries migration with template strategy', () => { shx.rm('-r', tmpDirPath); }); - function writeFakeAngular() { writeFile('/node_modules/@angular/core/index.d.ts', ``); } + function writeFakeAngular() { + writeFile('/node_modules/@angular/core/index.d.ts', ``); + } function writeFakeLibrary(selectorName = 'my-lib-selector') { writeFile('/node_modules/my-lib/index.d.ts', `export * from './public-api';`); @@ -105,8 +107,7 @@ describe('static-queries migration with template strategy', () => { } describe('ViewChild', () => { - - it('should detect queries selecting elements through template reference', async() => { + it('should detect queries selecting elements through template reference', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -135,7 +136,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('myStaticButton', { static: true }) query2: any;`); }); - it('should detect queries selecting ng-template as static', async() => { + it('should detect queries selecting ng-template as static', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -158,7 +159,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('myTmpl', { static: true }) query: any;`); }); - it('should detect queries selecting ng-template as static (BOM)', async() => { + it('should detect queries selecting ng-template as static (BOM)', async () => { writeFile('/index.ts', `\uFEFF import {Component, NgModule, ViewChild} from '@angular/core'; @@ -181,8 +182,9 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('myTmpl', { static: true }) query: any;`); }); - it('should detect queries selecting component view providers through string token', async() => { - writeFile('/index.ts', ` + it('should detect queries selecting component view providers through string token', + async () => { + writeFile('/index.ts', ` import {Component, Directive, NgModule, ViewChild} from '@angular/core'; @Directive({ @@ -211,22 +213,22 @@ describe('static-queries migration with template strategy', () => { export class MyModule {} `); - writeFile(`/my-tmpl.html`, ` + writeFile(`/my-tmpl.html`, ` `); - await runMigration(); + await runMigration(); - expect(tree.readContent('/index.ts')) - .toContain(`@ViewChild('my-token', { static: true }) query: any;`); - expect(tree.readContent('/index.ts')) - .toContain(`@ViewChild('my-token-2', { static: false }) query2: any;`); - }); + expect(tree.readContent('/index.ts')) + .toContain(`@ViewChild('my-token', { static: true }) query: any;`); + expect(tree.readContent('/index.ts')) + .toContain(`@ViewChild('my-token-2', { static: false }) query2: any;`); + }); - it('should detect queries selecting component view providers using class token', async() => { + it('should detect queries selecting component view providers using class token', async () => { writeFile('/index.ts', ` import {Component, Directive, NgModule, ViewChild} from '@angular/core'; @@ -270,7 +272,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild(MyService2, { static: false }) query2: any;`); }); - it('should detect queries selecting component', async() => { + it('should detect queries selecting component', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; import {HomeComponent, HomeComponent2} from './home-comp'; @@ -316,7 +318,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild(HomeComponent2, { static: false }) query2: any;`); }); - it('should detect queries selecting third-party component', async() => { + it('should detect queries selecting third-party component', async () => { writeFakeLibrary(); writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -341,9 +343,10 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild(MyLibComponent, { static: true }) query: any;`); }); - it('should detect queries selecting third-party component with multiple selectors', async() => { - writeFakeLibrary('a-selector, test-selector'); - writeFile('/index.ts', ` + it('should detect queries selecting third-party component with multiple selectors', + async () => { + writeFakeLibrary('a-selector, test-selector'); + writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; import {MyLibComponent} from 'my-lib'; @@ -356,20 +359,20 @@ describe('static-queries migration with template strategy', () => { export class MyModule {} `); - writeFile('/my-tmpl.html', ` + writeFile('/my-tmpl.html', ` Match 1 Match 2 `); - await runMigration(); + await runMigration(); - expect(tree.readContent('/index.ts')) - .toContain(`@ViewChild(MyLibComponent, { static: false }) query: any;`); - }); + expect(tree.readContent('/index.ts')) + .toContain(`@ViewChild(MyLibComponent, { static: false }) query: any;`); + }); - it('should detect queries within structural directive', async() => { + it('should detect queries within structural directive', async () => { writeFile('/index.ts', ` import {Component, Directive, NgModule, ViewChild} from '@angular/core'; @@ -399,7 +402,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('myRef2', { static: false }) query2: any;`); }); - it('should detect inherited queries', async() => { + it('should detect inherited queries', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -424,7 +427,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('myRef', { static: true }) query: any;`); }); - it('should detect queries declared on setter', async() => { + it('should detect queries declared on setter', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -448,7 +451,7 @@ describe('static-queries migration with template strategy', () => { .toMatch(/@ViewChild\('myRef', { static: true }\)\s+set query/); }); - it('should detect queries declared on getter', async() => { + it('should detect queries declared on getter', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -473,7 +476,7 @@ describe('static-queries migration with template strategy', () => { .toMatch(/@ViewChild\('myRef', { static: true }\)\s+get query/); }); - it('should add a todo if a query is not declared in any component', async() => { + it('should add a todo if a query is not declared in any component', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild, SomeToken} from '@angular/core'; @@ -493,7 +496,7 @@ describe('static-queries migration with template strategy', () => { /^⮑ {3}index.ts@5:11:.+could not be determined.+not declared in any component/); }); - it('should add a todo if a query is used multiple times with different timing', async() => { + it('should add a todo if a query is used multiple times with different timing', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -523,7 +526,7 @@ describe('static-queries migration with template strategy', () => { it('should be able to migrate an application with type checking failure which ' + 'does not affect analysis', - async() => { + async () => { // Fakes the `@angular/package` by creating a `ViewChild` decorator // function that requires developers to specify the "static" flag. writeFile('/node_modules/@angular/core/index.d.ts', ` @@ -565,7 +568,7 @@ describe('static-queries migration with template strategy', () => { it('should be able to migrate applications with template type checking failure ' + 'which does not affect analysis', - async() => { + async () => { writeFile('/index.ts', ` import {NgModule, Component, ViewChild} from '@angular/core'; @@ -596,7 +599,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('myRef', { static: true }) query: any;`); }); - it('should notify user if project has syntax errors which can affect analysis', async() => { + it('should notify user if project has syntax errors which can affect analysis', async () => { writeFile('/index.ts', ` import {Component, ViewChild} from '@angular/core'; @@ -630,7 +633,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('myRef', { static: true }) query: any;`); }); - it('should gracefully exit migration if queries could not be analyzed', async() => { + it('should gracefully exit migration if queries could not be analyzed', async () => { writeFile('/index.ts', ` import {Component, ViewChild} from '@angular/core'; @@ -650,7 +653,7 @@ describe('static-queries migration with template strategy', () => { expect(errorOutput[0]).toMatch(/Cannot determine the module for class MyComp/); }); - it('should gracefully exit migration if AOT compiler throws exception', async() => { + it('should gracefully exit migration if AOT compiler throws exception', async () => { writeFile('/my-component.ts', ` import {Component, ViewChild} from '@angular/core'; @@ -691,7 +694,7 @@ describe('static-queries migration with template strategy', () => { expect(errorOutput[0]).toMatch(/^TypeError: Cannot read property 'module' of undefined/); }); - it('should add a todo for content queries which are not detectable', async() => { + it('should add a todo for content queries which are not detectable', async () => { writeFile('/index.ts', ` import {Component, NgModule, ContentChild} from '@angular/core'; @@ -713,7 +716,7 @@ describe('static-queries migration with template strategy', () => { .toMatch(/^⮑ {3}index.ts@6:11: Content queries cannot be migrated automatically\./); }); - it('should add a todo if query options cannot be migrated inline', async() => { + it('should add a todo if query options cannot be migrated inline', async () => { writeFile('/index.ts', ` import {Component, NgModule, ViewChild} from '@angular/core'; @@ -738,7 +741,7 @@ describe('static-queries migration with template strategy', () => { expect(warnOutput[0]).toMatch(/Please manually set the query timing to.*static: true/); }); - it('should not normalize stylesheets which are referenced in component', async() => { + it('should not normalize stylesheets which are referenced in component', async () => { writeFile('sub_dir/index.ts', ` import {Component, NgModule, ContentChild} from '@angular/core'; @@ -765,7 +768,7 @@ describe('static-queries migration with template strategy', () => { expect(console.error).toHaveBeenCalledTimes(0); }); - it('should always use the test migration strategy for test tsconfig files', async() => { + it('should always use the test migration strategy for test tsconfig files', async () => { writeFile('/src/tsconfig.spec.json', JSON.stringify({ compilerOptions: { experimentalDecorators: true, @@ -812,7 +815,7 @@ describe('static-queries migration with template strategy', () => { .toContain(`@ViewChild('test', { static: true }) query: any;`); }); - it('should not fall back to test strategy if selected strategy fails', async() => { + it('should not fall back to test strategy if selected strategy fails', async () => { writeFile('/src/tsconfig.spec.json', JSON.stringify({ compilerOptions: { experimentalDecorators: true, diff --git a/packages/core/schematics/test/static_queries_migration_usage_spec.ts b/packages/core/schematics/test/static_queries_migration_usage_spec.ts index 1ec96166486e7..e5738dea4c91d 100644 --- a/packages/core/schematics/test/static_queries_migration_usage_spec.ts +++ b/packages/core/schematics/test/static_queries_migration_usage_spec.ts @@ -63,7 +63,7 @@ describe('static-queries migration with usage strategy', () => { describe('ViewChild', () => { createQueryTests('ViewChild'); - it('should mark view queries used in "ngAfterContentInit" as static', async() => { + it('should mark view queries used in "ngAfterContentInit" as static', async () => { writeFile('/index.ts', ` import {Component, ViewChild} from '@angular/core'; @@ -83,7 +83,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@ViewChild('test', { static: true }) query: any;`); }); - it('should mark view queries used in "ngAfterContentChecked" as static', async() => { + it('should mark view queries used in "ngAfterContentChecked" as static', async () => { writeFile('/index.ts', ` import {Component, ViewChild} from '@angular/core'; @@ -107,7 +107,7 @@ describe('static-queries migration with usage strategy', () => { describe('ContentChild', () => { createQueryTests('ContentChild'); - it('should not mark content queries used in "ngAfterContentInit" as static', async() => { + it('should not mark content queries used in "ngAfterContentInit" as static', async () => { writeFile('/index.ts', ` import {Component, ContentChild} from '@angular/core'; @@ -127,7 +127,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@ContentChild('test', { static: false }) query: any;`); }); - it('should not mark content queries used in "ngAfterContentInit" as static (BOM)', async() => { + it('should not mark content queries used in "ngAfterContentInit" as static (BOM)', async () => { writeFile('/index.ts', `\uFEFF import {Component, ContentChild} from '@angular/core'; @@ -147,7 +147,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@ContentChild('test', { static: false }) query: any;`); }); - it('should not mark content queries used in "ngAfterContentChecked" as static', async() => { + it('should not mark content queries used in "ngAfterContentChecked" as static', async () => { writeFile('/index.ts', ` import {Component, ContentChild} from '@angular/core'; @@ -176,8 +176,8 @@ describe('static-queries migration with usage strategy', () => { return runner.runSchematicAsync('migration-v8-static-queries', {}, tree).toPromise(); } - function createQueryTests(queryType: 'ViewChild' | 'ContentChild') { - it('should mark queries as dynamic', async() => { + function createQueryTests(queryType: 'ViewChild'|'ContentChild') { + it('should mark queries as dynamic', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -200,7 +200,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('dynamic', { static: false }) dynamic: any`); }); - it('should mark queries used in "ngOnChanges" as static', async() => { + it('should mark queries used in "ngOnChanges" as static', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -220,7 +220,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should mark queries used in "ngOnInit" as static', async() => { + it('should mark queries used in "ngOnInit" as static', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -240,7 +240,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should mark queries used in "ngDoCheck" as static', async() => { + it('should mark queries used in "ngDoCheck" as static', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -260,7 +260,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should keep existing query options when updating timing', async() => { + it('should keep existing query options when updating timing', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -280,7 +280,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { /* test */ read: null, static: true }) query: any;`); }); - it('should add a todo for queries declared on setter', async() => { + it('should add a todo for queries declared on setter', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -300,7 +300,7 @@ describe('static-queries migration with usage strategy', () => { .toMatch(/index.ts@6:11: Queries defined on accessors cannot be analyzed.$/); }); - it('should add a todo for queries declared on getter', async() => { + it('should add a todo for queries declared on getter', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -321,7 +321,7 @@ describe('static-queries migration with usage strategy', () => { .toMatch(/index.ts@6:11: Queries defined on accessors cannot be analyzed.$/); }); - it('should not overwrite existing explicit query timing', async() => { + it('should not overwrite existing explicit query timing', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -337,7 +337,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', {static: /* untouched */ someVal}) query: any;`); }); - it('should detect queries used in deep method chain', async() => { + it('should detect queries used in deep method chain', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -372,7 +372,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should properly exit if recursive function is analyzed', async() => { + it('should properly exit if recursive function is analyzed', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -396,7 +396,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) query: any;`); }); - it('should detect queries used in newly instantiated classes', async() => { + it('should detect queries used in newly instantiated classes', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -435,7 +435,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query2: any;`); }); - it('should detect queries used in parenthesized new expressions', async() => { + it('should detect queries used in parenthesized new expressions', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -461,7 +461,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect queries in lifecycle hook with string literal name', async() => { + it('should detect queries in lifecycle hook with string literal name', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -481,7 +481,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect static queries within nested inheritance', async() => { + it('should detect static queries within nested inheritance', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -506,7 +506,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect static queries used within input setters', async() => { + it('should detect static queries used within input setters', async () => { writeFile('/index.ts', ` import {Component, Input, ${queryType}} from '@angular/core'; @@ -528,7 +528,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect inputs defined in metadata', async() => { + it('should detect inputs defined in metadata', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -554,7 +554,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect aliased inputs declared in metadata', async() => { + it('should detect aliased inputs declared in metadata', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -577,7 +577,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should not mark query as static if query is used in non-input setter', async() => { + it('should not mark query as static if query is used in non-input setter', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -597,7 +597,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) query: any;`); }); - it('should detect input decorator on setter', async() => { + it('should detect input decorator on setter', async () => { writeFile('/index.ts', ` import {Input, Component, ${queryType}} from '@angular/core'; @@ -622,7 +622,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect setter inputs in derived classes', async() => { + it('should detect setter inputs in derived classes', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -647,7 +647,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should properly detect static query in external derived class', async() => { + it('should properly detect static query in external derived class', async () => { writeFile('/src/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -680,7 +680,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should not mark queries used in promises as static', async() => { + it('should not mark queries used in promises as static', async () => { writeFile('/es2015.dom.d.ts', ` interface PromiseConstructor { resolve(): Promise; @@ -735,7 +735,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query2: any;`); }); - it('should handle function callbacks which statically access queries', async() => { + it('should handle function callbacks which statically access queries', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -764,7 +764,7 @@ describe('static-queries migration with usage strategy', () => { }); it('should handle class instantiations with specified callbacks that access queries', - async() => { + async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; import {External} from './external'; @@ -794,7 +794,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should handle nested functions with arguments from parent closure', async() => { + it('should handle nested functions with arguments from parent closure', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -823,7 +823,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should not mark queries used in setTimeout as static', async() => { + it('should not mark queries used in setTimeout as static', async () => { writeFile('/lib.dom.d.ts', `declare function setTimeout(cb: Function);`); writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -859,7 +859,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) query3: any;`); }); - it('should not mark queries used in "addEventListener" as static', async() => { + it('should not mark queries used in "addEventListener" as static', async () => { writeFile('/lib.dom.d.ts', ` interface HTMLElement { addEventListener(cb: Function); @@ -888,7 +888,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) query: any;`); }); - it('should not mark queries used in "requestAnimationFrame" as static', async() => { + it('should not mark queries used in "requestAnimationFrame" as static', async () => { writeFile('/lib.dom.d.ts', `declare function requestAnimationFrame(cb: Function);`); writeFile('/index.ts', ` import {Component, ElementRef, ${queryType}} from '@angular/core'; @@ -913,8 +913,9 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) query: any;`); }); - it('should mark queries used in immediately-invoked function expression as static', async() => { - writeFile('/index.ts', ` + it('should mark queries used in immediately-invoked function expression as static', + async () => { + writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @Component({template: ''}) @@ -934,15 +935,15 @@ describe('static-queries migration with usage strategy', () => { } `); - await runMigration(); + await runMigration(); - expect(tree.readContent('/index.ts')) - .toContain(`@${queryType}('test', { static: true }) query: any;`); - expect(tree.readContent('/index.ts')) - .toContain(`@${queryType}('test', { static: true }) query2: any;`); - }); + expect(tree.readContent('/index.ts')) + .toContain(`@${queryType}('test', { static: true }) query: any;`); + expect(tree.readContent('/index.ts')) + .toContain(`@${queryType}('test', { static: true }) query2: any;`); + }); - it('should detect static queries used in external function-like declaration', async() => { + it('should detect static queries used in external function-like declaration', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; import {externalFn} from './external'; @@ -971,7 +972,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect static queries used through getter property access', async() => { + it('should detect static queries used through getter property access', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -995,7 +996,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect static queries used through external getter access', async() => { + it('should detect static queries used through external getter access', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; import {External} from './external'; @@ -1033,8 +1034,9 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should not mark queries as static if a value is assigned to accessor property', async() => { - writeFile('/index.ts', ` + it('should not mark queries as static if a value is assigned to accessor property', + async () => { + writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @Component({template: ''}) @@ -1052,13 +1054,13 @@ describe('static-queries migration with usage strategy', () => { } `); - await runMigration(); + await runMigration(); - expect(tree.readContent('/index.ts')) - .toContain(`@${queryType}('test', { static: false }) query: any;`); - }); + expect(tree.readContent('/index.ts')) + .toContain(`@${queryType}('test', { static: false }) query: any;`); + }); - it('should mark queries as static if non-input setter uses query', async() => { + it('should mark queries as static if non-input setter uses query', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1083,7 +1085,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should check setter and getter when using compound assignment', async() => { + it('should check setter and getter when using compound assignment', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1111,7 +1113,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query2: any;`); }); - it('should check getters when using comparison operator in binary expression', async() => { + it('should check getters when using comparison operator in binary expression', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1136,7 +1138,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should check derived abstract class methods', async() => { + it('should check derived abstract class methods', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1172,7 +1174,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect queries accessed through deep abstract class method', async() => { + it('should detect queries accessed through deep abstract class method', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1204,7 +1206,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect queries accessed through abstract property getter', async() => { + it('should detect queries accessed through abstract property getter', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1230,7 +1232,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect queries accessed through abstract property setter', async() => { + it('should detect queries accessed through abstract property setter', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1257,8 +1259,9 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect query usage in abstract class methods accessing inherited query', async() => { - writeFile('/index.ts', ` + it('should detect query usage in abstract class methods accessing inherited query', + async () => { + writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; export abstract class RootBaseClass { @@ -1287,13 +1290,13 @@ describe('static-queries migration with usage strategy', () => { } `); - await runMigration(); + await runMigration(); - expect(tree.readContent('/index.ts')) - .toContain(`@${queryType}('test', { static: true }) query: any;`); - }); + expect(tree.readContent('/index.ts')) + .toContain(`@${queryType}('test', { static: true }) query: any;`); + }); - it('should detect query usage within component template', async() => { + it('should detect query usage within component template', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1314,8 +1317,9 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: true }) query: any;`); }); - it('should detect query usage with nested property read within component template', async() => { - writeFile('/index.ts', ` + it('should detect query usage with nested property read within component template', + async () => { + writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @Component({templateUrl: 'my-template.html'}) @@ -1324,19 +1328,19 @@ describe('static-queries migration with usage strategy', () => { } `); - writeFile(`/my-template.html`, ` + writeFile(`/my-template.html`, ` `); - await runMigration(); + await runMigration(); - expect(tree.readContent('/index.ts')) - .toContain(`@${queryType}('test', { static: true }) query: any;`); - }); + expect(tree.readContent('/index.ts')) + .toContain(`@${queryType}('test', { static: true }) query: any;`); + }); it('should not mark query as static if template has template reference with same name', - async() => { + async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1360,7 +1364,7 @@ describe('static-queries migration with usage strategy', () => { }); it('should not mark query as static if template has property read with query name but different receiver', - async() => { + async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1385,7 +1389,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) someProp: any;`); }); - it('should ignore queries accessed within element', async() => { + it('should ignore queries accessed within element', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1409,7 +1413,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) query: any;`); }); - it('should detect inherited queries used in templates', async() => { + it('should detect inherited queries used in templates', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1433,7 +1437,7 @@ describe('static-queries migration with usage strategy', () => { }); it('should mark queries which could be accessed statically within third-party calls as ambiguous', - async() => { + async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; import {thirdPartySync} from 'my-lib'; @@ -1458,18 +1462,18 @@ describe('static-queries migration with usage strategy', () => { await runMigration(); expect(tree.readContent('/index.ts')) - .toContain( - `@${queryType}('test', /* TODO: check static flag */ { static: true }) query: any;`); + .toContain(`@${ + queryType}('test', /* TODO: check static flag */ { static: true }) query: any;`); expect(tree.readContent('/index.ts')) - .toContain( - `@${queryType}('test', /* TODO: check static flag */ { static: true }) query2: any;`); + .toContain(`@${ + queryType}('test', /* TODO: check static flag */ { static: true }) query2: any;`); expect(warnOutput.length).toBe(2); expect(warnOutput[0]).toContain('Query timing is ambiguous.'); expect(warnOutput[1]).toContain('Query timing is ambiguous.'); }); it('should mark queries which could be accessed statically within third-party new expressions as ambiguous', - async() => { + async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; import {ThirdParty} from 'my-lib'; @@ -1493,15 +1497,15 @@ describe('static-queries migration with usage strategy', () => { await runMigration(); expect(tree.readContent('/index.ts')) - .toContain( - `@${queryType}('test', /* TODO: check static flag */ { static: true }) query: any;`); + .toContain(`@${ + queryType}('test', /* TODO: check static flag */ { static: true }) query: any;`); expect(warnOutput.length).toBe(1); expect(warnOutput[0]) .toContain( 'Query timing is ambiguous. Please check if the query can be marked as dynamic'); }); - it('should properly handle multiple tsconfig files', async() => { + it('should properly handle multiple tsconfig files', async () => { writeFile('/src/index.ts', ` import {Component, ${queryType}} from '@angular/core'; @@ -1526,7 +1530,7 @@ describe('static-queries migration with usage strategy', () => { .toContain(`@${queryType}('test', { static: false }) query: any;`); }); - it('should support function call with default parameter value', async() => { + it('should support function call with default parameter value', async () => { writeFile('/index.ts', ` import {Component, ${queryType}} from '@angular/core'; diff --git a/packages/core/schematics/test/template_var_assignment_migration_spec.ts b/packages/core/schematics/test/template_var_assignment_migration_spec.ts index a7d0f30e86c38..54a97867e384b 100644 --- a/packages/core/schematics/test/template_var_assignment_migration_spec.ts +++ b/packages/core/schematics/test/template_var_assignment_migration_spec.ts @@ -62,7 +62,7 @@ describe('template variable assignment migration', () => { return runner.runSchematicAsync('migration-v8-template-local-variables', {}, tree).toPromise(); } - it('should warn for two-way data binding variable assignment', async() => { + it('should warn for two-way data binding variable assignment', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -78,7 +78,7 @@ describe('template variable assignment migration', () => { expect(warnOutput[0]).toMatch(/^⮑ {3}index.ts@5:69: Found assignment/); }); - it('should warn for two-way data binding assigning to "as" variable', async() => { + it('should warn for two-way data binding assigning to "as" variable', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -100,7 +100,7 @@ describe('template variable assignment migration', () => { expect(warnOutput).toMatch(/^⮑ {3}tmpl.html@3:31: Found assignment/); }); - it('should warn for bound event assignments to "as" variable', async() => { + it('should warn for bound event assignments to "as" variable', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -124,7 +124,7 @@ describe('template variable assignment migration', () => { expect(warnOutput[1]).toMatch(/^⮑ {3}sub_dir\/tmpl.html@4:25: Found assignment/); }); - it('should warn for bound event assignments to template "let" variables', async() => { + it('should warn for bound event assignments to template "let" variables', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -148,7 +148,7 @@ describe('template variable assignment migration', () => { expect(warnOutput[1]).toMatch(/^⮑ {3}sub_dir\/tmpl.html@4:25: Found assignment/); }); - it('should not warn for bound event assignments to component property', async() => { + it('should not warn for bound event assignments to component property', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -166,7 +166,7 @@ describe('template variable assignment migration', () => { }); it('should not warn for bound event assignments to template variable object property', - async() => { + async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -186,7 +186,7 @@ describe('template variable assignment migration', () => { }); it('should not warn for property writes with template variable name but different receiver', - async() => { + async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -211,7 +211,7 @@ describe('template variable assignment migration', () => { expect(warnOutput.length).toBe(0); }); - it('should warn for template variable assignments in expression conditional', async() => { + it('should warn for template variable assignments in expression conditional', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -236,7 +236,7 @@ describe('template variable assignment migration', () => { }); it('should not warn for property writes with template variable name but different scope', - async() => { + async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -259,7 +259,7 @@ describe('template variable assignment migration', () => { }); - it('should not throw an error if a detected template fails parsing', async() => { + it('should not throw an error if a detected template fails parsing', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @@ -276,7 +276,7 @@ describe('template variable assignment migration', () => { expect(warnOutput.length).toBe(0); }); - it('should be able to report multiple templates within the same source file', async() => { + it('should be able to report multiple templates within the same source file', async () => { writeFile('/index.ts', ` import {Component} from '@angular/core'; diff --git a/packages/core/schematics/test/undecorated_classes_with_di_migration_spec.ts b/packages/core/schematics/test/undecorated_classes_with_di_migration_spec.ts index 997dca5b52112..c67771226167e 100644 --- a/packages/core/schematics/test/undecorated_classes_with_di_migration_spec.ts +++ b/packages/core/schematics/test/undecorated_classes_with_di_migration_spec.ts @@ -83,7 +83,7 @@ describe('Undecorated classes with DI migration', () => { `); } - it('should print a failure message base class is declared through type definition', async() => { + it('should print a failure message base class is declared through type definition', async () => { writeFile('/node_modules/my-lib/package.json', JSON.stringify({ version: '0.0.0', main: './index.js', @@ -121,7 +121,7 @@ describe('Undecorated classes with DI migration', () => { 'dependency injection. Please manually fix the following failures'); }); - it('should add @Directive() decorator to extended base class', async() => { + it('should add @Directive() decorator to extended base class', async () => { writeFile('/index.ts', ` import {Component, NgModule, NgZone} from '@angular/core'; @@ -149,8 +149,8 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')).toMatch(/@Directive\(\)\nexport class BaseClass2 {/); }); - it('not decorated base class multiple times if extended multiple times', async() => { - writeFile('/index.ts', dedent ` + it('not decorated base class multiple times if extended multiple times', async () => { + writeFile('/index.ts', dedent` import {Component, NgModule, NgZone} from '@angular/core'; export class BaseClass { @@ -169,7 +169,7 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Directive() export class BaseClass { @@ -177,7 +177,7 @@ describe('Undecorated classes with DI migration', () => { }`); }); - it('should add @Injectable() decorator to extended base class', async() => { + it('should add @Injectable() decorator to extended base class', async () => { writeFile('/index.ts', ` import {Injectable, NgModule, NgZone} from '@angular/core'; @@ -197,8 +197,8 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')).toMatch(/@Injectable\(\)\nexport class BaseClass {/); }); - it('should not decorate base class for decorated pipe', async() => { - writeFile('/index.ts', dedent ` + it('should not decorate base class for decorated pipe', async () => { + writeFile('/index.ts', dedent` import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'test'}) @@ -213,13 +213,13 @@ describe('Undecorated classes with DI migration', () => { expect(errorOutput.length).toBe(0); expect(warnOutput.length).toBe(0); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Pipe({name: 'test'}) export class MyPipe extends PipeTransform {}`); }); - it('should not decorate base class if no constructor is inherited', async() => { - writeFile('/index.ts', dedent ` + it('should not decorate base class if no constructor is inherited', async () => { + writeFile('/index.ts', dedent` import {Component, NgModule, Directive} from '@angular/core'; export class BaseClassWithoutCtor { @@ -238,7 +238,7 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` export class BaseClassWithoutCtor { someUnrelatedProp = true; @@ -252,8 +252,8 @@ describe('Undecorated classes with DI migration', () => { }); it('should not decorate base class if directive/component/provider defines a constructor', - async() => { - writeFile('/index.ts', dedent ` + async () => { + writeFile('/index.ts', dedent` import {Component, Injectable, NgModule, NgZone} from '@angular/core'; export class BaseClass { @@ -284,15 +284,15 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` export class BaseClass { constructor(zone: NgZone) {} }`); }); - it('should not decorate base class if it already has decorator', async() => { - writeFile('/index.ts', dedent ` + it('should not decorate base class if it already has decorator', async () => { + writeFile('/index.ts', dedent` import {Component, Directive, NgModule, NgZone} from '@angular/core'; @Directive({selector: 'base-class'}) @@ -312,13 +312,13 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Directive({selector: 'base-class'}) export class BaseClass {`); }); - it('should add a comment if the base class is declared through type definition', async() => { + it('should add a comment if the base class is declared through type definition', async () => { writeFile('/node_modules/my-lib/package.json', JSON.stringify({ version: '0.0.0', main: './index.js', @@ -332,7 +332,7 @@ describe('Undecorated classes with DI migration', () => { } `); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {Component, Injectable, NgModule} from '@angular/core'; import {SuperBaseClass} from 'my-lib'; @@ -365,42 +365,42 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Directive() export class BaseClass extends SuperBaseClass { // TODO: add explicit constructor }`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Injectable() export class BaseClass2 extends SuperBaseClass { // TODO: add explicit constructor }`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Directive() export class PassThroughClass extends BaseClass {}`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({template: ''}) export class MyComponent extends PassThroughClass {}`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({template: ''}) export class MyComponent3 extends SuperBaseClass { // TODO: add explicit constructor }`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Injectable() export class MyService extends BaseClass2 {}`); }); it('should not add a comment if the base class is declared through type definition but is' + 'decorated', - async() => { + async () => { writeFakeLibrary(); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {Component, NgModule} from '@angular/core'; import {BaseComponent} from 'my-lib'; @@ -413,14 +413,14 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({template: ''}) export class MyComponent extends BaseComponent {}`); }); - it('should not decorate base class in typings if it misses an explicit constructor', async() => { + it('should not decorate base class in typings if it misses an explicit constructor', async () => { writeFakeLibrary(); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {Component, NgModule} from '@angular/core'; import {BaseDirective} from 'my-lib'; @@ -433,16 +433,16 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({template: ''}) export class MyComponent extends BaseDirective {}`); expect(tree.readContent('/node_modules/my-lib/public-api.d.ts')).not.toContain('@Directive'); }); - it('should detect decorated classes by respecting summary files', async() => { + it('should detect decorated classes by respecting summary files', async () => { writeSummaryOnlyThirdPartyLibrary(); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {Component, NgModule} from '@angular/core'; import {BaseComponent} from 'my-lib'; @@ -457,12 +457,12 @@ describe('Undecorated classes with DI migration', () => { expect(warnOutput.length).toBe(0); expect(errorOutput.length).toBe(0); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({template: ''}) export class MyComponent extends BaseComponent {}`); }); - it('should decorate all undecorated directives of inheritance chain', async() => { + it('should decorate all undecorated directives of inheritance chain', async () => { writeFile('/index.ts', ` import {Component, NgModule, NgZone} from '@angular/core'; @@ -486,7 +486,7 @@ describe('Undecorated classes with DI migration', () => { .toMatch(/}\s+@Directive\(\)\nexport class BaseClass extends SuperBaseClass {/); }); - it('should decorate all undecorated providers of inheritance chain', async() => { + it('should decorate all undecorated providers of inheritance chain', async () => { writeFile('/index.ts', ` import {Injectable, NgModule, NgZone} from '@angular/core'; @@ -511,7 +511,7 @@ describe('Undecorated classes with DI migration', () => { }); it('should properly update import if @Directive can be accessed through existing namespace import', - async() => { + async () => { writeFile('/index.ts', ` import {Component, NgModule, NgZone} from '@angular/core'; import {BaseClass} from './base'; @@ -537,7 +537,7 @@ describe('Undecorated classes with DI migration', () => { }); it('should properly update existing import with aliased specifier if identifier is already used', - async() => { + async () => { writeFile('/index.ts', ` import {Component, NgModule, NgZone} from '@angular/core'; import {Directive} from './third_party_directive'; @@ -561,7 +561,7 @@ describe('Undecorated classes with DI migration', () => { }); it('should properly create new import with aliased specifier if identifier is already used', - async() => { + async () => { writeFile('/index.ts', ` import {Component, NgModule, NgZone} from '@angular/core'; import {BaseClass} from './base'; @@ -590,8 +590,9 @@ describe('Undecorated classes with DI migration', () => { .toContain(`{ Directive as Directive_1 } from "@angular/core";`); }); - it('should use existing aliased import of @Directive instead of creating new import', async() => { - writeFile('/index.ts', ` + it('should use existing aliased import of @Directive instead of creating new import', + async () => { + writeFile('/index.ts', ` import {Component, NgModule} from '@angular/core'; import {BaseClass} from './base'; @@ -602,7 +603,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/base.ts', ` + writeFile('/base.ts', ` import {Directive as AliasedDir, NgZone} from '@angular/core'; export class BaseClass { @@ -610,15 +611,14 @@ describe('Undecorated classes with DI migration', () => { } `); - await runMigration(); - - expect(tree.readContent('/base.ts')).toMatch(/@AliasedDir\(\)\nexport class BaseClass {/); - }); + await runMigration(); - describe('decorator copying', async() => { + expect(tree.readContent('/base.ts')).toMatch(/@AliasedDir\(\)\nexport class BaseClass {/); + }); - it('should be able to copy the "templateUrl" field', async() => { - writeFile('/index.ts', dedent ` + describe('decorator copying', async () => { + it('should be able to copy the "templateUrl" field', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -628,7 +628,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Directive, NgModule} from '@angular/core'; @Directive({ @@ -645,7 +645,7 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')) .toContain(`import { NgModule, Directive } from '@angular/core';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Directive({ selector: 'my-dir', templateUrl: './my-dir.html' @@ -653,8 +653,8 @@ describe('Undecorated classes with DI migration', () => { export class MyDir extends BaseClass {}`); }); - it('should be able to copy the "styleUrls" field', async() => { - writeFile('/index.ts', dedent ` + it('should be able to copy the "styleUrls" field', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -664,7 +664,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Directive, NgModule} from '@angular/core'; /** my comment */ @@ -680,7 +680,7 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` import {BaseClass} from './lib/base'; @Directive({ @@ -690,8 +690,8 @@ describe('Undecorated classes with DI migration', () => { export class MyDir extends BaseClass {}`); }); - it('should be able to copy @Pipe decorator', async() => { - writeFile('/index.ts', dedent ` + it('should be able to copy @Pipe decorator', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BasePipe} from './lib/base'; @@ -701,7 +701,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Pipe, NgModule} from '@angular/core'; @Pipe({name: 'my-pipe-name'}) @@ -715,16 +715,16 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')) .toContain(`import { NgModule, Pipe } from '@angular/core';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Pipe({ name: 'my-pipe-name' }) export class MyPipe extends BasePipe {}`); }); - it('should be able to copy decorator in same source file', async() => { + it('should be able to copy decorator in same source file', async () => { writeFile( '/node_modules/@angular/cdk/table/index.d.ts', `export declare const CDK_TABLE_TEMPLATE = '';`); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {NgModule, Component} from '@angular/core'; import {CDK_TABLE_TEMPLATE} from '@angular/cdk/table'; @@ -748,7 +748,7 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ selector: 'my-dir', template: CDK_TABLE_TEMPLATE, @@ -757,8 +757,8 @@ describe('Undecorated classes with DI migration', () => { export class MyDir extends BaseClass {}`); }); - it('should be able to create new imports for copied identifier references', async() => { - writeFile('/index.ts', dedent ` + it('should be able to create new imports for copied identifier references', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -772,7 +772,7 @@ describe('Undecorated classes with DI migration', () => { '/node_modules/@angular/cdk/table/index.d.ts', `export declare const CDK_TABLE_TEMPLATE = '';`); writeFile('/styles.ts', `export const STYLE_THROUGH_VAR = 'external';`); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Component, NgModule} from '@angular/core'; import {CDK_TABLE_TEMPLATE as tableTmpl} from '@angular/cdk/table'; import {STYLE_THROUGH_VAR} from '../styles'; @@ -798,7 +798,7 @@ describe('Undecorated classes with DI migration', () => { .toContain(`import { STYLE_THROUGH_VAR } from "./styles";`); expect(tree.readContent('/index.ts')) .toContain(`import { BaseClass, LOCAL_STYLE } from './lib/base';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ selector: 'my-dir', template: CDK_TABLE_TEMPLATE, @@ -807,8 +807,8 @@ describe('Undecorated classes with DI migration', () => { export class MyDir extends BaseClass {}`); }); - it('should copy decorator once if directive is referenced multiple times', async() => { - writeFile('/index.ts', dedent ` + it('should copy decorator once if directive is referenced multiple times', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -818,7 +818,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/second-module.ts', dedent ` + writeFile('/second-module.ts', dedent` import {NgModule, Directive} from '@angular/core'; import {MyComp} from './index'; @@ -829,7 +829,7 @@ describe('Undecorated classes with DI migration', () => { export class MySecondModule {} `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Component, NgModule} from '@angular/core'; @Component({ @@ -844,7 +844,7 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` import {BaseClass} from './lib/base'; @Component({ @@ -854,8 +854,8 @@ describe('Undecorated classes with DI migration', () => { export class MyComp extends BaseClass {}`); }); - it('should create aliased imports to avoid collisions for referenced identifiers', async() => { - writeFile('/index.ts', dedent ` + it('should create aliased imports to avoid collisions for referenced identifiers', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -869,7 +869,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Component, NgModule} from '@angular/core'; export const MY_TEMPLATE = ''; @@ -888,7 +888,7 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')) .toContain(`import { BaseClass, MY_TEMPLATE as MY_TEMPLATE_1 } from './lib/base';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ selector: 'my-dir', template: MY_TEMPLATE_1 @@ -896,8 +896,8 @@ describe('Undecorated classes with DI migration', () => { export class MyComp extends BaseClass {}`); }); - it('should add comment for metadata fields which cannot be copied', async() => { - writeFile('/index.ts', dedent ` + it('should add comment for metadata fields which cannot be copied', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -907,7 +907,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Component, NgModule, Document} from '@angular/core'; // this variable cannot be imported automatically. @@ -926,7 +926,7 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ selector: 'my-dir', template: '', @@ -940,8 +940,8 @@ describe('Undecorated classes with DI migration', () => { }); it('should add comment for metadata fields which are added through spread operator', - async() => { - writeFile('/index.ts', dedent ` + async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -951,7 +951,7 @@ describe('Undecorated classes with DI migration', () => { export class MyModule {} `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Component, NgModule} from '@angular/core'; export const metadataThroughVar = { @@ -971,7 +971,7 @@ describe('Undecorated classes with DI migration', () => { await runMigration(); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ selector: 'my-dir', template: '', @@ -984,10 +984,10 @@ describe('Undecorated classes with DI migration', () => { export class MyComp extends BaseClass {}`); }); - it('should be able to copy fields specified through shorthand assignment', async() => { + it('should be able to copy fields specified through shorthand assignment', async () => { writeFile('/hello.css', ''); writeFile('/my-tmpl.html', ''); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -999,7 +999,7 @@ describe('Undecorated classes with DI migration', () => { writeFile('/lib/hello.css', ''); writeFile('/lib/my-tmpl.html', ''); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Component, NgModule} from '@angular/core'; export const host = {}; @@ -1022,7 +1022,7 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')) .toContain(`import { BaseClass, templateUrl, host } from './lib/base';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ selector: 'my-dir', templateUrl, @@ -1036,10 +1036,10 @@ describe('Undecorated classes with DI migration', () => { export class MyComp extends BaseClass {}`); }); - it('should serialize metadata from base class without source code', async() => { + it('should serialize metadata from base class without source code', async () => { writeFakeLibrary(); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseComponent, BasePipe} from 'my-lib'; @@ -1061,7 +1061,7 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')) .toContain( `import { NgModule, ChangeDetectionStrategy, ViewEncapsulation, NG_VALIDATORS, Component, Pipe } from '@angular/core';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ changeDetection: ChangeDetectionStrategy.Default, selector: "comp-selector", @@ -1077,7 +1077,7 @@ describe('Undecorated classes with DI migration', () => { } }) export class PassThrough extends BaseComponent {}`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ changeDetection: ChangeDetectionStrategy.Default, selector: "comp-selector", @@ -1093,7 +1093,7 @@ describe('Undecorated classes with DI migration', () => { } }) export class MyComp extends PassThrough {}`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Pipe({ pure: true, name: "external-pipe-name" @@ -1101,12 +1101,12 @@ describe('Undecorated classes with DI migration', () => { export class MyPipe extends BasePipe {}`); }); - it('should serialize metadata with external references from class without source code', async() => { + it('should serialize metadata with external references from class without source code', async () => { writeFakeLibrary({useImportedTemplate: true}); writeFile( '/node_modules/@angular/cdk/table/index.d.ts', `export declare const CDK_TABLE_TEMPLATE = 'Template of CDK Table.';`); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseComponent} from 'my-lib'; @@ -1121,7 +1121,7 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')) .toContain( `import { NgModule, ChangeDetectionStrategy, ViewEncapsulation, NG_VALIDATORS, Component } from '@angular/core';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Component({ changeDetection: ChangeDetectionStrategy.Default, selector: "comp-selector", @@ -1140,10 +1140,10 @@ describe('Undecorated classes with DI migration', () => { }); it('should not throw if metadata from base class without source code is not serializable', - async() => { + async () => { writeFakeLibrary({insertInvalidReference: true}); - writeFile('/index.ts', dedent ` + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseComponent} from 'my-lib'; @@ -1159,8 +1159,8 @@ describe('Undecorated classes with DI migration', () => { expect(errorOutput[0]).toMatch(/Could not resolve non-existent/); }); - it('should not create imports for identifiers resolving to target source file', async() => { - writeFile('/index.ts', dedent ` + it('should not create imports for identifiers resolving to target source file', async () => { + writeFile('/index.ts', dedent` import {NgModule} from '@angular/core'; import {BaseClass} from './lib/base'; @@ -1175,7 +1175,7 @@ describe('Undecorated classes with DI migration', () => { export {LOCAL_NAME as PUBLIC_NAME}; `); - writeFile('/lib/base.ts', dedent ` + writeFile('/lib/base.ts', dedent` import {Directive, NgModule} from '@angular/core'; import {SHARED_TEMPLATE_URL, PUBLIC_NAME} from '..'; @@ -1194,7 +1194,7 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/index.ts')) .toContain(`import { NgModule, Directive } from '@angular/core';`); - expect(tree.readContent('/index.ts')).toContain(dedent ` + expect(tree.readContent('/index.ts')).toContain(dedent` @Directive({ selector: 'my-dir', template: SHARED_TEMPLATE_URL, @@ -1388,7 +1388,7 @@ describe('Undecorated classes with DI migration', () => { })); } - it('should not run for test tsconfig files', async() => { + it('should not run for test tsconfig files', async () => { writeFile('/src/tsconfig.spec.json', JSON.stringify({ compilerOptions: { lib: ['es2015'], @@ -1429,8 +1429,8 @@ describe('Undecorated classes with DI migration', () => { expect(errorOutput.length).toBe(0); }); - describe('diagnostics', async() => { - it('should gracefully exit migration if project fails with structural diagnostic', async() => { + describe('diagnostics', async () => { + it('should gracefully exit migration if project fails with structural diagnostic', async () => { writeFile('/index.ts', ` import {Component, NgModule} from '@angular/core'; @@ -1455,28 +1455,29 @@ describe('Undecorated classes with DI migration', () => { 'TypeScript program failures'); }); - it('should gracefully exit migration if project fails with syntactical diagnostic', async() => { - writeFile('/index.ts', ` + it('should gracefully exit migration if project fails with syntactical diagnostic', + async () => { + writeFile('/index.ts', ` import {Component, NgModule} /* missing "from" */ '@angular/core'; `); - await runMigration(); + await runMigration(); - expect(warnOutput.length).toBe(1); - expect(warnOutput[0]) - .toMatch(/project "tsconfig.json" has syntactical errors which could cause/); - expect(errorOutput.length).toBe(1); - expect(errorOutput[0]).toMatch(/error TS1005: 'from' expected/); - expect(infoOutput.join(' ')) - .toContain( - 'Some project targets could not be analyzed due to ' + - 'TypeScript program failures'); - }); + expect(warnOutput.length).toBe(1); + expect(warnOutput[0]) + .toMatch(/project "tsconfig.json" has syntactical errors which could cause/); + expect(errorOutput.length).toBe(1); + expect(errorOutput[0]).toMatch(/error TS1005: 'from' expected/); + expect(infoOutput.join(' ')) + .toContain( + 'Some project targets could not be analyzed due to ' + + 'TypeScript program failures'); + }); // Regression test for: https://github.com/angular/angular/issues/34985. it('should be able to migrate libraries with multiple source files and flat-module ' + 'options set', - async() => { + async () => { writeFile('/tsconfig.json', JSON.stringify({ compilerOptions: { lib: ['es2015'], @@ -1507,7 +1508,7 @@ describe('Undecorated classes with DI migration', () => { expect(tree.readContent('/test.ts')).toMatch(/@Injectable\(\)\nexport class BaseClass {/); }); - it('should not throw if resources could not be read', async() => { + it('should not throw if resources could not be read', async () => { writeFile('/index.ts', ` import {Component, NgModule} from '@angular/core'; @@ -1529,7 +1530,7 @@ describe('Undecorated classes with DI migration', () => { expect(errorOutput.length).toBe(0); }); - it('should not throw if tsconfig references non-existent source file', async() => { + it('should not throw if tsconfig references non-existent source file', async () => { writeFile('/tsconfig.json', JSON.stringify({ compilerOptions: { lib: ['es2015'], diff --git a/packages/core/schematics/utils/import_manager.ts b/packages/core/schematics/utils/import_manager.ts index 12a9b6cbcc33b..07b7f945f9ae1 100644 --- a/packages/core/schematics/utils/import_manager.ts +++ b/packages/core/schematics/utils/import_manager.ts @@ -114,8 +114,8 @@ export class ImportManager { } if (existingImport) { - const propertyIdentifier = ts.createIdentifier(symbolName !); - const generatedUniqueIdentifier = this._getUniqueIdentifier(sourceFile, symbolName !); + const propertyIdentifier = ts.createIdentifier(symbolName!); + const generatedUniqueIdentifier = this._getUniqueIdentifier(sourceFile, symbolName!); const needsGeneratedUniqueName = generatedUniqueIdentifier.text !== symbolName; const importName = needsGeneratedUniqueName ? generatedUniqueIdentifier : propertyIdentifier; @@ -186,7 +186,7 @@ export class ImportManager { this.updatedImports.forEach((expressions, importDecl) => { const sourceFile = importDecl.getSourceFile(); const recorder = this.getUpdateRecorder(sourceFile); - const namedBindings = importDecl.importClause !.namedBindings as ts.NamedImports; + const namedBindings = importDecl.importClause!.namedBindings as ts.NamedImports; const newNamedBindings = ts.updateNamedImports( namedBindings, namedBindings.elements.concat(expressions.map( @@ -211,8 +211,8 @@ export class ImportManager { name = `${baseName}_${counter++}`; } while (!this.isUniqueIdentifierName(sourceFile, name)); - this._recordUsedIdentifier(sourceFile, name !); - return ts.createIdentifier(name !); + this._recordUsedIdentifier(sourceFile, name!); + return ts.createIdentifier(name!); } /** @@ -221,7 +221,7 @@ export class ImportManager { */ private isUniqueIdentifierName(sourceFile: ts.SourceFile, name: string) { if (this.usedIdentifierNames.has(sourceFile) && - this.usedIdentifierNames.get(sourceFile) !.indexOf(name) !== -1) { + this.usedIdentifierNames.get(sourceFile)!.indexOf(name) !== -1) { return false; } @@ -230,7 +230,7 @@ export class ImportManager { // is unique in the given declaration scope and we just return false. const nodeQueue: ts.Node[] = [sourceFile]; while (nodeQueue.length) { - const node = nodeQueue.shift() !; + const node = nodeQueue.shift()!; if (ts.isIdentifier(node) && node.text === name) { return false; } @@ -254,6 +254,6 @@ export class ImportManager { if (!commentRanges || !commentRanges.length) { return nodeEndPos; } - return commentRanges[commentRanges.length - 1] !.end; + return commentRanges[commentRanges.length - 1]!.end; } } diff --git a/packages/core/schematics/utils/ng_component_template.ts b/packages/core/schematics/utils/ng_component_template.ts index 5b20b964cbcf0..01b1dfcb5e69b 100644 --- a/packages/core/schematics/utils/ng_component_template.ts +++ b/packages/core/schematics/utils/ng_component_template.ts @@ -31,7 +31,9 @@ export interface ResolvedTemplate { * If the template is declared inline within a TypeScript source file, the line and * character are based on the full source file content. */ - getCharacterAndLineOfPosition: (pos: number) => { character: number, line: number }; + getCharacterAndLineOfPosition: (pos: number) => { + character: number, line: number + }; } /** @@ -103,8 +105,8 @@ export class NgComponentTemplateVisitor { content: property.initializer.text, inline: true, start: templateStartIdx, - getCharacterAndLineOfPosition: - pos => ts.getLineAndCharacterOfPosition(sourceFile, pos + templateStartIdx) + getCharacterAndLineOfPosition: pos => + ts.getLineAndCharacterOfPosition(sourceFile, pos + templateStartIdx) }); } if (propertyName === 'templateUrl' && ts.isStringLiteralLike(property.initializer)) { diff --git a/packages/core/schematics/utils/ng_decorators.ts b/packages/core/schematics/utils/ng_decorators.ts index 4e2fadea1c6ff..54f53c0b5cc74 100644 --- a/packages/core/schematics/utils/ng_decorators.ts +++ b/packages/core/schematics/utils/ng_decorators.ts @@ -9,7 +9,7 @@ import * as ts from 'typescript'; import {getCallDecoratorImport} from './typescript/decorators'; -export type CallExpressionDecorator = ts.Decorator & { +export type CallExpressionDecorator = ts.Decorator&{ expression: ts.CallExpression; }; @@ -30,8 +30,8 @@ export function getAngularDecorators( .filter(({importData}) => importData && importData.importModule.startsWith('@angular/')) .map(({node, importData}) => ({ node: node as CallExpressionDecorator, - name: importData !.name, - moduleName: importData !.importModule, - importNode: importData !.node + name: importData!.name, + moduleName: importData!.importModule, + importNode: importData!.node })); } diff --git a/packages/core/schematics/utils/project_tsconfig_paths.ts b/packages/core/schematics/utils/project_tsconfig_paths.ts index 6690974fb0dd4..64153a36a5ef0 100644 --- a/packages/core/schematics/utils/project_tsconfig_paths.ts +++ b/packages/core/schematics/utils/project_tsconfig_paths.ts @@ -71,7 +71,7 @@ function getTargetTsconfigPath(project: WorkspaceProject, targetName: string): s */ function getWorkspaceConfigGracefully(tree: Tree): any { const path = defaultWorkspaceConfigPaths.find(filePath => tree.exists(filePath)); - const configBuffer = tree.read(path !); + const configBuffer = tree.read(path!); if (!path || !configBuffer) { return null; diff --git a/packages/core/schematics/utils/schematics_prompt.ts b/packages/core/schematics/utils/schematics_prompt.ts index 9fcfc92f489ef..f32d64d7af821 100644 --- a/packages/core/schematics/utils/schematics_prompt.ts +++ b/packages/core/schematics/utils/schematics_prompt.ts @@ -30,5 +30,5 @@ export function supportsPrompt(): boolean { * create prompts. */ export function getInquirer(): Inquirer { - return resolvedInquirerModule !; + return resolvedInquirerModule!; } diff --git a/packages/core/schematics/utils/typescript/decorators.ts b/packages/core/schematics/utils/typescript/decorators.ts index de1df266e892e..7722961300282 100644 --- a/packages/core/schematics/utils/typescript/decorators.ts +++ b/packages/core/schematics/utils/typescript/decorators.ts @@ -7,7 +7,8 @@ */ import * as ts from 'typescript'; -import {Import, getImportOfIdentifier} from './imports'; + +import {getImportOfIdentifier, Import} from './imports'; export function getCallDecoratorImport( typeChecker: ts.TypeChecker, decorator: ts.Decorator): Import|null { diff --git a/packages/core/schematics/utils/typescript/functions.ts b/packages/core/schematics/utils/typescript/functions.ts index b8cd376588795..07c105604ef82 100644 --- a/packages/core/schematics/utils/typescript/functions.ts +++ b/packages/core/schematics/utils/typescript/functions.ts @@ -20,7 +20,7 @@ export function isFunctionLikeDeclaration(node: ts.Node): node is ts.FunctionLik * parentheses or as expression. e.g. "(((({exp}))))()". The function should return the * TypeScript node referring to the inner expression. e.g "exp". */ -export function unwrapExpression(node: ts.Expression | ts.ParenthesizedExpression): ts.Expression { +export function unwrapExpression(node: ts.Expression|ts.ParenthesizedExpression): ts.Expression { if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node)) { return unwrapExpression(node.expression); } else { diff --git a/packages/core/src/application_init.ts b/packages/core/src/application_init.ts index b9852148c1889..69a77c8bc5681 100644 --- a/packages/core/src/application_init.ts +++ b/packages/core/src/application_init.ts @@ -34,9 +34,9 @@ export const APP_INITIALIZER = new InjectionToken void>>('Applicatio @Injectable() export class ApplicationInitStatus { // TODO(issue/24571): remove '!'. - private resolve !: Function; + private resolve!: Function; // TODO(issue/24571): remove '!'. - private reject !: Function; + private reject!: Function; private initialized = false; public readonly donePromise: Promise; public readonly done = false; @@ -57,7 +57,7 @@ export class ApplicationInitStatus { const asyncInitPromises: Promise[] = []; const complete = () => { - (this as{done: boolean}).done = true; + (this as {done: boolean}).done = true; this.resolve(); }; @@ -70,7 +70,13 @@ export class ApplicationInitStatus { } } - Promise.all(asyncInitPromises).then(() => { complete(); }).catch(e => { this.reject(e); }); + Promise.all(asyncInitPromises) + .then(() => { + complete(); + }) + .catch(e => { + this.reject(e); + }); if (asyncInitPromises.length === 0) { complete(); diff --git a/packages/core/src/application_module.ts b/packages/core/src/application_module.ts index f59eb86cd3fdd..de727bc81b798 100644 --- a/packages/core/src/application_module.ts +++ b/packages/core/src/application_module.ts @@ -9,7 +9,7 @@ import {APP_INITIALIZER, ApplicationInitStatus} from './application_init'; import {ApplicationRef} from './application_ref'; import {APP_ID_RANDOM_PROVIDER} from './application_tokens'; -import {IterableDiffers, KeyValueDiffers, defaultIterableDiffers, defaultKeyValueDiffers} from './change_detection/change_detection'; +import {defaultIterableDiffers, defaultKeyValueDiffers, IterableDiffers, KeyValueDiffers} from './change_detection/change_detection'; import {Console} from './console'; import {Injector, StaticProvider} from './di'; import {Inject, Optional, SkipSelf} from './di/metadata'; @@ -78,8 +78,7 @@ export const APPLICATION_MODULE_PROVIDERS: StaticProvider[] = [ { provide: ApplicationRef, useClass: ApplicationRef, - deps: - [NgZone, Console, Injector, ErrorHandler, ComponentFactoryResolver, ApplicationInitStatus] + deps: [NgZone, Console, Injector, ErrorHandler, ComponentFactoryResolver, ApplicationInitStatus] }, {provide: SCHEDULER, deps: [NgZone], useFactory: zoneSchedulerFactory}, { @@ -112,10 +111,12 @@ export function zoneSchedulerFactory(ngZone: NgZone): (fn: () => void) => void { let queue: (() => void)[] = []; ngZone.onStable.subscribe(() => { while (queue.length) { - queue.pop() !(); + queue.pop()!(); } }); - return function(fn: () => void) { queue.push(fn); }; + return function(fn: () => void) { + queue.push(fn); + }; } /** diff --git a/packages/core/src/application_ref.ts b/packages/core/src/application_ref.ts index 694f5763b3c50..1149dc0ffca45 100644 --- a/packages/core/src/application_ref.ts +++ b/packages/core/src/application_ref.ts @@ -8,7 +8,7 @@ import './util/ng_jit_mode'; -import {Observable, Observer, Subscription, merge} from 'rxjs'; +import {merge, Observable, Observer, Subscription} from 'rxjs'; import {share} from 'rxjs/operators'; import {ApplicationInitStatus} from './application_init'; @@ -80,7 +80,7 @@ export function compileNgModuleFactory__POST_R3__( return Promise.resolve(moduleFactory); } - const compilerProviders = _mergeArrays(compilerOptions.map(o => o.providers !)); + const compilerProviders = _mergeArrays(compilerOptions.map(o => o.providers!)); // In case there are no compiler providers, we just return the module factory as // there won't be any resource loader. This can happen with Ivy, because AOT compiled @@ -157,9 +157,8 @@ export function createPlatform(injector: Injector): PlatformRef { * @publicApi */ export function createPlatformFactory( - parentPlatformFactory: ((extraProviders?: StaticProvider[]) => PlatformRef) | null, - name: string, providers: StaticProvider[] = []): (extraProviders?: StaticProvider[]) => - PlatformRef { + parentPlatformFactory: ((extraProviders?: StaticProvider[]) => PlatformRef)|null, name: string, + providers: StaticProvider[] = []): (extraProviders?: StaticProvider[]) => PlatformRef { const desc = `Platform: ${name}`; const marker = new InjectionToken(desc); return (extraProviders: StaticProvider[] = []) => { @@ -320,10 +319,12 @@ export class PlatformRef { throw new Error('No ErrorHandler. Is platform module (BrowserModule) included?'); } moduleRef.onDestroy(() => remove(this._modules, moduleRef)); - ngZone !.runOutsideAngular( - () => ngZone !.onError.subscribe( - {next: (error: any) => { exceptionHandler.handleError(error); }})); - return _callAndReportToErrorHandler(exceptionHandler, ngZone !, () => { + ngZone!.runOutsideAngular(() => ngZone!.onError.subscribe({ + next: (error: any) => { + exceptionHandler.handleError(error); + } + })); + return _callAndReportToErrorHandler(exceptionHandler, ngZone!, () => { const initStatus: ApplicationInitStatus = moduleRef.injector.get(ApplicationInitStatus); initStatus.runInitializers(); return initStatus.donePromise.then(() => { @@ -356,7 +357,8 @@ export class PlatformRef { * */ bootstrapModule( - moduleType: Type, compilerOptions: (CompilerOptions&BootstrapOptions)| + moduleType: Type, + compilerOptions: (CompilerOptions&BootstrapOptions)| Array = []): Promise> { const options = optionsReducer({}, compilerOptions); return compileNgModuleFactory(this.injector, options, moduleType) @@ -371,7 +373,10 @@ export class PlatformRef { moduleRef.instance.ngDoBootstrap(appRef); } else { throw new Error( - `The module ${stringify(moduleRef.instance.constructor)} was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` + + `The module ${ + stringify( + moduleRef.instance + .constructor)} was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` + `Please define one of these.`); } this._modules.push(moduleRef); @@ -380,13 +385,17 @@ export class PlatformRef { /** * Register a listener to be called when the platform is disposed. */ - onDestroy(callback: () => void): void { this._destroyListeners.push(callback); } + onDestroy(callback: () => void): void { + this._destroyListeners.push(callback); + } /** * Retrieve the platform {@link Injector}, which is the parent injector for * every Angular application on the page and provides singleton providers. */ - get injector(): Injector { return this._injector; } + get injector(): Injector { + return this._injector; + } /** * Destroy the Angular platform and all Angular applications on the page. @@ -400,11 +409,13 @@ export class PlatformRef { this._destroyed = true; } - get destroyed() { return this._destroyed; } + get destroyed() { + return this._destroyed; + } } function getNgZone( - ngZoneOption: NgZone | 'zone.js' | 'noop' | undefined, ngZoneEventCoalescing: boolean): NgZone { + ngZoneOption: NgZone|'zone.js'|'noop'|undefined, ngZoneEventCoalescing: boolean): NgZone { let ngZone: NgZone; if (ngZoneOption === 'noop') { @@ -438,7 +449,7 @@ function _callAndReportToErrorHandler( } } -function optionsReducer(dst: any, objs: T | T[]): T { +function optionsReducer(dst: any, objs: T|T[]): T { if (Array.isArray(objs)) { dst = objs.reduce(optionsReducer, dst); } else { @@ -566,7 +577,7 @@ export class ApplicationRef { * @see [Usage notes](#is-stable-examples) for examples and caveats when using this API. */ // TODO(issue/24571): remove '!'. - public readonly isStable !: Observable; + public readonly isStable!: Observable; /** @internal */ constructor( @@ -576,8 +587,13 @@ export class ApplicationRef { private _initStatus: ApplicationInitStatus) { this._enforceNoNewChanges = isDevMode(); - this._zone.onMicrotaskEmpty.subscribe( - {next: () => { this._zone.run(() => { this.tick(); }); }}); + this._zone.onMicrotaskEmpty.subscribe({ + next: () => { + this._zone.run(() => { + this.tick(); + }); + } + }); const isCurrentlyStable = new Observable((observer: Observer) => { this._stable = this._zone.isStable && !this._zone.hasPendingMacrotasks && @@ -612,7 +628,9 @@ export class ApplicationRef { NgZone.assertInAngularZone(); if (this._stable) { this._stable = false; - this._zone.runOutsideAngular(() => { observer.next(false); }); + this._zone.runOutsideAngular(() => { + observer.next(false); + }); } }); @@ -622,7 +640,7 @@ export class ApplicationRef { }; }); - (this as{isStable: Observable}).isStable = + (this as {isStable: Observable}).isStable = merge(isCurrentlyStable, isStable.pipe(share())); } @@ -653,7 +671,7 @@ export class ApplicationRef { componentFactory = componentOrFactory; } else { componentFactory = - this._componentFactoryResolver.resolveComponentFactory(componentOrFactory) !; + this._componentFactoryResolver.resolveComponentFactory(componentOrFactory)!; } this.componentTypes.push(componentFactory.componentType); @@ -663,7 +681,9 @@ export class ApplicationRef { const selectorOrNode = rootSelectorOrNode || componentFactory.selector; const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule); - compRef.onDestroy(() => { this._unloadComponent(compRef); }); + compRef.onDestroy(() => { + this._unloadComponent(compRef); + }); const testability = compRef.injector.get(Testability, null); if (testability) { compRef.injector.get(TestabilityRegistry) @@ -755,7 +775,9 @@ export class ApplicationRef { /** * Returns the number of attached views. */ - get viewCount() { return this._views.length; } + get viewCount() { + return this._views.length; + } } function remove(list: T[], el: T): void { diff --git a/packages/core/src/change_detection/change_detection.ts b/packages/core/src/change_detection/change_detection.ts index 158bc238f9052..327beb1f6e875 100644 --- a/packages/core/src/change_detection/change_detection.ts +++ b/packages/core/src/change_detection/change_detection.ts @@ -11,26 +11,16 @@ import {DefaultKeyValueDifferFactory} from './differs/default_keyvalue_differ'; import {IterableDifferFactory, IterableDiffers} from './differs/iterable_differs'; import {KeyValueDifferFactory, KeyValueDiffers} from './differs/keyvalue_differs'; -export {WrappedValue, devModeEqual} from './change_detection_util'; +export {SimpleChange, SimpleChanges} from '../interface/simple_change'; +export {devModeEqual, WrappedValue} from './change_detection_util'; export {ChangeDetectorRef} from './change_detector_ref'; export {ChangeDetectionStrategy, ChangeDetectorStatus, isDefaultChangeDetectionStrategy} from './constants'; export {DefaultIterableDifferFactory} from './differs/default_iterable_differ'; export {DefaultIterableDiffer} from './differs/default_iterable_differ'; export {DefaultKeyValueDifferFactory} from './differs/default_keyvalue_differ'; -export { - CollectionChangeRecord, - IterableChangeRecord, - IterableChanges, - IterableDiffer, - IterableDifferFactory, - IterableDiffers, - NgIterable, - TrackByFunction -} from -'./differs/iterable_differs'; +export {CollectionChangeRecord, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDifferFactory, IterableDiffers, NgIterable, TrackByFunction} from './differs/iterable_differs'; export {KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDifferFactory, KeyValueDiffers} from './differs/keyvalue_differs'; export {PipeTransform} from './pipe_transform'; -export {SimpleChange, SimpleChanges} from '../interface/simple_change'; diff --git a/packages/core/src/change_detection/change_detection_util.ts b/packages/core/src/change_detection/change_detection_util.ts index b98a3756e751a..3d0ad85a4ab54 100644 --- a/packages/core/src/change_detection/change_detection_util.ts +++ b/packages/core/src/change_detection/change_detection_util.ts @@ -49,19 +49,27 @@ export class WrappedValue { /** @deprecated from 5.3, use `unwrap()` instead - will switch to protected */ wrapped: any; - constructor(value: any) { this.wrapped = value; } + constructor(value: any) { + this.wrapped = value; + } /** Creates a wrapped value. */ - static wrap(value: any): WrappedValue { return new WrappedValue(value); } + static wrap(value: any): WrappedValue { + return new WrappedValue(value); + } /** * Returns the underlying value of a wrapped value. * Returns the given `value` when it is not wrapped. **/ - static unwrap(value: any): any { return WrappedValue.isWrapped(value) ? value.wrapped : value; } + static unwrap(value: any): any { + return WrappedValue.isWrapped(value) ? value.wrapped : value; + } /** Returns true if `value` is a wrapped value. */ - static isWrapped(value: any): value is WrappedValue { return value instanceof WrappedValue; } + static isWrapped(value: any): value is WrappedValue { + return value instanceof WrappedValue; + } } export function isListLikeIterable(obj: any): boolean { diff --git a/packages/core/src/change_detection/differs/default_iterable_differ.ts b/packages/core/src/change_detection/differs/default_iterable_differ.ts index dd6d22a06d5ae..ea402369ab55b 100644 --- a/packages/core/src/change_detection/differs/default_iterable_differ.ts +++ b/packages/core/src/change_detection/differs/default_iterable_differ.ts @@ -15,7 +15,9 @@ import {IterableChangeRecord, IterableChanges, IterableDiffer, IterableDifferFac export class DefaultIterableDifferFactory implements IterableDifferFactory { constructor() {} - supports(obj: Object|null|undefined): boolean { return isListLikeIterable(obj); } + supports(obj: Object|null|undefined): boolean { + return isListLikeIterable(obj); + } create(trackByFn?: TrackByFunction): DefaultIterableDiffer { return new DefaultIterableDiffer(trackByFn); @@ -31,7 +33,7 @@ const trackByIdentity = (index: number, item: any) => item; export class DefaultIterableDiffer implements IterableDiffer, IterableChanges { public readonly length: number = 0; // TODO(issue/24571): remove '!'. - public readonly collection !: V[] | Iterable| null; + public readonly collection!: V[]|Iterable|null; // Keeps track of the used records at any point in time (during & across `_check()` calls) private _linkedRecords: _DuplicateMap|null = null; // Keeps track of the removed records at any point in time during `_check()` calls. @@ -50,7 +52,9 @@ export class DefaultIterableDiffer implements IterableDiffer, IterableChan private _identityChangesTail: IterableChangeRecord_|null = null; private _trackByFn: TrackByFunction; - constructor(trackByFn?: TrackByFunction) { this._trackByFn = trackByFn || trackByIdentity; } + constructor(trackByFn?: TrackByFunction) { + this._trackByFn = trackByFn || trackByIdentity; + } forEachItem(fn: (record: IterableChangeRecord_) => void) { let record: IterableChangeRecord_|null; @@ -71,9 +75,9 @@ export class DefaultIterableDiffer implements IterableDiffer, IterableChan // Order: remove, add, move const record: IterableChangeRecord = !nextRemove || nextIt && - nextIt.currentIndex ! < + nextIt.currentIndex! < getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets) ? - nextIt ! : + nextIt! : nextRemove; const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets); const currentIndex = record.currentIndex; @@ -83,14 +87,14 @@ export class DefaultIterableDiffer implements IterableDiffer, IterableChan addRemoveOffset--; nextRemove = nextRemove._nextRemoved; } else { - nextIt = nextIt !._next; + nextIt = nextIt!._next; if (record.previousIndex == null) { addRemoveOffset++; } else { // INVARIANT: currentIndex < previousIndex if (!moveOffsets) moveOffsets = []; const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset; - const localCurrentIndex = currentIndex ! - addRemoveOffset; + const localCurrentIndex = currentIndex! - addRemoveOffset; if (localMovePreviousIndex != localCurrentIndex) { for (let i = 0; i < localMovePreviousIndex; i++) { const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0); @@ -171,7 +175,7 @@ export class DefaultIterableDiffer implements IterableDiffer, IterableChan let item: V; let itemTrackBy: any; if (Array.isArray(collection)) { - (this as{length: number}).length = collection.length; + (this as {length: number}).length = collection.length; for (let index = 0; index < this.length; index++) { item = collection[index]; @@ -206,11 +210,11 @@ export class DefaultIterableDiffer implements IterableDiffer, IterableChan record = record._next; index++; }); - (this as{length: number}).length = index; + (this as {length: number}).length = index; } this._truncate(record); - (this as{collection: V[] | Iterable}).collection = collection; + (this as {collection: V[] | Iterable}).collection = collection; return this.isDirty; } @@ -338,7 +342,7 @@ export class DefaultIterableDiffer implements IterableDiffer, IterableChan let reinsertRecord: IterableChangeRecord_|null = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null); if (reinsertRecord !== null) { - record = this._reinsertAfter(reinsertRecord, record._prev !, index); + record = this._reinsertAfter(reinsertRecord, record._prev!, index); } else if (record.currentIndex != index) { record.currentIndex = index; this._addToMoves(record, index); @@ -611,7 +615,7 @@ class _DuplicateItemRecordList { // TODO(vicb): // assert(record.item == _head.item || // record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN); - this._tail !._nextDup = record; + this._tail!._nextDup = record; record._prevDup = this._tail; record._nextDup = null; this._tail = record; @@ -623,7 +627,7 @@ class _DuplicateItemRecordList { get(trackById: any, atOrAfterIndex: number|null): IterableChangeRecord_|null { let record: IterableChangeRecord_|null; for (record = this._head; record !== null; record = record._nextDup) { - if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex !) && + if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex!) && looseIdentical(record.trackById, trackById)) { return record; } @@ -696,7 +700,7 @@ class _DuplicateMap { */ remove(record: IterableChangeRecord_): IterableChangeRecord_ { const key = record.trackById; - const recordList: _DuplicateItemRecordList = this.map.get(key) !; + const recordList: _DuplicateItemRecordList = this.map.get(key)!; // Remove the list of duplicates when it gets empty if (recordList.remove(record)) { this.map.delete(key); @@ -704,13 +708,16 @@ class _DuplicateMap { return record; } - get isEmpty(): boolean { return this.map.size === 0; } + get isEmpty(): boolean { + return this.map.size === 0; + } - clear() { this.map.clear(); } + clear() { + this.map.clear(); + } } -function getPreviousIndex( - item: any, addRemoveOffset: number, moveOffsets: number[] | null): number { +function getPreviousIndex(item: any, addRemoveOffset: number, moveOffsets: number[]|null): number { const previousIndex = item.previousIndex; if (previousIndex === null) return previousIndex; let moveOffset = 0; diff --git a/packages/core/src/change_detection/differs/default_keyvalue_differ.ts b/packages/core/src/change_detection/differs/default_keyvalue_differ.ts index b0d8f404b71e1..fce214ca4b30a 100644 --- a/packages/core/src/change_detection/differs/default_keyvalue_differ.ts +++ b/packages/core/src/change_detection/differs/default_keyvalue_differ.ts @@ -14,9 +14,13 @@ import {KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDifferFac export class DefaultKeyValueDifferFactory implements KeyValueDifferFactory { constructor() {} - supports(obj: any): boolean { return obj instanceof Map || isJsObject(obj); } + supports(obj: any): boolean { + return obj instanceof Map || isJsObject(obj); + } - create(): KeyValueDiffer { return new DefaultKeyValueDiffer(); } + create(): KeyValueDiffer { + return new DefaultKeyValueDiffer(); + } } export class DefaultKeyValueDiffer implements KeyValueDiffer, KeyValueChanges { @@ -175,7 +179,7 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer, KeyVal private _getOrCreateRecordForKey(key: K, value: V): KeyValueChangeRecord_ { if (this._records.has(key)) { - const record = this._records.get(key) !; + const record = this._records.get(key)!; this._maybeAddToChanges(record, value); const prev = record._prev; const next = record._next; @@ -236,7 +240,7 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer, KeyVal if (this._additionsHead === null) { this._additionsHead = this._additionsTail = record; } else { - this._additionsTail !._nextAdded = record; + this._additionsTail!._nextAdded = record; this._additionsTail = record; } } @@ -245,7 +249,7 @@ export class DefaultKeyValueDiffer implements KeyValueDiffer, KeyVal if (this._changesHead === null) { this._changesHead = this._changesTail = record; } else { - this._changesTail !._nextChanged = record; + this._changesTail!._nextChanged = record; this._changesTail = record; } } diff --git a/packages/core/src/change_detection/differs/iterable_differs.ts b/packages/core/src/change_detection/differs/iterable_differs.ts index e9f6f660d9f6d..0029e61bd1e5e 100644 --- a/packages/core/src/change_detection/differs/iterable_differs.ts +++ b/packages/core/src/change_detection/differs/iterable_differs.ts @@ -18,7 +18,7 @@ import {DefaultIterableDifferFactory} from '../differs/default_iterable_differ'; * * @publicApi */ -export type NgIterable = Array| Iterable; +export type NgIterable = Array|Iterable; /** * A strategy for tracking changes over time to an iterable. Used by {@link NgForOf} to @@ -86,8 +86,10 @@ export interface IterableChanges { /** Iterate over all removed items. */ forEachRemovedItem(fn: (record: IterableChangeRecord) => void): void; - /** Iterate over all items which had their identity (as computed by the `TrackByFunction`) - * changed. */ + /** + * Iterate over all items which had their identity (as computed by the `TrackByFunction`) + * changed. + */ forEachIdentityChange(fn: (record: IterableChangeRecord) => void): void; } @@ -124,7 +126,9 @@ export interface CollectionChangeRecord extends IterableChangeRecord {} * * @publicApi */ -export interface TrackByFunction { (index: number, item: T): any; } +export interface TrackByFunction { + (index: number, item: T): any; +} /** * Provides a factory for {@link IterableDiffer}. @@ -153,7 +157,9 @@ export class IterableDiffers { * @deprecated v4.0.0 - Should be private */ factories: IterableDifferFactory[]; - constructor(factories: IterableDifferFactory[]) { this.factories = factories; } + constructor(factories: IterableDifferFactory[]) { + this.factories = factories; + } static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers { if (parent != null) { @@ -206,8 +212,8 @@ export class IterableDiffers { if (factory != null) { return factory; } else { - throw new Error( - `Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`); + throw new Error(`Cannot find a differ supporting object '${iterable}' of type '${ + getTypeNameForDebugging(iterable)}'`); } } } diff --git a/packages/core/src/change_detection/differs/keyvalue_differs.ts b/packages/core/src/change_detection/differs/keyvalue_differs.ts index 953d787d36654..246bd4d357c6d 100644 --- a/packages/core/src/change_detection/differs/keyvalue_differs.ts +++ b/packages/core/src/change_detection/differs/keyvalue_differs.ts @@ -129,7 +129,9 @@ export class KeyValueDiffers { */ factories: KeyValueDifferFactory[]; - constructor(factories: KeyValueDifferFactory[]) { this.factories = factories; } + constructor(factories: KeyValueDifferFactory[]) { + this.factories = factories; + } static create(factories: KeyValueDifferFactory[], parent?: KeyValueDiffers): KeyValueDiffers { if (parent) { diff --git a/packages/core/src/change_detection/pipe_transform.ts b/packages/core/src/change_detection/pipe_transform.ts index 3a6889e3a85a9..db5b0f4dc8f4e 100644 --- a/packages/core/src/change_detection/pipe_transform.ts +++ b/packages/core/src/change_detection/pipe_transform.ts @@ -30,4 +30,6 @@ * * @publicApi */ -export interface PipeTransform { transform(value: any, ...args: any[]): any; } +export interface PipeTransform { + transform(value: any, ...args: any[]): any; +} diff --git a/packages/core/src/codegen_private_exports.ts b/packages/core/src/codegen_private_exports.ts index 177d4560abb80..76bcb8614853c 100644 --- a/packages/core/src/codegen_private_exports.ts +++ b/packages/core/src/codegen_private_exports.ts @@ -8,4 +8,4 @@ export {CodegenComponentFactoryResolver as ɵCodegenComponentFactoryResolver} from './linker/component_factory_resolver'; export {registerModuleFactory as ɵregisterModuleFactory} from './linker/ng_module_factory_registration'; -export {ArgumentType as ɵArgumentType, BindingFlags as ɵBindingFlags, DepFlags as ɵDepFlags, EMPTY_ARRAY as ɵEMPTY_ARRAY, EMPTY_MAP as ɵEMPTY_MAP, NodeFlags as ɵNodeFlags, QueryBindingType as ɵQueryBindingType, QueryValueType as ɵQueryValueType, ViewDefinition as ɵViewDefinition, ViewFlags as ɵViewFlags, anchorDef as ɵand, createComponentFactory as ɵccf, createNgModuleFactory as ɵcmf, createRendererType2 as ɵcrt, directiveDef as ɵdid, elementDef as ɵeld, getComponentViewDefinitionFactory as ɵgetComponentViewDefinitionFactory, inlineInterpolate as ɵinlineInterpolate, interpolate as ɵinterpolate, moduleDef as ɵmod, moduleProvideDef as ɵmpd, ngContentDef as ɵncd, nodeValue as ɵnov, pipeDef as ɵpid, providerDef as ɵprd, pureArrayDef as ɵpad, pureObjectDef as ɵpod, purePipeDef as ɵppd, queryDef as ɵqud, textDef as ɵted, unwrapValue as ɵunv, viewDef as ɵvid} from './view/index'; +export {anchorDef as ɵand, ArgumentType as ɵArgumentType, BindingFlags as ɵBindingFlags, createComponentFactory as ɵccf, createNgModuleFactory as ɵcmf, createRendererType2 as ɵcrt, DepFlags as ɵDepFlags, directiveDef as ɵdid, elementDef as ɵeld, EMPTY_ARRAY as ɵEMPTY_ARRAY, EMPTY_MAP as ɵEMPTY_MAP, getComponentViewDefinitionFactory as ɵgetComponentViewDefinitionFactory, inlineInterpolate as ɵinlineInterpolate, interpolate as ɵinterpolate, moduleDef as ɵmod, moduleProvideDef as ɵmpd, ngContentDef as ɵncd, NodeFlags as ɵNodeFlags, nodeValue as ɵnov, pipeDef as ɵpid, providerDef as ɵprd, pureArrayDef as ɵpad, pureObjectDef as ɵpod, purePipeDef as ɵppd, QueryBindingType as ɵQueryBindingType, queryDef as ɵqud, QueryValueType as ɵQueryValueType, textDef as ɵted, unwrapValue as ɵunv, viewDef as ɵvid, ViewDefinition as ɵViewDefinition, ViewFlags as ɵViewFlags} from './view/index'; diff --git a/packages/core/src/compiler/compiler_facade_interface.ts b/packages/core/src/compiler/compiler_facade_interface.ts index 79d06d41c1147..e563344f23f6a 100644 --- a/packages/core/src/compiler/compiler_facade_interface.ts +++ b/packages/core/src/compiler/compiler_facade_interface.ts @@ -22,7 +22,9 @@ * ``` */ -export interface ExportedCompilerFacade { ɵcompilerFacade: CompilerFacade; } +export interface ExportedCompilerFacade { + ɵcompilerFacade: CompilerFacade; +} export interface CompilerFacade { compilePipe(angularCoreEnv: CoreEnvironment, sourceMapUrl: string, meta: R3PipeMetadataFacade): @@ -44,13 +46,15 @@ export interface CompilerFacade { R3ResolvedDependencyType: typeof R3ResolvedDependencyType; R3FactoryTarget: typeof R3FactoryTarget; - ResourceLoader: {new (): ResourceLoader}; + ResourceLoader: {new(): ResourceLoader}; } -export interface CoreEnvironment { [name: string]: Function; } +export interface CoreEnvironment { + [name: string]: Function; +} export type ResourceLoader = { - get(url: string): Promise| string; + get(url: string): Promise|string; }; export type StringMap = { @@ -58,7 +62,7 @@ export type StringMap = { }; export type StringMapWithRename = { - [key: string]: string | [string, string]; + [key: string]: string|[string, string]; }; export type Provider = any; diff --git a/packages/core/src/core_private_export.ts b/packages/core/src/core_private_export.ts index 640d7369fb95b..e8d075ea93506 100644 --- a/packages/core/src/core_private_export.ts +++ b/packages/core/src/core_private_export.ts @@ -16,7 +16,7 @@ export {getDebugNodeR2 as ɵgetDebugNodeR2} from './debug/debug_node'; export {inject, setCurrentInjector as ɵsetCurrentInjector, ɵɵinject} from './di/injector_compatibility'; export {getInjectableDef as ɵgetInjectableDef, ɵɵInjectableDef, ɵɵInjectorDef} from './di/interface/defs'; export {INJECTOR_SCOPE as ɵINJECTOR_SCOPE} from './di/scope'; -export {CurrencyIndex as ɵCurrencyIndex, ExtraLocaleDataIndex as ɵExtraLocaleDataIndex, LocaleDataIndex as ɵLocaleDataIndex, findLocaleData as ɵfindLocaleData, getLocaleCurrencyCode as ɵgetLocaleCurrencyCode, getLocalePluralCase as ɵgetLocalePluralCase, registerLocaleData as ɵregisterLocaleData, unregisterAllLocaleData as ɵunregisterLocaleData} from './i18n/locale_data_api'; +export {CurrencyIndex as ɵCurrencyIndex, ExtraLocaleDataIndex as ɵExtraLocaleDataIndex, findLocaleData as ɵfindLocaleData, getLocaleCurrencyCode as ɵgetLocaleCurrencyCode, getLocalePluralCase as ɵgetLocalePluralCase, LocaleDataIndex as ɵLocaleDataIndex, registerLocaleData as ɵregisterLocaleData, unregisterAllLocaleData as ɵunregisterLocaleData} from './i18n/locale_data_api'; export {DEFAULT_LOCALE_ID as ɵDEFAULT_LOCALE_ID} from './i18n/localization'; export {ivyEnabled as ɵivyEnabled} from './ivy_switch'; export {ComponentFactory as ɵComponentFactory} from './linker/component_factory'; @@ -24,7 +24,7 @@ export {CodegenComponentFactoryResolver as ɵCodegenComponentFactoryResolver} fr export {clearResolutionOfComponentResourcesQueue as ɵclearResolutionOfComponentResourcesQueue, resolveComponentResources as ɵresolveComponentResources} from './metadata/resource_loading'; export {ReflectionCapabilities as ɵReflectionCapabilities} from './reflection/reflection_capabilities'; export {GetterFn as ɵGetterFn, MethodFn as ɵMethodFn, SetterFn as ɵSetterFn} from './reflection/types'; -export {BypassType as ɵBypassType, SafeHtml as ɵSafeHtml, SafeResourceUrl as ɵSafeResourceUrl, SafeScript as ɵSafeScript, SafeStyle as ɵSafeStyle, SafeUrl as ɵSafeUrl, SafeValue as ɵSafeValue, allowSanitizationBypassAndThrow as ɵallowSanitizationBypassAndThrow, getSanitizationBypassType as ɵgetSanitizationBypassType, unwrapSafeValue as ɵunwrapSafeValue} from './sanitization/bypass'; +export {allowSanitizationBypassAndThrow as ɵallowSanitizationBypassAndThrow, BypassType as ɵBypassType, getSanitizationBypassType as ɵgetSanitizationBypassType, SafeHtml as ɵSafeHtml, SafeResourceUrl as ɵSafeResourceUrl, SafeScript as ɵSafeScript, SafeStyle as ɵSafeStyle, SafeUrl as ɵSafeUrl, SafeValue as ɵSafeValue, unwrapSafeValue as ɵunwrapSafeValue} from './sanitization/bypass'; export {_sanitizeHtml as ɵ_sanitizeHtml} from './sanitization/html_sanitizer'; export {_sanitizeStyle as ɵ_sanitizeStyle} from './sanitization/style_sanitizer'; export {_sanitizeUrl as ɵ_sanitizeUrl} from './sanitization/url_sanitizer'; diff --git a/packages/core/src/core_render3_private_export.ts b/packages/core/src/core_render3_private_export.ts index 24fdccfd2a182..0f1c8e77d58f5 100644 --- a/packages/core/src/core_render3_private_export.ts +++ b/packages/core/src/core_render3_private_export.ts @@ -7,7 +7,101 @@ */ // clang-format off +// we reexport these symbols just so that they are retained during the dead code elimination +// performed by rollup while it's creating fesm files. +// +// no code actually imports these symbols from the @angular/core entry point +export { + compileNgModuleFactory__POST_R3__ as ɵcompileNgModuleFactory__POST_R3__, + isBoundToModule__POST_R3__ as ɵisBoundToModule__POST_R3__ +} from './application_ref'; +export { + SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__ as ɵSWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__, +} from './change_detection/change_detector_ref'; +export { + getDebugNode__POST_R3__ as ɵgetDebugNode__POST_R3__, +} from './debug/debug_node'; export { + SWITCH_COMPILE_INJECTABLE__POST_R3__ as ɵSWITCH_COMPILE_INJECTABLE__POST_R3__, +} from './di/injectable'; +export {INJECTOR_IMPL__POST_R3__ as ɵINJECTOR_IMPL__POST_R3__} from './di/injector'; +export { + NG_INJ_DEF as ɵNG_INJ_DEF, + NG_PROV_DEF as ɵNG_PROV_DEF, +} from './di/interface/defs'; +export {createInjector as ɵcreateInjector} from './di/r3_injector'; +export { + SWITCH_IVY_ENABLED__POST_R3__ as ɵSWITCH_IVY_ENABLED__POST_R3__, +} from './ivy_switch'; +export { + Compiler_compileModuleAndAllComponentsAsync__POST_R3__ as ɵCompiler_compileModuleAndAllComponentsAsync__POST_R3__, + Compiler_compileModuleAndAllComponentsSync__POST_R3__ as ɵCompiler_compileModuleAndAllComponentsSync__POST_R3__, + Compiler_compileModuleAsync__POST_R3__ as ɵCompiler_compileModuleAsync__POST_R3__, + Compiler_compileModuleSync__POST_R3__ as ɵCompiler_compileModuleSync__POST_R3__, +} from './linker/compiler'; +export { + SWITCH_ELEMENT_REF_FACTORY__POST_R3__ as ɵSWITCH_ELEMENT_REF_FACTORY__POST_R3__, +} from './linker/element_ref'; +export { getModuleFactory__POST_R3__ as ɵgetModuleFactory__POST_R3__ } from './linker/ng_module_factory_loader'; +export { registerNgModuleType as ɵregisterNgModuleType } from './linker/ng_module_factory_registration'; +export { + SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ as ɵSWITCH_TEMPLATE_REF_FACTORY__POST_R3__, +} from './linker/template_ref'; +export { + SWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__ as ɵSWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__, +} from './linker/view_container_ref'; +export { + SWITCH_COMPILE_COMPONENT__POST_R3__ as ɵSWITCH_COMPILE_COMPONENT__POST_R3__, + SWITCH_COMPILE_DIRECTIVE__POST_R3__ as ɵSWITCH_COMPILE_DIRECTIVE__POST_R3__, + SWITCH_COMPILE_PIPE__POST_R3__ as ɵSWITCH_COMPILE_PIPE__POST_R3__, +} from './metadata/directives'; +export { + NgModuleDef as ɵNgModuleDef, + NgModuleTransitiveScopes as ɵNgModuleTransitiveScopes, + ɵɵNgModuleDefWithMeta, +} from './metadata/ng_module'; +export { + SWITCH_COMPILE_NGMODULE__POST_R3__ as ɵSWITCH_COMPILE_NGMODULE__POST_R3__, +} from './metadata/ng_module'; +export { + SWITCH_RENDERER2_FACTORY__POST_R3__ as ɵSWITCH_RENDERER2_FACTORY__POST_R3__, +} from './render/api'; +export { + getLContext as ɵgetLContext +} from './render3/context_discovery'; +export { + NG_COMP_DEF as ɵNG_COMP_DEF, + NG_DIR_DEF as ɵNG_DIR_DEF, + NG_ELEMENT_ID as ɵNG_ELEMENT_ID, + NG_MOD_DEF as ɵNG_MOD_DEF, + NG_PIPE_DEF as ɵNG_PIPE_DEF, +} from './render3/fields'; +export { + AttributeMarker as ɵAttributeMarker, + ComponentDef as ɵComponentDef, + ComponentFactory as ɵRender3ComponentFactory, + ComponentRef as ɵRender3ComponentRef, + ComponentType as ɵComponentType, + CssSelectorList as ɵCssSelectorList, + detectChanges as ɵdetectChanges, + DirectiveDef as ɵDirectiveDef, + DirectiveType as ɵDirectiveType, + getDirectives as ɵgetDirectives, + getHostElement as ɵgetHostElement, + LifecycleHooksFeature as ɵLifecycleHooksFeature, + markDirty as ɵmarkDirty, + NgModuleFactory as ɵNgModuleFactory, + NgModuleRef as ɵRender3NgModuleRef, + NgModuleType as ɵNgModuleType, + NO_CHANGE as ɵNO_CHANGE, + PipeDef as ɵPipeDef, + renderComponent as ɵrenderComponent, + RenderFlags as ɵRenderFlags, + setClassMetadata as ɵsetClassMetadata, + setLocaleId as ɵsetLocaleId, + store as ɵstore, + whenRendered as ɵwhenRendered, + ɵɵadvance, ɵɵattribute, ɵɵattributeInterpolate1, ɵɵattributeInterpolate2, @@ -18,88 +112,72 @@ export { ɵɵattributeInterpolate7, ɵɵattributeInterpolate8, ɵɵattributeInterpolateV, + ɵɵclassMap, + ɵɵclassMapInterpolate1, + ɵɵclassMapInterpolate2, + ɵɵclassMapInterpolate3, + ɵɵclassMapInterpolate4, + ɵɵclassMapInterpolate5, + ɵɵclassMapInterpolate6, + ɵɵclassMapInterpolate7, + ɵɵclassMapInterpolate8, + ɵɵclassMapInterpolateV, + ɵɵclassProp, + ɵɵComponentDefWithMeta, + ɵɵcomponentHostSyntheticListener, + ɵɵcontainer, + ɵɵcontainerRefreshEnd, + ɵɵcontainerRefreshStart, + ɵɵcontentQuery, + ɵɵCopyDefinitionFeature, ɵɵdefineComponent, ɵɵdefineDirective, - ɵɵdefinePipe, ɵɵdefineNgModule, - detectChanges as ɵdetectChanges, - renderComponent as ɵrenderComponent, - AttributeMarker as ɵAttributeMarker, - ComponentType as ɵComponentType, - ComponentFactory as ɵRender3ComponentFactory, - ComponentRef as ɵRender3ComponentRef, - DirectiveType as ɵDirectiveType, - RenderFlags as ɵRenderFlags, + ɵɵdefinePipe, + ɵɵDirectiveDefWithMeta, ɵɵdirectiveInject, - ɵɵinjectAttribute, - ɵɵinjectPipeChangeDetectorRef, - ɵɵinvalidFactory, + ɵɵdisableBindings, + ɵɵelement, + ɵɵelementContainer, + ɵɵelementContainerEnd, + ɵɵelementContainerStart, + ɵɵelementEnd, + ɵɵelementStart, + ɵɵembeddedViewEnd, + ɵɵembeddedViewStart, + ɵɵenableBindings, + ɵɵFactoryDef, + ɵɵgetCurrentView, ɵɵgetFactoryOf, ɵɵgetInheritedFactory, - ɵɵsetComponentScope, - ɵɵsetNgModuleScope, - ɵɵtemplateRefExtractor, - ɵɵProvidersFeature, - ɵɵCopyDefinitionFeature, + ɵɵhostProperty, + ɵɵi18n, + ɵɵi18nApply, + ɵɵi18nAttributes, + ɵɵi18nEnd, + ɵɵi18nExp, + ɵɵi18nPostprocess, + ɵɵi18nStart, ɵɵInheritDefinitionFeature, - ɵɵNgOnChangesFeature, - LifecycleHooksFeature as ɵLifecycleHooksFeature, - NgModuleType as ɵNgModuleType, - NgModuleRef as ɵRender3NgModuleRef, - CssSelectorList as ɵCssSelectorList, - markDirty as ɵmarkDirty, - NgModuleFactory as ɵNgModuleFactory, - NO_CHANGE as ɵNO_CHANGE, - ɵɵcontainer, - ɵɵnextContext, - ɵɵelementStart, + ɵɵinjectAttribute, + ɵɵinjectPipeChangeDetectorRef, + ɵɵinvalidFactory, + ɵɵlistener, + ɵɵloadQuery, ɵɵnamespaceHTML, ɵɵnamespaceMathML, ɵɵnamespaceSVG, - ɵɵelement, - ɵɵlistener, - ɵɵtext, - ɵɵtextInterpolate, - ɵɵtextInterpolate1, - ɵɵtextInterpolate2, - ɵɵtextInterpolate3, - ɵɵtextInterpolate4, - ɵɵtextInterpolate5, - ɵɵtextInterpolate6, - ɵɵtextInterpolate7, - ɵɵtextInterpolate8, - ɵɵtextInterpolateV, - ɵɵembeddedViewStart, - ɵɵprojection, + ɵɵnextContext, + ɵɵNgOnChangesFeature, + ɵɵpipe, ɵɵpipeBind1, ɵɵpipeBind2, ɵɵpipeBind3, ɵɵpipeBind4, ɵɵpipeBindV, - ɵɵpureFunction0, - ɵɵpureFunction1, - ɵɵpureFunction2, - ɵɵpureFunction3, - ɵɵpureFunction4, - ɵɵpureFunction5, - ɵɵpureFunction6, - ɵɵpureFunction7, - ɵɵpureFunction8, - ɵɵpureFunctionV, - ɵɵgetCurrentView, - getDirectives as ɵgetDirectives, - getHostElement as ɵgetHostElement, - ɵɵrestoreView, - ɵɵcontainerRefreshStart, - ɵɵcontainerRefreshEnd, - ɵɵqueryRefresh, - ɵɵviewQuery, - ɵɵstaticViewQuery, - ɵɵstaticContentQuery, - ɵɵcontentQuery, - ɵɵloadQuery, - ɵɵelementEnd, - ɵɵhostProperty, + ɵɵPipeDefWithMeta, + ɵɵprojection, + ɵɵprojectionDef, ɵɵproperty, ɵɵpropertyInterpolate, ɵɵpropertyInterpolate1, @@ -111,15 +189,29 @@ export { ɵɵpropertyInterpolate7, ɵɵpropertyInterpolate8, ɵɵpropertyInterpolateV, - ɵɵupdateSyntheticHostBinding, - ɵɵcomponentHostSyntheticListener, - ɵɵprojectionDef, + ɵɵProvidersFeature, + ɵɵpureFunction0, + ɵɵpureFunction1, + ɵɵpureFunction2, + ɵɵpureFunction3, + ɵɵpureFunction4, + ɵɵpureFunction5, + ɵɵpureFunction6, + ɵɵpureFunction7, + ɵɵpureFunction8, + ɵɵpureFunctionV, + ɵɵqueryRefresh, ɵɵreference, - ɵɵenableBindings, - ɵɵdisableBindings, - ɵɵelementContainerStart, - ɵɵelementContainerEnd, - ɵɵelementContainer, + ɵɵresolveBody, + ɵɵresolveDocument, + ɵɵresolveWindow, + ɵɵrestoreView, + + ɵɵselect, + ɵɵsetComponentScope, + ɵɵsetNgModuleScope, + ɵɵstaticContentQuery, + ɵɵstaticViewQuery, ɵɵstyleMap, ɵɵstyleMapInterpolate1, ɵɵstyleMapInterpolate2, @@ -130,17 +222,6 @@ export { ɵɵstyleMapInterpolate7, ɵɵstyleMapInterpolate8, ɵɵstyleMapInterpolateV, - ɵɵstyleSanitizer, - ɵɵclassMap, - ɵɵclassMapInterpolate1, - ɵɵclassMapInterpolate2, - ɵɵclassMapInterpolate3, - ɵɵclassMapInterpolate4, - ɵɵclassMapInterpolate5, - ɵɵclassMapInterpolate6, - ɵɵclassMapInterpolate7, - ɵɵclassMapInterpolate8, - ɵɵclassMapInterpolateV, ɵɵstyleProp, ɵɵstylePropInterpolate1, ɵɵstylePropInterpolate2, @@ -151,170 +232,72 @@ export { ɵɵstylePropInterpolate7, ɵɵstylePropInterpolate8, ɵɵstylePropInterpolateV, - ɵɵclassProp, - - ɵɵselect, - ɵɵadvance, + ɵɵstyleSanitizer, ɵɵtemplate, - ɵɵembeddedViewEnd, - store as ɵstore, - ɵɵpipe, - ComponentDef as ɵComponentDef, - ɵɵComponentDefWithMeta, - ɵɵFactoryDef, - DirectiveDef as ɵDirectiveDef, - ɵɵDirectiveDefWithMeta, - PipeDef as ɵPipeDef, - ɵɵPipeDefWithMeta, - whenRendered as ɵwhenRendered, - ɵɵi18n, - ɵɵi18nAttributes, - ɵɵi18nExp, - ɵɵi18nStart, - ɵɵi18nEnd, - ɵɵi18nApply, - ɵɵi18nPostprocess, - setLocaleId as ɵsetLocaleId, - setClassMetadata as ɵsetClassMetadata, - ɵɵresolveWindow, - ɵɵresolveDocument, - ɵɵresolveBody, + ɵɵtemplateRefExtractor, + ɵɵtext, + ɵɵtextInterpolate, + ɵɵtextInterpolate1, + ɵɵtextInterpolate2, + ɵɵtextInterpolate3, + ɵɵtextInterpolate4, + ɵɵtextInterpolate5, + ɵɵtextInterpolate6, + ɵɵtextInterpolate7, + ɵɵtextInterpolate8, + ɵɵtextInterpolateV, + ɵɵupdateSyntheticHostBinding, + ɵɵviewQuery, } from './render3/index'; - - +export { + LContext as ɵLContext, +} from './render3/interfaces/context'; +export { + setDocument as ɵsetDocument +} from './render3/interfaces/document'; +export { + Player as ɵPlayer, + PlayerFactory as ɵPlayerFactory, + PlayerHandler as ɵPlayerHandler, + PlayState as ɵPlayState, +} from './render3/interfaces/player'; export { compileComponent as ɵcompileComponent, compileDirective as ɵcompileDirective, } from './render3/jit/directive'; +export { + resetJitOptions as ɵresetJitOptions, +} from './render3/jit/jit_options'; export { compileNgModule as ɵcompileNgModule, compileNgModuleDefs as ɵcompileNgModuleDefs, + flushModuleScopingQueueAsMuchAsPossible as ɵflushModuleScopingQueueAsMuchAsPossible, patchComponentDefWithScope as ɵpatchComponentDefWithScope, resetCompiledComponents as ɵresetCompiledComponents, - flushModuleScopingQueueAsMuchAsPossible as ɵflushModuleScopingQueueAsMuchAsPossible, transitiveScopesFor as ɵtransitiveScopesFor, } from './render3/jit/module'; export { compilePipe as ɵcompilePipe, } from './render3/jit/pipe'; export { - resetJitOptions as ɵresetJitOptions, -} from './render3/jit/jit_options'; - + publishDefaultGlobalUtils as ɵpublishDefaultGlobalUtils +, + publishGlobalUtil as ɵpublishGlobalUtil} from './render3/util/global_utils'; export { - NgModuleDef as ɵNgModuleDef, - ɵɵNgModuleDefWithMeta, - NgModuleTransitiveScopes as ɵNgModuleTransitiveScopes, -} from './metadata/ng_module'; - + bypassSanitizationTrustHtml as ɵbypassSanitizationTrustHtml, + bypassSanitizationTrustResourceUrl as ɵbypassSanitizationTrustResourceUrl, + bypassSanitizationTrustScript as ɵbypassSanitizationTrustScript, + bypassSanitizationTrustStyle as ɵbypassSanitizationTrustStyle, + bypassSanitizationTrustUrl as ɵbypassSanitizationTrustUrl, +} from './sanitization/bypass'; export { - ɵɵsanitizeHtml, - ɵɵsanitizeStyle, ɵɵdefaultStyleSanitizer, + ɵɵsanitizeHtml, + ɵɵsanitizeResourceUrl, ɵɵsanitizeScript, + ɵɵsanitizeStyle, ɵɵsanitizeUrl, - ɵɵsanitizeResourceUrl, ɵɵsanitizeUrlOrResourceUrl, } from './sanitization/sanitization'; -export { - bypassSanitizationTrustHtml as ɵbypassSanitizationTrustHtml, - bypassSanitizationTrustStyle as ɵbypassSanitizationTrustStyle, - bypassSanitizationTrustScript as ɵbypassSanitizationTrustScript, - bypassSanitizationTrustUrl as ɵbypassSanitizationTrustUrl, - bypassSanitizationTrustResourceUrl as ɵbypassSanitizationTrustResourceUrl, -} from './sanitization/bypass'; - -export { - getLContext as ɵgetLContext -} from './render3/context_discovery'; - -export { - NG_ELEMENT_ID as ɵNG_ELEMENT_ID, - NG_COMP_DEF as ɵNG_COMP_DEF, - NG_DIR_DEF as ɵNG_DIR_DEF, - NG_PIPE_DEF as ɵNG_PIPE_DEF, - NG_MOD_DEF as ɵNG_MOD_DEF, -} from './render3/fields'; - -export { - NG_PROV_DEF as ɵNG_PROV_DEF, - NG_INJ_DEF as ɵNG_INJ_DEF, -} from './di/interface/defs'; - -export { - Player as ɵPlayer, - PlayerFactory as ɵPlayerFactory, - PlayState as ɵPlayState, - PlayerHandler as ɵPlayerHandler, -} from './render3/interfaces/player'; - -export { - LContext as ɵLContext, -} from './render3/interfaces/context'; - -export { - setDocument as ɵsetDocument -} from './render3/interfaces/document'; - -// we reexport these symbols just so that they are retained during the dead code elimination -// performed by rollup while it's creating fesm files. -// -// no code actually imports these symbols from the @angular/core entry point -export { - compileNgModuleFactory__POST_R3__ as ɵcompileNgModuleFactory__POST_R3__, - isBoundToModule__POST_R3__ as ɵisBoundToModule__POST_R3__ -} from './application_ref'; -export { - SWITCH_COMPILE_COMPONENT__POST_R3__ as ɵSWITCH_COMPILE_COMPONENT__POST_R3__, - SWITCH_COMPILE_DIRECTIVE__POST_R3__ as ɵSWITCH_COMPILE_DIRECTIVE__POST_R3__, - SWITCH_COMPILE_PIPE__POST_R3__ as ɵSWITCH_COMPILE_PIPE__POST_R3__, -} from './metadata/directives'; -export { - SWITCH_COMPILE_NGMODULE__POST_R3__ as ɵSWITCH_COMPILE_NGMODULE__POST_R3__, -} from './metadata/ng_module'; -export { - getDebugNode__POST_R3__ as ɵgetDebugNode__POST_R3__, -} from './debug/debug_node'; -export { - SWITCH_COMPILE_INJECTABLE__POST_R3__ as ɵSWITCH_COMPILE_INJECTABLE__POST_R3__, -} from './di/injectable'; -export { - SWITCH_IVY_ENABLED__POST_R3__ as ɵSWITCH_IVY_ENABLED__POST_R3__, -} from './ivy_switch'; -export { - SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__ as ɵSWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__, -} from './change_detection/change_detector_ref'; -export { - Compiler_compileModuleSync__POST_R3__ as ɵCompiler_compileModuleSync__POST_R3__, - Compiler_compileModuleAsync__POST_R3__ as ɵCompiler_compileModuleAsync__POST_R3__, - Compiler_compileModuleAndAllComponentsSync__POST_R3__ as ɵCompiler_compileModuleAndAllComponentsSync__POST_R3__, - Compiler_compileModuleAndAllComponentsAsync__POST_R3__ as ɵCompiler_compileModuleAndAllComponentsAsync__POST_R3__, -} from './linker/compiler'; -export { - SWITCH_ELEMENT_REF_FACTORY__POST_R3__ as ɵSWITCH_ELEMENT_REF_FACTORY__POST_R3__, -} from './linker/element_ref'; -export { - SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ as ɵSWITCH_TEMPLATE_REF_FACTORY__POST_R3__, -} from './linker/template_ref'; -export { - SWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__ as ɵSWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__, -} from './linker/view_container_ref'; -export { - SWITCH_RENDERER2_FACTORY__POST_R3__ as ɵSWITCH_RENDERER2_FACTORY__POST_R3__, -} from './render/api'; - -export { getModuleFactory__POST_R3__ as ɵgetModuleFactory__POST_R3__ } from './linker/ng_module_factory_loader'; - -export { registerNgModuleType as ɵregisterNgModuleType } from './linker/ng_module_factory_registration'; - -export { - publishGlobalUtil as ɵpublishGlobalUtil, - publishDefaultGlobalUtils as ɵpublishDefaultGlobalUtils -} from './render3/util/global_utils'; - -export {createInjector as ɵcreateInjector} from './di/r3_injector'; - -export {INJECTOR_IMPL__POST_R3__ as ɵINJECTOR_IMPL__POST_R3__} from './di/injector'; - // clang-format on diff --git a/packages/core/src/debug/debug_node.ts b/packages/core/src/debug/debug_node.ts index 3270a568f13be..c6161dbe81110 100644 --- a/packages/core/src/debug/debug_node.ts +++ b/packages/core/src/debug/debug_node.ts @@ -10,7 +10,7 @@ import {Injector} from '../di'; import {CONTAINER_HEADER_OFFSET, LContainer, NATIVE} from '../render3/interfaces/container'; import {TElementNode, TNode, TNodeFlags, TNodeType} from '../render3/interfaces/node'; import {isComponentHost, isLContainer} from '../render3/interfaces/type_checks'; -import {DECLARATION_COMPONENT_VIEW, LView, PARENT, TData, TVIEW, T_HOST} from '../render3/interfaces/view'; +import {DECLARATION_COMPONENT_VIEW, LView, PARENT, T_HOST, TData, TVIEW} from '../render3/interfaces/view'; import {getComponent, getContext, getInjectionTokens, getInjector, getListeners, getLocalRefs, getOwningComponent, loadLContext} from '../render3/util/discovery_utils'; import {INTERPOLATION_DELIMITER, renderStringify} from '../render3/util/misc_utils'; import {getComponentLViewByIndex, getNativeByTNodeOrNull} from '../render3/util/view_utils'; @@ -53,15 +53,25 @@ export class DebugNode__PRE_R3__ { } } - get injector(): Injector { return this._debugContext.injector; } + get injector(): Injector { + return this._debugContext.injector; + } - get componentInstance(): any { return this._debugContext.component; } + get componentInstance(): any { + return this._debugContext.component; + } - get context(): any { return this._debugContext.context; } + get context(): any { + return this._debugContext.context; + } - get references(): {[key: string]: any} { return this._debugContext.references; } + get references(): {[key: string]: any} { + return this._debugContext.references; + } - get providerTokens(): any[] { return this._debugContext.providerTokens; } + get providerTokens(): any[] { + return this._debugContext.providerTokens; + } } /** @@ -70,9 +80,9 @@ export class DebugNode__PRE_R3__ { export interface DebugElement extends DebugNode { readonly name: string; readonly properties: {[key: string]: any}; - readonly attributes: {[key: string]: string | null}; + readonly attributes: {[key: string]: string|null}; readonly classes: {[key: string]: boolean}; - readonly styles: {[key: string]: string | null}; + readonly styles: {[key: string]: string|null}; readonly childNodes: DebugNode[]; readonly nativeElement: any; readonly children: DebugElement[]; @@ -83,11 +93,11 @@ export interface DebugElement extends DebugNode { triggerEventHandler(eventName: string, eventObj: any): void; } export class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ implements DebugElement { - readonly name !: string; + readonly name!: string; readonly properties: {[key: string]: any} = {}; - readonly attributes: {[key: string]: string | null} = {}; + readonly attributes: {[key: string]: string|null} = {}; readonly classes: {[key: string]: boolean} = {}; - readonly styles: {[key: string]: string | null} = {}; + readonly styles: {[key: string]: string|null} = {}; readonly childNodes: DebugNode[] = []; readonly nativeElement: any; @@ -99,14 +109,14 @@ export class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ implements Debug addChild(child: DebugNode) { if (child) { this.childNodes.push(child); - (child as{parent: DebugNode}).parent = this; + (child as {parent: DebugNode}).parent = this; } } removeChild(child: DebugNode) { const childIndex = this.childNodes.indexOf(child); if (childIndex !== -1) { - (child as{parent: DebugNode | null}).parent = null; + (child as {parent: DebugNode | null}).parent = null; this.childNodes.splice(childIndex, 1); } } @@ -119,7 +129,7 @@ export class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ implements Debug if (c.parent) { (c.parent as DebugElement__PRE_R3__).removeChild(c); } - (child as{parent: DebugNode}).parent = this; + (child as {parent: DebugNode}).parent = this; }); } } @@ -132,7 +142,7 @@ export class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ implements Debug if (newChild.parent) { (newChild.parent as DebugElement__PRE_R3__).removeChild(newChild); } - (newChild as{parent: DebugNode}).parent = this; + (newChild as {parent: DebugNode}).parent = this; this.childNodes.splice(refIndex, 0, newChild); } } @@ -155,9 +165,8 @@ export class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ implements Debug } get children(): DebugElement[] { - return this - .childNodes // - .filter((node) => node instanceof DebugElement__PRE_R3__) as DebugElement[]; + return this.childNodes // + .filter((node) => node instanceof DebugElement__PRE_R3__) as DebugElement[]; } triggerEventHandler(eventName: string, eventObj: any) { @@ -205,14 +214,18 @@ function _queryNodeChildren( class DebugNode__POST_R3__ implements DebugNode { readonly nativeNode: Node; - constructor(nativeNode: Node) { this.nativeNode = nativeNode; } + constructor(nativeNode: Node) { + this.nativeNode = nativeNode; + } get parent(): DebugElement|null { const parent = this.nativeNode.parentNode as Element; return parent ? new DebugElement__POST_R3__(parent) : null; } - get injector(): Injector { return getInjector(this.nativeNode); } + get injector(): Injector { + return getInjector(this.nativeNode); + } get componentInstance(): any { const nativeElement = this.nativeNode; @@ -227,9 +240,13 @@ class DebugNode__POST_R3__ implements DebugNode { return getListeners(this.nativeNode as Element).filter(listener => listener.type === 'dom'); } - get references(): {[key: string]: any;} { return getLocalRefs(this.nativeNode); } + get references(): {[key: string]: any;} { + return getLocalRefs(this.nativeNode); + } - get providerTokens(): any[] { return getInjectionTokens(this.nativeNode as Element); } + get providerTokens(): any[] { + return getInjectionTokens(this.nativeNode as Element); + } } class DebugElement__POST_R3__ extends DebugNode__POST_R3__ implements DebugElement { @@ -244,11 +261,11 @@ class DebugElement__POST_R3__ extends DebugNode__POST_R3__ implements DebugEleme get name(): string { try { - const context = loadLContext(this.nativeNode) !; + const context = loadLContext(this.nativeNode)!; const lView = context.lView; const tData = lView[TVIEW].data; const tNode = tData[context.nodeIndex] as TNode; - return tNode.tagName !; + return tNode.tagName!; } catch (e) { return this.nativeNode.nodeName; } @@ -285,8 +302,8 @@ class DebugElement__POST_R3__ extends DebugNode__POST_R3__ implements DebugEleme return properties; } - get attributes(): {[key: string]: string | null;} { - const attributes: {[key: string]: string | null;} = {}; + get attributes(): {[key: string]: string|null;} { + const attributes: {[key: string]: string|null;} = {}; const element = this.nativeElement; if (!element) { @@ -343,9 +360,9 @@ class DebugElement__POST_R3__ extends DebugNode__POST_R3__ implements DebugEleme return attributes; } - get styles(): {[key: string]: string | null} { + get styles(): {[key: string]: string|null} { if (this.nativeElement && (this.nativeElement as HTMLElement).style) { - return (this.nativeElement as HTMLElement).style as{[key: string]: any}; + return (this.nativeElement as HTMLElement).style as {[key: string]: any}; } return {}; } @@ -438,7 +455,7 @@ class DebugElement__POST_R3__ extends DebugNode__POST_R3__ implements DebugEleme } } -function copyDomProperties(element: Element | null, properties: {[name: string]: string}): void { +function copyDomProperties(element: Element|null, properties: {[name: string]: string}): void { if (element) { // Skip own properties (as those are patched) let obj = Object.getPrototypeOf(element); @@ -481,8 +498,8 @@ function _queryAllR3( parentElement: DebugElement, predicate: Predicate, matches: DebugNode[], elementsOnly: false): void; function _queryAllR3( - parentElement: DebugElement, predicate: Predicate| Predicate, - matches: DebugElement[] | DebugNode[], elementsOnly: boolean) { + parentElement: DebugElement, predicate: Predicate|Predicate, + matches: DebugElement[]|DebugNode[], elementsOnly: boolean) { const context = loadLContext(parentElement.nativeNode, false); if (context !== null) { const parentTNode = context.lView[TVIEW].data[context.nodeIndex] as TNode; @@ -506,8 +523,8 @@ function _queryAllR3( * @param rootNativeNode the root native node on which predicate should not be matched */ function _queryNodeChildrenR3( - tNode: TNode, lView: LView, predicate: Predicate| Predicate, - matches: DebugElement[] | DebugNode[], elementsOnly: boolean, rootNativeNode: any) { + tNode: TNode, lView: LView, predicate: Predicate|Predicate, + matches: DebugElement[]|DebugNode[], elementsOnly: boolean, rootNativeNode: any) { const nativeNode = getNativeByTNodeOrNull(tNode, lView); // For each type of TNode, specific logic is executed. if (tNode.type === TNodeType.Element || tNode.type === TNodeType.ElementContainer) { @@ -520,7 +537,7 @@ function _queryNodeChildrenR3( const componentView = getComponentLViewByIndex(tNode.index, lView); if (componentView && componentView[TVIEW].firstChild) { _queryNodeChildrenR3( - componentView[TVIEW].firstChild !, componentView, predicate, matches, elementsOnly, + componentView[TVIEW].firstChild!, componentView, predicate, matches, elementsOnly, rootNativeNode); } } else { @@ -556,17 +573,17 @@ function _queryNodeChildrenR3( } else if (tNode.type === TNodeType.Projection) { // Case 3: the TNode is a projection insertion point (i.e. a ). // The nodes projected at this location all need to be processed. - const componentView = lView ![DECLARATION_COMPONENT_VIEW]; + const componentView = lView![DECLARATION_COMPONENT_VIEW]; const componentHost = componentView[T_HOST] as TElementNode; const head: TNode|null = - (componentHost.projection as(TNode | null)[])[tNode.projection as number]; + (componentHost.projection as (TNode | null)[])[tNode.projection as number]; if (Array.isArray(head)) { for (let nativeNode of head) { _addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode); } } else if (head) { - const nextLView = componentView[PARENT] !as LView; + const nextLView = componentView[PARENT]! as LView; const nextTNode = nextLView[TVIEW].data[head.index] as TNode; _queryNodeChildrenR3(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode); } @@ -596,12 +613,12 @@ function _queryNodeChildrenR3( * @param rootNativeNode the root native node on which predicate should not be matched */ function _queryNodeChildrenInContainerR3( - lContainer: LContainer, predicate: Predicate| Predicate, - matches: DebugElement[] | DebugNode[], elementsOnly: boolean, rootNativeNode: any) { + lContainer: LContainer, predicate: Predicate|Predicate, + matches: DebugElement[]|DebugNode[], elementsOnly: boolean, rootNativeNode: any) { for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) { const childView = lContainer[i]; _queryNodeChildrenR3( - childView[TVIEW].node !, childView, predicate, matches, elementsOnly, rootNativeNode); + childView[TVIEW].node!, childView, predicate, matches, elementsOnly, rootNativeNode); } } @@ -615,8 +632,8 @@ function _queryNodeChildrenInContainerR3( * @param rootNativeNode the root native node on which predicate should not be matched */ function _addQueryMatchR3( - nativeNode: any, predicate: Predicate| Predicate, - matches: DebugElement[] | DebugNode[], elementsOnly: boolean, rootNativeNode: any) { + nativeNode: any, predicate: Predicate|Predicate, + matches: DebugElement[]|DebugNode[], elementsOnly: boolean, rootNativeNode: any) { if (rootNativeNode !== nativeNode) { const debugNode = getDebugNode(nativeNode); if (!debugNode) { @@ -645,8 +662,8 @@ function _addQueryMatchR3( * @param elementsOnly whether only elements should be searched */ function _queryNativeNodeDescendants( - parentNode: any, predicate: Predicate| Predicate, - matches: DebugElement[] | DebugNode[], elementsOnly: boolean) { + parentNode: any, predicate: Predicate|Predicate, + matches: DebugElement[]|DebugNode[], elementsOnly: boolean) { const nodes = parentNode.childNodes; const length = nodes.length; @@ -757,7 +774,9 @@ export function removeDebugNodeFromIndex(node: DebugNode) { * * @publicApi */ -export interface Predicate { (value: T): boolean; } +export interface Predicate { + (value: T): boolean; +} /** * @publicApi diff --git a/packages/core/src/di/forward_ref.ts b/packages/core/src/di/forward_ref.ts index 65708c7a4dc53..e13705b91a6a0 100644 --- a/packages/core/src/di/forward_ref.ts +++ b/packages/core/src/di/forward_ref.ts @@ -21,7 +21,9 @@ import {stringify} from '../util/stringify'; * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref_fn'} * @publicApi */ -export interface ForwardRefFn { (): any; } +export interface ForwardRefFn { + (): any; +} const __forward_ref__ = getClosureSafeProperty({__forward_ref__: getClosureSafeProperty}); @@ -39,7 +41,9 @@ const __forward_ref__ = getClosureSafeProperty({__forward_ref__: getClosureSafeP */ export function forwardRef(forwardRefFn: ForwardRefFn): Type { (forwardRefFn).__forward_ref__ = forwardRef; - (forwardRefFn).toString = function() { return stringify(this()); }; + (forwardRefFn).toString = function() { + return stringify(this()); + }; return (>forwardRefFn); } diff --git a/packages/core/src/di/injectable.ts b/packages/core/src/di/injectable.ts index e6a3c10050104..fc20a2a2697a3 100644 --- a/packages/core/src/di/injectable.ts +++ b/packages/core/src/di/injectable.ts @@ -7,9 +7,9 @@ */ import {Type} from '../interface/type'; -import {TypeDecorator, makeDecorator} from '../util/decorators'; +import {makeDecorator, TypeDecorator} from '../util/decorators'; -import {InjectableType, getInjectableDef, ɵɵdefineInjectable} from './interface/defs'; +import {getInjectableDef, InjectableType, ɵɵdefineInjectable} from './interface/defs'; import {ClassSansProvider, ConstructorSansProvider, ExistingSansProvider, FactorySansProvider, StaticClassSansProvider, ValueSansProvider} from './interface/provider'; import {compileInjectable as render3CompileInjectable} from './jit/injectable'; import {convertInjectableProviderToFactory} from './util'; @@ -21,8 +21,8 @@ import {convertInjectableProviderToFactory} from './util'; * * @publicApi */ -export type InjectableProvider = ValueSansProvider | ExistingSansProvider | - StaticClassSansProvider | ConstructorSansProvider | FactorySansProvider | ClassSansProvider; +export type InjectableProvider = ValueSansProvider|ExistingSansProvider|StaticClassSansProvider| + ConstructorSansProvider|FactorySansProvider|ClassSansProvider; /** * Type of the Injectable decorator / constructor function. @@ -50,11 +50,11 @@ export interface InjectableDecorator { * */ (): TypeDecorator; - (options?: {providedIn: Type| 'root' | 'platform' | 'any' | null}& + (options?: {providedIn: Type|'root'|'platform'|'any'|null}& InjectableProvider): TypeDecorator; - new (): Injectable; - new (options?: {providedIn: Type| 'root' | 'platform' | 'any' | null}& - InjectableProvider): Injectable; + new(): Injectable; + new(options?: {providedIn: Type|'root'|'platform'|'any'|null}& + InjectableProvider): Injectable; } /** @@ -91,9 +91,9 @@ export const Injectable: InjectableDecorator = makeDecorator( /** * Supports @Injectable() in JIT mode for Render2. */ -function render2CompileInjectable(injectableType: Type, options?: { - providedIn?: Type| 'root' | 'platform' | 'any' | null -} & InjectableProvider): void { +function render2CompileInjectable( + injectableType: Type, + options?: {providedIn?: Type|'root'|'platform'|'any'|null}&InjectableProvider): void { if (options && options.providedIn !== undefined && !getInjectableDef(injectableType)) { (injectableType as InjectableType).ɵprov = ɵɵdefineInjectable({ token: injectableType, diff --git a/packages/core/src/di/injection_token.ts b/packages/core/src/di/injection_token.ts index 5a3a6feb4eed3..f45c903ce6df7 100644 --- a/packages/core/src/di/injection_token.ts +++ b/packages/core/src/di/injection_token.ts @@ -57,8 +57,7 @@ export class InjectionToken { readonly ɵprov: never|undefined; constructor(protected _desc: string, options?: { - providedIn?: Type| 'root' | 'platform' | 'any' | null, - factory: () => T + providedIn?: Type|'root'|'platform'|'any'|null, factory: () => T }) { this.ɵprov = undefined; if (typeof options == 'number') { @@ -75,7 +74,11 @@ export class InjectionToken { } } - toString(): string { return `InjectionToken ${this._desc}`; } + toString(): string { + return `InjectionToken ${this._desc}`; + } } -export interface InjectableDefToken extends InjectionToken { ɵprov: never; } +export interface InjectableDefToken extends InjectionToken { + ɵprov: never; +} diff --git a/packages/core/src/di/injector.ts b/packages/core/src/di/injector.ts index e88b36d9a4753..607b610613bfb 100644 --- a/packages/core/src/di/injector.ts +++ b/packages/core/src/di/injector.ts @@ -11,7 +11,7 @@ import {stringify} from '../util/stringify'; import {resolveForwardRef} from './forward_ref'; import {InjectionToken} from './injection_token'; -import {INJECTOR, NG_TEMP_TOKEN_PATH, NullInjector, THROW_IF_NOT_FOUND, USE_VALUE, catchInjectorError, formatError, setCurrentInjector, ɵɵinject} from './injector_compatibility'; +import {catchInjectorError, formatError, INJECTOR, NG_TEMP_TOKEN_PATH, NullInjector, setCurrentInjector, THROW_IF_NOT_FOUND, USE_VALUE, ɵɵinject} from './injector_compatibility'; import {getInjectableDef, ɵɵdefineInjectable} from './interface/defs'; import {InjectFlags} from './interface/injector'; import {ConstructorProvider, ExistingProvider, FactoryProvider, StaticClassProvider, StaticProvider, ValueProvider} from './interface/provider'; @@ -20,12 +20,12 @@ import {createInjector} from './r3_injector'; import {INJECTOR_SCOPE} from './scope'; export function INJECTOR_IMPL__PRE_R3__( - providers: StaticProvider[], parent: Injector | undefined, name: string) { + providers: StaticProvider[], parent: Injector|undefined, name: string) { return new StaticInjector(providers, parent, name); } export function INJECTOR_IMPL__POST_R3__( - providers: StaticProvider[], parent: Injector | undefined, name: string) { + providers: StaticProvider[], parent: Injector|undefined, name: string) { return createInjector({name: name}, parent, providers, name); } @@ -166,8 +166,9 @@ export class StaticInjector implements Injector { const providedIn = injectableDef && injectableDef.providedIn; if (providedIn === 'any' || providedIn != null && providedIn === this.scope) { records.set( - token, record = resolveProvider( - {provide: token, useFactory: injectableDef.factory, deps: EMPTY})); + token, + record = resolveProvider( + {provide: token, useFactory: injectableDef.factory, deps: EMPTY})); } } if (record === undefined) { @@ -193,7 +194,7 @@ export class StaticInjector implements Injector { } type SupportedProvider = - ValueProvider | ExistingProvider | StaticClassProvider | ConstructorProvider | FactoryProvider; + ValueProvider|ExistingProvider|StaticClassProvider|ConstructorProvider|FactoryProvider; interface Record { fn: Function; @@ -293,7 +294,7 @@ function recursivelyProcessProviders(records: Map, provider: Static } function tryResolveToken( - token: any, record: Record | undefined | null, records: Map, parent: Injector, + token: any, record: Record|undefined|null, records: Map, parent: Injector, notFoundValue: any, flags: InjectFlags): any { try { return resolveToken(token, record, records, parent, notFoundValue, flags); @@ -313,7 +314,7 @@ function tryResolveToken( } function resolveToken( - token: any, record: Record | undefined | null, records: Map, parent: Injector, + token: any, record: Record|undefined|null, records: Map, parent: Injector, notFoundValue: any, flags: InjectFlags): any { let value; if (record && !(flags & InjectFlags.SkipSelf)) { diff --git a/packages/core/src/di/injector_compatibility.ts b/packages/core/src/di/injector_compatibility.ts index bb420a7b23b17..2bef2aa01d486 100644 --- a/packages/core/src/di/injector_compatibility.ts +++ b/packages/core/src/di/injector_compatibility.ts @@ -33,7 +33,7 @@ import {Inject, Optional, Self, SkipSelf} from './metadata'; export const INJECTOR = new InjectionToken( 'INJECTOR', -1 as any // `-1` is used by Ivy DI system as special value to recognize it as `Injector`. - ); +); const _THROW_IF_NOT_FOUND = {}; export const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND; @@ -55,7 +55,7 @@ export const USE_VALUE = */ let _currentInjector: Injector|undefined|null = undefined; -export function setCurrentInjector(injector: Injector | null | undefined): Injector|undefined|null { +export function setCurrentInjector(injector: Injector|null|undefined): Injector|undefined|null { const former = _currentInjector; _currentInjector = injector; return former; @@ -70,25 +70,25 @@ export function setCurrentInjector(injector: Injector | null | undefined): Injec * 1. `Injector` should not depend on ivy logic. * 2. To maintain tree shake-ability we don't want to bring in unnecessary code. */ -let _injectImplementation: - ((token: Type| InjectionToken, flags?: InjectFlags) => T | null)|undefined; +let _injectImplementation: ((token: Type|InjectionToken, flags?: InjectFlags) => T | null)| + undefined; /** * Sets the current inject implementation. */ export function setInjectImplementation( - impl: ((token: Type| InjectionToken, flags?: InjectFlags) => T | null) | undefined): - ((token: Type| InjectionToken, flags?: InjectFlags) => T | null)|undefined { + impl: ((token: Type|InjectionToken, flags?: InjectFlags) => T | null)| + undefined): ((token: Type|InjectionToken, flags?: InjectFlags) => T | null)|undefined { const previous = _injectImplementation; _injectImplementation = impl; return previous; } -export function injectInjectorOnly(token: Type| InjectionToken): T; -export function injectInjectorOnly(token: Type| InjectionToken, flags?: InjectFlags): T| +export function injectInjectorOnly(token: Type|InjectionToken): T; +export function injectInjectorOnly(token: Type|InjectionToken, flags?: InjectFlags): T| null; export function injectInjectorOnly( - token: Type| InjectionToken, flags = InjectFlags.Default): T|null { + token: Type|InjectionToken, flags = InjectFlags.Default): T|null { if (_currentInjector === undefined) { throw new Error(`inject() must be called from an injection context`); } else if (_currentInjector === null) { @@ -104,15 +104,15 @@ export function injectInjectorOnly( * Must be used in the context of a factory function such as one defined for an * `InjectionToken`. Throws an error if not called from such a context. * - * (Additional documentation moved to `inject`, as it is the public API, and an alias for this instruction) + * (Additional documentation moved to `inject`, as it is the public API, and an alias for this + * instruction) * * @see inject * @codeGenApi */ -export function ɵɵinject(token: Type| InjectionToken): T; -export function ɵɵinject(token: Type| InjectionToken, flags?: InjectFlags): T|null; -export function ɵɵinject(token: Type| InjectionToken, flags = InjectFlags.Default): T| - null { +export function ɵɵinject(token: Type|InjectionToken): T; +export function ɵɵinject(token: Type|InjectionToken, flags?: InjectFlags): T|null; +export function ɵɵinject(token: Type|InjectionToken, flags = InjectFlags.Default): T|null { return (_injectImplementation || injectInjectorOnly)(resolveForwardRef(token), flags); } @@ -130,10 +130,12 @@ export function ɵɵinject(token: Type| InjectionToken, flags = InjectF */ export function ɵɵinvalidFactoryDep(index: number): never { const msg = ngDevMode ? - `This constructor is not compatible with Angular Dependency Injection because its dependency at index ${index} of the parameter list is invalid. + `This constructor is not compatible with Angular Dependency Injection because its dependency at index ${ + index} of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. -Please check that 1) the type for the parameter at index ${index} is correct and 2) the correct Angular decorators are defined for this class and its ancestors.` : +Please check that 1) the type for the parameter at index ${ + index} is correct and 2) the correct Angular decorators are defined for this class and its ancestors.` : 'invalid'; throw new Error(msg); } @@ -172,7 +174,7 @@ export const inject = ɵɵinject; * `InjectableDef`. */ export function injectRootLimpMode( - token: Type| InjectionToken, notFoundValue: T | undefined, flags: InjectFlags): T|null { + token: Type|InjectionToken, notFoundValue: T|undefined, flags: InjectFlags): T|null { const injectableDef: ɵɵInjectableDef|null = getInjectableDef(token); if (injectableDef && injectableDef.providedIn == 'root') { return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() : @@ -183,7 +185,7 @@ export function injectRootLimpMode( throw new Error(`Injector: NOT_FOUND [${stringify(token)}]`); } -export function injectArgs(types: (Type| InjectionToken| any[])[]): any[] { +export function injectArgs(types: (Type|InjectionToken|any[])[]): any[] { const args: any[] = []; for (let i = 0; i < types.length; i++) { const arg = resolveForwardRef(types[i]); @@ -210,7 +212,7 @@ export function injectArgs(types: (Type| InjectionToken| any[])[]): an } } - args.push(ɵɵinject(type !, flags)); + args.push(ɵɵinject(type!, flags)); } else { args.push(ɵɵinject(arg)); } @@ -236,7 +238,7 @@ export class NullInjector implements Injector { export function catchInjectorError( - e: any, token: any, injectorErrorName: string, source: string | null): never { + e: any, token: any, injectorErrorName: string, source: string|null): never { const tokenPath: any[] = e[NG_TEMP_TOKEN_PATH]; if (token[SOURCE]) { tokenPath.unshift(token[SOURCE]); @@ -248,7 +250,7 @@ export function catchInjectorError( } export function formatError( - text: string, obj: any, injectorErrorName: string, source: string | null = null): string { + text: string, obj: any, injectorErrorName: string, source: string|null = null): string { text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text; let context = stringify(obj); if (Array.isArray(obj)) { @@ -264,5 +266,6 @@ export function formatError( } context = `{${parts.join(', ')}}`; } - return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`; + return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${ + text.replace(NEW_LINE, '\n ')}`; } diff --git a/packages/core/src/di/interface/defs.ts b/packages/core/src/di/interface/defs.ts index f30abbdd09bc5..b2d5bae5a84f4 100644 --- a/packages/core/src/di/interface/defs.ts +++ b/packages/core/src/di/interface/defs.ts @@ -140,13 +140,14 @@ export interface InjectorTypeWithProviders { */ export function ɵɵdefineInjectable(opts: { token: unknown, - providedIn?: Type| 'root' | 'platform' | 'any' | null, - factory: () => T, + providedIn?: Type|'root'|'platform'|'any'|null, factory: () => T, }): never { return ({ - token: opts.token, providedIn: opts.providedIn as any || null, factory: opts.factory, - value: undefined, - } as ɵɵInjectableDef) as never; + token: opts.token, + providedIn: opts.providedIn as any || null, + factory: opts.factory, + value: undefined, + } as ɵɵInjectableDef) as never; } /** @@ -179,8 +180,10 @@ export const defineInjectable = ɵɵdefineInjectable; export function ɵɵdefineInjector(options: {factory: () => any, providers?: any[], imports?: any[]}): never { return ({ - factory: options.factory, providers: options.providers || [], imports: options.imports || [], - } as ɵɵInjectorDef) as never; + factory: options.factory, + providers: options.providers || [], + imports: options.imports || [], + } as ɵɵInjectorDef) as never; } /** @@ -219,15 +222,17 @@ function getOwnDefinition(type: any, def: ɵɵInjectableDef): ɵɵInjectab */ export function getInheritedInjectableDef(type: any): ɵɵInjectableDef|null { // See `jit/injectable.ts#compileInjectable` for context on NG_PROV_DEF_FALLBACK. - const def = type && (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF] || - (type[NG_PROV_DEF_FALLBACK] && type[NG_PROV_DEF_FALLBACK]())); + const def = type && + (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF] || + (type[NG_PROV_DEF_FALLBACK] && type[NG_PROV_DEF_FALLBACK]())); if (def) { const typeName = getTypeName(type); // TODO(FW-1307): Re-add ngDevMode when closure can handle it // ngDevMode && console.warn( - `DEPRECATED: DI is instantiating a token "${typeName}" that inherits its @Injectable decorator but does not provide one itself.\n` + + `DEPRECATED: DI is instantiating a token "${ + typeName}" that inherits its @Injectable decorator but does not provide one itself.\n` + `This will become an error in v10. Please add @Injectable() to the "${typeName}" class.`); return def; } else { diff --git a/packages/core/src/di/interface/provider.ts b/packages/core/src/di/interface/provider.ts index ec8720d089ac2..486ed494d0979 100644 --- a/packages/core/src/di/interface/provider.ts +++ b/packages/core/src/di/interface/provider.ts @@ -255,8 +255,8 @@ export interface FactoryProvider extends FactorySansProvider { * * @publicApi */ -export type StaticProvider = ValueProvider | ExistingProvider | StaticClassProvider | - ConstructorProvider | FactoryProvider | any[]; +export type StaticProvider = + ValueProvider|ExistingProvider|StaticClassProvider|ConstructorProvider|FactoryProvider|any[]; /** @@ -329,8 +329,8 @@ export interface ClassProvider extends ClassSansProvider { * * @publicApi */ -export type Provider = TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | - ExistingProvider | FactoryProvider | any[]; +export type Provider = TypeProvider|ValueProvider|ClassProvider|ConstructorProvider| + ExistingProvider|FactoryProvider|any[]; /** * Describes a function that is used to process provider lists (such as provider diff --git a/packages/core/src/di/jit/environment.ts b/packages/core/src/di/jit/environment.ts index d544fcc446443..a89bbf0e6901e 100644 --- a/packages/core/src/di/jit/environment.ts +++ b/packages/core/src/di/jit/environment.ts @@ -31,9 +31,9 @@ function getFactoryOf(type: Type): ((type?: Type) => T)|null { if (isForwardRef(type)) { return (() => { - const factory = getFactoryOf(resolveForwardRef(typeAny)); - return factory ? factory() : null; - }) as any; + const factory = getFactoryOf(resolveForwardRef(typeAny)); + return factory ? factory() : null; + }) as any; } const def = getInjectableDef(typeAny) || getInjectorDef(typeAny); diff --git a/packages/core/src/di/jit/injectable.ts b/packages/core/src/di/jit/injectable.ts index e8419d3a470c5..e21ab787e29cc 100644 --- a/packages/core/src/di/jit/injectable.ts +++ b/packages/core/src/di/jit/injectable.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {R3InjectableMetadataFacade, getCompilerFacade} from '../../compiler/compiler_facade'; +import {getCompilerFacade, R3InjectableMetadataFacade} from '../../compiler/compiler_facade'; import {Type} from '../../interface/type'; import {NG_FACTORY_DEF} from '../../render3/fields'; import {getClosureSafeProperty} from '../../util/property'; @@ -76,7 +76,7 @@ export function compileInjectable(type: Type, srcMeta?: Injectable): void { } } -type UseClassProvider = Injectable & ClassSansProvider & {deps?: any[]}; +type UseClassProvider = Injectable&ClassSansProvider&{deps?: any[]}; const USE_VALUE = getClosureSafeProperty({provide: String, useValue: getClosureSafeProperty}); diff --git a/packages/core/src/di/jit/util.ts b/packages/core/src/di/jit/util.ts index ae81dcb89bd59..ab0a61cd85180 100644 --- a/packages/core/src/di/jit/util.ts +++ b/packages/core/src/di/jit/util.ts @@ -7,7 +7,7 @@ */ import {ChangeDetectorRef} from '../../change_detection/change_detector_ref'; -import {CompilerFacade, R3DependencyMetadataFacade, R3ResolvedDependencyType, getCompilerFacade} from '../../compiler/compiler_facade'; +import {CompilerFacade, getCompilerFacade, R3DependencyMetadataFacade, R3ResolvedDependencyType} from '../../compiler/compiler_facade'; import {Type} from '../../interface/type'; import {ReflectionCapabilities} from '../../reflection/reflection_capabilities'; import {Attribute, Host, Inject, Optional, Self, SkipSelf} from '../metadata'; @@ -27,7 +27,7 @@ export function convertDependencies(deps: any[]): R3DependencyMetadataFacade[] { return deps.map(dep => reflectDependency(compiler, dep)); } -function reflectDependency(compiler: CompilerFacade, dep: any | any[]): R3DependencyMetadataFacade { +function reflectDependency(compiler: CompilerFacade, dep: any|any[]): R3DependencyMetadataFacade { const meta: R3DependencyMetadataFacade = { token: null, host: false, diff --git a/packages/core/src/di/metadata.ts b/packages/core/src/di/metadata.ts index c572f235342a6..b29c5b4ac0653 100644 --- a/packages/core/src/di/metadata.ts +++ b/packages/core/src/di/metadata.ts @@ -33,7 +33,7 @@ export interface InjectDecorator { * */ (token: any): any; - new (token: any): Inject; + new(token: any): Inject; } /** @@ -82,7 +82,7 @@ export interface OptionalDecorator { * */ (): any; - new (): Optional; + new(): Optional; } /** @@ -128,7 +128,7 @@ export interface SelfDecorator { * */ (): any; - new (): Self; + new(): Self; } /** @@ -175,7 +175,7 @@ export interface SkipSelfDecorator { * */ (): any; - new (): SkipSelf; + new(): SkipSelf; } /** @@ -215,7 +215,7 @@ export interface HostDecorator { * */ (): any; - new (): Host; + new(): Host; } /** @@ -262,7 +262,7 @@ export interface AttributeDecorator { * */ (name: string): any; - new (name: string): Attribute; + new(name: string): Attribute; } /** diff --git a/packages/core/src/di/r3_injector.ts b/packages/core/src/di/r3_injector.ts index 10fc23852cc5b..bbe401037c4a4 100644 --- a/packages/core/src/di/r3_injector.ts +++ b/packages/core/src/di/r3_injector.ts @@ -15,11 +15,12 @@ import {throwCyclicDependencyError, throwInvalidProviderError, throwMixedMultiPr import {FactoryFn} from '../render3/interfaces/definition'; import {deepForEach, newArray} from '../util/array_utils'; import {stringify} from '../util/stringify'; + import {resolveForwardRef} from './forward_ref'; import {InjectionToken} from './injection_token'; import {Injector} from './injector'; -import {INJECTOR, NG_TEMP_TOKEN_PATH, NullInjector, THROW_IF_NOT_FOUND, USE_VALUE, catchInjectorError, injectArgs, setCurrentInjector, ɵɵinject} from './injector_compatibility'; -import {InjectorType, InjectorTypeWithProviders, getInheritedInjectableDef, getInjectableDef, getInjectorDef, ɵɵInjectableDef} from './interface/defs'; +import {catchInjectorError, injectArgs, INJECTOR, NG_TEMP_TOKEN_PATH, NullInjector, setCurrentInjector, THROW_IF_NOT_FOUND, USE_VALUE, ɵɵinject} from './injector_compatibility'; +import {getInheritedInjectableDef, getInjectableDef, getInjectorDef, InjectorType, InjectorTypeWithProviders, ɵɵInjectableDef} from './interface/defs'; import {InjectFlags} from './interface/injector'; import {ClassProvider, ConstructorProvider, ExistingProvider, FactoryProvider, StaticClassProvider, StaticProvider, TypeProvider, ValueProvider} from './interface/provider'; import {INJECTOR_SCOPE} from './scope'; @@ -29,8 +30,8 @@ import {INJECTOR_SCOPE} from './scope'; /** * Internal type for a single provider in a deep provider array. */ -type SingleProvider = TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | - ExistingProvider | FactoryProvider | StaticClassProvider; +type SingleProvider = TypeProvider|ValueProvider|ClassProvider|ConstructorProvider|ExistingProvider| + FactoryProvider|StaticClassProvider; /** * Marker which indicates that a value has not yet been created from the factory function. @@ -76,8 +77,8 @@ interface Record { * @publicApi */ export function createInjector( - defType: /* InjectorType */ any, parent: Injector | null = null, - additionalProviders: StaticProvider[] | null = null, name?: string): Injector { + defType: /* InjectorType */ any, parent: Injector|null = null, + additionalProviders: StaticProvider[]|null = null, name?: string): Injector { const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name); injector._resolveInjectorDefTypes(); @@ -90,8 +91,8 @@ export function createInjector( * should be resolved at a later point by calling `_resolveInjectorDefTypes`. */ export function createInjectorWithoutInjectorInstances( - defType: /* InjectorType */ any, parent: Injector | null = null, - additionalProviders: StaticProvider[] | null = null, name?: string): R3Injector { + defType: /* InjectorType */ any, parent: Injector|null = null, + additionalProviders: StaticProvider[]|null = null, name?: string): R3Injector { return new R3Injector(defType, additionalProviders, parent || getNullInjector(), name); } @@ -124,7 +125,9 @@ export class R3Injector { /** * Flag indicating that this injector was previously destroyed. */ - get destroyed(): boolean { return this._destroyed; } + get destroyed(): boolean { + return this._destroyed; + } private _destroyed = false; constructor( @@ -135,9 +138,10 @@ export class R3Injector { // Start off by creating Records for every provider declared in every InjectorType // included transitively in additional providers then do the same for `def`. This order is // important because `def` may include providers that override ones in additionalProviders. - additionalProviders && deepForEach( - additionalProviders, provider => this.processProvider( - provider, def, additionalProviders)); + additionalProviders && + deepForEach( + additionalProviders, + provider => this.processProvider(provider, def, additionalProviders)); deepForEach([def], injectorDef => this.processInjectorType(injectorDef, [], dedupStack)); @@ -235,7 +239,9 @@ export class R3Injector { } /** @internal */ - _resolveInjectorDefTypes() { this.injectorDefTypes.forEach(defType => this.get(defType)); } + _resolveInjectorDefTypes() { + this.injectorDefTypes.forEach(defType => this.get(defType)); + } toString() { const tokens = [], records = this.records; @@ -285,8 +291,8 @@ export class R3Injector { // Check for circular dependencies. if (ngDevMode && parents.indexOf(defType) !== -1) { const defName = stringify(defType); - throw new Error( - `Circular dependency in DI detected for type ${defName}. Dependency path: ${parents.map(defType => stringify(defType)).join(' > ')} > ${defName}.`); + throw new Error(`Circular dependency in DI detected for type ${defName}. Dependency path: ${ + parents.map(defType => stringify(defType)).join(' > ')} > ${defName}.`); } // Check for multiple imports of the same module @@ -335,7 +341,7 @@ export class R3Injector { for (let i = 0; i < importTypesWithProviders.length; i++) { const {ngModule, providers} = importTypesWithProviders[i]; deepForEach( - providers !, + providers!, provider => this.processProvider(provider, ngModule, providers || EMPTY_ARRAY)); } } @@ -383,11 +389,11 @@ export class R3Injector { } } else { multiRecord = makeRecord(undefined, NOT_YET, true); - multiRecord.factory = () => injectArgs(multiRecord !.multi !); + multiRecord.factory = () => injectArgs(multiRecord!.multi!); this.records.set(token, multiRecord); } token = provider; - multiRecord.multi !.push(provider); + multiRecord.multi!.push(provider); } else { const existing = this.records.get(token); if (existing && existing.multi !== undefined) { @@ -402,7 +408,7 @@ export class R3Injector { throwCyclicDependencyError(stringify(token)); } else if (record.value === NOT_YET) { record.value = CIRCULAR; - record.value = record.factory !(); + record.value = record.factory!(); } if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) { this.onDestroy.add(record.value); @@ -421,7 +427,7 @@ export class R3Injector { } } -function injectableDefOrInjectorDefFactory(token: Type| InjectionToken): FactoryFn { +function injectableDefOrInjectorDefFactory(token: Type|InjectionToken): FactoryFn { // Most tokens will have an injectable def directly on them, which specifies a factory directly. const injectableDef = getInjectableDef(token); const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token); @@ -519,7 +525,7 @@ export function providerToFactory( } function makeRecord( - factory: (() => T) | undefined, value: T | {}, multi: boolean = false): Record { + factory: (() => T)|undefined, value: T|{}, multi: boolean = false): Record { return { factory: factory, value: value, @@ -547,14 +553,14 @@ export function isClassProvider(value: SingleProvider): value is ClassProvider { return !!(value as StaticClassProvider | ClassProvider).useClass; } -function hasDeps(value: ClassProvider | ConstructorProvider | StaticClassProvider): - value is ClassProvider&{deps: any[]} { +function hasDeps(value: ClassProvider|ConstructorProvider| + StaticClassProvider): value is ClassProvider&{deps: any[]} { return !!(value as any).deps; } function hasOnDestroy(value: any): value is OnDestroy { return value !== null && typeof value === 'object' && - typeof(value as OnDestroy).ngOnDestroy === 'function'; + typeof (value as OnDestroy).ngOnDestroy === 'function'; } function couldBeInjectableType(value: any): value is Type|InjectionToken { diff --git a/packages/core/src/di/reflective_errors.ts b/packages/core/src/di/reflective_errors.ts index 584b863fedf0e..4a45534f46912 100644 --- a/packages/core/src/di/reflective_errors.ts +++ b/packages/core/src/di/reflective_errors.ts @@ -143,7 +143,8 @@ export function instantiationError( key: ReflectiveKey): InjectionError { return injectionError(injector, key, function(keys: ReflectiveKey[]) { const first = stringify(keys[0].token); - return `${originalException.message}: Error during instantiation of ${first}!${constructResolvingPath(keys)}.`; + return `${originalException.message}: Error during instantiation of ${first}!${ + constructResolvingPath(keys)}.`; }, originalException); } @@ -193,7 +194,7 @@ export function invalidProviderError(provider: any) { * ``` * */ -export function noAnnotationError(typeOrFunc: Type| Function, params: any[][]): Error { +export function noAnnotationError(typeOrFunc: Type|Function, params: any[][]): Error { const signature: string[] = []; for (let i = 0, ii = params.length; i < ii; i++) { const parameter = params[i]; diff --git a/packages/core/src/di/reflective_injector.ts b/packages/core/src/di/reflective_injector.ts index 6b979b8f4df41..c6c5d30a78cd4 100644 --- a/packages/core/src/di/reflective_injector.ts +++ b/packages/core/src/di/reflective_injector.ts @@ -308,7 +308,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector { createChildFromResolved(providers: ResolvedReflectiveProvider[]): ReflectiveInjector { const inj = new ReflectiveInjector_(providers); - (inj as{parent: Injector | null}).parent = this; + (inj as {parent: Injector | null}).parent = this; return inj; } @@ -335,7 +335,9 @@ export class ReflectiveInjector_ implements ReflectiveInjector { return this._instantiateProvider(provider); } - private _getMaxNumberOfObjects(): number { return this.objs.length; } + private _getMaxNumberOfObjects(): number { + return this.objs.length; + } private _instantiateProvider(provider: ResolvedReflectiveProvider): any { if (provider.multiProvider) { @@ -451,7 +453,9 @@ export class ReflectiveInjector_ implements ReflectiveInjector { return `ReflectiveInjector(providers: [${providers}])`; } - toString(): string { return this.displayName; } + toString(): string { + return this.displayName; + } } function _mapProviders(injector: ReflectiveInjector_, fn: Function): any[] { diff --git a/packages/core/src/di/reflective_key.ts b/packages/core/src/di/reflective_key.ts index f7219f60f57d0..6de91cad9bcb2 100644 --- a/packages/core/src/di/reflective_key.ts +++ b/packages/core/src/di/reflective_key.ts @@ -50,7 +50,9 @@ export class ReflectiveKey { /** * @returns the number of keys registered in the system. */ - static get numberOfKeys(): number { return _globalKeyRegistry.numberOfKeys; } + static get numberOfKeys(): number { + return _globalKeyRegistry.numberOfKeys; + } } export class KeyRegistry { @@ -60,7 +62,7 @@ export class KeyRegistry { if (token instanceof ReflectiveKey) return token; if (this._allKeys.has(token)) { - return this._allKeys.get(token) !; + return this._allKeys.get(token)!; } const newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys); @@ -68,7 +70,9 @@ export class KeyRegistry { return newKey; } - get numberOfKeys(): number { return this._allKeys.size; } + get numberOfKeys(): number { + return this._allKeys.size; + } } const _globalKeyRegistry = new KeyRegistry(); diff --git a/packages/core/src/di/reflective_provider.ts b/packages/core/src/di/reflective_provider.ts index 11ff4445552b9..c794bfb878d27 100644 --- a/packages/core/src/di/reflective_provider.ts +++ b/packages/core/src/di/reflective_provider.ts @@ -18,7 +18,7 @@ import {ReflectiveKey} from './reflective_key'; interface NormalizedProvider extends TypeProvider, ValueProvider, ClassProvider, ExistingProvider, - FactoryProvider {} + FactoryProvider {} /** * `Dependency` is used by the framework to extend DI. @@ -184,7 +184,7 @@ function _normalizeProviders( providers: Provider[], res: NormalizedProvider[]): NormalizedProvider[] { providers.forEach(b => { if (b instanceof Type) { - res.push({ provide: b, useClass: b } as NormalizedProvider); + res.push({provide: b, useClass: b} as NormalizedProvider); } else if (b && typeof b == 'object' && (b as any).provide !== undefined) { res.push(b as NormalizedProvider); @@ -221,7 +221,7 @@ function _dependenciesFor(typeOrFunc: any): ReflectiveDependency[] { } function _extractToken( - typeOrFunc: any, metadata: any[] | any, params: any[][]): ReflectiveDependency { + typeOrFunc: any, metadata: any[]|any, params: any[][]): ReflectiveDependency { let token: any = null; let optional = false; @@ -264,6 +264,6 @@ function _extractToken( } function _createDependency( - token: any, optional: boolean, visibility: Self | SkipSelf | null): ReflectiveDependency { + token: any, optional: boolean, visibility: Self|SkipSelf|null): ReflectiveDependency { return new ReflectiveDependency(ReflectiveKey.get(token), optional, visibility); } diff --git a/packages/core/src/di/util.ts b/packages/core/src/di/util.ts index 32b5bc595365a..dd5bf2c0aed8e 100644 --- a/packages/core/src/di/util.ts +++ b/packages/core/src/di/util.ts @@ -19,8 +19,9 @@ const USE_VALUE = const EMPTY_ARRAY: any[] = []; export function convertInjectableProviderToFactory( - type: Type, provider?: ValueSansProvider | ExistingSansProvider | StaticClassSansProvider | - ConstructorSansProvider | FactorySansProvider | ClassSansProvider): () => any { + type: Type, + provider?: ValueSansProvider|ExistingSansProvider|StaticClassSansProvider| + ConstructorSansProvider|FactorySansProvider|ClassSansProvider): () => any { if (!provider) { const reflectionCapabilities = new ReflectionCapabilities(); const deps = reflectionCapabilities.parameters(type); @@ -51,6 +52,6 @@ export function convertInjectableProviderToFactory( const reflectionCapabilities = new ReflectionCapabilities(); deps = reflectionCapabilities.parameters(type); } - return () => new type(...injectArgs(deps !)); + return () => new type(...injectArgs(deps!)); } } diff --git a/packages/core/src/event_emitter.ts b/packages/core/src/event_emitter.ts index 07143d9774a9e..02397f378d62e 100644 --- a/packages/core/src/event_emitter.ts +++ b/packages/core/src/event_emitter.ts @@ -83,7 +83,9 @@ export class EventEmitter extends Subject { * Emits an event containing a given value. * @param value The value to emit. */ - emit(value?: T) { super.next(value); } + emit(value?: T) { + super.next(value); + } /** * Registers handlers for events emitted by this instance. @@ -101,29 +103,46 @@ export class EventEmitter extends Subject { if (generatorOrNext && typeof generatorOrNext === 'object') { schedulerFn = this.__isAsync ? (value: any) => { setTimeout(() => generatorOrNext.next(value)); - } : (value: any) => { generatorOrNext.next(value); }; + } : (value: any) => { + generatorOrNext.next(value); + }; if (generatorOrNext.error) { - errorFn = this.__isAsync ? (err) => { setTimeout(() => generatorOrNext.error(err)); } : - (err) => { generatorOrNext.error(err); }; + errorFn = this.__isAsync ? (err) => { + setTimeout(() => generatorOrNext.error(err)); + } : (err) => { + generatorOrNext.error(err); + }; } if (generatorOrNext.complete) { - completeFn = this.__isAsync ? () => { setTimeout(() => generatorOrNext.complete()); } : - () => { generatorOrNext.complete(); }; + completeFn = this.__isAsync ? () => { + setTimeout(() => generatorOrNext.complete()); + } : () => { + generatorOrNext.complete(); + }; } } else { - schedulerFn = this.__isAsync ? (value: any) => { setTimeout(() => generatorOrNext(value)); } : - (value: any) => { generatorOrNext(value); }; + schedulerFn = this.__isAsync ? (value: any) => { + setTimeout(() => generatorOrNext(value)); + } : (value: any) => { + generatorOrNext(value); + }; if (error) { - errorFn = - this.__isAsync ? (err) => { setTimeout(() => error(err)); } : (err) => { error(err); }; + errorFn = this.__isAsync ? (err) => { + setTimeout(() => error(err)); + } : (err) => { + error(err); + }; } if (complete) { - completeFn = - this.__isAsync ? () => { setTimeout(() => complete()); } : () => { complete(); }; + completeFn = this.__isAsync ? () => { + setTimeout(() => complete()); + } : () => { + complete(); + }; } } diff --git a/packages/core/src/i18n/locale_data_api.ts b/packages/core/src/i18n/locale_data_api.ts index 63816bba38eea..75c9082080054 100644 --- a/packages/core/src/i18n/locale_data_api.ts +++ b/packages/core/src/i18n/locale_data_api.ts @@ -5,9 +5,10 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import localeEn from './locale_en'; import {global} from '../util/global'; +import localeEn from './locale_en'; + /** * This const is used to store the locale data registered with `registerLocaleData` */ @@ -19,7 +20,7 @@ let LOCALE_DATA: {[localeId: string]: any} = {}; * * The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1 */ -export function registerLocaleData(data: any, localeId?: string | any, extraData?: any): void { +export function registerLocaleData(data: any, localeId?: string|any, extraData?: any): void { if (typeof localeId !== 'string') { extraData = localeId; localeId = data[LocaleDataIndex.LocaleId]; @@ -151,7 +152,11 @@ export const enum ExtraLocaleDataIndex { /** * Index of each value in currency data (used to describe CURRENCIES_EN in currencies.ts) */ -export const enum CurrencyIndex {Symbol = 0, SymbolNarrow, NbOfDigits} +export const enum CurrencyIndex { + Symbol = 0, + SymbolNarrow, + NbOfDigits +} /** * Returns the canonical form of a locale name - lowercase with `_` replaced with `-`. diff --git a/packages/core/src/interface/lifecycle_hooks.ts b/packages/core/src/interface/lifecycle_hooks.ts index 0beb6d97086eb..45414583a9397 100644 --- a/packages/core/src/interface/lifecycle_hooks.ts +++ b/packages/core/src/interface/lifecycle_hooks.ts @@ -90,12 +90,12 @@ export interface OnInit { */ export interface DoCheck { /** - * A callback method that performs change-detection, invoked - * after the default change-detector runs. - * See `KeyValueDiffers` and `IterableDiffers` for implementing - * custom change checking for collections. - * - */ + * A callback method that performs change-detection, invoked + * after the default change-detector runs. + * See `KeyValueDiffers` and `IterableDiffers` for implementing + * custom change checking for collections. + * + */ ngDoCheck(): void; } diff --git a/packages/core/src/interface/simple_change.ts b/packages/core/src/interface/simple_change.ts index 6152cbd7ad506..081967868e54f 100644 --- a/packages/core/src/interface/simple_change.ts +++ b/packages/core/src/interface/simple_change.ts @@ -20,7 +20,9 @@ export class SimpleChange { /** * Check whether the new value is the first value assigned. */ - isFirstChange(): boolean { return this.firstChange; } + isFirstChange(): boolean { + return this.firstChange; + } } /** @@ -32,4 +34,6 @@ export class SimpleChange { * * @publicApi */ -export interface SimpleChanges { [propName: string]: SimpleChange; } +export interface SimpleChanges { + [propName: string]: SimpleChange; +} diff --git a/packages/core/src/interface/type.ts b/packages/core/src/interface/type.ts index e8b0188042593..a8c3f6a51be09 100644 --- a/packages/core/src/interface/type.ts +++ b/packages/core/src/interface/type.ts @@ -30,11 +30,15 @@ export function isType(v: any): v is Type { * * @publicApi */ -export interface AbstractType extends Function { prototype: T; } +export interface AbstractType extends Function { + prototype: T; +} -export interface Type extends Function { new (...args: any[]): T; } +export interface Type extends Function { + new(...args: any[]): T; +} -export type Mutable = { +export type Mutable = { [P in K]: T[P]; }; diff --git a/packages/core/src/linker.ts b/packages/core/src/linker.ts index b3b25b222ece8..4e34360e945f3 100644 --- a/packages/core/src/linker.ts +++ b/packages/core/src/linker.ts @@ -7,12 +7,12 @@ */ // Public API for compiler -export {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, ModuleWithComponentFactories} from './linker/compiler'; +export {Compiler, COMPILER_OPTIONS, CompilerFactory, CompilerOptions, ModuleWithComponentFactories} from './linker/compiler'; export {ComponentFactory, ComponentRef} from './linker/component_factory'; export {ComponentFactoryResolver} from './linker/component_factory_resolver'; export {ElementRef} from './linker/element_ref'; export {NgModuleFactory, NgModuleRef} from './linker/ng_module_factory'; -export {NgModuleFactoryLoader, getModuleFactory} from './linker/ng_module_factory_loader'; +export {getModuleFactory, NgModuleFactoryLoader} from './linker/ng_module_factory_loader'; export {QueryList} from './linker/query_list'; export {SystemJsNgModuleLoader, SystemJsNgModuleLoaderConfig} from './linker/system_js_ng_module_factory_loader'; export {TemplateRef} from './linker/template_ref'; diff --git a/packages/core/src/linker/compiler.ts b/packages/core/src/linker/compiler.ts index c6ad53f774d96..8d063b5e44834 100644 --- a/packages/core/src/linker/compiler.ts +++ b/packages/core/src/linker/compiler.ts @@ -60,7 +60,7 @@ export const Compiler_compileModuleAndAllComponentsSync__POST_R3__: (moduleTy ModuleWithComponentFactories = function(moduleType: Type): ModuleWithComponentFactories { const ngModuleFactory = Compiler_compileModuleSync__POST_R3__(moduleType); - const moduleDef = getNgModuleDef(moduleType) !; + const moduleDef = getNgModuleDef(moduleType)!; const componentFactories = maybeUnwrapFn(moduleDef.declarations) .reduce((factories: ComponentFactory[], declaration: Type) => { @@ -133,7 +133,9 @@ export class Compiler { /** * Returns the id for a given NgModule, if one is defined and known to the compiler. */ - getModuleId(moduleType: Type): string|undefined { return undefined; } + getModuleId(moduleType: Type): string|undefined { + return undefined; + } } /** diff --git a/packages/core/src/linker/component_factory_resolver.ts b/packages/core/src/linker/component_factory_resolver.ts index 90cdd073cf960..6d84307ddd9fb 100644 --- a/packages/core/src/linker/component_factory_resolver.ts +++ b/packages/core/src/linker/component_factory_resolver.ts @@ -14,8 +14,8 @@ import {ComponentFactory, ComponentRef} from './component_factory'; import {NgModuleRef} from './ng_module_factory'; export function noComponentFactoryError(component: Function) { - const error = Error( - `No component factory found for ${stringify(component)}. Did you add it to @NgModule.entryComponents?`); + const error = Error(`No component factory found for ${ + stringify(component)}. Did you add it to @NgModule.entryComponents?`); (error as any)[ERROR_COMPONENT] = component; return error; } @@ -28,7 +28,7 @@ export function getComponent(error: Error): Type { class _NullComponentFactoryResolver implements ComponentFactoryResolver { - resolveComponentFactory(component: {new (...args: any[]): T}): ComponentFactory { + resolveComponentFactory(component: {new(...args: any[]): T}): ComponentFactory { throw noComponentFactoryError(component); } } @@ -63,7 +63,7 @@ export class CodegenComponentFactoryResolver implements ComponentFactoryResolver } } - resolveComponentFactory(component: {new (...args: any[]): T}): ComponentFactory { + resolveComponentFactory(component: {new(...args: any[]): T}): ComponentFactory { let factory = this._factories.get(component); if (!factory && this._parent) { factory = this._parent.resolveComponentFactory(component); diff --git a/packages/core/src/linker/element_ref.ts b/packages/core/src/linker/element_ref.ts index 81eb088558b18..c357e307a33d3 100644 --- a/packages/core/src/linker/element_ref.ts +++ b/packages/core/src/linker/element_ref.ts @@ -48,7 +48,9 @@ export class ElementRef { */ public nativeElement: T; - constructor(nativeElement: T) { this.nativeElement = nativeElement; } + constructor(nativeElement: T) { + this.nativeElement = nativeElement; + } /** * @internal diff --git a/packages/core/src/linker/ng_module_factory_loader.ts b/packages/core/src/linker/ng_module_factory_loader.ts index 2f6f710c6e08b..717a3ab8821d5 100644 --- a/packages/core/src/linker/ng_module_factory_loader.ts +++ b/packages/core/src/linker/ng_module_factory_loader.ts @@ -43,6 +43,8 @@ export function getModuleFactory__POST_R3__(id: string): NgModuleFactory { */ export const getModuleFactory: (id: string) => NgModuleFactory = getModuleFactory__PRE_R3__; -function noModuleError(id: string, ): Error { +function noModuleError( + id: string, + ): Error { return new Error(`No module with ID ${id} loaded`); } diff --git a/packages/core/src/linker/ng_module_factory_registration.ts b/packages/core/src/linker/ng_module_factory_registration.ts index 3008d8434a825..639a772fb6e91 100644 --- a/packages/core/src/linker/ng_module_factory_registration.ts +++ b/packages/core/src/linker/ng_module_factory_registration.ts @@ -32,7 +32,7 @@ export function registerModuleFactory(id: string, factory: NgModuleFactory) modules.set(id, factory); } -function assertSameOrNotExisting(id: string, type: Type| null, incoming: Type): void { +function assertSameOrNotExisting(id: string, type: Type|null, incoming: Type): void { if (type && type !== incoming) { throw new Error( `Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`); diff --git a/packages/core/src/linker/query_list.ts b/packages/core/src/linker/query_list.ts index f89d35cd42200..855ad74c3e9c9 100644 --- a/packages/core/src/linker/query_list.ts +++ b/packages/core/src/linker/query_list.ts @@ -13,7 +13,7 @@ import {flatten} from '../util/array_utils'; import {getSymbolIterator} from '../util/symbol'; function symbolIterator(this: QueryList): Iterator { - return ((this as any as{_results: Array})._results as any)[getSymbolIterator()](); + return ((this as any as {_results: Array})._results as any)[getSymbolIterator()](); } /** @@ -49,9 +49,9 @@ export class QueryList implements Iterable { readonly length: number = 0; // TODO(issue/24571): remove '!'. - readonly first !: T; + readonly first!: T; // TODO(issue/24571): remove '!'. - readonly last !: T; + readonly last!: T; constructor() { // This function should be declared on the prototype, but doing so there will cause the class @@ -67,7 +67,9 @@ export class QueryList implements Iterable { * See * [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) */ - map(fn: (item: T, index: number, array: T[]) => U): U[] { return this._results.map(fn); } + map(fn: (item: T, index: number, array: T[]) => U): U[] { + return this._results.map(fn); + } /** * See @@ -97,7 +99,9 @@ export class QueryList implements Iterable { * See * [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) */ - forEach(fn: (item: T, index: number, array: T[]) => void): void { this._results.forEach(fn); } + forEach(fn: (item: T, index: number, array: T[]) => void): void { + this._results.forEach(fn); + } /** * See @@ -110,9 +114,13 @@ export class QueryList implements Iterable { /** * Returns a copy of the internal results list as an Array. */ - toArray(): T[] { return this._results.slice(); } + toArray(): T[] { + return this._results.slice(); + } - toString(): string { return this._results.toString(); } + toString(): string { + return this._results.toString(); + } /** * Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that @@ -123,19 +131,23 @@ export class QueryList implements Iterable { */ reset(resultsTree: Array): void { this._results = flatten(resultsTree); - (this as{dirty: boolean}).dirty = false; - (this as{length: number}).length = this._results.length; - (this as{last: T}).last = this._results[this.length - 1]; - (this as{first: T}).first = this._results[0]; + (this as {dirty: boolean}).dirty = false; + (this as {length: number}).length = this._results.length; + (this as {last: T}).last = this._results[this.length - 1]; + (this as {first: T}).first = this._results[0]; } /** * Triggers a change event by emitting on the `changes` {@link EventEmitter}. */ - notifyOnChanges(): void { (this.changes as EventEmitter).emit(this); } + notifyOnChanges(): void { + (this.changes as EventEmitter).emit(this); + } /** internal */ - setDirty() { (this as{dirty: boolean}).dirty = true; } + setDirty() { + (this as {dirty: boolean}).dirty = true; + } /** internal */ destroy(): void { @@ -148,5 +160,5 @@ export class QueryList implements Iterable { // there) and this declaration is left here to ensure that TypeScript considers QueryList to // implement the Iterable interface. This is required for template type-checking of NgFor loops // over QueryLists to work correctly, since QueryList must be assignable to NgIterable. - [Symbol.iterator] !: () => Iterator; + [Symbol.iterator]!: () => Iterator; } diff --git a/packages/core/src/linker/system_js_ng_module_factory_loader.ts b/packages/core/src/linker/system_js_ng_module_factory_loader.ts index 6221d6733377c..9b0075807c588 100644 --- a/packages/core/src/linker/system_js_ng_module_factory_loader.ts +++ b/packages/core/src/linker/system_js_ng_module_factory_loader.ts @@ -32,13 +32,13 @@ export abstract class SystemJsNgModuleLoaderConfig { * Prefix to add when computing the name of the factory module for a given module name. */ // TODO(issue/24571): remove '!'. - factoryPathPrefix !: string; + factoryPathPrefix!: string; /** * Suffix to add when computing the name of the factory module for a given module name. */ // TODO(issue/24571): remove '!'. - factoryPathSuffix !: string; + factoryPathSuffix!: string; } const DEFAULT_CONFIG: SystemJsNgModuleLoaderConfig = { diff --git a/packages/core/src/metadata/di.ts b/packages/core/src/metadata/di.ts index 3702f4e60b8af..fd7c10b799df1 100644 --- a/packages/core/src/metadata/di.ts +++ b/packages/core/src/metadata/di.ts @@ -75,7 +75,7 @@ export interface AttributeDecorator { * @publicApi */ (name: string): any; - new (name: string): Attribute; + new(name: string): Attribute; } @@ -158,7 +158,7 @@ export interface ContentChildrenDecorator { * @Annotation */ (selector: Type|Function|string, opts?: {descendants?: boolean, read?: any}): any; - new (selector: Type|Function|string, opts?: {descendants?: boolean, read?: any}): Query; + new(selector: Type|Function|string, opts?: {descendants?: boolean, read?: any}): Query; } /** @@ -219,7 +219,7 @@ export interface ContentChildDecorator { * @Annotation */ (selector: Type|Function|string, opts?: {read?: any, static?: boolean}): any; - new (selector: Type|Function|string, opts?: {read?: any, static?: boolean}): ContentChild; + new(selector: Type|Function|string, opts?: {read?: any, static?: boolean}): ContentChild; } /** @@ -238,8 +238,9 @@ export type ContentChild = Query; * @publicApi */ export const ContentChild: ContentChildDecorator = makePropDecorator( - 'ContentChild', (selector?: any, data: any = {}) => - ({selector, first: true, isViewQuery: false, descendants: true, ...data}), + 'ContentChild', + (selector?: any, data: any = {}) => + ({selector, first: true, isViewQuery: false, descendants: true, ...data}), Query); /** @@ -275,7 +276,7 @@ export interface ViewChildrenDecorator { * @Annotation */ (selector: Type|Function|string, opts?: {read?: any}): any; - new (selector: Type|Function|string, opts?: {read?: any}): ViewChildren; + new(selector: Type|Function|string, opts?: {read?: any}): ViewChildren; } /** @@ -292,8 +293,9 @@ export type ViewChildren = Query; * @publicApi */ export const ViewChildren: ViewChildrenDecorator = makePropDecorator( - 'ViewChildren', (selector?: any, data: any = {}) => - ({selector, first: false, isViewQuery: true, descendants: true, ...data}), + 'ViewChildren', + (selector?: any, data: any = {}) => + ({selector, first: false, isViewQuery: true, descendants: true, ...data}), Query); /** @@ -342,7 +344,7 @@ export interface ViewChildDecorator { * @Annotation */ (selector: Type|Function|string, opts?: {read?: any, static?: boolean}): any; - new (selector: Type|Function|string, opts?: {read?: any, static?: boolean}): ViewChild; + new(selector: Type|Function|string, opts?: {read?: any, static?: boolean}): ViewChild; } /** @@ -359,6 +361,7 @@ export type ViewChild = Query; * @publicApi */ export const ViewChild: ViewChildDecorator = makePropDecorator( - 'ViewChild', (selector: any, data: any) => - ({selector, first: true, isViewQuery: true, descendants: true, ...data}), + 'ViewChild', + (selector: any, data: any) => + ({selector, first: true, isViewQuery: true, descendants: true, ...data}), Query); diff --git a/packages/core/src/metadata/directives.ts b/packages/core/src/metadata/directives.ts index 08646edc27fbc..74cda20f57def 100644 --- a/packages/core/src/metadata/directives.ts +++ b/packages/core/src/metadata/directives.ts @@ -11,7 +11,7 @@ import {Provider} from '../di'; import {Type} from '../interface/type'; import {compileComponent as render3CompileComponent, compileDirective as render3CompileDirective} from '../render3/jit/directive'; import {compilePipe as render3CompilePipe} from '../render3/jit/pipe'; -import {TypeDecorator, makeDecorator, makePropDecorator} from '../util/decorators'; +import {makeDecorator, makePropDecorator, TypeDecorator} from '../util/decorators'; import {noop} from '../util/noop'; import {ViewEncapsulation} from './view'; @@ -73,7 +73,7 @@ export interface DirectiveDecorator { /** * See the `Directive` decorator. */ - new (obj?: Directive): Directive; + new(obj?: Directive): Directive; } /** @@ -445,7 +445,7 @@ export interface ComponentDecorator { /** * See the `Component` decorator. */ - new (obj: Component): Component; + new(obj: Component): Component; } /** @@ -598,7 +598,7 @@ export interface PipeDecorator { /** * See the `Pipe` decorator. */ - new (obj: Pipe): Pipe; + new(obj: Pipe): Pipe; } /** @@ -641,52 +641,52 @@ export const Pipe: PipeDecorator = makeDecorator( */ export interface InputDecorator { /** - * Decorator that marks a class field as an input property and supplies configuration metadata. - * The input property is bound to a DOM property in the template. During change detection, - * Angular automatically updates the data property with the DOM property's value. - * - * @usageNotes - * - * You can supply an optional name to use in templates when the - * component is instantiated, that maps to the - * name of the bound property. By default, the original - * name of the bound property is used for input binding. - * - * The following example creates a component with two input properties, - * one of which is given a special binding name. - * - * ```typescript - * @Component({ - * selector: 'bank-account', - * template: ` - * Bank Name: {{bankName}} - * Account Id: {{id}} - * ` - * }) - * class BankAccount { - * // This property is bound using its original name. - * @Input() bankName: string; - * // this property value is bound to a different property name - * // when this component is instantiated in a template. - * @Input('account-id') id: string; - * - * // this property is not bound, and is not automatically updated by Angular - * normalizedBankName: string; - * } - * - * @Component({ - * selector: 'app', - * template: ` - * - * ` - * }) - * class App {} - * ``` - * - * @see [Input and Output properties](guide/template-syntax#input-and-output-properties) - */ + * Decorator that marks a class field as an input property and supplies configuration metadata. + * The input property is bound to a DOM property in the template. During change detection, + * Angular automatically updates the data property with the DOM property's value. + * + * @usageNotes + * + * You can supply an optional name to use in templates when the + * component is instantiated, that maps to the + * name of the bound property. By default, the original + * name of the bound property is used for input binding. + * + * The following example creates a component with two input properties, + * one of which is given a special binding name. + * + * ```typescript + * @Component({ + * selector: 'bank-account', + * template: ` + * Bank Name: {{bankName}} + * Account Id: {{id}} + * ` + * }) + * class BankAccount { + * // This property is bound using its original name. + * @Input() bankName: string; + * // this property value is bound to a different property name + * // when this component is instantiated in a template. + * @Input('account-id') id: string; + * + * // this property is not bound, and is not automatically updated by Angular + * normalizedBankName: string; + * } + * + * @Component({ + * selector: 'app', + * template: ` + * + * ` + * }) + * class App {} + * ``` + * + * @see [Input and Output properties](guide/template-syntax#input-and-output-properties) + */ (bindingPropertyName?: string): any; - new (bindingPropertyName?: string): any; + new(bindingPropertyName?: string): any; } /** @@ -715,23 +715,23 @@ export const Input: InputDecorator = */ export interface OutputDecorator { /** - * Decorator that marks a class field as an output property and supplies configuration metadata. - * The DOM property bound to the output property is automatically updated during change detection. - * - * @usageNotes - * - * You can supply an optional name to use in templates when the - * component is instantiated, that maps to the - * name of the bound property. By default, the original - * name of the bound property is used for output binding. - * - * See `Input` decorator for an example of providing a binding name. - * - * @see [Input and Output properties](guide/template-syntax#input-and-output-properties) - * - */ + * Decorator that marks a class field as an output property and supplies configuration metadata. + * The DOM property bound to the output property is automatically updated during change detection. + * + * @usageNotes + * + * You can supply an optional name to use in templates when the + * component is instantiated, that maps to the + * name of the bound property. By default, the original + * name of the bound property is used for output binding. + * + * See `Input` decorator for an example of providing a binding name. + * + * @see [Input and Output properties](guide/template-syntax#input-and-output-properties) + * + */ (bindingPropertyName?: string): any; - new (bindingPropertyName?: string): any; + new(bindingPropertyName?: string): any; } /** @@ -741,8 +741,8 @@ export interface OutputDecorator { */ export interface Output { /** - * The name of the DOM property to which the output property is bound. - */ + * The name of the DOM property to which the output property is bound. + */ bindingPropertyName?: string; } @@ -791,7 +791,7 @@ export interface HostBindingDecorator { * */ (hostPropertyName?: string): any; - new (hostPropertyName?: string): any; + new(hostPropertyName?: string): any; } /** @@ -825,7 +825,7 @@ export interface HostListenerDecorator { * and provides a handler method to run when that event occurs. */ (eventName: string, args?: string[]): any; - new (eventName: string, args?: string[]): any; + new(eventName: string, args?: string[]): any; } /** diff --git a/packages/core/src/metadata/ng_module.ts b/packages/core/src/metadata/ng_module.ts index 9a8303228ae65..2d947c53fc3c7 100644 --- a/packages/core/src/metadata/ng_module.ts +++ b/packages/core/src/metadata/ng_module.ts @@ -13,7 +13,7 @@ import {convertInjectableProviderToFactory} from '../di/util'; import {Type} from '../interface/type'; import {SchemaMetadata} from '../metadata/schema'; import {compileNgModule as render3CompileNgModule} from '../render3/jit/module'; -import {TypeDecorator, makeDecorator} from '../util/decorators'; +import {makeDecorator, TypeDecorator} from '../util/decorators'; /** @@ -107,7 +107,7 @@ export interface NgModuleDecorator { * Decorator that marks a class as an NgModule and supplies configuration metadata. */ (obj?: NgModule): TypeDecorator; - new (obj?: NgModule): NgModule; + new(obj?: NgModule): NgModule; } /** @@ -345,7 +345,9 @@ export const NgModule: NgModuleDecorator = makeDecorator( * * @publicApi */ -export interface DoBootstrap { ngDoBootstrap(appRef: ApplicationRef): void; } +export interface DoBootstrap { + ngDoBootstrap(appRef: ApplicationRef): void; +} function preR3NgModuleCompile(moduleType: Type, metadata?: NgModule): void { let imports = (metadata && metadata.imports) || []; diff --git a/packages/core/src/metadata/resource_loading.ts b/packages/core/src/metadata/resource_loading.ts index 0aed1c1cd381a..e1b8bc7eb76c3 100644 --- a/packages/core/src/metadata/resource_loading.ts +++ b/packages/core/src/metadata/resource_loading.ts @@ -122,7 +122,7 @@ export function isComponentResourceResolutionQueueEmpty() { return componentResourceResolutionQueue.size === 0; } -function unwrapResponse(response: string | {text(): Promise}): string|Promise { +function unwrapResponse(response: string|{text(): Promise}): string|Promise { return typeof response == 'string' ? response : response.text(); } diff --git a/packages/core/src/metadata/schema.ts b/packages/core/src/metadata/schema.ts index 54c3d56dbe56e..7fa3e3f1b0a73 100644 --- a/packages/core/src/metadata/schema.ts +++ b/packages/core/src/metadata/schema.ts @@ -16,7 +16,9 @@ * * @publicApi */ -export interface SchemaMetadata { name: string; } +export interface SchemaMetadata { + name: string; +} /** * Defines a schema that allows an NgModule to contain the following: diff --git a/packages/core/src/platform_core_providers.ts b/packages/core/src/platform_core_providers.ts index aeae1d103a414..2d8e7d38fc28b 100644 --- a/packages/core/src/platform_core_providers.ts +++ b/packages/core/src/platform_core_providers.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {PlatformRef, createPlatformFactory} from './application_ref'; +import {createPlatformFactory, PlatformRef} from './application_ref'; import {PLATFORM_ID} from './application_tokens'; import {Console} from './console'; import {Injector, StaticProvider} from './di'; diff --git a/packages/core/src/r3_symbols.ts b/packages/core/src/r3_symbols.ts index 66771f54db9a6..28833b367bf1b 100644 --- a/packages/core/src/r3_symbols.ts +++ b/packages/core/src/r3_symbols.ts @@ -22,7 +22,7 @@ */ export {ɵɵinject} from './di/injector_compatibility'; -export {ɵɵInjectableDef, ɵɵInjectorDef, ɵɵdefineInjectable, ɵɵdefineInjector} from './di/interface/defs'; +export {ɵɵdefineInjectable, ɵɵdefineInjector, ɵɵInjectableDef, ɵɵInjectorDef} from './di/interface/defs'; export {NgModuleDef, ɵɵNgModuleDefWithMeta} from './metadata/ng_module'; export {ɵɵdefineNgModule} from './render3/definition'; export {ɵɵFactoryDef} from './render3/interfaces/definition'; diff --git a/packages/core/src/reflection/reflection_capabilities.ts b/packages/core/src/reflection/reflection_capabilities.ts index 0aac8ca00cedc..32a5112659c7f 100644 --- a/packages/core/src/reflection/reflection_capabilities.ts +++ b/packages/core/src/reflection/reflection_capabilities.ts @@ -6,11 +6,12 @@ * found in the LICENSE file at https://angular.io/license */ -import {Type, isType} from '../interface/type'; +import {isType, Type} from '../interface/type'; import {newArray} from '../util/array_utils'; import {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decorators'; import {global} from '../util/global'; import {stringify} from '../util/stringify'; + import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; import {GetterFn, MethodFn, SetterFn} from './types'; @@ -42,11 +43,17 @@ export function isDelegateCtor(typeStr: string): boolean { export class ReflectionCapabilities implements PlatformReflectionCapabilities { private _reflect: any; - constructor(reflect?: any) { this._reflect = reflect || global['Reflect']; } + constructor(reflect?: any) { + this._reflect = reflect || global['Reflect']; + } - isReflectionEnabled(): boolean { return true; } + isReflectionEnabled(): boolean { + return true; + } - factory(t: Type): (args: any[]) => T { return (...args: any[]) => new t(...args); } + factory(t: Type): (args: any[]) => T { + return (...args: any[]) => new t(...args); + } /** @internal */ _zipTypesAndAnnotations(paramTypes: any[], paramAnnotations: any[]): any[][] { @@ -235,9 +242,13 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities { return type instanceof Type && lcProperty in type.prototype; } - guards(type: any): {[key: string]: any} { return {}; } + guards(type: any): {[key: string]: any} { + return {}; + } - getter(name: string): GetterFn { return new Function('o', 'return o.' + name + ';'); } + getter(name: string): GetterFn { + return new Function('o', 'return o.' + name + ';'); + } setter(name: string): SetterFn { return new Function('o', 'v', 'return o.' + name + ' = v;'); @@ -259,12 +270,16 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities { return `./${stringify(type)}`; } - resourceUri(type: any): string { return `./${stringify(type)}`; } + resourceUri(type: any): string { + return `./${stringify(type)}`; + } resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any { return runtime; } - resolveEnum(enumIdentifier: any, name: string): any { return enumIdentifier[name]; } + resolveEnum(enumIdentifier: any, name: string): any { + return enumIdentifier[name]; + } } function convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] { diff --git a/packages/core/src/reflection/reflector.ts b/packages/core/src/reflection/reflector.ts index 6d7b8634f03d0..c8ec7710dfe56 100644 --- a/packages/core/src/reflection/reflector.ts +++ b/packages/core/src/reflection/reflector.ts @@ -20,9 +20,13 @@ export {GetterFn, MethodFn, SetterFn}; export class Reflector { constructor(public reflectionCapabilities: PlatformReflectionCapabilities) {} - updateCapabilities(caps: PlatformReflectionCapabilities) { this.reflectionCapabilities = caps; } + updateCapabilities(caps: PlatformReflectionCapabilities) { + this.reflectionCapabilities = caps; + } - factory(type: Type): Function { return this.reflectionCapabilities.factory(type); } + factory(type: Type): Function { + return this.reflectionCapabilities.factory(type); + } parameters(typeOrFunc: Type): any[][] { return this.reflectionCapabilities.parameters(typeOrFunc); @@ -40,15 +44,25 @@ export class Reflector { return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty); } - getter(name: string): GetterFn { return this.reflectionCapabilities.getter(name); } + getter(name: string): GetterFn { + return this.reflectionCapabilities.getter(name); + } - setter(name: string): SetterFn { return this.reflectionCapabilities.setter(name); } + setter(name: string): SetterFn { + return this.reflectionCapabilities.setter(name); + } - method(name: string): MethodFn { return this.reflectionCapabilities.method(name); } + method(name: string): MethodFn { + return this.reflectionCapabilities.method(name); + } - importUri(type: any): string { return this.reflectionCapabilities.importUri(type); } + importUri(type: any): string { + return this.reflectionCapabilities.importUri(type); + } - resourceUri(type: any): string { return this.reflectionCapabilities.resourceUri(type); } + resourceUri(type: any): string { + return this.reflectionCapabilities.resourceUri(type); + } resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any { return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, members, runtime); diff --git a/packages/core/src/render/api.ts b/packages/core/src/render/api.ts index f03f26eaf3442..36fcc6df541da 100644 --- a/packages/core/src/render/api.ts +++ b/packages/core/src/render/api.ts @@ -145,7 +145,7 @@ export abstract class Renderer2 { * This is used as a performance optimization for production mode. */ // TODO(issue/24571): remove '!'. - destroyNode !: ((node: any) => void) | null; + destroyNode!: ((node: any) => void)|null; /** * Appends a child to a given parent node in the host element DOM. * @param parent The parent node. diff --git a/packages/core/src/render3/assert.ts b/packages/core/src/render3/assert.ts index 186b0fde7766a..56c74663d5946 100644 --- a/packages/core/src/render3/assert.ts +++ b/packages/core/src/render3/assert.ts @@ -20,9 +20,10 @@ import {LView, TVIEW, TView} from './interfaces/view'; export function assertTNodeForLView(tNode: TNode, lView: LView) { - tNode.hasOwnProperty('tView_') && assertEqual( - (tNode as any as{tView_: TView}).tView_, lView[TVIEW], - 'This TNode does not belong to this LView.'); + tNode.hasOwnProperty('tView_') && + assertEqual( + (tNode as any as {tView_: TView}).tView_, lView[TVIEW], + 'This TNode does not belong to this LView.'); } export function assertComponentType( @@ -45,9 +46,9 @@ export function assertPreviousIsParent(isParent: boolean) { assertEqual(isParent, true, 'previousOrParentTNode should be a parent'); } -export function assertHasParent(tNode: TNode | null) { +export function assertHasParent(tNode: TNode|null) { assertDefined(tNode, 'previousOrParentTNode should exist!'); - assertDefined(tNode !.parent, 'previousOrParentTNode should have a parent'); + assertDefined(tNode!.parent, 'previousOrParentTNode should have a parent'); } export function assertDataNext(lView: LView, index: number, arr?: any[]) { diff --git a/packages/core/src/render3/component.ts b/packages/core/src/render3/component.ts index 892e49bd38108..c923209584084 100644 --- a/packages/core/src/render3/component.ts +++ b/packages/core/src/render3/component.ts @@ -12,15 +12,16 @@ import {Type} from '../core'; import {Injector} from '../di/injector'; import {Sanitizer} from '../sanitization/sanitizer'; import {assertDataInRange} from '../util/assert'; + import {assertComponentType} from './assert'; import {getComponentDef} from './definition'; import {diPublicInInjector, getOrCreateNodeInjectorForNode} from './di'; import {registerPostOrderHooks} from './hooks'; -import {CLEAN_PROMISE, addHostBindingsToExpandoInstructions, addToViewTree, createLView, createTView, getOrCreateTComponentView, getOrCreateTNode, growHostVarsSpace, initTNodeFlags, instantiateRootComponent, invokeHostBindingsInCreationMode, locateHostElement, markAsComponentHost, refreshView, renderView} from './instructions/shared'; +import {addHostBindingsToExpandoInstructions, addToViewTree, CLEAN_PROMISE, createLView, createTView, getOrCreateTComponentView, getOrCreateTNode, growHostVarsSpace, initTNodeFlags, instantiateRootComponent, invokeHostBindingsInCreationMode, locateHostElement, markAsComponentHost, refreshView, renderView} from './instructions/shared'; import {ComponentDef, ComponentType, RenderFlags} from './interfaces/definition'; import {TElementNode, TNode, TNodeType} from './interfaces/node'; import {PlayerHandler} from './interfaces/player'; -import {RElement, Renderer3, RendererFactory3, domRendererFactory3} from './interfaces/renderer'; +import {domRendererFactory3, RElement, Renderer3, RendererFactory3} from './interfaces/renderer'; import {CONTEXT, HEADER_OFFSET, LView, LViewFlags, RootContext, RootContextFlags, TVIEW, TViewType} from './interfaces/view'; import {writeDirectClass, writeDirectStyle} from './node_manipulation'; import {enterView, getPreviousOrParentTNode, leaveView, setSelectedIndex} from './state'; @@ -107,7 +108,7 @@ export const NULL_INJECTOR: Injector = { */ export function renderComponent( componentType: ComponentType| - Type/* Type as workaround for: Microsoft/TypeScript/issues/4881 */ + Type/* Type as workaround for: Microsoft/TypeScript/issues/4881 */ , opts: CreateComponentOptions = {}): T { ngDevMode && publishDefaultGlobalUtils(); @@ -115,11 +116,11 @@ export function renderComponent( const rendererFactory = opts.rendererFactory || domRendererFactory3; const sanitizer = opts.sanitizer || null; - const componentDef = getComponentDef(componentType) !; - if (componentDef.type != componentType) (componentDef as{type: Type}).type = componentType; + const componentDef = getComponentDef(componentType)!; + if (componentDef.type != componentType) (componentDef as {type: Type}).type = componentType; // The first index of the first selector is the tag name. - const componentTag = componentDef.selectors ![0] ![0] as string; + const componentTag = componentDef.selectors![0]![0] as string; const hostRenderer = rendererFactory.createRenderer(null, null); const hostRNode = locateHostElement(hostRenderer, opts.host || componentTag, componentDef.encapsulation); @@ -168,9 +169,8 @@ export function renderComponent( * @returns Component view created */ export function createRootComponentView( - rNode: RElement | null, def: ComponentDef, rootView: LView, - rendererFactory: RendererFactory3, hostRenderer: Renderer3, - sanitizer?: Sanitizer | null): LView { + rNode: RElement|null, def: ComponentDef, rootView: LView, + rendererFactory: RendererFactory3, hostRenderer: Renderer3, sanitizer?: Sanitizer|null): LView { const tView = rootView[TVIEW]; ngDevMode && assertDataInRange(rootView, 0 + HEADER_OFFSET); rootView[0 + HEADER_OFFSET] = rNode; @@ -213,7 +213,7 @@ export function createRootComponentView( */ export function createRootComponent( componentView: LView, componentDef: ComponentDef, rootLView: LView, rootContext: RootContext, - hostFeatures: HostFeature[] | null): any { + hostFeatures: HostFeature[]|null): any { const tView = rootLView[TVIEW]; // Create directive instance with factory() and store at next index in viewData const component = instantiateRootComponent(tView, rootLView, componentDef); @@ -270,13 +270,13 @@ export function createRootContext( * ``` */ export function LifecycleHooksFeature(component: any, def: ComponentDef): void { - const rootTView = readPatchedLView(component) ![TVIEW]; + const rootTView = readPatchedLView(component)![TVIEW]; const dirIndex = rootTView.data.length - 1; // TODO(misko): replace `as TNode` with createTNode call. (needs refactoring to lose dep on // LNode). registerPostOrderHooks( - rootTView, { directiveStart: dirIndex, directiveEnd: dirIndex + 1 } as TNode); + rootTView, {directiveStart: dirIndex, directiveEnd: dirIndex + 1} as TNode); } /** diff --git a/packages/core/src/render3/component_ref.ts b/packages/core/src/render3/component_ref.ts index 7655bbfa33352..86f9908b8a817 100644 --- a/packages/core/src/render3/component_ref.ts +++ b/packages/core/src/render3/component_ref.ts @@ -21,13 +21,13 @@ import {VERSION} from '../version'; import {NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR} from '../view/provider'; import {assertComponentType} from './assert'; -import {LifecycleHooksFeature, createRootComponent, createRootComponentView, createRootContext} from './component'; +import {createRootComponent, createRootComponentView, createRootContext, LifecycleHooksFeature} from './component'; import {getComponentDef} from './definition'; import {NodeInjector} from './di'; import {assignTViewNodeToLView, createLView, createTView, elementCreate, locateHostElement, renderView} from './instructions/shared'; import {ComponentDef} from './interfaces/definition'; import {TContainerNode, TElementContainerNode, TElementNode} from './interfaces/node'; -import {RNode, RendererFactory3, domRendererFactory3} from './interfaces/renderer'; +import {domRendererFactory3, RendererFactory3, RNode} from './interfaces/renderer'; import {LView, LViewFlags, TVIEW, TViewType} from './interfaces/view'; import {MATH_ML_NAMESPACE, SVG_NAMESPACE} from './namespaces'; import {writeDirectClass} from './node_manipulation'; @@ -43,11 +43,13 @@ export class ComponentFactoryResolver extends viewEngine_ComponentFactoryResolve /** * @param ngModule The NgModuleRef to which all resolved factories are bound. */ - constructor(private ngModule?: viewEngine_NgModuleRef) { super(); } + constructor(private ngModule?: viewEngine_NgModuleRef) { + super(); + } resolveComponentFactory(component: Type): viewEngine_ComponentFactory { ngDevMode && assertComponentType(component); - const componentDef = getComponentDef(component) !; + const componentDef = getComponentDef(component)!; return new ComponentFactory(componentDef, this.ngModule); } } @@ -79,7 +81,7 @@ export const SCHEDULER = new InjectionToken<((fn: () => void) => void)>('SCHEDUL function createChainedInjector(rootViewInjector: Injector, moduleInjector: Injector): Injector { return { - get: (token: Type| InjectionToken, notFoundValue?: T, flags?: InjectFlags): T => { + get: (token: Type|InjectionToken, notFoundValue?: T, flags?: InjectFlags): T => { const value = rootViewInjector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as T, flags); if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR || @@ -205,8 +207,9 @@ export class ComponentFactory extends viewEngine_ComponentFactory { // projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade // case). Here we do normalize passed data structure to be an array of arrays to avoid // complex checks down the line. - tElementNode.projection = - projectableNodes.map((nodesforSlot: RNode[]) => { return Array.from(nodesforSlot); }); + tElementNode.projection = projectableNodes.map((nodesforSlot: RNode[]) => { + return Array.from(nodesforSlot); + }); } // TODO: should LifecycleHooksFeature and other host features be generated by the compiler and @@ -227,7 +230,7 @@ export class ComponentFactory extends viewEngine_ComponentFactory { if (!rootSelectorOrNode || isIsolated) { // The host element of the internal or isolated root view is attached to the component's host // view node. - componentRef.hostView._tViewNode !.child = tElementNode; + componentRef.hostView._tViewNode!.child = tElementNode; } return componentRef; } @@ -272,7 +275,9 @@ export class ComponentRef extends viewEngine_ComponentRef { this.componentType = componentType; } - get injector(): Injector { return new NodeInjector(this._tNode, this._rootLView); } + get injector(): Injector { + return new NodeInjector(this._tNode, this._rootLView); + } destroy(): void { if (this.destroyCbs) { diff --git a/packages/core/src/render3/context_discovery.ts b/packages/core/src/render3/context_discovery.ts index 5429aba0edc79..c7da4fc3abb7b 100644 --- a/packages/core/src/render3/context_discovery.ts +++ b/packages/core/src/render3/context_discovery.ts @@ -18,7 +18,8 @@ import {getComponentLViewByIndex, getNativeByTNodeOrNull, readPatchedData, unwra -/** Returns the matching `LContext` data for a given DOM node, directive or component instance. +/** + * Returns the matching `LContext` data for a given DOM node, directive or component instance. * * This function will examine the provided DOM element, component, or directive instance\'s * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched @@ -43,7 +44,7 @@ export function getLContext(target: any): LContext|null { // only when it's an array is it considered an LView instance // ... otherwise it's an already constructed LContext instance if (Array.isArray(mpValue)) { - const lView: LView = mpValue !; + const lView: LView = mpValue!; let nodeIndex: number; let component: any = undefined; let directives: any[]|null|undefined = undefined; @@ -173,7 +174,7 @@ export function getComponentViewByInstance(componentInstance: {}): LView { * Assigns the given data to the given target (which could be a component, * directive or DOM node instance) using monkey-patching. */ -export function attachPatchData(target: any, data: LView | LContext) { +export function attachPatchData(target: any, data: LView|LContext) { target[MONKEY_PATCH_KEY_NAME] = data; } @@ -191,7 +192,7 @@ export function isDirectiveInstance(instance: any): boolean { function findViaNativeElement(lView: LView, target: RElement): number { let tNode = lView[TVIEW].firstChild; while (tNode) { - const native = getNativeByTNodeOrNull(tNode, lView) !; + const native = getNativeByTNodeOrNull(tNode, lView)!; if (native === target) { return tNode.index; } diff --git a/packages/core/src/render3/definition.ts b/packages/core/src/render3/definition.ts index 3b1215be9f44c..f4a7fedce7488 100644 --- a/packages/core/src/render3/definition.ts +++ b/packages/core/src/render3/definition.ts @@ -303,7 +303,7 @@ export function ɵɵdefineComponent(componentDefinition: { decls: componentDefinition.decls, vars: componentDefinition.vars, factory: null, - template: componentDefinition.template || null !, + template: componentDefinition.template || null!, consts: componentDefinition.consts || null, ngContentSelectors: componentDefinition.ngContentSelectors, hostBindings: componentDefinition.hostBindings || null, @@ -311,8 +311,8 @@ export function ɵɵdefineComponent(componentDefinition: { hostAttrs: componentDefinition.hostAttrs || null, contentQueries: componentDefinition.contentQueries || null, declaredInputs: declaredInputs, - inputs: null !, // assigned in noSideEffects - outputs: null !, // assigned in noSideEffects + inputs: null!, // assigned in noSideEffects + outputs: null!, // assigned in noSideEffects exportAs: componentDefinition.exportAs || null, onChanges: null, onInit: typePrototype.ngOnInit || null, @@ -323,8 +323,8 @@ export function ɵɵdefineComponent(componentDefinition: { afterViewChecked: typePrototype.ngAfterViewChecked || null, onDestroy: typePrototype.ngOnDestroy || null, onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush, - directiveDefs: null !, // assigned in noSideEffects - pipeDefs: null !, // assigned in noSideEffects + directiveDefs: null!, // assigned in noSideEffects + pipeDefs: null!, // assigned in noSideEffects selectors: componentDefinition.selectors || EMPTY_ARRAY, viewQuery: componentDefinition.viewQuery || null, features: componentDefinition.features as DirectiveDefFeature[] || null, @@ -339,9 +339,9 @@ export function ɵɵdefineComponent(componentDefinition: { schemas: componentDefinition.schemas || null, tView: null, }; - const directiveTypes = componentDefinition.directives !; + const directiveTypes = componentDefinition.directives!; const feature = componentDefinition.features; - const pipeTypes = componentDefinition.pipes !; + const pipeTypes = componentDefinition.pipes!; def.id += _renderCompCount++; def.inputs = invertObject(componentDefinition.inputs, declaredInputs), def.outputs = invertObject(componentDefinition.outputs), @@ -373,7 +373,7 @@ export function extractDirectiveDef(type: Type): DirectiveDef|Componen if (ngDevMode && !def) { throw new Error(`'${type.name}' is neither 'ComponentType' or 'DirectiveType'.`); } - return def !; + return def!; } export function extractPipeDef(type: Type): PipeDef { @@ -381,7 +381,7 @@ export function extractPipeDef(type: Type): PipeDef { if (ngDevMode && !def) { throw new Error(`'${type.name}' is not a 'PipeType'.`); } - return def !; + return def!; } export const autoRegisterModuleById: {[id: string]: NgModuleType} = {}; @@ -425,8 +425,9 @@ export function ɵɵdefineNgModule(def: { id: def.id || null, }; if (def.id != null) { - noSideEffects( - () => { autoRegisterModuleById[def.id !] = def.type as unknown as NgModuleType; }); + noSideEffects(() => { + autoRegisterModuleById[def.id!] = def.type as unknown as NgModuleType; + }); } return res as never; } @@ -443,7 +444,7 @@ export function ɵɵdefineNgModule(def: { */ export function ɵɵsetNgModuleScope(type: any, scope: { /** List of components, directives, and pipes declared by this module. */ - declarations?: Type[] | (() => Type[]); + declarations?: Type[]|(() => Type[]); /** List of modules or `ModuleWithProviders` imported by this module. */ imports?: Type[] | (() => Type[]); @@ -455,11 +456,11 @@ export function ɵɵsetNgModuleScope(type: any, scope: { exports?: Type[] | (() => Type[]); }): void { return noSideEffects(() => { - const ngModuleDef = getNgModuleDef(type, true); - ngModuleDef.declarations = scope.declarations || EMPTY_ARRAY; - ngModuleDef.imports = scope.imports || EMPTY_ARRAY; - ngModuleDef.exports = scope.exports || EMPTY_ARRAY; - }) as never; + const ngModuleDef = getNgModuleDef(type, true); + ngModuleDef.declarations = scope.declarations || EMPTY_ARRAY; + ngModuleDef.imports = scope.imports || EMPTY_ARRAY; + ngModuleDef.exports = scope.exports || EMPTY_ARRAY; + }) as never; } /** @@ -518,13 +519,13 @@ export function ɵɵsetNgModuleScope(type: any, scope: { */ function invertObject( - obj?: {[P in keyof T]?: string | [string, string]}, + obj?: {[P in keyof T]?: string|[string, string]}, secondary?: {[key: string]: string}): {[P in keyof T]: string} { if (obj == null) return EMPTY_OBJ as any; const newLookup: any = {}; for (const minifiedKey in obj) { if (obj.hasOwnProperty(minifiedKey)) { - let publicName: string|[string, string] = obj[minifiedKey] !; + let publicName: string|[string, string] = obj[minifiedKey]!; let declaredName = publicName; if (Array.isArray(publicName)) { declaredName = publicName[1]; @@ -555,142 +556,143 @@ function invertObject( * * @codeGenApi */ -export const ɵɵdefineDirective = ɵɵdefineComponent as any as(directiveDefinition: { - /** - * Directive type, needed to configure the injector. - */ - type: Type; - - /** The selectors that will be used to match nodes to this directive. */ - selectors?: CssSelectorList; - - /** - * A map of input names. - * - * The format is in: `{[actualPropertyName: string]:(string|[string, string])}`. - * - * Given: - * ``` - * class MyComponent { - * @Input() - * publicInput1: string; - * - * @Input('publicInput2') - * declaredInput2: string; - * } - * ``` - * - * is described as: - * ``` - * { - * publicInput1: 'publicInput1', - * declaredInput2: ['declaredInput2', 'publicInput2'], - * } - * ``` - * - * Which the minifier may translate to: - * ``` - * { - * minifiedPublicInput1: 'publicInput1', - * minifiedDeclaredInput2: [ 'publicInput2', 'declaredInput2'], - * } - * ``` - * - * This allows the render to re-construct the minified, public, and declared names - * of properties. - * - * NOTE: - * - Because declared and public name are usually same we only generate the array - * `['declared', 'public']` format when they differ. - * - The reason why this API and `outputs` API is not the same is that `NgOnChanges` has - * inconsistent behavior in that it uses declared names rather than minified or public. For - * this reason `NgOnChanges` will be deprecated and removed in future version and this - * API will be simplified to be consistent with `output`. - */ - inputs?: {[P in keyof T]?: string | [string, string]}; - - /** - * A map of output names. - * - * The format is in: `{[actualPropertyName: string]:string}`. - * - * Which the minifier may translate to: `{[minifiedPropertyName: string]:string}`. - * - * This allows the render to re-construct the minified and non-minified names - * of properties. - */ - outputs?: {[P in keyof T]?: string}; - - /** - * A list of optional features to apply. - * - * See: {@link NgOnChangesFeature}, {@link ProvidersFeature}, {@link InheritDefinitionFeature} - */ - features?: DirectiveDefFeature[]; - - /** - * Function executed by the parent template to allow child directive to apply host bindings. - */ - hostBindings?: HostBindingsFunction; - - /** - * The number of bindings in this directive `hostBindings` (including pure fn bindings). - * - * Used to calculate the length of the component's LView array, so we - * can pre-fill the array and set the host binding start index. - */ - hostVars?: number; - - /** - * Assign static attribute values to a host element. - * - * This property will assign static attribute values as well as class and style - * values to a host element. Since attribute values can consist of different types of values, the - * `hostAttrs` array must include the values in the following format: - * - * attrs = [ - * // static attributes (like `title`, `name`, `id`...) - * attr1, value1, attr2, value, - * - * // a single namespace value (like `x:id`) - * NAMESPACE_MARKER, namespaceUri1, name1, value1, - * - * // another single namespace value (like `x:name`) - * NAMESPACE_MARKER, namespaceUri2, name2, value2, - * - * // a series of CSS classes that will be applied to the element (no spaces) - * CLASSES_MARKER, class1, class2, class3, - * - * // a series of CSS styles (property + value) that will be applied to the element - * STYLES_MARKER, prop1, value1, prop2, value2 - * ] - * - * All non-class and non-style attributes must be defined at the start of the list - * first before all class and style values are set. When there is a change in value - * type (like when classes and styles are introduced) a marker must be used to separate - * the entries. The marker values themselves are set via entries found in the - * [AttributeMarker] enum. - */ - hostAttrs?: TAttributes; - - /** - * Function to create instances of content queries associated with a given directive. - */ - contentQueries?: ContentQueriesFunction; - - /** - * Additional set of instructions specific to view query processing. This could be seen as a - * set of instructions to be inserted into the template function. - */ - viewQuery?: ViewQueriesFunction| null; - - /** - * Defines the name that can be used in the template to assign this directive to a variable. - * - * See: {@link Directive.exportAs} - */ - exportAs?: string[]; -}) => never; +export const ɵɵdefineDirective = + ɵɵdefineComponent as any as(directiveDefinition: { + /** + * Directive type, needed to configure the injector. + */ + type: Type; + + /** The selectors that will be used to match nodes to this directive. */ + selectors?: CssSelectorList; + + /** + * A map of input names. + * + * The format is in: `{[actualPropertyName: string]:(string|[string, string])}`. + * + * Given: + * ``` + * class MyComponent { + * @Input() + * publicInput1: string; + * + * @Input('publicInput2') + * declaredInput2: string; + * } + * ``` + * + * is described as: + * ``` + * { + * publicInput1: 'publicInput1', + * declaredInput2: ['declaredInput2', 'publicInput2'], + * } + * ``` + * + * Which the minifier may translate to: + * ``` + * { + * minifiedPublicInput1: 'publicInput1', + * minifiedDeclaredInput2: [ 'publicInput2', 'declaredInput2'], + * } + * ``` + * + * This allows the render to re-construct the minified, public, and declared names + * of properties. + * + * NOTE: + * - Because declared and public name are usually same we only generate the array + * `['declared', 'public']` format when they differ. + * - The reason why this API and `outputs` API is not the same is that `NgOnChanges` has + * inconsistent behavior in that it uses declared names rather than minified or public. For + * this reason `NgOnChanges` will be deprecated and removed in future version and this + * API will be simplified to be consistent with `output`. + */ + inputs?: {[P in keyof T]?: string | [string, string]}; + + /** + * A map of output names. + * + * The format is in: `{[actualPropertyName: string]:string}`. + * + * Which the minifier may translate to: `{[minifiedPropertyName: string]:string}`. + * + * This allows the render to re-construct the minified and non-minified names + * of properties. + */ + outputs?: {[P in keyof T]?: string}; + + /** + * A list of optional features to apply. + * + * See: {@link NgOnChangesFeature}, {@link ProvidersFeature}, {@link InheritDefinitionFeature} + */ + features?: DirectiveDefFeature[]; + + /** + * Function executed by the parent template to allow child directive to apply host bindings. + */ + hostBindings?: HostBindingsFunction; + + /** + * The number of bindings in this directive `hostBindings` (including pure fn bindings). + * + * Used to calculate the length of the component's LView array, so we + * can pre-fill the array and set the host binding start index. + */ + hostVars?: number; + + /** + * Assign static attribute values to a host element. + * + * This property will assign static attribute values as well as class and style + * values to a host element. Since attribute values can consist of different types of values, + * the `hostAttrs` array must include the values in the following format: + * + * attrs = [ + * // static attributes (like `title`, `name`, `id`...) + * attr1, value1, attr2, value, + * + * // a single namespace value (like `x:id`) + * NAMESPACE_MARKER, namespaceUri1, name1, value1, + * + * // another single namespace value (like `x:name`) + * NAMESPACE_MARKER, namespaceUri2, name2, value2, + * + * // a series of CSS classes that will be applied to the element (no spaces) + * CLASSES_MARKER, class1, class2, class3, + * + * // a series of CSS styles (property + value) that will be applied to the element + * STYLES_MARKER, prop1, value1, prop2, value2 + * ] + * + * All non-class and non-style attributes must be defined at the start of the list + * first before all class and style values are set. When there is a change in value + * type (like when classes and styles are introduced) a marker must be used to separate + * the entries. The marker values themselves are set via entries found in the + * [AttributeMarker] enum. + */ + hostAttrs?: TAttributes; + + /** + * Function to create instances of content queries associated with a given directive. + */ + contentQueries?: ContentQueriesFunction; + + /** + * Additional set of instructions specific to view query processing. This could be seen as a + * set of instructions to be inserted into the template function. + */ + viewQuery?: ViewQueriesFunction| null; + + /** + * Defines the name that can be used in the template to assign this directive to a variable. + * + * See: {@link Directive.exportAs} + */ + exportAs?: string[]; + }) => never; /** * Create a pipe definition object. @@ -719,12 +721,12 @@ export function ɵɵdefinePipe(pipeDef: { pure?: boolean }): never { return (>{ - type: pipeDef.type, - name: pipeDef.name, - factory: null, - pure: pipeDef.pure !== false, - onDestroy: pipeDef.type.prototype.ngOnDestroy || null - }) as never; + type: pipeDef.type, + name: pipeDef.name, + factory: null, + pure: pipeDef.pure !== false, + onDestroy: pipeDef.type.prototype.ngOnDestroy || null + }) as never; } /** diff --git a/packages/core/src/render3/di.ts b/packages/core/src/render3/di.ts index c70505a2d1e6d..3b6eca4d6e872 100644 --- a/packages/core/src/render3/di.ts +++ b/packages/core/src/render3/di.ts @@ -21,10 +21,10 @@ import {getFactoryDef} from './definition'; import {NG_ELEMENT_ID, NG_FACTORY_DEF} from './fields'; import {registerPreOrderHooks} from './hooks'; import {DirectiveDef, FactoryFn} from './interfaces/definition'; -import {NO_PARENT_INJECTOR, NodeInjectorFactory, PARENT_INJECTOR, RelativeInjectorLocation, RelativeInjectorLocationFlags, TNODE, isFactory} from './interfaces/injector'; +import {isFactory, NO_PARENT_INJECTOR, NodeInjectorFactory, PARENT_INJECTOR, RelativeInjectorLocation, RelativeInjectorLocationFlags, TNODE} from './interfaces/injector'; import {AttributeMarker, TContainerNode, TDirectiveHostNode, TElementContainerNode, TElementNode, TNode, TNodeProviderIndexes, TNodeType} from './interfaces/node'; import {isComponentDef, isComponentHost} from './interfaces/type_checks'; -import {DECLARATION_COMPONENT_VIEW, DECLARATION_VIEW, INJECTOR, LView, TData, TVIEW, TView, T_HOST} from './interfaces/view'; +import {DECLARATION_COMPONENT_VIEW, DECLARATION_VIEW, INJECTOR, LView, T_HOST, TData, TVIEW, TView} from './interfaces/view'; import {assertNodeOfPossibleTypes} from './node_assert'; import {enterDI, leaveDI} from './state'; import {isNameOnlyAttributeMarker} from './util/attrs_utils'; @@ -97,7 +97,7 @@ let nextNgElementId = 0; * @param type The directive token to register */ export function bloomAdd( - injectorIndex: number, tView: TView, type: Type| InjectionToken| string): void { + injectorIndex: number, tView: TView, type: Type|InjectionToken|string): void { ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true'); let id: number|undefined = typeof type !== 'string' ? (type as any)[NG_ELEMENT_ID] : type.charCodeAt(0) || 0; @@ -141,7 +141,7 @@ export function bloomAdd( * @returns Node injector */ export function getOrCreateNodeInjectorForNode( - tNode: TElementNode | TContainerNode | TElementContainerNode, hostView: LView): number { + tNode: TElementNode|TContainerNode|TElementContainerNode, hostView: LView): number { const existingInjectorIndex = getInjectorIndex(tNode, hostView); if (existingInjectorIndex !== -1) { return existingInjectorIndex; @@ -175,7 +175,7 @@ export function getOrCreateNodeInjectorForNode( return injectorIndex; } -function insertBloom(arr: any[], footer: TNode | null): void { +function insertBloom(arr: any[], footer: TNode|null): void { arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer); } @@ -211,7 +211,7 @@ export function getParentInjectorLocation(tNode: TNode, view: LView): RelativeIn let hostTNode = view[T_HOST]; let viewOffset = 1; while (hostTNode && hostTNode.injectorIndex === -1) { - view = view[DECLARATION_VIEW] !; + view = view[DECLARATION_VIEW]!; hostTNode = view ? view[T_HOST] : null; viewOffset++; } @@ -229,7 +229,7 @@ export function getParentInjectorLocation(tNode: TNode, view: LView): RelativeIn * @param token The type or the injection token to be made public */ export function diPublicInInjector( - injectorIndex: number, tView: TView, token: InjectionToken| Type): void { + injectorIndex: number, tView: TView, token: InjectionToken|Type): void { bloomAdd(injectorIndex, tView, token); } @@ -265,8 +265,9 @@ export function diPublicInInjector( * @publicApi */ export function injectAttributeImpl(tNode: TNode, attrNameToInject: string): string|null { - ngDevMode && assertNodeOfPossibleTypes( - tNode, TNodeType.Container, TNodeType.Element, TNodeType.ElementContainer); + ngDevMode && + assertNodeOfPossibleTypes( + tNode, TNodeType.Container, TNodeType.Element, TNodeType.ElementContainer); ngDevMode && assertDefined(tNode, 'expecting tNode'); if (attrNameToInject === 'class') { return tNode.classes; @@ -327,7 +328,7 @@ export function injectAttributeImpl(tNode: TNode, attrNameToInject: string): str * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided */ export function getOrCreateInjectable( - tNode: TDirectiveHostNode | null, lView: LView, token: Type| InjectionToken, + tNode: TDirectiveHostNode|null, lView: LView, token: Type|InjectionToken, flags: InjectFlags = InjectFlags.Default, notFoundValue?: any): T|null { if (tNode !== null) { const bloomHash = bloomHashBitOrFactory(token); @@ -443,8 +444,8 @@ export function getOrCreateInjectable( const NOT_FOUND = {}; function searchTokensOnInjector( - injectorIndex: number, lView: LView, token: Type| InjectionToken, - previousTView: TView | null, flags: InjectFlags, hostTElementNode: TNode | null) { + injectorIndex: number, lView: LView, token: Type|InjectionToken, + previousTView: TView|null, flags: InjectFlags, hostTElementNode: TNode|null) { const currentTView = lView[TVIEW]; const tNode = currentTView.data[injectorIndex + TNODE] as TNode; // First, we need to determine if view providers can be accessed by the starting element. @@ -490,8 +491,8 @@ function searchTokensOnInjector( * @returns Index of a found directive or provider, or null when none found. */ export function locateDirectiveOrProvider( - tNode: TNode, tView: TView, token: Type| InjectionToken, canAccessViewProviders: boolean, - isHostSpecialCase: boolean | number): number|null { + tNode: TNode, tView: TView, token: Type|InjectionToken, canAccessViewProviders: boolean, + isHostSpecialCase: boolean|number): number|null { const nodeProviderIndexes = tNode.providerIndexes; const tInjectables = tView.data; @@ -521,12 +522,12 @@ export function locateDirectiveOrProvider( } /** -* Retrieve or instantiate the injectable from the `LView` at particular `index`. -* -* This function checks to see if the value has already been instantiated and if so returns the -* cached `injectable`. Otherwise if it detects that the value is still a factory it -* instantiates the `injectable` and caches the value. -*/ + * Retrieve or instantiate the injectable from the `LView` at particular `index`. + * + * This function checks to see if the value has already been instantiated and if so returns the + * cached `injectable`. Otherwise if it detects that the value is still a factory it + * instantiates the `injectable` and caches the value. + */ export function getNodeInjectable( lView: LView, tView: TView, index: number, tNode: TDirectiveHostNode): any { let value = lView[index]; @@ -577,8 +578,8 @@ export function getNodeInjectable( * @returns the matching bit to check in the bloom filter or `null` if the token is not known. * When the returned value is negative then it represents special values such as `Injector`. */ -export function bloomHashBitOrFactory(token: Type| InjectionToken| string): number| - Function|undefined { +export function bloomHashBitOrFactory(token: Type|InjectionToken|string): number|Function| + undefined { ngDevMode && assertDefined(token, 'token must be defined'); if (typeof token === 'string') { return token.charCodeAt(0) || 0; @@ -588,8 +589,7 @@ export function bloomHashBitOrFactory(token: Type| InjectionToken| str return (typeof tokenId === 'number' && tokenId > 0) ? tokenId & BLOOM_MASK : tokenId; } -export function bloomHasToken( - bloomHash: number, injectorIndex: number, injectorView: LView | TData) { +export function bloomHasToken(bloomHash: number, injectorIndex: number, injectorView: LView|TData) { // Create a mask that targets the specific bit associated with the directive we're looking for. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding // to bit positions 0 - 31 in a 32 bit integer. @@ -639,9 +639,9 @@ export function ɵɵgetFactoryOf(type: Type): FactoryFn|null { if (isForwardRef(type)) { return (() => { - const factory = ɵɵgetFactoryOf(resolveForwardRef(typeAny)); - return factory ? factory() : null; - }) as any; + const factory = ɵɵgetFactoryOf(resolveForwardRef(typeAny)); + return factory ? factory() : null; + }) as any; } let factory = getFactoryDef(typeAny); diff --git a/packages/core/src/render3/empty.ts b/packages/core/src/render3/empty.ts index 36be572fbe5d1..fa7af07343e6f 100644 --- a/packages/core/src/render3/empty.ts +++ b/packages/core/src/render3/empty.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {initNgDevMode} from '../util/ng_dev_mode'; /** diff --git a/packages/core/src/render3/errors.ts b/packages/core/src/render3/errors.ts index d92cb4ebc27e1..b1fc6a6457e2c 100644 --- a/packages/core/src/render3/errors.ts +++ b/packages/core/src/render3/errors.ts @@ -47,7 +47,8 @@ export function throwErrorIfNoChangesMode( creationMode: boolean, oldValue: any, currValue: any, propName?: string): never|void { const field = propName ? ` for '${propName}'` : ''; let msg = - `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${field}: '${oldValue}'. Current value: '${currValue}'.`; + `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${ + field}: '${oldValue}'. Current value: '${currValue}'.`; if (creationMode) { msg += ` It seems like the view has been created after its parent and its children have been dirty checked.` + diff --git a/packages/core/src/render3/features/copy_definition_feature.ts b/packages/core/src/render3/features/copy_definition_feature.ts index 3d4bc0f2569c0..4cad1d4446cca 100644 --- a/packages/core/src/render3/features/copy_definition_feature.ts +++ b/packages/core/src/render3/features/copy_definition_feature.ts @@ -64,16 +64,16 @@ const COPY_COMPONENT_FIELDS: Exclude, keyof Directiv * * @codeGenApi */ -export function ɵɵCopyDefinitionFeature(definition: DirectiveDef| ComponentDef): void { - let superType = getSuperType(definition.type) !; +export function ɵɵCopyDefinitionFeature(definition: DirectiveDef|ComponentDef): void { + let superType = getSuperType(definition.type)!; let superDef: DirectiveDef|ComponentDef|undefined = undefined; if (isComponentDef(definition)) { // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance. - superDef = superType.ɵcmp !; + superDef = superType.ɵcmp!; } else { // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance. - superDef = superType.ɵdir !; + superDef = superType.ɵdir!; } // Needed because `definition` fields are readonly. diff --git a/packages/core/src/render3/features/inherit_definition_feature.ts b/packages/core/src/render3/features/inherit_definition_feature.ts index 4d96eafef300c..66b0f689fb8a6 100644 --- a/packages/core/src/render3/features/inherit_definition_feature.ts +++ b/packages/core/src/render3/features/inherit_definition_feature.ts @@ -27,7 +27,7 @@ type WritableDef = Writable|ComponentDef>; * * @codeGenApi */ -export function ɵɵInheritDefinitionFeature(definition: DirectiveDef| ComponentDef): void { +export function ɵɵInheritDefinitionFeature(definition: DirectiveDef|ComponentDef): void { let superType = getSuperType(definition.type); let shouldInheritFields = true; const inheritanceChain: WritableDef[] = [definition]; diff --git a/packages/core/src/render3/features/ng_onchanges_feature.ts b/packages/core/src/render3/features/ng_onchanges_feature.ts index 7d749c624fdd7..3e7bf13830688 100644 --- a/packages/core/src/render3/features/ng_onchanges_feature.ts +++ b/packages/core/src/render3/features/ng_onchanges_feature.ts @@ -13,7 +13,7 @@ import {DirectiveDef, DirectiveDefFeature} from '../interfaces/definition'; const PRIVATE_PREFIX = '__ngOnChanges_'; -type OnChangesExpando = OnChanges & { +type OnChangesExpando = OnChanges&{ __ngOnChanges_: SimpleChanges|null|undefined; // tslint:disable-next-line:no-any Can hold any value [key: string]: any; @@ -45,7 +45,7 @@ type OnChangesExpando = OnChanges & { export function ɵɵNgOnChangesFeature(definition: DirectiveDef): void { if (definition.type.prototype.ngOnChanges) { definition.setInput = ngOnChangesSetInput; - (definition as{onChanges: Function}).onChanges = wrapOnChanges(); + (definition as {onChanges: Function}).onChanges = wrapOnChanges(); } } @@ -61,9 +61,9 @@ function wrapOnChanges() { const current = simpleChangesStore && simpleChangesStore.current; if (current) { - const previous = simpleChangesStore !.previous; + const previous = simpleChangesStore!.previous; if (previous === EMPTY_OBJ) { - simpleChangesStore !.previous = current; + simpleChangesStore!.previous = current; } else { // New changes are copied to the previous store, so that we don't lose history for inputs // which were not changed this time @@ -71,7 +71,7 @@ function wrapOnChanges() { previous[key] = current[key]; } } - simpleChangesStore !.current = null; + simpleChangesStore!.current = null; this.ngOnChanges(current); } }; @@ -84,7 +84,7 @@ function ngOnChangesSetInput( const current = simpleChangesStore.current || (simpleChangesStore.current = {}); const previous = simpleChangesStore.previous; - const declaredName = (this.declaredInputs as{[key: string]: string})[publicName]; + const declaredName = (this.declaredInputs as {[key: string]: string})[publicName]; const previousChange = previous[declaredName]; current[declaredName] = new SimpleChange( previousChange && previousChange.currentValue, value, previous === EMPTY_OBJ); diff --git a/packages/core/src/render3/global_utils_api.ts b/packages/core/src/render3/global_utils_api.ts index 330918cf0369f..feb419de1d3ae 100644 --- a/packages/core/src/render3/global_utils_api.ts +++ b/packages/core/src/render3/global_utils_api.ts @@ -16,4 +16,4 @@ */ export {applyChanges} from './util/change_detection_utils'; -export {Listener, getComponent, getContext, getDirectives, getHostElement, getInjector, getListeners, getOwningComponent, getRootComponents} from './util/discovery_utils'; +export {getComponent, getContext, getDirectives, getHostElement, getInjector, getListeners, getOwningComponent, getRootComponents, Listener} from './util/discovery_utils'; diff --git a/packages/core/src/render3/hooks.ts b/packages/core/src/render3/hooks.ts index eebaed60aa362..0667d62e23b51 100644 --- a/packages/core/src/render3/hooks.ts +++ b/packages/core/src/render3/hooks.ts @@ -79,8 +79,8 @@ export function registerPostOrderHooks(tView: TView, tNode: TNode): void { if (directiveDef.afterContentChecked) { (tView.contentHooks || (tView.contentHooks = [])).push(i, directiveDef.afterContentChecked); - (tView.contentCheckHooks || (tView.contentCheckHooks = [ - ])).push(i, directiveDef.afterContentChecked); + (tView.contentCheckHooks || (tView.contentCheckHooks = [])) + .push(i, directiveDef.afterContentChecked); } if (directiveDef.afterViewInit) { @@ -132,7 +132,7 @@ export function registerPostOrderHooks(tView: TView, tNode: TNode): void { * - number: execute hooks only from the saved index until that node index exclusive (pre-order * case, when executing select(number)) */ -export function executeCheckHooks(lView: LView, hooks: HookData, nodeIndex?: number | null) { +export function executeCheckHooks(lView: LView, hooks: HookData, nodeIndex?: number|null) { callHooks(lView, hooks, InitPhaseState.InitPhaseCompleted, nodeIndex); } @@ -150,10 +150,11 @@ export function executeCheckHooks(lView: LView, hooks: HookData, nodeIndex?: num * case, when executing select(number)) */ export function executeInitAndCheckHooks( - lView: LView, hooks: HookData, initPhase: InitPhaseState, nodeIndex?: number | null) { - ngDevMode && assertNotEqual( - initPhase, InitPhaseState.InitPhaseCompleted, - 'Init pre-order hooks should not be called more than once'); + lView: LView, hooks: HookData, initPhase: InitPhaseState, nodeIndex?: number|null) { + ngDevMode && + assertNotEqual( + initPhase, InitPhaseState.InitPhaseCompleted, + 'Init pre-order hooks should not be called more than once'); if ((lView[FLAGS] & LViewFlags.InitPhaseStateMask) === initPhase) { callHooks(lView, hooks, initPhase, nodeIndex); } @@ -188,17 +189,18 @@ export function incrementInitPhaseFlags(lView: LView, initPhase: InitPhaseState) */ function callHooks( currentView: LView, arr: HookData, initPhase: InitPhaseState, - currentNodeIndex: number | null | undefined): void { - ngDevMode && assertEqual( - getCheckNoChangesMode(), false, - 'Hooks should never be run in the check no changes mode.'); + currentNodeIndex: number|null|undefined): void { + ngDevMode && + assertEqual( + getCheckNoChangesMode(), false, + 'Hooks should never be run in the check no changes mode.'); const startIndex = currentNodeIndex !== undefined ? (currentView[PREORDER_HOOK_FLAGS] & PreOrderHookFlags.IndexOfTheNextPreOrderHookMaskMask) : 0; const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1; let lastNodeIndexFound = 0; for (let i = startIndex; i < arr.length; i++) { - const hook = arr[i + 1] as() => void; + const hook = arr[i + 1] as () => void; if (typeof hook === 'number') { lastNodeIndexFound = arr[i] as number; if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) { @@ -229,7 +231,7 @@ function callHooks( */ function callHook(currentView: LView, initPhase: InitPhaseState, arr: HookData, i: number) { const isInitHook = arr[i] < 0; - const hook = arr[i + 1] as() => void; + const hook = arr[i + 1] as () => void; const directiveIndex = isInitHook ? -arr[i] : arr[i] as number; const directive = currentView[directiveIndex]; if (isInitHook) { diff --git a/packages/core/src/render3/i18n.ts b/packages/core/src/render3/i18n.ts index 640c3eefd9b7b..f947dd3942b8c 100644 --- a/packages/core/src/render3/i18n.ts +++ b/packages/core/src/render3/i18n.ts @@ -8,11 +8,12 @@ import '../util/ng_i18n_closure_mode'; import {DEFAULT_LOCALE_ID, getPluralCase} from '../i18n/localization'; -import {SRCSET_ATTRS, URI_ATTRS, VALID_ATTRS, VALID_ELEMENTS, getTemplateContent} from '../sanitization/html_sanitizer'; +import {getTemplateContent, SRCSET_ATTRS, URI_ATTRS, VALID_ATTRS, VALID_ELEMENTS} from '../sanitization/html_sanitizer'; import {InertBodyHelper} from '../sanitization/inert_body'; import {_sanitizeUrl, sanitizeSrcset} from '../sanitization/url_sanitizer'; import {addAllToArray} from '../util/array_utils'; import {assertDataInRange, assertDefined, assertEqual} from '../util/assert'; + import {bindingUpdated} from './bindings'; import {attachPatchData} from './context_discovery'; import {setDelayProjection} from './instructions/all'; @@ -25,7 +26,7 @@ import {TElementNode, TIcuContainerNode, TNode, TNodeFlags, TNodeType, TProjecti import {RComment, RElement, RText} from './interfaces/renderer'; import {SanitizerFn} from './interfaces/sanitization'; import {isLContainer} from './interfaces/type_checks'; -import {HEADER_OFFSET, LView, RENDERER, TVIEW, TView, T_HOST} from './interfaces/view'; +import {HEADER_OFFSET, LView, RENDERER, T_HOST, TVIEW, TView} from './interfaces/view'; import {appendChild, applyProjection, createTextNode, nativeRemoveNode} from './node_manipulation'; import {getBindingIndex, getIsParent, getLView, getPreviousOrParentTNode, getTView, nextBindingIndex, setIsNotParent, setPreviousOrParentTNode} from './state'; import {renderStringify} from './util/misc_utils'; @@ -105,14 +106,14 @@ interface IcuCase { * @param pattern (sub)Pattern to be broken. * */ -function extractParts(pattern: string): (string | IcuExpression)[] { +function extractParts(pattern: string): (string|IcuExpression)[] { if (!pattern) { return []; } let prevPos = 0; const braceStack = []; - const results: (string | IcuExpression)[] = []; + const results: (string|IcuExpression)[] = []; const braces = /[{}]/g; // lastIndex doesn't get set to 0 so we have to. braces.lastIndex = 0; @@ -158,7 +159,7 @@ function extractParts(pattern: string): (string | IcuExpression)[] { */ function parseICUBlock(pattern: string): IcuExpression { const cases = []; - const values: (string | IcuExpression)[][] = []; + const values: (string|IcuExpression)[][] = []; let icuType = IcuType.plural; let mainBinding = 0; pattern = pattern.replace(ICU_BLOCK_REGEXP, function(str: string, binding: string, type: string) { @@ -219,7 +220,8 @@ function removeInnerTemplateTranslation(message: string): string { ngDevMode && assertEqual( inTemplate, false, - `Tag mismatch: unable to find the end of the sub-template in the translation "${message}"`); + `Tag mismatch: unable to find the end of the sub-template in the translation "${ + message}"`); res += message.substr(index); return res; @@ -263,7 +265,7 @@ export function getTranslationForTemplate(message: string, subTemplateIndex?: nu */ function generateBindingUpdateOpCodes( str: string, destinationNode: number, attrName?: string, - sanitizeFn: SanitizerFn | null = null): I18nUpdateOpCodes { + sanitizeFn: SanitizerFn|null = null): I18nUpdateOpCodes { const updateOpCodes: I18nUpdateOpCodes = [null, null]; // Alloc space for mask and size const textParts = str.split(BINDING_REGEXP); let mask = 0; @@ -508,7 +510,7 @@ function i18nStartFirstPass( } function appendI18nNode( - tView: TView, tNode: TNode, parentTNode: TNode, previousTNode: TNode | null, + tView: TView, tNode: TNode, parentTNode: TNode, previousTNode: TNode|null, lView: LView): TNode { ngDevMode && ngDevMode.rendererMoveNode++; const nextNode = tNode.next; @@ -577,7 +579,7 @@ function appendI18nNode( * @codeGenApi */ export function ɵɵi18nPostprocess( - message: string, replacements: {[key: string]: (string | string[])} = {}): string { + message: string, replacements: {[key: string]: (string|string[])} = {}): string { /** * Step 1: resolve all multi-value placeholders like [�#5�|�*1:1��#2:1�|�#4:1�] * @@ -660,7 +662,7 @@ export function ɵɵi18nPostprocess( if (!list.length) { throw new Error(`i18n postprocess: unmatched ICU - ${match} with key: ${key}`); } - return list.shift() !; + return list.shift()!; } return match; }); @@ -687,9 +689,10 @@ export function ɵɵi18nEnd(): void { * See `i18nEnd` above. */ function i18nEndFirstPass(tView: TView, lView: LView) { - ngDevMode && assertEqual( - getBindingIndex(), tView.bindingStartIndex, - 'i18nEnd should be called before any binding'); + ngDevMode && + assertEqual( + getBindingIndex(), tView.bindingStartIndex, + 'i18nEnd should be called before any binding'); const rootIndex = i18nIndexStack[i18nIndexStackPointer--]; const tI18n = tView.data[rootIndex + HEADER_OFFSET] as TI18n; @@ -709,8 +712,9 @@ function i18nEndFirstPass(tView: TView, lView: LView) { } // Check if an element has any local refs and skip them const tNode = getTNode(tView, index); - if (tNode && (tNode.type === TNodeType.Container || tNode.type === TNodeType.Element || - tNode.type === TNodeType.ElementContainer) && + if (tNode && + (tNode.type === TNodeType.Container || tNode.type === TNodeType.Element || + tNode.type === TNodeType.ElementContainer) && tNode.localNames !== null) { // Divide by 2 to get the number of local refs, // since they are stored as an array that also includes directive indexes, @@ -725,8 +729,8 @@ function i18nEndFirstPass(tView: TView, lView: LView) { * Creates and stores the dynamic TNode, and unhooks it from the tree for now. */ function createDynamicNodeAtIndex( - tView: TView, lView: LView, index: number, type: TNodeType, native: RElement | RText | null, - name: string | null): TElementNode|TIcuContainerNode { + tView: TView, lView: LView, index: number, type: TNodeType, native: RElement|RText|null, + name: string|null): TElementNode|TIcuContainerNode { const previousOrParentTNode = getPreviousOrParentTNode(); ngDevMode && assertDataInRange(lView, index + HEADER_OFFSET); lView[index + HEADER_OFFSET] = native; @@ -766,16 +770,16 @@ function readCreateOpCodes( if (destinationNodeIndex === index) { // If the destination node is `i18nStart`, we don't have a // top-level node and we should use the host node instead - destinationTNode = lView[T_HOST] !; + destinationTNode = lView[T_HOST]!; } else { destinationTNode = getTNode(tView, destinationNodeIndex); } ngDevMode && assertDefined( - currentTNode !, + currentTNode!, `You need to create or select a node before you can insert it into the DOM`); previousTNode = - appendI18nNode(tView, currentTNode !, destinationTNode, previousTNode, lView); + appendI18nNode(tView, currentTNode!, destinationTNode, previousTNode, lView); break; case I18nMutateOpCode.Select: // Negative indicies indicate that a given TNode is a sibling node, not a parent node @@ -811,9 +815,10 @@ function readCreateOpCodes( case COMMENT_MARKER: const commentValue = createOpCodes[++i] as string; const commentNodeIndex = createOpCodes[++i] as number; - ngDevMode && assertEqual( - typeof commentValue, 'string', - `Expected "${commentValue}" to be a comment node value`); + ngDevMode && + assertEqual( + typeof commentValue, 'string', + `Expected "${commentValue}" to be a comment node value`); const commentRNode = renderer.createComment(commentValue); ngDevMode && ngDevMode.rendererCreateComment++; previousTNode = currentTNode; @@ -828,9 +833,10 @@ function readCreateOpCodes( case ELEMENT_MARKER: const tagNameValue = createOpCodes[++i] as string; const elementNodeIndex = createOpCodes[++i] as number; - ngDevMode && assertEqual( - typeof tagNameValue, 'string', - `Expected "${tagNameValue}" to be an element node tag name`); + ngDevMode && + assertEqual( + typeof tagNameValue, 'string', + `Expected "${tagNameValue}" to be an element node tag name`); const elementRNode = renderer.createElement(tagNameValue); ngDevMode && ngDevMode.rendererCreateElement++; previousTNode = currentTNode; @@ -850,7 +856,7 @@ function readCreateOpCodes( } function readUpdateOpCodes( - updateOpCodes: I18nUpdateOpCodes, icus: TIcu[] | null, bindingsStartIndex: number, + updateOpCodes: I18nUpdateOpCodes, icus: TIcu[]|null, bindingsStartIndex: number, changeMask: number, tView: TView, lView: LView, bypassCheckBit = false) { let caseCreated = false; for (let i = 0; i < updateOpCodes.length; i++) { @@ -887,7 +893,7 @@ function readUpdateOpCodes( break; case I18nUpdateOpCode.IcuSwitch: tIcuIndex = updateOpCodes[++j] as number; - tIcu = icus ![tIcuIndex]; + tIcu = icus![tIcuIndex]; icuTNode = getTNode(tView, nodeIndex) as TIcuContainerNode; // If there is an active case, delete the old nodes if (icuTNode.activeCaseIndex !== null) { @@ -910,7 +916,7 @@ function readUpdateOpCodes( const activeIndex = nestedIcuTNode.activeCaseIndex; if (activeIndex !== null) { const nestedIcuTIndex = removeOpCode >>> I18nMutateOpCode.SHIFT_REF; - const nestedTIcu = icus ![nestedIcuTIndex]; + const nestedTIcu = icus![nestedIcuTIndex]; addAllToArray(nestedTIcu.remove[activeIndex], removeCodes); } break; @@ -929,7 +935,7 @@ function readUpdateOpCodes( break; case I18nUpdateOpCode.IcuUpdate: tIcuIndex = updateOpCodes[++j] as number; - tIcu = icus ![tIcuIndex]; + tIcu = icus![tIcuIndex]; icuTNode = getTNode(tView, nodeIndex) as TIcuContainerNode; if (icuTNode.activeCaseIndex !== null) { readUpdateOpCodes( @@ -1215,7 +1221,7 @@ function parseIcuCase( if (!inertBodyElement) { throw new Error('Unable to generate inert body element'); } - const wrapper = getTemplateContent(inertBodyElement !) as Element || inertBodyElement; + const wrapper = getTemplateContent(inertBodyElement!) as Element || inertBodyElement; const opCodes: IcuCase = {vars: 0, childIcus: [], create: [], remove: [], update: []}; parseNodes(wrapper.firstChild, opCodes, parentIndex, nestedIcus, tIcus, expandoStartIndex); return opCodes; @@ -1234,7 +1240,7 @@ const NESTED_ICU = /�(\d+)�/; * @param expandoStartIndex Expando start index for the current ICU expression */ function parseNodes( - currentNode: Node | null, icuCase: IcuCase, parentIndex: number, nestedIcus: IcuExpression[], + currentNode: Node|null, icuCase: IcuCase, parentIndex: number, nestedIcus: IcuExpression[], tIcus: TIcu[], expandoStartIndex: number) { if (currentNode) { const nestedIcusToCreate: [IcuExpression, number][] = []; @@ -1254,7 +1260,7 @@ function parseNodes( parentIndex << I18nMutateOpCode.SHIFT_PARENT | I18nMutateOpCode.AppendChild); const elAttrs = element.attributes; for (let i = 0; i < elAttrs.length; i++) { - const attr = elAttrs.item(i) !; + const attr = elAttrs.item(i)!; const lowerAttrName = attr.name.toLowerCase(); const hasBinding = !!attr.value.match(BINDING_REGEXP); // we assume the input string is safe, unless it's using a binding @@ -1276,8 +1282,8 @@ function parseNodes( } } else { ngDevMode && - console.warn( - `WARNING: ignoring unsafe attribute value ${lowerAttrName} on element ${tagName} (see http://g.co/ng/security#xss)`); + console.warn(`WARNING: ignoring unsafe attribute value ${ + lowerAttrName} on element ${tagName} (see http://g.co/ng/security#xss)`); } } else { icuCase.create.push( @@ -1324,7 +1330,7 @@ function parseNodes( // We do not handle any other type of element icuCase.vars--; } - currentNode = nextNode !; + currentNode = nextNode!; } for (let i = 0; i < nestedIcusToCreate.length; i++) { diff --git a/packages/core/src/render3/index.ts b/packages/core/src/render3/index.ts index d88585000efae..cea4adee29992 100644 --- a/packages/core/src/render3/index.ts +++ b/packages/core/src/render3/index.ts @@ -16,13 +16,14 @@ import {getComponent, getDirectives, getHostElement, getRenderedText} from './ut export {ComponentFactory, ComponentFactoryResolver, ComponentRef, injectComponentFactoryResolver} from './component_ref'; export {ɵɵgetFactoryOf, ɵɵgetInheritedFactory} from './di'; - +export {getLocaleId, setLocaleId, ɵɵi18n, ɵɵi18nApply, ɵɵi18nAttributes, ɵɵi18nEnd, ɵɵi18nExp, ɵɵi18nPostprocess, ɵɵi18nStart,} from './i18n'; // clang-format off export { detectChanges, markDirty, store, tick, + ɵɵadvance, ɵɵattribute, ɵɵattributeInterpolate1, @@ -54,7 +55,6 @@ export { ɵɵcontainerRefreshStart, ɵɵdirectiveInject, - ɵɵinvalidFactory, ɵɵelement, ɵɵelementContainer, @@ -69,7 +69,9 @@ export { ɵɵembeddedViewStart, ɵɵgetCurrentView, + ɵɵhostProperty, ɵɵinjectAttribute, + ɵɵinvalidFactory, ɵɵlistener, @@ -81,7 +83,6 @@ export { ɵɵprojection, ɵɵprojectionDef, - ɵɵhostProperty, ɵɵproperty, ɵɵpropertyInterpolate, ɵɵpropertyInterpolate1, @@ -98,7 +99,6 @@ export { // TODO: remove `select` once we've refactored all of the tests not to use it. ɵɵselect, - ɵɵadvance, ɵɵstyleMap, ɵɵstyleMapInterpolate1, ɵɵstyleMapInterpolate2, @@ -139,37 +139,14 @@ export { ɵɵupdateSyntheticHostBinding, } from './instructions/all'; export {RenderFlags} from './interfaces/definition'; -export {CssSelectorList, ProjectionSlots} from './interfaces/projection'; - -export { - ɵɵrestoreView, - - ɵɵenableBindings, - ɵɵdisableBindings, -} from './state'; - -export { - ɵɵi18n, - ɵɵi18nAttributes, - ɵɵi18nExp, - ɵɵi18nStart, - ɵɵi18nEnd, - ɵɵi18nApply, - ɵɵi18nPostprocess, - getLocaleId, - setLocaleId, -} from './i18n'; - -export {NgModuleFactory, NgModuleRef, NgModuleType} from './ng_module_ref'; - export { AttributeMarker } from './interfaces/node'; - +export {CssSelectorList, ProjectionSlots} from './interfaces/projection'; export { setClassMetadata, } from './metadata'; - +export {NgModuleFactory, NgModuleRef, NgModuleType} from './ng_module_ref'; export { ɵɵpipe, ɵɵpipeBind1, @@ -178,16 +155,6 @@ export { ɵɵpipeBind4, ɵɵpipeBindV, } from './pipe'; - -export { - ɵɵqueryRefresh, - ɵɵviewQuery, - ɵɵstaticViewQuery, - ɵɵloadQuery, - ɵɵcontentQuery, - ɵɵstaticContentQuery -} from './query'; - export { ɵɵpureFunction0, ɵɵpureFunction1, @@ -200,41 +167,51 @@ export { ɵɵpureFunction8, ɵɵpureFunctionV, } from './pure_function'; +export { + ɵɵcontentQuery, + ɵɵloadQuery, + ɵɵqueryRefresh, + ɵɵstaticContentQuery +, + ɵɵstaticViewQuery, + ɵɵviewQuery} from './query'; +export { + ɵɵdisableBindings, -export {ɵɵtemplateRefExtractor, ɵɵinjectPipeChangeDetectorRef} from './view_engine_compatibility_prebound'; - -export {ɵɵresolveWindow, ɵɵresolveDocument, ɵɵresolveBody} from './util/misc_utils'; - + ɵɵenableBindings, + ɵɵrestoreView, +} from './state'; +export {NO_CHANGE} from './tokens'; +export { ɵɵresolveBody, ɵɵresolveDocument,ɵɵresolveWindow} from './util/misc_utils'; +export { ɵɵinjectPipeChangeDetectorRef,ɵɵtemplateRefExtractor} from './view_engine_compatibility_prebound'; // clang-format on export { ComponentDef, - ɵɵComponentDefWithMeta, - ɵɵFactoryDef, ComponentTemplate, ComponentType, DirectiveDef, - ɵɵDirectiveDefWithMeta, DirectiveType, - ɵɵNgOnChangesFeature, - ɵɵCopyDefinitionFeature, - ɵɵInheritDefinitionFeature, - ɵɵProvidersFeature, - PipeDef, - ɵɵPipeDefWithMeta, + getComponent, + getDirectives, + getHostElement, + getRenderedText, LifecycleHooksFeature, + PipeDef, + renderComponent, + whenRendered, + ɵɵComponentDefWithMeta, + ɵɵCopyDefinitionFeature, ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineNgModule, ɵɵdefinePipe, - getHostElement, - getComponent, - getDirectives, - getRenderedText, - renderComponent, + ɵɵDirectiveDefWithMeta, + ɵɵFactoryDef, + ɵɵInheritDefinitionFeature, + ɵɵNgOnChangesFeature, + ɵɵPipeDefWithMeta, + ɵɵProvidersFeature, ɵɵsetComponentScope, ɵɵsetNgModuleScope, - whenRendered, }; - -export {NO_CHANGE} from './tokens'; diff --git a/packages/core/src/render3/instructions/advance.ts b/packages/core/src/render3/instructions/advance.ts index 551de37caf1fa..a4eabdd557bd6 100644 --- a/packages/core/src/render3/instructions/advance.ts +++ b/packages/core/src/render3/instructions/advance.ts @@ -19,21 +19,21 @@ import {getCheckNoChangesMode, getLView, getSelectedIndex, getTView, setSelected * * ```ts * (rf: RenderFlags, ctx: any) => { - * if (rf & 1) { - * text(0, 'Hello'); - * text(1, 'Goodbye') - * element(2, 'div'); - * } - * if (rf & 2) { - * advance(2); // Advance twice to the
. - * property('title', 'test'); - * } - * } - * ``` - * @param delta Number of elements to advance forwards by. - * - * @codeGenApi - */ + * if (rf & 1) { + * text(0, 'Hello'); + * text(1, 'Goodbye') + * element(2, 'div'); + * } + * if (rf & 2) { + * advance(2); // Advance twice to the
. + * property('title', 'test'); + * } + * } + * ``` + * @param delta Number of elements to advance forwards by. + * + * @codeGenApi + */ export function ɵɵadvance(delta: number): void { ngDevMode && assertGreaterThan(delta, 0, 'Can only advance forward'); selectIndexInternal(getTView(), getLView(), getSelectedIndex() + delta, getCheckNoChangesMode()); diff --git a/packages/core/src/render3/instructions/attribute.ts b/packages/core/src/render3/instructions/attribute.ts index a3a2bfab8fba8..380eec1ba23f3 100644 --- a/packages/core/src/render3/instructions/attribute.ts +++ b/packages/core/src/render3/instructions/attribute.ts @@ -26,7 +26,7 @@ import {elementAttributeInternal, storePropertyBindingMetadata} from './shared'; * @codeGenApi */ export function ɵɵattribute( - name: string, value: any, sanitizer?: SanitizerFn | null, + name: string, value: any, sanitizer?: SanitizerFn|null, namespace?: string): typeof ɵɵattribute { const lView = getLView(); const bindingIndex = nextBindingIndex(); diff --git a/packages/core/src/render3/instructions/attribute_interpolation.ts b/packages/core/src/render3/instructions/attribute_interpolation.ts index 96f7e8b01e1a4..0de336c78af0f 100644 --- a/packages/core/src/render3/instructions/attribute_interpolation.ts +++ b/packages/core/src/render3/instructions/attribute_interpolation.ts @@ -130,9 +130,10 @@ export function ɵɵattributeInterpolate3( if (interpolatedValue !== NO_CHANGE) { const tNode = getSelectedTNode(); elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace); - ngDevMode && storePropertyBindingMetadata( - getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 3, prefix, i0, - i1, suffix); + ngDevMode && + storePropertyBindingMetadata( + getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 3, prefix, i0, i1, + suffix); } return ɵɵattributeInterpolate3; } @@ -177,9 +178,10 @@ export function ɵɵattributeInterpolate4( if (interpolatedValue !== NO_CHANGE) { const tNode = getSelectedTNode(); elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace); - ngDevMode && storePropertyBindingMetadata( - getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 4, prefix, i0, - i1, i2, suffix); + ngDevMode && + storePropertyBindingMetadata( + getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 4, prefix, i0, i1, i2, + suffix); } return ɵɵattributeInterpolate4; } @@ -227,9 +229,10 @@ export function ɵɵattributeInterpolate5( if (interpolatedValue !== NO_CHANGE) { const tNode = getSelectedTNode(); elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace); - ngDevMode && storePropertyBindingMetadata( - getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 5, prefix, i0, - i1, i2, i3, suffix); + ngDevMode && + storePropertyBindingMetadata( + getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 5, prefix, i0, i1, i2, + i3, suffix); } return ɵɵattributeInterpolate5; } @@ -279,9 +282,10 @@ export function ɵɵattributeInterpolate6( if (interpolatedValue !== NO_CHANGE) { const tNode = getSelectedTNode(); elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace); - ngDevMode && storePropertyBindingMetadata( - getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 6, prefix, i0, - i1, i2, i3, i4, suffix); + ngDevMode && + storePropertyBindingMetadata( + getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 6, prefix, i0, i1, i2, + i3, i4, suffix); } return ɵɵattributeInterpolate6; } @@ -333,9 +337,10 @@ export function ɵɵattributeInterpolate7( if (interpolatedValue !== NO_CHANGE) { const tNode = getSelectedTNode(); elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace); - ngDevMode && storePropertyBindingMetadata( - getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 7, prefix, i0, - i1, i2, i3, i4, i5, suffix); + ngDevMode && + storePropertyBindingMetadata( + getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 7, prefix, i0, i1, i2, + i3, i4, i5, suffix); } return ɵɵattributeInterpolate7; } @@ -389,9 +394,10 @@ export function ɵɵattributeInterpolate8( if (interpolatedValue !== NO_CHANGE) { const tNode = getSelectedTNode(); elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace); - ngDevMode && storePropertyBindingMetadata( - getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 8, prefix, i0, - i1, i2, i3, i4, i5, i6, suffix); + ngDevMode && + storePropertyBindingMetadata( + getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 8, prefix, i0, i1, i2, + i3, i4, i5, i6, suffix); } return ɵɵattributeInterpolate8; } diff --git a/packages/core/src/render3/instructions/change_detection.ts b/packages/core/src/render3/instructions/change_detection.ts index 3a78623e3c91e..c667cfac7c67d 100644 --- a/packages/core/src/render3/instructions/change_detection.ts +++ b/packages/core/src/render3/instructions/change_detection.ts @@ -35,7 +35,7 @@ export function detectChanges(component: {}): void { */ export function markDirty(component: {}): void { ngDevMode && assertDefined(component, 'component'); - const rootView = markViewDirty(getComponentViewByInstance(component)) !; + const rootView = markViewDirty(getComponentViewByInstance(component))!; ngDevMode && assertDefined(rootView[CONTEXT], 'rootContext should be defined'); scheduleTick(rootView[CONTEXT] as RootContext, RootContextFlags.DetectChanges); diff --git a/packages/core/src/render3/instructions/container.ts b/packages/core/src/render3/instructions/container.ts index 70c0ce0cd888c..4685b665c2d14 100644 --- a/packages/core/src/render3/instructions/container.ts +++ b/packages/core/src/render3/instructions/container.ts @@ -13,11 +13,12 @@ import {ACTIVE_INDEX, CONTAINER_HEADER_OFFSET, LContainer} from '../interfaces/c import {ComponentTemplate} from '../interfaces/definition'; import {LocalRefExtractor, TAttributes, TContainerNode, TNode, TNodeType, TViewNode} from '../interfaces/node'; import {isDirectiveHost} from '../interfaces/type_checks'; -import {FLAGS, HEADER_OFFSET, InitPhaseState, LView, LViewFlags, RENDERER, TView, TViewType, T_HOST} from '../interfaces/view'; +import {FLAGS, HEADER_OFFSET, InitPhaseState, LView, LViewFlags, RENDERER, T_HOST, TView, TViewType} from '../interfaces/view'; import {assertNodeType} from '../node_assert'; import {appendChild, removeView} from '../node_manipulation'; import {getBindingIndex, getCheckNoChangesMode, getIsParent, getLView, getPreviousOrParentTNode, getTView, setIsNotParent, setPreviousOrParentTNode} from '../state'; import {getConstant, getLContainerActiveIndex, load} from '../util/view_utils'; + import {addToViewTree, createDirectivesInstances, createLContainer, createTNode, createTView, getOrCreateTNode, resolveDirectives, saveResolvedLocalsInData} from './shared'; @@ -45,9 +46,9 @@ export function ɵɵcontainer(index: number): void { } function templateFirstCreatePass( - index: number, tView: TView, lView: LView, templateFn: ComponentTemplate| null, - decls: number, vars: number, tagName?: string | null, attrsIndex?: number | null, - localRefsIndex?: number | null): TContainerNode { + index: number, tView: TView, lView: LView, templateFn: ComponentTemplate|null, + decls: number, vars: number, tagName?: string|null, attrsIndex?: number|null, + localRefsIndex?: number|null): TContainerNode { ngDevMode && assertFirstCreatePass(tView); ngDevMode && ngDevMode.firstCreatePass++; const tViewConsts = tView.consts; @@ -94,8 +95,8 @@ function templateFirstCreatePass( * @codeGenApi */ export function ɵɵtemplate( - index: number, templateFn: ComponentTemplate| null, decls: number, vars: number, - tagName?: string | null, attrsIndex?: number | null, localRefsIndex?: number | null, + index: number, templateFn: ComponentTemplate|null, decls: number, vars: number, + tagName?: string|null, attrsIndex?: number|null, localRefsIndex?: number|null, localRefExtractor?: LocalRefExtractor) { const lView = getLView(); const tView = getTView(); @@ -172,7 +173,7 @@ export function ɵɵcontainerRefreshEnd(): void { } else { ngDevMode && assertNodeType(previousOrParentTNode, TNodeType.View); ngDevMode && assertHasParent(previousOrParentTNode); - previousOrParentTNode = previousOrParentTNode.parent !; + previousOrParentTNode = previousOrParentTNode.parent!; setPreviousOrParentTNode(previousOrParentTNode, false); } @@ -188,11 +189,12 @@ export function ɵɵcontainerRefreshEnd(): void { } function containerInternal( - tView: TView, lView: LView, nodeIndex: number, tagName: string | null, - attrs: TAttributes | null): TContainerNode { - ngDevMode && assertEqual( - getBindingIndex(), tView.bindingStartIndex, - 'container nodes should be created before any bindings'); + tView: TView, lView: LView, nodeIndex: number, tagName: string|null, + attrs: TAttributes|null): TContainerNode { + ngDevMode && + assertEqual( + getBindingIndex(), tView.bindingStartIndex, + 'container nodes should be created before any bindings'); const adjustedIndex = nodeIndex + HEADER_OFFSET; ngDevMode && assertDataInRange(lView, nodeIndex + HEADER_OFFSET); diff --git a/packages/core/src/render3/instructions/di.ts b/packages/core/src/render3/instructions/di.ts index 71a2f8b6d910b..5c0be8f07962a 100644 --- a/packages/core/src/render3/instructions/di.ts +++ b/packages/core/src/render3/instructions/di.ts @@ -37,10 +37,10 @@ import {getLView, getPreviousOrParentTNode} from '../state'; * * @codeGenApi */ -export function ɵɵdirectiveInject(token: Type| InjectionToken): T; -export function ɵɵdirectiveInject(token: Type| InjectionToken, flags: InjectFlags): T; +export function ɵɵdirectiveInject(token: Type|InjectionToken): T; +export function ɵɵdirectiveInject(token: Type|InjectionToken, flags: InjectFlags): T; export function ɵɵdirectiveInject( - token: Type| InjectionToken, flags = InjectFlags.Default): T|null { + token: Type|InjectionToken, flags = InjectFlags.Default): T|null { const lView = getLView(); // Fall back to inject() if view hasn't been created. This situation can happen in tests // if inject utilities are used before bootstrapping. diff --git a/packages/core/src/render3/instructions/element.ts b/packages/core/src/render3/instructions/element.ts index 52eda6249bcef..2810fa4073da6 100644 --- a/packages/core/src/render3/instructions/element.ts +++ b/packages/core/src/render3/instructions/element.ts @@ -10,23 +10,24 @@ import {assertDataInRange, assertDefined, assertEqual} from '../../util/assert'; import {assertFirstCreatePass, assertHasParent} from '../assert'; import {attachPatchData} from '../context_discovery'; import {registerPostOrderHooks} from '../hooks'; -import {TAttributes, TElementNode, TNode, TNodeType, hasClassInput, hasStyleInput} from '../interfaces/node'; +import {hasClassInput, hasStyleInput, TAttributes, TElementNode, TNode, TNodeType} from '../interfaces/node'; import {RElement} from '../interfaces/renderer'; import {isContentQueryHost, isDirectiveHost} from '../interfaces/type_checks'; -import {HEADER_OFFSET, LView, RENDERER, TVIEW, TView, T_HOST} from '../interfaces/view'; +import {HEADER_OFFSET, LView, RENDERER, T_HOST, TVIEW, TView} from '../interfaces/view'; import {assertNodeType} from '../node_assert'; import {appendChild, writeDirectClass, writeDirectStyle} from '../node_manipulation'; import {decreaseElementDepthCount, getBindingIndex, getElementDepthCount, getIsParent, getLView, getNamespace, getPreviousOrParentTNode, getTView, increaseElementDepthCount, setIsNotParent, setPreviousOrParentTNode} from '../state'; import {computeStaticStyling} from '../styling/static_styling'; import {setUpAttributes} from '../util/attrs_utils'; import {getConstant} from '../util/view_utils'; + import {setDirectiveInputsWhichShadowsStyling} from './property'; import {createDirectivesInstances, elementCreate, executeContentQueries, getOrCreateTNode, matchingSchemas, resolveDirectives, saveResolvedLocalsInData} from './shared'; function elementStartFirstCreatePass( index: number, tView: TView, lView: LView, native: RElement, name: string, - attrsIndex?: number | null, localRefsIndex?: number): TElementNode { + attrsIndex?: number|null, localRefsIndex?: number): TElementNode { ngDevMode && assertFirstCreatePass(tView); ngDevMode && ngDevMode.firstCreatePass++; @@ -64,14 +65,15 @@ function elementStartFirstCreatePass( * @codeGenApi */ export function ɵɵelementStart( - index: number, name: string, attrsIndex?: number | null, localRefsIndex?: number): void { + index: number, name: string, attrsIndex?: number|null, localRefsIndex?: number): void { const lView = getLView(); const tView = getTView(); const adjustedIndex = HEADER_OFFSET + index; - ngDevMode && assertEqual( - getBindingIndex(), tView.bindingStartIndex, - 'elements should be created before any bindings'); + ngDevMode && + assertEqual( + getBindingIndex(), tView.bindingStartIndex, + 'elements should be created before any bindings'); ngDevMode && ngDevMode.rendererCreateElement++; ngDevMode && assertDataInRange(lView, adjustedIndex); @@ -128,7 +130,7 @@ export function ɵɵelementEnd(): void { setIsNotParent(); } else { ngDevMode && assertHasParent(getPreviousOrParentTNode()); - previousOrParentTNode = previousOrParentTNode.parent !; + previousOrParentTNode = previousOrParentTNode.parent!; setPreviousOrParentTNode(previousOrParentTNode, false); } @@ -142,7 +144,7 @@ export function ɵɵelementEnd(): void { if (tView.firstCreatePass) { registerPostOrderHooks(tView, previousOrParentTNode); if (isContentQueryHost(previousOrParentTNode)) { - tView.queries !.elementEnd(previousOrParentTNode); + tView.queries!.elementEnd(previousOrParentTNode); } } @@ -166,7 +168,7 @@ export function ɵɵelementEnd(): void { * @codeGenApi */ export function ɵɵelement( - index: number, name: string, attrsIndex?: number | null, localRefsIndex?: number): void { + index: number, name: string, attrsIndex?: number|null, localRefsIndex?: number): void { ɵɵelementStart(index, name, attrsIndex, localRefsIndex); ɵɵelementEnd(); } @@ -198,11 +200,11 @@ function warnAboutUnknownElement( if (isUnknown && !matchingSchemas(tView, lView, tagName)) { let warning = `'${tagName}' is not a known element:\n`; - warning += - `1. If '${tagName}' is an Angular component, then verify that it is part of this module.\n`; + warning += `1. If '${ + tagName}' is an Angular component, then verify that it is part of this module.\n`; if (tagName && tagName.indexOf('-') > -1) { - warning += - `2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`; + warning += `2. If '${ + tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`; } else { warning += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`; diff --git a/packages/core/src/render3/instructions/element_container.ts b/packages/core/src/render3/instructions/element_container.ts index 54f1cd9dd31b9..d7e3549c6175b 100644 --- a/packages/core/src/render3/instructions/element_container.ts +++ b/packages/core/src/render3/instructions/element_container.ts @@ -11,7 +11,7 @@ import {attachPatchData} from '../context_discovery'; import {registerPostOrderHooks} from '../hooks'; import {TAttributes, TElementContainerNode, TNodeType} from '../interfaces/node'; import {isContentQueryHost, isDirectiveHost} from '../interfaces/type_checks'; -import {HEADER_OFFSET, LView, RENDERER, TView, T_HOST} from '../interfaces/view'; +import {HEADER_OFFSET, LView, RENDERER, T_HOST, TView} from '../interfaces/view'; import {assertNodeType} from '../node_assert'; import {appendChild} from '../node_manipulation'; import {getBindingIndex, getIsParent, getLView, getPreviousOrParentTNode, getTView, setIsNotParent, setPreviousOrParentTNode} from '../state'; @@ -21,7 +21,7 @@ import {getConstant} from '../util/view_utils'; import {createDirectivesInstances, executeContentQueries, getOrCreateTNode, resolveDirectives, saveResolvedLocalsInData} from './shared'; function elementContainerStartFirstCreatePass( - index: number, tView: TView, lView: LView, attrsIndex?: number | null, + index: number, tView: TView, lView: LView, attrsIndex?: number|null, localRefsIndex?: number): TElementContainerNode { ngDevMode && ngDevMode.firstCreatePass++; @@ -61,15 +61,16 @@ function elementContainerStartFirstCreatePass( * @codeGenApi */ export function ɵɵelementContainerStart( - index: number, attrsIndex?: number | null, localRefsIndex?: number): void { + index: number, attrsIndex?: number|null, localRefsIndex?: number): void { const lView = getLView(); const tView = getTView(); const adjustedIndex = index + HEADER_OFFSET; ngDevMode && assertDataInRange(lView, adjustedIndex); - ngDevMode && assertEqual( - getBindingIndex(), tView.bindingStartIndex, - 'element containers should be created before any bindings'); + ngDevMode && + assertEqual( + getBindingIndex(), tView.bindingStartIndex, + 'element containers should be created before any bindings'); const tNode = tView.firstCreatePass ? elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) : @@ -104,7 +105,7 @@ export function ɵɵelementContainerEnd(): void { setIsNotParent(); } else { ngDevMode && assertHasParent(previousOrParentTNode); - previousOrParentTNode = previousOrParentTNode.parent !; + previousOrParentTNode = previousOrParentTNode.parent!; setPreviousOrParentTNode(previousOrParentTNode, false); } @@ -113,7 +114,7 @@ export function ɵɵelementContainerEnd(): void { if (tView.firstCreatePass) { registerPostOrderHooks(tView, previousOrParentTNode); if (isContentQueryHost(previousOrParentTNode)) { - tView.queries !.elementEnd(previousOrParentTNode); + tView.queries!.elementEnd(previousOrParentTNode); } } } @@ -129,7 +130,7 @@ export function ɵɵelementContainerEnd(): void { * @codeGenApi */ export function ɵɵelementContainer( - index: number, attrsIndex?: number | null, localRefsIndex?: number): void { + index: number, attrsIndex?: number|null, localRefsIndex?: number): void { ɵɵelementContainerStart(index, attrsIndex, localRefsIndex); ɵɵelementContainerEnd(); } diff --git a/packages/core/src/render3/instructions/embedded_view.ts b/packages/core/src/render3/instructions/embedded_view.ts index 777d22911baa2..971d04214f954 100644 --- a/packages/core/src/render3/instructions/embedded_view.ts +++ b/packages/core/src/render3/instructions/embedded_view.ts @@ -11,7 +11,7 @@ import {assertLContainerOrUndefined} from '../assert'; import {ACTIVE_INDEX, ActiveIndexFlag, CONTAINER_HEADER_OFFSET, LContainer} from '../interfaces/container'; import {RenderFlags} from '../interfaces/definition'; import {TContainerNode, TNodeType} from '../interfaces/node'; -import {CONTEXT, LView, LViewFlags, PARENT, TVIEW, TView, TViewType, T_HOST} from '../interfaces/view'; +import {CONTEXT, LView, LViewFlags, PARENT, T_HOST, TVIEW, TView, TViewType} from '../interfaces/view'; import {assertNodeType} from '../node_assert'; import {insertView, removeView} from '../node_manipulation'; import {enterView, getIsParent, getLView, getPreviousOrParentTNode, getTView, leaveView, setIsParent, setPreviousOrParentTNode} from '../state'; @@ -34,7 +34,7 @@ export function ɵɵembeddedViewStart(viewBlockId: number, decls: number, vars: const previousOrParentTNode = getPreviousOrParentTNode(); // The previous node can be a view node if we are processing an inline for loop const containerTNode = previousOrParentTNode.type === TNodeType.View ? - previousOrParentTNode.parent ! : + previousOrParentTNode.parent! : previousOrParentTNode; const lContainer = lView[containerTNode.index] as LContainer; @@ -141,5 +141,5 @@ export function ɵɵembeddedViewEnd(): void { const lContainer = lView[PARENT] as LContainer; ngDevMode && assertLContainerOrUndefined(lContainer); leaveView(); - setPreviousOrParentTNode(viewHost !, false); + setPreviousOrParentTNode(viewHost!, false); } diff --git a/packages/core/src/render3/instructions/host_property.ts b/packages/core/src/render3/instructions/host_property.ts index cc662152dcc16..800519c932450 100644 --- a/packages/core/src/render3/instructions/host_property.ts +++ b/packages/core/src/render3/instructions/host_property.ts @@ -28,7 +28,7 @@ import {elementPropertyInternal, loadComponentRenderer, storePropertyBindingMeta * @codeGenApi */ export function ɵɵhostProperty( - propName: string, value: T, sanitizer?: SanitizerFn | null): typeof ɵɵhostProperty { + propName: string, value: T, sanitizer?: SanitizerFn|null): typeof ɵɵhostProperty { const lView = getLView(); const bindingIndex = nextBindingIndex(); if (bindingUpdated(lView, bindingIndex, value)) { @@ -63,8 +63,8 @@ export function ɵɵhostProperty( * @codeGenApi */ export function ɵɵupdateSyntheticHostBinding( - propName: string, value: T | NO_CHANGE, - sanitizer?: SanitizerFn | null): typeof ɵɵupdateSyntheticHostBinding { + propName: string, value: T|NO_CHANGE, + sanitizer?: SanitizerFn|null): typeof ɵɵupdateSyntheticHostBinding { const lView = getLView(); const bindingIndex = nextBindingIndex(); if (bindingUpdated(lView, bindingIndex, value)) { diff --git a/packages/core/src/render3/instructions/interpolation.ts b/packages/core/src/render3/instructions/interpolation.ts index 21ef666c231aa..8b775b6691ece 100644 --- a/packages/core/src/render3/instructions/interpolation.ts +++ b/packages/core/src/render3/instructions/interpolation.ts @@ -102,10 +102,9 @@ export function interpolation4( const different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3); incrementBindingIndex(4); - return different ? - prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + - renderStringify(v3) + suffix : - NO_CHANGE; + return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + + renderStringify(v2) + i2 + renderStringify(v3) + suffix : + NO_CHANGE; } /** @@ -119,10 +118,9 @@ export function interpolation5( different = bindingUpdated(lView, bindingIndex + 4, v4) || different; incrementBindingIndex(5); - return different ? - prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + - renderStringify(v3) + i3 + renderStringify(v4) + suffix : - NO_CHANGE; + return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + suffix : + NO_CHANGE; } /** @@ -154,11 +152,10 @@ export function interpolation7( different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different; incrementBindingIndex(7); - return different ? - prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + - renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + i5 + - renderStringify(v6) + suffix : - NO_CHANGE; + return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 + + renderStringify(v5) + i5 + renderStringify(v6) + suffix : + NO_CHANGE; } /** @@ -173,9 +170,8 @@ export function interpolation8( different = bindingUpdated4(lView, bindingIndex + 4, v4, v5, v6, v7) || different; incrementBindingIndex(8); - return different ? - prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 + - renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + i5 + - renderStringify(v6) + i6 + renderStringify(v7) + suffix : - NO_CHANGE; + return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + + renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 + + renderStringify(v5) + i5 + renderStringify(v6) + i6 + renderStringify(v7) + suffix : + NO_CHANGE; } diff --git a/packages/core/src/render3/instructions/listener.ts b/packages/core/src/render3/instructions/listener.ts index 981924a988033..dc7cc4faefa18 100644 --- a/packages/core/src/render3/instructions/listener.ts +++ b/packages/core/src/render3/instructions/listener.ts @@ -11,12 +11,13 @@ import {assertDataInRange} from '../../util/assert'; import {isObservable} from '../../util/lang'; import {EMPTY_OBJ} from '../empty'; import {PropertyAliasValue, TNode, TNodeFlags, TNodeType} from '../interfaces/node'; -import {GlobalTargetResolver, RElement, Renderer3, isProceduralRenderer} from '../interfaces/renderer'; +import {GlobalTargetResolver, isProceduralRenderer, RElement, Renderer3} from '../interfaces/renderer'; import {isDirectiveHost} from '../interfaces/type_checks'; import {CLEANUP, FLAGS, LView, LViewFlags, RENDERER, TView} from '../interfaces/view'; import {assertNodeOfPossibleTypes} from '../node_assert'; import {getLView, getPreviousOrParentTNode, getTView} from '../state'; import {getComponentLViewByIndex, getNativeByTNode, unwrapRNode} from '../util/view_utils'; + import {getLCleanup, handleError, loadComponentRenderer, markViewDirty} from './shared'; @@ -47,26 +48,26 @@ export function ɵɵlistener( } /** -* Registers a synthetic host listener (e.g. `(@foo.start)`) on a component. -* -* This instruction is for compatibility purposes and is designed to ensure that a -* synthetic host listener (e.g. `@HostListener('@foo.start')`) properly gets rendered -* in the component's renderer. Normally all host listeners are evaluated with the -* parent component's renderer, but, in the case of animation @triggers, they need -* to be evaluated with the sub component's renderer (because that's where the -* animation triggers are defined). -* -* Do not use this instruction as a replacement for `listener`. This instruction -* only exists to ensure compatibility with the ViewEngine's host binding behavior. -* -* @param eventName Name of the event -* @param listenerFn The function to be called when event emits -* @param useCapture Whether or not to use capture in event listener -* @param eventTargetResolver Function that returns global target information in case this listener -* should be attached to a global object like window, document or body + * Registers a synthetic host listener (e.g. `(@foo.start)`) on a component. + * + * This instruction is for compatibility purposes and is designed to ensure that a + * synthetic host listener (e.g. `@HostListener('@foo.start')`) properly gets rendered + * in the component's renderer. Normally all host listeners are evaluated with the + * parent component's renderer, but, in the case of animation @triggers, they need + * to be evaluated with the sub component's renderer (because that's where the + * animation triggers are defined). + * + * Do not use this instruction as a replacement for `listener`. This instruction + * only exists to ensure compatibility with the ViewEngine's host binding behavior. + * + * @param eventName Name of the event + * @param listenerFn The function to be called when event emits + * @param useCapture Whether or not to use capture in event listener + * @param eventTargetResolver Function that returns global target information in case this listener + * should be attached to a global object like window, document or body * * @codeGenApi -*/ + */ export function ɵɵcomponentHostSyntheticListener( eventName: string, listenerFn: (e?: any) => any, useCapture = false, eventTargetResolver?: GlobalTargetResolver): typeof ɵɵcomponentHostSyntheticListener { @@ -94,7 +95,7 @@ function findExistingListener( // We have found a matching event name on the same node but it might not have been // registered yet, so we must explicitly verify entries in the LView cleanup data // structures. - const lCleanup = lView[CLEANUP] !; + const lCleanup = lView[CLEANUP]!; const listenerIdxInLCleanup = tCleanup[i + 2]; return lCleanup.length > listenerIdxInLCleanup ? lCleanup[listenerIdxInLCleanup] : null; } @@ -124,8 +125,9 @@ function listenerInternal( // register a listener and store its cleanup function on LView. const lCleanup = getLCleanup(lView); - ngDevMode && assertNodeOfPossibleTypes( - tNode, TNodeType.Element, TNodeType.Container, TNodeType.ElementContainer); + ngDevMode && + assertNodeOfPossibleTypes( + tNode, TNodeType.Element, TNodeType.Container, TNodeType.ElementContainer); let processOutputs = true; @@ -207,8 +209,8 @@ function listenerInternal( const output = directiveInstance[minifiedName]; if (ngDevMode && !isObservable(output)) { - throw new Error( - `@Output ${minifiedName} not initialized in '${directiveInstance.constructor.name}'.`); + throw new Error(`@Output ${minifiedName} not initialized in '${ + directiveInstance.constructor.name}'.`); } const subscription = output.subscribe(listenerFn); diff --git a/packages/core/src/render3/instructions/projection.ts b/packages/core/src/render3/instructions/projection.ts index b432a37d646d8..c6ded02f7a6bd 100644 --- a/packages/core/src/render3/instructions/projection.ts +++ b/packages/core/src/render3/instructions/projection.ts @@ -79,9 +79,9 @@ export function ɵɵprojectionDef(projectionSlots?: ProjectionSlots): void { // If no explicit projection slots are defined, fall back to a single // projection slot with the wildcard selector. const numProjectionSlots = projectionSlots ? projectionSlots.length : 1; - const projectionHeads: (TNode | null)[] = componentNode.projection = - newArray(numProjectionSlots, null !as TNode); - const tails: (TNode | null)[] = projectionHeads.slice(); + const projectionHeads: (TNode|null)[] = componentNode.projection = + newArray(numProjectionSlots, null! as TNode); + const tails: (TNode|null)[] = projectionHeads.slice(); let componentChild: TNode|null = componentNode.child; @@ -91,7 +91,7 @@ export function ɵɵprojectionDef(projectionSlots?: ProjectionSlots): void { if (slotIndex !== null) { if (tails[slotIndex]) { - tails[slotIndex] !.projectionNext = componentChild; + tails[slotIndex]!.projectionNext = componentChild; } else { projectionHeads[slotIndex] = componentChild; } @@ -119,7 +119,7 @@ export function setDelayProjection(value: boolean) { * - 1 based index of the selector from the {@link projectionDef} * * @codeGenApi -*/ + */ export function ɵɵprojection( nodeIndex: number, selectorIndex: number = 0, attrs?: TAttributes): void { const lView = getLView(); diff --git a/packages/core/src/render3/instructions/property.ts b/packages/core/src/render3/instructions/property.ts index 5867fc9eca8e0..ab79a35bcdd12 100644 --- a/packages/core/src/render3/instructions/property.ts +++ b/packages/core/src/render3/instructions/property.ts @@ -33,7 +33,7 @@ import {elementPropertyInternal, setInputsForProperty, storePropertyBindingMetad * @codeGenApi */ export function ɵɵproperty( - propName: string, value: T, sanitizer?: SanitizerFn | null): typeof ɵɵproperty { + propName: string, value: T, sanitizer?: SanitizerFn|null): typeof ɵɵproperty { const lView = getLView(); const bindingIndex = nextBindingIndex(); if (bindingUpdated(lView, bindingIndex, value)) { @@ -52,7 +52,7 @@ export function ɵɵproperty( */ export function setDirectiveInputsWhichShadowsStyling( tView: TView, tNode: TNode, lView: LView, value: any, isClassBased: boolean) { - const inputs = tNode.inputs !; + const inputs = tNode.inputs!; const property = isClassBased ? 'class' : 'style'; // We support both 'class' and `className` hence the fallback. setInputsForProperty(tView, lView, inputs[property], property, value); diff --git a/packages/core/src/render3/instructions/property_interpolation.ts b/packages/core/src/render3/instructions/property_interpolation.ts index 373f5912116bd..6059d1985b003 100644 --- a/packages/core/src/render3/instructions/property_interpolation.ts +++ b/packages/core/src/render3/instructions/property_interpolation.ts @@ -88,8 +88,9 @@ export function ɵɵpropertyInterpolate1( const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false); - ngDevMode && storePropertyBindingMetadata( - tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix); + ngDevMode && + storePropertyBindingMetadata( + tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix); } return ɵɵpropertyInterpolate1; } @@ -134,8 +135,9 @@ export function ɵɵpropertyInterpolate2( const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false); - ngDevMode && storePropertyBindingMetadata( - tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix); + ngDevMode && + storePropertyBindingMetadata( + tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix); } return ɵɵpropertyInterpolate2; } @@ -183,8 +185,9 @@ export function ɵɵpropertyInterpolate3( const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false); - ngDevMode && storePropertyBindingMetadata( - tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix); + ngDevMode && + storePropertyBindingMetadata( + tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix); } return ɵɵpropertyInterpolate3; } @@ -408,9 +411,10 @@ export function ɵɵpropertyInterpolate7( const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false); - ngDevMode && storePropertyBindingMetadata( - tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, - i5, suffix); + ngDevMode && + storePropertyBindingMetadata( + tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, + suffix); } return ɵɵpropertyInterpolate7; } @@ -470,9 +474,10 @@ export function ɵɵpropertyInterpolate8( const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false); - ngDevMode && storePropertyBindingMetadata( - tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, - i5, i6, suffix); + ngDevMode && + storePropertyBindingMetadata( + tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, + suffix); } return ɵɵpropertyInterpolate8; } diff --git a/packages/core/src/render3/instructions/style_prop_interpolation.ts b/packages/core/src/render3/instructions/style_prop_interpolation.ts index cde0b3335b559..86eaff4cb5c8d 100644 --- a/packages/core/src/render3/instructions/style_prop_interpolation.ts +++ b/packages/core/src/render3/instructions/style_prop_interpolation.ts @@ -39,7 +39,7 @@ import {checkStylingProperty} from './styling'; */ export function ɵɵstylePropInterpolate1( prop: string, prefix: string, v0: any, suffix: string, - valueSuffix?: string | null): typeof ɵɵstylePropInterpolate1 { + valueSuffix?: string|null): typeof ɵɵstylePropInterpolate1 { const lView = getLView(); const interpolatedValue = interpolation1(lView, prefix, v0, suffix); checkStylingProperty(prop, interpolatedValue, valueSuffix, false); @@ -76,7 +76,7 @@ export function ɵɵstylePropInterpolate1( */ export function ɵɵstylePropInterpolate2( prop: string, prefix: string, v0: any, i0: string, v1: any, suffix: string, - valueSuffix?: string | null): typeof ɵɵstylePropInterpolate2 { + valueSuffix?: string|null): typeof ɵɵstylePropInterpolate2 { const lView = getLView(); const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix); checkStylingProperty(prop, interpolatedValue, valueSuffix, false); @@ -115,7 +115,7 @@ export function ɵɵstylePropInterpolate2( */ export function ɵɵstylePropInterpolate3( prop: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, suffix: string, - valueSuffix?: string | null): typeof ɵɵstylePropInterpolate3 { + valueSuffix?: string|null): typeof ɵɵstylePropInterpolate3 { const lView = getLView(); const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix); checkStylingProperty(prop, interpolatedValue, valueSuffix, false); @@ -156,7 +156,7 @@ export function ɵɵstylePropInterpolate3( */ export function ɵɵstylePropInterpolate4( prop: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, - v3: any, suffix: string, valueSuffix?: string | null): typeof ɵɵstylePropInterpolate4 { + v3: any, suffix: string, valueSuffix?: string|null): typeof ɵɵstylePropInterpolate4 { const lView = getLView(); const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix); checkStylingProperty(prop, interpolatedValue, valueSuffix, false); @@ -200,7 +200,7 @@ export function ɵɵstylePropInterpolate4( export function ɵɵstylePropInterpolate5( prop: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, suffix: string, - valueSuffix?: string | null): typeof ɵɵstylePropInterpolate5 { + valueSuffix?: string|null): typeof ɵɵstylePropInterpolate5 { const lView = getLView(); const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix); @@ -247,7 +247,7 @@ export function ɵɵstylePropInterpolate5( export function ɵɵstylePropInterpolate6( prop: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, suffix: string, - valueSuffix?: string | null): typeof ɵɵstylePropInterpolate6 { + valueSuffix?: string|null): typeof ɵɵstylePropInterpolate6 { const lView = getLView(); const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix); @@ -297,7 +297,7 @@ export function ɵɵstylePropInterpolate6( export function ɵɵstylePropInterpolate7( prop: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, suffix: string, - valueSuffix?: string | null): typeof ɵɵstylePropInterpolate7 { + valueSuffix?: string|null): typeof ɵɵstylePropInterpolate7 { const lView = getLView(); const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix); @@ -349,7 +349,7 @@ export function ɵɵstylePropInterpolate7( export function ɵɵstylePropInterpolate8( prop: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, i6: string, v7: any, - suffix: string, valueSuffix?: string | null): typeof ɵɵstylePropInterpolate8 { + suffix: string, valueSuffix?: string|null): typeof ɵɵstylePropInterpolate8 { const lView = getLView(); const interpolatedValue = interpolation8( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix); @@ -388,7 +388,7 @@ export function ɵɵstylePropInterpolate8( * @codeGenApi */ export function ɵɵstylePropInterpolateV( - prop: string, values: any[], valueSuffix?: string | null): typeof ɵɵstylePropInterpolateV { + prop: string, values: any[], valueSuffix?: string|null): typeof ɵɵstylePropInterpolateV { const lView = getLView(); const interpolatedValue = interpolationV(lView, values); checkStylingProperty(prop, interpolatedValue, valueSuffix, false); diff --git a/packages/core/src/render3/instructions/styling.ts b/packages/core/src/render3/instructions/styling.ts index 6370ebd952b3d..16c53d4f2796e 100644 --- a/packages/core/src/render3/instructions/styling.ts +++ b/packages/core/src/render3/instructions/styling.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {SafeValue, unwrapSafeValue} from '../../sanitization/bypass'; import {stylePropNeedsSanitization, ɵɵsanitizeStyle} from '../../sanitization/sanitization'; @@ -19,7 +19,7 @@ import {DirectiveDef} from '../interfaces/definition'; import {AttributeMarker, TAttributes, TNode, TNodeFlags, TNodeType} from '../interfaces/node'; import {RElement, Renderer3} from '../interfaces/renderer'; import {SanitizerFn} from '../interfaces/sanitization'; -import {TStylingKey, TStylingRange, getTStylingRangeNext, getTStylingRangeNextDuplicate, getTStylingRangePrev, getTStylingRangePrevDuplicate} from '../interfaces/styling'; +import {getTStylingRangeNext, getTStylingRangeNextDuplicate, getTStylingRangePrev, getTStylingRangePrevDuplicate, TStylingKey, TStylingRange} from '../interfaces/styling'; import {HEADER_OFFSET, LView, RENDERER, TData, TView} from '../interfaces/view'; import {applyStyling} from '../node_manipulation'; import {getCurrentDirectiveIndex, getCurrentStyleSanitizer, getLView, getSelectedIndex, getTView, incrementBindingIndex, setCurrentStyleSanitizer} from '../state'; @@ -27,6 +27,7 @@ import {insertTStylingBinding} from '../styling/style_binding_list'; import {getLastParsedKey, getLastParsedValue, parseClassName, parseClassNameNext, parseStyle, parseStyleNext} from '../styling/styling_parser'; import {NO_CHANGE} from '../tokens'; import {getNativeByIndex} from '../util/view_utils'; + import {setDirectiveInputsWhichShadowsStyling} from './property'; @@ -46,7 +47,7 @@ import {setDirectiveInputsWhichShadowsStyling} from './property'; * * @codeGenApi */ -export function ɵɵstyleSanitizer(sanitizer: StyleSanitizeFn | null): void { +export function ɵɵstyleSanitizer(sanitizer: StyleSanitizeFn|null): void { setCurrentStyleSanitizer(sanitizer); } @@ -72,8 +73,8 @@ export function ɵɵstyleSanitizer(sanitizer: StyleSanitizeFn | null): void { * @codeGenApi */ export function ɵɵstyleProp( - prop: string, value: string | number | SafeValue | undefined | null, - suffix?: string | null): typeof ɵɵstyleProp { + prop: string, value: string|number|SafeValue|undefined|null, + suffix?: string|null): typeof ɵɵstyleProp { checkStylingProperty(prop, value, suffix, false); return ɵɵstyleProp; } @@ -93,8 +94,7 @@ export function ɵɵstyleProp( * * @codeGenApi */ -export function ɵɵclassProp( - className: string, value: boolean | undefined | null): typeof ɵɵclassProp { +export function ɵɵclassProp(className: string, value: boolean|undefined|null): typeof ɵɵclassProp { checkStylingProperty(className, value, null, true); return ɵɵclassProp; } @@ -119,7 +119,7 @@ export function ɵɵclassProp( * * @codeGenApi */ -export function ɵɵstyleMap(styles: {[styleName: string]: any} | string | undefined | null): void { +export function ɵɵstyleMap(styles: {[styleName: string]: any}|string|undefined|null): void { checkStylingMap(styleKeyValueArraySet, styleStringParser, styles, false); } @@ -158,8 +158,8 @@ export function styleStringParser(keyValueArray: KeyValueArray, text: strin * * @codeGenApi */ -export function ɵɵclassMap( - classes: {[className: string]: boolean | undefined | null} | string | undefined | null): void { +export function ɵɵclassMap(classes: {[className: string]: boolean|undefined|null}|string|undefined| + null): void { checkStylingMap(keyValueArraySet, classStringParser, classes, true); } @@ -187,8 +187,8 @@ export function classStringParser(keyValueArray: KeyValueArray, text: strin * @param isClassBased `true` if `class` change (`false` if `style`) */ export function checkStylingProperty( - prop: string, value: any | NO_CHANGE, - suffixOrSanitizer: SanitizerFn | string | undefined | null, isClassBased: boolean): void { + prop: string, value: any|NO_CHANGE, suffixOrSanitizer: SanitizerFn|string|undefined|null, + isClassBased: boolean): void { const lView = getLView(); const tView = getTView(); // Styling instructions use 2 slots per binding. @@ -289,14 +289,14 @@ function isInHostBindings(tView: TView, bindingIndex: number): boolean { } /** -* Collects the necessary information to insert the binding into a linked list of style bindings -* using `insertTStylingBinding`. -* -* @param tView `TView` where the binding linked list will be stored. -* @param tStylingKey Property/key of the binding. -* @param bindingIndex Index of binding associated with the `prop` -* @param isClassBased `true` if `class` change (`false` if `style`) -*/ + * Collects the necessary information to insert the binding into a linked list of style bindings + * using `insertTStylingBinding`. + * + * @param tView `TView` where the binding linked list will be stored. + * @param tStylingKey Property/key of the binding. + * @param bindingIndex Index of binding associated with the `prop` + * @param isClassBased `true` if `class` change (`false` if `style`) + */ function stylingFirstUpdatePass( tView: TView, tStylingKey: TStylingKey, bindingIndex: number, isClassBased: boolean): void { ngDevMode && assertFirstUpdatePass(tView); @@ -477,9 +477,10 @@ function getTemplateHeadTStylingKey(tData: TData, tNode: TNode, isClassBased: bo function setTemplateHeadTStylingKey( tData: TData, tNode: TNode, isClassBased: boolean, tStylingKey: TStylingKey): void { const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings; - ngDevMode && assertNotEqual( - getTStylingRangeNext(bindings), 0, - 'Expecting to have at least one template styling binding.'); + ngDevMode && + assertNotEqual( + getTStylingRangeNext(bindings), 0, + 'Expecting to have at least one template styling binding.'); tData[getTStylingRangePrev(bindings)] = tStylingKey; } @@ -523,7 +524,7 @@ function collectResidual(tData: TData, tNode: TNode, isClassBased: boolean): Key * @param isClassBased `true` if `class` (`false` if `style`) */ function collectStylingFromDirectives( - hostDirectiveDef: DirectiveDef| null, tData: TData, tNode: TNode, stylingKey: TStylingKey, + hostDirectiveDef: DirectiveDef|null, tData: TData, tNode: TNode, stylingKey: TStylingKey, isClassBased: boolean): TStylingKey { // We need to loop because there can be directives which have `hostAttrs` but don't have // `hostBindings` so this loop catches up to the current directive.. @@ -559,7 +560,7 @@ function collectStylingFromDirectives( * @param isClassBased `true` if `class` (`false` if `style`) */ function collectStylingFromTAttrs( - stylingKey: TStylingKey | undefined, attrs: TAttributes | null, + stylingKey: TStylingKey|undefined, attrs: TAttributes|null, isClassBased: boolean): TStylingKey { const desiredMarker = isClassBased ? AttributeMarker.Classes : AttributeMarker.Styles; let currentMarker = AttributeMarker.ImplicitAttributes; @@ -711,7 +712,7 @@ function updateStylingMap( setKey = newKey; setValue = newValue; } - } else if (newKey === null || oldKey !== null && oldKey < newKey !) { + } else if (newKey === null || oldKey !== null && oldKey < newKey!) { // DELETE: oldKey key is missing or we did not find the oldKey in the newValue // (because the keyValueArray is sorted and `newKey` is found later alphabetically). // `"background" < "color"` so we need to delete `"background"` because it is not found in the @@ -754,7 +755,7 @@ function updateStylingMap( */ function updateStyling( tView: TView, tNode: TNode, lView: LView, renderer: Renderer3, prop: string, - value: string | undefined | null | boolean, isClassBased: boolean, bindingIndex: number) { + value: string|undefined|null|boolean, isClassBased: boolean, bindingIndex: number) { if (tNode.type !== TNodeType.Element) { // It is possible to have styling on non-elements (such as ng-container). // This is rare, but it does happen. In such a case, just ignore the binding. @@ -811,7 +812,7 @@ function updateStyling( * @param isClassBased `true` if `class` (`false` if `style`) */ function findStylingValue( - tData: TData, tNode: TNode | null, lView: LView, prop: string, index: number, + tData: TData, tNode: TNode|null, lView: LView, prop: string, index: number, isClassBased: boolean): any { // `TNode` to use for resolving static styling. Also controls search direction. // - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true. @@ -856,7 +857,7 @@ function findStylingValue( // consult residual styling let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles; if (residual != null /** OR residual !=== undefined */) { - value = keyValueArrayGet(residual !, prop); + value = keyValueArrayGet(residual!, prop); } } return value; @@ -884,7 +885,7 @@ function isStylingValuePresent(value: any): boolean { * @param suffixOrSanitizer */ function normalizeAndApplySuffixOrSanitizer( - value: any, suffixOrSanitizer: SanitizerFn | string | undefined | null): string|null|undefined| + value: any, suffixOrSanitizer: SanitizerFn|string|undefined|null): string|null|undefined| boolean { if (value == null /** || value === undefined */) { // do nothing diff --git a/packages/core/src/render3/instructions/text.ts b/packages/core/src/render3/instructions/text.ts index b7b1c909060bb..a6ab9338223b3 100644 --- a/packages/core/src/render3/instructions/text.ts +++ b/packages/core/src/render3/instructions/text.ts @@ -27,9 +27,10 @@ export function ɵɵtext(index: number, value: string = ''): void { const tView = getTView(); const adjustedIndex = index + HEADER_OFFSET; - ngDevMode && assertEqual( - getBindingIndex(), tView.bindingStartIndex, - 'text nodes should be created before any bindings'); + ngDevMode && + assertEqual( + getBindingIndex(), tView.bindingStartIndex, + 'text nodes should be created before any bindings'); ngDevMode && assertDataInRange(lView, adjustedIndex); const tNode = tView.firstCreatePass ? diff --git a/packages/core/src/render3/interfaces/definition.ts b/packages/core/src/render3/interfaces/definition.ts index f89895e2d880f..31ea33b9da1fb 100644 --- a/packages/core/src/render3/interfaces/definition.ts +++ b/packages/core/src/render3/interfaces/definition.ts @@ -22,7 +22,7 @@ export type ComponentTemplate = { // Note: the ctx parameter is typed as T|U, as using only U would prevent a template with // e.g. ctx: {} from being assigned to ComponentTemplate as TypeScript won't infer U = any // in that scenario. By including T this incompatibility is resolved. - (rf: RenderFlags, ctx: T | U): void; + (rf: RenderFlags, ctx: T|U): void; }; /** @@ -72,7 +72,9 @@ export const enum RenderFlags { * A subclass of `Type` which has a static `ɵcmp`:`ComponentDef` field making it * consumable for rendering. */ -export interface ComponentType extends Type { ɵcmp: never; } +export interface ComponentType extends Type { + ɵcmp: never; +} /** * A subclass of `Type` which has a static `ɵdir`:`DirectiveDef` field making it @@ -87,7 +89,9 @@ export interface DirectiveType extends Type { * A subclass of `Type` which has a static `ɵpipe`:`PipeDef` field making it * consumable for rendering. */ -export interface PipeType extends Type { ɵpipe: never; } +export interface PipeType extends Type { + ɵpipe: never; +} /** * An object literal of this type is used to represent the metadata of a constructor dependency. @@ -99,7 +103,7 @@ export type CtorDependency = { * attribute name is a dynamic expression instead of a string literal, this will be the unknown * type. */ - attribute?: string | unknown; + attribute?: string|unknown; /** * If `@Optional()` is used, this key is set to true. @@ -120,14 +124,17 @@ export type CtorDependency = { * If `@SkipSelf` is used, this key is set to true. */ skipSelf?: true; -} | null; +}|null; /** * @codeGenApi */ export type ɵɵDirectiveDefWithMeta< - T, Selector extends string, ExportAs extends string[], InputMap extends{[key: string]: string}, - OutputMap extends{[key: string]: string}, QueryFields extends string[]> = DirectiveDef; + T, Selector extends string, ExportAs extends + string[], InputMap extends {[key: string]: string}, + OutputMap extends {[key: string]: string}, + QueryFields extends string[]> = + DirectiveDef; /** * Runtime link information for Directives. @@ -268,9 +275,10 @@ export interface DirectiveDef { * @codeGenApi */ export type ɵɵComponentDefWithMeta< - T, Selector extends String, ExportAs extends string[], InputMap extends{[key: string]: string}, - OutputMap extends{[key: string]: string}, QueryFields extends string[], - NgContentSelectors extends string[]> = ComponentDef; + T, Selector extends String, ExportAs extends + string[], InputMap extends {[key: string]: string}, + OutputMap extends {[key: string]: string}, QueryFields extends + string[], NgContentSelectors extends string[]> = ComponentDef; /** * @codeGenApi @@ -467,14 +475,14 @@ export interface ComponentDefFeature { * * The function is necessary to be able to support forward declarations. */ -export type DirectiveDefListOrFactory = (() => DirectiveDefList) | DirectiveDefList; +export type DirectiveDefListOrFactory = (() => DirectiveDefList)|DirectiveDefList; -export type DirectiveDefList = (DirectiveDef| ComponentDef)[]; +export type DirectiveDefList = (DirectiveDef|ComponentDef)[]; -export type DirectiveTypesOrFactory = (() => DirectiveTypeList) | DirectiveTypeList; +export type DirectiveTypesOrFactory = (() => DirectiveTypeList)|DirectiveTypeList; export type DirectiveTypeList = - (DirectiveType| ComponentType| + (DirectiveType|ComponentType| Type/* Type as workaround for: Microsoft/TypeScript/issues/4881 */)[]; export type HostBindingsFunction = (rf: RenderFlags, ctx: U) => void; @@ -484,14 +492,14 @@ export type HostBindingsFunction = (rf: RenderFlags, ctx: U) => * * The function is necessary to be able to support forward declarations. */ -export type PipeDefListOrFactory = (() => PipeDefList) | PipeDefList; +export type PipeDefListOrFactory = (() => PipeDefList)|PipeDefList; export type PipeDefList = PipeDef[]; -export type PipeTypesOrFactory = (() => PipeTypeList) | PipeTypeList; +export type PipeTypesOrFactory = (() => PipeTypeList)|PipeTypeList; export type PipeTypeList = - (PipeType| Type/* Type as workaround for: Microsoft/TypeScript/issues/4881 */)[]; + (PipeType|Type/* Type as workaround for: Microsoft/TypeScript/issues/4881 */)[]; // Note: This hack is necessary so we don't erroneously get a circular dependency diff --git a/packages/core/src/render3/interfaces/document.ts b/packages/core/src/render3/interfaces/document.ts index 3e630c38ee458..30ca7fbf0fab1 100644 --- a/packages/core/src/render3/interfaces/document.ts +++ b/packages/core/src/render3/interfaces/document.ts @@ -31,7 +31,7 @@ let DOCUMENT: Document|undefined = undefined; * * @param document The object representing the global `document` in this environment. */ -export function setDocument(document: Document | undefined): void { +export function setDocument(document: Document|undefined): void { DOCUMENT = document; } @@ -52,5 +52,5 @@ export function getDocument(): Document { // this should not happen in Angular apps. // Once we support running ivy outside of Angular we will need to publish `setDocument()` as a // public API. Meanwhile we just return `undefined` and let the application fail. - return undefined !; + return undefined!; } diff --git a/packages/core/src/render3/interfaces/i18n.ts b/packages/core/src/render3/interfaces/i18n.ts index 98da1ca9c4298..4143415f42f1c 100644 --- a/packages/core/src/render3/interfaces/i18n.ts +++ b/packages/core/src/render3/interfaces/i18n.ts @@ -66,7 +66,9 @@ export const enum I18nMutateOpCode { export const ELEMENT_MARKER: ELEMENT_MARKER = { marker: 'element' }; -export interface ELEMENT_MARKER { marker: 'element'; } +export interface ELEMENT_MARKER { + marker: 'element'; +} /** * Marks that the next string is for comment. @@ -77,7 +79,9 @@ export const COMMENT_MARKER: COMMENT_MARKER = { marker: 'comment' }; -export interface COMMENT_MARKER { marker: 'comment'; } +export interface COMMENT_MARKER { + marker: 'comment'; +} /** * Array storing OpCode for dynamically creating `i18n` blocks. diff --git a/packages/core/src/render3/interfaces/injector.ts b/packages/core/src/render3/interfaces/injector.ts index a4324225394ed..270c38b8160c5 100644 --- a/packages/core/src/render3/interfaces/injector.ts +++ b/packages/core/src/render3/interfaces/injector.ts @@ -23,7 +23,9 @@ export const INJECTOR_BLOOM_PARENT_SIZE = 9; * The interfaces encodes number of parents `LView`s to traverse and index in the `LView` * pointing to the parent injector. */ -export interface RelativeInjectorLocation { __brand__: 'RelativeInjectorLocationFlags'; } +export interface RelativeInjectorLocation { + __brand__: 'RelativeInjectorLocationFlags'; +} export const enum RelativeInjectorLocationFlags { InjectorIndexMask = 0b111111111111111, @@ -114,20 +116,20 @@ export const NO_PARENT_INJECTOR: RelativeInjectorLocation = -1 as any; */ /** -* Factory for creating instances of injectors in the NodeInjector. -* -* This factory is complicated by the fact that it can resolve `multi` factories as well. -* -* NOTE: Some of the fields are optional which means that this class has two hidden classes. -* - One without `multi` support (most common) -* - One with `multi` values, (rare). -* -* Since VMs can cache up to 4 inline hidden classes this is OK. -* -* - Single factory: Only `resolving` and `factory` is defined. -* - `providers` factory: `componentProviders` is a number and `index = -1`. -* - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`. -*/ + * Factory for creating instances of injectors in the NodeInjector. + * + * This factory is complicated by the fact that it can resolve `multi` factories as well. + * + * NOTE: Some of the fields are optional which means that this class has two hidden classes. + * - One without `multi` support (most common) + * - One with `multi` values, (rare). + * + * Since VMs can cache up to 4 inline hidden classes this is OK. + * + * - Single factory: Only `resolving` and `factory` is defined. + * - `providers` factory: `componentProviders` is a number and `index = -1`. + * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`. + */ export class NodeInjectorFactory { /** * The inject implementation to be activated when using the factory. @@ -234,7 +236,8 @@ export class NodeInjectorFactory { /** * Set to `true` if the token is declared in `viewProviders` (or if it is component). */ - isViewProvider: boolean, injectImplementation: null| + isViewProvider: boolean, + injectImplementation: null| ((token: Type|InjectionToken, flags?: InjectFlags) => T)) { this.canSeeViewProviders = isViewProvider; this.injectImpl = injectImplementation; diff --git a/packages/core/src/render3/interfaces/node.ts b/packages/core/src/render3/interfaces/node.ts index e2d662f517c80..a60d7d5f80d42 100644 --- a/packages/core/src/render3/interfaces/node.ts +++ b/packages/core/src/render3/interfaces/node.ts @@ -90,8 +90,10 @@ export const enum TNodeProviderIndexes { /** The index of the first provider on this node is encoded on the least significant bits */ ProvidersStartIndexMask = 0b00000000000000001111111111111111, - /** The count of view providers from the component on this node is encoded on the 16 most - significant bits */ + /** + The count of view providers from the component on this node is encoded on the 16 most + significant bits + */ CptViewProvidersCountShift = 16, CptViewProvidersCountShifter = 0b00000000000000010000000000000000, } @@ -117,21 +119,21 @@ export const enum AttributeMarker { NamespaceURI = 0, /** - * Signals class declaration. - * - * Each value following `Classes` designates a class name to include on the element. - * ## Example: - * - * Given: - * ``` - *
... - * ``` - * - * the generated code is: - * ``` - * var _c1 = [AttributeMarker.Classes, 'foo', 'bar', 'baz']; - * ``` - */ + * Signals class declaration. + * + * Each value following `Classes` designates a class name to include on the element. + * ## Example: + * + * Given: + * ``` + *
... + * ``` + * + * the generated code is: + * ``` + * var _c1 = [AttributeMarker.Classes, 'foo', 'bar', 'baz']; + * ``` + */ Classes = 1, /** @@ -235,14 +237,14 @@ export const enum AttributeMarker { * - Special markers acting as flags to alter attributes processing. * - Parsed ngProjectAs selectors. */ -export type TAttributes = (string | AttributeMarker | CssSelector)[]; +export type TAttributes = (string|AttributeMarker|CssSelector)[]; /** * Constants that are associated with a view. Includes: * - Attribute arrays. * - Local definition arrays. */ -export type TConstants = (TAttributes | string)[]; +export type TConstants = (TAttributes|string)[]; /** * Binding data (flyweight) for a particular node that is shared between all templates @@ -700,7 +702,7 @@ export interface TProjectionNode extends TNode { /** * A union type representing all TNode types that can host a directive. */ -export type TDirectiveHostNode = TElementNode | TContainerNode | TElementContainerNode; +export type TDirectiveHostNode = TElementNode|TContainerNode|TElementContainerNode; /** * This mapping is necessary so we can set input properties and output listeners @@ -725,7 +727,7 @@ export type PropertyAliases = { * * e.g. [0, 'change-minified'] */ -export type PropertyAliasValue = (number | string)[]; +export type PropertyAliasValue = (number|string)[]; /** * This array contains information about input properties that @@ -745,7 +747,7 @@ export type PropertyAliasValue = (number | string)[]; * * e.g. [null, ['role-min', 'minified-input', 'button']] */ -export type InitialInputData = (InitialInputs | null)[]; +export type InitialInputData = (InitialInputs|null)[]; /** * Used by InitialInputData to store input properties @@ -766,7 +768,7 @@ export const unusedValueExportToPlacateAjd = 1; /** * Type representing a set of TNodes that can have local refs (`#foo`) placed on them. */ -export type TNodeWithLocalRefs = TContainerNode | TElementNode | TElementContainerNode; +export type TNodeWithLocalRefs = TContainerNode|TElementNode|TElementContainerNode; /** * Type for a function that extracts a value for a local refs. diff --git a/packages/core/src/render3/interfaces/player.ts b/packages/core/src/render3/interfaces/player.ts index 518aba8d28aca..37620de2118b4 100644 --- a/packages/core/src/render3/interfaces/player.ts +++ b/packages/core/src/render3/interfaces/player.ts @@ -25,7 +25,9 @@ export const enum BindingType { Style = 2, } -export interface BindingStore { setValue(prop: string, value: any): void; } +export interface BindingStore { + setValue(prop: string, value: any): void; +} /** * Defines the shape which produces the Player. @@ -50,7 +52,9 @@ export interface PlayerFactoryBuildFn { * `[style]`, `[style.prop]`, `[class]` and `[class.name]` template bindings * all accept a `PlayerFactory` as input and this player factories. */ -export interface PlayerFactory { '__brand__': 'Brand for PlayerFactory that nothing will match'; } +export interface PlayerFactory { + '__brand__': 'Brand for PlayerFactory that nothing will match'; +} export interface PlayerBuilder extends BindingStore { buildPlayer(currentPlayer: Player|null, isFirstRender: boolean): Player|undefined|null; @@ -63,7 +67,13 @@ export interface PlayerBuilder extends BindingStore { * code may compare state by checking if a number is higher or lower than * a certain numeric value. */ -export const enum PlayState {Pending = 0, Running = 1, Paused = 2, Finished = 100, Destroyed = 200} +export const enum PlayState { + Pending = 0, + Running = 1, + Paused = 2, + Finished = 100, + Destroyed = 200 +} /** * The context that stores all the active players and queued player factories present on an element. diff --git a/packages/core/src/render3/interfaces/projection.ts b/packages/core/src/render3/interfaces/projection.ts index 6657ab7ff9527..1ef2c6bca43cc 100644 --- a/packages/core/src/render3/interfaces/projection.ts +++ b/packages/core/src/render3/interfaces/projection.ts @@ -37,7 +37,7 @@ * * See more examples in node_selector_matcher_spec.ts */ -export type CssSelector = (string | SelectorFlags)[]; +export type CssSelector = (string|SelectorFlags)[]; /** * A list of CssSelectors. @@ -58,7 +58,7 @@ export type CssSelectorList = CssSelector[]; * using {@link ViewContainerRef#createComponent}. The last slot that specifies the * wildcard selector will retrieve all projectable nodes which do not match any selector. */ -export type ProjectionSlots = (CssSelectorList | '*')[]; +export type ProjectionSlots = (CssSelectorList|'*')[]; /** Flags used to build up CssSelectors */ export const enum SelectorFlags { diff --git a/packages/core/src/render3/interfaces/query.ts b/packages/core/src/render3/interfaces/query.ts index 2c5d14df12d6a..e184fa42566ff 100644 --- a/packages/core/src/render3/interfaces/query.ts +++ b/packages/core/src/render3/interfaces/query.ts @@ -145,7 +145,7 @@ export interface TQueries { template(tView: TView, tNode: TNode): void; /** - * A proxy method that iterates over all the TQueries in a given TView and calls the corresponding + * A proxy method that iterates over all the TQueries in a given TView and calls the corresponding * `embeddedTView` on each and every TQuery. * @param tNode */ diff --git a/packages/core/src/render3/interfaces/renderer.ts b/packages/core/src/render3/interfaces/renderer.ts index a61d7c4a90462..b34f5195eb297 100644 --- a/packages/core/src/render3/interfaces/renderer.ts +++ b/packages/core/src/render3/interfaces/renderer.ts @@ -24,9 +24,9 @@ export enum RendererStyleFlags3 { DashCase = 1 << 1 } -export type Renderer3 = ObjectOrientedRenderer3 | ProceduralRenderer3; +export type Renderer3 = ObjectOrientedRenderer3|ProceduralRenderer3; -export type GlobalTargetName = 'document' | 'window' | 'body'; +export type GlobalTargetName = 'document'|'window'|'body'; export type GlobalTargetResolver = (element: any) => { name: GlobalTargetName, target: EventTarget @@ -49,8 +49,8 @@ export interface ObjectOrientedRenderer3 { } /** Returns whether the `renderer` is a `ProceduralRenderer3` */ -export function isProceduralRenderer(renderer: ProceduralRenderer3 | ObjectOrientedRenderer3): - renderer is ProceduralRenderer3 { +export function isProceduralRenderer(renderer: ProceduralRenderer3| + ObjectOrientedRenderer3): renderer is ProceduralRenderer3 { return !!((renderer as any).listen); } @@ -104,8 +104,9 @@ export interface RendererFactory3 { } export const domRendererFactory3: RendererFactory3 = { - createRenderer: (hostElement: RElement | null, rendererType: RendererType2 | null): - Renderer3 => { return getDocument();} + createRenderer: (hostElement: RElement|null, rendererType: RendererType2|null): Renderer3 => { + return getDocument(); + } }; /** Subset of API needed for appending elements and text nodes. */ @@ -175,9 +176,13 @@ export interface RDomTokenList { remove(token: string): void; } -export interface RText extends RNode { textContent: string|null; } +export interface RText extends RNode { + textContent: string|null; +} -export interface RComment extends RNode { textContent: string|null; } +export interface RComment extends RNode { + textContent: string|null; +} // Note: This hack is necessary so we don't erroneously get a circular dependency // failure based on types. diff --git a/packages/core/src/render3/interfaces/styling.ts b/packages/core/src/render3/interfaces/styling.ts index e80ed1fbaee43..050b9756a321c 100644 --- a/packages/core/src/render3/interfaces/styling.ts +++ b/packages/core/src/render3/interfaces/styling.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {KeyValueArray} from '../../util/array_utils'; import {assertNumber, assertNumberInRange} from '../../util/assert'; @@ -14,7 +14,7 @@ import {assertNumber, assertNumberInRange} from '../../util/assert'; * * See: `TStylingKeyPrimitive` and `TStylingStatic` */ -export type TStylingKey = TStylingKeyPrimitive | TStylingStatic; +export type TStylingKey = TStylingKeyPrimitive|TStylingStatic; /** @@ -27,7 +27,7 @@ export type TStylingKey = TStylingKeyPrimitive | TStylingStatic; * is combined with directive which shadows its input `@Input('class')`. That way the binding * should not participate in the styling resolution. */ -export type TStylingKeyPrimitive = string | null | false; +export type TStylingKeyPrimitive = string|null|false; /** * Store the static values for the styling binding. @@ -119,7 +119,9 @@ export interface TStylingStatic extends KeyValueArray {} * * NOTE: `0` has special significance and represents `null` as in no additional pointer. */ -export interface TStylingRange { __brand__: 'TStylingRange'; } +export interface TStylingRange { + __brand__: 'TStylingRange'; +} /** * Shift and masks constants for encoding two numbers into and duplicate info into a single number. @@ -177,9 +179,8 @@ export function setTStylingRangePrev( tStylingRange: TStylingRange, previous: number): TStylingRange { ngDevMode && assertNumber(tStylingRange, 'expected number'); ngDevMode && assertNumberInRange(previous, 0, StylingRange.UNSIGNED_MASK); - return ( - ((tStylingRange as any as number) & ~StylingRange.PREV_MASK) | - (previous << StylingRange.PREV_SHIFT)) as any; + return (((tStylingRange as any as number) & ~StylingRange.PREV_MASK) | + (previous << StylingRange.PREV_SHIFT)) as any; } export function setTStylingRangePrevDuplicate(tStylingRange: TStylingRange): TStylingRange { @@ -195,9 +196,8 @@ export function getTStylingRangeNext(tStylingRange: TStylingRange): number { export function setTStylingRangeNext(tStylingRange: TStylingRange, next: number): TStylingRange { ngDevMode && assertNumber(tStylingRange, 'expected number'); ngDevMode && assertNumberInRange(next, 0, StylingRange.UNSIGNED_MASK); - return ( - ((tStylingRange as any as number) & ~StylingRange.NEXT_MASK) | // - next << StylingRange.NEXT_SHIFT) as any; + return (((tStylingRange as any as number) & ~StylingRange.NEXT_MASK) | // + next << StylingRange.NEXT_SHIFT) as any; } export function getTStylingRangeNextDuplicate(tStylingRange: TStylingRange): boolean { diff --git a/packages/core/src/render3/interfaces/type_checks.ts b/packages/core/src/render3/interfaces/type_checks.ts index eca8324340cb2..875c409466b49 100644 --- a/packages/core/src/render3/interfaces/type_checks.ts +++ b/packages/core/src/render3/interfaces/type_checks.ts @@ -15,10 +15,10 @@ import {FLAGS, LView, LViewFlags} from './view'; /** -* True if `value` is `LView`. -* @param value wrapped value of `RNode`, `LView`, `LContainer` -*/ -export function isLView(value: RNode | LView | LContainer | {} | null): value is LView { + * True if `value` is `LView`. + * @param value wrapped value of `RNode`, `LView`, `LContainer` + */ +export function isLView(value: RNode|LView|LContainer|{}|null): value is LView { return Array.isArray(value) && typeof value[TYPE] === 'object'; } @@ -26,7 +26,7 @@ export function isLView(value: RNode | LView | LContainer | {} | null): value is * True if `value` is `LContainer`. * @param value wrapped value of `RNode`, `LView`, `LContainer` */ -export function isLContainer(value: RNode | LView | LContainer | {} | null): value is LContainer { +export function isLContainer(value: RNode|LView|LContainer|{}|null): value is LContainer { return Array.isArray(value) && value[TYPE] === true; } diff --git a/packages/core/src/render3/jit/directive.ts b/packages/core/src/render3/jit/directive.ts index 06398cb75cb02..0397485773e37 100644 --- a/packages/core/src/render3/jit/directive.ts +++ b/packages/core/src/render3/jit/directive.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {R3DirectiveMetadataFacade, getCompilerFacade} from '../../compiler/compiler_facade'; +import {getCompilerFacade, R3DirectiveMetadataFacade} from '../../compiler/compiler_facade'; import {R3ComponentMetadataFacade, R3QueryMetadataFacade} from '../../compiler/compiler_facade_interface'; import {resolveForwardRef} from '../../di/forward_ref'; import {getReflect, reflectDependencies} from '../../di/jit/util'; @@ -95,12 +95,14 @@ export function compileComponent(type: Type, metadata: Component): void { const meta: R3ComponentMetadataFacade = { ...directiveMetadata(type, metadata), typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl), - template: metadata.template || '', preserveWhitespaces, + template: metadata.template || '', + preserveWhitespaces, styles: metadata.styles || EMPTY_ARRAY, animations: metadata.animations, directives: [], changeDetection: metadata.changeDetection, - pipes: new Map(), encapsulation, + pipes: new Map(), + encapsulation, interpolation: metadata.interpolation, viewProviders: metadata.viewProviders || null, }; @@ -135,7 +137,7 @@ export function compileComponent(type: Type, metadata: Component): void { function hasSelectorScope(component: Type): component is Type& {ngSelectorScope: Type} { - return (component as{ngSelectorScope?: any}).ngSelectorScope !== undefined; + return (component as {ngSelectorScope?: any}).ngSelectorScope !== undefined; } /** @@ -145,7 +147,7 @@ function hasSelectorScope(component: Type): component is Type& * In the event that compilation is not immediate, `compileDirective` will return a `Promise` which * will resolve when compilation completes and the directive becomes usable. */ -export function compileDirective(type: Type, directive: Directive | null): void { +export function compileDirective(type: Type, directive: Directive|null): void { let ngDirectiveDef: any = null; addDirectiveFactoryDef(type, directive || {}); @@ -179,7 +181,7 @@ function getDirectiveMetadata(type: Type, metadata: Directive) { return {metadata: facade, sourceMapUrl}; } -function addDirectiveFactoryDef(type: Type, metadata: Directive | Component) { +function addDirectiveFactoryDef(type: Type, metadata: Directive|Component) { let ngFactoryDef: any = null; Object.defineProperty(type, NG_FACTORY_DEF, { @@ -225,7 +227,7 @@ export function directiveMetadata(type: Type, metadata: Directive): R3Direc outputs: metadata.outputs || EMPTY_ARRAY, queries: extractQueriesMetadata(type, propMetadata, isContentQuery), lifecycle: {usesOnChanges: reflect.hasLifecycleHook(type, 'ngOnChanges')}, - typeSourceSpan: null !, + typeSourceSpan: null!, usesInheritance: !extendsDirectlyFromObject(type), exportAs: extractExportAs(metadata.exportAs), providers: metadata.providers || null, @@ -291,7 +293,7 @@ function extractQueriesMetadata( return queriesMeta; } -function extractExportAs(exportAs: string | undefined): string[]|null { +function extractExportAs(exportAs: string|undefined): string[]|null { return exportAs === undefined ? null : splitByComma(exportAs); } diff --git a/packages/core/src/render3/jit/module.ts b/packages/core/src/render3/jit/module.ts index 49b93eefd19f0..375c17322de5d 100644 --- a/packages/core/src/render3/jit/module.ts +++ b/packages/core/src/render3/jit/module.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {R3InjectorMetadataFacade, getCompilerFacade} from '../../compiler/compiler_facade'; +import {getCompilerFacade, R3InjectorMetadataFacade} from '../../compiler/compiler_facade'; import {resolveForwardRef} from '../../di/forward_ref'; import {NG_INJ_DEF} from '../../di/interface/defs'; import {reflectDependencies} from '../../di/jit/util'; @@ -70,7 +70,7 @@ export function flushModuleScopingQueueAsMuchAsPossible() { * an array of declarations, it will recurse to check each declaration in that array * (which may also be arrays). */ -function isResolvedDeclaration(declaration: any[] | Type): boolean { +function isResolvedDeclaration(declaration: any[]|Type): boolean { if (Array.isArray(declaration)) { return declaration.every(isResolvedDeclaration); } @@ -144,8 +144,9 @@ export function compileNgModuleDefs( Object.defineProperty(moduleType, NG_INJ_DEF, { get: () => { if (ngInjectorDef === null) { - ngDevMode && verifySemanticsOfNgModuleDef( - moduleType as any as NgModuleType, allowDuplicateDeclarationsInRoot); + ngDevMode && + verifySemanticsOfNgModuleDef( + moduleType as any as NgModuleType, allowDuplicateDeclarationsInRoot); const meta: R3InjectorMetadataFacade = { name: moduleType.name, type: moduleType, @@ -174,10 +175,10 @@ function verifySemanticsOfNgModuleDef( moduleType = resolveForwardRef(moduleType); let ngModuleDef: NgModuleDef; if (importingModule) { - ngModuleDef = getNgModuleDef(moduleType) !; + ngModuleDef = getNgModuleDef(moduleType)!; if (!ngModuleDef) { - throw new Error( - `Unexpected value '${moduleType.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`); + throw new Error(`Unexpected value '${moduleType.name}' imported by the module '${ + importingModule.name}'. Please add an @NgModule annotation.`); } } else { ngModuleDef = getNgModuleDef(moduleType, true); @@ -222,8 +223,8 @@ function verifySemanticsOfNgModuleDef( type = resolveForwardRef(type); const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef(type); if (!def) { - errors.push( - `Unexpected value '${stringifyForError(type)}' declared by the module '${stringifyForError(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`); + errors.push(`Unexpected value '${stringifyForError(type)}' declared by the module '${ + stringifyForError(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`); } } @@ -244,8 +245,8 @@ function verifySemanticsOfNgModuleDef( // Modules don't need to be declared or imported. if (combinedDeclarations.lastIndexOf(type) === -1) { // We are exporting something which we don't explicitly declare or import. - errors.push( - `Can't export ${kind} ${stringifyForError(type)} from ${stringifyForError(moduleType)} as it was neither declared nor imported!`); + errors.push(`Can't export ${kind} ${stringifyForError(type)} from ${ + stringifyForError(moduleType)} as it was neither declared nor imported!`); } } } @@ -257,9 +258,13 @@ function verifySemanticsOfNgModuleDef( if (!suppressErrors) { const modules = [existingModule, moduleType].map(stringifyForError).sort(); errors.push( - `Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${modules[0]} and ${modules[1]}! ` + - `Please consider moving ${stringifyForError(type)} to a higher module that imports ${modules[0]} and ${modules[1]}. ` + - `You can also create a new NgModule that exports and includes ${stringifyForError(type)} then import that NgModule in ${modules[0]} and ${modules[1]}.`); + `Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${ + modules[0]} and ${modules[1]}! ` + + `Please consider moving ${stringifyForError(type)} to a higher module that imports ${ + modules[0]} and ${modules[1]}. ` + + `You can also create a new NgModule that exports and includes ${ + stringifyForError( + type)} then import that NgModule in ${modules[0]} and ${modules[1]}.`); } } else { // Mark type as having owner. @@ -271,8 +276,9 @@ function verifySemanticsOfNgModuleDef( type = resolveForwardRef(type); const existingModule = ownerNgModule.get(type); if (!existingModule) { - errors.push( - `Component ${stringifyForError(type)} is not part of any NgModule or the module has not been imported into your module.`); + errors.push(`Component ${ + stringifyForError( + type)} is not part of any NgModule or the module has not been imported into your module.`); } } @@ -298,19 +304,19 @@ function verifySemanticsOfNgModuleDef( type = resolveForwardRef(type); if (getComponentDef(type) || getDirectiveDef(type)) { - throw new Error( - `Unexpected directive '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`); + throw new Error(`Unexpected directive '${type.name}' imported by the module '${ + importingModule.name}'. Please add an @NgModule annotation.`); } if (getPipeDef(type)) { - throw new Error( - `Unexpected pipe '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`); + throw new Error(`Unexpected pipe '${type.name}' imported by the module '${ + importingModule.name}'. Please add an @NgModule annotation.`); } } } -function unwrapModuleWithProvidersImports( - typeOrWithProviders: NgModuleType| {ngModule: NgModuleType}): NgModuleType { +function unwrapModuleWithProvidersImports(typeOrWithProviders: NgModuleType| + {ngModule: NgModuleType}): NgModuleType { typeOrWithProviders = resolveForwardRef(typeOrWithProviders); return (typeOrWithProviders as any).ngModule || typeOrWithProviders; } @@ -321,7 +327,7 @@ function getAnnotation(type: any, name: string): T|null { collect(type.decorators); return annotation; - function collect(annotations: any[] | null) { + function collect(annotations: any[]|null) { if (annotations) { annotations.forEach(readAnnotation); } @@ -391,7 +397,7 @@ function setScopeOnDeclaredComponents(moduleType: Type, ngModule: NgModule) if (declaration.hasOwnProperty(NG_COMP_DEF)) { // A `ɵcmp` field exists - go ahead and patch the component directly. const component = declaration as Type& {ɵcmp: ComponentDef}; - const componentDef = getComponentDef(component) !; + const componentDef = getComponentDef(component)!; patchComponentDefWithScope(componentDef, transitiveScopes); } else if ( !declaration.hasOwnProperty(NG_DIR_DEF) && !declaration.hasOwnProperty(NG_PIPE_DEF)) { @@ -410,11 +416,11 @@ export function patchComponentDefWithScope( componentDef.directiveDefs = () => Array.from(transitiveScopes.compilation.directives) .map( - dir => - dir.hasOwnProperty(NG_COMP_DEF) ? getComponentDef(dir) ! : getDirectiveDef(dir) !) + dir => dir.hasOwnProperty(NG_COMP_DEF) ? getComponentDef(dir)! : getDirectiveDef(dir)! + ) .filter(def => !!def); componentDef.pipeDefs = () => - Array.from(transitiveScopes.compilation.pipes).map(pipe => getPipeDef(pipe) !); + Array.from(transitiveScopes.compilation.pipes).map(pipe => getPipeDef(pipe)!); componentDef.schemas = transitiveScopes.schemas; // Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we @@ -437,7 +443,7 @@ export function transitiveScopesFor(moduleType: Type): NgModuleTransitiveS if (!isNgModule(moduleType)) { throw new Error(`${moduleType.name} does not have a module def (ɵmod property)`); } - const def = getNgModuleDef(moduleType) !; + const def = getNgModuleDef(moduleType)!; if (def.transitiveCompileScopes !== null) { return def.transitiveCompileScopes; @@ -473,7 +479,9 @@ export function transitiveScopesFor(moduleType: Type): NgModuleTransitiveS }); maybeUnwrapFn(def.declarations).forEach(declared => { - const declaredWithDefs = declared as Type& { ɵpipe?: any; }; + const declaredWithDefs = declared as Type& { + ɵpipe?: any; + }; if (getPipeDef(declaredWithDefs)) { scopes.compilation.pipes.add(declared); @@ -519,7 +527,7 @@ export function transitiveScopesFor(moduleType: Type): NgModuleTransitiveS return scopes; } -function expandModuleWithProviders(value: Type| ModuleWithProviders<{}>): Type { +function expandModuleWithProviders(value: Type|ModuleWithProviders<{}>): Type { if (isModuleWithProviders(value)) { return value.ngModule; } @@ -527,7 +535,7 @@ function expandModuleWithProviders(value: Type| ModuleWithProviders<{}>): T } function isModuleWithProviders(value: any): value is ModuleWithProviders<{}> { - return (value as{ngModule?: any}).ngModule !== undefined; + return (value as {ngModule?: any}).ngModule !== undefined; } function isNgModule(value: Type): value is Type&{ɵmod: NgModuleDef} { diff --git a/packages/core/src/render3/jit/pipe.ts b/packages/core/src/render3/jit/pipe.ts index 2ecd57799f07d..46975ae2ba55a 100644 --- a/packages/core/src/render3/jit/pipe.ts +++ b/packages/core/src/render3/jit/pipe.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {R3PipeMetadataFacade, getCompilerFacade} from '../../compiler/compiler_facade'; +import {getCompilerFacade, R3PipeMetadataFacade} from '../../compiler/compiler_facade'; import {reflectDependencies} from '../../di/jit/util'; import {Type} from '../../interface/type'; import {Pipe} from '../../metadata/directives'; diff --git a/packages/core/src/render3/metadata.ts b/packages/core/src/render3/metadata.ts index 4927c671e0fab..919b4ed375ae4 100644 --- a/packages/core/src/render3/metadata.ts +++ b/packages/core/src/render3/metadata.ts @@ -25,43 +25,46 @@ interface TypeWithMetadata extends Type { * tree-shaken away during production builds. */ export function setClassMetadata( - type: Type, decorators: any[] | null, ctorParameters: (() => any[]) | null, - propDecorators: {[field: string]: any} | null): void { + type: Type, decorators: any[]|null, ctorParameters: (() => any[])|null, + propDecorators: {[field: string]: any}|null): void { return noSideEffects(() => { - const clazz = type as TypeWithMetadata; + const clazz = type as TypeWithMetadata; - // We determine whether a class has its own metadata by taking the metadata from the parent - // constructor and checking whether it's the same as the subclass metadata below. We can't use - // `hasOwnProperty` here because it doesn't work correctly in IE10 for static fields that are - // defined by TS. See https://github.com/angular/angular/pull/28439#issuecomment-459349218. - const parentPrototype = clazz.prototype ? Object.getPrototypeOf(clazz.prototype) : null; - const parentConstructor: TypeWithMetadata|null = parentPrototype && parentPrototype.constructor; + // We determine whether a class has its own metadata by taking the metadata from the + // parent constructor and checking whether it's the same as the subclass metadata below. + // We can't use `hasOwnProperty` here because it doesn't work correctly in IE10 for + // static fields that are defined by TS. See + // https://github.com/angular/angular/pull/28439#issuecomment-459349218. + const parentPrototype = clazz.prototype ? Object.getPrototypeOf(clazz.prototype) : null; + const parentConstructor: TypeWithMetadata|null = + parentPrototype && parentPrototype.constructor; - if (decorators !== null) { - if (clazz.decorators !== undefined && - (!parentConstructor || parentConstructor.decorators !== clazz.decorators)) { - clazz.decorators.push(...decorators); - } else { - clazz.decorators = decorators; - } - } - if (ctorParameters !== null) { - // Rather than merging, clobber the existing parameters. If other projects exist which use - // tsickle-style annotations and reflect over them in the same way, this could cause issues, - // but that is vanishingly unlikely. - clazz.ctorParameters = ctorParameters; - } - if (propDecorators !== null) { - // The property decorator objects are merged as it is possible different fields have different - // decorator types. Decorators on individual fields are not merged, as it's also incredibly - // unlikely that a field will be decorated both with an Angular decorator and a non-Angular - // decorator that's also been downleveled. - if (clazz.propDecorators !== undefined && - (!parentConstructor || parentConstructor.propDecorators !== clazz.propDecorators)) { - clazz.propDecorators = {...clazz.propDecorators, ...propDecorators}; - } else { - clazz.propDecorators = propDecorators; - } - } - }) as never; + if (decorators !== null) { + if (clazz.decorators !== undefined && + (!parentConstructor || parentConstructor.decorators !== clazz.decorators)) { + clazz.decorators.push(...decorators); + } else { + clazz.decorators = decorators; + } + } + if (ctorParameters !== null) { + // Rather than merging, clobber the existing parameters. If other projects exist which + // use tsickle-style annotations and reflect over them in the same way, this could + // cause issues, but that is vanishingly unlikely. + clazz.ctorParameters = ctorParameters; + } + if (propDecorators !== null) { + // The property decorator objects are merged as it is possible different fields have + // different decorator types. Decorators on individual fields are not merged, as it's + // also incredibly unlikely that a field will be decorated both with an Angular + // decorator and a non-Angular decorator that's also been downleveled. + if (clazz.propDecorators !== undefined && + (!parentConstructor || + parentConstructor.propDecorators !== clazz.propDecorators)) { + clazz.propDecorators = {...clazz.propDecorators, ...propDecorators}; + } else { + clazz.propDecorators = propDecorators; + } + } + }) as never; } diff --git a/packages/core/src/render3/ng_module_ref.ts b/packages/core/src/render3/ng_module_ref.ts index e3c3326082f6a..5c6a8c8403ffe 100644 --- a/packages/core/src/render3/ng_module_ref.ts +++ b/packages/core/src/render3/ng_module_ref.ts @@ -9,7 +9,7 @@ import {Injector} from '../di/injector'; import {INJECTOR} from '../di/injector_compatibility'; import {InjectFlags} from '../di/interface/injector'; -import {R3Injector, createInjectorWithoutInjectorInstances} from '../di/r3_injector'; +import {createInjectorWithoutInjectorInstances, R3Injector} from '../di/r3_injector'; import {Type} from '../interface/type'; import {ComponentFactoryResolver as viewEngine_ComponentFactoryResolver} from '../linker/component_factory_resolver'; import {InternalNgModuleRef, NgModuleFactory as viewEngine_NgModuleFactory, NgModuleRef as viewEngine_NgModuleRef} from '../linker/ng_module_factory'; @@ -23,7 +23,9 @@ import {getNgLocaleIdDef, getNgModuleDef} from './definition'; import {setLocaleId} from './i18n'; import {maybeUnwrapFn} from './util/misc_utils'; -export interface NgModuleType extends Type { ɵmod: NgModuleDef; } +export interface NgModuleType extends Type { + ɵmod: NgModuleDef; +} export class NgModuleRef extends viewEngine_NgModuleRef implements InternalNgModuleRef { // tslint:disable-next-line:require-internal-with-underscore @@ -45,20 +47,23 @@ export class NgModuleRef extends viewEngine_NgModuleRef implements Interna constructor(ngModuleType: Type, public _parent: Injector|null) { super(); const ngModuleDef = getNgModuleDef(ngModuleType); - ngDevMode && assertDefined( - ngModuleDef, - `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`); + ngDevMode && + assertDefined( + ngModuleDef, + `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`); const ngLocaleIdDef = getNgLocaleIdDef(ngModuleType); ngLocaleIdDef && setLocaleId(ngLocaleIdDef); - this._bootstrapComponents = maybeUnwrapFn(ngModuleDef !.bootstrap); + this._bootstrapComponents = maybeUnwrapFn(ngModuleDef!.bootstrap); this._r3Injector = createInjectorWithoutInjectorInstances( - ngModuleType, _parent, - [ - {provide: viewEngine_NgModuleRef, useValue: this}, - {provide: viewEngine_ComponentFactoryResolver, useValue: this.componentFactoryResolver} - ], - stringify(ngModuleType)) as R3Injector; + ngModuleType, _parent, + [ + {provide: viewEngine_NgModuleRef, useValue: this}, { + provide: viewEngine_ComponentFactoryResolver, + useValue: this.componentFactoryResolver + } + ], + stringify(ngModuleType)) as R3Injector; // We need to resolve the injector types separately from the injector creation, because // the module might be trying to use this ref in its contructor for DI which will cause a @@ -79,12 +84,12 @@ export class NgModuleRef extends viewEngine_NgModuleRef implements Interna ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed'); const injector = this._r3Injector; !injector.destroyed && injector.destroy(); - this.destroyCbs !.forEach(fn => fn()); + this.destroyCbs!.forEach(fn => fn()); this.destroyCbs = null; } onDestroy(callback: () => void): void { ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed'); - this.destroyCbs !.push(callback); + this.destroyCbs!.push(callback); } } diff --git a/packages/core/src/render3/node_selector_matcher.ts b/packages/core/src/render3/node_selector_matcher.ts index 8b539d5bbcb85..5d724774b3814 100644 --- a/packages/core/src/render3/node_selector_matcher.ts +++ b/packages/core/src/render3/node_selector_matcher.ts @@ -46,7 +46,7 @@ function isCssClassMatching( } } else if (item === AttributeMarker.Classes) { // We found the classes section. Start searching for the class. - while (i < attrs.length && typeof(item = attrs[i++]) == 'string') { + while (i < attrs.length && typeof (item = attrs[i++]) == 'string') { // while we have strings if (item.toLowerCase() === cssClassToMatch) return true; } @@ -151,9 +151,10 @@ export function isNodeMatchingSelector( if (attrIndexInNode > nameOnlyMarkerIdx) { nodeAttrValue = ''; } else { - ngDevMode && assertNotEqual( - nodeAttrs[attrIndexInNode], AttributeMarker.NamespaceURI, - 'We do not match directives on namespaced attributes'); + ngDevMode && + assertNotEqual( + nodeAttrs[attrIndexInNode], AttributeMarker.NamespaceURI, + 'We do not match directives on namespaced attributes'); // we lowercase the attribute value to be able to match // selectors without case-sensitivity // (selectors are already in lowercase when generated) @@ -208,7 +209,7 @@ function isPositive(mode: SelectorFlags): boolean { * matching against directives. */ function findAttrIndexInNode( - name: string, attrs: TAttributes | null, isInlineTemplate: boolean, + name: string, attrs: TAttributes|null, isInlineTemplate: boolean, isProjectionMode: boolean): number { if (attrs === null) return -1; diff --git a/packages/core/src/render3/node_util.ts b/packages/core/src/render3/node_util.ts index 8f750ea399050..39865239908e8 100644 --- a/packages/core/src/render3/node_util.ts +++ b/packages/core/src/render3/node_util.ts @@ -43,7 +43,7 @@ export function getParentInjectorTNode( let parentTNode = startView[T_HOST] as TElementNode; // view offset is superior to 1 while (viewOffset > 1) { - parentView = parentView[DECLARATION_VIEW] !; + parentView = parentView[DECLARATION_VIEW]!; parentTNode = parentView[T_HOST] as TElementNode; viewOffset--; } diff --git a/packages/core/src/render3/pipe.ts b/packages/core/src/render3/pipe.ts index d7e79f0dbdb06..60a4ec490e0d4 100644 --- a/packages/core/src/render3/pipe.ts +++ b/packages/core/src/render3/pipe.ts @@ -61,7 +61,7 @@ export function ɵɵpipe(index: number, pipeName: string): any { * @param registry Full list of available pipes * @returns Matching PipeDef */ -function getPipeDef(name: string, registry: PipeDefList | null): PipeDef { +function getPipeDef(name: string, registry: PipeDefList|null): PipeDef { if (registry) { for (let i = registry.length - 1; i >= 0; i--) { const pipeDef = registry[i]; @@ -89,7 +89,8 @@ export function ɵɵpipeBind1(index: number, slotOffset: number, v1: any): any { const lView = getLView(); const pipeInstance = load(lView, index); return unwrapValue( - lView, isPure(lView, index) ? + lView, + isPure(lView, index) ? pureFunction1Internal( lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, pipeInstance) : pipeInstance.transform(v1)); @@ -112,7 +113,8 @@ export function ɵɵpipeBind2(index: number, slotOffset: number, v1: any, v2: an const lView = getLView(); const pipeInstance = load(lView, index); return unwrapValue( - lView, isPure(lView, index) ? + lView, + isPure(lView, index) ? pureFunction2Internal( lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, pipeInstance) : pipeInstance.transform(v1, v2)); @@ -136,10 +138,11 @@ export function ɵɵpipeBind3(index: number, slotOffset: number, v1: any, v2: an const lView = getLView(); const pipeInstance = load(lView, index); return unwrapValue( - lView, isPure(lView, index) ? pureFunction3Internal( - lView, getBindingRoot(), slotOffset, pipeInstance.transform, - v1, v2, v3, pipeInstance) : - pipeInstance.transform(v1, v2, v3)); + lView, + isPure(lView, index) ? pureFunction3Internal( + lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, + v2, v3, pipeInstance) : + pipeInstance.transform(v1, v2, v3)); } /** @@ -162,10 +165,11 @@ export function ɵɵpipeBind4( const lView = getLView(); const pipeInstance = load(lView, index); return unwrapValue( - lView, isPure(lView, index) ? pureFunction4Internal( - lView, getBindingRoot(), slotOffset, pipeInstance.transform, - v1, v2, v3, v4, pipeInstance) : - pipeInstance.transform(v1, v2, v3, v4)); + lView, + isPure(lView, index) ? pureFunction4Internal( + lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, + v2, v3, v4, pipeInstance) : + pipeInstance.transform(v1, v2, v3, v4)); } /** @@ -184,7 +188,8 @@ export function ɵɵpipeBindV(index: number, slotOffset: number, values: [any, . const lView = getLView(); const pipeInstance = load(lView, index); return unwrapValue( - lView, isPure(lView, index) ? + lView, + isPure(lView, index) ? pureFunctionVInternal( lView, getBindingRoot(), slotOffset, pipeInstance.transform, values, pipeInstance) : pipeInstance.transform.apply(pipeInstance, values)); diff --git a/packages/core/src/render3/pure_function.ts b/packages/core/src/render3/pure_function.ts index 2594661166792..762837c866916 100644 --- a/packages/core/src/render3/pure_function.ts +++ b/packages/core/src/render3/pure_function.ts @@ -154,8 +154,9 @@ export function ɵɵpureFunction5( const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4); return bindingUpdated(lView, bindingIndex + 4, exp5) || different ? updateBinding( - lView, bindingIndex + 5, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5) : - pureFn(exp1, exp2, exp3, exp4, exp5)) : + lView, bindingIndex + 5, + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5) : + pureFn(exp1, exp2, exp3, exp4, exp5)) : getBinding(lView, bindingIndex + 5); } @@ -184,9 +185,9 @@ export function ɵɵpureFunction6( const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4); return bindingUpdated2(lView, bindingIndex + 4, exp5, exp6) || different ? updateBinding( - lView, bindingIndex + 6, thisArg ? - pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6) : - pureFn(exp1, exp2, exp3, exp4, exp5, exp6)) : + lView, bindingIndex + 6, + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6) : + pureFn(exp1, exp2, exp3, exp4, exp5, exp6)) : getBinding(lView, bindingIndex + 6); } @@ -217,9 +218,9 @@ export function ɵɵpureFunction7( let different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4); return bindingUpdated3(lView, bindingIndex + 4, exp5, exp6, exp7) || different ? updateBinding( - lView, bindingIndex + 7, thisArg ? - pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7) : - pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7)) : + lView, bindingIndex + 7, + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7) : + pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7)) : getBinding(lView, bindingIndex + 7); } @@ -252,9 +253,9 @@ export function ɵɵpureFunction8( const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4); return bindingUpdated4(lView, bindingIndex + 4, exp5, exp6, exp7, exp8) || different ? updateBinding( - lView, bindingIndex + 8, thisArg ? - pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8) : - pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)) : + lView, bindingIndex + 8, + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8) : + pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)) : getBinding(lView, bindingIndex + 8); } diff --git a/packages/core/src/render3/query.ts b/packages/core/src/render3/query.ts index ca1b736a1ba3a..3286f439b0436 100644 --- a/packages/core/src/render3/query.ts +++ b/packages/core/src/render3/query.ts @@ -36,8 +36,12 @@ const unusedValueToPlacateAjd = unused1 + unused2 + unused3 + unused4; class LQuery_ implements LQuery { matches: (T|null)[]|null = null; constructor(public queryList: QueryList) {} - clone(): LQuery { return new LQuery_(this.queryList); } - setDirty(): void { this.queryList.setDirty(); } + clone(): LQuery { + return new LQuery_(this.queryList); + } + setDirty(): void { + this.queryList.setDirty(); + } } class LQueries_ implements LQueries { @@ -66,9 +70,13 @@ class LQueries_ implements LQueries { return null; } - insertView(tView: TView): void { this.dirtyQueriesWithMatches(tView); } + insertView(tView: TView): void { + this.dirtyQueriesWithMatches(tView); + } - detachView(tView: TView): void { this.dirtyQueriesWithMatches(tView); } + detachView(tView: TView): void { + this.dirtyQueriesWithMatches(tView); + } private dirtyQueriesWithMatches(tView: TView) { for (let i = 0; i < this.queries.length; i++) { @@ -89,8 +97,9 @@ class TQueries_ implements TQueries { constructor(private queries: TQuery[] = []) {} elementStart(tView: TView, tNode: TNode): void { - ngDevMode && assertFirstCreatePass( - tView, 'Queries should collect results on the first template pass only'); + ngDevMode && + assertFirstCreatePass( + tView, 'Queries should collect results on the first template pass only'); for (let i = 0; i < this.queries.length; i++) { this.queries[i].elementStart(tView, tNode); } @@ -121,8 +130,9 @@ class TQueries_ implements TQueries { } template(tView: TView, tNode: TNode): void { - ngDevMode && assertFirstCreatePass( - tView, 'Queries should collect results on the first template pass only'); + ngDevMode && + assertFirstCreatePass( + tView, 'Queries should collect results on the first template pass only'); for (let i = 0; i < this.queries.length; i++) { this.queries[i].template(tView, tNode); } @@ -133,9 +143,13 @@ class TQueries_ implements TQueries { return this.queries[index]; } - get length(): number { return this.queries.length; } + get length(): number { + return this.queries.length; + } - track(tquery: TQuery): void { this.queries.push(tquery); } + track(tquery: TQuery): void { + this.queries.push(tquery); + } } class TQuery_ implements TQuery { @@ -173,7 +187,9 @@ class TQuery_ implements TQuery { } } - template(tView: TView, tNode: TNode): void { this.elementStart(tView, tNode); } + template(tView: TView, tNode: TNode): void { + this.elementStart(tView, tNode); + } embeddedTView(tNode: TNode, childQueryIndex: number): TQuery|null { if (this.isApplyingToNode(tNode)) { @@ -307,15 +323,17 @@ function createSpecialToken(lView: LView, tNode: TNode, read: any): any { } else if (read === ViewEngine_TemplateRef) { return createTemplateRef(ViewEngine_TemplateRef, ViewEngine_ElementRef, tNode, lView); } else if (read === ViewContainerRef) { - ngDevMode && assertNodeOfPossibleTypes( - tNode, TNodeType.Element, TNodeType.Container, TNodeType.ElementContainer); + ngDevMode && + assertNodeOfPossibleTypes( + tNode, TNodeType.Element, TNodeType.Container, TNodeType.ElementContainer); return createContainerRef( ViewContainerRef, ViewEngine_ElementRef, tNode as TElementNode | TContainerNode | TElementContainerNode, lView); } else { ngDevMode && throwError( - `Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${stringify(read)}.`); + `Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${ + stringify(read)}.`); } } @@ -325,11 +343,11 @@ function createSpecialToken(lView: LView, tNode: TNode, read: any): any { * doesn't change). */ function materializeViewResults( - tView: TView, lView: LView, tQuery: TQuery, queryIndex: number): (T | null)[] { - const lQuery = lView[QUERIES] !.queries ![queryIndex]; + tView: TView, lView: LView, tQuery: TQuery, queryIndex: number): (T|null)[] { + const lQuery = lView[QUERIES]!.queries![queryIndex]; if (lQuery.matches === null) { const tViewData = tView.data; - const tQueryMatches = tQuery.matches !; + const tQueryMatches = tQuery.matches!; const result: T|null[] = []; for (let i = 0; i < tQueryMatches.length; i += 2) { const matchedNodeIdx = tQueryMatches[i]; @@ -355,7 +373,7 @@ function materializeViewResults( * starting with a provided LView. */ function collectQueryResults(tView: TView, lView: LView, queryIndex: number, result: T[]): T[] { - const tQuery = tView.queries !.getByIndex(queryIndex); + const tQuery = tView.queries!.getByIndex(queryIndex); const tQueryMatches = tQuery.matches; if (tQueryMatches !== null) { const lViewResults = materializeViewResults(tView, lView, tQuery, queryIndex); @@ -381,7 +399,7 @@ function collectQueryResults(tView: TView, lView: LView, queryIndex: number, // collect matches for views created from this declaration container and inserted into // different containers if (declarationLContainer[MOVED_VIEWS] !== null) { - const embeddedLViews = declarationLContainer[MOVED_VIEWS] !; + const embeddedLViews = declarationLContainer[MOVED_VIEWS]!; for (let i = 0; i < embeddedLViews.length; i++) { const embeddedLView = embeddedLViews[i]; collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result); @@ -436,7 +454,7 @@ export function ɵɵqueryRefresh(queryList: QueryList): boolean { * @codeGenApi */ export function ɵɵstaticViewQuery( - predicate: Type| string[], descend: boolean, read?: any): void { + predicate: Type|string[], descend: boolean, read?: any): void { viewQueryInternal(getTView(), getLView(), predicate, descend, read, true); } @@ -449,12 +467,12 @@ export function ɵɵstaticViewQuery( * * @codeGenApi */ -export function ɵɵviewQuery(predicate: Type| string[], descend: boolean, read?: any): void { +export function ɵɵviewQuery(predicate: Type|string[], descend: boolean, read?: any): void { viewQueryInternal(getTView(), getLView(), predicate, descend, read, false); } function viewQueryInternal( - tView: TView, lView: LView, predicate: Type| string[], descend: boolean, read: any, + tView: TView, lView: LView, predicate: Type|string[], descend: boolean, read: any, isStatic: boolean): void { if (tView.firstCreatePass) { createTQuery(tView, new TQueryMetadata_(predicate, descend, isStatic, read), -1); @@ -478,7 +496,7 @@ function viewQueryInternal( * @codeGenApi */ export function ɵɵcontentQuery( - directiveIndex: number, predicate: Type| string[], descend: boolean, read?: any): void { + directiveIndex: number, predicate: Type|string[], descend: boolean, read?: any): void { contentQueryInternal( getTView(), getLView(), predicate, descend, read, false, getPreviousOrParentTNode(), directiveIndex); @@ -497,14 +515,14 @@ export function ɵɵcontentQuery( * @codeGenApi */ export function ɵɵstaticContentQuery( - directiveIndex: number, predicate: Type| string[], descend: boolean, read?: any): void { + directiveIndex: number, predicate: Type|string[], descend: boolean, read?: any): void { contentQueryInternal( getTView(), getLView(), predicate, descend, read, true, getPreviousOrParentTNode(), directiveIndex); } function contentQueryInternal( - tView: TView, lView: LView, predicate: Type| string[], descend: boolean, read: any, + tView: TView, lView: LView, predicate: Type|string[], descend: boolean, read: any, isStatic: boolean, tNode: TNode, directiveIndex: number): void { if (tView.firstCreatePass) { createTQuery(tView, new TQueryMetadata_(predicate, descend, isStatic, read), tNode.index); @@ -529,8 +547,8 @@ export function ɵɵloadQuery(): QueryList { function loadQueryInternal(lView: LView, queryIndex: number): QueryList { ngDevMode && assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query'); - ngDevMode && assertDataInRange(lView[QUERIES] !.queries, queryIndex); - return lView[QUERIES] !.queries[queryIndex].queryList; + ngDevMode && assertDataInRange(lView[QUERIES]!.queries, queryIndex); + return lView[QUERIES]!.queries[queryIndex].queryList; } function createLQuery(tView: TView, lView: LView) { @@ -538,7 +556,7 @@ function createLQuery(tView: TView, lView: LView) { storeCleanupWithContext(tView, lView, queryList, queryList.destroy); if (lView[QUERIES] === null) lView[QUERIES] = new LQueries_(); - lView[QUERIES] !.queries.push(new LQuery_(queryList)); + lView[QUERIES]!.queries.push(new LQuery_(queryList)); } function createTQuery(tView: TView, metadata: TQueryMetadata, nodeIndex: number): void { @@ -551,11 +569,11 @@ function saveContentQueryAndDirectiveIndex(tView: TView, directiveIndex: number) const lastSavedDirectiveIndex = tView.contentQueries.length ? tViewContentQueries[tViewContentQueries.length - 1] : -1; if (directiveIndex !== lastSavedDirectiveIndex) { - tViewContentQueries.push(tView.queries !.length - 1, directiveIndex); + tViewContentQueries.push(tView.queries!.length - 1, directiveIndex); } } function getTQuery(tView: TView, index: number): TQuery { ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery'); - return tView.queries !.getByIndex(index); + return tView.queries!.getByIndex(index); } diff --git a/packages/core/src/render3/state.ts b/packages/core/src/render3/state.ts index 2a45f8c6019d9..79210bb34e1c1 100644 --- a/packages/core/src/render3/state.ts +++ b/packages/core/src/render3/state.ts @@ -373,7 +373,7 @@ export function enterDI(newView: LView, tNode: TNode) { ngDevMode && assertLViewOrUndefined(newView); const newLFrame = allocLFrame(); instructionState.lFrame = newLFrame; - newLFrame.previousOrParentTNode = tNode !; + newLFrame.previousOrParentTNode = tNode!; newLFrame.lView = newView; } @@ -389,7 +389,7 @@ export function enterDI(newView: LView, tNode: TNode) { * @param tNode Element to which the View is a child of * @returns the previously active lView; */ -export function enterView(newView: LView, tNode: TNode | null): void { +export function enterView(newView: LView, tNode: TNode|null): void { ngDevMode && assertLViewOrUndefined(newView); const newLFrame = allocLFrame(); if (ngDevMode) { @@ -406,10 +406,10 @@ export function enterView(newView: LView, tNode: TNode | null): void { } const tView = newView[TVIEW]; instructionState.lFrame = newLFrame; - newLFrame.previousOrParentTNode = tNode !; + newLFrame.previousOrParentTNode = tNode!; newLFrame.lView = newView; newLFrame.tView = tView; - newLFrame.contextLView = newView !; + newLFrame.contextLView = newView!; newLFrame.bindingIndex = tView.bindingStartIndex; } @@ -423,23 +423,23 @@ function allocLFrame() { return newLFrame; } -function createLFrame(parent: LFrame | null): LFrame { +function createLFrame(parent: LFrame|null): LFrame { const lFrame: LFrame = { - previousOrParentTNode: null !, // - isParent: true, // - lView: null !, // - tView: null !, // - selectedIndex: 0, // - contextLView: null !, // - elementDepthCount: 0, // - currentNamespace: null, // - currentSanitizer: null, // - currentDirectiveIndex: -1, // - bindingRootIndex: -1, // - bindingIndex: -1, // - currentQueryIndex: 0, // - parent: parent !, // - child: null, // + previousOrParentTNode: null!, // + isParent: true, // + lView: null!, // + tView: null!, // + selectedIndex: 0, // + contextLView: null!, // + elementDepthCount: 0, // + currentNamespace: null, // + currentSanitizer: null, // + currentDirectiveIndex: -1, // + bindingRootIndex: -1, // + bindingIndex: -1, // + currentQueryIndex: 0, // + parent: parent!, // + child: null, // }; parent !== null && (parent.child = lFrame); // link the new LFrame for reuse. return lFrame; @@ -457,8 +457,8 @@ function createLFrame(parent: LFrame | null): LFrame { function leaveViewLight(): LFrame { const oldLFrame = instructionState.lFrame; instructionState.lFrame = oldLFrame.parent; - oldLFrame.previousOrParentTNode = null !; - oldLFrame.lView = null !; + oldLFrame.previousOrParentTNode = null!; + oldLFrame.lView = null!; return oldLFrame; } @@ -481,9 +481,9 @@ export const leaveDI: () => void = leaveViewLight; export function leaveView() { const oldLFrame = leaveViewLight(); oldLFrame.isParent = true; - oldLFrame.tView = null !; + oldLFrame.tView = null!; oldLFrame.selectedIndex = 0; - oldLFrame.contextLView = null !; + oldLFrame.contextLView = null!; oldLFrame.elementDepthCount = 0; oldLFrame.currentDirectiveIndex = -1; oldLFrame.currentNamespace = null; @@ -495,16 +495,17 @@ export function leaveView() { export function nextContextImpl(level: number): T { const contextLView = instructionState.lFrame.contextLView = - walkUpViews(level, instructionState.lFrame.contextLView !); + walkUpViews(level, instructionState.lFrame.contextLView!); return contextLView[CONTEXT] as T; } function walkUpViews(nestingLevel: number, currentView: LView): LView { while (nestingLevel > 0) { - ngDevMode && assertDefined( - currentView[DECLARATION_VIEW], - 'Declaration view should be defined if nesting level is greater than 0.'); - currentView = currentView[DECLARATION_VIEW] !; + ngDevMode && + assertDefined( + currentView[DECLARATION_VIEW], + 'Declaration view should be defined if nesting level is greater than 0.'); + currentView = currentView[DECLARATION_VIEW]!; nestingLevel--; } return currentView; @@ -581,7 +582,7 @@ export function getNamespace(): string|null { return instructionState.lFrame.currentNamespace; } -export function setCurrentStyleSanitizer(sanitizer: StyleSanitizeFn | null) { +export function setCurrentStyleSanitizer(sanitizer: StyleSanitizeFn|null) { instructionState.lFrame.currentSanitizer = sanitizer; } diff --git a/packages/core/src/render3/styling/class_differ.ts b/packages/core/src/render3/styling/class_differ.ts index 36b8f05c0b0f0..3f3f5e8f8fc5f 100644 --- a/packages/core/src/render3/styling/class_differ.ts +++ b/packages/core/src/render3/styling/class_differ.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {assertNotEqual} from '../../util/assert'; import {CharCode} from '../../util/char_code'; diff --git a/packages/core/src/render3/styling/static_styling.ts b/packages/core/src/render3/styling/static_styling.ts index 9a54073ac9e8f..d27fa5519181a 100644 --- a/packages/core/src/render3/styling/static_styling.ts +++ b/packages/core/src/render3/styling/static_styling.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {concatStringsWithSpace} from '../../util/stringify'; import {assertFirstCreatePass} from '../assert'; diff --git a/packages/core/src/render3/styling/style_binding_list.ts b/packages/core/src/render3/styling/style_binding_list.ts index 808e4e11eb98b..636cce8de520b 100644 --- a/packages/core/src/render3/styling/style_binding_list.ts +++ b/packages/core/src/render3/styling/style_binding_list.ts @@ -1,16 +1,16 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {KeyValueArray, keyValueArrayIndexOf} from '../../util/array_utils'; import {assertDataInRange, assertEqual, assertNotEqual} from '../../util/assert'; import {assertFirstUpdatePass} from '../assert'; import {TNode} from '../interfaces/node'; -import {TStylingKey, TStylingKeyPrimitive, TStylingRange, getTStylingRangeNext, getTStylingRangePrev, setTStylingRangeNext, setTStylingRangeNextDuplicate, setTStylingRangePrev, setTStylingRangePrevDuplicate, toTStylingRange} from '../interfaces/styling'; +import {getTStylingRangeNext, getTStylingRangePrev, setTStylingRangeNext, setTStylingRangeNextDuplicate, setTStylingRangePrev, setTStylingRangePrevDuplicate, toTStylingRange, TStylingKey, TStylingKeyPrimitive, TStylingRange} from '../interfaces/styling'; import {TData} from '../interfaces/view'; import {getTView} from '../state'; @@ -249,9 +249,10 @@ export function insertTStylingBinding( // We are inserting in template section. // We need to set this binding's "previous" to the current template tail tData[index + 1] = toTStylingRange(tmplTail, 0); - ngDevMode && assertEqual( - tmplHead !== 0 && tmplTail === 0, false, - 'Adding template bindings after hostBindings is not allowed.'); + ngDevMode && + assertEqual( + tmplHead !== 0 && tmplTail === 0, false, + 'Adding template bindings after hostBindings is not allowed.'); if (tmplHead === 0) { tmplHead = index; } else { @@ -409,13 +410,14 @@ function isStylingMatch(tStylingKeyCursor: TStylingKey, tStylingKey: TStylingKey ngDevMode && assertNotEqual( Array.isArray(tStylingKey), true, 'Expected that \'tStylingKey\' has been unwrapped'); - if (tStylingKeyCursor === null || // If the cursor is `null` it means that we have map at that + if ( + tStylingKeyCursor === null || // If the cursor is `null` it means that we have map at that // location so we must assume that we have a match. tStylingKey == null || // If `tStylingKey` is `null` then it is a map therefor assume that it // contains a match. (Array.isArray(tStylingKeyCursor) ? tStylingKeyCursor[1] : tStylingKeyCursor) === tStylingKey // If the keys match explicitly than we are a match. - ) { + ) { return true; } else if (Array.isArray(tStylingKeyCursor) && typeof tStylingKey === 'string') { // if we did not find a match, but `tStylingKeyCursor` is `KeyValueArray` that means cursor has diff --git a/packages/core/src/render3/styling/styling_parser.ts b/packages/core/src/render3/styling/styling_parser.ts index 89f24757a14db..1d97f51c8ff5b 100644 --- a/packages/core/src/render3/styling/styling_parser.ts +++ b/packages/core/src/render3/styling/styling_parser.ts @@ -244,7 +244,7 @@ export function consumeSeparator( * @param startIndex Starting index of character where the scan should start. * @param endIndex Ending index of character where the scan should end. * @returns Index after last style value character. -*/ + */ export function consumeStyleValue(text: string, startIndex: number, endIndex: number): number { let ch1 = -1; // 1st previous character let ch2 = -1; // 2nd previous character diff --git a/packages/core/src/render3/util/attrs_utils.ts b/packages/core/src/render3/util/attrs_utils.ts index 4b6201dfa45c0..e9b6939602db4 100644 --- a/packages/core/src/render3/util/attrs_utils.ts +++ b/packages/core/src/render3/util/attrs_utils.ts @@ -8,7 +8,7 @@ import {CharCode} from '../../util/char_code'; import {AttributeMarker, TAttributes} from '../interfaces/node'; import {CssSelector} from '../interfaces/projection'; -import {ProceduralRenderer3, RElement, Renderer3, isProceduralRenderer} from '../interfaces/renderer'; +import {isProceduralRenderer, ProceduralRenderer3, RElement, Renderer3} from '../interfaces/renderer'; @@ -96,7 +96,7 @@ export function setUpAttributes(renderer: Renderer3, native: RElement, attrs: TA * @param marker The attribute marker to test. * @returns true if the marker is a "name-only" marker (e.g. `Bindings`, `Template` or `I18n`). */ -export function isNameOnlyAttributeMarker(marker: string | AttributeMarker | CssSelector) { +export function isNameOnlyAttributeMarker(marker: string|AttributeMarker|CssSelector) { return marker === AttributeMarker.Bindings || marker === AttributeMarker.Template || marker === AttributeMarker.I18n; } @@ -116,7 +116,7 @@ export function isAnimationProp(name: string): boolean { * @param dst Location of where the merged `TAttributes` should end up. * @param src `TAttributes` which should be appended to `dst` */ -export function mergeHostAttrs(dst: TAttributes | null, src: TAttributes | null): TAttributes|null { +export function mergeHostAttrs(dst: TAttributes|null, src: TAttributes|null): TAttributes|null { if (src === null || src.length === 0) { // do nothing } else if (dst === null || dst.length === 0) { @@ -156,8 +156,8 @@ export function mergeHostAttrs(dst: TAttributes | null, src: TAttributes | null) * @param value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class. */ export function mergeHostAttribute( - dst: TAttributes, marker: AttributeMarker, key1: string, key2: string | null, - value: string | null): void { + dst: TAttributes, marker: AttributeMarker, key1: string, key2: string|null, + value: string|null): void { let i = 0; // Assume that new markers will be inserted at the end. let markerInsertPosition = dst.length; @@ -195,7 +195,7 @@ export function mergeHostAttribute( } return; } else if (key2 === dst[i + 1]) { - dst[i + 2] = value !; + dst[i + 2] = value!; return; } } diff --git a/packages/core/src/render3/util/discovery_utils.ts b/packages/core/src/render3/util/discovery_utils.ts index 695d2899ff405..41b4ba81d193d 100644 --- a/packages/core/src/render3/util/discovery_utils.ts +++ b/packages/core/src/render3/util/discovery_utils.ts @@ -10,12 +10,13 @@ import {Injector} from '../../di/injector'; import {assertLView} from '../assert'; import {discoverLocalRefs, getComponentAtNodeIndex, getDirectivesAtNodeIndex, getLContext} from '../context_discovery'; import {NodeInjector} from '../di'; -import {DebugNode, buildDebugNode} from '../instructions/lview_debug'; +import {buildDebugNode, DebugNode} from '../instructions/lview_debug'; import {LContext} from '../interfaces/context'; import {DirectiveDef} from '../interfaces/definition'; import {TElementNode, TNode, TNodeProviderIndexes} from '../interfaces/node'; import {isLView} from '../interfaces/type_checks'; -import {CLEANUP, CONTEXT, FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, TVIEW, T_HOST} from '../interfaces/view'; +import {CLEANUP, CONTEXT, FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, T_HOST, TVIEW} from '../interfaces/view'; + import {stringifyForError} from './misc_utils'; import {getLViewParent, getRootContext} from './view_traversal_utils'; import {getTNode, unwrapRNode} from './view_utils'; @@ -93,14 +94,14 @@ export function getContext(element: Element): T|null { * @publicApi * @globalApi ng */ -export function getOwningComponent(elementOrDir: Element | {}): T|null { +export function getOwningComponent(elementOrDir: Element|{}): T|null { const context = loadLContext(elementOrDir, false); if (context === null) return null; let lView = context.lView; let parent: LView|null; ngDevMode && assertLView(lView); - while (lView[HOST] === null && (parent = getLViewParent(lView) !)) { + while (lView[HOST] === null && (parent = getLViewParent(lView)!)) { // As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf` lView = parent; } @@ -118,7 +119,7 @@ export function getOwningComponent(elementOrDir: Element | {}): T|null { * @publicApi * @globalApi ng */ -export function getRootComponents(elementOrDir: Element | {}): {}[] { +export function getRootComponents(elementOrDir: Element|{}): {}[] { return [...getRootContext(elementOrDir).components]; } @@ -132,7 +133,7 @@ export function getRootComponents(elementOrDir: Element | {}): {}[] { * @publicApi * @globalApi ng */ -export function getInjector(elementOrDir: Element | {}): Injector { +export function getInjector(elementOrDir: Element|{}): Injector { const context = loadLContext(elementOrDir, false); if (context === null) return Injector.NULL; @@ -192,7 +193,7 @@ export function getInjectionTokens(element: Element): any[] { * @globalApi ng */ export function getDirectives(element: Element): {}[] { - const context = loadLContext(element) !; + const context = loadLContext(element)!; if (context.directives === undefined) { context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false); @@ -250,7 +251,7 @@ export function getLocalRefs(target: {}): {[key: string]: any} { * @globalApi ng */ export function getHostElement(componentOrDirective: {}): Element { - return getLContext(componentOrDirective) !.native as never as Element; + return getLContext(componentOrDirective)!.native as never as Element; } /** @@ -270,7 +271,7 @@ export function getRenderedText(component: any): string { export function loadLContextFromNode(node: Node): LContext { if (!(node instanceof Node)) throw new Error('Expecting instance of DOM Element'); - return loadLContext(node) !; + return loadLContext(node)!; } /** diff --git a/packages/core/src/render3/util/injector_utils.ts b/packages/core/src/render3/util/injector_utils.ts index 0de9682a56404..4d77357745db9 100644 --- a/packages/core/src/render3/util/injector_utils.ts +++ b/packages/core/src/render3/util/injector_utils.ts @@ -37,7 +37,7 @@ export function getParentInjectorView(location: RelativeInjectorLocation, startV // tags or inline views, where the parent injector might live many views // above the child injector. while (viewOffset > 0) { - parentView = parentView[DECLARATION_VIEW] !; + parentView = parentView[DECLARATION_VIEW]!; viewOffset--; } return parentView; diff --git a/packages/core/src/render3/util/misc_utils.ts b/packages/core/src/render3/util/misc_utils.ts index 5d0b9ea648cec..d2805739e1546 100644 --- a/packages/core/src/render3/util/misc_utils.ts +++ b/packages/core/src/render3/util/misc_utils.ts @@ -37,16 +37,18 @@ export function stringifyForError(value: any): string { export const defaultScheduler = - (() => - (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame || // browser only - setTimeout // everything else - ).bind(global))(); + (() => ( + typeof requestAnimationFrame !== 'undefined' && + requestAnimationFrame || // browser only + setTimeout // everything else + ) + .bind(global))(); /** * * @codeGenApi */ -export function ɵɵresolveWindow(element: RElement & {ownerDocument: Document}) { +export function ɵɵresolveWindow(element: RElement&{ownerDocument: Document}) { return {name: 'window', target: element.ownerDocument.defaultView}; } @@ -54,7 +56,7 @@ export function ɵɵresolveWindow(element: RElement & {ownerDocument: Document}) * * @codeGenApi */ -export function ɵɵresolveDocument(element: RElement & {ownerDocument: Document}) { +export function ɵɵresolveDocument(element: RElement&{ownerDocument: Document}) { return {name: 'document', target: element.ownerDocument}; } @@ -62,7 +64,7 @@ export function ɵɵresolveDocument(element: RElement & {ownerDocument: Document * * @codeGenApi */ -export function ɵɵresolveBody(element: RElement & {ownerDocument: Document}) { +export function ɵɵresolveBody(element: RElement&{ownerDocument: Document}) { return {name: 'body', target: element.ownerDocument.body}; } @@ -85,7 +87,7 @@ export const INTERPOLATION_DELIMITER = `�`; /** * Unwrap a value which might be behind a closure (for forward declaration reasons). */ -export function maybeUnwrapFn(value: T | (() => T)): T { +export function maybeUnwrapFn(value: T|(() => T)): T { if (value instanceof Function) { return value(); } else { diff --git a/packages/core/src/render3/util/view_traversal_utils.ts b/packages/core/src/render3/util/view_traversal_utils.ts index 0be540c9f9ef1..7cda0ad9656f1 100644 --- a/packages/core/src/render3/util/view_traversal_utils.ts +++ b/packages/core/src/render3/util/view_traversal_utils.ts @@ -21,7 +21,7 @@ import {readPatchedLView} from './view_utils'; export function getLViewParent(lView: LView): LView|null { ngDevMode && assertLView(lView); const parent = lView[PARENT]; - return isLContainer(parent) ? parent[PARENT] ! : parent; + return isLContainer(parent) ? parent[PARENT]! : parent; } /** @@ -30,11 +30,11 @@ export function getLViewParent(lView: LView): LView|null { * * @param componentOrLView any component or `LView` */ -export function getRootView(componentOrLView: LView | {}): LView { +export function getRootView(componentOrLView: LView|{}): LView { ngDevMode && assertDefined(componentOrLView, 'component'); - let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView) !; + let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView)!; while (lView && !(lView[FLAGS] & LViewFlags.IsRoot)) { - lView = getLViewParent(lView) !; + lView = getLViewParent(lView)!; } ngDevMode && assertLView(lView); return lView; @@ -47,7 +47,7 @@ export function getRootView(componentOrLView: LView | {}): LView { * * @param viewOrComponent the `LView` or component to get the root context for. */ -export function getRootContext(viewOrComponent: LView | {}): RootContext { +export function getRootContext(viewOrComponent: LView|{}): RootContext { const rootView = getRootView(viewOrComponent); ngDevMode && assertDefined(rootView[CONTEXT], 'RootView has no context. Perhaps it is disconnected?'); diff --git a/packages/core/src/render3/util/view_utils.ts b/packages/core/src/render3/util/view_utils.ts index d98c91f825c69..54fe62be011fe 100644 --- a/packages/core/src/render3/util/view_utils.ts +++ b/packages/core/src/render3/util/view_utils.ts @@ -11,7 +11,7 @@ import {assertTNodeForLView} from '../assert'; import {ACTIVE_INDEX, ActiveIndexFlag, LContainer, TYPE} from '../interfaces/container'; import {LContext, MONKEY_PATCH_KEY_NAME} from '../interfaces/context'; import {TConstants, TNode} from '../interfaces/node'; -import {RNode, isProceduralRenderer} from '../interfaces/renderer'; +import {isProceduralRenderer, RNode} from '../interfaces/renderer'; import {isLContainer, isLView} from '../interfaces/type_checks'; import {FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, PARENT, PREORDER_HOOK_FLAGS, RENDERER, TData, TView} from '../interfaces/view'; @@ -38,7 +38,7 @@ import {FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, PARENT, PREORDER_HOOK_FLA * Returns `RNode`. * @param value wrapped value of `RNode`, `LView`, `LContainer` */ -export function unwrapRNode(value: RNode | LView | LContainer): RNode { +export function unwrapRNode(value: RNode|LView|LContainer): RNode { while (Array.isArray(value)) { value = value[HOST] as any; } @@ -49,7 +49,7 @@ export function unwrapRNode(value: RNode | LView | LContainer): RNode { * Returns `LView` or `null` if not found. * @param value wrapped value of `RNode`, `LView`, `LContainer` */ -export function unwrapLView(value: RNode | LView | LContainer): LView|null { +export function unwrapLView(value: RNode|LView|LContainer): LView|null { while (Array.isArray(value)) { // This check is same as `isLView()` but we don't call at as we don't want to call // `Array.isArray()` twice and give JITer more work for inlining. @@ -63,7 +63,7 @@ export function unwrapLView(value: RNode | LView | LContainer): LView|null { * Returns `LContainer` or `null` if not found. * @param value wrapped value of `RNode`, `LView`, `LContainer` */ -export function unwrapLContainer(value: RNode | LView | LContainer): LContainer|null { +export function unwrapLContainer(value: RNode|LView|LContainer): LContainer|null { while (Array.isArray(value)) { // This check is same as `isLContainer()` but we don't call at as we don't want to call // `Array.isArray()` twice and give JITer more work for inlining. @@ -124,7 +124,7 @@ export function getTNode(tView: TView, index: number): TNode { } /** Retrieves a value from any `LView` or `TData`. */ -export function load(view: LView | TData, index: number): T { +export function load(view: LView|TData, index: number): T { ngDevMode && assertDataInRange(view, index + HEADER_OFFSET); return view[index + HEADER_OFFSET]; } @@ -176,8 +176,7 @@ export function viewAttachedToContainer(view: LView): boolean { } /** Returns a constant from `TConstants` instance. */ -export function getConstant(consts: TConstants | null, index: number | null | undefined): T| - null { +export function getConstant(consts: TConstants|null, index: number|null|undefined): T|null { return consts === null || index == null ? null : consts[index] as unknown as T; } diff --git a/packages/core/src/render3/view_engine_compatibility.ts b/packages/core/src/render3/view_engine_compatibility.ts index 36c9aa2b75626..5727db3f30639 100644 --- a/packages/core/src/render3/view_engine_compatibility.ts +++ b/packages/core/src/render3/view_engine_compatibility.ts @@ -19,13 +19,13 @@ import {addToArray, removeFromArray} from '../util/array_utils'; import {assertDefined, assertEqual, assertGreaterThan, assertLessThan} from '../util/assert'; import {assertLContainer} from './assert'; -import {NodeInjector, getParentInjectorLocation} from './di'; +import {getParentInjectorLocation, NodeInjector} from './di'; import {addToViewTree, createLContainer, createLView, renderView} from './instructions/shared'; import {ActiveIndexFlag, CONTAINER_HEADER_OFFSET, LContainer, VIEW_REFS} from './interfaces/container'; import {TContainerNode, TDirectiveHostNode, TElementContainerNode, TElementNode, TNode, TNodeType, TViewNode} from './interfaces/node'; -import {RComment, RElement, isProceduralRenderer} from './interfaces/renderer'; +import {isProceduralRenderer, RComment, RElement} from './interfaces/renderer'; import {isComponentHost, isLContainer, isLView, isRootView} from './interfaces/type_checks'; -import {DECLARATION_COMPONENT_VIEW, DECLARATION_LCONTAINER, LView, LViewFlags, PARENT, QUERIES, RENDERER, TVIEW, TView, T_HOST} from './interfaces/view'; +import {DECLARATION_COMPONENT_VIEW, DECLARATION_LCONTAINER, LView, LViewFlags, PARENT, QUERIES, RENDERER, T_HOST, TVIEW, TView} from './interfaces/view'; import {assertNodeOfPossibleTypes} from './node_assert'; import {addRemoveViewFromContainer, appendChild, detachView, getBeforeNodeForView, insertView, nativeInsertBefore, nativeNextSibling, nativeParentNode, removeView} from './node_manipulation'; import {getParentInjectorTNode} from './node_util'; @@ -46,7 +46,7 @@ export function injectElementRef(ElementRefToken: typeof ViewEngine_ElementRef): return createElementRef(ElementRefToken, getPreviousOrParentTNode(), getLView()); } -let R3ElementRef: {new (native: RElement | RComment): ViewEngine_ElementRef}; +let R3ElementRef: {new (native: RElement|RComment): ViewEngine_ElementRef}; /** * Creates an ElementRef given a node. @@ -95,7 +95,7 @@ export function createTemplateRef( TemplateRefToken: typeof ViewEngine_TemplateRef, ElementRefToken: typeof ViewEngine_ElementRef, hostTNode: TNode, hostView: LView): ViewEngine_TemplateRef|null { if (!R3TemplateRef) { - R3TemplateRef = class TemplateRef extends TemplateRefToken { + R3TemplateRef = class TemplateRef extends TemplateRefToken{ constructor( private _declarationView: LView, private _declarationTContainer: TContainerNode, readonly elementRef: ViewEngine_ElementRef) { @@ -138,7 +138,7 @@ export function createTemplateRef( let R3ViewContainerRef: { new ( - lContainer: LContainer, hostTNode: TElementNode | TContainerNode | TElementContainerNode, + lContainer: LContainer, hostTNode: TElementNode|TContainerNode|TElementContainerNode, hostView: LView): ViewEngine_ViewContainerRef }; @@ -183,7 +183,9 @@ export function createContainerRef( return createElementRef(ElementRefToken, this._hostTNode, this._hostView); } - get injector(): Injector { return new NodeInjector(this._hostTNode, this._hostView); } + get injector(): Injector { + return new NodeInjector(this._hostTNode, this._hostView); + } /** @deprecated No replacement */ get parentInjector(): Injector { @@ -203,10 +205,12 @@ export function createContainerRef( } get(index: number): viewEngine_ViewRef|null { - return this._lContainer[VIEW_REFS] !== null && this._lContainer[VIEW_REFS] ![index] || null; + return this._lContainer[VIEW_REFS] !== null && this._lContainer[VIEW_REFS]![index] || null; } - get length(): number { return this._lContainer.length - CONTAINER_HEADER_OFFSET; } + get length(): number { + return this._lContainer.length - CONTAINER_HEADER_OFFSET; + } createEmbeddedView(templateRef: ViewEngine_TemplateRef, context?: C, index?: number): viewEngine_EmbeddedViewRef { @@ -237,7 +241,7 @@ export function createContainerRef( } insert(viewRef: viewEngine_ViewRef, index?: number): viewEngine_ViewRef { - const lView = (viewRef as ViewRef)._lView !; + const lView = (viewRef as ViewRef)._lView!; const tView = lView[TVIEW]; if (viewRef.destroyed) { @@ -259,9 +263,10 @@ export function createContainerRef( this.detach(prevIdx); } else { const prevLContainer = lView[PARENT] as LContainer; - ngDevMode && assertEqual( - isLContainer(prevLContainer), true, - 'An attached view should have its PARENT point to a container.'); + ngDevMode && + assertEqual( + isLContainer(prevLContainer), true, + 'An attached view should have its PARENT point to a container.'); // We need to re-create a R3ViewContainerRef instance since those are not stored on @@ -281,7 +286,7 @@ export function createContainerRef( addRemoveViewFromContainer(tView, lView, true, beforeNode); (viewRef as ViewRef).attachToViewContainerRef(this); - addToArray(this._lContainer[VIEW_REFS] !, adjustedIdx, viewRef); + addToArray(this._lContainer[VIEW_REFS]!, adjustedIdx, viewRef); return viewRef; } @@ -302,7 +307,7 @@ export function createContainerRef( this.allocateContainerIfNeeded(); const adjustedIdx = this._adjustIndex(index, -1); removeView(this._lContainer, adjustedIdx); - removeFromArray(this._lContainer[VIEW_REFS] !, adjustedIdx); + removeFromArray(this._lContainer[VIEW_REFS]!, adjustedIdx); } detach(index?: number): viewEngine_ViewRef|null { @@ -311,8 +316,8 @@ export function createContainerRef( const view = detachView(this._lContainer, adjustedIdx); const wasDetached = - view && removeFromArray(this._lContainer[VIEW_REFS] !, adjustedIdx) != null; - return wasDetached ? new ViewRef(view !) : null; + view && removeFromArray(this._lContainer[VIEW_REFS]!, adjustedIdx) != null; + return wasDetached ? new ViewRef(view!) : null; } private _adjustIndex(index?: number, shift: number = 0) { @@ -335,8 +340,9 @@ export function createContainerRef( }; } - ngDevMode && assertNodeOfPossibleTypes( - hostTNode, TNodeType.Container, TNodeType.Element, TNodeType.ElementContainer); + ngDevMode && + assertNodeOfPossibleTypes( + hostTNode, TNodeType.Container, TNodeType.Element, TNodeType.ElementContainer); let lContainer: LContainer; const slotValue = hostView[hostTNode.index]; @@ -363,10 +369,10 @@ export function createContainerRef( // node. if (isRootView(hostView)) { const renderer = hostView[RENDERER]; - const hostNative = getNativeByTNode(hostTNode, hostView) !; + const hostNative = getNativeByTNode(hostTNode, hostView)!; const parentOfHostNative = nativeParentNode(renderer, hostNative); nativeInsertBefore( - renderer, parentOfHostNative !, commentNode, nativeNextSibling(renderer, hostNative)); + renderer, parentOfHostNative!, commentNode, nativeNextSibling(renderer, hostNative)); } else { appendChild(hostView[TVIEW], hostView, commentNode, hostTNode); } @@ -412,7 +418,7 @@ function createViewRef(tNode: TNode, lView: LView, isPipe: boolean): ViewEngine_ const hostComponentView = lView[DECLARATION_COMPONENT_VIEW]; // look up return new ViewRef(hostComponentView, lView); } - return null !; + return null!; } /** Returns a Renderer2 (or throws when application was bootstrapped with Renderer3) */ diff --git a/packages/core/src/render3/view_ref.ts b/packages/core/src/render3/view_ref.ts index 722733dbb4940..10f67c6b66b31 100644 --- a/packages/core/src/render3/view_ref.ts +++ b/packages/core/src/render3/view_ref.ts @@ -10,11 +10,12 @@ import {ApplicationRef} from '../application_ref'; import {ChangeDetectorRef as viewEngine_ChangeDetectorRef} from '../change_detection/change_detector_ref'; import {ViewContainerRef as viewEngine_ViewContainerRef} from '../linker/view_container_ref'; import {EmbeddedViewRef as viewEngine_EmbeddedViewRef, InternalViewRef as viewEngine_InternalViewRef} from '../linker/view_ref'; + import {checkNoChangesInRootView, checkNoChangesInternal, detectChangesInRootView, detectChangesInternal, markViewDirty, storeCleanupFn} from './instructions/shared'; import {CONTAINER_HEADER_OFFSET} from './interfaces/container'; import {TElementNode, TNode, TNodeType, TViewNode} from './interfaces/node'; import {isLContainer} from './interfaces/type_checks'; -import {CONTEXT, DECLARATION_COMPONENT_VIEW, FLAGS, HOST, LView, LViewFlags, TVIEW, TView, T_HOST} from './interfaces/view'; +import {CONTEXT, DECLARATION_COMPONENT_VIEW, FLAGS, HOST, LView, LViewFlags, T_HOST, TVIEW, TView} from './interfaces/view'; import {assertNodeOfPossibleTypes} from './node_assert'; import {destroyLView, renderDetachView} from './node_manipulation'; import {getLViewParent} from './util/view_traversal_utils'; @@ -28,7 +29,7 @@ import {unwrapRNode} from './util/view_utils'; export interface viewEngine_ChangeDetectorRef_interface extends viewEngine_ChangeDetectorRef {} export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_InternalViewRef, - viewEngine_ChangeDetectorRef_interface { + viewEngine_ChangeDetectorRef_interface { private _appRef: ApplicationRef|null = null; private _viewContainerRef: viewEngine_ViewContainerRef|null = null; @@ -68,7 +69,9 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int */ private _cdRefInjectingView?: LView) {} - get context(): T { return this._lView[CONTEXT] as T; } + get context(): T { + return this._lView[CONTEXT] as T; + } get destroyed(): boolean { return (this._lView[FLAGS] & LViewFlags.Destroyed) === LViewFlags.Destroyed; @@ -89,7 +92,9 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int destroyLView(this._lView[TVIEW], this._lView); } - onDestroy(callback: Function) { storeCleanupFn(this._lView[TVIEW], this._lView, callback); } + onDestroy(callback: Function) { + storeCleanupFn(this._lView[TVIEW], this._lView, callback); + } /** * Marks a view and all of its ancestors dirty. @@ -125,7 +130,9 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int * } * ``` */ - markForCheck(): void { markViewDirty(this._cdRefInjectingView || this._lView); } + markForCheck(): void { + markViewDirty(this._cdRefInjectingView || this._lView); + } /** * Detaches the view from the change detection tree. @@ -180,7 +187,9 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int * } * ``` */ - detach(): void { this._lView[FLAGS] &= ~LViewFlags.Attached; } + detach(): void { + this._lView[FLAGS] &= ~LViewFlags.Attached; + } /** * Re-attaches a view to the change detection tree. @@ -238,7 +247,9 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int * } * ``` */ - reattach(): void { this._lView[FLAGS] |= LViewFlags.Attached; } + reattach(): void { + this._lView[FLAGS] |= LViewFlags.Attached; + } /** * Checks the view and its children. @@ -261,7 +272,9 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int * * See {@link ChangeDetectorRef#detach detach} for more information. */ - detectChanges(): void { detectChangesInternal(this._lView[TVIEW], this._lView, this.context); } + detectChanges(): void { + detectChangesInternal(this._lView[TVIEW], this._lView, this.context); + } /** * Checks the change detector and its children, and throws if any changes are detected. @@ -269,7 +282,9 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int * This is used in development mode to verify that running change detection doesn't * introduce other changes. */ - checkNoChanges(): void { checkNoChangesInternal(this._lView[TVIEW], this._lView, this.context); } + checkNoChanges(): void { + checkNoChangesInternal(this._lView[TVIEW], this._lView, this.context); + } attachToViewContainerRef(vcRef: viewEngine_ViewContainerRef) { if (this._appRef) { @@ -293,22 +308,31 @@ export class ViewRef implements viewEngine_EmbeddedViewRef, viewEngine_Int /** @internal */ export class RootViewRef extends ViewRef { - constructor(public _view: LView) { super(_view); } + constructor(public _view: LView) { + super(_view); + } - detectChanges(): void { detectChangesInRootView(this._view); } + detectChanges(): void { + detectChangesInRootView(this._view); + } - checkNoChanges(): void { checkNoChangesInRootView(this._view); } + checkNoChanges(): void { + checkNoChangesInRootView(this._view); + } - get context(): T { return null !; } + get context(): T { + return null!; + } } function collectNativeNodes( - tView: TView, lView: LView, tNode: TNode | null, result: any[], + tView: TView, lView: LView, tNode: TNode|null, result: any[], isProjection: boolean = false): any[] { while (tNode !== null) { - ngDevMode && assertNodeOfPossibleTypes( - tNode, TNodeType.Element, TNodeType.Container, TNodeType.Projection, - TNodeType.ElementContainer, TNodeType.IcuContainer); + ngDevMode && + assertNodeOfPossibleTypes( + tNode, TNodeType.Element, TNodeType.Container, TNodeType.Projection, + TNodeType.ElementContainer, TNodeType.IcuContainer); const lNode = lView[tNode.index]; if (lNode !== null) { @@ -337,7 +361,7 @@ function collectNativeNodes( const componentHost = componentView[T_HOST] as TElementNode; const parentView = getLViewParent(componentView); let firstProjectedNode: TNode|null = - (componentHost.projection as(TNode | null)[])[tNode.projection as number]; + (componentHost.projection as (TNode | null)[])[tNode.projection as number]; if (firstProjectedNode !== null && parentView !== null) { collectNativeNodes(parentView[TVIEW], parentView, firstProjectedNode, result, true); } diff --git a/packages/core/src/sanitization/bypass.ts b/packages/core/src/sanitization/bypass.ts index 7a0272cd301cc..01287ad15caed 100644 --- a/packages/core/src/sanitization/bypass.ts +++ b/packages/core/src/sanitization/bypass.ts @@ -70,24 +70,34 @@ abstract class SafeValueImpl implements SafeValue { } class SafeHtmlImpl extends SafeValueImpl implements SafeHtml { - getTypeName() { return BypassType.Html; } + getTypeName() { + return BypassType.Html; + } } class SafeStyleImpl extends SafeValueImpl implements SafeStyle { - getTypeName() { return BypassType.Style; } + getTypeName() { + return BypassType.Style; + } } class SafeScriptImpl extends SafeValueImpl implements SafeScript { - getTypeName() { return BypassType.Script; } + getTypeName() { + return BypassType.Script; + } } class SafeUrlImpl extends SafeValueImpl implements SafeUrl { - getTypeName() { return BypassType.Url; } + getTypeName() { + return BypassType.Url; + } } class SafeResourceUrlImpl extends SafeValueImpl implements SafeResourceUrl { - getTypeName() { return BypassType.ResourceUrl; } + getTypeName() { + return BypassType.ResourceUrl; + } } export function unwrapSafeValue(value: SafeValue): string; export function unwrapSafeValue(value: T): T; -export function unwrapSafeValue(value: T | SafeValue): T { +export function unwrapSafeValue(value: T|SafeValue): T { return value instanceof SafeValueImpl ? value.changingThisBreaksApplicationSecurity as any as T : value as any as T; } diff --git a/packages/core/src/sanitization/html_sanitizer.ts b/packages/core/src/sanitization/html_sanitizer.ts index faf6ce328786f..7a8e710eea068 100644 --- a/packages/core/src/sanitization/html_sanitizer.ts +++ b/packages/core/src/sanitization/html_sanitizer.ts @@ -114,19 +114,19 @@ class SanitizingHtmlSerializer { // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters. // However this code never accesses properties off of `document` before deleting its contents // again, so it shouldn't be vulnerable to DOM clobbering. - let current: Node = el.firstChild !; + let current: Node = el.firstChild!; let traverseContent = true; while (current) { if (current.nodeType === Node.ELEMENT_NODE) { traverseContent = this.startElement(current as Element); } else if (current.nodeType === Node.TEXT_NODE) { - this.chars(current.nodeValue !); + this.chars(current.nodeValue!); } else { // Strip non-element, non-text nodes. this.sanitizedSomething = true; } if (traverseContent && current.firstChild) { - current = current.firstChild !; + current = current.firstChild!; continue; } while (current) { @@ -135,14 +135,14 @@ class SanitizingHtmlSerializer { this.endElement(current as Element); } - let next = this.checkClobberedElement(current, current.nextSibling !); + let next = this.checkClobberedElement(current, current.nextSibling!); if (next) { current = next; break; } - current = this.checkClobberedElement(current, current.parentNode !); + current = this.checkClobberedElement(current, current.parentNode!); } } return this.buf.join(''); @@ -167,13 +167,13 @@ class SanitizingHtmlSerializer { const elAttrs = element.attributes; for (let i = 0; i < elAttrs.length; i++) { const elAttr = elAttrs.item(i); - const attrName = elAttr !.name; + const attrName = elAttr!.name; const lower = attrName.toLowerCase(); if (!VALID_ATTRS.hasOwnProperty(lower)) { this.sanitizedSomething = true; continue; } - let value = elAttr !.value; + let value = elAttr!.value; // TODO(martinprobst): Special case image URIs for data:image/... if (URI_ATTRS[lower]) value = _sanitizeUrl(value); if (SRCSET_ATTRS[lower]) value = sanitizeSrcset(value); @@ -192,14 +192,16 @@ class SanitizingHtmlSerializer { } } - private chars(chars: string) { this.buf.push(encodeEntities(chars)); } + private chars(chars: string) { + this.buf.push(encodeEntities(chars)); + } checkClobberedElement(node: Node, nextNode: Node): Node { if (nextNode && (node.compareDocumentPosition(nextNode) & Node.DOCUMENT_POSITION_CONTAINED_BY) === Node.DOCUMENT_POSITION_CONTAINED_BY) { - throw new Error( - `Failed to sanitize html because the element is clobbered: ${(node as Element).outerHTML}`); + throw new Error(`Failed to sanitize html because the element is clobbered: ${ + (node as Element).outerHTML}`); } return nextNode; } @@ -227,7 +229,9 @@ function encodeEntities(value: string) { }) .replace( NON_ALPHANUMERIC_REGEXP, - function(match: string) { return '&#' + match.charCodeAt(0) + ';'; }) + function(match: string) { + return '&#' + match.charCodeAt(0) + ';'; + }) .replace(//g, '>'); } @@ -258,13 +262,13 @@ export function _sanitizeHtml(defaultDoc: any, unsafeHtmlInput: string): string mXSSAttempts--; unsafeHtml = parsedHtml; - parsedHtml = inertBodyElement !.innerHTML; + parsedHtml = inertBodyElement!.innerHTML; inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml); } while (unsafeHtml !== parsedHtml); const sanitizer = new SanitizingHtmlSerializer(); const safeHtml = sanitizer.sanitizeChildren( - getTemplateContent(inertBodyElement !) as Element || inertBodyElement); + getTemplateContent(inertBodyElement!) as Element || inertBodyElement); if (isDevMode() && sanitizer.sanitizedSomething) { console.warn( 'WARNING: sanitizing HTML stripped some content, see http://g.co/ng/security#xss'); diff --git a/packages/core/src/sanitization/inert_body.ts b/packages/core/src/sanitization/inert_body.ts index 37fc574b66c55..e79311fd08145 100644 --- a/packages/core/src/sanitization/inert_body.ts +++ b/packages/core/src/sanitization/inert_body.ts @@ -80,7 +80,7 @@ export class InertBodyHelper { xhr.open('GET', 'data:text/html;charset=utf-8,' + html, false); xhr.send(undefined); const body: HTMLBodyElement = xhr.response.body; - body.removeChild(body.firstChild !); + body.removeChild(body.firstChild!); return body; } @@ -95,11 +95,9 @@ export class InertBodyHelper { // `` tag. html = '' + html + ''; try { - const body = new (window as any) - .DOMParser() - .parseFromString(html, 'text/html') - .body as HTMLBodyElement; - body.removeChild(body.firstChild !); + const body = new (window as any).DOMParser().parseFromString(html, 'text/html').body as + HTMLBodyElement; + body.removeChild(body.firstChild!); return body; } catch { return null; @@ -152,7 +150,7 @@ export class InertBodyHelper { // loop backwards so that we can support removals. for (let i = elAttrs.length - 1; 0 < i; i--) { const attrib = elAttrs.item(i); - const attrName = attrib !.name; + const attrName = attrib!.name; if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) { el.removeAttribute(attrName); } diff --git a/packages/core/src/sanitization/sanitization.ts b/packages/core/src/sanitization/sanitization.ts index 653f5a5b69ceb..cf9a3a4562579 100644 --- a/packages/core/src/sanitization/sanitization.ts +++ b/packages/core/src/sanitization/sanitization.ts @@ -11,11 +11,11 @@ import {SANITIZER} from '../render3/interfaces/view'; import {getLView} from '../render3/state'; import {renderStringify} from '../render3/util/misc_utils'; -import {BypassType, allowSanitizationBypassAndThrow, unwrapSafeValue} from './bypass'; +import {allowSanitizationBypassAndThrow, BypassType, unwrapSafeValue} from './bypass'; import {_sanitizeHtml as _sanitizeHtml} from './html_sanitizer'; import {Sanitizer} from './sanitizer'; import {SecurityContext} from './security'; -import {StyleSanitizeFn, StyleSanitizeMode, _sanitizeStyle} from './style_sanitizer'; +import {_sanitizeStyle, StyleSanitizeFn, StyleSanitizeMode} from './style_sanitizer'; import {_sanitizeUrl as _sanitizeUrl} from './url_sanitizer'; @@ -152,8 +152,9 @@ export function ɵɵsanitizeScript(unsafeScript: any): string { * If tag and prop names don't match Resource URL schema, use URL sanitizer. */ export function getUrlSanitizer(tag: string, prop: string) { - if ((prop === 'src' && (tag === 'embed' || tag === 'frame' || tag === 'iframe' || - tag === 'media' || tag === 'script')) || + if ((prop === 'src' && + (tag === 'embed' || tag === 'frame' || tag === 'iframe' || tag === 'media' || + tag === 'script')) || (prop === 'href' && (tag === 'base' || tag === 'link'))) { return ɵɵsanitizeResourceUrl; } @@ -186,7 +187,7 @@ export function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl: any, tag: string, prop: * @publicApi */ export const ɵɵdefaultStyleSanitizer = - (function(prop: string, value: string|null, mode?: StyleSanitizeMode): string | boolean | null { + (function(prop: string, value: string|null, mode?: StyleSanitizeMode): string|boolean|null { if (value === undefined && mode === undefined) { // This is a workaround for the fact that `StyleSanitizeFn` should not exist once PR#34480 // lands. For now the `StyleSanitizeFn` and should act like `(value: any) => string` as a diff --git a/packages/core/src/testability/testability.ts b/packages/core/src/testability/testability.ts index 05cfc9c53644b..d4309947a17c7 100644 --- a/packages/core/src/testability/testability.ts +++ b/packages/core/src/testability/testability.ts @@ -133,7 +133,7 @@ export class Testability implements PublicTestability { // Schedules the call backs in a new frame so that it is always async. scheduleMicroTask(() => { while (this._callbacks.length !== 0) { - let cb = this._callbacks.pop() !; + let cb = this._callbacks.pop()!; clearTimeout(cb.timeoutId); cb.doneCb(this._didWork); } @@ -210,7 +210,9 @@ export class Testability implements PublicTestability { * Get the number of pending requests * @deprecated pending requests are now tracked with zones */ - getPendingRequestCount(): number { return this._pendingCount; } + getPendingRequestCount(): number { + return this._pendingCount; + } /** * Find providers by name @@ -233,7 +235,9 @@ export class TestabilityRegistry { /** @internal */ _applications = new Map(); - constructor() { _testabilityGetter.addToWindow(this); } + constructor() { + _testabilityGetter.addToWindow(this); + } /** * Registers an application with a testability hook so that it can be tracked @@ -248,28 +252,38 @@ export class TestabilityRegistry { * Unregisters an application. * @param token token of application, root element */ - unregisterApplication(token: any) { this._applications.delete(token); } + unregisterApplication(token: any) { + this._applications.delete(token); + } /** * Unregisters all applications */ - unregisterAllApplications() { this._applications.clear(); } + unregisterAllApplications() { + this._applications.clear(); + } /** * Get a testability hook associated with the application * @param elem root element */ - getTestability(elem: any): Testability|null { return this._applications.get(elem) || null; } + getTestability(elem: any): Testability|null { + return this._applications.get(elem) || null; + } /** * Get all registered testabilities */ - getAllTestabilities(): Testability[] { return Array.from(this._applications.values()); } + getAllTestabilities(): Testability[] { + return Array.from(this._applications.values()); + } /** * Get all registered applications(root elements) */ - getAllRootElements(): any[] { return Array.from(this._applications.keys()); } + getAllRootElements(): any[] { + return Array.from(this._applications.keys()); + } /** * Find testability of a node in the Tree diff --git a/packages/core/src/util/WrappedValue.ts b/packages/core/src/util/WrappedValue.ts index 48e5e3f76b33d..a19003474f3ed 100644 --- a/packages/core/src/util/WrappedValue.ts +++ b/packages/core/src/util/WrappedValue.ts @@ -30,17 +30,25 @@ export class WrappedValue { /** @deprecated from 5.3, use `unwrap()` instead - will switch to protected */ wrapped: any; - constructor(value: any) { this.wrapped = value; } + constructor(value: any) { + this.wrapped = value; + } /** Creates a wrapped value. */ - static wrap(value: any): WrappedValue { return new WrappedValue(value); } + static wrap(value: any): WrappedValue { + return new WrappedValue(value); + } /** * Returns the underlying value of a wrapped value. * Returns the given `value` when it is not wrapped. **/ - static unwrap(value: any): any { return WrappedValue.isWrapped(value) ? value.wrapped : value; } + static unwrap(value: any): any { + return WrappedValue.isWrapped(value) ? value.wrapped : value; + } /** Returns true if `value` is a wrapped value. */ - static isWrapped(value: any): value is WrappedValue { return value instanceof WrappedValue; } + static isWrapped(value: any): value is WrappedValue { + return value instanceof WrappedValue; + } } diff --git a/packages/core/src/util/array_utils.ts b/packages/core/src/util/array_utils.ts index 78b1723350b23..08bf5e8b87223 100644 --- a/packages/core/src/util/array_utils.ts +++ b/packages/core/src/util/array_utils.ts @@ -9,11 +9,11 @@ import {assertEqual, assertLessThanOrEqual} from './assert'; /** -* Equivalent to ES6 spread, add each item to an array. -* -* @param items The items to add -* @param arr The array to which you want to add the items -*/ + * Equivalent to ES6 spread, add each item to an array. + * + * @param items The items to add + * @param arr The array to which you want to add the items + */ export function addAllToArray(items: any[], arr: any[]) { for (let i = 0; i < items.length; i++) { arr.push(items[i]); @@ -42,7 +42,7 @@ export function flatten(list: any[], dst?: any[]): any[] { return dst; } -export function deepForEach(input: (T | any[])[], fn: (value: T) => void): void { +export function deepForEach(input: (T|any[])[], fn: (value: T) => void): void { input.forEach(value => Array.isArray(value) ? deepForEach(value, fn) : fn(value)); } @@ -69,7 +69,7 @@ export function newArray(size: number, value: T): T[]; export function newArray(size: number, value?: T): T[] { const list: T[] = []; for (let i = 0; i < size; i++) { - list.push(value !); + list.push(value!); } return list; } @@ -228,7 +228,9 @@ export function arrayIndexOfSorted(array: string[], value: string): number { * * See: `keyValueArraySet`, `keyValueArrayGet`, `keyValueArrayIndexOf`, `keyValueArrayDelete`. */ -export interface KeyValueArray extends Array { __brand__: 'array-map'; } +export interface KeyValueArray extends Array { + __brand__: 'array-map'; +} /** * Set a `value` for a `key`. @@ -253,7 +255,7 @@ export function keyValueArraySet( /** * Retrieve a `value` for a `key` (on `undefined` if not found.) - * + * * @param keyValueArray to search. * @param key The key to locate. * @return The `value` stored at the `key` location or `undefined if not found. diff --git a/packages/core/src/util/char_code.ts b/packages/core/src/util/char_code.ts index 18a023dec43c4..5523acd44f558 100644 --- a/packages/core/src/util/char_code.ts +++ b/packages/core/src/util/char_code.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ /** * List ASCII char codes to be used with `String.charCodeAt` diff --git a/packages/core/src/util/decorators.ts b/packages/core/src/util/decorators.ts index 7ffb8fe56539d..757b6e81d6e90 100644 --- a/packages/core/src/util/decorators.ts +++ b/packages/core/src/util/decorators.ts @@ -52,7 +52,7 @@ export function makeDecorator( const metaCtor = makeMetadataCtor(props); function DecoratorFactory( - this: unknown | typeof DecoratorFactory, ...args: any[]): (cls: Type) => any { + this: unknown|typeof DecoratorFactory, ...args: any[]): (cls: Type) => any { if (this instanceof DecoratorFactory) { metaCtor.call(this, ...args); return this as typeof DecoratorFactory; @@ -101,7 +101,7 @@ export function makeParamDecorator( return noSideEffects(() => { const metaCtor = makeMetadataCtor(props); function ParamDecoratorFactory( - this: unknown | typeof ParamDecoratorFactory, ...args: any[]): any { + this: unknown|typeof ParamDecoratorFactory, ...args: any[]): any { if (this instanceof ParamDecoratorFactory) { metaCtor.apply(this, args); return this; @@ -143,8 +143,7 @@ export function makePropDecorator( return noSideEffects(() => { const metaCtor = makeMetadataCtor(props); - function PropDecoratorFactory( - this: unknown | typeof PropDecoratorFactory, ...args: any[]): any { + function PropDecoratorFactory(this: unknown|typeof PropDecoratorFactory, ...args: any[]): any { if (this instanceof PropDecoratorFactory) { metaCtor.apply(this, args); return this; diff --git a/packages/core/src/util/empty.ts b/packages/core/src/util/empty.ts index d30b12e7720a8..0db2000237238 100644 --- a/packages/core/src/util/empty.ts +++ b/packages/core/src/util/empty.ts @@ -1,10 +1,10 @@ /** -* @license -* Copyright Google Inc. All Rights Reserved. -* -* Use of this source code is governed by an MIT-style license that can be -* found in the LICENSE file at https://angular.io/license -*/ + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ import {initNgDevMode} from './ng_dev_mode'; /** diff --git a/packages/core/src/util/errors.ts b/packages/core/src/util/errors.ts index 7f895c4420573..6e0eb9d1247b2 100644 --- a/packages/core/src/util/errors.ts +++ b/packages/core/src/util/errors.ts @@ -13,8 +13,8 @@ export const ERROR_LOGGER = 'ngErrorLogger'; export function wrappedError(message: string, originalError: any): Error { - const msg = - `${message} caused by: ${originalError instanceof Error ? originalError.message: originalError }`; + const msg = `${message} caused by: ${ + originalError instanceof Error ? originalError.message : originalError}`; const error = Error(msg); (error as any)[ERROR_ORIGINAL_ERROR] = originalError; return error; diff --git a/packages/core/src/util/lang.ts b/packages/core/src/util/lang.ts index d69c39a1465ec..056a61b4cfb9a 100644 --- a/packages/core/src/util/lang.ts +++ b/packages/core/src/util/lang.ts @@ -20,7 +20,7 @@ export function isPromise(obj: any): obj is Promise { /** * Determine if the argument is an Observable */ -export function isObservable(obj: any | Observable): obj is Observable { +export function isObservable(obj: any|Observable): obj is Observable { // TODO: use isObservable once we update pass rxjs 6.1 // https://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md#610-2018-05-03 return !!obj && typeof obj.subscribe === 'function'; diff --git a/packages/core/src/util/microtask.ts b/packages/core/src/util/microtask.ts index fdc8a2b4f6443..4cda89fac18b8 100644 --- a/packages/core/src/util/microtask.ts +++ b/packages/core/src/util/microtask.ts @@ -13,7 +13,9 @@ declare const Zone: any; export function scheduleMicroTask(fn: Function) { if (typeof Zone === 'undefined') { // use promise to schedule microTask instead of use Zone - promise.then(() => { fn && fn.apply(null, null); }); + promise.then(() => { + fn && fn.apply(null, null); + }); } else { Zone.current.scheduleMicroTask('scheduleMicrotask', fn); } diff --git a/packages/core/src/util/stringify.ts b/packages/core/src/util/stringify.ts index 11c5f331f858a..519be71f5e2c3 100644 --- a/packages/core/src/util/stringify.ts +++ b/packages/core/src/util/stringify.ts @@ -45,7 +45,7 @@ export function stringify(token: any): string { * @param after after string. * @returns concatenated string. */ -export function concatStringsWithSpace(before: string | null, after: string | null): string { +export function concatStringsWithSpace(before: string|null, after: string|null): string { return (before == null || before === '') ? (after === null ? '' : after) : ((after == null || after === '') ? before : before + ' ' + after); diff --git a/packages/core/src/view/element.ts b/packages/core/src/view/element.ts index ed4b9f71c03d5..d31d5b43f41d3 100644 --- a/packages/core/src/view/element.ts +++ b/packages/core/src/view/element.ts @@ -10,12 +10,12 @@ import {ViewEncapsulation} from '../metadata/view'; import {RendererType2} from '../render/api'; import {SecurityContext} from '../sanitization/security'; -import {BindingDef, BindingFlags, ElementData, ElementHandleEventFn, NodeDef, NodeFlags, OutputDef, OutputType, QueryValueType, ViewData, ViewDefinitionFactory, asElementData} from './types'; -import {NOOP, calcBindingFlags, checkAndUpdateBinding, dispatchEvent, elementEventFullName, getParentRenderElement, resolveDefinition, resolveRendererType2, splitMatchedQueriesDsl, splitNamespace} from './util'; +import {asElementData, BindingDef, BindingFlags, ElementData, ElementHandleEventFn, NodeDef, NodeFlags, OutputDef, OutputType, QueryValueType, ViewData, ViewDefinitionFactory} from './types'; +import {calcBindingFlags, checkAndUpdateBinding, dispatchEvent, elementEventFullName, getParentRenderElement, NOOP, resolveDefinition, resolveRendererType2, splitMatchedQueriesDsl, splitNamespace} from './util'; export function anchorDef( - flags: NodeFlags, matchedQueriesDsl: null | [string | number, QueryValueType][], - ngContentIndex: null | number, childCount: number, handleEvent?: null | ElementHandleEventFn, + flags: NodeFlags, matchedQueriesDsl: null|[string | number, QueryValueType][], + ngContentIndex: null|number, childCount: number, handleEvent?: null|ElementHandleEventFn, templateFactory?: ViewDefinitionFactory): NodeDef { flags |= NodeFlags.TypeElement; const {matchedQueries, references, matchedQueryIds} = splitMatchedQueriesDsl(matchedQueriesDsl); @@ -33,14 +33,20 @@ export function anchorDef( checkIndex: -1, childFlags: 0, directChildFlags: 0, - childMatchedQueries: 0, matchedQueries, matchedQueryIds, references, ngContentIndex, childCount, + childMatchedQueries: 0, + matchedQueries, + matchedQueryIds, + references, + ngContentIndex, + childCount, bindings: [], bindingFlags: 0, outputs: [], element: { ns: null, name: null, - attrs: null, template, + attrs: null, + template, componentProvider: null, componentView: null, componentRendererType: null, @@ -57,18 +63,18 @@ export function anchorDef( export function elementDef( checkIndex: number, flags: NodeFlags, - matchedQueriesDsl: null | [string | number, QueryValueType][], ngContentIndex: null | number, - childCount: number, namespaceAndName: string | null, fixedAttrs: null | [string, string][] = [], - bindings?: null | [BindingFlags, string, string | SecurityContext | null][], - outputs?: null | ([string, string])[], handleEvent?: null | ElementHandleEventFn, - componentView?: null | ViewDefinitionFactory, - componentRendererType?: RendererType2 | null): NodeDef { + matchedQueriesDsl: null|[string | number, QueryValueType][], ngContentIndex: null|number, + childCount: number, namespaceAndName: string|null, fixedAttrs: null|[string, string][] = [], + bindings?: null|[BindingFlags, string, string | SecurityContext | null][], + outputs?: null|([string, string])[], handleEvent?: null|ElementHandleEventFn, + componentView?: null|ViewDefinitionFactory, + componentRendererType?: RendererType2|null): NodeDef { if (!handleEvent) { handleEvent = NOOP; } const {matchedQueries, references, matchedQueryIds} = splitMatchedQueriesDsl(matchedQueriesDsl); - let ns: string = null !; - let name: string = null !; + let ns: string = null!; + let name: string = null!; if (namespaceAndName) { [ns, name] = splitNamespace(namespaceAndName); } @@ -78,8 +84,8 @@ export function elementDef( const [bindingFlags, namespaceAndName, suffixOrSecurityContext] = bindings[i]; const [ns, name] = splitNamespace(namespaceAndName); - let securityContext: SecurityContext = undefined !; - let suffix: string = undefined !; + let securityContext: SecurityContext = undefined!; + let suffix: string = undefined!; switch (bindingFlags & BindingFlags.Types) { case BindingFlags.TypeElementStyle: suffix = suffixOrSecurityContext; @@ -96,11 +102,8 @@ export function elementDef( const outputDefs: OutputDef[] = []; for (let i = 0; i < outputs.length; i++) { const [target, eventName] = outputs[i]; - outputDefs[i] = { - type: OutputType.ElementOutput, - target: target, eventName, - propName: null - }; + outputDefs[i] = + {type: OutputType.ElementOutput, target: target, eventName, propName: null}; } fixedAttrs = fixedAttrs || []; const attrs = <[string, string, string][]>fixedAttrs.map(([namespaceAndName, value]) => { @@ -124,7 +127,12 @@ export function elementDef( flags, childFlags: 0, directChildFlags: 0, - childMatchedQueries: 0, matchedQueries, matchedQueryIds, references, ngContentIndex, childCount, + childMatchedQueries: 0, + matchedQueries, + matchedQueryIds, + references, + ngContentIndex, + childCount, bindings: bindingDefs, bindingFlags: calcBindingFlags(bindingDefs), outputs: outputDefs, @@ -149,7 +157,7 @@ export function elementDef( } export function createElement(view: ViewData, renderHost: any, def: NodeDef): ElementData { - const elDef = def.element !; + const elDef = def.element!; const rootSelectorOrNode = view.root.selectorOrNode; const renderer = view.renderer; let el: any; @@ -192,7 +200,7 @@ export function listenToElementOutputs(view: ViewData, compView: ViewData, def: } const disposable = listenerView.renderer.listen(listenTarget || el, output.eventName, handleEventClosure); - view.disposables ![def.outputIndex + i] = disposable; + view.disposables![def.outputIndex + i] = disposable; } } @@ -234,7 +242,7 @@ function checkAndUpdateElementValue(view: ViewData, def: NodeDef, bindingIdx: nu const binding = def.bindings[bindingIdx]; const elData = asElementData(view, def.nodeIndex); const renderNode = elData.renderElement; - const name = binding.name !; + const name = binding.name!; switch (binding.flags & BindingFlags.Types) { case BindingFlags.TypeElementAttribute: setElementAttribute(view, binding, renderNode, binding.ns, name, value); @@ -257,7 +265,7 @@ function checkAndUpdateElementValue(view: ViewData, def: NodeDef, bindingIdx: nu } function setElementAttribute( - view: ViewData, binding: BindingDef, renderNode: any, ns: string | null, name: string, + view: ViewData, binding: BindingDef, renderNode: any, ns: string|null, name: string, value: any) { const securityContext = binding.securityContext; let renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value; @@ -282,7 +290,7 @@ function setElementClass(view: ViewData, renderNode: any, name: string, value: b function setElementStyle( view: ViewData, binding: BindingDef, renderNode: any, name: string, value: any) { let renderValue: string|null = - view.root.sanitizer.sanitize(SecurityContext.STYLE, value as{} | string); + view.root.sanitizer.sanitize(SecurityContext.STYLE, value as {} | string); if (renderValue != null) { renderValue = renderValue.toString(); const unit = binding.suffix; diff --git a/packages/core/src/view/entrypoint.ts b/packages/core/src/view/entrypoint.ts index ae1cb7004eb7d..db14d4d7f1e86 100644 --- a/packages/core/src/view/entrypoint.ts +++ b/packages/core/src/view/entrypoint.ts @@ -48,7 +48,10 @@ function cloneNgModuleDefinition(def: NgModuleDefinition): NgModuleDefinition { return { factory: def.factory, - scope: def.scope, providers, modules, providersByKey, + scope: def.scope, + providers, + modules, + providersByKey, }; } diff --git a/packages/core/src/view/errors.ts b/packages/core/src/view/errors.ts index d7ded67a01add..1e78713982eeb 100644 --- a/packages/core/src/view/errors.ts +++ b/packages/core/src/view/errors.ts @@ -14,7 +14,8 @@ import {DebugContext} from './types'; export function expressionChangedAfterItHasBeenCheckedError( context: DebugContext, oldValue: any, currValue: any, isFirstCheck: boolean): Error { let msg = - `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '${oldValue}'. Current value: '${currValue}'.`; + `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '${ + oldValue}'. Current value: '${currValue}'.`; if (isFirstCheck) { msg += ` It seems like the view has been created after its parent and its children have been dirty checked.` + diff --git a/packages/core/src/view/index.ts b/packages/core/src/view/index.ts index 28b0947d26ab6..563f307784083 100644 --- a/packages/core/src/view/index.ts +++ b/packages/core/src/view/index.ts @@ -13,10 +13,10 @@ export {moduleDef, moduleProvideDef} from './ng_module'; export {directiveDef, pipeDef, providerDef} from './provider'; export {pureArrayDef, pureObjectDef, purePipeDef} from './pure_expression'; export {queryDef} from './query'; -export {ViewRef_, createComponentFactory, getComponentViewDefinitionFactory, nodeValue} from './refs'; +export {createComponentFactory, getComponentViewDefinitionFactory, nodeValue, ViewRef_} from './refs'; export {initServicesIfNeeded} from './services'; export {textDef} from './text'; -export {EMPTY_ARRAY, EMPTY_MAP, createRendererType2, elementEventFullName, inlineInterpolate, interpolate, rootRenderNodes, tokenKey, unwrapValue} from './util'; +export {createRendererType2, elementEventFullName, EMPTY_ARRAY, EMPTY_MAP, inlineInterpolate, interpolate, rootRenderNodes, tokenKey, unwrapValue} from './util'; export {viewDef} from './view'; export {attachEmbeddedView, detachEmbeddedView, moveEmbeddedView} from './view_attach'; diff --git a/packages/core/src/view/ng_content.ts b/packages/core/src/view/ng_content.ts index fd7ce7e9fcedc..a566c8f25a40a 100644 --- a/packages/core/src/view/ng_content.ts +++ b/packages/core/src/view/ng_content.ts @@ -7,9 +7,9 @@ */ import {NodeDef, NodeFlags, ViewData} from './types'; -import {RenderNodeAction, getParentRenderElement, visitProjectedRenderNodes} from './util'; +import {getParentRenderElement, RenderNodeAction, visitProjectedRenderNodes} from './util'; -export function ngContentDef(ngContentIndex: null | number, index: number): NodeDef { +export function ngContentDef(ngContentIndex: null|number, index: number): NodeDef { return { // will bet set by the view definition nodeIndex: -1, @@ -25,7 +25,8 @@ export function ngContentDef(ngContentIndex: null | number, index: number): Node childMatchedQueries: 0, matchedQueries: {}, matchedQueryIds: 0, - references: {}, ngContentIndex, + references: {}, + ngContentIndex, childCount: 0, bindings: [], bindingFlags: 0, @@ -44,7 +45,7 @@ export function appendNgContent(view: ViewData, renderHost: any, def: NodeDef) { // Nothing to do if there is no parent element. return; } - const ngContentIndex = def.ngContent !.index; + const ngContentIndex = def.ngContent!.index; visitProjectedRenderNodes( view, ngContentIndex, RenderNodeAction.AppendChild, parentEl, null, undefined); } diff --git a/packages/core/src/view/ng_module.ts b/packages/core/src/view/ng_module.ts index 4700396465509..cc44b4b1ea476 100644 --- a/packages/core/src/view/ng_module.ts +++ b/packages/core/src/view/ng_module.ts @@ -25,8 +25,7 @@ const INJECTORRefTokenKey = tokenKey(INJECTOR); const NgModuleRefTokenKey = tokenKey(NgModuleRef); export function moduleProvideDef( - flags: NodeFlags, token: any, value: any, - deps: ([DepFlags, any] | any)[]): NgModuleProviderDef { + flags: NodeFlags, token: any, value: any, deps: ([DepFlags, any]|any)[]): NgModuleProviderDef { // Need to resolve forwardRefs as e.g. for `useValue` we // lowered the expression and then stopped evaluating it, // i.e. also didn't unwrap it. @@ -35,7 +34,10 @@ export function moduleProvideDef( return { // will bet set by the module definition index: -1, - deps: depDefs, flags, token, value + deps: depDefs, + flags, + token, + value }; } @@ -113,7 +115,8 @@ export function resolveNgModuleDep( data._def.providers[index] = data._def.providersByKey[depDef.tokenKey] = { flags: NodeFlags.TypeFactoryProvider | NodeFlags.LazyProvider, value: injectableDef.factory, - deps: [], index, + deps: [], + index, token: depDef.token, }; data._providers[index] = UNDEFINED_VALUE; @@ -135,8 +138,9 @@ function moduleTransitivelyPresent(ngModule: NgModuleData, scope: any): boolean function targetsModule(ngModule: NgModuleData, def: ɵɵInjectableDef): boolean { const providedIn = def.providedIn; - return providedIn != null && (providedIn === 'any' || providedIn === ngModule._def.scope || - moduleTransitivelyPresent(ngModule, providedIn)); + return providedIn != null && + (providedIn === 'any' || providedIn === ngModule._def.scope || + moduleTransitivelyPresent(ngModule, providedIn)); } function _createProviderInstance(ngModule: NgModuleData, providerDef: NgModuleProviderDef): any { diff --git a/packages/core/src/view/provider.ts b/packages/core/src/view/provider.ts index f8421a03bc821..338af6969ef72 100644 --- a/packages/core/src/view/provider.ts +++ b/packages/core/src/view/provider.ts @@ -16,7 +16,7 @@ import {isObservable} from '../util/lang'; import {stringify} from '../util/stringify'; import {createChangeDetectorRef, createInjector} from './refs'; -import {BindingDef, BindingFlags, DepDef, DepFlags, NodeDef, NodeFlags, OutputDef, OutputType, ProviderData, QueryValueType, Services, ViewData, ViewFlags, ViewState, asElementData, asProviderData, shouldCallLifecycleInitHook} from './types'; +import {asElementData, asProviderData, BindingDef, BindingFlags, DepDef, DepFlags, NodeDef, NodeFlags, OutputDef, OutputType, ProviderData, QueryValueType, Services, shouldCallLifecycleInitHook, ViewData, ViewFlags, ViewState} from './types'; import {calcBindingFlags, checkBinding, dispatchEvent, isComponentView, splitDepsDsl, splitMatchedQueriesDsl, tokenKey, viewParentEl} from './util'; const Renderer2TokenKey = tokenKey(Renderer2); @@ -28,17 +28,18 @@ const InjectorRefTokenKey = tokenKey(Injector); const INJECTORRefTokenKey = tokenKey(INJECTOR); export function directiveDef( - checkIndex: number, flags: NodeFlags, - matchedQueries: null | [string | number, QueryValueType][], childCount: number, ctor: any, - deps: ([DepFlags, any] | any)[], props?: null | {[name: string]: [number, string]}, - outputs?: null | {[name: string]: string}): NodeDef { + checkIndex: number, flags: NodeFlags, matchedQueries: null|[string | number, QueryValueType][], + childCount: number, ctor: any, deps: ([DepFlags, any]|any)[], + props?: null|{[name: string]: [number, string]}, + outputs?: null|{[name: string]: string}): NodeDef { const bindings: BindingDef[] = []; if (props) { for (let prop in props) { const [bindingIndex, nonMinifiedName] = props[prop]; bindings[bindingIndex] = { flags: BindingFlags.TypeProperty, - name: prop, nonMinifiedName, + name: prop, + nonMinifiedName, ns: null, securityContext: null, suffix: null @@ -57,22 +58,21 @@ export function directiveDef( checkIndex, flags, matchedQueries, childCount, ctor, ctor, deps, bindings, outputDefs); } -export function pipeDef(flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef { +export function pipeDef(flags: NodeFlags, ctor: any, deps: ([DepFlags, any]|any)[]): NodeDef { flags |= NodeFlags.TypePipe; return _def(-1, flags, null, 0, ctor, ctor, deps); } export function providerDef( - flags: NodeFlags, matchedQueries: null | [string | number, QueryValueType][], token: any, - value: any, deps: ([DepFlags, any] | any)[]): NodeDef { + flags: NodeFlags, matchedQueries: null|[string | number, QueryValueType][], token: any, + value: any, deps: ([DepFlags, any]|any)[]): NodeDef { return _def(-1, flags, matchedQueries, 0, token, value, deps); } export function _def( - checkIndex: number, flags: NodeFlags, - matchedQueriesDsl: [string | number, QueryValueType][] | null, childCount: number, token: any, - value: any, deps: ([DepFlags, any] | any)[], bindings?: BindingDef[], - outputs?: OutputDef[]): NodeDef { + checkIndex: number, flags: NodeFlags, matchedQueriesDsl: [string|number, QueryValueType][]|null, + childCount: number, token: any, value: any, deps: ([DepFlags, any]|any)[], + bindings?: BindingDef[], outputs?: OutputDef[]): NodeDef { const {matchedQueries, references, matchedQueryIds} = splitMatchedQueriesDsl(matchedQueriesDsl); if (!outputs) { outputs = []; @@ -99,9 +99,15 @@ export function _def( flags, childFlags: 0, directChildFlags: 0, - childMatchedQueries: 0, matchedQueries, matchedQueryIds, references, - ngContentIndex: -1, childCount, bindings, - bindingFlags: calcBindingFlags(bindings), outputs, + childMatchedQueries: 0, + matchedQueries, + matchedQueryIds, + references, + ngContentIndex: -1, + childCount, + bindings, + bindingFlags: calcBindingFlags(bindings), + outputs, element: null, provider: {token, value, deps: depDefs}, text: null, @@ -124,24 +130,24 @@ export function createPipeInstance(view: ViewData, def: NodeDef): any { const allowPrivateServices = true; // pipes are always eager and classes! return createClass( - compView.parent !, viewParentEl(compView) !, allowPrivateServices, def.provider !.value, - def.provider !.deps); + compView.parent!, viewParentEl(compView)!, allowPrivateServices, def.provider!.value, + def.provider!.deps); } export function createDirectiveInstance(view: ViewData, def: NodeDef): any { // components can see other private services, other directives can't. const allowPrivateServices = (def.flags & NodeFlags.Component) > 0; // directives are always eager and classes! - const instance = createClass( - view, def.parent !, allowPrivateServices, def.provider !.value, def.provider !.deps); + const instance = + createClass(view, def.parent!, allowPrivateServices, def.provider!.value, def.provider!.deps); if (def.outputs.length) { for (let i = 0; i < def.outputs.length; i++) { const output = def.outputs[i]; - const outputObservable = instance[output.propName !]; + const outputObservable = instance[output.propName!]; if (isObservable(outputObservable)) { const subscription = outputObservable.subscribe( - eventHandlerClosure(view, def.parent !.nodeIndex, output.eventName)); - view.disposables ![def.outputIndex + i] = subscription.unsubscribe.bind(subscription); + eventHandlerClosure(view, def.parent!.nodeIndex, output.eventName)); + view.disposables![def.outputIndex + i] = subscription.unsubscribe.bind(subscription); } else { throw new Error( `@Output ${output.propName} not initialized in '${instance.constructor.name}'.`); @@ -161,7 +167,7 @@ export function checkAndUpdateDirectiveInline( const providerData = asProviderData(view, def.nodeIndex); const directive = providerData.instance; let changed = false; - let changes: SimpleChanges = undefined !; + let changes: SimpleChanges = undefined!; const bindLen = def.bindings.length; if (bindLen > 0 && checkBinding(view, def, 0, v0)) { changed = true; @@ -221,7 +227,7 @@ export function checkAndUpdateDirectiveDynamic( const providerData = asProviderData(view, def.nodeIndex); const directive = providerData.instance; let changed = false; - let changes: SimpleChanges = undefined !; + let changes: SimpleChanges = undefined!; for (let i = 0; i < values.length; i++) { if (checkBinding(view, def, i, values[i])) { changed = true; @@ -248,14 +254,14 @@ function _createProviderInstance(view: ViewData, def: NodeDef): any { switch (def.flags & NodeFlags.Types) { case NodeFlags.TypeClassProvider: return createClass( - view, def.parent !, allowPrivateServices, providerDef !.value, providerDef !.deps); + view, def.parent!, allowPrivateServices, providerDef!.value, providerDef!.deps); case NodeFlags.TypeFactoryProvider: return callFactory( - view, def.parent !, allowPrivateServices, providerDef !.value, providerDef !.deps); + view, def.parent!, allowPrivateServices, providerDef!.value, providerDef!.deps); case NodeFlags.TypeUseExistingProvider: - return resolveDep(view, def.parent !, allowPrivateServices, providerDef !.deps[0]); + return resolveDep(view, def.parent!, allowPrivateServices, providerDef!.deps[0]); case NodeFlags.TypeValueProvider: - return providerDef !.value; + return providerDef!.value; } } @@ -346,12 +352,12 @@ export function resolveDep( if (tokenKey === ChangeDetectorRefTokenKey) { // directives on the same element as a component should be able to control the change detector // of that component as well. - allowPrivateServices = !!(elDef && elDef.element !.componentView); + allowPrivateServices = !!(elDef && elDef.element!.componentView); } if (elDef && (depDef.flags & DepFlags.SkipSelf)) { allowPrivateServices = false; - elDef = elDef.parent !; + elDef = elDef.parent!; } let searchView: ViewData|null = view; @@ -367,7 +373,7 @@ export function resolveDep( case ViewContainerRefTokenKey: return asElementData(searchView, elDef.nodeIndex).viewContainer; case TemplateRefTokenKey: { - if (elDef.element !.template) { + if (elDef.element!.template) { return asElementData(searchView, elDef.nodeIndex).template; } break; @@ -381,8 +387,8 @@ export function resolveDep( return createInjector(searchView, elDef); default: const providerDef = - (allowPrivateServices ? elDef.element !.allProviders : - elDef.element !.publicProviders) ![tokenKey]; + (allowPrivateServices ? elDef.element!.allProviders : + elDef.element!.publicProviders)![tokenKey]; if (providerDef) { let providerData = asProviderData(searchView, providerDef.nodeIndex); if (!providerData) { @@ -395,8 +401,8 @@ export function resolveDep( } allowPrivateServices = isComponentView(searchView); - elDef = viewParentEl(searchView) !; - searchView = searchView.parent !; + elDef = viewParentEl(searchView)!; + searchView = searchView.parent!; if (depDef.flags & DepFlags.Self) { searchView = null; @@ -435,13 +441,13 @@ function updateProp( view: ViewData, providerData: ProviderData, def: NodeDef, bindingIdx: number, value: any, changes: SimpleChanges): SimpleChanges { if (def.flags & NodeFlags.Component) { - const compView = asElementData(view, def.parent !.nodeIndex).componentView; + const compView = asElementData(view, def.parent!.nodeIndex).componentView; if (compView.def.flags & ViewFlags.OnPush) { compView.state |= ViewState.ChecksEnabled; } } const binding = def.bindings[bindingIdx]; - const propName = binding.name !; + const propName = binding.name!; // Note: This is still safe with Closure Compiler as // the user passed in the property name as an object has to `providerDef`, // so Closure Compiler will have renamed the property correctly already. @@ -450,7 +456,7 @@ function updateProp( changes = changes || {}; const oldValue = WrappedValue.unwrap(view.oldValues[def.bindingIndex + bindingIdx]); const binding = def.bindings[bindingIdx]; - changes[binding.nonMinifiedName !] = + changes[binding.nonMinifiedName!] = new SimpleChange(oldValue, value, (view.state & ViewState.FirstCheck) !== 0); } view.oldValues[def.bindingIndex + bindingIdx] = value; diff --git a/packages/core/src/view/pure_expression.ts b/packages/core/src/view/pure_expression.ts index 1cbcae3558d16..c8b300913a639 100644 --- a/packages/core/src/view/pure_expression.ts +++ b/packages/core/src/view/pure_expression.ts @@ -8,7 +8,7 @@ import {newArray} from '../util/array_utils'; -import {BindingDef, BindingFlags, NodeDef, NodeFlags, PureExpressionData, ViewData, asPureExpressionData} from './types'; +import {asPureExpressionData, BindingDef, BindingFlags, NodeDef, NodeFlags, PureExpressionData, ViewData} from './types'; import {calcBindingFlags, checkAndUpdateBinding} from './util'; export function purePipeDef(checkIndex: number, argCount: number): NodeDef { @@ -64,7 +64,8 @@ function _pureExpressionDef( matchedQueryIds: 0, references: {}, ngContentIndex: -1, - childCount: 0, bindings, + childCount: 0, + bindings, bindingFlags: calcBindingFlags(bindings), outputs: [], element: null, @@ -115,16 +116,16 @@ export function checkAndUpdatePureExpressionInline( break; case NodeFlags.TypePureObject: value = {}; - if (bindLen > 0) value[bindings[0].name !] = v0; - if (bindLen > 1) value[bindings[1].name !] = v1; - if (bindLen > 2) value[bindings[2].name !] = v2; - if (bindLen > 3) value[bindings[3].name !] = v3; - if (bindLen > 4) value[bindings[4].name !] = v4; - if (bindLen > 5) value[bindings[5].name !] = v5; - if (bindLen > 6) value[bindings[6].name !] = v6; - if (bindLen > 7) value[bindings[7].name !] = v7; - if (bindLen > 8) value[bindings[8].name !] = v8; - if (bindLen > 9) value[bindings[9].name !] = v9; + if (bindLen > 0) value[bindings[0].name!] = v0; + if (bindLen > 1) value[bindings[1].name!] = v1; + if (bindLen > 2) value[bindings[2].name!] = v2; + if (bindLen > 3) value[bindings[3].name!] = v3; + if (bindLen > 4) value[bindings[4].name!] = v4; + if (bindLen > 5) value[bindings[5].name!] = v5; + if (bindLen > 6) value[bindings[6].name!] = v6; + if (bindLen > 7) value[bindings[7].name!] = v7; + if (bindLen > 8) value[bindings[8].name!] = v8; + if (bindLen > 9) value[bindings[9].name!] = v9; break; case NodeFlags.TypePurePipe: const pipe = v0; @@ -188,7 +189,7 @@ export function checkAndUpdatePureExpressionDynamic( case NodeFlags.TypePureObject: value = {}; for (let i = 0; i < values.length; i++) { - value[bindings[i].name !] = values[i]; + value[bindings[i].name!] = values[i]; } break; case NodeFlags.TypePurePipe: diff --git a/packages/core/src/view/query.ts b/packages/core/src/view/query.ts index 9e734b4be33d8..d462885d56994 100644 --- a/packages/core/src/view/query.ts +++ b/packages/core/src/view/query.ts @@ -9,7 +9,7 @@ import {ElementRef} from '../linker/element_ref'; import {QueryList} from '../linker/query_list'; -import {NodeDef, NodeFlags, QueryBindingDef, QueryBindingType, QueryDef, QueryValueType, ViewData, asElementData, asProviderData, asQueryList} from './types'; +import {asElementData, asProviderData, asQueryList, NodeDef, NodeFlags, QueryBindingDef, QueryBindingType, QueryDef, QueryValueType, ViewData} from './types'; import {declaredViewContainer, filterQueryId, isEmbeddedView} from './util'; export function queryDef( @@ -29,7 +29,8 @@ export function queryDef( outputIndex: -1, // regular values // TODO(vicb): check - checkIndex: -1, flags, + checkIndex: -1, + flags, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, @@ -56,7 +57,7 @@ export function createQuery(): QueryList { export function dirtyParentQueries(view: ViewData) { const queryIds = view.def.nodeMatchedQueries; while (view.parent && isEmbeddedView(view)) { - let tplDef = view.parentNodeDef !; + let tplDef = view.parentNodeDef!; view = view.parent; // content queries const end = tplDef.nodeIndex + tplDef.childCount; @@ -64,7 +65,7 @@ export function dirtyParentQueries(view: ViewData) { const nodeDef = view.def.nodes[i]; if ((nodeDef.flags & NodeFlags.TypeContentQuery) && (nodeDef.flags & NodeFlags.DynamicQuery) && - (nodeDef.query !.filterId & queryIds) === nodeDef.query !.filterId) { + (nodeDef.query!.filterId & queryIds) === nodeDef.query!.filterId) { asQueryList(view, i).setDirty(); } if ((nodeDef.flags & NodeFlags.TypeElement && i + nodeDef.childCount < tplDef.nodeIndex) || @@ -95,19 +96,19 @@ export function checkAndUpdateQuery(view: ViewData, nodeDef: NodeDef) { return; } let directiveInstance: any; - let newValues: any[] = undefined !; + let newValues: any[] = undefined!; if (nodeDef.flags & NodeFlags.TypeContentQuery) { - const elementDef = nodeDef.parent !.parent !; + const elementDef = nodeDef.parent!.parent!; newValues = calcQueryValues( - view, elementDef.nodeIndex, elementDef.nodeIndex + elementDef.childCount, nodeDef.query !, + view, elementDef.nodeIndex, elementDef.nodeIndex + elementDef.childCount, nodeDef.query!, []); - directiveInstance = asProviderData(view, nodeDef.parent !.nodeIndex).instance; + directiveInstance = asProviderData(view, nodeDef.parent!.nodeIndex).instance; } else if (nodeDef.flags & NodeFlags.TypeViewQuery) { - newValues = calcQueryValues(view, 0, view.def.nodes.length - 1, nodeDef.query !, []); + newValues = calcQueryValues(view, 0, view.def.nodes.length - 1, nodeDef.query!, []); directiveInstance = view.component; } queryList.reset(newValues); - const bindings = nodeDef.query !.bindings; + const bindings = nodeDef.query!.bindings; let notify = false; for (let i = 0; i < bindings.length; i++) { const binding = bindings[i]; @@ -137,8 +138,8 @@ function calcQueryValues( if (valueType != null) { values.push(getQueryValue(view, nodeDef, valueType)); } - if (nodeDef.flags & NodeFlags.TypeElement && nodeDef.element !.template && - (nodeDef.element !.template !.nodeMatchedQueries & queryDef.filterId) === + if (nodeDef.flags & NodeFlags.TypeElement && nodeDef.element!.template && + (nodeDef.element!.template !.nodeMatchedQueries & queryDef.filterId) === queryDef.filterId) { const elementData = asElementData(view, i); // check embedded views that were attached at the place of their template, @@ -148,7 +149,7 @@ function calcQueryValues( i += nodeDef.childCount; } if (nodeDef.flags & NodeFlags.EmbeddedViews) { - const embeddedViews = elementData.viewContainer !._embeddedViews; + const embeddedViews = elementData.viewContainer!._embeddedViews; for (let k = 0; k < embeddedViews.length; k++) { const embeddedView = embeddedViews[k]; const dvc = declaredViewContainer(embeddedView); diff --git a/packages/core/src/view/refs.ts b/packages/core/src/view/refs.ts index 4fe9a5d731fff..36fe5cfa8616e 100644 --- a/packages/core/src/view/refs.ts +++ b/packages/core/src/view/refs.ts @@ -22,7 +22,7 @@ import {stringify} from '../util/stringify'; import {VERSION} from '../version'; import {callNgModuleLifecycle, initNgModule, resolveNgModuleDep} from './ng_module'; -import {DepFlags, ElementData, NgModuleData, NgModuleDefinition, NodeDef, NodeFlags, Services, TemplateData, ViewContainerData, ViewData, ViewDefinitionFactory, ViewState, asElementData, asProviderData, asTextData} from './types'; +import {asElementData, asProviderData, asTextData, DepFlags, ElementData, NgModuleData, NgModuleDefinition, NodeDef, NodeFlags, Services, TemplateData, ViewContainerData, ViewData, ViewDefinitionFactory, ViewState} from './types'; import {markParentViewsForCheck, resolveDefinition, rootRenderNodes, splitNamespace, tokenKey, viewParentEl} from './util'; import {attachEmbeddedView, detachEmbeddedView, moveEmbeddedView, renderDetachView} from './view_attach'; @@ -32,7 +32,7 @@ const EMPTY_CONTEXT = {}; // Putting any logic in here will destroy closure tree shaking! export function createComponentFactory( selector: string, componentType: Type, viewDefFactory: ViewDefinitionFactory, - inputs: {[propName: string]: string} | null, outputs: {[propName: string]: string}, + inputs: {[propName: string]: string}|null, outputs: {[propName: string]: string}, ngContentSelectors: string[]): ComponentFactory { return new ComponentFactory_( selector, componentType, viewDefFactory, inputs, outputs, ngContentSelectors); @@ -61,7 +61,7 @@ class ComponentFactory_ extends ComponentFactory { get inputs() { const inputsArr: {propName: string, templateName: string}[] = []; - const inputs = this._inputs !; + const inputs = this._inputs!; for (let propName in inputs) { const templateName = inputs[propName]; inputsArr.push({propName, templateName}); @@ -88,7 +88,7 @@ class ComponentFactory_ extends ComponentFactory { throw new Error('ngModule should be provided'); } const viewDef = resolveDefinition(this.viewDefFactory); - const componentNodeIndex = viewDef.nodes[0].element !.componentProvider !.nodeIndex; + const componentNodeIndex = viewDef.nodes[0].element!.componentProvider!.nodeIndex; const view = Services.createRootView( injector, projectableNodes || [], rootSelectorOrNode, viewDef, ngModule, EMPTY_CONTEXT); const component = asProviderData(view, componentNodeIndex).instance; @@ -115,11 +115,19 @@ class ComponentRef_ extends ComponentRef { get location(): ElementRef { return new ElementRef(asElementData(this._view, this._elDef.nodeIndex).renderElement); } - get injector(): Injector { return new Injector_(this._view, this._elDef); } - get componentType(): Type { return this._component.constructor; } + get injector(): Injector { + return new Injector_(this._view, this._elDef); + } + get componentType(): Type { + return this._component.constructor; + } - destroy(): void { this._viewRef.destroy(); } - onDestroy(callback: Function): void { this._viewRef.onDestroy(callback); } + destroy(): void { + this._viewRef.destroy(); + } + onDestroy(callback: Function): void { + this._viewRef.onDestroy(callback); + } } export function createViewContainerData( @@ -134,9 +142,13 @@ class ViewContainerRef_ implements ViewContainerData { _embeddedViews: ViewData[] = []; constructor(private _view: ViewData, private _elDef: NodeDef, private _data: ElementData) {} - get element(): ElementRef { return new ElementRef(this._data.renderElement); } + get element(): ElementRef { + return new ElementRef(this._data.renderElement); + } - get injector(): Injector { return new Injector_(this._view, this._elDef); } + get injector(): Injector { + return new Injector_(this._view, this._elDef); + } /** @deprecated No replacement */ get parentInjector(): Injector { @@ -144,7 +156,7 @@ class ViewContainerRef_ implements ViewContainerData { let elDef = this._elDef.parent; while (!elDef && view) { elDef = viewParentEl(view); - view = view.parent !; + view = view.parent!; } return view ? new Injector_(view, elDef) : new Injector_(this._view, null); @@ -153,7 +165,7 @@ class ViewContainerRef_ implements ViewContainerData { clear(): void { const len = this._embeddedViews.length; for (let i = len - 1; i >= 0; i--) { - const view = detachEmbeddedView(this._data, i) !; + const view = detachEmbeddedView(this._data, i)!; Services.destroyView(view); } } @@ -168,7 +180,9 @@ class ViewContainerRef_ implements ViewContainerData { return null; } - get length(): number { return this._embeddedViews.length; } + get length(): number { + return this._embeddedViews.length; + } createEmbeddedView(templateRef: TemplateRef, context?: C, index?: number): EmbeddedViewRef { @@ -243,14 +257,24 @@ export class ViewRef_ implements EmbeddedViewRef, InternalViewRef { this._appRef = null; } - get rootNodes(): any[] { return rootRenderNodes(this._view); } + get rootNodes(): any[] { + return rootRenderNodes(this._view); + } - get context() { return this._view.context; } + get context() { + return this._view.context; + } - get destroyed(): boolean { return (this._view.state & ViewState.Destroyed) !== 0; } + get destroyed(): boolean { + return (this._view.state & ViewState.Destroyed) !== 0; + } - markForCheck(): void { markParentViewsForCheck(this._view); } - detach(): void { this._view.state &= ~ViewState.Attached; } + markForCheck(): void { + markParentViewsForCheck(this._view); + } + detach(): void { + this._view.state &= ~ViewState.Attached; + } detectChanges(): void { const fs = this._view.root.rendererFactory; if (fs.begin) { @@ -264,9 +288,13 @@ export class ViewRef_ implements EmbeddedViewRef, InternalViewRef { } } } - checkNoChanges(): void { Services.checkNoChangesView(this._view); } + checkNoChanges(): void { + Services.checkNoChangesView(this._view); + } - reattach(): void { this._view.state |= ViewState.Attached; } + reattach(): void { + this._view.state |= ViewState.Attached; + } onDestroy(callback: Function) { if (!this._view.disposables) { this._view.disposables = []; @@ -313,13 +341,15 @@ class TemplateRef_ extends TemplateRef implements TemplateData { * @internal */ // TODO(issue/24571): remove '!'. - _projectedViews !: ViewData[]; + _projectedViews!: ViewData[]; - constructor(private _parentView: ViewData, private _def: NodeDef) { super(); } + constructor(private _parentView: ViewData, private _def: NodeDef) { + super(); + } createEmbeddedView(context: any): EmbeddedViewRef { return new ViewRef_(Services.createEmbeddedView( - this._parentView, this._def, this._def.element !.template !, context)); + this._parentView, this._def, this._def.element!.template !, context)); } get elementRef(): ElementRef { @@ -346,7 +376,7 @@ export function nodeValue(view: ViewData, index: number): any { const def = view.def.nodes[index]; if (def.flags & NodeFlags.TypeElement) { const elData = asElementData(view, def.nodeIndex); - return def.element !.template ? elData.template : elData.renderElement; + return def.element!.template ? elData.template : elData.renderElement; } else if (def.flags & NodeFlags.TypeText) { return asTextData(view, def.nodeIndex).renderText; } else if (def.flags & (NodeFlags.CatProvider | NodeFlags.TypePipe)) { @@ -366,10 +396,10 @@ class NgModuleRef_ implements NgModuleData, InternalNgModuleRef { private _destroyed: boolean = false; /** @internal */ // TODO(issue/24571): remove '!'. - _providers !: any[]; + _providers!: any[]; /** @internal */ // TODO(issue/24571): remove '!'. - _modules !: any[]; + _modules!: any[]; readonly injector: Injector = this; @@ -391,9 +421,13 @@ class NgModuleRef_ implements NgModuleData, InternalNgModuleRef { this, {token: token, tokenKey: tokenKey(token), flags: flags}, notFoundValue); } - get instance() { return this.get(this._moduleType); } + get instance() { + return this.get(this._moduleType); + } - get componentFactoryResolver() { return this.get(ComponentFactoryResolver); } + get componentFactoryResolver() { + return this.get(ComponentFactoryResolver); + } destroy(): void { if (this._destroyed) { @@ -405,5 +439,7 @@ class NgModuleRef_ implements NgModuleData, InternalNgModuleRef { this._destroyListeners.forEach((listener) => listener()); } - onDestroy(callback: () => void): void { this._destroyListeners.push(callback); } + onDestroy(callback: () => void): void { + this._destroyListeners.push(callback); + } } diff --git a/packages/core/src/view/services.ts b/packages/core/src/view/services.ts index 82caa09c75a4c..97b9f2bf9208d 100644 --- a/packages/core/src/view/services.ts +++ b/packages/core/src/view/services.ts @@ -8,7 +8,7 @@ import {DebugElement__PRE_R3__, DebugEventListener, DebugNode__PRE_R3__, getDebugNode, indexDebugNode, removeDebugNodeFromIndex} from '../debug/debug_node'; import {Injector} from '../di'; -import {InjectableType, getInjectableDef, ɵɵInjectableDef} from '../di/interface/defs'; +import {getInjectableDef, InjectableType, ɵɵInjectableDef} from '../di/interface/defs'; import {ErrorHandler} from '../error_handler'; import {Type} from '../interface/type'; import {ComponentFactory} from '../linker/component_factory'; @@ -22,8 +22,8 @@ import {isViewDebugError, viewDestroyedError, viewWrappedDebugError} from './err import {resolveDep} from './provider'; import {dirtyParentQueries, getQueryValue} from './query'; import {createInjector, createNgModuleRef, getComponentViewDefinitionFactory} from './refs'; -import {ArgumentType, BindingFlags, CheckType, DebugContext, ElementData, NgModuleDefinition, NodeDef, NodeFlags, NodeLogger, ProviderOverride, RootData, Services, ViewData, ViewDefinition, ViewState, asElementData, asPureExpressionData} from './types'; -import {NOOP, isComponentView, renderNode, resolveDefinition, splitDepsDsl, tokenKey, viewParentEl} from './util'; +import {ArgumentType, asElementData, asPureExpressionData, BindingFlags, CheckType, DebugContext, ElementData, NgModuleDefinition, NodeDef, NodeFlags, NodeLogger, ProviderOverride, RootData, Services, ViewData, ViewDefinition, ViewState} from './types'; +import {isComponentView, NOOP, renderNode, resolveDefinition, splitDepsDsl, tokenKey, viewParentEl} from './util'; import {checkAndUpdateNode, checkAndUpdateView, checkNoChangesNode, checkNoChangesView, createComponentView, createEmbeddedView, createRootView, destroyView} from './view'; @@ -69,15 +69,13 @@ function createProdServices() { destroyView: destroyView, createDebugContext: (view: ViewData, nodeIndex: number) => new DebugContext_(view, nodeIndex), handleEvent: (view: ViewData, nodeIndex: number, eventName: string, event: any) => - view.def.handleEvent(view, nodeIndex, eventName, event), + view.def.handleEvent(view, nodeIndex, eventName, event), updateDirectives: (view: ViewData, checkType: CheckType) => view.def.updateDirectives( - checkType === CheckType.CheckAndUpdate ? prodCheckAndUpdateNode : - prodCheckNoChangesNode, - view), + checkType === CheckType.CheckAndUpdate ? prodCheckAndUpdateNode : prodCheckNoChangesNode, + view), updateRenderer: (view: ViewData, checkType: CheckType) => view.def.updateRenderer( - checkType === CheckType.CheckAndUpdate ? prodCheckAndUpdateNode : - prodCheckNoChangesNode, - view), + checkType === CheckType.CheckAndUpdate ? prodCheckAndUpdateNode : prodCheckNoChangesNode, + view), }; } @@ -102,7 +100,7 @@ function createDebugServices() { } function createProdRootView( - elInjector: Injector, projectableNodes: any[][], rootSelectorOrNode: string | any, + elInjector: Injector, projectableNodes: any[][], rootSelectorOrNode: string|any, def: ViewDefinition, ngModule: NgModuleRef, context?: any): ViewData { const rendererFactory: RendererFactory2 = ngModule.injector.get(RendererFactory2); return createRootView( @@ -111,7 +109,7 @@ function createProdRootView( } function debugCreateRootView( - elInjector: Injector, projectableNodes: any[][], rootSelectorOrNode: string | any, + elInjector: Injector, projectableNodes: any[][], rootSelectorOrNode: string|any, def: ViewDefinition, ngModule: NgModuleRef, context?: any): ViewData { const rendererFactory: RendererFactory2 = ngModule.injector.get(RendererFactory2); const root = createRootData( @@ -130,8 +128,13 @@ function createRootData( const renderer = rendererFactory.createRenderer(null, null); return { ngModule, - injector: elInjector, projectableNodes, - selectorOrNode: rootSelectorOrNode, sanitizer, rendererFactory, renderer, errorHandler + injector: elInjector, + projectableNodes, + selectorOrNode: rootSelectorOrNode, + sanitizer, + rendererFactory, + renderer, + errorHandler }; } @@ -146,7 +149,7 @@ function debugCreateEmbeddedView( function debugCreateComponentView( parentView: ViewData, nodeDef: NodeDef, viewDef: ViewDefinition, hostElement: any): ViewData { const overrideComponentView = - viewDefOverrides.get(nodeDef.element !.componentProvider !.provider !.token); + viewDefOverrides.get(nodeDef.element!.componentProvider!.provider!.token); if (overrideComponentView) { viewDef = overrideComponentView; } else { @@ -178,7 +181,7 @@ function debugOverrideProvider(override: ProviderOverride) { function debugOverrideComponentView(comp: any, compFactory: ComponentFactory) { const hostViewDef = resolveDefinition(getComponentViewDefinitionFactory(compFactory)); - const compViewDef = resolveDefinition(hostViewDef.nodes[0].element !.componentView !); + const compViewDef = resolveDefinition(hostViewDef.nodes[0].element!.componentView!); viewDefOverrides.set(comp, compViewDef); } @@ -204,7 +207,7 @@ function applyProviderOverridesToView(def: ViewDefinition): ViewDefinition { } // clone the whole view definition, // as it maintains references between the nodes that are hard to update. - def = def.factory !(() => NOOP); + def = def.factory!(() => NOOP); for (let i = 0; i < elementIndicesWithOverwrittenProviders.length; i++) { applyProviderOverridesToElement(def, elementIndicesWithOverwrittenProviders[i]); } @@ -219,8 +222,8 @@ function applyProviderOverridesToView(def: ViewDefinition): ViewDefinition { lastElementDef = nodeDef; } if (lastElementDef && nodeDef.flags & NodeFlags.CatProviderNoDirective && - providerOverrides.has(nodeDef.provider !.token)) { - elIndicesWithOverwrittenProviders.push(lastElementDef !.nodeIndex); + providerOverrides.has(nodeDef.provider!.token)) { + elIndicesWithOverwrittenProviders.push(lastElementDef!.nodeIndex); lastElementDef = null; } } @@ -235,7 +238,7 @@ function applyProviderOverridesToView(def: ViewDefinition): ViewDefinition { return; } if (nodeDef.flags & NodeFlags.CatProviderNoDirective) { - const provider = nodeDef.provider !; + const provider = nodeDef.provider!; const override = providerOverrides.get(provider.token); if (override) { nodeDef.flags = (nodeDef.flags & ~NodeFlags.CatProviderNoDirective) | override.flags; @@ -257,7 +260,7 @@ function applyProviderOverridesToNgModule(def: NgModuleDefinition): NgModuleDefi } // clone the whole view definition, // as it maintains references between the nodes that are hard to update. - def = def.factory !(() => NOOP); + def = def.factory!(() => NOOP); applyProviderOverrides(def); return def; @@ -277,7 +280,7 @@ function applyProviderOverridesToNgModule(def: NgModuleDefinition): NgModuleDefi }); def.modules.forEach(module => { providerOverridesWithScope.forEach((override, token) => { - if (getInjectableDef(token) !.providedIn === module) { + if (getInjectableDef(token)!.providedIn === module) { hasOverrides = true; hasDeprecatedOverrides = hasDeprecatedOverrides || override.deprecatedBehavior; } @@ -305,7 +308,7 @@ function applyProviderOverridesToNgModule(def: NgModuleDefinition): NgModuleDefi if (providerOverridesWithScope.size > 0) { let moduleSet = new Set(def.modules); providerOverridesWithScope.forEach((override, token) => { - if (moduleSet.has(getInjectableDef(token) !.providedIn)) { + if (moduleSet.has(getInjectableDef(token)!.providedIn)) { let provider = { token: token, flags: @@ -366,7 +369,7 @@ let _currentAction: DebugAction; let _currentView: ViewData; let _currentNodeIndex: number|null; -function debugSetCurrentNode(view: ViewData, nodeIndex: number | null) { +function debugSetCurrentNode(view: ViewData, nodeIndex: number|null) { _currentView = view; _currentNodeIndex = nodeIndex; } @@ -436,13 +439,13 @@ function debugCheckAndUpdateNode( const binding = nodeDef.bindings[i]; const value = values[i]; if (binding.flags & BindingFlags.TypeProperty) { - bindingValues[normalizeDebugBindingName(binding.nonMinifiedName !)] = + bindingValues[normalizeDebugBindingName(binding.nonMinifiedName!)] = normalizeDebugBindingValue(value); } } - const elDef = nodeDef.parent !; + const elDef = nodeDef.parent!; const el = asElementData(view, elDef.nodeIndex).renderElement; - if (!elDef.element !.name) { + if (!elDef.element!.name) { // a comment. view.renderer.setValue(el, `bindings=${JSON.stringify(bindingValues, null, 2)}`); } else { @@ -498,12 +501,12 @@ class DebugContext_ implements DebugContext { let elDef = this.nodeDef; let elView = view; while (elDef && (elDef.flags & NodeFlags.TypeElement) === 0) { - elDef = elDef.parent !; + elDef = elDef.parent!; } if (!elDef) { while (!elDef && elView) { - elDef = viewParentEl(elView) !; - elView = elView.parent !; + elDef = viewParentEl(elView)!; + elView = elView.parent!; } } this.elDef = elDef; @@ -515,11 +518,17 @@ class DebugContext_ implements DebugContext { return asElementData(this.elView, this.elDef.nodeIndex).componentView || this.view; } - get injector(): Injector { return createInjector(this.elView, this.elDef); } + get injector(): Injector { + return createInjector(this.elView, this.elDef); + } - get component(): any { return this.elOrCompView.component; } + get component(): any { + return this.elOrCompView.component; + } - get context(): any { return this.elOrCompView.context; } + get context(): any { + return this.elOrCompView.context; + } get providerTokens(): any[] { const tokens: any[] = []; @@ -528,7 +537,7 @@ class DebugContext_ implements DebugContext { i++) { const childDef = this.elView.def.nodes[i]; if (childDef.flags & NodeFlags.CatProvider) { - tokens.push(childDef.provider !.token); + tokens.push(childDef.provider!.token); } i += childDef.childCount; } @@ -585,7 +594,7 @@ class DebugContext_ implements DebugContext { return NOOP; } }; - logViewDef.factory !(nodeLogger); + logViewDef.factory!(nodeLogger); if (currRenderNodeIndex < renderNodeIndex) { console.error('Illegal state: the ViewDefinitionFactory did not call the logger!'); (console.error)(...values); @@ -606,10 +615,10 @@ function getRenderNodeIndex(viewDef: ViewDefinition, nodeIndex: number): number function findHostElement(view: ViewData): ElementData|null { while (view && !isComponentView(view)) { - view = view.parent !; + view = view.parent!; } if (view.parent) { - return asElementData(view.parent, viewParentEl(view) !.nodeIndex); + return asElementData(view.parent, viewParentEl(view)!.nodeIndex); } return null; } @@ -635,7 +644,7 @@ function callWithDebugContext(action: DebugAction, fn: any, self: any, args: any if (isViewDebugError(e) || !_currentView) { throw e; } - throw viewWrappedDebugError(e, getCurrentDebugContext() !); + throw viewWrappedDebugError(e, getCurrentDebugContext()!); } } @@ -672,7 +681,9 @@ export class DebugRendererFactory2 implements RendererFactory2 { export class DebugRenderer2 implements Renderer2 { readonly data: {[key: string]: any}; - private createDebugContext(nativeElement: any) { return this.debugContextFactory(nativeElement); } + private createDebugContext(nativeElement: any) { + return this.debugContextFactory(nativeElement); + } /** * Factory function used to create a `DebugContext` when a node is created. @@ -684,10 +695,12 @@ export class DebugRenderer2 implements Renderer2 { */ debugContextFactory: (nativeElement?: any) => DebugContext | null = getCurrentDebugContext; - constructor(private delegate: Renderer2) { this.data = this.delegate.data; } + constructor(private delegate: Renderer2) { + this.data = this.delegate.data; + } destroyNode(node: any) { - const debugNode = getDebugNode(node) !; + const debugNode = getDebugNode(node)!; removeDebugNodeFromIndex(debugNode); if (debugNode instanceof DebugNode__PRE_R3__) { debugNode.listeners.length = 0; @@ -697,14 +710,16 @@ export class DebugRenderer2 implements Renderer2 { } } - destroy() { this.delegate.destroy(); } + destroy() { + this.delegate.destroy(); + } createElement(name: string, namespace?: string): any { const el = this.delegate.createElement(name, namespace); const debugCtx = this.createDebugContext(el); if (debugCtx) { const debugEl = new DebugElement__PRE_R3__(el, null, debugCtx); - (debugEl as{name: string}).name = name; + (debugEl as {name: string}).name = name; indexDebugNode(debugEl); } return el; @@ -740,7 +755,7 @@ export class DebugRenderer2 implements Renderer2 { insertBefore(parent: any, newChild: any, refChild: any): void { const debugEl = getDebugNode(parent); const debugChildEl = getDebugNode(newChild); - const debugRefEl = getDebugNode(refChild) !; + const debugRefEl = getDebugNode(refChild)!; if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) { debugEl.insertBefore(debugRefEl, debugChildEl); } @@ -837,7 +852,13 @@ export class DebugRenderer2 implements Renderer2 { return this.delegate.listen(target, eventName, callback); } - parentNode(node: any): any { return this.delegate.parentNode(node); } - nextSibling(node: any): any { return this.delegate.nextSibling(node); } - setValue(node: any, value: string): void { return this.delegate.setValue(node, value); } + parentNode(node: any): any { + return this.delegate.parentNode(node); + } + nextSibling(node: any): any { + return this.delegate.nextSibling(node); + } + setValue(node: any, value: string): void { + return this.delegate.setValue(node, value); + } } diff --git a/packages/core/src/view/text.ts b/packages/core/src/view/text.ts index 7067d7fe43de2..51f31e25c7e83 100644 --- a/packages/core/src/view/text.ts +++ b/packages/core/src/view/text.ts @@ -6,11 +6,11 @@ * found in the LICENSE file at https://angular.io/license */ -import {BindingDef, BindingFlags, NodeDef, NodeFlags, TextData, ViewData, asTextData} from './types'; +import {asTextData, BindingDef, BindingFlags, NodeDef, NodeFlags, TextData, ViewData} from './types'; import {checkAndUpdateBinding, getParentRenderElement} from './util'; export function textDef( - checkIndex: number, ngContentIndex: number | null, staticText: string[]): NodeDef { + checkIndex: number, ngContentIndex: number|null, staticText: string[]): NodeDef { const bindings: BindingDef[] = []; for (let i = 1; i < staticText.length; i++) { bindings[i - 1] = { @@ -38,8 +38,10 @@ export function textDef( childMatchedQueries: 0, matchedQueries: {}, matchedQueryIds: 0, - references: {}, ngContentIndex, - childCount: 0, bindings, + references: {}, + ngContentIndex, + childCount: 0, + bindings, bindingFlags: BindingFlags.TypeProperty, outputs: [], element: null, @@ -53,7 +55,7 @@ export function textDef( export function createText(view: ViewData, renderHost: any, def: NodeDef): TextData { let renderNode: any; const renderer = view.renderer; - renderNode = renderer.createText(def.text !.prefix); + renderNode = renderer.createText(def.text!.prefix); const parentEl = getParentRenderElement(view, renderHost, def); if (parentEl) { renderer.appendChild(parentEl, renderNode); @@ -79,7 +81,7 @@ export function checkAndUpdateTextInline( if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9)) changed = true; if (changed) { - let value = def.text !.prefix; + let value = def.text!.prefix; if (bindLen > 0) value += _addInterpolationPart(v0, bindings[0]); if (bindLen > 1) value += _addInterpolationPart(v1, bindings[1]); if (bindLen > 2) value += _addInterpolationPart(v2, bindings[2]); @@ -111,7 +113,7 @@ export function checkAndUpdateTextDynamic(view: ViewData, def: NodeDef, values: for (let i = 0; i < values.length; i++) { value = value + _addInterpolationPart(values[i], bindings[i]); } - value = def.text !.prefix + value; + value = def.text!.prefix + value; const renderNode = asTextData(view, def.nodeIndex).renderText; view.renderer.setValue(renderNode, value); } diff --git a/packages/core/src/view/types.ts b/packages/core/src/view/types.ts index 3172afa33bc79..da23eb3675d6a 100644 --- a/packages/core/src/view/types.ts +++ b/packages/core/src/view/types.ts @@ -30,16 +30,22 @@ import {SecurityContext} from '../sanitization/security'; * function to log the error from the definition of the node, which is shown in all browser * logs. */ -export interface DefinitionFactory> { (logger: NodeLogger): D; } +export interface DefinitionFactory> { + (logger: NodeLogger): D; +} /** * Function to call console.error at the right source location. This is an indirection * via another function as browser will log the location that actually called * `console.error`. */ -export interface NodeLogger { (): () => void; } +export interface NodeLogger { + (): () => void; +} -export interface Definition> { factory: DF|null; } +export interface Definition> { + factory: DF|null; +} export interface NgModuleDefinition extends Definition { providers: NgModuleProviderDef[]; @@ -77,7 +83,9 @@ export interface ViewDefinition extends Definition { export interface ViewDefinitionFactory extends DefinitionFactory {} -export interface ViewUpdateFn { (check: NodeCheckFn, view: ViewData): void; } +export interface ViewUpdateFn { + (check: NodeCheckFn, view: ViewData): void; +} // helper functions to create an overloaded function type. export interface NodeCheckFn { @@ -87,7 +95,10 @@ export interface NodeCheckFn { v3?: any, v4?: any, v5?: any, v6?: any, v7?: any, v8?: any, v9?: any): any; } -export const enum ArgumentType {Inline = 0, Dynamic = 1} +export const enum ArgumentType { + Inline = 0, + Dynamic = 1 +} export interface ViewHandleEventFn { (view: ViewData, nodeIndex: number, eventName: string, event: any): boolean; @@ -232,7 +243,10 @@ export interface OutputDef { propName: string|null; } -export const enum OutputType {ElementOutput, DirectiveOutput} +export const enum OutputType { + ElementOutput, + DirectiveOutput +} export const enum QueryValueType { ElementRef = 0, @@ -266,7 +280,9 @@ export interface ElementDef { handleEvent: ElementHandleEventFn|null; } -export interface ElementHandleEventFn { (view: ViewData, eventName: string, event: any): boolean; } +export interface ElementHandleEventFn { + (view: ViewData, eventName: string, event: any): boolean; +} export interface ProviderDef { token: any; @@ -299,7 +315,9 @@ export const enum DepFlags { Value = 1 << 3, } -export interface TextDef { prefix: string; } +export interface TextDef { + prefix: string; +} export interface QueryDef { id: number; @@ -313,7 +331,10 @@ export interface QueryBindingDef { bindingType: QueryBindingType; } -export const enum QueryBindingType {First = 0, All = 1} +export const enum QueryBindingType { + First = 0, + All = 1 +} export interface NgContentDef { /** @@ -424,7 +445,9 @@ export function shouldCallLifecycleInitHook( return false; } -export interface DisposableFn { (): void; } +export interface DisposableFn { + (): void; +} /** * Node instance data. @@ -437,14 +460,18 @@ export interface DisposableFn { (): void; } * This way, no usage site can get a `NodeData` from view.nodes and then use it for different * purposes. */ -export class NodeData { private __brand: any; } +export class NodeData { + private __brand: any; +} /** * Data for an instantiated NodeType.Text. * * Attention: Adding fields to this is performance sensitive! */ -export interface TextData { renderText: any; } +export interface TextData { + renderText: any; +} /** * Accessor for view.nodes, enforcing that every usage site stays monomorphic. @@ -494,7 +521,9 @@ export function asElementData(view: ViewData, index: number): ElementData { * * Attention: Adding fields to this is performance sensitive! */ -export interface ProviderData { instance: any; } +export interface ProviderData { + instance: any; +} /** * Accessor for view.nodes, enforcing that every usage site stays monomorphic. @@ -508,7 +537,9 @@ export function asProviderData(view: ViewData, index: number): ProviderData { * * Attention: Adding fields to this is performance sensitive! */ -export interface PureExpressionData { value: any; } +export interface PureExpressionData { + value: any; +} /** * Accessor for view.nodes, enforcing that every usage site stays monomorphic. @@ -552,7 +583,10 @@ export abstract class DebugContext { // Other // ------------------------------------- -export const enum CheckType {CheckAndUpdate, CheckNoChanges} +export const enum CheckType { + CheckAndUpdate, + CheckNoChanges +} export interface ProviderOverride { token: any; @@ -595,21 +629,21 @@ export interface Services { * debug mode can hook it. It is lazily filled when `isDevMode` is known. */ export const Services: Services = { - setCurrentNode: undefined !, - createRootView: undefined !, - createEmbeddedView: undefined !, - createComponentView: undefined !, - createNgModuleRef: undefined !, - overrideProvider: undefined !, - overrideComponentView: undefined !, - clearOverrides: undefined !, - checkAndUpdateView: undefined !, - checkNoChangesView: undefined !, - destroyView: undefined !, - resolveDep: undefined !, - createDebugContext: undefined !, - handleEvent: undefined !, - updateDirectives: undefined !, - updateRenderer: undefined !, - dirtyParentQueries: undefined !, + setCurrentNode: undefined!, + createRootView: undefined!, + createEmbeddedView: undefined!, + createComponentView: undefined!, + createNgModuleRef: undefined!, + overrideProvider: undefined!, + overrideComponentView: undefined!, + clearOverrides: undefined!, + checkAndUpdateView: undefined!, + checkNoChangesView: undefined!, + destroyView: undefined!, + resolveDep: undefined!, + createDebugContext: undefined!, + handleEvent: undefined!, + updateDirectives: undefined!, + updateRenderer: undefined!, + dirtyParentQueries: undefined!, }; diff --git a/packages/core/src/view/util.ts b/packages/core/src/view/util.ts index 5e88b2124bf6b..29077efb69212 100644 --- a/packages/core/src/view/util.ts +++ b/packages/core/src/view/util.ts @@ -6,14 +6,15 @@ * found in the LICENSE file at https://angular.io/license */ -import {WrappedValue, devModeEqual} from '../change_detection/change_detection'; +import {devModeEqual, WrappedValue} from '../change_detection/change_detection'; import {SOURCE} from '../di/injector_compatibility'; import {ViewEncapsulation} from '../metadata/view'; import {RendererType2} from '../render/api'; import {looseIdentical} from '../util/comparison'; import {stringify} from '../util/stringify'; + import {expressionChangedAfterItHasBeenCheckedError} from './errors'; -import {BindingDef, BindingFlags, Definition, DefinitionFactory, DepDef, DepFlags, ElementData, NodeDef, NodeFlags, QueryValueType, Services, ViewData, ViewDefinition, ViewDefinitionFactory, ViewFlags, ViewState, asElementData, asTextData} from './types'; +import {asElementData, asTextData, BindingDef, BindingFlags, Definition, DefinitionFactory, DepDef, DepFlags, ElementData, NodeDef, NodeFlags, QueryValueType, Services, ViewData, ViewDefinition, ViewDefinitionFactory, ViewFlags, ViewState} from './types'; export const NOOP: any = () => {}; @@ -44,7 +45,7 @@ const EMPTY_RENDERER_TYPE_ID = '$$empty'; // Attention: this function is called as top level function. // Putting any logic in here will destroy closure tree shaking! export function createRendererType2(values: { - styles: (string | any[])[], + styles: (string|any[])[], encapsulation: ViewEncapsulation, data: {[kind: string]: any[]} }): RendererType2 { @@ -58,7 +59,7 @@ export function createRendererType2(values: { let _renderCompCount = 0; -export function resolveRendererType2(type?: RendererType2 | null): RendererType2|null { +export function resolveRendererType2(type?: RendererType2|null): RendererType2|null { if (type && type.id === UNDEFINED_RENDERER_TYPE_ID) { // first time we see this RendererType2. Initialize it... const isFilled = @@ -142,7 +143,7 @@ export function dispatchEvent( export function declaredViewContainer(view: ViewData): ElementData|null { if (view.parent) { const parentView = view.parent; - return asElementData(parentView, view.parentNodeDef !.nodeIndex); + return asElementData(parentView, view.parentNodeDef!.nodeIndex); } return null; } @@ -155,7 +156,7 @@ export function declaredViewContainer(view: ViewData): ElementData|null { export function viewParentEl(view: ViewData): NodeDef|null { const parentView = view.parent; if (parentView) { - return view.parentNodeDef !.parent; + return view.parentNodeDef!.parent; } else { return null; } @@ -170,24 +171,23 @@ export function renderNode(view: ViewData, def: NodeDef): any { } } -export function elementEventFullName(target: string | null, name: string): string { +export function elementEventFullName(target: string|null, name: string): string { return target ? `${target}:${name}` : name; } export function isComponentView(view: ViewData): boolean { - return !!view.parent && !!(view.parentNodeDef !.flags & NodeFlags.Component); + return !!view.parent && !!(view.parentNodeDef!.flags & NodeFlags.Component); } export function isEmbeddedView(view: ViewData): boolean { - return !!view.parent && !(view.parentNodeDef !.flags & NodeFlags.Component); + return !!view.parent && !(view.parentNodeDef!.flags & NodeFlags.Component); } export function filterQueryId(queryId: number): number { return 1 << (queryId % 32); } -export function splitMatchedQueriesDsl( - matchedQueriesDsl: [string | number, QueryValueType][] | null): { +export function splitMatchedQueriesDsl(matchedQueriesDsl: [string|number, QueryValueType][]|null): { matchedQueries: {[queryId: string]: QueryValueType}, references: {[refId: string]: QueryValueType}, matchedQueryIds: number @@ -208,7 +208,7 @@ export function splitMatchedQueriesDsl( return {matchedQueries, references, matchedQueryIds}; } -export function splitDepsDsl(deps: ([DepFlags, any] | any)[], sourceName?: string): DepDef[] { +export function splitDepsDsl(deps: ([DepFlags, any]|any)[], sourceName?: string): DepDef[] { return deps.map(value => { let token: any; let flags: DepFlags; @@ -230,12 +230,11 @@ export function getParentRenderElement(view: ViewData, renderHost: any, def: Nod if (renderParent) { if ((renderParent.flags & NodeFlags.TypeElement) === 0 || (renderParent.flags & NodeFlags.ComponentView) === 0 || - (renderParent.element !.componentRendererType && - renderParent.element !.componentRendererType !.encapsulation === - ViewEncapsulation.Native)) { + (renderParent.element!.componentRendererType && + renderParent.element!.componentRendererType!.encapsulation === ViewEncapsulation.Native)) { // only children of non components, or children of components with native encapsulation should // be attached. - return asElementData(view, def.renderParent !.nodeIndex).renderElement; + return asElementData(view, def.renderParent!.nodeIndex).renderElement; } } else { return renderHost; @@ -245,7 +244,7 @@ export function getParentRenderElement(view: ViewData, renderHost: any, def: Nod const DEFINITION_CACHE = new WeakMap>(); export function resolveDefinition>(factory: DefinitionFactory): D { - let value = DEFINITION_CACHE.get(factory) !as D; + let value = DEFINITION_CACHE.get(factory)! as D; if (!value) { value = factory(() => NOOP); value.factory = factory; @@ -260,13 +259,18 @@ export function rootRenderNodes(view: ViewData): any[] { return renderNodes; } -export const enum RenderNodeAction {Collect, AppendChild, InsertBefore, RemoveChild} +export const enum RenderNodeAction { + Collect, + AppendChild, + InsertBefore, + RemoveChild +} export function visitRootRenderNodes( view: ViewData, action: RenderNodeAction, parentNode: any, nextSibling: any, target?: any[]) { // We need to re-compute the parent node in case the nodes have been moved around manually if (action === RenderNodeAction.RemoveChild) { - parentNode = view.renderer.parentNode(renderNode(view, view.def.lastRenderRootNode !)); + parentNode = view.renderer.parentNode(renderNode(view, view.def.lastRenderRootNode!)); } visitSiblingRenderNodes( view, action, 0, view.def.nodes.length - 1, parentNode, nextSibling, target); @@ -292,19 +296,19 @@ export function visitProjectedRenderNodes( while (compView && !isComponentView(compView)) { compView = compView.parent; } - const hostView = compView !.parent; - const hostElDef = viewParentEl(compView !); - const startIndex = hostElDef !.nodeIndex + 1; - const endIndex = hostElDef !.nodeIndex + hostElDef !.childCount; + const hostView = compView!.parent; + const hostElDef = viewParentEl(compView!); + const startIndex = hostElDef!.nodeIndex + 1; + const endIndex = hostElDef!.nodeIndex + hostElDef!.childCount; for (let i = startIndex; i <= endIndex; i++) { - const nodeDef = hostView !.def.nodes[i]; + const nodeDef = hostView!.def.nodes[i]; if (nodeDef.ngContentIndex === ngContentIndex) { - visitRenderNode(hostView !, nodeDef, action, parentNode, nextSibling, target); + visitRenderNode(hostView!, nodeDef, action, parentNode, nextSibling, target); } // jump to next sibling i += nodeDef.childCount; } - if (!hostView !.parent) { + if (!hostView!.parent) { // a root view const projectedNodes = view.root.projectableNodes[ngContentIndex]; if (projectedNodes) { @@ -320,7 +324,7 @@ function visitRenderNode( target?: any[]) { if (nodeDef.flags & NodeFlags.TypeNgContent) { visitProjectedRenderNodes( - view, nodeDef.ngContent !.index, action, parentNode, nextSibling, target); + view, nodeDef.ngContent!.index, action, parentNode, nextSibling, target); } else { const rn = renderNode(view, nodeDef); if (action === RenderNodeAction.RemoveChild && (nodeDef.flags & NodeFlags.ComponentView) && @@ -337,12 +341,12 @@ function visitRenderNode( execRenderNodeAction(view, rn, action, parentNode, nextSibling, target); } if (nodeDef.flags & NodeFlags.EmbeddedViews) { - const embeddedViews = asElementData(view, nodeDef.nodeIndex).viewContainer !._embeddedViews; + const embeddedViews = asElementData(view, nodeDef.nodeIndex).viewContainer!._embeddedViews; for (let k = 0; k < embeddedViews.length; k++) { visitRootRenderNodes(embeddedViews[k], action, parentNode, nextSibling, target); } } - if (nodeDef.flags & NodeFlags.TypeElement && !nodeDef.element !.name) { + if (nodeDef.flags & NodeFlags.TypeElement && !nodeDef.element!.name) { visitSiblingRenderNodes( view, action, nodeDef.nodeIndex + 1, nodeDef.nodeIndex + nodeDef.childCount, parentNode, nextSibling, target); @@ -365,7 +369,7 @@ function execRenderNodeAction( renderer.removeChild(parentNode, renderNode); break; case RenderNodeAction.Collect: - target !.push(renderNode); + target!.push(renderNode); break; } } @@ -374,7 +378,7 @@ const NS_PREFIX_RE = /^:([^:]+):(.+)$/; export function splitNamespace(name: string): string[] { if (name[0] === ':') { - const match = name.match(NS_PREFIX_RE) !; + const match = name.match(NS_PREFIX_RE)!; return [match[1], match[2]]; } return ['', name]; diff --git a/packages/core/src/view/view.ts b/packages/core/src/view/view.ts index 434473f435def..a9cc1e13e3590 100644 --- a/packages/core/src/view/view.ts +++ b/packages/core/src/view/view.ts @@ -16,13 +16,13 @@ import {checkAndUpdatePureExpressionDynamic, checkAndUpdatePureExpressionInline, import {checkAndUpdateQuery, createQuery} from './query'; import {createTemplateData, createViewContainerData} from './refs'; import {checkAndUpdateTextDynamic, checkAndUpdateTextInline, createText} from './text'; -import {ArgumentType, CheckType, ElementData, NodeData, NodeDef, NodeFlags, ProviderData, RootData, Services, ViewData, ViewDefinition, ViewFlags, ViewHandleEventFn, ViewState, ViewUpdateFn, asElementData, asQueryList, asTextData, shiftInitState} from './types'; -import {NOOP, checkBindingNoChanges, isComponentView, markParentViewsForCheckProjectedViews, resolveDefinition, tokenKey} from './util'; +import {ArgumentType, asElementData, asQueryList, asTextData, CheckType, ElementData, NodeData, NodeDef, NodeFlags, ProviderData, RootData, Services, shiftInitState, ViewData, ViewDefinition, ViewFlags, ViewHandleEventFn, ViewState, ViewUpdateFn} from './types'; +import {checkBindingNoChanges, isComponentView, markParentViewsForCheckProjectedViews, NOOP, resolveDefinition, tokenKey} from './util'; import {detachProjectedView} from './view_attach'; export function viewDef( - flags: ViewFlags, nodes: NodeDef[], updateDirectives?: null | ViewUpdateFn, - updateRenderer?: null | ViewUpdateFn): ViewDefinition { + flags: ViewFlags, nodes: NodeDef[], updateDirectives?: null|ViewUpdateFn, + updateRenderer?: null|ViewUpdateFn): ViewDefinition { // clone nodes and set auto calculated values let viewBindingCount = 0; let viewDisposableCount = 0; @@ -48,7 +48,7 @@ export function viewDef( if (node.element) { const elDef = node.element; elDef.publicProviders = - currentParent ? currentParent.element !.publicProviders : Object.create(null); + currentParent ? currentParent.element!.publicProviders : Object.create(null); elDef.allProviders = elDef.publicProviders; // Note: We assume that all providers of an element are before any child element! currentElementHasPublicProviders = false; @@ -72,25 +72,25 @@ export function viewDef( if (!currentElementHasPublicProviders) { currentElementHasPublicProviders = true; // Use prototypical inheritance to not get O(n^2) complexity... - currentParent !.element !.publicProviders = - Object.create(currentParent !.element !.publicProviders); - currentParent !.element !.allProviders = currentParent !.element !.publicProviders; + currentParent!.element!.publicProviders = + Object.create(currentParent!.element!.publicProviders); + currentParent!.element!.allProviders = currentParent!.element!.publicProviders; } const isPrivateService = (node.flags & NodeFlags.PrivateProvider) !== 0; const isComponent = (node.flags & NodeFlags.Component) !== 0; if (!isPrivateService || isComponent) { - currentParent !.element !.publicProviders ![tokenKey(node.provider !.token)] = node; + currentParent!.element!.publicProviders![tokenKey(node.provider!.token)] = node; } else { if (!currentElementHasPrivateProviders) { currentElementHasPrivateProviders = true; // Use prototypical inheritance to not get O(n^2) complexity... - currentParent !.element !.allProviders = - Object.create(currentParent !.element !.publicProviders); + currentParent!.element!.allProviders = + Object.create(currentParent!.element!.publicProviders); } - currentParent !.element !.allProviders ![tokenKey(node.provider !.token)] = node; + currentParent!.element!.allProviders![tokenKey(node.provider!.token)] = node; } if (isComponent) { - currentParent !.element !.componentProvider = node; + currentParent!.element!.componentProvider = node; } } @@ -135,27 +135,30 @@ export function viewDef( } const handleEvent: ViewHandleEventFn = (view, nodeIndex, eventName, event) => - nodes[nodeIndex].element !.handleEvent !(view, eventName, event); + nodes[nodeIndex].element!.handleEvent!(view, eventName, event); return { // Will be filled later... factory: null, nodeFlags: viewNodeFlags, rootNodeFlags: viewRootNodeFlags, - nodeMatchedQueries: viewMatchedQueries, flags, + nodeMatchedQueries: viewMatchedQueries, + flags, nodes: nodes, updateDirectives: updateDirectives || NOOP, - updateRenderer: updateRenderer || NOOP, handleEvent, + updateRenderer: updateRenderer || NOOP, + handleEvent, bindingCount: viewBindingCount, - outputCount: viewDisposableCount, lastRenderRootNode + outputCount: viewDisposableCount, + lastRenderRootNode }; } function isNgContainer(node: NodeDef): boolean { - return (node.flags & NodeFlags.TypeElement) !== 0 && node.element !.name === null; + return (node.flags & NodeFlags.TypeElement) !== 0 && node.element!.name === null; } -function validateNode(parent: NodeDef | null, node: NodeDef, nodeCount: number) { +function validateNode(parent: NodeDef|null, node: NodeDef, nodeCount: number) { const template = node.element && node.element.template; if (template) { if (!template.lastRenderRootNode) { @@ -164,25 +167,28 @@ function validateNode(parent: NodeDef | null, node: NodeDef, nodeCount: number) if (template.lastRenderRootNode && template.lastRenderRootNode.flags & NodeFlags.EmbeddedViews) { throw new Error( - `Illegal State: Last root node of a template can't have embedded views, at index ${node.nodeIndex}!`); + `Illegal State: Last root node of a template can't have embedded views, at index ${ + node.nodeIndex}!`); } } if (node.flags & NodeFlags.CatProvider) { const parentFlags = parent ? parent.flags : 0; if ((parentFlags & NodeFlags.TypeElement) === 0) { throw new Error( - `Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index ${node.nodeIndex}!`); + `Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index ${ + node.nodeIndex}!`); } } if (node.query) { if (node.flags & NodeFlags.TypeContentQuery && (!parent || (parent.flags & NodeFlags.TypeDirective) === 0)) { throw new Error( - `Illegal State: Content Query nodes need to be children of directives, at index ${node.nodeIndex}!`); + `Illegal State: Content Query nodes need to be children of directives, at index ${ + node.nodeIndex}!`); } if (node.flags & NodeFlags.TypeViewQuery && parent) { - throw new Error( - `Illegal State: View Query nodes have to be top level nodes, at index ${node.nodeIndex}!`); + throw new Error(`Illegal State: View Query nodes have to be top level nodes, at index ${ + node.nodeIndex}!`); } } if (node.childCount) { @@ -213,7 +219,7 @@ export function createRootView(root: RootData, def: ViewDefinition, context?: an export function createComponentView( parentView: ViewData, nodeDef: NodeDef, viewDef: ViewDefinition, hostElement: any): ViewData { - const rendererType = nodeDef.element !.componentRendererType; + const rendererType = nodeDef.element!.componentRendererType; let compRenderer: Renderer2; if (!rendererType) { compRenderer = parentView.root.renderer; @@ -221,22 +227,27 @@ export function createComponentView( compRenderer = parentView.root.rendererFactory.createRenderer(hostElement, rendererType); } return createView( - parentView.root, compRenderer, parentView, nodeDef.element !.componentProvider, viewDef); + parentView.root, compRenderer, parentView, nodeDef.element!.componentProvider, viewDef); } function createView( - root: RootData, renderer: Renderer2, parent: ViewData | null, parentNodeDef: NodeDef | null, + root: RootData, renderer: Renderer2, parent: ViewData|null, parentNodeDef: NodeDef|null, def: ViewDefinition): ViewData { const nodes: NodeData[] = new Array(def.nodes.length); const disposables = def.outputCount ? new Array(def.outputCount) : null; const view: ViewData = { def, parent, - viewContainerParent: null, parentNodeDef, + viewContainerParent: null, + parentNodeDef, context: null, - component: null, nodes, - state: ViewState.CatInit, root, renderer, - oldValues: new Array(def.bindingCount), disposables, + component: null, + nodes, + state: ViewState.CatInit, + root, + renderer, + oldValues: new Array(def.bindingCount), + disposables, initIndex: -1 }; return view; @@ -251,7 +262,7 @@ function createViewNodes(view: ViewData) { let renderHost: any; if (isComponentView(view)) { const hostDef = view.parentNodeDef; - renderHost = asElementData(view.parent !, hostDef !.parent !.nodeIndex).renderElement; + renderHost = asElementData(view.parent!, hostDef!.parent!.nodeIndex).renderElement; } const def = view.def; const nodes = view.nodes; @@ -262,9 +273,9 @@ function createViewNodes(view: ViewData) { switch (nodeDef.flags & NodeFlags.Types) { case NodeFlags.TypeElement: const el = createElement(view, renderHost, nodeDef) as any; - let componentView: ViewData = undefined !; + let componentView: ViewData = undefined!; if (nodeDef.flags & NodeFlags.ComponentView) { - const compViewDef = resolveDefinition(nodeDef.element !.componentView !); + const compViewDef = resolveDefinition(nodeDef.element!.componentView!); componentView = Services.createComponentView(view, nodeDef, compViewDef, el); } listenToElementOutputs(view, componentView, nodeDef, el); @@ -272,7 +283,7 @@ function createViewNodes(view: ViewData) { renderElement: el, componentView, viewContainer: null, - template: nodeDef.element !.template ? createTemplateData(view, nodeDef) : undefined + template: nodeDef.element!.template ? createTemplateData(view, nodeDef) : undefined }; if (nodeDef.flags & NodeFlags.EmbeddedViews) { nodeData.viewContainer = createViewContainerData(view, nodeDef, nodeData); @@ -304,7 +315,7 @@ function createViewNodes(view: ViewData) { nodeData = {instance}; } if (nodeDef.flags & NodeFlags.Component) { - const compView = asElementData(view, nodeDef.parent !.nodeIndex).componentView; + const compView = asElementData(view, nodeDef.parent!.nodeIndex).componentView; initView(compView, nodeData.instance, nodeData.instance); } break; @@ -529,9 +540,9 @@ function destroyViewNodes(view: ViewData) { for (let i = 0; i < len; i++) { const def = view.def.nodes[i]; if (def.flags & NodeFlags.TypeElement) { - view.renderer.destroyNode !(asElementData(view, i).renderElement); + view.renderer.destroyNode!(asElementData(view, i).renderElement); } else if (def.flags & NodeFlags.TypeText) { - view.renderer.destroyNode !(asTextData(view, i).renderText); + view.renderer.destroyNode!(asTextData(view, i).renderText); } else if (def.flags & NodeFlags.TypeContentQuery || def.flags & NodeFlags.TypeViewQuery) { asQueryList(view, i).destroy(); } @@ -575,7 +586,7 @@ function execEmbeddedViewsAction(view: ViewData, action: ViewAction) { const nodeDef = def.nodes[i]; if (nodeDef.flags & NodeFlags.EmbeddedViews) { // a leaf - const embeddedViews = asElementData(view, i).viewContainer !._embeddedViews; + const embeddedViews = asElementData(view, i).viewContainer!._embeddedViews; for (let k = 0; k < embeddedViews.length; k++) { callViewAction(embeddedViews[k], action); } diff --git a/packages/core/src/view/view_attach.ts b/packages/core/src/view/view_attach.ts index ea86b9a4276ca..81c392d9f4edc 100644 --- a/packages/core/src/view/view_attach.ts +++ b/packages/core/src/view/view_attach.ts @@ -7,23 +7,24 @@ */ import {addToArray, removeFromArray} from '../util/array_utils'; + import {ElementData, NodeDef, NodeFlags, Services, ViewData, ViewDefinition, ViewState} from './types'; -import {RenderNodeAction, declaredViewContainer, renderNode, visitRootRenderNodes} from './util'; +import {declaredViewContainer, renderNode, RenderNodeAction, visitRootRenderNodes} from './util'; export function attachEmbeddedView( - parentView: ViewData, elementData: ElementData, viewIndex: number | undefined | null, + parentView: ViewData, elementData: ElementData, viewIndex: number|undefined|null, view: ViewData) { - let embeddedViews = elementData.viewContainer !._embeddedViews; + let embeddedViews = elementData.viewContainer!._embeddedViews; if (viewIndex === null || viewIndex === undefined) { viewIndex = embeddedViews.length; } view.viewContainerParent = parentView; - addToArray(embeddedViews, viewIndex !, view); + addToArray(embeddedViews, viewIndex!, view); attachProjectedView(elementData, view); Services.dirtyParentQueries(view); - const prevView = viewIndex ! > 0 ? embeddedViews[viewIndex ! - 1] : null; + const prevView = viewIndex! > 0 ? embeddedViews[viewIndex! - 1] : null; renderAttachEmbeddedView(elementData, prevView, view); } @@ -48,7 +49,7 @@ function attachProjectedView(vcElementData: ElementData, view: ViewData) { projectedViews.push(view); // Note: we are changing the NodeDef here as we cannot calculate // the fact whether a template is used for projection during compilation. - markNodeAsProjectedTemplate(view.parent !.def, view.parentNodeDef !); + markNodeAsProjectedTemplate(view.parent!.def, view.parentNodeDef!); } function markNodeAsProjectedTemplate(viewDef: ViewDefinition, nodeDef: NodeDef) { @@ -65,7 +66,7 @@ function markNodeAsProjectedTemplate(viewDef: ViewDefinition, nodeDef: NodeDef) } export function detachEmbeddedView(elementData: ElementData, viewIndex?: number): ViewData|null { - const embeddedViews = elementData.viewContainer !._embeddedViews; + const embeddedViews = elementData.viewContainer!._embeddedViews; if (viewIndex == null || viewIndex >= embeddedViews.length) { viewIndex = embeddedViews.length - 1; } @@ -100,7 +101,7 @@ export function detachProjectedView(view: ViewData) { export function moveEmbeddedView( elementData: ElementData, oldViewIndex: number, newViewIndex: number): ViewData { - const embeddedViews = elementData.viewContainer !._embeddedViews; + const embeddedViews = elementData.viewContainer!._embeddedViews; const view = embeddedViews[oldViewIndex]; removeFromArray(embeddedViews, oldViewIndex); if (newViewIndex == null) { @@ -121,9 +122,9 @@ export function moveEmbeddedView( } function renderAttachEmbeddedView( - elementData: ElementData, prevView: ViewData | null, view: ViewData) { - const prevRenderNode = prevView ? renderNode(prevView, prevView.def.lastRenderRootNode !) : - elementData.renderElement; + elementData: ElementData, prevView: ViewData|null, view: ViewData) { + const prevRenderNode = + prevView ? renderNode(prevView, prevView.def.lastRenderRootNode!) : elementData.renderElement; const parentNode = view.renderer.parentNode(prevRenderNode); const nextSibling = view.renderer.nextSibling(prevRenderNode); // Note: We can't check if `nextSibling` is present, as on WebWorkers it will always be! diff --git a/packages/core/src/zone/ng_zone.ts b/packages/core/src/zone/ng_zone.ts index bfca86e193850..a5387e4cdb5be 100644 --- a/packages/core/src/zone/ng_zone.ts +++ b/packages/core/src/zone/ng_zone.ts @@ -148,7 +148,9 @@ export class NgZone { forkInnerZoneWithAngularBehavior(self); } - static isInAngularZone(): boolean { return Zone.current.get('isAngularZone') === true; } + static isInAngularZone(): boolean { + return Zone.current.get('isAngularZone') === true; + } static assertInAngularZone(): void { if (!NgZone.isInAngularZone()) { @@ -274,36 +276,40 @@ function delayChangeDetectionForEvents(zone: NgZonePrivate) { } function forkInnerZoneWithAngularBehavior(zone: NgZonePrivate) { - const delayChangeDetectionForEventsDelegate = () => { delayChangeDetectionForEvents(zone); }; + const delayChangeDetectionForEventsDelegate = () => { + delayChangeDetectionForEvents(zone); + }; const maybeDelayChangeDetection = !!zone.shouldCoalesceEventChangeDetection && zone.nativeRequestAnimationFrame && delayChangeDetectionForEventsDelegate; zone._inner = zone._inner.fork({ name: 'angular', properties: {'isAngularZone': true, 'maybeDelayChangeDetection': maybeDelayChangeDetection}, - onInvokeTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task, applyThis: any, - applyArgs: any): any => { - try { - onEnter(zone); - return delegate.invokeTask(target, task, applyThis, applyArgs); - } finally { - if (maybeDelayChangeDetection && task.type === 'eventTask') { - maybeDelayChangeDetection(); - } - onLeave(zone); - } - }, + onInvokeTask: + (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task, applyThis: any, + applyArgs: any): any => { + try { + onEnter(zone); + return delegate.invokeTask(target, task, applyThis, applyArgs); + } finally { + if (maybeDelayChangeDetection && task.type === 'eventTask') { + maybeDelayChangeDetection(); + } + onLeave(zone); + } + }, - onInvoke: (delegate: ZoneDelegate, current: Zone, target: Zone, callback: Function, - applyThis: any, applyArgs?: any[], source?: string): any => { - try { - onEnter(zone); - return delegate.invoke(target, callback, applyThis, applyArgs, source); - } finally { - onLeave(zone); - } - }, + onInvoke: + (delegate: ZoneDelegate, current: Zone, target: Zone, callback: Function, applyThis: any, + applyArgs?: any[], source?: string): any => { + try { + onEnter(zone); + return delegate.invoke(target, callback, applyThis, applyArgs, source); + } finally { + onLeave(zone); + } + }, onHasTask: (delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) => { @@ -372,7 +378,9 @@ export class NoopNgZone implements NgZone { return fn.apply(applyThis, applyArgs); } - runOutsideAngular(fn: (...args: any[]) => any): any { return fn(); } + runOutsideAngular(fn: (...args: any[]) => any): any { + return fn(); + } runTask(fn: (...args: any[]) => any, applyThis?: any, applyArgs?: any, name?: string): any { return fn.apply(applyThis, applyArgs); diff --git a/packages/core/test/acceptance/bootstrap_spec.ts b/packages/core/test/acceptance/bootstrap_spec.ts index 91dd57d46b1fa..a2fc8ced6f4e3 100644 --- a/packages/core/test/acceptance/bootstrap_spec.ts +++ b/packages/core/test/acceptance/bootstrap_spec.ts @@ -6,18 +6,17 @@ * found in the LICENSE file at https://angular.io/license */ -import {COMPILER_OPTIONS, Component, NgModule, ViewEncapsulation, destroyPlatform} from '@angular/core'; +import {COMPILER_OPTIONS, Component, destroyPlatform, NgModule, ViewEncapsulation} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {onlyInIvy, withBody} from '@angular/private/testing'; describe('bootstrap', () => { - beforeEach(destroyPlatform); afterEach(destroyPlatform); it('should bootstrap using #id selector', - withBody('
before|
', async() => { + withBody('
before|
', async () => { try { const ngModuleRef = await platformBrowserDynamic().bootstrapModule(IdSelectorAppModule); expect(document.body.textContent).toEqual('before|works!'); @@ -28,7 +27,7 @@ describe('bootstrap', () => { })); it('should bootstrap using one of selectors from the list', - withBody('
before|
', async() => { + withBody('
before|
', async () => { try { const ngModuleRef = await platformBrowserDynamic().bootstrapModule(MultipleSelectorsAppModule); @@ -66,7 +65,7 @@ describe('bootstrap', () => { } it('should use ViewEncapsulation.Emulated as default', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); @@ -75,7 +74,7 @@ describe('bootstrap', () => { })); it('should allow setting defaultEncapsulation using bootstrap option', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule( @@ -86,7 +85,7 @@ describe('bootstrap', () => { })); it('should allow setting defaultEncapsulation using compiler option', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic([{ @@ -100,7 +99,7 @@ describe('bootstrap', () => { })); it('should prefer encapsulation on component over bootstrap option', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule({encapsulation: ViewEncapsulation.Emulated}); const ngModuleRef = await platformBrowserDynamic().bootstrapModule( @@ -110,7 +109,7 @@ describe('bootstrap', () => { })); it('should use preserveWhitespaces: false as default', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); @@ -119,7 +118,7 @@ describe('bootstrap', () => { })); it('should allow setting preserveWhitespaces using bootstrap option', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule( @@ -129,7 +128,7 @@ describe('bootstrap', () => { })); it('should allow setting preserveWhitespaces using compiler option', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = @@ -141,7 +140,7 @@ describe('bootstrap', () => { })); it('should prefer preserveWhitespaces on component over bootstrap option', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule({preserveWhitespaces: false}); const ngModuleRef = await platformBrowserDynamic().bootstrapModule( @@ -151,10 +150,12 @@ describe('bootstrap', () => { })); onlyInIvy('options cannot be changed in Ivy').describe('changing bootstrap options', () => { - beforeEach(() => { spyOn(console, 'error'); }); + beforeEach(() => { + spyOn(console, 'error'); + }); it('should log an error when changing defaultEncapsulation bootstrap options', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const platformRef = platformBrowserDynamic(); @@ -175,7 +176,7 @@ describe('bootstrap', () => { })); it('should log an error when changing preserveWhitespaces bootstrap options', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const platformRef = platformBrowserDynamic(); @@ -196,7 +197,7 @@ describe('bootstrap', () => { })); it('should log an error when changing defaultEncapsulation to its default', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const platformRef = platformBrowserDynamic(); @@ -215,7 +216,7 @@ describe('bootstrap', () => { })); it('should log an error when changing preserveWhitespaces to its default', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const platformRef = platformBrowserDynamic(); @@ -234,7 +235,7 @@ describe('bootstrap', () => { })); it('should not log an error when passing identical bootstrap options', - withBody('', async() => { + withBody('', async () => { const TestModule = createComponentAndModule(); const platformRef = platformBrowserDynamic(); diff --git a/packages/core/test/acceptance/change_detection_spec.ts b/packages/core/test/acceptance/change_detection_spec.ts index a5d6b41b2ef3a..9e9643ddbc917 100644 --- a/packages/core/test/acceptance/change_detection_spec.ts +++ b/packages/core/test/acceptance/change_detection_spec.ts @@ -16,16 +16,16 @@ import {ivyEnabled} from '@angular/private/testing'; import {BehaviorSubject} from 'rxjs'; describe('change detection', () => { - describe('embedded views', () => { - @Directive({selector: '[viewManipulation]', exportAs: 'vm'}) class ViewManipulation { constructor( private _tplRef: TemplateRef<{}>, public vcRef: ViewContainerRef, private _appRef: ApplicationRef) {} - insertIntoVcRef() { return this.vcRef.createEmbeddedView(this._tplRef); } + insertIntoVcRef() { + return this.vcRef.createEmbeddedView(this._tplRef); + } insertIntoAppRef(): EmbeddedViewRef<{}> { const viewRef = this._tplRef.createEmbeddedView({}); @@ -80,7 +80,9 @@ describe('change detection', () => { changeDetection: ChangeDetectionStrategy.OnPush }) class App { - increment(counter: 'componentView'|'embeddedView') { counters[counter]++; } + increment(counter: 'componentView'|'embeddedView') { + counters[counter]++; + } noop() {} } @@ -129,7 +131,9 @@ describe('change detection', () => { changeDetection: ChangeDetectionStrategy.OnPush }) class DynamicComp { - increment() { counter++; } + increment() { + counter++; + } noop() {} } @@ -170,13 +174,10 @@ describe('change detection', () => { expect(counter).toBe(3); }); - }); describe('markForCheck', () => { - it('should mark OnPush ancestor of dynamically created component views as dirty', () => { - @Component({ selector: `test-cmpt`, template: `{{counter}}|`, @@ -184,7 +185,7 @@ describe('change detection', () => { }) class TestCmpt { counter = 0; - @ViewChild('vc', {read: ViewContainerRef}) vcRef !: ViewContainerRef; + @ViewChild('vc', {read: ViewContainerRef}) vcRef!: ViewContainerRef; constructor(private _cfr: ComponentFactoryResolver) {} @@ -252,11 +253,13 @@ describe('change detection', () => { /** * @internal */ - private _input !: number; + private _input!: number; constructor(private cdr: ChangeDetectorRef) {} - get input() { return this._input; } + get input() { + return this._input; + } set input(value: number) { this._input = value; @@ -286,18 +289,19 @@ describe('change detection', () => { template: `{{ doCheckCount }} - {{ name }} ` }) class MyComponent implements DoCheck { - @Input() - name = 'Nancy'; + @Input() name = 'Nancy'; doCheckCount = 0; - ngDoCheck(): void { this.doCheckCount++; } + ngDoCheck(): void { + this.doCheckCount++; + } onClick() {} } @Component({selector: 'my-app', template: ''}) class MyApp { - @ViewChild(MyComponent) comp !: MyComponent; + @ViewChild(MyComponent) comp!: MyComponent; name: string = 'Nancy'; } @@ -369,7 +373,7 @@ describe('change detection', () => { expect(fixture.componentInstance.comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); - const button = fixture.nativeElement.querySelector('button') !; + const button = fixture.nativeElement.querySelector('button')!; button.click(); // No ticks should have been scheduled. @@ -389,7 +393,7 @@ describe('change detection', () => { template: '' }) class ButtonParent { - @ViewChild(MyComponent) comp !: MyComponent; + @ViewChild(MyComponent) comp!: MyComponent; noop() {} } @@ -415,16 +419,18 @@ describe('change detection', () => { changeDetection: ChangeDetectionStrategy.OnPush }) class ButtonParent implements DoCheck { - @ViewChild(MyComponent) comp !: MyComponent; + @ViewChild(MyComponent) comp!: MyComponent; noop() {} doCheckCount = 0; - ngDoCheck(): void { this.doCheckCount++; } + ngDoCheck(): void { + this.doCheckCount++; + } } @Component({selector: 'my-button-app', template: ''}) class MyButtonApp { - @ViewChild(ButtonParent) parent !: ButtonParent; + @ViewChild(ButtonParent) parent!: ButtonParent; } TestBed.configureTestingModule({declarations: [MyButtonApp, MyComponent, ButtonParent]}); @@ -456,7 +462,6 @@ describe('change detection', () => { expect(comp.doCheckCount).toEqual(2); expect(fixture.nativeElement.textContent.trim()).toEqual('3 - 2 - Nancy'); }); - }); describe('ChangeDetectorRef', () => { @@ -472,18 +477,22 @@ describe('change detection', () => { constructor(public cdr: ChangeDetectorRef) {} - ngDoCheck() { this.doCheckCount++; } + ngDoCheck() { + this.doCheckCount++; + } } @Component({selector: 'parent-comp', template: `{{ doCheckCount}} - `}) class ParentComp implements DoCheck { - @ViewChild(MyComp) myComp !: MyComp; + @ViewChild(MyComp) myComp!: MyComp; doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} - ngDoCheck() { this.doCheckCount++; } + ngDoCheck() { + this.doCheckCount++; + } } @Directive({selector: '[dir]'}) @@ -562,8 +571,8 @@ describe('change detection', () => { it('should check component view when called by directive on component node', () => { @Component({template: ''}) class MyApp { - @ViewChild(MyComp) myComp !: MyComp; - @ViewChild(Dir) dir !: Dir; + @ViewChild(MyComp) myComp!: MyComp; + @ViewChild(Dir) dir!: Dir; } TestBed.configureTestingModule({declarations: [MyComp, Dir, MyApp]}); @@ -580,8 +589,8 @@ describe('change detection', () => { it('should check host component when called by directive on element node', () => { @Component({template: '{{ value }}
'}) class MyApp { - @ViewChild(MyComp) myComp !: MyComp; - @ViewChild(Dir) dir !: Dir; + @ViewChild(MyComp) myComp!: MyComp; + @ViewChild(Dir) dir!: Dir; value = ''; } @@ -601,7 +610,7 @@ describe('change detection', () => { it('should check the host component when called from EmbeddedViewRef', () => { @Component({template: '{{ name }}
'}) class MyApp { - @ViewChild(Dir) dir !: Dir; + @ViewChild(Dir) dir!: Dir; showing = true; name = 'Amelia'; } @@ -642,21 +651,30 @@ describe('change detection', () => { @Component({template: ''}) class ParentComp { constructor(public cdr: ChangeDetectorRef) {} - triggerChangeDetection() { this.cdr.detectChanges(); } + triggerChangeDetection() { + this.cdr.detectChanges(); + } } @Component({template: '{{inp}}', selector: 'child-comp'}) class ChildComp { - @Input() - inp: any = ''; + @Input() inp: any = ''; count = 0; constructor(public parentComp: ParentComp) {} - ngOnInit() { this.check('OnInit'); } - ngAfterContentInit() { this.check('AfterContentInit'); } - ngAfterViewInit() { this.check('AfterViewInit'); } - ngOnChanges() { this.check('OnChanges'); } + ngOnInit() { + this.check('OnInit'); + } + ngAfterContentInit() { + this.check('AfterContentInit'); + } + ngAfterViewInit() { + this.check('AfterViewInit'); + } + ngOnChanges() { + this.check('OnChanges'); + } check(h: string) { if (h === hook) { @@ -704,8 +722,7 @@ describe('change detection', () => { ` }) class App { - @ViewChildren('ref') - ref !: QueryList; + @ViewChildren('ref') ref!: QueryList; visible = false; @@ -737,13 +754,14 @@ describe('change detection', () => { describe('dynamic views', () => { @Component({selector: 'structural-comp', template: '{{ value }}'}) class StructuralComp { - @Input() - tmp !: TemplateRef; + @Input() tmp!: TemplateRef; value = 'one'; constructor(public vcr: ViewContainerRef) {} - create() { return this.vcr.createEmbeddedView(this.tmp, {ctx: this}); } + create() { + return this.vcr.createEmbeddedView(this.tmp, {ctx: this}); + } } it('should support ViewRef.detectChanges()', () => { @@ -752,7 +770,7 @@ describe('change detection', () => { '{{ ctx.value }}' }) class App { - @ViewChild(StructuralComp) structuralComp !: StructuralComp; + @ViewChild(StructuralComp) structuralComp!: StructuralComp; } TestBed.configureTestingModule({declarations: [App, StructuralComp]}); @@ -781,7 +799,7 @@ describe('change detection', () => { template: 'Template text' }) class App { - @ViewChild(StructuralComp) structuralComp !: StructuralComp; + @ViewChild(StructuralComp) structuralComp!: StructuralComp; } TestBed.configureTestingModule({declarations: [App, StructuralComp]}); @@ -794,9 +812,7 @@ describe('change detection', () => { viewRef.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('oneTemplate text'); }); - }); - }); describe('attach/detach', () => { @@ -807,12 +823,14 @@ describe('change detection', () => { constructor(public cdr: ChangeDetectorRef) {} - ngDoCheck() { this.doCheckCount++; } + ngDoCheck() { + this.doCheckCount++; + } } @Component({template: ''}) class MyApp { - @ViewChild(DetachedComp) comp !: DetachedComp; + @ViewChild(DetachedComp) comp!: DetachedComp; constructor(public cdr: ChangeDetectorRef) {} } @@ -908,22 +926,20 @@ describe('change detection', () => { }); it('should detach OnPush components properly', () => { - @Component({ selector: 'on-push-comp', template: '{{ value }}', changeDetection: ChangeDetectionStrategy.OnPush }) class OnPushComp { - @Input() - value !: string; + @Input() value!: string; constructor(public cdr: ChangeDetectorRef) {} } @Component({template: ''}) class OnPushApp { - @ViewChild(OnPushComp) onPushComp !: OnPushComp; + @ViewChild(OnPushComp) onPushComp!: OnPushComp; value = ''; } @@ -946,7 +962,6 @@ describe('change detection', () => { fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); - }); describe('markForCheck()', () => { @@ -962,7 +977,9 @@ describe('change detection', () => { constructor(public cdr: ChangeDetectorRef) {} - ngDoCheck() { this.doCheckCount++; } + ngDoCheck() { + this.doCheckCount++; + } } @Component({ @@ -970,7 +987,7 @@ describe('change detection', () => { changeDetection: ChangeDetectionStrategy.OnPush }) class OnPushParent { - @ViewChild(OnPushComp) comp !: OnPushComp; + @ViewChild(OnPushComp) comp!: OnPushComp; value = 'one'; } @@ -1023,7 +1040,6 @@ describe('change detection', () => { fixture.componentInstance.comp.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two - one'); - }); it('should ensure OnPush components in embedded views are checked', () => { @@ -1032,7 +1048,7 @@ describe('change detection', () => { changeDetection: ChangeDetectionStrategy.OnPush }) class EmbeddedViewParent { - @ViewChild(OnPushComp) comp !: OnPushComp; + @ViewChild(OnPushComp) comp!: OnPushComp; value = 'one'; showing = true; } @@ -1112,13 +1128,21 @@ describe('change detection', () => { contentCheckCount = 0; viewCheckCount = 0; - ngDoCheck() { this.doCheckCount++; } + ngDoCheck() { + this.doCheckCount++; + } - ngAfterContentChecked() { this.contentCheckCount++; } + ngAfterContentChecked() { + this.contentCheckCount++; + } - ngAfterViewChecked() { this.viewCheckCount++; } + ngAfterViewChecked() { + this.viewCheckCount++; + } - constructor(public cdr: ChangeDetectorRef) { comp = this; } + constructor(public cdr: ChangeDetectorRef) { + comp = this; + } } @Component({template: '{{ value }} - '}) @@ -1131,7 +1155,9 @@ describe('change detection', () => { // Custom error handler that just rethrows all the errors from the // view, rather than logging them out. Used to keep our logs clean. class RethrowErrorHandler extends ErrorHandler { - handleError(error: any) { throw error; } + handleError(error: any) { + throw error; + } } it('should throw if bindings in current view have changed', () => { @@ -1141,7 +1167,9 @@ describe('change detection', () => { }); const fixture = TestBed.createComponent(NoChangesComp); - expect(() => { fixture.componentInstance.cdr.checkNoChanges(); }) + expect(() => { + fixture.componentInstance.cdr.checkNoChanges(); + }) .toThrowError( /ExpressionChangedAfterItHasBeenCheckedError: .+ Previous value: '.*undefined'. Current value: '.*1'/gi); }); @@ -1196,9 +1224,7 @@ describe('change detection', () => { expect(comp.contentCheckCount).toEqual(1); expect(comp.viewCheckCount).toEqual(1); }); - }); - }); describe('transplanted views', () => { @@ -1216,13 +1242,20 @@ describe('change detection', () => {
` }) - class InsertComp implements DoCheck, - AfterViewChecked { - get template(): TemplateRef { return declareComp.myTmpl; } + class InsertComp implements DoCheck, AfterViewChecked { + get template(): TemplateRef { + return declareComp.myTmpl; + } greeting: string = 'Hello'; - constructor(public changeDetectorRef: ChangeDetectorRef) { insertComp = this; } - ngDoCheck(): void { logValue = 'Insert'; } - ngAfterViewChecked(): void { logValue = null; } + constructor(public changeDetectorRef: ChangeDetectorRef) { + insertComp = this; + } + ngDoCheck(): void { + logValue = 'Insert'; + } + ngAfterViewChecked(): void { + logValue = null; + } } @Component({ @@ -1234,20 +1267,24 @@ describe('change detection', () => { ` }) - class DeclareComp implements DoCheck, - AfterViewChecked { - @ViewChild('myTmpl') - myTmpl !: TemplateRef; + class DeclareComp implements DoCheck, AfterViewChecked { + @ViewChild('myTmpl') myTmpl!: TemplateRef; name: string = 'world'; - constructor() { declareComp = this; } - ngDoCheck(): void { logValue = 'Declare'; } + constructor() { + declareComp = this; + } + ngDoCheck(): void { + logValue = 'Declare'; + } logName() { // This will log when the embedded view gets CD. The `logValue` will show if the CD was from // `Insert` or from `Declare` component. - log.push(logValue !); + log.push(logValue!); return this.name; } - ngAfterViewChecked(): void { logValue = null; } + ngAfterViewChecked(): void { + logValue = null; + } } @Component({ @@ -1259,15 +1296,17 @@ describe('change detection', () => { class AppComp { showDeclare: boolean = true; showInsert: boolean = true; - constructor() { appComp = this; } + constructor() { + appComp = this; + } } - let log !: string[]; - let logValue !: string | null; - let fixture !: ComponentFixture; - let appComp !: AppComp; - let insertComp !: InsertComp; - let declareComp !: DeclareComp; + let log!: string[]; + let logValue!: string|null; + let fixture!: ComponentFixture; + let appComp!: AppComp; + let insertComp!: InsertComp; + let declareComp!: DeclareComp; beforeEach(() => { TestBed.configureTestingModule({ @@ -1376,16 +1415,16 @@ describe('change detection', () => { class OnPushComp { text = 'initial'; - constructor(private _cdRef: ChangeDetectorRef){} + constructor(private _cdRef: ChangeDetectorRef) {} - [hookName]() { + [hookName]() { this._cdRef.markForCheck(); } } @Component({template: ``}) class TestApp { - @ViewChild(OnPushComp) onPushComp !: OnPushComp; + @ViewChild(OnPushComp) onPushComp!: OnPushComp; } TestBed.configureTestingModule( @@ -1419,16 +1458,16 @@ describe('change detection', () => { class OnPushComp { text = 'initial'; - constructor(private _cdRef: ChangeDetectorRef){} + constructor(private _cdRef: ChangeDetectorRef) {} - [hookName]() { + [hookName]() { this._cdRef.markForCheck(); } } @Component({template: ``}) class TestApp { - @ViewChild(OnPushComp) onPushComp !: OnPushComp; + @ViewChild(OnPushComp) onPushComp!: OnPushComp; } TestBed.configureTestingModule( @@ -1478,7 +1517,9 @@ describe('change detection', () => { return fixture; } - function initWithTemplate(template: string) { return initComponent({template}); } + function initWithTemplate(template: string) { + return initComponent({template}); + } function initWithHostBindings(bindings: {[key: string]: string}) { return initComponent({host: bindings}); } @@ -1612,6 +1653,6 @@ describe('change detection', () => { }); }); -function trim(text: string | null): string { +function trim(text: string|null): string { return text ? text.replace(/[\s\n]+/gm, ' ').trim() : ''; } diff --git a/packages/core/test/acceptance/common_integration_spec.ts b/packages/core/test/acceptance/common_integration_spec.ts index 14615fb8f6100..307d8da888e32 100644 --- a/packages/core/test/acceptance/common_integration_spec.ts +++ b/packages/core/test/acceptance/common_integration_spec.ts @@ -11,7 +11,6 @@ import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('@angular/common integration', () => { - describe('NgForOf', () => { @Directive({selector: '[dir]'}) class MyDirective { @@ -244,7 +243,9 @@ describe('@angular/common integration', () => { name = 'app'; events: string[] = []; - onClick(value: string, name: string) { this.events.push(value, name); } + onClick(value: string, name: string) { + this.events.push(value, name); + } } TestBed.configureTestingModule({declarations: [MultiLevelWithListenerComponent]}); @@ -485,7 +486,6 @@ describe('@angular/common integration', () => { }); describe('NgTemplateOutlet', () => { - it('should create and remove embedded views', () => { @Component({ selector: 'app-multi', diff --git a/packages/core/test/acceptance/component_spec.ts b/packages/core/test/acceptance/component_spec.ts index 352cb57ce841a..dfb34d294a4a6 100644 --- a/packages/core/test/acceptance/component_spec.ts +++ b/packages/core/test/acceptance/component_spec.ts @@ -28,7 +28,9 @@ describe('component', () => { providers: [{provide: testToken, useExisting: ParentWithOnDestroy}] }) class ParentWithOnDestroy { - ngOnDestroy() { destroyCalls++; } + ngOnDestroy() { + destroyCalls++; + } } @Component({selector: 'child', template: ''}) @@ -75,7 +77,7 @@ describe('component', () => { entryComponents: [OtherComponent] }) class TestComponent { - @ViewChild('vc', {read: ViewContainerRef, static: true}) vcref !: ViewContainerRef; + @ViewChild('vc', {read: ViewContainerRef, static: true}) vcref!: ViewContainerRef; constructor(private _cfr: ComponentFactoryResolver) {} @@ -152,7 +154,8 @@ describe('component', () => { expect(match).toBeDefined(); expect(match.length).toEqual(2); expect(html).toMatch( - `bar
`); + `bar
`); }); }); @@ -162,7 +165,9 @@ describe('component', () => { @Component({selector: 'comp-with-destroy', template: ``}) class ComponentWithOnDestroy implements OnDestroy { - ngOnDestroy() { wasOnDestroyCalled = true; } + ngOnDestroy() { + wasOnDestroyCalled = true; + } } // This test asserts that the view tree is set up correctly based on the knowledge that this @@ -244,7 +249,7 @@ describe('component', () => { encapsulation: ViewEncapsulation.Emulated, }) class Parent { - @ViewChild(Child) childInstance !: Child; + @ViewChild(Child) childInstance!: Child; constructor(public renderer: Renderer2) {} } @@ -266,7 +271,9 @@ describe('component', () => { }) class CompA { @Input() a: string = ''; - ngDoCheck() { log.push('CompA:ngDoCheck'); } + ngDoCheck() { + log.push('CompA:ngDoCheck'); + } } @Component({ @@ -275,7 +282,9 @@ describe('component', () => { }) class CompB { @Input() b: string = ''; - ngDoCheck() { log.push('CompB:ngDoCheck'); } + ngDoCheck() { + log.push('CompB:ngDoCheck'); + } } @Component({template: ``}) @@ -435,14 +444,14 @@ describe('component', () => { fixture.detectChanges(); // Create an instance of DynamicComponent and provide host element *reference* - let targetEl = document.getElementById('dynamic-comp-root-a') !; + let targetEl = document.getElementById('dynamic-comp-root-a')!; fixture.componentInstance.createDynamicComponent(targetEl); fixture.detectChanges(); expect(targetEl.innerHTML).not.toContain('Existing content in slot A'); expect(targetEl.innerHTML).toContain('DynamicComponent Content'); // Create an instance of DynamicComponent and provide host element *selector* - targetEl = document.getElementById('dynamic-comp-root-b') !; + targetEl = document.getElementById('dynamic-comp-root-b')!; fixture.componentInstance.createDynamicComponent('#dynamic-comp-root-b'); fixture.detectChanges(); expect(targetEl.innerHTML).not.toContain('Existing content in slot B'); @@ -453,7 +462,8 @@ describe('component', () => { () => runTestWithRenderer([{provide: RendererFactory2, useClass: DomRendererFactory2}])); onlyInIvy('Renderer3 is supported only in Ivy') - .it('with Renderer3', () => runTestWithRenderer( - [{provide: RendererFactory2, useValue: domRendererFactory3}])); + .it('with Renderer3', + () => + runTestWithRenderer([{provide: RendererFactory2, useValue: domRendererFactory3}])); }); }); diff --git a/packages/core/test/acceptance/content_spec.ts b/packages/core/test/acceptance/content_spec.ts index 9aef0532a49d7..d9116753c6386 100644 --- a/packages/core/test/acceptance/content_spec.ts +++ b/packages/core/test/acceptance/content_spec.ts @@ -14,7 +14,6 @@ import {By} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('projection', () => { - function getElementHtml(element: HTMLElement) { return element.innerHTML.replace(//g, '') .replace(/\sng-reflect-\S*="[^"]*"/g, ''); @@ -328,11 +327,13 @@ describe('projection', () => { @Directive({selector: '[trigger]'}) class Trigger { - @Input() trigger !: Comp; + @Input() trigger!: Comp; constructor(public vcr: ViewContainerRef) {} - open() { this.vcr.createEmbeddedView(this.trigger.template); } + open() { + this.vcr.createEmbeddedView(this.trigger.template); + } } @Component({ @@ -861,7 +862,6 @@ describe('projection', () => { expect(getElementHtml(fixture.nativeElement)) .toEqual('Has title'); - }); it('should match selectors against projected containers', () => { @@ -934,7 +934,9 @@ describe('projection', () => { it('should project content if the change detector has been detached', () => { @Component({selector: 'my-comp', template: ''}) class MyComp { - constructor(changeDetectorRef: ChangeDetectorRef) { changeDetectorRef.detach(); } + constructor(changeDetectorRef: ChangeDetectorRef) { + changeDetectorRef.detach(); + } } @Component({ @@ -1108,7 +1110,9 @@ describe('projection', () => { @Directive({selector: 'div'}) class DivDirective { - constructor() { divDirectives++; } + constructor() { + divDirectives++; + } } @Component({ @@ -1135,7 +1139,9 @@ describe('projection', () => { @Directive({selector: '[x]'}) class XDirective { - constructor() { xDirectives++; } + constructor() { + xDirectives++; + } } @Component({ @@ -1162,7 +1168,9 @@ describe('projection', () => { @Directive({selector: '.x'}) class XDirective { - constructor() { xDirectives++; } + constructor() { + xDirectives++; + } } @Component({ @@ -1199,7 +1207,9 @@ describe('projection', () => { {id: 2, name: 'two'}, {id: 3, name: 'three'}, ]; - getItemId(item: {id: number}) { return item.id; } + getItemId(item: {id: number}) { + return item.id; + } } TestBed.configureTestingModule({declarations: [SelectedNgContentComp, SelectorMainComp]}); @@ -1265,7 +1275,9 @@ describe('projection', () => { @Directive({selector: '[x]'}) class XDirective { - constructor() { xDirectives++; } + constructor() { + xDirectives++; + } } @Component({ @@ -1293,7 +1305,9 @@ describe('projection', () => { @Directive({selector: '.x'}) class XDirective { - constructor() { xDirectives++; } + constructor() { + xDirectives++; + } } @Component({ diff --git a/packages/core/test/acceptance/copy_definition_feature_spec.ts b/packages/core/test/acceptance/copy_definition_feature_spec.ts index ea4c220c70179..c200ad6f41e4f 100644 --- a/packages/core/test/acceptance/copy_definition_feature_spec.ts +++ b/packages/core/test/acceptance/copy_definition_feature_spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Component, NgModule, ɵɵCopyDefinitionFeature as CopyDefinitionFeature, ɵɵInheritDefinitionFeature as InheritDefinitionFeature, ɵɵdefineComponent as defineComponent} from '@angular/core'; +import {Component, NgModule, ɵɵCopyDefinitionFeature as CopyDefinitionFeature, ɵɵdefineComponent as defineComponent, ɵɵInheritDefinitionFeature as InheritDefinitionFeature} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {onlyInIvy} from '@angular/private/testing'; @@ -14,20 +14,22 @@ describe('Ivy CopyDefinitionFeature', () => { onlyInIvy('this feature is not required in View Engine') .it('should copy the template function of a component definition from parent to child', () => { - // It would be nice if the base component could be JIT compiled. However, this creates // a getter for ɵcmp which precludes adding a static definition of that field for the // child class. // TODO(alxhub): see if there's a cleaner way to do this. class BaseComponent { - name !: string; + name!: string; static ɵcmp = defineComponent({ type: BaseComponent, selectors: [['some-cmp']], decls: 0, vars: 0, inputs: {name: 'name'}, - template: function BaseComponent_Template(rf, ctx) { ctx.rendered = true; }, + template: + function BaseComponent_Template(rf, ctx) { + ctx.rendered = true; + }, encapsulation: 2 }); static ɵfac = function BaseComponent_Factory(t: any) { diff --git a/packages/core/test/acceptance/debug_spec.ts b/packages/core/test/acceptance/debug_spec.ts index d4bfa91531d79..5cdb0ea011e47 100644 --- a/packages/core/test/acceptance/debug_spec.ts +++ b/packages/core/test/acceptance/debug_spec.ts @@ -14,9 +14,7 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; import {onlyInIvy} from '@angular/private/testing'; describe('Debug Representation', () => { - onlyInIvy('Ivy specific').it('should generate a human readable version', () => { - @Component({selector: 'my-comp', template: '
Hello World
'}) class MyComponent { } @@ -25,11 +23,11 @@ describe('Debug Representation', () => { const fixture = TestBed.createComponent(MyComponent); fixture.detectChanges(); - const hostView = toDebug(getLContext(fixture.componentInstance) !.lView); + const hostView = toDebug(getLContext(fixture.componentInstance)!.lView); expect(hostView.host).toEqual(null); const myCompView = hostView.childViews[0] as LViewDebug; expect(myCompView.host).toContain('
Hello World
'); - expect(myCompView.nodes ![0].html).toEqual('
'); - expect(myCompView.nodes ![0].nodes ![0].html).toEqual('Hello World'); + expect(myCompView.nodes![0].html).toEqual('
'); + expect(myCompView.nodes![0].nodes![0].html).toEqual('Hello World'); }); }); diff --git a/packages/core/test/acceptance/di_spec.ts b/packages/core/test/acceptance/di_spec.ts index 23d319de03617..31e7c1a1dd1a1 100644 --- a/packages/core/test/acceptance/di_spec.ts +++ b/packages/core/test/acceptance/di_spec.ts @@ -7,7 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import {Attribute, ChangeDetectorRef, Component, ComponentFactoryResolver, ComponentRef, Directive, ElementRef, EventEmitter, Host, HostBinding, INJECTOR, Inject, Injectable, InjectionToken, Injector, Input, LOCALE_ID, ModuleWithProviders, NgModule, NgZone, Optional, Output, Pipe, PipeTransform, Self, SkipSelf, TemplateRef, ViewChild, ViewContainerRef, forwardRef, ɵDEFAULT_LOCALE_ID as DEFAULT_LOCALE_ID} from '@angular/core'; +import {Attribute, ChangeDetectorRef, Component, ComponentFactoryResolver, ComponentRef, Directive, ElementRef, EventEmitter, forwardRef, Host, HostBinding, Inject, Injectable, InjectionToken, INJECTOR, Injector, Input, LOCALE_ID, ModuleWithProviders, NgModule, NgZone, Optional, Output, Pipe, PipeTransform, Self, SkipSelf, TemplateRef, ViewChild, ViewContainerRef, ɵDEFAULT_LOCALE_ID as DEFAULT_LOCALE_ID} from '@angular/core'; import {ɵINJECTOR_SCOPE} from '@angular/core/src/core'; import {ViewRef} from '@angular/core/src/render3/view_ref'; import {TestBed} from '@angular/core/testing'; @@ -60,14 +60,15 @@ describe('di', () => { }); describe('directive injection', () => { - let log: string[] = []; @Directive({selector: '[dirB]', exportAs: 'dirB'}) class DirectiveB { @Input() value = 'DirB'; - constructor() { log.push(this.value); } + constructor() { + log.push(this.value); + } } beforeEach(() => log = []); @@ -82,7 +83,9 @@ describe('di', () => { class DirectiveC { value: string; - constructor(dirA: DirectiveA, dirB: DirectiveB) { this.value = dirA.value + dirB.value; } + constructor(dirA: DirectiveA, dirB: DirectiveB) { + this.value = dirA.value + dirB.value; + } } @Component({ @@ -108,7 +111,9 @@ describe('di', () => { class DirectiveA { value = 'dirA'; - constructor(dirB: DirectiveB) { log.push(`DirA (dep: ${dirB.value})`); } + constructor(dirB: DirectiveB) { + log.push(`DirA (dep: ${dirB.value})`); + } } @Component({template: '
'}) @@ -127,7 +132,9 @@ describe('di', () => { class DirectiveA { value = 'dirA'; - constructor(dirB: DirectiveB) { log.push(`DirA (dep: ${dirB.value})`); } + constructor(dirB: DirectiveB) { + log.push(`DirA (dep: ${dirB.value})`); + } } // - dirB is know to the node injectors @@ -150,7 +157,9 @@ describe('di', () => { it('should instantiate injected directives before components', () => { @Component({selector: 'my-comp', template: ''}) class MyComp { - constructor(dirB: DirectiveB) { log.push(`Comp (dep: ${dirB.value})`); } + constructor(dirB: DirectiveB) { + log.push(`Comp (dep: ${dirB.value})`); + } } @Component({template: ''}) @@ -167,7 +176,9 @@ describe('di', () => { it('should inject directives in the correct order in a for loop', () => { @Directive({selector: '[dirA]'}) class DirectiveA { - constructor(dir: DirectiveB) { log.push(`DirA (dep: ${dir.value})`); } + constructor(dir: DirectiveB) { + log.push(`DirA (dep: ${dir.value})`); + } } @Component({template: '
'}) @@ -188,14 +199,18 @@ describe('di', () => { class DirectiveA { value = 'DirA'; - constructor() { log.push(this.value); } + constructor() { + log.push(this.value); + } } @Directive({selector: '[dirC]'}) class DirectiveC { value = 'DirC'; - constructor() { log.push(this.value); } + constructor() { + log.push(this.value); + } } @Directive({selector: '[dirB]'}) @@ -221,26 +236,34 @@ describe('di', () => { class DirectiveC { value = 'DirC'; - constructor(dirB: DirectiveB) { log.push(`DirC (dep: ${dirB.value})`); } + constructor(dirB: DirectiveB) { + log.push(`DirC (dep: ${dirB.value})`); + } } @Directive({selector: '[dirA]'}) class DirectiveA { value = 'DirA'; - constructor(dirC: DirectiveC) { log.push(`DirA (dep: ${dirC.value})`); } + constructor(dirC: DirectiveC) { + log.push(`DirA (dep: ${dirC.value})`); + } } @Directive({selector: '[dirD]'}) class DirectiveD { value = 'DirD'; - constructor(dirA: DirectiveA) { log.push(`DirD (dep: ${dirA.value})`); } + constructor(dirA: DirectiveA) { + log.push(`DirD (dep: ${dirA.value})`); + } } @Component({selector: 'my-comp', template: ''}) class MyComp { - constructor(dirD: DirectiveD) { log.push(`Comp (dep: ${dirD.value})`); } + constructor(dirD: DirectiveD) { + log.push(`Comp (dep: ${dirD.value})`); + } } @Component({template: ''}) @@ -291,7 +314,9 @@ describe('di', () => { @Directive({selector: '[dirA]'}) class DirectiveA { - constructor(dirB: DirectiveB) { log.push(`DirA (dep: DirB - ${dirB.count})`); } + constructor(dirB: DirectiveB) { + log.push(`DirA (dep: DirB - ${dirB.count})`); + } } @Component({selector: 'my-comp', template: '
'}) @@ -310,7 +335,6 @@ describe('di', () => { }); describe('dependencies in parent views', () => { - @Directive({selector: '[dirA]', exportAs: 'dirA'}) class DirectiveA { injector: Injector; @@ -385,11 +409,13 @@ describe('di', () => { it('should find dependencies in declaration tree of ng-template (not insertion tree)', () => { @Directive({selector: '[structuralDir]'}) class StructuralDirective { - @Input() tmp !: TemplateRef; + @Input() tmp!: TemplateRef; constructor(public vcr: ViewContainerRef) {} - create() { this.vcr.createEmbeddedView(this.tmp); } + create() { + this.vcr.createEmbeddedView(this.tmp); + } } @Component({ @@ -405,7 +431,7 @@ describe('di', () => {
` }) class MyComp { - @ViewChild(StructuralDirective) structuralDir !: StructuralDirective; + @ViewChild(StructuralDirective) structuralDir!: StructuralDirective; } TestBed.configureTestingModule( @@ -449,8 +475,8 @@ describe('di', () => {
` }) class MyApp { - @ViewChild(HostBindingDirective) hostBindingDir !: HostBindingDirective; - @ViewChild(DirectiveA) dirA !: DirectiveA; + @ViewChild(HostBindingDirective) hostBindingDir!: HostBindingDirective; + @ViewChild(DirectiveA) dirA!: DirectiveA; } TestBed.configureTestingModule( @@ -501,15 +527,19 @@ describe('di', () => { }) class MyApp { @ViewChild('childOrigin', {read: ViewContainerRef, static: true}) - childOrigin !: ViewContainerRef; + childOrigin!: ViewContainerRef; @ViewChild('childOriginWithDirB', {read: ViewContainerRef, static: true}) - childOriginWithDirB !: ViewContainerRef; + childOriginWithDirB!: ViewContainerRef; childFactory = this.resolver.resolveComponentFactory(Child); constructor(readonly resolver: ComponentFactoryResolver, readonly injector: Injector) {} - addChild() { return this.childOrigin.createComponent(this.childFactory); } - addChildWithDirB() { return this.childOriginWithDirB.createComponent(this.childFactory); } + addChild() { + return this.childOrigin.createComponent(this.childFactory); + } + addChildWithDirB() { + return this.childOriginWithDirB.createComponent(this.childFactory); + } } const fixture = @@ -604,24 +634,21 @@ describe('di', () => { }); describe('flags', () => { - @Directive({selector: '[dirB]'}) class DirectiveB { @Input('dirB') value = ''; } describe('Optional', () => { - @Directive({selector: '[dirA]'}) class DirectiveA { constructor(@Optional() public dirB: DirectiveB) {} } it('should not throw if dependency is @Optional (module injector)', () => { - @Component({template: '
'}) class MyComp { - @ViewChild(DirectiveA) dirA !: DirectiveA; + @ViewChild(DirectiveA) dirA!: DirectiveA; } TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]}); @@ -633,7 +660,6 @@ describe('di', () => { }); it('should return null if @Optional dependency has @Self flag', () => { - @Directive({selector: '[dirC]'}) class DirectiveC { constructor(@Optional() @Self() public dirB: DirectiveB) {} @@ -641,7 +667,7 @@ describe('di', () => { @Component({template: '
'}) class MyComp { - @ViewChild(DirectiveC) dirC !: DirectiveC; + @ViewChild(DirectiveC) dirC!: DirectiveC; } TestBed.configureTestingModule({declarations: [DirectiveC, MyComp]}); @@ -653,7 +679,6 @@ describe('di', () => { }); it('should not throw if dependency is @Optional but defined elsewhere', () => { - @Directive({selector: '[dirC]'}) class DirectiveC { constructor(@Optional() public dirB: DirectiveB) {} @@ -661,7 +686,7 @@ describe('di', () => { @Component({template: '
'}) class MyComp { - @ViewChild(DirectiveC) dirC !: DirectiveC; + @ViewChild(DirectiveC) dirC!: DirectiveC; } TestBed.configureTestingModule({declarations: [DirectiveB, DirectiveC, MyComp]}); @@ -674,7 +699,6 @@ describe('di', () => { }); it('should skip the current node with @SkipSelf', () => { - @Directive({selector: '[dirA]'}) class DirectiveA { constructor(@SkipSelf() public dirB: DirectiveB) {} @@ -682,12 +706,12 @@ describe('di', () => { @Component({selector: 'my-comp', template: '
'}) class MyComp { - @ViewChild(DirectiveA) dirA !: DirectiveA; + @ViewChild(DirectiveA) dirA!: DirectiveA; } @Component({template: ''}) class MyApp { - @ViewChild(MyComp) myComp !: MyComp; + @ViewChild(MyComp) myComp!: MyComp; } TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]}); @@ -700,7 +724,6 @@ describe('di', () => { onlyInIvy('Ivy has different error message when dependency is not found') .it('should check only the current node with @Self', () => { - @Directive({selector: '[dirA]'}) class DirectiveA { constructor(@Self() public dirB: DirectiveB) {} @@ -732,12 +755,12 @@ describe('di', () => { viewProviders: [{provide: String, useValue: 'Foo'}] }) class MyComp { - @ViewChild(DirectiveString) dirString !: DirectiveString; + @ViewChild(DirectiveString) dirString!: DirectiveString; } @Component({template: ''}) class MyApp { - @ViewChild(MyComp) myComp !: MyComp; + @ViewChild(MyComp) myComp!: MyComp; } TestBed.configureTestingModule({declarations: [DirectiveString, MyComp, MyApp]}); @@ -756,12 +779,12 @@ describe('di', () => { @Component({selector: 'my-comp', template: '
'}) class MyComp { - @ViewChild(DirectiveComp) dirComp !: DirectiveComp; + @ViewChild(DirectiveComp) dirComp!: DirectiveComp; } @Component({template: ''}) class MyApp { - @ViewChild(MyComp) myComp !: MyComp; + @ViewChild(MyComp) myComp!: MyComp; } TestBed.configureTestingModule({declarations: [DirectiveComp, MyComp, MyApp]}); @@ -820,7 +843,7 @@ describe('di', () => { @Component({template: ''}) class MyApp { - @ViewChild(MyComp) myComp !: MyComp; + @ViewChild(MyComp) myComp!: MyComp; } TestBed.configureTestingModule( @@ -837,8 +860,8 @@ describe('di', () => { @Component({template: '
'}) class MyApp { showing = false; - @ViewChild(DirectiveA) dirA !: DirectiveA; - @ViewChild(DirectiveB) dirB !: DirectiveB; + @ViewChild(DirectiveA) dirA!: DirectiveA; + @ViewChild(DirectiveB) dirB!: DirectiveB; } TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyApp]}); @@ -885,7 +908,9 @@ describe('di', () => { providers: [{provide: ControlContainer, useExisting: GroupDirective}] }) class GroupDirective { - constructor() { controlContainers.push(this); } + constructor() { + controlContainers.push(this); + } } @Directive({selector: '[control]'}) @@ -919,7 +944,7 @@ describe('di', () => { const fixture = TestBed.createComponent(MyApp); expect(fixture.nativeElement.innerHTML) .toBe('
'); - expect(controlContainers).toEqual([injectedControlContainer !]); + expect(controlContainers).toEqual([injectedControlContainer!]); }); }); }); @@ -958,7 +983,6 @@ describe('di', () => { }); describe('service injection', () => { - it('should create instance even when no injector present', () => { @Injectable({providedIn: 'root'}) class MyService { @@ -1063,7 +1087,6 @@ describe('di', () => { expect(fixture.componentInstance.myService instanceof MyService).toBe(true); expect(fixture.componentInstance.myOtherService instanceof MyOtherService).toBe(true); }); - }); describe('service injection with useClass', () => { @@ -1075,7 +1098,9 @@ describe('di', () => { @Injectable({providedIn: 'root'}) class BarService { constructor(public dep: BarServiceDep) {} - getMessage() { return 'bar'; } + getMessage() { + return 'bar'; + } } @Injectable({providedIn: 'root'}) @@ -1086,7 +1111,9 @@ describe('di', () => { @Injectable({providedIn: 'root', useClass: BarService}) class FooService { constructor(public dep: FooServiceDep) {} - getMessage() { return 'foo'; } + getMessage() { + return 'foo'; + } } it('should use @Injectable useClass config when token is not provided', () => { @@ -1094,18 +1121,20 @@ describe('di', () => { @Component({template: ''}) class App { - constructor(service: FooService) { provider = service; } + constructor(service: FooService) { + provider = service; + } } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(provider !.getMessage()).toBe('bar'); + expect(provider!.getMessage()).toBe('bar'); // ViewEngine incorrectly uses the original class DI config, instead of the one from useClass. if (ivyEnabled) { - expect(provider !.dep.name).toBe('BarServiceDep'); + expect(provider!.dep.name).toBe('BarServiceDep'); } }); @@ -1115,7 +1144,9 @@ describe('di', () => { @Component({template: ''}) class App { - constructor(service: FooService) { provider = service; } + constructor(service: FooService) { + provider = service; + } } TestBed.configureTestingModule( @@ -1123,7 +1154,7 @@ describe('di', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(provider !.getMessage()).toBe('foo'); + expect(provider!.getMessage()).toBe('foo'); }); @@ -1144,13 +1175,13 @@ describe('di', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(directProvider !.getMessage()).toBe('bar'); - expect(overriddenProvider !.getMessage()).toBe('foo'); + expect(directProvider!.getMessage()).toBe('bar'); + expect(overriddenProvider!.getMessage()).toBe('foo'); // ViewEngine incorrectly uses the original class DI config, instead of the one from useClass. if (ivyEnabled) { - expect(directProvider !.dep.name).toBe('BarServiceDep'); - expect(overriddenProvider !.dep.name).toBe('FooServiceDep'); + expect(directProvider!.dep.name).toBe('BarServiceDep'); + expect(overriddenProvider!.dep.name).toBe('FooServiceDep'); } }); @@ -1160,20 +1191,21 @@ describe('di', () => { @Component({template: ''}) class App { - constructor(service: FooService) { provider = service; } + constructor(service: FooService) { + provider = service; + } } TestBed.configureTestingModule({declarations: [App], providers: [FooService]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(provider !.getMessage()).toBe('foo'); - expect(provider !.dep.name).toBe('FooServiceDep'); + expect(provider!.getMessage()).toBe('foo'); + expect(provider!.dep.name).toBe('FooServiceDep'); }); }); describe('inject', () => { - it('should inject from parent view', () => { @Directive({selector: '[parentDir]'}) class ParentDirective { @@ -1182,7 +1214,9 @@ describe('di', () => { @Directive({selector: '[childDir]', exportAs: 'childDir'}) class ChildDirective { value: string; - constructor(public parent: ParentDirective) { this.value = parent.constructor.name; } + constructor(public parent: ParentDirective) { + this.value = parent.constructor.name; + } } @Directive({selector: '[child2Dir]', exportAs: 'child2Dir'}) @@ -1214,9 +1248,7 @@ describe('di', () => { }); describe('Special tokens', () => { - describe('Injector', () => { - it('should inject the injector', () => { @Directive({selector: '[injectorDir]'}) class InjectorDir { @@ -1230,8 +1262,8 @@ describe('di', () => { @Component({template: '
'}) class MyComp { - @ViewChild(InjectorDir) injectorDir !: InjectorDir; - @ViewChild(OtherInjectorDir) otherInjectorDir !: OtherInjectorDir; + @ViewChild(InjectorDir) injectorDir!: InjectorDir; + @ViewChild(OtherInjectorDir) otherInjectorDir!: OtherInjectorDir; } TestBed.configureTestingModule({declarations: [InjectorDir, OtherInjectorDir, MyComp]}); @@ -1256,7 +1288,7 @@ describe('di', () => { @Component({template: '
'}) class MyComp { - @ViewChild(InjectorDir) injectorDir !: InjectorDir; + @ViewChild(InjectorDir) injectorDir!: InjectorDir; } TestBed.configureTestingModule({declarations: [InjectorDir, MyComp]}); @@ -1273,7 +1305,6 @@ describe('di', () => { }); describe('ElementRef', () => { - it('should create directive with ElementRef dependencies', () => { @Directive({selector: '[dir]'}) class MyDir { @@ -1293,8 +1324,8 @@ describe('di', () => { @Component({template: '
'}) class MyComp { - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyDir, MyOtherDir, MyComp]}); @@ -1325,7 +1356,7 @@ describe('di', () => { @Component({template: ''}) class MyComp { - @ViewChild(MyDir) directive !: MyDir; + @ViewChild(MyDir) directive!: MyDir; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); @@ -1346,7 +1377,9 @@ describe('di', () => { constructor(protected zone: NgZone) { this.subject = new BehaviorSubject(1); // trigger change detection - zone.run(() => { this.subject.next(2); }); + zone.run(() => { + this.subject.next(2); + }); } } @@ -1360,7 +1393,7 @@ describe('di', () => { template: `
`, }) class ChildComp { - @ViewChild(DirectiveA) directive !: DirectiveA; + @ViewChild(DirectiveA) directive!: DirectiveA; } @Component({ @@ -1368,7 +1401,7 @@ describe('di', () => { template: '...', }) class RootComp { - public childCompRef !: ComponentRef; + public childCompRef!: ComponentRef; constructor( public factoryResolver: ComponentFactoryResolver, public vcr: ViewContainerRef) {} @@ -1404,7 +1437,6 @@ describe('di', () => { }); describe('TemplateRef', () => { - @Directive({selector: '[dir]', exportAs: 'dir'}) class MyDir { value: string; @@ -1426,8 +1458,8 @@ describe('di', () => { template: '' }) class MyComp { - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyDir, MyOtherDir, MyComp]}); @@ -1470,7 +1502,7 @@ describe('di', () => { } @Component({template: '
'}) class MyComp { - @ViewChild(OptionalDir) directive !: OptionalDir; + @ViewChild(OptionalDir) directive!: OptionalDir; } TestBed.configureTestingModule({declarations: [OptionalDir, MyComp]}); @@ -1499,8 +1531,8 @@ describe('di', () => { } @Component({template: '
'}) class MyComp { - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyDir, MyOtherDir, MyComp]}); @@ -1524,12 +1556,13 @@ describe('di', () => { template: `Test`, }) class Root { - @ViewChild(TemplateRef, {static: true}) - tmpl !: TemplateRef; + @ViewChild(TemplateRef, {static: true}) tmpl!: TemplateRef; constructor(public vcr: ViewContainerRef, public vcr2: ViewContainerRef) {} - ngOnInit(): void { this.vcr.createEmbeddedView(this.tmpl); } + ngOnInit(): void { + this.vcr.createEmbeddedView(this.tmpl); + } } TestBed.configureTestingModule({ @@ -1551,11 +1584,12 @@ describe('di', () => { }); describe('ChangeDetectorRef', () => { - @Directive({selector: '[dir]', exportAs: 'dir'}) class MyDir { value: string; - constructor(public cdr: ChangeDetectorRef) { this.value = (cdr.constructor as any).name; } + constructor(public cdr: ChangeDetectorRef) { + this.value = (cdr.constructor as any).name; + } } @Directive({selector: '[otherDir]', exportAs: 'otherDir'}) class MyOtherDir { @@ -1571,9 +1605,13 @@ describe('di', () => { @Pipe({name: 'pipe'}) class MyPipe implements PipeTransform { - constructor(public cdr: ChangeDetectorRef) { pipeInstance = this; } + constructor(public cdr: ChangeDetectorRef) { + pipeInstance = this; + } - transform(value: any): any { return value; } + transform(value: any): any { + return value; + } } @Component({ @@ -1589,29 +1627,29 @@ describe('di', () => { TestBed.configureTestingModule({declarations: [MyApp, MyPipe], imports: [CommonModule]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); - expect((pipeInstance !.cdr as ViewRef).context).toBe(fixture.componentInstance); + expect((pipeInstance!.cdr as ViewRef).context).toBe(fixture.componentInstance); }); it('should inject current component ChangeDetectorRef into directives on the same node as components', () => { @Component({selector: 'my-app', template: ''}) class MyApp { - @ViewChild(MyComp) component !: MyComp; - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyComp) component!: MyComp; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyApp, MyComp, MyDir, MyOtherDir]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const app = fixture.componentInstance; const comp = fixture.componentInstance.component; - expect((comp !.cdr as ViewRef).context).toBe(comp); + expect((comp!.cdr as ViewRef).context).toBe(comp); // ChangeDetectorRef is the token, ViewRef has historically been the constructor expect(app.directive.value).toContain('ViewRef'); // Each ChangeDetectorRef instance should be unique - expect(app.directive !.cdr).not.toBe(comp !.cdr); - expect(app.directive !.cdr).not.toBe(app.otherDirective !.cdr); + expect(app.directive!.cdr).not.toBe(comp!.cdr); + expect(app.directive!.cdr).not.toBe(app.otherDirective!.cdr); }); it('should inject host component ChangeDetectorRef into directives on normal elements', @@ -1619,20 +1657,20 @@ describe('di', () => { @Component({selector: 'my-comp', template: '
'}) class MyComp { constructor(public cdr: ChangeDetectorRef) {} - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyOtherDir]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const comp = fixture.componentInstance; - expect((comp !.cdr as ViewRef).context).toBe(comp); + expect((comp!.cdr as ViewRef).context).toBe(comp); // ChangeDetectorRef is the token, ViewRef has historically been the constructor expect(comp.directive.value).toContain('ViewRef'); // Each ChangeDetectorRef instance should be unique - expect(comp.directive !.cdr).not.toBe(comp.cdr); - expect(comp.directive !.cdr).not.toBe(comp.otherDirective !.cdr); + expect(comp.directive!.cdr).not.toBe(comp.cdr); + expect(comp.directive!.cdr).not.toBe(comp.otherDirective!.cdr); }); it('should inject host component ChangeDetectorRef into directives in a component\'s ContentChildren', @@ -1646,22 +1684,22 @@ describe('di', () => { }) class MyApp { constructor(public cdr: ChangeDetectorRef) {} - @ViewChild(MyComp) component !: MyComp; - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyComp) component!: MyComp; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyApp, MyComp, MyDir, MyOtherDir]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const app = fixture.componentInstance; - expect((app !.cdr as ViewRef).context).toBe(app); + expect((app!.cdr as ViewRef).context).toBe(app); const comp = fixture.componentInstance.component; // ChangeDetectorRef is the token, ViewRef has historically been the constructor expect(app.directive.value).toContain('ViewRef'); // Each ChangeDetectorRef instance should be unique - expect(app.directive !.cdr).not.toBe(comp.cdr); - expect(app.directive !.cdr).not.toBe(app.otherDirective !.cdr); + expect(app.directive!.cdr).not.toBe(comp.cdr); + expect(app.directive!.cdr).not.toBe(app.otherDirective!.cdr); }); it('should inject host component ChangeDetectorRef into directives in embedded views', () => { @@ -1674,21 +1712,21 @@ describe('di', () => { class MyComp { showing = true; constructor(public cdr: ChangeDetectorRef) {} - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyOtherDir]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const comp = fixture.componentInstance; - expect((comp !.cdr as ViewRef).context).toBe(comp); + expect((comp!.cdr as ViewRef).context).toBe(comp); // ChangeDetectorRef is the token, ViewRef has historically been the constructor expect(comp.directive.value).toContain('ViewRef'); // Each ChangeDetectorRef instance should be unique - expect(comp.directive !.cdr).not.toBe(comp.cdr); - expect(comp.directive !.cdr).not.toBe(comp.otherDirective !.cdr); + expect(comp.directive!.cdr).not.toBe(comp.cdr); + expect(comp.directive!.cdr).not.toBe(comp.otherDirective!.cdr); }); it('should inject host component ChangeDetectorRef into directives on containers', () => { @@ -1697,21 +1735,21 @@ describe('di', () => { class MyComp { showing = true; constructor(public cdr: ChangeDetectorRef) {} - @ViewChild(MyDir) directive !: MyDir; - @ViewChild(MyOtherDir) otherDirective !: MyOtherDir; + @ViewChild(MyDir) directive!: MyDir; + @ViewChild(MyOtherDir) otherDirective!: MyOtherDir; } TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyOtherDir]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const comp = fixture.componentInstance; - expect((comp !.cdr as ViewRef).context).toBe(comp); + expect((comp!.cdr as ViewRef).context).toBe(comp); // ChangeDetectorRef is the token, ViewRef has historically been the constructor expect(comp.directive.value).toContain('ViewRef'); // Each ChangeDetectorRef instance should be unique - expect(comp.directive !.cdr).not.toBe(comp.cdr); - expect(comp.directive !.cdr).not.toBe(comp.otherDirective !.cdr); + expect(comp.directive!.cdr).not.toBe(comp.cdr); + expect(comp.directive!.cdr).not.toBe(comp.otherDirective!.cdr); }); it('should inject host component ChangeDetectorRef into directives on ng-container', () => { @@ -1719,7 +1757,9 @@ describe('di', () => { @Directive({selector: '[getCDR]'}) class MyDirective { - constructor(public cdr: ChangeDetectorRef) { dirInstance = this; } + constructor(public cdr: ChangeDetectorRef) { + dirInstance = this; + } } @Component({ @@ -1733,7 +1773,7 @@ describe('di', () => { TestBed.configureTestingModule({declarations: [MyApp, MyDirective]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); - expect((dirInstance !.cdr as ViewRef).context).toBe(fixture.componentInstance); + expect((dirInstance!.cdr as ViewRef).context).toBe(fixture.componentInstance); }); }); }); @@ -1747,7 +1787,7 @@ describe('di', () => { @Component({template: '
'}) class MyComp { - @ViewChild(InjectorDir) injectorDirInstance !: InjectorDir; + @ViewChild(InjectorDir) injectorDirInstance!: InjectorDir; } TestBed.configureTestingModule({declarations: [InjectorDir, MyComp]}); @@ -1840,7 +1880,7 @@ describe('di', () => { providers: [{provide: LOCALE_ID, useValue: 'en-GB'}] }) class MyComp { - @ViewChild(MyDir) myDir !: MyDir; + @ViewChild(MyDir) myDir!: MyDir; constructor(@Inject(LOCALE_ID) public localeId: string) {} } @@ -1851,7 +1891,6 @@ describe('di', () => { }); describe('@Attribute', () => { - it('should inject attributes', () => { @Directive({selector: '[dir]'}) class MyDir { @@ -1862,7 +1901,7 @@ describe('di', () => { @Component({template: '
'}) class MyComp { - @ViewChild(MyDir) directiveInstance !: MyDir; + @ViewChild(MyDir) directiveInstance!: MyDir; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); @@ -1886,7 +1925,7 @@ describe('di', () => { @Component( {template: ''}) class MyComp { - @ViewChild(MyDir) directiveInstance !: MyDir; + @ViewChild(MyDir) directiveInstance!: MyDir; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); @@ -1911,7 +1950,7 @@ describe('di', () => { template: '' }) class MyComp { - @ViewChild(MyDir) directiveInstance !: MyDir; + @ViewChild(MyDir) directiveInstance!: MyDir; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); @@ -1938,7 +1977,7 @@ describe('di', () => { '
' }) class MyComp { - @ViewChild(MyDir) directiveInstance !: MyDir; + @ViewChild(MyDir) directiveInstance!: MyDir; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); @@ -1966,7 +2005,7 @@ describe('di', () => { template: '
' }) class MyComp { - @ViewChild(MyDir) directiveInstance !: MyDir; + @ViewChild(MyDir) directiveInstance!: MyDir; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); @@ -1983,7 +2022,7 @@ describe('di', () => { it('should not inject attributes representing bindings and outputs', () => { @Directive({selector: '[dir]'}) class MyDir { - @Input() binding !: string; + @Input() binding!: string; @Output() output = new EventEmitter(); constructor( @Attribute('exist') public exist: string, @@ -1997,7 +2036,7 @@ describe('di', () => { '
' }) class MyComp { - @ViewChild(MyDir) directiveInstance !: MyDir; + @ViewChild(MyDir) directiveInstance!: MyDir; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); @@ -2016,13 +2055,17 @@ describe('di', () => { it('should support dependencies in Pipes used inside ICUs', () => { @Injectable() class MyService { - transform(value: string): string { return `${value} (transformed)`; } + transform(value: string): string { + return `${value} (transformed)`; + } } @Pipe({name: 'somePipe'}) class MyPipe { constructor(private service: MyService) {} - transform(value: any): any { return this.service.transform(value); } + transform(value: any): any { + return this.service.transform(value); + } } @Component({ @@ -2051,13 +2094,17 @@ describe('di', () => { it('should support dependencies in Pipes used inside i18n blocks', () => { @Injectable() class MyService { - transform(value: string): string { return `${value} (transformed)`; } + transform(value: string): string { + return `${value} (transformed)`; + } } @Pipe({name: 'somePipe'}) class MyPipe { constructor(private service: MyService) {} - transform(value: any): any { return this.service.transform(value); } + transform(value: any): any { + return this.service.transform(value); + } } @Component({ @@ -2071,10 +2118,12 @@ describe('di', () => { class MyComp { count = '2'; - @ViewChild('target', {read: ViewContainerRef}) target !: ViewContainerRef; - @ViewChild('source', {read: TemplateRef}) source !: TemplateRef; + @ViewChild('target', {read: ViewContainerRef}) target!: ViewContainerRef; + @ViewChild('source', {read: TemplateRef}) source!: TemplateRef; - create() { this.target.createEmbeddedView(this.source); } + create() { + this.target.createEmbeddedView(this.source); + } } TestBed.configureTestingModule({ @@ -2109,8 +2158,8 @@ describe('di', () => { @Component({template: `
`}) class App { - @ViewChild(DirA) dirA !: DirA; - @ViewChild(Child) child !: Child; + @ViewChild(DirA) dirA!: DirA; + @ViewChild(Child) child!: Child; } const fixture = TestBed.configureTestingModule({declarations: [DirA, DirB, App, Child]}) diff --git a/packages/core/test/acceptance/directive_spec.ts b/packages/core/test/acceptance/directive_spec.ts index 437cf825f23c4..f8174f08a39c9 100644 --- a/packages/core/test/acceptance/directive_spec.ts +++ b/packages/core/test/acceptance/directive_spec.ts @@ -13,9 +13,7 @@ import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('directives', () => { - describe('matching', () => { - @Directive({selector: 'ng-template[test]'}) class TestDirective { constructor(public templateRef: TemplateRef) {} @@ -241,7 +239,9 @@ describe('directives', () => { @Directive({selector: '[dir]'}) class MyDir { - ngOnInit() { calls.push('MyDir.ngOnInit'); } + ngOnInit() { + calls.push('MyDir.ngOnInit'); + } } @Component({ @@ -266,7 +266,9 @@ describe('directives', () => { @Directive({selector: 'svg[dir]'}) class MyDir { constructor(private el: ElementRef) {} - ngOnInit() { calls.push(`MyDir.ngOnInit: ${this.el.nativeElement.tagName}`); } + ngOnInit() { + calls.push(`MyDir.ngOnInit: ${this.el.nativeElement.tagName}`); + } } @Component({ @@ -289,7 +291,9 @@ describe('directives', () => { @Directive({selector: 'text[dir]'}) class MyDir { constructor(private el: ElementRef) {} - ngOnInit() { calls.push(`MyDir.ngOnInit: ${this.el.nativeElement.tagName}`); } + ngOnInit() { + calls.push(`MyDir.ngOnInit: ${this.el.nativeElement.tagName}`); + } } @Component({ @@ -311,13 +315,13 @@ describe('directives', () => { @Directive({selector: '[test]'}) class MyDir { - constructor() { logs.push('MyDir.contructor'); } + constructor() { + logs.push('MyDir.contructor'); + } - @Input('test') - myInput = ''; + @Input('test') myInput = ''; - @Input('disabled') - myInput2 = ''; + @Input('disabled') myInput2 = ''; } @Component({ @@ -338,7 +342,6 @@ describe('directives', () => { expect(logs).toEqual(['MyDir.contructor']); }); - }); describe('inputs', () => { @@ -346,7 +349,9 @@ describe('directives', () => { let dirInstance: WithInput; @Directive({selector: '[dir]'}) class WithInput { - constructor() { dirInstance = this; } + constructor() { + dirInstance = this; + } @Input() dir: string = ''; } @@ -362,14 +367,16 @@ describe('directives', () => { const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); - expect(dirInstance !.dir).toBe('Hello'); + expect(dirInstance!.dir).toBe('Hello'); }); it('should allow directive inputs (as an interpolated prop) on ', () => { let dirInstance: WithInput; @Directive({selector: '[dir]'}) class WithInput { - constructor() { dirInstance = this; } + constructor() { + dirInstance = this; + } @Input() dir: string = ''; } @@ -385,7 +392,7 @@ describe('directives', () => { const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); - expect(dirInstance !.dir).toBe('Hello'); + expect(dirInstance!.dir).toBe('Hello'); }); it('should allow directive inputs (as an interpolated prop) on with structural directives', @@ -393,7 +400,9 @@ describe('directives', () => { let dirInstance: WithInput; @Directive({selector: '[dir]'}) class WithInput { - constructor() { dirInstance = this; } + constructor() { + dirInstance = this; + } @Input() dir: string = ''; } @@ -409,7 +418,7 @@ describe('directives', () => { const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); - expect(dirInstance !.dir).toBe('Hello'); + expect(dirInstance!.dir).toBe('Hello'); }); }); @@ -433,7 +442,7 @@ describe('directives', () => { expect(fixture.componentInstance.testDir).toBeTruthy(); expect(fixture.componentInstance.value).toBe(false); - fixture.componentInstance.testDir !.out.emit(); + fixture.componentInstance.testDir!.out.emit(); fixture.detectChanges(); expect(fixture.componentInstance.value).toBe(true); }); @@ -459,7 +468,6 @@ describe('directives', () => { fixture.detectChanges(); expect(fixture.componentInstance.value).toBeTruthy(); }); - }); describe('attribute shadowing behaviors', () => { @@ -471,8 +479,7 @@ describe('directives', () => { selector: '[dir-with-title]', }) class DirWithTitle { - @Input() - title = ''; + @Input() title = ''; } it('should set both the div attribute and the directive input for `title="value"`', () => { @@ -711,8 +718,12 @@ describe('directives', () => { const log: string[] = []; @Directive({selector: '[dir]'}) class DirectiveA { - constructor() { log.push('DirectiveA.constructor'); } - ngOnInit() { log.push('DirectiveA.ngOnInit'); } + constructor() { + log.push('DirectiveA.constructor'); + } + ngOnInit() { + log.push('DirectiveA.ngOnInit'); + } } @NgModule({ @@ -724,8 +735,12 @@ describe('directives', () => { @Directive({selector: '[dir]'}) class DirectiveB { - constructor() { log.push('DirectiveB.constructor'); } - ngOnInit() { log.push('DirectiveB.ngOnInit'); } + constructor() { + log.push('DirectiveB.constructor'); + } + ngOnInit() { + log.push('DirectiveB.ngOnInit'); + } } @Component({ @@ -752,8 +767,12 @@ describe('directives', () => { const log: string[] = []; @Directive({selector: '[dir]'}) class DirectiveA { - constructor() { log.push('DirectiveA.constructor'); } - ngOnInit() { log.push('DirectiveA.ngOnInit'); } + constructor() { + log.push('DirectiveA.constructor'); + } + ngOnInit() { + log.push('DirectiveA.ngOnInit'); + } } @NgModule({ @@ -765,8 +784,12 @@ describe('directives', () => { @Directive({selector: '[dir]'}) class DirectiveB { - constructor() { log.push('DirectiveB.constructor'); } - ngOnInit() { log.push('DirectiveB.ngOnInit'); } + constructor() { + log.push('DirectiveB.constructor'); + } + ngOnInit() { + log.push('DirectiveB.ngOnInit'); + } } @NgModule({ @@ -795,6 +818,5 @@ describe('directives', () => { 'DirectiveB.ngOnInit' ]); }); - }); }); diff --git a/packages/core/test/acceptance/discover_utils_spec.ts b/packages/core/test/acceptance/discover_utils_spec.ts index 101750b3d1eec..9bbebc4fda6c8 100644 --- a/packages/core/test/acceptance/discover_utils_spec.ts +++ b/packages/core/test/acceptance/discover_utils_spec.ts @@ -48,12 +48,16 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils', () => { @Component( {selector: 'child', template: '

', providers: [{provide: String, useValue: 'Child'}]}) class Child { - constructor() { childComponent.push(this); } + constructor() { + childComponent.push(this); + } } @Directive({selector: '[dirA]', exportAs: 'dirA'}) class DirectiveA { - constructor() { dirA.push(this); } + constructor() { + dirA.push(this); + } } @Component({ @@ -69,9 +73,13 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils', () => { }) class MyApp { text: string = 'INIT'; - constructor() { myApp = this; } + constructor() { + myApp = this; + } - log(event: any) { log.push(event); } + log(event: any) { + log.push(event); + } } describe('getComponent', () => { @@ -112,7 +120,7 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils', () => { }); it('should return context from element', () => { expect(getContext(child[0])).toEqual(myApp); - expect(getContext<{$implicit: boolean}>(child[2]) !.$implicit).toEqual(true); + expect(getContext<{$implicit: boolean}>(child[2])!.$implicit).toEqual(true); expect(getContext(p[0])).toEqual(childComponent[0]); }); }); @@ -264,7 +272,7 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils', () => { it('should work on templates', () => { const templateComment = Array.from((fixture.nativeElement as HTMLElement).childNodes) - .find((node: ChildNode) => node.nodeType === Node.COMMENT_NODE) !; + .find((node: ChildNode) => node.nodeType === Node.COMMENT_NODE)!; const lContext = loadLContext(templateComment); expect(lContext).toBeDefined(); expect(lContext.native as any).toBe(templateComment); @@ -274,7 +282,7 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils', () => { const ngContainerComment = Array.from((fixture.nativeElement as HTMLElement).childNodes) .find( (node: ChildNode) => node.nodeType === Node.COMMENT_NODE && - node.textContent === `ng-container`) !; + node.textContent === `ng-container`)!; const lContext = loadLContext(ngContainerComment); expect(lContext).toBeDefined(); expect(lContext.native as any).toBe(ngContainerComment); @@ -285,7 +293,6 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils', () => { onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => { describe('getRootComponents()', () => { it('should return a list of the root components of the application from an element', () => { - @Component({selector: 'inner-comp', template: '
'}) class InnerComp { } @@ -299,13 +306,13 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => fixture.detectChanges(); const hostElm = fixture.nativeElement; - const innerElm = hostElm.querySelector('inner-comp') !; - const divElm = hostElm.querySelector('div') !; + const innerElm = hostElm.querySelector('inner-comp')!; + const divElm = hostElm.querySelector('div')!; const component = fixture.componentInstance; - expect(getRootComponents(hostElm) !).toEqual([component]); - expect(getRootComponents(innerElm) !).toEqual([component]); - expect(getRootComponents(divElm) !).toEqual([component]); + expect(getRootComponents(hostElm)!).toEqual([component]); + expect(getRootComponents(innerElm)!).toEqual([component]); + expect(getRootComponents(divElm)!).toEqual([component]); }); }); @@ -331,9 +338,9 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => ` }) class Comp { - @ViewChild(MyDir1) myDir1Instance !: MyDir1; - @ViewChild(MyDir2) myDir2Instance !: MyDir2; - @ViewChild(MyDir3) myDir3Instance !: MyDir3; + @ViewChild(MyDir1) myDir1Instance!: MyDir1; + @ViewChild(MyDir2) myDir2Instance!: MyDir2; + @ViewChild(MyDir3) myDir3Instance!: MyDir3; } TestBed.configureTestingModule({declarations: [Comp, MyDir1, MyDir2, MyDir3]}); @@ -345,19 +352,17 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => const elm1 = elements[0]; const elm1Dirs = getDirectives(elm1); - expect(elm1Dirs).toContain(fixture.componentInstance.myDir1Instance !); - expect(elm1Dirs).toContain(fixture.componentInstance.myDir2Instance !); + expect(elm1Dirs).toContain(fixture.componentInstance.myDir1Instance!); + expect(elm1Dirs).toContain(fixture.componentInstance.myDir2Instance!); const elm2 = elements[1]; const elm2Dirs = getDirectives(elm2); - expect(elm2Dirs).toContain(fixture.componentInstance.myDir3Instance !); + expect(elm2Dirs).toContain(fixture.componentInstance.myDir3Instance!); }); }); describe('getInjector', () => { - it('should return an injector that can return directive instances', () => { - @Component({template: ''}) class Comp { } @@ -386,7 +391,6 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => describe('getLocalRefs', () => { it('should return a map of local refs for an element', () => { - @Directive({selector: '[myDir]', exportAs: 'myDir'}) class MyDir { } @@ -399,7 +403,7 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); - const divEl = fixture.nativeElement.querySelector('div') !; + const divEl = fixture.nativeElement.querySelector('div')!; const localRefs = getLocalRefs(divEl); expect(localRefs.elRef.tagName.toLowerCase()).toBe('div'); @@ -416,7 +420,7 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); - const divEl = fixture.nativeElement.querySelector('div') !; + const divEl = fixture.nativeElement.querySelector('div')!; const localRefs = getLocalRefs(divEl); expect(localRefs.elRef.tagName.toLowerCase()).toBe('div'); @@ -439,11 +443,11 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); - const parent = fixture.nativeElement.querySelector('.parent') !; - const child = fixture.nativeElement.querySelector('.child') !; + const parent = fixture.nativeElement.querySelector('.parent')!; + const child = fixture.nativeElement.querySelector('.child')!; - const parentDebug = getDebugNode(parent) !; - const childDebug = getDebugNode(child) !; + const parentDebug = getDebugNode(parent)!; + const childDebug = getDebugNode(child)!; expect(parentDebug.native).toBe(parent); expect(childDebug.native).toBe(child); @@ -472,8 +476,8 @@ onlyInIvy('Ivy-specific utilities').describe('discovery utils deprecated', () => const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); - const child = fixture.nativeElement.querySelector('child-comp') !; - const childDebug = getDebugNode(child) !; + const child = fixture.nativeElement.querySelector('child-comp')!; + const childDebug = getDebugNode(child)!; expect(childDebug.native).toBe(child); expect(getElementStyles(child)).toEqual({ diff --git a/packages/core/test/acceptance/embedded_views_spec.ts b/packages/core/test/acceptance/embedded_views_spec.ts index a4fd8ba31bd1e..d0f17974e0f8d 100644 --- a/packages/core/test/acceptance/embedded_views_spec.ts +++ b/packages/core/test/acceptance/embedded_views_spec.ts @@ -10,7 +10,6 @@ import {Component, Input} from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('embedded views', () => { - it('should correctly resolve the implicit receiver in expressions', () => { const items: string[] = []; @@ -27,7 +26,9 @@ describe('embedded views', () => { }) class TestCmp { item: string = 'CmpItem'; - addItem() { items.push(this.item); } + addItem() { + items.push(this.item); + } } TestBed.configureTestingModule({declarations: [ChildCmp, TestCmp]}); @@ -36,8 +37,8 @@ describe('embedded views', () => { const childCmp: ChildCmp = fixture.debugElement.children[0].componentInstance; - childCmp.addItemFn !(); - childCmp.addItemFn !(); + childCmp.addItemFn!(); + childCmp.addItemFn!(); expect(items).toEqual(['CmpItem', 'CmpItem']); }); @@ -71,5 +72,4 @@ describe('embedded views', () => { expect(fixture.nativeElement.textContent).toBe('HelloHello'); }); - }); diff --git a/packages/core/test/acceptance/exports_spec.ts b/packages/core/test/acceptance/exports_spec.ts index 41921f280557b..1513528a13bd0 100644 --- a/packages/core/test/acceptance/exports_spec.ts +++ b/packages/core/test/acceptance/exports_spec.ts @@ -247,7 +247,13 @@ class DirWithCompInput { class DirToReferenceWithPreOrderHooks implements OnInit, OnChanges, DoCheck { @Input() in : any = null; name = 'Drew'; - ngOnChanges(changes: SimpleChanges) { this.name += '!'; } - ngOnInit() { this.name += '?'; } - ngDoCheck() { this.name += '@'; } + ngOnChanges(changes: SimpleChanges) { + this.name += '!'; + } + ngOnInit() { + this.name += '?'; + } + ngDoCheck() { + this.name += '@'; + } } diff --git a/packages/core/test/acceptance/host_binding_spec.ts b/packages/core/test/acceptance/host_binding_spec.ts index 6ed40776605c3..8457bf06d03c3 100644 --- a/packages/core/test/acceptance/host_binding_spec.ts +++ b/packages/core/test/acceptance/host_binding_spec.ts @@ -121,10 +121,9 @@ describe('host bindings', () => { class ParentCmp { private _prop = ''; - @ViewChild('template', {read: ViewContainerRef}) - vcr: ViewContainerRef = null !; + @ViewChild('template', {read: ViewContainerRef}) vcr: ViewContainerRef = null!; - private child: ComponentRef = null !; + private child: ComponentRef = null!; @Input() set prop(value: string) { @@ -137,10 +136,11 @@ describe('host bindings', () => { } } - get prop() { return this._prop; } + get prop() { + return this._prop; + } - @Input() - prop2 = 0; + @Input() prop2 = 0; ngAfterViewInit() { const factory = this.componentFactoryResolver.resolveComponentFactory(ChildCmp); @@ -212,7 +212,6 @@ describe('host bindings', () => { onlyInIvy('[style.prop] and [class.name] prioritization is a new feature') .it('should prioritize styling present in the order of directive hostBinding evaluation, but consider sub-classed directive styling to be the most important', () => { - @Component({template: '
'}) class MyApp { } @@ -220,37 +219,55 @@ describe('host bindings', () => { @Directive({selector: '[parent-dir]'}) class ParentDir { @HostBinding('style.width') - get width1() { return '100px'; } + get width1() { + return '100px'; + } @HostBinding('style.height') - get height1() { return '100px'; } + get height1() { + return '100px'; + } @HostBinding('style.color') - get color1() { return 'red'; } + get color1() { + return 'red'; + } } @Directive({selector: '[child-dir]'}) class ChildDir extends ParentDir { @HostBinding('style.width') - get width2() { return '200px'; } + get width2() { + return '200px'; + } @HostBinding('style.height') - get height2() { return '200px'; } + get height2() { + return '200px'; + } } @Directive({selector: '[sibling-dir]'}) class SiblingDir { @HostBinding('style.width') - get width3() { return '300px'; } + get width3() { + return '300px'; + } @HostBinding('style.height') - get height3() { return '300px'; } + get height3() { + return '300px'; + } @HostBinding('style.opacity') - get opacity3() { return '0.5'; } + get opacity3() { + return '0.5'; + } @HostBinding('style.color') - get color1() { return 'blue'; } + get color1() { + return 'blue'; + } } TestBed.configureTestingModule( @@ -295,25 +312,22 @@ describe('host bindings', () => { fixture.detectChanges(); }).not.toThrow(); }); - }); @Directive({selector: '[hostBindingDir]'}) class HostBindingDir { - @HostBinding() - id = 'foo'; + @HostBinding() id = 'foo'; } it('should support host bindings in directives', () => { @Directive({selector: '[dir]'}) class Dir { - @HostBinding('className') - klass = 'foo'; + @HostBinding('className') klass = 'foo'; } @Component({template: ''}) class App { - @ViewChild(Dir) directiveInstance !: Dir; + @ViewChild(Dir) directiveInstance!: Dir; } TestBed.configureTestingModule({declarations: [App, Dir]}); @@ -333,8 +347,7 @@ describe('host bindings', () => { it('should support host bindings on root component', () => { @Component({template: ''}) class HostBindingComp { - @HostBinding() - title = 'my-title'; + @HostBinding() title = 'my-title'; } TestBed.configureTestingModule({declarations: [HostBindingComp]}); @@ -365,8 +378,7 @@ describe('host bindings', () => { class App { constructor(public serviceOne: ServiceOne, public serviceTwo: ServiceTwo) {} - @HostBinding() - title = 'my-title'; + @HostBinding() title = 'my-title'; } TestBed.configureTestingModule({declarations: [App]}); @@ -390,8 +402,7 @@ describe('host bindings', () => { @Component({selector: 'host-title-comp', template: ''}) class HostTitleComp { - @HostBinding() - title = 'my-title'; + @HostBinding() title = 'my-title'; } @Component({ @@ -402,7 +413,7 @@ describe('host bindings', () => { ` }) class App { - @ViewChild(HostBindingDir) hostBindingDir !: HostBindingDir; + @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, SomeDir, HostTitleComp, HostBindingDir]}); @@ -415,7 +426,7 @@ describe('host bindings', () => { expect(hostBindingDiv.id).toEqual('foo'); expect(hostTitleComp.title).toEqual('my-title'); - fixture.componentInstance.hostBindingDir !.id = 'bar'; + fixture.componentInstance.hostBindingDir!.id = 'bar'; fixture.detectChanges(); expect(hostBindingDiv.id).toEqual('bar'); }); @@ -423,8 +434,7 @@ describe('host bindings', () => { it('should support consecutive components with host bindings', () => { @Component({selector: 'host-binding-comp', template: ''}) class HostBindingComp { - @HostBinding() - id = 'blue'; + @HostBinding() id = 'blue'; } @Component({ @@ -434,7 +444,7 @@ describe('host bindings', () => { ` }) class App { - @ViewChildren(HostBindingComp) hostBindingComp !: QueryList; + @ViewChildren(HostBindingComp) hostBindingComp!: QueryList; } TestBed.configureTestingModule({declarations: [App, HostBindingComp]}); @@ -470,7 +480,7 @@ describe('host bindings', () => { @Component({template: '
'}) class App { - @ViewChild(HostBindingDir) hostBindingDir !: HostBindingDir; + @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, SomeDir, HostBindingDir]}); @@ -480,7 +490,7 @@ describe('host bindings', () => { const hostBindingDiv = fixture.nativeElement.querySelector('div') as HTMLElement; expect(hostBindingDiv.id).toEqual('foo'); - fixture.componentInstance.hostBindingDir !.id = 'bar'; + fixture.componentInstance.hostBindingDir!.id = 'bar'; fixture.detectChanges(); expect(hostBindingDiv.id).toEqual('bar'); }); @@ -490,18 +500,23 @@ describe('host bindings', () => { it('should support host bindings that rely on values from init hooks', () => { @Component({template: '', selector: 'init-hook-comp'}) class InitHookComp implements OnInit, OnChanges, DoCheck { - @Input() - inputValue = ''; + @Input() inputValue = ''; changesValue = ''; initValue = ''; checkValue = ''; - ngOnChanges() { this.changesValue = 'changes'; } + ngOnChanges() { + this.changesValue = 'changes'; + } - ngOnInit() { this.initValue = 'init'; } + ngOnInit() { + this.initValue = 'init'; + } - ngDoCheck() { this.checkValue = 'check'; } + ngDoCheck() { + this.checkValue = 'check'; + } @HostBinding('title') get value() { @@ -529,16 +544,14 @@ describe('host bindings', () => { it('should support host bindings with the same name as inputs', () => { @Directive({selector: '[hostBindingDir]'}) class HostBindingInputDir { - @Input() - disabled = false; + @Input() disabled = false; - @HostBinding('disabled') - hostDisabled = false; + @HostBinding('disabled') hostDisabled = false; } @Component({template: ''}) class App { - @ViewChild(HostBindingInputDir) hostBindingInputDir !: HostBindingInputDir; + @ViewChild(HostBindingInputDir) hostBindingInputDir!: HostBindingInputDir; isDisabled = true; } @@ -611,14 +624,12 @@ describe('host bindings', () => { it('should support component with host bindings and array literals', () => { @Component({selector: 'host-binding-comp', template: ''}) class HostBindingComp { - @HostBinding() - id = 'my-id'; + @HostBinding() id = 'my-id'; } @Component({selector: 'name-comp', template: ''}) class NameComp { - @Input() - names !: string[]; + @Input() names!: string[]; } @Component({ @@ -628,7 +639,7 @@ describe('host bindings', () => { ` }) class App { - @ViewChild(NameComp) nameComp !: NameComp; + @ViewChild(NameComp) nameComp!: NameComp; name = ''; } @@ -661,8 +672,7 @@ describe('host bindings', () => { it('should support host bindings that contain array literals', () => { @Component({selector: 'name-comp', template: ''}) class NameComp { - @Input() - names !: string[]; + @Input() names!: string[]; } @Component({ @@ -684,8 +694,8 @@ describe('host bindings', () => { ` }) class App { - @ViewChild(HostBindingComp) hostBindingComp !: HostBindingComp; - @ViewChild(NameComp) nameComp !: NameComp; + @ViewChild(HostBindingComp) hostBindingComp!: HostBindingComp; + @ViewChild(NameComp) nameComp!: NameComp; name = ''; otherName = ''; } @@ -703,11 +713,11 @@ describe('host bindings', () => { expect(hostBindingEl.id).toBe('red,blue'); expect(hostBindingEl.dir).toBe('ltr'); expect(hostBindingEl.title).toBe('my title,other title'); - expect(nameComp !.names).toEqual(['Frank', 'Nancy', 'Joe']); + expect(nameComp!.names).toEqual(['Frank', 'Nancy', 'Joe']); - const firstArray = nameComp !.names; + const firstArray = nameComp!.names; fixture.detectChanges(); - expect(firstArray).toBe(nameComp !.names); + expect(firstArray).toBe(nameComp!.names); hostBindingComp.id = 'green'; hostBindingComp.dir = 'rtl'; @@ -729,7 +739,9 @@ describe('host bindings', () => { @Directive({selector: '[hostListenerDir]'}) class HostListenerDir { @HostListener('click') - onClick() { events.push('click!'); } + onClick() { + events.push('click!'); + } } @Component({template: ''}) @@ -740,7 +752,7 @@ describe('host bindings', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - const button = fixture.nativeElement.querySelector('button') !; + const button = fixture.nativeElement.querySelector('button')!; button.click(); expect(events).toEqual(['click!']); expect(button.title).toEqual('my title,other title'); @@ -759,8 +771,8 @@ describe('host bindings', () => { @Component({template: ''}) class App { - @ViewChild(HostBindingComp) hostBindingComp !: HostBindingComp; - @ViewChild(HostBindingDir) hostBindingDir !: HostBindingDir; + @ViewChild(HostBindingComp) hostBindingComp!: HostBindingComp; + @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, HostBindingComp, HostBindingDir]}); @@ -798,7 +810,7 @@ describe('host bindings', () => { @Component({template: `{{ name }}`}) class App { - @ViewChild(HostBindingComp) hostBindingComp !: HostBindingComp; + @ViewChild(HostBindingComp) hostBindingComp!: HostBindingComp; name = ''; } @@ -872,8 +884,8 @@ describe('host bindings', () => { ` }) class App { - @ViewChild(SubDirective) subDir !: SubDirective; - @ViewChild(SuperDirective) superDir !: SuperDirective; + @ViewChild(SubDirective) subDir!: SubDirective; + @ViewChild(SuperDirective) superDir!: SuperDirective; } TestBed.configureTestingModule({declarations: [App, SuperDirective, SubDirective]}); @@ -927,8 +939,7 @@ describe('host bindings', () => { host: {'[id]': 'foos.length'} }) class HostBindingWithContentChildren { - @ContentChildren('foo') - foos !: QueryList; + @ContentChildren('foo') foos!: QueryList; } @Component({ @@ -955,7 +966,9 @@ describe('host bindings', () => { class HostBindingWithContentHooks implements AfterContentInit { myValue = 'initial'; - ngAfterContentInit() { this.myValue = 'after-content'; } + ngAfterContentInit() { + this.myValue = 'after-content'; + } } @Component({template: ''}) @@ -971,7 +984,6 @@ describe('host bindings', () => { }); describe('styles', () => { - it('should bind to host styles', () => { @Component( {selector: 'host-binding-to-styles', host: {'[style.width.px]': 'width'}, template: ''}) @@ -981,7 +993,7 @@ describe('host bindings', () => { @Component({template: ''}) class App { - @ViewChild(HostBindingToStyles) hostBindingDir !: HostBindingToStyles; + @ViewChild(HostBindingToStyles) hostBindingDir!: HostBindingToStyles; } TestBed.configureTestingModule({declarations: [App, HostBindingToStyles]}); @@ -1010,7 +1022,7 @@ describe('host bindings', () => { @Component({template: '
'}) class App { - @ViewChild(HostBindingToStyles) hostBindingDir !: HostBindingToStyles; + @ViewChild(HostBindingToStyles) hostBindingDir!: HostBindingToStyles; } TestBed.configureTestingModule({declarations: [App, HostBindingToStyles, ContainerDir]}); @@ -1044,10 +1056,12 @@ describe('host bindings', () => { }); describe('sanitization', () => { - function identity(value: any) { return value; } - function verify( - tag: string, prop: string, value: any, expectedSanitizedValue: any, bypassFn: Function, - isAttribute: boolean = true, throws: boolean = false) { + function identity(value: any) { + return value; + } + function verify(tag: string, prop: string, value: any, expectedSanitizedValue: any, + bypassFn: Function, isAttribute: boolean = true, + throws: boolean = false) { it(`should sanitize <${tag} ${prop}> ${isAttribute ? 'properties' : 'attributes'}`, () => { @Directive({ selector: '[unsafeUrlHostBindingDir]', @@ -1061,13 +1075,13 @@ describe('host bindings', () => { @Component({template: `<${tag} unsafeUrlHostBindingDir>`}) class App { - @ViewChild(UnsafeDir) unsafeDir !: UnsafeDir; + @ViewChild(UnsafeDir) unsafeDir!: UnsafeDir; } TestBed.configureTestingModule({declarations: [App, UnsafeDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); - const el = fixture.nativeElement.querySelector(tag) !; + const el = fixture.nativeElement.querySelector(tag)!; const current = () => isAttribute ? el.getAttribute(prop) : (el as any)[prop]; fixture.componentInstance.unsafeDir.value = value; @@ -1103,5 +1117,4 @@ describe('host bindings', () => { '', bypassSanitizationTrustHtml, /* isAttribute */ false); }); - }); diff --git a/packages/core/test/acceptance/i18n_spec.ts b/packages/core/test/acceptance/i18n_spec.ts index bf598a8868976..846cb6b0d02f9 100644 --- a/packages/core/test/acceptance/i18n_spec.ts +++ b/packages/core/test/acceptance/i18n_spec.ts @@ -8,16 +8,17 @@ // Make the `$localize()` global function available to the compiled templates, and the direct calls // below. This would normally be done inside the application `polyfills.ts` file. import '@angular/localize/init'; + import {CommonModule, registerLocaleData} from '@angular/common'; import localeRo from '@angular/common/locales/ro'; -import {Component, ContentChild, ElementRef, ContentChildren, Directive, HostBinding, Input, LOCALE_ID, QueryList, TemplateRef, Type, ViewChild, ViewContainerRef, Pipe, PipeTransform, NO_ERRORS_SCHEMA} from '@angular/core'; +import {computeMsgId} from '@angular/compiler'; +import {Component, ContentChild, ContentChildren, Directive, ElementRef, HostBinding, Input, LOCALE_ID, NO_ERRORS_SCHEMA, Pipe, PipeTransform, QueryList, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core'; import {setDelayProjection} from '@angular/core/src/render3/instructions/projection'; import {TestBed} from '@angular/core/testing'; -import {loadTranslations, clearTranslations} from '@angular/localize'; +import {clearTranslations, loadTranslations} from '@angular/localize'; import {By} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {onlyInIvy} from '@angular/private/testing'; -import {computeMsgId} from '@angular/compiler'; import {BehaviorSubject} from 'rxjs'; @@ -72,7 +73,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { it('should support interpolations with custom interpolation config', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); - const interpolation = ['{%', '%}'] as[string, string]; + const interpolation = ['{%', '%}'] as [string, string]; TestBed.overrideComponent(AppComp, {set: {interpolation}}); const fixture = initWithTemplate(AppComp, `
Hello {% name %}
`); @@ -277,7 +278,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { name = `Angular`; clicks = 0; - onClick() { this.clicks++; } + onClick() { + this.clicks++; + } } TestBed.configureTestingModule({declarations: [ListenerComp]}); @@ -619,7 +622,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { [computeMsgId('{VAR_SELECT, select, 10 {ten} other {{INTERPOLATION}}}')]: '{VAR_SELECT, select, 10 {dix} other {{INTERPOLATION}}}' }); - const interpolation = ['{%', '%}'] as[string, string]; + const interpolation = ['{%', '%}'] as [string, string]; TestBed.overrideComponent(AppComp, {set: {interpolation}}); const fixture = initWithTemplate(AppComp, `
{count, select, 10 {ten} other {{% name %}}}
`); @@ -704,7 +707,8 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { '{VAR_SELECT, select, 10 {dix} 20 {vingt} other {autre}}' }); const fixture = initWithTemplate( - AppComp, ` + AppComp, + ` ` + `{count, select, 10 {ten} 20 {twenty} other {other}}` + ` @@ -864,7 +868,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { private readonly viewContainerRef: ViewContainerRef, private readonly templateRef: TemplateRef) {} - ngOnInit() { this.viewContainerRef.createEmbeddedView(this.templateRef); } + ngOnInit() { + this.viewContainerRef.createEmbeddedView(this.templateRef); + } } @Component({ @@ -941,7 +947,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { dir = this; } - attachEmbeddedView() { this.viewContainerRef.createEmbeddedView(this.templateRef); } + attachEmbeddedView() { + this.viewContainerRef.createEmbeddedView(this.templateRef); + } } @Component({ @@ -983,7 +991,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { expect(fixture.debugElement.nativeElement.innerHTML) .toBe(''); - dir !.attachEmbeddedView(); + dir!.attachEmbeddedView(); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML) .toBe( @@ -1019,7 +1027,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { class Comp { type = 'A'; visible = true; - isVisible() { return true; } + isVisible() { + return true; + } } TestBed.configureTestingModule({declarations: [Comp]}); @@ -1042,7 +1052,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { '{VAR_SELECT, select, A {A - {PH_A}} ' + 'B {B - {PH_B}} other {other - {PH_WITH_SPACES}}}')]: '{VAR_SELECT, select, A {A (translated) - {PH_A}} ' + - 'B {B (translated) - {PH_B}} other {other (translated) - {PH_WITH_SPACES}}}', + 'B {B (translated) - {PH_B}} other {other (translated) - {PH_WITH_SPACES}}}', }); @Component({ selector: 'comp', @@ -1326,7 +1336,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { it('with custom interpolation config', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}', 'm')]: 'Bonjour {$INTERPOLATION}'}); - const interpolation = ['{%', '%}'] as[string, string]; + const interpolation = ['{%', '%}'] as [string, string]; TestBed.overrideComponent(AppComp, {set: {interpolation}}); const fixture = initWithTemplate(AppComp, `
`); @@ -1367,7 +1377,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { }) class TitleDir { @Input() title = ''; - constructor() { titleDirInstances.push(this); } + constructor() { + titleDirInstances.push(this); + } } @Component({ @@ -1397,7 +1409,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { @Directive({selector: '[title]'}) class TitleDir { @Input() title: string = ''; - constructor(public elRef: ElementRef) { titleDirInstances.push(this); } + constructor(public elRef: ElementRef) { + titleDirInstances.push(this); + } } @Component({ @@ -1429,7 +1443,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { let dirInstance: WithInput; @Directive({selector: '[dir]'}) class WithInput { - constructor() { dirInstance = this; } + constructor() { + dirInstance = this; + } @Input() dir: string = ''; } @@ -1445,7 +1461,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); - expect(dirInstance !.dir).toBe('Bonjour Angular'); + expect(dirInstance!.dir).toBe('Bonjour Angular'); }); it('should allow directive inputs (as interpolated props)' + @@ -1456,7 +1472,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { let dirInstance: WithInput; @Directive({selector: '[dir]'}) class WithInput { - constructor() { dirInstance = this; } + constructor() { + dirInstance = this; + } @Input() dir: string = ''; } @@ -1472,7 +1490,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); - expect(dirInstance !.dir).toBe('Bonjour Angular'); + expect(dirInstance!.dir).toBe('Bonjour Angular'); }); it('should apply i18n attributes during second template pass', () => { @@ -1537,7 +1555,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { template: '{{ messageText }}', }) class WelcomeComp { - @Input() messageText !: string; + @Input() messageText!: string; } @Component({ @@ -1598,10 +1616,11 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { @Directive({selector: '[test]'}) class ClsDir { - @HostBinding('className') - klass = 'foo'; + @HostBinding('className') klass = 'foo'; - constructor() { directiveInstances.push(this); } + constructor() { + directiveInstances.push(this); + } } @Component({ @@ -1641,7 +1660,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { // but IE does not. expect(outerDiv.getAttribute('title')).toBe('début 2 milieu 1 fin'); expect(outerDiv.getAttribute('class')).toBe('foo'); - expect(outerDiv.textContent !.trim()).toBe('traduction: un email'); + expect(outerDiv.textContent!.trim()).toBe('traduction: un email'); expect(innerDiv.getAttribute('class')).toBe('foo'); directiveInstances.forEach(instance => instance.klass = 'bar'); @@ -1651,7 +1670,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { expect(outerDiv.getAttribute('title')).toBe('début 3 milieu 2 fin'); expect(outerDiv.getAttribute('class')).toBe('bar'); - expect(outerDiv.textContent !.trim()).toBe('traduction: 2 emails'); + expect(outerDiv.textContent!.trim()).toBe('traduction: 2 emails'); expect(innerDiv.getAttribute('class')).toBe('bar'); }); @@ -1660,21 +1679,25 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { let calledValue = false; @Component({selector: 'my-comp', template: ''}) class MyComp { - t !: string; + t!: string; @Input() - get title() { return this.t; } + get title() { + return this.t; + } set title(title) { calledTitle = true; this.t = title; } @Input() - get value() { return this.val; } + get value() { + return this.val; + } set value(value: string) { calledValue = true; this.val = value; } - val !: string; + val!: string; } TestBed.configureTestingModule({declarations: [AppComp, MyComp]}); @@ -2050,7 +2073,6 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { }); it('should display/destroy projected i18n content', () => { - loadTranslations({ [computeMsgId('{VAR_SELECT, select, A {A} B {B} other {other}}')]: '{VAR_SELECT, select, A {A} B {B} other {other}}' @@ -2109,7 +2131,7 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { @Directive({selector: '[text]', inputs: ['text'], exportAs: 'textDir'}) class TextDirective { // TODO(issue/24571): remove '!'. - text !: string; + text!: string; constructor() {} } @@ -2119,16 +2141,18 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { @ContentChild(TemplateRef, {static: true}) template !: TemplateRef; // TODO(issue/24571): remove '!'. - @ViewChild('vc', {read: ViewContainerRef, static: true}) - vc !: ViewContainerRef; + @ViewChild('vc', {read: ViewContainerRef, static: true}) vc!: ViewContainerRef; // TODO(issue/24571): remove '!'. - @ContentChildren(TextDirective, {descendants: true}) - query !: QueryList; + @ContentChildren(TextDirective, {descendants: true}) query!: QueryList; - create() { this.vc.createEmbeddedView(this.template); } + create() { + this.vc.createEmbeddedView(this.template); + } - destroy() { this.vc.clear(); } + destroy() { + this.vc.clear(); + } } TestBed.configureTestingModule({declarations: [TextDirective, DivQuery]}); @@ -2224,7 +2248,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { @Directive({selector: 'input'}) class InputsDir { constructor(private elementRef: ElementRef) {} - ngOnInit() { this.elementRef.nativeElement.value = 'value set in Directive.ngOnInit'; } + ngOnInit() { + this.elementRef.nativeElement.value = 'value set in Directive.ngOnInit'; + } } @Component({ @@ -2248,7 +2274,9 @@ onlyInIvy('Ivy i18n logic').describe('runtime i18n', () => { @Directive({selector: 'input'}) class InputsDir { constructor(private elementRef: ElementRef) {} - ngOnInit() { this.elementRef.nativeElement.value = 'value set in Directive.ngOnInit'; } + ngOnInit() { + this.elementRef.nativeElement.value = 'value set in Directive.ngOnInit'; + } } @Component({ @@ -2401,12 +2429,16 @@ class AppCompWithWhitespaces { }) class DirectiveWithTplRef { constructor(public vcRef: ViewContainerRef, public tplRef: TemplateRef<{}>) {} - ngOnInit() { this.vcRef.createEmbeddedView(this.tplRef, {}); } + ngOnInit() { + this.vcRef.createEmbeddedView(this.tplRef, {}); + } } @Pipe({name: 'uppercase'}) class UppercasePipe implements PipeTransform { - transform(value: string) { return value.toUpperCase(); } + transform(value: string) { + return value.toUpperCase(); + } } @Directive({selector: `[dialog]`}) diff --git a/packages/core/test/acceptance/inherit_definition_feature_spec.ts b/packages/core/test/acceptance/inherit_definition_feature_spec.ts index 91fc4dfa3d60d..42f69a2e7aa6c 100644 --- a/packages/core/test/acceptance/inherit_definition_feature_spec.ts +++ b/packages/core/test/acceptance/inherit_definition_feature_spec.ts @@ -118,10 +118,10 @@ describe('inheritance', () => { 'Base.backgroundColor', 'Super.color', 'Sub2.width', // ]); if (ivyEnabled) { - expect(getDirectiveDef(BaseDirective) !.hostVars).toEqual(2); - expect(getDirectiveDef(SuperDirective) !.hostVars).toEqual(4); - expect(getDirectiveDef(Sub1Directive) !.hostVars).toEqual(6); - expect(getDirectiveDef(Sub2Directive) !.hostVars).toEqual(6); + expect(getDirectiveDef(BaseDirective)!.hostVars).toEqual(2); + expect(getDirectiveDef(SuperDirective)!.hostVars).toEqual(4); + expect(getDirectiveDef(Sub1Directive)!.hostVars).toEqual(6); + expect(getDirectiveDef(Sub2Directive)!.hostVars).toEqual(6); } }); }); @@ -134,7 +134,9 @@ describe('inheritance', () => { class SuperDirective implements OnChanges { @Input() someInput = ''; - ngOnChanges() { log.push('on changes!'); } + ngOnChanges() { + log.push('on changes!'); + } } @Directive({selector: '[subDir]'}) @@ -158,7 +160,9 @@ describe('inheritance', () => { const log: string[] = []; class SuperClass { - ngOnChanges() { log.push('on changes!'); } + ngOnChanges() { + log.push('on changes!'); + } } @Directive({selector: '[subDir]'}) @@ -186,7 +190,9 @@ describe('inheritance', () => { class GrandSuperDirective implements OnChanges { @Input() someInput = ''; - ngOnChanges() { log.push('on changes!'); } + ngOnChanges() { + log.push('on changes!'); + } } @Directive({selector: '[superDir]'}) @@ -215,7 +221,9 @@ describe('inheritance', () => { const log: string[] = []; class GrandSuperClass { - ngOnChanges() { log.push('on changes!'); } + ngOnChanges() { + log.push('on changes!'); + } } @Directive({selector: '[superDir]'}) @@ -248,7 +256,9 @@ describe('inheritance', () => { class GrandSuperDirective implements OnChanges { @Input() someInput = ''; - ngOnChanges() { log.push('on changes!'); } + ngOnChanges() { + log.push('on changes!'); + } } class SuperClass extends GrandSuperDirective {} @@ -275,7 +285,9 @@ describe('inheritance', () => { const log: string[] = []; class GrandSuperClass { - ngOnChanges() { log.push('on changes!'); } + ngOnChanges() { + log.push('on changes!'); + } } class SuperClass extends GrandSuperClass {} @@ -310,7 +322,9 @@ describe('inheritance', () => { abstract class UndecoratedBase extends Base { abstract input: any; - ngOnChanges() { changes++; } + ngOnChanges() { + changes++; + } } @Component({selector: 'my-comp', template: ''}) @@ -339,13 +353,27 @@ describe('inheritance', () => { const fired: string[] = []; class SuperDirective { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } beforeEach(() => fired.length = 0); @@ -355,7 +383,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -394,7 +424,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -433,7 +465,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -472,7 +506,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -511,7 +547,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -550,7 +588,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -589,7 +629,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -631,25 +673,20 @@ describe('inheritance', () => { it('should inherit inputs', () => { class SuperDirective { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - bar = ''; + @Input() bar = ''; - @Input() - baz = ''; + @Input() baz = ''; } @Directive({ selector: '[sub-dir]', }) class SubDirective extends SuperDirective { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({template: `

`}) @@ -684,15 +721,16 @@ describe('inheritance', () => { it('should inherit outputs', () => { class SuperDirective { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } @Directive({ selector: '[sub-dir]', }) class SubDirective extends SuperDirective { - ngOnInit() { this.foo.emit('test'); } + ngOnInit() { + this.foo.emit('test'); + } } @Component({ @@ -703,7 +741,9 @@ describe('inheritance', () => { class App { foo = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } } TestBed.configureTestingModule({ @@ -722,11 +762,9 @@ describe('inheritance', () => { // TODO: sub and super HostBinding same binding on two different properties it('should compose host bindings for styles', () => { class SuperDirective { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } @Directive({ @@ -762,10 +800,11 @@ describe('inheritance', () => { it('should compose host bindings (non-style related)', () => { class SuperDirective { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } @Directive({ @@ -803,15 +842,16 @@ describe('inheritance', () => { } class SuperDirective { - @ContentChildren(ChildDir) - customDirs !: QueryList; + @ContentChildren(ChildDir) customDirs!: QueryList; } @Directive({ selector: '[sub-dir]', }) class SubDirective extends SuperDirective { - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -831,7 +871,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(2); + expect(foundQueryList!.length).toBe(2); }); }); @@ -873,13 +913,27 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } beforeEach(() => fired.length = 0); @@ -889,7 +943,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -928,7 +984,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -967,7 +1025,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -1006,7 +1066,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -1045,7 +1107,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -1084,7 +1148,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -1123,7 +1189,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -1166,25 +1234,20 @@ describe('inheritance', () => { it('should inherit inputs', () => { @Directive({selector: '[super-dir]'}) class SuperDirective { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - bar = ''; + @Input() bar = ''; - @Input() - baz = ''; + @Input() baz = ''; } @Directive({ selector: '[sub-dir]', }) class SubDirective extends SuperDirective { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({template: `

`}) @@ -1209,7 +1272,6 @@ describe('inheritance', () => { expect(subDir.baz).toBe('c'); expect(subDir.qux).toBe('d'); }); - }); describe('outputs', () => { @@ -1223,15 +1285,16 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } @Directive({ selector: '[sub-dir]', }) class SubDirective extends SuperDirective { - ngOnInit() { this.foo.emit('test'); } + ngOnInit() { + this.foo.emit('test'); + } } @Component({ @@ -1242,7 +1305,9 @@ describe('inheritance', () => { class App { foo = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } } TestBed.configureTestingModule({ @@ -1264,11 +1329,9 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } @Directive({ @@ -1307,10 +1370,11 @@ describe('inheritance', () => { }) class SuperDirective { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } @Directive({ @@ -1348,15 +1412,16 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @ContentChildren(ChildDir) - customDirs !: QueryList; + @ContentChildren(ChildDir) customDirs!: QueryList; } @Directive({ selector: '[sub-dir]', }) class SubDirective extends SuperDirective { - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -1376,7 +1441,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(2); + expect(foundQueryList!.length).toBe(2); }); xdescribe( @@ -1416,13 +1481,27 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperSuperDirective { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } class SuperDirective extends SuperSuperDirective {} @@ -1434,7 +1513,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -1473,7 +1554,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -1512,7 +1595,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -1551,7 +1636,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -1590,7 +1677,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -1629,7 +1718,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -1668,7 +1759,9 @@ describe('inheritance', () => { selector: '[subDir]', }) class SubDirective extends SuperDirective { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -1711,27 +1804,22 @@ describe('inheritance', () => { it('should inherit inputs', () => { @Directive({selector: '[super-dir]'}) class SuperSuperDirective { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - baz = ''; + @Input() baz = ''; } class SuperDirective extends SuperSuperDirective { - @Input() - bar = ''; + @Input() bar = ''; } @Directive({ selector: '[sub-dir]', }) class SubDirective extends SuperDirective { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({ @@ -1772,13 +1860,11 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperSuperDirective { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } class SuperDirective extends SuperSuperDirective { - @Output() - bar = new EventEmitter(); + @Output() bar = new EventEmitter(); } @Directive({ @@ -1801,9 +1887,13 @@ describe('inheritance', () => { bar = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } - handleBar(event: string) { this.bar = event; } + handleBar(event: string) { + this.bar = event; + } } TestBed.configureTestingModule({ @@ -1826,13 +1916,11 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperSuperDirective { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; } class SuperDirective extends SuperSuperDirective { - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } @Directive({ @@ -1871,18 +1959,20 @@ describe('inheritance', () => { }) class SuperSuperDirective { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } class SuperDirective extends SuperSuperDirective { @HostBinding('accessKey') - get boundAltKey() { return this.superAccessKey + '???'; } + get boundAltKey() { + return this.superAccessKey + '???'; + } - @Input() - superAccessKey = ''; + @Input() superAccessKey = ''; } @Directive({ @@ -1927,13 +2017,11 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperSuperDirective { - @ContentChildren(ChildDir1) - childDir1s !: QueryList; + @ContentChildren(ChildDir1) childDir1s!: QueryList; } class SuperDirective extends SuperSuperDirective { - @ContentChildren(ChildDir1) - childDir2s !: QueryList; + @ContentChildren(ChildDir1) childDir2s!: QueryList; } @Directive({ @@ -1964,8 +2052,8 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundChildDir1s !.length).toBe(2); - expect(foundChildDir2s !.length).toBe(2); + expect(foundChildDir1s!.length).toBe(2); + expect(foundChildDir2s!.length).toBe(2); }); xdescribe( @@ -2002,13 +2090,27 @@ describe('inheritance', () => { const fired: string[] = []; class SuperComponent { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } beforeEach(() => fired.length = 0); @@ -2016,7 +2118,9 @@ describe('inheritance', () => { it('ngOnInit', () => { @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends SuperComponent { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -2055,7 +2159,9 @@ describe('inheritance', () => { selector: 'my-comp', }) class MyComponent extends SuperComponent { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -2095,7 +2201,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -2135,7 +2243,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -2175,7 +2285,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -2215,7 +2327,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -2255,7 +2369,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -2297,23 +2413,18 @@ describe('inheritance', () => { it('should inherit inputs', () => { class SuperComponent { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - bar = ''; + @Input() bar = ''; - @Input() - baz = ''; + @Input() baz = ''; } @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends SuperComponent { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({template: ``}) @@ -2338,7 +2449,6 @@ describe('inheritance', () => { expect(subDir.baz).toEqual('c'); expect(subDir.qux).toEqual('d'); }); - }); describe('outputs', () => { @@ -2349,8 +2459,7 @@ describe('inheritance', () => { it('should inherit outputs', () => { class SuperComponent { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } @Component({ @@ -2358,7 +2467,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngOnInit() { this.foo.emit('test'); } + ngOnInit() { + this.foo.emit('test'); + } } @Component({ @@ -2369,7 +2480,9 @@ describe('inheritance', () => { class App { foo = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } } TestBed.configureTestingModule({ @@ -2388,11 +2501,9 @@ describe('inheritance', () => { // TODO: sub and super HostBinding same binding on two different properties it('should compose host bindings for styles', () => { class SuperComponent { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } @Component({ @@ -2429,10 +2540,11 @@ describe('inheritance', () => { it('should compose host bindings (non-style related)', () => { class SuperComponent { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } @Component({ @@ -2468,13 +2580,14 @@ describe('inheritance', () => { } class SuperComponent { - @ContentChildren(ChildDir) - customDirs !: QueryList; + @ContentChildren(ChildDir) customDirs!: QueryList; } @Component({selector: 'my-comp', template: `
`}) class MyComponent extends SuperComponent { - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -2494,7 +2607,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(2); + expect(foundQueryList!.length).toBe(2); }); xdescribe( @@ -2534,13 +2647,27 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } beforeEach(() => fired.length = 0); @@ -2548,7 +2675,9 @@ describe('inheritance', () => { it('ngOnInit', () => { @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends SuperDirective { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -2588,7 +2717,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperDirective { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -2628,7 +2759,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperDirective { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -2668,7 +2801,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperDirective { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -2708,7 +2843,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperDirective { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -2748,7 +2885,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperDirective { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -2788,7 +2927,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperDirective { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -2833,23 +2974,18 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - bar = ''; + @Input() bar = ''; - @Input() - baz = ''; + @Input() baz = ''; } @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends SuperDirective { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({template: ``}) @@ -2887,8 +3023,7 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } @Component({ @@ -2896,7 +3031,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperDirective { - ngOnInit() { this.foo.emit('test'); } + ngOnInit() { + this.foo.emit('test'); + } } @Component({ @@ -2907,7 +3044,9 @@ describe('inheritance', () => { class App { foo = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } } TestBed.configureTestingModule({ @@ -2929,11 +3068,9 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } @Component({ @@ -2973,10 +3110,11 @@ describe('inheritance', () => { }) class SuperDirective { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } @Component({ @@ -3015,13 +3153,14 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @ContentChildren(ChildDir) - customDirs !: QueryList; + @ContentChildren(ChildDir) customDirs!: QueryList; } @Component({selector: 'my-comp', template: `
`}) class MyComponent extends SuperDirective { - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -3041,7 +3180,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(2); + expect(foundQueryList!.length).toBe(2); }); it('should inherit ViewChildren queries', () => { @@ -3055,8 +3194,7 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @ViewChildren(ChildDir) - customDirs !: QueryList; + @ViewChildren(ChildDir) customDirs!: QueryList; } @Component({ @@ -3069,7 +3207,9 @@ describe('inheritance', () => { }) class MyComponent extends SuperDirective { items = [1, 2, 3, 4, 5]; - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -3086,7 +3226,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(5); + expect(foundQueryList!.length).toBe(5); }); xdescribe( @@ -3126,13 +3266,27 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } class BareClass extends SuperDirective {} @@ -3142,7 +3296,9 @@ describe('inheritance', () => { it('ngOnInit', () => { @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends BareClass { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -3181,7 +3337,9 @@ describe('inheritance', () => { selector: 'my-comp', }) class MyComponent extends BareClass { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -3221,7 +3379,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends BareClass { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -3261,7 +3421,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends BareClass { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -3301,7 +3463,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends BareClass { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -3341,7 +3505,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends BareClass { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -3381,7 +3547,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends BareClass { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -3426,25 +3594,20 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - baz = ''; + @Input() baz = ''; } class BareClass extends SuperDirective { - @Input() - bar = ''; + @Input() bar = ''; } @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends BareClass { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({template: ``}) @@ -3482,8 +3645,7 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } class BareClass extends SuperDirective {} @@ -3493,7 +3655,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends BareClass { - ngOnInit() { this.foo.emit('test'); } + ngOnInit() { + this.foo.emit('test'); + } } @Component({ @@ -3504,7 +3668,9 @@ describe('inheritance', () => { class App { foo = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } } TestBed.configureTestingModule({ @@ -3526,11 +3692,9 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } class BareClass extends SuperDirective {} @@ -3572,18 +3736,20 @@ describe('inheritance', () => { }) class SuperDirective { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } class BareClass extends SuperDirective { @HostBinding('accessKey') - get boundAccessKey() { return this.superAccessKey + '???'; } + get boundAccessKey() { + return this.superAccessKey + '???'; + } - @Input() - superAccessKey = ''; + @Input() superAccessKey = ''; } @Component({ @@ -3623,8 +3789,7 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @ContentChildren(ChildDir) - customDirs !: QueryList; + @ContentChildren(ChildDir) customDirs!: QueryList; } class BareClass extends SuperDirective {} @@ -3634,7 +3799,9 @@ describe('inheritance', () => { template: `
`, }) class MyComponent extends BareClass { - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -3654,7 +3821,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(2); + expect(foundQueryList!.length).toBe(2); }); it('should inherit ViewChildren queries', () => { @@ -3668,8 +3835,7 @@ describe('inheritance', () => { selector: '[super-dir]', }) class SuperDirective { - @ViewChildren(ChildDir) - customDirs !: QueryList; + @ViewChildren(ChildDir) customDirs!: QueryList; } class BareClass extends SuperDirective {} @@ -3684,7 +3850,9 @@ describe('inheritance', () => { }) class MyComponent extends BareClass { items = [1, 2, 3, 4, 5]; - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -3701,7 +3869,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(5); + expect(foundQueryList!.length).toBe(5); }); xdescribe( @@ -3742,13 +3910,27 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } beforeEach(() => fired.length = 0); @@ -3759,7 +3941,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -3799,7 +3983,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -3839,7 +4025,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -3879,7 +4067,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -3919,7 +4109,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -3959,7 +4151,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -3999,7 +4193,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -4045,23 +4241,18 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - bar = ''; + @Input() bar = ''; - @Input() - baz = ''; + @Input() baz = ''; } @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends SuperComponent { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({template: ``}) @@ -4100,8 +4291,7 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } @Component({ @@ -4109,7 +4299,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngOnInit() { this.foo.emit('test'); } + ngOnInit() { + this.foo.emit('test'); + } } @Component({ @@ -4120,7 +4312,9 @@ describe('inheritance', () => { class App { foo = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } } TestBed.configureTestingModule({ @@ -4236,11 +4430,9 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } @Component({ @@ -4281,10 +4473,11 @@ describe('inheritance', () => { }) class SuperComponent { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } @Component({ @@ -4324,8 +4517,7 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - @ContentChildren(ChildDir) - customDirs !: QueryList; + @ContentChildren(ChildDir) customDirs!: QueryList; } @Component({ @@ -4333,7 +4525,9 @@ describe('inheritance', () => { template: `
`, }) class MyComponent extends SuperComponent { - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -4353,7 +4547,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(2); + expect(foundQueryList!.length).toBe(2); }); it('should inherit ViewChildren queries', () => { @@ -4368,8 +4562,7 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - @ViewChildren(ChildDir) - customDirs !: QueryList; + @ViewChildren(ChildDir) customDirs!: QueryList; } @Component({ @@ -4382,7 +4575,9 @@ describe('inheritance', () => { }) class MyComponent extends SuperComponent { items = [1, 2, 3, 4, 5]; - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -4399,7 +4594,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(5); + expect(foundQueryList!.length).toBe(5); }); it('should inherit host listeners from base class once', () => { @@ -4411,7 +4606,9 @@ describe('inheritance', () => { }) class BaseComponent { @HostListener('click') - clicked() { events.push('BaseComponent.clicked'); } + clicked() { + events.push('BaseComponent.clicked'); + } } @Component({ @@ -4423,9 +4620,12 @@ describe('inheritance', () => { // component def, which would trigger `hostBindings` functions merge operation in // InheritDefinitionFeature logic (merging Child and Base host binding functions) @HostListener('focus') - focused() {} + focused() { + } - clicked() { events.push('ChildComponent.clicked'); } + clicked() { + events.push('ChildComponent.clicked'); + } } @Component({ @@ -4437,9 +4637,12 @@ describe('inheritance', () => { // component def, which would trigger `hostBindings` functions merge operation in // InheritDefinitionFeature logic (merging GrandChild and Child host binding functions) @HostListener('blur') - blurred() {} + blurred() { + } - clicked() { events.push('GrandChildComponent.clicked'); } + clicked() { + events.push('GrandChildComponent.clicked'); + } } @Component({ @@ -4505,13 +4708,27 @@ describe('inheritance', () => { template: `

super

`, }) class SuperSuperComponent { - ngOnInit() { fired.push('super init'); } - ngOnDestroy() { fired.push('super destroy'); } - ngAfterContentInit() { fired.push('super after content init'); } - ngAfterContentChecked() { fired.push('super after content checked'); } - ngAfterViewInit() { fired.push('super after view init'); } - ngAfterViewChecked() { fired.push('super after view checked'); } - ngDoCheck() { fired.push('super do check'); } + ngOnInit() { + fired.push('super init'); + } + ngOnDestroy() { + fired.push('super destroy'); + } + ngAfterContentInit() { + fired.push('super after content init'); + } + ngAfterContentChecked() { + fired.push('super after content checked'); + } + ngAfterViewInit() { + fired.push('super after view init'); + } + ngAfterViewChecked() { + fired.push('super after view checked'); + } + ngDoCheck() { + fired.push('super do check'); + } } class SuperComponent extends SuperSuperComponent {} @@ -4524,7 +4741,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngOnInit() { fired.push('sub init'); } + ngOnInit() { + fired.push('sub init'); + } } @Component({ @@ -4564,7 +4783,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngDoCheck() { fired.push('sub do check'); } + ngDoCheck() { + fired.push('sub do check'); + } } @Component({ @@ -4604,7 +4825,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterContentInit() { fired.push('sub after content init'); } + ngAfterContentInit() { + fired.push('sub after content init'); + } } @Component({ @@ -4644,7 +4867,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterContentChecked() { fired.push('sub after content checked'); } + ngAfterContentChecked() { + fired.push('sub after content checked'); + } } @Component({ @@ -4684,7 +4909,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterViewInit() { fired.push('sub after view init'); } + ngAfterViewInit() { + fired.push('sub after view init'); + } } @Component({ @@ -4724,7 +4951,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngAfterViewChecked() { fired.push('sub after view checked'); } + ngAfterViewChecked() { + fired.push('sub after view checked'); + } } @Component({ @@ -4764,7 +4993,9 @@ describe('inheritance', () => { template: `

test

`, }) class MyComponent extends SuperComponent { - ngOnDestroy() { fired.push('sub destroy'); } + ngOnDestroy() { + fired.push('sub destroy'); + } } @Component({ @@ -4810,25 +5041,20 @@ describe('inheritance', () => { template: `

super

`, }) class SuperSuperComponent { - @Input() - foo = ''; + @Input() foo = ''; - @Input() - baz = ''; + @Input() baz = ''; } class BareClass extends SuperSuperComponent { - @Input() - bar = ''; + @Input() bar = ''; } @Component({selector: 'my-comp', template: `

test

`}) class MyComponent extends BareClass { - @Input() - baz = ''; + @Input() baz = ''; - @Input() - qux = ''; + @Input() qux = ''; } @Component({template: ``}) @@ -4867,13 +5093,11 @@ describe('inheritance', () => { template: `

super

`, }) class SuperSuperComponent { - @Output() - foo = new EventEmitter(); + @Output() foo = new EventEmitter(); } class SuperComponent extends SuperSuperComponent { - @Output() - bar = new EventEmitter(); + @Output() bar = new EventEmitter(); } @Component({ @@ -4895,11 +5119,15 @@ describe('inheritance', () => { class App { foo = ''; - handleFoo(event: string) { this.foo = event; } + handleFoo(event: string) { + this.foo = event; + } bar = ''; - handleBar(event: string) { this.bar = event; } + handleBar(event: string) { + this.bar = event; + } } TestBed.configureTestingModule({ @@ -4987,13 +5215,11 @@ describe('inheritance', () => { template: `

super

`, }) class SuperSuperComponent { - @HostBinding('style.color') - color = 'red'; + @HostBinding('style.color') color = 'red'; } class SuperComponent extends SuperSuperComponent { - @HostBinding('style.backgroundColor') - bg = 'black'; + @HostBinding('style.backgroundColor') bg = 'black'; } @Component({ @@ -5034,18 +5260,20 @@ describe('inheritance', () => { }) class SuperSuperComponent { @HostBinding('title') - get boundTitle() { return this.superTitle + '!!!'; } + get boundTitle() { + return this.superTitle + '!!!'; + } - @Input() - superTitle = ''; + @Input() superTitle = ''; } class SuperComponent extends SuperSuperComponent { @HostBinding('accessKey') - get boundAccessKey() { return this.superAccessKey + '???'; } + get boundAccessKey() { + return this.superAccessKey + '???'; + } - @Input() - superAccessKey = ''; + @Input() superAccessKey = ''; } @Component({ @@ -5087,8 +5315,7 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - @ContentChildren(ChildDir) - customDirs !: QueryList; + @ContentChildren(ChildDir) customDirs!: QueryList; } @Component({ @@ -5096,7 +5323,9 @@ describe('inheritance', () => { template: `
`, }) class MyComponent extends SuperComponent { - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -5116,7 +5345,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(2); + expect(foundQueryList!.length).toBe(2); }); it('should inherit ViewChildren queries', () => { @@ -5131,8 +5360,7 @@ describe('inheritance', () => { template: `

super

`, }) class SuperComponent { - @ViewChildren(ChildDir) - customDirs !: QueryList; + @ViewChildren(ChildDir) customDirs!: QueryList; } @Component({ @@ -5145,7 +5373,9 @@ describe('inheritance', () => { }) class MyComponent extends SuperComponent { items = [1, 2, 3, 4, 5]; - ngAfterViewInit() { foundQueryList = this.customDirs; } + ngAfterViewInit() { + foundQueryList = this.customDirs; + } } @Component({ @@ -5162,7 +5392,7 @@ describe('inheritance', () => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); - expect(foundQueryList !.length).toBe(5); + expect(foundQueryList!.length).toBe(5); }); xdescribe( diff --git a/packages/core/test/acceptance/integration_spec.ts b/packages/core/test/acceptance/integration_spec.ts index d53825871c82b..164550bdf5ca0 100644 --- a/packages/core/test/acceptance/integration_spec.ts +++ b/packages/core/test/acceptance/integration_spec.ts @@ -16,10 +16,11 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; import {ivyEnabled, onlyInIvy} from '@angular/private/testing'; describe('acceptance integration tests', () => { - function stripHtmlComments(str: string) { return str.replace(//g, ''); } + function stripHtmlComments(str: string) { + return str.replace(//g, ''); + } describe('render', () => { - it('should render basic template', () => { @Component({template: 'Greetings'}) class App { @@ -64,12 +65,10 @@ describe('acceptance integration tests', () => { tView: 2, tNode: 4, }); - }); }); describe('ng-container', () => { - it('should insert as a child of a regular element', () => { @Component( {template: '
before|Greetings|after
'}) @@ -108,7 +107,6 @@ describe('acceptance integration tests', () => { }); it('should add and remove DOM nodes when ng-container is a child of an embedded view', () => { - @Component({template: 'content'}) class App { render = false; @@ -131,21 +129,24 @@ describe('acceptance integration tests', () => { // https://stackblitz.com/edit/angular-tfhcz1?file=src%2Fapp%2Fapp.component.ts it('should add and remove DOM nodes when ng-container is a child of a delayed embedded view', () => { - @Directive({selector: '[testDirective]'}) class TestDirective { constructor(private _tplRef: TemplateRef, private _vcRef: ViewContainerRef) {} - createAndInsert() { this._vcRef.insert(this._tplRef.createEmbeddedView({})); } + createAndInsert() { + this._vcRef.insert(this._tplRef.createEmbeddedView({})); + } - clear() { this._vcRef.clear(); } + clear() { + this._vcRef.clear(); + } } @Component({ template: 'content' }) class App { - @ViewChild(TestDirective, {static: true}) testDirective !: TestDirective; + @ViewChild(TestDirective, {static: true}) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); @@ -205,9 +206,13 @@ describe('acceptance integration tests', () => { class TestDirective { constructor(private _tplRef: TemplateRef, private _vcRef: ViewContainerRef) {} - createAndInsert() { this._vcRef.insert(this._tplRef.createEmbeddedView({})); } + createAndInsert() { + this._vcRef.insert(this._tplRef.createEmbeddedView({})); + } - clear() { this._vcRef.clear(); } + clear() { + this._vcRef.clear(); + } } @Component({ @@ -215,7 +220,7 @@ describe('acceptance integration tests', () => { 'content' }) class App { - @ViewChild(TestDirective, {static: true}) testDirective !: TestDirective; + @ViewChild(TestDirective, {static: true}) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); @@ -245,7 +250,7 @@ describe('acceptance integration tests', () => { @Component({template: '
'}) class App { - @ViewChild(TestDirective) testDirective !: TestDirective; + @ViewChild(TestDirective) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); @@ -260,14 +265,17 @@ describe('acceptance integration tests', () => { it('should support ViewContainerRef when ng-container is at the root of a view', () => { @Directive({selector: '[dir]'}) class TestDirective { - @Input() - contentTpl: TemplateRef<{}>|null = null; + @Input() contentTpl: TemplateRef<{}>|null = null; constructor(private _vcRef: ViewContainerRef) {} - insertView() { this._vcRef.createEmbeddedView(this.contentTpl as TemplateRef<{}>); } + insertView() { + this._vcRef.createEmbeddedView(this.contentTpl as TemplateRef<{}>); + } - clear() { this._vcRef.clear(); } + clear() { + this._vcRef.clear(); + } } @Component({ @@ -275,7 +283,7 @@ describe('acceptance integration tests', () => { 'Content' }) class App { - @ViewChild(TestDirective) testDirective !: TestDirective; + @ViewChild(TestDirective) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); @@ -298,14 +306,18 @@ describe('acceptance integration tests', () => { class TestDirective { constructor(private _tplRef: TemplateRef<{}>, private _vcRef: ViewContainerRef) {} - insertView() { this._vcRef.createEmbeddedView(this._tplRef); } + insertView() { + this._vcRef.createEmbeddedView(this._tplRef); + } - clear() { this._vcRef.clear(); } + clear() { + this._vcRef.clear(); + } } @Component({template: 'Content'}) class App { - @ViewChild(TestDirective) testDirective !: TestDirective; + @ViewChild(TestDirective) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); @@ -334,7 +346,6 @@ describe('acceptance integration tests', () => { expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual('
'); }); - }); describe('text bindings', () => { @@ -373,11 +384,12 @@ describe('acceptance integration tests', () => { expect(fixture.nativeElement.innerHTML).toEqual(''); }); - }); describe('ngNonBindable handling', () => { - function stripNgNonBindable(str: string) { return str.replace(/ ngnonbindable=""/i, ''); } + function stripNgNonBindable(str: string) { + return str.replace(/ ngnonbindable=""/i, ''); + } it('should keep local ref for host element', () => { @Component({ @@ -404,7 +416,9 @@ describe('acceptance integration tests', () => { @Directive({selector: '[directive]'}) class TestDirective implements OnInit { - ngOnInit() { directiveInvoked = true; } + ngOnInit() { + directiveInvoked = true; + } } @Component({ @@ -432,7 +446,9 @@ describe('acceptance integration tests', () => { @Directive({selector: '[directive]'}) class TestDirective implements OnInit { - ngOnInit() { directiveInvoked = true; } + ngOnInit() { + directiveInvoked = true; + } } @Component({ @@ -604,14 +620,12 @@ describe('acceptance integration tests', () => { it('should support a component with binding on host element', () => { @Component({selector: 'todo', template: '{{title}}'}) class TodoComponentHostBinding { - @HostBinding() - title = 'one'; + @HostBinding() title = 'one'; } @Component({template: ''}) class App { - @ViewChild(TodoComponentHostBinding) - todoComponentHostBinding !: TodoComponentHostBinding; + @ViewChild(TodoComponentHostBinding) todoComponentHostBinding!: TodoComponentHostBinding; } TestBed.configureTestingModule({declarations: [App, TodoComponentHostBinding]}); @@ -658,8 +672,7 @@ describe('acceptance integration tests', () => { it('should support a component with sub-views', () => { @Component({selector: 'comp', template: '
text
'}) class MyComp { - @Input() - condition !: boolean; + @Input() condition!: boolean; } @Component({template: ''}) @@ -680,7 +693,6 @@ describe('acceptance integration tests', () => { fixture.detectChanges(); expect(stripHtmlComments(compElement.innerHTML)).toEqual(''); }); - }); describe('element bindings', () => { @@ -814,7 +826,7 @@ describe('acceptance integration tests', () => { fixture.detectChanges(); const span: HTMLSpanElement = fixture.nativeElement.querySelector('span'); - const bold: HTMLElement = span.querySelector('b') !; + const bold: HTMLElement = span.querySelector('b')!; fixture.componentInstance.title = 'Hello'; fixture.detectChanges(); @@ -840,13 +852,12 @@ describe('acceptance integration tests', () => { it('should support host attribute bindings', () => { @Directive({selector: '[hostBindingDir]'}) class HostBindingDir { - @HostBinding('attr.aria-label') - label = 'some label'; + @HostBinding('attr.aria-label') label = 'some label'; } @Component({template: '
'}) class App { - @ViewChild(HostBindingDir) hostBindingDir !: HostBindingDir; + @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, HostBindingDir]}); @@ -999,12 +1010,13 @@ describe('acceptance integration tests', () => { it('should apply classes properly when nodes have containers', () => { @Component({selector: 'structural-comp', template: 'Comp Content'}) class StructuralComp { - @Input() - tmp !: TemplateRef; + @Input() tmp!: TemplateRef; constructor(public vcr: ViewContainerRef) {} - create() { this.vcr.createEmbeddedView(this.tmp); } + create() { + this.vcr.createEmbeddedView(this.tmp); + } } @Component({ @@ -1014,7 +1026,7 @@ describe('acceptance integration tests', () => { ` }) class App { - @ViewChild(StructuralComp) structuralComp !: StructuralComp; + @ViewChild(StructuralComp) structuralComp!: StructuralComp; value: any; } @@ -1040,7 +1052,9 @@ describe('acceptance integration tests', () => { public classesVal: string = ''; @Input('class') - set klass(value: string) { this.classesVal = value; } + set klass(value: string) { + this.classesVal = value; + } } @Directive({selector: '[DirWithStyle]'}) @@ -1048,15 +1062,16 @@ describe('acceptance integration tests', () => { public stylesVal: any = ''; @Input() - set style(value: any) { this.stylesVal = value; } + set style(value: any) { + this.stylesVal = value; + } } it('should delegate initial classes to a [class] input binding if present on a directive on the same element', () => { @Component({template: '
'}) class App { - @ViewChild(DirWithClassDirective) - mockClassDirective !: DirWithClassDirective; + @ViewChild(DirWithClassDirective) mockClassDirective!: DirWithClassDirective; } TestBed.configureTestingModule({declarations: [App, DirWithClassDirective]}); @@ -1073,8 +1088,7 @@ describe('acceptance integration tests', () => { () => { @Component({template: '
'}) class App { - @ViewChild(DirWithStyleDirective) - mockStyleDirective !: DirWithStyleDirective; + @ViewChild(DirWithStyleDirective) mockStyleDirective!: DirWithStyleDirective; } TestBed.configureTestingModule({declarations: [App, DirWithStyleDirective]}); @@ -1092,8 +1106,7 @@ describe('acceptance integration tests', () => { () => { @Component({template: '
'}) class App { - @ViewChild(DirWithClassDirective) - mockClassDirective !: DirWithClassDirective; + @ViewChild(DirWithClassDirective) mockClassDirective!: DirWithClassDirective; value = ''; } @@ -1111,9 +1124,8 @@ describe('acceptance integration tests', () => { () => { @Component({template: '
'}) class App { - @ViewChild(DirWithStyleDirective) - mockStyleDirective !: DirWithStyleDirective; - value !: {[key: string]: string}; + @ViewChild(DirWithStyleDirective) mockStyleDirective!: DirWithStyleDirective; + value!: {[key: string]: string}; } TestBed.configureTestingModule({declarations: [App, DirWithStyleDirective]}); @@ -1155,7 +1167,7 @@ describe('acceptance integration tests', () => { fixture.detectChanges(); const target: HTMLDivElement = fixture.nativeElement.querySelector('div'); - const classes = target.getAttribute('class') !.split(/\s+/).sort(); + const classes = target.getAttribute('class')!.split(/\s+/).sort(); expect(classes).toEqual(['big', 'golden', 'heavy']); expect(target.getAttribute('title')).toEqual('foo'); @@ -1189,7 +1201,7 @@ describe('acceptance integration tests', () => { }) class App { @ViewChild(DirWithSingleStylingBindings) - dirInstance !: DirWithSingleStylingBindings; + dirInstance!: DirWithSingleStylingBindings; } TestBed.configureTestingModule({declarations: [App, DirWithSingleStylingBindings]}); @@ -1244,8 +1256,8 @@ describe('acceptance integration tests', () => { @Component( {template: '
'}) class App { - @ViewChild(Dir1WithStyle) dir1Instance !: Dir1WithStyle; - @ViewChild(Dir2WithStyle) dir2Instance !: Dir2WithStyle; + @ViewChild(Dir1WithStyle) dir1Instance!: Dir1WithStyle; + @ViewChild(Dir2WithStyle) dir2Instance!: Dir2WithStyle; width: string|null|undefined = undefined; } @@ -1309,8 +1321,8 @@ describe('acceptance integration tests', () => { '
' }) class App { - @ViewChild(Dir1WithStyling) dir1Instance !: Dir1WithStyling; - @ViewChild(Dir2WithStyling) dir2Instance !: Dir2WithStyling; + @ViewChild(Dir1WithStyling) dir1Instance!: Dir1WithStyling; + @ViewChild(Dir2WithStyling) dir2Instance!: Dir2WithStyling; stylesExp: any = {}; classesExp: any = {}; } @@ -1321,7 +1333,7 @@ describe('acceptance integration tests', () => { fixture.detectChanges(); const {dir1Instance, dir2Instance} = fixture.componentInstance; - const target = fixture.nativeElement.querySelector('div') !; + const target = fixture.nativeElement.querySelector('div')!; expect(target.style.getPropertyValue('width')).toEqual('111px'); const compInstance = fixture.componentInstance; @@ -1393,7 +1405,7 @@ describe('acceptance integration tests', () => { TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); - const target = fixture.nativeElement.querySelector('div') !; + const target = fixture.nativeElement.querySelector('div')!; expect(target.classList.contains('-fred-36-')).toBeFalsy(); @@ -1510,7 +1522,6 @@ describe('acceptance integration tests', () => { // The ViewEngine error has a typo, whereas the Ivy one fixes it. /^Unexpected value 'SomeModule' imported by the module 'ModuleWithImportedModule'\. Please add (a|an) @NgModule annotation\.$/); }); - }); it('should only call inherited host listeners once', () => { @@ -1519,7 +1530,9 @@ describe('acceptance integration tests', () => { @Component({template: ''}) class ButtonSuperClass { @HostListener('click') - clicked() { clicks++; } + clicked() { + clicks++; + } } @Component({selector: 'button[custom-button]', template: ''}) @@ -1548,7 +1561,7 @@ describe('acceptance integration tests', () => { @Component({template: '
'}) class SuperComp { - @ViewChildren(SomeDir) dirs !: QueryList; + @ViewChildren(SomeDir) dirs!: QueryList; } @Component({selector: 'button[custom-button]', template: '
'}) @@ -1576,7 +1589,9 @@ describe('acceptance integration tests', () => { private _isDestroyed = false; @Input() - get value() { return this._value; } + get value() { + return this._value; + } set value(newValue: any) { if (this._isDestroyed) { throw Error('Cannot assign to value after destroy.'); @@ -1586,7 +1601,9 @@ describe('acceptance integration tests', () => { } private _value: any; - ngOnDestroy() { this._isDestroyed = true; } + ngOnDestroy() { + this._isDestroyed = true; + } } @Component({template: '
'}) @@ -1608,7 +1625,7 @@ describe('acceptance integration tests', () => { @Component( {selector: 'test-component', template: `foo`, host: {'[attr.aria-disabled]': 'true'}}) class TestComponent { - @ContentChild(TemplateRef, {static: true}) tpl !: TemplateRef; + @ContentChild(TemplateRef, {static: true}) tpl!: TemplateRef; } TestBed.configureTestingModule({declarations: [TestComponent]}); @@ -1621,7 +1638,7 @@ describe('acceptance integration tests', () => { it('should inherit inputs from undecorated superclasses', () => { class ButtonSuperClass { - @Input() isDisabled !: boolean; + @Input() isDisabled!: boolean; } @Component({selector: 'button[custom-button]', template: ''}) @@ -1651,7 +1668,9 @@ describe('acceptance integration tests', () => { class ButtonSuperClass { @Output() clicked = new EventEmitter(); - emitClick() { this.clicked.emit(); } + emitClick() { + this.clicked.emit(); + } } @Component({selector: 'button[custom-button]', template: ''}) @@ -1660,7 +1679,9 @@ describe('acceptance integration tests', () => { @Component({template: ''}) class MyApp { - handleClick() { clicks++; } + handleClick() { + clicks++; + } } TestBed.configureTestingModule({declarations: [MyApp, ButtonSubClass]}); @@ -1675,8 +1696,7 @@ describe('acceptance integration tests', () => { it('should inherit host bindings from undecorated superclasses', () => { class BaseButton { - @HostBinding('attr.tabindex') - tabindex = -1; + @HostBinding('attr.tabindex') tabindex = -1; } @Component({selector: '[sub-button]', template: ''}) @@ -1702,8 +1722,7 @@ describe('acceptance integration tests', () => { it('should inherit host bindings from undecorated grand superclasses', () => { class SuperBaseButton { - @HostBinding('attr.tabindex') - tabindex = -1; + @HostBinding('attr.tabindex') tabindex = -1; } class BaseButton extends SuperBaseButton {} @@ -1734,7 +1753,9 @@ describe('acceptance integration tests', () => { class BaseButton { @HostListener('click') - handleClick() { clicks++; } + handleClick() { + clicks++; + } } @Component({selector: '[sub-button]', template: ''}) @@ -1761,7 +1782,9 @@ describe('acceptance integration tests', () => { @Directive({selector: '[baseButton]'}) class BaseButton { @HostListener('click') - handleClick() { clicks++; } + handleClick() { + clicks++; + } } @Component({selector: '[subButton]', template: ''}) @@ -1788,7 +1811,9 @@ describe('acceptance integration tests', () => { @Directive({selector: '[superBaseButton]'}) class SuperBaseButton { @HostListener('click') - handleClick() { clicks++; } + handleClick() { + clicks++; + } } @Directive({selector: '[baseButton]'}) @@ -1819,7 +1844,9 @@ describe('acceptance integration tests', () => { @Directive({selector: '[superSuperBaseButton]'}) class SuperSuperBaseButton { @HostListener('click') - handleClick() { clicks++; } + handleClick() { + clicks++; + } } @Directive({selector: '[superBaseButton]'}) @@ -1855,9 +1882,13 @@ describe('acceptance integration tests', () => { inputs: ['dir'], }) class Dir { - get dir(): any { return null; } + get dir(): any { + return null; + } - set dir(value: any) { throw new Error('this error is expected'); } + set dir(value: any) { + throw new Error('this error is expected'); + } } @Component({ @@ -1919,7 +1950,7 @@ describe('acceptance integration tests', () => { }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(false); - const element = fixture.nativeElement.querySelector('div') !; + const element = fixture.nativeElement.querySelector('div')!; assertAttrValues(element, 'first-update-pass'); diff --git a/packages/core/test/acceptance/lifecycle_spec.ts b/packages/core/test/acceptance/lifecycle_spec.ts index ebfd9aa7f882a..ebccdf3fe4c4e 100644 --- a/packages/core/test/acceptance/lifecycle_spec.ts +++ b/packages/core/test/acceptance/lifecycle_spec.ts @@ -69,13 +69,13 @@ describe('onChanges', () => { template: `

test

`, }) class Comp { - @Input() - val1 = 'a'; + @Input() val1 = 'a'; - @Input('publicVal2') - val2 = 'b'; + @Input('publicVal2') val2 = 'b'; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'comp', changes}); + } } @Component({template: ``}) @@ -122,10 +122,11 @@ describe('onChanges', () => { template: ``, }) class Parent { - @Input() - val = ''; + @Input() val = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'parent', changes}); + } } @Component({ @@ -133,10 +134,11 @@ describe('onChanges', () => { template: `

test

`, }) class Child { - @Input() - val = ''; + @Input() val = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'child', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'child', changes}); + } } @Component({template: ``}) @@ -193,13 +195,13 @@ describe('onChanges', () => { template: ``, }) class Parent { - @Input() - val = ''; + @Input() val = ''; - @Input() - name = ''; + @Input() name = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent ' + this.name, changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'parent ' + this.name, changes}); + } } @Component({ @@ -207,13 +209,13 @@ describe('onChanges', () => { template: `

test

`, }) class Child { - @Input() - val = ''; + @Input() val = ''; - @Input() - name = ''; + @Input() name = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'child ' + this.name, changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'child ' + this.name, changes}); + } } @Component({ @@ -303,10 +305,11 @@ describe('onChanges', () => { template: `

{{val}}

`, }) class Comp { - @Input() - val = ''; + @Input() val = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'comp', changes}); + } } @Component({template: ``}) @@ -355,10 +358,11 @@ describe('onChanges', () => { template: `

{{val}}

`, }) class Projected { - @Input() - val = ''; + @Input() val = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'projected', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'projected', changes}); + } } @Component({ @@ -366,10 +370,11 @@ describe('onChanges', () => { template: `
`, }) class Comp { - @Input() - val = ''; + @Input() val = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'comp', changes}); + } } @Component({ @@ -427,11 +432,9 @@ describe('onChanges', () => { template: `

{{val}}

`, }) class Projected { - @Input() - val = ''; + @Input() val = ''; - @Input() - name = ''; + @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'projected ' + this.name, changes}); @@ -443,13 +446,13 @@ describe('onChanges', () => { template: `
`, }) class Comp { - @Input() - val = ''; + @Input() val = ''; - @Input() - name = ''; + @Input() name = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp ' + this.name, changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'comp ' + this.name, changes}); + } } @Component({ @@ -542,10 +545,11 @@ describe('onChanges', () => { selector: '[dir]', }) class Dir { - @Input() - dir = ''; + @Input() dir = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'dir', changes}); + } } @Component({ @@ -553,10 +557,11 @@ describe('onChanges', () => { template: `

{{val}}

`, }) class Comp { - @Input() - val = ''; + @Input() val = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'comp', changes}); + } } @Component({ @@ -608,17 +613,17 @@ describe('onChanges', () => { }); it('should be called on directives before component if component injects directives', () => { - const events: any[] = []; @Directive({ selector: '[dir]', }) class Dir { - @Input() - dir = ''; + @Input() dir = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'dir', changes}); + } } @Component({ @@ -626,12 +631,13 @@ describe('onChanges', () => { template: `

{{val}}

`, }) class Comp { - @Input() - val = ''; + @Input() val = ''; constructor(public dir: Dir) {} - ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'comp', changes}); + } } @Component({ @@ -680,33 +686,33 @@ describe('onChanges', () => { } } ]); - }); it('should be called on multiple directives in injection order', () => { - const events: any[] = []; @Directive({ selector: '[dir]', }) class Dir { - @Input() - dir = ''; + @Input() dir = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'dir', changes}); + } } @Directive({ selector: '[injectionDir]', }) class InjectionDir { - @Input() - injectionDir = ''; + @Input() injectionDir = ''; constructor(public dir: Dir) {} - ngOnChanges(changes: SimpleChanges) { events.push({name: 'injectionDir', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'injectionDir', changes}); + } } @Component({ @@ -746,13 +752,13 @@ describe('onChanges', () => { selector: '[dir]', }) class Dir { - @Input() - dir = ''; + @Input() dir = ''; - @Input('dir-val') - val = ''; + @Input('dir-val') val = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'dir', changes}); + } } @Component({template: `
`}) @@ -796,13 +802,13 @@ describe('onChanges', () => { template: `

{{val}}

`, }) class Comp { - @Input() - val = ''; + @Input() val = ''; - @Input() - name = ''; + @Input() name = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp ' + this.name, changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'comp ' + this.name, changes}); + } } @Component({ @@ -909,11 +915,9 @@ describe('onChanges', () => { template: `

{{val}}

`, }) class Child { - @Input() - val = ''; + @Input() val = ''; - @Input() - name = ''; + @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'child of parent ' + this.name, changes}); @@ -925,13 +929,13 @@ describe('onChanges', () => { template: ``, }) class Parent { - @Input() - val = ''; + @Input() val = ''; - @Input() - name = ''; + @Input() name = ''; - ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent ' + this.name, changes}); } + ngOnChanges(changes: SimpleChanges) { + events.push({name: 'parent ' + this.name, changes}); + } } @Component({ @@ -1100,7 +1104,9 @@ describe('onChanges', () => { @Component({template: `

{{value}}

`}) class App { value = 'a'; - ngOnChanges(changes: SimpleChanges) { events.push(changes); } + ngOnChanges(changes: SimpleChanges) { + events.push(changes); + } } TestBed.configureTestingModule({ @@ -1125,15 +1131,31 @@ it('should call all hooks in correct order when several directives on same node' id: number = -1; /** @internal */ - private _log(hook: string, id: number) { log.push(hook + id); } - - ngOnChanges() { this._log('onChanges', this.id); } - ngOnInit() { this._log('onInit', this.id); } - ngDoCheck() { this._log('doCheck', this.id); } - ngAfterContentInit() { this._log('afterContentInit', this.id); } - ngAfterContentChecked() { this._log('afterContentChecked', this.id); } - ngAfterViewInit() { this._log('afterViewInit', this.id); } - ngAfterViewChecked() { this._log('afterViewChecked', this.id); } + private _log(hook: string, id: number) { + log.push(hook + id); + } + + ngOnChanges() { + this._log('onChanges', this.id); + } + ngOnInit() { + this._log('onInit', this.id); + } + ngDoCheck() { + this._log('doCheck', this.id); + } + ngAfterContentInit() { + this._log('afterContentInit', this.id); + } + ngAfterContentChecked() { + this._log('afterContentChecked', this.id); + } + ngAfterViewInit() { + this._log('afterViewInit', this.id); + } + ngAfterViewChecked() { + this._log('afterViewChecked', this.id); + } } @Directive({selector: 'div'}) @@ -1190,21 +1212,31 @@ it('should call hooks after setting directives inputs', () => { @Directive({selector: 'div'}) class DirA { @Input() a: number = 0; - ngOnInit() { log.push('onInitA' + this.a); } + ngOnInit() { + log.push('onInitA' + this.a); + } } @Directive({selector: 'div'}) class DirB { @Input() b: number = 0; - ngOnInit() { log.push('onInitB' + this.b); } - ngDoCheck() { log.push('doCheckB' + this.b); } + ngOnInit() { + log.push('onInitB' + this.b); + } + ngDoCheck() { + log.push('doCheckB' + this.b); + } } @Directive({selector: 'div'}) class DirC { @Input() c: number = 0; - ngOnInit() { log.push('onInitC' + this.c); } - ngDoCheck() { log.push('doCheckC' + this.c); } + ngOnInit() { + log.push('onInitC' + this.c); + } + ngDoCheck() { + log.push('doCheckC' + this.c); + } } @Component({ @@ -1240,11 +1272,9 @@ describe('onInit', () => { template: `

test

`, }) class MyComponent { - @Input() - input1 = ''; + @Input() input1 = ''; - @Input() - input2 = ''; + @Input() input2 = ''; ngOnInit() { input1Values.push(this.input1); @@ -1285,7 +1315,9 @@ describe('onInit', () => { @Component({template: ``}) class App { - ngOnInit() { onInitCalled++; } + ngOnInit() { + onInitCalled++; + } } TestBed.configureTestingModule({ @@ -1305,14 +1337,18 @@ describe('onInit', () => { template: `

child

`, }) class ChildComp { - ngOnInit() { initCalls.push('child'); } + ngOnInit() { + initCalls.push('child'); + } } @Component({ template: ``, }) class ParentComp { - ngOnInit() { initCalls.push('parent'); } + ngOnInit() { + initCalls.push('parent'); + } } TestBed.configureTestingModule({ @@ -1332,10 +1368,11 @@ describe('onInit', () => { template: `

child

`, }) class ChildComp { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initCalls.push(`child of parent ${this.name}`); } + ngOnInit() { + initCalls.push(`child of parent ${this.name}`); + } } @Component({ @@ -1343,10 +1380,11 @@ describe('onInit', () => { template: ``, }) class ParentComp { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initCalls.push(`parent ${this.name}`); } + ngOnInit() { + initCalls.push(`parent ${this.name}`); + } } @Component({ @@ -1372,7 +1410,9 @@ describe('onInit', () => { @Component({selector: 'my-comp', template: '

test

'}) class MyComp { - ngOnInit() { onInitCalls++; } + ngOnInit() { + onInitCalls++; + } } @Component({ @@ -1407,7 +1447,9 @@ describe('onInit', () => { class MyComp { onInitCalled = false; - ngOnInit() { this.onInitCalled = true; } + ngOnInit() { + this.onInitCalled = true; + } } @Component({ @@ -1425,8 +1467,7 @@ describe('onInit', () => { `, }) class App { - @ViewChild('container', {read: ViewContainerRef}) - viewContainerRef !: ViewContainerRef; + @ViewChild('container', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; constructor(public compFactoryResolver: ComponentFactoryResolver) {} @@ -1464,7 +1505,9 @@ describe('onInit', () => { template: '', }) class Projected { - ngOnInit() { initialized.push('projected'); } + ngOnInit() { + initialized.push('projected'); + } } @Component({ @@ -1472,7 +1515,9 @@ describe('onInit', () => { template: ``, }) class Comp { - ngOnInit() { initialized.push('comp'); } + ngOnInit() { + initialized.push('comp'); + } } @Component({ @@ -1483,7 +1528,9 @@ describe('onInit', () => { ` }) class App { - ngOnInit() { initialized.push('app'); } + ngOnInit() { + initialized.push('app'); + } } TestBed.configureTestingModule({ @@ -1504,10 +1551,11 @@ describe('onInit', () => { template: '', }) class Projected { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initialized.push('projected ' + this.name); } + ngOnInit() { + initialized.push('projected ' + this.name); + } } @Component({ @@ -1515,10 +1563,11 @@ describe('onInit', () => { template: ``, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initialized.push('comp ' + this.name); } + ngOnInit() { + initialized.push('comp ' + this.name); + } } @Component({ @@ -1532,7 +1581,9 @@ describe('onInit', () => { ` }) class App { - ngOnInit() { initialized.push('app'); } + ngOnInit() { + initialized.push('app'); + } } TestBed.configureTestingModule({ @@ -1551,10 +1602,11 @@ describe('onInit', () => { selector: '[dir]', }) class Dir { - @Input('dir-name') - name = ''; + @Input('dir-name') name = ''; - ngOnInit() { initialized.push('dir ' + this.name); } + ngOnInit() { + initialized.push('dir ' + this.name); + } } @Component({ @@ -1562,10 +1614,11 @@ describe('onInit', () => { template: `

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initialized.push('comp ' + this.name); } + ngOnInit() { + initialized.push('comp ' + this.name); + } } @Component({ @@ -1575,7 +1628,9 @@ describe('onInit', () => { ` }) class App { - ngOnInit() { initialized.push('app'); } + ngOnInit() { + initialized.push('app'); + } } TestBed.configureTestingModule({ @@ -1588,29 +1643,30 @@ describe('onInit', () => { }); it('should be called on multiple directives in injection order', () => { - const events: any[] = []; @Directive({ selector: '[dir]', }) class Dir { - @Input() - dir = ''; + @Input() dir = ''; - ngOnInit() { events.push('dir'); } + ngOnInit() { + events.push('dir'); + } } @Directive({ selector: '[injectionDir]', }) class InjectionDir { - @Input() - injectionDir = ''; + @Input() injectionDir = ''; constructor(public dir: Dir) {} - ngOnInit() { events.push('injectionDir'); } + ngOnInit() { + events.push('injectionDir'); + } } @Component({ @@ -1619,7 +1675,9 @@ describe('onInit', () => { class App { val = 'a'; - ngOnInit() { events.push('app'); } + ngOnInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -1638,10 +1696,11 @@ describe('onInit', () => { selector: '[dir]', }) class Dir { - @Input('dir-name') - name = ''; + @Input('dir-name') name = ''; - ngOnInit() { initialized.push('dir ' + this.name); } + ngOnInit() { + initialized.push('dir ' + this.name); + } } @Component({ @@ -1649,12 +1708,13 @@ describe('onInit', () => { template: `

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; constructor(public dir: Dir) {} - ngOnInit() { initialized.push('comp ' + this.name); } + ngOnInit() { + initialized.push('comp ' + this.name); + } } @Component({ @@ -1664,7 +1724,9 @@ describe('onInit', () => { ` }) class App { - ngOnInit() { initialized.push('app'); } + ngOnInit() { + initialized.push('app'); + } } TestBed.configureTestingModule({ @@ -1683,10 +1745,11 @@ describe('onInit', () => { selector: '[dir]', }) class Dir { - @Input('dir-name') - name = ''; + @Input('dir-name') name = ''; - ngOnInit() { initialized.push('dir ' + this.name); } + ngOnInit() { + initialized.push('dir ' + this.name); + } } @Component({ @@ -1696,7 +1759,9 @@ describe('onInit', () => { ` }) class App { - ngOnInit() { initialized.push('app'); } + ngOnInit() { + initialized.push('app'); + } } TestBed.configureTestingModule({ @@ -1717,10 +1782,11 @@ describe('onInit', () => { template: `

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initialized.push('comp ' + this.name); } + ngOnInit() { + initialized.push('comp ' + this.name); + } } @Component({ @@ -1754,18 +1820,20 @@ describe('onInit', () => { template: `

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initialized.push('child of parent ' + this.name); } + ngOnInit() { + initialized.push('child of parent ' + this.name); + } } @Component({selector: 'parent', template: ''}) class Parent { - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { initialized.push('parent ' + this.name); } + ngOnInit() { + initialized.push('parent ' + this.name); + } } @Component({ @@ -1816,7 +1884,9 @@ describe('doCheck', () => { @Component({template: ``}) class App { - ngDoCheck() { doCheckCalled++; } + ngDoCheck() { + doCheckCalled++; + } } TestBed.configureTestingModule({ @@ -1840,7 +1910,9 @@ describe('doCheck', () => { template: ``, }) class Parent { - ngDoCheck() { doChecks.push('parent'); } + ngDoCheck() { + doChecks.push('parent'); + } } @Component({ @@ -1848,12 +1920,16 @@ describe('doCheck', () => { template: ``, }) class Child { - ngDoCheck() { doChecks.push('child'); } + ngDoCheck() { + doChecks.push('child'); + } } @Component({template: ``}) class App { - ngDoCheck() { doChecks.push('app'); } + ngDoCheck() { + doChecks.push('app'); + } } TestBed.configureTestingModule({ @@ -1869,9 +1945,13 @@ describe('doCheck', () => { const events: string[] = []; @Component({template: ``}) class App { - ngOnInit() { events.push('onInit'); } + ngOnInit() { + events.push('onInit'); + } - ngDoCheck() { events.push('doCheck'); } + ngDoCheck() { + events.push('doCheck'); + } } TestBed.configureTestingModule({ @@ -1889,10 +1969,11 @@ describe('doCheck', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngDoCheck() { doChecks.push('dir ' + this.name); } + ngDoCheck() { + doChecks.push('dir ' + this.name); + } } @Component({ @@ -1900,10 +1981,11 @@ describe('doCheck', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngDoCheck() { doChecks.push('comp ' + this.name); } + ngDoCheck() { + doChecks.push('comp ' + this.name); + } } @Component({ @@ -1913,7 +1995,9 @@ describe('doCheck', () => { ` }) class App { - ngDoCheck() { doChecks.push('app'); } + ngDoCheck() { + doChecks.push('app'); + } } TestBed.configureTestingModule({ @@ -1931,10 +2015,11 @@ describe('doCheck', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngDoCheck() { doChecks.push('dir ' + this.name); } + ngDoCheck() { + doChecks.push('dir ' + this.name); + } } @Component({ @@ -1942,12 +2027,13 @@ describe('doCheck', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; constructor(public dir: Dir) {} - ngDoCheck() { doChecks.push('comp ' + this.name); } + ngDoCheck() { + doChecks.push('comp ' + this.name); + } } @Component({ @@ -1957,7 +2043,9 @@ describe('doCheck', () => { ` }) class App { - ngDoCheck() { doChecks.push('app'); } + ngDoCheck() { + doChecks.push('app'); + } } TestBed.configureTestingModule({ @@ -1970,29 +2058,30 @@ describe('doCheck', () => { }); it('should be called on multiple directives in injection order', () => { - const events: any[] = []; @Directive({ selector: '[dir]', }) class Dir { - @Input() - dir = ''; + @Input() dir = ''; - ngDoCheck() { events.push('dir'); } + ngDoCheck() { + events.push('dir'); + } } @Directive({ selector: '[injectionDir]', }) class InjectionDir { - @Input() - injectionDir = ''; + @Input() injectionDir = ''; constructor(public dir: Dir) {} - ngDoCheck() { events.push('injectionDir'); } + ngDoCheck() { + events.push('injectionDir'); + } } @Component({ @@ -2001,7 +2090,9 @@ describe('doCheck', () => { class App { val = 'a'; - ngDoCheck() { events.push('app'); } + ngDoCheck() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2020,10 +2111,11 @@ describe('doCheck', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngDoCheck() { doChecks.push('dir ' + this.name); } + ngDoCheck() { + doChecks.push('dir ' + this.name); + } } @Component({ @@ -2033,7 +2125,9 @@ describe('doCheck', () => { ` }) class App { - ngDoCheck() { doChecks.push('app'); } + ngDoCheck() { + doChecks.push('app'); + } } TestBed.configureTestingModule({ @@ -2055,7 +2149,9 @@ describe('afterContentinit', () => { template: `

test

`, }) class Comp { - ngAfterContentInit() { afterContentInitCalls++; } + ngAfterContentInit() { + afterContentInitCalls++; + } } @Component({template: ``}) class App { @@ -2079,7 +2175,9 @@ describe('afterContentinit', () => { @Component({template: `

test

`}) class App { - ngAfterContentInit() { afterContentInitCalls++; } + ngAfterContentInit() { + afterContentInitCalls++; + } } TestBed.configureTestingModule({ @@ -2103,14 +2201,18 @@ describe('afterContentinit', () => { template: `

test

`, }) class Comp { - ngAfterContentInit() { events.push('comp afterContentInit'); } + ngAfterContentInit() { + events.push('comp afterContentInit'); + } } @Component({template: ``}) class App { show = true; - ngAfterContentInit() { events.push('app afterContentInit'); } + ngAfterContentInit() { + events.push('app afterContentInit'); + } } TestBed.configureTestingModule({ @@ -2143,10 +2245,11 @@ describe('afterContentinit', () => { template: ``, }) class Parent { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('parent ' + this.name); } + ngAfterContentInit() { + events.push('parent ' + this.name); + } } @Component({ @@ -2154,10 +2257,11 @@ describe('afterContentinit', () => { template: `

test

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('child of parent ' + this.name); } + ngAfterContentInit() { + events.push('child of parent ' + this.name); + } } @Component({ @@ -2167,7 +2271,9 @@ describe('afterContentinit', () => { ` }) class App { - ngAfterContentInit() { events.push('app'); } + ngAfterContentInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2188,10 +2294,11 @@ describe('afterContentinit', () => { template: `

test

`, }) class ProjectedChild { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('projected child ' + this.name); } + ngAfterContentInit() { + events.push('projected child ' + this.name); + } } @Component({ @@ -2199,10 +2306,11 @@ describe('afterContentinit', () => { template: `
`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('comp ' + this.name); } + ngAfterContentInit() { + events.push('comp ' + this.name); + } } @Component({ @@ -2210,10 +2318,11 @@ describe('afterContentinit', () => { template: ``, }) class Projected { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('projected ' + this.name); } + ngAfterContentInit() { + events.push('projected ' + this.name); + } } @Component({ @@ -2229,7 +2338,9 @@ describe('afterContentinit', () => { ` }) class App { - ngAfterContentInit() { events.push('app'); } + ngAfterContentInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2267,10 +2378,11 @@ describe('afterContentinit', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('comp ' + this.name); } + ngAfterContentInit() { + events.push('comp ' + this.name); + } } @Component({ @@ -2283,7 +2395,9 @@ describe('afterContentinit', () => { class App { numbers = [0, 1, 2, 3]; - ngAfterContentInit() { events.push('app'); } + ngAfterContentInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2304,10 +2418,11 @@ describe('afterContentinit', () => { template: ``, }) class Parent { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('parent ' + this.name); } + ngAfterContentInit() { + events.push('parent ' + this.name); + } } @Component({ @@ -2315,10 +2430,11 @@ describe('afterContentinit', () => { template: `

test

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('child of parent ' + this.name); } + ngAfterContentInit() { + events.push('child of parent ' + this.name); + } } @Component({ @@ -2330,7 +2446,9 @@ describe('afterContentinit', () => { }) class App { numbers = [0, 1, 2, 3]; - ngAfterContentInit() { events.push('app'); } + ngAfterContentInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2366,10 +2484,11 @@ describe('afterContentinit', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngAfterContentInit() { events.push('dir ' + this.name); } + ngAfterContentInit() { + events.push('dir ' + this.name); + } } @Component({ @@ -2377,10 +2496,11 @@ describe('afterContentinit', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterContentInit() { events.push('comp ' + this.name); } + ngAfterContentInit() { + events.push('comp ' + this.name); + } } @Component({ @@ -2390,7 +2510,9 @@ describe('afterContentinit', () => { ` }) class App { - ngAfterContentInit() { events.push('app'); } + ngAfterContentInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2418,16 +2540,24 @@ describe('afterContentChecked', () => { template: `

test

`, }) class Comp { - ngAfterContentInit() { events.push('comp afterContentInit'); } + ngAfterContentInit() { + events.push('comp afterContentInit'); + } - ngAfterContentChecked() { events.push('comp afterContentChecked'); } + ngAfterContentChecked() { + events.push('comp afterContentChecked'); + } } @Component({template: ``}) class App { - ngAfterContentInit() { events.push('app afterContentInit'); } + ngAfterContentInit() { + events.push('app afterContentInit'); + } - ngAfterContentChecked() { events.push('app afterContentChecked'); } + ngAfterContentChecked() { + events.push('app afterContentChecked'); + } } TestBed.configureTestingModule({ @@ -2454,7 +2584,9 @@ describe('afterViewInit', () => { template: `

test

`, }) class Comp { - ngAfterViewInit() { afterViewInitCalls++; } + ngAfterViewInit() { + afterViewInitCalls++; + } } @Component({template: ``}) @@ -2472,7 +2604,6 @@ describe('afterViewInit', () => { fixture.detectChanges(); expect(afterViewInitCalls).toBe(1); - }); it('should be called on root component in creation mode', () => { @@ -2480,7 +2611,9 @@ describe('afterViewInit', () => { @Component({template: `

test

`}) class App { - ngAfterViewInit() { afterViewInitCalls++; } + ngAfterViewInit() { + afterViewInitCalls++; + } } TestBed.configureTestingModule({ @@ -2504,7 +2637,9 @@ describe('afterViewInit', () => { template: `

test

`, }) class Comp { - ngAfterViewInit() { events.push('comp'); } + ngAfterViewInit() { + events.push('comp'); + } } @Component({ @@ -2513,7 +2648,9 @@ describe('afterViewInit', () => { class App { show = true; - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2543,10 +2680,11 @@ describe('afterViewInit', () => { template: ``, }) class Parent { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('parent ' + this.name); } + ngAfterViewInit() { + events.push('parent ' + this.name); + } } @Component({ @@ -2554,10 +2692,11 @@ describe('afterViewInit', () => { template: `

test

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('child of parent ' + this.name); } + ngAfterViewInit() { + events.push('child of parent ' + this.name); + } } @Component({ @@ -2567,7 +2706,9 @@ describe('afterViewInit', () => { ` }) class App { - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2593,10 +2734,11 @@ describe('afterViewInit', () => { template: `

test

`, }) class Projected { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('projected ' + this.name); } + ngAfterViewInit() { + events.push('projected ' + this.name); + } } @Component({ @@ -2604,10 +2746,11 @@ describe('afterViewInit', () => { template: ``, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('comp ' + this.name); } + ngAfterViewInit() { + events.push('comp ' + this.name); + } } @Component({ @@ -2617,7 +2760,9 @@ describe('afterViewInit', () => { ` }) class App { - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2644,10 +2789,11 @@ describe('afterViewInit', () => { template: `

test

`, }) class ProjectedChild { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('child of projected ' + this.name); } + ngAfterViewInit() { + events.push('child of projected ' + this.name); + } } @Component({ @@ -2655,10 +2801,11 @@ describe('afterViewInit', () => { template: ``, }) class Projected { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('projected ' + this.name); } + ngAfterViewInit() { + events.push('projected ' + this.name); + } } @Component({ @@ -2666,10 +2813,11 @@ describe('afterViewInit', () => { template: `
`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('comp ' + this.name); } + ngAfterViewInit() { + events.push('comp ' + this.name); + } } @Component({ @@ -2679,7 +2827,9 @@ describe('afterViewInit', () => { ` }) class App { - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2707,10 +2857,11 @@ describe('afterViewInit', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('comp ' + this.name); } + ngAfterViewInit() { + events.push('comp ' + this.name); + } } @Component({ @@ -2723,7 +2874,9 @@ describe('afterViewInit', () => { class App { numbers = [0, 1, 2, 3]; - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2752,20 +2905,22 @@ describe('afterViewInit', () => { template: `

test

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('child of parent ' + this.name); } + ngAfterViewInit() { + events.push('child of parent ' + this.name); + } } @Component({ selector: 'parent', template: ``, }) class Parent { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('parent ' + this.name); } + ngAfterViewInit() { + events.push('parent ' + this.name); + } } @Component({ @@ -2778,7 +2933,9 @@ describe('afterViewInit', () => { class App { numbers = [0, 1, 2, 3]; - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2812,10 +2969,11 @@ describe('afterViewInit', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngAfterViewInit() { events.push('dir ' + this.name); } + ngAfterViewInit() { + events.push('dir ' + this.name); + } } @Component({ @@ -2823,10 +2981,11 @@ describe('afterViewInit', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewInit() { events.push('comp ' + this.name); } + ngAfterViewInit() { + events.push('comp ' + this.name); + } } @Component({ @@ -2836,7 +2995,9 @@ describe('afterViewInit', () => { ` }) class App { - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2861,10 +3022,11 @@ describe('afterViewInit', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngAfterViewInit() { events.push('dir ' + this.name); } + ngAfterViewInit() { + events.push('dir ' + this.name); + } } @Component({ @@ -2874,7 +3036,9 @@ describe('afterViewInit', () => { ` }) class App { - ngAfterViewInit() { events.push('app'); } + ngAfterViewInit() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -2900,7 +3064,9 @@ describe('afterViewChecked', () => { template: `

test

`, }) class Comp { - ngAfterViewChecked() { afterViewCheckedCalls++; } + ngAfterViewChecked() { + afterViewCheckedCalls++; + } } @Component({template: ``}) @@ -2927,7 +3093,9 @@ describe('afterViewChecked', () => { @Component({template: `

test

`}) class App { - ngAfterViewChecked() { afterViewCheckedCalls++; } + ngAfterViewChecked() { + afterViewCheckedCalls++; + } } TestBed.configureTestingModule({ @@ -2953,9 +3121,10 @@ describe('afterViewChecked', () => { template: `

{{value}}

`, }) class Comp { - @Input() - value = ''; - ngAfterViewChecked() { afterViewCheckedCalls++; } + @Input() value = ''; + ngAfterViewChecked() { + afterViewCheckedCalls++; + } } @Component({template: ``}) @@ -2983,10 +3152,11 @@ describe('afterViewChecked', () => { template: `

test

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewChecked() { events.push('child of parent ' + this.name); } + ngAfterViewChecked() { + events.push('child of parent ' + this.name); + } } @Component({ @@ -2994,10 +3164,11 @@ describe('afterViewChecked', () => { template: ``, }) class Parent { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewChecked() { events.push('parent ' + this.name); } + ngAfterViewChecked() { + events.push('parent ' + this.name); + } } @Component({ @@ -3010,7 +3181,9 @@ describe('afterViewChecked', () => { class App { numbers = [0, 1, 2, 3]; - ngAfterViewChecked() { events.push('app'); } + ngAfterViewChecked() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -3043,10 +3216,11 @@ describe('afterViewChecked', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngAfterViewChecked() { events.push('dir ' + this.name); } + ngAfterViewChecked() { + events.push('dir ' + this.name); + } } @Component({ @@ -3054,10 +3228,11 @@ describe('afterViewChecked', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngAfterViewChecked() { events.push('comp ' + this.name); } + ngAfterViewChecked() { + events.push('comp ' + this.name); + } } @Component({ @@ -3067,7 +3242,9 @@ describe('afterViewChecked', () => { ` }) class App { - ngAfterViewChecked() { events.push('app'); } + ngAfterViewChecked() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -3092,10 +3269,11 @@ describe('afterViewChecked', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngAfterViewChecked() { events.push('dir ' + this.name); } + ngAfterViewChecked() { + events.push('dir ' + this.name); + } } @Component({ @@ -3105,7 +3283,9 @@ describe('afterViewChecked', () => { ` }) class App { - ngAfterViewChecked() { events.push('app'); } + ngAfterViewChecked() { + events.push('app'); + } } TestBed.configureTestingModule({ @@ -3120,12 +3300,9 @@ describe('afterViewChecked', () => { 'app', ]); }); - }); describe('onDestroy', () => { - - it('should call destroy when view is removed', () => { let destroyCalled = 0; @@ -3134,7 +3311,9 @@ describe('onDestroy', () => { template: `

test

`, }) class Comp { - ngOnDestroy() { destroyCalled++; } + ngOnDestroy() { + destroyCalled++; + } } @Component({ @@ -3177,10 +3356,11 @@ describe('onDestroy', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('comp ' + this.name); } + ngOnDestroy() { + events.push('comp ' + this.name); + } } @Component({ @@ -3218,10 +3398,11 @@ describe('onDestroy', () => { template: `

test

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('child of parent ' + this.name); } + ngOnDestroy() { + events.push('child of parent ' + this.name); + } } @Component({ @@ -3229,9 +3410,10 @@ describe('onDestroy', () => { template: ``, }) class Parent { - @Input() - name = ''; - ngOnDestroy() { events.push('parent ' + this.name); } + @Input() name = ''; + ngOnDestroy() { + events.push('parent ' + this.name); + } } @Component({ @@ -3274,10 +3456,11 @@ describe('onDestroy', () => { template: `

test

`, }) class Child { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('child ' + this.name); } + ngOnDestroy() { + events.push('child ' + this.name); + } } @Component({ @@ -3285,9 +3468,10 @@ describe('onDestroy', () => { template: ``, }) class Parent { - @Input() - name = ''; - ngOnDestroy() { events.push('parent ' + this.name); } + @Input() name = ''; + ngOnDestroy() { + events.push('parent ' + this.name); + } } @Component({ @@ -3295,10 +3479,11 @@ describe('onDestroy', () => { template: ``, }) class Grandparent { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('grandparent ' + this.name); } + ngOnDestroy() { + events.push('grandparent ' + this.name); + } } @Component({ template: ` @@ -3342,10 +3527,11 @@ describe('onDestroy', () => { template: `

test

`, }) class Projected { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('projected ' + this.name); } + ngOnDestroy() { + events.push('projected ' + this.name); + } } @Component({ @@ -3353,10 +3539,11 @@ describe('onDestroy', () => { template: `
`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('comp ' + this.name); } + ngOnDestroy() { + events.push('comp ' + this.name); + } } @Component({ @@ -3403,10 +3590,11 @@ describe('onDestroy', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('comp ' + this.name); } + ngOnDestroy() { + events.push('comp ' + this.name); + } } @Component({ @@ -3473,10 +3661,11 @@ describe('onDestroy', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('comp ' + this.name); } + ngOnDestroy() { + events.push('comp ' + this.name); + } } @Component({ @@ -3551,7 +3740,9 @@ describe('onDestroy', () => { template: `

test

`, }) class Comp { - ngOnDestroy() { events.push('comp'); } + ngOnDestroy() { + events.push('comp'); + } } @Component({ template: ` @@ -3569,9 +3760,13 @@ describe('onDestroy', () => { clicksToButton2 = 0; - handleClick1() { this.clicksToButton1++; } + handleClick1() { + this.clicksToButton1++; + } - handleClick2() { this.clicksToButton2++; } + handleClick2() { + this.clicksToButton2++; + } } TestBed.configureTestingModule({ @@ -3604,7 +3799,7 @@ describe('onDestroy', () => { @Component({selector: 'parent', template: ``}) class Parent { - @ContentChildren(Child, {descendants: true}) child !: QueryList; + @ContentChildren(Child, {descendants: true}) child!: QueryList; } @Component({ @@ -3619,13 +3814,13 @@ describe('onDestroy', () => { ` }) class App { - @ViewChild('container', {read: ViewContainerRef, static: true}) - container !: ViewContainerRef; + @ViewChild('container', {read: ViewContainerRef, static: true}) container!: ViewContainerRef; - @ViewChild('tpl', {read: TemplateRef, static: true}) - tpl !: TemplateRef; + @ViewChild('tpl', {read: TemplateRef, static: true}) tpl!: TemplateRef; - ngOnInit() { this.container.createEmbeddedView(this.tpl); } + ngOnInit() { + this.container.createEmbeddedView(this.tpl); + } } @Directive({selector: '[dir]'}) @@ -3659,10 +3854,11 @@ describe('onDestroy', () => { selector: '[dir]', }) class Dir { - @Input('dir') - name = ''; + @Input('dir') name = ''; - ngOnDestroy() { events.push('dir ' + this.name); } + ngOnDestroy() { + events.push('dir ' + this.name); + } } @Component({ @@ -3670,10 +3866,11 @@ describe('onDestroy', () => { template: `

test

`, }) class Comp { - @Input() - name = ''; + @Input() name = ''; - ngOnDestroy() { events.push('comp ' + this.name); } + ngOnDestroy() { + events.push('comp ' + this.name); + } } @Component({ @@ -3715,7 +3912,9 @@ describe('onDestroy', () => { selector: '[dir]', }) class Dir { - ngOnDestroy() { events.push('dir'); } + ngOnDestroy() { + events.push('dir'); + } } @Component({template: `

`}) @@ -3749,27 +3948,41 @@ describe('hook order', () => { template: `{{value}}
`, }) class Comp { - @Input() - value = ''; + @Input() value = ''; - @Input() - name = ''; + @Input() name = ''; - ngOnInit() { events.push(`${this.name} onInit`); } + ngOnInit() { + events.push(`${this.name} onInit`); + } - ngDoCheck() { events.push(`${this.name} doCheck`); } + ngDoCheck() { + events.push(`${this.name} doCheck`); + } - ngOnChanges() { events.push(`${this.name} onChanges`); } + ngOnChanges() { + events.push(`${this.name} onChanges`); + } - ngAfterContentInit() { events.push(`${this.name} afterContentInit`); } + ngAfterContentInit() { + events.push(`${this.name} afterContentInit`); + } - ngAfterContentChecked() { events.push(`${this.name} afterContentChecked`); } + ngAfterContentChecked() { + events.push(`${this.name} afterContentChecked`); + } - ngAfterViewInit() { events.push(`${this.name} afterViewInit`); } + ngAfterViewInit() { + events.push(`${this.name} afterViewInit`); + } - ngAfterViewChecked() { events.push(`${this.name} afterViewChecked`); } + ngAfterViewChecked() { + events.push(`${this.name} afterViewChecked`); + } - ngOnDestroy() { events.push(`${this.name} onDestroy`); } + ngOnDestroy() { + events.push(`${this.name} onDestroy`); + } } @Component({ @@ -4044,7 +4257,9 @@ describe('non-regression', () => { selector: '[onDestroyDir]', }) class OnDestroyDir { - ngOnDestroy() { destroyed = true; } + ngOnDestroy() { + destroyed = true; + } } @Component({ diff --git a/packages/core/test/acceptance/listener_spec.ts b/packages/core/test/acceptance/listener_spec.ts index 8c42981b12b81..7bb045800cd04 100644 --- a/packages/core/test/acceptance/listener_spec.ts +++ b/packages/core/test/acceptance/listener_spec.ts @@ -16,36 +16,40 @@ function getNoOfNativeListeners(): number { } describe('event listeners', () => { - describe('coalescing', () => { - @Component({ selector: 'with-clicks-cmpt', template: `` }) class WithClicksCmpt { counter = 0; - count() { this.counter++; } + count() { + this.counter++; + } } @Directive({selector: '[md-button]'}) class MdButton { counter = 0; @HostListener('click') - count() { this.counter++; } + count() { + this.counter++; + } } @Directive({selector: '[likes-clicks]'}) class LikesClicks { counter = 0; @HostListener('click') - count() { this.counter++; } + count() { + this.counter++; + } } @Directive({selector: '[returns-false]'}) class ReturnsFalse { counter = 0; - event !: Event; + event!: Event; handlerShouldReturn: boolean|undefined = undefined; @HostListener('click', ['$event']) @@ -65,7 +69,6 @@ describe('event listeners', () => { onlyInIvy('ngDevMode.rendererAddEventListener counters are only available in ivy') .it('should coalesce multiple event listeners for the same event on the same element', () => { - @Component({ selector: 'test-cmpt', template: @@ -107,7 +110,6 @@ describe('event listeners', () => { onlyInIvy('ngDevMode.rendererAddEventListener counters are only available in ivy') .it('should coalesce multiple event listeners in presence of queries', () => { - @Component({ selector: 'test-cmpt', template: `` @@ -115,7 +117,7 @@ describe('event listeners', () => { class TestCmpt { counter = 0; - @ViewChildren('nothing') nothing !: QueryList; + @ViewChildren('nothing') nothing!: QueryList; } TestBed.configureTestingModule({declarations: [TestCmpt, LikesClicks]}); @@ -136,11 +138,12 @@ describe('event listeners', () => { it('should try to execute remaining coalesced listeners if one of the listeners throws', () => { - @Directive({selector: '[throws-on-clicks]'}) class ThrowsOnClicks { @HostListener('click') - dontCount() { throw new Error('I was clicked and I don\'t like it!'); } + dontCount() { + throw new Error('I was clicked and I don\'t like it!'); + } } @Component( @@ -151,7 +154,9 @@ describe('event listeners', () => { let noOfErrors = 0; class CountingErrorHandler extends ErrorHandler { - handleError(error: any): void { noOfErrors++; } + handleError(error: any): void { + noOfErrors++; + } } TestBed.configureTestingModule({ @@ -209,7 +214,9 @@ describe('event listeners', () => { @Input('foo') model: any; @Output('fooChange') update = new EventEmitter(); - updateValue(value: any) { this.update.emit(value); } + updateValue(value: any) { + this.update.emit(value); + } } @Component({ @@ -222,9 +229,13 @@ describe('event listeners', () => { @ViewChild(FooDirective) fooDirective: FooDirective|null = null; - fooChange() { this.count++; } + fooChange() { + this.count++; + } - triggerUpdate(value: any) { this.fooDirective !.updateValue(value); } + triggerUpdate(value: any) { + this.fooDirective!.updateValue(value); + } } TestBed.configureTestingModule({declarations: [TestComponent, FooDirective]}); @@ -247,19 +258,25 @@ describe('event listeners', () => { }) class MyComp { counter = 0; - count() { log.push('component.click'); } + count() { + log.push('component.click'); + } } @Directive({selector: '[dirA]'}) class DirA { @HostListener('click') - count() { log.push('dirA.click'); } + count() { + log.push('dirA.click'); + } } @Directive({selector: '[dirB]'}) class DirB { @HostListener('click') - count() { log.push('dirB.click'); } + count() { + log.push('dirB.click'); + } } TestBed.configureTestingModule({declarations: [MyComp, DirA, DirB]}); diff --git a/packages/core/test/acceptance/ng_module_spec.ts b/packages/core/test/acceptance/ng_module_spec.ts index e23031c32ed64..6c6d53643a8ad 100644 --- a/packages/core/test/acceptance/ng_module_spec.ts +++ b/packages/core/test/acceptance/ng_module_spec.ts @@ -7,7 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import {CUSTOM_ELEMENTS_SCHEMA, Component, Injectable, InjectionToken, NO_ERRORS_SCHEMA, NgModule, NgModuleRef, ɵsetClassMetadata as setClassMetadata, ɵɵdefineComponent as defineComponent, ɵɵdefineInjector as defineInjector, ɵɵdefineNgModule as defineNgModule, ɵɵelement as element} from '@angular/core'; +import {Component, CUSTOM_ELEMENTS_SCHEMA, Injectable, InjectionToken, NgModule, NgModuleRef, NO_ERRORS_SCHEMA, ɵsetClassMetadata as setClassMetadata, ɵɵdefineComponent as defineComponent, ɵɵdefineInjector as defineInjector, ɵɵdefineNgModule as defineNgModule, ɵɵelement as element} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {modifiedInIvy, onlyInIvy} from '@angular/private/testing'; @@ -84,12 +84,16 @@ describe('NgModule', () => { } @NgModule({providers: [Service]}) class RoutesModule { - constructor(service: Service) { service.initializations.push('RoutesModule'); } + constructor(service: Service) { + service.initializations.push('RoutesModule'); + } } @NgModule({imports: [RoutesModule]}) class AppModule { - constructor(service: Service) { service.initializations.push('AppModule'); } + constructor(service: Service) { + service.initializations.push('AppModule'); + } } TestBed.configureTestingModule({imports: [AppModule]}); @@ -188,7 +192,6 @@ describe('NgModule', () => { onlyInIvy('unknown element check logs a warning rather than throwing') .it('should warn about unknown element without CUSTOM_ELEMENTS_SCHEMA for element with dash in tag name', () => { - @Component({template: ``}) class MyComp { } @@ -262,11 +265,12 @@ describe('NgModule', () => { selectors: [['comp']], decls: 1, vars: 0, - template: function MyComp_Template(rf, ctx) { - if (rf & 1) { - element(0, 'custom-el'); - } - }, + template: + function MyComp_Template(rf, ctx) { + if (rf & 1) { + element(0, 'custom-el'); + } + }, encapsulation: 2 }); } @@ -472,7 +476,6 @@ describe('NgModule', () => { fixture.detectChanges(); }).not.toThrow(); }); - }); it('should be able to use DI through the NgModuleRef inside the module constructor', () => { @@ -484,7 +487,9 @@ describe('NgModule', () => { providers: [{provide: token, useValue: 'foo'}], }) class TestModule { - constructor(ngRef: NgModuleRef) { value = ngRef.injector.get(token); } + constructor(ngRef: NgModuleRef) { + value = ngRef.injector.get(token); + } } TestBed.configureTestingModule({imports: [TestModule], declarations: [TestCmp]}); @@ -514,5 +519,4 @@ describe('NgModule', () => { TestBed.createComponent(TestCmp); expect(componentInstance).toBeAnInstanceOf(TestCmp); }); - }); diff --git a/packages/core/test/acceptance/ngdevmode_debug_spec.ts b/packages/core/test/acceptance/ngdevmode_debug_spec.ts index 44027dea6e27c..080c532098d5a 100644 --- a/packages/core/test/acceptance/ngdevmode_debug_spec.ts +++ b/packages/core/test/acceptance/ngdevmode_debug_spec.ts @@ -40,10 +40,9 @@ onlyInIvy('Debug information exist in ivy only').describe('ngDevMode debug', () const element: HTMLElement = fixture.nativeElement; fixture.detectChanges(); - const li = element.querySelector('li') !; + const li = element.querySelector('li')!; const embeddedLView = loadLContext(li).lView; expect(embeddedLView.constructor.name).toEqual('LEmbeddedView_MyApp_li_1'); - }); }); }); diff --git a/packages/core/test/acceptance/outputs_spec.ts b/packages/core/test/acceptance/outputs_spec.ts index 873b6633888f3..f99f3f26eff45 100644 --- a/packages/core/test/acceptance/outputs_spec.ts +++ b/packages/core/test/acceptance/outputs_spec.ts @@ -13,29 +13,27 @@ import {TestBed} from '@angular/core/testing'; describe('outputs', () => { @Component({selector: 'button-toggle', template: ''}) class ButtonToggle { - @Output('change') - change = new EventEmitter(); + @Output('change') change = new EventEmitter(); - @Output('reset') - resetStream = new EventEmitter(); + @Output('reset') resetStream = new EventEmitter(); } @Directive({selector: '[otherDir]'}) class OtherDir { - @Output('change') - changeStream = new EventEmitter(); + @Output('change') changeStream = new EventEmitter(); } @Component({selector: 'destroy-comp', template: ''}) class DestroyComp implements OnDestroy { events: string[] = []; - ngOnDestroy() { this.events.push('destroy'); } + ngOnDestroy() { + this.events.push('destroy'); + } } @Directive({selector: '[myButton]'}) class MyButton { - @Output() - click = new EventEmitter(); + @Output() click = new EventEmitter(); } it('should call component output function when event is emitted', () => { @@ -43,8 +41,10 @@ describe('outputs', () => { @Component({template: ''}) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; - onChange() { counter++; } + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; + onChange() { + counter++; + } } TestBed.configureTestingModule({declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); @@ -64,9 +64,13 @@ describe('outputs', () => { @Component( {template: ''}) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; - onChange() { counter++; } - onReset() { resetCounter++; } + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; + onChange() { + counter++; + } + onReset() { + resetCounter++; + } } TestBed.configureTestingModule({declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); @@ -82,7 +86,7 @@ describe('outputs', () => { it('should eval component output expression when event is emitted', () => { @Component({template: ''}) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; counter = 0; } TestBed.configureTestingModule({declarations: [App, ButtonToggle]}); @@ -102,10 +106,12 @@ describe('outputs', () => { @Component( {template: ''}) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; condition = true; - onChange() { counter++; } + onChange() { + counter++; + } } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); @@ -133,11 +139,13 @@ describe('outputs', () => { ` }) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; condition = true; condition2 = true; - onChange() { counter++; } + onChange() { + counter++; + } } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); @@ -168,12 +176,16 @@ describe('outputs', () => { ` }) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; - @ViewChild(DestroyComp) destroyComp !: DestroyComp; + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; + @ViewChild(DestroyComp) destroyComp!: DestroyComp; condition = true; - onClick() { clickCounter++; } - onChange() { changeCounter++; } + onClick() { + clickCounter++; + } + onChange() { + changeCounter++; + } } TestBed.configureTestingModule( {imports: [CommonModule], declarations: [App, ButtonToggle, DestroyComp]}); @@ -206,8 +218,10 @@ describe('outputs', () => { @Component({template: ''}) class App { - @ViewChild(MyButton) buttonDir !: MyButton; - onClick() { counter++; } + @ViewChild(MyButton) buttonDir!: MyButton; + onClick() { + counter++; + } } TestBed.configureTestingModule({declarations: [App, MyButton]}); const fixture = TestBed.createComponent(App); @@ -228,9 +242,11 @@ describe('outputs', () => { @Component({template: ''}) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; - @ViewChild(OtherDir) otherDir !: OtherDir; - onChange() { counter++; } + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; + @ViewChild(OtherDir) otherDir!: OtherDir; + onChange() { + counter++; + } } TestBed.configureTestingModule({declarations: [App, ButtonToggle, OtherDir]}); const fixture = TestBed.createComponent(App); @@ -248,8 +264,7 @@ describe('outputs', () => { @Directive({selector: '[otherChangeDir]'}) class OtherChangeDir { - @Input() - change !: boolean; + @Input() change!: boolean; } @Component({ @@ -257,11 +272,13 @@ describe('outputs', () => { '' }) class App { - @ViewChild(ButtonToggle) buttonToggle !: ButtonToggle; - @ViewChild(OtherChangeDir) otherDir !: OtherChangeDir; + @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; + @ViewChild(OtherChangeDir) otherDir!: OtherChangeDir; change = true; - onChange() { counter++; } + onChange() { + counter++; + } } TestBed.configureTestingModule({declarations: [App, ButtonToggle, OtherChangeDir]}); const fixture = TestBed.createComponent(App); @@ -278,5 +295,4 @@ describe('outputs', () => { buttonToggle.change.next(); expect(counter).toBe(1); }); - }); diff --git a/packages/core/test/acceptance/pipe_spec.ts b/packages/core/test/acceptance/pipe_spec.ts index 49c020337b9c3..f0e610921f10c 100644 --- a/packages/core/test/acceptance/pipe_spec.ts +++ b/packages/core/test/acceptance/pipe_spec.ts @@ -14,7 +14,9 @@ describe('pipe', () => { @Pipe({name: 'countingPipe'}) class CountingPipe implements PipeTransform { state: number = 0; - transform(value: any) { return `${value} state:${this.state++}`; } + transform(value: any) { + return `${value} state:${this.state++}`; + } } @Pipe({name: 'multiArgPipe'}) @@ -57,20 +59,21 @@ describe('pipe', () => { it('should support bindings', () => { @Directive({selector: '[my-dir]'}) class Dir { - @Input() - dirProp: string = ''; + @Input() dirProp: string = ''; } @Pipe({name: 'double'}) class DoublePipe implements PipeTransform { - transform(value: any) { return `${value}${value}`; } + transform(value: any) { + return `${value}${value}`; + } } @Component({ template: `
`, }) class App { - @ViewChild(Dir) directive !: Dir; + @ViewChild(Dir) directive!: Dir; } TestBed.configureTestingModule({declarations: [App, DoublePipe, Dir]}); @@ -113,7 +116,9 @@ describe('pipe', () => { it('should pick a Pipe defined in `declarations` over imported Pipes', () => { @Pipe({name: 'number'}) class PipeA implements PipeTransform { - transform(value: any) { return `PipeA: ${value}`; } + transform(value: any) { + return `PipeA: ${value}`; + } } @NgModule({ @@ -125,7 +130,9 @@ describe('pipe', () => { @Pipe({name: 'number'}) class PipeB implements PipeTransform { - transform(value: any) { return `PipeB: ${value}`; } + transform(value: any) { + return `PipeB: ${value}`; + } } @Component({ @@ -150,7 +157,9 @@ describe('pipe', () => { () => { @Pipe({name: 'number'}) class PipeA implements PipeTransform { - transform(value: any) { return `PipeA: ${value}`; } + transform(value: any) { + return `PipeA: ${value}`; + } } @NgModule({ @@ -162,7 +171,9 @@ describe('pipe', () => { @Pipe({name: 'number'}) class PipeB implements PipeTransform { - transform(value: any) { return `PipeB: ${value}`; } + transform(value: any) { + return `PipeB: ${value}`; + } } @NgModule({ @@ -222,12 +233,16 @@ describe('pipe', () => { it('should support duplicates by using the later entry', () => { @Pipe({name: 'duplicatePipe'}) class DuplicatePipe1 implements PipeTransform { - transform(value: any) { return `${value} from duplicate 1`; } + transform(value: any) { + return `${value} from duplicate 1`; + } } @Pipe({name: 'duplicatePipe'}) class DuplicatePipe2 implements PipeTransform { - transform(value: any) { return `${value} from duplicate 2`; } + transform(value: any) { + return `${value} from duplicate 2`; + } } @Component({ @@ -247,7 +262,9 @@ describe('pipe', () => { it('should support pipe in context of ternary operator', () => { @Pipe({name: 'pipe'}) class MyPipe implements PipeTransform { - transform(value: any): any { return value; } + transform(value: any): any { + return value; + } } @Component({ @@ -313,8 +330,12 @@ describe('pipe', () => { @Pipe({name: 'countingImpurePipe', pure: false}) class CountingImpurePipe implements PipeTransform { state: number = 0; - transform(value: any) { return `${value} state:${this.state++}`; } - constructor() { impurePipeInstances.push(this); } + transform(value: any) { + return `${value} state:${this.state++}`; + } + constructor() { + impurePipeInstances.push(this); + } } beforeEach(() => impurePipeInstances = []); @@ -372,8 +393,12 @@ describe('pipe', () => { @Pipe({name: 'pipeWithOnDestroy'}) class PipeWithOnDestroy implements PipeTransform, OnDestroy { - ngOnDestroy() { destroyCalls++; } - transform(value: any): any { return null; } + ngOnDestroy() { + destroyCalls++; + } + transform(value: any): any { + return null; + } } @Component({ @@ -401,7 +426,9 @@ describe('pipe', () => { @Pipe({name: 'myConcatPipe'}) class ConcatPipe implements PipeTransform { constructor(public service: Service) {} - transform(value: string): string { return `${value} - ${this.service.title}`; } + transform(value: string): string { + return `${value} - ${this.service.title}`; + } } @Component({ @@ -428,7 +455,9 @@ describe('pipe', () => { @Pipe({name: 'myConcatPipe'}) class ConcatPipe implements PipeTransform { constructor(@Inject(token) public service: Service) {} - transform(value: string): string { return `${value} - ${this.service.title}`; } + transform(value: string): string { + return `${value} - ${this.service.title}`; + } } @Component({ @@ -461,7 +490,9 @@ describe('pipe', () => { @Pipe({name: 'myConcatPipe'}) class ConcatPipe implements PipeTransform { constructor(public service: Service) {} - transform(value: string): string { return `${value} - ${this.service.title}`; } + transform(value: string): string { + return `${value} - ${this.service.title}`; + } } @Component({ @@ -501,7 +532,7 @@ describe('pipe', () => { }) class App { @Input() something: any; - @ViewChild(SomeComp) comp !: SomeComp; + @ViewChild(SomeComp) comp!: SomeComp; pipeValue = 10; displayValue = 0; } @@ -512,7 +543,9 @@ describe('pipe', () => { pipeChangeDetectorRef = changeDetectorRef; } - transform() { return ''; } + transform() { + return ''; + } } TestBed.configureTestingModule({declarations: [App, SomeComp, TestPipe]}); @@ -521,7 +554,7 @@ describe('pipe', () => { fixture.componentInstance.displayValue = 1; fixture.componentInstance.comp.displayValue = 1; - pipeChangeDetectorRef !.markForCheck(); + pipeChangeDetectorRef!.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Outer value: "1"'); @@ -553,7 +586,7 @@ describe('pipe', () => { }) class App { @Input() something: any; - @ViewChild(SomeComp) comp !: SomeComp; + @ViewChild(SomeComp) comp!: SomeComp; pipeValue = 10; displayValue = 0; } @@ -564,7 +597,9 @@ describe('pipe', () => { pipeChangeDetectorRef = changeDetectorRef; } - transform() { return ''; } + transform() { + return ''; + } } TestBed.configureTestingModule({declarations: [App, SomeComp, TestPipe]}); @@ -573,22 +608,21 @@ describe('pipe', () => { fixture.componentInstance.displayValue = 1; fixture.componentInstance.comp.displayValue = 1; - pipeChangeDetectorRef !.markForCheck(); + pipeChangeDetectorRef!.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Outer value: "1"'); expect(fixture.nativeElement.textContent).toContain('Inner value: "0"'); }); - }); describe('pure pipe error handling', () => { - it('should not re-invoke pure pipes if it fails initially', () => { - @Pipe({name: 'throwPipe', pure: true}) class ThrowPipe implements PipeTransform { - transform(): never { throw new Error('ThrowPipeError'); } + transform(): never { + throw new Error('ThrowPipeError'); + } } @Component({template: `{{val | throwPipe}}`}) class App { @@ -607,7 +641,6 @@ describe('pipe', () => { it('should display the last known result from a pure pipe when it throws', () => { - @Pipe({name: 'throwPipe', pure: true}) class ThrowPipe implements PipeTransform { transform(value: string): string { @@ -647,7 +680,8 @@ describe('pipe', () => { describe('pure pipe error handling with multiple arguments', () => { const args: string[] = new Array(10).fill(':0'); for (let numberOfPipeArgs = 0; numberOfPipeArgs < args.length; numberOfPipeArgs++) { - it(`should not invoke ${numberOfPipeArgs} argument pure pipe second time if it throws unless input changes`, + it(`should not invoke ${ + numberOfPipeArgs} argument pure pipe second time if it throws unless input changes`, () => { // https://stackblitz.com/edit/angular-mbx2pg const log: string[] = []; @@ -685,8 +719,5 @@ describe('pipe', () => { }); } }); - }); - - }); diff --git a/packages/core/test/acceptance/property_binding_spec.ts b/packages/core/test/acceptance/property_binding_spec.ts index a2343c9009ca2..5b465d1c05e73 100644 --- a/packages/core/test/acceptance/property_binding_spec.ts +++ b/packages/core/test/acceptance/property_binding_spec.ts @@ -91,7 +91,6 @@ describe('property bindings', () => { it('should not map properties whose names do not correspond to their attribute names, ' + 'if they correspond to inputs', () => { - @Component({template: '', selector: 'my-comp'}) class MyComp { @Input() for !:string; @@ -393,7 +392,6 @@ describe('property bindings', () => { }); describe('attributes and input properties', () => { - @Directive({selector: '[myDir]', exportAs: 'myDir'}) class MyDir { @Input() role: string|undefined; @@ -596,7 +594,6 @@ describe('property bindings', () => { expect(comp2.children[0].getAttribute('role')).toBe('button'); expect(comp2.textContent).toBe('role: button'); }); - }); it('should not throw on synthetic property bindings when a directive on the same element injects ViewContainerRef', @@ -626,5 +623,4 @@ describe('property bindings', () => { fixture.detectChanges(); }).not.toThrow(); }); - }); diff --git a/packages/core/test/acceptance/property_interpolation_spec.ts b/packages/core/test/acceptance/property_interpolation_spec.ts index 0330f08a2a8b7..c3b5dfb03014b 100644 --- a/packages/core/test/acceptance/property_interpolation_spec.ts +++ b/packages/core/test/acceptance/property_interpolation_spec.ts @@ -8,7 +8,7 @@ import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; -import {of } from 'rxjs'; +import {of} from 'rxjs'; describe('property interpolation', () => { it('should handle all flavors of interpolated properties', () => { @@ -67,7 +67,7 @@ describe('property interpolation', () => { ` }) class App { - details = of ({ + details = of({ title: 'cool image', url: 'http://somecooldomain:1234/cool_image.png', }); @@ -93,7 +93,11 @@ describe('property interpolation', () => { /** Clearly this is a doctor of heavy metals. */ leadSurgeon = { getCommonInfo() { - return {getPhotoUrl() { return 'http://somecooldomain:1234/cool_image.png'; }}; + return { + getPhotoUrl() { + return 'http://somecooldomain:1234/cool_image.png'; + } + }; } }; } diff --git a/packages/core/test/acceptance/pure_function_spec.ts b/packages/core/test/acceptance/pure_function_spec.ts index 8b03174a16681..406e8b185a7af 100644 --- a/packages/core/test/acceptance/pure_function_spec.ts +++ b/packages/core/test/acceptance/pure_function_spec.ts @@ -18,8 +18,7 @@ describe('components using pure function instructions internally', () => { template: ``, }) class MyComp { - @Input() - names: string[] = []; + @Input() names: string[] = []; } @@ -60,7 +59,7 @@ describe('components using pure function instructions internally', () => { myComp.names = ['should not be overwritten']; fixture.detectChanges(); - expect(myComp !.names).toEqual(['should not be overwritten']); + expect(myComp!.names).toEqual(['should not be overwritten']); }); @@ -91,11 +90,9 @@ describe('components using pure function instructions internally', () => { template: ``, }) class ManyPropComp { - @Input() - names1: string[] = []; + @Input() names1: string[] = []; - @Input() - names2: string[] = []; + @Input() names2: string[] = []; } @Component({ @@ -117,14 +114,14 @@ describe('components using pure function instructions internally', () => { fixture.detectChanges(); const manyPropComp = fixture.debugElement.query(By.directive(ManyPropComp)).componentInstance; - expect(manyPropComp !.names1).toEqual(['Nancy', 'Carson']); - expect(manyPropComp !.names2).toEqual(['George']); + expect(manyPropComp!.names1).toEqual(['Nancy', 'Carson']); + expect(manyPropComp!.names2).toEqual(['George']); fixture.componentInstance.customName = 'George'; fixture.componentInstance.customName2 = 'Carson'; fixture.detectChanges(); - expect(manyPropComp !.names1).toEqual(['Nancy', 'George']); - expect(manyPropComp !.names2).toEqual(['Carson']); + expect(manyPropComp!.names1).toEqual(['Nancy', 'George']); + expect(manyPropComp!.names2).toEqual(['Carson']); }); @@ -222,7 +219,6 @@ describe('components using pure function instructions internally', () => { it('should work up to 8 bindings', () => { - @Component({ template: ` @@ -346,8 +342,7 @@ describe('components using pure function instructions internally', () => { template: ``, }) class ObjectComp { - @Input() - config: any = []; + @Input() config: any = []; } it('should support an object literal', () => { @@ -495,7 +490,7 @@ describe('components using pure function instructions internally', () => { ` }) class App { - @ViewChildren(Dir) directives !: QueryList; + @ViewChildren(Dir) directives!: QueryList; } TestBed.configureTestingModule({declarations: [Dir, App]}); @@ -514,7 +509,7 @@ describe('components using pure function instructions internally', () => { ` }) class App { - @ViewChildren(Dir) directives !: QueryList; + @ViewChildren(Dir) directives!: QueryList; } TestBed.configureTestingModule({declarations: [Dir, App]}); @@ -528,7 +523,7 @@ describe('components using pure function instructions internally', () => { it('should not share object literals across component instances', () => { @Component({template: `
`}) class App { - @ViewChild(Dir) directive !: Dir; + @ViewChild(Dir) directive!: Dir; } TestBed.configureTestingModule({declarations: [Dir, App]}); @@ -545,7 +540,7 @@ describe('components using pure function instructions internally', () => { it('should not share array literals across component instances', () => { @Component({template: `
`}) class App { - @ViewChild(Dir) directive !: Dir; + @ViewChild(Dir) directive!: Dir; } TestBed.configureTestingModule({declarations: [Dir, App]}); @@ -567,7 +562,7 @@ describe('components using pure function instructions internally', () => { ` }) class App { - @ViewChildren(Dir) directives !: QueryList; + @ViewChildren(Dir) directives!: QueryList; } TestBed.configureTestingModule({declarations: [Dir, App]}); @@ -586,7 +581,7 @@ describe('components using pure function instructions internally', () => { ` }) class App { - @ViewChildren(Dir) directives !: QueryList; + @ViewChildren(Dir) directives!: QueryList; } TestBed.configureTestingModule({declarations: [Dir, App]}); @@ -605,8 +600,10 @@ describe('components using pure function instructions internally', () => { ` }) class App { - @ViewChildren(Dir) directives !: QueryList; - getFoo() { return 'foo!'; } + @ViewChildren(Dir) directives!: QueryList; + getFoo() { + return 'foo!'; + } } TestBed.configureTestingModule({declarations: [Dir, App]}); @@ -616,8 +613,5 @@ describe('components using pure function instructions internally', () => { expect(values).toEqual([{foo: null}, {foo: 'foo!'}]); }); - - - }); }); diff --git a/packages/core/test/acceptance/query_spec.ts b/packages/core/test/acceptance/query_spec.ts index 8ebe7aba626ef..c36f6027fb18b 100644 --- a/packages/core/test/acceptance/query_spec.ts +++ b/packages/core/test/acceptance/query_spec.ts @@ -7,7 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import {AfterViewInit, Component, ContentChild, ContentChildren, Directive, ElementRef, Input, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef, ViewRef, forwardRef} from '@angular/core'; +import {AfterViewInit, Component, ContentChild, ContentChildren, Directive, ElementRef, forwardRef, Input, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef, ViewRef} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; @@ -215,7 +215,7 @@ describe('query logic', () => { } class MyComp { - @ViewChildren(SomeDir) foo !: QueryList; + @ViewChildren(SomeDir) foo!: QueryList; } @Component({ @@ -242,7 +242,7 @@ describe('query logic', () => { } class MySuperComp { - @ViewChildren(SomeDir) foo !: QueryList; + @ViewChildren(SomeDir) foo!: QueryList; } class MyComp extends MySuperComp {} @@ -275,7 +275,7 @@ describe('query logic', () => { template: `` }) class Insertion { - @Input() content !: TemplateRef<{}>; + @Input() content!: TemplateRef<{}>; } @Component({ @@ -287,7 +287,7 @@ describe('query logic', () => { ` }) class App { - @ViewChild(Required) requiredEl !: Required; + @ViewChild(Required) requiredEl!: Required; viewChildAvailableInAfterViewInit?: boolean; ngAfterViewInit() { @@ -300,7 +300,6 @@ describe('query logic', () => { fixture.detectChanges(); expect(fixture.componentInstance.viewChildAvailableInAfterViewInit).toBe(true); }); - }); describe('content queries', () => { @@ -538,7 +537,7 @@ describe('query logic', () => { @Component({template: '
'}) class App { - @ViewChild(SubComp) subComp !: SubComp; + @ViewChild(SubComp) subComp!: SubComp; } TestBed.configureTestingModule({declarations: [App, SubComp]}); @@ -561,7 +560,7 @@ describe('query logic', () => { @Component({template: '
'}) class App { - @ViewChild(SubComp) subComp !: SubComp; + @ViewChild(SubComp) subComp!: SubComp; } TestBed.configureTestingModule({declarations: [App, SubComp]}); @@ -577,7 +576,7 @@ describe('query logic', () => { } class MyComp { - @ContentChildren(SomeDir) foo !: QueryList; + @ContentChildren(SomeDir) foo!: QueryList; } @Component({selector: 'sub-comp', template: ''}) @@ -593,7 +592,7 @@ describe('query logic', () => { ` }) class App { - @ViewChild(SubComp) subComp !: SubComp; + @ViewChild(SubComp) subComp!: SubComp; } TestBed.configureTestingModule({declarations: [App, SubComp, SomeDir]}); @@ -610,7 +609,7 @@ describe('query logic', () => { } class MySuperComp { - @ContentChildren(SomeDir) foo !: QueryList; + @ContentChildren(SomeDir) foo!: QueryList; } class MyComp extends MySuperComp {} @@ -628,7 +627,7 @@ describe('query logic', () => { ` }) class App { - @ViewChild(SubComp) subComp !: SubComp; + @ViewChild(SubComp) subComp!: SubComp; } TestBed.configureTestingModule({declarations: [App, SubComp, SomeDir]}); @@ -657,7 +656,7 @@ describe('query logic', () => { template: '', }) class ShallowComp { - @ContentChildren('foo', {descendants: false}) foos !: QueryList; + @ContentChildren('foo', {descendants: false}) foos!: QueryList; } TestBed.configureTestingModule( @@ -666,7 +665,7 @@ describe('query logic', () => { fixture.detectChanges(); const shallowComp = fixture.debugElement.query(By.directive(ShallowComp)).componentInstance; - const queryList = shallowComp !.foos; + const queryList = shallowComp!.foos; expect(queryList.length).toBe(0); fixture.componentInstance.showing = true; @@ -691,24 +690,24 @@ describe('query logic', () => { }); describe('descendants: false (default)', () => { - /** * A helper function to check if a given object looks like ElementRef. It is used in place of * the `instanceof ElementRef` check since ivy returns a type that looks like ElementRef (have * the same properties but doesn't pass the instanceof ElementRef test) */ - function isElementRefLike(result: any): boolean { return result.nativeElement != null; } + function isElementRefLike(result: any): boolean { + return result.nativeElement != null; + } it('should match directives on elements that used to be wrapped by a required parent in HTML parser', () => { - @Directive({selector: '[myDef]'}) class MyDef { } @Component({selector: 'my-container', template: ``}) class MyContainer { - @ContentChildren(MyDef) myDefs !: QueryList; + @ContentChildren(MyDef) myDefs!: QueryList; } @Component( {selector: 'test-cmpt', template: ``}) @@ -724,10 +723,9 @@ describe('query logic', () => { }); it('should match elements with local refs inside ', () => { - @Component({selector: 'needs-target', template: ``}) class NeedsTarget { - @ContentChildren('target') targets !: QueryList; + @ContentChildren('target') targets!: QueryList; } @Component({ selector: 'test-cmpt', @@ -752,10 +750,9 @@ describe('query logic', () => { }); it('should match elements with local refs inside nested ', () => { - @Component({selector: 'needs-target', template: ``}) class NeedsTarget { - @ContentChildren('target') targets !: QueryList; + @ContentChildren('target') targets!: QueryList; } @Component({ @@ -791,7 +788,7 @@ describe('query logic', () => { @Component({selector: 'needs-target', template: ``}) class NeedsTarget { - @ContentChildren(TargetDir) targets !: QueryList; + @ContentChildren(TargetDir) targets!: QueryList; } @Component({ @@ -823,7 +820,7 @@ describe('query logic', () => { @Component({selector: 'needs-target', template: ``}) class NeedsTarget { - @ContentChildren(TargetDir) targets !: QueryList; + @ContentChildren(TargetDir) targets!: QueryList; } @Component({ @@ -859,7 +856,7 @@ describe('query logic', () => { @Directive({selector: '[needs-target]'}) class NeedsTarget { - @ContentChildren(TargetDir) targets !: QueryList; + @ContentChildren(TargetDir) targets!: QueryList; } @Component({ @@ -893,8 +890,8 @@ describe('query logic', () => { @Component({selector: 'needs-target', template: ``}) class NeedsTarget { - @ContentChildren(TargetDir) dirTargets !: QueryList; - @ContentChildren('target') localRefsTargets !: QueryList; + @ContentChildren(TargetDir) dirTargets!: QueryList; + @ContentChildren('target') localRefsTargets!: QueryList; } @Component({ @@ -931,7 +928,7 @@ describe('query logic', () => { @Component({selector: 'needs-target', template: ``}) class NeedsTarget { - @ContentChildren(TargetDir) targets !: QueryList; + @ContentChildren(TargetDir) targets!: QueryList; } @Component({ @@ -963,7 +960,6 @@ describe('query logic', () => { describe('observable interface', () => { - it('should allow observing changes to query list', () => { const fixture = TestBed.createComponent(QueryCompWithChanges); let changes = 0; @@ -983,13 +979,10 @@ describe('query logic', () => { fixture.detectChanges(); expect(changes).toBe(1); }); - }); describe('view boundaries', () => { - describe('ViewContainerRef', () => { - @Directive({selector: '[vc]', exportAs: 'vc'}) class ViewContainerManipulatorDirective { constructor(private _vcRef: ViewContainerRef) {} @@ -998,9 +991,13 @@ describe('query logic', () => { return this._vcRef.createEmbeddedView(tpl, ctx, idx); } - remove(index?: number) { this._vcRef.remove(index); } + remove(index?: number) { + this._vcRef.remove(index); + } - move(viewRef: ViewRef, index: number) { this._vcRef.move(viewRef, index); } + move(viewRef: ViewRef, index: number) { + this._vcRef.move(viewRef, index); + } } it('should report results in views inserted / removed by ngIf', () => { @@ -1014,7 +1011,7 @@ describe('query logic', () => { }) class TestComponent { value: boolean = false; - @ViewChildren('foo') query !: QueryList; + @ViewChildren('foo') query!: QueryList; } TestBed.configureTestingModule({declarations: [TestComponent]}); @@ -1045,7 +1042,7 @@ describe('query logic', () => { }) class TestComponent { value: string[]|undefined; - @ViewChildren('foo') query !: QueryList; + @ViewChildren('foo') query!: QueryList; } TestBed.configureTestingModule({declarations: [TestComponent]}); @@ -1082,7 +1079,6 @@ describe('query logic', () => { */ it('should notify on changes when a given view is removed and re-inserted at the same index', () => { - @Component({ selector: 'test-comp', template: ` @@ -1093,10 +1089,9 @@ describe('query logic', () => { class TestComponent implements AfterViewInit { queryListNotificationCounter = 0; - @ViewChild(ViewContainerManipulatorDirective) - vc !: ViewContainerManipulatorDirective; - @ViewChild('tpl') tpl !: TemplateRef; - @ViewChildren('foo') query !: QueryList; + @ViewChild(ViewContainerManipulatorDirective) vc!: ViewContainerManipulatorDirective; + @ViewChild('tpl') tpl!: TemplateRef; + @ViewChildren('foo') query!: QueryList; ngAfterViewInit() { this.query.changes.subscribe(() => this.queryListNotificationCounter++); @@ -1125,13 +1120,13 @@ describe('query logic', () => { it('should support a mix of content queries from the declaration and embedded view', () => { @Directive({selector: '[query-for-lots-of-content]'}) class QueryForLotsOfContent { - @ContentChildren('foo', {descendants: true}) foos1 !: QueryList; - @ContentChildren('foo', {descendants: true}) foos2 !: QueryList; + @ContentChildren('foo', {descendants: true}) foos1!: QueryList; + @ContentChildren('foo', {descendants: true}) foos2!: QueryList; } @Directive({selector: '[query-for-content]'}) class QueryForContent { - @ContentChildren('foo') foos !: QueryList; + @ContentChildren('foo') foos!: QueryList; } @Component({ @@ -1192,11 +1187,10 @@ describe('query logic', () => { `, }) class TestComponent { - @ViewChild(ViewContainerManipulatorDirective) - vc !: ViewContainerManipulatorDirective; - @ViewChild('tpl1') tpl1 !: TemplateRef; - @ViewChild('tpl2') tpl2 !: TemplateRef; - @ViewChildren('foo') query !: QueryList; + @ViewChild(ViewContainerManipulatorDirective) vc!: ViewContainerManipulatorDirective; + @ViewChild('tpl1') tpl1!: TemplateRef; + @ViewChild('tpl2') tpl2!: TemplateRef; + @ViewChildren('foo') query!: QueryList; } TestBed.configureTestingModule( @@ -1210,8 +1204,8 @@ describe('query logic', () => { expect(queryList.length).toBe(1); expect(queryList.first.nativeElement.getAttribute('id')).toBe('middle'); - vc.insertTpl(tpl1 !, {idx: 0}, 0); - vc.insertTpl(tpl2 !, {idx: 1}, 1); + vc.insertTpl(tpl1!, {idx: 0}, 0); + vc.insertTpl(tpl2!, {idx: 1}, 1); fixture.detectChanges(); expect(queryList.length).toBe(3); @@ -1220,7 +1214,7 @@ describe('query logic', () => { expect(qListArr[1].nativeElement.getAttribute('id')).toBe('middle'); expect(qListArr[2].nativeElement.getAttribute('id')).toBe('foo2_1'); - vc.insertTpl(tpl1 !, {idx: 1}, 1); + vc.insertTpl(tpl1!, {idx: 1}, 1); fixture.detectChanges(); expect(queryList.length).toBe(4); @@ -1264,10 +1258,10 @@ describe('query logic', () => { `, }) class TestComponent { - @ViewChild('tpl') tpl !: TemplateRef; - @ViewChild('vi0') vi0 !: ViewContainerManipulatorDirective; - @ViewChild('vi1') vi1 !: ViewContainerManipulatorDirective; - @ViewChildren('foo') query !: QueryList; + @ViewChild('tpl') tpl!: TemplateRef; + @ViewChild('vi0') vi0!: ViewContainerManipulatorDirective; + @ViewChild('vi1') vi1!: ViewContainerManipulatorDirective; + @ViewChildren('foo') query!: QueryList; } TestBed.configureTestingModule( @@ -1280,8 +1274,8 @@ describe('query logic', () => { expect(queryList.length).toBe(0); - vi0.insertTpl(tpl !, {idx: 0, container_idx: 0}, 0); - vi1.insertTpl(tpl !, {idx: 0, container_idx: 1}, 0); + vi0.insertTpl(tpl!, {idx: 0, container_idx: 0}, 0); + vi1.insertTpl(tpl!, {idx: 0, container_idx: 1}, 0); fixture.detectChanges(); expect(queryList.length).toBe(2); @@ -1315,7 +1309,7 @@ describe('query logic', () => { }) class MyApp { show = false; - @ViewChildren('foo') query !: QueryList; + @ViewChildren('foo') query!: QueryList; } TestBed.configureTestingModule({declarations: [MyApp], imports: [CommonModule]}); @@ -1334,14 +1328,11 @@ describe('query logic', () => { fixture.detectChanges(); expect(queryList.length).toBe(0); }); - }); }); describe('non-regression', () => { - it('should query by provider super-type in an embedded view', () => { - @Directive({selector: '[child]'}) class Child { } @@ -1356,7 +1347,7 @@ describe('query logic', () => { `
` }) class TestCmpt { - @ViewChildren(Child) instances !: QueryList; + @ViewChildren(Child) instances!: QueryList; } TestBed.configureTestingModule({declarations: [TestCmpt, Parent, Child]}); @@ -1367,7 +1358,6 @@ describe('query logic', () => { }); it('should flatten multi-provider results', () => { - class MyClass {} @Component({ @@ -1381,7 +1371,7 @@ describe('query logic', () => { @Component({selector: 'test-cmpt', template: ``}) class TestCmpt { - @ViewChildren(MyClass) queryResults !: QueryList; + @ViewChildren(MyClass) queryResults!: QueryList; } TestBed.configureTestingModule({declarations: [TestCmpt, WithMultiProvider]}); @@ -1393,7 +1383,6 @@ describe('query logic', () => { }); it('should flatten multi-provider results when crossing ng-template', () => { - class MyClass {} @Component({ @@ -1413,7 +1402,7 @@ describe('query logic', () => { ` }) class TestCmpt { - @ViewChildren(MyClass) queryResults !: QueryList; + @ViewChildren(MyClass) queryResults!: QueryList; } TestBed.configureTestingModule({declarations: [TestCmpt, WithMultiProvider]}); @@ -1444,7 +1433,7 @@ describe('query logic', () => { ` }) class App { - @ViewChild(GroupDir) group !: GroupDir; + @ViewChild(GroupDir) group!: GroupDir; } TestBed.configureTestingModule( @@ -1481,7 +1470,7 @@ describe('query logic', () => { ` }) class App { - @ViewChildren(GroupDir) groups !: QueryList; + @ViewChildren(GroupDir) groups!: QueryList; } TestBed.configureTestingModule( @@ -1497,9 +1486,7 @@ describe('query logic', () => { expect(groups[1]).toBeAnInstanceOf(GroupDir); expect(groups[2]).toBeUndefined(); }); - }); - }); function initWithTemplate(compType: Type, template: string) { @@ -1511,11 +1498,11 @@ function initWithTemplate(compType: Type, template: string) { @Component({selector: 'local-ref-query-component', template: ''}) class QueryComp { - @ViewChild('viewQuery') viewChild !: any; - @ContentChild('contentQuery') contentChild !: any; + @ViewChild('viewQuery') viewChild!: any; + @ContentChild('contentQuery') contentChild!: any; - @ViewChildren('viewQuery') viewChildren !: QueryList; - @ContentChildren('contentQuery') contentChildren !: QueryList; + @ViewChildren('viewQuery') viewChildren!: QueryList; + @ContentChildren('contentQuery') contentChildren!: QueryList; } @Component({selector: 'app-comp', template: ``}) @@ -1543,12 +1530,14 @@ class TextDirective { ` }) class StaticViewQueryComp { - private _textDir !: TextDirective; - private _foo !: ElementRef; + private _textDir!: TextDirective; + private _foo!: ElementRef; setEvents: string[] = []; @ViewChild(TextDirective, {static: true}) - get textDir(): TextDirective { return this._textDir; } + get textDir(): TextDirective { + return this._textDir; + } set textDir(value: TextDirective) { this.setEvents.push('textDir set'); @@ -1556,7 +1545,9 @@ class StaticViewQueryComp { } @ViewChild('foo') - get foo(): ElementRef { return this._foo; } + get foo(): ElementRef { + return this._foo; + } set foo(value: ElementRef) { this.setEvents.push('foo set'); @@ -1577,22 +1568,22 @@ class StaticViewQueryComp { ` }) class SubclassStaticViewQueryComp extends StaticViewQueryComp { - @ViewChild('bar', {static: true}) - bar !: ElementRef; + @ViewChild('bar', {static: true}) bar!: ElementRef; - @ViewChild('baz') - baz !: ElementRef; + @ViewChild('baz') baz!: ElementRef; } @Component({selector: 'static-content-query-comp', template: ``}) class StaticContentQueryComp { - private _textDir !: TextDirective; - private _foo !: ElementRef; + private _textDir!: TextDirective; + private _foo!: ElementRef; setEvents: string[] = []; @ContentChild(TextDirective, {static: true}) - get textDir(): TextDirective { return this._textDir; } + get textDir(): TextDirective { + return this._textDir; + } set textDir(value: TextDirective) { this.setEvents.push('textDir set'); @@ -1600,7 +1591,9 @@ class StaticContentQueryComp { } @ContentChild('foo') - get foo(): ElementRef { return this._foo; } + get foo(): ElementRef { + return this._foo; + } set foo(value: ElementRef) { this.setEvents.push('foo set'); @@ -1610,12 +1603,14 @@ class StaticContentQueryComp { @Directive({selector: '[staticContentQueryDir]'}) class StaticContentQueryDir { - private _textDir !: TextDirective; - private _foo !: ElementRef; + private _textDir!: TextDirective; + private _foo!: ElementRef; setEvents: string[] = []; @ContentChild(TextDirective, {static: true}) - get textDir(): TextDirective { return this._textDir; } + get textDir(): TextDirective { + return this._textDir; + } set textDir(value: TextDirective) { this.setEvents.push('textDir set'); @@ -1623,7 +1618,9 @@ class StaticContentQueryDir { } @ContentChild('foo') - get foo(): ElementRef { return this._foo; } + get foo(): ElementRef { + return this._foo; + } set foo(value: ElementRef) { this.setEvents.push('foo set'); @@ -1633,11 +1630,9 @@ class StaticContentQueryDir { @Component({selector: 'subclass-static-content-query-comp', template: ``}) class SubclassStaticContentQueryComp extends StaticContentQueryComp { - @ContentChild('bar', {static: true}) - bar !: ElementRef; + @ContentChild('bar', {static: true}) bar!: ElementRef; - @ContentChild('baz') - baz !: ElementRef; + @ContentChild('baz') baz!: ElementRef; } @Component({ @@ -1647,7 +1642,7 @@ class SubclassStaticContentQueryComp extends StaticContentQueryComp { ` }) export class QueryCompWithChanges { - @ViewChildren('foo') foos !: QueryList; + @ViewChildren('foo') foos!: QueryList; showing = false; } @@ -1658,7 +1653,7 @@ class SuperDirectiveQueryTarget { @Directive({selector: '[super-directive]'}) class SuperDirective { - @ViewChildren(SuperDirectiveQueryTarget) headers !: QueryList; + @ViewChildren(SuperDirectiveQueryTarget) headers!: QueryList; } @Component({ diff --git a/packages/core/test/acceptance/renderer_factory_spec.ts b/packages/core/test/acceptance/renderer_factory_spec.ts index f10269cf63b91..856997f47e8dc 100644 --- a/packages/core/test/acceptance/renderer_factory_spec.ts +++ b/packages/core/test/acceptance/renderer_factory_spec.ts @@ -24,19 +24,29 @@ describe('renderer factory lifecycle', () => { @Component({selector: 'some-component', template: `foo`}) class SomeComponent implements DoCheck { - ngOnInit() { logs.push('some_component create'); } - ngDoCheck() { logs.push('some_component update'); } + ngOnInit() { + logs.push('some_component create'); + } + ngDoCheck() { + logs.push('some_component update'); + } } @Component({selector: 'some-component-with-error', template: `With error`}) class SomeComponentWhichThrows { - ngOnInit() { throw new Error('SomeComponentWhichThrows threw'); } + ngOnInit() { + throw new Error('SomeComponentWhichThrows threw'); + } } @Component({selector: 'lol', template: ``}) class TestComponent implements DoCheck { - ngOnInit() { logs.push('test_component create'); } - ngDoCheck() { logs.push('test_component update'); } + ngOnInit() { + logs.push('test_component create'); + } + ngDoCheck() { + logs.push('test_component update'); + } } /** Creates a patched renderer factory that pushes entries to the test log */ @@ -44,7 +54,7 @@ describe('renderer factory lifecycle', () => { let rendererFactory = getRendererFactory2(document); const createRender = rendererFactory.createRenderer; - rendererFactory.createRenderer = (hostElement: any, type: RendererType2 | null) => { + rendererFactory.createRenderer = (hostElement: any, type: RendererType2|null) => { logs.push('create'); return createRender.apply(rendererFactory, [hostElement, type]); }; @@ -168,7 +178,7 @@ describe('animation renderer factory', () => { ]); player.finish(); - rendererFactory !.whenRenderingDone !().then(() => { + rendererFactory!.whenRenderingDone!().then(() => { expect(eventLogs).toEqual(['void - start', 'void - done', 'on - start', 'on - done']); done(); }); diff --git a/packages/core/test/acceptance/styling_spec.ts b/packages/core/test/acceptance/styling_spec.ts index 02397afb41e43..8f1fc30b54320 100644 --- a/packages/core/test/acceptance/styling_spec.ts +++ b/packages/core/test/acceptance/styling_spec.ts @@ -440,11 +440,12 @@ describe('styling', () => { @Directive({selector: '[dir-shadows-class-input]'}) class DirectiveShadowsClassInput { - @Input('class') - klass: string|undefined; + @Input('class') klass: string|undefined; @HostBinding('class') - get hostClasses() { return `${this.klass} SUFFIX`; } + get hostClasses() { + return `${this.klass} SUFFIX`; + } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveShadowsClassInput]}); @@ -671,7 +672,7 @@ describe('styling', () => { it('should be able to bind zero', () => { @Component({template: '
'}) class App { - @ViewChild('div') div !: ElementRef; + @ViewChild('div') div!: ElementRef; opacity = 0; } @@ -685,7 +686,7 @@ describe('styling', () => { it('should be able to bind a SafeValue to backgroundImage', () => { @Component({template: '
'}) class Cmp { - image !: SafeStyle; + image!: SafeStyle; } TestBed.configureTestingModule({declarations: [Cmp]}); @@ -724,7 +725,7 @@ describe('styling', () => { it('should be able to bind a SafeValue to clip-path', () => { @Component({template: '
'}) class Cmp { - path !: SafeStyle; + path!: SafeStyle; } TestBed.configureTestingModule({declarations: [Cmp]}); @@ -1011,15 +1012,15 @@ describe('styling', () => { expect(capturedClassBindingCount).toEqual(1); expect(capturedClassBindingValue as any).toEqual(null); expect(capturedMyClassBindingCount).toEqual(1); - expect(capturedMyClassBindingValue !).toEqual('foo'); + expect(capturedMyClassBindingValue!).toEqual('foo'); fixture.componentInstance.c = 'dynamic-value'; fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(2); - expect(capturedClassBindingValue !).toEqual('dynamic-value'); + expect(capturedClassBindingValue!).toEqual('dynamic-value'); expect(capturedMyClassBindingCount).toEqual(1); - expect(capturedMyClassBindingValue !).toEqual('foo'); + expect(capturedMyClassBindingValue!).toEqual('foo'); fixture.componentInstance.c = null; fixture.detectChanges(); @@ -1027,7 +1028,7 @@ describe('styling', () => { expect(capturedClassBindingCount).toEqual(3); expect(capturedClassBindingValue as any).toEqual(null); expect(capturedMyClassBindingCount).toEqual(1); - expect(capturedMyClassBindingValue !).toEqual('foo'); + expect(capturedMyClassBindingValue!).toEqual('foo'); fixture.componentInstance.c = ''; fixture.detectChanges(); @@ -1035,7 +1036,7 @@ describe('styling', () => { expect(capturedClassBindingCount).toEqual(4); expect(capturedClassBindingValue as any).toEqual(''); expect(capturedMyClassBindingCount).toEqual(1); - expect(capturedMyClassBindingValue !).toEqual('foo'); + expect(capturedMyClassBindingValue!).toEqual('foo'); }); it('should write to [class] binding during `update` mode if there is an instantiation-level value', @@ -1069,7 +1070,7 @@ describe('styling', () => { fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(2); - expect(capturedClassBindingValue !).toEqual('dynamic-bar'); + expect(capturedClassBindingValue!).toEqual('dynamic-bar'); }); it('should write to a `class` input binding if there is a static class value', () => { @@ -1102,9 +1103,9 @@ describe('styling', () => { const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); - expect(capturedClassBindingValue !).toEqual('static-val'); + expect(capturedClassBindingValue!).toEqual('static-val'); expect(capturedClassBindingCount).toEqual(1); - expect(capturedMyClassBindingValue !).toEqual('foo'); + expect(capturedMyClassBindingValue!).toEqual('foo'); expect(capturedMyClassBindingCount).toEqual(1); }); @@ -1195,19 +1196,19 @@ describe('styling', () => { // would check if we possibly have this situation on every `advance()` // instruction. We don't think this is worth it, and we are just going to live // with this. - ); - expect(capturedClassBindingValue !).toEqual('static-val'); + ); + expect(capturedClassBindingValue!).toEqual('static-val'); expect(capturedMyClassBindingCount).toEqual(1); - expect(capturedMyClassBindingValue !).toEqual('foo'); + expect(capturedMyClassBindingValue!).toEqual('foo'); capturedClassBindingCount = 0; fixture.componentInstance.c = 'dynamic-val'; fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(1); - expect(capturedClassBindingValue !).toEqual('static-val dynamic-val'); + expect(capturedClassBindingValue!).toEqual('static-val dynamic-val'); expect(capturedMyClassBindingCount).toEqual(1); - expect(capturedMyClassBindingValue !).toEqual('foo'); + expect(capturedMyClassBindingValue!).toEqual('foo'); }); onlyInIvy('only ivy balances styling across directives and component host bindings') @@ -1240,7 +1241,6 @@ describe('styling', () => { }); describe('NgClass', () => { - // We had a bug where NgClass would not allocate sufficient slots for host bindings, // so it would overwrite information about other directives nearby. This test checks // that TestDir's injector is not overwritten by NgClass, so TestDir should still @@ -1297,7 +1297,7 @@ describe('styling', () => { template: '', }) class App { - @ViewChild(Dir) dir !: Dir; + @ViewChild(Dir) dir!: Dir; classes = 'math'; style = '80s'; @@ -1315,8 +1315,7 @@ describe('styling', () => { it('should be able to bind to `className`', () => { @Component({template: ''}) class App { - @HostBinding('className') - klass = 'one two'; + @HostBinding('className') klass = 'one two'; } TestBed.configureTestingModule({declarations: [App]}); @@ -1471,8 +1470,7 @@ describe('styling', () => { opacity: string|null = '0.5'; @ViewChild(CompWithStyling, {static: true}) compWithStyling: CompWithStyling|null = null; - @ViewChild(DirWithStyling, {static: true}) - dirWithStyling: DirWithStyling|null = null; + @ViewChild(DirWithStyling, {static: true}) dirWithStyling: DirWithStyling|null = null; } TestBed.configureTestingModule({declarations: [Cmp, DirWithStyling, CompWithStyling]}); @@ -1488,13 +1486,13 @@ describe('styling', () => { expect(element.style.fontSize).toEqual('100px'); // once for the template flush and again for the host bindings - expect(ngDevMode !.rendererSetStyle).toEqual(4); + expect(ngDevMode!.rendererSetStyle).toEqual(4); ngDevModeResetPerfCounters(); component.opacity = '0.6'; - component.compWithStyling !.height = '100px'; - component.compWithStyling !.width = '100px'; - component.dirWithStyling !.fontSize = '50px'; + component.compWithStyling!.height = '100px'; + component.compWithStyling!.width = '100px'; + component.dirWithStyling!.fontSize = '50px'; fixture.detectChanges(); expect(element.style.opacity).toEqual('0.6'); @@ -1503,7 +1501,7 @@ describe('styling', () => { expect(element.style.fontSize).toEqual('50px'); // once for the template flush and again for the host bindings - expect(ngDevMode !.rendererSetStyle).toEqual(4); + expect(ngDevMode!.rendererSetStyle).toEqual(4); }); onlyInIvy('ivy resolves styling across directives, components and templates in unison') @@ -1634,8 +1632,12 @@ describe('styling', () => { public c: {[key: string]: any}|null = null; updateClasses(classes: string) { const c = this.c || (this.c = {}); - Object.keys(this.c).forEach(className => { c[className] = false; }); - classes.split(/\s+/).forEach(className => { c[className] = true; }); + Object.keys(this.c).forEach(className => { + c[className] = false; + }); + classes.split(/\s+/).forEach(className => { + c[className] = true; + }); } public s: {[key: string]: any}|null = null; @@ -1694,8 +1696,7 @@ describe('styling', () => { map: any = {width: '111px', opacity: '0.5'}; width: string|null|undefined = '555px'; - @ViewChild('dir', {read: DirThatSetsStyling, static: true}) - dir !: DirThatSetsStyling; + @ViewChild('dir', {read: DirThatSetsStyling, static: true}) dir!: DirThatSetsStyling; } TestBed.configureTestingModule({declarations: [Cmp, DirThatSetsStyling]}); @@ -1763,8 +1764,7 @@ describe('styling', () => { map: any = {width: '555px', height: '555px'}; - @ViewChild('dir', {read: DirThatSetsStyling, static: true}) - dir !: DirThatSetsStyling; + @ViewChild('dir', {read: DirThatSetsStyling, static: true}) dir!: DirThatSetsStyling; } TestBed.configureTestingModule({declarations: [Cmp, DirThatSetsStyling]}); @@ -1991,7 +1991,7 @@ describe('styling', () => { it('should be able to bind a SafeValue to clip-path', () => { @Component({template: '
'}) class Cmp { - path !: SafeStyle; + path!: SafeStyle; } TestBed.configureTestingModule({declarations: [Cmp]}); @@ -2028,12 +2028,22 @@ describe('styling', () => { public background: string = '1.png'; public color: string = 'red'; - private getSafeStyle(value: string) { return this.sanitizer.bypassSecurityTrustStyle(value); } + private getSafeStyle(value: string) { + return this.sanitizer.bypassSecurityTrustStyle(value); + } - getBackgroundSafe() { return this.getSafeStyle(`url("/${this.background}")`); } - getWidthSafe() { return this.getSafeStyle(this.width); } - getHeightSafe() { return this.getSafeStyle(this.height); } - getColorUnsafe() { return this.color; } + getBackgroundSafe() { + return this.getSafeStyle(`url("/${this.background}")`); + } + getWidthSafe() { + return this.getSafeStyle(this.width); + } + getHeightSafe() { + return this.getSafeStyle(this.height); + } + getColorUnsafe() { + return this.color; + } } TestBed.configureTestingModule({ @@ -2089,11 +2099,9 @@ describe('styling', () => { class Cmp { map: any = null; - @ViewChild('div', {read: DirWithStyleMap, static: true}) - dir1 !: DirWithStyleMap; + @ViewChild('div', {read: DirWithStyleMap, static: true}) dir1!: DirWithStyleMap; - @ViewChild('div', {read: DirWithStyleMapPart2, static: true}) - dir2 !: DirWithStyleMapPart2; + @ViewChild('div', {read: DirWithStyleMapPart2, static: true}) dir2!: DirWithStyleMapPart2; } TestBed.configureTestingModule( @@ -2352,8 +2360,8 @@ describe('styling', () => { @Component({template: '
'}) class Cmp { - @ViewChild('target', {read: DirOne, static: true}) one !: DirOne; - @ViewChild('target', {read: DirTwo, static: true}) two !: DirTwo; + @ViewChild('target', {read: DirOne, static: true}) one!: DirOne; + @ViewChild('target', {read: DirTwo, static: true}) two!: DirTwo; } TestBed.configureTestingModule({declarations: [Cmp, DirOne, DirTwo]}); @@ -2443,7 +2451,9 @@ describe('styling', () => { class Cmp { s: any = {opacity: '1'}; - clearStyle(): void { this.s = null; } + clearStyle(): void { + this.s = null; + } } TestBed.configureTestingModule({declarations: [Cmp]}); @@ -2471,8 +2481,7 @@ describe('styling', () => { class ChildCmp { readyTpl = false; - @HostBinding('class.ready-host') - readyHost = false; + @HostBinding('class.ready-host') readyHost = false; } @Component({ @@ -2490,10 +2499,9 @@ describe('styling', () => { class ParentCmp { private _prop = ''; - @ViewChild('template', {read: ViewContainerRef}) - vcr: ViewContainerRef = null !; + @ViewChild('template', {read: ViewContainerRef}) vcr: ViewContainerRef = null!; - private child: ComponentRef = null !; + private child: ComponentRef = null!; @Input() set prop(value: string) { @@ -2505,7 +2513,9 @@ describe('styling', () => { } } - get prop() { return this._prop; } + get prop() { + return this._prop; + } ngAfterViewInit() { const factory = this.componentFactoryResolver.resolveComponentFactory(ChildCmp); @@ -2559,8 +2569,7 @@ describe('styling', () => { class ChildCmp { readyTpl = false; - @HostBinding('class.ready-host') - readyHost = false; + @HostBinding('class.ready-host') readyHost = false; } @Component({ @@ -2575,10 +2584,9 @@ describe('styling', () => { class ParentCmp { updateChild = false; - @ViewChild('template', {read: ViewContainerRef}) - vcr: ViewContainerRef = null !; + @ViewChild('template', {read: ViewContainerRef}) vcr: ViewContainerRef = null!; - private child: ComponentRef = null !; + private child: ComponentRef = null!; ngDoCheck() { if (this.updateChild) { @@ -2619,7 +2627,7 @@ describe('styling', () => { expect(readyHost).toBeFalsy(); expect(readyChild).toBeFalsy(); - const parent = fixture.componentInstance.parent !; + const parent = fixture.componentInstance.parent!; parent.updateChild = true; fixture.detectChanges(false); @@ -2675,7 +2683,9 @@ describe('styling', () => { selector: '[dir]', }) class Dir { - constructor(public elementRef: ElementRef, public renderer: Renderer2) { dirInstance = this; } + constructor(public elementRef: ElementRef, public renderer: Renderer2) { + dirInstance = this; + } setStyles() { const nativeEl = this.elementRef.nativeElement; @@ -2730,11 +2740,9 @@ describe('styling', () => { () => { @Directive({selector: '[blockStyles]'}) class StylesDirective { - @HostBinding('style.border') - border = '1px solid red'; + @HostBinding('style.border') border = '1px solid red'; - @HostBinding('style.background') - background = 'white'; + @HostBinding('style.background') background = 'white'; } @Component({ @@ -2863,7 +2871,7 @@ describe('styling', () => { TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(MyComp); fixture.detectChanges(); - const div = fixture.nativeElement.querySelector('div') !; + const div = fixture.nativeElement.querySelector('div')!; div.className += ' abc'; expect(splitSortJoin(div.className)).toEqual('abc'); @@ -2877,7 +2885,9 @@ describe('styling', () => { expect(splitSortJoin(div.className)).toEqual('4 5 6 7 abc'); - function splitSortJoin(s: string) { return s.split(/\s+/).sort().join(' ').trim(); } + function splitSortJoin(s: string) { + return s.split(/\s+/).sort().join(' ').trim(); + } }); describe('ExpressionChangedAfterItHasBeenCheckedError', () => { @@ -2885,7 +2895,9 @@ describe('styling', () => { @Component({template: `
`}) class MyComp { icon = 'https://i.imgur.com/4AiXzf8.jpg'; - get iconSafe() { return this.sanitizer.bypassSecurityTrustStyle(`url("${this.icon}")`); } + get iconSafe() { + return this.sanitizer.bypassSecurityTrustStyle(`url("${this.icon}")`); + } constructor(private sanitizer: DomSanitizer) {} } @@ -2951,7 +2963,7 @@ describe('styling', () => { TestBed.configureTestingModule({declarations: [MyComp, DirThatSetsStyling]}) .createComponent(MyComp); fixture.detectChanges(); - const div = fixture.nativeElement.querySelector('div') !; + const div = fixture.nativeElement.querySelector('div')!; expect(div.style.getPropertyValue('width')).toEqual('100px'); expect(div.style.getPropertyValue('height')).toEqual('200px'); expect(div.style.getPropertyValue('font-size')).toEqual('300px'); @@ -3051,20 +3063,16 @@ describe('styling', () => { () => { @Component({selector: 'my-comp-with-styling', template: ''}) class MyCompWithStyling { - @HostBinding('style') - myStyles: any = {width: '300px'}; + @HostBinding('style') myStyles: any = {width: '300px'}; - @HostBinding('style.height') - myHeight: any = '305px'; + @HostBinding('style.height') myHeight: any = '305px'; } @Directive({selector: '[my-dir-with-styling]'}) class MyDirWithStyling { - @HostBinding('style') - myStyles: any = {width: '200px'}; + @HostBinding('style') myStyles: any = {width: '200px'}; - @HostBinding('style.height') - myHeight: any = '205px'; + @HostBinding('style.height') myHeight: any = '205px'; } @Component({ @@ -3081,15 +3089,15 @@ describe('styling', () => { myStyles: {width?: string} = {width: '100px'}; myHeight: string|null|undefined = '100px'; - @ViewChild(MyDirWithStyling) dir !: MyDirWithStyling; - @ViewChild(MyCompWithStyling) comp !: MyCompWithStyling; + @ViewChild(MyDirWithStyling) dir!: MyDirWithStyling; + @ViewChild(MyCompWithStyling) comp!: MyCompWithStyling; } TestBed.configureTestingModule( {declarations: [MyComp, MyCompWithStyling, MyDirWithStyling]}); const fixture = TestBed.createComponent(MyComp); const comp = fixture.componentInstance; - const elm = fixture.nativeElement.querySelector('my-comp-with-styling') !; + const elm = fixture.nativeElement.querySelector('my-comp-with-styling')!; fixture.detectChanges(); expect(elm.style.width).toEqual('100px'); @@ -3131,7 +3139,7 @@ describe('styling', () => { TestBed.configureTestingModule( {declarations: [MyComp, MyCompWithStyling, MyDirWithStyling]}); const fixture = TestBed.createComponent(MyComp); - const elm = fixture.nativeElement.querySelector('my-comp-with-styling') !; + const elm = fixture.nativeElement.querySelector('my-comp-with-styling')!; fixture.detectChanges(); expect(elm.style.color).toEqual('red'); @@ -3139,7 +3147,6 @@ describe('styling', () => { it('should combine host class.foo bindings from multiple directives', () => { - @Directive({ selector: '[dir-that-sets-one-two]', exportAs: 'one', @@ -3197,8 +3204,8 @@ describe('styling', () => { expect(div2.className).toBe(''); const comp = fixture.componentInstance; - comp.dirOneA !.one = comp.dirOneB !.one = true; - comp.dirOneA !.two = comp.dirOneB !.two = true; + comp.dirOneA!.one = comp.dirOneB!.one = true; + comp.dirOneA!.two = comp.dirOneB!.two = true; fixture.detectChanges(); expect(div1.classList.contains('one')).toBeTruthy(); @@ -3211,8 +3218,8 @@ describe('styling', () => { expect(div2.classList.contains('four')).toBeFalsy(); expect(div2.classList.contains('zero')).toBeFalsy(); - comp.dirTwoA !.three = comp.dirTwoB !.three = true; - comp.dirTwoA !.four = comp.dirTwoB !.four = true; + comp.dirTwoA!.three = comp.dirTwoB!.three = true; + comp.dirTwoA!.four = comp.dirTwoB!.four = true; fixture.detectChanges(); expect(div1.classList.contains('one')).toBeTruthy(); @@ -3242,7 +3249,9 @@ describe('styling', () => { it('should combine static host classes with component "class" host attribute', () => { @Component({selector: 'comp-with-classes', template: '', host: {'class': 'host'}}) class CompWithClasses { - constructor(ref: ElementRef) { ref.nativeElement.classList.add('custom'); } + constructor(ref: ElementRef) { + ref.nativeElement.classList.add('custom'); + } } @Component({ @@ -3282,8 +3291,7 @@ describe('styling', () => { @Directive({selector: '[single-host-style-dir]'}) class SingleHostStyleDir { - @HostBinding('style.width') - width = '100px'; + @HostBinding('style.width') width = '100px'; } TestBed.configureTestingModule({declarations: [Cmp, SingleHostStyleDir]}); @@ -3340,7 +3348,9 @@ describe('styling', () => { @Directive({selector: '[test]'}) class MyDir { @Input('class') - set className(value: string) { logs.push(value); } + set className(value: string) { + logs.push(value); + } } @Component({ @@ -3456,8 +3466,7 @@ describe('styling', () => { template: `className = {{className}}`, }) class MyCmp { - @Input() - className: string = 'unbound'; + @Input() className: string = 'unbound'; } @Component({template: ``}) class MyApp { @@ -3475,8 +3484,7 @@ describe('styling', () => { template: `className = {{className}}`, }) class MyCmp { - @Input() - className: string = 'unbound'; + @Input() className: string = 'unbound'; } @Component({template: ``}) class MyApp { @@ -3491,8 +3499,8 @@ describe('styling', () => { }); function assertStyleCounters(countForSet: number, countForRemove: number) { - expect(ngDevMode !.rendererSetStyle).toEqual(countForSet); - expect(ngDevMode !.rendererRemoveStyle).toEqual(countForRemove); + expect(ngDevMode!.rendererSetStyle).toEqual(countForSet); + expect(ngDevMode!.rendererRemoveStyle).toEqual(countForRemove); } function assertStyle(element: HTMLElement, prop: string, value: any) { diff --git a/packages/core/test/acceptance/template_ref_spec.ts b/packages/core/test/acceptance/template_ref_spec.ts index b55018e8ec91f..026dcc2c5a464 100644 --- a/packages/core/test/acceptance/template_ref_spec.ts +++ b/packages/core/test/acceptance/template_ref_spec.ts @@ -13,11 +13,9 @@ import {ivyEnabled, onlyInIvy} from '@angular/private/testing'; describe('TemplateRef', () => { describe('rootNodes', () => { - @Component({template: ``}) class App { - @ViewChild('templateRef', {static: true}) - templateRef !: TemplateRef; + @ViewChild('templateRef', {static: true}) templateRef!: TemplateRef; minutes = 0; } @@ -80,7 +78,7 @@ describe('TemplateRef', () => { ` }) class App { - @ViewChild(MenuContent) content !: MenuContent; + @ViewChild(MenuContent) content!: MenuContent; constructor(public viewContainerRef: ViewContainerRef) {} } diff --git a/packages/core/test/acceptance/text_spec.ts b/packages/core/test/acceptance/text_spec.ts index 9f666ef49a9ac..ff16353b99595 100644 --- a/packages/core/test/acceptance/text_spec.ts +++ b/packages/core/test/acceptance/text_spec.ts @@ -7,7 +7,7 @@ */ import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; -import {of } from 'rxjs'; +import {of} from 'rxjs'; describe('text instructions', () => { it('should handle all flavors of interpolated text', () => { @@ -66,8 +66,8 @@ describe('text instructions', () => { ` }) class App { - who = of ('Sally'); - item = of ({ + who = of('Sally'); + item = of({ what: 'seashells', where: 'seashore', }); diff --git a/packages/core/test/acceptance/view_container_ref_spec.ts b/packages/core/test/acceptance/view_container_ref_spec.ts index 13f1a2c137dfb..cfa09f498bf37 100644 --- a/packages/core/test/acceptance/view_container_ref_spec.ts +++ b/packages/core/test/acceptance/view_container_ref_spec.ts @@ -8,7 +8,7 @@ import {CommonModule, DOCUMENT} from '@angular/common'; import {computeMsgId} from '@angular/compiler'; -import {Compiler, Component, ComponentFactoryResolver, Directive, DoCheck, ElementRef, EmbeddedViewRef, ErrorHandler, Injector, NO_ERRORS_SCHEMA, NgModule, OnInit, Pipe, PipeTransform, QueryList, RendererFactory2, RendererType2, Sanitizer, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, ɵsetDocument} from '@angular/core'; +import {Compiler, Component, ComponentFactoryResolver, Directive, DoCheck, ElementRef, EmbeddedViewRef, ErrorHandler, Injector, NgModule, NO_ERRORS_SCHEMA, OnInit, Pipe, PipeTransform, QueryList, RendererFactory2, RendererType2, Sanitizer, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, ɵsetDocument} from '@angular/core'; import {Input} from '@angular/core/src/metadata'; import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode'; import {TestBed, TestComponentRenderer} from '@angular/core/testing'; @@ -18,7 +18,6 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; import {ivyEnabled, onlyInIvy} from '@angular/private/testing'; describe('ViewContainerRef', () => { - /** * Gets the inner HTML of the given element with all HTML comments and Angular internal * reflect attributes omitted. This makes HTML comparisons easier and less verbose. @@ -40,7 +39,6 @@ describe('ViewContainerRef', () => { afterEach(() => clearTranslations()); describe('create', () => { - it('should support view queries inside embedded views created in dir constructors', () => { const fixture = TestBed.createComponent(ConstructorApp); fixture.detectChanges(); @@ -87,7 +85,7 @@ describe('ViewContainerRef', () => { ` }) class TestComp { - @ViewChild(VCRefDirective, {static: true}) vcRefDir !: VCRefDirective; + @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } TestBed.configureTestingModule( @@ -141,7 +139,7 @@ describe('ViewContainerRef', () => { ` }) class TestComp { - @ViewChild('container', {read: ViewContainerRef}) vcRef !: ViewContainerRef; + @ViewChild('container', {read: ViewContainerRef}) vcRef!: ViewContainerRef; constructor(public cfr: ComponentFactoryResolver) {} @@ -196,8 +194,8 @@ describe('ViewContainerRef', () => { ` }) class TestComp { - @ViewChild('svg', {read: ViewContainerRef}) svgVCRef !: ViewContainerRef; - @ViewChild('mathml', {read: ViewContainerRef}) mathMLVCRef !: ViewContainerRef; + @ViewChild('svg', {read: ViewContainerRef}) svgVCRef!: ViewContainerRef; + @ViewChild('mathml', {read: ViewContainerRef}) mathMLVCRef!: ViewContainerRef; constructor(public cfr: ComponentFactoryResolver) {} @@ -273,7 +271,7 @@ describe('ViewContainerRef', () => { ` }) class TestComp { - @ViewChild('container', {read: ViewContainerRef}) vcRef !: ViewContainerRef; + @ViewChild('container', {read: ViewContainerRef}) vcRef!: ViewContainerRef; private helloCompFactory = this.cfr.resolveComponentFactory(HelloComp); @@ -357,7 +355,9 @@ describe('ViewContainerRef', () => { // Insert the view again at the same index viewContainerRef.insert(ref0, 0); - expect(() => { fixture.destroy(); }).not.toThrow(); + expect(() => { + fixture.destroy(); + }).not.toThrow(); expect(fixture.nativeElement.textContent).toEqual('0'); }); @@ -405,7 +405,6 @@ describe('ViewContainerRef', () => { }); it('should insert a view already inserted into another container', () => { - @Component({ selector: 'test-cmpt', template: ` @@ -414,9 +413,9 @@ describe('ViewContainerRef', () => { ` }) class TestComponent { - @ViewChild('t', {static: true}) t !: TemplateRef<{}>; - @ViewChild('c1', {static: true, read: ViewContainerRef}) c1 !: ViewContainerRef; - @ViewChild('c2', {static: true, read: ViewContainerRef}) c2 !: ViewContainerRef; + @ViewChild('t', {static: true}) t!: TemplateRef<{}>; + @ViewChild('c1', {static: true, read: ViewContainerRef}) c1!: ViewContainerRef; + @ViewChild('c2', {static: true, read: ViewContainerRef}) c2!: ViewContainerRef; } TestBed.configureTestingModule({declarations: [TestComponent]}); @@ -660,7 +659,6 @@ describe('ViewContainerRef', () => { }); describe('get and indexOf', () => { - beforeEach(() => { TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]}); }); @@ -677,13 +675,13 @@ describe('ViewContainerRef', () => { fixture.detectChanges(); let viewRef = vcRefDir.vcref.get(0); - expect(vcRefDir.vcref.indexOf(viewRef !)).toEqual(0); + expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(0); viewRef = vcRefDir.vcref.get(1); - expect(vcRefDir.vcref.indexOf(viewRef !)).toEqual(1); + expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(1); viewRef = vcRefDir.vcref.get(2); - expect(vcRefDir.vcref.indexOf(viewRef !)).toEqual(2); + expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(2); }); it('should handle out of bounds cases', () => { @@ -700,7 +698,7 @@ describe('ViewContainerRef', () => { const viewRef = vcRefDir.vcref.get(0); vcRefDir.vcref.remove(0); - expect(vcRefDir.vcref.indexOf(viewRef !)).toEqual(-1); + expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(-1); }); it('should return -1 as indexOf when no views were inserted', () => { @@ -742,21 +740,21 @@ describe('ViewContainerRef', () => { expect(getElementHtml(fixture.nativeElement)).toEqual('

**A**BC'); let viewRef = vcRefDir.vcref.get(0); - vcRefDir.vcref.move(viewRef !, 2); + vcRefDir.vcref.move(viewRef!, 2); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('

BC**A**'); - vcRefDir.vcref.move(viewRef !, 0); + vcRefDir.vcref.move(viewRef!, 0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('

**A**BC'); - vcRefDir.vcref.move(viewRef !, 1); + vcRefDir.vcref.move(viewRef!, 1); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('

B**A**C'); // Invalid indices when detaching throws an exception in Ivy: FW-1330. - ivyEnabled && expect(() => vcRefDir.vcref.move(viewRef !, -1)).toThrow(); - ivyEnabled && expect(() => vcRefDir.vcref.move(viewRef !, 42)).toThrow(); + ivyEnabled && expect(() => vcRefDir.vcref.move(viewRef!, -1)).toThrow(); + ivyEnabled && expect(() => vcRefDir.vcref.move(viewRef!, 42)).toThrow(); }); }); @@ -769,7 +767,7 @@ describe('ViewContainerRef', () => { ` }) class TestComponent { - @ViewChild(VCRefDirective, {static: true}) vcRefDir !: VCRefDirective; + @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } TestBed.configureTestingModule({declarations: [VCRefDirective, TestComponent]}); @@ -789,7 +787,6 @@ describe('ViewContainerRef', () => { }); describe('detach', () => { - beforeEach(() => { TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]}); @@ -825,7 +822,7 @@ describe('ViewContainerRef', () => { // Invalid indices when detaching throws an exception in Ivy: FW-1330. ivyEnabled && expect(() => vcRefDir.vcref.detach(-1)).toThrow(); ivyEnabled && expect(() => vcRefDir.vcref.detach(42)).toThrow(); - ivyEnabled && expect(ngDevMode !.rendererDestroyNode).toBe(0); + ivyEnabled && expect(ngDevMode!.rendererDestroyNode).toBe(0); }); it('should detach the last embedded view when no index is specified', () => { @@ -846,7 +843,7 @@ describe('ViewContainerRef', () => { fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('

ABCD'); expect(viewE.destroyed).toBeFalsy(); - ivyEnabled && expect(ngDevMode !.rendererDestroyNode).toBe(0); + ivyEnabled && expect(ngDevMode!.rendererDestroyNode).toBe(0); }); }); @@ -895,7 +892,7 @@ describe('ViewContainerRef', () => { // Invalid indices when detaching throws an exception in Ivy: FW-1330. ivyEnabled && expect(() => vcRefDir.vcref.remove(-1)).toThrow(); ivyEnabled && expect(() => vcRefDir.vcref.remove(42)).toThrow(); - ivyEnabled && expect(ngDevMode !.rendererDestroyNode).toBe(2); + ivyEnabled && expect(ngDevMode!.rendererDestroyNode).toBe(2); }); it('should remove the last embedded view when no index is specified', () => { @@ -916,7 +913,7 @@ describe('ViewContainerRef', () => { fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('

ABCD'); expect(viewE.destroyed).toBeTruthy(); - ivyEnabled && expect(ngDevMode !.rendererDestroyNode).toBe(1); + ivyEnabled && expect(ngDevMode!.rendererDestroyNode).toBe(1); }); it('should throw when trying to insert a removed or destroyed view', () => { @@ -1063,7 +1060,7 @@ describe('ViewContainerRef', () => { ` }) class TestComponent { - @ViewChild(VCRefDirective, {static: true}) vcRef !: VCRefDirective; + @ViewChild(VCRefDirective, {static: true}) vcRef!: VCRefDirective; } TestBed.configureTestingModule({declarations: [TestComponent, VCRefDirective]}); @@ -1087,8 +1084,8 @@ describe('ViewContainerRef', () => { expect(getElementHtml(fixture.nativeElement)).toEqual('YABC
'); // Invalid indices when detaching throws an exception in Ivy: FW-1330. - ivyEnabled && expect(() => vcRef !.createView('Z', -1)).toThrow(); - ivyEnabled && expect(() => vcRef !.createView('Z', 5)).toThrow(); + ivyEnabled && expect(() => vcRef!.createView('Z', -1)).toThrow(); + ivyEnabled && expect(() => vcRef!.createView('Z', 5)).toThrow(); }); it('should apply directives and pipes of the host view to the TemplateRef', () => { @@ -1099,7 +1096,9 @@ describe('ViewContainerRef', () => { @Pipe({name: 'starPipe'}) class StarPipe implements PipeTransform { - transform(value: any) { return `**${value}**`; } + transform(value: any) { + return `**${value}**`; + } } @Component({ @@ -1121,15 +1120,14 @@ describe('ViewContainerRef', () => { fixture.debugElement.query(By.directive(VCRefDirective)).injector.get(VCRefDirective); fixture.detectChanges(); - vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef !); - vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef !); + vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); + vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)) .toEqual( '**A****C****C****B**'); }); - }); describe('createComponent', () => { @@ -1140,9 +1138,13 @@ describe('ViewContainerRef', () => { it('should work without Injector and NgModuleRef', () => { @Component({selector: 'embedded-cmp', template: `foo`}) class EmbeddedComponent implements DoCheck, OnInit { - ngOnInit() { templateExecutionCounter++; } + ngOnInit() { + templateExecutionCounter++; + } - ngDoCheck() { templateExecutionCounter++; } + ngDoCheck() { + templateExecutionCounter++; + } } @NgModule({entryComponents: [EmbeddedComponent], declarations: [EmbeddedComponent]}) @@ -1185,13 +1187,16 @@ describe('ViewContainerRef', () => { selector: 'embedded-cmp', template: `foo`, }) - class EmbeddedComponent implements DoCheck, - OnInit { + class EmbeddedComponent implements DoCheck, OnInit { constructor(public s: String) {} - ngOnInit() { templateExecutionCounter++; } + ngOnInit() { + templateExecutionCounter++; + } - ngDoCheck() { templateExecutionCounter++; } + ngDoCheck() { + templateExecutionCounter++; + } } @NgModule({entryComponents: [EmbeddedComponent], declarations: [EmbeddedComponent]}) @@ -1423,7 +1428,7 @@ describe('ViewContainerRef', () => { const makeComponentFactory = (componentType: any) => ({ create: () => TestBed.createComponent(componentType).componentRef, }); - this.viewContainerRef !.createComponent(makeComponentFactory(Child) as any); + this.viewContainerRef!.createComponent(makeComponentFactory(Child) as any); } } @@ -1493,8 +1498,8 @@ describe('ViewContainerRef', () => { `, }) class LoopComp { - @Input() tpl !: TemplateRef; - @Input() rows !: any[]; + @Input() tpl!: TemplateRef; + @Input() rows!: any[]; name = 'Loop'; } @@ -1715,7 +1720,6 @@ describe('ViewContainerRef', () => { }); describe('lifecycle hooks', () => { - // Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-vcref const log: string[] = []; @@ -1723,19 +1727,37 @@ describe('ViewContainerRef', () => { class ComponentWithHooks { @Input() name: string|undefined; - private log(msg: string) { log.push(msg); } + private log(msg: string) { + log.push(msg); + } - ngOnChanges() { this.log('onChanges-' + this.name); } - ngOnInit() { this.log('onInit-' + this.name); } - ngDoCheck() { this.log('doCheck-' + this.name); } + ngOnChanges() { + this.log('onChanges-' + this.name); + } + ngOnInit() { + this.log('onInit-' + this.name); + } + ngDoCheck() { + this.log('doCheck-' + this.name); + } - ngAfterContentInit() { this.log('afterContentInit-' + this.name); } - ngAfterContentChecked() { this.log('afterContentChecked-' + this.name); } + ngAfterContentInit() { + this.log('afterContentInit-' + this.name); + } + ngAfterContentChecked() { + this.log('afterContentChecked-' + this.name); + } - ngAfterViewInit() { this.log('afterViewInit-' + this.name); } - ngAfterViewChecked() { this.log('afterViewChecked-' + this.name); } + ngAfterViewInit() { + this.log('afterViewInit-' + this.name); + } + ngAfterViewChecked() { + this.log('afterViewChecked-' + this.name); + } - ngOnDestroy() { this.log('onDestroy-' + this.name); } + ngOnDestroy() { + this.log('onDestroy-' + this.name); + } } @NgModule({ @@ -1784,7 +1806,7 @@ describe('ViewContainerRef', () => { ]); log.length = 0; - vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef !); + vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); expect(getElementHtml(fixture.nativeElement)) .toEqual('AB'); expect(log).toEqual([]); @@ -1815,7 +1837,7 @@ describe('ViewContainerRef', () => { ]); log.length = 0; - vcRefDir.vcref.insert(viewRef !); + vcRefDir.vcref.insert(viewRef!); fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'doCheck-C', 'afterContentChecked-C', 'afterViewChecked-C', @@ -1898,7 +1920,7 @@ describe('ViewContainerRef', () => { ]); log.length = 0; - vcRefDir.vcref.insert(viewRef !); + vcRefDir.vcref.insert(viewRef!); fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'doCheck-D', 'afterContentChecked-D', 'afterViewChecked-D', @@ -1916,7 +1938,6 @@ describe('ViewContainerRef', () => { }); describe('host bindings', () => { - it('should support host bindings on dynamically created components', () => { @Component( {selector: 'host-bindings', host: {'id': 'attribute', '[title]': 'title'}, template: ``}) @@ -1926,7 +1947,7 @@ describe('ViewContainerRef', () => { @Component({template: ``}) class TestComponent { - @ViewChild(VCRefDirective, {static: true}) vcRefDir !: VCRefDirective; + @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } @NgModule({declarations: [HostBindingCmpt], entryComponents: [HostBindingCmpt]}) @@ -1956,11 +1977,9 @@ describe('ViewContainerRef', () => { expect(fixture.nativeElement.children[0].getAttribute('id')).toBe('attribute'); expect(fixture.nativeElement.children[0].getAttribute('title')).toBe('changed'); }); - }); describe('projection', () => { - it('should project the ViewContainerRef content along its host, in an element', () => { @Component({selector: 'child', template: '
'}) class Child { @@ -1990,7 +2009,7 @@ describe('ViewContainerRef', () => { expect(getElementHtml(fixture.nativeElement)) .toEqual('
blah
'); - vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef !); + vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)) .toEqual('
blah
bar
'); @@ -2031,7 +2050,7 @@ describe('ViewContainerRef', () => { .toEqual( 'Before (inside)- Before projected
blah
After projected -After (inside)
'); - vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef !); + vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)) @@ -2067,7 +2086,6 @@ describe('ViewContainerRef', () => { }); describe('with select', () => { - @Component({ selector: 'child-with-selector', template: ` @@ -2105,7 +2123,7 @@ describe('ViewContainerRef', () => { .toEqual( '

blah

'); - vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef !); + vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)) @@ -2132,13 +2150,13 @@ describe('ViewContainerRef', () => { ` }) class MyComp { - @ViewChild('source', {static: true}) - source !: TemplateRef<{}>; + @ViewChild('source', {static: true}) source!: TemplateRef<{}>; - @ViewChild('target', {read: ViewContainerRef, static: true}) - target !: ViewContainerRef; + @ViewChild('target', {read: ViewContainerRef, static: true}) target!: ViewContainerRef; - ngOnInit() { this.target.createEmbeddedView(this.source); } + ngOnInit() { + this.target.createEmbeddedView(this.source); + } } TestBed.configureTestingModule({declarations: [MyComp, ContentComp]}); @@ -2175,7 +2193,7 @@ describe('ViewContainerRef', () => { .toEqual( '

blah

'); - vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef !); + vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)) @@ -2183,7 +2201,6 @@ describe('ViewContainerRef', () => { '

blah
bar

'); }); }); - }); describe('root view container ref', () => { @@ -2204,7 +2221,7 @@ describe('ViewContainerRef', () => { containerEl = document.createElement('div'); document.body.appendChild(containerEl); - containerEl !.appendChild(rootEl); + containerEl!.appendChild(rootEl); } }; } @@ -2223,7 +2240,9 @@ describe('ViewContainerRef', () => { class DynamicCompWithBindings implements DoCheck { checkCount = 0; - ngDoCheck() { this.checkCount++; } + ngDoCheck() { + this.checkCount++; + } } @Component({template: ``}) @@ -2248,21 +2267,21 @@ describe('ViewContainerRef', () => { // Ivy inserts a comment for the root view container ref instance. This is not // the case for view engine and we need to adjust the assertions. - expect(containerEl !.childNodes.length).toBe(ivyEnabled ? 2 : 1); - ivyEnabled && expect(containerEl !.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); + expect(containerEl!.childNodes.length).toBe(ivyEnabled ? 2 : 1); + ivyEnabled && expect(containerEl!.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); - expect((containerEl !.childNodes[0] as Element).tagName).toBe('DIV'); + expect((containerEl!.childNodes[0] as Element).tagName).toBe('DIV'); vcRef.createComponent(cfResolver.resolveComponentFactory(DynamicCompWithBindings)); fixture.detectChanges(); - expect(containerEl !.childNodes.length).toBe(ivyEnabled ? 3 : 2); - expect(containerEl !.childNodes[1].textContent).toBe('check count: 1'); + expect(containerEl!.childNodes.length).toBe(ivyEnabled ? 3 : 2); + expect(containerEl!.childNodes[1].textContent).toBe('check count: 1'); fixture.detectChanges(); - expect(containerEl !.childNodes.length).toBe(ivyEnabled ? 3 : 2); - expect(containerEl !.childNodes[1].textContent).toBe('check count: 2'); + expect(containerEl!.childNodes.length).toBe(ivyEnabled ? 3 : 2); + expect(containerEl!.childNodes[1].textContent).toBe('check count: 2'); }); it('should create deep DOM tree immediately for dynamically created components', () => { @@ -2299,21 +2318,21 @@ describe('ViewContainerRef', () => { // Ivy inserts a comment for the root view container ref instance. This is not // the case for view engine and we need to adjust the assertions. - expect(containerEl !.childNodes.length).toBe(ivyEnabled ? 2 : 1); - ivyEnabled && expect(containerEl !.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); + expect(containerEl!.childNodes.length).toBe(ivyEnabled ? 2 : 1); + ivyEnabled && expect(containerEl!.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); - expect((containerEl !.childNodes[0] as Element).tagName).toBe('DIV'); + expect((containerEl!.childNodes[0] as Element).tagName).toBe('DIV'); vcRef.createComponent(cfResolver.resolveComponentFactory(DynamicCompWithChildren)); - expect(containerEl !.childNodes.length).toBe(ivyEnabled ? 3 : 2); - expect(getElementHtml(containerEl !.childNodes[1] as Element)) + expect(containerEl!.childNodes.length).toBe(ivyEnabled ? 3 : 2); + expect(getElementHtml(containerEl!.childNodes[1] as Element)) .toBe('
'); fixture.detectChanges(); - expect(containerEl !.childNodes.length).toBe(ivyEnabled ? 3 : 2); - expect(getElementHtml(containerEl !.childNodes[1] as Element)) + expect(containerEl!.childNodes.length).toBe(ivyEnabled ? 3 : 2); + expect(getElementHtml(containerEl!.childNodes[1] as Element)) .toBe(`
text
`); }); }); @@ -2374,7 +2393,7 @@ class EmbeddedComponentWithNgZoneModule { ` }) class ViewContainerRefComp { - @ViewChildren(TemplateRef) templates !: QueryList>; + @ViewChildren(TemplateRef) templates!: QueryList>; constructor(public vcr: ViewContainerRef) {} } @@ -2386,21 +2405,25 @@ class ViewContainerRefComp { ` }) class ViewContainerRefApp { - @ViewChild(ViewContainerRefComp) vcrComp !: ViewContainerRefComp; + @ViewChild(ViewContainerRefComp) vcrComp!: ViewContainerRefComp; } @Directive({selector: '[structDir]'}) export class StructDir { constructor(private vcref: ViewContainerRef, private tplRef: TemplateRef) {} - create() { this.vcref.createEmbeddedView(this.tplRef); } + create() { + this.vcref.createEmbeddedView(this.tplRef); + } - destroy() { this.vcref.clear(); } + destroy() { + this.vcref.clear(); + } } @Component({selector: 'destroy-cases', template: ` `}) class DestroyCasesComp { - @ViewChildren(StructDir) structDirs !: QueryList; + @ViewChildren(StructDir) structDirs!: QueryList; } @Directive({selector: '[constructorDir]'}) @@ -2419,7 +2442,7 @@ class ConstructorDir { ` }) class ConstructorApp { - @ViewChild('foo', {static: true}) foo !: ElementRef; + @ViewChild('foo', {static: true}) foo!: ElementRef; } @Component({ @@ -2431,5 +2454,5 @@ class ConstructorApp { ` }) class ConstructorAppWithQueries { - @ViewChild('foo', {static: true}) foo !: TemplateRef; + @ViewChild('foo', {static: true}) foo!: TemplateRef; } diff --git a/packages/core/test/acceptance/view_insertion_spec.ts b/packages/core/test/acceptance/view_insertion_spec.ts index 41099fd2478ab..265816486503b 100644 --- a/packages/core/test/acceptance/view_insertion_spec.ts +++ b/packages/core/test/acceptance/view_insertion_spec.ts @@ -33,15 +33,14 @@ describe('view insertion', () => { }) class App { @ViewChild('container', {read: ViewContainerRef, static: true}) - container: ViewContainerRef = null !; + container: ViewContainerRef = null!; - @ViewChild('simple', {read: TemplateRef, static: true}) - simple: TemplateRef = null !; + @ViewChild('simple', {read: TemplateRef, static: true}) simple: TemplateRef = null!; - view0: EmbeddedViewRef = null !; - view1: EmbeddedViewRef = null !; - view2: EmbeddedViewRef = null !; - view3: EmbeddedViewRef = null !; + view0: EmbeddedViewRef = null!; + view1: EmbeddedViewRef = null!; + view2: EmbeddedViewRef = null!; + view3: EmbeddedViewRef = null!; constructor(public changeDetector: ChangeDetectorRef) {} @@ -90,16 +89,14 @@ describe('view insertion', () => { ` }) class App { - @ViewChild('container', {read: ViewContainerRef}) - container: ViewContainerRef = null !; + @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; - @ViewChild('empty', {read: TemplateRef}) - empty: TemplateRef = null !; + @ViewChild('empty', {read: TemplateRef}) empty: TemplateRef = null!; - view0: EmbeddedViewRef = null !; - view1: EmbeddedViewRef = null !; - view2: EmbeddedViewRef = null !; - view3: EmbeddedViewRef = null !; + view0: EmbeddedViewRef = null!; + view1: EmbeddedViewRef = null!; + view2: EmbeddedViewRef = null!; + view3: EmbeddedViewRef = null!; ngAfterViewInit() { // insert at the front @@ -140,16 +137,14 @@ describe('view insertion', () => { ` }) class Comp { - @ViewChild('container', {read: ViewContainerRef}) - container: ViewContainerRef = null !; + @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; - @ViewChild('projection', {read: TemplateRef}) - projection: TemplateRef = null !; + @ViewChild('projection', {read: TemplateRef}) projection: TemplateRef = null!; - view0: EmbeddedViewRef = null !; - view1: EmbeddedViewRef = null !; - view2: EmbeddedViewRef = null !; - view3: EmbeddedViewRef = null !; + view0: EmbeddedViewRef = null!; + view1: EmbeddedViewRef = null!; + view2: EmbeddedViewRef = null!; + view3: EmbeddedViewRef = null!; ngAfterViewInit() { // insert at the front @@ -201,16 +196,14 @@ describe('view insertion', () => { ` }) class App { - @ViewChild('container', {read: ViewContainerRef}) - container: ViewContainerRef = null !; + @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; - @ViewChild('subContainer', {read: TemplateRef}) - subContainer: TemplateRef = null !; + @ViewChild('subContainer', {read: TemplateRef}) subContainer: TemplateRef = null!; - view0: EmbeddedViewRef = null !; - view1: EmbeddedViewRef = null !; - view2: EmbeddedViewRef = null !; - view3: EmbeddedViewRef = null !; + view0: EmbeddedViewRef = null!; + view1: EmbeddedViewRef = null!; + view2: EmbeddedViewRef = null!; + view3: EmbeddedViewRef = null!; constructor(public changeDetectorRef: ChangeDetectorRef) {} @@ -265,9 +258,9 @@ describe('view insertion', () => { describe('before embedded view', () => { @Component({selector: 'test-cmpt', template: ''}) class TestCmpt { - @ViewChild('before', {static: true}) beforeTpl !: TemplateRef<{}>; - @ViewChild('insert', {static: true}) insertTpl !: TemplateRef<{}>; - @ViewChild('vi', {static: true}) viewInsertingDir !: ViewInsertingDir; + @ViewChild('before', {static: true}) beforeTpl!: TemplateRef<{}>; + @ViewChild('insert', {static: true}) insertTpl!: TemplateRef<{}>; + @ViewChild('vi', {static: true}) viewInsertingDir!: ViewInsertingDir; minutes = 10; @@ -303,8 +296,9 @@ describe('view insertion', () => { } - it('should insert before a view with the text node as the first root node', - () => { expect(createAndInsertViews('|before').textContent).toBe('insert|before'); }); + it('should insert before a view with the text node as the first root node', () => { + expect(createAndInsertViews('|before').textContent).toBe('insert|before'); + }); it('should insert before a view with the element as the first root node', () => { expect(createAndInsertViews('|before').textContent).toBe('insert|before'); @@ -336,13 +330,11 @@ describe('view insertion', () => { it('should insert before a view with a container as the first root node', () => { expect(createAndInsertViews(`|before`).textContent) .toBe('insert|before'); - }); it('should insert before a view with an empty container as the first root node', () => { expect(createAndInsertViews(`|before`).textContent) .toBe('insert|before'); - }); onlyInIvy('VE incorrectly inserts views before ng-container content') @@ -353,7 +345,6 @@ describe('view insertion', () => { |after `).textContent) .toBe('insert|before|after'); - }); @@ -363,7 +354,6 @@ describe('view insertion', () => { |after `).textContent) .toBe('insert|before|after'); - }); it('should insert before a view with an empty projection as the first root node', () => { @@ -414,11 +404,9 @@ describe('view insertion', () => { fixture.detectChanges(); expect(fixture.debugElement.nativeElement.textContent).toBe('start|testtest|end'); }); - }); describe('before embedded view with projection', () => { - @Component({ selector: 'with-content', template: ` @@ -428,9 +416,9 @@ describe('view insertion', () => { ` }) class WithContentCmpt { - @ViewChild('insert', {static: true}) insertTpl !: TemplateRef<{}>; - @ViewChild('before', {static: true}) beforeTpl !: TemplateRef<{}>; - @ViewChild('vi', {static: true}) viewInsertingDir !: ViewInsertingDir; + @ViewChild('insert', {static: true}) insertTpl!: TemplateRef<{}>; + @ViewChild('before', {static: true}) beforeTpl!: TemplateRef<{}>; + @ViewChild('vi', {static: true}) viewInsertingDir!: ViewInsertingDir; insert() { const beforeView = this.beforeTpl.createEmbeddedView({}); @@ -442,7 +430,7 @@ describe('view insertion', () => { @Component({selector: 'test-cmpt', template: ''}) class TestCmpt { - @ViewChild('wc', {static: true}) withContentCmpt !: WithContentCmpt; + @ViewChild('wc', {static: true}) withContentCmpt!: WithContentCmpt; } beforeEach(() => { @@ -476,7 +464,6 @@ describe('view insertion', () => { expect(fixture.nativeElement.textContent).toBe('insert|before'); }); - }); describe('before component view', () => { @@ -503,8 +490,8 @@ describe('view insertion', () => { ` }) class TestCmpt { - @ViewChild('insert', {static: true}) insertTpl !: TemplateRef<{}>; - @ViewChild('vi', {static: true}) viewInsertingDir !: ViewInsertingDir; + @ViewChild('insert', {static: true}) insertTpl!: TemplateRef<{}>; + @ViewChild('vi', {static: true}) viewInsertingDir!: ViewInsertingDir; constructor(private _cfr: ComponentFactoryResolver, private _injector: Injector) {} @@ -537,16 +524,13 @@ describe('view insertion', () => { expect(fixture.nativeElement.textContent).toBe('insert|before'); }); - }); }); describe('non-regression', () => { - // https://github.com/angular/angular/issues/31971 it('should insert component views into ViewContainerRef injected by querying ', () => { - @Component({selector: 'dynamic-cmpt', template: 'dynamic'}) class DynamicComponent { } @@ -562,8 +546,7 @@ describe('view insertion', () => { ` }) class AppComponent { - @ViewChild('container', {read: ViewContainerRef, static: true}) - vcr !: ViewContainerRef; + @ViewChild('container', {read: ViewContainerRef, static: true}) vcr!: ViewContainerRef; constructor(private _cfr: ComponentFactoryResolver) {} @@ -595,7 +578,6 @@ describe('view insertion', () => { // https://github.com/angular/angular/issues/33679 it('should insert embedded views into ViewContainerRef injected by querying ', () => { - @Component({ selector: 'app-root', template: ` @@ -608,12 +590,13 @@ describe('view insertion', () => { ` }) class AppComponent { - @ViewChild('container', {read: ViewContainerRef, static: true}) - vcr !: ViewContainerRef; + @ViewChild('container', {read: ViewContainerRef, static: true}) vcr!: ViewContainerRef; @ViewChild('template', {read: TemplateRef, static: true}) template !: TemplateRef; - click() { this.vcr.createEmbeddedView(this.template, undefined, 0); } + click() { + this.vcr.createEmbeddedView(this.template, undefined, 0); + } } TestBed.configureTestingModule({ @@ -659,6 +642,5 @@ describe('view insertion', () => { expect(fixture.nativeElement.textContent.trim()).toContain('2 1'); }); - }); }); diff --git a/packages/core/test/acceptance/view_ref_spec.ts b/packages/core/test/acceptance/view_ref_spec.ts index fcb1cf28f635b..04e2104ba902f 100644 --- a/packages/core/test/acceptance/view_ref_spec.ts +++ b/packages/core/test/acceptance/view_ref_spec.ts @@ -13,7 +13,6 @@ import {TestBed} from '@angular/core/testing'; describe('ViewRef', () => { it('should remove nodes from DOM when the view is detached from app ref', () => { - @Component({selector: 'dynamic-cpt', template: '
'}) class DynamicComponent { constructor(public elRef: ElementRef) {} @@ -21,7 +20,7 @@ describe('ViewRef', () => { @Component({template: ``}) class App { - componentRef !: ComponentRef; + componentRef!: ComponentRef; constructor( public appRef: ApplicationRef, private cfr: ComponentFactoryResolver, private injector: Injector) {} @@ -33,7 +32,9 @@ describe('ViewRef', () => { document.body.appendChild(this.componentRef.instance.elRef.nativeElement); } - destroy() { (this.componentRef.hostView as InternalViewRef).detachFromAppRef(); } + destroy() { + (this.componentRef.hostView as InternalViewRef).detachFromAppRef(); + } } @NgModule({declarations: [App, DynamicComponent], entryComponents: [DynamicComponent]}) diff --git a/packages/core/test/animation/animation_integration_spec.ts b/packages/core/test/animation/animation_integration_spec.ts index d2034fb6a28d2..15ebcef106e24 100644 --- a/packages/core/test/animation/animation_integration_spec.ts +++ b/packages/core/test/animation/animation_integration_spec.ts @@ -5,12 +5,12 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ -import {AUTO_STYLE, AnimationEvent, AnimationOptions, animate, animateChild, group, keyframes, query, state, style, transition, trigger, ɵPRE_STYLE as PRE_STYLE} from '@angular/animations'; +import {animate, animateChild, AnimationEvent, AnimationOptions, AUTO_STYLE, group, keyframes, query, state, style, transition, trigger, ɵPRE_STYLE as PRE_STYLE} from '@angular/animations'; import {AnimationDriver, ɵAnimationEngine, ɵNoopAnimationDriver as NoopAnimationDriver} from '@angular/animations/browser'; import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing'; import {ɵgetDOM as getDOM} from '@angular/common'; import {ChangeDetectorRef, Component, HostBinding, HostListener, Inject, RendererFactory2, ViewChild} from '@angular/core'; -import {TestBed, fakeAsync, flushMicrotasks} from '@angular/core/testing'; +import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing'; import {ɵDomRendererFactory2} from '@angular/platform-browser'; import {ANIMATION_MODULE_TYPE, BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations'; import {hasStyle} from '@angular/platform-browser/testing/src/browser_util'; @@ -20,792 +20,853 @@ const DEFAULT_NAMESPACE_ID = 'id'; const DEFAULT_COMPONENT_ID = '1'; (function() { - // these tests are only mean't to be run within the DOM (for now) - if (isNode) return; +// these tests are only mean't to be run within the DOM (for now) +if (isNode) return; - describe('animation tests', function() { - function getLog(): MockAnimationPlayer[] { - return MockAnimationDriver.log as MockAnimationPlayer[]; - } +describe('animation tests', function() { + function getLog(): MockAnimationPlayer[] { + return MockAnimationDriver.log as MockAnimationPlayer[]; + } - function resetLog() { MockAnimationDriver.log = []; } + function resetLog() { + MockAnimationDriver.log = []; + } - beforeEach(() => { - resetLog(); - TestBed.configureTestingModule({ - providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], - imports: [BrowserAnimationsModule] - }); + beforeEach(() => { + resetLog(); + TestBed.configureTestingModule({ + providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], + imports: [BrowserAnimationsModule] }); + }); - describe('animation modules', function() { - it('should hint at BrowserAnimationsModule being used', () => { - TestBed.resetTestingModule(); - TestBed.configureTestingModule( - {declarations: [SharedAnimationCmp], imports: [BrowserAnimationsModule]}); + describe('animation modules', function() { + it('should hint at BrowserAnimationsModule being used', () => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule( + {declarations: [SharedAnimationCmp], imports: [BrowserAnimationsModule]}); - const fixture = TestBed.createComponent(SharedAnimationCmp); - const cmp = fixture.componentInstance; - expect(cmp.animationType).toEqual('BrowserAnimations'); - }); + const fixture = TestBed.createComponent(SharedAnimationCmp); + const cmp = fixture.componentInstance; + expect(cmp.animationType).toEqual('BrowserAnimations'); + }); - it('should hint at NoopAnimationsModule being used', () => { - TestBed.resetTestingModule(); - TestBed.configureTestingModule( - {declarations: [SharedAnimationCmp], imports: [NoopAnimationsModule]}); + it('should hint at NoopAnimationsModule being used', () => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule( + {declarations: [SharedAnimationCmp], imports: [NoopAnimationsModule]}); - const fixture = TestBed.createComponent(SharedAnimationCmp); - const cmp = fixture.componentInstance; - expect(cmp.animationType).toEqual('NoopAnimations'); - }); + const fixture = TestBed.createComponent(SharedAnimationCmp); + const cmp = fixture.componentInstance; + expect(cmp.animationType).toEqual('NoopAnimations'); }); + }); - @Component({template: '

template text

'}) - class SharedAnimationCmp { - constructor(@Inject(ANIMATION_MODULE_TYPE) public animationType: 'NoopAnimations'| - 'BrowserAnimations') {} - } + @Component({template: '

template text

'}) + class SharedAnimationCmp { + constructor(@Inject(ANIMATION_MODULE_TYPE) public animationType: 'NoopAnimations'| + 'BrowserAnimations') {} + } - describe('fakeAsync testing', () => { - it('should only require one flushMicrotasks call to kick off animation callbacks', - fakeAsync(() => { + describe('fakeAsync testing', () => { + it('should only require one flushMicrotasks call to kick off animation callbacks', + fakeAsync(() => { + @Component({ + selector: 'cmp', + template: ` +
+ `, + animations: [trigger( + 'myAnimation', + [transition('* => on, * => off', [animate(1000, style({opacity: 1}))])])] + }) + class Cmp { + exp: any = false; + status: string = ''; + cb(status: string) { + this.status = status; + } + } + + TestBed.configureTestingModule({declarations: [Cmp]}); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'on'; + fixture.detectChanges(); + expect(cmp.status).toEqual(''); + + flushMicrotasks(); + expect(cmp.status).toEqual('start'); + + let player = MockAnimationDriver.log.pop()!; + player.finish(); + expect(cmp.status).toEqual('done'); + + cmp.status = ''; + cmp.exp = 'off'; + fixture.detectChanges(); + expect(cmp.status).toEqual(''); + + player = MockAnimationDriver.log.pop()!; + player.finish(); + expect(cmp.status).toEqual(''); + flushMicrotasks(); + expect(cmp.status).toEqual('done'); + })); + + it('should always run .start callbacks before .done callbacks even for noop animations', + fakeAsync(() => { + @Component({ + selector: 'cmp', + template: ` +
+ `, + animations: [ + trigger( + 'myAnimation', + [ + transition('* => go', []), + ]), + ] + }) + class Cmp { + exp: any = false; + log: string[] = []; + cb(status: string) { + this.log.push(status); + } + } + + TestBed.configureTestingModule({declarations: [Cmp]}); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'go'; + fixture.detectChanges(); + expect(cmp.log).toEqual([]); + + flushMicrotasks(); + expect(cmp.log).toEqual(['start', 'done']); + })); + + it('should emit the correct totalTime value for a noop-animation', fakeAsync(() => { + @Component({ + selector: 'cmp', + template: ` +
+ `, + animations: [ + trigger( + 'myAnimation', + [ + transition( + '* => go', + [ + animate('1s', style({opacity: 0})), + ]), + ]), + ] + }) + class Cmp { + exp: any = false; + log: AnimationEvent[] = []; + cb(event: AnimationEvent) { + this.log.push(event); + } + } + + TestBed.configureTestingModule({ + declarations: [Cmp], + providers: [ + {provide: AnimationDriver, useClass: NoopAnimationDriver}, + ], + }); + + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'go'; + fixture.detectChanges(); + expect(cmp.log).toEqual([]); + + flushMicrotasks(); + expect(cmp.log.length).toEqual(2); + const [start, end] = cmp.log; + expect(start.totalTime).toEqual(1000); + expect(end.totalTime).toEqual(1000); + })); + }); + + describe('component fixture integration', () => { + describe('whenRenderingDone', () => { + it('should wait until the animations are finished until continuing', fakeAsync(() => { @Component({ selector: 'cmp', template: ` -
- `, +
+ `, animations: [trigger( - 'myAnimation', - [transition('* => on, * => off', [animate(1000, style({opacity: 1}))])])] + 'myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])])] }) class Cmp { exp: any = false; - status: string = ''; - cb(status: string) { this.status = status; } } TestBed.configureTestingModule({declarations: [Cmp]}); + const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; - cmp.exp = 'on'; - fixture.detectChanges(); - expect(cmp.status).toEqual(''); - - flushMicrotasks(); - expect(cmp.status).toEqual('start'); - let player = MockAnimationDriver.log.pop() !; - player.finish(); - expect(cmp.status).toEqual('done'); + let isDone = false; + fixture.whenRenderingDone().then(() => isDone = true); + expect(isDone).toBe(false); - cmp.status = ''; - cmp.exp = 'off'; + cmp.exp = 'on'; fixture.detectChanges(); - expect(cmp.status).toEqual(''); + engine.flush(); + expect(isDone).toBe(false); + + const players = engine.players; + expect(players.length).toEqual(1); + players[0].finish(); + expect(isDone).toBe(false); - player = MockAnimationDriver.log.pop() !; - player.finish(); - expect(cmp.status).toEqual(''); flushMicrotasks(); - expect(cmp.status).toEqual('done'); + expect(isDone).toBe(true); })); - it('should always run .start callbacks before .done callbacks even for noop animations', - fakeAsync(() => { + it('should wait for a noop animation to finish before continuing', fakeAsync(() => { @Component({ selector: 'cmp', template: ` -
- `, - animations: [ - trigger( - 'myAnimation', - [ - transition('* => go', []), - ]), - ] +
+ `, + animations: [trigger( + 'myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])])] }) class Cmp { exp: any = false; - log: string[] = []; - cb(status: string) { this.log.push(status); } } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({ + providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], + declarations: [Cmp] + }); + + const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; - cmp.exp = 'go'; + + let isDone = false; + fixture.whenRenderingDone().then(() => isDone = true); + expect(isDone).toBe(false); + + cmp.exp = 'off'; fixture.detectChanges(); - expect(cmp.log).toEqual([]); + engine.flush(); + expect(isDone).toBe(false); flushMicrotasks(); - expect(cmp.log).toEqual(['start', 'done']); + expect(isDone).toBe(true); })); - it('should emit the correct totalTime value for a noop-animation', fakeAsync(() => { + it('should wait for active animations to finish even if they have already started', + fakeAsync(() => { @Component({ selector: 'cmp', template: ` -
- `, - animations: [ - trigger( - 'myAnimation', - [ - transition( - '* => go', - [ - animate('1s', style({opacity: 0})), - ]), - ]), - ] +
+ `, + animations: [trigger( + 'myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])])] }) class Cmp { exp: any = false; - log: AnimationEvent[] = []; - cb(event: AnimationEvent) { this.log.push(event); } } - TestBed.configureTestingModule({ - declarations: [Cmp], - providers: [ - {provide: AnimationDriver, useClass: NoopAnimationDriver}, - ], - }); - + TestBed.configureTestingModule({declarations: [Cmp]}); + const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; - cmp.exp = 'go'; + cmp.exp = 'on'; fixture.detectChanges(); - expect(cmp.log).toEqual([]); - - flushMicrotasks(); - expect(cmp.log.length).toEqual(2); - const [start, end] = cmp.log; - expect(start.totalTime).toEqual(1000); - expect(end.totalTime).toEqual(1000); - })); - }); - - describe('component fixture integration', () => { - describe('whenRenderingDone', () => { - it('should wait until the animations are finished until continuing', fakeAsync(() => { - @Component({ - selector: 'cmp', - template: ` -
- `, - animations: [trigger( - 'myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])])] - }) - class Cmp { - exp: any = false; - } + engine.flush(); - TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - - let isDone = false; - fixture.whenRenderingDone().then(() => isDone = true); - expect(isDone).toBe(false); - - cmp.exp = 'on'; - fixture.detectChanges(); - engine.flush(); - expect(isDone).toBe(false); - - const players = engine.players; - expect(players.length).toEqual(1); - players[0].finish(); - expect(isDone).toBe(false); - - flushMicrotasks(); - expect(isDone).toBe(true); - })); - - it('should wait for a noop animation to finish before continuing', fakeAsync(() => { - @Component({ - selector: 'cmp', - template: ` -
- `, - animations: [trigger( - 'myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])])] - }) - class Cmp { - exp: any = false; - } + const players = engine.players; + expect(players.length).toEqual(1); - TestBed.configureTestingModule({ - providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], - declarations: [Cmp] - }); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - - let isDone = false; - fixture.whenRenderingDone().then(() => isDone = true); - expect(isDone).toBe(false); - - cmp.exp = 'off'; - fixture.detectChanges(); - engine.flush(); - expect(isDone).toBe(false); - - flushMicrotasks(); - expect(isDone).toBe(true); - })); - - it('should wait for active animations to finish even if they have already started', - fakeAsync(() => { - @Component({ - selector: 'cmp', - template: ` -
- `, - animations: [trigger( - 'myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])])] - }) - class Cmp { - exp: any = false; - } + let isDone = false; + fixture.whenRenderingDone().then(() => isDone = true); + flushMicrotasks(); + expect(isDone).toBe(false); - TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = 'on'; - fixture.detectChanges(); - engine.flush(); - - const players = engine.players; - expect(players.length).toEqual(1); - - let isDone = false; - fixture.whenRenderingDone().then(() => isDone = true); - flushMicrotasks(); - expect(isDone).toBe(false); - - players[0].finish(); - flushMicrotasks(); - expect(isDone).toBe(true); - })); - }); + players[0].finish(); + flushMicrotasks(); + expect(isDone).toBe(true); + })); }); + }); - describe('animation triggers', () => { - it('should trigger a state change animation from void => state', () => { - @Component({ - selector: 'if-cmp', - template: ` + describe('animation triggers', () => { + it('should trigger a state change animation from void => state', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [transition( - 'void => *', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], - }) - class Cmp { - exp: any = false; - } - - TestBed.configureTestingModule({declarations: [Cmp]}); + animations: [trigger( + 'myAnimation', + [transition( + 'void => *', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], + }) + class Cmp { + exp: any = false; + } - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = true; - fixture.detectChanges(); - engine.flush(); + TestBed.configureTestingModule({declarations: [Cmp]}); - expect(getLog().length).toEqual(1); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, opacity: '0'}, {offset: 1, opacity: '1'} - ]); - }); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = true; + fixture.detectChanges(); + engine.flush(); + + expect(getLog().length).toEqual(1); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, opacity: '0'}, {offset: 1, opacity: '1'} + ]); + }); - // https://github.com/angular/angular/issues/32794 - it('should support nested animation triggers', () => { - const REUSABLE_ANIMATION = [trigger( - 'myAnimation', - [transition( - 'void => *', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])]; + // https://github.com/angular/angular/issues/32794 + it('should support nested animation triggers', () => { + const REUSABLE_ANIMATION = [trigger('myAnimation', [ + transition('void => *', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))]) + ])]; - @Component({ - selector: 'if-cmp', - template: ` + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [REUSABLE_ANIMATION], - }) - class Cmp { - } - - TestBed.configureTestingModule({declarations: [Cmp]}); + animations: [REUSABLE_ANIMATION], + }) + class Cmp { + } - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - fixture.detectChanges(); - engine.flush(); + TestBed.configureTestingModule({declarations: [Cmp]}); - expect(getLog().length).toEqual(1); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, opacity: '0'}, {offset: 1, opacity: '1'} - ]); - }); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + fixture.detectChanges(); + engine.flush(); - it('should allow a transition to use a function to determine what method to run', () => { - let valueToMatch = ''; - let capturedElement: any; - const transitionFn = (fromState: string, toState: string, element: any) => { - capturedElement = element; - return toState == valueToMatch; - }; + expect(getLog().length).toEqual(1); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, opacity: '0'}, {offset: 1, opacity: '1'} + ]); + }); - @Component({ - selector: 'if-cmp', - template: '
', - animations: [ - trigger('myAnimation', [transition( - transitionFn, - [style({opacity: 0}), animate(1234, style({opacity: 1}))])]), - ] - }) - class Cmp { - @ViewChild('element') - element: any; - exp: any = ''; - } + it('should allow a transition to use a function to determine what method to run', () => { + let valueToMatch = ''; + let capturedElement: any; + const transitionFn = (fromState: string, toState: string, element: any) => { + capturedElement = element; + return toState == valueToMatch; + }; - TestBed.configureTestingModule({declarations: [Cmp]}); + @Component({ + selector: 'if-cmp', + template: '
', + animations: [ + trigger('myAnimation', [transition( + transitionFn, + [style({opacity: 0}), animate(1234, style({opacity: 1}))])]), + ] + }) + class Cmp { + @ViewChild('element') element: any; + exp: any = ''; + } - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - valueToMatch = cmp.exp = 'something'; - fixture.detectChanges(); - const element = cmp.element.nativeElement; + TestBed.configureTestingModule({declarations: [Cmp]}); - let players = getLog(); - expect(players.length).toEqual(1); - let [p1] = players; - expect(p1.totalTime).toEqual(1234); - expect(capturedElement).toEqual(element); - resetLog(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + valueToMatch = cmp.exp = 'something'; + fixture.detectChanges(); + const element = cmp.element.nativeElement; + + let players = getLog(); + expect(players.length).toEqual(1); + let [p1] = players; + expect(p1.totalTime).toEqual(1234); + expect(capturedElement).toEqual(element); + resetLog(); - valueToMatch = 'something-else'; - cmp.exp = 'this-wont-match'; - fixture.detectChanges(); + valueToMatch = 'something-else'; + cmp.exp = 'this-wont-match'; + fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(0); - }); + players = getLog(); + expect(players.length).toEqual(0); + }); - it('should allow a transition to use a function to determine what method to run and expose any parameter values', - () => { - const transitionFn = - (fromState: string, toState: string, element?: any, - params?: {[key: string]: any}) => { return params !['doMatch'] == true; }; + it('should allow a transition to use a function to determine what method to run and expose any parameter values', + () => { + const transitionFn = + (fromState: string, toState: string, element?: any, params?: {[key: string]: any}) => { + return params!['doMatch'] == true; + }; - @Component({ - selector: 'if-cmp', - template: '
', - animations: [ - trigger( - 'myAnimation', - [transition( - transitionFn, [style({opacity: 0}), animate(3333, style({opacity: 1}))])]), - ] - }) - class Cmp { - doMatch = false; - exp: any = ''; - } + @Component({ + selector: 'if-cmp', + template: '
', + animations: [ + trigger( + 'myAnimation', + [transition( + transitionFn, [style({opacity: 0}), animate(3333, style({opacity: 1}))])]), + ] + }) + class Cmp { + doMatch = false; + exp: any = ''; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.doMatch = true; - fixture.detectChanges(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.doMatch = true; + fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(1); - let [p1] = players; - expect(p1.totalTime).toEqual(3333); - resetLog(); + let players = getLog(); + expect(players.length).toEqual(1); + let [p1] = players; + expect(p1.totalTime).toEqual(3333); + resetLog(); - cmp.doMatch = false; - cmp.exp = 'this-wont-match'; - fixture.detectChanges(); + cmp.doMatch = false; + cmp.exp = 'this-wont-match'; + fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(0); - }); + players = getLog(); + expect(players.length).toEqual(0); + }); - it('should allow a state value to be `0`', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should allow a state value to be `0`', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [ - transition( - '0 => 1', [style({height: '0px'}), animate(1234, style({height: '100px'}))]), - transition( - '* => 1', [style({width: '0px'}), animate(4567, style({width: '100px'}))]) - ])] - }) - class Cmp { - exp: any = false; - } + animations: [trigger( + 'myAnimation', + [ + transition( + '0 => 1', [style({height: '0px'}), animate(1234, style({height: '100px'}))]), + transition('* => 1', [style({width: '0px'}), animate(4567, style({width: '100px'}))]) + ])] + }) + class Cmp { + exp: any = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = 0; - fixture.detectChanges(); - engine.flush(); - resetLog(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 0; + fixture.detectChanges(); + engine.flush(); + resetLog(); - cmp.exp = 1; - fixture.detectChanges(); - engine.flush(); + cmp.exp = 1; + fixture.detectChanges(); + engine.flush(); - expect(getLog().length).toEqual(1); - const player = getLog().pop() !; - expect(player.duration).toEqual(1234); - }); + expect(getLog().length).toEqual(1); + const player = getLog().pop()!; + expect(player.duration).toEqual(1234); + }); - it('should always cancel the previous transition if a follow-up transition is not matched', - fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` + it('should always cancel the previous transition if a follow-up transition is not matched', + fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [transition( - 'a => b', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], - }) - class Cmp { - exp: any; - startEvent: any; - doneEvent: any; - - callback(event: any) { - if (event.phaseName == 'done') { - this.doneEvent = event; - } else { - this.startEvent = event; - } + animations: [trigger( + 'myAnimation', + [transition( + 'a => b', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], + }) + class Cmp { + exp: any; + startEvent: any; + doneEvent: any; + + callback(event: any) { + if (event.phaseName == 'done') { + this.doneEvent = event; + } else { + this.startEvent = event; } } + } - TestBed.configureTestingModule({declarations: [Cmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - - cmp.exp = 'a'; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(0); - expect(engine.players.length).toEqual(0); + TestBed.configureTestingModule({declarations: [Cmp]}); - flushMicrotasks(); - expect(cmp.startEvent.toState).toEqual('a'); - expect(cmp.startEvent.totalTime).toEqual(0); - expect(cmp.startEvent.toState).toEqual('a'); - expect(cmp.startEvent.totalTime).toEqual(0); - resetLog(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = 'b'; - fixture.detectChanges(); - engine.flush(); + cmp.exp = 'a'; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); + expect(engine.players.length).toEqual(0); + + flushMicrotasks(); + expect(cmp.startEvent.toState).toEqual('a'); + expect(cmp.startEvent.totalTime).toEqual(0); + expect(cmp.startEvent.toState).toEqual('a'); + expect(cmp.startEvent.totalTime).toEqual(0); + resetLog(); + + cmp.exp = 'b'; + fixture.detectChanges(); + engine.flush(); - const players = getLog(); - expect(players.length).toEqual(1); - expect(engine.players.length).toEqual(1); + const players = getLog(); + expect(players.length).toEqual(1); + expect(engine.players.length).toEqual(1); - flushMicrotasks(); - expect(cmp.startEvent.toState).toEqual('b'); - expect(cmp.startEvent.totalTime).toEqual(500); - expect(cmp.startEvent.toState).toEqual('b'); - expect(cmp.startEvent.totalTime).toEqual(500); - resetLog(); + flushMicrotasks(); + expect(cmp.startEvent.toState).toEqual('b'); + expect(cmp.startEvent.totalTime).toEqual(500); + expect(cmp.startEvent.toState).toEqual('b'); + expect(cmp.startEvent.totalTime).toEqual(500); + resetLog(); - let completed = false; - players[0].onDone(() => completed = true); + let completed = false; + players[0].onDone(() => completed = true); - cmp.exp = 'c'; - fixture.detectChanges(); - engine.flush(); + cmp.exp = 'c'; + fixture.detectChanges(); + engine.flush(); - expect(engine.players.length).toEqual(0); - expect(getLog().length).toEqual(0); + expect(engine.players.length).toEqual(0); + expect(getLog().length).toEqual(0); - flushMicrotasks(); - expect(cmp.startEvent.toState).toEqual('c'); - expect(cmp.startEvent.totalTime).toEqual(0); - expect(cmp.startEvent.toState).toEqual('c'); - expect(cmp.startEvent.totalTime).toEqual(0); + flushMicrotasks(); + expect(cmp.startEvent.toState).toEqual('c'); + expect(cmp.startEvent.totalTime).toEqual(0); + expect(cmp.startEvent.toState).toEqual('c'); + expect(cmp.startEvent.totalTime).toEqual(0); - expect(completed).toBe(true); - })); + expect(completed).toBe(true); + })); - it('should always fire inner callbacks even if no animation is fired when a view is inserted', - fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` + it('should always fire inner callbacks even if no animation is fired when a view is inserted', + fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger('myAnimation', []), - ] - }) - class Cmp { - exp: any = false; - log: string[] = []; - track(event: any) { this.log.push(`${event.triggerName}-${event.phaseName}`); } + animations: [ + trigger('myAnimation', []), + ] + }) + class Cmp { + exp: any = false; + log: string[] = []; + track(event: any) { + this.log.push(`${event.triggerName}-${event.phaseName}`); } + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - flushMicrotasks(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + flushMicrotasks(); - expect(cmp.log).toEqual([]); + expect(cmp.log).toEqual([]); - cmp.exp = true; - fixture.detectChanges(); - flushMicrotasks(); + cmp.exp = true; + fixture.detectChanges(); + flushMicrotasks(); - expect(cmp.log).toEqual(['myAnimation-start', 'myAnimation-done']); - })); + expect(cmp.log).toEqual(['myAnimation-start', 'myAnimation-done']); + })); - it('should only turn a view removal as into `void` state transition', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should only turn a view removal as into `void` state transition', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [ - transition( - 'void <=> *', [style({width: '0px'}), animate(1000, style({width: '100px'}))]), - transition( - '* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]), - ])] - }) - class Cmp { - exp1: any = false; - exp2: any = false; - } - - TestBed.configureTestingModule({declarations: [Cmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + animations: [trigger( + 'myAnimation', + [ + transition( + 'void <=> *', [style({width: '0px'}), animate(1000, style({width: '100px'}))]), + transition( + '* => *', [style({height: '0px'}), animate(1000, style({height: '100px'}))]), + ])] + }) + class Cmp { + exp1: any = false; + exp2: any = false; + } - function resetState() { - cmp.exp2 = 'something'; - fixture.detectChanges(); - engine.flush(); - resetLog(); - } + TestBed.configureTestingModule({declarations: [Cmp]}); - cmp.exp1 = true; - cmp.exp2 = null; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + function resetState() { + cmp.exp2 = 'something'; fixture.detectChanges(); engine.flush(); + resetLog(); + } - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, width: '0px'}, {offset: 1, width: '100px'} - ]); + cmp.exp1 = true; + cmp.exp2 = null; - resetState(); - cmp.exp2 = false; + fixture.detectChanges(); + engine.flush(); - fixture.detectChanges(); - engine.flush(); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, width: '0px'}, {offset: 1, width: '100px'} + ]); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, height: '0px'}, {offset: 1, height: '100px'} - ]); + resetState(); + cmp.exp2 = false; - resetState(); - cmp.exp2 = 0; + fixture.detectChanges(); + engine.flush(); - fixture.detectChanges(); - engine.flush(); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, height: '0px'}, {offset: 1, height: '100px'} + ]); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, height: '0px'}, {offset: 1, height: '100px'} - ]); + resetState(); + cmp.exp2 = 0; - resetState(); - cmp.exp2 = ''; + fixture.detectChanges(); + engine.flush(); - fixture.detectChanges(); - engine.flush(); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, height: '0px'}, {offset: 1, height: '100px'} + ]); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, height: '0px'}, {offset: 1, height: '100px'} - ]); + resetState(); + cmp.exp2 = ''; - resetState(); - cmp.exp2 = undefined; + fixture.detectChanges(); + engine.flush(); - fixture.detectChanges(); - engine.flush(); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, height: '0px'}, {offset: 1, height: '100px'} + ]); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, height: '0px'}, {offset: 1, height: '100px'} - ]); + resetState(); + cmp.exp2 = undefined; - resetState(); - cmp.exp1 = false; - cmp.exp2 = 'abc'; + fixture.detectChanges(); + engine.flush(); - fixture.detectChanges(); - engine.flush(); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, height: '0px'}, {offset: 1, height: '100px'} + ]); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, width: '0px'}, {offset: 1, width: '100px'} - ]); - }); + resetState(); + cmp.exp1 = false; + cmp.exp2 = 'abc'; - it('should stringify boolean triggers to `1` and `0`', () => { - @Component({ - selector: 'if-cmp', - template: ` + fixture.detectChanges(); + engine.flush(); + + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, width: '0px'}, {offset: 1, width: '100px'} + ]); + }); + + it('should stringify boolean triggers to `1` and `0`', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [ - transition('void => 1', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), - transition('1 => 0', [style({opacity: 1}), animate(1000, style({opacity: 0}))]) - ])] - }) - class Cmp { - exp: any = false; - } + animations: [trigger( + 'myAnimation', + [ + transition('void => 1', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), + transition('1 => 0', [style({opacity: 1}), animate(1000, style({opacity: 0}))]) + ])] + }) + class Cmp { + exp: any = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = true; - fixture.detectChanges(); - engine.flush(); + cmp.exp = true; + fixture.detectChanges(); + engine.flush(); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, opacity: '0'}, {offset: 1, opacity: '1'} - ]); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, opacity: '0'}, {offset: 1, opacity: '1'} + ]); - cmp.exp = false; - fixture.detectChanges(); - engine.flush(); + cmp.exp = false; + fixture.detectChanges(); + engine.flush(); - expect(getLog().pop() !.keyframes).toEqual([ - {offset: 0, opacity: '1'}, {offset: 1, opacity: '0'} - ]); - }); + expect(getLog().pop()!.keyframes).toEqual([ + {offset: 0, opacity: '1'}, {offset: 1, opacity: '0'} + ]); + }); - it('should understand boolean values as `true` and `false` for transition animations', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should understand boolean values as `true` and `false` for transition animations', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - 'true => false', - [ - style({opacity: 0}), - animate(1234, style({opacity: 1})), - ]), - transition( - 'false => true', - [ - style({opacity: 1}), - animate(4567, style({opacity: 0})), - ]) - ]), - ] - }) - class Cmp { - exp: any = false; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + 'true => false', + [ + style({opacity: 0}), + animate(1234, style({opacity: 1})), + ]), + transition( + 'false => true', + [ + style({opacity: 1}), + animate(4567, style({opacity: 0})), + ]) + ]), + ] + }) + class Cmp { + exp: any = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = true; - fixture.detectChanges(); + cmp.exp = true; + fixture.detectChanges(); - cmp.exp = false; - fixture.detectChanges(); + cmp.exp = false; + fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(1); - let [player] = players; + let players = getLog(); + expect(players.length).toEqual(1); + let [player] = players; - expect(player.duration).toEqual(1234); - }); + expect(player.duration).toEqual(1234); + }); - it('should understand boolean values as `true` and `false` for transition animations and apply the corresponding state() value', - () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should understand boolean values as `true` and `false` for transition animations and apply the corresponding state() value', + () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - state('true', style({color: 'red'})), - state('false', style({color: 'blue'})), - transition( - 'true <=> false', - [ - animate(1000, style({color: 'gold'})), - animate(1000), - ]), - ]), - ] + animations: [ + trigger( + 'myAnimation', + [ + state('true', style({color: 'red'})), + state('false', style({color: 'blue'})), + transition( + 'true <=> false', + [ + animate(1000, style({color: 'gold'})), + animate(1000), + ]), + ]), + ] + }) + class Cmp { + exp: any = false; + } + + TestBed.configureTestingModule({declarations: [Cmp]}); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + + cmp.exp = false; + fixture.detectChanges(); + + cmp.exp = true; + fixture.detectChanges(); + + let players = getLog(); + expect(players.length).toEqual(1); + let [player] = players; + + expect(player.keyframes).toEqual([ + {color: 'blue', offset: 0}, + {color: 'gold', offset: 0.5}, + {color: 'red', offset: 1}, + ]); + }); + + it('should not throw an error if a trigger with the same name exists in separate components', + () => { + @Component({selector: 'cmp1', template: '...', animations: [trigger('trig', [])]}) + class Cmp1 { + } + + @Component({selector: 'cmp2', template: '...', animations: [trigger('trig', [])]}) + class Cmp2 { + } + + TestBed.configureTestingModule({declarations: [Cmp1, Cmp2]}); + const cmp1 = TestBed.createComponent(Cmp1); + const cmp2 = TestBed.createComponent(Cmp2); + }); + + describe('host bindings', () => { + it('should trigger a state change animation from state => state on the component host element', + fakeAsync(() => { + @Component({ + selector: 'my-cmp', + template: '...', + animations: [trigger( + 'myAnimation', + [transition( + 'a => b', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], }) class Cmp { - exp: any = false; + @HostBinding('@myAnimation') exp = 'a'; } TestBed.configureTestingModule({declarations: [Cmp]}); @@ -813,435 +874,375 @@ const DEFAULT_COMPONENT_ID = '1'; const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); - cmp.exp = false; + cmp.exp = 'b'; fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(1); + + const data = getLog().pop()!; + expect(data.element).toEqual(fixture.elementRef.nativeElement); + expect(data.keyframes).toEqual([{offset: 0, opacity: '0'}, {offset: 1, opacity: '1'}]); + })); + + it('should trigger a leave animation when the inner components host binding updates', + fakeAsync(() => { + @Component({ + selector: 'parent-cmp', + template: ` + + ` + }) + class ParentCmp { + public exp = true; + } + + @Component({ + selector: 'child-cmp', + template: '...', + animations: [trigger( + 'host', + [transition(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))])])] + }) + class ChildCmp { + @HostBinding('@host') public hostAnimation = true; + } - cmp.exp = true; + TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ParentCmp); + const cmp = fixture.componentInstance; fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); - let players = getLog(); - expect(players.length).toEqual(1); - let [player] = players; + cmp.exp = false; + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement.children.length).toBe(1); + engine.flush(); + expect(getLog().length).toEqual(1); + + const [player] = getLog(); expect(player.keyframes).toEqual([ - {color: 'blue', offset: 0}, - {color: 'gold', offset: 0.5}, - {color: 'red', offset: 1}, + {opacity: '1', offset: 0}, + {opacity: '0', offset: 1}, ]); - }); - it('should not throw an error if a trigger with the same name exists in separate components', - () => { - @Component({selector: 'cmp1', template: '...', animations: [trigger('trig', [])]}) - class Cmp1 { + player.finish(); + expect(fixture.debugElement.nativeElement.children.length).toBe(0); + })); + + it('should wait for child animations before removing parent', fakeAsync(() => { + @Component({ + template: '', + animations: [trigger( + 'parentTrigger', [transition(':leave', [group([query('@*', animateChild())])])])] + }) + class ParentCmp { + exp = true; } - @Component({selector: 'cmp2', template: '...', animations: [trigger('trig', [])]}) - class Cmp2 { + @Component({ + selector: 'child-cmp', + template: '

Hello there

', + animations: [trigger( + 'childTrigger', + [transition( + ':leave', [style({opacity: 1}), animate('200ms', style({opacity: 0}))])])] + }) + class ChildCmp { } - TestBed.configureTestingModule({declarations: [Cmp1, Cmp2]}); - const cmp1 = TestBed.createComponent(Cmp1); - const cmp2 = TestBed.createComponent(Cmp2); - }); + TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ParentCmp); - describe('host bindings', () => { - it('should trigger a state change animation from state => state on the component host element', - fakeAsync(() => { - @Component({ - selector: 'my-cmp', - template: '...', - animations: [trigger( - 'myAnimation', - [transition( - 'a => b', - [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], - }) - class Cmp { - @HostBinding('@myAnimation') - exp = 'a'; - } + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toBe(0); - TestBed.configureTestingModule({declarations: [Cmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(0); - - cmp.exp = 'b'; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(1); - - const data = getLog().pop() !; - expect(data.element).toEqual(fixture.elementRef.nativeElement); - expect(data.keyframes).toEqual([{offset: 0, opacity: '0'}, {offset: 1, opacity: '1'}]); - })); - - it('should trigger a leave animation when the inner components host binding updates', - fakeAsync(() => { - @Component({ - selector: 'parent-cmp', - template: ` - - ` - }) - class ParentCmp { - public exp = true; - } + fixture.componentInstance.exp = false; + fixture.detectChanges(); + expect(fixture.nativeElement.children.length).toBe(1); - @Component({ - selector: 'child-cmp', - template: '...', - animations: [trigger( - 'host', - [transition( - ':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))])])] - }) - class ChildCmp { - @HostBinding('@host') public hostAnimation = true; - } + engine.flush(); + expect(getLog().length).toBe(1); - TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ParentCmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(0); - - cmp.exp = false; - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.children.length).toBe(1); - - engine.flush(); - expect(getLog().length).toEqual(1); - - const [player] = getLog(); - expect(player.keyframes).toEqual([ - {opacity: '1', offset: 0}, - {opacity: '0', offset: 1}, - ]); - - player.finish(); - expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); - - it('should wait for child animations before removing parent', fakeAsync(() => { - @Component({ - template: '', - animations: [trigger( - 'parentTrigger', [transition(':leave', [group([query('@*', animateChild())])])])] - }) - class ParentCmp { - exp = true; - } + const player = getLog()[0]; + expect(player.keyframes).toEqual([ + {opacity: '1', offset: 0}, + {opacity: '0', offset: 1}, + ]); - @Component({ - selector: 'child-cmp', - template: '

Hello there

', - animations: [trigger( - 'childTrigger', - [transition( - ':leave', [style({opacity: 1}), animate('200ms', style({opacity: 0}))])])] - }) - class ChildCmp { - } + player.finish(); + flushMicrotasks(); + expect(fixture.nativeElement.children.length).toBe(0); + })); - TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ParentCmp); - - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toBe(0); - - fixture.componentInstance.exp = false; - fixture.detectChanges(); - expect(fixture.nativeElement.children.length).toBe(1); - - engine.flush(); - expect(getLog().length).toBe(1); - - const player = getLog()[0]; - expect(player.keyframes).toEqual([ - {opacity: '1', offset: 0}, - {opacity: '0', offset: 1}, - ]); - - player.finish(); - flushMicrotasks(); - expect(fixture.nativeElement.children.length).toBe(0); - })); - - // animationRenderer => nonAnimationRenderer - it('should trigger a leave animation when the outer components element binding updates on the host component element', - fakeAsync(() => { - @Component({ - selector: 'parent-cmp', - animations: [trigger( - 'host', - [transition( - ':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))])])], - template: ` + // animationRenderer => nonAnimationRenderer + it('should trigger a leave animation when the outer components element binding updates on the host component element', + fakeAsync(() => { + @Component({ + selector: 'parent-cmp', + animations: [trigger( + 'host', + [transition( + ':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))])])], + template: ` ` - }) - class ParentCmp { - public exp = true; - } + }) + class ParentCmp { + public exp = true; + } - @Component({ - selector: 'child-cmp', - template: '...', - }) - class ChildCmp { - } + @Component({ + selector: 'child-cmp', + template: '...', + }) + class ChildCmp { + } - TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ParentCmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(0); - - cmp.exp = false; - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.children.length).toBe(1); - - engine.flush(); - expect(getLog().length).toEqual(1); - - const [player] = getLog(); - expect(player.keyframes).toEqual([ - {opacity: '1', offset: 0}, - {opacity: '0', offset: 1}, - ]); - - player.finish(); - flushMicrotasks(); - expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); - - it('should trigger a leave animation when both the inner and outer components trigger on the same element', - fakeAsync(() => { - @Component({ - selector: 'parent-cmp', - animations: [trigger( - 'host', - [transition( - ':leave', - [style({height: '100px'}), animate(1000, style({height: '0px'}))])])], - template: ` + TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ParentCmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); + + cmp.exp = false; + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement.children.length).toBe(1); + + engine.flush(); + expect(getLog().length).toEqual(1); + + const [player] = getLog(); + expect(player.keyframes).toEqual([ + {opacity: '1', offset: 0}, + {opacity: '0', offset: 1}, + ]); + + player.finish(); + flushMicrotasks(); + expect(fixture.debugElement.nativeElement.children.length).toBe(0); + })); + + it('should trigger a leave animation when both the inner and outer components trigger on the same element', + fakeAsync(() => { + @Component({ + selector: 'parent-cmp', + animations: [trigger( + 'host', [transition( + ':leave', + [style({height: '100px'}), animate(1000, style({height: '0px'}))])])], + template: ` ` - }) - class ParentCmp { - public exp = true; - } + }) + class ParentCmp { + public exp = true; + } - @Component({ - selector: 'child-cmp', - template: '...', - animations: [trigger( - 'host', [transition( - ':leave', - [style({width: '100px'}), animate(1000, style({width: '0px'}))])])] - }) - class ChildCmp { - @HostBinding('@host') public hostAnimation = true; - } + @Component({ + selector: 'child-cmp', + template: '...', + animations: [trigger( + 'host', + [transition( + ':leave', [style({width: '100px'}), animate(1000, style({width: '0px'}))])])] + }) + class ChildCmp { + @HostBinding('@host') public hostAnimation = true; + } - TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ParentCmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(0); - - cmp.exp = false; - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.children.length).toBe(1); - - engine.flush(); - expect(getLog().length).toEqual(2); - - const [p1, p2] = getLog(); - expect(p1.keyframes).toEqual([ - {width: '100px', offset: 0}, - {width: '0px', offset: 1}, - ]); - - expect(p2.keyframes).toEqual([ - {height: '100px', offset: 0}, - {height: '0px', offset: 1}, - ]); - - p1.finish(); - p2.finish(); - flushMicrotasks(); - expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); - - it('should not throw when the host element is removed and no animation triggers', - fakeAsync(() => { - @Component({ - selector: 'parent-cmp', - template: ` - - ` - }) - class ParentCmp { - public exp = true; - } + TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - @Component({ - selector: 'child-cmp', - template: '...', - animations: [trigger('host', [transition('a => b', [style({height: '100px'})])])], - }) - class ChildCmp { - @HostBinding('@host') public hostAnimation = 'a'; - } + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ParentCmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); - TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ParentCmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - expect(fixture.debugElement.nativeElement.children.length).toBe(1); - - engine.flush(); - expect(getLog().length).toEqual(0); - - cmp.exp = false; - fixture.detectChanges(); - engine.flush(); - flushMicrotasks(); - expect(getLog().length).toEqual(0); - expect(fixture.debugElement.nativeElement.children.length).toBe(0); - - flushMicrotasks(); - expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); - - it('should properly evaluate pre/auto-style values when components are inserted/removed which contain host animations', - fakeAsync(() => { - @Component({ - selector: 'parent-cmp', - template: ` - - ` - }) - class ParentCmp { - items: any[] = [1, 2, 3, 4, 5]; - } + cmp.exp = false; + fixture.detectChanges(); + expect(fixture.debugElement.nativeElement.children.length).toBe(1); - @Component({ - selector: 'child-cmp', - template: '... child ...', - animations: - [trigger('host', [transition(':leave', [animate(1000, style({opacity: 0}))])])] - }) - class ChildCmp { - @HostBinding('@host') public hostAnimation = 'a'; - } + engine.flush(); + expect(getLog().length).toEqual(2); - TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); + const [p1, p2] = getLog(); + expect(p1.keyframes).toEqual([ + {width: '100px', offset: 0}, + {width: '0px', offset: 1}, + ]); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ParentCmp); - const cmp = fixture.componentInstance; - const element = fixture.nativeElement; - fixture.detectChanges(); + expect(p2.keyframes).toEqual([ + {height: '100px', offset: 0}, + {height: '0px', offset: 1}, + ]); - cmp.items = [0, 2, 4, 6]; // 1,3,5 get removed - fixture.detectChanges(); + p1.finish(); + p2.finish(); + flushMicrotasks(); + expect(fixture.debugElement.nativeElement.children.length).toBe(0); + })); - const items = element.querySelectorAll('child-cmp'); - for (let i = 0; i < items.length; i++) { - const item = items[i]; - expect(item.style['display']).toBeFalsy(); - } - })); - }); + it('should not throw when the host element is removed and no animation triggers', + fakeAsync(() => { + @Component({ + selector: 'parent-cmp', + template: ` + + ` + }) + class ParentCmp { + public exp = true; + } - it('should cancel and merge in mid-animation styles into the follow-up animation, but only for animation keyframes that start right away', - () => { @Component({ - selector: 'ani-cmp', - template: ` -
- `, - animations: [trigger( - 'myAnimation', - [ - transition( - 'a => b', - [ - style({'opacity': '0'}), - animate(500, style({'opacity': '1'})), - ]), - transition( - 'b => c', - [ - group([ - animate(500, style({'width': '100px'})), - animate(500, style({'height': '100px'})), - ]), - animate(500, keyframes([ - style({'opacity': '0'}), - style({'opacity': '1'}) - ])) - ]), - ])], - }) - class Cmp { - exp: any = false; + selector: 'child-cmp', + template: '...', + animations: [trigger('host', [transition('a => b', [style({height: '100px'})])])], + }) + class ChildCmp { + @HostBinding('@host') public hostAnimation = 'a'; } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); + const fixture = TestBed.createComponent(ParentCmp); const cmp = fixture.componentInstance; - - cmp.exp = 'a'; fixture.detectChanges(); + expect(fixture.debugElement.nativeElement.children.length).toBe(1); + engine.flush(); expect(getLog().length).toEqual(0); - resetLog(); - cmp.exp = 'b'; + cmp.exp = false; fixture.detectChanges(); engine.flush(); - expect(getLog().length).toEqual(1); - resetLog(); + flushMicrotasks(); + expect(getLog().length).toEqual(0); + expect(fixture.debugElement.nativeElement.children.length).toBe(0); - cmp.exp = 'c'; - fixture.detectChanges(); - engine.flush(); + flushMicrotasks(); + expect(fixture.debugElement.nativeElement.children.length).toBe(0); + })); - const players = getLog(); - expect(players.length).toEqual(3); - const [p1, p2, p3] = players; - expect(p1.previousStyles).toEqual({opacity: AUTO_STYLE}); - expect(p2.previousStyles).toEqual({opacity: AUTO_STYLE}); - expect(p3.previousStyles).toEqual({}); - }); + it('should properly evaluate pre/auto-style values when components are inserted/removed which contain host animations', + fakeAsync(() => { + @Component({ + selector: 'parent-cmp', + template: ` + + ` + }) + class ParentCmp { + items: any[] = [1, 2, 3, 4, 5]; + } - it('should provide the styling of previous players that are grouped', () => { - @Component({ + @Component({ + selector: 'child-cmp', + template: '... child ...', + animations: + [trigger('host', [transition(':leave', [animate(1000, style({opacity: 0}))])])] + }) + class ChildCmp { + @HostBinding('@host') public hostAnimation = 'a'; + } + + TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ParentCmp); + const cmp = fixture.componentInstance; + const element = fixture.nativeElement; + fixture.detectChanges(); + + cmp.items = [0, 2, 4, 6]; // 1,3,5 get removed + fixture.detectChanges(); + + const items = element.querySelectorAll('child-cmp'); + for (let i = 0; i < items.length; i++) { + const item = items[i]; + expect(item.style['display']).toBeFalsy(); + } + })); + }); + + it('should cancel and merge in mid-animation styles into the follow-up animation, but only for animation keyframes that start right away', + () => { + @Component({ + selector: 'ani-cmp', + template: ` +
+ `, + animations: [trigger( + 'myAnimation', + [ + transition( + 'a => b', + [ + style({'opacity': '0'}), + animate(500, style({'opacity': '1'})), + ]), + transition( + 'b => c', + [ + group([ + animate(500, style({'width': '100px'})), + animate(500, style({'height': '100px'})), + ]), + animate(500, keyframes([style({'opacity': '0'}), style({'opacity': '1'})])) + ]), + ])], + }) + class Cmp { + exp: any = false; + } + + TestBed.configureTestingModule({declarations: [Cmp]}); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + + cmp.exp = 'a'; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); + resetLog(); + + cmp.exp = 'b'; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(1); + resetLog(); + + cmp.exp = 'c'; + fixture.detectChanges(); + engine.flush(); + + const players = getLog(); + expect(players.length).toEqual(3); + const [p1, p2, p3] = players; + expect(p1.previousStyles).toEqual({opacity: AUTO_STYLE}); + expect(p2.previousStyles).toEqual({opacity: AUTO_STYLE}); + expect(p3.previousStyles).toEqual({}); + }); + + it('should provide the styling of previous players that are grouped', () => { + @Component({ selector: 'ani-cmp', template: `
@@ -1270,1637 +1271,1641 @@ const DEFAULT_COMPONENT_ID = '1'; ])], }) class Cmp { - exp: any = false; - } + exp: any = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - fixture.detectChanges(); - engine.flush(); + fixture.detectChanges(); + engine.flush(); - cmp.exp = '1'; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(0); - resetLog(); + cmp.exp = '1'; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); + resetLog(); - cmp.exp = '2'; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(3); - resetLog(); + cmp.exp = '2'; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(3); + resetLog(); - cmp.exp = '3'; - fixture.detectChanges(); - engine.flush(); + cmp.exp = '3'; + fixture.detectChanges(); + engine.flush(); - const players = getLog(); - expect(players.length).toEqual(1); - const player = players[0] as MockAnimationPlayer; - const pp = player.previousPlayers as MockAnimationPlayer[]; + const players = getLog(); + expect(players.length).toEqual(1); + const player = players[0] as MockAnimationPlayer; + const pp = player.previousPlayers as MockAnimationPlayer[]; - expect(pp.length).toEqual(3); - expect(pp[0].currentSnapshot).toEqual({width: AUTO_STYLE}); - expect(pp[1].currentSnapshot).toEqual({height: AUTO_STYLE}); - expect(pp[2].currentSnapshot).toEqual({opacity: AUTO_STYLE}); - }); + expect(pp.length).toEqual(3); + expect(pp[0].currentSnapshot).toEqual({width: AUTO_STYLE}); + expect(pp[1].currentSnapshot).toEqual({height: AUTO_STYLE}); + expect(pp[2].currentSnapshot).toEqual({opacity: AUTO_STYLE}); + }); - it('should provide the styling of previous players that are grouped and queried and make sure match the players with the correct elements', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should provide the styling of previous players that are grouped and queried and make sure match the players with the correct elements', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - '1 => 2', - [ - style({fontSize: '10px'}), - query( - '.inner', - [ - style({fontSize: '20px'}), - ]), - animate('1s', style({fontSize: '100px'})), - query( - '.inner', - [ - animate('1s', style({fontSize: '200px'})), - ]), - ]), - transition( - '2 => 3', - [ - animate('1s', style({fontSize: '0px'})), - query( - '.inner', - [ - animate('1s', style({fontSize: '0px'})), - ]), - ]), - ]), - ], - }) - class Cmp { - exp: any = false; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + '1 => 2', + [ + style({fontSize: '10px'}), + query( + '.inner', + [ + style({fontSize: '20px'}), + ]), + animate('1s', style({fontSize: '100px'})), + query( + '.inner', + [ + animate('1s', style({fontSize: '200px'})), + ]), + ]), + transition( + '2 => 3', + [ + animate('1s', style({fontSize: '0px'})), + query( + '.inner', + [ + animate('1s', style({fontSize: '0px'})), + ]), + ]), + ]), + ], + }) + class Cmp { + exp: any = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - fixture.detectChanges(); + fixture.detectChanges(); - cmp.exp = '1'; - fixture.detectChanges(); - resetLog(); + cmp.exp = '1'; + fixture.detectChanges(); + resetLog(); - cmp.exp = '2'; - fixture.detectChanges(); - resetLog(); + cmp.exp = '2'; + fixture.detectChanges(); + resetLog(); - cmp.exp = '3'; - fixture.detectChanges(); - const players = getLog(); - expect(players.length).toEqual(2); - const [p1, p2] = players as MockAnimationPlayer[]; - - const pp1 = p1.previousPlayers as MockAnimationPlayer[]; - expect(p1.element.classList.contains('container')).toBeTruthy(); - for (let i = 0; i < pp1.length; i++) { - expect(pp1[i].element).toEqual(p1.element); - } + cmp.exp = '3'; + fixture.detectChanges(); + const players = getLog(); + expect(players.length).toEqual(2); + const [p1, p2] = players as MockAnimationPlayer[]; + + const pp1 = p1.previousPlayers as MockAnimationPlayer[]; + expect(p1.element.classList.contains('container')).toBeTruthy(); + for (let i = 0; i < pp1.length; i++) { + expect(pp1[i].element).toEqual(p1.element); + } - const pp2 = p2.previousPlayers as MockAnimationPlayer[]; - expect(p2.element.classList.contains('inner')).toBeTruthy(); - for (let i = 0; i < pp2.length; i++) { - expect(pp2[i].element).toEqual(p2.element); - } - }); + const pp2 = p2.previousPlayers as MockAnimationPlayer[]; + expect(p2.element.classList.contains('inner')).toBeTruthy(); + for (let i = 0; i < pp2.length; i++) { + expect(pp2[i].element).toEqual(p2.element); + } + }); - it('should properly balance styles between states even if there are no destination state styles', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should properly balance styles between states even if there are no destination state styles', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [ - state('void', style({opacity: 0, width: '0px', height: '0px'})), - transition(':enter', animate(1000)) - ])] - }) - class Cmp { - exp: boolean = false; - } + animations: [trigger( + 'myAnimation', + [ + state('void', style({opacity: 0, width: '0px', height: '0px'})), + transition(':enter', animate(1000)) + ])] + }) + class Cmp { + exp: boolean = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = true; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = true; - fixture.detectChanges(); - engine.flush(); + fixture.detectChanges(); + engine.flush(); - const [p1] = getLog(); - expect(p1.keyframes).toEqual([ - {opacity: '0', width: '0px', height: '0px', offset: 0}, - {opacity: AUTO_STYLE, width: AUTO_STYLE, height: AUTO_STYLE, offset: 1} - ]); - }); + const [p1] = getLog(); + expect(p1.keyframes).toEqual([ + {opacity: '0', width: '0px', height: '0px', offset: 0}, + {opacity: AUTO_STYLE, width: AUTO_STYLE, height: AUTO_STYLE, offset: 1} + ]); + }); - it('should not apply the destination styles if the final animate step already contains styles', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should not apply the destination styles if the final animate step already contains styles', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [ - state('void', style({color: 'red'})), state('*', style({color: 'blue'})), - transition( - ':enter', - [style({fontSize: '0px '}), animate(1000, style({fontSize: '100px'}))]) - ])] - }) - class Cmp { - exp: boolean = false; - } + animations: [trigger( + 'myAnimation', + [ + state('void', style({color: 'red'})), state('*', style({color: 'blue'})), + transition( + ':enter', + [style({fontSize: '0px '}), animate(1000, style({fontSize: '100px'}))]) + ])] + }) + class Cmp { + exp: boolean = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = true; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = true; - fixture.detectChanges(); - engine.flush(); + fixture.detectChanges(); + engine.flush(); - const players = getLog(); - expect(players.length).toEqual(1); + const players = getLog(); + expect(players.length).toEqual(1); - // notice how the final color is NOT blue - expect(players[0].keyframes).toEqual([ - {fontSize: '0px', color: 'red', offset: 0}, - {fontSize: '100px', color: 'red', offset: 1} - ]); - }); + // notice how the final color is NOT blue + expect(players[0].keyframes).toEqual([ + {fontSize: '0px', color: 'red', offset: 0}, {fontSize: '100px', color: 'red', offset: 1} + ]); + }); - it('should invoke an animation trigger that is state-less', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should invoke an animation trigger that is state-less', () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] - }) - class Cmp { - items: number[] = []; - } + animations: [trigger( + 'myAnimation', + [transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] + }) + class Cmp { + items: number[] = []; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.items = [1, 2, 3, 4, 5]; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(5); + cmp.items = [1, 2, 3, 4, 5]; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(5); - for (let i = 0; i < 5; i++) { - const item = getLog()[i]; - expect(item.duration).toEqual(1000); - expect(item.keyframes).toEqual([{opacity: '0', offset: 0}, {opacity: '1', offset: 1}]); - } - }); + for (let i = 0; i < 5; i++) { + const item = getLog()[i]; + expect(item.duration).toEqual(1000); + expect(item.keyframes).toEqual([{opacity: '0', offset: 0}, {opacity: '1', offset: 1}]); + } + }); - it('should retain styles on the element once the animation is complete', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should retain styles on the element once the animation is complete', () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'green', - [ - state('*', style({backgroundColor: 'green'})), transition('* => *', animate(500)) - ])] - }) - class Cmp { - @ViewChild('green') public element: any; - } + animations: [trigger( + 'green', + [state('*', style({backgroundColor: 'green'})), transition('* => *', animate(500))])] + }) + class Cmp { + @ViewChild('green') public element: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - engine.flush(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + engine.flush(); - const player = engine.players.pop() !; - player.finish(); + const player = engine.players.pop()!; + player.finish(); - expect(hasStyle(cmp.element.nativeElement, 'background-color', 'green')).toBeTruthy(); - }); + expect(hasStyle(cmp.element.nativeElement, 'background-color', 'green')).toBeTruthy(); + }); - it('should retain state styles when the underlying DOM structure changes even if there are no insert/remove animations', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should retain state styles when the underlying DOM structure changes even if there are no insert/remove animations', + () => { + @Component({ + selector: 'ani-cmp', + template: `
{{ item }}
`, - animations: [trigger('color', [state('green', style({backgroundColor: 'green'}))])] - }) - class Cmp { - public colorExp = 'green'; - public items = [0, 1, 2, 3]; + animations: [trigger('color', [state('green', style({backgroundColor: 'green'}))])] + }) + class Cmp { + public colorExp = 'green'; + public items = [0, 1, 2, 3]; - reorder() { - const temp = this.items[0]; - this.items[0] = this.items[1]; - this.items[1] = temp; - } + reorder() { + const temp = this.items[0]; + this.items[0] = this.items[1]; + this.items[1] = temp; } + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); - let elements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.item'); - assertBackgroundColor(elements[0], 'green'); - assertBackgroundColor(elements[1], 'green'); - assertBackgroundColor(elements[2], 'green'); - assertBackgroundColor(elements[3], 'green'); + let elements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.item'); + assertBackgroundColor(elements[0], 'green'); + assertBackgroundColor(elements[1], 'green'); + assertBackgroundColor(elements[2], 'green'); + assertBackgroundColor(elements[3], 'green'); - elements[0].title = '0a'; - elements[1].title = '1a'; + elements[0].title = '0a'; + elements[1].title = '1a'; - cmp.reorder(); - fixture.detectChanges(); + cmp.reorder(); + fixture.detectChanges(); - elements = fixture.nativeElement.querySelectorAll('.item'); - assertBackgroundColor(elements[0], 'green'); - assertBackgroundColor(elements[1], 'green'); - assertBackgroundColor(elements[2], 'green'); - assertBackgroundColor(elements[3], 'green'); + elements = fixture.nativeElement.querySelectorAll('.item'); + assertBackgroundColor(elements[0], 'green'); + assertBackgroundColor(elements[1], 'green'); + assertBackgroundColor(elements[2], 'green'); + assertBackgroundColor(elements[3], 'green'); - function assertBackgroundColor(element: HTMLElement, color: string) { - expect(element.style.getPropertyValue('background-color')).toEqual(color); - } - }); + function assertBackgroundColor(element: HTMLElement, color: string) { + expect(element.style.getPropertyValue('background-color')).toEqual(color); + } + }); - it('should retain state styles when the underlying DOM structure changes even if there are insert/remove animations', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should retain state styles when the underlying DOM structure changes even if there are insert/remove animations', + () => { + @Component({ + selector: 'ani-cmp', + template: `
{{ item }}
`, - animations: [trigger( - 'color', - [ - transition('* => *', animate(500)), - state('green', style({backgroundColor: 'green'})) - ])] - }) - class Cmp { - public colorExp = 'green'; - public items = [0, 1, 2, 3]; + animations: [trigger( + 'color', + [ + transition('* => *', animate(500)), + state('green', style({backgroundColor: 'green'})) + ])] + }) + class Cmp { + public colorExp = 'green'; + public items = [0, 1, 2, 3]; - reorder() { - const temp = this.items[0]; - this.items[0] = this.items[1]; - this.items[1] = temp; - } + reorder() { + const temp = this.items[0]; + this.items[0] = this.items[1]; + this.items[1] = temp; } + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); - getLog().forEach(p => p.finish()); + getLog().forEach(p => p.finish()); - let elements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.item'); - assertBackgroundColor(elements[0], 'green'); - assertBackgroundColor(elements[1], 'green'); - assertBackgroundColor(elements[2], 'green'); - assertBackgroundColor(elements[3], 'green'); + let elements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.item'); + assertBackgroundColor(elements[0], 'green'); + assertBackgroundColor(elements[1], 'green'); + assertBackgroundColor(elements[2], 'green'); + assertBackgroundColor(elements[3], 'green'); - elements[0].title = '0a'; - elements[1].title = '1a'; + elements[0].title = '0a'; + elements[1].title = '1a'; - cmp.reorder(); - fixture.detectChanges(); + cmp.reorder(); + fixture.detectChanges(); - getLog().forEach(p => p.finish()); + getLog().forEach(p => p.finish()); - elements = fixture.nativeElement.querySelectorAll('.item'); - assertBackgroundColor(elements[0], 'green'); - assertBackgroundColor(elements[1], 'green'); - assertBackgroundColor(elements[2], 'green'); - assertBackgroundColor(elements[3], 'green'); + elements = fixture.nativeElement.querySelectorAll('.item'); + assertBackgroundColor(elements[0], 'green'); + assertBackgroundColor(elements[1], 'green'); + assertBackgroundColor(elements[2], 'green'); + assertBackgroundColor(elements[3], 'green'); - function assertBackgroundColor(element: HTMLElement, color: string) { - expect(element.style.getPropertyValue('background-color')).toEqual(color); - } - }); + function assertBackgroundColor(element: HTMLElement, color: string) { + expect(element.style.getPropertyValue('background-color')).toEqual(color); + } + }); - it('should animate removals of nodes to the `void` state for each animation trigger, but treat all auto styles as pre styles', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should animate removals of nodes to the `void` state for each animation trigger, but treat all auto styles as pre styles', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger( - 'trig1', [transition('state => void', [animate(1000, style({opacity: 0}))])]), - trigger('trig2', [transition(':leave', [animate(1000, style({width: '0px'}))])]) - ] - }) - class Cmp { - public exp = true; - public exp2 = 'state'; - } + animations: [ + trigger('trig1', [transition('state => void', [animate(1000, style({opacity: 0}))])]), + trigger('trig2', [transition(':leave', [animate(1000, style({width: '0px'}))])]) + ] + }) + class Cmp { + public exp = true; + public exp2 = 'state'; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = true; - fixture.detectChanges(); - engine.flush(); - resetLog(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = true; + fixture.detectChanges(); + engine.flush(); + resetLog(); - const element = fixture.nativeElement.querySelector('.ng-if'); - assertHasParent(element, true); + const element = fixture.nativeElement.querySelector('.ng-if'); + assertHasParent(element, true); - cmp.exp = false; - fixture.detectChanges(); - engine.flush(); + cmp.exp = false; + fixture.detectChanges(); + engine.flush(); - assertHasParent(element, true); + assertHasParent(element, true); - expect(getLog().length).toEqual(2); + expect(getLog().length).toEqual(2); - const player2 = getLog().pop() !; - const player1 = getLog().pop() !; + const player2 = getLog().pop()!; + const player1 = getLog().pop()!; - expect(player2.keyframes).toEqual([ - {width: PRE_STYLE, offset: 0}, - {width: '0px', offset: 1}, - ]); + expect(player2.keyframes).toEqual([ + {width: PRE_STYLE, offset: 0}, + {width: '0px', offset: 1}, + ]); - expect(player1.keyframes).toEqual([ - {opacity: PRE_STYLE, offset: 0}, {opacity: '0', offset: 1} - ]); + expect(player1.keyframes).toEqual([ + {opacity: PRE_STYLE, offset: 0}, {opacity: '0', offset: 1} + ]); - player2.finish(); - player1.finish(); - assertHasParent(element, false); - }); + player2.finish(); + player1.finish(); + assertHasParent(element, false); + }); - it('should properly cancel all existing animations when a removal occurs', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should properly cancel all existing animations when a removal occurs', () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - '* => go', [style({width: '0px'}), animate(1000, style({width: '100px'}))]), - ]), - ] - }) - class Cmp { - // TODO(issue/24571): remove '!'. - public exp !: string | null; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + '* => go', [style({width: '0px'}), animate(1000, style({width: '100px'}))]), + ]), + ] + }) + class Cmp { + // TODO(issue/24571): remove '!'. + public exp!: string|null; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = 'go'; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(1); - const [player1] = getLog(); - resetLog(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'go'; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(1); + const [player1] = getLog(); + resetLog(); - let finished = false; - player1.onDone(() => finished = true); + let finished = false; + player1.onDone(() => finished = true); - let destroyed = false; - player1.onDestroy(() => destroyed = true); + let destroyed = false; + player1.onDestroy(() => destroyed = true); - cmp.exp = null; - fixture.detectChanges(); - engine.flush(); + cmp.exp = null; + fixture.detectChanges(); + engine.flush(); - expect(finished).toBeTruthy(); - expect(destroyed).toBeTruthy(); - }); + expect(finished).toBeTruthy(); + expect(destroyed).toBeTruthy(); + }); - it('should not run inner child animations when a parent is set to be removed', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should not run inner child animations when a parent is set to be removed', () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', [transition('a => b', [animate(1000, style({width: '0px'}))])])] - }) - class Cmp { - public exp = true; - public exp2 = '0'; - } + animations: + [trigger('myAnimation', [transition('a => b', [animate(1000, style({width: '0px'}))])])] + }) + class Cmp { + public exp = true; + public exp2 = '0'; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = true; - cmp.exp2 = 'a'; - fixture.detectChanges(); - engine.flush(); - resetLog(); + cmp.exp = true; + cmp.exp2 = 'a'; + fixture.detectChanges(); + engine.flush(); + resetLog(); - cmp.exp = false; - cmp.exp2 = 'b'; - fixture.detectChanges(); - engine.flush(); - expect(getLog().length).toEqual(0); - }); + cmp.exp = false; + cmp.exp2 = 'b'; + fixture.detectChanges(); + engine.flush(); + expect(getLog().length).toEqual(0); + }); - it('should cancel all active inner child animations when a parent removal animation is set to go', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should cancel all active inner child animations when a parent removal animation is set to go', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger('parent', [transition( - ':leave', - [style({opacity: 0}), animate(1000, style({opacity: 1}))])]), - trigger('child', [transition( - 'a => b', - [style({opacity: 0}), animate(1000, style({opacity: 1}))])]) - ] - }) - class Cmp { - public exp1: any; - public exp2: any; - } + animations: [ + trigger( + 'parent', + [transition(':leave', [style({opacity: 0}), animate(1000, style({opacity: 1}))])]), + trigger( + 'child', + [transition('a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))])]) + ] + }) + class Cmp { + public exp1: any; + public exp2: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp1 = true; - cmp.exp2 = 'a'; - fixture.detectChanges(); - engine.flush(); - resetLog(); + cmp.exp1 = true; + cmp.exp2 = 'a'; + fixture.detectChanges(); + engine.flush(); + resetLog(); - cmp.exp2 = 'b'; - fixture.detectChanges(); - engine.flush(); + cmp.exp2 = 'b'; + fixture.detectChanges(); + engine.flush(); - let players = getLog(); - expect(players.length).toEqual(2); - const [p1, p2] = players; + let players = getLog(); + expect(players.length).toEqual(2); + const [p1, p2] = players; - let count = 0; - p1.onDone(() => count++); - p2.onDone(() => count++); + let count = 0; + p1.onDone(() => count++); + p2.onDone(() => count++); - cmp.exp1 = false; - fixture.detectChanges(); - engine.flush(); + cmp.exp1 = false; + fixture.detectChanges(); + engine.flush(); - expect(count).toEqual(2); - }); + expect(count).toEqual(2); + }); - it('should destroy inner animations when a parent node is set for removal', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should destroy inner animations when a parent node is set for removal', () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'child', - [transition('a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] - }) - class Cmp { - public exp: any; + animations: [trigger( + 'child', + [transition('a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] + }) + class Cmp { + public exp: any; - @ViewChild('parent') public parentElement: any; - } + @ViewChild('parent') public parentElement: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - const someTrigger = trigger('someTrigger', []); - const hostElement = fixture.nativeElement; - engine.register(DEFAULT_NAMESPACE_ID, hostElement); - engine.registerTrigger( - DEFAULT_COMPONENT_ID, DEFAULT_NAMESPACE_ID, hostElement, someTrigger.name, someTrigger); + const someTrigger = trigger('someTrigger', []); + const hostElement = fixture.nativeElement; + engine.register(DEFAULT_NAMESPACE_ID, hostElement); + engine.registerTrigger( + DEFAULT_COMPONENT_ID, DEFAULT_NAMESPACE_ID, hostElement, someTrigger.name, someTrigger); - cmp.exp = 'a'; - fixture.detectChanges(); - engine.flush(); - resetLog(); + cmp.exp = 'a'; + fixture.detectChanges(); + engine.flush(); + resetLog(); - cmp.exp = 'b'; - fixture.detectChanges(); - engine.flush(); + cmp.exp = 'b'; + fixture.detectChanges(); + engine.flush(); - const players = getLog(); - expect(players.length).toEqual(2); - const [p1, p2] = players; + const players = getLog(); + expect(players.length).toEqual(2); + const [p1, p2] = players; - let count = 0; - p1.onDone(() => count++); - p2.onDone(() => count++); + let count = 0; + p1.onDone(() => count++); + p2.onDone(() => count++); - engine.onRemove(DEFAULT_NAMESPACE_ID, cmp.parentElement.nativeElement, null); - expect(count).toEqual(2); - }); + engine.onRemove(DEFAULT_NAMESPACE_ID, cmp.parentElement.nativeElement, null); + expect(count).toEqual(2); + }); - it('should allow inner removals to happen when a non removal-based parent animation is set to animate', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should allow inner removals to happen when a non removal-based parent animation is set to animate', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'parent', - [transition( - 'a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] - }) - class Cmp { - public exp1: any; - public exp2: any; + animations: [trigger( + 'parent', + [transition('a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] + }) + class Cmp { + public exp1: any; + public exp2: any; - @ViewChild('parent') public parent: any; + @ViewChild('parent') public parent: any; - @ViewChild('child') public child: any; - } + @ViewChild('child') public child: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp1 = 'a'; - cmp.exp2 = true; - fixture.detectChanges(); - engine.flush(); - resetLog(); + cmp.exp1 = 'a'; + cmp.exp2 = true; + fixture.detectChanges(); + engine.flush(); + resetLog(); - cmp.exp1 = 'b'; - fixture.detectChanges(); - engine.flush(); + cmp.exp1 = 'b'; + fixture.detectChanges(); + engine.flush(); - const player = getLog()[0]; - const p = cmp.parent.nativeElement; - const c = cmp.child.nativeElement; + const player = getLog()[0]; + const p = cmp.parent.nativeElement; + const c = cmp.child.nativeElement; - expect(p.contains(c)).toBeTruthy(); + expect(p.contains(c)).toBeTruthy(); - cmp.exp2 = false; - fixture.detectChanges(); - engine.flush(); + cmp.exp2 = false; + fixture.detectChanges(); + engine.flush(); - expect(p.contains(c)).toBeFalsy(); + expect(p.contains(c)).toBeFalsy(); - player.finish(); + player.finish(); - expect(p.contains(c)).toBeFalsy(); - }); + expect(p.contains(c)).toBeFalsy(); + }); - it('should make inner removals wait until a parent based removal animation has finished', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should make inner removals wait until a parent based removal animation has finished', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'parent', - [transition( - ':leave', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] - }) - class Cmp { - public exp1: any; - public exp2: any; + animations: [trigger( + 'parent', + [transition(':leave', [style({opacity: 0}), animate(1000, style({opacity: 1}))])])] + }) + class Cmp { + public exp1: any; + public exp2: any; - @ViewChild('parent') public parent: any; + @ViewChild('parent') public parent: any; - @ViewChild('child1') public child1Elm: any; + @ViewChild('child1') public child1Elm: any; - @ViewChild('child2') public child2Elm: any; - } + @ViewChild('child2') public child2Elm: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp1 = true; - cmp.exp2 = true; - fixture.detectChanges(); - engine.flush(); - resetLog(); + cmp.exp1 = true; + cmp.exp2 = true; + fixture.detectChanges(); + engine.flush(); + resetLog(); - const p = cmp.parent.nativeElement; - const c1 = cmp.child1Elm.nativeElement; - const c2 = cmp.child2Elm.nativeElement; + const p = cmp.parent.nativeElement; + const c1 = cmp.child1Elm.nativeElement; + const c2 = cmp.child2Elm.nativeElement; - cmp.exp1 = false; - cmp.exp2 = false; - fixture.detectChanges(); - engine.flush(); + cmp.exp1 = false; + cmp.exp2 = false; + fixture.detectChanges(); + engine.flush(); - expect(p.contains(c1)).toBeTruthy(); - expect(p.contains(c2)).toBeTruthy(); + expect(p.contains(c1)).toBeTruthy(); + expect(p.contains(c2)).toBeTruthy(); - cmp.exp2 = false; - fixture.detectChanges(); - engine.flush(); + cmp.exp2 = false; + fixture.detectChanges(); + engine.flush(); - expect(p.contains(c1)).toBeTruthy(); - expect(p.contains(c2)).toBeTruthy(); - }); + expect(p.contains(c1)).toBeTruthy(); + expect(p.contains(c2)).toBeTruthy(); + }); - it('should detect trigger changes based on object.value properties', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should detect trigger changes based on object.value properties', () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition('* => 1', [animate(1234, style({opacity: 0}))]), - transition('* => 2', [animate(5678, style({opacity: 0}))]), - ]), - ] - }) - class Cmp { - public exp: any; - } + animations: [ + trigger( + 'myAnimation', + [ + transition('* => 1', [animate(1234, style({opacity: 0}))]), + transition('* => 2', [animate(5678, style({opacity: 0}))]), + ]), + ] + }) + class Cmp { + public exp: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = '1'; - fixture.detectChanges(); - engine.flush(); - let players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].duration).toEqual(1234); - resetLog(); + cmp.exp = '1'; + fixture.detectChanges(); + engine.flush(); + let players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].duration).toEqual(1234); + resetLog(); - cmp.exp = '2'; - fixture.detectChanges(); - engine.flush(); - players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].duration).toEqual(5678); - }); + cmp.exp = '2'; + fixture.detectChanges(); + engine.flush(); + players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].duration).toEqual(5678); + }); - it('should not render animations when the object expression value is the same as it was previously', - () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should not render animations when the object expression value is the same as it was previously', + () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition('* => *', [animate(1234, style({opacity: 0}))]), - ]), - ] - }) - class Cmp { - public exp: any; - public params: any; - } - - TestBed.configureTestingModule({declarations: [Cmp]}); + animations: [ + trigger( + 'myAnimation', + [ + transition('* => *', [animate(1234, style({opacity: 0}))]), + ]), + ] + }) + class Cmp { + public exp: any; + public params: any; + } - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + TestBed.configureTestingModule({declarations: [Cmp]}); - cmp.exp = '1'; - cmp.params = {}; - fixture.detectChanges(); - engine.flush(); - let players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].duration).toEqual(1234); - resetLog(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = '1'; - cmp.params = {}; - fixture.detectChanges(); - engine.flush(); - players = getLog(); - expect(players.length).toEqual(0); - }); + cmp.exp = '1'; + cmp.params = {}; + fixture.detectChanges(); + engine.flush(); + let players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].duration).toEqual(1234); + resetLog(); + + cmp.exp = '1'; + cmp.params = {}; + fixture.detectChanges(); + engine.flush(); + players = getLog(); + expect(players.length).toEqual(0); + }); - it('should update the final state styles when params update even if the expression hasn\'t changed', - fakeAsync(() => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should update the final state styles when params update even if the expression hasn\'t changed', + fakeAsync(() => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - state('*', style({color: '{{ color }}'}), {params: {color: 'black'}}), - transition('* => 1', animate(500)) - ]), - ] - }) - class Cmp { - public exp: any; - // TODO(issue/24571): remove '!'. - public color !: string | null; - } + animations: [ + trigger( + 'myAnimation', + [ + state('*', style({color: '{{ color }}'}), {params: {color: 'black'}}), + transition('* => 1', animate(500)) + ]), + ] + }) + class Cmp { + public exp: any; + // TODO(issue/24571): remove '!'. + public color!: string|null; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = '1'; - cmp.color = 'red'; - fixture.detectChanges(); - const player = getLog()[0] !; - const element = player.element; - player.finish(); + cmp.exp = '1'; + cmp.color = 'red'; + fixture.detectChanges(); + const player = getLog()[0]!; + const element = player.element; + player.finish(); - flushMicrotasks(); - expect(hasStyle(element, 'color', 'red')).toBeTruthy(); + flushMicrotasks(); + expect(hasStyle(element, 'color', 'red')).toBeTruthy(); - cmp.exp = '1'; - cmp.color = 'blue'; - fixture.detectChanges(); - resetLog(); + cmp.exp = '1'; + cmp.color = 'blue'; + fixture.detectChanges(); + resetLog(); - flushMicrotasks(); - expect(hasStyle(element, 'color', 'blue')).toBeTruthy(); + flushMicrotasks(); + expect(hasStyle(element, 'color', 'blue')).toBeTruthy(); - cmp.exp = '1'; - cmp.color = null; - fixture.detectChanges(); - resetLog(); + cmp.exp = '1'; + cmp.color = null; + fixture.detectChanges(); + resetLog(); - flushMicrotasks(); - expect(hasStyle(element, 'color', 'black')).toBeTruthy(); - })); + flushMicrotasks(); + expect(hasStyle(element, 'color', 'black')).toBeTruthy(); + })); - it('should substitute in values if the provided state match is an object with values', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should substitute in values if the provided state match is an object with values', () => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [transition( - 'a => b', - [style({opacity: '{{ start }}'}), animate(1000, style({opacity: '{{ end }}'}))], - buildParams({start: '0', end: '1'}))])] - }) - class Cmp { - public exp: any; - } + animations: [trigger( + 'myAnimation', + [transition( + 'a => b', + [style({opacity: '{{ start }}'}), animate(1000, style({opacity: '{{ end }}'}))], + buildParams({start: '0', end: '1'}))])] + }) + class Cmp { + public exp: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = {value: 'a'}; - fixture.detectChanges(); - engine.flush(); - resetLog(); + cmp.exp = {value: 'a'}; + fixture.detectChanges(); + engine.flush(); + resetLog(); - cmp.exp = {value: 'b', params: {start: .3, end: .6}}; - fixture.detectChanges(); - engine.flush(); - const player = getLog().pop() !; - expect(player.keyframes).toEqual([ - {opacity: '0.3', offset: 0}, {opacity: '0.6', offset: 1} - ]); - }); + cmp.exp = {value: 'b', params: {start: .3, end: .6}}; + fixture.detectChanges(); + engine.flush(); + const player = getLog().pop()!; + expect(player.keyframes).toEqual([{opacity: '0.3', offset: 0}, {opacity: '0.6', offset: 1}]); + }); - it('should retain substituted styles on the element once the animation is complete if referenced in the final state', - fakeAsync(() => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should retain substituted styles on the element once the animation is complete if referenced in the final state', + fakeAsync(() => { + @Component({ + selector: 'ani-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - state( - 'start', style({ - color: '{{ color }}', - fontSize: '{{ fontSize }}px', - width: '{{ width }}' - }), - {params: {color: 'red', fontSize: '200', width: '10px'}}), - - state( - 'final', - style( - {color: '{{ color }}', fontSize: '{{ fontSize }}px', width: '888px'}), - {params: {color: 'green', fontSize: '50', width: '100px'}}), - - transition('start => final', animate(500)), - ]), - ] - }) - class Cmp { - public exp: any; - public color: any; - } + animations: [ + trigger( + 'myAnimation', + [ + state( + 'start', style({ + color: '{{ color }}', + fontSize: '{{ fontSize }}px', + width: '{{ width }}' + }), + {params: {color: 'red', fontSize: '200', width: '10px'}}), + + state( + 'final', + style({color: '{{ color }}', fontSize: '{{ fontSize }}px', width: '888px'}), + {params: {color: 'green', fontSize: '50', width: '100px'}}), + + transition('start => final', animate(500)), + ]), + ] + }) + class Cmp { + public exp: any; + public color: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = 'start'; - cmp.color = 'red'; - fixture.detectChanges(); - resetLog(); + cmp.exp = 'start'; + cmp.color = 'red'; + fixture.detectChanges(); + resetLog(); - cmp.exp = 'final'; - cmp.color = 'blue'; - fixture.detectChanges(); + cmp.exp = 'final'; + cmp.color = 'blue'; + fixture.detectChanges(); - const players = getLog(); - expect(players.length).toEqual(1); - const [p1] = players; + const players = getLog(); + expect(players.length).toEqual(1); + const [p1] = players; - expect(p1.keyframes).toEqual([ - {color: 'red', fontSize: '200px', width: '10px', offset: 0}, - {color: 'blue', fontSize: '50px', width: '888px', offset: 1} - ]); + expect(p1.keyframes).toEqual([ + {color: 'red', fontSize: '200px', width: '10px', offset: 0}, + {color: 'blue', fontSize: '50px', width: '888px', offset: 1} + ]); - const element = p1.element; - p1.finish(); - flushMicrotasks(); + const element = p1.element; + p1.finish(); + flushMicrotasks(); - expect(hasStyle(element, 'color', 'blue')).toBeTruthy(); - expect(hasStyle(element, 'fontSize', '50px')).toBeTruthy(); - expect(hasStyle(element, 'width', '888px')).toBeTruthy(); - })); + expect(hasStyle(element, 'color', 'blue')).toBeTruthy(); + expect(hasStyle(element, 'fontSize', '50px')).toBeTruthy(); + expect(hasStyle(element, 'width', '888px')).toBeTruthy(); + })); - it('should only evaluate final state param substitutions from the expression and state values and not from the transition options ', - fakeAsync(() => { - @Component({ - selector: 'ani-cmp', - template: ` -
+ it('should only evaluate final state param substitutions from the expression and state values and not from the transition options ', + fakeAsync(() => { + @Component({ + selector: 'ani-cmp', + template: ` +
`, - animations: [ - trigger( - 'myAnimation', - [ - state( - 'start', style({ - width: '{{ width }}', - height: '{{ height }}', - }), - {params: {width: '0px', height: '0px'}}), - - state( - 'final', style({ - width: '{{ width }}', - height: '{{ height }}', - }), - {params: {width: '100px', height: '100px'}}), + animations: [ + trigger( + 'myAnimation', + [ + state( + 'start', style({ + width: '{{ width }}', + height: '{{ height }}', + }), + {params: {width: '0px', height: '0px'}}), + + state( + 'final', style({ + width: '{{ width }}', + height: '{{ height }}', + }), + {params: {width: '100px', height: '100px'}}), - transition( - 'start => final', [animate(500)], - {params: {width: '333px', height: '666px'}}), - ]), - ] - }) - class Cmp { - public exp: any; - } + transition( + 'start => final', [animate(500)], + {params: {width: '333px', height: '666px'}}), + ]), + ] + }) + class Cmp { + public exp: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = 'start'; - fixture.detectChanges(); - resetLog(); + cmp.exp = 'start'; + fixture.detectChanges(); + resetLog(); - cmp.exp = 'final'; - fixture.detectChanges(); + cmp.exp = 'final'; + fixture.detectChanges(); - const players = getLog(); - expect(players.length).toEqual(1); - const [p1] = players; + const players = getLog(); + expect(players.length).toEqual(1); + const [p1] = players; - expect(p1.keyframes).toEqual([ - {width: '0px', height: '0px', offset: 0}, - {width: '100px', height: '100px', offset: 1}, - ]); + expect(p1.keyframes).toEqual([ + {width: '0px', height: '0px', offset: 0}, + {width: '100px', height: '100px', offset: 1}, + ]); - const element = p1.element; - p1.finish(); - flushMicrotasks(); + const element = p1.element; + p1.finish(); + flushMicrotasks(); - expect(hasStyle(element, 'width', '100px')).toBeTruthy(); - expect(hasStyle(element, 'height', '100px')).toBeTruthy(); - })); + expect(hasStyle(element, 'width', '100px')).toBeTruthy(); + expect(hasStyle(element, 'height', '100px')).toBeTruthy(); + })); - it('should not flush animations twice when an inner component runs change detection', () => { - @Component({ - selector: 'outer-cmp', - template: ` + it('should not flush animations twice when an inner component runs change detection', () => { + @Component({ + selector: 'outer-cmp', + template: `
`, - animations: [trigger( - 'outer', - [transition(':enter', [style({opacity: 0}), animate('1s', style({opacity: 1}))])])] - }) - class OuterCmp { - @ViewChild('inner') public inner: any; - public exp: any = null; + animations: [trigger( + 'outer', + [transition(':enter', [style({opacity: 0}), animate('1s', style({opacity: 1}))])])] + }) + class OuterCmp { + @ViewChild('inner') public inner: any; + public exp: any = null; - update() { this.exp = 'go'; } + update() { + this.exp = 'go'; + } - ngDoCheck() { - if (this.exp == 'go') { - this.inner.update(); - } + ngDoCheck() { + if (this.exp == 'go') { + this.inner.update(); } } + } - @Component({ - selector: 'inner-cmp', - template: ` + @Component({ + selector: 'inner-cmp', + template: `
`, - animations: [trigger('inner', [transition( - ':enter', - [ - style({opacity: 0}), - animate('1s', style({opacity: 1})), - ])])] - }) - class InnerCmp { - public exp: any; - constructor(private _ref: ChangeDetectorRef) {} - update() { - this.exp = 'go'; - this._ref.detectChanges(); - } + animations: [trigger('inner', [transition( + ':enter', + [ + style({opacity: 0}), + animate('1s', style({opacity: 1})), + ])])] + }) + class InnerCmp { + public exp: any; + constructor(private _ref: ChangeDetectorRef) {} + update() { + this.exp = 'go'; + this._ref.detectChanges(); } + } - TestBed.configureTestingModule({declarations: [OuterCmp, InnerCmp]}); + TestBed.configureTestingModule({declarations: [OuterCmp, InnerCmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(OuterCmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - expect(getLog()).toEqual([]); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(OuterCmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + expect(getLog()).toEqual([]); - cmp.update(); - fixture.detectChanges(); + cmp.update(); + fixture.detectChanges(); - const players = getLog(); - expect(players.length).toEqual(2); - }); + const players = getLog(); + expect(players.length).toEqual(2); + }); - describe('transition aliases', () => { - describe(':increment', () => { - it('should detect when a value has incremented', () => { - @Component({ - selector: 'if-cmp', - template: ` + describe('transition aliases', () => { + describe(':increment', () => { + it('should detect when a value has incremented', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - ':increment', - [ - animate(1234, style({background: 'red'})), - ]), - ]), - ] - }) - class Cmp { - exp: number = 0; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + ':increment', + [ + animate(1234, style({background: 'red'})), + ]), + ]), + ] + }) + class Cmp { + exp: number = 0; + } - TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(0); - - cmp.exp++; - fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].duration).toEqual(1234); - resetLog(); - - cmp.exp = 5; - fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].duration).toEqual(1234); - }); + TestBed.configureTestingModule({declarations: [Cmp]}); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + let players = getLog(); + expect(players.length).toEqual(0); + + cmp.exp++; + fixture.detectChanges(); + players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].duration).toEqual(1234); + resetLog(); + + cmp.exp = 5; + fixture.detectChanges(); + players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].duration).toEqual(1234); }); + }); - describe(':decrement', () => { - it('should detect when a value has decremented', () => { - @Component({ - selector: 'if-cmp', - template: ` + describe(':decrement', () => { + it('should detect when a value has decremented', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - ':decrement', - [ - animate(1234, style({background: 'red'})), - ]), - ]), - ] - }) - class Cmp { - exp: number = 5; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + ':decrement', + [ + animate(1234, style({background: 'red'})), + ]), + ]), + ] + }) + class Cmp { + exp: number = 5; + } - TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(0); - - cmp.exp--; - fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].duration).toEqual(1234); - resetLog(); - - cmp.exp = 0; - fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].duration).toEqual(1234); - }); + TestBed.configureTestingModule({declarations: [Cmp]}); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + let players = getLog(); + expect(players.length).toEqual(0); + + cmp.exp--; + fixture.detectChanges(); + players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].duration).toEqual(1234); + resetLog(); + + cmp.exp = 0; + fixture.detectChanges(); + players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].duration).toEqual(1234); }); }); + }); - it('should animate nodes properly when they have been re-ordered', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should animate nodes properly when they have been re-ordered', () => { + @Component({ + selector: 'if-cmp', + template: `
{{ item.value }}
`, - animations: [ - trigger( - 'myAnimation', - [ - state('0', style({opacity: 0})), state('1', style({opacity: 0.4})), - state('2', style({opacity: 0.8})), transition('* => 1, * => 2', [animate(1000)]) - ]), - ] - }) - class Cmp { - items = [ - {value: '1', count: 0}, - {value: '2', count: 0}, - {value: '3', count: 0}, - {value: '4', count: 0}, - {value: '5', count: 0}, + animations: [ + trigger( + 'myAnimation', + [ + state('0', style({opacity: 0})), state('1', style({opacity: 0.4})), + state('2', style({opacity: 0.8})), transition('* => 1, * => 2', [animate(1000)]) + ]), + ] + }) + class Cmp { + items = [ + {value: '1', count: 0}, + {value: '2', count: 0}, + {value: '3', count: 0}, + {value: '4', count: 0}, + {value: '5', count: 0}, + ]; + + reOrder() { + this.items = [ + this.items[4], + this.items[1], + this.items[3], + this.items[0], + this.items[2], ]; - - reOrder() { - this.items = [ - this.items[4], - this.items[1], - this.items[3], - this.items[0], - this.items[2], - ]; - } } + } - TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - const one = cmp.items[0]; - const two = cmp.items[1]; - one.count++; - fixture.detectChanges(); - - cmp.reOrder(); - fixture.detectChanges(); - resetLog(); + TestBed.configureTestingModule({declarations: [Cmp]}); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + const one = cmp.items[0]; + const two = cmp.items[1]; + one.count++; + fixture.detectChanges(); + + cmp.reOrder(); + fixture.detectChanges(); + resetLog(); - one.count++; - two.count++; - fixture.detectChanges(); + one.count++; + two.count++; + fixture.detectChanges(); - const players = getLog(); - expect(players.length).toEqual(2); - }); + const players = getLog(); + expect(players.length).toEqual(2); }); + }); - describe('animation listeners', () => { - it('should trigger a `start` state change listener for when the animation changes state from void => state', - fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` + describe('animation listeners', () => { + it('should trigger a `start` state change listener for when the animation changes state from void => state', + fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [transition( - 'void => *', - [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], - }) - class Cmp { - exp: any = false; - // TODO(issue/24571): remove '!'. - event !: AnimationEvent; + animations: [trigger( + 'myAnimation', + [transition( + 'void => *', + [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))])])], + }) + class Cmp { + exp: any = false; + // TODO(issue/24571): remove '!'. + event!: AnimationEvent; - callback = (event: any) => { this.event = event; }; + callback = (event: any) => { + this.event = event; } + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = 'true'; - fixture.detectChanges(); - flushMicrotasks(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'true'; + fixture.detectChanges(); + flushMicrotasks(); - expect(cmp.event.triggerName).toEqual('myAnimation'); - expect(cmp.event.phaseName).toEqual('start'); - expect(cmp.event.totalTime).toEqual(500); - expect(cmp.event.fromState).toEqual('void'); - expect(cmp.event.toState).toEqual('true'); - })); + expect(cmp.event.triggerName).toEqual('myAnimation'); + expect(cmp.event.phaseName).toEqual('start'); + expect(cmp.event.totalTime).toEqual(500); + expect(cmp.event.fromState).toEqual('void'); + expect(cmp.event.toState).toEqual('true'); + })); - it('should trigger a `done` state change listener for when the animation changes state from a => b', - fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` + it('should trigger a `done` state change listener for when the animation changes state from a => b', + fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation123', - [transition( - '* => b', [style({'opacity': '0'}), animate(999, style({'opacity': '1'}))])])], - }) - class Cmp { - exp: any = false; - // TODO(issue/24571): remove '!'. - event !: AnimationEvent; + animations: [trigger( + 'myAnimation123', + [transition( + '* => b', [style({'opacity': '0'}), animate(999, style({'opacity': '1'}))])])], + }) + class Cmp { + exp: any = false; + // TODO(issue/24571): remove '!'. + event!: AnimationEvent; - callback = (event: any) => { this.event = event; }; + callback = (event: any) => { + this.event = event; } + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = 'b'; - fixture.detectChanges(); - engine.flush(); + cmp.exp = 'b'; + fixture.detectChanges(); + engine.flush(); - expect(cmp.event).toBeFalsy(); + expect(cmp.event).toBeFalsy(); - const player = engine.players.pop() !; - player.finish(); - flushMicrotasks(); + const player = engine.players.pop()!; + player.finish(); + flushMicrotasks(); - expect(cmp.event.triggerName).toEqual('myAnimation123'); - expect(cmp.event.phaseName).toEqual('done'); - expect(cmp.event.totalTime).toEqual(999); - expect(cmp.event.fromState).toEqual('void'); - expect(cmp.event.toState).toEqual('b'); - })); + expect(cmp.event.triggerName).toEqual('myAnimation123'); + expect(cmp.event.phaseName).toEqual('done'); + expect(cmp.event.totalTime).toEqual(999); + expect(cmp.event.fromState).toEqual('void'); + expect(cmp.event.toState).toEqual('b'); + })); - it('should handle callbacks for multiple triggers running simultaneously', fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` + it('should handle callbacks for multiple triggers running simultaneously', fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'ani1', - [ - transition( - '* => a', - [style({'opacity': '0'}), animate(999, style({'opacity': '1'}))]), - ]), - trigger( - 'ani2', - [ - transition( - '* => b', - [style({'width': '0px'}), animate(999, style({'width': '100px'}))]), - ]) - ], - }) - class Cmp { - exp1: any = false; - exp2: any = false; - // TODO(issue/24571): remove '!'. - event1 !: AnimationEvent; - // TODO(issue/24571): remove '!'. - event2 !: AnimationEvent; - // tslint:disable:semicolon - callback1 = (event: any) => { this.event1 = event; }; - // tslint:disable:semicolon - callback2 = (event: any) => { this.event2 = event; }; - } + animations: [ + trigger( + 'ani1', + [ + transition( + '* => a', [style({'opacity': '0'}), animate(999, style({'opacity': '1'}))]), + ]), + trigger( + 'ani2', + [ + transition( + '* => b', + [style({'width': '0px'}), animate(999, style({'width': '100px'}))]), + ]) + ], + }) + class Cmp { + exp1: any = false; + exp2: any = false; + // TODO(issue/24571): remove '!'. + event1!: AnimationEvent; + // TODO(issue/24571): remove '!'. + event2!: AnimationEvent; + // tslint:disable:semicolon + callback1 = (event: any) => { + this.event1 = event; + }; + // tslint:disable:semicolon + callback2 = (event: any) => { + this.event2 = event; + }; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp1 = 'a'; - cmp.exp2 = 'b'; - fixture.detectChanges(); - engine.flush(); + cmp.exp1 = 'a'; + cmp.exp2 = 'b'; + fixture.detectChanges(); + engine.flush(); - expect(cmp.event1).toBeFalsy(); - expect(cmp.event2).toBeFalsy(); + expect(cmp.event1).toBeFalsy(); + expect(cmp.event2).toBeFalsy(); - const player1 = engine.players[0]; - const player2 = engine.players[1]; + const player1 = engine.players[0]; + const player2 = engine.players[1]; - player1.finish(); - player2.finish(); - expect(cmp.event1).toBeFalsy(); - expect(cmp.event2).toBeFalsy(); + player1.finish(); + player2.finish(); + expect(cmp.event1).toBeFalsy(); + expect(cmp.event2).toBeFalsy(); - flushMicrotasks(); - expect(cmp.event1.triggerName).toBeTruthy('ani1'); - expect(cmp.event2.triggerName).toBeTruthy('ani2'); - })); + flushMicrotasks(); + expect(cmp.event1.triggerName).toBeTruthy('ani1'); + expect(cmp.event2.triggerName).toBeTruthy('ani2'); + })); - it('should handle callbacks for multiple triggers running simultaneously on the same element', - fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` + it('should handle callbacks for multiple triggers running simultaneously on the same element', + fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'ani1', - [ - transition( - '* => a', - [style({'opacity': '0'}), animate(999, style({'opacity': '1'}))]), - ]), - trigger( - 'ani2', - [ - transition( - '* => b', - [style({'width': '0px'}), animate(999, style({'width': '100px'}))]), - ]) - ], - }) - class Cmp { - exp1: any = false; - exp2: any = false; - // TODO(issue/24571): remove '!'. - event1 !: AnimationEvent; - // TODO(issue/24571): remove '!'. - event2 !: AnimationEvent; - callback1 = (event: any) => { this.event1 = event; }; - callback2 = (event: any) => { this.event2 = event; }; - } + animations: [ + trigger( + 'ani1', + [ + transition( + '* => a', [style({'opacity': '0'}), animate(999, style({'opacity': '1'}))]), + ]), + trigger( + 'ani2', + [ + transition( + '* => b', + [style({'width': '0px'}), animate(999, style({'width': '100px'}))]), + ]) + ], + }) + class Cmp { + exp1: any = false; + exp2: any = false; + // TODO(issue/24571): remove '!'. + event1!: AnimationEvent; + // TODO(issue/24571): remove '!'. + event2!: AnimationEvent; + callback1 = (event: any) => { + this.event1 = event; + }; + callback2 = (event: any) => { + this.event2 = event; + }; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp1 = 'a'; - cmp.exp2 = 'b'; - fixture.detectChanges(); - engine.flush(); + cmp.exp1 = 'a'; + cmp.exp2 = 'b'; + fixture.detectChanges(); + engine.flush(); - expect(cmp.event1).toBeFalsy(); - expect(cmp.event2).toBeFalsy(); + expect(cmp.event1).toBeFalsy(); + expect(cmp.event2).toBeFalsy(); - const player1 = engine.players[0]; - const player2 = engine.players[1]; + const player1 = engine.players[0]; + const player2 = engine.players[1]; - player1.finish(); - player2.finish(); - expect(cmp.event1).toBeFalsy(); - expect(cmp.event2).toBeFalsy(); + player1.finish(); + player2.finish(); + expect(cmp.event1).toBeFalsy(); + expect(cmp.event2).toBeFalsy(); - flushMicrotasks(); - expect(cmp.event1.triggerName).toBeTruthy('ani1'); - expect(cmp.event2.triggerName).toBeTruthy('ani2'); - })); + flushMicrotasks(); + expect(cmp.event1.triggerName).toBeTruthy('ani1'); + expect(cmp.event2.triggerName).toBeTruthy('ani2'); + })); - it('should handle a leave animation for multiple triggers even if not all triggers have their own leave transition specified', - fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` + it('should handle a leave animation for multiple triggers even if not all triggers have their own leave transition specified', + fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: `
123
`, - animations: [ - trigger( - 'foo', - [ - transition( - ':enter', - [ - style({opacity: 0}), - animate(1000, style({opacity: 1})), - ]), - ]), - trigger( - 'bar', - [ - transition( - ':leave', - [ - animate(1000, style({opacity: 0})), - ]), - ]) - ], - }) - class Cmp { - exp: boolean = false; - } + animations: [ + trigger( + 'foo', + [ + transition( + ':enter', + [ + style({opacity: 0}), + animate(1000, style({opacity: 1})), + ]), + ]), + trigger( + 'bar', + [ + transition( + ':leave', + [ + animate(1000, style({opacity: 0})), + ]), + ]) + ], + }) + class Cmp { + exp: boolean = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const elm = fixture.elementRef.nativeElement; - const cmp = fixture.componentInstance; + TestBed.configureTestingModule({declarations: [Cmp]}); + const fixture = TestBed.createComponent(Cmp); + const elm = fixture.elementRef.nativeElement; + const cmp = fixture.componentInstance; - cmp.exp = true; - fixture.detectChanges(); + cmp.exp = true; + fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(1); - let [p1] = players; - p1.finish(); - flushMicrotasks(); - expect(elm.innerText.trim()).toEqual('123'); + let players = getLog(); + expect(players.length).toEqual(1); + let [p1] = players; + p1.finish(); + flushMicrotasks(); + expect(elm.innerText.trim()).toEqual('123'); - resetLog(); - cmp.exp = false; - fixture.detectChanges(); + resetLog(); + cmp.exp = false; + fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - [p1] = players; - p1.finish(); - flushMicrotasks(); - expect(elm.innerText.trim()).toEqual(''); - })); + players = getLog(); + expect(players.length).toEqual(1); + [p1] = players; + p1.finish(); + flushMicrotasks(); + expect(elm.innerText.trim()).toEqual(''); + })); - it('should trigger a state change listener for when the animation changes state from void => state on the host element', - fakeAsync(() => { - @Component({ - selector: 'my-cmp', - template: `...`, - animations: [trigger( - 'myAnimation2', - [transition( - 'void => *', - [style({'opacity': '0'}), animate(1000, style({'opacity': '1'}))])])], - }) - class Cmp { - // TODO(issue/24571): remove '!'. - event !: AnimationEvent; + it('should trigger a state change listener for when the animation changes state from void => state on the host element', + fakeAsync(() => { + @Component({ + selector: 'my-cmp', + template: `...`, + animations: [trigger( + 'myAnimation2', + [transition( + 'void => *', + [style({'opacity': '0'}), animate(1000, style({'opacity': '1'}))])])], + }) + class Cmp { + // TODO(issue/24571): remove '!'. + event!: AnimationEvent; - @HostBinding('@myAnimation2') - exp: any = false; + @HostBinding('@myAnimation2') exp: any = false; - @HostListener('@myAnimation2.start', ['$event']) - callback = (event: any) => { this.event = event; } + @HostListener('@myAnimation2.start', ['$event']) + callback = (event: any) => { + this.event = event; } + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = 'TRUE'; - fixture.detectChanges(); - flushMicrotasks(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'TRUE'; + fixture.detectChanges(); + flushMicrotasks(); - expect(cmp.event.triggerName).toEqual('myAnimation2'); - expect(cmp.event.phaseName).toEqual('start'); - expect(cmp.event.totalTime).toEqual(1000); - expect(cmp.event.fromState).toEqual('void'); - expect(cmp.event.toState).toEqual('TRUE'); - })); + expect(cmp.event.triggerName).toEqual('myAnimation2'); + expect(cmp.event.phaseName).toEqual('start'); + expect(cmp.event.totalTime).toEqual(1000); + expect(cmp.event.fromState).toEqual('void'); + expect(cmp.event.toState).toEqual('TRUE'); + })); - it('should always fire callbacks even when a transition is not detected', fakeAsync(() => { - @Component({ - selector: 'my-cmp', - template: ` + it('should always fire callbacks even when a transition is not detected', fakeAsync(() => { + @Component({ + selector: 'my-cmp', + template: `
`, - animations: [trigger('myAnimation', [])] - }) - class Cmp { - // TODO(issue/24571): remove '!'. - exp !: string; - log: any[] = []; - callback = (event: any) => this.log.push(`${event.phaseName} => ${event.toState}`); - } + animations: [trigger('myAnimation', [])] + }) + class Cmp { + // TODO(issue/24571): remove '!'. + exp!: string; + log: any[] = []; + callback = (event: any) => this.log.push(`${event.phaseName} => ${event.toState}`); + } - TestBed.configureTestingModule({ - providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], - declarations: [Cmp] - }); + TestBed.configureTestingModule({ + providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], + declarations: [Cmp] + }); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = 'a'; - fixture.detectChanges(); - flushMicrotasks(); - expect(cmp.log).toEqual(['start => a', 'done => a']); + cmp.exp = 'a'; + fixture.detectChanges(); + flushMicrotasks(); + expect(cmp.log).toEqual(['start => a', 'done => a']); - cmp.log = []; - cmp.exp = 'b'; - fixture.detectChanges(); - flushMicrotasks(); + cmp.log = []; + cmp.exp = 'b'; + fixture.detectChanges(); + flushMicrotasks(); - expect(cmp.log).toEqual(['start => b', 'done => b']); - })); + expect(cmp.log).toEqual(['start => b', 'done => b']); + })); - it('should fire callback events for leave animations even if there is no leave transition', - fakeAsync(() => { - @Component({ - selector: 'my-cmp', - template: ` + it('should fire callback events for leave animations even if there is no leave transition', + fakeAsync(() => { + @Component({ + selector: 'my-cmp', + template: `
`, - animations: [trigger('myAnimation', [])] - }) - class Cmp { - exp: boolean = false; - log: any[] = []; - callback = (event: any) => { - const state = event.toState || '_default_'; - this.log.push(`${event.phaseName} => ${state}`); - } + animations: [trigger('myAnimation', [])] + }) + class Cmp { + exp: boolean = false; + log: any[] = []; + callback = (event: any) => { + const state = event.toState || '_default_'; + this.log.push(`${event.phaseName} => ${state}`); } + } - TestBed.configureTestingModule({ - providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], - declarations: [Cmp] - }); + TestBed.configureTestingModule({ + providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], + declarations: [Cmp] + }); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; - cmp.exp = true; - fixture.detectChanges(); - flushMicrotasks(); - expect(cmp.log).toEqual(['start => _default_', 'done => _default_']); + cmp.exp = true; + fixture.detectChanges(); + flushMicrotasks(); + expect(cmp.log).toEqual(['start => _default_', 'done => _default_']); - cmp.log = []; + cmp.log = []; - cmp.exp = false; - fixture.detectChanges(); - flushMicrotasks(); + cmp.exp = false; + fixture.detectChanges(); + flushMicrotasks(); - expect(cmp.log).toEqual(['start => void', 'done => void']); - })); + expect(cmp.log).toEqual(['start => void', 'done => void']); + })); - it('should fire callbacks on a sub animation once it starts and finishes', fakeAsync(() => { - @Component({ - selector: 'my-cmp', - template: ` + it('should fire callbacks on a sub animation once it starts and finishes', fakeAsync(() => { + @Component({ + selector: 'my-cmp', + template: `
`, - animations: [ - trigger( - 'parent', - [ - transition( - '* => go', - [ - style({width: '0px'}), - animate(1000, style({width: '100px'})), - query( - '.child', - [ - animateChild({duration: '1s'}), - ]), - animate(1000, style({width: '0px'})), - ]), - ]), - trigger( - 'child', - [ - transition( - '* => go', - [ - style({height: '0px'}), - animate(1000, style({height: '100px'})), - ]), - ]) - ] - }) - class Cmp { - log: string[] = []; - // TODO(issue/24571): remove '!'. - exp1 !: string; - // TODO(issue/24571): remove '!'. - exp2 !: string; - - cb(name: string, event: AnimationEvent) { this.log.push(name); } + animations: [ + trigger( + 'parent', + [ + transition( + '* => go', + [ + style({width: '0px'}), + animate(1000, style({width: '100px'})), + query( + '.child', + [ + animateChild({duration: '1s'}), + ]), + animate(1000, style({width: '0px'})), + ]), + ]), + trigger( + 'child', + [ + transition( + '* => go', + [ + style({height: '0px'}), + animate(1000, style({height: '100px'})), + ]), + ]) + ] + }) + class Cmp { + log: string[] = []; + // TODO(issue/24571): remove '!'. + exp1!: string; + // TODO(issue/24571): remove '!'. + exp2!: string; + + cb(name: string, event: AnimationEvent) { + this.log.push(name); } + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp1 = 'go'; - cmp.exp2 = 'go'; - fixture.detectChanges(); - engine.flush(); - flushMicrotasks(); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp1 = 'go'; + cmp.exp2 = 'go'; + fixture.detectChanges(); + engine.flush(); + flushMicrotasks(); - expect(cmp.log).toEqual(['parent-start', 'child-start']); - cmp.log = []; + expect(cmp.log).toEqual(['parent-start', 'child-start']); + cmp.log = []; - const players = getLog(); - expect(players.length).toEqual(3); - const [p1, p2, p3] = players; + const players = getLog(); + expect(players.length).toEqual(3); + const [p1, p2, p3] = players; - p1.finish(); - flushMicrotasks(); - expect(cmp.log).toEqual([]); + p1.finish(); + flushMicrotasks(); + expect(cmp.log).toEqual([]); - p2.finish(); - flushMicrotasks(); - expect(cmp.log).toEqual([]); + p2.finish(); + flushMicrotasks(); + expect(cmp.log).toEqual([]); - p3.finish(); - flushMicrotasks(); - expect(cmp.log).toEqual(['parent-done', 'child-done']); - })); + p3.finish(); + flushMicrotasks(); + expect(cmp.log).toEqual(['parent-done', 'child-done']); + })); - it('should fire callbacks and collect the correct the totalTime and element details for any queried sub animations', - fakeAsync( - () => { - @Component({ - selector: 'my-cmp', - template: ` + it('should fire callbacks and collect the correct the totalTime and element details for any queried sub animations', + fakeAsync(() => { + @Component({ + selector: 'my-cmp', + template: `
`, - animations: [ - trigger('parent', [ - transition('* => go', [ - style({ opacity: 0 }), - animate('1s', style({ opacity: 1 })), - query('.item', [ - style({ opacity: 0 }), - animate(1000, style({ opacity: 1 })) - ]), - query('.item', [ - animateChild({ duration: '1.8s', delay: '300ms' }) - ]) - ]) - ]), - trigger('child', [ - transition(':enter', [ - style({ opacity: 0 }), - animate(1500, style({ opacity: 1 })) - ]) - ]) - ] - }) - class Cmp { - log: string[] = []; - events: {[name: string]: any} = {}; - // TODO(issue/24571): remove '!'. - exp !: string; - items: any = [0, 1, 2, 3]; - - cb(name: string, phase: string, event: AnimationEvent) { - this.log.push(name + '-' + phase); - this.events[name] = event; - } - } - - TestBed.configureTestingModule({declarations: [Cmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.exp = 'go'; - fixture.detectChanges(); - engine.flush(); - flushMicrotasks(); - - expect(cmp.log).toEqual(['c-0-start', 'c-1-start', 'c-2-start', 'c-3-start']); - cmp.log = []; - - const players = getLog(); - // 1 + 4 + 4 = 9 players - expect(players.length).toEqual(9); - - const [pA, pq1a, pq1b, pq1c, pq1d, pq2a, pq2b, pq2c, pq2d] = getLog(); - pA.finish(); - pq1a.finish(); - pq1b.finish(); - pq1c.finish(); - pq1d.finish(); - flushMicrotasks(); - - expect(cmp.log).toEqual([]); - pq2a.finish(); - pq2b.finish(); - pq2c.finish(); - pq2d.finish(); - flushMicrotasks(); - - expect(cmp.log).toEqual( - ['all-done', 'c-0-done', 'c-1-done', 'c-2-done', 'c-3-done']); - - expect(cmp.events['c-0'].totalTime).toEqual(4100); // 1000 + 1000 + 1800 + 300 - expect(cmp.events['c-0'].element.innerText.trim()).toEqual('0'); - expect(cmp.events['c-1'].totalTime).toEqual(4100); - expect(cmp.events['c-1'].element.innerText.trim()).toEqual('1'); - expect(cmp.events['c-2'].totalTime).toEqual(4100); - expect(cmp.events['c-2'].element.innerText.trim()).toEqual('2'); - expect(cmp.events['c-3'].totalTime).toEqual(4100); - expect(cmp.events['c-3'].element.innerText.trim()).toEqual('3'); - })); - }); + animations: [ + trigger( + 'parent', + [transition( + '* => go', + [ + style({opacity: 0}), animate('1s', style({opacity: 1})), + query('.item', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), + query('.item', [animateChild({duration: '1.8s', delay: '300ms'})]) + ])]), + trigger( + 'child', + [transition(':enter', [style({opacity: 0}), animate(1500, style({opacity: 1}))])]) + ] + }) + class Cmp { + log: string[] = []; + events: {[name: string]: any} = {}; + // TODO(issue/24571): remove '!'. + exp!: string; + items: any = [0, 1, 2, 3]; + + cb(name: string, phase: string, event: AnimationEvent) { + this.log.push(name + '-' + phase); + this.events[name] = event; + } + } - describe('animation control flags', () => { - describe('[@.disabled]', () => { - it('should disable child animations when set to true', () => { - @Component({ - selector: 'if-cmp', - template: ` + TestBed.configureTestingModule({declarations: [Cmp]}); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'go'; + fixture.detectChanges(); + engine.flush(); + flushMicrotasks(); + + expect(cmp.log).toEqual(['c-0-start', 'c-1-start', 'c-2-start', 'c-3-start']); + cmp.log = []; + + const players = getLog(); + // 1 + 4 + 4 = 9 players + expect(players.length).toEqual(9); + + const [pA, pq1a, pq1b, pq1c, pq1d, pq2a, pq2b, pq2c, pq2d] = getLog(); + pA.finish(); + pq1a.finish(); + pq1b.finish(); + pq1c.finish(); + pq1d.finish(); + flushMicrotasks(); + + expect(cmp.log).toEqual([]); + pq2a.finish(); + pq2b.finish(); + pq2c.finish(); + pq2d.finish(); + flushMicrotasks(); + + expect(cmp.log).toEqual(['all-done', 'c-0-done', 'c-1-done', 'c-2-done', 'c-3-done']); + + expect(cmp.events['c-0'].totalTime).toEqual(4100); // 1000 + 1000 + 1800 + 300 + expect(cmp.events['c-0'].element.innerText.trim()).toEqual('0'); + expect(cmp.events['c-1'].totalTime).toEqual(4100); + expect(cmp.events['c-1'].element.innerText.trim()).toEqual('1'); + expect(cmp.events['c-2'].totalTime).toEqual(4100); + expect(cmp.events['c-2'].element.innerText.trim()).toEqual('2'); + expect(cmp.events['c-3'].totalTime).toEqual(4100); + expect(cmp.events['c-3'].element.innerText.trim()).toEqual('3'); + })); + }); + + describe('animation control flags', () => { + describe('[@.disabled]', () => { + it('should disable child animations when set to true', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - '* => 1, * => 2', - [ - animate(1234, style({width: '100px'})), - ]), - ]), - ] - }) - class Cmp { - exp: any = false; - disableExp = false; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + '* => 1, * => 2', + [ + animate(1234, style({width: '100px'})), + ]), + ]), + ] + }) + class Cmp { + exp: any = false; + disableExp = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - resetLog(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + resetLog(); - cmp.disableExp = true; - cmp.exp = '1'; - fixture.detectChanges(); + cmp.disableExp = true; + cmp.exp = '1'; + fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(0); + let players = getLog(); + expect(players.length).toEqual(0); - cmp.disableExp = false; - cmp.exp = '2'; - fixture.detectChanges(); + cmp.disableExp = false; + cmp.exp = '2'; + fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].totalTime).toEqual(1234); - }); + players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].totalTime).toEqual(1234); + }); - it('should ensure state() values are applied when an animation is disabled', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should ensure state() values are applied when an animation is disabled', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - state('1', style({height: '100px'})), state('2', style({height: '200px'})), - state('3', style({height: '300px'})), transition('* => *', animate(500)) - ]), - ] - }) - class Cmp { - exp: any = false; - disableExp = false; + animations: [ + trigger( + 'myAnimation', + [ + state('1', style({height: '100px'})), state('2', style({height: '200px'})), + state('3', style({height: '300px'})), transition('* => *', animate(500)) + ]), + ] + }) + class Cmp { + exp: any = false; + disableExp = false; - @ViewChild('elm', {static: true}) public element: any; - } + @ViewChild('elm', {static: true}) public element: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const engine = TestBed.inject(ɵAnimationEngine); - function assertHeight(element: any, height: string) { - expect(element.style['height']).toEqual(height); - } + function assertHeight(element: any, height: string) { + expect(element.style['height']).toEqual(height); + } - // In Ivy, change detection needs to run before the ViewQuery for cmp.element will - // resolve. Keeping this test enabled since we still want to test the animation logic. - if (ivyEnabled) fixture.detectChanges(); + // In Ivy, change detection needs to run before the ViewQuery for cmp.element will + // resolve. Keeping this test enabled since we still want to test the animation logic. + if (ivyEnabled) fixture.detectChanges(); - const cmp = fixture.componentInstance; - const element = cmp.element.nativeElement; - fixture.detectChanges(); + const cmp = fixture.componentInstance; + const element = cmp.element.nativeElement; + fixture.detectChanges(); - cmp.disableExp = true; - cmp.exp = '1'; - fixture.detectChanges(); - assertHeight(element, '100px'); + cmp.disableExp = true; + cmp.exp = '1'; + fixture.detectChanges(); + assertHeight(element, '100px'); - cmp.exp = '2'; - fixture.detectChanges(); - assertHeight(element, '200px'); + cmp.exp = '2'; + fixture.detectChanges(); + assertHeight(element, '200px'); - cmp.exp = '3'; - fixture.detectChanges(); - assertHeight(element, '300px'); - }); + cmp.exp = '3'; + fixture.detectChanges(); + assertHeight(element, '300px'); + }); - it('should disable animations for the element that they are disabled on', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should disable animations for the element that they are disabled on', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - '* => 1, * => 2', - [ - animate(1234, style({width: '100px'})), - ]), - ]), - ] - }) - class Cmp { - exp: any = false; - disableExp = false; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + '* => 1, * => 2', + [ + animate(1234, style({width: '100px'})), + ]), + ]), + ] + }) + class Cmp { + exp: any = false; + disableExp = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - resetLog(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + resetLog(); - cmp.disableExp = true; - cmp.exp = '1'; - fixture.detectChanges(); + cmp.disableExp = true; + cmp.exp = '1'; + fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(0); - resetLog(); + let players = getLog(); + expect(players.length).toEqual(0); + resetLog(); - cmp.disableExp = false; - cmp.exp = '2'; - fixture.detectChanges(); + cmp.disableExp = false; + cmp.exp = '2'; + fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].totalTime).toEqual(1234); - }); + players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].totalTime).toEqual(1234); + }); - it('should respect inner disabled nodes once a parent becomes enabled', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should respect inner disabled nodes once a parent becomes enabled', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [transition('* => 1, * => 2, * => 3', [animate(1234, style({width: '100px'}))])])] - }) - class Cmp { - disableParentExp = false; - disableChildExp = false; - exp = ''; - } + animations: [trigger( + 'myAnimation', + [transition('* => 1, * => 2, * => 3', [animate(1234, style({width: '100px'}))])])] + }) + class Cmp { + disableParentExp = false; + disableChildExp = false; + exp = ''; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - resetLog(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + resetLog(); - cmp.disableParentExp = true; - cmp.disableChildExp = true; - cmp.exp = '1'; - fixture.detectChanges(); + cmp.disableParentExp = true; + cmp.disableChildExp = true; + cmp.exp = '1'; + fixture.detectChanges(); - let players = getLog(); - expect(players.length).toEqual(0); + let players = getLog(); + expect(players.length).toEqual(0); - cmp.disableParentExp = false; - cmp.exp = '2'; - fixture.detectChanges(); + cmp.disableParentExp = false; + cmp.exp = '2'; + fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(0); + players = getLog(); + expect(players.length).toEqual(0); - cmp.disableChildExp = false; - cmp.exp = '3'; - fixture.detectChanges(); + cmp.disableChildExp = false; + cmp.exp = '3'; + fixture.detectChanges(); - players = getLog(); - expect(players.length).toEqual(1); - }); + players = getLog(); + expect(players.length).toEqual(1); + }); - it('should properly handle dom operations when disabled', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should properly handle dom operations when disabled', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - ':enter', - [ - style({opacity: 0}), - animate(1234, style({opacity: 1})), - ]), - transition( - ':leave', - [ - animate(1234, style({opacity: 0})), - ]), - ]), - ] - }) - class Cmp { - @ViewChild('parent') public parentElm: any; - disableExp = false; - exp = false; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + ':enter', + [ + style({opacity: 0}), + animate(1234, style({opacity: 1})), + ]), + transition( + ':leave', + [ + animate(1234, style({opacity: 0})), + ]), + ]), + ] + }) + class Cmp { + @ViewChild('parent') public parentElm: any; + disableExp = false; + exp = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.disableExp = true; - fixture.detectChanges(); - resetLog(); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.disableExp = true; + fixture.detectChanges(); + resetLog(); - const parent = cmp.parentElm !.nativeElement; + const parent = cmp.parentElm!.nativeElement; - cmp.exp = true; - fixture.detectChanges(); - expect(getLog().length).toEqual(0); - expect(parent.childElementCount).toEqual(1); + cmp.exp = true; + fixture.detectChanges(); + expect(getLog().length).toEqual(0); + expect(parent.childElementCount).toEqual(1); - cmp.exp = false; - fixture.detectChanges(); - expect(getLog().length).toEqual(0); - expect(parent.childElementCount).toEqual(0); - }); + cmp.exp = false; + fixture.detectChanges(); + expect(getLog().length).toEqual(0); + expect(parent.childElementCount).toEqual(0); + }); + + it('should properly resolve animation event listeners when disabled', fakeAsync(() => { + @Component({ + selector: 'if-cmp', + template: ` +
+
+
+ `, + animations: [ + trigger( + 'myAnimation', + [ + transition( + '* => 1, * => 2', + [style({opacity: 0}), animate(9876, style({opacity: 1}))]), + ]), + ] + }) + class Cmp { + disableExp = false; + exp = ''; + // TODO(issue/24571): remove '!'. + startEvent!: AnimationEvent; + // TODO(issue/24571): remove '!'. + doneEvent!: AnimationEvent; + } + + TestBed.configureTestingModule({declarations: [Cmp]}); + + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.disableExp = true; + fixture.detectChanges(); + resetLog(); + expect(cmp.startEvent).toBeFalsy(); + expect(cmp.doneEvent).toBeFalsy(); + + cmp.exp = '1'; + fixture.detectChanges(); + flushMicrotasks(); + expect(cmp.startEvent.totalTime).toEqual(9876); + expect(cmp.startEvent.disabled).toBeTruthy(); + expect(cmp.doneEvent.totalTime).toEqual(9876); + expect(cmp.doneEvent.disabled).toBeTruthy(); - it('should properly resolve animation event listeners when disabled', fakeAsync(() => { - @Component({ - selector: 'if-cmp', - template: ` -
-
-
- `, - animations: [ - trigger( - 'myAnimation', - [ - transition( - '* => 1, * => 2', - [style({opacity: 0}), animate(9876, style({opacity: 1}))]), - ]), - ] - }) - class Cmp { - disableExp = false; - exp = ''; - // TODO(issue/24571): remove '!'. - startEvent !: AnimationEvent; - // TODO(issue/24571): remove '!'. - doneEvent !: AnimationEvent; - } + cmp.exp = '2'; + cmp.disableExp = false; + fixture.detectChanges(); + flushMicrotasks(); + expect(cmp.startEvent.totalTime).toEqual(9876); + expect(cmp.startEvent.disabled).toBeFalsy(); + // the done event isn't fired because it's an actual animation + })); - TestBed.configureTestingModule({declarations: [Cmp]}); - - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.disableExp = true; - fixture.detectChanges(); - resetLog(); - expect(cmp.startEvent).toBeFalsy(); - expect(cmp.doneEvent).toBeFalsy(); - - cmp.exp = '1'; - fixture.detectChanges(); - flushMicrotasks(); - expect(cmp.startEvent.totalTime).toEqual(9876); - expect(cmp.startEvent.disabled).toBeTruthy(); - expect(cmp.doneEvent.totalTime).toEqual(9876); - expect(cmp.doneEvent.disabled).toBeTruthy(); - - cmp.exp = '2'; - cmp.disableExp = false; - fixture.detectChanges(); - flushMicrotasks(); - expect(cmp.startEvent.totalTime).toEqual(9876); - expect(cmp.startEvent.disabled).toBeFalsy(); - // the done event isn't fired because it's an actual animation - })); - - it('should work when there are no animations on the component handling the disable/enable flag', - () => { - @Component({ - selector: 'parent-cmp', - template: ` + it('should work when there are no animations on the component handling the disable/enable flag', + () => { + @Component({ + selector: 'parent-cmp', + template: `
` - }) - class ParentCmp { - @ViewChild('child') public child: ChildCmp|null = null; - disableExp = false; - } + }) + class ParentCmp { + @ViewChild('child') public child: ChildCmp|null = null; + disableExp = false; + } - @Component({ - selector: 'child-cmp', - template: ` + @Component({ + selector: 'child-cmp', + template: `
`, - animations: [trigger( - 'myAnimation', - [transition( - '* => go, * => goAgain', - [style({opacity: 0}), animate('1s', style({opacity: 1}))])])] - }) - class ChildCmp { - public exp = ''; - } - - TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - - const fixture = TestBed.createComponent(ParentCmp); - const cmp = fixture.componentInstance; - cmp.disableExp = true; - fixture.detectChanges(); - resetLog(); - - const child = cmp.child !; - child.exp = 'go'; - fixture.detectChanges(); - - expect(getLog().length).toEqual(0); - resetLog(); - - cmp.disableExp = false; - child.exp = 'goAgain'; - fixture.detectChanges(); - expect(getLog().length).toEqual(1); - }); - - it('should treat the property as true when the expression is missing', () => { - @Component({ - selector: 'parent-cmp', - animations: [ - trigger( - 'myAnimation', - [ - transition( - '* => go', - [ - style({opacity: 0}), - animate(500, style({opacity: 1})), - ]), - ]), - ], - template: ` -
-
-
- ` - }) - class Cmp { - exp = ''; - } - - TestBed.configureTestingModule({declarations: [Cmp]}); - - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - fixture.detectChanges(); - resetLog(); + animations: [trigger( + 'myAnimation', [transition( + '* => go, * => goAgain', + [style({opacity: 0}), animate('1s', style({opacity: 1}))])])] + }) + class ChildCmp { + public exp = ''; + } - cmp.exp = 'go'; - fixture.detectChanges(); - expect(getLog().length).toEqual(0); - }); + TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); - it('should respect parent/sub animations when the respective area in the DOM is disabled', - fakeAsync(() => { - @Component({ - selector: 'parent-cmp', - animations: [ - trigger( - 'parent', - [ - transition( - '* => empty', - [ - style({opacity: 0}), - query( - '@child', - [ - animateChild(), - ]), - animate('1s', style({opacity: 1})), - ]), - ]), - trigger( - 'child', - [ - transition( - ':leave', - [ - animate('1s', style({opacity: 0})), - ]), - ]), - ], - template: ` -
-
-
-
-
- ` - }) - class Cmp { - @ViewChild('container') public container: any; + const fixture = TestBed.createComponent(ParentCmp); + const cmp = fixture.componentInstance; + cmp.disableExp = true; + fixture.detectChanges(); + resetLog(); - disableExp = false; - exp = ''; - items: any[] = []; - doneLog: any[] = []; + const child = cmp.child!; + child.exp = 'go'; + fixture.detectChanges(); - onDone(event: any) { this.doneLog.push(event); } - } + expect(getLog().length).toEqual(0); + resetLog(); - TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - cmp.disableExp = true; - cmp.items = [0, 1, 2, 3, 4]; - fixture.detectChanges(); - flushMicrotasks(); - - cmp.exp = 'empty'; - cmp.items = []; - cmp.doneLog = []; - fixture.detectChanges(); - flushMicrotasks(); - - const elms = cmp.container.nativeElement.querySelectorAll('.item'); - expect(elms.length).toEqual(0); - - expect(cmp.doneLog.length).toEqual(6); - })); - }); - }); + cmp.disableExp = false; + child.exp = 'goAgain'; + fixture.detectChanges(); + expect(getLog().length).toEqual(1); + }); - describe('animation normalization', () => { - it('should convert hyphenated properties to camelcase by default', () => { + it('should treat the property as true when the expression is missing', () => { @Component({ - selector: 'cmp', - template: ` -
- `, + selector: 'parent-cmp', animations: [ trigger( 'myAnimation', @@ -3561,194 +3445,311 @@ const DEFAULT_COMPONENT_ID = '1'; transition( '* => go', [ - style({'background-color': 'red', height: '100px', fontSize: '100px'}), - animate( - '1s', - style( - {'background-color': 'blue', height: '200px', fontSize: '200px'})), + style({opacity: 0}), + animate(500, style({opacity: 1})), ]), ]), - ] + ], + template: ` +
+
+
+ ` }) class Cmp { - exp: any = false; + exp = ''; } TestBed.configureTestingModule({declarations: [Cmp]}); + const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; - cmp.exp = 'go'; fixture.detectChanges(); + resetLog(); - const players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].keyframes).toEqual([ - {backgroundColor: 'red', height: '100px', fontSize: '100px', offset: 0}, - {backgroundColor: 'blue', height: '200px', fontSize: '200px', offset: 1}, - ]); + cmp.exp = 'go'; + fixture.detectChanges(); + expect(getLog().length).toEqual(0); }); - it('should convert hyphenated properties to camelcase by default that are auto/pre style properties', - () => { + it('should respect parent/sub animations when the respective area in the DOM is disabled', + fakeAsync(() => { @Component({ - selector: 'cmp', - template: ` -
- `, + selector: 'parent-cmp', animations: [ trigger( - 'myAnimation', + 'parent', [ transition( - '* => go', + '* => empty', [ - style({'background-color': AUTO_STYLE, 'font-size': '100px'}), - animate( - '1s', style({'background-color': 'blue', 'font-size': PRE_STYLE})), + style({opacity: 0}), + query( + '@child', + [ + animateChild(), + ]), + animate('1s', style({opacity: 1})), ]), ]), - ] + trigger( + 'child', + [ + transition( + ':leave', + [ + animate('1s', style({opacity: 0})), + ]), + ]), + ], + template: ` +
+
+
+
+
+ ` }) class Cmp { - exp: any = false; + @ViewChild('container') public container: any; + + disableExp = false; + exp = ''; + items: any[] = []; + doneLog: any[] = []; + + onDone(event: any) { + this.doneLog.push(event); + } } TestBed.configureTestingModule({declarations: [Cmp]}); + const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; - cmp.exp = 'go'; + cmp.disableExp = true; + cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); + flushMicrotasks(); - const players = getLog(); - expect(players.length).toEqual(1); - expect(players[0].keyframes).toEqual([ - {backgroundColor: AUTO_STYLE, fontSize: '100px', offset: 0}, - {backgroundColor: 'blue', fontSize: PRE_STYLE, offset: 1}, - ]); - }); + cmp.exp = 'empty'; + cmp.items = []; + cmp.doneLog = []; + fixture.detectChanges(); + flushMicrotasks(); + + const elms = cmp.container.nativeElement.querySelectorAll('.item'); + expect(elms.length).toEqual(0); + + expect(cmp.doneLog.length).toEqual(6); + })); }); + }); - it('should throw neither state() or transition() are used inside of trigger()', () => { + describe('animation normalization', () => { + it('should convert hyphenated properties to camelcase by default', () => { @Component({ - selector: 'if-cmp', + selector: 'cmp', template: ` -
- `, - animations: [trigger('myAnimation', [animate(1000, style({width: '100px'}))])] +
+ `, + animations: [ + trigger( + 'myAnimation', + [ + transition( + '* => go', + [ + style({'background-color': 'red', height: '100px', fontSize: '100px'}), + animate( + '1s', + style({'background-color': 'blue', height: '200px', fontSize: '200px'})), + ]), + ]), + ] }) class Cmp { exp: any = false; } TestBed.configureTestingModule({declarations: [Cmp]}); - - expect(() => { TestBed.createComponent(Cmp); }) - .toThrowError( - /only state\(\) and transition\(\) definitions can sit inside of a trigger\(\)/); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + cmp.exp = 'go'; + fixture.detectChanges(); + + const players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].keyframes).toEqual([ + {backgroundColor: 'red', height: '100px', fontSize: '100px', offset: 0}, + {backgroundColor: 'blue', height: '200px', fontSize: '200px', offset: 1}, + ]); }); - it('should combine multiple errors together into one exception when an animation fails to be built', + it('should convert hyphenated properties to camelcase by default that are auto/pre style properties', () => { @Component({ - selector: 'if-cmp', + selector: 'cmp', template: ` -
- `, +
+ `, animations: [ trigger( - 'foo', - [ - transition(':enter', []), - transition( - '* => *', - [ - query('foo', animate(1000, style({background: 'red'}))), - ]), - ]), - trigger( - 'bar', + 'myAnimation', [ - transition(':enter', []), transition( - '* => *', + '* => go', [ - query('bar', animate(1000, style({background: 'blue'}))), + style({'background-color': AUTO_STYLE, 'font-size': '100px'}), + animate('1s', style({'background-color': 'blue', 'font-size': PRE_STYLE})), ]), ]), ] }) class Cmp { - fooExp: any = false; - barExp: any = false; + exp: any = false; } TestBed.configureTestingModule({declarations: [Cmp]}); - - const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; + cmp.exp = 'go'; fixture.detectChanges(); - cmp.fooExp = 'go'; - cmp.barExp = 'go'; + const players = getLog(); + expect(players.length).toEqual(1); + expect(players[0].keyframes).toEqual([ + {backgroundColor: AUTO_STYLE, fontSize: '100px', offset: 0}, + {backgroundColor: 'blue', fontSize: PRE_STYLE, offset: 1}, + ]); + }); + }); + + it('should throw neither state() or transition() are used inside of trigger()', () => { + @Component({ + selector: 'if-cmp', + template: ` +
+ `, + animations: [trigger('myAnimation', [animate(1000, style({width: '100px'}))])] + }) + class Cmp { + exp: any = false; + } - let errorMsg: string = ''; - try { - fixture.detectChanges(); - } catch (e) { - errorMsg = e.message; - } + TestBed.configureTestingModule({declarations: [Cmp]}); - expect(errorMsg).toMatch(/@foo has failed due to:/); - expect(errorMsg).toMatch(/`query\("foo"\)` returned zero elements/); - expect(errorMsg).toMatch(/@bar has failed due to:/); - expect(errorMsg).toMatch(/`query\("bar"\)` returned zero elements/); - }); + expect(() => { + TestBed.createComponent(Cmp); + }) + .toThrowError( + /only state\(\) and transition\(\) definitions can sit inside of a trigger\(\)/); + }); - it('should not throw an error if styles overlap in separate transitions', () => { - @Component({ - selector: 'if-cmp', - template: ` + it('should combine multiple errors together into one exception when an animation fails to be built', + () => { + @Component({ + selector: 'if-cmp', + template: ` +
+ `, + animations: [ + trigger( + 'foo', + [ + transition(':enter', []), + transition( + '* => *', + [ + query('foo', animate(1000, style({background: 'red'}))), + ]), + ]), + trigger( + 'bar', + [ + transition(':enter', []), + transition( + '* => *', + [ + query('bar', animate(1000, style({background: 'blue'}))), + ]), + ]), + ] + }) + class Cmp { + fooExp: any = false; + barExp: any = false; + } + + TestBed.configureTestingModule({declarations: [Cmp]}); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + fixture.detectChanges(); + + cmp.fooExp = 'go'; + cmp.barExp = 'go'; + + let errorMsg: string = ''; + try { + fixture.detectChanges(); + } catch (e) { + errorMsg = e.message; + } + + expect(errorMsg).toMatch(/@foo has failed due to:/); + expect(errorMsg).toMatch(/`query\("foo"\)` returned zero elements/); + expect(errorMsg).toMatch(/@bar has failed due to:/); + expect(errorMsg).toMatch(/`query\("bar"\)` returned zero elements/); + }); + + it('should not throw an error if styles overlap in separate transitions', () => { + @Component({ + selector: 'if-cmp', + template: `
`, - animations: [ - trigger( - 'myAnimation', - [ - transition( - 'void => *', - [ - style({opacity: 0}), - animate('0.5s 1s', style({opacity: 1})), - ]), - transition( - '* => void', - [animate(1000, style({height: 0})), animate(1000, style({opacity: 0}))]), - ]), - ] - }) - class Cmp { - exp: any = false; - } + animations: [ + trigger( + 'myAnimation', + [ + transition( + 'void => *', + [ + style({opacity: 0}), + animate('0.5s 1s', style({opacity: 1})), + ]), + transition( + '* => void', + [animate(1000, style({height: 0})), animate(1000, style({opacity: 0}))]), + ]), + ] + }) + class Cmp { + exp: any = false; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - expect(() => { TestBed.createComponent(Cmp); }).not.toThrowError(); - }); + expect(() => { + TestBed.createComponent(Cmp); + }).not.toThrowError(); + }); - modifiedInIvy('FW-952 - Error recovery is handled differently in Ivy than VE') - .it('should continue to clean up DOM-related animation artifacts even if a compiler-level error is thrown midway', - () => { - @Component({ - selector: 'if-cmp', - animations: [ - trigger( - 'foo', - [ - transition('* => something', []), - ]), - ], - template: ` + modifiedInIvy('FW-952 - Error recovery is handled differently in Ivy than VE') + .it('should continue to clean up DOM-related animation artifacts even if a compiler-level error is thrown midway', + () => { + @Component({ + selector: 'if-cmp', + animations: [ + trigger( + 'foo', + [ + transition('* => something', []), + ]), + ], + template: ` value = {{ foo[bar] }}
1
@@ -3756,67 +3757,66 @@ const DEFAULT_COMPONENT_ID = '1';
3
`, - }) - class Cmp { - exp: any = false; + }) + class Cmp { + exp: any = false; - @ViewChild('contents', {static: true}) public contents: any; - } + @ViewChild('contents', {static: true}) public contents: any; + } - TestBed.configureTestingModule({declarations: [Cmp]}); + TestBed.configureTestingModule({declarations: [Cmp]}); - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(Cmp); + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(Cmp); - const runCD = () => fixture.detectChanges(); - const cmp = fixture.componentInstance; + const runCD = () => fixture.detectChanges(); + const cmp = fixture.componentInstance; - cmp.exp = true; - expect(runCD).toThrow(); + cmp.exp = true; + expect(runCD).toThrow(); - const contents = cmp.contents.nativeElement; - expect(contents.innerText.replace(/\s+/gm, '')).toEqual('123'); + const contents = cmp.contents.nativeElement; + expect(contents.innerText.replace(/\s+/gm, '')).toEqual('123'); - cmp.exp = false; - expect(runCD).toThrow(); + cmp.exp = false; + expect(runCD).toThrow(); - expect(contents.innerText.trim()).toEqual(''); - }); + expect(contents.innerText.trim()).toEqual(''); + }); - describe('errors for not using the animation module', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [{provide: RendererFactory2, useExisting: ɵDomRendererFactory2}], - }); + describe('errors for not using the animation module', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [{provide: RendererFactory2, useExisting: ɵDomRendererFactory2}], }); + }); - it('should throw when using an @prop binding without the animation module', () => { - @Component({template: `
`}) - class Cmp { - } - - TestBed.configureTestingModule({declarations: [Cmp]}); - const comp = TestBed.createComponent(Cmp); - expect(() => comp.detectChanges()) - .toThrowError( - 'Found the synthetic property @myAnimation. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'); - }); + it('should throw when using an @prop binding without the animation module', () => { + @Component({template: `
`}) + class Cmp { + } - it('should throw when using an @prop listener without the animation module', () => { - @Component({template: `
`}) - class Cmp { - a: any; - } + TestBed.configureTestingModule({declarations: [Cmp]}); + const comp = TestBed.createComponent(Cmp); + expect(() => comp.detectChanges()) + .toThrowError( + 'Found the synthetic property @myAnimation. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'); + }); - TestBed.configureTestingModule({declarations: [Cmp]}); + it('should throw when using an @prop listener without the animation module', () => { + @Component({template: `
`}) + class Cmp { + a: any; + } - expect(() => TestBed.createComponent(Cmp)) - .toThrowError( - 'Found the synthetic listener @myAnimation.start. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'); + TestBed.configureTestingModule({declarations: [Cmp]}); - }); + expect(() => TestBed.createComponent(Cmp)) + .toThrowError( + 'Found the synthetic listener @myAnimation.start. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'); }); }); +}); })(); function assertHasParent(element: any, yes: boolean) { diff --git a/packages/core/test/animation/animation_router_integration_spec.ts b/packages/core/test/animation/animation_router_integration_spec.ts index 9a33ef40bbe37..033a8a3eebdb9 100644 --- a/packages/core/test/animation/animation_router_integration_spec.ts +++ b/packages/core/test/animation/animation_router_integration_spec.ts @@ -10,376 +10,377 @@ import {AnimationDriver, ɵAnimationEngine} from '@angular/animations/browser'; import {TransitionAnimationPlayer} from '@angular/animations/browser/src/render/transition_animation_engine'; import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing'; import {Component, HostBinding} from '@angular/core'; -import {TestBed, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing'; +import {fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {ActivatedRoute, Router, RouterOutlet} from '@angular/router'; import {RouterTestingModule} from '@angular/router/testing'; (function() { - // these tests are only mean't to be run within the DOM (for now) - if (isNode) return; - - describe('Animation Router Tests', function() { - function getLog(): MockAnimationPlayer[] { - return MockAnimationDriver.log as MockAnimationPlayer[]; - } - - function resetLog() { MockAnimationDriver.log = []; } - - beforeEach(() => { - resetLog(); - TestBed.configureTestingModule({ - imports: [RouterTestingModule, BrowserAnimationsModule], - providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}] - }); +// these tests are only mean't to be run within the DOM (for now) +if (isNode) return; + +describe('Animation Router Tests', function() { + function getLog(): MockAnimationPlayer[] { + return MockAnimationDriver.log as MockAnimationPlayer[]; + } + + function resetLog() { + MockAnimationDriver.log = []; + } + + beforeEach(() => { + resetLog(); + TestBed.configureTestingModule({ + imports: [RouterTestingModule, BrowserAnimationsModule], + providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}] }); + }); - it('should query the old and new routes via :leave and :enter', fakeAsync(() => { - @Component({ - animations: [ - trigger( - 'routerAnimations', - [ - transition( - 'page1 => page2', - [ - query(':leave', animateChild()), - query(':enter', animateChild()), - ]), - ]), - ], - template: ` + it('should query the old and new routes via :leave and :enter', fakeAsync(() => { + @Component({ + animations: [ + trigger( + 'routerAnimations', + [ + transition( + 'page1 => page2', + [ + query(':leave', animateChild()), + query(':enter', animateChild()), + ]), + ]), + ], + template: `
` - }) - class ContainerCmp { - constructor(public router: Router) {} - - prepareRouteAnimation(r: RouterOutlet) { - const animation = r.activatedRouteData['animation']; - const value = animation ? animation['value'] : null; - return value; - } - } - - @Component({ - selector: 'page1', - template: `page1`, - animations: [ - trigger( - 'page1Animation', - [ - transition( - ':leave', - [ - style({width: '200px'}), - animate(1000, style({width: '0px'})), - ]), - ]), - ] - }) - class Page1Cmp { - @HostBinding('@page1Animation') public doAnimate = true; - } - - @Component({ - selector: 'page2', - template: `page2`, - animations: [ - trigger( - 'page2Animation', - [ - transition( - ':enter', - [ - style({opacity: 0}), - animate(1000, style({opacity: 1})), - ]), - ]), - ] - }) - class Page2Cmp { - @HostBinding('@page2Animation') public doAnimate = true; + }) + class ContainerCmp { + constructor(public router: Router) {} + + prepareRouteAnimation(r: RouterOutlet) { + const animation = r.activatedRouteData['animation']; + const value = animation ? animation['value'] : null; + return value; } - - TestBed.configureTestingModule({ - declarations: [Page1Cmp, Page2Cmp, ContainerCmp], - imports: [RouterTestingModule.withRoutes([ - {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, - {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} - ])] - }); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ContainerCmp); - const cmp = fixture.componentInstance; - cmp.router.initialNavigation(); - tick(); - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page1'); - tick(); - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page2'); - tick(); - fixture.detectChanges(); - engine.flush(); - - const player = engine.players[0] !; - const groupPlayer = - (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer; - const players = groupPlayer.players as MockAnimationPlayer[]; - - expect(players.length).toEqual(2); - const [p1, p2] = players; - - expect(p1.duration).toEqual(1000); - expect(p1.keyframes).toEqual([ - {offset: 0, width: '200px'}, - {offset: 1, width: '0px'}, - ]); - - expect(p2.duration).toEqual(2000); - expect(p2.keyframes).toEqual([ - {offset: 0, opacity: '0'}, - {offset: .5, opacity: '0'}, - {offset: 1, opacity: '1'}, - ]); - })); - - it('should allow inner enter animations to be emulated within a routed item', fakeAsync(() => { - @Component({ - animations: [ - trigger( - 'routerAnimations', - [ - transition( - 'page1 => page2', - [ - query(':enter', animateChild()), - ]), - ]), - ], - template: ` + } + + @Component({ + selector: 'page1', + template: `page1`, + animations: [ + trigger( + 'page1Animation', + [ + transition( + ':leave', + [ + style({width: '200px'}), + animate(1000, style({width: '0px'})), + ]), + ]), + ] + }) + class Page1Cmp { + @HostBinding('@page1Animation') public doAnimate = true; + } + + @Component({ + selector: 'page2', + template: `page2`, + animations: [ + trigger( + 'page2Animation', + [ + transition( + ':enter', + [ + style({opacity: 0}), + animate(1000, style({opacity: 1})), + ]), + ]), + ] + }) + class Page2Cmp { + @HostBinding('@page2Animation') public doAnimate = true; + } + + TestBed.configureTestingModule({ + declarations: [Page1Cmp, Page2Cmp, ContainerCmp], + imports: [RouterTestingModule.withRoutes([ + {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, + {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} + ])] + }); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ContainerCmp); + const cmp = fixture.componentInstance; + cmp.router.initialNavigation(); + tick(); + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page1'); + tick(); + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page2'); + tick(); + fixture.detectChanges(); + engine.flush(); + + const player = engine.players[0]!; + const groupPlayer = + (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer; + const players = groupPlayer.players as MockAnimationPlayer[]; + + expect(players.length).toEqual(2); + const [p1, p2] = players; + + expect(p1.duration).toEqual(1000); + expect(p1.keyframes).toEqual([ + {offset: 0, width: '200px'}, + {offset: 1, width: '0px'}, + ]); + + expect(p2.duration).toEqual(2000); + expect(p2.keyframes).toEqual([ + {offset: 0, opacity: '0'}, + {offset: .5, opacity: '0'}, + {offset: 1, opacity: '1'}, + ]); + })); + + it('should allow inner enter animations to be emulated within a routed item', fakeAsync(() => { + @Component({ + animations: [ + trigger( + 'routerAnimations', + [ + transition( + 'page1 => page2', + [ + query(':enter', animateChild()), + ]), + ]), + ], + template: `
` - }) - class ContainerCmp { - constructor(public router: Router) {} - - prepareRouteAnimation(r: RouterOutlet) { - const animation = r.activatedRouteData['animation']; - const value = animation ? animation['value'] : null; - return value; - } + }) + class ContainerCmp { + constructor(public router: Router) {} + + prepareRouteAnimation(r: RouterOutlet) { + const animation = r.activatedRouteData['animation']; + const value = animation ? animation['value'] : null; + return value; } + } - @Component({selector: 'page1', template: `page1`, animations: []}) - class Page1Cmp { - } + @Component({selector: 'page1', template: `page1`, animations: []}) + class Page1Cmp { + } - @Component({ - selector: 'page2', - template: ` + @Component({ + selector: 'page2', + template: `

Page 2

`, - animations: [ - trigger( - 'page2Animation', - [ - transition( - ':enter', - [query('.if-one', animateChild()), query('.if-two', animateChild())]), - ]), - trigger( - 'ifAnimation', - [transition( - ':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))])]) - ] - }) - class Page2Cmp { - @HostBinding('@page2Animation') public doAnimate = true; - - public exp = true; - } - - TestBed.configureTestingModule({ - declarations: [Page1Cmp, Page2Cmp, ContainerCmp], - imports: [RouterTestingModule.withRoutes([ - {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, - {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} - ])] - }); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ContainerCmp); - const cmp = fixture.componentInstance; - cmp.router.initialNavigation(); - tick(); - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page1'); - tick(); - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page2'); - tick(); - fixture.detectChanges(); - engine.flush(); - - const player = engine.players[0] !; - const groupPlayer = - (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer; - const players = groupPlayer.players as MockAnimationPlayer[]; - - expect(players.length).toEqual(2); - const [p1, p2] = players; - - expect(p1.keyframes).toEqual([ - {offset: 0, opacity: '0'}, - {offset: 1, opacity: '1'}, - ]); - - expect(p2.keyframes).toEqual([ - {offset: 0, opacity: '0'}, - {offset: .5, opacity: '0'}, - {offset: 1, opacity: '1'}, - ]); - })); - - it('should allow inner leave animations to be emulated within a routed item', fakeAsync(() => { - @Component({ - animations: [ - trigger( - 'routerAnimations', - [ - transition( - 'page1 => page2', - [ - query(':leave', animateChild()), - ]), - ]), - ], - template: ` + animations: [ + trigger( + 'page2Animation', + [ + transition( + ':enter', + [query('.if-one', animateChild()), query('.if-two', animateChild())]), + ]), + trigger( + 'ifAnimation', + [transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))])]) + ] + }) + class Page2Cmp { + @HostBinding('@page2Animation') public doAnimate = true; + + public exp = true; + } + + TestBed.configureTestingModule({ + declarations: [Page1Cmp, Page2Cmp, ContainerCmp], + imports: [RouterTestingModule.withRoutes([ + {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, + {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} + ])] + }); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ContainerCmp); + const cmp = fixture.componentInstance; + cmp.router.initialNavigation(); + tick(); + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page1'); + tick(); + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page2'); + tick(); + fixture.detectChanges(); + engine.flush(); + + const player = engine.players[0]!; + const groupPlayer = + (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer; + const players = groupPlayer.players as MockAnimationPlayer[]; + + expect(players.length).toEqual(2); + const [p1, p2] = players; + + expect(p1.keyframes).toEqual([ + {offset: 0, opacity: '0'}, + {offset: 1, opacity: '1'}, + ]); + + expect(p2.keyframes).toEqual([ + {offset: 0, opacity: '0'}, + {offset: .5, opacity: '0'}, + {offset: 1, opacity: '1'}, + ]); + })); + + it('should allow inner leave animations to be emulated within a routed item', fakeAsync(() => { + @Component({ + animations: [ + trigger( + 'routerAnimations', + [ + transition( + 'page1 => page2', + [ + query(':leave', animateChild()), + ]), + ]), + ], + template: `
` - }) - class ContainerCmp { - constructor(public router: Router) {} - - prepareRouteAnimation(r: RouterOutlet) { - const animation = r.activatedRouteData['animation']; - const value = animation ? animation['value'] : null; - return value; - } + }) + class ContainerCmp { + constructor(public router: Router) {} + + prepareRouteAnimation(r: RouterOutlet) { + const animation = r.activatedRouteData['animation']; + const value = animation ? animation['value'] : null; + return value; } + } - @Component({ - selector: 'page1', - template: ` + @Component({ + selector: 'page1', + template: `

Page 1

`, - animations: [ - trigger( - 'page1Animation', - [ - transition( - ':leave', - [query('.if-one', animateChild()), query('.if-two', animateChild())]), - ]), - trigger( - 'ifAnimation', - [transition(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))])]), - ] - }) - class Page1Cmp { - @HostBinding('@page1Animation') public doAnimate = true; - - public exp = true; - } - - @Component({selector: 'page2', template: `page2`, animations: []}) - class Page2Cmp { - } - - TestBed.configureTestingModule({ - declarations: [Page1Cmp, Page2Cmp, ContainerCmp], - imports: [RouterTestingModule.withRoutes([ - {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, - {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} - ])] - }); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ContainerCmp); - const cmp = fixture.componentInstance; - cmp.router.initialNavigation(); - tick(); - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page1'); - tick(); - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page2'); - tick(); - fixture.detectChanges(); - engine.flush(); - - const player = engine.players[0] !; - const groupPlayer = - (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer; - const players = groupPlayer.players as MockAnimationPlayer[]; - - expect(players.length).toEqual(2); - const [p1, p2] = players; - - expect(p1.keyframes).toEqual([ - {offset: 0, opacity: '1'}, - {offset: 1, opacity: '0'}, - ]); - - expect(p2.keyframes).toEqual([ - {offset: 0, opacity: '1'}, - {offset: .5, opacity: '1'}, - {offset: 1, opacity: '0'}, - ]); - })); - - it('should properly collect :enter / :leave router nodes even when another non-router *template component is within the trigger boundaries', - fakeAsync(() => { - @Component({ - selector: 'ani-cmp', - animations: [ - trigger( - 'pageAnimation', - [ - transition( - 'page1 => page2', - [ - query('.router-container :leave', animate('1s', style({opacity: 0}))), - query('.router-container :enter', animate('1s', style({opacity: 1}))), - ]), - ]), - ], - template: ` + animations: [ + trigger( + 'page1Animation', + [ + transition( + ':leave', + [query('.if-one', animateChild()), query('.if-two', animateChild())]), + ]), + trigger( + 'ifAnimation', + [transition(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))])]), + ] + }) + class Page1Cmp { + @HostBinding('@page1Animation') public doAnimate = true; + + public exp = true; + } + + @Component({selector: 'page2', template: `page2`, animations: []}) + class Page2Cmp { + } + + TestBed.configureTestingModule({ + declarations: [Page1Cmp, Page2Cmp, ContainerCmp], + imports: [RouterTestingModule.withRoutes([ + {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, + {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} + ])] + }); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ContainerCmp); + const cmp = fixture.componentInstance; + cmp.router.initialNavigation(); + tick(); + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page1'); + tick(); + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page2'); + tick(); + fixture.detectChanges(); + engine.flush(); + + const player = engine.players[0]!; + const groupPlayer = + (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer; + const players = groupPlayer.players as MockAnimationPlayer[]; + + expect(players.length).toEqual(2); + const [p1, p2] = players; + + expect(p1.keyframes).toEqual([ + {offset: 0, opacity: '1'}, + {offset: 1, opacity: '0'}, + ]); + + expect(p2.keyframes).toEqual([ + {offset: 0, opacity: '1'}, + {offset: .5, opacity: '1'}, + {offset: 1, opacity: '0'}, + ]); + })); + + it('should properly collect :enter / :leave router nodes even when another non-router *template component is within the trigger boundaries', + fakeAsync(() => { + @Component({ + selector: 'ani-cmp', + animations: [ + trigger( + 'pageAnimation', + [ + transition( + 'page1 => page2', + [ + query('.router-container :leave', animate('1s', style({opacity: 0}))), + query('.router-container :enter', animate('1s', style({opacity: 1}))), + ]), + ]), + ], + template: `
@@ -392,138 +393,144 @@ import {RouterTestingModule} from '@angular/router/testing';
` - }) - class ContainerCmp { - loading = false; + }) + class ContainerCmp { + loading = false; - constructor(public router: Router) {} - - prepRoute(outlet: any) { return outlet.activatedRouteData['animation']; } - } + constructor(public router: Router) {} - @Component({selector: 'page1', template: `page1`}) - class Page1Cmp { + prepRoute(outlet: any) { + return outlet.activatedRouteData['animation']; } - - @Component({selector: 'page2', template: `page2`}) - class Page2Cmp { + } + + @Component({selector: 'page1', template: `page1`}) + class Page1Cmp { + } + + @Component({selector: 'page2', template: `page2`}) + class Page2Cmp { + } + + TestBed.configureTestingModule({ + declarations: [Page1Cmp, Page2Cmp, ContainerCmp], + imports: [RouterTestingModule.withRoutes([ + {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, + {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} + ])] + }); + + const engine = TestBed.inject(ɵAnimationEngine); + const fixture = TestBed.createComponent(ContainerCmp); + const cmp = fixture.componentInstance; + cmp.router.initialNavigation(); + tick(); + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page1'); + tick(); + cmp.loading = true; + fixture.detectChanges(); + engine.flush(); + + cmp.router.navigateByUrl('/page2'); + tick(); + cmp.loading = false; + fixture.detectChanges(); + engine.flush(); + + const players = engine.players; + expect(players.length).toEqual(1); + const [p1] = players; + + const innerPlayers = + ((p1 as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer).players; + expect(innerPlayers.length).toEqual(2); + + const [ip1, ip2] = innerPlayers as any; + expect(ip1.element.innerText).toEqual('page1'); + expect(ip2.element.innerText).toEqual('page2'); + })); + + it('should allow a recursive set of :leave animations to occur for nested routes', + fakeAsync(() => { + @Component({selector: 'ani-cmp', template: ''}) + class ContainerCmp { + constructor(private _router: Router) {} + log: string[] = []; + + enter() { + this._router.navigateByUrl('/(recur:recur/nested)'); } - TestBed.configureTestingModule({ - declarations: [Page1Cmp, Page2Cmp, ContainerCmp], - imports: [RouterTestingModule.withRoutes([ - {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, - {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')} - ])] - }); - - const engine = TestBed.inject(ɵAnimationEngine); - const fixture = TestBed.createComponent(ContainerCmp); - const cmp = fixture.componentInstance; - cmp.router.initialNavigation(); - tick(); - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page1'); - tick(); - cmp.loading = true; - fixture.detectChanges(); - engine.flush(); - - cmp.router.navigateByUrl('/page2'); - tick(); - cmp.loading = false; - fixture.detectChanges(); - engine.flush(); - - const players = engine.players; - expect(players.length).toEqual(1); - const [p1] = players; - - const innerPlayers = - ((p1 as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer).players; - expect(innerPlayers.length).toEqual(2); - - const [ip1, ip2] = innerPlayers as any; - expect(ip1.element.innerText).toEqual('page1'); - expect(ip2.element.innerText).toEqual('page2'); - })); - - it('should allow a recursive set of :leave animations to occur for nested routes', - fakeAsync(() => { - @Component({selector: 'ani-cmp', template: ''}) - class ContainerCmp { - constructor(private _router: Router) {} - log: string[] = []; - - enter() { this._router.navigateByUrl('/(recur:recur/nested)'); } - - leave() { this._router.navigateByUrl('/'); } + leave() { + this._router.navigateByUrl('/'); } - - @Component({ - selector: 'recur-page', - template: 'Depth: {{ depth }} \n ', - animations: [ - trigger( - 'pageAnimations', - [ - transition(':leave', [group([ - sequence([style({opacity: 1}), animate('1s', style({opacity: 0}))]), - query('@*', animateChild(), {optional: true}) - ])]), - ]), - ] - }) - class RecurPageCmp { - @HostBinding('@pageAnimations') public animatePage = true; - - @HostBinding('attr.data-depth') public depth = 0; - - constructor(private container: ContainerCmp, private route: ActivatedRoute) { - this.route.data.subscribe(data => { - this.container.log.push(`DEPTH ${data.depth}`); - this.depth = data.depth; - }); - } + } + + @Component({ + selector: 'recur-page', + template: 'Depth: {{ depth }} \n ', + animations: [ + trigger( + 'pageAnimations', + [ + transition(':leave', [group([ + sequence([style({opacity: 1}), animate('1s', style({opacity: 0}))]), + query('@*', animateChild(), {optional: true}) + ])]), + ]), + ] + }) + class RecurPageCmp { + @HostBinding('@pageAnimations') public animatePage = true; + + @HostBinding('attr.data-depth') public depth = 0; + + constructor(private container: ContainerCmp, private route: ActivatedRoute) { + this.route.data.subscribe(data => { + this.container.log.push(`DEPTH ${data.depth}`); + this.depth = data.depth; + }); } - - TestBed.configureTestingModule({ - declarations: [ContainerCmp, RecurPageCmp], - imports: [RouterTestingModule.withRoutes([{ - path: 'recur', - component: RecurPageCmp, - outlet: 'recur', - data: {depth: 0}, - children: [{path: 'nested', component: RecurPageCmp, data: {depth: 1}}] - }])] - }); - - const fixture = TestBed.createComponent(ContainerCmp); - const cmp = fixture.componentInstance; - cmp.enter(); - tick(); - fixture.detectChanges(); - flushMicrotasks(); - - expect(cmp.log).toEqual([ - 'DEPTH 0', - 'DEPTH 1', - ]); - - cmp.leave(); - tick(); - fixture.detectChanges(); - - const players = getLog(); - expect(players.length).toEqual(2); - - const [p1, p2] = players; - expect(p1.element.getAttribute('data-depth')).toEqual('0'); - expect(p2.element.getAttribute('data-depth')).toEqual('1'); - })); - }); + } + + TestBed.configureTestingModule({ + declarations: [ContainerCmp, RecurPageCmp], + imports: [RouterTestingModule.withRoutes([{ + path: 'recur', + component: RecurPageCmp, + outlet: 'recur', + data: {depth: 0}, + children: [{path: 'nested', component: RecurPageCmp, data: {depth: 1}}] + }])] + }); + + const fixture = TestBed.createComponent(ContainerCmp); + const cmp = fixture.componentInstance; + cmp.enter(); + tick(); + fixture.detectChanges(); + flushMicrotasks(); + + expect(cmp.log).toEqual([ + 'DEPTH 0', + 'DEPTH 1', + ]); + + cmp.leave(); + tick(); + fixture.detectChanges(); + + const players = getLog(); + expect(players.length).toEqual(2); + + const [p1, p2] = players; + expect(p1.element.getAttribute('data-depth')).toEqual('0'); + expect(p2.element.getAttribute('data-depth')).toEqual('1'); + })); +}); }); function makeAnimationData(value: string, params: {[key: string]: any} = {}): {[key: string]: any} { diff --git a/packages/core/test/animation/animations_with_css_keyframes_animations_integration_spec.ts b/packages/core/test/animation/animations_with_css_keyframes_animations_integration_spec.ts index 9590b533449ac..5bb6822b049e0 100644 --- a/packages/core/test/animation/animations_with_css_keyframes_animations_integration_spec.ts +++ b/packages/core/test/animation/animations_with_css_keyframes_animations_integration_spec.ts @@ -15,23 +15,22 @@ import {browserDetection} from '@angular/platform-browser/testing/src/browser_ut import {TestBed} from '../../testing'; (function() { - // these tests are only mean't to be run within the DOM (for now) - // Buggy in Chromium 39, see https://github.com/angular/angular/issues/15793 - if (isNode) return; - - describe('animation integration tests using css keyframe animations', function() { - - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [{provide: AnimationDriver, useClass: CssKeyframesDriver}], - imports: [BrowserAnimationsModule] - }); +// these tests are only mean't to be run within the DOM (for now) +// Buggy in Chromium 39, see https://github.com/angular/angular/issues/15793 +if (isNode) return; + +describe('animation integration tests using css keyframe animations', function() { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [{provide: AnimationDriver, useClass: CssKeyframesDriver}], + imports: [BrowserAnimationsModule] }); + }); - it('should compute (*) animation styles for a container that is being removed', () => { - @Component({ - selector: 'ani-cmp', - template: ` + it('should compute (*) animation styles for a container that is being removed', () => { + @Component({ + selector: 'ani-cmp', + template: `
1
2
@@ -40,46 +39,46 @@ import {TestBed} from '../../testing';
5
`, - animations: [trigger( - 'auto', - [ - state('void', style({height: '0px'})), - state('*', style({height: '*'})), - transition('* => *', animate(1000)), - ])] - }) - class Cmp { - public exp: boolean = false; - } - - TestBed.configureTestingModule({declarations: [Cmp]}); - - const engine = TestBed.inject(AnimationEngine); - const fixture = TestBed.createComponent(Cmp); - const cmp = fixture.componentInstance; - - cmp.exp = true; - fixture.detectChanges(); - - expect(engine.players.length).toEqual(1); - let player = getPlayer(engine) as CssKeyframesPlayer; - expect(player.keyframes).toEqual([{height: '0px', offset: 0}, {height: '100px', offset: 1}]); - - player.finish(); - if (browserDetection.isOldChrome) return; - - cmp.exp = false; - fixture.detectChanges(); - - player = getPlayer(engine) as CssKeyframesPlayer; - expect(player.keyframes).toEqual([{height: '100px', offset: 0}, {height: '0px', offset: 1}]); - }); + animations: [trigger( + 'auto', + [ + state('void', style({height: '0px'})), + state('*', style({height: '*'})), + transition('* => *', animate(1000)), + ])] + }) + class Cmp { + public exp: boolean = false; + } + + TestBed.configureTestingModule({declarations: [Cmp]}); + + const engine = TestBed.inject(AnimationEngine); + const fixture = TestBed.createComponent(Cmp); + const cmp = fixture.componentInstance; + + cmp.exp = true; + fixture.detectChanges(); + + expect(engine.players.length).toEqual(1); + let player = getPlayer(engine) as CssKeyframesPlayer; + expect(player.keyframes).toEqual([{height: '0px', offset: 0}, {height: '100px', offset: 1}]); + + player.finish(); + if (browserDetection.isOldChrome) return; + + cmp.exp = false; + fixture.detectChanges(); + + player = getPlayer(engine) as CssKeyframesPlayer; + expect(player.keyframes).toEqual([{height: '100px', offset: 0}, {height: '0px', offset: 1}]); + }); - it('should cleanup all existing @keyframe