revert(format): Revert "chore(format): update to latest formatter"

This reverts commit 03627aa84d.
This commit is contained in:
Alex Rickabaugh
2016-04-12 09:41:01 -07:00
parent 03627aa84d
commit 60727c4d2b
527 changed files with 19246 additions and 13969 deletions
@@ -2,10 +2,34 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {DirectiveIndex, BindingRecord, DirectiveRecord, ChangeDetectionStrategy, ChangeDetectorDefinition, ChangeDetectorGenConfig, ASTWithSource} from 'angular2/src/core/change_detection/change_detection';
import {
DirectiveIndex,
BindingRecord,
DirectiveRecord,
ChangeDetectionStrategy,
ChangeDetectorDefinition,
ChangeDetectorGenConfig,
ASTWithSource
} from 'angular2/src/core/change_detection/change_detection';
import {CompileDirectiveMetadata, CompileTypeMetadata} from './directive_metadata';
import {TemplateAst, ElementAst, BoundTextAst, PropertyBindingType, DirectiveAst, TemplateAstVisitor, templateVisitAll, NgContentAst, EmbeddedTemplateAst, VariableAst, BoundElementPropertyAst, BoundEventAst, BoundDirectivePropertyAst, AttrAst, TextAst} from './template_ast';
import {
TemplateAst,
ElementAst,
BoundTextAst,
PropertyBindingType,
DirectiveAst,
TemplateAstVisitor,
templateVisitAll,
NgContentAst,
EmbeddedTemplateAst,
VariableAst,
BoundElementPropertyAst,
BoundEventAst,
BoundDirectivePropertyAst,
AttrAst,
TextAst
} from './template_ast';
import {LifecycleHooks} from 'angular2/src/core/linker/interfaces';
export function createChangeDetectorDefinitions(
@@ -26,9 +50,8 @@ class ProtoViewVisitor implements TemplateAstVisitor {
eventRecords: BindingRecord[] = [];
directiveRecords: DirectiveRecord[] = [];
constructor(
public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[],
public strategy: ChangeDetectionStrategy) {
constructor(public parent: ProtoViewVisitor, public allVisitors: ProtoViewVisitor[],
public strategy: ChangeDetectionStrategy) {
this.viewIndex = allVisitors.length;
allVisitors.push(this);
}
@@ -73,9 +96,10 @@ class ProtoViewVisitor implements TemplateAstVisitor {
}
visitEvent(ast: BoundEventAst, directiveRecord: DirectiveRecord): any {
var bindingRecord = isPresent(directiveRecord) ?
BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) :
BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1);
var bindingRecord =
isPresent(directiveRecord) ?
BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) :
BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1);
this.eventRecords.push(bindingRecord);
return null;
}
@@ -85,21 +109,25 @@ class ProtoViewVisitor implements TemplateAstVisitor {
var dirIndex = isPresent(directiveRecord) ? directiveRecord.directiveIndex : null;
var bindingRecord;
if (ast.type === PropertyBindingType.Property) {
bindingRecord = isPresent(dirIndex) ?
BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) :
BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name);
bindingRecord =
isPresent(dirIndex) ?
BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) :
BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name);
} else if (ast.type === PropertyBindingType.Attribute) {
bindingRecord = isPresent(dirIndex) ?
BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) :
BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name);
bindingRecord =
isPresent(dirIndex) ?
BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) :
BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name);
} else if (ast.type === PropertyBindingType.Class) {
bindingRecord = isPresent(dirIndex) ?
BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) :
BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name);
bindingRecord =
isPresent(dirIndex) ?
BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) :
BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name);
} else if (ast.type === PropertyBindingType.Style) {
bindingRecord = isPresent(dirIndex) ?
BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) :
BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit);
bindingRecord =
isPresent(dirIndex) ?
BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) :
BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit);
}
this.bindingRecords.push(bindingRecord);
return null;
@@ -167,9 +195,8 @@ class ProtoViewVisitor implements TemplateAstVisitor {
}
function createChangeDefinitions(
pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata,
genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] {
function createChangeDefinitions(pvVisitors: ProtoViewVisitor[], componentType: CompileTypeMetadata,
genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] {
var pvVariableNames = _collectNestedProtoViewsVariableNames(pvVisitors);
return pvVisitors.map(pvVisitor => {
var id = `${componentType.name}_${pvVisitor.viewIndex}`;
@@ -1,6 +1,8 @@
import {CompileTypeMetadata} from './directive_metadata';
import {SourceExpressions, moduleRef} from './source_module';
import {ChangeDetectorJITGenerator} from 'angular2/src/core/change_detection/change_detection_jit_generator';
import {
ChangeDetectorJITGenerator
} from 'angular2/src/core/change_detection/change_detection_jit_generator';
import {AbstractChangeDetector} from 'angular2/src/core/change_detection/abstract_change_detector';
import {ChangeDetectionUtil} from 'angular2/src/core/change_detection/change_detection_util';
import {ChangeDetectorState} from 'angular2/src/core/change_detection/constants';
@@ -8,16 +10,21 @@ import {ChangeDetectorState} from 'angular2/src/core/change_detection/constants'
import {createChangeDetectorDefinitions} from './change_definition_factory';
import {IS_DART, isJsObject, CONST_EXPR} from 'angular2/src/facade/lang';
import {ChangeDetectorGenConfig, ChangeDetectorDefinition, DynamicProtoChangeDetector, ChangeDetectionStrategy} from 'angular2/src/core/change_detection/change_detection';
import {
ChangeDetectorGenConfig,
ChangeDetectorDefinition,
DynamicProtoChangeDetector,
ChangeDetectionStrategy
} from 'angular2/src/core/change_detection/change_detection';
import {TemplateAst} from './template_ast';
import {Codegen} from 'angular2/src/transform/template_compiler/change_detector_codegen';
import {MODULE_SUFFIX} from './util';
import {Injectable} from 'angular2/src/core/di';
const ABSTRACT_CHANGE_DETECTOR = 'AbstractChangeDetector';
const UTIL = 'ChangeDetectionUtil';
const CHANGE_DETECTOR_STATE = 'ChangeDetectorState';
const ABSTRACT_CHANGE_DETECTOR = "AbstractChangeDetector";
const UTIL = "ChangeDetectionUtil";
const CHANGE_DETECTOR_STATE = "ChangeDetectorState";
export const CHANGE_DETECTION_JIT_IMPORTS = CONST_EXPR({
'AbstractChangeDetector': AbstractChangeDetector,
@@ -38,13 +45,12 @@ var CONSTANTS_MODULE =
export class ChangeDetectionCompiler {
constructor(private _genConfig: ChangeDetectorGenConfig) {}
compileComponentRuntime(
componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy,
parsedTemplate: TemplateAst[]): Function[] {
compileComponentRuntime(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy,
parsedTemplate: TemplateAst[]): Function[] {
var changeDetectorDefinitions =
createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate);
return changeDetectorDefinitions.map(
definition => this._createChangeDetectorFactory(definition));
return changeDetectorDefinitions.map(definition =>
this._createChangeDetectorFactory(definition));
}
private _createChangeDetectorFactory(definition: ChangeDetectorDefinition): Function {
@@ -52,9 +58,8 @@ export class ChangeDetectionCompiler {
return () => proto.instantiate();
}
compileComponentCodeGen(
componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy,
parsedTemplate: TemplateAst[]): SourceExpressions {
compileComponentCodeGen(componentType: CompileTypeMetadata, strategy: ChangeDetectionStrategy,
parsedTemplate: TemplateAst[]): SourceExpressions {
var changeDetectorDefinitions =
createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate);
var factories = [];
@@ -69,8 +74,8 @@ export class ChangeDetectionCompiler {
codegen = new Codegen(PREGEN_PROTO_CHANGE_DETECTOR_MODULE);
var className = `_${definition.id}`;
var typeRef = (index === 0 && componentType.isHost) ?
'dynamic' :
`${moduleRef(componentType.moduleUrl)}${componentType.name}`;
'dynamic' :
`${moduleRef(componentType.moduleUrl)}${componentType.name}`;
codegen.generate(typeRef, className, definition);
factories.push(`${className}.newChangeDetector`);
sourcePart = codegen.toString();
+23 -8
View File
@@ -1,6 +1,10 @@
import {RuntimeCompiler_} from './runtime_compiler';
import {RuntimeCompiler_} from "./runtime_compiler";
export {TemplateCompiler} from './template_compiler';
export {CompileDirectiveMetadata, CompileTypeMetadata, CompileTemplateMetadata} from './directive_metadata';
export {
CompileDirectiveMetadata,
CompileTypeMetadata,
CompileTemplateMetadata
} from './directive_metadata';
export {SourceModule, SourceWithImports} from './source_module';
export {PLATFORM_DIRECTIVES, PLATFORM_PIPES} from 'angular2/src/core/platform_directives_and_pipes';
export * from 'angular2/src/compiler/template_ast';
@@ -32,12 +36,23 @@ function _createChangeDetectorGenConfig() {
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
* template compilation.
*/
export const COMPILER_PROVIDERS: Array<Type|Provider|any[]> = CONST_EXPR([
Lexer, Parser, HtmlParser, TemplateParser, TemplateNormalizer, RuntimeMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER, StyleCompiler, ProtoViewCompiler, ViewCompiler,
export const COMPILER_PROVIDERS: Array<Type | Provider | any[]> = CONST_EXPR([
Lexer,
Parser,
HtmlParser,
TemplateParser,
TemplateNormalizer,
RuntimeMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER,
StyleCompiler,
ProtoViewCompiler,
ViewCompiler,
ChangeDetectionCompiler,
new Provider(ChangeDetectorGenConfig, {useFactory: _createChangeDetectorGenConfig, deps: []}),
TemplateCompiler, new Provider(RuntimeCompiler, {useClass: RuntimeCompiler_}),
new Provider(Compiler, {useExisting: RuntimeCompiler}), DomElementSchemaRegistry,
new Provider(ElementSchemaRegistry, {useExisting: DomElementSchemaRegistry}), UrlResolver
TemplateCompiler,
new Provider(RuntimeCompiler, {useClass: RuntimeCompiler_}),
new Provider(Compiler, {useExisting: RuntimeCompiler}),
DomElementSchemaRegistry,
new Provider(ElementSchemaRegistry, {useExisting: DomElementSchemaRegistry}),
UrlResolver
]);
+87 -35
View File
@@ -1,9 +1,65 @@
import {NumberWrapper, StringWrapper, isPresent, resolveEnumToken} from 'angular2/src/facade/lang';
import {NumberWrapper, StringWrapper, isPresent, resolveEnumToken} from "angular2/src/facade/lang";
import {BaseException} from 'angular2/src/facade/exceptions';
import {isWhitespace, $EOF, $HASH, $TILDA, $CARET, $PERCENT, $$, $_, $COLON, $SQ, $DQ, $EQ, $SLASH, $BACKSLASH, $PERIOD, $STAR, $PLUS, $LPAREN, $RPAREN, $LBRACE, $RBRACE, $LBRACKET, $RBRACKET, $PIPE, $COMMA, $SEMICOLON, $MINUS, $BANG, $QUESTION, $AT, $AMPERSAND, $GT, $a, $A, $z, $Z, $0, $9, $FF, $CR, $LF, $VTAB} from 'angular2/src/compiler/chars';
import {
isWhitespace,
$EOF,
$HASH,
$TILDA,
$CARET,
$PERCENT,
$$,
$_,
$COLON,
$SQ,
$DQ,
$EQ,
$SLASH,
$BACKSLASH,
$PERIOD,
$STAR,
$PLUS,
$LPAREN,
$RPAREN,
$LBRACE,
$RBRACE,
$LBRACKET,
$RBRACKET,
$PIPE,
$COMMA,
$SEMICOLON,
$MINUS,
$BANG,
$QUESTION,
$AT,
$AMPERSAND,
$GT,
$a,
$A,
$z,
$Z,
$0,
$9,
$FF,
$CR,
$LF,
$VTAB
} from "angular2/src/compiler/chars";
export {$EOF, $AT, $RBRACE, $LBRACE, $LBRACKET, $RBRACKET, $LPAREN, $RPAREN, $COMMA, $COLON, $SEMICOLON, isWhitespace} from 'angular2/src/compiler/chars';
export {
$EOF,
$AT,
$RBRACE,
$LBRACE,
$LBRACKET,
$RBRACKET,
$LPAREN,
$RPAREN,
$COMMA,
$COLON,
$SEMICOLON,
isWhitespace
} from "angular2/src/compiler/chars";
export enum CssTokenType {
EOF,
@@ -38,37 +94,35 @@ export class LexedCssResult {
constructor(public error: CssScannerError, public token: CssToken) {}
}
export function generateErrorMessage(
input: string, message: string, errorValue: string, index: number, row: number,
column: number): string {
export function generateErrorMessage(input: string, message: string, errorValue: string,
index: number, row: number, column: number): string {
return `${message} at column ${row}:${column} in expression [` +
findProblemCode(input, errorValue, index, column) + ']';
findProblemCode(input, errorValue, index, column) + ']';
}
export function findProblemCode(
input: string, errorValue: string, index: number, column: number): string {
export function findProblemCode(input: string, errorValue: string, index: number,
column: number): string {
var endOfProblemLine = index;
var current = charCode(input, index);
while (current > 0 && !isNewline(current)) {
current = charCode(input, ++endOfProblemLine);
}
var choppedString = input.substring(0, endOfProblemLine);
var pointerPadding = '';
var pointerPadding = "";
for (var i = 0; i < column; i++) {
pointerPadding += ' ';
pointerPadding += " ";
}
var pointerString = '';
var pointerString = "";
for (var i = 0; i < errorValue.length; i++) {
pointerString += '^';
pointerString += "^";
}
return choppedString + '\n' + pointerPadding + pointerString + '\n';
return choppedString + "\n" + pointerPadding + pointerString + "\n";
}
export class CssToken {
numValue: number;
constructor(
public index: number, public column: number, public line: number, public type: CssTokenType,
public strValue: string) {
constructor(public index: number, public column: number, public line: number,
public type: CssTokenType, public strValue: string) {
this.numValue = charCode(strValue, 0);
}
}
@@ -194,7 +248,7 @@ export class CssScanner {
var next = output.token;
if (!isPresent(next)) {
next = new CssToken(0, 0, 0, CssTokenType.EOF, 'end of file');
next = new CssToken(0, 0, 0, CssTokenType.EOF, "end of file");
}
var isMatchingType;
@@ -211,17 +265,16 @@ export class CssScanner {
var error = null;
if (!isMatchingType || (isPresent(value) && value != next.strValue)) {
var errorMessage = resolveEnumToken(CssTokenType, next.type) + ' does not match expected ' +
resolveEnumToken(CssTokenType, type) + ' value';
var errorMessage = resolveEnumToken(CssTokenType, next.type) + " does not match expected " +
resolveEnumToken(CssTokenType, type) + " value";
if (isPresent(value)) {
errorMessage += ' ("' + next.strValue + '" should match "' + value + '")';
}
error = new CssScannerError(
next, generateErrorMessage(
this.input, errorMessage, next.strValue, previousIndex, previousLine,
previousColumn));
next, generateErrorMessage(this.input, errorMessage, next.strValue, previousIndex,
previousLine, previousColumn));
}
return new LexedCssResult(error, next);
@@ -301,8 +354,8 @@ export class CssScanner {
}
scanComment(): CssToken {
if (this.assertCondition(
isCommentStart(this.peek, this.peekPeek), 'Expected comment start value')) {
if (this.assertCondition(isCommentStart(this.peek, this.peekPeek),
"Expected comment start value")) {
return null;
}
@@ -339,8 +392,8 @@ export class CssScanner {
}
scanString(): CssToken {
if (this.assertCondition(
isStringStart(this.peek, this.peekPeek), 'Unexpected non-string starting value')) {
if (this.assertCondition(isStringStart(this.peek, this.peekPeek),
"Unexpected non-string starting value")) {
return null;
}
@@ -359,7 +412,7 @@ export class CssScanner {
this.advance();
}
if (this.assertCondition(this.peek == target, 'Unterminated quote')) {
if (this.assertCondition(this.peek == target, "Unterminated quote")) {
return null;
}
this.advance();
@@ -389,8 +442,8 @@ export class CssScanner {
}
scanIdentifier(): CssToken {
if (this.assertCondition(
isIdentifierStart(this.peek, this.peekPeek), 'Expected identifier starting value')) {
if (this.assertCondition(isIdentifierStart(this.peek, this.peekPeek),
'Expected identifier starting value')) {
return null;
}
@@ -416,9 +469,8 @@ export class CssScanner {
scanCharacter(): CssToken {
var start = this.index;
var startingColumn = this.column;
if (this.assertCondition(
isValidCssCharacter(this.peek, this._currentMode),
charStr(this.peek) + ' is not a valid CSS character')) {
if (this.assertCondition(isValidCssCharacter(this.peek, this._currentMode),
charStr(this.peek) + ' is not a valid CSS character')) {
return null;
}
@@ -505,12 +557,12 @@ function isIdentifierStart(code: number, next: number): boolean {
}
return ($a <= target && target <= $z) || ($A <= target && target <= $Z) || target == $BACKSLASH ||
target == $MINUS || target == $_;
target == $MINUS || target == $_;
}
function isIdentifierPart(target: number): boolean {
return ($a <= target && target <= $z) || ($A <= target && target <= $Z) || target == $BACKSLASH ||
target == $MINUS || target == $_ || isDigit(target);
target == $MINUS || target == $_ || isDigit(target);
}
function isValidPseudoSelectorCharacter(code: number): boolean {
+63 -38
View File
@@ -1,10 +1,40 @@
import {ParseSourceSpan, ParseSourceFile, ParseLocation, ParseError} from 'angular2/src/compiler/parse_util';
import {
ParseSourceSpan,
ParseSourceFile,
ParseLocation,
ParseError
} from "angular2/src/compiler/parse_util";
import {bitWiseOr, bitWiseAnd, NumberWrapper, StringWrapper, isPresent} from 'angular2/src/facade/lang';
import {
bitWiseOr,
bitWiseAnd,
NumberWrapper,
StringWrapper,
isPresent
} from "angular2/src/facade/lang";
import {CssLexerMode, CssToken, CssTokenType, CssScanner, CssScannerError, generateErrorMessage, $AT, $EOF, $RBRACE, $LBRACE, $LBRACKET, $RBRACKET, $LPAREN, $RPAREN, $COMMA, $COLON, $SEMICOLON, isNewline} from 'angular2/src/compiler/css/lexer';
import {
CssLexerMode,
CssToken,
CssTokenType,
CssScanner,
CssScannerError,
generateErrorMessage,
$AT,
$EOF,
$RBRACE,
$LBRACE,
$LBRACKET,
$RBRACKET,
$LPAREN,
$RPAREN,
$COMMA,
$COLON,
$SEMICOLON,
isNewline
} from "angular2/src/compiler/css/lexer";
export {CssToken} from 'angular2/src/compiler/css/lexer';
export {CssToken} from "angular2/src/compiler/css/lexer";
export enum BlockType {
Import,
@@ -30,7 +60,7 @@ const SEMICOLON_DELIM = 32;
const NEWLINE_DELIM = 64;
const RPAREN_DELIM = 128;
function mergeTokens(tokens: CssToken[], separator: string = ''): CssToken {
function mergeTokens(tokens: CssToken[], separator: string = ""): CssToken {
var mainToken = tokens[0];
var str = mainToken.strValue;
for (var i = 1; i < tokens.length; i++) {
@@ -175,9 +205,8 @@ export class CssParser {
var token = this._scan();
this._assertCondition(
token.type == CssTokenType.AtKeyword,
`The CSS Rule ${token.strValue} is not a valid [@] rule.`, token);
this._assertCondition(token.type == CssTokenType.AtKeyword,
`The CSS Rule ${token.strValue} is not a valid [@] rule.`, token);
var block, type = this._resolveBlockType(token);
switch (type) {
@@ -216,12 +245,11 @@ export class CssParser {
default:
var listOfTokens = [];
this._scanner.setMode(CssLexerMode.ALL);
this._error(
generateErrorMessage(
this._scanner.input,
`The CSS "at" rule "${token.strValue}" is not allowed to used here`, token.strValue,
token.index, token.line, token.column),
token);
this._error(generateErrorMessage(
this._scanner.input,
`The CSS "at" rule "${token.strValue}" is not allowed to used here`,
token.strValue, token.index, token.line, token.column),
token);
this._collectUntilDelim(bitWiseOr([delimiters, LBRACE_DELIM, SEMICOLON_DELIM]))
.forEach((token) => { listOfTokens.push(token); });
@@ -375,7 +403,7 @@ export class CssParser {
// contains an inner selector that needs to be parsed
// in isolation
if (this._scanner.getMode() == CssLexerMode.PSEUDO_SELECTOR && isPresent(previousToken) &&
previousToken.numValue == $COLON && token.strValue == 'not' &&
previousToken.numValue == $COLON && token.strValue == "not" &&
this._scanner.peek == $LPAREN) {
selectorCssTokens.push(token);
selectorCssTokens.push(this._consume(CssTokenType.Character, '('));
@@ -425,7 +453,7 @@ export class CssParser {
this._scanner.setMode(CssLexerMode.STYLE_VALUE);
var strValue = '';
var strValue = "";
var tokens = [];
var previous: CssToken;
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
@@ -465,9 +493,9 @@ export class CssParser {
this._consume(CssTokenType.Character, ';');
} else if (code != $RBRACE) {
this._error(
generateErrorMessage(
this._scanner.input, `The CSS key/value definition did not end with a semicolon`,
previous.strValue, previous.index, previous.line, previous.column),
generateErrorMessage(this._scanner.input,
`The CSS key/value definition did not end with a semicolon`,
previous.strValue, previous.index, previous.line, previous.column),
previous);
}
@@ -564,7 +592,7 @@ export class CssParser {
remainingTokens.forEach((token) => { propStr.push(token.strValue); });
}
prop = new CssToken(prop.index, prop.column, prop.line, prop.type, propStr.join(' '));
prop = new CssToken(prop.index, prop.column, prop.line, prop.type, propStr.join(" "));
}
// this means we've reached the end of the definition and/or block
@@ -580,11 +608,10 @@ export class CssParser {
if (parseValue) {
value = this._parseValue(delimiters);
} else {
this._error(
generateErrorMessage(
this._scanner.input, `The CSS property was not paired with a style value`,
prop.strValue, prop.index, prop.line, prop.column),
prop);
this._error(generateErrorMessage(this._scanner.input,
`The CSS property was not paired with a style value`,
prop.strValue, prop.index, prop.line, prop.column),
prop);
}
return new CssDefinitionAST(prop, value);
@@ -602,8 +629,8 @@ export class CssParser {
/** @internal */
_error(message: string, problemToken: CssToken) {
var length = problemToken.strValue.length;
var error = CssParseError.create(
this._file, 0, problemToken.line, problemToken.column, length, message);
var error = CssParseError.create(this._file, 0, problemToken.line, problemToken.column, length,
message);
this._errors.push(error);
}
}
@@ -630,7 +657,7 @@ export class CssKeyframeRuleAST extends CssBlockRuleAST {
export class CssKeyframeDefinitionAST extends CssBlockRuleAST {
public steps;
constructor(_steps: CssToken[], block: CssBlockAST) {
super(BlockType.Keyframes, block, mergeTokens(_steps, ','));
super(BlockType.Keyframes, block, mergeTokens(_steps, ","));
this.steps = _steps;
}
visit(visitor: CssASTVisitor, context?: any) {
@@ -642,11 +669,10 @@ export class CssBlockDefinitionRuleAST extends CssBlockRuleAST {
public strValue: string;
constructor(type: BlockType, public query: CssToken[], block: CssBlockAST) {
super(type, block);
this.strValue = query.map(token => token.strValue).join('');
this.strValue = query.map(token => token.strValue).join("");
var firstCssToken: CssToken = query[0];
this.name = new CssToken(
firstCssToken.index, firstCssToken.column, firstCssToken.line, CssTokenType.Identifier,
this.strValue);
this.name = new CssToken(firstCssToken.index, firstCssToken.column, firstCssToken.line,
CssTokenType.Identifier, this.strValue);
}
visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssBlock(this.block, context); }
}
@@ -666,7 +692,7 @@ export class CssSelectorRuleAST extends CssBlockRuleAST {
constructor(public selectors: CssSelectorAST[], block: CssBlockAST) {
super(BlockType.Selector, block);
this.strValue = selectors.map(selector => selector.strValue).join(',');
this.strValue = selectors.map(selector => selector.strValue).join(",");
}
visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssSelectorRule(this, context); }
@@ -681,7 +707,7 @@ export class CssSelectorAST extends CssAST {
public strValue;
constructor(public tokens: CssToken[], public isComplex: boolean = false) {
super();
this.strValue = tokens.map(token => token.strValue).join('');
this.strValue = tokens.map(token => token.strValue).join("");
}
visit(visitor: CssASTVisitor, context?: any) { visitor.visitCssSelector(this, context); }
}
@@ -697,13 +723,12 @@ export class CssStyleSheetAST extends CssAST {
}
export class CssParseError extends ParseError {
static create(
file: ParseSourceFile, offset: number, line: number, col: number, length: number,
errMsg: string): CssParseError {
static create(file: ParseSourceFile, offset: number, line: number, col: number, length: number,
errMsg: string): CssParseError {
var start = new ParseLocation(file, offset, line, col);
var end = new ParseLocation(file, offset, line, col + length);
var span = new ParseSourceSpan(start, end);
return new CssParseError(span, 'CSS Parse Error: ' + errMsg);
return new CssParseError(span, "CSS Parse Error: " + errMsg);
}
constructor(span: ParseSourceSpan, message: string) { super(span, message); }
@@ -1,7 +1,23 @@
import {isPresent, isBlank, isNumber, isBoolean, normalizeBool, normalizeBlank, serializeEnum, Type, isString, RegExpWrapper, StringWrapper, isArray} from 'angular2/src/facade/lang';
import {
isPresent,
isBlank,
isNumber,
isBoolean,
normalizeBool,
normalizeBlank,
serializeEnum,
Type,
isString,
RegExpWrapper,
StringWrapper,
isArray
} from 'angular2/src/facade/lang';
import {unimplemented} from 'angular2/src/facade/exceptions';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectionStrategy, CHANGE_DETECTION_STRATEGY_VALUES} from 'angular2/src/core/change_detection/change_detection';
import {
ChangeDetectionStrategy,
CHANGE_DETECTION_STRATEGY_VALUES
} from 'angular2/src/core/change_detection/change_detection';
import {ViewEncapsulation, VIEW_ENCAPSULATION_VALUES} from 'angular2/src/core/metadata/view';
import {CssSelector} from 'angular2/src/compiler/selector';
import {splitAtColon} from './util';
@@ -89,7 +105,7 @@ export class CompileDiDependencyMetadata {
isOptional: boolean;
query: CompileQueryMetadata;
viewQuery: CompileQueryMetadata;
token: CompileIdentifierMetadata|string;
token: CompileIdentifierMetadata | string;
constructor({isAttribute, isSelf, isHost, isSkipSelf, isOptional, query, viewQuery, token}: {
isAttribute?: boolean,
@@ -99,7 +115,7 @@ export class CompileDiDependencyMetadata {
isOptional?: boolean,
query?: CompileQueryMetadata,
viewQuery?: CompileQueryMetadata,
token?: CompileIdentifierMetadata|string
token?: CompileIdentifierMetadata | string
} = {}) {
this.isAttribute = normalizeBool(isAttribute);
this.isSelf = normalizeBool(isSelf);
@@ -140,10 +156,10 @@ export class CompileDiDependencyMetadata {
}
export class CompileProviderMetadata {
token: CompileIdentifierMetadata|string;
token: CompileIdentifierMetadata | string;
useClass: CompileTypeMetadata;
useValue: any;
useExisting: CompileIdentifierMetadata|string;
useExisting: CompileIdentifierMetadata | string;
useFactory: CompileFactoryMetadata;
deps: CompileDiDependencyMetadata[];
multi: boolean;
@@ -152,7 +168,7 @@ export class CompileProviderMetadata {
token?: CompileIdentifierMetadata | string,
useClass?: CompileTypeMetadata,
useValue?: any,
useExisting?: CompileIdentifierMetadata|string,
useExisting?: CompileIdentifierMetadata | string,
useFactory?: CompileFactoryMetadata,
deps?: CompileDiDependencyMetadata[],
multi?: boolean
@@ -307,13 +323,13 @@ export class CompileTypeMetadata implements CompileIdentifierMetadata, CompileMe
}
export class CompileQueryMetadata {
selectors: Array<CompileIdentifierMetadata|string>;
selectors: Array<CompileIdentifierMetadata | string>;
descendants: boolean;
first: boolean;
propertyName: string;
constructor({selectors, descendants, first, propertyName}: {
selectors?: Array<CompileIdentifierMetadata|string>,
selectors?: Array<CompileIdentifierMetadata | string>,
descendants?: boolean,
first?: boolean,
propertyName?: string
@@ -373,8 +389,8 @@ export class CompileTemplateMetadata {
static fromJson(data: {[key: string]: any}): CompileTemplateMetadata {
return new CompileTemplateMetadata({
encapsulation: isPresent(data['encapsulation']) ?
VIEW_ENCAPSULATION_VALUES[data['encapsulation']] :
data['encapsulation'],
VIEW_ENCAPSULATION_VALUES[data['encapsulation']] :
data['encapsulation'],
template: data['template'],
templateUrl: data['templateUrl'],
styles: data['styles'],
@@ -385,8 +401,8 @@ export class CompileTemplateMetadata {
toJson(): {[key: string]: any} {
return {
'encapsulation': isPresent(this.encapsulation) ? serializeEnum(this.encapsulation) :
this.encapsulation,
'encapsulation':
isPresent(this.encapsulation) ? serializeEnum(this.encapsulation) : this.encapsulation,
'template': this.template,
'templateUrl': this.templateUrl,
'styles': this.styles,
@@ -400,27 +416,27 @@ export class CompileTemplateMetadata {
* Metadata regarding compilation of a directive.
*/
export class CompileDirectiveMetadata implements CompileMetadataWithType {
static create(
{type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs,
host, lifecycleHooks, providers, viewProviders, queries, viewQueries, template}: {
type?: CompileTypeMetadata,
isComponent?: boolean,
dynamicLoadable?: boolean,
selector?: string,
exportAs?: string,
changeDetection?: ChangeDetectionStrategy,
inputs?: string[],
outputs?: string[],
host?: {[key: string]: string},
lifecycleHooks?: LifecycleHooks[],
providers?:
Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>,
viewProviders?:
Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>,
queries?: CompileQueryMetadata[],
viewQueries?: CompileQueryMetadata[],
template?: CompileTemplateMetadata
} = {}): CompileDirectiveMetadata {
static create({type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs,
outputs, host, lifecycleHooks, providers, viewProviders, queries, viewQueries,
template}: {
type?: CompileTypeMetadata,
isComponent?: boolean,
dynamicLoadable?: boolean,
selector?: string,
exportAs?: string,
changeDetection?: ChangeDetectionStrategy,
inputs?: string[],
outputs?: string[],
host?: {[key: string]: string},
lifecycleHooks?: LifecycleHooks[],
providers?:
Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>,
viewProviders?:
Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>,
queries?: CompileQueryMetadata[],
viewQueries?: CompileQueryMetadata[],
template?: CompileTemplateMetadata
} = {}): CompileDirectiveMetadata {
var hostListeners: {[key: string]: string} = {};
var hostProperties: {[key: string]: string} = {};
var hostAttributes: {[key: string]: string} = {};
@@ -487,35 +503,34 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType {
hostProperties: {[key: string]: string};
hostAttributes: {[key: string]: string};
lifecycleHooks: LifecycleHooks[];
providers: Array<CompileProviderMetadata|CompileTypeMetadata|any[]>;
viewProviders: Array<CompileProviderMetadata|CompileTypeMetadata|any[]>;
providers: Array<CompileProviderMetadata | CompileTypeMetadata | any[]>;
viewProviders: Array<CompileProviderMetadata | CompileTypeMetadata | any[]>;
queries: CompileQueryMetadata[];
viewQueries: CompileQueryMetadata[];
template: CompileTemplateMetadata;
constructor(
{type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs, outputs,
hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers, viewProviders,
queries, viewQueries, template}: {
type?: CompileTypeMetadata,
isComponent?: boolean,
dynamicLoadable?: boolean,
selector?: string,
exportAs?: string,
changeDetection?: ChangeDetectionStrategy,
inputs?: {[key: string]: string},
outputs?: {[key: string]: string},
hostListeners?: {[key: string]: string},
hostProperties?: {[key: string]: string},
hostAttributes?: {[key: string]: string},
lifecycleHooks?: LifecycleHooks[],
providers?:
Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>,
viewProviders?:
Array<CompileProviderMetadata|CompileTypeMetadata|CompileIdentifierMetadata|any[]>,
queries?: CompileQueryMetadata[],
viewQueries?: CompileQueryMetadata[],
template?: CompileTemplateMetadata
} = {}) {
constructor({type, isComponent, dynamicLoadable, selector, exportAs, changeDetection, inputs,
outputs, hostListeners, hostProperties, hostAttributes, lifecycleHooks, providers,
viewProviders, queries, viewQueries, template}: {
type?: CompileTypeMetadata,
isComponent?: boolean,
dynamicLoadable?: boolean,
selector?: string,
exportAs?: string,
changeDetection?: ChangeDetectionStrategy,
inputs?: {[key: string]: string},
outputs?: {[key: string]: string},
hostListeners?: {[key: string]: string},
hostProperties?: {[key: string]: string},
hostAttributes?: {[key: string]: string},
lifecycleHooks?: LifecycleHooks[],
providers?:
Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>,
viewProviders?:
Array<CompileProviderMetadata | CompileTypeMetadata | CompileIdentifierMetadata | any[]>,
queries?: CompileQueryMetadata[],
viewQueries?: CompileQueryMetadata[],
template?: CompileTemplateMetadata
} = {}) {
this.type = type;
this.isComponent = isComponent;
this.dynamicLoadable = dynamicLoadable;
@@ -545,8 +560,8 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType {
exportAs: data['exportAs'],
type: isPresent(data['type']) ? CompileTypeMetadata.fromJson(data['type']) : data['type'],
changeDetection: isPresent(data['changeDetection']) ?
CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] :
data['changeDetection'],
CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] :
data['changeDetection'],
inputs: data['inputs'],
outputs: data['outputs'],
hostListeners: data['hostListeners'],
@@ -591,8 +606,8 @@ export class CompileDirectiveMetadata implements CompileMetadataWithType {
/**
* Construct {@link CompileDirectiveMetadata} from {@link ComponentTypeMetadata} and a selector.
*/
export function createHostComponentMeta(
componentType: CompileTypeMetadata, componentSelector: string): CompileDirectiveMetadata {
export function createHostComponentMeta(componentType: CompileTypeMetadata,
componentSelector: string): CompileDirectiveMetadata {
var template = CssSelector.parse(componentSelector)[0].getMatchingElementTemplate();
return CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({
@@ -623,9 +638,8 @@ export class CompilePipeMetadata implements CompileMetadataWithType {
type: CompileTypeMetadata;
name: string;
pure: boolean;
constructor({type, name, pure}: {type?: CompileTypeMetadata,
name?: string,
pure?: boolean} = {}) {
constructor({type, name,
pure}: {type?: CompileTypeMetadata, name?: string, pure?: boolean} = {}) {
this.type = type;
this.name = name;
this.pure = normalizeBool(pure);
@@ -663,7 +677,7 @@ function arrayFromJson(obj: any[], fn: (a: {[key: string]: any}) => any): any {
return isBlank(obj) ? null : obj.map(o => objFromJson(o, fn));
}
function arrayToJson(obj: any[]): string|{[key: string]: any} {
function arrayToJson(obj: any[]): string | {[key: string]: any} {
return isBlank(obj) ? null : obj.map(objToJson);
}
@@ -673,7 +687,7 @@ function objFromJson(obj: any, fn: (a: {[key: string]: any}) => any): any {
return fn(obj);
}
function objToJson(obj: any): string|{[key: string]: any} {
function objToJson(obj: any): string | {[key: string]: any} {
if (isArray(obj)) return arrayToJson(obj);
if (isString(obj) || isBlank(obj) || isBoolean(obj) || isNumber(obj)) return obj;
return obj.toJson();
+3 -4
View File
@@ -18,10 +18,9 @@ export class HtmlAttrAst implements HtmlAst {
}
export class HtmlElementAst implements HtmlAst {
constructor(
public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[],
public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan,
public endSourceSpan: ParseSourceSpan) {}
constructor(public name: string, public attrs: HtmlAttrAst[], public children: HtmlAst[],
public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan,
public endSourceSpan: ParseSourceSpan) {}
visit(visitor: HtmlAstVisitor, context: any): any { return visitor.visitElement(this, context); }
}
+19 -12
View File
@@ -1,4 +1,11 @@
import {StringWrapper, NumberWrapper, isPresent, isBlank, CONST_EXPR, serializeEnum} from 'angular2/src/facade/lang';
import {
StringWrapper,
NumberWrapper,
isPresent,
isBlank,
CONST_EXPR,
serializeEnum
} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import {ParseLocation, ParseError, ParseSourceFile, ParseSourceSpan} from './parse_util';
import {getHtmlTagDefinition, HtmlTagContentType, NAMED_ENTITIES} from './html_tags';
@@ -22,8 +29,8 @@ export enum HtmlTokenType {
}
export class HtmlToken {
constructor(
public type: HtmlTokenType, public parts: string[], public sourceSpan: ParseSourceSpan) {}
constructor(public type: HtmlTokenType, public parts: string[],
public sourceSpan: ParseSourceSpan) {}
}
export class HtmlTokenError extends ParseError {
@@ -184,8 +191,8 @@ class _HtmlTokenizer {
if (isBlank(end)) {
end = this._getLocation();
}
var token = new HtmlToken(
this.currentTokenType, parts, new ParseSourceSpan(this.currentTokenStart, end));
var token = new HtmlToken(this.currentTokenType, parts,
new ParseSourceSpan(this.currentTokenStart, end));
this.tokens.push(token);
this.currentTokenStart = null;
this.currentTokenType = null;
@@ -232,8 +239,8 @@ class _HtmlTokenizer {
private _requireCharCode(charCode: number) {
var location = this._getLocation();
if (!this._attemptCharCode(charCode)) {
throw this._createError(
unexpectedCharacterErrorMsg(this.peek), this._getSpan(location, location));
throw this._createError(unexpectedCharacterErrorMsg(this.peek),
this._getSpan(location, location));
}
}
@@ -328,12 +335,12 @@ class _HtmlTokenizer {
}
}
private _consumeRawText(
decodeEntities: boolean, firstCharOfEnd: number, attemptEndRest: Function): HtmlToken {
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);
this._beginToken(decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT,
textStart);
var parts = [];
while (true) {
tagCloseStart = this._getLocation();
@@ -536,7 +543,7 @@ function isWhitespace(code: number): boolean {
function isNameEnd(code: number): boolean {
return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ ||
code === $EQ;
code === $EQ;
}
function isPrefixEnd(code: number): boolean {
+24 -16
View File
@@ -1,4 +1,13 @@
import {isPresent, isBlank, StringWrapper, stringify, assertionsEnabled, StringJoiner, serializeEnum, CONST_EXPR} from 'angular2/src/facade/lang';
import {
isPresent,
isBlank,
StringWrapper,
stringify,
assertionsEnabled,
StringJoiner,
serializeEnum,
CONST_EXPR
} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
@@ -26,9 +35,8 @@ export class HtmlParser {
parse(sourceContent: string, sourceUrl: string): HtmlParseTreeResult {
var tokensAndErrors = tokenizeHtml(sourceContent, sourceUrl);
var treeAndErrors = new TreeBuilder(tokensAndErrors.tokens).build();
return new HtmlParseTreeResult(
treeAndErrors.rootNodes,
(<ParseError[]>tokensAndErrors.errors).concat(treeAndErrors.errors));
return new HtmlParseTreeResult(treeAndErrors.rootNodes, (<ParseError[]>tokensAndErrors.errors)
.concat(treeAndErrors.errors));
}
}
@@ -55,9 +63,9 @@ class TreeBuilder {
} else if (this.peek.type === HtmlTokenType.COMMENT_START) {
this._closeVoidElement();
this._consumeComment(this._advance());
} else if (
this.peek.type === HtmlTokenType.TEXT || this.peek.type === HtmlTokenType.RAW_TEXT ||
this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) {
} else if (this.peek.type === HtmlTokenType.TEXT ||
this.peek.type === HtmlTokenType.RAW_TEXT ||
this.peek.type === HtmlTokenType.ESCAPABLE_RAW_TEXT) {
this._closeVoidElement();
this._consumeText(this._advance());
} else {
@@ -166,8 +174,8 @@ class TreeBuilder {
var tagDef = getHtmlTagDefinition(el.name);
var parentEl = this._getParentElement();
if (tagDef.requireExtraParent(isPresent(parentEl) ? parentEl.name : null)) {
var newParent = new HtmlElementAst(
tagDef.parentToAdd, [], [el], el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
var newParent = new HtmlElementAst(tagDef.parentToAdd, [], [el], el.sourceSpan,
el.startSourceSpan, el.endSourceSpan);
this._addToParent(newParent);
this.elementStack.push(newParent);
this.elementStack.push(el);
@@ -184,12 +192,12 @@ class TreeBuilder {
this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
if (getHtmlTagDefinition(fullName).isVoid) {
this.errors.push(HtmlTreeError.create(
fullName, endTagToken.sourceSpan,
`Void elements do not have end tags "${endTagToken.parts[1]}"`));
this.errors.push(
HtmlTreeError.create(fullName, endTagToken.sourceSpan,
`Void elements do not have end tags "${endTagToken.parts[1]}"`));
} else if (!this._popElement(fullName)) {
this.errors.push(HtmlTreeError.create(
fullName, endTagToken.sourceSpan, `Unexpected closing tag "${endTagToken.parts[1]}"`));
this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan,
`Unexpected closing tag "${endTagToken.parts[1]}"`));
}
}
@@ -234,8 +242,8 @@ class TreeBuilder {
}
}
function getElementFullName(
prefix: string, localName: string, parentElement: HtmlElementAst): string {
function getElementFullName(prefix: string, localName: string,
parentElement: HtmlElementAst): string {
if (isBlank(prefix)) {
prefix = getHtmlTagDefinition(localName).implicitNamespacePrefix;
if (isBlank(prefix) && isPresent(parentElement)) {
+43 -15
View File
@@ -1,4 +1,10 @@
import {isPresent, isBlank, normalizeBool, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang';
import {
isPresent,
isBlank,
normalizeBool,
RegExpWrapper,
CONST_EXPR
} from 'angular2/src/facade/lang';
// see http://www.w3.org/TR/html51/syntax.html#named-character-references
// see https://html.spec.whatwg.org/multipage/entities.json
@@ -275,17 +281,16 @@ export class HtmlTagDefinition {
public isVoid: boolean;
public ignoreFirstLf: boolean;
constructor(
{closedByChildren, requiredParents, implicitNamespacePrefix, contentType, closedByParent,
isVoid, ignoreFirstLf}: {
closedByChildren?: string[],
closedByParent?: boolean,
requiredParents?: string[],
implicitNamespacePrefix?: string,
contentType?: HtmlTagContentType,
isVoid?: boolean,
ignoreFirstLf?: boolean
} = {}) {
constructor({closedByChildren, requiredParents, implicitNamespacePrefix, contentType,
closedByParent, isVoid, ignoreFirstLf}: {
closedByChildren?: string[],
closedByParent?: boolean,
requiredParents?: string[],
implicitNamespacePrefix?: string,
contentType?: HtmlTagContentType,
isVoid?: boolean,
ignoreFirstLf?: boolean
} = {}) {
if (isPresent(closedByChildren) && closedByChildren.length > 0) {
closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true);
}
@@ -337,9 +342,32 @@ var TAG_DEFINITIONS: {[key: string]: HtmlTagDefinition} = {
'wbr': new HtmlTagDefinition({isVoid: true}),
'p': new HtmlTagDefinition({
closedByChildren: [
'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr',
'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'
'address',
'article',
'aside',
'blockquote',
'div',
'dl',
'fieldset',
'footer',
'form',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'header',
'hgroup',
'hr',
'main',
'nav',
'ol',
'p',
'pre',
'section',
'table',
'ul'
],
closedByParent: true
}),
@@ -1,8 +1,21 @@
import {Injectable, Provider, provide} from 'angular2/src/core/di';
import {StringWrapper, RegExpWrapper, CONST_EXPR, isBlank, isPresent} from 'angular2/src/facade/lang';
import {
StringWrapper,
RegExpWrapper,
CONST_EXPR,
isBlank,
isPresent
} from 'angular2/src/facade/lang';
import {HtmlAstVisitor, HtmlAttrAst, HtmlElementAst, HtmlTextAst, HtmlCommentAst, HtmlAst} from './html_ast';
import {
HtmlAstVisitor,
HtmlAttrAst,
HtmlElementAst,
HtmlTextAst,
HtmlCommentAst,
HtmlAst
} from './html_ast';
import {HtmlParser, HtmlParseTreeResult} from './html_parser';
import {dashCaseToCamelCase, camelCaseToDashCase} from './util';
@@ -37,8 +50,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor {
this.visitingTemplateEl = ast.name.toLowerCase() == 'template';
let attrs = ast.attrs.map(attr => attr.visit(this, null));
let children = ast.children.map(child => child.visit(this, null));
return new HtmlElementAst(
ast.name, attrs, children, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
return new HtmlElementAst(ast.name, attrs, children, ast.sourceSpan, ast.startSourceSpan,
ast.endSourceSpan);
}
visitAttr(originalAst: HtmlAttrAst, context: any): HtmlAttrAst {
@@ -90,8 +103,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor {
}
return attrName == ast.name && attrValue == ast.value ?
ast :
new HtmlAttrAst(attrName, attrValue, ast.sourceSpan);
ast :
new HtmlAttrAst(attrName, attrValue, ast.sourceSpan);
}
private _rewriteTemplateAttribute(ast: HtmlAttrAst): HtmlAttrAst {
@@ -102,8 +115,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor {
name = 'template';
// rewrite the directive selector
value = StringWrapper.replaceAllMapped(
value, TEMPLATE_SELECTOR_REGEXP, (m) => { return dashCaseToCamelCase(m[1]); });
value = StringWrapper.replaceAllMapped(value, TEMPLATE_SELECTOR_REGEXP,
(m) => { return dashCaseToCamelCase(m[1]); });
// rewrite the var declarations
value = StringWrapper.replaceAllMapped(value, VARIABLE_TPL_BINDING_REGEXP, m => {
@@ -129,8 +142,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor {
} else if (isPresent(m[2])) {
attrName = `[(${dashCaseToCamelCase(m[2])})]`;
} else if (isPresent(m[3])) {
let prop = StringWrapper.replaceAllMapped(
m[3], SPECIAL_PREFIXES_REGEXP, (m) => { return m[1].toLowerCase() + '.'; });
let prop = StringWrapper.replaceAllMapped(m[3], SPECIAL_PREFIXES_REGEXP,
(m) => { return m[1].toLowerCase() + '.'; });
if (prop.startsWith('class.') || prop.startsWith('attr.') || prop.startsWith('style.')) {
attrName = `[${prop}]`;
@@ -144,8 +157,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor {
}
return attrName == ast.name && attrValue == ast.value ?
ast :
new HtmlAttrAst(attrName, attrValue, ast.sourceSpan);
ast :
new HtmlAttrAst(attrName, attrValue, ast.sourceSpan);
}
private _rewriteStar(ast: HtmlAttrAst): HtmlAttrAst {
@@ -161,8 +174,8 @@ export class LegacyHtmlAstTransformer implements HtmlAstVisitor {
}
return attrName == ast.name && attrValue == ast.value ?
ast :
new HtmlAttrAst(attrName, attrValue, ast.sourceSpan);
ast :
new HtmlAttrAst(attrName, attrValue, ast.sourceSpan);
}
private _rewriteInterpolation(ast: HtmlAttrAst): HtmlAttrAst {
@@ -205,7 +218,7 @@ export class LegacyHtmlParser extends HtmlParser {
let rootNodes = htmlParseTreeResult.rootNodes.map(node => node.visit(transformer, null));
return transformer.rewrittenAst.length > 0 ?
new HtmlParseTreeResult(rootNodes, htmlParseTreeResult.errors) :
htmlParseTreeResult;
new HtmlParseTreeResult(rootNodes, htmlParseTreeResult.errors) :
htmlParseTreeResult;
}
}
+5 -6
View File
@@ -1,7 +1,6 @@
export class ParseLocation {
constructor(
public file: ParseSourceFile, public offset: number, public line: number,
public col: number) {}
constructor(public file: ParseSourceFile, public offset: number, public line: number,
public col: number) {}
toString(): string { return `${this.file.url}@${this.line}:${this.col}`; }
}
@@ -34,7 +33,7 @@ export abstract class ParseError {
while (ctxLen < 100 && ctxStart > 0) {
ctxStart--;
ctxLen++;
if (source[ctxStart] == '\n') {
if (source[ctxStart] == "\n") {
if (++ctxLines == 3) {
break;
}
@@ -46,7 +45,7 @@ export abstract class ParseError {
while (ctxLen < 100 && ctxEnd < source.length - 1) {
ctxEnd++;
ctxLen++;
if (source[ctxEnd] == '\n') {
if (source[ctxEnd] == "\n") {
if (++ctxLines == 3) {
break;
}
@@ -54,7 +53,7 @@ export abstract class ParseError {
}
let context = source.substring(ctxStart, this.span.start.offset) + '[ERROR ->]' +
source.substring(this.span.start.offset, ctxEnd + 1);
source.substring(this.span.start.offset, ctxEnd + 1);
return `${this.msg} ("${context}"): ${this.span.start}`;
}
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,12 @@
import {resolveForwardRef} from 'angular2/src/core/di';
import {Type, isBlank, isPresent, isArray, stringify, RegExpWrapper} from 'angular2/src/facade/lang';
import {
Type,
isBlank,
isPresent,
isArray,
stringify,
RegExpWrapper
} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import * as cpl from './directive_metadata';
import * as md from 'angular2/src/core/metadata/directives';
@@ -23,11 +30,10 @@ export class RuntimeMetadataResolver {
private _anonymousTypes = new Map<Object, number>();
private _anonymousTypeIndex = 0;
constructor(
private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver,
private _viewResolver: ViewResolver,
@Optional() @Inject(PLATFORM_DIRECTIVES) private _platformDirectives: Type[],
@Optional() @Inject(PLATFORM_PIPES) private _platformPipes: Type[]) {}
constructor(private _directiveResolver: DirectiveResolver, private _pipeResolver: PipeResolver,
private _viewResolver: ViewResolver,
@Optional() @Inject(PLATFORM_DIRECTIVES) private _platformDirectives: Type[],
@Optional() @Inject(PLATFORM_PIPES) private _platformPipes: Type[]) {}
/**
* Wrap the stringify method to avoid naming things `function (arg1...) {`
@@ -151,7 +157,7 @@ function flattenPipes(view: ViewMetadata, platformPipes: any[]): Type[] {
return pipes;
}
function flattenArray(tree: any[], out: Array<Type|any[]>): void {
function flattenArray(tree: any[], out: Array<Type | any[]>): void {
for (var i = 0; i < tree.length; i++) {
var item = resolveForwardRef(tree[i]);
if (isArray(item)) {
@@ -18,8 +18,8 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry {
if (isBlank(element)) {
var nsAndName = splitNsName(tagName);
element = isPresent(nsAndName[0]) ?
DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) :
DOM.createElement(nsAndName[1]);
DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) :
DOM.createElement(nsAndName[1]);
this._protoElements.set(tagName, element);
}
return element;
+28 -25
View File
@@ -1,5 +1,11 @@
import {Map, ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isBlank, RegExpWrapper, RegExpMatcherWrapper, StringWrapper} from 'angular2/src/facade/lang';
import {
isPresent,
isBlank,
RegExpWrapper,
RegExpMatcherWrapper,
StringWrapper
} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
const _EMPTY_ATTR_VALUE = '';
@@ -30,7 +36,7 @@ export class CssSelector {
var _addResult = (res: CssSelector[], cssSel) => {
if (cssSel.notSelectors.length > 0 && isBlank(cssSel.element) &&
ListWrapper.isEmpty(cssSel.classNames) && ListWrapper.isEmpty(cssSel.attrs)) {
cssSel.element = '*';
cssSel.element = "*";
}
res.push(cssSel);
};
@@ -75,7 +81,7 @@ export class CssSelector {
isElementSelector(): boolean {
return isPresent(this.element) && ListWrapper.isEmpty(this.classNames) &&
ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0;
ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0;
}
setElement(element: string = null) { this.element = element; }
@@ -168,8 +174,8 @@ export class SelectorMatcher {
* @param cssSelector A css selector
* @param callbackCtxt An opaque object that will be given to the callback of the `match` function
*/
private _addSelectable(
cssSelector: CssSelector, callbackCtxt: any, listContext: SelectorListContext) {
private _addSelectable(cssSelector: CssSelector, callbackCtxt: any,
listContext: SelectorListContext) {
var matcher: SelectorMatcher = this;
var element = cssSelector.element;
var classNames = cssSelector.classNames;
@@ -223,8 +229,8 @@ export class SelectorMatcher {
}
}
private _addTerminal(
map: Map<string, SelectorContext[]>, name: string, selectable: SelectorContext) {
private _addTerminal(map: Map<string, SelectorContext[]>, name: string,
selectable: SelectorContext) {
var terminalList = map.get(name);
if (isBlank(terminalList)) {
terminalList = [];
@@ -261,7 +267,7 @@ export class SelectorMatcher {
result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
result;
result;
if (isPresent(classNames)) {
for (var index = 0; index < classNames.length; index++) {
@@ -281,18 +287,18 @@ export class SelectorMatcher {
var terminalValuesMap = this._attrValueMap.get(attrName);
if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) {
result = this._matchTerminal(
terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) ||
result;
result = this._matchTerminal(terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector,
matchedCallback) ||
result;
}
result = this._matchTerminal(terminalValuesMap, attrValue, cssSelector, matchedCallback) ||
result;
result;
var partialValuesMap = this._attrValuePartialMap.get(attrName);
if (!StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) {
result = this._matchPartial(
partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) ||
result;
result = this._matchPartial(partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector,
matchedCallback) ||
result;
}
result =
this._matchPartial(partialValuesMap, attrValue, cssSelector, matchedCallback) || result;
@@ -302,15 +308,14 @@ export class SelectorMatcher {
}
/** @internal */
_matchTerminal(
map: Map<string, SelectorContext[]>, name, cssSelector: CssSelector,
matchedCallback: (c: CssSelector, a: any) => void): boolean {
_matchTerminal(map: Map<string, SelectorContext[]>, name, cssSelector: CssSelector,
matchedCallback: (c: CssSelector, a: any) => void): boolean {
if (isBlank(map) || isBlank(name)) {
return false;
}
var selectables = map.get(name);
var starSelectables = map.get('*');
var starSelectables = map.get("*");
if (isPresent(starSelectables)) {
selectables = selectables.concat(starSelectables);
}
@@ -327,9 +332,8 @@ export class SelectorMatcher {
}
/** @internal */
_matchPartial(
map: Map<string, SelectorMatcher>, name, cssSelector: CssSelector,
matchedCallback /*: (c: CssSelector, a: any) => void*/): boolean {
_matchPartial(map: Map<string, SelectorMatcher>, name, cssSelector: CssSelector,
matchedCallback /*: (c: CssSelector, a: any) => void*/): boolean {
if (isBlank(map) || isBlank(name)) {
return false;
}
@@ -355,9 +359,8 @@ export class SelectorListContext {
export class SelectorContext {
notSelectors: CssSelector[];
constructor(
public selector: CssSelector, public cbContext: any,
public listContext: SelectorListContext) {
constructor(public selector: CssSelector, public cbContext: any,
public listContext: SelectorListContext) {
this.notSelectors = selector.notSelectors;
}
+37 -30
View File
@@ -1,5 +1,12 @@
import {ListWrapper} from 'angular2/src/facade/collection';
import {StringWrapper, RegExp, RegExpWrapper, RegExpMatcherWrapper, isPresent, isBlank} from 'angular2/src/facade/lang';
import {
StringWrapper,
RegExp,
RegExpWrapper,
RegExpMatcherWrapper,
isPresent,
isBlank
} from 'angular2/src/facade/lang';
/**
* This file is a port of shadowCSS from webcomponents.js to TypeScript.
@@ -167,8 +174,8 @@ export class ShadowCss {
**/
private _insertPolyfillDirectivesInCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
return StringWrapper.replaceAllMapped(
cssText, _cssContentNextSelectorRe, function(m) { return m[1] + '{'; });
return StringWrapper.replaceAllMapped(cssText, _cssContentNextSelectorRe,
function(m) { return m[1] + '{'; });
}
/*
@@ -272,8 +279,8 @@ export class ShadowCss {
* scopeName.foo .bar { ... }
*/
private _convertColonHostContext(cssText: string): string {
return this._convertColonRule(
cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
return this._convertColonRule(cssText, _cssColonHostContextRe,
this._colonHostContextPartReplacer);
}
private _convertColonRule(cssText: string, regExp: RegExp, partReplacer: Function): string {
@@ -332,8 +339,8 @@ export class ShadowCss {
});
}
private _scopeSelector(
selector: string, scopeSelector: string, hostSelector: string, strict: boolean): string {
private _scopeSelector(selector: string, scopeSelector: string, hostSelector: string,
strict: boolean): string {
var r = [], parts = selector.split(',');
for (var i = 0; i < parts.length; i++) {
var p = parts[i].trim();
@@ -341,8 +348,8 @@ export class ShadowCss {
var shallowPart = deepParts[0];
if (this._selectorNeedsScoping(shallowPart, scopeSelector)) {
deepParts[0] = strict && !StringWrapper.contains(shallowPart, _polyfillHostNoCombinator) ?
this._applyStrictSelectorScope(shallowPart, scopeSelector) :
this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
this._applyStrictSelectorScope(shallowPart, scopeSelector) :
this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
}
// replace /deep/ with a space for child selectors
r.push(deepParts.join(' '));
@@ -363,15 +370,15 @@ export class ShadowCss {
return RegExpWrapper.create('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
}
private _applySelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
private _applySelectorScope(selector: string, scopeSelector: string,
hostSelector: string): string {
// Difference from webcomponentsjs: scopeSelector could not be an array
return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
}
// scope via name and [is=name]
private _applySimpleSelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
private _applySimpleSelectorScope(selector: string, scopeSelector: string,
hostSelector: string): string {
if (isPresent(RegExpWrapper.firstMatch(_polyfillHostRe, selector))) {
var replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;
selector = StringWrapper.replace(selector, _polyfillHostNoCombinator, replaceBy);
@@ -390,20 +397,19 @@ export class ShadowCss {
for (var i = 0; i < splits.length; i++) {
var sep = splits[i];
var parts = scoped.split(sep);
scoped = parts
.map(p => {
// remove :host since it should be unnecessary
var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, '');
if (t.length > 0 && !ListWrapper.contains(splits, t) &&
!StringWrapper.contains(t, attrName)) {
var re = /([^:]*)(:*)(.*)/g;
var m = RegExpWrapper.firstMatch(re, t);
if (isPresent(m)) {
p = m[1] + attrName + m[2] + m[3];
}
}
return p;
})
scoped = parts.map(p => {
// remove :host since it should be unnecessary
var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, '');
if (t.length > 0 && !ListWrapper.contains(splits, t) &&
!StringWrapper.contains(t, attrName)) {
var re = /([^:]*)(:*)(.*)/g;
var m = RegExpWrapper.firstMatch(re, t);
if (isPresent(m)) {
p = m[1] + attrName + m[2] + m[3];
}
}
return p;
})
.join(sep);
}
return scoped;
@@ -424,13 +430,14 @@ var _polyfillHost = '-shadowcsshost';
// note: :host-context pre-processed to -shadowcsshostcontext.
var _polyfillHostContext = '-shadowcsscontext';
var _parenSuffix = ')(?:\\((' +
'(?:\\([^)(]*\\)|[^)(]*)+?' +
')\\))?([^,{]*)';
'(?:\\([^)(]*\\)|[^)(]*)+?' +
')\\))?([^,{]*)';
var _cssColonHostRe = RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, 'im');
var _cssColonHostContextRe = RegExpWrapper.create('(' + _polyfillHostContext + _parenSuffix, 'im');
var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
var _shadowDOMSelectorsRe = [
/::shadow/g, /::content/g,
/::shadow/g,
/::content/g,
// Deprecated selectors
// TODO(vicb): see https://github.com/angular/clang-format/issues/16
// clang-format off
File diff suppressed because it is too large Load Diff
+18 -14
View File
@@ -7,7 +7,12 @@ import {PromiseWrapper} from 'angular2/src/facade/async';
import {ShadowCss} from 'angular2/src/compiler/shadow_css';
import {UrlResolver} from 'angular2/src/compiler/url_resolver';
import {extractStyleUrls} from './style_url_resolver';
import {escapeSingleQuoteString, codeGenExportVariable, codeGenToString, MODULE_SUFFIX} from './util';
import {
escapeSingleQuoteString,
codeGenExportVariable,
codeGenToString,
MODULE_SUFFIX
} from './util';
import {Injectable} from 'angular2/src/core/di';
const COMPONENT_VARIABLE = '%COMP%';
@@ -21,11 +26,11 @@ export class StyleCompiler {
constructor(private _xhr: XHR, private _urlResolver: UrlResolver) {}
compileComponentRuntime(template: CompileTemplateMetadata): Promise<Array<string|any[]>> {
compileComponentRuntime(template: CompileTemplateMetadata): Promise<Array<string | any[]>> {
var styles = template.styles;
var styleAbsUrls = template.styleUrls;
return this._loadStyles(
styles, styleAbsUrls, template.encapsulation === ViewEncapsulation.Emulated);
return this._loadStyles(styles, styleAbsUrls,
template.encapsulation === ViewEncapsulation.Emulated);
}
compileComponentCodeGen(template: CompileTemplateMetadata): SourceExpression {
@@ -39,31 +44,30 @@ export class StyleCompiler {
this._styleModule(
stylesheetUrl, false,
this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, false)),
this._styleModule(
stylesheetUrl, true,
this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, true))
this._styleModule(stylesheetUrl, true, this._styleCodeGen([styleWithImports.style],
styleWithImports.styleUrls, true))
];
}
clearCache() { this._styleCache.clear(); }
private _loadStyles(plainStyles: string[], absUrls: string[], encapsulate: boolean):
Promise<Array<string|any[]>> {
private _loadStyles(plainStyles: string[], absUrls: string[],
encapsulate: boolean): Promise<Array<string | any[]>> {
var promises: Promise<string[]>[] = absUrls.map((absUrl: string): Promise<string[]> => {
var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`;
var result: Promise<string[]> = this._styleCache.get(cacheKey);
if (isBlank(result)) {
result = this._xhr.get(absUrl).then((style) => {
var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style);
return this._loadStyles(
[styleWithImports.style], styleWithImports.styleUrls, encapsulate);
return this._loadStyles([styleWithImports.style], styleWithImports.styleUrls,
encapsulate);
});
this._styleCache.set(cacheKey, result);
}
return result;
});
return PromiseWrapper.all<string[]>(promises).then((nestedStyles: string[][]) => {
var result: Array<string|any[]> =
var result: Array<string | any[]> =
plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate));
nestedStyles.forEach(styles => result.push(styles));
return result;
@@ -83,8 +87,8 @@ export class StyleCompiler {
return new SourceExpression([], expressionSource);
}
private _styleModule(stylesheetUrl: string, shim: boolean, expression: SourceExpression):
SourceModule {
private _styleModule(stylesheetUrl: string, shim: boolean,
expression: SourceExpression): SourceModule {
var moduleSource = `
${expression.declarations.join('\n')}
${codeGenExportVariable('STYLES')}${expression.expression};
@@ -18,8 +18,8 @@ export function isStyleUrlResolvable(url: string): boolean {
* Rewrites stylesheets by resolving and removing the @import urls that
* are either relative or don't have a `package:` scheme
*/
export function extractStyleUrls(
resolver: UrlResolver, baseUrl: string, cssText: string): StyleWithImports {
export function extractStyleUrls(resolver: UrlResolver, baseUrl: string,
cssText: string): StyleWithImports {
var foundUrls = [];
var modifiedCssText = StringWrapper.replaceAllMapped(cssText, _cssImportRe, (m) => {
var url = isPresent(m[1]) ? m[1] : m[2];
+30 -35
View File
@@ -22,8 +22,8 @@ export interface TemplateAst {
* A segment of text within the template.
*/
export class TextAst implements TemplateAst {
constructor(
public value: string, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
constructor(public value: string, public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any { return visitor.visitText(this, context); }
}
@@ -31,8 +31,8 @@ export class TextAst implements TemplateAst {
* A bound expression within the text of a template.
*/
export class BoundTextAst implements TemplateAst {
constructor(
public value: AST, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
constructor(public value: AST, public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitBoundText(this, context);
}
@@ -50,9 +50,8 @@ export class AttrAst implements TemplateAst {
* A binding for an element property (e.g. `[property]="expression"`).
*/
export class BoundElementPropertyAst implements TemplateAst {
constructor(
public name: string, public type: PropertyBindingType, public value: AST, public unit: string,
public sourceSpan: ParseSourceSpan) {}
constructor(public name: string, public type: PropertyBindingType, public value: AST,
public unit: string, public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitElementProperty(this, context);
}
@@ -62,9 +61,8 @@ export class BoundElementPropertyAst implements TemplateAst {
* A binding for an element event (e.g. `(event)="handler()"`).
*/
export class BoundEventAst implements TemplateAst {
constructor(
public name: string, public target: string, public handler: AST,
public sourceSpan: ParseSourceSpan) {}
constructor(public name: string, public target: string, public handler: AST,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitEvent(this, context);
}
@@ -91,11 +89,11 @@ export class VariableAst implements TemplateAst {
* An element declaration in a template.
*/
export class ElementAst implements TemplateAst {
constructor(
public name: string, public attrs: AttrAst[], public inputs: BoundElementPropertyAst[],
public outputs: BoundEventAst[], public exportAsVars: VariableAst[],
public directives: DirectiveAst[], public children: TemplateAst[],
public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
constructor(public name: string, public attrs: AttrAst[],
public inputs: BoundElementPropertyAst[], public outputs: BoundEventAst[],
public exportAsVars: VariableAst[], public directives: DirectiveAst[],
public children: TemplateAst[], public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitElement(this, context);
}
@@ -104,9 +102,8 @@ export class ElementAst implements TemplateAst {
* Whether the element has any active bindings (inputs, outputs, vars, or directives).
*/
isBound(): boolean {
return (
this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 ||
this.directives.length > 0);
return (this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 ||
this.directives.length > 0);
}
/**
@@ -114,8 +111,8 @@ export class ElementAst implements TemplateAst {
*/
getComponent(): CompileDirectiveMetadata {
return this.directives.length > 0 && this.directives[0].directive.isComponent ?
this.directives[0].directive :
null;
this.directives[0].directive :
null;
}
}
@@ -123,10 +120,9 @@ export class ElementAst implements TemplateAst {
* A `<template>` element included in an Angular template.
*/
export class EmbeddedTemplateAst implements TemplateAst {
constructor(
public attrs: AttrAst[], public outputs: BoundEventAst[], public vars: VariableAst[],
public directives: DirectiveAst[], public children: TemplateAst[],
public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
constructor(public attrs: AttrAst[], public outputs: BoundEventAst[], public vars: VariableAst[],
public directives: DirectiveAst[], public children: TemplateAst[],
public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitEmbeddedTemplate(this, context);
}
@@ -136,9 +132,8 @@ export class EmbeddedTemplateAst implements TemplateAst {
* A directive property with a bound value (e.g. `*ngIf="condition").
*/
export class BoundDirectivePropertyAst implements TemplateAst {
constructor(
public directiveName: string, public templateName: string, public value: AST,
public sourceSpan: ParseSourceSpan) {}
constructor(public directiveName: string, public templateName: string, public value: AST,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitDirectiveProperty(this, context);
}
@@ -148,10 +143,10 @@ export class BoundDirectivePropertyAst implements TemplateAst {
* A directive declared on an element.
*/
export class DirectiveAst implements TemplateAst {
constructor(
public directive: CompileDirectiveMetadata, public inputs: BoundDirectivePropertyAst[],
public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[],
public exportAsVars: VariableAst[], public sourceSpan: ParseSourceSpan) {}
constructor(public directive: CompileDirectiveMetadata,
public inputs: BoundDirectivePropertyAst[],
public hostProperties: BoundElementPropertyAst[], public hostEvents: BoundEventAst[],
public exportAsVars: VariableAst[], public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitDirective(this, context);
}
@@ -161,8 +156,8 @@ export class DirectiveAst implements TemplateAst {
* Position where content is to be projected (instance of `<ng-content>` in a template).
*/
export class NgContentAst implements TemplateAst {
constructor(
public index: number, public ngContentIndex: number, public sourceSpan: ParseSourceSpan) {}
constructor(public index: number, public ngContentIndex: number,
public sourceSpan: ParseSourceSpan) {}
visit(visitor: TemplateAstVisitor, context: any): any {
return visitor.visitNgContent(this, context);
}
@@ -214,8 +209,8 @@ export interface TemplateAstVisitor {
/**
* Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
*/
export function templateVisitAll(
visitor: TemplateAstVisitor, asts: TemplateAst[], context: any = null): any[] {
export function templateVisitAll(visitor: TemplateAstVisitor, asts: TemplateAst[],
context: any = null): any[] {
var result = [];
asts.forEach(ast => {
var astResult = ast.visit(visitor, context);
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,8 @@
import {CompileTypeMetadata, CompileDirectiveMetadata, CompileTemplateMetadata} from './directive_metadata';
import {
CompileTypeMetadata,
CompileDirectiveMetadata,
CompileTemplateMetadata
} from './directive_metadata';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {PromiseWrapper} from 'angular2/src/facade/async';
@@ -10,35 +14,41 @@ import {Injectable} from 'angular2/src/core/di';
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
import {HtmlAstVisitor, HtmlElementAst, HtmlTextAst, HtmlAttrAst, HtmlAst, HtmlCommentAst, htmlVisitAll} from './html_ast';
import {
HtmlAstVisitor,
HtmlElementAst,
HtmlTextAst,
HtmlAttrAst,
HtmlAst,
HtmlCommentAst,
htmlVisitAll
} from './html_ast';
import {HtmlParser} from './html_parser';
import {preparseElement, PreparsedElement, PreparsedElementType} from './template_preparser';
@Injectable()
export class TemplateNormalizer {
constructor(
private _xhr: XHR, private _urlResolver: UrlResolver, private _htmlParser: HtmlParser) {}
constructor(private _xhr: XHR, private _urlResolver: UrlResolver,
private _htmlParser: HtmlParser) {}
normalizeTemplate(directiveType: CompileTypeMetadata, template: CompileTemplateMetadata):
Promise<CompileTemplateMetadata> {
normalizeTemplate(directiveType: CompileTypeMetadata,
template: CompileTemplateMetadata): Promise<CompileTemplateMetadata> {
if (isPresent(template.template)) {
return PromiseWrapper.resolve(this.normalizeLoadedTemplate(
directiveType, template, template.template, directiveType.moduleUrl));
} else if (isPresent(template.templateUrl)) {
var sourceAbsUrl = this._urlResolver.resolve(directiveType.moduleUrl, template.templateUrl);
return this._xhr.get(sourceAbsUrl)
.then(
templateContent => this.normalizeLoadedTemplate(
directiveType, template, templateContent, sourceAbsUrl));
.then(templateContent => this.normalizeLoadedTemplate(directiveType, template,
templateContent, sourceAbsUrl));
} else {
throw new BaseException(`No template specified for component ${directiveType.name}`);
}
}
normalizeLoadedTemplate(
directiveType: CompileTypeMetadata, templateMeta: CompileTemplateMetadata, template: string,
templateAbsUrl: string): CompileTemplateMetadata {
normalizeLoadedTemplate(directiveType: CompileTypeMetadata, templateMeta: CompileTemplateMetadata,
template: string, templateAbsUrl: string): CompileTemplateMetadata {
var rootNodesAndErrors = this._htmlParser.parse(template, directiveType.name);
if (rootNodesAndErrors.errors.length > 0) {
var errorString = rootNodesAndErrors.errors.join('\n');
File diff suppressed because it is too large Load Diff
@@ -59,9 +59,8 @@ export enum PreparsedElementType {
}
export class PreparsedElement {
constructor(
public type: PreparsedElementType, public selectAttr: string, public hrefAttr: string,
public nonBindable: boolean, public projectAs: string) {}
constructor(public type: PreparsedElementType, public selectAttr: string, public hrefAttr: string,
public nonBindable: boolean, public projectAs: string) {}
}
+37 -32
View File
@@ -1,5 +1,11 @@
import {Injectable, Inject} from 'angular2/src/core/di';
import {StringWrapper, isPresent, isBlank, RegExpWrapper, normalizeBlank} from 'angular2/src/facade/lang';
import {
StringWrapper,
isPresent,
isBlank,
RegExpWrapper,
normalizeBlank
} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {ListWrapper} from 'angular2/src/facade/collection';
import {PACKAGE_ROOT_URL} from 'angular2/src/core/application_tokens';
@@ -15,7 +21,7 @@ export function createWithoutPackagePrefix(): UrlResolver {
/**
* A default provider for {@link PACKAGE_ROOT_URL} that maps to '/'.
*/
export var DEFAULT_PACKAGE_URL_PROVIDER = new Provider(PACKAGE_ROOT_URL, {useValue: '/'});
export var DEFAULT_PACKAGE_URL_PROVIDER = new Provider(PACKAGE_ROOT_URL, {useValue: "/"});
/**
* Used by the {@link Compiler} when resolving HTML and CSS template URLs.
@@ -34,7 +40,7 @@ export class UrlResolver {
constructor(@Inject(PACKAGE_ROOT_URL) packagePrefix: string = null) {
if (isPresent(packagePrefix)) {
this._packagePrefix = StringWrapper.stripRight(packagePrefix, '/') + '/';
this._packagePrefix = StringWrapper.stripRight(packagePrefix, "/") + "/";
}
}
@@ -55,8 +61,8 @@ export class UrlResolver {
if (isPresent(baseUrl) && baseUrl.length > 0) {
resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
}
if (isPresent(this._packagePrefix) && getUrlScheme(resolvedUrl) == 'package') {
resolvedUrl = resolvedUrl.replace('package:', this._packagePrefix);
if (isPresent(this._packagePrefix) && getUrlScheme(resolvedUrl) == "package") {
resolvedUrl = resolvedUrl.replace("package:", this._packagePrefix);
}
return resolvedUrl;
}
@@ -67,7 +73,7 @@ export class UrlResolver {
*/
export function getUrlScheme(url: string): string {
var match = _split(url);
return (match && match[_ComponentIndex.Scheme]) || '';
return (match && match[_ComponentIndex.Scheme]) || "";
}
// The code below is adapted from Traceur:
@@ -90,9 +96,9 @@ export function getUrlScheme(url: string): string {
* @param {?string=} opt_fragment The URI-encoded fragment identifier.
* @return {string} The fully combined URI.
*/
function _buildFromEncodedParts(
opt_scheme?: string, opt_userInfo?: string, opt_domain?: string, opt_port?: string,
opt_path?: string, opt_queryData?: string, opt_fragment?: string): string {
function _buildFromEncodedParts(opt_scheme?: string, opt_userInfo?: string, opt_domain?: string,
opt_port?: string, opt_path?: string, opt_queryData?: string,
opt_fragment?: string): string {
var out = [];
if (isPresent(opt_scheme)) {
@@ -190,24 +196,24 @@ function _buildFromEncodedParts(
* @type {!RegExp}
* @internal
*/
var _splitRe = RegExpWrapper.create(
'^' +
'(?:' +
'([^:/?#.]+)' + // scheme - ignore special characters
// used by other URL parts such as :,
// ?, /, #, and .
':)?' +
'(?://' +
'(?:([^/?#]*)@)?' + // userInfo
'([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
// digits, dashes, dots, percent
// escapes, and unicode characters.
'(?::([0-9]+))?' + // port
')?' +
'([^?#]+)?' + // path
'(?:\\?([^#]*))?' + // query
'(?:#(.*))?' + // fragment
'$');
var _splitRe =
RegExpWrapper.create('^' +
'(?:' +
'([^:/?#.]+)' + // scheme - ignore special characters
// used by other URL parts such as :,
// ?, /, #, and .
':)?' +
'(?://' +
'(?:([^/?#]*)@)?' + // userInfo
'([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
// digits, dashes, dots, percent
// escapes, and unicode characters.
'(?::([0-9]+))?' + // port
')?' +
'([^?#]+)?' + // path
'(?:\\?([^#]*))?' + // query
'(?:#(.*))?' + // fragment
'$');
/**
* The index of each URI component in the return value of goog.uri.utils.split.
@@ -238,7 +244,7 @@ enum _ComponentIndex {
* on the browser's regular expression implementation. Never null, since
* arbitrary strings may still look like path names.
*/
function _split(uri: string): Array<string|any> {
function _split(uri: string): Array<string | any> {
return RegExpWrapper.firstMatch(_splitRe, uri);
}
@@ -298,10 +304,9 @@ function _joinAndCanonicalizePath(parts: any[]): string {
path = isBlank(path) ? '' : _removeDotSegments(path);
parts[_ComponentIndex.Path] = path;
return _buildFromEncodedParts(
parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain],
parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData],
parts[_ComponentIndex.Fragment]);
return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo],
parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path,
parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
}
/**
+12 -5
View File
@@ -1,4 +1,11 @@
import {IS_DART, StringWrapper, isBlank, isPresent, isString, isArray} from 'angular2/src/facade/lang';
import {
IS_DART,
StringWrapper,
isBlank,
isPresent,
isString,
isArray
} from 'angular2/src/facade/lang';
var CAMEL_CASE_REGEXP = /([A-Z])/g;
var DASH_CASE_REGEXP = /-([a-z])/g;
@@ -10,13 +17,13 @@ export var MODULE_SUFFIX = IS_DART ? '.dart' : '.js';
export var CONST_VAR = IS_DART ? 'const' : 'var';
export function camelCaseToDashCase(input: string): string {
return StringWrapper.replaceAllMapped(
input, CAMEL_CASE_REGEXP, (m) => { return '-' + m[1].toLowerCase(); });
return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP,
(m) => { return '-' + m[1].toLowerCase(); });
}
export function dashCaseToCamelCase(input: string): string {
return StringWrapper.replaceAllMapped(
input, DASH_CASE_REGEXP, (m) => { return m[1].toUpperCase(); });
return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP,
(m) => { return m[1].toUpperCase(); });
}
export function escapeSingleQuoteString(input: string): string {
File diff suppressed because it is too large Load Diff