feat(compiler): add full directive metadata and validation logic

With this, the new `TemplateParser` has feature/data parity with the `ProtoViewDto` of the `RenderCompiler`.

Part of #3605

Closes #3880
This commit is contained in:
Tobias Bosch
2015-08-28 14:55:47 -07:00
parent 0f4eb1b524
commit f93cd9ced7
11 changed files with 902 additions and 200 deletions
+37 -9
View File
@@ -1,7 +1,8 @@
import {isPresent} from 'angular2/src/core/facade/lang';
import {isPresent, normalizeBool} from 'angular2/src/core/facade/lang';
import {HtmlAst} from './html_ast';
import {ChangeDetectionStrategy} from 'angular2/src/core/change_detection/change_detection';
export class TypeMeta {
export class TypeMetadata {
type: any;
typeName: string;
typeUrl: string;
@@ -13,7 +14,28 @@ export class TypeMeta {
}
}
export class TemplateMeta {
export class ChangeDetectionMetadata {
changeDetection: ChangeDetectionStrategy;
properties: string[];
events: string[];
hostListeners: StringMap<string, string>;
hostProperties: StringMap<string, string>;
constructor({changeDetection, properties, events, hostListeners, hostProperties}: {
changeDetection?: ChangeDetectionStrategy,
properties?: string[],
events?: string[],
hostListeners?: StringMap<string, string>,
hostProperties?: StringMap<string, string>
}) {
this.changeDetection = changeDetection;
this.properties = properties;
this.events = events;
this.hostListeners = hostListeners;
this.hostProperties = hostProperties;
}
}
export class TemplateMetadata {
encapsulation: ViewEncapsulation;
nodes: HtmlAst[];
styles: string[];
@@ -54,19 +76,25 @@ export enum ViewEncapsulation {
}
export class DirectiveMetadata {
type: TypeMeta;
type: TypeMetadata;
isComponent: boolean;
selector: string;
template: TemplateMeta;
constructor({type, isComponent, selector, template}: {
type?: TypeMeta,
hostAttributes: Map<string, string>;
changeDetection: ChangeDetectionMetadata;
template: TemplateMetadata;
constructor({type, isComponent, selector, hostAttributes, changeDetection, template}: {
type?: TypeMetadata,
isComponent?: boolean,
selector?: string,
template?: TemplateMeta
hostAttributes?: Map<string, string>,
changeDetection?: ChangeDetectionMetadata,
template?: TemplateMetadata
} = {}) {
this.type = type;
this.isComponent = isPresent(isComponent) ? isComponent : false;
this.isComponent = normalizeBool(isComponent);
this.selector = selector;
this.hostAttributes = hostAttributes;
this.changeDetection = changeDetection;
this.template = template;
}
}
+34 -10
View File
@@ -22,13 +22,15 @@ export class AttrAst implements TemplateAst {
visit(visitor: TemplateAstVisitor): any { return visitor.visitAttr(this); }
}
export class BoundPropertyAst implements TemplateAst {
constructor(public name: string, public value: AST, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitProperty(this); }
export class BoundElementPropertyAst implements TemplateAst {
constructor(public name: string, public type: PropertyBindingType, public value: AST,
public unit: string, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitElementProperty(this); }
}
export class BoundEventAst implements TemplateAst {
constructor(public name: string, public handler: AST, public sourceInfo: string) {}
constructor(public name: string, public target: string, public handler: AST,
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitEvent(this); }
}
@@ -38,35 +40,57 @@ export class VariableAst implements TemplateAst {
}
export class ElementAst implements TemplateAst {
constructor(public attrs: AttrAst[], public properties: BoundPropertyAst[],
constructor(public attrs: AttrAst[], public properties: BoundElementPropertyAst[],
public events: BoundEventAst[], public vars: VariableAst[],
public directives: DirectiveMetadata[], public children: TemplateAst[],
public directives: DirectiveAst[], public children: TemplateAst[],
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitElement(this); }
}
export class EmbeddedTemplateAst implements TemplateAst {
constructor(public attrs: AttrAst[], public properties: BoundPropertyAst[],
public vars: VariableAst[], public directives: DirectiveMetadata[],
public children: TemplateAst[], public sourceInfo: string) {}
constructor(public attrs: AttrAst[], public vars: VariableAst[],
public directives: DirectiveAst[], public children: TemplateAst[],
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitEmbeddedTemplate(this); }
}
export class BoundDirectivePropertyAst implements TemplateAst {
constructor(public directiveName: string, public templateName: string, public value: AST,
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitDirectiveProperty(this); }
}
export class DirectiveAst implements TemplateAst {
constructor(public directive: DirectiveMetadata, public properties: BoundDirectivePropertyAst[],
public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[],
public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitDirective(this); }
}
export class NgContentAst implements TemplateAst {
constructor(public select: string, public sourceInfo: string) {}
visit(visitor: TemplateAstVisitor): any { return visitor.visitNgContent(this); }
}
export enum PropertyBindingType {
Property,
Attribute,
Class,
Style
}
export interface TemplateAstVisitor {
visitNgContent(ast: NgContentAst): any;
visitEmbeddedTemplate(ast: EmbeddedTemplateAst): any;
visitElement(ast: ElementAst): any;
visitVariable(ast: VariableAst): any;
visitEvent(ast: BoundEventAst): any;
visitProperty(ast: BoundPropertyAst): any;
visitElementProperty(ast: BoundElementPropertyAst): any;
visitAttr(ast: AttrAst): any;
visitBoundText(ast: BoundTextAst): any;
visitText(ast: TextAst): any;
visitDirective(ast: DirectiveAst): any;
visitDirectiveProperty(ast: BoundDirectivePropertyAst): any;
}
@@ -1,4 +1,4 @@
import {TypeMeta, TemplateMeta, ViewEncapsulation} from './api';
import {TypeMetadata, TemplateMetadata, ViewEncapsulation} from './api';
import {isPresent} from 'angular2/src/core/facade/lang';
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
@@ -28,8 +28,9 @@ export class TemplateLoader {
constructor(private _xhr: XHR, private _urlResolver: UrlResolver,
private _styleUrlResolver: StyleUrlResolver, private _domParser: HtmlParser) {}
loadTemplate(directiveType: TypeMeta, encapsulation: ViewEncapsulation, template: string,
templateUrl: string, styles: string[], styleUrls: string[]): Promise<TemplateMeta> {
loadTemplate(directiveType: TypeMetadata, encapsulation: ViewEncapsulation, template: string,
templateUrl: string, styles: string[],
styleUrls: string[]): Promise<TemplateMetadata> {
if (isPresent(template)) {
return PromiseWrapper.resolve(this.createTemplateFromString(
directiveType, encapsulation, template, directiveType.typeUrl, styles, styleUrls));
@@ -42,9 +43,9 @@ export class TemplateLoader {
}
}
createTemplateFromString(directiveType: TypeMeta, encapsulation: ViewEncapsulation,
createTemplateFromString(directiveType: TypeMetadata, encapsulation: ViewEncapsulation,
template: string, templateSourceUrl: string, styles: string[],
styleUrls: string[]): TemplateMeta {
styleUrls: string[]): TemplateMetadata {
var domNodes = this._domParser.parse(template, directiveType.typeName);
var visitor = new TemplatePreparseVisitor();
var remainingNodes = htmlVisitAll(visitor, domNodes);
@@ -60,7 +61,7 @@ export class TemplateLoader {
allStyles.map(style => this._styleUrlResolver.resolveUrls(style, templateSourceUrl));
var allStyleAbsUrls =
allStyleUrls.map(styleUrl => this._urlResolver.resolve(templateSourceUrl, styleUrl));
return new TemplateMeta({
return new TemplateMetadata({
encapsulation: encapsulation,
nodes: remainingNodes,
styles: allResolvedStyles,
File diff suppressed because it is too large Load Diff
+7
View File
@@ -1,7 +1,14 @@
import {StringWrapper} from 'angular2/src/core/facade/lang';
var CAMEL_CASE_REGEXP = /([A-Z])/g;
var DASH_CASE_REGEXP = /-([a-z])/g;
export function camelCaseToDashCase(input: string): string {
return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP,
(m) => { return '-' + m[1].toLowerCase(); });
}
export function dashCaseToCamelCase(input: string): string {
return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP,
(m) => { return m[1].toUpperCase(); });
@@ -1,17 +1,28 @@
import {isPresent} from 'angular2/src/core/facade/lang';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
import {StringMapWrapper} from 'angular2/src/core/facade/collection';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ElementSchemaRegistry} from './element_schema_registry';
export class DomElementSchemaRegistry extends ElementSchemaRegistry {
hasProperty(elm: any, propName: string): boolean {
var tagName = DOM.tagName(elm);
private _protoElements: Map<string, Element> = new Map();
private _getProtoElement(tagName: string): Element {
var element = this._protoElements.get(tagName);
if (isBlank(element)) {
element = DOM.createElement(tagName);
this._protoElements.set(tagName, element);
}
return element;
}
hasProperty(tagName: string, propName: string): boolean {
if (tagName.indexOf('-') !== -1) {
// can't tell now as we don't know which properties a custom element will get
// once it is instantiated
return true;
} else {
var elm = this._getProtoElement(tagName);
return DOM.hasProperty(elm, propName);
}
}
@@ -1,4 +1,4 @@
export class ElementSchemaRegistry {
hasProperty(elm: any, propName: string): boolean { return true; }
hasProperty(tagName: string, propName: string): boolean { return true; }
getMappedPropName(propName: string): string { return propName; }
}
@@ -369,7 +369,7 @@ function isValidElementPropertyBinding(schemaRegistry: ElementSchemaRegistry,
binding: ElementPropertyBinding): boolean {
if (binding.type === PropertyBindingType.PROPERTY) {
if (!isNgComponent) {
return schemaRegistry.hasProperty(protoElement, binding.property);
return schemaRegistry.hasProperty(DOM.tagName(protoElement), binding.property);
} else {
// TODO(pk): change this logic as soon as we can properly detect custom elements
return DOM.hasProperty(protoElement, binding.property);
@@ -15,7 +15,7 @@ import {
} from 'angular2/test_lib';
import {HtmlParser} from 'angular2/src/compiler/html_parser';
import {TypeMeta, ViewEncapsulation, TemplateMeta} from 'angular2/src/compiler/api';
import {TypeMetadata, ViewEncapsulation, TemplateMetadata} from 'angular2/src/compiler/api';
import {TemplateLoader} from 'angular2/src/compiler/template_loader';
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
@@ -28,21 +28,21 @@ import {MockXHR} from 'angular2/src/core/render/xhr_mock';
export function main() {
describe('TemplateLoader', () => {
var loader: TemplateLoader;
var dirType: TypeMeta;
var dirType: TypeMetadata;
var xhr: MockXHR;
beforeEach(inject([XHR], (mockXhr) => {
xhr = mockXhr;
var urlResolver = new UrlResolver();
loader =
new TemplateLoader(xhr, urlResolver, new StyleUrlResolver(urlResolver), new HtmlParser());
dirType = new TypeMeta({typeUrl: 'http://sometypeurl', typeName: 'SomeComp'});
dirType = new TypeMetadata({typeUrl: 'http://sometypeurl', typeName: 'SomeComp'});
}));
describe('loadTemplate', () => {
describe('inline template', () => {
it('should parse the template', inject([AsyncTestCompleter], (async) => {
loader.loadTemplate(dirType, null, 'a', null, [], ['test.css'])
.then((template: TemplateMeta) => {
.then((template: TemplateMetadata) => {
expect(humanizeDom(template.nodes))
.toEqual([[HtmlTextAst, 'a', 'SomeComp > #text(a):nth-child(0)']])
async.done();
@@ -51,7 +51,7 @@ export function main() {
it('should resolve styles against the typeUrl', inject([AsyncTestCompleter], (async) => {
loader.loadTemplate(dirType, null, 'a', null, [], ['test.css'])
.then((template: TemplateMeta) => {
.then((template: TemplateMetadata) => {
expect(template.styleAbsUrls).toEqual(['http://sometypeurl/test.css']);
async.done();
});
@@ -64,7 +64,7 @@ export function main() {
inject([AsyncTestCompleter], (async) => {
xhr.expect('http://sometypeurl/sometplurl', 'a');
loader.loadTemplate(dirType, null, null, 'sometplurl', [], ['test.css'])
.then((template: TemplateMeta) => {
.then((template: TemplateMetadata) => {
expect(humanizeDom(template.nodes))
.toEqual([[HtmlTextAst, 'a', 'SomeComp > #text(a):nth-child(0)']])
async.done();
@@ -76,7 +76,7 @@ export function main() {
inject([AsyncTestCompleter], (async) => {
xhr.expect('http://sometypeurl/tpl/sometplurl', 'a');
loader.loadTemplate(dirType, null, null, 'tpl/sometplurl', [], ['test.css'])
.then((template: TemplateMeta) => {
.then((template: TemplateMetadata) => {
expect(template.styleAbsUrls).toEqual(['http://sometypeurl/tpl/test.css']);
async.done();
});
File diff suppressed because it is too large Load Diff
@@ -14,30 +14,26 @@ import {IS_DART} from '../../../../platform';
import {
DomElementSchemaRegistry
} from 'angular2/src/core/render/dom/schema/dom_element_schema_registry';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
export function main() {
// DOMElementSchema can only be used on the JS side where we can safely
// use reflection for DOM elements
if (IS_DART) return;
var registry;
var registry: DomElementSchemaRegistry;
beforeEach(() => { registry = new DomElementSchemaRegistry(); });
describe('DOMElementSchema', () => {
it('should detect properties on regular elements', () => {
var divEl = DOM.createElement('div');
expect(registry.hasProperty(divEl, 'id')).toBeTruthy();
expect(registry.hasProperty(divEl, 'title')).toBeTruthy();
expect(registry.hasProperty(divEl, 'unknown')).toBeFalsy();
expect(registry.hasProperty('div', 'id')).toBeTruthy();
expect(registry.hasProperty('div', 'title')).toBeTruthy();
expect(registry.hasProperty('div', 'unknown')).toBeFalsy();
});
it('should return true for custom-like elements', () => {
var customLikeEl = DOM.createElement('custom-like');
expect(registry.hasProperty(customLikeEl, 'unknown')).toBeTruthy();
});
it('should return true for custom-like elements',
() => { expect(registry.hasProperty('custom-like', 'unknown')).toBeTruthy(); });
it('should not re-map property names that are not specified in DOM facade',
() => { expect(registry.getMappedPropName('readonly')).toEqual('readOnly'); });