feat(compile): add HtmlParser, TemplateParser, ComponentMetadataLoader
First bits of new compile pipeline #3605 Closes #3839
This commit is contained in:
parent
343dcfa0c0
commit
9f576b0233
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
|
@ -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;
|
||||
}
|
|
@ -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;
|
|
@ -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;
|
||||
}
|
|
@ -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; }
|
||||
}
|
|
@ -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);
|
||||
}
|
|
@ -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(); });
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/test_lib';
|
||||
|
||||
import {HtmlParser} from 'angular2/src/compiler/html_parser';
|
||||
import {
|
||||
HtmlAst,
|
||||
HtmlAstVisitor,
|
||||
HtmlElementAst,
|
||||
HtmlAttrAst,
|
||||
HtmlTextAst,
|
||||
htmlVisitAll
|
||||
} from 'angular2/src/compiler/html_ast';
|
||||
|
||||
export function main() {
|
||||
describe('DomParser', () => {
|
||||
var parser: HtmlParser;
|
||||
beforeEach(() => { parser = new HtmlParser(); });
|
||||
|
||||
describe('text nodes', () => {
|
||||
it('should parse root level text nodes', () => {
|
||||
expect(humanizeDom(parser.parse('a', 'TestComp')))
|
||||
.toEqual([[HtmlTextAst, 'a', 'TestComp > #text(a):nth-child(0)']]);
|
||||
});
|
||||
|
||||
it('should parse text nodes inside regular elements', () => {
|
||||
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
||||
[HtmlTextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(0)']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse text nodes inside template elements', () => {
|
||||
expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
|
||||
[HtmlTextAst, 'a', 'TestComp > template:nth-child(0) > #text(a):nth-child(0)']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('elements', () => {
|
||||
it('should parse root level elements', () => {
|
||||
expect(humanizeDom(parser.parse('<div></div>', 'TestComp')))
|
||||
.toEqual([[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)']]);
|
||||
});
|
||||
|
||||
it('should parse elements inside of regular elements', () => {
|
||||
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
||||
[HtmlElementAst, 'span', 'TestComp > div:nth-child(0) > span:nth-child(0)']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse elements inside of template elements', () => {
|
||||
expect(humanizeDom(parser.parse('<template><span></span></template>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
|
||||
[HtmlElementAst, 'span', 'TestComp > template:nth-child(0) > span:nth-child(0)']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('attributes', () => {
|
||||
it('should parse attributes on regular elements', () => {
|
||||
expect(humanizeDom(parser.parse('<div k="v"></div>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
||||
[HtmlAttrAst, 'k', 'v', 'TestComp > div:nth-child(0)[k=v]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse attributes on template elements', () => {
|
||||
expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
|
||||
[HtmlAttrAst, 'k', 'v', 'TestComp > template:nth-child(0)[k=v]']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ng-non-bindable', () => {
|
||||
it('should ignore text nodes and elements inside of elements with ng-non-bindable', () => {
|
||||
expect(
|
||||
humanizeDom(parser.parse('<div ng-non-bindable>hello<span></span></div>', 'TestComp')))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
||||
[
|
||||
HtmlAttrAst,
|
||||
'ng-non-bindable',
|
||||
'',
|
||||
'TestComp > div:nth-child(0)[ng-non-bindable=]'
|
||||
]
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function humanizeDom(asts: HtmlAst[]): any[] {
|
||||
var humanizer = new Humanizer();
|
||||
htmlVisitAll(humanizer, asts);
|
||||
return humanizer.result;
|
||||
}
|
||||
|
||||
class Humanizer implements HtmlAstVisitor {
|
||||
result: any[] = [];
|
||||
visitElement(ast: HtmlElementAst): any {
|
||||
this.result.push([HtmlElementAst, ast.name, ast.sourceInfo]);
|
||||
htmlVisitAll(this, ast.attrs);
|
||||
htmlVisitAll(this, ast.children);
|
||||
return null;
|
||||
}
|
||||
visitAttr(ast: HtmlAttrAst): any {
|
||||
this.result.push([HtmlAttrAst, ast.name, ast.value, ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
visitText(ast: HtmlTextAst): any {
|
||||
this.result.push([HtmlTextAst, ast.value, ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
import {describe, it, expect, beforeEach, ddescribe, iit, xit, el} from 'angular2/test_lib';
|
||||
import {StyleUrlResolver} from 'angular2/src/compiler/style_url_resolver';
|
||||
|
||||
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
|
||||
|
||||
export function main() {
|
||||
describe('StyleUrlResolver', () => {
|
||||
let styleUrlResolver: StyleUrlResolver;
|
||||
|
||||
beforeEach(() => { styleUrlResolver = new StyleUrlResolver(new UrlResolver()); });
|
||||
|
||||
describe('resolveUrls', () => {
|
||||
it('should resolve "url()" urls', () => {
|
||||
var css = `
|
||||
.foo {
|
||||
background-image: url("double.jpg");
|
||||
background-image: url('simple.jpg');
|
||||
background-image: url(noquote.jpg);
|
||||
}`;
|
||||
var expectedCss = `
|
||||
.foo {
|
||||
background-image: url('http://ng.io/double.jpg');
|
||||
background-image: url('http://ng.io/simple.jpg');
|
||||
background-image: url('http://ng.io/noquote.jpg');
|
||||
}`;
|
||||
|
||||
var resolvedCss = styleUrlResolver.resolveUrls(css, 'http://ng.io');
|
||||
expect(resolvedCss).toEqual(expectedCss);
|
||||
});
|
||||
|
||||
it('should not strip quotes from inlined SVG styles', () => {
|
||||
var css = `
|
||||
.selector {
|
||||
background:rgb(55,71,79) url('data:image/svg+xml;utf8,<?xml version="1.0"?>');
|
||||
background:rgb(55,71,79) url("data:image/svg+xml;utf8,<?xml version='1.0'?>");
|
||||
background:rgb(55,71,79) url("/some/data:image");
|
||||
}
|
||||
`;
|
||||
|
||||
var expectedCss = `
|
||||
.selector {
|
||||
background:rgb(55,71,79) url('data:image/svg+xml;utf8,<?xml version="1.0"?>');
|
||||
background:rgb(55,71,79) url("data:image/svg+xml;utf8,<?xml version='1.0'?>");
|
||||
background:rgb(55,71,79) url('http://ng.io/some/data:image');
|
||||
}
|
||||
`;
|
||||
|
||||
var resolvedCss = styleUrlResolver.resolveUrls(css, 'http://ng.io');
|
||||
expect(resolvedCss).toEqual(expectedCss);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractUrls', () => {
|
||||
it('should extract "@import" urls', () => {
|
||||
var css = `
|
||||
@import '1.css';
|
||||
@import "2.css";
|
||||
`;
|
||||
var styleWithImports = styleUrlResolver.extractImports(css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls).toEqual(['1.css', '2.css']);
|
||||
});
|
||||
|
||||
it('should extract "@import url()" urls', () => {
|
||||
var css = `
|
||||
@import url('3.css');
|
||||
@import url("4.css");
|
||||
@import url(5.css);
|
||||
`;
|
||||
var styleWithImports = styleUrlResolver.extractImports(css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls).toEqual(['3.css', '4.css', '5.css']);
|
||||
});
|
||||
|
||||
it('should extract media query in "@import"', () => {
|
||||
var css = `
|
||||
@import 'print.css' print;
|
||||
@import url(print2.css) print;
|
||||
`;
|
||||
var styleWithImports = styleUrlResolver.extractImports(css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls).toEqual(['print.css', 'print2.css']);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
}
|
|
@ -0,0 +1,185 @@
|
|||
import {
|
||||
AsyncTestCompleter,
|
||||
beforeEach,
|
||||
ddescribe,
|
||||
describe,
|
||||
el,
|
||||
expect,
|
||||
iit,
|
||||
inject,
|
||||
it,
|
||||
xit,
|
||||
TestComponentBuilder,
|
||||
asNativeElements,
|
||||
By
|
||||
} from 'angular2/test_lib';
|
||||
|
||||
import {HtmlParser} from 'angular2/src/compiler/html_parser';
|
||||
import {TypeMeta, ViewEncapsulation, TemplateMeta} from 'angular2/src/compiler/api';
|
||||
|
||||
import {TemplateLoader} from 'angular2/src/compiler/template_loader';
|
||||
import {UrlResolver} from 'angular2/src/core/services/url_resolver';
|
||||
import {StyleUrlResolver} from 'angular2/src/compiler/style_url_resolver';
|
||||
import {humanizeDom} from './html_parser_spec';
|
||||
import {HtmlTextAst, HtmlElementAst, HtmlAttrAst} from 'angular2/src/compiler/html_ast';
|
||||
import {XHR} from 'angular2/src/core/render/xhr';
|
||||
import {MockXHR} from 'angular2/src/core/render/xhr_mock';
|
||||
|
||||
export function main() {
|
||||
describe('TemplateLoader', () => {
|
||||
var loader: TemplateLoader;
|
||||
var dirType: TypeMeta;
|
||||
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'});
|
||||
}));
|
||||
|
||||
describe('loadTemplate', () => {
|
||||
describe('inline template', () => {
|
||||
it('should parse the template', inject([AsyncTestCompleter], (async) => {
|
||||
loader.loadTemplate(dirType, null, 'a', null, [], ['test.css'])
|
||||
.then((template: TemplateMeta) => {
|
||||
expect(humanizeDom(template.nodes))
|
||||
.toEqual([[HtmlTextAst, 'a', 'SomeComp > #text(a):nth-child(0)']])
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
it('should resolve styles against the typeUrl', inject([AsyncTestCompleter], (async) => {
|
||||
loader.loadTemplate(dirType, null, 'a', null, [], ['test.css'])
|
||||
.then((template: TemplateMeta) => {
|
||||
expect(template.styleAbsUrls).toEqual(['http://sometypeurl/test.css']);
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
});
|
||||
|
||||
describe('templateUrl', () => {
|
||||
|
||||
it('should load a template from a url that is resolved against typeUrl',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
xhr.expect('http://sometypeurl/sometplurl', 'a');
|
||||
loader.loadTemplate(dirType, null, null, 'sometplurl', [], ['test.css'])
|
||||
.then((template: TemplateMeta) => {
|
||||
expect(humanizeDom(template.nodes))
|
||||
.toEqual([[HtmlTextAst, 'a', 'SomeComp > #text(a):nth-child(0)']])
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
|
||||
it('should resolve styles against the templateUrl',
|
||||
inject([AsyncTestCompleter], (async) => {
|
||||
xhr.expect('http://sometypeurl/tpl/sometplurl', 'a');
|
||||
loader.loadTemplate(dirType, null, null, 'tpl/sometplurl', [], ['test.css'])
|
||||
.then((template: TemplateMeta) => {
|
||||
expect(template.styleAbsUrls).toEqual(['http://sometypeurl/tpl/test.css']);
|
||||
async.done();
|
||||
});
|
||||
xhr.flush();
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('loadTemplateFromString', () => {
|
||||
it('should store the viewEncapsulationin the result', () => {
|
||||
var viewEncapsulation = ViewEncapsulation.Native;
|
||||
var template = loader.createTemplateFromString(dirType, viewEncapsulation, '',
|
||||
'http://someurl/', [], []);
|
||||
expect(template.encapsulation).toBe(viewEncapsulation);
|
||||
});
|
||||
|
||||
it('should parse the template as html', () => {
|
||||
var template =
|
||||
loader.createTemplateFromString(dirType, null, 'a', 'http://someurl/', [], []);
|
||||
expect(humanizeDom(template.nodes))
|
||||
.toEqual([[HtmlTextAst, 'a', 'SomeComp > #text(a):nth-child(0)']])
|
||||
});
|
||||
|
||||
it('should collect and keep ngContent', () => {
|
||||
var template = loader.createTemplateFromString(dirType, null, '<ng-content select="a">',
|
||||
'http://someurl/', [], []);
|
||||
expect(template.ngContentSelectors).toEqual(['a']);
|
||||
expect(humanizeDom(template.nodes))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'ng-content', 'SomeComp > ng-content:nth-child(0)'],
|
||||
[HtmlAttrAst, 'select', 'a', 'SomeComp > ng-content:nth-child(0)[select=a]']
|
||||
])
|
||||
});
|
||||
|
||||
it('should collect and remove top level styles in the template', () => {
|
||||
var template = loader.createTemplateFromString(dirType, null, '<style>a</style>',
|
||||
'http://someurl/', [], []);
|
||||
expect(template.styles).toEqual(['a']);
|
||||
expect(template.nodes).toEqual([]);
|
||||
});
|
||||
|
||||
it('should collect and remove styles inside in elements', () => {
|
||||
var template = loader.createTemplateFromString(dirType, null, '<div><style>a</style></div>',
|
||||
'http://someurl/', [], []);
|
||||
expect(template.styles).toEqual(['a']);
|
||||
expect(humanizeDom(template.nodes))
|
||||
.toEqual([[HtmlElementAst, 'div', 'SomeComp > div:nth-child(0)']]);
|
||||
});
|
||||
|
||||
it('should collect and remove styleUrls in the template', () => {
|
||||
var template = loader.createTemplateFromString(
|
||||
dirType, null, '<link rel="stylesheet" href="aUrl">', 'http://someurl/', [], []);
|
||||
expect(template.styleAbsUrls).toEqual(['http://someurl/aUrl']);
|
||||
expect(template.nodes).toEqual([]);
|
||||
});
|
||||
|
||||
it('should collect and remove styleUrls in elements', () => {
|
||||
var template = loader.createTemplateFromString(
|
||||
dirType, null, '<div><link rel="stylesheet" href="aUrl"></div>', 'http://someurl/', [],
|
||||
[]);
|
||||
expect(template.styleAbsUrls).toEqual(['http://someurl/aUrl']);
|
||||
expect(humanizeDom(template.nodes))
|
||||
.toEqual([[HtmlElementAst, 'div', 'SomeComp > div:nth-child(0)']]);
|
||||
});
|
||||
|
||||
it('should keep link elements with non stylesheet rel attribute', () => {
|
||||
var template = loader.createTemplateFromString(dirType, null, '<link rel="a" href="b">',
|
||||
'http://someurl/', [], []);
|
||||
expect(template.styleAbsUrls).toEqual([]);
|
||||
expect(humanizeDom(template.nodes))
|
||||
.toEqual([
|
||||
[HtmlElementAst, 'link', 'SomeComp > link:nth-child(0)'],
|
||||
[HtmlAttrAst, 'href', 'b', 'SomeComp > link:nth-child(0)[href=b]'],
|
||||
[HtmlAttrAst, 'rel', 'a', 'SomeComp > link:nth-child(0)[rel=a]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should extract @import style urls into styleAbsUrl', () => {
|
||||
var template = loader.createTemplateFromString(dirType, null, '', 'http://someurl',
|
||||
['@import "test.css";'], []);
|
||||
expect(template.styles).toEqual(['']);
|
||||
expect(template.styleAbsUrls).toEqual(['http://someurl/test.css']);
|
||||
});
|
||||
|
||||
it('should resolve relative urls in inline styles', () => {
|
||||
var template =
|
||||
loader.createTemplateFromString(dirType, null, '', 'http://someurl',
|
||||
['.foo{background-image: url(\'double.jpg\');'], []);
|
||||
expect(template.styles)
|
||||
.toEqual(['.foo{background-image: url(\'http://someurl/double.jpg\');']);
|
||||
});
|
||||
|
||||
it('should resolve relative style urls in styleUrls', () => {
|
||||
var template =
|
||||
loader.createTemplateFromString(dirType, null, '', 'http://someurl', [], ['test.css']);
|
||||
expect(template.styles).toEqual([]);
|
||||
expect(template.styleAbsUrls).toEqual(['http://someurl/test.css']);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
}
|
|
@ -0,0 +1,385 @@
|
|||
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from 'angular2/test_lib';
|
||||
|
||||
import {Parser, Lexer} from 'angular2/src/core/change_detection/change_detection';
|
||||
import {TemplateParser, splitClasses} from 'angular2/src/compiler/template_parser';
|
||||
import {HtmlParser} from 'angular2/src/compiler/html_parser';
|
||||
import {DirectiveMetadata, ComponentMetadata, TypeMeta} from 'angular2/src/compiler/api';
|
||||
import {
|
||||
templateVisitAll,
|
||||
TemplateAstVisitor,
|
||||
TemplateAst,
|
||||
NgContentAst,
|
||||
EmbeddedTemplateAst,
|
||||
ElementAst,
|
||||
VariableAst,
|
||||
BoundEventAst,
|
||||
BoundPropertyAst,
|
||||
AttrAst,
|
||||
BoundTextAst,
|
||||
TextAst
|
||||
} from 'angular2/src/compiler/template_ast';
|
||||
|
||||
import {Unparser} from '../core/change_detection/parser/unparser';
|
||||
|
||||
var expressionUnparser = new Unparser();
|
||||
|
||||
export function main() {
|
||||
describe('TemplateParser', () => {
|
||||
var domParser: HtmlParser;
|
||||
var parser: TemplateParser;
|
||||
|
||||
beforeEach(() => {
|
||||
domParser = new HtmlParser();
|
||||
parser = new TemplateParser(new Parser(new Lexer()));
|
||||
});
|
||||
|
||||
function parse(template: string, directives: DirectiveMetadata[]): TemplateAst[] {
|
||||
return parser.parse(domParser.parse(template, 'TestComp'), directives);
|
||||
}
|
||||
|
||||
describe('parse', () => {
|
||||
describe('nodes without bindings', () => {
|
||||
|
||||
it('should parse text nodes', () => {
|
||||
expect(humanizeTemplateAsts(parse('a', [])))
|
||||
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(0)']]);
|
||||
});
|
||||
|
||||
it('should parse elements with attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div a=b>', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[AttrAst, 'a', 'b', 'TestComp > div:nth-child(0)[a=b]']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse ngContent', () => {
|
||||
var parsed = parse('<ng-content select="a">', []);
|
||||
expect(humanizeTemplateAsts(parsed))
|
||||
.toEqual([[NgContentAst, 'a', 'TestComp > ng-content:nth-child(0)']]);
|
||||
});
|
||||
|
||||
it('should parse bound text nodes', () => {
|
||||
expect(humanizeTemplateAsts(parse('{{a}}', [])))
|
||||
.toEqual([[BoundTextAst, '{{ a }}', 'TestComp > #text({{a}}):nth-child(0)']]);
|
||||
});
|
||||
|
||||
describe('property, event and variable bindings', () => {
|
||||
|
||||
it('should parse bound properties via [...] and not report them as attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div [prop]="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'prop', 'v', 'TestComp > div:nth-child(0)[[prop]=v]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should camel case bound properties', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div [some-prop]="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'someProp', 'v', 'TestComp > div:nth-child(0)[[some-prop]=v]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse bound properties via bind- and not report them as attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div bind-prop="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'prop', 'v', 'TestComp > div:nth-child(0)[bind-prop=v]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse bound properties via {{...}} and not report them as attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div prop="{{v}}">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'prop', '{{ v }}', 'TestComp > div:nth-child(0)[prop={{v}}]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse bound events via (...) and not report them as attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div (event)="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundEventAst, 'event', 'v', 'TestComp > div:nth-child(0)[(event)=v]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should camel case event names', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div (some-event)="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundEventAst, 'someEvent', 'v', 'TestComp > div:nth-child(0)[(some-event)=v]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse bound events via on- and not report them as attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div on-event="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundEventAst, 'event', 'v', 'TestComp > div:nth-child(0)[on-event=v]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse bound events and properties via [(...)] and not report them as attributes',
|
||||
() => {
|
||||
expect(humanizeTemplateAsts(parse('<div [(prop)]="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'prop', 'v', 'TestComp > div:nth-child(0)[[(prop)]=v]'],
|
||||
[
|
||||
BoundEventAst,
|
||||
'prop',
|
||||
'v = $event',
|
||||
'TestComp > div:nth-child(0)[[(prop)]=v]'
|
||||
]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse bound events and properties via bindon- and not report them as attributes',
|
||||
() => {
|
||||
expect(humanizeTemplateAsts(parse('<div bindon-prop="v">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'prop', 'v', 'TestComp > div:nth-child(0)[bindon-prop=v]'],
|
||||
[
|
||||
BoundEventAst,
|
||||
'prop',
|
||||
'v = $event',
|
||||
'TestComp > div:nth-child(0)[bindon-prop=v]'
|
||||
]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse variables via #... and not report them as attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div #a="b">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[#a=b]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse variables via var-... and not report them as attributes', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div var-a="b">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[var-a=b]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should camel case variables', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div var-some-a="b">', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'someA', 'b', 'TestComp > div:nth-child(0)[var-some-a=b]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should use $implicit as variable name if none was specified', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div var-a>', [])))
|
||||
.toEqual([
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'a', '$implicit', 'TestComp > div:nth-child(0)[var-a=]']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('directives', () => {
|
||||
it('should locate directives ordered by typeName and components first', () => {
|
||||
var dirA =
|
||||
new DirectiveMetadata({selector: '[a=b]', type: new TypeMeta({typeName: 'DirA'})});
|
||||
var dirB =
|
||||
new DirectiveMetadata({selector: '[a]', type: new TypeMeta({typeName: 'DirB'})});
|
||||
var comp =
|
||||
new ComponentMetadata({selector: 'div', type: new TypeMeta({typeName: 'ZComp'})});
|
||||
expect(humanizeTemplateAsts(parse('<div a="b">', [dirB, dirA, comp])))
|
||||
.toEqual([
|
||||
[ElementAst, [comp, dirA, dirB], 'TestComp > div:nth-child(0)'],
|
||||
[AttrAst, 'a', 'b', 'TestComp > div:nth-child(0)[a=b]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should locate directives in property bindings', () => {
|
||||
var dirA =
|
||||
new DirectiveMetadata({selector: '[a=b]', type: new TypeMeta({typeName: 'DirA'})});
|
||||
var dirB =
|
||||
new DirectiveMetadata({selector: '[b]', type: new TypeMeta({typeName: 'DirB'})});
|
||||
expect(humanizeTemplateAsts(parse('<div [a]="b">', [dirA, dirB])))
|
||||
.toEqual([
|
||||
[ElementAst, [dirA], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'a', 'b', 'TestComp > div:nth-child(0)[[a]=b]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should locate directives in variable bindings', () => {
|
||||
var dirA =
|
||||
new DirectiveMetadata({selector: '[a=b]', type: new TypeMeta({typeName: 'DirA'})});
|
||||
var dirB =
|
||||
new DirectiveMetadata({selector: '[b]', type: new TypeMeta({typeName: 'DirB'})});
|
||||
expect(humanizeTemplateAsts(parse('<div #a="b">', [dirA, dirB])))
|
||||
.toEqual([
|
||||
[ElementAst, [dirA], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[#a=b]']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('explicit templates', () => {
|
||||
it('should create embedded templates for <template> elements', () => {
|
||||
expect(humanizeTemplateAsts(parse('<template></template>', [])))
|
||||
.toEqual([[EmbeddedTemplateAst, [], 'TestComp > template:nth-child(0)']]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('inline templates', () => {
|
||||
it('should wrap the element into an EmbeddedTemplateAST', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div template>', [])))
|
||||
.toEqual([
|
||||
[EmbeddedTemplateAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse bound properties', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div template="ngIf test">', [])))
|
||||
.toEqual([
|
||||
[EmbeddedTemplateAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[
|
||||
BoundPropertyAst,
|
||||
'ngIf',
|
||||
'test',
|
||||
'TestComp > div:nth-child(0)[template=ngIf test]'
|
||||
],
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse variables via #...', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div template="ngIf #a=b">', [])))
|
||||
.toEqual([
|
||||
[EmbeddedTemplateAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=ngIf #a=b]'],
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should parse variables via var ...', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div template="ngIf var a=b">', [])))
|
||||
.toEqual([
|
||||
[EmbeddedTemplateAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=ngIf var a=b]'],
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)']
|
||||
]);
|
||||
});
|
||||
|
||||
describe('directives', () => {
|
||||
it('should locate directives in property bindings', () => {
|
||||
var dirA =
|
||||
new DirectiveMetadata({selector: '[a=b]', type: new TypeMeta({typeName: 'DirA'})});
|
||||
var dirB =
|
||||
new DirectiveMetadata({selector: '[b]', type: new TypeMeta({typeName: 'DirB'})});
|
||||
expect(humanizeTemplateAsts(parse('<div template="a b" b>', [dirA, dirB])))
|
||||
.toEqual([
|
||||
[EmbeddedTemplateAst, [dirA], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=a b]'],
|
||||
[ElementAst, [dirB], 'TestComp > div:nth-child(0)'],
|
||||
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should locate directives in variable bindings', () => {
|
||||
var dirA =
|
||||
new DirectiveMetadata({selector: '[a=b]', type: new TypeMeta({typeName: 'DirA'})});
|
||||
var dirB =
|
||||
new DirectiveMetadata({selector: '[b]', type: new TypeMeta({typeName: 'DirB'})});
|
||||
expect(humanizeTemplateAsts(parse('<div template="#a=b" b>', [dirA, dirB])))
|
||||
.toEqual([
|
||||
[EmbeddedTemplateAst, [dirA], 'TestComp > div:nth-child(0)'],
|
||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=#a=b]'],
|
||||
[ElementAst, [dirB], 'TestComp > div:nth-child(0)'],
|
||||
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]']
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
it('should work with *... and use the attribute name as property binding name', () => {
|
||||
expect(humanizeTemplateAsts(parse('<div *ng-if="test">', [])))
|
||||
.toEqual([
|
||||
[EmbeddedTemplateAst, [], 'TestComp > div:nth-child(0)'],
|
||||
[BoundPropertyAst, 'ngIf', 'test', 'TestComp > div:nth-child(0)[*ng-if=test]'],
|
||||
[ElementAst, [], 'TestComp > div:nth-child(0)']
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('splitClasses', () => {
|
||||
it('should keep an empty class', () => { expect(splitClasses('a')).toEqual(['a']); });
|
||||
|
||||
it('should split 2 classes', () => { expect(splitClasses('a b')).toEqual(['a', 'b']); });
|
||||
|
||||
it('should trim classes', () => { expect(splitClasses(' a b ')).toEqual(['a', 'b']); });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function humanizeTemplateAsts(templateAsts: TemplateAst[]): any[] {
|
||||
var humanizer = new TemplateHumanizer();
|
||||
templateVisitAll(humanizer, templateAsts);
|
||||
return humanizer.result;
|
||||
}
|
||||
|
||||
class TemplateHumanizer implements TemplateAstVisitor {
|
||||
result: any[] = [];
|
||||
visitNgContent(ast: NgContentAst): any {
|
||||
this.result.push([NgContentAst, ast.select, ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
visitEmbeddedTemplate(ast: EmbeddedTemplateAst): any {
|
||||
this.result.push([EmbeddedTemplateAst, ast.directives, ast.sourceInfo]);
|
||||
templateVisitAll(this, ast.attrs);
|
||||
templateVisitAll(this, ast.properties);
|
||||
templateVisitAll(this, ast.vars);
|
||||
templateVisitAll(this, ast.children);
|
||||
return null;
|
||||
}
|
||||
visitElement(ast: ElementAst): any {
|
||||
this.result.push([ElementAst, ast.directives, ast.sourceInfo]);
|
||||
templateVisitAll(this, ast.attrs);
|
||||
templateVisitAll(this, ast.properties);
|
||||
templateVisitAll(this, ast.events);
|
||||
templateVisitAll(this, ast.vars);
|
||||
templateVisitAll(this, ast.children);
|
||||
return null;
|
||||
}
|
||||
visitVariable(ast: VariableAst): any {
|
||||
this.result.push([VariableAst, ast.name, ast.value, ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
visitEvent(ast: BoundEventAst): any {
|
||||
this.result.push(
|
||||
[BoundEventAst, ast.name, expressionUnparser.unparse(ast.handler), ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
visitProperty(ast: BoundPropertyAst): any {
|
||||
this.result.push(
|
||||
[BoundPropertyAst, ast.name, expressionUnparser.unparse(ast.value), ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
visitAttr(ast: AttrAst): any {
|
||||
this.result.push([AttrAst, ast.name, ast.value, ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
visitBoundText(ast: BoundTextAst): any {
|
||||
this.result.push([BoundTextAst, expressionUnparser.unparse(ast.value), ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
visitText(ast: TextAst): any {
|
||||
this.result.push([TextAst, ast.value, ast.sourceInfo]);
|
||||
return null;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue