feat(Compiler): case sensitive html parser
This commit is contained in:
parent
0db02523d3
commit
adb87562bb
|
@ -1,23 +1,25 @@
|
||||||
import {isPresent} from 'angular2/src/facade/lang';
|
import {isPresent} from 'angular2/src/facade/lang';
|
||||||
|
|
||||||
|
import {ParseSourceSpan} from './parse_util';
|
||||||
|
|
||||||
export interface HtmlAst {
|
export interface HtmlAst {
|
||||||
sourceInfo: string;
|
sourceSpan: ParseSourceSpan;
|
||||||
visit(visitor: HtmlAstVisitor, context: any): any;
|
visit(visitor: HtmlAstVisitor, context: any): any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class HtmlTextAst implements HtmlAst {
|
export class HtmlTextAst implements HtmlAst {
|
||||||
constructor(public value: string, public sourceInfo: string) {}
|
constructor(public value: string, public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitText(this, context); }
|
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitText(this, context); }
|
||||||
}
|
}
|
||||||
|
|
||||||
export class HtmlAttrAst implements HtmlAst {
|
export class HtmlAttrAst implements HtmlAst {
|
||||||
constructor(public name: string, public value: string, public sourceInfo: string) {}
|
constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitAttr(this, context); }
|
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitAttr(this, context); }
|
||||||
}
|
}
|
||||||
|
|
||||||
export class HtmlElementAst implements HtmlAst {
|
export class HtmlElementAst implements HtmlAst {
|
||||||
constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[],
|
constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[],
|
||||||
public sourceInfo: string) {}
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitElement(this, context); }
|
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitElement(this, context); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,478 @@
|
||||||
|
import {
|
||||||
|
StringWrapper,
|
||||||
|
NumberWrapper,
|
||||||
|
isPresent,
|
||||||
|
isBlank,
|
||||||
|
CONST_EXPR,
|
||||||
|
serializeEnum
|
||||||
|
} from 'angular2/src/facade/lang';
|
||||||
|
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||||
|
import {ParseLocation, ParseError, ParseSourceFile, ParseSourceSpan} from './parse_util';
|
||||||
|
import {getHtmlTagDefinition, HtmlTagContentType, NAMED_ENTITIES} from './html_tags';
|
||||||
|
|
||||||
|
export enum HtmlTokenType {
|
||||||
|
TAG_OPEN_START,
|
||||||
|
TAG_OPEN_END,
|
||||||
|
TAG_OPEN_END_VOID,
|
||||||
|
TAG_CLOSE,
|
||||||
|
TEXT,
|
||||||
|
ESCAPABLE_RAW_TEXT,
|
||||||
|
RAW_TEXT,
|
||||||
|
COMMENT_START,
|
||||||
|
COMMENT_END,
|
||||||
|
CDATA_START,
|
||||||
|
CDATA_END,
|
||||||
|
ATTR_NAME,
|
||||||
|
ATTR_VALUE,
|
||||||
|
DOC_TYPE,
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HtmlToken {
|
||||||
|
constructor(public type: HtmlTokenType, public parts: string[],
|
||||||
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HtmlTokenError extends ParseError {
|
||||||
|
constructor(errorMsg: string, public tokenType: HtmlTokenType, location: ParseLocation) {
|
||||||
|
super(location, errorMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HtmlTokenizeResult {
|
||||||
|
constructor(public tokens: HtmlToken[], public errors: HtmlTokenError[]) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function tokenizeHtml(sourceContent: string, sourceUrl: string): HtmlTokenizeResult {
|
||||||
|
return new _HtmlTokenizer(new ParseSourceFile(sourceContent, sourceUrl)).tokenize();
|
||||||
|
}
|
||||||
|
|
||||||
|
const $EOF = 0;
|
||||||
|
const $TAB = 9;
|
||||||
|
const $LF = 10;
|
||||||
|
const $CR = 13;
|
||||||
|
|
||||||
|
const $SPACE = 32;
|
||||||
|
|
||||||
|
const $BANG = 33;
|
||||||
|
const $DQ = 34;
|
||||||
|
const $$ = 36;
|
||||||
|
const $AMPERSAND = 38;
|
||||||
|
const $SQ = 39;
|
||||||
|
const $MINUS = 45;
|
||||||
|
const $SLASH = 47;
|
||||||
|
const $0 = 48;
|
||||||
|
|
||||||
|
const $SEMICOLON = 59;
|
||||||
|
|
||||||
|
const $9 = 57;
|
||||||
|
const $COLON = 58;
|
||||||
|
const $LT = 60;
|
||||||
|
const $EQ = 61;
|
||||||
|
const $GT = 62;
|
||||||
|
const $QUESTION = 63;
|
||||||
|
const $A = 65;
|
||||||
|
const $Z = 90;
|
||||||
|
const $LBRACKET = 91;
|
||||||
|
const $RBRACKET = 93;
|
||||||
|
const $a = 97;
|
||||||
|
const $z = 122;
|
||||||
|
|
||||||
|
const $NBSP = 160;
|
||||||
|
|
||||||
|
function unexpectedCharacterErrorMsg(charCode: number): string {
|
||||||
|
var char = charCode === $EOF ? 'EOF' : StringWrapper.fromCharCode(charCode);
|
||||||
|
return `Unexpected character "${char}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function unknownEntityErrorMsg(entitySrc: string): string {
|
||||||
|
return `Unknown entity "${entitySrc}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ControlFlowError {
|
||||||
|
constructor(public error: HtmlTokenError) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// See http://www.w3.org/TR/html51/syntax.html#writing
|
||||||
|
class _HtmlTokenizer {
|
||||||
|
private input: string;
|
||||||
|
private inputLowercase: string;
|
||||||
|
private length: number;
|
||||||
|
// Note: this is always lowercase!
|
||||||
|
private peek: number = -1;
|
||||||
|
private index: number = -1;
|
||||||
|
private line: number = 0;
|
||||||
|
private column: number = -1;
|
||||||
|
private currentTokenStart: ParseLocation;
|
||||||
|
private currentTokenType: HtmlTokenType;
|
||||||
|
|
||||||
|
tokens: HtmlToken[] = [];
|
||||||
|
errors: HtmlTokenError[] = [];
|
||||||
|
|
||||||
|
constructor(private file: ParseSourceFile) {
|
||||||
|
this.input = file.content;
|
||||||
|
this.inputLowercase = file.content.toLowerCase();
|
||||||
|
this.length = file.content.length;
|
||||||
|
this._advance();
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenize(): HtmlTokenizeResult {
|
||||||
|
while (this.peek !== $EOF) {
|
||||||
|
var start = this._getLocation();
|
||||||
|
try {
|
||||||
|
if (this._attemptChar($LT)) {
|
||||||
|
if (this._attemptChar($BANG)) {
|
||||||
|
if (this._attemptChar($LBRACKET)) {
|
||||||
|
this._consumeCdata(start);
|
||||||
|
} else if (this._attemptChar($MINUS)) {
|
||||||
|
this._consumeComment(start);
|
||||||
|
} else {
|
||||||
|
this._consumeDocType(start);
|
||||||
|
}
|
||||||
|
} else if (this._attemptChar($SLASH)) {
|
||||||
|
this._consumeTagClose(start);
|
||||||
|
} else {
|
||||||
|
this._consumeTagOpen(start);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this._consumeText();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ControlFlowError) {
|
||||||
|
this.errors.push(e.error);
|
||||||
|
} else {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this._beginToken(HtmlTokenType.EOF);
|
||||||
|
this._endToken([]);
|
||||||
|
return new HtmlTokenizeResult(this.tokens, this.errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getLocation(): ParseLocation {
|
||||||
|
return new ParseLocation(this.file, this.index, this.line, this.column);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _beginToken(type: HtmlTokenType, start: ParseLocation = null) {
|
||||||
|
if (isBlank(start)) {
|
||||||
|
start = this._getLocation();
|
||||||
|
}
|
||||||
|
this.currentTokenStart = start;
|
||||||
|
this.currentTokenType = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _endToken(parts: string[], end: ParseLocation = null): HtmlToken {
|
||||||
|
if (isBlank(end)) {
|
||||||
|
end = this._getLocation();
|
||||||
|
}
|
||||||
|
var token = new HtmlToken(this.currentTokenType, parts,
|
||||||
|
new ParseSourceSpan(this.currentTokenStart, end));
|
||||||
|
this.tokens.push(token);
|
||||||
|
this.currentTokenStart = null;
|
||||||
|
this.currentTokenType = null;
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _createError(msg: string, position: ParseLocation): ControlFlowError {
|
||||||
|
var error = new HtmlTokenError(msg, this.currentTokenType, position);
|
||||||
|
this.currentTokenStart = null;
|
||||||
|
this.currentTokenType = null;
|
||||||
|
return new ControlFlowError(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _advance() {
|
||||||
|
if (this.index >= this.length) {
|
||||||
|
throw this._createError(unexpectedCharacterErrorMsg($EOF), this._getLocation());
|
||||||
|
}
|
||||||
|
if (this.peek === $LF) {
|
||||||
|
this.line++;
|
||||||
|
this.column = 0;
|
||||||
|
} else if (this.peek !== $LF && this.peek !== $CR) {
|
||||||
|
this.column++;
|
||||||
|
}
|
||||||
|
this.index++;
|
||||||
|
this.peek = this.index >= this.length ? $EOF : StringWrapper.charCodeAt(this.inputLowercase,
|
||||||
|
this.index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _attemptChar(charCode: number): boolean {
|
||||||
|
if (this.peek === charCode) {
|
||||||
|
this._advance();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _requireChar(charCode: number) {
|
||||||
|
var location = this._getLocation();
|
||||||
|
if (!this._attemptChar(charCode)) {
|
||||||
|
throw this._createError(unexpectedCharacterErrorMsg(this.peek), location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _attemptChars(chars: string): boolean {
|
||||||
|
for (var i = 0; i < chars.length; i++) {
|
||||||
|
if (!this._attemptChar(StringWrapper.charCodeAt(chars, i))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _requireChars(chars: string) {
|
||||||
|
var location = this._getLocation();
|
||||||
|
if (!this._attemptChars(chars)) {
|
||||||
|
throw this._createError(unexpectedCharacterErrorMsg(this.peek), location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _attemptUntilFn(predicate: Function) {
|
||||||
|
while (!predicate(this.peek)) {
|
||||||
|
this._advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _requireUntilFn(predicate: Function, len: number) {
|
||||||
|
var start = this._getLocation();
|
||||||
|
this._attemptUntilFn(predicate);
|
||||||
|
if (this.index - start.offset < len) {
|
||||||
|
throw this._createError(unexpectedCharacterErrorMsg(this.peek), start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _attemptUntilChar(char: number) {
|
||||||
|
while (this.peek !== char) {
|
||||||
|
this._advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _readChar(decodeEntities: boolean): string {
|
||||||
|
if (decodeEntities && this.peek === $AMPERSAND) {
|
||||||
|
var start = this._getLocation();
|
||||||
|
this._attemptUntilChar($SEMICOLON);
|
||||||
|
this._advance();
|
||||||
|
var entitySrc = this.input.substring(start.offset + 1, this.index - 1);
|
||||||
|
var decodedEntity = decodeEntity(entitySrc);
|
||||||
|
if (isPresent(decodedEntity)) {
|
||||||
|
return decodedEntity;
|
||||||
|
} else {
|
||||||
|
throw this._createError(unknownEntityErrorMsg(entitySrc), start);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var index = this.index;
|
||||||
|
this._advance();
|
||||||
|
return this.input[index];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeRawText(decodeEntities: boolean, firstCharOfEnd: number,
|
||||||
|
attemptEndRest: Function): HtmlToken {
|
||||||
|
var tagCloseStart;
|
||||||
|
var textStart = this._getLocation();
|
||||||
|
this._beginToken(decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT,
|
||||||
|
textStart);
|
||||||
|
var parts = [];
|
||||||
|
while (true) {
|
||||||
|
tagCloseStart = this._getLocation();
|
||||||
|
if (this._attemptChar(firstCharOfEnd) && attemptEndRest()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (this.index > tagCloseStart.offset) {
|
||||||
|
parts.push(this.input.substring(tagCloseStart.offset, this.index));
|
||||||
|
}
|
||||||
|
while (this.peek !== firstCharOfEnd) {
|
||||||
|
parts.push(this._readChar(decodeEntities));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this._endToken([parts.join('')], tagCloseStart);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeComment(start: ParseLocation) {
|
||||||
|
this._beginToken(HtmlTokenType.COMMENT_START, start);
|
||||||
|
this._requireChar($MINUS);
|
||||||
|
this._endToken([]);
|
||||||
|
var textToken = this._consumeRawText(false, $MINUS, () => this._attemptChars('->'));
|
||||||
|
this._beginToken(HtmlTokenType.COMMENT_END, textToken.sourceSpan.end);
|
||||||
|
this._endToken([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeCdata(start: ParseLocation) {
|
||||||
|
this._beginToken(HtmlTokenType.CDATA_START, start);
|
||||||
|
this._requireChars('cdata[');
|
||||||
|
this._endToken([]);
|
||||||
|
var textToken = this._consumeRawText(false, $RBRACKET, () => this._attemptChars(']>'));
|
||||||
|
this._beginToken(HtmlTokenType.CDATA_END, textToken.sourceSpan.end);
|
||||||
|
this._endToken([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeDocType(start: ParseLocation) {
|
||||||
|
this._beginToken(HtmlTokenType.DOC_TYPE, start);
|
||||||
|
this._attemptUntilChar($GT);
|
||||||
|
this._advance();
|
||||||
|
this._endToken([this.input.substring(start.offset + 2, this.index - 1)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumePrefixAndName(): string[] {
|
||||||
|
var nameOrPrefixStart = this.index;
|
||||||
|
var prefix = null;
|
||||||
|
while (this.peek !== $COLON && !isPrefixEnd(this.peek)) {
|
||||||
|
this._advance();
|
||||||
|
}
|
||||||
|
var nameStart;
|
||||||
|
if (this.peek === $COLON) {
|
||||||
|
this._advance();
|
||||||
|
prefix = this.input.substring(nameOrPrefixStart, this.index - 1);
|
||||||
|
nameStart = this.index;
|
||||||
|
} else {
|
||||||
|
nameStart = nameOrPrefixStart;
|
||||||
|
}
|
||||||
|
this._requireUntilFn(isNameEnd, this.index === nameStart ? 1 : 0);
|
||||||
|
var name = this.input.substring(nameStart, this.index);
|
||||||
|
return [prefix, name];
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeTagOpen(start: ParseLocation) {
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
var nameStart = this.index;
|
||||||
|
this._consumeTagOpenStart(start);
|
||||||
|
var lowercaseTagName = this.inputLowercase.substring(nameStart, this.index);
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
while (this.peek !== $SLASH && this.peek !== $GT) {
|
||||||
|
this._consumeAttributeName();
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
if (this._attemptChar($EQ)) {
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
this._consumeAttributeValue();
|
||||||
|
}
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
}
|
||||||
|
this._consumeTagOpenEnd();
|
||||||
|
var contentTokenType = getHtmlTagDefinition(lowercaseTagName).contentType;
|
||||||
|
if (contentTokenType === HtmlTagContentType.RAW_TEXT) {
|
||||||
|
this._consumeRawTextWithTagClose(lowercaseTagName, false);
|
||||||
|
} else if (contentTokenType === HtmlTagContentType.ESCAPABLE_RAW_TEXT) {
|
||||||
|
this._consumeRawTextWithTagClose(lowercaseTagName, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeRawTextWithTagClose(lowercaseTagName: string, decodeEntities: boolean) {
|
||||||
|
var textToken = this._consumeRawText(decodeEntities, $LT, () => {
|
||||||
|
if (!this._attemptChar($SLASH)) return false;
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
if (!this._attemptChars(lowercaseTagName)) return false;
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
if (!this._attemptChar($GT)) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
this._beginToken(HtmlTokenType.TAG_CLOSE, textToken.sourceSpan.end);
|
||||||
|
this._endToken([null, lowercaseTagName]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeTagOpenStart(start: ParseLocation) {
|
||||||
|
this._beginToken(HtmlTokenType.TAG_OPEN_START, start);
|
||||||
|
var parts = this._consumePrefixAndName();
|
||||||
|
this._endToken(parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeAttributeName() {
|
||||||
|
this._beginToken(HtmlTokenType.ATTR_NAME);
|
||||||
|
var prefixAndName = this._consumePrefixAndName();
|
||||||
|
this._endToken(prefixAndName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeAttributeValue() {
|
||||||
|
this._beginToken(HtmlTokenType.ATTR_VALUE);
|
||||||
|
var value;
|
||||||
|
if (this.peek === $SQ || this.peek === $DQ) {
|
||||||
|
var quoteChar = this.peek;
|
||||||
|
this._advance();
|
||||||
|
var parts = [];
|
||||||
|
while (this.peek !== quoteChar) {
|
||||||
|
parts.push(this._readChar(true));
|
||||||
|
}
|
||||||
|
value = parts.join('');
|
||||||
|
this._advance();
|
||||||
|
} else {
|
||||||
|
var valueStart = this.index;
|
||||||
|
this._requireUntilFn(isNameEnd, 1);
|
||||||
|
value = this.input.substring(valueStart, this.index);
|
||||||
|
}
|
||||||
|
this._endToken([value]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeTagOpenEnd() {
|
||||||
|
var tokenType =
|
||||||
|
this._attemptChar($SLASH) ? HtmlTokenType.TAG_OPEN_END_VOID : HtmlTokenType.TAG_OPEN_END;
|
||||||
|
this._beginToken(tokenType);
|
||||||
|
this._requireChar($GT);
|
||||||
|
this._endToken([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeTagClose(start: ParseLocation) {
|
||||||
|
this._beginToken(HtmlTokenType.TAG_CLOSE, start);
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
var prefixAndName;
|
||||||
|
prefixAndName = this._consumePrefixAndName();
|
||||||
|
this._attemptUntilFn(isNotWhitespace);
|
||||||
|
this._requireChar($GT);
|
||||||
|
this._endToken(prefixAndName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeText() {
|
||||||
|
var start = this._getLocation();
|
||||||
|
this._beginToken(HtmlTokenType.TEXT, start);
|
||||||
|
var parts = [this._readChar(true)];
|
||||||
|
while (!isTextEnd(this.peek)) {
|
||||||
|
parts.push(this._readChar(true));
|
||||||
|
}
|
||||||
|
this._endToken([parts.join('')]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNotWhitespace(code: number): boolean {
|
||||||
|
return !isWhitespace(code) || code === $EOF;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWhitespace(code: number): boolean {
|
||||||
|
return (code >= $TAB && code <= $SPACE) || (code === $NBSP);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNameEnd(code: number): boolean {
|
||||||
|
return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ ||
|
||||||
|
code === $EQ
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPrefixEnd(code: number): boolean {
|
||||||
|
return (code < $a || $z < code) && (code < $A || $Z < code) && (code < $0 || code > $9);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTextEnd(code: number): boolean {
|
||||||
|
return code === $LT || code === $EOF;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeEntity(entity: string): string {
|
||||||
|
var i = 0;
|
||||||
|
var isNumber = entity.length > i && entity[i] == '#';
|
||||||
|
if (isNumber) i++;
|
||||||
|
var isHex = entity.length > i && entity[i] == 'x';
|
||||||
|
if (isHex) i++;
|
||||||
|
var value = entity.substring(i);
|
||||||
|
var result = null;
|
||||||
|
if (isNumber) {
|
||||||
|
var charCode;
|
||||||
|
try {
|
||||||
|
charCode = NumberWrapper.parseInt(value, isHex ? 16 : 10);
|
||||||
|
} catch (e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
result = StringWrapper.fromCharCode(charCode);
|
||||||
|
} else {
|
||||||
|
result = NAMED_ENTITIES[value];
|
||||||
|
}
|
||||||
|
if (isPresent(result)) {
|
||||||
|
return result;
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,118 +1,248 @@
|
||||||
import {
|
import {
|
||||||
isPresent,
|
isPresent,
|
||||||
|
isBlank,
|
||||||
StringWrapper,
|
StringWrapper,
|
||||||
stringify,
|
stringify,
|
||||||
assertionsEnabled,
|
assertionsEnabled,
|
||||||
StringJoiner
|
StringJoiner,
|
||||||
|
RegExpWrapper,
|
||||||
|
serializeEnum,
|
||||||
|
CONST_EXPR
|
||||||
} from 'angular2/src/facade/lang';
|
} from 'angular2/src/facade/lang';
|
||||||
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
import {DOM} from 'angular2/src/core/dom/dom_adapter';
|
||||||
|
import {ListWrapper} from 'angular2/src/facade/collection';
|
||||||
|
|
||||||
import {
|
import {HtmlAst, HtmlAttrAst, HtmlTextAst, HtmlElementAst} from './html_ast';
|
||||||
HtmlAst,
|
|
||||||
HtmlAttrAst,
|
|
||||||
HtmlTextAst,
|
|
||||||
HtmlElementAst,
|
|
||||||
HtmlAstVisitor,
|
|
||||||
htmlVisitAll
|
|
||||||
} from './html_ast';
|
|
||||||
|
|
||||||
import {escapeDoubleQuoteString} from './util';
|
import {escapeDoubleQuoteString} from './util';
|
||||||
import {Injectable} from 'angular2/src/core/di';
|
import {Injectable} from 'angular2/src/core/di';
|
||||||
|
import {HtmlToken, HtmlTokenType, tokenizeHtml} from './html_lexer';
|
||||||
|
import {ParseError, ParseLocation, ParseSourceSpan} from './parse_util';
|
||||||
|
import {HtmlTagDefinition, getHtmlTagDefinition} from './html_tags';
|
||||||
|
|
||||||
|
// TODO: remove this, just provide a plain error message!
|
||||||
|
export enum HtmlTreeErrorType {
|
||||||
|
UnexpectedClosingTag
|
||||||
|
}
|
||||||
|
|
||||||
|
const HTML_ERROR_TYPE_MSGS = CONST_EXPR(['Unexpected closing tag']);
|
||||||
|
|
||||||
|
|
||||||
|
export class HtmlTreeError extends ParseError {
|
||||||
|
static create(type: HtmlTreeErrorType, elementName: string,
|
||||||
|
location: ParseLocation): HtmlTreeError {
|
||||||
|
return new HtmlTreeError(type, HTML_ERROR_TYPE_MSGS[serializeEnum(type)], elementName,
|
||||||
|
location);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(public type: HtmlTreeErrorType, msg: string, public elementName: string,
|
||||||
|
location: ParseLocation) {
|
||||||
|
super(location, msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HtmlParseTreeResult {
|
||||||
|
constructor(public rootNodes: HtmlAst[], public errors: ParseError[]) {}
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class HtmlParser {
|
export class HtmlParser {
|
||||||
parse(template: string, sourceInfo: string): HtmlAst[] {
|
parse(sourceContent: string, sourceUrl: string): HtmlParseTreeResult {
|
||||||
var root = DOM.createTemplate(template);
|
var tokensAndErrors = tokenizeHtml(sourceContent, sourceUrl);
|
||||||
return parseChildNodes(root, sourceInfo);
|
var treeAndErrors = new TreeBuilder(tokensAndErrors.tokens).build();
|
||||||
}
|
return new HtmlParseTreeResult(treeAndErrors.rootNodes, (<ParseError[]>tokensAndErrors.errors)
|
||||||
unparse(nodes: HtmlAst[]): string {
|
.concat(treeAndErrors.errors));
|
||||||
var visitor = new UnparseVisitor();
|
|
||||||
var parts = [];
|
|
||||||
htmlVisitAll(visitor, nodes, parts);
|
|
||||||
return parts.join('');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseText(text: Text, indexInParent: number, parentSourceInfo: string): HtmlTextAst {
|
var NS_PREFIX_RE = /^@[^:]+/g;
|
||||||
// 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,
|
class TreeBuilder {
|
||||||
attrValue: string): HtmlAttrAst {
|
private index: number = -1;
|
||||||
// TODO(tbosch): add source row/column source info from parse5 / package:html
|
private length: number;
|
||||||
return new HtmlAttrAst(attrName, attrValue, `${parentSourceInfo}[${attrName}=${attrValue}]`);
|
private peek: HtmlToken;
|
||||||
}
|
|
||||||
|
|
||||||
function parseElement(element: Element, indexInParent: number,
|
private rootNodes: HtmlAst[] = [];
|
||||||
parentSourceInfo: string): HtmlElementAst {
|
private errors: HtmlTreeError[] = [];
|
||||||
// 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 = parseChildNodes(element, sourceInfo);
|
private elementStack: HtmlElementAst[] = [];
|
||||||
return new HtmlElementAst(nodeName, attrs, childNodes, sourceInfo);
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseAttrs(element: Element, elementSourceInfo: string): HtmlAttrAst[] {
|
constructor(private tokens: HtmlToken[]) { this._advance(); }
|
||||||
// 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[][] = [];
|
|
||||||
attrMap.forEach((value, name) => attrList.push([name, value]));
|
|
||||||
attrList.sort((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[] {
|
build(): HtmlParseTreeResult {
|
||||||
var root = DOM.templateAwareRoot(element);
|
while (this.peek.type !== HtmlTokenType.EOF) {
|
||||||
var childNodes = DOM.childNodesAsList(root);
|
if (this.peek.type === HtmlTokenType.TAG_OPEN_START) {
|
||||||
var result = [];
|
this._consumeStartTag(this._advance());
|
||||||
var index = 0;
|
} else if (this.peek.type === HtmlTokenType.TAG_CLOSE) {
|
||||||
childNodes.forEach(childNode => {
|
this._consumeEndTag(this._advance());
|
||||||
var childResult = null;
|
} else if (this.peek.type === HtmlTokenType.CDATA_START) {
|
||||||
if (DOM.isTextNode(childNode)) {
|
this._consumeCdata(this._advance());
|
||||||
var text = <Text>childNode;
|
} else if (this.peek.type === HtmlTokenType.COMMENT_START) {
|
||||||
childResult = parseText(text, index, parentSourceInfo);
|
this._consumeComment(this._advance());
|
||||||
} else if (DOM.isElementNode(childNode)) {
|
} else if (this.peek.type === HtmlTokenType.TEXT ||
|
||||||
var el = <Element>childNode;
|
this.peek.type === HtmlTokenType.RAW_TEXT ||
|
||||||
childResult = parseElement(el, index, parentSourceInfo);
|
this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) {
|
||||||
|
this._consumeText(this._advance());
|
||||||
|
} else {
|
||||||
|
// Skip all other tokens...
|
||||||
|
this._advance();
|
||||||
}
|
}
|
||||||
if (isPresent(childResult)) {
|
|
||||||
// Won't have a childResult for e.g. comment nodes
|
|
||||||
result.push(childResult);
|
|
||||||
}
|
}
|
||||||
index++;
|
return new HtmlParseTreeResult(this.rootNodes, this.errors);
|
||||||
});
|
}
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
class UnparseVisitor implements HtmlAstVisitor {
|
private _advance(): HtmlToken {
|
||||||
visitElement(ast: HtmlElementAst, parts: string[]): any {
|
var prev = this.peek;
|
||||||
parts.push(`<${ast.name}`);
|
if (this.index < this.tokens.length - 1) {
|
||||||
|
// Note: there is always an EOF token at the end
|
||||||
|
this.index++;
|
||||||
|
}
|
||||||
|
this.peek = this.tokens[this.index];
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _advanceIf(type: HtmlTokenType): HtmlToken {
|
||||||
|
if (this.peek.type === type) {
|
||||||
|
return this._advance();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeCdata(startToken: HtmlToken) {
|
||||||
|
this._consumeText(this._advance());
|
||||||
|
this._advanceIf(HtmlTokenType.CDATA_END);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeComment(startToken: HtmlToken) {
|
||||||
|
this._advanceIf(HtmlTokenType.RAW_TEXT);
|
||||||
|
this._advanceIf(HtmlTokenType.COMMENT_END);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeText(token: HtmlToken) {
|
||||||
|
this._addToParent(new HtmlTextAst(token.parts[0], token.sourceSpan));
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeStartTag(startTagToken: HtmlToken) {
|
||||||
|
var prefix = startTagToken.parts[0];
|
||||||
|
var name = startTagToken.parts[1];
|
||||||
var attrs = [];
|
var attrs = [];
|
||||||
htmlVisitAll(this, ast.attrs, attrs);
|
while (this.peek.type === HtmlTokenType.ATTR_NAME) {
|
||||||
if (ast.attrs.length > 0) {
|
attrs.push(this._consumeAttr(this._advance()));
|
||||||
parts.push(' ');
|
|
||||||
parts.push(attrs.join(' '));
|
|
||||||
}
|
}
|
||||||
parts.push(`>`);
|
var fullName = elementName(prefix, name, this._getParentElement());
|
||||||
htmlVisitAll(this, ast.children, parts);
|
var voidElement = false;
|
||||||
parts.push(`</${ast.name}>`);
|
// Note: There could have been a tokenizer error
|
||||||
return null;
|
// so that we don't get a token for the end tag...
|
||||||
|
if (this.peek.type === HtmlTokenType.TAG_OPEN_END_VOID) {
|
||||||
|
this._advance();
|
||||||
|
voidElement = true;
|
||||||
|
} else if (this.peek.type === HtmlTokenType.TAG_OPEN_END) {
|
||||||
|
this._advance();
|
||||||
|
voidElement = false;
|
||||||
}
|
}
|
||||||
visitAttr(ast: HtmlAttrAst, parts: string[]): any {
|
var end = this.peek.sourceSpan.start;
|
||||||
parts.push(`${ast.name}=${escapeDoubleQuoteString(ast.value)}`);
|
var el = new HtmlElementAst(fullName, attrs, [],
|
||||||
return null;
|
new ParseSourceSpan(startTagToken.sourceSpan.start, end));
|
||||||
|
this._pushElement(el);
|
||||||
|
if (voidElement) {
|
||||||
|
this._popElement(fullName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _pushElement(el: HtmlElementAst) {
|
||||||
|
var stackIndex = this.elementStack.length - 1;
|
||||||
|
while (stackIndex >= 0) {
|
||||||
|
var parentEl = this.elementStack[stackIndex];
|
||||||
|
if (!getHtmlTagDefinition(parentEl.name).isClosedByChild(el.name)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
stackIndex--;
|
||||||
|
}
|
||||||
|
this.elementStack.splice(stackIndex, this.elementStack.length - 1 - stackIndex);
|
||||||
|
|
||||||
|
var tagDef = getHtmlTagDefinition(el.name);
|
||||||
|
var parentEl = this._getParentElement();
|
||||||
|
if (tagDef.requireExtraParent(isPresent(parentEl) ? parentEl.name : null)) {
|
||||||
|
var newParent = new HtmlElementAst(tagDef.requiredParent, [], [el], el.sourceSpan);
|
||||||
|
this._addToParent(newParent);
|
||||||
|
this.elementStack.push(newParent);
|
||||||
|
this.elementStack.push(el);
|
||||||
|
} else {
|
||||||
|
this._addToParent(el);
|
||||||
|
this.elementStack.push(el);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeEndTag(endTagToken: HtmlToken) {
|
||||||
|
var fullName =
|
||||||
|
elementName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
|
||||||
|
if (!this._popElement(fullName)) {
|
||||||
|
this.errors.push(HtmlTreeError.create(HtmlTreeErrorType.UnexpectedClosingTag, fullName,
|
||||||
|
endTagToken.sourceSpan.start));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _popElement(fullName: string): boolean {
|
||||||
|
var stackIndex = this.elementStack.length - 1;
|
||||||
|
var hasError = false;
|
||||||
|
while (stackIndex >= 0) {
|
||||||
|
var el = this.elementStack[stackIndex];
|
||||||
|
if (el.name == fullName) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!getHtmlTagDefinition(el.name).closedByParent) {
|
||||||
|
hasError = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
stackIndex--;
|
||||||
|
}
|
||||||
|
if (!hasError) {
|
||||||
|
this.elementStack.splice(stackIndex, this.elementStack.length - stackIndex);
|
||||||
|
}
|
||||||
|
return !hasError;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _consumeAttr(attrName: HtmlToken): HtmlAttrAst {
|
||||||
|
var fullName = elementName(attrName.parts[0], attrName.parts[1], null);
|
||||||
|
var end = attrName.sourceSpan.end;
|
||||||
|
var value = '';
|
||||||
|
if (this.peek.type === HtmlTokenType.ATTR_VALUE) {
|
||||||
|
var valueToken = this._advance();
|
||||||
|
value = valueToken.parts[0];
|
||||||
|
end = valueToken.sourceSpan.end;
|
||||||
|
}
|
||||||
|
return new HtmlAttrAst(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end));
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getParentElement(): HtmlElementAst {
|
||||||
|
return this.elementStack.length > 0 ? ListWrapper.last(this.elementStack) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _addToParent(node: HtmlAst) {
|
||||||
|
var parent = this._getParentElement();
|
||||||
|
if (isPresent(parent)) {
|
||||||
|
parent.children.push(node);
|
||||||
|
} else {
|
||||||
|
this.rootNodes.push(node);
|
||||||
}
|
}
|
||||||
visitText(ast: HtmlTextAst, parts: string[]): any {
|
|
||||||
parts.push(ast.value);
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function elementName(prefix: string, localName: string, parentElement: HtmlElementAst) {
|
||||||
|
if (isBlank(prefix)) {
|
||||||
|
prefix = getHtmlTagDefinition(localName).implicitNamespacePrefix;
|
||||||
|
}
|
||||||
|
if (isBlank(prefix) && isPresent(parentElement)) {
|
||||||
|
prefix = namespacePrefix(parentElement.name);
|
||||||
|
}
|
||||||
|
if (isPresent(prefix)) {
|
||||||
|
return `@${prefix}:${localName}`;
|
||||||
|
} else {
|
||||||
|
return localName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function namespacePrefix(elementName: string): string {
|
||||||
|
var match = RegExpWrapper.firstMatch(NS_PREFIX_RE, elementName);
|
||||||
|
return isBlank(match) ? null : match[1];
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,69 @@
|
||||||
|
import {isPresent, isBlank, normalizeBool, CONST_EXPR} from 'angular2/src/facade/lang';
|
||||||
|
|
||||||
|
// TODO: fill this!
|
||||||
|
export const NAMED_ENTITIES: {[key: string]: string} = <any>CONST_EXPR({'amp': '&'});
|
||||||
|
|
||||||
|
export enum HtmlTagContentType {
|
||||||
|
RAW_TEXT,
|
||||||
|
ESCAPABLE_RAW_TEXT,
|
||||||
|
PARSABLE_DATA
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HtmlTagDefinition {
|
||||||
|
private closedByChildren: {[key: string]: boolean} = {};
|
||||||
|
public closedByParent: boolean;
|
||||||
|
public requiredParent: string;
|
||||||
|
public implicitNamespacePrefix: string;
|
||||||
|
public contentType: HtmlTagContentType;
|
||||||
|
|
||||||
|
constructor({closedByChildren, requiredParent, implicitNamespacePrefix, contentType}: {
|
||||||
|
closedByChildren?: string[],
|
||||||
|
requiredParent?: string,
|
||||||
|
implicitNamespacePrefix?: string,
|
||||||
|
contentType?: HtmlTagContentType
|
||||||
|
} = {}) {
|
||||||
|
if (isPresent(closedByChildren)) {
|
||||||
|
closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true);
|
||||||
|
}
|
||||||
|
this.closedByParent = isPresent(closedByChildren) && closedByChildren.length > 0;
|
||||||
|
this.requiredParent = requiredParent;
|
||||||
|
this.implicitNamespacePrefix = implicitNamespacePrefix;
|
||||||
|
this.contentType = isPresent(contentType) ? contentType : HtmlTagContentType.PARSABLE_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
requireExtraParent(currentParent: string) {
|
||||||
|
return isPresent(this.requiredParent) &&
|
||||||
|
(isBlank(currentParent) || this.requiredParent != currentParent.toLocaleLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
isClosedByChild(name: string) {
|
||||||
|
return normalizeBool(this.closedByChildren['*']) ||
|
||||||
|
normalizeBool(this.closedByChildren[name.toLowerCase()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Fill this table using
|
||||||
|
// https://github.com/greim/html-tokenizer/blob/master/parser.js
|
||||||
|
// and http://www.w3.org/TR/html51/syntax.html#optional-tags
|
||||||
|
var TAG_DEFINITIONS: {[key: string]: HtmlTagDefinition} = {
|
||||||
|
'link': new HtmlTagDefinition({closedByChildren: ['*']}),
|
||||||
|
'ng-content': new HtmlTagDefinition({closedByChildren: ['*']}),
|
||||||
|
'img': new HtmlTagDefinition({closedByChildren: ['*']}),
|
||||||
|
'input': new HtmlTagDefinition({closedByChildren: ['*']}),
|
||||||
|
'p': new HtmlTagDefinition({closedByChildren: ['p']}),
|
||||||
|
'tr': new HtmlTagDefinition({closedByChildren: ['tr'], requiredParent: 'tbody'}),
|
||||||
|
'col': new HtmlTagDefinition({closedByChildren: ['col'], requiredParent: 'colgroup'}),
|
||||||
|
'svg': new HtmlTagDefinition({implicitNamespacePrefix: 'svg'}),
|
||||||
|
'math': new HtmlTagDefinition({implicitNamespacePrefix: 'math'}),
|
||||||
|
'style': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}),
|
||||||
|
'script': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}),
|
||||||
|
'title': new HtmlTagDefinition({contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT}),
|
||||||
|
'textarea': new HtmlTagDefinition({contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT})
|
||||||
|
};
|
||||||
|
|
||||||
|
var DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
|
||||||
|
|
||||||
|
export function getHtmlTagDefinition(tagName: string): HtmlTagDefinition {
|
||||||
|
var result = TAG_DEFINITIONS[tagName.toLowerCase()];
|
||||||
|
return isPresent(result) ? result : DEFAULT_TAG_DEFINITION;
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
import {Math} from 'angular2/src/facade/math';
|
||||||
|
|
||||||
|
export class ParseLocation {
|
||||||
|
constructor(public file: ParseSourceFile, public offset: number, public line: number,
|
||||||
|
public col: number) {}
|
||||||
|
|
||||||
|
toString() { return `${this.file.url}@${this.line}:${this.col}`; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ParseSourceFile {
|
||||||
|
constructor(public content: string, public url: string) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class ParseError {
|
||||||
|
constructor(public location: ParseLocation, public msg: string) {}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
var source = this.location.file.content;
|
||||||
|
var ctxStart = Math.max(this.location.offset - 10, 0);
|
||||||
|
var ctxEnd = Math.min(this.location.offset + 10, source.length);
|
||||||
|
return `${this.msg} (${source.substring(ctxStart, ctxEnd)}): ${this.location}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ParseSourceSpan {
|
||||||
|
constructor(public start: ParseLocation, public end: ParseLocation) {}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.start.file.content.substring(this.start.offset, this.end.offset);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,32 +1,35 @@
|
||||||
import {AST} from 'angular2/src/core/change_detection/change_detection';
|
import {AST} from 'angular2/src/core/change_detection/change_detection';
|
||||||
import {isPresent} from 'angular2/src/facade/lang';
|
import {isPresent} from 'angular2/src/facade/lang';
|
||||||
import {CompileDirectiveMetadata} from './directive_metadata';
|
import {CompileDirectiveMetadata} from './directive_metadata';
|
||||||
|
import {ParseSourceSpan} from './parse_util';
|
||||||
|
|
||||||
export interface TemplateAst {
|
export interface TemplateAst {
|
||||||
sourceInfo: string;
|
sourceSpan: ParseSourceSpan;
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any;
|
visit(visitor: TemplateAstVisitor, context: any): any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TextAst implements TemplateAst {
|
export class TextAst implements TemplateAst {
|
||||||
constructor(public value: string, public ngContentIndex: number, public sourceInfo: string) {}
|
constructor(public value: string, public ngContentIndex: number,
|
||||||
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitText(this, context); }
|
visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitText(this, context); }
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BoundTextAst implements TemplateAst {
|
export class BoundTextAst implements TemplateAst {
|
||||||
constructor(public value: AST, public ngContentIndex: number, public sourceInfo: string) {}
|
constructor(public value: AST, public ngContentIndex: number,
|
||||||
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitBoundText(this, context);
|
return visitor.visitBoundText(this, context);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AttrAst implements TemplateAst {
|
export class AttrAst implements TemplateAst {
|
||||||
constructor(public name: string, public value: string, public sourceInfo: string) {}
|
constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitAttr(this, context); }
|
visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitAttr(this, context); }
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BoundElementPropertyAst implements TemplateAst {
|
export class BoundElementPropertyAst implements TemplateAst {
|
||||||
constructor(public name: string, public type: PropertyBindingType, public value: AST,
|
constructor(public name: string, public type: PropertyBindingType, public value: AST,
|
||||||
public unit: string, public sourceInfo: string) {}
|
public unit: string, public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitElementProperty(this, context);
|
return visitor.visitElementProperty(this, context);
|
||||||
}
|
}
|
||||||
|
@ -34,7 +37,7 @@ export class BoundElementPropertyAst implements TemplateAst {
|
||||||
|
|
||||||
export class BoundEventAst implements TemplateAst {
|
export class BoundEventAst implements TemplateAst {
|
||||||
constructor(public name: string, public target: string, public handler: AST,
|
constructor(public name: string, public target: string, public handler: AST,
|
||||||
public sourceInfo: string) {}
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitEvent(this, context);
|
return visitor.visitEvent(this, context);
|
||||||
}
|
}
|
||||||
|
@ -48,7 +51,7 @@ export class BoundEventAst implements TemplateAst {
|
||||||
}
|
}
|
||||||
|
|
||||||
export class VariableAst implements TemplateAst {
|
export class VariableAst implements TemplateAst {
|
||||||
constructor(public name: string, public value: string, public sourceInfo: string) {}
|
constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitVariable(this, context);
|
return visitor.visitVariable(this, context);
|
||||||
}
|
}
|
||||||
|
@ -59,7 +62,7 @@ export class ElementAst implements TemplateAst {
|
||||||
public inputs: BoundElementPropertyAst[], public outputs: BoundEventAst[],
|
public inputs: BoundElementPropertyAst[], public outputs: BoundEventAst[],
|
||||||
public exportAsVars: VariableAst[], public directives: DirectiveAst[],
|
public exportAsVars: VariableAst[], public directives: DirectiveAst[],
|
||||||
public children: TemplateAst[], public ngContentIndex: number,
|
public children: TemplateAst[], public ngContentIndex: number,
|
||||||
public sourceInfo: string) {}
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitElement(this, context);
|
return visitor.visitElement(this, context);
|
||||||
}
|
}
|
||||||
|
@ -79,7 +82,7 @@ export class ElementAst implements TemplateAst {
|
||||||
export class EmbeddedTemplateAst implements TemplateAst {
|
export class EmbeddedTemplateAst implements TemplateAst {
|
||||||
constructor(public attrs: AttrAst[], public outputs: BoundEventAst[], public vars: VariableAst[],
|
constructor(public attrs: AttrAst[], public outputs: BoundEventAst[], public vars: VariableAst[],
|
||||||
public directives: DirectiveAst[], public children: TemplateAst[],
|
public directives: DirectiveAst[], public children: TemplateAst[],
|
||||||
public ngContentIndex: number, public sourceInfo: string) {}
|
public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitEmbeddedTemplate(this, context);
|
return visitor.visitEmbeddedTemplate(this, context);
|
||||||
}
|
}
|
||||||
|
@ -87,7 +90,7 @@ export class EmbeddedTemplateAst implements TemplateAst {
|
||||||
|
|
||||||
export class BoundDirectivePropertyAst implements TemplateAst {
|
export class BoundDirectivePropertyAst implements TemplateAst {
|
||||||
constructor(public directiveName: string, public templateName: string, public value: AST,
|
constructor(public directiveName: string, public templateName: string, public value: AST,
|
||||||
public sourceInfo: string) {}
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitDirectiveProperty(this, context);
|
return visitor.visitDirectiveProperty(this, context);
|
||||||
}
|
}
|
||||||
|
@ -97,14 +100,15 @@ export class DirectiveAst implements TemplateAst {
|
||||||
constructor(public directive: CompileDirectiveMetadata,
|
constructor(public directive: CompileDirectiveMetadata,
|
||||||
public inputs: BoundDirectivePropertyAst[],
|
public inputs: BoundDirectivePropertyAst[],
|
||||||
public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[],
|
public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[],
|
||||||
public exportAsVars: VariableAst[], public sourceInfo: string) {}
|
public exportAsVars: VariableAst[], public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitDirective(this, context);
|
return visitor.visitDirective(this, context);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class NgContentAst implements TemplateAst {
|
export class NgContentAst implements TemplateAst {
|
||||||
constructor(public index: number, public ngContentIndex: number, public sourceInfo: string) {}
|
constructor(public index: number, public ngContentIndex: number,
|
||||||
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
visit(visitor: TemplateAstVisitor, context: any): any {
|
visit(visitor: TemplateAstVisitor, context: any): any {
|
||||||
return visitor.visitNgContent(this, context);
|
return visitor.visitNgContent(this, context);
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,7 +29,7 @@ import {preparseElement, PreparsedElement, PreparsedElementType} from './templat
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TemplateNormalizer {
|
export class TemplateNormalizer {
|
||||||
constructor(private _xhr: XHR, private _urlResolver: UrlResolver,
|
constructor(private _xhr: XHR, private _urlResolver: UrlResolver,
|
||||||
private _domParser: HtmlParser) {}
|
private _htmlParser: HtmlParser) {}
|
||||||
|
|
||||||
normalizeTemplate(directiveType: CompileTypeMetadata,
|
normalizeTemplate(directiveType: CompileTypeMetadata,
|
||||||
template: CompileTemplateMetadata): Promise<CompileTemplateMetadata> {
|
template: CompileTemplateMetadata): Promise<CompileTemplateMetadata> {
|
||||||
|
@ -48,9 +48,14 @@ export class TemplateNormalizer {
|
||||||
|
|
||||||
normalizeLoadedTemplate(directiveType: CompileTypeMetadata, templateMeta: CompileTemplateMetadata,
|
normalizeLoadedTemplate(directiveType: CompileTypeMetadata, templateMeta: CompileTemplateMetadata,
|
||||||
template: string, templateAbsUrl: string): CompileTemplateMetadata {
|
template: string, templateAbsUrl: string): CompileTemplateMetadata {
|
||||||
var domNodes = this._domParser.parse(template, directiveType.name);
|
var rootNodesAndErrors = this._htmlParser.parse(template, directiveType.name);
|
||||||
|
if (rootNodesAndErrors.errors.length > 0) {
|
||||||
|
var errorString = rootNodesAndErrors.errors.join('\n');
|
||||||
|
throw new BaseException(`Template parse errors:\n${errorString}`);
|
||||||
|
}
|
||||||
|
|
||||||
var visitor = new TemplatePreparseVisitor();
|
var visitor = new TemplatePreparseVisitor();
|
||||||
htmlVisitAll(visitor, domNodes);
|
htmlVisitAll(visitor, rootNodesAndErrors.rootNodes);
|
||||||
var allStyles = templateMeta.styles.concat(visitor.styles);
|
var allStyles = templateMeta.styles.concat(visitor.styles);
|
||||||
|
|
||||||
var allStyleAbsUrls =
|
var allStyleAbsUrls =
|
||||||
|
|
|
@ -19,6 +19,8 @@ import {Parser, AST, ASTWithSource} from 'angular2/src/core/change_detection/cha
|
||||||
import {TemplateBinding} from 'angular2/src/core/change_detection/parser/ast';
|
import {TemplateBinding} from 'angular2/src/core/change_detection/parser/ast';
|
||||||
import {CompileDirectiveMetadata} from './directive_metadata';
|
import {CompileDirectiveMetadata} from './directive_metadata';
|
||||||
import {HtmlParser} from './html_parser';
|
import {HtmlParser} from './html_parser';
|
||||||
|
import {ParseSourceSpan, ParseError, ParseLocation} from './parse_util';
|
||||||
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ElementAst,
|
ElementAst,
|
||||||
|
@ -69,25 +71,30 @@ const TEMPLATE_ATTR = 'template';
|
||||||
const TEMPLATE_ATTR_PREFIX = '*';
|
const TEMPLATE_ATTR_PREFIX = '*';
|
||||||
const CLASS_ATTR = 'class';
|
const CLASS_ATTR = 'class';
|
||||||
|
|
||||||
var PROPERTY_PARTS_SEPARATOR = new RegExp('\\.');
|
var PROPERTY_PARTS_SEPARATOR = '.';
|
||||||
const ATTRIBUTE_PREFIX = 'attr';
|
const ATTRIBUTE_PREFIX = 'attr';
|
||||||
const CLASS_PREFIX = 'class';
|
const CLASS_PREFIX = 'class';
|
||||||
const STYLE_PREFIX = 'style';
|
const STYLE_PREFIX = 'style';
|
||||||
|
|
||||||
var TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
|
var TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
|
||||||
|
|
||||||
|
export class TemplateParseError extends ParseError {
|
||||||
|
constructor(message: string, location: ParseLocation) { super(location, message); }
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TemplateParser {
|
export class TemplateParser {
|
||||||
constructor(private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry,
|
constructor(private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry,
|
||||||
private _htmlParser: HtmlParser) {}
|
private _htmlParser: HtmlParser) {}
|
||||||
|
|
||||||
parse(template: string, directives: CompileDirectiveMetadata[],
|
parse(template: string, directives: CompileDirectiveMetadata[],
|
||||||
sourceInfo: string): TemplateAst[] {
|
templateUrl: string): TemplateAst[] {
|
||||||
var parseVisitor = new TemplateParseVisitor(directives, this._exprParser, this._schemaRegistry);
|
var parseVisitor = new TemplateParseVisitor(directives, this._exprParser, this._schemaRegistry);
|
||||||
var result =
|
var htmlAstWithErrors = this._htmlParser.parse(template, templateUrl);
|
||||||
htmlVisitAll(parseVisitor, this._htmlParser.parse(template, sourceInfo), EMPTY_COMPONENT);
|
var result = htmlVisitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_COMPONENT);
|
||||||
if (parseVisitor.errors.length > 0) {
|
var errors: ParseError[] = htmlAstWithErrors.errors.concat(parseVisitor.errors);
|
||||||
var errorString = parseVisitor.errors.join('\n');
|
if (errors.length > 0) {
|
||||||
|
var errorString = errors.join('\n');
|
||||||
throw new BaseException(`Template parse errors:\n${errorString}`);
|
throw new BaseException(`Template parse errors:\n${errorString}`);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
|
@ -96,7 +103,7 @@ export class TemplateParser {
|
||||||
|
|
||||||
class TemplateParseVisitor implements HtmlAstVisitor {
|
class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
selectorMatcher: SelectorMatcher;
|
selectorMatcher: SelectorMatcher;
|
||||||
errors: string[] = [];
|
errors: TemplateParseError[] = [];
|
||||||
directivesIndex = new Map<CompileDirectiveMetadata, number>();
|
directivesIndex = new Map<CompileDirectiveMetadata, number>();
|
||||||
ngContentCount: number = 0;
|
ngContentCount: number = 0;
|
||||||
|
|
||||||
|
@ -111,56 +118,62 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private _reportError(message: string) { this.errors.push(message); }
|
private _reportError(message: string, sourceSpan: ParseSourceSpan) {
|
||||||
|
this.errors.push(new TemplateParseError(message, sourceSpan.start));
|
||||||
|
}
|
||||||
|
|
||||||
private _parseInterpolation(value: string, sourceInfo: string): ASTWithSource {
|
private _parseInterpolation(value: string, sourceSpan: ParseSourceSpan): ASTWithSource {
|
||||||
|
var sourceInfo = sourceSpan.start.toString();
|
||||||
try {
|
try {
|
||||||
return this._exprParser.parseInterpolation(value, sourceInfo);
|
return this._exprParser.parseInterpolation(value, sourceInfo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this._reportError(`${e}`); // sourceInfo is already contained in the AST
|
this._reportError(`${e}`, sourceSpan);
|
||||||
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
|
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseAction(value: string, sourceInfo: string): ASTWithSource {
|
private _parseAction(value: string, sourceSpan: ParseSourceSpan): ASTWithSource {
|
||||||
|
var sourceInfo = sourceSpan.start.toString();
|
||||||
try {
|
try {
|
||||||
return this._exprParser.parseAction(value, sourceInfo);
|
return this._exprParser.parseAction(value, sourceInfo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this._reportError(`${e}`); // sourceInfo is already contained in the AST
|
this._reportError(`${e}`, sourceSpan);
|
||||||
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
|
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseBinding(value: string, sourceInfo: string): ASTWithSource {
|
private _parseBinding(value: string, sourceSpan: ParseSourceSpan): ASTWithSource {
|
||||||
|
var sourceInfo = sourceSpan.start.toString();
|
||||||
try {
|
try {
|
||||||
return this._exprParser.parseBinding(value, sourceInfo);
|
return this._exprParser.parseBinding(value, sourceInfo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this._reportError(`${e}`); // sourceInfo is already contained in the AST
|
this._reportError(`${e}`, sourceSpan);
|
||||||
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
|
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseTemplateBindings(value: string, sourceInfo: string): TemplateBinding[] {
|
private _parseTemplateBindings(value: string, sourceSpan: ParseSourceSpan): TemplateBinding[] {
|
||||||
|
var sourceInfo = sourceSpan.start.toString();
|
||||||
try {
|
try {
|
||||||
return this._exprParser.parseTemplateBindings(value, sourceInfo);
|
return this._exprParser.parseTemplateBindings(value, sourceInfo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this._reportError(`${e}`); // sourceInfo is already contained in the AST
|
this._reportError(`${e}`, sourceSpan);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
visitText(ast: HtmlTextAst, component: Component): any {
|
visitText(ast: HtmlTextAst, component: Component): any {
|
||||||
var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
|
var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
|
||||||
var expr = this._parseInterpolation(ast.value, ast.sourceInfo);
|
var expr = this._parseInterpolation(ast.value, ast.sourceSpan);
|
||||||
if (isPresent(expr)) {
|
if (isPresent(expr)) {
|
||||||
return new BoundTextAst(expr, ngContentIndex, ast.sourceInfo);
|
return new BoundTextAst(expr, ngContentIndex, ast.sourceSpan);
|
||||||
} else {
|
} else {
|
||||||
return new TextAst(ast.value, ngContentIndex, ast.sourceInfo);
|
return new TextAst(ast.value, ngContentIndex, ast.sourceSpan);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
visitAttr(ast: HtmlAttrAst, contex: any): any {
|
visitAttr(ast: HtmlAttrAst, contex: any): any {
|
||||||
return new AttrAst(ast.name, ast.value, ast.sourceInfo);
|
return new AttrAst(ast.name, ast.value, ast.sourceSpan);
|
||||||
}
|
}
|
||||||
|
|
||||||
visitElement(element: HtmlElementAst, component: Component): any {
|
visitElement(element: HtmlElementAst, component: Component): any {
|
||||||
|
@ -176,8 +189,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
|
if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
|
||||||
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
|
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
|
||||||
// Skipping stylesheets with either relative urls or package scheme as we already processed
|
// Skipping stylesheets with either relative urls or package scheme as we already processed
|
||||||
// them
|
// them in the StyleCompiler
|
||||||
// in the StyleCompiler
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -191,6 +203,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
var templateMatchableAttrs: string[][] = [];
|
var templateMatchableAttrs: string[][] = [];
|
||||||
var hasInlineTemplates = false;
|
var hasInlineTemplates = false;
|
||||||
var attrs = [];
|
var attrs = [];
|
||||||
|
|
||||||
element.attrs.forEach(attr => {
|
element.attrs.forEach(attr => {
|
||||||
matchableAttrs.push([attr.name, attr.value]);
|
matchableAttrs.push([attr.name, attr.value]);
|
||||||
var hasBinding = this._parseAttr(attr, matchableAttrs, elementOrDirectiveProps, events, vars);
|
var hasBinding = this._parseAttr(attr, matchableAttrs, elementOrDirectiveProps, events, vars);
|
||||||
|
@ -204,11 +217,12 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
hasInlineTemplates = true;
|
hasInlineTemplates = true;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
var isTemplateElement = nodeName == TEMPLATE_ELEMENT;
|
var isTemplateElement = nodeName == TEMPLATE_ELEMENT;
|
||||||
var elementCssSelector = createElementCssSelector(nodeName, matchableAttrs);
|
var elementCssSelector = createElementCssSelector(nodeName, matchableAttrs);
|
||||||
var directives = this._createDirectiveAsts(
|
var directives = this._createDirectiveAsts(
|
||||||
element.name, this._parseDirectives(this.selectorMatcher, elementCssSelector),
|
element.name, this._parseDirectives(this.selectorMatcher, elementCssSelector),
|
||||||
elementOrDirectiveProps, isTemplateElement ? [] : vars, element.sourceInfo);
|
elementOrDirectiveProps, isTemplateElement ? [] : vars, element.sourceSpan);
|
||||||
var elementProps: BoundElementPropertyAst[] =
|
var elementProps: BoundElementPropertyAst[] =
|
||||||
this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directives);
|
this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directives);
|
||||||
var children = htmlVisitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this,
|
var children = htmlVisitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this,
|
||||||
|
@ -218,32 +232,32 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
var parsedElement;
|
var parsedElement;
|
||||||
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
|
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
|
||||||
parsedElement =
|
parsedElement =
|
||||||
new NgContentAst(this.ngContentCount++, elementNgContentIndex, element.sourceInfo);
|
new NgContentAst(this.ngContentCount++, elementNgContentIndex, element.sourceSpan);
|
||||||
} else if (isTemplateElement) {
|
} else if (isTemplateElement) {
|
||||||
this._assertAllEventsPublishedByDirectives(directives, events, element.sourceInfo);
|
this._assertAllEventsPublishedByDirectives(directives, events);
|
||||||
this._assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps,
|
this._assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps,
|
||||||
element.sourceInfo);
|
element.sourceSpan);
|
||||||
parsedElement = new EmbeddedTemplateAst(attrs, events, vars, directives, children,
|
parsedElement = new EmbeddedTemplateAst(attrs, events, vars, directives, children,
|
||||||
elementNgContentIndex, element.sourceInfo);
|
elementNgContentIndex, element.sourceSpan);
|
||||||
} else {
|
} else {
|
||||||
this._assertOnlyOneComponent(directives, element.sourceInfo);
|
this._assertOnlyOneComponent(directives, element.sourceSpan);
|
||||||
var elementExportAsVars = vars.filter(varAst => varAst.value.length === 0);
|
var elementExportAsVars = vars.filter(varAst => varAst.value.length === 0);
|
||||||
parsedElement =
|
parsedElement =
|
||||||
new ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives,
|
new ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives,
|
||||||
children, elementNgContentIndex, element.sourceInfo);
|
children, elementNgContentIndex, element.sourceSpan);
|
||||||
}
|
}
|
||||||
if (hasInlineTemplates) {
|
if (hasInlineTemplates) {
|
||||||
var templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs);
|
var templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs);
|
||||||
var templateDirectives = this._createDirectiveAsts(
|
var templateDirectives = this._createDirectiveAsts(
|
||||||
element.name, this._parseDirectives(this.selectorMatcher, templateCssSelector),
|
element.name, this._parseDirectives(this.selectorMatcher, templateCssSelector),
|
||||||
templateElementOrDirectiveProps, [], element.sourceInfo);
|
templateElementOrDirectiveProps, [], element.sourceSpan);
|
||||||
var templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(
|
var templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(
|
||||||
element.name, templateElementOrDirectiveProps, templateDirectives);
|
element.name, templateElementOrDirectiveProps, templateDirectives);
|
||||||
this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectives, templateElementProps,
|
this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectives, templateElementProps,
|
||||||
element.sourceInfo);
|
element.sourceSpan);
|
||||||
parsedElement = new EmbeddedTemplateAst(
|
parsedElement = new EmbeddedTemplateAst(
|
||||||
[], [], templateVars, templateDirectives, [parsedElement],
|
[], [], templateVars, templateDirectives, [parsedElement],
|
||||||
component.findNgContentIndex(templateCssSelector), element.sourceInfo);
|
component.findNgContentIndex(templateCssSelector), element.sourceSpan);
|
||||||
}
|
}
|
||||||
return parsedElement;
|
return parsedElement;
|
||||||
}
|
}
|
||||||
|
@ -259,20 +273,20 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value;
|
templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value;
|
||||||
}
|
}
|
||||||
if (isPresent(templateBindingsSource)) {
|
if (isPresent(templateBindingsSource)) {
|
||||||
var bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceInfo);
|
var bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan);
|
||||||
for (var i = 0; i < bindings.length; i++) {
|
for (var i = 0; i < bindings.length; i++) {
|
||||||
var binding = bindings[i];
|
var binding = bindings[i];
|
||||||
var dashCaseKey = camelCaseToDashCase(binding.key);
|
var dashCaseKey = camelCaseToDashCase(binding.key);
|
||||||
if (binding.keyIsVar) {
|
if (binding.keyIsVar) {
|
||||||
targetVars.push(
|
targetVars.push(
|
||||||
new VariableAst(dashCaseToCamelCase(binding.key), binding.name, attr.sourceInfo));
|
new VariableAst(dashCaseToCamelCase(binding.key), binding.name, attr.sourceSpan));
|
||||||
targetMatchableAttrs.push([dashCaseKey, binding.name]);
|
targetMatchableAttrs.push([dashCaseKey, binding.name]);
|
||||||
} else if (isPresent(binding.expression)) {
|
} else if (isPresent(binding.expression)) {
|
||||||
this._parsePropertyAst(dashCaseKey, binding.expression, attr.sourceInfo,
|
this._parsePropertyAst(dashCaseKey, binding.expression, attr.sourceSpan,
|
||||||
targetMatchableAttrs, targetProps);
|
targetMatchableAttrs, targetProps);
|
||||||
} else {
|
} else {
|
||||||
targetMatchableAttrs.push([dashCaseKey, '']);
|
targetMatchableAttrs.push([dashCaseKey, '']);
|
||||||
this._parseLiteralAttr(dashCaseKey, null, attr.sourceInfo, targetProps);
|
this._parseLiteralAttr(dashCaseKey, null, attr.sourceSpan, targetProps);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
@ -290,44 +304,44 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
if (isPresent(bindParts)) {
|
if (isPresent(bindParts)) {
|
||||||
hasBinding = true;
|
hasBinding = true;
|
||||||
if (isPresent(bindParts[1])) { // match: bind-prop
|
if (isPresent(bindParts[1])) { // match: bind-prop
|
||||||
this._parseProperty(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetProps);
|
targetProps);
|
||||||
|
|
||||||
} else if (isPresent(
|
} else if (isPresent(
|
||||||
bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden"
|
bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden"
|
||||||
var identifier = bindParts[5];
|
var identifier = bindParts[5];
|
||||||
this._parseVariable(identifier, attrValue, attr.sourceInfo, targetVars);
|
this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars);
|
||||||
|
|
||||||
} else if (isPresent(bindParts[3])) { // match: on-event
|
} else if (isPresent(bindParts[3])) { // match: on-event
|
||||||
this._parseEvent(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetEvents);
|
targetEvents);
|
||||||
|
|
||||||
} else if (isPresent(bindParts[4])) { // match: bindon-prop
|
} else if (isPresent(bindParts[4])) { // match: bindon-prop
|
||||||
this._parseProperty(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetProps);
|
targetProps);
|
||||||
this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetEvents);
|
targetEvents);
|
||||||
|
|
||||||
} else if (isPresent(bindParts[6])) { // match: [(expr)]
|
} else if (isPresent(bindParts[6])) { // match: [(expr)]
|
||||||
this._parseProperty(bindParts[6], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseProperty(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetProps);
|
targetProps);
|
||||||
this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetEvents);
|
targetEvents);
|
||||||
|
|
||||||
} else if (isPresent(bindParts[7])) { // match: [expr]
|
} else if (isPresent(bindParts[7])) { // match: [expr]
|
||||||
this._parseProperty(bindParts[7], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseProperty(bindParts[7], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetProps);
|
targetProps);
|
||||||
|
|
||||||
} else if (isPresent(bindParts[8])) { // match: (event)
|
} else if (isPresent(bindParts[8])) { // match: (event)
|
||||||
this._parseEvent(bindParts[8], attrValue, attr.sourceInfo, targetMatchableAttrs,
|
this._parseEvent(bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs,
|
||||||
targetEvents);
|
targetEvents);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceInfo,
|
hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceSpan,
|
||||||
targetMatchableAttrs, targetProps);
|
targetMatchableAttrs, targetProps);
|
||||||
}
|
}
|
||||||
if (!hasBinding) {
|
if (!hasBinding) {
|
||||||
this._parseLiteralAttr(attrName, attrValue, attr.sourceInfo, targetProps);
|
this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps);
|
||||||
}
|
}
|
||||||
return hasBinding;
|
return hasBinding;
|
||||||
}
|
}
|
||||||
|
@ -336,59 +350,59 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
return attrName.startsWith('data-') ? attrName.substring(5) : attrName;
|
return attrName.startsWith('data-') ? attrName.substring(5) : attrName;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseVariable(identifier: string, value: string, sourceInfo: any,
|
private _parseVariable(identifier: string, value: string, sourceSpan: ParseSourceSpan,
|
||||||
targetVars: VariableAst[]) {
|
targetVars: VariableAst[]) {
|
||||||
targetVars.push(new VariableAst(dashCaseToCamelCase(identifier), value, sourceInfo));
|
targetVars.push(new VariableAst(dashCaseToCamelCase(identifier), value, sourceSpan));
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseProperty(name: string, expression: string, sourceInfo: any,
|
private _parseProperty(name: string, expression: string, sourceSpan: ParseSourceSpan,
|
||||||
targetMatchableAttrs: string[][],
|
targetMatchableAttrs: string[][],
|
||||||
targetProps: BoundElementOrDirectiveProperty[]) {
|
targetProps: BoundElementOrDirectiveProperty[]) {
|
||||||
this._parsePropertyAst(name, this._parseBinding(expression, sourceInfo), sourceInfo,
|
this._parsePropertyAst(name, this._parseBinding(expression, sourceSpan), sourceSpan,
|
||||||
targetMatchableAttrs, targetProps);
|
targetMatchableAttrs, targetProps);
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parsePropertyInterpolation(name: string, value: string, sourceInfo: any,
|
private _parsePropertyInterpolation(name: string, value: string, sourceSpan: ParseSourceSpan,
|
||||||
targetMatchableAttrs: string[][],
|
targetMatchableAttrs: string[][],
|
||||||
targetProps: BoundElementOrDirectiveProperty[]): boolean {
|
targetProps: BoundElementOrDirectiveProperty[]): boolean {
|
||||||
var expr = this._parseInterpolation(value, sourceInfo);
|
var expr = this._parseInterpolation(value, sourceSpan);
|
||||||
if (isPresent(expr)) {
|
if (isPresent(expr)) {
|
||||||
this._parsePropertyAst(name, expr, sourceInfo, targetMatchableAttrs, targetProps);
|
this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parsePropertyAst(name: string, ast: ASTWithSource, sourceInfo: any,
|
private _parsePropertyAst(name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan,
|
||||||
targetMatchableAttrs: string[][],
|
targetMatchableAttrs: string[][],
|
||||||
targetProps: BoundElementOrDirectiveProperty[]) {
|
targetProps: BoundElementOrDirectiveProperty[]) {
|
||||||
targetMatchableAttrs.push([name, ast.source]);
|
targetMatchableAttrs.push([name, ast.source]);
|
||||||
targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceInfo));
|
targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan));
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseAssignmentEvent(name: string, expression: string, sourceInfo: string,
|
private _parseAssignmentEvent(name: string, expression: string, sourceSpan: ParseSourceSpan,
|
||||||
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
|
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
|
||||||
this._parseEvent(`${name}-change`, `${expression}=$event`, sourceInfo, targetMatchableAttrs,
|
this._parseEvent(`${name}-change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs,
|
||||||
targetEvents);
|
targetEvents);
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseEvent(name: string, expression: string, sourceInfo: string,
|
private _parseEvent(name: string, expression: string, sourceSpan: ParseSourceSpan,
|
||||||
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
|
targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) {
|
||||||
// long format: 'target: eventName'
|
// long format: 'target: eventName'
|
||||||
var parts = splitAtColon(name, [null, name]);
|
var parts = splitAtColon(name, [null, name]);
|
||||||
var target = parts[0];
|
var target = parts[0];
|
||||||
var eventName = parts[1];
|
var eventName = parts[1];
|
||||||
targetEvents.push(new BoundEventAst(dashCaseToCamelCase(eventName), target,
|
targetEvents.push(new BoundEventAst(dashCaseToCamelCase(eventName), target,
|
||||||
this._parseAction(expression, sourceInfo), sourceInfo));
|
this._parseAction(expression, sourceSpan), sourceSpan));
|
||||||
// Don't detect directives for event names for now,
|
// Don't detect directives for event names for now,
|
||||||
// so don't add the event name to the matchableAttrs
|
// so don't add the event name to the matchableAttrs
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseLiteralAttr(name: string, value: string, sourceInfo: string,
|
private _parseLiteralAttr(name: string, value: string, sourceSpan: ParseSourceSpan,
|
||||||
targetProps: BoundElementOrDirectiveProperty[]) {
|
targetProps: BoundElementOrDirectiveProperty[]) {
|
||||||
targetProps.push(new BoundElementOrDirectiveProperty(
|
targetProps.push(new BoundElementOrDirectiveProperty(
|
||||||
dashCaseToCamelCase(name), this._exprParser.wrapLiteralPrimitive(value, sourceInfo), true,
|
dashCaseToCamelCase(name), this._exprParser.wrapLiteralPrimitive(value, ''), true,
|
||||||
sourceInfo));
|
sourceSpan));
|
||||||
}
|
}
|
||||||
|
|
||||||
private _parseDirectives(selectorMatcher: SelectorMatcher,
|
private _parseDirectives(selectorMatcher: SelectorMatcher,
|
||||||
|
@ -417,15 +431,15 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
private _createDirectiveAsts(elementName: string, directives: CompileDirectiveMetadata[],
|
private _createDirectiveAsts(elementName: string, directives: CompileDirectiveMetadata[],
|
||||||
props: BoundElementOrDirectiveProperty[],
|
props: BoundElementOrDirectiveProperty[],
|
||||||
possibleExportAsVars: VariableAst[],
|
possibleExportAsVars: VariableAst[],
|
||||||
sourceInfo: string): DirectiveAst[] {
|
sourceSpan: ParseSourceSpan): DirectiveAst[] {
|
||||||
var matchedVariables = new Set<string>();
|
var matchedVariables = new Set<string>();
|
||||||
var directiveAsts = directives.map((directive: CompileDirectiveMetadata) => {
|
var directiveAsts = directives.map((directive: CompileDirectiveMetadata) => {
|
||||||
var hostProperties: BoundElementPropertyAst[] = [];
|
var hostProperties: BoundElementPropertyAst[] = [];
|
||||||
var hostEvents: BoundEventAst[] = [];
|
var hostEvents: BoundEventAst[] = [];
|
||||||
var directiveProperties: BoundDirectivePropertyAst[] = [];
|
var directiveProperties: BoundDirectivePropertyAst[] = [];
|
||||||
this._createDirectiveHostPropertyAsts(elementName, directive.hostProperties, sourceInfo,
|
this._createDirectiveHostPropertyAsts(elementName, directive.hostProperties, sourceSpan,
|
||||||
hostProperties);
|
hostProperties);
|
||||||
this._createDirectiveHostEventAsts(directive.hostListeners, sourceInfo, hostEvents);
|
this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents);
|
||||||
this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties);
|
this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties);
|
||||||
var exportAsVars = [];
|
var exportAsVars = [];
|
||||||
possibleExportAsVars.forEach((varAst) => {
|
possibleExportAsVars.forEach((varAst) => {
|
||||||
|
@ -436,34 +450,35 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents,
|
return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents,
|
||||||
exportAsVars, sourceInfo);
|
exportAsVars, sourceSpan);
|
||||||
});
|
});
|
||||||
possibleExportAsVars.forEach((varAst) => {
|
possibleExportAsVars.forEach((varAst) => {
|
||||||
if (varAst.value.length > 0 && !SetWrapper.has(matchedVariables, varAst.name)) {
|
if (varAst.value.length > 0 && !SetWrapper.has(matchedVariables, varAst.name)) {
|
||||||
this._reportError(
|
this._reportError(`There is no directive with "exportAs" set to "${varAst.value}"`,
|
||||||
`There is no directive with "exportAs" set to "${varAst.value}" at ${varAst.sourceInfo}`);
|
varAst.sourceSpan);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return directiveAsts;
|
return directiveAsts;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _createDirectiveHostPropertyAsts(elementName: string, hostProps: {[key: string]: string},
|
private _createDirectiveHostPropertyAsts(elementName: string, hostProps: {[key: string]: string},
|
||||||
sourceInfo: string,
|
sourceSpan: ParseSourceSpan,
|
||||||
targetPropertyAsts: BoundElementPropertyAst[]) {
|
targetPropertyAsts: BoundElementPropertyAst[]) {
|
||||||
if (isPresent(hostProps)) {
|
if (isPresent(hostProps)) {
|
||||||
StringMapWrapper.forEach(hostProps, (expression, propName) => {
|
StringMapWrapper.forEach(hostProps, (expression, propName) => {
|
||||||
var exprAst = this._parseBinding(expression, sourceInfo);
|
var exprAst = this._parseBinding(expression, sourceSpan);
|
||||||
targetPropertyAsts.push(
|
targetPropertyAsts.push(
|
||||||
this._createElementPropertyAst(elementName, propName, exprAst, sourceInfo));
|
this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _createDirectiveHostEventAsts(hostListeners: {[key: string]: string}, sourceInfo: string,
|
private _createDirectiveHostEventAsts(hostListeners: {[key: string]: string},
|
||||||
|
sourceSpan: ParseSourceSpan,
|
||||||
targetEventAsts: BoundEventAst[]) {
|
targetEventAsts: BoundEventAst[]) {
|
||||||
if (isPresent(hostListeners)) {
|
if (isPresent(hostListeners)) {
|
||||||
StringMapWrapper.forEach(hostListeners, (expression, propName) => {
|
StringMapWrapper.forEach(hostListeners, (expression, propName) => {
|
||||||
this._parseEvent(propName, expression, sourceInfo, [], targetEventAsts);
|
this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -489,7 +504,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
// Bindings are optional, so this binding only needs to be set up if an expression is given.
|
// Bindings are optional, so this binding only needs to be set up if an expression is given.
|
||||||
if (isPresent(boundProp)) {
|
if (isPresent(boundProp)) {
|
||||||
targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(
|
targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(
|
||||||
dirProp, boundProp.name, boundProp.expression, boundProp.sourceInfo));
|
dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -507,24 +522,25 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
props.forEach((prop: BoundElementOrDirectiveProperty) => {
|
props.forEach((prop: BoundElementOrDirectiveProperty) => {
|
||||||
if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) {
|
if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) {
|
||||||
boundElementProps.push(this._createElementPropertyAst(elementName, prop.name,
|
boundElementProps.push(this._createElementPropertyAst(elementName, prop.name,
|
||||||
prop.expression, prop.sourceInfo));
|
prop.expression, prop.sourceSpan));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return boundElementProps;
|
return boundElementProps;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _createElementPropertyAst(elementName: string, name: string, ast: AST,
|
private _createElementPropertyAst(elementName: string, name: string, ast: AST,
|
||||||
sourceInfo: any): BoundElementPropertyAst {
|
sourceSpan: ParseSourceSpan): BoundElementPropertyAst {
|
||||||
var unit = null;
|
var unit = null;
|
||||||
var bindingType;
|
var bindingType;
|
||||||
var boundPropertyName;
|
var boundPropertyName;
|
||||||
var parts = StringWrapper.split(name, PROPERTY_PARTS_SEPARATOR);
|
var parts = name.split(PROPERTY_PARTS_SEPARATOR);
|
||||||
if (parts.length === 1) {
|
if (parts.length === 1) {
|
||||||
boundPropertyName = this._schemaRegistry.getMappedPropName(dashCaseToCamelCase(parts[0]));
|
boundPropertyName = this._schemaRegistry.getMappedPropName(dashCaseToCamelCase(parts[0]));
|
||||||
bindingType = PropertyBindingType.Property;
|
bindingType = PropertyBindingType.Property;
|
||||||
if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName)) {
|
if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName)) {
|
||||||
this._reportError(
|
this._reportError(
|
||||||
`Can't bind to '${boundPropertyName}' since it isn't a known native property in ${sourceInfo}`);
|
`Can't bind to '${boundPropertyName}' since it isn't a known native property`,
|
||||||
|
sourceSpan);
|
||||||
}
|
}
|
||||||
} else if (parts[0] == ATTRIBUTE_PREFIX) {
|
} else if (parts[0] == ATTRIBUTE_PREFIX) {
|
||||||
boundPropertyName = dashCaseToCamelCase(parts[1]);
|
boundPropertyName = dashCaseToCamelCase(parts[1]);
|
||||||
|
@ -538,10 +554,10 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
boundPropertyName = dashCaseToCamelCase(parts[1]);
|
boundPropertyName = dashCaseToCamelCase(parts[1]);
|
||||||
bindingType = PropertyBindingType.Style;
|
bindingType = PropertyBindingType.Style;
|
||||||
} else {
|
} else {
|
||||||
this._reportError(`Invalid property name ${name} in ${sourceInfo}`);
|
this._reportError(`Invalid property name ${name}`, sourceSpan);
|
||||||
bindingType = null;
|
bindingType = null;
|
||||||
}
|
}
|
||||||
return new BoundElementPropertyAst(boundPropertyName, bindingType, ast, unit, sourceInfo);
|
return new BoundElementPropertyAst(boundPropertyName, bindingType, ast, unit, sourceSpan);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -556,30 +572,30 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
return componentTypeNames;
|
return componentTypeNames;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _assertOnlyOneComponent(directives: DirectiveAst[], sourceInfo: string) {
|
private _assertOnlyOneComponent(directives: DirectiveAst[], sourceSpan: ParseSourceSpan) {
|
||||||
var componentTypeNames = this._findComponentDirectiveNames(directives);
|
var componentTypeNames = this._findComponentDirectiveNames(directives);
|
||||||
if (componentTypeNames.length > 1) {
|
if (componentTypeNames.length > 1) {
|
||||||
this._reportError(
|
this._reportError(`More than one component: ${componentTypeNames.join(',')}`, sourceSpan);
|
||||||
`More than one component: ${componentTypeNames.join(',')} in ${sourceInfo}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private _assertNoComponentsNorElementBindingsOnTemplate(directives: DirectiveAst[],
|
private _assertNoComponentsNorElementBindingsOnTemplate(directives: DirectiveAst[],
|
||||||
elementProps: BoundElementPropertyAst[],
|
elementProps: BoundElementPropertyAst[],
|
||||||
sourceInfo: string) {
|
sourceSpan: ParseSourceSpan) {
|
||||||
var componentTypeNames: string[] = this._findComponentDirectiveNames(directives);
|
var componentTypeNames: string[] = this._findComponentDirectiveNames(directives);
|
||||||
if (componentTypeNames.length > 0) {
|
if (componentTypeNames.length > 0) {
|
||||||
this._reportError(
|
this._reportError(`Components on an embedded template: ${componentTypeNames.join(',')}`,
|
||||||
`Components on an embedded template: ${componentTypeNames.join(',')} in ${sourceInfo}`);
|
sourceSpan);
|
||||||
}
|
}
|
||||||
elementProps.forEach(prop => {
|
elementProps.forEach(prop => {
|
||||||
this._reportError(
|
this._reportError(
|
||||||
`Property binding ${prop.name} not used by any directive on an embedded template in ${prop.sourceInfo}`);
|
`Property binding ${prop.name} not used by any directive on an embedded template`,
|
||||||
|
sourceSpan);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private _assertAllEventsPublishedByDirectives(directives: DirectiveAst[], events: BoundEventAst[],
|
private _assertAllEventsPublishedByDirectives(directives: DirectiveAst[],
|
||||||
sourceInfo: string) {
|
events: BoundEventAst[]) {
|
||||||
var allDirectiveEvents = new Set<string>();
|
var allDirectiveEvents = new Set<string>();
|
||||||
directives.forEach(directive => {
|
directives.forEach(directive => {
|
||||||
StringMapWrapper.forEach(directive.directive.outputs,
|
StringMapWrapper.forEach(directive.directive.outputs,
|
||||||
|
@ -588,7 +604,8 @@ class TemplateParseVisitor implements HtmlAstVisitor {
|
||||||
events.forEach(event => {
|
events.forEach(event => {
|
||||||
if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) {
|
if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) {
|
||||||
this._reportError(
|
this._reportError(
|
||||||
`Event binding ${event.fullName} not emitted by any directive on an embedded template in ${sourceInfo}`);
|
`Event binding ${event.fullName} not emitted by any directive on an embedded template`,
|
||||||
|
event.sourceSpan);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -611,20 +628,20 @@ class NonBindableVisitor implements HtmlAstVisitor {
|
||||||
var ngContentIndex = component.findNgContentIndex(selector);
|
var ngContentIndex = component.findNgContentIndex(selector);
|
||||||
var children = htmlVisitAll(this, ast.children, EMPTY_COMPONENT);
|
var children = htmlVisitAll(this, ast.children, EMPTY_COMPONENT);
|
||||||
return new ElementAst(ast.name, htmlVisitAll(this, ast.attrs), [], [], [], [], children,
|
return new ElementAst(ast.name, htmlVisitAll(this, ast.attrs), [], [], [], [], children,
|
||||||
ngContentIndex, ast.sourceInfo);
|
ngContentIndex, ast.sourceSpan);
|
||||||
}
|
}
|
||||||
visitAttr(ast: HtmlAttrAst, context: any): AttrAst {
|
visitAttr(ast: HtmlAttrAst, context: any): AttrAst {
|
||||||
return new AttrAst(ast.name, ast.value, ast.sourceInfo);
|
return new AttrAst(ast.name, ast.value, ast.sourceSpan);
|
||||||
}
|
}
|
||||||
visitText(ast: HtmlTextAst, component: Component): TextAst {
|
visitText(ast: HtmlTextAst, component: Component): TextAst {
|
||||||
var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
|
var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
|
||||||
return new TextAst(ast.value, ngContentIndex, ast.sourceInfo);
|
return new TextAst(ast.value, ngContentIndex, ast.sourceSpan);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class BoundElementOrDirectiveProperty {
|
class BoundElementOrDirectiveProperty {
|
||||||
constructor(public name: string, public expression: AST, public isLiteral: boolean,
|
constructor(public name: string, public expression: AST, public isLiteral: boolean,
|
||||||
public sourceInfo: string) {}
|
public sourceSpan: ParseSourceSpan) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function splitClasses(classAttrValue: string): string[] {
|
export function splitClasses(classAttrValue: string): string[] {
|
||||||
|
|
|
@ -380,7 +380,7 @@ export function main() {
|
||||||
run(rootComp, [dir], 1)
|
run(rootComp, [dir], 1)
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
expect(data[0][2])
|
expect(data[0][2])
|
||||||
.toEqual(['someEmptyVar', '$implicit', 'someVar', 'someValue']);
|
.toEqual(['someVar', 'someValue', 'someEmptyVar', '$implicit']);
|
||||||
async.done();
|
async.done();
|
||||||
});
|
});
|
||||||
}));
|
}));
|
||||||
|
|
|
@ -0,0 +1,523 @@
|
||||||
|
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach} from '../../test_lib';
|
||||||
|
import {BaseException} from '../../src/facade/exceptions';
|
||||||
|
|
||||||
|
import {tokenizeHtml, HtmlToken, HtmlTokenType} from '../../src/compiler/html_lexer';
|
||||||
|
import {ParseSourceSpan, ParseLocation} from '../../src/compiler/parse_util';
|
||||||
|
|
||||||
|
export function main() {
|
||||||
|
describe('HtmlLexer', () => {
|
||||||
|
describe('line/column numbers', () => {
|
||||||
|
it('should work without newlines', () => {
|
||||||
|
expect(tokenizeAndHumanizeLineColumn('<t>a</t>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, '0:0'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END, '0:2'],
|
||||||
|
[HtmlTokenType.TEXT, '0:3'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, '0:4'],
|
||||||
|
[HtmlTokenType.EOF, '0:8']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should work with one newline', () => {
|
||||||
|
expect(tokenizeAndHumanizeLineColumn('<t>\na</t>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, '0:0'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END, '0:2'],
|
||||||
|
[HtmlTokenType.TEXT, '0:3'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, '1:1'],
|
||||||
|
[HtmlTokenType.EOF, '1:5']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should work with multiple newlines', () => {
|
||||||
|
expect(tokenizeAndHumanizeLineColumn('<t\n>\na</t>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, '0:0'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END, '1:0'],
|
||||||
|
[HtmlTokenType.TEXT, '1:1'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, '2:1'],
|
||||||
|
[HtmlTokenType.EOF, '2:5']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('comments', () => {
|
||||||
|
it('should parse comments', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<!--test-->'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.COMMENT_START],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'test'],
|
||||||
|
[HtmlTokenType.COMMENT_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {expect(tokenizeAndHumanizeSourceSpans('<!--test-->'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.COMMENT_START, '<!--'],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'test'],
|
||||||
|
[HtmlTokenType.COMMENT_END, '-->'],
|
||||||
|
[HtmlTokenType.EOF, '']
|
||||||
|
])});
|
||||||
|
|
||||||
|
it('should report <!- without -', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<!-a'))
|
||||||
|
.toEqual([[HtmlTokenType.COMMENT_START, 'Unexpected character "a"', '0:3']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing end comment', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<!--'))
|
||||||
|
.toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:4']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('doctype', () => {
|
||||||
|
it('should parse doctypes', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<!doctype html>'))
|
||||||
|
.toEqual([[HtmlTokenType.DOC_TYPE, 'doctype html'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans('<!doctype html>'))
|
||||||
|
.toEqual([[HtmlTokenType.DOC_TYPE, '<!doctype html>'], [HtmlTokenType.EOF, '']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing end doctype', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<!'))
|
||||||
|
.toEqual([[HtmlTokenType.DOC_TYPE, 'Unexpected character "EOF"', '0:2']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cdata', () => {
|
||||||
|
it('should parse cdata', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<![cdata[test]]>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.CDATA_START],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'test'],
|
||||||
|
[HtmlTokenType.CDATA_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans('<![cdata[test]]>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.CDATA_START, '<![cdata['],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'test'],
|
||||||
|
[HtmlTokenType.CDATA_END, ']]>'],
|
||||||
|
[HtmlTokenType.EOF, '']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report <![ without cdata[', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<![a'))
|
||||||
|
.toEqual([[HtmlTokenType.CDATA_START, 'Unexpected character "a"', '0:3']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing end cdata', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<![cdata['))
|
||||||
|
.toEqual([[HtmlTokenType.RAW_TEXT, 'Unexpected character "EOF"', '0:9']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('open tags', () => {
|
||||||
|
it('should parse open tags without prefix', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<test>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse namespace prefix', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<ns1:test>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, 'ns1', 'test'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse void tags', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<test/>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END_VOID],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should allow whitespace', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('< test >'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'test'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans('<test>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, '<test'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||||
|
[HtmlTokenType.EOF, '']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing name after <', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_OPEN_START, 'Unexpected character "EOF"', '0:1']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing >', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<name'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_OPEN_START, 'Unexpected character "EOF"', '0:5']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('attributes', () => {
|
||||||
|
it('should parse attributes without prefix', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<t a>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse attributes with prefix', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<t ns1:a>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, 'ns1', 'a'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse attributes whose prefix is not valid', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<t (ns1:a)>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, null, '(ns1:a)'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse attributes with single quote value', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts("<t a='b'>"))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||||
|
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse attributes with double quote value', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<t a="b">'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||||
|
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse attributes with unquoted value', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<t a=b>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||||
|
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should allow whitespace', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<t a = b >'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||||
|
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse attributes with entities in values', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('<t a="A">'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 't'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, null, 'a'],
|
||||||
|
[HtmlTokenType.ATTR_VALUE, 'A'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans('<t a=b>'))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, '<t'],
|
||||||
|
[HtmlTokenType.ATTR_NAME, 'a'],
|
||||||
|
[HtmlTokenType.ATTR_VALUE, 'b'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||||
|
[HtmlTokenType.EOF, '']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing value after =', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<name a='))
|
||||||
|
.toEqual([[HtmlTokenType.ATTR_VALUE, 'Unexpected character "EOF"', '0:8']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing end quote for \'', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<name a=\''))
|
||||||
|
.toEqual([[HtmlTokenType.ATTR_VALUE, 'Unexpected character "EOF"', '0:9']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing end quote for "', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('<name a="'))
|
||||||
|
.toEqual([[HtmlTokenType.ATTR_VALUE, 'Unexpected character "EOF"', '0:9']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('closing tags', () => {
|
||||||
|
it('should parse closing tags without prefix', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('</test>'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse closing tags with prefix', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('</ns1:test>'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_CLOSE, 'ns1', 'test'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should allow whitespace', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('</ test >'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_CLOSE, null, 'test'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans('</test>'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_CLOSE, '</test>'], [HtmlTokenType.EOF, '']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing name after </', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('</'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:2']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report missing >', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('</test'))
|
||||||
|
.toEqual([[HtmlTokenType.TAG_CLOSE, 'Unexpected character "EOF"', '0:6']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('entities', () => {
|
||||||
|
it('should parse named entities', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('a&b'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse hexadecimal entities', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('A'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse decimal entities', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('A'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'A'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans('a&b'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF, '']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should report unknown named entities >', () => {
|
||||||
|
expect(tokenizeAndHumanizeErrors('&tbo;'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'Unknown entity "tbo"', '0:0']]);
|
||||||
|
expect(tokenizeAndHumanizeErrors('&#asdf;'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'Unknown entity "#asdf"', '0:0']]);
|
||||||
|
expect(tokenizeAndHumanizeErrors('
sdf;'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'Unknown entity "#xasdf"', '0:0']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('regular text', () => {
|
||||||
|
it('should parse text', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('a'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should parse entities', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts('a&b'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'a&b'], [HtmlTokenType.EOF]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans('a'))
|
||||||
|
.toEqual([[HtmlTokenType.TEXT, 'a'], [HtmlTokenType.EOF, '']]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('raw text', () => {
|
||||||
|
it('should parse text', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<script>a</script>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'a'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not detect entities', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<script>&</script>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.RAW_TEXT, '&'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should ignore other opening tags', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<script>a<div></script>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'a<div>'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should ignore other closing tags', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<script>a</test></script>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'script'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'a</test>'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'script'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans(`<script>a</script>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, '<script'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||||
|
[HtmlTokenType.RAW_TEXT, 'a'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, '</script>'],
|
||||||
|
[HtmlTokenType.EOF, '']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('escapable raw text', () => {
|
||||||
|
it('should parse text', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<title>a</title>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should detect entities', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<title>&</title>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.ESCAPABLE_RAW_TEXT, '&'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should ignore other opening tags', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<title>a<div></title>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a<div>'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should ignore other closing tags', () => {
|
||||||
|
expect(tokenizeAndHumanizeParts(`<title>a</test></title>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, null, 'title'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END],
|
||||||
|
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a</test>'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, null, 'title'],
|
||||||
|
[HtmlTokenType.EOF]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should store the locations', () => {
|
||||||
|
expect(tokenizeAndHumanizeSourceSpans(`<title>a</title>`))
|
||||||
|
.toEqual([
|
||||||
|
[HtmlTokenType.TAG_OPEN_START, '<title'],
|
||||||
|
[HtmlTokenType.TAG_OPEN_END, '>'],
|
||||||
|
[HtmlTokenType.ESCAPABLE_RAW_TEXT, 'a'],
|
||||||
|
[HtmlTokenType.TAG_CLOSE, '</title>'],
|
||||||
|
[HtmlTokenType.EOF, '']
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeWithoutErrors(input: string): HtmlToken[] {
|
||||||
|
var tokenizeResult = tokenizeHtml(input, 'someUrl');
|
||||||
|
if (tokenizeResult.errors.length > 0) {
|
||||||
|
var errorString = tokenizeResult.errors.join('\n');
|
||||||
|
throw new BaseException(`Unexpected parse errors:\n${errorString}`);
|
||||||
|
}
|
||||||
|
return tokenizeResult.tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeAndHumanizeParts(input: string): any[] {
|
||||||
|
return tokenizeWithoutErrors(input).map(token => [<any>token.type].concat(token.parts));
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeAndHumanizeSourceSpans(input: string): any[] {
|
||||||
|
return tokenizeWithoutErrors(input).map(token => [<any>token.type, token.sourceSpan.toString()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function humanizeLineColumn(location: ParseLocation): string {
|
||||||
|
return `${location.line}:${location.col}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeAndHumanizeLineColumn(input: string): any[] {
|
||||||
|
return tokenizeWithoutErrors(input)
|
||||||
|
.map(token => [<any>token.type, humanizeLineColumn(token.sourceSpan.start)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeAndHumanizeErrors(input: string): any[] {
|
||||||
|
return tokenizeHtml(input, 'someUrl')
|
||||||
|
.errors.map(
|
||||||
|
tokenError =>
|
||||||
|
[<any>tokenError.tokenType, tokenError.msg, humanizeLineColumn(tokenError.location)]);
|
||||||
|
}
|
|
@ -9,7 +9,8 @@ import {
|
||||||
afterEach
|
afterEach
|
||||||
} from 'angular2/testing_internal';
|
} from 'angular2/testing_internal';
|
||||||
|
|
||||||
import {HtmlParser} from 'angular2/src/compiler/html_parser';
|
|
||||||
|
import {HtmlParser, HtmlParseTreeResult} from 'angular2/src/compiler/html_parser';
|
||||||
import {
|
import {
|
||||||
HtmlAst,
|
HtmlAst,
|
||||||
HtmlAstVisitor,
|
HtmlAstVisitor,
|
||||||
|
@ -20,129 +21,106 @@ import {
|
||||||
} from 'angular2/src/compiler/html_ast';
|
} from 'angular2/src/compiler/html_ast';
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('DomParser', () => {
|
describe('HtmlParser', () => {
|
||||||
var parser: HtmlParser;
|
var parser: HtmlParser;
|
||||||
beforeEach(() => { parser = new HtmlParser(); });
|
beforeEach(() => { parser = new HtmlParser(); });
|
||||||
|
|
||||||
describe('parse', () => {
|
// TODO: add more test cases
|
||||||
|
// TODO: separate tests for source spans from tests for tree parsing
|
||||||
|
// TODO: find a better way to assert the tree structure!
|
||||||
|
// -> maybe with arrays and object hashes!!
|
||||||
|
|
||||||
|
describe('parse', () => {
|
||||||
describe('text nodes', () => {
|
describe('text nodes', () => {
|
||||||
it('should parse root level text nodes', () => {
|
it('should parse root level text nodes', () => {
|
||||||
expect(humanizeDom(parser.parse('a', 'TestComp')))
|
expect(humanizeDom(parser.parse('a', 'TestComp'))).toEqual([[HtmlTextAst, 'a']]);
|
||||||
.toEqual([[HtmlTextAst, 'a', 'TestComp > #text(a):nth-child(0)']]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse text nodes inside regular elements', () => {
|
it('should parse text nodes inside regular elements', () => {
|
||||||
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<div>a</div>', 'TestComp')))
|
||||||
.toEqual([
|
.toEqual([[HtmlElementAst, 'div'], [HtmlTextAst, 'a']]);
|
||||||
[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', () => {
|
it('should parse text nodes inside template elements', () => {
|
||||||
expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<template>a</template>', 'TestComp')))
|
||||||
.toEqual([
|
.toEqual([[HtmlElementAst, 'template'], [HtmlTextAst, 'a']]);
|
||||||
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
|
|
||||||
[HtmlTextAst, 'a', 'TestComp > template:nth-child(0) > #text(a):nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('elements', () => {
|
describe('elements', () => {
|
||||||
it('should parse root level elements', () => {
|
it('should parse root level elements', () => {
|
||||||
expect(humanizeDom(parser.parse('<div></div>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<div></div>', 'TestComp')))
|
||||||
.toEqual([[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)']]);
|
.toEqual([[HtmlElementAst, 'div']]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse elements inside of regular elements', () => {
|
it('should parse elements inside of regular elements', () => {
|
||||||
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<div><span></span></div>', 'TestComp')))
|
||||||
.toEqual([
|
.toEqual([[HtmlElementAst, 'div'], [HtmlElementAst, 'span']]);
|
||||||
[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', () => {
|
it('should parse elements inside of template elements', () => {
|
||||||
expect(humanizeDom(parser.parse('<template><span></span></template>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<template><span></span></template>', 'TestComp')))
|
||||||
.toEqual([
|
.toEqual([[HtmlElementAst, 'template'], [HtmlElementAst, 'span']]);
|
||||||
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
|
|
||||||
[HtmlElementAst, 'span', 'TestComp > template:nth-child(0) > span:nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('attributes', () => {
|
describe('attributes', () => {
|
||||||
it('should parse attributes on regular elements', () => {
|
it('should parse attributes on regular elements', () => {
|
||||||
expect(humanizeDom(parser.parse('<div k="v"></div>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<div kEy="v" key2=v2></div>', 'TestComp')))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[HtmlElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[HtmlElementAst, 'div'],
|
||||||
[HtmlAttrAst, 'k', 'v', 'TestComp > div:nth-child(0)[k=v]']
|
[HtmlAttrAst, 'kEy', 'v'],
|
||||||
|
[HtmlAttrAst, 'key2', 'v2'],
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should parse attributes without values', () => {
|
||||||
|
expect(humanizeDom(parser.parse('<div k></div>', 'TestComp')))
|
||||||
|
.toEqual([[HtmlElementAst, 'div'], [HtmlAttrAst, 'k', '']]);
|
||||||
|
});
|
||||||
|
|
||||||
it('should parse attributes on svg elements case sensitive', () => {
|
it('should parse attributes on svg elements case sensitive', () => {
|
||||||
expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<svg viewBox="0"></svg>', 'TestComp')))
|
||||||
.toEqual([
|
.toEqual([[HtmlElementAst, '@svg:svg'], [HtmlAttrAst, 'viewBox', '0']]);
|
||||||
[HtmlElementAst, 'svg', 'TestComp > svg:nth-child(0)'],
|
|
||||||
[HtmlAttrAst, 'viewBox', '0', 'TestComp > svg:nth-child(0)[viewBox=0]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse attributes on template elements', () => {
|
it('should parse attributes on template elements', () => {
|
||||||
expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp')))
|
expect(humanizeDom(parser.parse('<template k="v"></template>', 'TestComp')))
|
||||||
.toEqual([
|
.toEqual([[HtmlElementAst, 'template'], [HtmlAttrAst, 'k', 'v']]);
|
||||||
[HtmlElementAst, 'template', 'TestComp > template:nth-child(0)'],
|
|
||||||
[HtmlAttrAst, 'k', 'v', 'TestComp > template:nth-child(0)[k=v]']
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('unparse', () => {
|
|
||||||
it('should unparse text nodes',
|
|
||||||
() => { expect(parser.unparse(parser.parse('a', null))).toEqual('a'); });
|
|
||||||
|
|
||||||
it('should unparse elements',
|
|
||||||
() => { expect(parser.unparse(parser.parse('<a></a>', null))).toEqual('<a></a>'); });
|
|
||||||
|
|
||||||
it('should unparse attributes', () => {
|
|
||||||
expect(parser.unparse(parser.parse('<div a b="c"></div>', null)))
|
|
||||||
.toEqual('<div a="" b="c"></div>');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should unparse nested elements', () => {
|
|
||||||
expect(parser.unparse(parser.parse('<div><a></a></div>', null)))
|
|
||||||
.toEqual('<div><a></a></div>');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should unparse nested text nodes', () => {
|
|
||||||
expect(parser.unparse(parser.parse('<div>a</div>', null))).toEqual('<div>a</div>');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function humanizeDom(asts: HtmlAst[]): any[] {
|
function humanizeDom(parseResult: HtmlParseTreeResult): any[] {
|
||||||
|
// TODO: humanize errors as well!
|
||||||
|
if (parseResult.errors.length > 0) {
|
||||||
|
throw parseResult.errors;
|
||||||
|
}
|
||||||
var humanizer = new Humanizer();
|
var humanizer = new Humanizer();
|
||||||
htmlVisitAll(humanizer, asts);
|
htmlVisitAll(humanizer, parseResult.rootNodes);
|
||||||
return humanizer.result;
|
return humanizer.result;
|
||||||
}
|
}
|
||||||
|
|
||||||
class Humanizer implements HtmlAstVisitor {
|
class Humanizer implements HtmlAstVisitor {
|
||||||
result: any[] = [];
|
result: any[] = [];
|
||||||
|
|
||||||
visitElement(ast: HtmlElementAst, context: any): any {
|
visitElement(ast: HtmlElementAst, context: any): any {
|
||||||
this.result.push([HtmlElementAst, ast.name, ast.sourceInfo]);
|
this.result.push([HtmlElementAst, ast.name]);
|
||||||
htmlVisitAll(this, ast.attrs);
|
htmlVisitAll(this, ast.attrs);
|
||||||
htmlVisitAll(this, ast.children);
|
htmlVisitAll(this, ast.children);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
visitAttr(ast: HtmlAttrAst, context: any): any {
|
visitAttr(ast: HtmlAttrAst, context: any): any {
|
||||||
this.result.push([HtmlAttrAst, ast.name, ast.value, ast.sourceInfo]);
|
this.result.push([HtmlAttrAst, ast.name, ast.value]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
visitText(ast: HtmlTextAst, context: any): any {
|
visitText(ast: HtmlTextAst, context: any): any {
|
||||||
this.result.push([HtmlTextAst, ast.value, ast.sourceInfo]);
|
this.result.push([HtmlTextAst, ast.value]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,7 +8,7 @@ import {
|
||||||
beforeEach,
|
beforeEach,
|
||||||
afterEach,
|
afterEach,
|
||||||
inject,
|
inject,
|
||||||
beforeEachBindings
|
beforeEachProviders
|
||||||
} from 'angular2/testing_internal';
|
} from 'angular2/testing_internal';
|
||||||
import {provide} from 'angular2/src/core/di';
|
import {provide} from 'angular2/src/core/di';
|
||||||
|
|
||||||
|
@ -45,9 +45,12 @@ import {Unparser} from '../core/change_detection/parser/unparser';
|
||||||
|
|
||||||
var expressionUnparser = new Unparser();
|
var expressionUnparser = new Unparser();
|
||||||
|
|
||||||
|
// TODO(tbosch): add tests for checking that we
|
||||||
|
// keep the correct sourceSpans!
|
||||||
|
|
||||||
export function main() {
|
export function main() {
|
||||||
describe('TemplateParser', () => {
|
describe('TemplateParser', () => {
|
||||||
beforeEachBindings(() => [
|
beforeEachProviders(() => [
|
||||||
TEST_PROVIDERS,
|
TEST_PROVIDERS,
|
||||||
provide(ElementSchemaRegistry,
|
provide(ElementSchemaRegistry,
|
||||||
{
|
{
|
||||||
|
@ -72,29 +75,22 @@ export function main() {
|
||||||
describe('parse', () => {
|
describe('parse', () => {
|
||||||
describe('nodes without bindings', () => {
|
describe('nodes without bindings', () => {
|
||||||
|
|
||||||
it('should parse text nodes', () => {
|
it('should parse text nodes',
|
||||||
expect(humanizeTemplateAsts(parse('a', [])))
|
() => { expect(humanizeTemplateAsts(parse('a', []))).toEqual([[TextAst, 'a']]); });
|
||||||
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(0)']]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should parse elements with attributes', () => {
|
it('should parse elements with attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div a=b>', [])))
|
expect(humanizeTemplateAsts(parse('<div a=b>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [AttrAst, 'a', 'b']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[AttrAst, 'a', 'b', 'TestComp > div:nth-child(0)[a=b]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse ngContent', () => {
|
it('should parse ngContent', () => {
|
||||||
var parsed = parse('<ng-content select="a">', []);
|
var parsed = parse('<ng-content select="a">', []);
|
||||||
expect(humanizeTemplateAsts(parsed))
|
expect(humanizeTemplateAsts(parsed)).toEqual([[NgContentAst]]);
|
||||||
.toEqual([[NgContentAst, 'TestComp > ng-content:nth-child(0)']]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse bound text nodes', () => {
|
it('should parse bound text nodes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('{{a}}', [])))
|
expect(humanizeTemplateAsts(parse('{{a}}', []))).toEqual([[BoundTextAst, '{{ a }}']]);
|
||||||
.toEqual([[BoundTextAst, '{{ a }}', 'TestComp > #text({{a}}):nth-child(0)']]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('bound properties', () => {
|
describe('bound properties', () => {
|
||||||
|
@ -102,120 +98,64 @@ export function main() {
|
||||||
it('should parse and camel case bound properties', () => {
|
it('should parse and camel case bound properties', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div [some-prop]="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div [some-prop]="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Property,
|
|
||||||
'someProp',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[some-prop]=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should normalize property names via the element schema', () => {
|
it('should normalize property names via the element schema', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div [mapped-attr]="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div [mapped-attr]="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'mappedProp', 'v', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Property,
|
|
||||||
'mappedProp',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[mapped-attr]=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse and camel case bound attributes', () => {
|
it('should parse and camel case bound attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div [attr.some-attr]="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div [attr.some-attr]="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Attribute, 'someAttr', 'v', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Attribute,
|
|
||||||
'someAttr',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[attr.some-attr]=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse and dash case bound classes', () => {
|
it('should parse and dash case bound classes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div [class.some-class]="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div [class.some-class]="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Class, 'some-class', 'v', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Class,
|
|
||||||
'some-class',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[class.some-class]=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse and camel case bound styles', () => {
|
it('should parse and camel case bound styles', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div [style.some-style]="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div [style.some-style]="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Style, 'someStyle', 'v', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Style,
|
|
||||||
'someStyle',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[style.some-style]=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse bound properties via [...] and not report them as attributes', () => {
|
it('should parse bound properties via [...] and not report them as attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div [prop]="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div [prop]="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Property,
|
|
||||||
'prop',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[prop]=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse bound properties via bind- and not report them as attributes', () => {
|
it('should parse bound properties via bind- and not report them as attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div bind-prop="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div bind-prop="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Property,
|
|
||||||
'prop',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[bind-prop=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse bound properties via {{...}} and not report them as attributes', () => {
|
it('should parse bound properties via {{...}} and not report them as attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div prop="{{v}}">', [])))
|
expect(humanizeTemplateAsts(parse('<div prop="{{v}}">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Property,
|
|
||||||
'prop',
|
|
||||||
'{{ v }}',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[prop={{v}}]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -225,46 +165,22 @@ export function main() {
|
||||||
|
|
||||||
it('should parse bound events with a target', () => {
|
it('should parse bound events with a target', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div (window:event)="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div (window:event)="v">', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', 'window', 'v']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[
|
|
||||||
BoundEventAst,
|
|
||||||
'event',
|
|
||||||
'window',
|
|
||||||
'v',
|
|
||||||
'TestComp > div:nth-child(0)[(window:event)=v]'
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse bound events via (...) and not report them as attributes', () => {
|
it('should parse bound events via (...) and not report them as attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div (event)="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div (event)="v">', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[BoundEventAst, 'event', null, 'v', 'TestComp > div:nth-child(0)[(event)=v]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should camel case event names', () => {
|
it('should camel case event names', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div (some-event)="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div (some-event)="v">', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'someEvent', null, 'v']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[
|
|
||||||
BoundEventAst,
|
|
||||||
'someEvent',
|
|
||||||
null,
|
|
||||||
'v',
|
|
||||||
'TestComp > div:nth-child(0)[(some-event)=v]'
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse bound events via on- and not report them as attributes', () => {
|
it('should parse bound events via on- and not report them as attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div on-event="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div on-event="v">', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[BoundEventAst, 'event', null, 'v', 'TestComp > div:nth-child(0)[on-event=v]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow events on explicit embedded templates that are emitted by a directive',
|
it('should allow events on explicit embedded templates that are emitted by a directive',
|
||||||
|
@ -276,9 +192,9 @@ export function main() {
|
||||||
});
|
});
|
||||||
expect(humanizeTemplateAsts(parse('<template (e)="f"></template>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<template (e)="f"></template>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[EmbeddedTemplateAst, 'TestComp > template:nth-child(0)'],
|
[EmbeddedTemplateAst],
|
||||||
[BoundEventAst, 'e', null, 'f', 'TestComp > template:nth-child(0)[(e)=f]'],
|
[BoundEventAst, 'e', null, 'f'],
|
||||||
[DirectiveAst, dirA, 'TestComp > template:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -288,22 +204,9 @@ export function main() {
|
||||||
() => {
|
() => {
|
||||||
expect(humanizeTemplateAsts(parse('<div [(prop)]="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div [(prop)]="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null],
|
||||||
BoundElementPropertyAst,
|
[BoundEventAst, 'propChange', null, 'v = $event']
|
||||||
PropertyBindingType.Property,
|
|
||||||
'prop',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[(prop)]=v]'
|
|
||||||
],
|
|
||||||
[
|
|
||||||
BoundEventAst,
|
|
||||||
'propChange',
|
|
||||||
null,
|
|
||||||
'v = $event',
|
|
||||||
'TestComp > div:nth-child(0)[[(prop)]=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -311,22 +214,9 @@ export function main() {
|
||||||
() => {
|
() => {
|
||||||
expect(humanizeTemplateAsts(parse('<div bindon-prop="v">', [])))
|
expect(humanizeTemplateAsts(parse('<div bindon-prop="v">', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null],
|
||||||
BoundElementPropertyAst,
|
[BoundEventAst, 'propChange', null, 'v = $event']
|
||||||
PropertyBindingType.Property,
|
|
||||||
'prop',
|
|
||||||
'v',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[bindon-prop=v]'
|
|
||||||
],
|
|
||||||
[
|
|
||||||
BoundEventAst,
|
|
||||||
'propChange',
|
|
||||||
null,
|
|
||||||
'v = $event',
|
|
||||||
'TestComp > div:nth-child(0)[bindon-prop=v]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -349,14 +239,14 @@ export function main() {
|
||||||
});
|
});
|
||||||
expect(humanizeTemplateAsts(parse('<div a c b>', [dirA, dirB, dirC, comp])))
|
expect(humanizeTemplateAsts(parse('<div a c b>', [dirA, dirB, dirC, comp])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'a', '', 'TestComp > div:nth-child(0)[a=]'],
|
[AttrAst, 'a', ''],
|
||||||
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]'],
|
[AttrAst, 'c', ''],
|
||||||
[AttrAst, 'c', '', 'TestComp > div:nth-child(0)[c=]'],
|
[AttrAst, 'b', ''],
|
||||||
[DirectiveAst, comp, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, comp],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[DirectiveAst, dirB, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirB],
|
||||||
[DirectiveAst, dirC, 'TestComp > div:nth-child(0)']
|
[DirectiveAst, dirC]
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -367,16 +257,9 @@ export function main() {
|
||||||
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
|
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
|
||||||
expect(humanizeTemplateAsts(parse('<div [a]="b">', [dirA, dirB])))
|
expect(humanizeTemplateAsts(parse('<div [a]="b">', [dirA, dirB])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'b', null],
|
||||||
BoundElementPropertyAst,
|
[DirectiveAst, dirA]
|
||||||
PropertyBindingType.Property,
|
|
||||||
'a',
|
|
||||||
'b',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)[[a]=b]'
|
|
||||||
],
|
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -388,16 +271,9 @@ export function main() {
|
||||||
});
|
});
|
||||||
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[
|
[BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'expr', null]
|
||||||
BoundElementPropertyAst,
|
|
||||||
PropertyBindingType.Property,
|
|
||||||
'a',
|
|
||||||
'expr',
|
|
||||||
null,
|
|
||||||
'TestComp > div:nth-child(0)'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -408,11 +284,8 @@ export function main() {
|
||||||
host: {'(a)': 'expr'}
|
host: {'(a)': 'expr'}
|
||||||
});
|
});
|
||||||
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual(
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[[ElementAst, 'div'], [DirectiveAst, dirA], [BoundEventAst, 'a', null, 'expr']]);
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
|
||||||
[BoundEventAst, 'a', null, 'expr', 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse directive properties', () => {
|
it('should parse directive properties', () => {
|
||||||
|
@ -420,14 +293,9 @@ export function main() {
|
||||||
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['aProp']});
|
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['aProp']});
|
||||||
expect(humanizeTemplateAsts(parse('<div [a-prop]="expr"></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div [a-prop]="expr"></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[
|
[BoundDirectivePropertyAst, 'aProp', 'expr']
|
||||||
BoundDirectivePropertyAst,
|
|
||||||
'aProp',
|
|
||||||
'expr',
|
|
||||||
'TestComp > div:nth-child(0)[[a-prop]=expr]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -436,9 +304,9 @@ export function main() {
|
||||||
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['b:a']});
|
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['b:a']});
|
||||||
expect(humanizeTemplateAsts(parse('<div [a]="expr"></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div [a]="expr"></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[BoundDirectivePropertyAst, 'b', 'expr', 'TestComp > div:nth-child(0)[[a]=expr]']
|
[BoundDirectivePropertyAst, 'b', 'expr']
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -447,15 +315,10 @@ export function main() {
|
||||||
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
|
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
|
||||||
expect(humanizeTemplateAsts(parse('<div a="literal"></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div a="literal"></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'a', 'literal', 'TestComp > div:nth-child(0)[a=literal]'],
|
[AttrAst, 'a', 'literal'],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[
|
[BoundDirectivePropertyAst, 'a', '"literal"']
|
||||||
BoundDirectivePropertyAst,
|
|
||||||
'a',
|
|
||||||
'"literal"',
|
|
||||||
'TestComp > div:nth-child(0)[a=literal]'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -464,15 +327,10 @@ export function main() {
|
||||||
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
|
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
|
||||||
expect(humanizeTemplateAsts(parse('<div a="literal" [a]="\'literal2\'"></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div a="literal" [a]="\'literal2\'"></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'a', 'literal', 'TestComp > div:nth-child(0)[a=literal]'],
|
[AttrAst, 'a', 'literal'],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[
|
[BoundDirectivePropertyAst, 'a', '"literal2"']
|
||||||
BoundDirectivePropertyAst,
|
|
||||||
'a',
|
|
||||||
'"literal2"',
|
|
||||||
'TestComp > div:nth-child(0)[[a]=\'literal2\']'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -480,10 +338,7 @@ export function main() {
|
||||||
var dirA = CompileDirectiveMetadata.create(
|
var dirA = CompileDirectiveMetadata.create(
|
||||||
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
|
{selector: 'div', type: new CompileTypeMetadata({name: 'DirA'}), inputs: ['a']});
|
||||||
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [DirectiveAst, dirA]]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
@ -492,34 +347,22 @@ export function main() {
|
||||||
|
|
||||||
it('should parse variables via #... and not report them as attributes', () => {
|
it('should parse variables via #... and not report them as attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div #a>', [])))
|
expect(humanizeTemplateAsts(parse('<div #a>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse variables via var-... and not report them as attributes', () => {
|
it('should parse variables via var-... and not report them as attributes', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div var-a>', [])))
|
expect(humanizeTemplateAsts(parse('<div var-a>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[var-a=]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should camel case variables', () => {
|
it('should camel case variables', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div var-some-a>', [])))
|
expect(humanizeTemplateAsts(parse('<div var-some-a>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [VariableAst, 'someA', '']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[VariableAst, 'someA', '', 'TestComp > div:nth-child(0)[var-some-a=]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should assign variables with empty value to the element', () => {
|
it('should assign variables with empty value to the element', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div #a></div>', [])))
|
expect(humanizeTemplateAsts(parse('<div #a></div>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [VariableAst, 'a', '']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should assign variables to directives via exportAs', () => {
|
it('should assign variables to directives via exportAs', () => {
|
||||||
|
@ -527,25 +370,22 @@ export function main() {
|
||||||
{selector: '[a]', type: new CompileTypeMetadata({name: 'DirA'}), exportAs: 'dirA'});
|
{selector: '[a]', type: new CompileTypeMetadata({name: 'DirA'}), exportAs: 'dirA'});
|
||||||
expect(humanizeTemplateAsts(parse('<div a #a="dirA"></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div a #a="dirA"></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'a', '', 'TestComp > div:nth-child(0)[a=]'],
|
[AttrAst, 'a', ''],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[VariableAst, 'a', 'dirA', 'TestComp > div:nth-child(0)[#a=dirA]']
|
[VariableAst, 'a', 'dirA']
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should report variables with values that dont match a directive as errors', () => {
|
it('should report variables with values that dont match a directive as errors', () => {
|
||||||
expect(() => parse('<div #a="dirA"></div>', [])).toThrowError(`Template parse errors:
|
expect(() => parse('<div #a="dirA"></div>', [])).toThrowError(`Template parse errors:
|
||||||
There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(0)[#a=dirA]`);
|
There is no directive with "exportAs" set to "dirA" (<div #a="dirA">): TestComp@0:5`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should allow variables with values that dont match a directive on embedded template elements',
|
it('should allow variables with values that dont match a directive on embedded template elements',
|
||||||
() => {
|
() => {
|
||||||
expect(humanizeTemplateAsts(parse('<template #a="b"></template>', [])))
|
expect(humanizeTemplateAsts(parse('<template #a="b"></template>', [])))
|
||||||
.toEqual([
|
.toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b']]);
|
||||||
[EmbeddedTemplateAst, 'TestComp > template:nth-child(0)'],
|
|
||||||
[VariableAst, 'a', 'b', 'TestComp > template:nth-child(0)[#a=b]']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should assign variables with empty value to components', () => {
|
it('should assign variables with empty value to components', () => {
|
||||||
|
@ -558,11 +398,11 @@ There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(
|
||||||
});
|
});
|
||||||
expect(humanizeTemplateAsts(parse('<div a #a></div>', [dirA])))
|
expect(humanizeTemplateAsts(parse('<div a #a></div>', [dirA])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'a', '', 'TestComp > div:nth-child(0)[a=]'],
|
[AttrAst, 'a', ''],
|
||||||
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]'],
|
[VariableAst, 'a', ''],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[VariableAst, 'a', '', 'TestComp > div:nth-child(0)[#a=]']
|
[VariableAst, 'a', '']
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -571,50 +411,34 @@ There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(
|
||||||
describe('explicit templates', () => {
|
describe('explicit templates', () => {
|
||||||
it('should create embedded templates for <template> elements', () => {
|
it('should create embedded templates for <template> elements', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<template></template>', [])))
|
expect(humanizeTemplateAsts(parse('<template></template>', [])))
|
||||||
.toEqual([[EmbeddedTemplateAst, 'TestComp > template:nth-child(0)']]);
|
.toEqual([[EmbeddedTemplateAst]]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('inline templates', () => {
|
describe('inline templates', () => {
|
||||||
it('should wrap the element into an EmbeddedTemplateAST', () => {
|
it('should wrap the element into an EmbeddedTemplateAST', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div template>', [])))
|
expect(humanizeTemplateAsts(parse('<div template>', [])))
|
||||||
.toEqual([
|
.toEqual([[EmbeddedTemplateAst], [ElementAst, 'div']]);
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse bound properties', () => {
|
it('should parse bound properties', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div template="ngIf test">', [ngIf])))
|
expect(humanizeTemplateAsts(parse('<div template="ngIf test">', [ngIf])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
[EmbeddedTemplateAst],
|
||||||
[DirectiveAst, ngIf, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, ngIf],
|
||||||
[
|
[BoundDirectivePropertyAst, 'ngIf', 'test'],
|
||||||
BoundDirectivePropertyAst,
|
[ElementAst, 'div']
|
||||||
'ngIf',
|
|
||||||
'test',
|
|
||||||
'TestComp > div:nth-child(0)[template=ngIf test]'
|
|
||||||
],
|
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse variables via #...', () => {
|
it('should parse variables via #...', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div template="ngIf #a=b">', [])))
|
expect(humanizeTemplateAsts(parse('<div template="ngIf #a=b">', [])))
|
||||||
.toEqual([
|
.toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]);
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
|
||||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=ngIf #a=b]'],
|
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse variables via var ...', () => {
|
it('should parse variables via var ...', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div template="ngIf var a=b">', [])))
|
expect(humanizeTemplateAsts(parse('<div template="ngIf var a=b">', [])))
|
||||||
.toEqual([
|
.toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]);
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
|
||||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=ngIf var a=b]'],
|
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('directives', () => {
|
describe('directives', () => {
|
||||||
|
@ -625,17 +449,12 @@ There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(
|
||||||
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
|
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
|
||||||
expect(humanizeTemplateAsts(parse('<div template="a b" b>', [dirA, dirB])))
|
expect(humanizeTemplateAsts(parse('<div template="a b" b>', [dirA, dirB])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
[EmbeddedTemplateAst],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[
|
[BoundDirectivePropertyAst, 'a', 'b'],
|
||||||
BoundDirectivePropertyAst,
|
[ElementAst, 'div'],
|
||||||
'a',
|
[AttrAst, 'b', ''],
|
||||||
'b',
|
[DirectiveAst, dirB]
|
||||||
'TestComp > div:nth-child(0)[template=a b]'
|
|
||||||
],
|
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]'],
|
|
||||||
[DirectiveAst, dirB, 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -646,12 +465,12 @@ There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(
|
||||||
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
|
{selector: '[b]', type: new CompileTypeMetadata({name: 'DirB'})});
|
||||||
expect(humanizeTemplateAsts(parse('<div template="#a=b" b>', [dirA, dirB])))
|
expect(humanizeTemplateAsts(parse('<div template="#a=b" b>', [dirA, dirB])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
[EmbeddedTemplateAst],
|
||||||
[VariableAst, 'a', 'b', 'TestComp > div:nth-child(0)[template=#a=b]'],
|
[VariableAst, 'a', 'b'],
|
||||||
[DirectiveAst, dirA, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, dirA],
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'b', '', 'TestComp > div:nth-child(0)[b=]'],
|
[AttrAst, 'b', ''],
|
||||||
[DirectiveAst, dirB, 'TestComp > div:nth-child(0)']
|
[DirectiveAst, dirB]
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -660,30 +479,23 @@ There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(
|
||||||
it('should work with *... and use the attribute name as property binding name', () => {
|
it('should work with *... and use the attribute name as property binding name', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div *ng-if="test">', [ngIf])))
|
expect(humanizeTemplateAsts(parse('<div *ng-if="test">', [ngIf])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
[EmbeddedTemplateAst],
|
||||||
[DirectiveAst, ngIf, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, ngIf],
|
||||||
[
|
[BoundDirectivePropertyAst, 'ngIf', 'test'],
|
||||||
BoundDirectivePropertyAst,
|
[ElementAst, 'div']
|
||||||
'ngIf',
|
|
||||||
'test',
|
|
||||||
'TestComp > div:nth-child(0)[*ng-if=test]'
|
|
||||||
],
|
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work with *... and empty value', () => {
|
it('should work with *... and empty value', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div *ng-if>', [ngIf])))
|
expect(humanizeTemplateAsts(parse('<div *ng-if>', [ngIf])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[EmbeddedTemplateAst, 'TestComp > div:nth-child(0)'],
|
[EmbeddedTemplateAst],
|
||||||
[DirectiveAst, ngIf, 'TestComp > div:nth-child(0)'],
|
[DirectiveAst, ngIf],
|
||||||
[BoundDirectivePropertyAst, 'ngIf', 'null', 'TestComp > div:nth-child(0)[*ng-if=]'],
|
[BoundDirectivePropertyAst, 'ngIf', 'null'],
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)']
|
[ElementAst, 'div']
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('content projection', () => {
|
describe('content projection', () => {
|
||||||
|
@ -788,14 +600,14 @@ There is no directive with "exportAs" set to "dirA" at TestComp > div:nth-child(
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('error cases', () => {
|
describe('error cases', () => {
|
||||||
it('should throw on invalid property names', () => {
|
it('should report invalid property names', () => {
|
||||||
expect(() => parse('<div [invalid-prop]></div>', [])).toThrowError(`Template parse errors:
|
expect(() => parse('<div [invalid-prop]></div>', [])).toThrowError(`Template parse errors:
|
||||||
Can't bind to 'invalidProp' since it isn't a known native property in TestComp > div:nth-child(0)[[invalid-prop]=]`);
|
Can't bind to 'invalidProp' since it isn't a known native property (<div [invalid-prop]>): TestComp@0:5`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should report errors in expressions', () => {
|
it('should report errors in expressions', () => {
|
||||||
expect(() => parse('<div [prop]="a b"></div>', [])).toThrowErrorWith(`Template parse errors:
|
expect(() => parse('<div [prop]="a b"></div>', [])).toThrowErrorWith(`Template parse errors:
|
||||||
Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp > div:nth-child(0)[[prop]=a b]`);
|
Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 in [prop]="a b": TestComp@0:5`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not throw on invalid property names if the property is used by a directive',
|
it('should not throw on invalid property names if the property is used by a directive',
|
||||||
|
@ -821,8 +633,8 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp > div:nth-ch
|
||||||
type: new CompileTypeMetadata({name: 'DirB'}),
|
type: new CompileTypeMetadata({name: 'DirB'}),
|
||||||
template: new CompileTemplateMetadata({ngContentSelectors: []})
|
template: new CompileTemplateMetadata({ngContentSelectors: []})
|
||||||
});
|
});
|
||||||
expect(() => parse('<div>', [dirB, dirA])).toThrowError(`Template parse errors:
|
expect(() => parse('<div/>', [dirB, dirA])).toThrowError(`Template parse errors:
|
||||||
More than one component: DirB,DirA in TestComp > div:nth-child(0)`);
|
More than one component: DirB,DirA in <div/>: TestComp@0:0`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not allow components or element bindings nor dom events on explicit embedded templates',
|
it('should not allow components or element bindings nor dom events on explicit embedded templates',
|
||||||
|
@ -847,23 +659,20 @@ Property binding a not used by any directive on an embedded template in TestComp
|
||||||
type: new CompileTypeMetadata({name: 'DirA'}),
|
type: new CompileTypeMetadata({name: 'DirA'}),
|
||||||
template: new CompileTemplateMetadata({ngContentSelectors: []})
|
template: new CompileTemplateMetadata({ngContentSelectors: []})
|
||||||
});
|
});
|
||||||
expect(() => parse('<div *a="b">', [dirA])).toThrowError(`Template parse errors:
|
expect(() => parse('<div *a="b"></div>', [dirA])).toThrowError(`Template parse errors:
|
||||||
Components on an embedded template: DirA in TestComp > div:nth-child(0)
|
Components on an embedded template: DirA in <div *a="b">: TestComp@0:0
|
||||||
Property binding a not used by any directive on an embedded template in TestComp > div:nth-child(0)[*a=b]`);
|
Property binding a not used by any directive on an embedded template in <div *a="b">: TestComp@0:0`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('ignore elements', () => {
|
describe('ignore elements', () => {
|
||||||
it('should ignore <script> elements but include them for source info', () => {
|
it('should ignore <script> elements', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<script></script>a', [])))
|
expect(humanizeTemplateAsts(parse('<script></script>a', []))).toEqual([[TextAst, 'a']]);
|
||||||
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore <style> elements but include them for source info', () => {
|
it('should ignore <style> elements', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<style></style>a', [])))
|
expect(humanizeTemplateAsts(parse('<style></style>a', []))).toEqual([[TextAst, 'a']]);
|
||||||
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('<link rel="stylesheet">', () => {
|
describe('<link rel="stylesheet">', () => {
|
||||||
|
@ -873,108 +682,73 @@ Property binding a not used by any directive on an embedded template in TestComp
|
||||||
expect(humanizeTemplateAsts(
|
expect(humanizeTemplateAsts(
|
||||||
parse('<link rel="stylesheet" href="http://someurl"></link>a', [])))
|
parse('<link rel="stylesheet" href="http://someurl"></link>a', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'link', 'TestComp > link:nth-child(0)'],
|
[ElementAst, 'link'],
|
||||||
[
|
[AttrAst, 'href', 'http://someurl'],
|
||||||
AttrAst,
|
[AttrAst, 'rel', 'stylesheet'],
|
||||||
'href',
|
[TextAst, 'a']
|
||||||
'http://someurl',
|
|
||||||
'TestComp > link:nth-child(0)[href=http://someurl]'
|
|
||||||
],
|
|
||||||
[AttrAst, 'rel', 'stylesheet', 'TestComp > link:nth-child(0)[rel=stylesheet]'],
|
|
||||||
[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should keep <link rel="stylesheet"> elements if they have no uri', () => {
|
it('should keep <link rel="stylesheet"> elements if they have no uri', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<link rel="stylesheet"></link>a', [])))
|
expect(humanizeTemplateAsts(parse('<link rel="stylesheet"></link>a', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'link'], [AttrAst, 'rel', 'stylesheet'], [TextAst, 'a']]);
|
||||||
[ElementAst, 'link', 'TestComp > link:nth-child(0)'],
|
|
||||||
[AttrAst, 'rel', 'stylesheet', 'TestComp > link:nth-child(0)[rel=stylesheet]'],
|
|
||||||
[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore <link rel="stylesheet"> elements if they have a relative uri', () => {
|
it('should ignore <link rel="stylesheet"> elements if they have a relative uri', () => {
|
||||||
expect(
|
expect(
|
||||||
humanizeTemplateAsts(parse('<link rel="stylesheet" href="./other.css"></link>a', [])))
|
humanizeTemplateAsts(parse('<link rel="stylesheet" href="./other.css"></link>a', [])))
|
||||||
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
|
.toEqual([[TextAst, 'a']]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore <link rel="stylesheet"> elements if they have a package: uri', () => {
|
it('should ignore <link rel="stylesheet"> elements if they have a package: uri', () => {
|
||||||
expect(humanizeTemplateAsts(
|
expect(humanizeTemplateAsts(
|
||||||
parse('<link rel="stylesheet" href="package:somePackage"></link>a', [])))
|
parse('<link rel="stylesheet" href="package:somePackage"></link>a', [])))
|
||||||
.toEqual([[TextAst, 'a', 'TestComp > #text(a):nth-child(1)']]);
|
.toEqual([[TextAst, 'a']]);
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore bindings on children of elements with ng-non-bindable', () => {
|
it('should ignore bindings on children of elements with ng-non-bindable', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div ng-non-bindable>{{b}}</div>', [])))
|
expect(humanizeTemplateAsts(parse('<div ng-non-bindable>{{b}}</div>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, '{{b}}']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
|
|
||||||
[TextAst, '{{b}}', 'TestComp > div:nth-child(0) > #text({{b}}):nth-child(0)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should keep nested children of elements with ng-non-bindable', () => {
|
it('should keep nested children of elements with ng-non-bindable', () => {
|
||||||
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><span>{{b}}</span></div>', [])))
|
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><span>{{b}}</span></div>', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
|
[AttrAst, 'ng-non-bindable', ''],
|
||||||
[ElementAst, 'span', 'TestComp > div:nth-child(0) > span:nth-child(0)'],
|
[ElementAst, 'span'],
|
||||||
[
|
[TextAst, '{{b}}']
|
||||||
TextAst,
|
|
||||||
'{{b}}',
|
|
||||||
'TestComp > div:nth-child(0) > span:nth-child(0) > #text({{b}}):nth-child(0)'
|
|
||||||
]
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore <script> elements inside of elements with ng-non-bindable but include them for source info',
|
it('should ignore <script> elements inside of elements with ng-non-bindable', () => {
|
||||||
() => {
|
|
||||||
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><script></script>a</div>', [])))
|
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><script></script>a</div>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, 'a']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
|
|
||||||
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore <style> elements inside of elements with ng-non-bindable but include them for source info',
|
it('should ignore <style> elements inside of elements with ng-non-bindable', () => {
|
||||||
() => {
|
|
||||||
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><style></style>a</div>', [])))
|
expect(humanizeTemplateAsts(parse('<div ng-non-bindable><style></style>a</div>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, 'a']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
|
|
||||||
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should ignore <link rel="stylesheet"> elements inside of elements with ng-non-bindable but include them for source info',
|
it('should ignore <link rel="stylesheet"> elements inside of elements with ng-non-bindable',
|
||||||
() => {
|
() => {
|
||||||
expect(humanizeTemplateAsts(
|
expect(humanizeTemplateAsts(
|
||||||
parse('<div ng-non-bindable><link rel="stylesheet"></link>a</div>', [])))
|
parse('<div ng-non-bindable><link rel="stylesheet"></link>a</div>', [])))
|
||||||
.toEqual([
|
.toEqual([[ElementAst, 'div'], [AttrAst, 'ng-non-bindable', ''], [TextAst, 'a']]);
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
|
||||||
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
|
|
||||||
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should convert <ng-content> elements into regular elements inside of elements with ng-non-bindable but include them for source info',
|
it('should convert <ng-content> elements into regular elements inside of elements with ng-non-bindable',
|
||||||
() => {
|
() => {
|
||||||
expect(humanizeTemplateAsts(
|
expect(humanizeTemplateAsts(
|
||||||
parse('<div ng-non-bindable><ng-content></ng-content>a</div>', [])))
|
parse('<div ng-non-bindable><ng-content></ng-content>a</div>', [])))
|
||||||
.toEqual([
|
.toEqual([
|
||||||
[ElementAst, 'div', 'TestComp > div:nth-child(0)'],
|
[ElementAst, 'div'],
|
||||||
[AttrAst, 'ng-non-bindable', '', 'TestComp > div:nth-child(0)[ng-non-bindable=]'],
|
[AttrAst, 'ng-non-bindable', ''],
|
||||||
[
|
[ElementAst, 'ng-content'],
|
||||||
ElementAst,
|
[TextAst, 'a']
|
||||||
'ng-content',
|
|
||||||
'TestComp > div:nth-child(0) > ng-content:nth-child(0)'
|
|
||||||
],
|
|
||||||
[TextAst, 'a', 'TestComp > div:nth-child(0) > #text(a):nth-child(1)']
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -991,11 +765,11 @@ export function humanizeTemplateAsts(templateAsts: TemplateAst[]): any[] {
|
||||||
class TemplateHumanizer implements TemplateAstVisitor {
|
class TemplateHumanizer implements TemplateAstVisitor {
|
||||||
result: any[] = [];
|
result: any[] = [];
|
||||||
visitNgContent(ast: NgContentAst, context: any): any {
|
visitNgContent(ast: NgContentAst, context: any): any {
|
||||||
this.result.push([NgContentAst, ast.sourceInfo]);
|
this.result.push([NgContentAst]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
|
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
|
||||||
this.result.push([EmbeddedTemplateAst, ast.sourceInfo]);
|
this.result.push([EmbeddedTemplateAst]);
|
||||||
templateVisitAll(this, ast.attrs);
|
templateVisitAll(this, ast.attrs);
|
||||||
templateVisitAll(this, ast.outputs);
|
templateVisitAll(this, ast.outputs);
|
||||||
templateVisitAll(this, ast.vars);
|
templateVisitAll(this, ast.vars);
|
||||||
|
@ -1004,7 +778,7 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitElement(ast: ElementAst, context: any): any {
|
visitElement(ast: ElementAst, context: any): any {
|
||||||
this.result.push([ElementAst, ast.name, ast.sourceInfo]);
|
this.result.push([ElementAst, ast.name]);
|
||||||
templateVisitAll(this, ast.attrs);
|
templateVisitAll(this, ast.attrs);
|
||||||
templateVisitAll(this, ast.inputs);
|
templateVisitAll(this, ast.inputs);
|
||||||
templateVisitAll(this, ast.outputs);
|
templateVisitAll(this, ast.outputs);
|
||||||
|
@ -1014,17 +788,12 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitVariable(ast: VariableAst, context: any): any {
|
visitVariable(ast: VariableAst, context: any): any {
|
||||||
this.result.push([VariableAst, ast.name, ast.value, ast.sourceInfo]);
|
this.result.push([VariableAst, ast.name, ast.value]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitEvent(ast: BoundEventAst, context: any): any {
|
visitEvent(ast: BoundEventAst, context: any): any {
|
||||||
this.result.push([
|
this.result.push(
|
||||||
BoundEventAst,
|
[BoundEventAst, ast.name, ast.target, expressionUnparser.unparse(ast.handler)]);
|
||||||
ast.name,
|
|
||||||
ast.target,
|
|
||||||
expressionUnparser.unparse(ast.handler),
|
|
||||||
ast.sourceInfo
|
|
||||||
]);
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
|
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
|
||||||
|
@ -1033,25 +802,24 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||||
ast.type,
|
ast.type,
|
||||||
ast.name,
|
ast.name,
|
||||||
expressionUnparser.unparse(ast.value),
|
expressionUnparser.unparse(ast.value),
|
||||||
ast.unit,
|
ast.unit
|
||||||
ast.sourceInfo
|
|
||||||
]);
|
]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitAttr(ast: AttrAst, context: any): any {
|
visitAttr(ast: AttrAst, context: any): any {
|
||||||
this.result.push([AttrAst, ast.name, ast.value, ast.sourceInfo]);
|
this.result.push([AttrAst, ast.name, ast.value]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitBoundText(ast: BoundTextAst, context: any): any {
|
visitBoundText(ast: BoundTextAst, context: any): any {
|
||||||
this.result.push([BoundTextAst, expressionUnparser.unparse(ast.value), ast.sourceInfo]);
|
this.result.push([BoundTextAst, expressionUnparser.unparse(ast.value)]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitText(ast: TextAst, context: any): any {
|
visitText(ast: TextAst, context: any): any {
|
||||||
this.result.push([TextAst, ast.value, ast.sourceInfo]);
|
this.result.push([TextAst, ast.value]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitDirective(ast: DirectiveAst, context: any): any {
|
visitDirective(ast: DirectiveAst, context: any): any {
|
||||||
this.result.push([DirectiveAst, ast.directive, ast.sourceInfo]);
|
this.result.push([DirectiveAst, ast.directive]);
|
||||||
templateVisitAll(this, ast.inputs);
|
templateVisitAll(this, ast.inputs);
|
||||||
templateVisitAll(this, ast.hostProperties);
|
templateVisitAll(this, ast.hostProperties);
|
||||||
templateVisitAll(this, ast.hostEvents);
|
templateVisitAll(this, ast.hostEvents);
|
||||||
|
@ -1059,16 +827,16 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
|
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
|
||||||
this.result.push([
|
this.result.push(
|
||||||
BoundDirectivePropertyAst,
|
[BoundDirectivePropertyAst, ast.directiveName, expressionUnparser.unparse(ast.value)]);
|
||||||
ast.directiveName,
|
|
||||||
expressionUnparser.unparse(ast.value),
|
|
||||||
ast.sourceInfo
|
|
||||||
]);
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sourceInfo(ast: TemplateAst): string {
|
||||||
|
return `${ast.sourceSpan}: ${ast.sourceSpan.start}`;
|
||||||
|
}
|
||||||
|
|
||||||
function humanizeContentProjection(templateAsts: TemplateAst[]): any[] {
|
function humanizeContentProjection(templateAsts: TemplateAst[]): any[] {
|
||||||
var humanizer = new TemplateContentProjectionHumanizer();
|
var humanizer = new TemplateContentProjectionHumanizer();
|
||||||
templateVisitAll(humanizer, templateAsts);
|
templateVisitAll(humanizer, templateAsts);
|
||||||
|
|
|
@ -26,7 +26,7 @@ export function main() {
|
||||||
beforeEach(inject([HtmlParser], (_htmlParser: HtmlParser) => { htmlParser = _htmlParser; }));
|
beforeEach(inject([HtmlParser], (_htmlParser: HtmlParser) => { htmlParser = _htmlParser; }));
|
||||||
|
|
||||||
function preparse(html: string): PreparsedElement {
|
function preparse(html: string): PreparsedElement {
|
||||||
return preparseElement(htmlParser.parse(html, '')[0]);
|
return preparseElement(htmlParser.parse(html, '').rootNodes[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
it('should detect script elements', inject([HtmlParser], (htmlParser: HtmlParser) => {
|
it('should detect script elements', inject([HtmlParser], (htmlParser: HtmlParser) => {
|
||||||
|
|
|
@ -577,9 +577,8 @@ export function main() {
|
||||||
inject(
|
inject(
|
||||||
[TestComponentBuilder, AsyncTestCompleter],
|
[TestComponentBuilder, AsyncTestCompleter],
|
||||||
(tcb: TestComponentBuilder, async) => {
|
(tcb: TestComponentBuilder, async) => {
|
||||||
tcb.overrideView(
|
tcb.overrideView(MyComp, new ViewMetadata({
|
||||||
MyComp, new ViewMetadata({
|
template: '<p><child-cmp var-alice/><child-cmp var-bob/></p>',
|
||||||
template: '<p><child-cmp var-alice></child-cmp><child-cmp var-bob></p>',
|
|
||||||
directives: [ChildComp]
|
directives: [ChildComp]
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
@ -1314,7 +1313,7 @@ export function main() {
|
||||||
tcb =
|
tcb =
|
||||||
tcb.overrideView(MyComp, new ViewMetadata({
|
tcb.overrideView(MyComp, new ViewMetadata({
|
||||||
directives: [DirectiveThrowingAnError],
|
directives: [DirectiveThrowingAnError],
|
||||||
template: `<directive-throwing-error></<directive-throwing-error>`
|
template: `<directive-throwing-error></directive-throwing-error>`
|
||||||
}));
|
}));
|
||||||
|
|
||||||
PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {
|
PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {
|
||||||
|
|
Loading…
Reference in New Issue