feat(compile): add HtmlParser, TemplateParser, ComponentMetadataLoader
First bits of new compile pipeline #3605 Closes #3839
This commit is contained in:
71
modules/angular2/src/compiler/api.ts
Normal file
71
modules/angular2/src/compiler/api.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import {HtmlAst} from './html_ast';
|
||||
|
||||
export class TypeMeta {
|
||||
type: any;
|
||||
typeName: string;
|
||||
typeUrl: string;
|
||||
constructor({type, typeName, typeUrl}:
|
||||
{type?: string, typeName?: string, typeUrl?: string} = {}) {
|
||||
this.type = type;
|
||||
this.typeName = typeName;
|
||||
this.typeUrl = typeUrl;
|
||||
}
|
||||
}
|
||||
|
||||
export class TemplateMeta {
|
||||
encapsulation: ViewEncapsulation;
|
||||
nodes: HtmlAst[];
|
||||
styles: string[];
|
||||
styleAbsUrls: string[];
|
||||
ngContentSelectors: string[];
|
||||
constructor({encapsulation, nodes, styles, styleAbsUrls, ngContentSelectors}: {
|
||||
encapsulation: ViewEncapsulation,
|
||||
nodes: HtmlAst[],
|
||||
styles: string[],
|
||||
styleAbsUrls: string[],
|
||||
ngContentSelectors: string[]
|
||||
}) {
|
||||
this.encapsulation = encapsulation;
|
||||
this.nodes = nodes;
|
||||
this.styles = styles;
|
||||
this.styleAbsUrls = styleAbsUrls;
|
||||
this.ngContentSelectors = ngContentSelectors;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How the template and styles of a view should be encapsulated.
|
||||
*/
|
||||
export enum ViewEncapsulation {
|
||||
/**
|
||||
* Emulate scoping of styles by preprocessing the style rules
|
||||
* and adding additional attributes to elements. This is the default.
|
||||
*/
|
||||
Emulated,
|
||||
/**
|
||||
* Uses the native mechanism of the renderer. For the DOM this means creating a ShadowRoot.
|
||||
*/
|
||||
Native,
|
||||
/**
|
||||
* Don't scope the template nor the styles.
|
||||
*/
|
||||
None
|
||||
}
|
||||
|
||||
export class DirectiveMetadata {
|
||||
type: TypeMeta;
|
||||
selector: string;
|
||||
constructor({type, selector}: {type?: TypeMeta, selector?: string} = {}) {
|
||||
this.type = type;
|
||||
this.selector = selector;
|
||||
}
|
||||
}
|
||||
|
||||
export class ComponentMetadata extends DirectiveMetadata {
|
||||
template: TemplateMeta;
|
||||
constructor({type, selector, template}:
|
||||
{type?: TypeMeta, selector?: string, template?: TemplateMeta}) {
|
||||
super({type: type, selector: selector});
|
||||
this.template = template;
|
||||
}
|
||||
}
|
39
modules/angular2/src/compiler/html_ast.ts
Normal file
39
modules/angular2/src/compiler/html_ast.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import {isPresent} from 'angular2/src/core/facade/lang';
|
||||
|
||||
export interface HtmlAst {
|
||||
sourceInfo: string;
|
||||
visit(visitor: HtmlAstVisitor): any;
|
||||
}
|
||||
|
||||
export class HtmlTextAst implements HtmlAst {
|
||||
constructor(public value: string, public sourceInfo: string) {}
|
||||
visit(visitor: HtmlAstVisitor): any { return visitor.visitText(this); }
|
||||
}
|
||||
|
||||
export class HtmlAttrAst implements HtmlAst {
|
||||
constructor(public name: string, public value: string, public sourceInfo: string) {}
|
||||
visit(visitor: HtmlAstVisitor): any { return visitor.visitAttr(this); }
|
||||
}
|
||||
|
||||
export class HtmlElementAst implements HtmlAst {
|
||||
constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[],
|
||||
public sourceInfo: string) {}
|
||||
visit(visitor: HtmlAstVisitor): any { return visitor.visitElement(this); }
|
||||
}
|
||||
|
||||
export interface HtmlAstVisitor {
|
||||
visitElement(ast: HtmlElementAst): any;
|
||||
visitAttr(ast: HtmlAttrAst): any;
|
||||
visitText(ast: HtmlTextAst): any;
|
||||
}
|
||||
|
||||
export function htmlVisitAll(visitor: HtmlAstVisitor, asts: HtmlAst[]): any[] {
|
||||
var result = [];
|
||||
asts.forEach(ast => {
|
||||
var astResult = ast.visit(visitor);
|
||||
if (isPresent(astResult)) {
|
||||
result.push(astResult);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
95
modules/angular2/src/compiler/html_parser.ts
Normal file
95
modules/angular2/src/compiler/html_parser.ts
Normal file
@ -0,0 +1,95 @@
|
||||
import {MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
|
||||
import {
|
||||
isPresent,
|
||||
StringWrapper,
|
||||
stringify,
|
||||
assertionsEnabled,
|
||||
StringJoiner
|
||||
} from 'angular2/src/core/facade/lang';
|
||||
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
||||
|
||||
import {HtmlAst, HtmlAttrAst, HtmlTextAst, HtmlElementAst} from './html_ast';
|
||||
|
||||
const NG_NON_BINDABLE = 'ng-non-bindable';
|
||||
|
||||
export class HtmlParser {
|
||||
parse(template: string, sourceInfo: string): HtmlAst[] {
|
||||
var root = DOM.createTemplate(template);
|
||||
return parseChildNodes(root, sourceInfo);
|
||||
}
|
||||
}
|
||||
|
||||
function parseText(text: Text, indexInParent: number, parentSourceInfo: string): HtmlTextAst {
|
||||
// TODO(tbosch): add source row/column source info from parse5 / package:html
|
||||
var value = DOM.getText(text);
|
||||
return new HtmlTextAst(value,
|
||||
`${parentSourceInfo} > #text(${value}):nth-child(${indexInParent})`);
|
||||
}
|
||||
|
||||
function parseAttr(element: Element, parentSourceInfo: string, attrName: string, attrValue: string):
|
||||
HtmlAttrAst {
|
||||
// TODO(tbosch): add source row/column source info from parse5 / package:html
|
||||
return new HtmlAttrAst(attrName, attrValue, `${parentSourceInfo}[${attrName}=${attrValue}]`);
|
||||
}
|
||||
|
||||
function parseElement(element: Element, indexInParent: number, parentSourceInfo: string):
|
||||
HtmlElementAst {
|
||||
// normalize nodename always as lower case so that following build steps
|
||||
// can rely on this
|
||||
var nodeName = DOM.nodeName(element).toLowerCase();
|
||||
// TODO(tbosch): add source row/column source info from parse5 / package:html
|
||||
var sourceInfo = `${parentSourceInfo} > ${nodeName}:nth-child(${indexInParent})`;
|
||||
var attrs = parseAttrs(element, sourceInfo);
|
||||
|
||||
var childNodes;
|
||||
if (ignoreChildren(attrs)) {
|
||||
childNodes = [];
|
||||
} else {
|
||||
childNodes = parseChildNodes(element, sourceInfo);
|
||||
}
|
||||
return new HtmlElementAst(nodeName, attrs, childNodes, sourceInfo);
|
||||
}
|
||||
|
||||
function parseAttrs(element: Element, elementSourceInfo: string): HtmlAttrAst[] {
|
||||
// Note: sort the attributes early in the pipeline to get
|
||||
// consistent results throughout the pipeline, as attribute order is not defined
|
||||
// in DOM parsers!
|
||||
var attrMap = DOM.attributeMap(element);
|
||||
var attrList: string[][] = [];
|
||||
MapWrapper.forEach(attrMap, (value, name) => { attrList.push([name, value]); });
|
||||
ListWrapper.sort(attrList, (entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0]));
|
||||
return attrList.map(entry => parseAttr(element, elementSourceInfo, entry[0], entry[1]));
|
||||
}
|
||||
|
||||
function parseChildNodes(element: Element, parentSourceInfo: string): HtmlAst[] {
|
||||
var root = DOM.templateAwareRoot(element);
|
||||
var childNodes = DOM.childNodesAsList(root);
|
||||
var result = [];
|
||||
var index = 0;
|
||||
childNodes.forEach(childNode => {
|
||||
var childResult = null;
|
||||
if (DOM.isTextNode(childNode)) {
|
||||
var text = <Text>childNode;
|
||||
childResult = parseText(text, index, parentSourceInfo);
|
||||
} else if (DOM.isElementNode(childNode)) {
|
||||
var el = <Element>childNode;
|
||||
childResult = parseElement(el, index, parentSourceInfo);
|
||||
}
|
||||
if (isPresent(childResult)) {
|
||||
// Won't have a childResult for e.g. comment nodes
|
||||
result.push(childResult);
|
||||
}
|
||||
index++;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
function ignoreChildren(attrs: HtmlAttrAst[]): boolean {
|
||||
for (var i = 0; i < attrs.length; i++) {
|
||||
var a = attrs[i];
|
||||
if (a.name == NG_NON_BINDABLE) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
65
modules/angular2/src/compiler/style_url_resolver.ts
Normal file
65
modules/angular2/src/compiler/style_url_resolver.ts
Normal file
@ -0,0 +1,65 @@
|
||||
// Some of the code comes from WebComponents.JS
|
||||
// https://github.com/webcomponents/webcomponentsjs/blob/master/src/HTMLImports/path.js
|
||||
|
||||
import {Injectable} from 'angular2/di';
|
||||
import {RegExp, RegExpWrapper, StringWrapper} from 'angular2/src/core/facade/lang';
|
||||
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
|
||||
|
||||
/**
|
||||
* Rewrites URLs by resolving '@import' and 'url()' URLs from the given base URL,
|
||||
* removes and returns the @import urls
|
||||
*/
|
||||
@Injectable()
|
||||
export class StyleUrlResolver {
|
||||
constructor(public _resolver: UrlResolver) {}
|
||||
|
||||
resolveUrls(cssText: string, baseUrl: string): string {
|
||||
cssText = this._replaceUrls(cssText, _cssUrlRe, baseUrl);
|
||||
return cssText;
|
||||
}
|
||||
|
||||
extractImports(cssText: string): StyleWithImports {
|
||||
var foundUrls = [];
|
||||
cssText = this._extractUrls(cssText, _cssImportRe, foundUrls);
|
||||
return new StyleWithImports(cssText, foundUrls);
|
||||
}
|
||||
|
||||
_replaceUrls(cssText: string, re: RegExp, baseUrl: string) {
|
||||
return StringWrapper.replaceAllMapped(cssText, re, (m) => {
|
||||
var pre = m[1];
|
||||
var originalUrl = m[2];
|
||||
if (RegExpWrapper.test(_dataUrlRe, originalUrl)) {
|
||||
// Do not attempt to resolve data: URLs
|
||||
return m[0];
|
||||
}
|
||||
var url = StringWrapper.replaceAll(originalUrl, _quoteRe, '');
|
||||
var post = m[3];
|
||||
|
||||
var resolvedUrl = this._resolver.resolve(baseUrl, url);
|
||||
|
||||
return pre + "'" + resolvedUrl + "'" + post;
|
||||
});
|
||||
}
|
||||
|
||||
_extractUrls(cssText: string, re: RegExp, foundUrls: string[]) {
|
||||
return StringWrapper.replaceAllMapped(cssText, re, (m) => {
|
||||
var originalUrl = m[2];
|
||||
if (RegExpWrapper.test(_dataUrlRe, originalUrl)) {
|
||||
// Do not attempt to resolve data: URLs
|
||||
return m[0];
|
||||
}
|
||||
var url = StringWrapper.replaceAll(originalUrl, _quoteRe, '');
|
||||
foundUrls.push(url);
|
||||
return '';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class StyleWithImports {
|
||||
constructor(public style: string, public styleUrls: string[]) {}
|
||||
}
|
||||
|
||||
var _cssUrlRe = /(url\()([^)]*)(\))/g;
|
||||
var _cssImportRe = /(@import[\s]+(?:url\()?)['"]?([^'"\)]*)['"]?(.*;)/g;
|
||||
var _quoteRe = /['"]/g;
|
||||
var _dataUrlRe = /^['"]?data:/g;
|
82
modules/angular2/src/compiler/template_ast.ts
Normal file
82
modules/angular2/src/compiler/template_ast.ts
Normal file
@ -0,0 +1,82 @@
|
||||
import {AST} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {isPresent} from 'angular2/src/core/facade/lang';
|
||||
import {DirectiveMetadata} from './api';
|
||||
|
||||
export interface TemplateAst {
|
||||
sourceInfo: string;
|
||||
visit(visitor: TemplateAstVisitor): any;
|
||||
}
|
||||
|
||||
export class TextAst implements TemplateAst {
|
||||
constructor(public value: string, public sourceInfo: string) {}
|
||||
visit(visitor: TemplateAstVisitor): any { return visitor.visitText(this); }
|
||||
}
|
||||
|
||||
export class BoundTextAst implements TemplateAst {
|
||||
constructor(public value: AST, public sourceInfo: string) {}
|
||||
visit(visitor: TemplateAstVisitor): any { return visitor.visitBoundText(this); }
|
||||
}
|
||||
|
||||
export class AttrAst implements TemplateAst {
|
||||
constructor(public name: string, public value: string, public sourceInfo: string) {}
|
||||
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 BoundEventAst implements TemplateAst {
|
||||
constructor(public name: string, public handler: AST, public sourceInfo: string) {}
|
||||
visit(visitor: TemplateAstVisitor): any { return visitor.visitEvent(this); }
|
||||
}
|
||||
|
||||
export class VariableAst implements TemplateAst {
|
||||
constructor(public name: string, public value: string, public sourceInfo: string) {}
|
||||
visit(visitor: TemplateAstVisitor): any { return visitor.visitVariable(this); }
|
||||
}
|
||||
|
||||
export class ElementAst implements TemplateAst {
|
||||
constructor(public attrs: AttrAst[], public properties: BoundPropertyAst[],
|
||||
public events: BoundEventAst[], public vars: VariableAst[],
|
||||
public directives: DirectiveMetadata[], 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) {}
|
||||
visit(visitor: TemplateAstVisitor): any { return visitor.visitEmbeddedTemplate(this); }
|
||||
}
|
||||
|
||||
export class NgContentAst implements TemplateAst {
|
||||
constructor(public select: string, public sourceInfo: string) {}
|
||||
visit(visitor: TemplateAstVisitor): any { return visitor.visitNgContent(this); }
|
||||
}
|
||||
|
||||
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;
|
||||
visitAttr(ast: AttrAst): any;
|
||||
visitBoundText(ast: BoundTextAst): any;
|
||||
visitText(ast: TextAst): any;
|
||||
}
|
||||
|
||||
|
||||
export function templateVisitAll(visitor: TemplateAstVisitor, asts: TemplateAst[]): any[] {
|
||||
var result = [];
|
||||
asts.forEach(ast => {
|
||||
var astResult = ast.visit(visitor);
|
||||
if (isPresent(astResult)) {
|
||||
result.push(astResult);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
117
modules/angular2/src/compiler/template_loader.ts
Normal file
117
modules/angular2/src/compiler/template_loader.ts
Normal file
@ -0,0 +1,117 @@
|
||||
import {TypeMeta, TemplateMeta, ViewEncapsulation} from './api';
|
||||
import {isPresent} from 'angular2/src/core/facade/lang';
|
||||
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
|
||||
|
||||
import {XHR} from 'angular2/src/core/render/xhr';
|
||||
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
|
||||
import {StyleUrlResolver} from './style_url_resolver';
|
||||
|
||||
import {
|
||||
HtmlAstVisitor,
|
||||
HtmlElementAst,
|
||||
HtmlTextAst,
|
||||
HtmlAttrAst,
|
||||
HtmlAst,
|
||||
htmlVisitAll
|
||||
} from './html_ast';
|
||||
import {HtmlParser} from './html_parser';
|
||||
|
||||
const NG_CONTENT_SELECT_ATTR = 'select';
|
||||
const NG_CONTENT_ELEMENT = 'ng-content';
|
||||
const LINK_ELEMENT = 'link';
|
||||
const LINK_STYLE_REL_ATTR = 'rel';
|
||||
const LINK_STYLE_HREF_ATTR = 'href';
|
||||
const LINK_STYLE_REL_VALUE = 'stylesheet';
|
||||
const STYLE_ELEMENT = 'style';
|
||||
|
||||
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> {
|
||||
if (isPresent(template)) {
|
||||
return PromiseWrapper.resolve(this.createTemplateFromString(
|
||||
directiveType, encapsulation, template, directiveType.typeUrl, styles, styleUrls));
|
||||
} else {
|
||||
var sourceAbsUrl = this._urlResolver.resolve(directiveType.typeUrl, templateUrl);
|
||||
return this._xhr.get(sourceAbsUrl)
|
||||
.then(templateContent =>
|
||||
this.createTemplateFromString(directiveType, encapsulation, templateContent,
|
||||
sourceAbsUrl, styles, styleUrls));
|
||||
}
|
||||
}
|
||||
|
||||
createTemplateFromString(directiveType: TypeMeta, encapsulation: ViewEncapsulation,
|
||||
template: string, templateSourceUrl: string, styles: string[],
|
||||
styleUrls: string[]): TemplateMeta {
|
||||
var domNodes = this._domParser.parse(template, directiveType.typeName);
|
||||
var visitor = new TemplatePreparseVisitor();
|
||||
var remainingNodes = htmlVisitAll(visitor, domNodes);
|
||||
var allStyles = styles.concat(visitor.styles);
|
||||
var allStyleUrls = styleUrls.concat(visitor.styleUrls);
|
||||
allStyles = allStyles.map(style => {
|
||||
var styleWithImports = this._styleUrlResolver.extractImports(style);
|
||||
styleWithImports.styleUrls.forEach(styleUrl => allStyleUrls.push(styleUrl));
|
||||
return styleWithImports.style;
|
||||
});
|
||||
|
||||
var allResolvedStyles =
|
||||
allStyles.map(style => this._styleUrlResolver.resolveUrls(style, templateSourceUrl));
|
||||
var allStyleAbsUrls =
|
||||
allStyleUrls.map(styleUrl => this._urlResolver.resolve(templateSourceUrl, styleUrl));
|
||||
return new TemplateMeta({
|
||||
encapsulation: encapsulation,
|
||||
nodes: remainingNodes,
|
||||
styles: allResolvedStyles,
|
||||
styleAbsUrls: allStyleAbsUrls,
|
||||
ngContentSelectors: visitor.ngContentSelectors
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class TemplatePreparseVisitor implements HtmlAstVisitor {
|
||||
ngContentSelectors: string[] = [];
|
||||
styles: string[] = [];
|
||||
styleUrls: string[] = [];
|
||||
|
||||
visitElement(ast: HtmlElementAst): HtmlElementAst {
|
||||
var selectAttr = null;
|
||||
var hrefAttr = null;
|
||||
var relAttr = null;
|
||||
ast.attrs.forEach(attr => {
|
||||
if (attr.name == NG_CONTENT_SELECT_ATTR) {
|
||||
selectAttr = attr.value;
|
||||
} else if (attr.name == LINK_STYLE_HREF_ATTR) {
|
||||
hrefAttr = attr.value;
|
||||
} else if (attr.name == LINK_STYLE_REL_ATTR) {
|
||||
relAttr = attr.value;
|
||||
}
|
||||
});
|
||||
var nodeName = ast.name;
|
||||
var keepElement = true;
|
||||
if (nodeName == NG_CONTENT_ELEMENT) {
|
||||
this.ngContentSelectors.push(selectAttr);
|
||||
} else if (nodeName == STYLE_ELEMENT) {
|
||||
keepElement = false;
|
||||
var textContent = '';
|
||||
ast.children.forEach(child => {
|
||||
if (child instanceof HtmlTextAst) {
|
||||
textContent += (<HtmlTextAst>child).value;
|
||||
}
|
||||
});
|
||||
this.styles.push(textContent);
|
||||
} else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
|
||||
keepElement = false;
|
||||
this.styleUrls.push(hrefAttr);
|
||||
}
|
||||
if (keepElement) {
|
||||
return new HtmlElementAst(ast.name, ast.attrs, htmlVisitAll(this, ast.children),
|
||||
ast.sourceInfo);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
visitAttr(ast: HtmlAttrAst): HtmlAttrAst { return ast; }
|
||||
visitText(ast: HtmlTextAst): HtmlTextAst { return ast; }
|
||||
}
|
298
modules/angular2/src/compiler/template_parser.ts
Normal file
298
modules/angular2/src/compiler/template_parser.ts
Normal file
@ -0,0 +1,298 @@
|
||||
import {MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
|
||||
import {
|
||||
RegExpWrapper,
|
||||
isPresent,
|
||||
StringWrapper,
|
||||
BaseException,
|
||||
StringJoiner,
|
||||
stringify,
|
||||
assertionsEnabled,
|
||||
isBlank
|
||||
} from 'angular2/src/core/facade/lang';
|
||||
|
||||
import {Parser, AST, ASTWithSource} from 'angular2/src/core/change_detection/change_detection';
|
||||
|
||||
import {DirectiveMetadata, ComponentMetadata} from './api';
|
||||
import {
|
||||
ElementAst,
|
||||
BoundPropertyAst,
|
||||
BoundEventAst,
|
||||
VariableAst,
|
||||
TemplateAst,
|
||||
TextAst,
|
||||
BoundTextAst,
|
||||
EmbeddedTemplateAst,
|
||||
AttrAst,
|
||||
NgContentAst
|
||||
} from './template_ast';
|
||||
import {CssSelector, SelectorMatcher} from 'angular2/src/core/render/dom/compiler/selector';
|
||||
|
||||
import {
|
||||
HtmlAstVisitor,
|
||||
HtmlAst,
|
||||
HtmlElementAst,
|
||||
HtmlAttrAst,
|
||||
HtmlTextAst,
|
||||
htmlVisitAll
|
||||
} from './html_ast';
|
||||
|
||||
import {dashCaseToCamelCase} from './util';
|
||||
|
||||
// Group 1 = "bind-"
|
||||
// Group 2 = "var-" or "#"
|
||||
// Group 3 = "on-"
|
||||
// Group 4 = "bindon-"
|
||||
// Group 5 = the identifier after "bind-", "var-/#", or "on-"
|
||||
// Group 6 = idenitifer inside [()]
|
||||
// Group 7 = idenitifer inside []
|
||||
// Group 8 = identifier inside ()
|
||||
var BIND_NAME_REGEXP =
|
||||
/^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g;
|
||||
|
||||
const NG_CONTENT_SELECT_ATTR = 'select';
|
||||
const NG_CONTENT_ELEMENT = 'ng-content';
|
||||
const TEMPLATE_ELEMENT = 'template';
|
||||
const TEMPLATE_ATTR = 'template';
|
||||
const TEMPLATE_ATTR_PREFIX = '*';
|
||||
const CLASS_ATTR = 'class';
|
||||
const IMPLICIT_VAR_NAME = '$implicit';
|
||||
|
||||
export class TemplateParser {
|
||||
constructor(private _exprParser: Parser) {}
|
||||
|
||||
parse(domNodes: HtmlAst[], directives: DirectiveMetadata[]): TemplateAst[] {
|
||||
var parseVisitor = new TemplateParseVisitor(directives, this._exprParser);
|
||||
return htmlVisitAll(parseVisitor, domNodes);
|
||||
}
|
||||
}
|
||||
|
||||
class TemplateParseVisitor implements HtmlAstVisitor {
|
||||
selectorMatcher: SelectorMatcher;
|
||||
constructor(directives: DirectiveMetadata[], private _exprParser: Parser) {
|
||||
this.selectorMatcher = new SelectorMatcher();
|
||||
directives.forEach(directive => {
|
||||
var selector = CssSelector.parse(directive.selector);
|
||||
this.selectorMatcher.addSelectables(selector, directive);
|
||||
});
|
||||
}
|
||||
|
||||
visitText(ast: HtmlTextAst): any {
|
||||
var expr = this._exprParser.parseInterpolation(ast.value, ast.sourceInfo);
|
||||
if (isPresent(expr)) {
|
||||
return new BoundTextAst(expr, ast.sourceInfo);
|
||||
} else {
|
||||
return new TextAst(ast.value, ast.sourceInfo);
|
||||
}
|
||||
}
|
||||
|
||||
visitAttr(ast: HtmlAttrAst): any { return new AttrAst(ast.name, ast.value, ast.sourceInfo); }
|
||||
|
||||
visitElement(element: HtmlElementAst): any {
|
||||
var nodeName = element.name;
|
||||
var matchableAttrs: string[][] = [];
|
||||
var props: BoundPropertyAst[] = [];
|
||||
var vars: VariableAst[] = [];
|
||||
var events: BoundEventAst[] = [];
|
||||
|
||||
var templateProps: BoundPropertyAst[] = [];
|
||||
var templateVars: VariableAst[] = [];
|
||||
var templateMatchableAttrs: string[][] = [];
|
||||
var hasInlineTemplates = false;
|
||||
var attrs = [];
|
||||
var selectAttr = null;
|
||||
element.attrs.forEach(attr => {
|
||||
matchableAttrs.push([attr.name, attr.value]);
|
||||
if (attr.name == NG_CONTENT_SELECT_ATTR) {
|
||||
selectAttr = attr.value;
|
||||
}
|
||||
var hasBinding = this._parseAttr(attr, matchableAttrs, props, events, vars);
|
||||
var hasTemplateBinding = this._parseInlineTemplateBinding(attr, templateMatchableAttrs,
|
||||
templateProps, templateVars);
|
||||
if (!hasBinding && !hasTemplateBinding) {
|
||||
// don't include the bindings as attributes as well in the AST
|
||||
attrs.push(this.visitAttr(attr));
|
||||
}
|
||||
if (hasTemplateBinding) {
|
||||
hasInlineTemplates = true;
|
||||
}
|
||||
});
|
||||
var directives = this._parseDirectives(this.selectorMatcher, nodeName, matchableAttrs);
|
||||
var children = htmlVisitAll(this, element.children);
|
||||
var parsedElement;
|
||||
if (nodeName == NG_CONTENT_ELEMENT) {
|
||||
parsedElement = new NgContentAst(selectAttr, element.sourceInfo);
|
||||
} else if (nodeName == TEMPLATE_ELEMENT) {
|
||||
parsedElement =
|
||||
new EmbeddedTemplateAst(attrs, props, vars, directives, children, element.sourceInfo);
|
||||
} else {
|
||||
parsedElement =
|
||||
new ElementAst(attrs, props, events, vars, directives, children, element.sourceInfo);
|
||||
}
|
||||
if (hasInlineTemplates) {
|
||||
var templateDirectives =
|
||||
this._parseDirectives(this.selectorMatcher, TEMPLATE_ELEMENT, templateMatchableAttrs);
|
||||
parsedElement = new EmbeddedTemplateAst([], templateProps, templateVars, templateDirectives,
|
||||
[parsedElement], element.sourceInfo);
|
||||
}
|
||||
return parsedElement;
|
||||
}
|
||||
|
||||
private _parseInlineTemplateBinding(attr: HtmlAttrAst, matchableAttrs: string[][],
|
||||
props: BoundPropertyAst[], vars: VariableAst[]): boolean {
|
||||
var templateBindingsSource = null;
|
||||
if (attr.name == TEMPLATE_ATTR) {
|
||||
templateBindingsSource = attr.value;
|
||||
} else if (StringWrapper.startsWith(attr.name, TEMPLATE_ATTR_PREFIX)) {
|
||||
var key = StringWrapper.substring(attr.name, TEMPLATE_ATTR_PREFIX.length); // remove the star
|
||||
templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value;
|
||||
}
|
||||
if (isPresent(templateBindingsSource)) {
|
||||
var bindings =
|
||||
this._exprParser.parseTemplateBindings(templateBindingsSource, attr.sourceInfo);
|
||||
for (var i = 0; i < bindings.length; i++) {
|
||||
var binding = bindings[i];
|
||||
if (binding.keyIsVar) {
|
||||
vars.push(
|
||||
new VariableAst(dashCaseToCamelCase(binding.key), binding.name, attr.sourceInfo));
|
||||
matchableAttrs.push([binding.key, binding.name]);
|
||||
} else if (isPresent(binding.expression)) {
|
||||
props.push(new BoundPropertyAst(dashCaseToCamelCase(binding.key), binding.expression,
|
||||
attr.sourceInfo));
|
||||
matchableAttrs.push([binding.key, binding.expression.source]);
|
||||
} else {
|
||||
matchableAttrs.push([binding.key, '']);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private _parseAttr(attr: HtmlAttrAst, matchableAttrs: string[][], props: BoundPropertyAst[],
|
||||
events: BoundEventAst[], vars: VariableAst[]): boolean {
|
||||
var attrName = this._normalizeAttributeName(attr.name);
|
||||
var attrValue = attr.value;
|
||||
var bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName);
|
||||
var hasBinding = false;
|
||||
if (isPresent(bindParts)) {
|
||||
hasBinding = true;
|
||||
if (isPresent(bindParts[1])) { // match: bind-prop
|
||||
this._parseProperty(bindParts[5], attrValue, attr.sourceInfo, matchableAttrs, props);
|
||||
|
||||
} else if (isPresent(
|
||||
bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden"
|
||||
var identifier = bindParts[5];
|
||||
var value = attrValue.length === 0 ? IMPLICIT_VAR_NAME : attrValue;
|
||||
this._parseVariable(identifier, value, attr.sourceInfo, matchableAttrs, vars);
|
||||
|
||||
} else if (isPresent(bindParts[3])) { // match: on-event
|
||||
this._parseEvent(bindParts[5], attrValue, attr.sourceInfo, matchableAttrs, events);
|
||||
|
||||
} else if (isPresent(bindParts[4])) { // match: bindon-prop
|
||||
this._parseProperty(bindParts[5], attrValue, attr.sourceInfo, matchableAttrs, props);
|
||||
this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceInfo, matchableAttrs,
|
||||
events);
|
||||
|
||||
} else if (isPresent(bindParts[6])) { // match: [(expr)]
|
||||
this._parseProperty(bindParts[6], attrValue, attr.sourceInfo, matchableAttrs, props);
|
||||
this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceInfo, matchableAttrs,
|
||||
events);
|
||||
|
||||
} else if (isPresent(bindParts[7])) { // match: [expr]
|
||||
this._parseProperty(bindParts[7], attrValue, attr.sourceInfo, matchableAttrs, props);
|
||||
|
||||
} else if (isPresent(bindParts[8])) { // match: (event)
|
||||
this._parseEvent(bindParts[8], attrValue, attr.sourceInfo, matchableAttrs, events);
|
||||
}
|
||||
} else {
|
||||
hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceInfo,
|
||||
matchableAttrs, props);
|
||||
}
|
||||
return hasBinding;
|
||||
}
|
||||
|
||||
private _normalizeAttributeName(attrName: string): string {
|
||||
return StringWrapper.startsWith(attrName, 'data-') ? StringWrapper.substring(attrName, 5) :
|
||||
attrName;
|
||||
}
|
||||
|
||||
private _parseVariable(identifier: string, value: string, sourceInfo: any,
|
||||
matchableAttrs: string[][], vars: VariableAst[]) {
|
||||
vars.push(new VariableAst(dashCaseToCamelCase(identifier), value, sourceInfo));
|
||||
matchableAttrs.push([identifier, value]);
|
||||
}
|
||||
|
||||
private _parseProperty(name: string, expression: string, sourceInfo: any,
|
||||
matchableAttrs: string[][], props: BoundPropertyAst[]) {
|
||||
this._parsePropertyAst(name, this._exprParser.parseBinding(expression, sourceInfo), sourceInfo,
|
||||
matchableAttrs, props);
|
||||
}
|
||||
|
||||
private _parsePropertyInterpolation(name: string, value: string, sourceInfo: any,
|
||||
matchableAttrs: string[][],
|
||||
props: BoundPropertyAst[]): boolean {
|
||||
var expr = this._exprParser.parseInterpolation(value, sourceInfo);
|
||||
if (isPresent(expr)) {
|
||||
this._parsePropertyAst(name, expr, sourceInfo, matchableAttrs, props);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private _parsePropertyAst(name: string, ast: ASTWithSource, sourceInfo: any,
|
||||
matchableAttrs: string[][], props: BoundPropertyAst[]) {
|
||||
props.push(new BoundPropertyAst(dashCaseToCamelCase(name), ast, sourceInfo));
|
||||
matchableAttrs.push([name, ast.source]);
|
||||
}
|
||||
|
||||
private _parseAssignmentEvent(name: string, expression: string, sourceInfo: string,
|
||||
matchableAttrs: string[][], events: BoundEventAst[]) {
|
||||
this._parseEvent(name, `${expression}=$event`, sourceInfo, matchableAttrs, events);
|
||||
}
|
||||
|
||||
private _parseEvent(name: string, expression: string, sourceInfo: string,
|
||||
matchableAttrs: string[][], events: BoundEventAst[]) {
|
||||
events.push(new BoundEventAst(dashCaseToCamelCase(name),
|
||||
this._exprParser.parseAction(expression, sourceInfo),
|
||||
sourceInfo));
|
||||
// Don't detect directives for event names for now,
|
||||
// so don't add the event name to the matchableAttrs
|
||||
}
|
||||
|
||||
private _parseDirectives(selectorMatcher: SelectorMatcher, elementName: string,
|
||||
matchableAttrs: string[][]): DirectiveMetadata[] {
|
||||
var cssSelector = new CssSelector();
|
||||
|
||||
cssSelector.setElement(elementName);
|
||||
for (var i = 0; i < matchableAttrs.length; i++) {
|
||||
var attrName = matchableAttrs[i][0].toLowerCase();
|
||||
var attrValue = matchableAttrs[i][1];
|
||||
cssSelector.addAttribute(attrName, attrValue);
|
||||
if (attrName == CLASS_ATTR) {
|
||||
var classes = splitClasses(attrValue);
|
||||
classes.forEach(className => cssSelector.addClassName(className));
|
||||
}
|
||||
}
|
||||
var directives = [];
|
||||
selectorMatcher.match(cssSelector, (selector, directive) => { directives.push(directive); });
|
||||
// Need to sort the directives so that we get consistent results throughout,
|
||||
// as selectorMatcher uses Maps inside.
|
||||
// Also need to make components the first directive in the array
|
||||
ListWrapper.sort(directives, (dir1: DirectiveMetadata, dir2: DirectiveMetadata) => {
|
||||
var dir1Comp = dir1 instanceof ComponentMetadata;
|
||||
var dir2Comp = dir2 instanceof ComponentMetadata;
|
||||
if (dir1Comp && !dir2Comp) {
|
||||
return -1;
|
||||
} else if (!dir1Comp && dir2Comp) {
|
||||
return 1;
|
||||
} else {
|
||||
return StringWrapper.compare(dir1.type.typeName, dir2.type.typeName);
|
||||
}
|
||||
});
|
||||
return directives;
|
||||
}
|
||||
}
|
||||
|
||||
export function splitClasses(classAttrValue: string): string[] {
|
||||
return StringWrapper.split(classAttrValue.trim(), /\s+/g);
|
||||
}
|
8
modules/angular2/src/compiler/util.ts
Normal file
8
modules/angular2/src/compiler/util.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import {StringWrapper} from 'angular2/src/core/facade/lang';
|
||||
|
||||
var DASH_CASE_REGEXP = /-([a-z])/g;
|
||||
|
||||
export function dashCaseToCamelCase(input: string): string {
|
||||
return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP,
|
||||
(m) => { return m[1].toUpperCase(); });
|
||||
}
|
Reference in New Issue
Block a user