feat(core): speed up view creation via code gen for view factories.

BREAKING CHANGE:
- Platform pipes can only contain types and arrays of types,
  but no bindings any more.
- When using transformers, platform pipes need to be specified explicitly
  in the pubspec.yaml via the new config option
  `platform_pipes`.
- `Compiler.compileInHost` now returns a `HostViewFactoryRef`
- Component view is not yet created when component constructor is called.
  -> use `onInit` lifecycle callback to access the view of a component
- `ViewRef#setLocal` has been moved to new type `EmbeddedViewRef`
- `internalView` is gone, use `EmbeddedViewRef.rootNodes` to access
  the root nodes of an embedded view
- `renderer.setElementProperty`, `..setElementStyle`, `..setElementAttribute` now
  take a native element instead of an ElementRef
- `Renderer` interface now operates on plain native nodes,
  instead of `RenderElementRef`s or `RenderViewRef`s

Closes #5993
This commit is contained in:
Tobias Bosch
2015-12-02 10:35:51 -08:00
parent a08f50badd
commit 7ae23adaff
191 changed files with 6476 additions and 10232 deletions
@@ -47,7 +47,6 @@ export function main() {
var directive: TestDirective;
var locals: Locals;
var pipes: Pipes;
var eventLocals: Locals;
beforeEach(inject([TemplateParser], (_templateParser) => {
parser = _templateParser;
@@ -55,7 +54,6 @@ export function main() {
directive = new TestDirective();
dispatcher = new TestDispatcher([directive], []);
locals = new Locals(null, MapWrapper.createFromStringMap({'someVar': null}));
eventLocals = new Locals(null, MapWrapper.createFromStringMap({'$event': null}));
pipes = new TestPipes();
}));
@@ -65,9 +63,9 @@ export function main() {
createChangeDetectorDefinitions(new CompileTypeMetadata({name: 'SomeComp'}),
ChangeDetectionStrategy.Default,
new ChangeDetectorGenConfig(true, false, false),
parser.parse(template, directives, 'TestComp'))
parser.parse(template, directives, [], 'TestComp'))
.map(definition => new DynamicProtoChangeDetector(definition));
var changeDetector = protoChangeDetectors[protoViewIndex].instantiate(dispatcher);
var changeDetector = protoChangeDetectors[protoViewIndex].instantiate();
changeDetector.hydrate(context, locals, dispatcher, pipes);
return changeDetector;
}
@@ -91,8 +89,7 @@ export function main() {
it('should handle events on regular elements', () => {
var changeDetector = createChangeDetector('<div on-click="onEvent($event)">', [], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('click', 0, eventLocals);
changeDetector.handleEvent('click', 0, 'click');
expect(context.eventLog).toEqual(['click']);
});
@@ -105,16 +102,14 @@ export function main() {
var changeDetector =
createChangeDetector('<template on-click="onEvent($event)">', [dirMeta], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('click', 0, eventLocals);
changeDetector.handleEvent('click', 0, 'click');
expect(context.eventLog).toEqual(['click']);
});
it('should handle events with targets', () => {
var changeDetector = createChangeDetector('<div (window:click)="onEvent($event)">', [], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('window:click', 0, eventLocals);
changeDetector.handleEvent('window:click', 0, 'click');
expect(context.eventLog).toEqual(['click']);
});
@@ -177,8 +172,7 @@ export function main() {
var changeDetector = createChangeDetector('<div>', [dirMeta], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('click', 0, eventLocals);
changeDetector.handleEvent('click', 0, 'click');
expect(directive.eventLog).toEqual(['click']);
});
@@ -56,10 +56,18 @@ var THIS_MODULE_REF = moduleRef(THIS_MODULE_URL);
export function main() {
describe('ChangeDetectorCompiler', () => {
beforeEachProviders(() => TEST_PROVIDERS);
beforeEachProviders(() => [
TEST_PROVIDERS,
provide(ChangeDetectorGenConfig,
{useValue: new ChangeDetectorGenConfig(true, false, false)})
]);
var parser: TemplateParser;
var compiler: ChangeDetectionCompiler;
beforeEachProviders(() => [
provide(ChangeDetectorGenConfig,
{useValue: new ChangeDetectorGenConfig(true, false, false)})
]);
beforeEach(inject([TemplateParser, ChangeDetectionCompiler], (_parser, _compiler) => {
parser = _parser;
@@ -71,35 +79,16 @@ export function main() {
directives: CompileDirectiveMetadata[] = CONST_EXPR([])): string[] {
var type =
new CompileTypeMetadata({name: stringify(SomeComponent), moduleUrl: THIS_MODULE_URL});
var parsedTemplate = parser.parse(template, directives, 'TestComp');
var parsedTemplate = parser.parse(template, directives, [], 'TestComp');
var factories =
compiler.compileComponentRuntime(type, ChangeDetectionStrategy.Default, parsedTemplate);
return testChangeDetector(factories[0]);
}
describe('no jit', () => {
beforeEachProviders(() => [
provide(ChangeDetectorGenConfig,
{useValue: new ChangeDetectorGenConfig(true, false, false)})
]);
it('should watch element properties', () => {
expect(detectChanges(compiler, '<div [elProp]="someProp">'))
.toEqual(['elementProperty(elProp)=someValue']);
});
it('should watch element properties', () => {
expect(detectChanges(compiler, '<div [elProp]="someProp">'))
.toEqual(['elementProperty(elProp)=someValue']);
});
describe('jit', () => {
beforeEachProviders(() => [
provide(ChangeDetectorGenConfig,
{useValue: new ChangeDetectorGenConfig(true, false, true)})
]);
it('should watch element properties', () => {
expect(detectChanges(compiler, '<div [elProp]="someProp">'))
.toEqual(['elementProperty(elProp)=someValue']);
});
});
});
describe('compileComponentCodeGen', () => {
@@ -108,7 +97,7 @@ export function main() {
directives: CompileDirectiveMetadata[] = CONST_EXPR([])): Promise<string[]> {
var type =
new CompileTypeMetadata({name: stringify(SomeComponent), moduleUrl: THIS_MODULE_URL});
var parsedTemplate = parser.parse(template, directives, 'TestComp');
var parsedTemplate = parser.parse(template, directives, [], 'TestComp');
var sourceExpressions =
compiler.compileComponentCodeGen(type, ChangeDetectionStrategy.Default, parsedTemplate);
var testableModule = createTestableModule(sourceExpressions, 0).getSourceWithImports();
@@ -140,7 +129,7 @@ function createTestableModule(source: SourceExpressions,
export function testChangeDetector(changeDetectorFactory: Function): string[] {
var dispatcher = new TestDispatcher([], []);
var cd = changeDetectorFactory(dispatcher);
var cd = changeDetectorFactory();
var ctx = new SomeComponent();
ctx.someProp = 'someValue';
var locals = new Locals(null, MapWrapper.createFromStringMap({'someVar': null}));
@@ -1,7 +1,8 @@
import {isBlank} from 'angular2/src/facade/lang';
import {Pipes} from 'angular2/src/core/change_detection/pipes';
import {EventEmitter} from 'angular2/src/facade/async';
import {
ProtoChangeDetector,
ChangeDetector,
ChangeDispatcher,
DirectiveIndex,
BindingTarget
@@ -10,6 +11,7 @@ import {
export class TestDirective {
eventLog: string[] = [];
dirProp: string;
click: EventEmitter<any> = new EventEmitter<any>();
onEvent(value: string) { this.eventLog.push(value); }
}
@@ -17,7 +19,7 @@ export class TestDirective {
export class TestDispatcher implements ChangeDispatcher {
log: string[];
constructor(public directives: any[], public detectors: ProtoChangeDetector[]) { this.clear(); }
constructor(public directives: any[], public detectors: ChangeDetector[]) { this.clear(); }
getDirectiveFor(di: DirectiveIndex) { return this.directives[di.directiveIndex]; }
@@ -34,7 +36,9 @@ export class TestDispatcher implements ChangeDispatcher {
notifyAfterContentChecked() {}
notifyAfterViewChecked() {}
getDebugContext(a, b) { return null; }
notifyOnDestroy() {}
getDebugContext(a, b, c) { return null; }
_asString(value) { return (isBlank(value) ? 'null' : value.toString()); }
}
@@ -1,597 +0,0 @@
import {
ddescribe,
describe,
xdescribe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
AsyncTestCompleter,
inject,
beforeEachProviders
} from 'angular2/testing_internal';
import {
CONST_EXPR,
stringify,
isType,
Type,
isBlank,
serializeEnum,
IS_DART
} from 'angular2/src/facade/lang';
import {MapWrapper} from 'angular2/src/facade/collection';
import {PromiseWrapper, Promise} from 'angular2/src/facade/async';
import {TemplateParser} from 'angular2/src/compiler/template_parser';
import {
CommandVisitor,
TextCmd,
NgContentCmd,
BeginElementCmd,
BeginComponentCmd,
EmbeddedTemplateCmd,
TemplateCmd,
visitAllCommands,
CompiledComponentTemplate
} from 'angular2/src/core/linker/template_commands';
import {CommandCompiler} from 'angular2/src/compiler/command_compiler';
import {
CompileDirectiveMetadata,
CompileTypeMetadata,
CompileTemplateMetadata
} from 'angular2/src/compiler/directive_metadata';
import {SourceModule, SourceExpression, moduleRef} from 'angular2/src/compiler/source_module';
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
import {evalModule} from './eval_module';
import {
escapeSingleQuoteString,
codeGenValueFn,
codeGenExportVariable,
codeGenConstConstructorCall,
MODULE_SUFFIX
} from 'angular2/src/compiler/util';
import {TEST_PROVIDERS} from './test_bindings';
const BEGIN_ELEMENT = 'BEGIN_ELEMENT';
const END_ELEMENT = 'END_ELEMENT';
const BEGIN_COMPONENT = 'BEGIN_COMPONENT';
const END_COMPONENT = 'END_COMPONENT';
const TEXT = 'TEXT';
const NG_CONTENT = 'NG_CONTENT';
const EMBEDDED_TEMPLATE = 'EMBEDDED_TEMPLATE';
// Attention: These module names have to correspond to real modules!
var THIS_MODULE_URL = `package:angular2/test/compiler/command_compiler_spec${MODULE_SUFFIX}`;
var THIS_MODULE_REF = moduleRef(THIS_MODULE_URL);
var TEMPLATE_COMMANDS_MODULE_REF =
moduleRef(`package:angular2/src/core/linker/template_commands${MODULE_SUFFIX}`);
// Attention: read by eval!
export class RootComp {}
export class SomeDir {}
export class AComp {}
var RootCompTypeMeta =
new CompileTypeMetadata({name: 'RootComp', runtime: RootComp, moduleUrl: THIS_MODULE_URL});
var SomeDirTypeMeta =
new CompileTypeMetadata({name: 'SomeDir', runtime: SomeDir, moduleUrl: THIS_MODULE_URL});
var ACompTypeMeta =
new CompileTypeMetadata({name: 'AComp', runtime: AComp, moduleUrl: THIS_MODULE_URL});
var compTypeTemplateId: Map<CompileTypeMetadata, string> = MapWrapper.createFromPairs(
[[RootCompTypeMeta, 'rootCompId'], [SomeDirTypeMeta, 'someDirId'], [ACompTypeMeta, 'aCompId']]);
export function main() {
describe('CommandCompiler', () => {
beforeEachProviders(() => TEST_PROVIDERS);
var parser: TemplateParser;
var commandCompiler: CommandCompiler;
var componentTemplateFactory: Function;
beforeEach(inject([TemplateParser, CommandCompiler], (_templateParser, _commandCompiler) => {
parser = _templateParser;
commandCompiler = _commandCompiler;
}));
function createComp({type, selector, template, encapsulation, ngContentSelectors}: {
type?: CompileTypeMetadata,
selector?: string,
template?: string,
encapsulation?: ViewEncapsulation,
ngContentSelectors?: string[]
}): CompileDirectiveMetadata {
if (isBlank(encapsulation)) {
encapsulation = ViewEncapsulation.None;
}
if (isBlank(selector)) {
selector = 'root';
}
if (isBlank(ngContentSelectors)) {
ngContentSelectors = [];
}
if (isBlank(template)) {
template = '';
}
return CompileDirectiveMetadata.create({
selector: selector,
isComponent: true,
type: type,
template: new CompileTemplateMetadata({
template: template,
ngContentSelectors: ngContentSelectors,
encapsulation: encapsulation
})
});
}
function createDirective(type: CompileTypeMetadata, selector: string,
exportAs: string = null): CompileDirectiveMetadata {
return CompileDirectiveMetadata.create(
{selector: selector, exportAs: exportAs, isComponent: false, type: type});
}
function createTests(run: Function) {
describe('text', () => {
it('should create unbound text commands', inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({type: RootCompTypeMeta, template: 'a'});
run(rootComp, [])
.then((data) => {
expect(data).toEqual([[TEXT, 'a', false, null]]);
async.done();
});
}));
it('should create bound text commands', inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({type: RootCompTypeMeta, template: '{{a}}'});
run(rootComp, [])
.then((data) => {
expect(data).toEqual([[TEXT, null, true, null]]);
async.done();
});
}));
});
describe('elements', () => {
it('should create unbound element commands', inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({type: RootCompTypeMeta, template: '<div a="b">'});
run(rootComp, [])
.then((data) => {
expect(data).toEqual([
[BEGIN_ELEMENT, 'div', ['a', 'b'], [], [], [], false, null],
[END_ELEMENT]
]);
async.done();
});
}));
it('should create bound element commands', inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({
type: RootCompTypeMeta,
template: '<div a="b" #someVar (click)="someHandler" (window:scroll)="scrollTo()">'
});
run(rootComp, [])
.then((data) => {
expect(data).toEqual([
[
BEGIN_ELEMENT,
'div',
['a', 'b'],
[null, 'click', 'window', 'scroll'],
['someVar', null],
[],
true,
null
],
[END_ELEMENT]
]);
async.done();
});
}));
it('should create element commands with directives',
inject([AsyncTestCompleter], (async) => {
var rootComp =
createComp({type: RootCompTypeMeta, template: '<div a #someVar="someExport">'});
var dir = CompileDirectiveMetadata.create({
selector: '[a]',
exportAs: 'someExport',
isComponent: false,
type: SomeDirTypeMeta,
host: {'(click)': 'doIt()', '(window:scroll)': 'doIt()', 'role': 'button'}
});
run(rootComp, [dir])
.then((data) => {
expect(data).toEqual([
[
BEGIN_ELEMENT,
'div',
['a', '', 'role', 'button'],
[null, 'click', 'window', 'scroll'],
['someVar', 0],
['SomeDirType'],
true,
null
],
[END_ELEMENT]
]);
async.done();
});
}));
it('should merge element attributes with host attributes',
inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({
type: RootCompTypeMeta,
template: '<div class="origclass" style="color: red;" role="origrole" attr1>'
});
var dir = CompileDirectiveMetadata.create({
selector: 'div',
isComponent: false,
type: SomeDirTypeMeta,
host: {'class': 'newclass', 'style': 'newstyle', 'role': 'newrole', 'attr2': ''}
});
run(rootComp, [dir])
.then((data) => {
expect(data).toEqual([
[
BEGIN_ELEMENT,
'div',
[
'attr1',
'',
'attr2',
'',
'class',
'origclass newclass',
'role',
'newrole',
'style',
'color: red; newstyle'
],
[],
[],
['SomeDirType'],
true,
null
],
[END_ELEMENT]
]);
async.done();
});
}));
it('should create nested nodes', inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({type: RootCompTypeMeta, template: '<div>a</div>'});
run(rootComp, [])
.then((data) => {
expect(data).toEqual([
[BEGIN_ELEMENT, 'div', [], [], [], [], false, null],
[TEXT, 'a', false, null],
[END_ELEMENT]
]);
async.done();
});
}));
});
describe('components', () => {
it('should create component commands', inject([AsyncTestCompleter], (async) => {
var rootComp = createComp(
{type: RootCompTypeMeta, template: '<a a="b" #someVar (click)="someHandler">'});
var comp = createComp({type: ACompTypeMeta, selector: 'a'});
run(rootComp, [comp])
.then((data) => {
expect(data).toEqual([
[
BEGIN_COMPONENT,
'a',
['a', 'b'],
[null, 'click'],
['someVar', 0],
['ACompType'],
serializeEnum(ViewEncapsulation.None),
null,
'aCompId'
],
[END_COMPONENT]
]);
async.done();
});
}));
it('should store viewEncapsulation', inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({type: RootCompTypeMeta, template: '<a></a>'});
var comp = createComp(
{type: ACompTypeMeta, selector: 'a', encapsulation: ViewEncapsulation.Native});
run(rootComp, [comp])
.then((data) => {
expect(data).toEqual([
[
BEGIN_COMPONENT,
'a',
[],
[],
[],
['ACompType'],
serializeEnum(ViewEncapsulation.Native),
null,
'aCompId'
],
[END_COMPONENT]
]);
async.done();
});
}));
it('should create nested nodes and set ngContentIndex',
inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({type: RootCompTypeMeta, template: '<a>t</a>'});
var comp = createComp({type: ACompTypeMeta, selector: 'a', ngContentSelectors: ['*']});
run(rootComp, [comp])
.then((data) => {
expect(data).toEqual([
[
BEGIN_COMPONENT,
'a',
[],
[],
[],
['ACompType'],
serializeEnum(ViewEncapsulation.None),
null,
'aCompId'
],
[TEXT, 't', false, 0],
[END_COMPONENT]
]);
async.done();
});
}));
});
describe('embedded templates', () => {
it('should create embedded template commands', inject([AsyncTestCompleter], (async) => {
var rootComp =
createComp({type: RootCompTypeMeta, template: '<template a="b"></template>'});
var dir = createDirective(SomeDirTypeMeta, '[a]');
run(rootComp, [dir], 1)
.then((data) => {
expect(data).toEqual([
[EMBEDDED_TEMPLATE, ['a', 'b'], [], ['SomeDirType'], false, null, 'cd1', []]
]);
async.done();
});
}));
it('should keep variable name and value for <template> elements',
inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({
type: RootCompTypeMeta,
template: '<template #someVar="someValue" #someEmptyVar></template>'
});
var dir = createDirective(SomeDirTypeMeta, '[a]');
run(rootComp, [dir], 1)
.then((data) => {
expect(data[0][2])
.toEqual(['someVar', 'someValue', 'someEmptyVar', '$implicit']);
async.done();
});
}));
it('should keep variable name and value for template attributes',
inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({
type: RootCompTypeMeta,
template: '<div template="var someVar=someValue; var someEmptyVar"></div>'
});
var dir = createDirective(SomeDirTypeMeta, '[a]');
run(rootComp, [dir], 1)
.then((data) => {
expect(data[0][2])
.toEqual(['someVar', 'someValue', 'someEmptyVar', '$implicit']);
async.done();
});
}));
it('should created nested nodes', inject([AsyncTestCompleter], (async) => {
var rootComp =
createComp({type: RootCompTypeMeta, template: '<template>t</template>'});
run(rootComp, [], 1)
.then((data) => {
expect(data).toEqual([
[
EMBEDDED_TEMPLATE,
[],
[],
[],
false,
null,
'cd1',
[[TEXT, 't', false, null]]
]
]);
async.done();
});
}));
it('should calculate wether the template is merged based on nested ng-content elements',
inject([AsyncTestCompleter], (async) => {
var rootComp = createComp({
type: RootCompTypeMeta,
template: '<template><ng-content></ng-content></template>'
});
run(rootComp, [], 1)
.then((data) => {
expect(data).toEqual(
[[EMBEDDED_TEMPLATE, [], [], [], true, null, 'cd1', [[NG_CONTENT, null]]]]);
async.done();
});
}));
});
describe('ngContent', () => {
it('should create ng-content commands', inject([AsyncTestCompleter], (async) => {
var rootComp =
createComp({type: RootCompTypeMeta, template: '<ng-content></ng-content>'});
run(rootComp, [])
.then((data) => {
expect(data).toEqual([[NG_CONTENT, null]]);
async.done();
});
}));
});
}
describe('compileComponentRuntime', () => {
beforeEach(() => {
componentTemplateFactory = (directive: CompileDirectiveMetadata) => {
return () => new CompiledComponentTemplate(compTypeTemplateId.get(directive.type), null,
null, null);
};
});
function run(component: CompileDirectiveMetadata, directives: CompileDirectiveMetadata[],
embeddedTemplateCount: number = 0): Promise<any[][]> {
var changeDetectorFactories = [];
for (var i = 0; i < embeddedTemplateCount + 1; i++) {
(function(i) { changeDetectorFactories.push((_) => `cd${i}`); })(i);
}
var parsedTemplate =
parser.parse(component.template.template, directives, component.type.name);
var commands = commandCompiler.compileComponentRuntime(
component, parsedTemplate, changeDetectorFactories, componentTemplateFactory);
return PromiseWrapper.resolve(humanize(commands));
}
createTests(run);
});
describe('compileComponentCodeGen', () => {
beforeEach(() => {
componentTemplateFactory = (directive: CompileDirectiveMetadata) => {
return `${directive.type.name}TemplateGetter`;
};
});
function run(component: CompileDirectiveMetadata, directives: CompileDirectiveMetadata[],
embeddedTemplateCount: number = 0): Promise<any[][]> {
var testDeclarations = [];
var changeDetectorFactoryExpressions = [];
for (var i = 0; i < embeddedTemplateCount + 1; i++) {
var fnName = `cd${i}`;
testDeclarations.push(`${codeGenValueFn(['_'], ` 'cd${i}' `, fnName)};`);
changeDetectorFactoryExpressions.push(fnName);
}
for (var i = 0; i < directives.length; i++) {
var directive = directives[i];
if (directive.isComponent) {
var nestedTemplate =
`${codeGenConstConstructorCall(TEMPLATE_COMMANDS_MODULE_REF+'CompiledComponentTemplate')}('${compTypeTemplateId.get(directive.type)}', null, null, null)`;
var getterName = `${directive.type.name}TemplateGetter`;
testDeclarations.push(`${codeGenValueFn([], nestedTemplate, getterName)};`)
}
}
var parsedTemplate =
parser.parse(component.template.template, directives, component.type.name);
var sourceExpression = commandCompiler.compileComponentCodeGen(
component, parsedTemplate, changeDetectorFactoryExpressions, componentTemplateFactory);
testDeclarations.forEach(decl => sourceExpression.declarations.push(decl));
var testableModule = createTestableModule(sourceExpression).getSourceWithImports();
return evalModule(testableModule.source, testableModule.imports, null);
}
createTests(run);
});
});
}
// Attention: read by eval!
export function humanize(cmds: TemplateCmd[]): any[][] {
var visitor = new CommandHumanizer();
visitAllCommands(visitor, cmds);
return visitor.result;
}
function checkAndStringifyType(type: Type): string {
expect(isType(type)).toBe(true);
return `${stringify(type)}Type`;
}
class CommandHumanizer implements CommandVisitor {
result: any[][] = [];
visitText(cmd: TextCmd, context: any): any {
this.result.push([TEXT, cmd.value, cmd.isBound, cmd.ngContentIndex]);
return null;
}
visitNgContent(cmd: NgContentCmd, context: any): any {
this.result.push([NG_CONTENT, cmd.ngContentIndex]);
return null;
}
visitBeginElement(cmd: BeginElementCmd, context: any): any {
this.result.push([
BEGIN_ELEMENT,
cmd.name,
cmd.attrNameAndValues,
cmd.eventTargetAndNames,
cmd.variableNameAndValues,
cmd.directives.map(checkAndStringifyType),
cmd.isBound,
cmd.ngContentIndex
]);
return null;
}
visitEndElement(context: any): any {
this.result.push([END_ELEMENT]);
return null;
}
visitBeginComponent(cmd: BeginComponentCmd, context: any): any {
this.result.push([
BEGIN_COMPONENT,
cmd.name,
cmd.attrNameAndValues,
cmd.eventTargetAndNames,
cmd.variableNameAndValues,
cmd.directives.map(checkAndStringifyType),
serializeEnum(cmd.encapsulation),
cmd.ngContentIndex,
cmd.templateId
]);
return null;
}
visitEndComponent(context: any): any {
this.result.push([END_COMPONENT]);
return null;
}
visitEmbeddedTemplate(cmd: EmbeddedTemplateCmd, context: any): any {
this.result.push([
EMBEDDED_TEMPLATE,
cmd.attrNameAndValues,
cmd.variableNameAndValues,
cmd.directives.map(checkAndStringifyType),
cmd.isMerged,
cmd.ngContentIndex,
cmd.changeDetectorFactory(null),
humanize(cmd.children)
]);
return null;
}
}
function createTestableModule(source: SourceExpression): SourceModule {
var resultExpression = `${THIS_MODULE_REF}humanize(${source.expression})`;
var testableSource = `${source.declarations.join('\n')}
${codeGenValueFn(['_'], resultExpression, '_run')};
${codeGenExportVariable('run')}_run;
`;
return new SourceModule(null, testableSource);
}
@@ -15,73 +15,40 @@ import {
import {Component, View, provide} from 'angular2/core';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {SpyProtoViewFactory} from '../core/spies';
import {
CompiledHostTemplate,
CompiledComponentTemplate,
BeginComponentCmd
} from 'angular2/src/core/linker/template_commands';
import {RuntimeCompiler} from 'angular2/src/compiler/runtime_compiler';
import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory';
import {AppProtoView} from 'angular2/src/core/linker/view';
import {SpyTemplateCompiler} from './spies';
import {TemplateCompiler} from 'angular2/src/compiler/compiler';
import {RuntimeCompiler, RuntimeCompiler_} from 'angular2/src/compiler/runtime_compiler';
import {HostViewFactory} from 'angular2/src/core/linker/view';
export function main() {
describe('RuntimeCompiler', () => {
var compiler: RuntimeCompiler;
var compiler: RuntimeCompiler_;
var templateCompilerSpy;
var someHostViewFactory;
beforeEachProviders(() => {
templateCompilerSpy = new SpyTemplateCompiler();
someHostViewFactory = new HostViewFactory(null, null);
templateCompilerSpy.spy('compileHostComponentRuntime')
.andReturn(PromiseWrapper.resolve(someHostViewFactory));
return [provide(TemplateCompiler, {useValue: templateCompilerSpy})];
});
beforeEach(inject([RuntimeCompiler], (_compiler) => { compiler = _compiler; }));
describe('compileInHost', () => {
var protoViewFactorySpy;
var someProtoView;
beforeEachProviders(() => {
protoViewFactorySpy = new SpyProtoViewFactory();
someProtoView = new AppProtoView(null, null, null, null, null, null, null);
protoViewFactorySpy.spy('createHost').andReturn(someProtoView);
return [provide(ProtoViewFactory, {useValue: protoViewFactorySpy})];
});
it('should compile the template via TemplateCompiler',
inject([AsyncTestCompleter], (async) => {
var cht: CompiledHostTemplate;
protoViewFactorySpy.spy('createHost')
.andCallFake((_cht) => {
cht = _cht;
return someProtoView;
});
compiler.compileInHost(SomeComponent)
.then((_) => {
var beginComponentCmd = <BeginComponentCmd>cht.template.commands[0];
expect(beginComponentCmd.name).toEqual('some-comp');
async.done();
});
}));
});
it('should cache the result', inject([AsyncTestCompleter], (async) => {
PromiseWrapper
.all([compiler.compileInHost(SomeComponent), compiler.compileInHost(SomeComponent)])
.then((protoViewRefs) => {
expect(protoViewRefs[0]).toBe(protoViewRefs[1]);
it('compileInHost should compile the template via TemplateCompiler',
inject([AsyncTestCompleter], (async) => {
compiler.compileInHost(SomeComponent)
.then((hostViewFactoryRef) => {
expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
async.done();
});
}));
it('should clear the cache',
inject([AsyncTestCompleter], (async) => {compiler.compileInHost(SomeComponent)
.then((protoViewRef1) => {
compiler.clearCache();
compiler.compileInHost(SomeComponent)
.then((protoViewRef2) => {
expect(protoViewRef1)
.not.toBe(protoViewRef2);
async.done();
});
})}));
it('should clear the cache', () => {
compiler.clearCache();
expect(templateCompilerSpy.spy('clearCache')).toHaveBeenCalled();
});
});
}
@@ -46,7 +46,7 @@ export function main() {
describe('getMetadata', () => {
it('should read metadata',
inject([RuntimeMetadataResolver], (resolver: RuntimeMetadataResolver) => {
var meta = resolver.getMetadata(ComponentWithEverything);
var meta = resolver.getDirectiveMetadata(ComponentWithEverything);
expect(meta.selector).toEqual('someSelector');
expect(meta.exportAs).toEqual('someExportAs');
expect(meta.isComponent).toBe(true);
@@ -70,7 +70,8 @@ export function main() {
it('should use the moduleUrl from the reflector if none is given',
inject([RuntimeMetadataResolver], (resolver: RuntimeMetadataResolver) => {
var value: string = resolver.getMetadata(ComponentWithoutModuleId).type.moduleUrl;
var value: string =
resolver.getDirectiveMetadata(ComponentWithoutModuleId).type.moduleUrl;
var expectedEndValue =
IS_DART ? 'base/dist/dart/angular2/test/compiler/runtime_metadata_spec.dart' : './';
expect(value.endsWith(expectedEndValue)).toBe(true);
@@ -82,7 +83,7 @@ export function main() {
it('should return the directive metadatas',
inject([RuntimeMetadataResolver], (resolver: RuntimeMetadataResolver) => {
expect(resolver.getViewDirectivesMetadata(ComponentWithEverything))
.toEqual([resolver.getMetadata(SomeDirective)]);
.toEqual([resolver.getDirectiveMetadata(SomeDirective)]);
}));
describe("platform directives", () => {
@@ -91,7 +92,10 @@ export function main() {
it('should include platform directives when available',
inject([RuntimeMetadataResolver], (resolver: RuntimeMetadataResolver) => {
expect(resolver.getViewDirectivesMetadata(ComponentWithEverything))
.toEqual([resolver.getMetadata(ADirective), resolver.getMetadata(SomeDirective)]);
.toEqual([
resolver.getDirectiveMetadata(ADirective),
resolver.getDirectiveMetadata(SomeDirective)
]);
}));
});
});
+7 -1
View File
@@ -1,9 +1,15 @@
library core.spies;
library compiler.spies;
import 'package:angular2/src/compiler/xhr.dart';
import 'package:angular2/testing_internal.dart';
import 'package:angular2/src/compiler/template_compiler.dart';
@proxy
class SpyXHR extends SpyObject implements XHR {
noSuchMethod(m) => super.noSuchMethod(m);
}
@proxy
class SpyTemplateCompiler extends SpyObject implements TemplateCompiler {
noSuchMethod(m) => super.noSuchMethod(m);
}
+5
View File
@@ -1,7 +1,12 @@
import {XHR} from 'angular2/src/compiler/xhr';
import {TemplateCompiler} from 'angular2/src/compiler/template_compiler';
import {SpyObject, proxy} from 'angular2/testing_internal';
export class SpyXHR extends SpyObject {
constructor() { super(XHR); }
}
export class SpyTemplateCompiler extends SpyObject {
constructor() { super(TemplateCompiler); }
}
@@ -15,7 +15,12 @@ import {
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {Type, isPresent, isBlank, stringify, isString} from 'angular2/src/facade/lang';
import {MapWrapper, SetWrapper, ListWrapper} from 'angular2/src/facade/collection';
import {
MapWrapper,
SetWrapper,
ListWrapper,
StringMapWrapper
} from 'angular2/src/facade/collection';
import {RuntimeMetadataResolver} from 'angular2/src/compiler/runtime_metadata';
import {
TemplateCompiler,
@@ -26,31 +31,31 @@ import {evalModule} from './eval_module';
import {SourceModule, moduleRef} from 'angular2/src/compiler/source_module';
import {XHR} from 'angular2/src/compiler/xhr';
import {MockXHR} from 'angular2/src/compiler/xhr_mock';
import {SpyRootRenderer, SpyRenderer, SpyAppViewManager} from '../core/spies';
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
import {AppView, AppProtoView} from 'angular2/src/core/linker/view';
import {AppElement} from 'angular2/src/core/linker/element';
import {Locals, ChangeDetectorGenConfig} from 'angular2/src/core/change_detection/change_detection';
import {Locals} from 'angular2/src/core/change_detection/change_detection';
import {
CommandVisitor,
TextCmd,
NgContentCmd,
BeginElementCmd,
BeginComponentCmd,
EmbeddedTemplateCmd,
TemplateCmd,
visitAllCommands,
CompiledComponentTemplate
} from 'angular2/src/core/linker/template_commands';
import {Component, View, Directive, provide} from 'angular2/core';
import {Component, View, Directive, provide, RenderComponentType} from 'angular2/core';
import {TEST_PROVIDERS} from './test_bindings';
import {TestDispatcher, TestPipes} from './change_detector_mocks';
import {codeGenValueFn, codeGenExportVariable, MODULE_SUFFIX} from 'angular2/src/compiler/util';
import {
codeGenValueFn,
codeGenFnHeader,
codeGenExportVariable,
MODULE_SUFFIX
} from 'angular2/src/compiler/util';
import {PipeTransform, WrappedValue, Injectable, Pipe} from 'angular2/core';
// Attention: This path has to point to this test file!
const THIS_MODULE_ID = 'angular2/test/compiler/template_compiler_spec';
var THIS_MODULE_REF = moduleRef(`package:${THIS_MODULE_ID}${MODULE_SUFFIX}`);
var REFLECTOR_MODULE_REF =
moduleRef(`package:angular2/src/core/reflection/reflection${MODULE_SUFFIX}`);
var REFLECTION_CAPS_MODULE_REF =
moduleRef(`package:angular2/src/core/reflection/reflection_capabilities${MODULE_SUFFIX}`);
export function main() {
describe('TemplateCompiler', () => {
@@ -77,23 +82,24 @@ export function main() {
}));
it('should compile host components', inject([AsyncTestCompleter], (async) => {
compile([CompWithBindingsAndStyles])
.then((humanizedTemplate) => {
expect(humanizedTemplate['styles']).toEqual([]);
expect(humanizedTemplate['commands'][0]).toEqual('<comp-a>');
expect(humanizedTemplate['cd']).toEqual(['elementProperty(title)=someDirValue']);
compile([CompWithBindingsAndStylesAndPipes])
.then((humanizedView) => {
expect(humanizedView['styles']).toEqual([]);
expect(humanizedView['elements']).toEqual(['<comp-a>']);
expect(humanizedView['pipes']).toEqual({});
expect(humanizedView['cd']).toEqual(['prop(title)=someHostValue']);
async.done();
});
}));
it('should compile nested components', inject([AsyncTestCompleter], (async) => {
compile([CompWithBindingsAndStyles])
.then((humanizedTemplate) => {
var nestedTemplate = humanizedTemplate['commands'][1];
expect(nestedTemplate['styles']).toEqual(['div {color: red}']);
expect(nestedTemplate['commands'][0]).toEqual('<a>');
expect(nestedTemplate['cd']).toEqual(['elementProperty(href)=someCtxValue']);
compile([CompWithBindingsAndStylesAndPipes])
.then((humanizedView) => {
var componentView = humanizedView['componentViews'][0];
expect(componentView['styles']).toEqual(['div {color: red}']);
expect(componentView['elements']).toEqual(['<a>']);
expect(componentView['pipes']).toEqual({'uppercase': stringify(UpperCasePipe)});
expect(componentView['cd']).toEqual(['prop(href)=SOMECTXVALUE']);
async.done();
});
@@ -101,23 +107,24 @@ export function main() {
it('should compile recursive components', inject([AsyncTestCompleter], (async) => {
compile([TreeComp])
.then((humanizedTemplate) => {
expect(humanizedTemplate['commands'][0]).toEqual('<tree>');
expect(humanizedTemplate['commands'][1]['commands'][0]).toEqual('<tree>');
expect(humanizedTemplate['commands'][1]['commands'][1]['commands'][0])
.toEqual('<tree>');
.then((humanizedView) => {
expect(humanizedView['elements']).toEqual(['<tree>']);
expect(humanizedView['componentViews'][0]['embeddedViews'][0]['elements'])
.toEqual(['<tree>']);
expect(humanizedView['componentViews'][0]['embeddedViews'][0]['componentViews']
[0]['embeddedViews'][0]['elements'])
.toEqual(['<tree>']);
async.done();
});
}));
it('should pass the right change detector to embedded templates',
inject([AsyncTestCompleter], (async) => {
it('should compile embedded templates', inject([AsyncTestCompleter], (async) => {
compile([CompWithEmbeddedTemplate])
.then((humanizedTemplate) => {
expect(humanizedTemplate['commands'][1]['commands'][0]).toEqual('<template>');
expect(humanizedTemplate['commands'][1]['commands'][1]['cd'])
.toEqual(['elementProperty(href)=someCtxValue']);
.then((humanizedView) => {
var embeddedView = humanizedView['componentViews'][0]['embeddedViews'][0];
expect(embeddedView['elements']).toEqual(['<a>']);
expect(embeddedView['cd']).toEqual(['prop(href)=someEmbeddedValue']);
async.done();
});
@@ -125,8 +132,8 @@ export function main() {
it('should dedup directives', inject([AsyncTestCompleter], (async) => {
compile([CompWithDupDirectives, TreeComp])
.then((humanizedTemplate) => {
expect(humanizedTemplate['commands'][1]['commands'][0]).toEqual("<tree>");
.then((humanizedView) => {
expect(humanizedView['componentViews'][0]['componentViews'].length).toBe(1);
async.done();
});
@@ -136,18 +143,34 @@ export function main() {
describe('compileHostComponentRuntime', () => {
function compile(components: Type[]): Promise<any[]> {
return compiler.compileHostComponentRuntime(components[0])
.then((compiledHostTemplate) => humanizeTemplate(compiledHostTemplate.template));
.then((compiledHostTemplate) =>
humanizeViewFactory(compiledHostTemplate.viewFactory));
}
runTests(compile);
describe('no jit', () => {
beforeEachProviders(() => [
provide(ChangeDetectorGenConfig,
{useValue: new ChangeDetectorGenConfig(true, false, false)})
]);
runTests(compile);
});
describe('jit', () => {
beforeEachProviders(() => [
provide(ChangeDetectorGenConfig,
{useValue: new ChangeDetectorGenConfig(true, false, true)})
]);
runTests(compile);
});
it('should cache components for parallel requests',
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/compiler/compUrl.html', 'a');
// Expecting only one xhr...
xhr.expect('package:angular2/test/compiler/compUrl.html', '<a></a>');
PromiseWrapper.all([compile([CompWithTemplateUrl]), compile([CompWithTemplateUrl])])
.then((humanizedTemplates) => {
expect(humanizedTemplates[0]['commands'][1]['commands']).toEqual(['#text(a)']);
expect(humanizedTemplates[1]['commands'][1]['commands']).toEqual(['#text(a)']);
.then((humanizedViews) => {
expect(humanizedViews[0]['componentViews'][0]['elements']).toEqual(['<a>']);
expect(humanizedViews[1]['componentViews'][0]['elements']).toEqual(['<a>']);
async.done();
});
@@ -156,15 +179,14 @@ export function main() {
it('should cache components for sequential requests',
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/compiler/compUrl.html', 'a');
// Expecting only one xhr...
xhr.expect('package:angular2/test/compiler/compUrl.html', '<a>');
compile([CompWithTemplateUrl])
.then((humanizedTemplate0) => {
.then((humanizedView0) => {
return compile([CompWithTemplateUrl])
.then((humanizedTemplate1) => {
expect(humanizedTemplate0['commands'][1]['commands'])
.toEqual(['#text(a)']);
expect(humanizedTemplate1['commands'][1]['commands'])
.toEqual(['#text(a)']);
.then((humanizedView1) => {
expect(humanizedView0['componentViews'][0]['elements']).toEqual(['<a>']);
expect(humanizedView1['componentViews'][0]['elements']).toEqual(['<a>']);
async.done();
});
});
@@ -173,17 +195,17 @@ export function main() {
it('should allow to clear the cache',
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/compiler/compUrl.html', 'a');
xhr.expect('package:angular2/test/compiler/compUrl.html', '<a>');
compile([CompWithTemplateUrl])
.then((humanizedTemplate) => {
.then((humanizedView) => {
compiler.clearCache();
xhr.expect('package:angular2/test/compiler/compUrl.html', 'b');
xhr.expect('package:angular2/test/compiler/compUrl.html', '<b>');
var result = compile([CompWithTemplateUrl]);
xhr.flush();
return result;
})
.then((humanizedTemplate) => {
expect(humanizedTemplate['commands'][1]['commands']).toEqual(['#text(b)']);
.then((humanizedView) => {
expect(humanizedView['componentViews'][0]['elements']).toEqual(['<b>']);
async.done();
});
xhr.flush();
@@ -193,14 +215,17 @@ export function main() {
describe('compileTemplatesCodeGen', () => {
function normalizeComponent(
component: Type): Promise<NormalizedComponentWithViewDirectives> {
var compAndViewDirMetas = [runtimeMetadataResolver.getMetadata(component)].concat(
runtimeMetadataResolver.getViewDirectivesMetadata(component));
var compAndViewDirMetas =
[runtimeMetadataResolver.getDirectiveMetadata(component)].concat(
runtimeMetadataResolver.getViewDirectivesMetadata(component));
var upperCasePipeMeta = runtimeMetadataResolver.getPipeMetadata(UpperCasePipe);
upperCasePipeMeta.type.moduleUrl = `package:${THIS_MODULE_ID}${MODULE_SUFFIX}`;
return PromiseWrapper.all(compAndViewDirMetas.map(
meta => compiler.normalizeDirectiveMetadata(meta)))
.then((normalizedCompAndViewDirMetas: CompileDirectiveMetadata[]) =>
new NormalizedComponentWithViewDirectives(
normalizedCompAndViewDirMetas[0],
normalizedCompAndViewDirMetas.slice(1)));
normalizedCompAndViewDirMetas.slice(1), [upperCasePipeMeta]));
}
function compile(components: Type[]): Promise<any[]> {
@@ -223,7 +248,7 @@ export function main() {
describe('normalizeDirectiveMetadata', () => {
it('should return the given DirectiveMetadata for non components',
inject([AsyncTestCompleter], (async) => {
var meta = runtimeMetadataResolver.getMetadata(NonComponent);
var meta = runtimeMetadataResolver.getDirectiveMetadata(NonComponent);
compiler.normalizeDirectiveMetadata(meta).then(normMeta => {
expect(normMeta).toBe(meta);
async.done();
@@ -234,7 +259,7 @@ export function main() {
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/compiler/compUrl.html', 'loadedTemplate');
compiler.normalizeDirectiveMetadata(
runtimeMetadataResolver.getMetadata(CompWithTemplateUrl))
runtimeMetadataResolver.getDirectiveMetadata(CompWithTemplateUrl))
.then((meta: CompileDirectiveMetadata) => {
expect(meta.template.template).toEqual('loadedTemplate');
async.done();
@@ -243,7 +268,8 @@ export function main() {
}));
it('should copy all the other fields', inject([AsyncTestCompleter], (async) => {
var meta = runtimeMetadataResolver.getMetadata(CompWithBindingsAndStyles);
var meta =
runtimeMetadataResolver.getDirectiveMetadata(CompWithBindingsAndStylesAndPipes);
compiler.normalizeDirectiveMetadata(meta).then((normMeta: CompileDirectiveMetadata) => {
expect(normMeta.type).toEqual(meta.type);
expect(normMeta.isComponent).toEqual(meta.isComponent);
@@ -279,23 +305,35 @@ export function main() {
});
}
@Pipe({name: 'uppercase'})
@Injectable()
export class UpperCasePipe implements PipeTransform {
transform(value: string, args: any[] = null): string { return value.toUpperCase(); }
}
@Component({
selector: 'comp-a',
host: {'[title]': 'someProp'},
host: {'[title]': '\'someHostValue\''},
moduleId: THIS_MODULE_ID,
exportAs: 'someExportAs'
})
@View({
template: '<a [href]="someProp"></a>',
template: '<a [href]="\'someCtxValue\' | uppercase"></a>',
styles: ['div {color: red}'],
encapsulation: ViewEncapsulation.None
encapsulation: ViewEncapsulation.None,
pipes: [UpperCasePipe]
})
class CompWithBindingsAndStyles {
export class CompWithBindingsAndStylesAndPipes {
}
@Component({selector: 'tree', moduleId: THIS_MODULE_ID})
@View({template: '<tree></tree>', directives: [TreeComp], encapsulation: ViewEncapsulation.None})
class TreeComp {
@View({
template: '<template><tree></tree></template>',
directives: [TreeComp],
encapsulation: ViewEncapsulation.None
})
export class TreeComp {
}
@Component({selector: 'comp-wit-dup-tpl', moduleId: THIS_MODULE_ID})
@@ -304,34 +342,37 @@ class TreeComp {
directives: [TreeComp, TreeComp],
encapsulation: ViewEncapsulation.None
})
class CompWithDupDirectives {
export class CompWithDupDirectives {
}
@Component({selector: 'comp-url', moduleId: THIS_MODULE_ID})
@View({templateUrl: 'compUrl.html', encapsulation: ViewEncapsulation.None})
class CompWithTemplateUrl {
export class CompWithTemplateUrl {
}
@Component({selector: 'comp-tpl', moduleId: THIS_MODULE_ID})
@View({
template: '<template><a [href]="someProp"></a></template>',
template: '<template><a [href]="\'someEmbeddedValue\'"></a></template>',
encapsulation: ViewEncapsulation.None
})
class CompWithEmbeddedTemplate {
export class CompWithEmbeddedTemplate {
}
@Directive({selector: 'plain'})
@View({template: ''})
class NonComponent {
export class NonComponent {
}
function testableTemplateModule(sourceModule: SourceModule,
normComp: CompileDirectiveMetadata): SourceModule {
var resultExpression =
`${THIS_MODULE_REF}humanizeTemplate(Host${normComp.type.name}Template.template)`;
var testableSource = `${sourceModule.sourceWithModuleRefs}
${codeGenValueFn(['_'], resultExpression, '_run')};
var testableSource = `
${sourceModule.sourceWithModuleRefs}
${codeGenFnHeader(['_'], '_run')}{
${REFLECTOR_MODULE_REF}reflector.reflectionCapabilities = new ${REFLECTION_CAPS_MODULE_REF}ReflectionCapabilities();
return ${THIS_MODULE_REF}humanizeViewFactory(hostViewFactory_${normComp.type.name}.viewFactory);
}
${codeGenExportVariable('run')}_run;`;
return new SourceModule(sourceModule.moduleUrl, testableSource);
}
@@ -343,75 +384,71 @@ function testableStylesModule(sourceModule: SourceModule): SourceModule {
return new SourceModule(sourceModule.moduleUrl, testableSource);
}
// Attention: read by eval!
export function humanizeTemplate(
template: CompiledComponentTemplate,
humanizedTemplates: Map<string, {[key: string]: any}> = null): {[key: string]: any} {
if (isBlank(humanizedTemplates)) {
humanizedTemplates = new Map<string, {[key: string]: any}>();
}
var result = humanizedTemplates.get(template.id);
function humanizeView(view: AppView, cachedResults: Map<AppProtoView, any>): {[key: string]: any} {
var result = cachedResults.get(view.proto);
if (isPresent(result)) {
return result;
}
var commands = [];
result = {
'styles': template.styles,
'commands': commands,
'cd': testChangeDetector(template.changeDetectorFactory)
};
humanizedTemplates.set(template.id, result);
visitAllCommands(new CommandHumanizer(commands, humanizedTemplates), template.commands);
result = {};
// fill the cache early to break cycles.
cachedResults.set(view.proto, result);
view.changeDetector.detectChanges();
var pipes = {};
if (isPresent(view.proto.protoPipes)) {
StringMapWrapper.forEach(view.proto.protoPipes.config, (pipeProvider, pipeName) => {
pipes[pipeName] = stringify(pipeProvider.key.token);
});
}
var componentViews = [];
var embeddedViews = [];
view.appElements.forEach((appElement) => {
if (isPresent(appElement.componentView)) {
componentViews.push(humanizeView(appElement.componentView, cachedResults));
} else if (isPresent(appElement.embeddedViewFactory)) {
embeddedViews.push(
humanizeViewFactory(appElement.embeddedViewFactory, appElement, cachedResults));
}
});
result['styles'] = (<any>view.renderer).styles;
result['elements'] = (<any>view.renderer).elements;
result['pipes'] = pipes;
result['cd'] = (<any>view.renderer).props;
result['componentViews'] = componentViews;
result['embeddedViews'] = embeddedViews;
return result;
}
class TestContext implements CompWithBindingsAndStyles, TreeComp, CompWithTemplateUrl,
CompWithEmbeddedTemplate, CompWithDupDirectives {
someProp: string;
// Attention: read by eval!
export function humanizeViewFactory(
viewFactory: Function, containerAppElement: AppElement = null,
cachedResults: Map<AppProtoView, any> = null): {[key: string]: any} {
if (isBlank(cachedResults)) {
cachedResults = new Map<AppProtoView, any>();
}
var viewManager = new SpyAppViewManager();
viewManager.spy('createRenderComponentType')
.andCallFake((encapsulation: ViewEncapsulation, styles: Array<string | any[]>) => {
return new RenderComponentType('someId', encapsulation, styles);
});
var view: AppView = viewFactory(new RecordingRenderer([]), viewManager, containerAppElement, [],
null, null, null);
return humanizeView(view, cachedResults);
}
class RecordingRenderer extends SpyRenderer {
props: string[] = [];
elements: string[] = [];
function testChangeDetector(changeDetectorFactory: Function): string[] {
var ctx = new TestContext();
ctx.someProp = 'someCtxValue';
var dir1 = new TestContext();
dir1.someProp = 'someDirValue';
var dispatcher = new TestDispatcher([dir1], []);
var cd = changeDetectorFactory(dispatcher);
var locals = new Locals(null, MapWrapper.createFromStringMap({'someVar': null}));
cd.hydrate(ctx, locals, dispatcher, new TestPipes());
cd.detectChanges();
return dispatcher.log;
}
class CommandHumanizer implements CommandVisitor {
constructor(private result: any[],
private humanizedTemplates: Map<string, {[key: string]: any}>) {}
visitText(cmd: TextCmd, context: any): any {
this.result.push(`#text(${cmd.value})`);
return null;
}
visitNgContent(cmd: NgContentCmd, context: any): any { return null; }
visitBeginElement(cmd: BeginElementCmd, context: any): any {
this.result.push(`<${cmd.name}>`);
return null;
}
visitEndElement(context: any): any {
this.result.push('</>');
return null;
}
visitBeginComponent(cmd: BeginComponentCmd, context: any): any {
this.result.push(`<${cmd.name}>`);
this.result.push(humanizeTemplate(cmd.templateGetter(), this.humanizedTemplates));
return null;
}
visitEndComponent(context: any): any { return this.visitEndElement(context); }
visitEmbeddedTemplate(cmd: EmbeddedTemplateCmd, context: any): any {
this.result.push(`<template>`);
this.result.push({'cd': testChangeDetector(cmd.changeDetectorFactory)});
this.result.push(`</template>`);
return null;
constructor(public styles: string[]) {
super();
this.spy('renderComponent')
.andCallFake((componentProto) => new RecordingRenderer(componentProto.styles));
this.spy('setElementProperty')
.andCallFake((el, prop, value) => { this.props.push(`prop(${prop})=${value}`); });
this.spy('createElement')
.andCallFake((parent, elName) => { this.elements.push(`<${elName}>`); });
}
}
@@ -21,6 +21,7 @@ import {
} from 'angular2/src/compiler/template_parser';
import {
CompileDirectiveMetadata,
CompilePipeMetadata,
CompileTypeMetadata,
CompileTemplateMetadata
} from 'angular2/src/compiler/directive_metadata';
@@ -69,8 +70,12 @@ export function main() {
{selector: '[ngIf]', type: new CompileTypeMetadata({name: 'NgIf'}), inputs: ['ngIf']});
}));
function parse(template: string, directives: CompileDirectiveMetadata[]): TemplateAst[] {
return parser.parse(template, directives, 'TestComp');
function parse(template: string, directives: CompileDirectiveMetadata[],
pipes: CompilePipeMetadata[] = null): TemplateAst[] {
if (pipes === null) {
pipes = [];
}
return parser.parse(template, directives, pipes, 'TestComp');
}
describe('template transform', () => {
@@ -938,15 +943,29 @@ Property binding a not used by any directive on an embedded template ("[ERROR ->
it('should support directive property', () => {
var dirA = CompileDirectiveMetadata.create(
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['aProp']});
expect(humanizeTplAstSourceSpans(parse('<div [aProp]="foo | bar"></div>', [dirA])))
expect(humanizeTplAstSourceSpans(parse('<div [aProp]="foo"></div>', [dirA])))
.toEqual([
[ElementAst, 'div', '<div [aProp]="foo | bar">'],
[DirectiveAst, dirA, '<div [aProp]="foo | bar">'],
[BoundDirectivePropertyAst, 'aProp', '(foo | bar)', '[aProp]="foo | bar"']
[ElementAst, 'div', '<div [aProp]="foo">'],
[DirectiveAst, dirA, '<div [aProp]="foo">'],
[BoundDirectivePropertyAst, 'aProp', 'foo', '[aProp]="foo"']
]);
});
});
describe('pipes', () => {
it('should allow pipes that have been defined as dependencies', () => {
var testPipe =
new CompilePipeMetadata({name: 'test', type: new CompileTypeMetadata({name: 'DirA'})});
expect(() => parse('{{a | test}}', [], [testPipe])).not.toThrow();
});
it('should report pipes as error that have not been defined as dependencies', () => {
expect(() => parse('{{a | test}}', [])).toThrowError(`Template parse errors:
The pipe 'test' could not be found ("[ERROR ->]{{a | test}}"): TestComp@0:0`);
});
});
});
}