diff --git a/packages/core/src/render3/definition.ts b/packages/core/src/render3/definition.ts index 5c47c59d30..d675b5612e 100644 --- a/packages/core/src/render3/definition.ts +++ b/packages/core/src/render3/definition.ts @@ -181,7 +181,10 @@ export const defineDirective = defineComponent as(directiveDefinition: Direct * @param pure Whether the pipe is pure. */ export function definePipe( - {type, factory, pure}: {type: Type, factory: () => PipeTransform, pure?: boolean}): - PipeDef { - throw new Error('TODO: implement!'); + {type, factory, pure}: {type: Type, factory: () => T, pure?: boolean}): PipeDef { + return >{ + n: factory, + pure: pure !== false, + onDestroy: type.prototype.ngOnDestroy || null + }; } diff --git a/packages/core/src/render3/instructions.ts b/packages/core/src/render3/instructions.ts index 786fb55b5e..c059b5ee5a 100644 --- a/packages/core/src/render3/instructions.ts +++ b/packages/core/src/render3/instructions.ts @@ -20,7 +20,7 @@ import {assertNodeType} from './node_assert'; import {appendChild, insertChild, insertView, appendProjectedNode, removeView, canInsertNativeNode} from './node_manipulation'; import {matchingSelectorIndex} from './node_selector_matcher'; import {ComponentDef, ComponentTemplate, ComponentType, DirectiveDef, DirectiveType} from './interfaces/definition'; -import {RElement, RText, Renderer3, RendererFactory3, ProceduralRenderer3, RendererStyleFlags3, isProceduralRenderer} from './interfaces/renderer'; +import {RElement, RText, Renderer3, RendererFactory3, ProceduralRenderer3, ObjectOrientedRenderer3, RendererStyleFlags3, isProceduralRenderer} from './interfaces/renderer'; import {isDifferent, stringify} from './util'; import {executeHooks, executeContentHooks, queueLifecycleHooks, queueInitHooks, executeInitHooks} from './hooks'; import {ViewRef} from './view_ref'; @@ -122,7 +122,7 @@ export function getCreationMode(): boolean { } /** - * An array of nodes (text, element, container, etc), their bindings, and + * An array of nodes (text, element, container, etc), pipes, their bindings, and * any local variables that need to be stored between invocations. */ let data: any[]; @@ -1806,6 +1806,10 @@ export function bindingUpdated4(exp1: any, exp2: any, exp3: any, exp4: any): boo return bindingUpdated2(exp3, exp4) || different; } +export function getTView(): TView { + return currentView.tView; +} + export function getDirectiveInstance(instanceOrArray: T | [T]): T { // Directives with content queries store an array in data[directiveIndex] // with the instance as the first index diff --git a/packages/core/src/render3/interfaces/definition.ts b/packages/core/src/render3/interfaces/definition.ts index b1a9d067d4..45d6d7a054 100644 --- a/packages/core/src/render3/interfaces/definition.ts +++ b/packages/core/src/render3/interfaces/definition.ts @@ -140,7 +140,7 @@ export interface PipeDef { * NOTE: this property is short (1 char) because it is used in * component templates which is sensitive to size. */ - n: () => PipeTransform; + n: () => T; /** * Whether or not the pipe is pure. diff --git a/packages/core/src/render3/interfaces/view.ts b/packages/core/src/render3/interfaces/view.ts index 3796ad0d6c..0bd4d67992 100644 --- a/packages/core/src/render3/interfaces/view.ts +++ b/packages/core/src/render3/interfaces/view.ts @@ -7,7 +7,7 @@ */ import {LContainer} from './container'; -import {ComponentTemplate, DirectiveDef} from './definition'; +import {ComponentTemplate, DirectiveDef, PipeDef} from './definition'; import {LElementNode, LViewNode, TNode} from './node'; import {LQueries} from './query'; import {Renderer3} from './renderer'; @@ -324,11 +324,11 @@ export const enum LifecycleStage { * Static data that corresponds to the instance-specific data array on an LView. * * Each node's static data is stored in tData at the same index that it's stored - * in the data array. Each directive's definition is stored here at the same index - * as its directive instance in the data array. Any nodes that do not have static + * in the data array. Each directive/pipe's definition is stored here at the same index + * as its directive/pipe instance in the data array. Any nodes that do not have static * data store a null value in tData to avoid a sparse array. */ -export type TData = (TNode | DirectiveDef| null)[]; +export type TData = (TNode | DirectiveDef| PipeDef| 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/pipe.ts b/packages/core/src/render3/pipe.ts index 6af5df0630..d223996310 100644 --- a/packages/core/src/render3/pipe.ts +++ b/packages/core/src/render3/pipe.ts @@ -6,17 +6,32 @@ * found in the LICENSE file at https://angular.io/license */ +import {PipeTransform} from '../change_detection/pipe_transform'; + +import {getTView, load, store} from './instructions'; import {PipeDef} from './interfaces/definition'; +import {pureFunction1, pureFunction2, pureFunction3, pureFunction4, pureFunctionV} from './pure_function'; + /** * Create a pipe. * * @param index Pipe index where the pipe will be stored. * @param pipeDef Pipe definition object for registering life cycle hooks. - * @param pipe A Pipe instance. + * @param firstInstance (optional) The first instance of the pipe that can be reused for pure pipes. + * @returns T the instance of the pipe. */ -export function pipe(index: number, pipeDef: PipeDef, pipe: T): void { - throw new Error('TODO: implement!'); +export function pipe(index: number, pipeDef: PipeDef, firstInstance?: T): T { + const tView = getTView(); + if (tView.firstTemplatePass) { + tView.data[index] = pipeDef; + if (pipeDef.onDestroy != null) { + (tView.destroyHooks || (tView.destroyHooks = [])).push(index, pipeDef.onDestroy); + } + } + const pipeInstance = pipeDef.pure && firstInstance ? firstInstance : pipeDef.n(); + store(index, pipeInstance); + return pipeInstance; } /** @@ -29,7 +44,9 @@ export function pipe(index: number, pipeDef: PipeDef, pipe: T): void { * @param v1 1st argument to {@link PipeTransform#transform}. */ export function pipeBind1(index: number, v1: any): any { - throw new Error('TODO: implement!'); + const pipeInstance = load(index); + return isPure(index) ? pureFunction1(pipeInstance.transform, v1, pipeInstance) : + pipeInstance.transform(v1); } /** @@ -43,7 +60,9 @@ export function pipeBind1(index: number, v1: any): any { * @param v2 2nd argument to {@link PipeTransform#transform}. */ export function pipeBind2(index: number, v1: any, v2: any): any { - throw new Error('TODO: implement!'); + const pipeInstance = load(index); + return isPure(index) ? pureFunction2(pipeInstance.transform, v1, v2, pipeInstance) : + pipeInstance.transform(v1, v2); } /** @@ -58,7 +77,9 @@ export function pipeBind2(index: number, v1: any, v2: any): any { * @param v3 4rd argument to {@link PipeTransform#transform}. */ export function pipeBind3(index: number, v1: any, v2: any, v3: any): any { - throw new Error('TODO: implement!'); + const pipeInstance = load(index); + return isPure(index) ? pureFunction3(pipeInstance.transform.bind(pipeInstance), v1, v2, v3) : + pipeInstance.transform(v1, v2, v3); } /** @@ -74,7 +95,9 @@ export function pipeBind3(index: number, v1: any, v2: any, v3: any): any { * @param v4 4th argument to {@link PipeTransform#transform}. */ export function pipeBind4(index: number, v1: any, v2: any, v3: any, v4: any): any { - throw new Error('TODO: implement!'); + const pipeInstance = load(index); + return isPure(index) ? pureFunction4(pipeInstance.transform, v1, v2, v3, v4, pipeInstance) : + pipeInstance.transform(v1, v2, v3, v4); } /** @@ -87,5 +110,11 @@ export function pipeBind4(index: number, v1: any, v2: any, v3: any, v4: any): an * @param values Array of arguments to pass to {@link PipeTransform#transform} method. */ export function pipeBindV(index: number, values: any[]): any { - throw new Error('TODO: implement!'); -} \ No newline at end of file + const pipeInstance = load(index); + return isPure(index) ? pureFunctionV(pipeInstance.transform, values, pipeInstance) : + pipeInstance.transform.apply(pipeInstance, values); +} + +function isPure(index: number): boolean { + return (>getTView().data[index]).pure; +} diff --git a/packages/core/src/render3/pure_function.ts b/packages/core/src/render3/pure_function.ts index 4aad400b27..071c6d2966 100644 --- a/packages/core/src/render3/pure_function.ts +++ b/packages/core/src/render3/pure_function.ts @@ -17,8 +17,9 @@ import {bindingUpdated, bindingUpdated2, bindingUpdated4, checkAndUpdateBinding, * @param pureFn Function that returns a value * @returns value */ -export function pureFunction0(pureFn: () => T): T { - return getCreationMode() ? checkAndUpdateBinding(pureFn()) : consumeBinding(); +export function pureFunction0(pureFn: () => T, thisArg?: any): T { + return getCreationMode() ? checkAndUpdateBinding(thisArg ? pureFn.call(thisArg) : pureFn()) : + consumeBinding(); } /** @@ -29,8 +30,10 @@ export function pureFunction0(pureFn: () => T): T { * @param exp Updated expression value * @returns Updated value */ -export function pureFunction1(pureFn: (v: any) => any, exp: any): any { - return bindingUpdated(exp) ? checkAndUpdateBinding(pureFn(exp)) : consumeBinding(); +export function pureFunction1(pureFn: (v: any) => any, exp: any, thisArg?: any): any { + return bindingUpdated(exp) ? + checkAndUpdateBinding(thisArg ? pureFn.call(thisArg, exp) : pureFn(exp)) : + consumeBinding(); } /** @@ -42,8 +45,11 @@ export function pureFunction1(pureFn: (v: any) => any, exp: any): any { * @param exp2 * @returns Updated value */ -export function pureFunction2(pureFn: (v1: any, v2: any) => any, exp1: any, exp2: any): any { - return bindingUpdated2(exp1, exp2) ? checkAndUpdateBinding(pureFn(exp1, exp2)) : consumeBinding(); +export function pureFunction2( + pureFn: (v1: any, v2: any) => any, exp1: any, exp2: any, thisArg?: any): any { + return bindingUpdated2(exp1, exp2) ? + checkAndUpdateBinding(thisArg ? pureFn.call(thisArg, exp1, exp2) : pureFn(exp1, exp2)) : + consumeBinding(); } /** @@ -57,10 +63,13 @@ export function pureFunction2(pureFn: (v1: any, v2: any) => any, exp1: any, exp2 * @returns Updated value */ export function pureFunction3( - pureFn: (v1: any, v2: any, v3: any) => any, exp1: any, exp2: any, exp3: any): any { + pureFn: (v1: any, v2: any, v3: any) => any, exp1: any, exp2: any, exp3: any, + thisArg?: any): any { const different = bindingUpdated2(exp1, exp2); - return bindingUpdated(exp3) || different ? checkAndUpdateBinding(pureFn(exp1, exp2, exp3)) : - consumeBinding(); + return bindingUpdated(exp3) || different ? + checkAndUpdateBinding( + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3) : pureFn(exp1, exp2, exp3)) : + consumeBinding(); } /** @@ -75,10 +84,11 @@ export function pureFunction3( * @returns Updated value */ export function pureFunction4( - pureFn: (v1: any, v2: any, v3: any, v4: any) => any, exp1: any, exp2: any, exp3: any, - exp4: any): any { + pureFn: (v1: any, v2: any, v3: any, v4: any) => any, exp1: any, exp2: any, exp3: any, exp4: any, + thisArg?: any): any { return bindingUpdated4(exp1, exp2, exp3, exp4) ? - checkAndUpdateBinding(pureFn(exp1, exp2, exp3, exp4)) : + checkAndUpdateBinding( + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4) : pureFn(exp1, exp2, exp3, exp4)) : consumeBinding(); } @@ -96,10 +106,12 @@ export function pureFunction4( */ export function pureFunction5( pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any) => any, exp1: any, exp2: any, exp3: any, - exp4: any, exp5: any): any { + exp4: any, exp5: any, thisArg?: any): any { const different = bindingUpdated4(exp1, exp2, exp3, exp4); return bindingUpdated(exp5) || different ? - checkAndUpdateBinding(pureFn(exp1, exp2, exp3, exp4, exp5)) : + checkAndUpdateBinding( + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5) : + pureFn(exp1, exp2, exp3, exp4, exp5)) : consumeBinding(); } @@ -118,10 +130,12 @@ export function pureFunction5( */ export function pureFunction6( pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any, v6: any) => any, exp1: any, exp2: any, - exp3: any, exp4: any, exp5: any, exp6: any): any { + exp3: any, exp4: any, exp5: any, exp6: any, thisArg?: any): any { const different = bindingUpdated4(exp1, exp2, exp3, exp4); return bindingUpdated2(exp5, exp6) || different ? - checkAndUpdateBinding(pureFn(exp1, exp2, exp3, exp4, exp5, exp6)) : + checkAndUpdateBinding( + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6) : + pureFn(exp1, exp2, exp3, exp4, exp5, exp6)) : consumeBinding(); } @@ -141,11 +155,13 @@ export function pureFunction6( */ export function pureFunction7( pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any, v6: any, v7: any) => any, exp1: any, - exp2: any, exp3: any, exp4: any, exp5: any, exp6: any, exp7: any): any { + exp2: any, exp3: any, exp4: any, exp5: any, exp6: any, exp7: any, thisArg?: any): any { let different = bindingUpdated4(exp1, exp2, exp3, exp4); different = bindingUpdated2(exp5, exp6) || different; return bindingUpdated(exp7) || different ? - checkAndUpdateBinding(pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7)) : + checkAndUpdateBinding( + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7) : + pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7)) : consumeBinding(); } @@ -166,10 +182,13 @@ export function pureFunction7( */ export function pureFunction8( pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any, v6: any, v7: any, v8: any) => any, - exp1: any, exp2: any, exp3: any, exp4: any, exp5: any, exp6: any, exp7: any, exp8: any): any { + exp1: any, exp2: any, exp3: any, exp4: any, exp5: any, exp6: any, exp7: any, exp8: any, + thisArg?: any): any { const different = bindingUpdated4(exp1, exp2, exp3, exp4); return bindingUpdated4(exp5, exp6, exp7, exp8) || different ? - checkAndUpdateBinding(pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)) : + checkAndUpdateBinding( + thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8) : + pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)) : consumeBinding(); } @@ -184,11 +203,11 @@ export function pureFunction8( * @param exp An array of binding values * @returns Updated value */ -export function pureFunctionV(pureFn: (...v: any[]) => any, exps: any[]): any { +export function pureFunctionV(pureFn: (...v: any[]) => any, exps: any[], thisArg?: any): any { let different = false; for (let i = 0; i < exps.length; i++) { bindingUpdated(exps[i]) && (different = true); } - return different ? checkAndUpdateBinding(pureFn.apply(null, exps)) : consumeBinding(); + return different ? checkAndUpdateBinding(pureFn.apply(thisArg, exps)) : consumeBinding(); } diff --git a/packages/core/test/render3/compiler_canonical/pipes_spec.ts b/packages/core/test/render3/compiler_canonical/pipes_spec.ts index 5cdf0a5ca9..41d1aab086 100644 --- a/packages/core/test/render3/compiler_canonical/pipes_spec.ts +++ b/packages/core/test/render3/compiler_canonical/pipes_spec.ts @@ -8,21 +8,33 @@ import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, Directive, HostBinding, HostListener, Injectable, Input, NgModule, OnDestroy, Optional, Pipe, PipeTransform, QueryList, SimpleChanges, TemplateRef, ViewChild, ViewChildren, ViewContainerRef} from '../../../src/core'; import * as $r3$ from '../../../src/core_render3_private_export'; -import {renderComponent, toHtml} from '../render_util'; +import {containerEl, renderComponent, toHtml} from '../render_util'; /// See: `normative.md` -xdescribe('pipes', () => { - type $MyApp$ = MyApp; +describe('pipes', () => { + type $any$ = any; type $boolean$ = boolean; + let myPipeTransformCalls = 0; + let myPurePipeTransformCalls = 0; + @Pipe({ name: 'myPipe', pure: false, }) class MyPipe implements PipeTransform, OnDestroy { - transform(value: any, ...args: any[]) { throw new Error('Method not implemented.'); } - ngOnDestroy(): void { throw new Error('Method not implemented.'); } + private numberOfBang = 1; + + transform(value: string, size: number): string { + let result = value.substring(size); + for (let i = 0; i < this.numberOfBang; i++) result += '!'; + this.numberOfBang++; + myPipeTransformCalls++; + return result; + } + + ngOnDestroy() { this.numberOfBang = 1; } // NORMATIVE static ngPipeDef = $r3$.ɵdefinePipe({ @@ -35,14 +47,19 @@ xdescribe('pipes', () => { @Pipe({ name: 'myPurePipe', + pure: true, }) class MyPurePipe implements PipeTransform { - transform(value: any, ...args: any[]) { throw new Error('Method not implemented.'); } + transform(value: string, size: number): string { + myPurePipeTransformCalls++; + return value.substring(size); + } // NORMATIVE static ngPipeDef = $r3$.ɵdefinePipe({ type: MyPurePipe, factory: function MyPurePipe_Factory() { return new MyPurePipe(); }, + pure: true, }); // /NORMATIVE } @@ -52,29 +69,128 @@ xdescribe('pipes', () => { const $MyPipe_ngPipeDef$ = MyPipe.ngPipeDef; // /NORMATIVE - @Component({template: `{{name | myPipe:size | myPurePipe:size }}`}) - class MyApp { - name = 'World'; - size = 0; - - // NORMATIVE - static ngComponentDef = $r3$.ɵdefineComponent({ - type: MyApp, - tag: 'my-app', - factory: function MyApp_Factory() { return new MyApp(); }, - template: function MyApp_Template(ctx: $MyApp$, cm: $boolean$) { - if (cm) { - $r3$.ɵT(0); - $r3$.ɵPp(1, $MyPurePipe_ngPipeDef$, $MyPurePipe_ngPipeDef$.n()); - $r3$.ɵPp(2, $MyPipe_ngPipeDef$, $MyPipe_ngPipeDef$.n()); - } - $r3$.ɵt(2, $r3$.ɵi1('', $r3$.ɵpb2(1, $r3$.ɵpb2(2, ctx.name, ctx.size), ctx.size), '')); - } - }); - // /NORMATIVE - } - it('should render pipes', () => { - // TODO(misko): write a test once pipes runtime is implemented. - }); + type $MyApp$ = MyApp; + myPipeTransformCalls = 0; + myPurePipeTransformCalls = 0; + + @Component({template: `{{name | myPipe:size | myPurePipe:size }}`}) + class MyApp { + name = '12World'; + size = 1; + + // NORMATIVE + static ngComponentDef = $r3$.ɵdefineComponent({ + type: MyApp, + tag: 'my-app', + factory: function MyApp_Factory() { return new MyApp(); }, + template: function MyApp_Template(ctx: $MyApp$, cm: $boolean$) { + if (cm) { + $r3$.ɵT(0); + $r3$.ɵPp(1, $MyPipe_ngPipeDef$); + $r3$.ɵPp(2, $MyPurePipe_ngPipeDef$); + } + $r3$.ɵt(0, $r3$.ɵi1('', $r3$.ɵpb2(1, $r3$.ɵpb2(2, ctx.name, ctx.size), ctx.size), '')); + } + }); + // /NORMATIVE + } + + let myApp: MyApp = renderComponent(MyApp); + expect(toHtml(containerEl)).toEqual('World!'); + expect(myPurePipeTransformCalls).toEqual(1); + expect(myPipeTransformCalls).toEqual(1); + + $r3$.ɵdetectChanges(myApp); + expect(toHtml(containerEl)).toEqual('World!!'); + expect(myPurePipeTransformCalls).toEqual(1); + expect(myPipeTransformCalls).toEqual(2); + + myApp.name = '34WORLD'; + $r3$.ɵdetectChanges(myApp); + expect(toHtml(containerEl)).toEqual('WORLD!!!'); + expect(myPurePipeTransformCalls).toEqual(2); + expect(myPipeTransformCalls).toEqual(3); + }); + + it('should render many pipes and forward the first instance (pure or impure pipe)', () => { + type $MyApp$ = MyApp; + type $MyPurePipe$ = MyPurePipe; + myPipeTransformCalls = 0; + myPurePipeTransformCalls = 0; + + @Directive({ + selector: '[oneTimeIf]', + }) + class OneTimeIf { + @Input() oneTimeIf: any; + constructor(private view: ViewContainerRef, private template: TemplateRef) {} + ngDoCheck(): void { + if (this.oneTimeIf) { + this.view.createEmbeddedView(this.template); + } + } + // NORMATIVE + static ngDirectiveDef = $r3$.ɵdefineDirective({ + type: OneTimeIf, + factory: () => new OneTimeIf($r3$.ɵinjectViewContainerRef(), $r3$.ɵinjectTemplateRef()), + inputs: {oneTimeIf: 'oneTimeIf'} + }); + // /NORMATIVE + } + + // Important: keep arrays outside of function to not create new instances. + // NORMATIVE + const $c1_dirs$ = [OneTimeIf]; + // /NORMATIVE + + @Component({ + template: `{{name | myPurePipe:size}}{{name | myPurePipe:size}} +
{{name | myPurePipe:size}}
` + }) + class MyApp { + name = '1World'; + size = 1; + more = true; + + // NORMATIVE + static ngComponentDef = $r3$.ɵdefineComponent({ + type: MyApp, + tag: 'my-app', + factory: function MyApp_Factory() { return new MyApp(); }, + template: function MyApp_Template(ctx: $MyApp$, cm: $boolean$) { + let $pi$: $MyPurePipe$; + if (cm) { + $r3$.ɵT(0); + $pi$ = $r3$.ɵPp(1, $MyPurePipe_ngPipeDef$); + $r3$.ɵT(2); + $r3$.ɵPp(3, $MyPurePipe_ngPipeDef$, $pi$); + $r3$.ɵC(4, $c1_dirs$, C4); + } + $r3$.ɵt(0, $r3$.ɵi1('', $r3$.ɵpb2(1, ctx.name, ctx.size), '')); + $r3$.ɵt(2, $r3$.ɵi1('', $r3$.ɵpb2(3, ctx.name, ctx.size), '')); + $r3$.ɵp(4, 'oneTimeIf', $r3$.ɵb(ctx.more)); + $r3$.ɵcR(4); + $r3$.ɵr(5, 4); + $r3$.ɵcr(); + + function C4(ctx1: $any$, cm: $boolean$) { + if (cm) { + $r3$.ɵE(0, 'div'); + $r3$.ɵT(1); + $r3$.ɵPp(2, $MyPurePipe_ngPipeDef$, $pi$); + $r3$.ɵe(); + } + $r3$.ɵt(1, $r3$.ɵi1('', $r3$.ɵpb2(2, ctx.name, ctx.size), '')); + } + } + }); + // /NORMATIVE + } + + let myApp: MyApp = renderComponent(MyApp); + expect(toHtml(containerEl)).toEqual('WorldWorld
World
'); + expect(myPurePipeTransformCalls).toEqual(3); + expect(myPipeTransformCalls).toEqual(0); + }); }); diff --git a/packages/core/test/render3/imported_renderer2.ts b/packages/core/test/render3/imported_renderer2.ts index 984e4398a9..30d25b5789 100644 --- a/packages/core/test/render3/imported_renderer2.ts +++ b/packages/core/test/render3/imported_renderer2.ts @@ -11,6 +11,7 @@ import {MockAnimationDriver} from '@angular/animations/browser/testing'; import {NgZone, RendererFactory2} from '@angular/core'; import {EventManager, ɵDomRendererFactory2, ɵDomSharedStylesHost} from '@angular/platform-browser'; import {ɵAnimationRendererFactory} from '@angular/platform-browser/animations'; +import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {EventManagerPlugin} from '@angular/platform-browser/src/dom/events/event_manager'; import {NoopNgZone} from '../../src/zone/ng_zone'; @@ -44,3 +45,58 @@ export function getAnimationRendererFactory2(document: any): RendererFactory2 { new ɵAnimationEngine(new MockAnimationDriver(), new ɵNoopAnimationStyleNormalizer()), fakeNgZone); } + +// TODO: code duplicated from ../linker/change_detection_integration_spec.ts, to be removed +// START duplicated code +export class RenderLog { + log: string[] = []; + loggedValues: any[] = []; + + setElementProperty(el: any, propName: string, propValue: any) { + this.log.push(`${propName}=${propValue}`); + this.loggedValues.push(propValue); + } + + setText(node: any, value: string) { + this.log.push(`{{${value}}}`); + this.loggedValues.push(value); + } + + clear() { + this.log = []; + this.loggedValues = []; + } +} + +/** + * This function patches the DomRendererFactory2 so that it returns a DefaultDomRenderer2 + * which logs some of the DOM operations through a RenderLog instance. + */ +export function patchLoggingRenderer2(rendererFactory: RendererFactory2, log: RenderLog) { + if ((rendererFactory).__patchedForLogging) { + return; + } + (rendererFactory).__patchedForLogging = true; + const origCreateRenderer = rendererFactory.createRenderer; + rendererFactory.createRenderer = function() { + const renderer = origCreateRenderer.apply(this, arguments); + if ((renderer).__patchedForLogging) { + return renderer; + } + (renderer).__patchedForLogging = true; + const origSetProperty = renderer.setProperty; + const origSetValue = renderer.setValue; + renderer.setProperty = function(el: any, name: string, value: any): void { + log.setElementProperty(el, name, value); + origSetProperty.call(renderer, el, name, value); + }; + renderer.setValue = function(node: any, value: string): void { + if (getDOM().isTextNode(node)) { + log.setText(node, value); + } + origSetValue.call(renderer, node, value); + }; + return renderer; + }; +} +// END duplicated code diff --git a/packages/core/test/render3/pipe_spec.ts b/packages/core/test/render3/pipe_spec.ts new file mode 100644 index 0000000000..330386f87d --- /dev/null +++ b/packages/core/test/render3/pipe_spec.ts @@ -0,0 +1,401 @@ +/** + * @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 {Directive, OnChanges, OnDestroy, Pipe, PipeTransform, SimpleChange, SimpleChanges, WrappedValue} from '@angular/core'; +import {expect} from '@angular/platform-browser/testing/src/matchers'; + +import {NgOnChangesFeature, defineComponent, defineDirective, definePipe} from '../../src/render3/definition'; +import {bind, container, containerRefreshEnd, containerRefreshStart, directiveRefresh, elementEnd, elementProperty, elementStart, embeddedViewEnd, embeddedViewStart, interpolation1, load, text, textBinding} from '../../src/render3/instructions'; +import {pipe, pipeBind1, pipeBind3, pipeBind4, pipeBindV} from '../../src/render3/pipe'; + +import {RenderLog, getRendererFactory2, patchLoggingRenderer2} from './imported_renderer2'; +import {renderComponent, renderToHtml} from './render_util'; + + +let log: string[] = []; +let person: Person; +let renderLog: RenderLog = new RenderLog(); +const rendererFactory2 = getRendererFactory2(document); +patchLoggingRenderer2(rendererFactory2, renderLog); + +describe('pipe', () => { + beforeEach(() => { + log = []; + renderLog.clear(); + person = new Person(); + }); + + it('should support interpolation', () => { + function Template(person: Person, cm: boolean) { + if (cm) { + text(0); + pipe(1, CountingPipe.ngPipeDef); + } + textBinding(0, interpolation1('', pipeBind1(1, person.name), '')); + } + person.init('bob', null); + expect(renderToHtml(Template, person)).toEqual('bob state:0'); + }); + + it('should support bindings', () => { + let directive: any = null; + + @Directive({selector: '[my-dir]', inputs: ['dirProp: elprop'], exportAs: 'mydir'}) + class MyDir { + dirProp: string; + + constructor() { this.dirProp = ''; } + + static ngDirectiveDef = + defineDirective({type: MyDir, factory: () => new MyDir(), inputs: {dirProp: 'elprop'}}); + } + + @Pipe({name: 'double'}) + class DoublePipe implements PipeTransform { + transform(value: any) { return `${value}${value}`; } + + static ngPipeDef = definePipe({ + type: DoublePipe, + factory: function DoublePipe_Factory() { return new DoublePipe(); }, + }); + } + + function Template(ctx: string, cm: boolean) { + if (cm) { + elementStart(0, 'div', null, [MyDir]); + pipe(2, DoublePipe.ngPipeDef); + elementEnd(); + } + MyDir.ngDirectiveDef.h(1, 0); + elementProperty(0, 'elprop', bind(pipeBind1(2, ctx))); + directiveRefresh(1, 0); + directive = load(1); + } + renderToHtml(Template, 'a'); + expect(directive !.dirProp).toEqual('aa'); + }); + + it('should support arguments in pipes', () => { + function Template(person: Person, cm: boolean) { + if (cm) { + text(0); + pipe(1, MultiArgPipe.ngPipeDef); + } + textBinding( + 0, interpolation1('', pipeBind3(1, person.name, 'one', person.address !.city), '')); + } + person.init('value', new Address('two')); + expect(renderToHtml(Template, person)).toEqual('value one two default'); + }); + + it('should support calling pipes with different number of arguments', () => { + function Template(person: Person, cm: boolean) { + if (cm) { + text(0); + pipe(1, MultiArgPipe.ngPipeDef); + pipe(2, MultiArgPipe.ngPipeDef); + } + textBinding( + 0, interpolation1('', pipeBind4(2, pipeBindV(1, [person.name, 'a', 'b']), 0, 1, 2), '')); + } + person.init('value', null); + expect(renderToHtml(Template, person)).toEqual('value a b default 0 1 2'); + }); + + it('should do nothing when no change', () => { + @Pipe({name: 'identityPipe'}) + class IdentityPipe implements PipeTransform { + transform(value: any) { return value; } + + static ngPipeDef = definePipe({ + type: IdentityPipe, + factory: function IdentityPipe_Factory() { return new IdentityPipe(); }, + }); + } + + function Template(person: Person, cm: boolean) { + if (cm) { + elementStart(0, 'div'); + pipe(1, IdentityPipe.ngPipeDef); + elementEnd(); + } + elementProperty(0, 'someProp', bind(pipeBind1(1, 'Megatron'))); + } + renderToHtml(Template, person, rendererFactory2); + expect(renderLog.log).toEqual(['someProp=Megatron']); + + renderLog.clear(); + renderToHtml(Template, person, rendererFactory2); + expect(renderLog.log).toEqual([]); + }); + + describe('pure', () => { + it('should call pure pipes only if the arguments change', () => { + function Template(person: Person, cm: boolean) { + if (cm) { + text(0); + pipe(1, CountingPipe.ngPipeDef); + } + textBinding(0, interpolation1('', pipeBind1(1, person.name), '')); + } + + // change from undefined -> null + person.name = null; + expect(renderToHtml(Template, person)).toEqual('null state:0'); + expect(renderToHtml(Template, person)).toEqual('null state:0'); + + // change from null -> some value + person.name = 'bob'; + expect(renderToHtml(Template, person)).toEqual('bob state:1'); + expect(renderToHtml(Template, person)).toEqual('bob state:1'); + + // change from some value -> some other value + person.name = 'bart'; + expect(renderToHtml(Template, person)).toEqual('bart state:2'); + expect(renderToHtml(Template, person)).toEqual('bart state:2'); + }); + + it('should cache pure pipes', () => { + function Template(ctx: any, cm: boolean) { + let pipeInstance; + if (cm) { + elementStart(0, 'div'); + pipeInstance = pipe(1, CountingPipe.ngPipeDef); + elementEnd(); + elementStart(2, 'div'); + pipe(3, CountingPipe.ngPipeDef, pipeInstance); + elementEnd(); + container(4); + } + elementProperty(0, 'someProp', bind(pipeBind1(1, true))); + elementProperty(2, 'someProp', bind(pipeBind1(3, true))); + pipeInstances.push(load(1), load(3)); + containerRefreshStart(4); + { + for (let i of [1, 2]) { + let cm1 = embeddedViewStart(1); + { + if (cm1) { + elementStart(0, 'div'); + pipe(1, CountingPipe.ngPipeDef, pipeInstance); + elementEnd(); + } + elementProperty(0, 'someProp', bind(pipeBind1(1, true))); + pipeInstances.push(load(1)); + } + embeddedViewEnd(); + } + } + containerRefreshEnd(); + } + const pipeInstances: CountingPipe[] = []; + renderToHtml(Template, {}, rendererFactory2); + expect(pipeInstances.length).toEqual(4); + expect(pipeInstances[0]).toBeAnInstanceOf(CountingPipe); + expect(pipeInstances[1]).toBe(pipeInstances[0]); + expect(pipeInstances[2]).toBe(pipeInstances[0]); + expect(pipeInstances[3]).toBe(pipeInstances[0]); + }); + }); + + describe('impure', () => { + it('should call impure pipes on each change detection run', () => { + function Template(person: Person, cm: boolean) { + if (cm) { + text(0); + pipe(1, CountingImpurePipe.ngPipeDef); + } + textBinding(0, interpolation1('', pipeBind1(1, person.name), '')); + } + + person.name = 'bob'; + expect(renderToHtml(Template, person)).toEqual('bob state:0'); + expect(renderToHtml(Template, person)).toEqual('bob state:1'); + }); + + it('should not cache impure pipes', () => { + function Template(ctx: any, cm: boolean) { + if (cm) { + elementStart(0, 'div'); + pipe(1, CountingImpurePipe.ngPipeDef); + elementEnd(); + elementStart(2, 'div'); + pipe(3, CountingImpurePipe.ngPipeDef); + elementEnd(); + container(4); + } + elementProperty(0, 'someProp', bind(pipeBind1(1, true))); + elementProperty(2, 'someProp', bind(pipeBind1(3, true))); + pipeInstances.push(load(1), load(3)); + containerRefreshStart(4); + { + for (let i of [1, 2]) { + let cm1 = embeddedViewStart(1); + { + if (cm1) { + elementStart(0, 'div'); + pipe(1, CountingImpurePipe.ngPipeDef); + elementEnd(); + } + elementProperty(0, 'someProp', bind(pipeBind1(1, true))); + pipeInstances.push(load(1)); + } + embeddedViewEnd(); + } + } + containerRefreshEnd(); + } + const pipeInstances: CountingImpurePipe[] = []; + renderToHtml(Template, {}, rendererFactory2); + expect(pipeInstances.length).toEqual(4); + expect(pipeInstances[0]).toBeAnInstanceOf(CountingImpurePipe); + expect(pipeInstances[1]).toBeAnInstanceOf(CountingImpurePipe); + expect(pipeInstances[1]).not.toBe(pipeInstances[0]); + expect(pipeInstances[2]).toBeAnInstanceOf(CountingImpurePipe); + expect(pipeInstances[2]).not.toBe(pipeInstances[0]); + expect(pipeInstances[3]).toBeAnInstanceOf(CountingImpurePipe); + expect(pipeInstances[3]).not.toBe(pipeInstances[0]); + }); + }); + + describe('lifecycles', () => { + @Pipe({name: 'pipeWithOnDestroy'}) + class PipeWithOnDestroy implements PipeTransform, OnDestroy { + ngOnDestroy() { log.push('pipeWithOnDestroy - ngOnDestroy'); } + + transform(value: any): any { return null; } + + static ngPipeDef = definePipe({ + type: PipeWithOnDestroy, + factory: function PipeWithOnDestroy_Factory() { return new PipeWithOnDestroy(); }, + }); + } + + it('should call ngOnDestroy on pipes', () => { + function Template(person: Person, cm: boolean) { + if (cm) { + container(0); + } + containerRefreshStart(0); + { + if (person.age > 20) { + let cm1 = embeddedViewStart(1); + { + if (cm1) { + text(0); + pipe(1, PipeWithOnDestroy.ngPipeDef); + } + textBinding(0, interpolation1('', pipeBind1(1, person.age), '')); + } + embeddedViewEnd(); + } + } + containerRefreshEnd(); + } + person.age = 25; + renderToHtml(Template, person); + + person.age = 15; + renderToHtml(Template, person); + expect(log).toEqual(['pipeWithOnDestroy - ngOnDestroy']); + + log = []; + person.age = 30; + renderToHtml(Template, person); + expect(log).toEqual([]); + + log = []; + person.age = 10; + renderToHtml(Template, person); + expect(log).toEqual(['pipeWithOnDestroy - ngOnDestroy']); + }); + }); + +}); + +@Pipe({name: 'countingPipe'}) +class CountingPipe implements PipeTransform { + state: number = 0; + + transform(value: any) { return `${value} state:${this.state++}`; } + + static ngPipeDef = definePipe({ + type: CountingPipe, + factory: function CountingPipe_Factory() { return new CountingPipe(); }, + }); +} + +@Pipe({name: 'countingImpurePipe', pure: false}) +class CountingImpurePipe implements PipeTransform { + state: number = 0; + + transform(value: any) { return `${value} state:${this.state++}`; } + + static ngPipeDef = definePipe({ + type: CountingImpurePipe, + factory: function CountingImpurePipe_Factory() { return new CountingImpurePipe(); }, + pure: false, + }); +} + +@Pipe({name: 'multiArgPipe'}) +class MultiArgPipe implements PipeTransform { + transform(value: any, arg1: any, arg2: any, arg3 = 'default') { + return `${value} ${arg1} ${arg2} ${arg3}`; + } + + static ngPipeDef = definePipe({ + type: MultiArgPipe, + factory: function MultiArgPipe_Factory() { return new MultiArgPipe(); }, + }); +} + +class Person { + age: number; + name: string|null; + address: Address|null = null; + phones: number[]; + + init(name: string|null, address: Address|null = null) { + this.name = name; + this.address = address; + } + + sayHi(m: any): string { return `Hi, ${m}`; } + + passThrough(val: any): any { return val; } + + toString(): string { + const address = this.address == null ? '' : ' address=' + this.address.toString(); + + return 'name=' + this.name + address; + } +} + +class Address { + cityGetterCalls: number = 0; + zipCodeGetterCalls: number = 0; + + constructor(public _city: string, public _zipcode: any = null) {} + + get city() { + this.cityGetterCalls++; + return this._city; + } + + get zipcode() { + this.zipCodeGetterCalls++; + return this._zipcode; + } + + set city(v) { this._city = v; } + + set zipcode(v) { this._zipcode = v; } + + toString(): string { return this.city || '-'; } +}