refactor(): use const and let instead of var
This commit is contained in:

committed by
Victor Berchet

parent
73593d4bf3
commit
77ee27c59e
@ -29,19 +29,19 @@ export class AnimationCompiler {
|
||||
}
|
||||
}
|
||||
|
||||
var _ANIMATION_FACTORY_ELEMENT_VAR = o.variable('element');
|
||||
var _ANIMATION_DEFAULT_STATE_VAR = o.variable('defaultStateStyles');
|
||||
var _ANIMATION_FACTORY_VIEW_VAR = o.variable('view');
|
||||
var _ANIMATION_FACTORY_VIEW_CONTEXT = _ANIMATION_FACTORY_VIEW_VAR.prop('animationContext');
|
||||
var _ANIMATION_FACTORY_RENDERER_VAR = _ANIMATION_FACTORY_VIEW_VAR.prop('renderer');
|
||||
var _ANIMATION_CURRENT_STATE_VAR = o.variable('currentState');
|
||||
var _ANIMATION_NEXT_STATE_VAR = o.variable('nextState');
|
||||
var _ANIMATION_PLAYER_VAR = o.variable('player');
|
||||
var _ANIMATION_TIME_VAR = o.variable('totalTime');
|
||||
var _ANIMATION_START_STATE_STYLES_VAR = o.variable('startStateStyles');
|
||||
var _ANIMATION_END_STATE_STYLES_VAR = o.variable('endStateStyles');
|
||||
var _ANIMATION_COLLECTED_STYLES = o.variable('collectedStyles');
|
||||
var EMPTY_MAP = o.literalMap([]);
|
||||
const _ANIMATION_FACTORY_ELEMENT_VAR = o.variable('element');
|
||||
const _ANIMATION_DEFAULT_STATE_VAR = o.variable('defaultStateStyles');
|
||||
const _ANIMATION_FACTORY_VIEW_VAR = o.variable('view');
|
||||
const _ANIMATION_FACTORY_VIEW_CONTEXT = _ANIMATION_FACTORY_VIEW_VAR.prop('animationContext');
|
||||
const _ANIMATION_FACTORY_RENDERER_VAR = _ANIMATION_FACTORY_VIEW_VAR.prop('renderer');
|
||||
const _ANIMATION_CURRENT_STATE_VAR = o.variable('currentState');
|
||||
const _ANIMATION_NEXT_STATE_VAR = o.variable('nextState');
|
||||
const _ANIMATION_PLAYER_VAR = o.variable('player');
|
||||
const _ANIMATION_TIME_VAR = o.variable('totalTime');
|
||||
const _ANIMATION_START_STATE_STYLES_VAR = o.variable('startStateStyles');
|
||||
const _ANIMATION_END_STATE_STYLES_VAR = o.variable('endStateStyles');
|
||||
const _ANIMATION_COLLECTED_STYLES = o.variable('collectedStyles');
|
||||
const EMPTY_MAP = o.literalMap([]);
|
||||
|
||||
class _AnimationBuilder implements AnimationAstVisitor {
|
||||
private _fnVarName: string;
|
||||
@ -55,7 +55,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
}
|
||||
|
||||
visitAnimationStyles(ast: AnimationStylesAst, context: _AnimationBuilderContext): o.Expression {
|
||||
var stylesArr: any[] = [];
|
||||
const stylesArr: any[] = [];
|
||||
if (context.isExpectingFirstStyleStep) {
|
||||
stylesArr.push(_ANIMATION_START_STATE_STYLES_VAR);
|
||||
context.isExpectingFirstStyleStep = false;
|
||||
@ -86,8 +86,8 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
return this._visitEndStateAnimation(ast, context);
|
||||
}
|
||||
|
||||
var startingStylesExpr = ast.startingStyles.visit(this, context);
|
||||
var keyframeExpressions =
|
||||
const startingStylesExpr = ast.startingStyles.visit(this, context);
|
||||
const keyframeExpressions =
|
||||
ast.keyframes.map(keyframeEntry => keyframeEntry.visit(this, context));
|
||||
return this._callAnimateMethod(
|
||||
ast, startingStylesExpr, o.literalArr(keyframeExpressions), context);
|
||||
@ -95,9 +95,9 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
|
||||
/** @internal */
|
||||
_visitEndStateAnimation(ast: AnimationStepAst, context: _AnimationBuilderContext): o.Expression {
|
||||
var startingStylesExpr = ast.startingStyles.visit(this, context);
|
||||
var keyframeExpressions = ast.keyframes.map(keyframe => keyframe.visit(this, context));
|
||||
var keyframesExpr =
|
||||
const startingStylesExpr = ast.startingStyles.visit(this, context);
|
||||
const keyframeExpressions = ast.keyframes.map(keyframe => keyframe.visit(this, context));
|
||||
const keyframesExpr =
|
||||
o.importExpr(resolveIdentifier(Identifiers.balanceAnimationKeyframes)).callFn([
|
||||
_ANIMATION_COLLECTED_STYLES, _ANIMATION_END_STATE_STYLES_VAR,
|
||||
o.literalArr(keyframeExpressions)
|
||||
@ -119,14 +119,14 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
|
||||
visitAnimationSequence(ast: AnimationSequenceAst, context: _AnimationBuilderContext):
|
||||
o.Expression {
|
||||
var playerExprs = ast.steps.map(step => step.visit(this, context));
|
||||
const playerExprs = ast.steps.map(step => step.visit(this, context));
|
||||
return o.importExpr(resolveIdentifier(Identifiers.AnimationSequencePlayer)).instantiate([
|
||||
o.literalArr(playerExprs)
|
||||
]);
|
||||
}
|
||||
|
||||
visitAnimationGroup(ast: AnimationGroupAst, context: _AnimationBuilderContext): o.Expression {
|
||||
var playerExprs = ast.steps.map(step => step.visit(this, context));
|
||||
const playerExprs = ast.steps.map(step => step.visit(this, context));
|
||||
return o.importExpr(resolveIdentifier(Identifiers.AnimationGroupPlayer)).instantiate([
|
||||
o.literalArr(playerExprs)
|
||||
]);
|
||||
@ -134,7 +134,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
|
||||
visitAnimationStateDeclaration(
|
||||
ast: AnimationStateDeclarationAst, context: _AnimationBuilderContext): void {
|
||||
var flatStyles: {[key: string]: string | number} = {};
|
||||
const flatStyles: {[key: string]: string | number} = {};
|
||||
_getStylesArray(ast).forEach(
|
||||
entry => { Object.keys(entry).forEach(key => { flatStyles[key] = entry[key]; }); });
|
||||
context.stateMap.registerState(ast.stateName, flatStyles);
|
||||
@ -142,8 +142,8 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
|
||||
visitAnimationStateTransition(
|
||||
ast: AnimationStateTransitionAst, context: _AnimationBuilderContext): any {
|
||||
var steps = ast.animation.steps;
|
||||
var lastStep = steps[steps.length - 1];
|
||||
const steps = ast.animation.steps;
|
||||
const lastStep = steps[steps.length - 1];
|
||||
if (_isEndStateAnimateStep(lastStep)) {
|
||||
context.endStateAnimateStep = <AnimationStepAst>lastStep;
|
||||
}
|
||||
@ -151,7 +151,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
context.totalTransitionTime = 0;
|
||||
context.isExpectingFirstStyleStep = true;
|
||||
|
||||
var stateChangePreconditions: o.Expression[] = [];
|
||||
const stateChangePreconditions: o.Expression[] = [];
|
||||
|
||||
ast.stateChanges.forEach(stateChange => {
|
||||
stateChangePreconditions.push(
|
||||
@ -167,14 +167,14 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
}
|
||||
});
|
||||
|
||||
var animationPlayerExpr = ast.animation.visit(this, context);
|
||||
const animationPlayerExpr = ast.animation.visit(this, context);
|
||||
|
||||
var reducedStateChangesPrecondition = stateChangePreconditions.reduce((a, b) => a.or(b));
|
||||
var precondition =
|
||||
const reducedStateChangesPrecondition = stateChangePreconditions.reduce((a, b) => a.or(b));
|
||||
const precondition =
|
||||
_ANIMATION_PLAYER_VAR.equals(o.NULL_EXPR).and(reducedStateChangesPrecondition);
|
||||
|
||||
var animationStmt = _ANIMATION_PLAYER_VAR.set(animationPlayerExpr).toStmt();
|
||||
var totalTimeStmt = _ANIMATION_TIME_VAR.set(o.literal(context.totalTransitionTime)).toStmt();
|
||||
const animationStmt = _ANIMATION_PLAYER_VAR.set(animationPlayerExpr).toStmt();
|
||||
const totalTimeStmt = _ANIMATION_TIME_VAR.set(o.literal(context.totalTransitionTime)).toStmt();
|
||||
|
||||
return new o.IfStmt(precondition, [animationStmt, totalTimeStmt]);
|
||||
}
|
||||
@ -186,7 +186,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
// this should always be defined even if the user overrides it
|
||||
context.stateMap.registerState(DEFAULT_STATE, {});
|
||||
|
||||
var statements: o.Statement[] = [];
|
||||
const statements: o.Statement[] = [];
|
||||
statements.push(_ANIMATION_FACTORY_VIEW_CONTEXT
|
||||
.callMethod(
|
||||
'cancelActiveAnimation',
|
||||
@ -221,7 +221,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
_ANIMATION_END_STATE_STYLES_VAR.equals(o.NULL_EXPR),
|
||||
[_ANIMATION_END_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()]));
|
||||
|
||||
var RENDER_STYLES_FN = o.importExpr(resolveIdentifier(Identifiers.renderStyles));
|
||||
const RENDER_STYLES_FN = o.importExpr(resolveIdentifier(Identifiers.renderStyles));
|
||||
|
||||
// before we start any animation we want to clear out the starting
|
||||
// styles from the element's style property (since they were placed
|
||||
@ -297,16 +297,16 @@ class _AnimationBuilder implements AnimationAstVisitor {
|
||||
}
|
||||
|
||||
build(ast: AnimationAst): AnimationEntryCompileResult {
|
||||
var context = new _AnimationBuilderContext();
|
||||
var fnStatement = ast.visit(this, context).toDeclStmt(this._fnVarName);
|
||||
var fnVariable = o.variable(this._fnVarName);
|
||||
const context = new _AnimationBuilderContext();
|
||||
const fnStatement = ast.visit(this, context).toDeclStmt(this._fnVarName);
|
||||
const fnVariable = o.variable(this._fnVarName);
|
||||
|
||||
var lookupMap: any[] = [];
|
||||
const lookupMap: any[] = [];
|
||||
Object.keys(context.stateMap.states).forEach(stateName => {
|
||||
const value = context.stateMap.states[stateName];
|
||||
var variableValue = EMPTY_MAP;
|
||||
let variableValue = EMPTY_MAP;
|
||||
if (isPresent(value)) {
|
||||
let styleMap: any[] = [];
|
||||
const styleMap: any[] = [];
|
||||
Object.keys(value).forEach(key => { styleMap.push([key, o.literal(value[key])]); });
|
||||
variableValue = o.literalMap(styleMap);
|
||||
}
|
||||
@ -331,7 +331,7 @@ class _AnimationBuilderStateMap {
|
||||
private _states: {[key: string]: {[prop: string]: string | number}} = {};
|
||||
get states() { return this._states; }
|
||||
registerState(name: string, value: {[prop: string]: string | number} = null): void {
|
||||
var existingEntry = this._states[name];
|
||||
const existingEntry = this._states[name];
|
||||
if (!existingEntry) {
|
||||
this._states[name] = value;
|
||||
}
|
||||
@ -339,7 +339,7 @@ class _AnimationBuilderStateMap {
|
||||
}
|
||||
|
||||
function _compareToAnimationStateExpr(value: o.Expression, animationState: string): o.Expression {
|
||||
var emptyStateLiteral = o.literal(EMPTY_STATE);
|
||||
const emptyStateLiteral = o.literal(EMPTY_STATE);
|
||||
switch (animationState) {
|
||||
case EMPTY_STATE:
|
||||
return value.equals(emptyStateLiteral);
|
||||
@ -356,8 +356,8 @@ function _isEndStateAnimateStep(step: AnimationAst): boolean {
|
||||
// the final animation step is characterized by having only TWO
|
||||
// keyframe values and it must have zero styles for both keyframes
|
||||
if (step instanceof AnimationStepAst && step.duration > 0 && step.keyframes.length == 2) {
|
||||
var styles1 = _getStylesArray(step.keyframes[0])[0];
|
||||
var styles2 = _getStylesArray(step.keyframes[1])[0];
|
||||
const styles1 = _getStylesArray(step.keyframes[0])[0];
|
||||
const styles2 = _getStylesArray(step.keyframes[1])[0];
|
||||
return Object.keys(styles1).length === 0 && Object.keys(styles2).length === 0;
|
||||
}
|
||||
return false;
|
||||
|
@ -72,11 +72,11 @@ export class AnimationParser {
|
||||
}
|
||||
|
||||
parseEntry(entry: CompileAnimationEntryMetadata): AnimationEntryParseResult {
|
||||
var errors: AnimationParseError[] = [];
|
||||
var stateStyles: {[key: string]: AnimationStylesAst} = {};
|
||||
var transitions: CompileAnimationStateTransitionMetadata[] = [];
|
||||
const errors: AnimationParseError[] = [];
|
||||
const stateStyles: {[key: string]: AnimationStylesAst} = {};
|
||||
const transitions: CompileAnimationStateTransitionMetadata[] = [];
|
||||
|
||||
var stateDeclarationAsts: AnimationStateDeclarationAst[] = [];
|
||||
const stateDeclarationAsts: AnimationStateDeclarationAst[] = [];
|
||||
entry.definitions.forEach(def => {
|
||||
if (def instanceof CompileAnimationStateDeclarationMetadata) {
|
||||
_parseAnimationDeclarationStates(def, this._schema, errors).forEach(ast => {
|
||||
@ -88,10 +88,10 @@ export class AnimationParser {
|
||||
}
|
||||
});
|
||||
|
||||
var stateTransitionAsts = transitions.map(
|
||||
const stateTransitionAsts = transitions.map(
|
||||
transDef => _parseAnimationStateTransition(transDef, stateStyles, this._schema, errors));
|
||||
|
||||
var ast = new AnimationEntryAst(entry.name, stateDeclarationAsts, stateTransitionAsts);
|
||||
const ast = new AnimationEntryAst(entry.name, stateDeclarationAsts, stateTransitionAsts);
|
||||
return new AnimationEntryParseResult(ast, errors);
|
||||
}
|
||||
}
|
||||
@ -99,9 +99,9 @@ export class AnimationParser {
|
||||
function _parseAnimationDeclarationStates(
|
||||
stateMetadata: CompileAnimationStateDeclarationMetadata, schema: ElementSchemaRegistry,
|
||||
errors: AnimationParseError[]): AnimationStateDeclarationAst[] {
|
||||
var normalizedStyles = _normalizeStyleMetadata(stateMetadata.styles, {}, schema, errors, false);
|
||||
var defStyles = new AnimationStylesAst(normalizedStyles);
|
||||
var states = stateMetadata.stateNameExpr.split(/\s*,\s*/);
|
||||
const normalizedStyles = _normalizeStyleMetadata(stateMetadata.styles, {}, schema, errors, false);
|
||||
const defStyles = new AnimationStylesAst(normalizedStyles);
|
||||
const states = stateMetadata.stateNameExpr.split(/\s*,\s*/);
|
||||
return states.map(state => new AnimationStateDeclarationAst(state, defStyles));
|
||||
}
|
||||
|
||||
@ -109,19 +109,19 @@ function _parseAnimationStateTransition(
|
||||
transitionStateMetadata: CompileAnimationStateTransitionMetadata,
|
||||
stateStyles: {[key: string]: AnimationStylesAst}, schema: ElementSchemaRegistry,
|
||||
errors: AnimationParseError[]): AnimationStateTransitionAst {
|
||||
var styles = new StylesCollection();
|
||||
var transitionExprs: AnimationStateTransitionExpression[] = [];
|
||||
var transitionStates = transitionStateMetadata.stateChangeExpr.split(/\s*,\s*/);
|
||||
const styles = new StylesCollection();
|
||||
const transitionExprs: AnimationStateTransitionExpression[] = [];
|
||||
const transitionStates = transitionStateMetadata.stateChangeExpr.split(/\s*,\s*/);
|
||||
transitionStates.forEach(
|
||||
expr => { transitionExprs.push(..._parseAnimationTransitionExpr(expr, errors)); });
|
||||
var entry = _normalizeAnimationEntry(transitionStateMetadata.steps);
|
||||
var animation = _normalizeStyleSteps(entry, stateStyles, schema, errors);
|
||||
var animationAst = _parseTransitionAnimation(animation, 0, styles, stateStyles, errors);
|
||||
const entry = _normalizeAnimationEntry(transitionStateMetadata.steps);
|
||||
const animation = _normalizeStyleSteps(entry, stateStyles, schema, errors);
|
||||
const animationAst = _parseTransitionAnimation(animation, 0, styles, stateStyles, errors);
|
||||
if (errors.length == 0) {
|
||||
_fillAnimationAstStartingKeyframes(animationAst, styles, errors);
|
||||
}
|
||||
|
||||
var stepsAst: AnimationWithStepsAst = (animationAst instanceof AnimationWithStepsAst) ?
|
||||
const stepsAst: AnimationWithStepsAst = (animationAst instanceof AnimationWithStepsAst) ?
|
||||
animationAst :
|
||||
new AnimationSequenceAst([animationAst]);
|
||||
|
||||
@ -143,22 +143,22 @@ function _parseAnimationAlias(alias: string, errors: AnimationParseError[]): str
|
||||
|
||||
function _parseAnimationTransitionExpr(
|
||||
eventStr: string, errors: AnimationParseError[]): AnimationStateTransitionExpression[] {
|
||||
var expressions: AnimationStateTransitionExpression[] = [];
|
||||
const expressions: AnimationStateTransitionExpression[] = [];
|
||||
if (eventStr[0] == ':') {
|
||||
eventStr = _parseAnimationAlias(eventStr, errors);
|
||||
}
|
||||
var match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
|
||||
const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
|
||||
if (!isPresent(match) || match.length < 4) {
|
||||
errors.push(new AnimationParseError(`the provided ${eventStr} is not of a supported format`));
|
||||
return expressions;
|
||||
}
|
||||
|
||||
var fromState = match[1];
|
||||
var separator = match[2];
|
||||
var toState = match[3];
|
||||
const fromState = match[1];
|
||||
const separator = match[2];
|
||||
const toState = match[3];
|
||||
expressions.push(new AnimationStateTransitionExpression(fromState, toState));
|
||||
|
||||
var isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
|
||||
const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
|
||||
if (separator[0] == '<' && !isFullAnyStateExpr) {
|
||||
expressions.push(new AnimationStateTransitionExpression(toState, fromState));
|
||||
}
|
||||
@ -174,7 +174,7 @@ function _normalizeStyleMetadata(
|
||||
entry: CompileAnimationStyleMetadata, stateStyles: {[key: string]: AnimationStylesAst},
|
||||
schema: ElementSchemaRegistry, errors: AnimationParseError[],
|
||||
permitStateReferences: boolean): {[key: string]: string | number}[] {
|
||||
var normalizedStyles: {[key: string]: string | number}[] = [];
|
||||
const normalizedStyles: {[key: string]: string | number}[] = [];
|
||||
entry.styles.forEach(styleEntry => {
|
||||
if (typeof styleEntry === 'string') {
|
||||
if (permitStateReferences) {
|
||||
@ -184,13 +184,13 @@ function _normalizeStyleMetadata(
|
||||
`State based animations cannot contain references to other states`));
|
||||
}
|
||||
} else {
|
||||
var stylesObj = <Styles>styleEntry;
|
||||
var normalizedStylesObj: Styles = {};
|
||||
const stylesObj = <Styles>styleEntry;
|
||||
const normalizedStylesObj: Styles = {};
|
||||
Object.keys(stylesObj).forEach(propName => {
|
||||
var normalizedProp = schema.normalizeAnimationStyleProperty(propName);
|
||||
var normalizedOutput =
|
||||
const normalizedProp = schema.normalizeAnimationStyleProperty(propName);
|
||||
const normalizedOutput =
|
||||
schema.normalizeAnimationStyleValue(normalizedProp, propName, stylesObj[propName]);
|
||||
var normalizationError = normalizedOutput['error'];
|
||||
const normalizationError = normalizedOutput['error'];
|
||||
if (normalizationError) {
|
||||
errors.push(new AnimationParseError(normalizationError));
|
||||
}
|
||||
@ -205,7 +205,7 @@ function _normalizeStyleMetadata(
|
||||
function _normalizeStyleSteps(
|
||||
entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst},
|
||||
schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata {
|
||||
var steps = _normalizeStyleStepEntry(entry, stateStyles, schema, errors);
|
||||
const steps = _normalizeStyleStepEntry(entry, stateStyles, schema, errors);
|
||||
return (entry instanceof CompileAnimationGroupMetadata) ?
|
||||
new CompileAnimationGroupMetadata(steps) :
|
||||
new CompileAnimationSequenceMetadata(steps);
|
||||
@ -214,8 +214,8 @@ function _normalizeStyleSteps(
|
||||
function _mergeAnimationStyles(
|
||||
stylesList: any[], newItem: {[key: string]: string | number} | string) {
|
||||
if (typeof newItem === 'object' && newItem !== null && stylesList.length > 0) {
|
||||
var lastIndex = stylesList.length - 1;
|
||||
var lastItem = stylesList[lastIndex];
|
||||
const lastIndex = stylesList.length - 1;
|
||||
const lastItem = stylesList[lastIndex];
|
||||
if (typeof lastItem === 'object' && lastItem !== null) {
|
||||
stylesList[lastIndex] = StringMapWrapper.merge(
|
||||
<{[key: string]: string | number}>lastItem, <{[key: string]: string | number}>newItem);
|
||||
@ -228,15 +228,15 @@ function _mergeAnimationStyles(
|
||||
function _normalizeStyleStepEntry(
|
||||
entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst},
|
||||
schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata[] {
|
||||
var steps: CompileAnimationMetadata[];
|
||||
let steps: CompileAnimationMetadata[];
|
||||
if (entry instanceof CompileAnimationWithStepsMetadata) {
|
||||
steps = entry.steps;
|
||||
} else {
|
||||
return [entry];
|
||||
}
|
||||
|
||||
var newSteps: CompileAnimationMetadata[] = [];
|
||||
var combinedStyles: Styles[];
|
||||
const newSteps: CompileAnimationMetadata[] = [];
|
||||
let combinedStyles: Styles[];
|
||||
steps.forEach(step => {
|
||||
if (step instanceof CompileAnimationStyleMetadata) {
|
||||
// this occurs when a style step is followed by a previous style step
|
||||
@ -262,7 +262,7 @@ function _normalizeStyleStepEntry(
|
||||
if (step instanceof CompileAnimationAnimateMetadata) {
|
||||
// we do not recurse into CompileAnimationAnimateMetadata since
|
||||
// those style steps are not going to be squashed
|
||||
var animateStyleValue = (<CompileAnimationAnimateMetadata>step).styles;
|
||||
const animateStyleValue = (<CompileAnimationAnimateMetadata>step).styles;
|
||||
if (animateStyleValue instanceof CompileAnimationStyleMetadata) {
|
||||
animateStyleValue.styles =
|
||||
_normalizeStyleMetadata(animateStyleValue, stateStyles, schema, errors, true);
|
||||
@ -272,7 +272,7 @@ function _normalizeStyleStepEntry(
|
||||
});
|
||||
}
|
||||
} else if (step instanceof CompileAnimationWithStepsMetadata) {
|
||||
let innerSteps = _normalizeStyleStepEntry(step, stateStyles, schema, errors);
|
||||
const innerSteps = _normalizeStyleStepEntry(step, stateStyles, schema, errors);
|
||||
step = step instanceof CompileAnimationGroupMetadata ?
|
||||
new CompileAnimationGroupMetadata(innerSteps) :
|
||||
new CompileAnimationSequenceMetadata(innerSteps);
|
||||
@ -294,12 +294,12 @@ function _normalizeStyleStepEntry(
|
||||
function _resolveStylesFromState(
|
||||
stateName: string, stateStyles: {[key: string]: AnimationStylesAst},
|
||||
errors: AnimationParseError[]) {
|
||||
var styles: Styles[] = [];
|
||||
const styles: Styles[] = [];
|
||||
if (stateName[0] != ':') {
|
||||
errors.push(new AnimationParseError(`Animation states via styles must be prefixed with a ":"`));
|
||||
} else {
|
||||
var normalizedStateName = stateName.substring(1);
|
||||
var value = stateStyles[normalizedStateName];
|
||||
const normalizedStateName = stateName.substring(1);
|
||||
const value = stateStyles[normalizedStateName];
|
||||
if (!isPresent(value)) {
|
||||
errors.push(new AnimationParseError(
|
||||
`Unable to apply styles due to missing a state: "${normalizedStateName}"`));
|
||||
@ -322,8 +322,8 @@ function _parseAnimationKeyframes(
|
||||
keyframeSequence: CompileAnimationKeyframesSequenceMetadata, currentTime: number,
|
||||
collectedStyles: StylesCollection, stateStyles: {[key: string]: AnimationStylesAst},
|
||||
errors: AnimationParseError[]): AnimationKeyframeAst[] {
|
||||
var totalEntries = keyframeSequence.steps.length;
|
||||
var totalOffsets = 0;
|
||||
const totalEntries = keyframeSequence.steps.length;
|
||||
let totalOffsets = 0;
|
||||
keyframeSequence.steps.forEach(step => totalOffsets += (isPresent(step.offset) ? 1 : 0));
|
||||
|
||||
if (totalOffsets > 0 && totalOffsets < totalEntries) {
|
||||
@ -332,15 +332,15 @@ function _parseAnimationKeyframes(
|
||||
totalOffsets = totalEntries;
|
||||
}
|
||||
|
||||
var limit = totalEntries - 1;
|
||||
var margin = totalOffsets == 0 ? (1 / limit) : 0;
|
||||
var rawKeyframes: any[] /** TODO #9100 */ = [];
|
||||
var index = 0;
|
||||
var doSortKeyframes = false;
|
||||
var lastOffset = 0;
|
||||
let limit = totalEntries - 1;
|
||||
const margin = totalOffsets == 0 ? (1 / limit) : 0;
|
||||
const rawKeyframes: any[] /** TODO #9100 */ = [];
|
||||
let index = 0;
|
||||
let doSortKeyframes = false;
|
||||
let lastOffset = 0;
|
||||
keyframeSequence.steps.forEach(styleMetadata => {
|
||||
var offset = styleMetadata.offset;
|
||||
var keyframeStyles: Styles = {};
|
||||
let offset = styleMetadata.offset;
|
||||
const keyframeStyles: Styles = {};
|
||||
styleMetadata.styles.forEach(entry => {
|
||||
Object.keys(entry).forEach(prop => {
|
||||
if (prop != 'offset') {
|
||||
@ -364,23 +364,23 @@ function _parseAnimationKeyframes(
|
||||
rawKeyframes.sort((a, b) => a[0] <= b[0] ? -1 : 1);
|
||||
}
|
||||
|
||||
var firstKeyframe = rawKeyframes[0];
|
||||
let firstKeyframe = rawKeyframes[0];
|
||||
if (firstKeyframe[0] != _INITIAL_KEYFRAME) {
|
||||
rawKeyframes.splice(0, 0, firstKeyframe = [_INITIAL_KEYFRAME, {}]);
|
||||
}
|
||||
|
||||
var firstKeyframeStyles = firstKeyframe[1];
|
||||
const firstKeyframeStyles = firstKeyframe[1];
|
||||
limit = rawKeyframes.length - 1;
|
||||
var lastKeyframe = rawKeyframes[limit];
|
||||
let lastKeyframe = rawKeyframes[limit];
|
||||
if (lastKeyframe[0] != _TERMINAL_KEYFRAME) {
|
||||
rawKeyframes.push(lastKeyframe = [_TERMINAL_KEYFRAME, {}]);
|
||||
limit++;
|
||||
}
|
||||
|
||||
var lastKeyframeStyles = lastKeyframe[1];
|
||||
const lastKeyframeStyles = lastKeyframe[1];
|
||||
for (let i = 1; i <= limit; i++) {
|
||||
let entry = rawKeyframes[i];
|
||||
let styles = entry[1];
|
||||
const entry = rawKeyframes[i];
|
||||
const styles = entry[1];
|
||||
|
||||
Object.keys(styles).forEach(prop => {
|
||||
if (!isPresent(firstKeyframeStyles[prop])) {
|
||||
@ -390,8 +390,8 @@ function _parseAnimationKeyframes(
|
||||
}
|
||||
|
||||
for (let i = limit - 1; i >= 0; i--) {
|
||||
let entry = rawKeyframes[i];
|
||||
let styles = entry[1];
|
||||
const entry = rawKeyframes[i];
|
||||
const styles = entry[1];
|
||||
|
||||
Object.keys(styles).forEach(prop => {
|
||||
if (!isPresent(lastKeyframeStyles[prop])) {
|
||||
@ -407,21 +407,21 @@ function _parseAnimationKeyframes(
|
||||
function _parseTransitionAnimation(
|
||||
entry: CompileAnimationMetadata, currentTime: number, collectedStyles: StylesCollection,
|
||||
stateStyles: {[key: string]: AnimationStylesAst}, errors: AnimationParseError[]): AnimationAst {
|
||||
var ast: any /** TODO #9100 */;
|
||||
var playTime = 0;
|
||||
var startingTime = currentTime;
|
||||
let ast: any /** TODO #9100 */;
|
||||
let playTime = 0;
|
||||
const startingTime = currentTime;
|
||||
if (entry instanceof CompileAnimationWithStepsMetadata) {
|
||||
var maxDuration = 0;
|
||||
var steps: any[] /** TODO #9100 */ = [];
|
||||
var isGroup = entry instanceof CompileAnimationGroupMetadata;
|
||||
var previousStyles: any /** TODO #9100 */;
|
||||
let maxDuration = 0;
|
||||
const steps: any[] /** TODO #9100 */ = [];
|
||||
const isGroup = entry instanceof CompileAnimationGroupMetadata;
|
||||
let previousStyles: any /** TODO #9100 */;
|
||||
entry.steps.forEach(entry => {
|
||||
// these will get picked up by the next step...
|
||||
var time = isGroup ? startingTime : currentTime;
|
||||
const time = isGroup ? startingTime : currentTime;
|
||||
if (entry instanceof CompileAnimationStyleMetadata) {
|
||||
entry.styles.forEach(stylesEntry => {
|
||||
// by this point we know that we only have stringmap values
|
||||
var map = stylesEntry as Styles;
|
||||
const map = stylesEntry as Styles;
|
||||
Object.keys(map).forEach(
|
||||
prop => { collectedStyles.insertAtTime(prop, time, map[prop]); });
|
||||
});
|
||||
@ -429,26 +429,26 @@ function _parseTransitionAnimation(
|
||||
return;
|
||||
}
|
||||
|
||||
var innerAst = _parseTransitionAnimation(entry, time, collectedStyles, stateStyles, errors);
|
||||
const innerAst = _parseTransitionAnimation(entry, time, collectedStyles, stateStyles, errors);
|
||||
if (isPresent(previousStyles)) {
|
||||
if (entry instanceof CompileAnimationWithStepsMetadata) {
|
||||
let startingStyles = new AnimationStylesAst(previousStyles);
|
||||
const startingStyles = new AnimationStylesAst(previousStyles);
|
||||
steps.push(new AnimationStepAst(startingStyles, [], 0, 0, ''));
|
||||
} else {
|
||||
var innerStep = <AnimationStepAst>innerAst;
|
||||
const innerStep = <AnimationStepAst>innerAst;
|
||||
innerStep.startingStyles.styles.push(...previousStyles);
|
||||
}
|
||||
previousStyles = null;
|
||||
}
|
||||
|
||||
var astDuration = innerAst.playTime;
|
||||
const astDuration = innerAst.playTime;
|
||||
currentTime += astDuration;
|
||||
playTime += astDuration;
|
||||
maxDuration = Math.max(astDuration, maxDuration);
|
||||
steps.push(innerAst);
|
||||
});
|
||||
if (isPresent(previousStyles)) {
|
||||
let startingStyles = new AnimationStylesAst(previousStyles);
|
||||
const startingStyles = new AnimationStylesAst(previousStyles);
|
||||
steps.push(new AnimationStepAst(startingStyles, [], 0, 0, ''));
|
||||
}
|
||||
if (isGroup) {
|
||||
@ -459,18 +459,18 @@ function _parseTransitionAnimation(
|
||||
ast = new AnimationSequenceAst(steps);
|
||||
}
|
||||
} else if (entry instanceof CompileAnimationAnimateMetadata) {
|
||||
var timings = _parseTimeExpression(entry.timings, errors);
|
||||
var styles = entry.styles;
|
||||
const timings = _parseTimeExpression(entry.timings, errors);
|
||||
const styles = entry.styles;
|
||||
|
||||
var keyframes: any /** TODO #9100 */;
|
||||
let keyframes: any /** TODO #9100 */;
|
||||
if (styles instanceof CompileAnimationKeyframesSequenceMetadata) {
|
||||
keyframes =
|
||||
_parseAnimationKeyframes(styles, currentTime, collectedStyles, stateStyles, errors);
|
||||
} else {
|
||||
let styleData = <CompileAnimationStyleMetadata>styles;
|
||||
let offset = _TERMINAL_KEYFRAME;
|
||||
let styleAst = new AnimationStylesAst(styleData.styles as Styles[]);
|
||||
var keyframe = new AnimationKeyframeAst(offset, styleAst);
|
||||
const styleData = <CompileAnimationStyleMetadata>styles;
|
||||
const offset = _TERMINAL_KEYFRAME;
|
||||
const styleAst = new AnimationStylesAst(styleData.styles as Styles[]);
|
||||
const keyframe = new AnimationKeyframeAst(offset, styleAst);
|
||||
keyframes = [keyframe];
|
||||
}
|
||||
|
||||
@ -499,10 +499,10 @@ function _fillAnimationAstStartingKeyframes(
|
||||
ast: AnimationAst, collectedStyles: StylesCollection, errors: AnimationParseError[]): void {
|
||||
// steps that only contain style will not be filled
|
||||
if ((ast instanceof AnimationStepAst) && ast.keyframes.length > 0) {
|
||||
var keyframes = ast.keyframes;
|
||||
const keyframes = ast.keyframes;
|
||||
if (keyframes.length == 1) {
|
||||
var endKeyframe = keyframes[0];
|
||||
var startKeyframe = _createStartKeyframeFromEndKeyframe(
|
||||
const endKeyframe = keyframes[0];
|
||||
const startKeyframe = _createStartKeyframeFromEndKeyframe(
|
||||
endKeyframe, ast.startTime, ast.playTime, collectedStyles, errors);
|
||||
ast.keyframes = [startKeyframe, endKeyframe];
|
||||
}
|
||||
@ -513,10 +513,10 @@ function _fillAnimationAstStartingKeyframes(
|
||||
|
||||
function _parseTimeExpression(
|
||||
exp: string | number, errors: AnimationParseError[]): _AnimationTimings {
|
||||
var regex = /^([\.\d]+)(m?s)(?:\s+([\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?/i;
|
||||
var duration: number;
|
||||
var delay: number = 0;
|
||||
var easing: string = null;
|
||||
const regex = /^([\.\d]+)(m?s)(?:\s+([\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?/i;
|
||||
let duration: number;
|
||||
let delay: number = 0;
|
||||
let easing: string = null;
|
||||
if (typeof exp === 'string') {
|
||||
const matches = exp.match(regex);
|
||||
if (matches === null) {
|
||||
@ -524,24 +524,24 @@ function _parseTimeExpression(
|
||||
return new _AnimationTimings(0, 0, null);
|
||||
}
|
||||
|
||||
var durationMatch = parseFloat(matches[1]);
|
||||
var durationUnit = matches[2];
|
||||
let durationMatch = parseFloat(matches[1]);
|
||||
const durationUnit = matches[2];
|
||||
if (durationUnit == 's') {
|
||||
durationMatch *= _ONE_SECOND;
|
||||
}
|
||||
duration = Math.floor(durationMatch);
|
||||
|
||||
var delayMatch = matches[3];
|
||||
var delayUnit = matches[4];
|
||||
const delayMatch = matches[3];
|
||||
const delayUnit = matches[4];
|
||||
if (isPresent(delayMatch)) {
|
||||
var delayVal: number = parseFloat(delayMatch);
|
||||
let delayVal: number = parseFloat(delayMatch);
|
||||
if (isPresent(delayUnit) && delayUnit == 's') {
|
||||
delayVal *= _ONE_SECOND;
|
||||
}
|
||||
delay = Math.floor(delayVal);
|
||||
}
|
||||
|
||||
var easingVal = matches[5];
|
||||
const easingVal = matches[5];
|
||||
if (!isBlank(easingVal)) {
|
||||
easing = easingVal;
|
||||
}
|
||||
@ -555,15 +555,15 @@ function _parseTimeExpression(
|
||||
function _createStartKeyframeFromEndKeyframe(
|
||||
endKeyframe: AnimationKeyframeAst, startTime: number, duration: number,
|
||||
collectedStyles: StylesCollection, errors: AnimationParseError[]): AnimationKeyframeAst {
|
||||
var values: Styles = {};
|
||||
var endTime = startTime + duration;
|
||||
const values: Styles = {};
|
||||
const endTime = startTime + duration;
|
||||
endKeyframe.styles.styles.forEach((styleData: Styles) => {
|
||||
Object.keys(styleData).forEach(prop => {
|
||||
const val = styleData[prop];
|
||||
if (prop == 'offset') return;
|
||||
|
||||
var resultIndex = collectedStyles.indexOfAtOrBeforeTime(prop, startTime);
|
||||
var resultEntry: any /** TODO #9100 */, nextEntry: any /** TODO #9100 */,
|
||||
const resultIndex = collectedStyles.indexOfAtOrBeforeTime(prop, startTime);
|
||||
let resultEntry: any /** TODO #9100 */, nextEntry: any /** TODO #9100 */,
|
||||
value: any /** TODO #9100 */;
|
||||
if (isPresent(resultIndex)) {
|
||||
resultEntry = collectedStyles.getByIndex(prop, resultIndex);
|
||||
|
@ -20,16 +20,16 @@ export class StylesCollection {
|
||||
styles: {[key: string]: StylesCollectionEntry[]} = {};
|
||||
|
||||
insertAtTime(property: string, time: number, value: string|number) {
|
||||
var tuple = new StylesCollectionEntry(time, value);
|
||||
var entries = this.styles[property];
|
||||
const tuple = new StylesCollectionEntry(time, value);
|
||||
let entries = this.styles[property];
|
||||
if (!isPresent(entries)) {
|
||||
entries = this.styles[property] = [];
|
||||
}
|
||||
|
||||
// insert this at the right stop in the array
|
||||
// this way we can keep it sorted
|
||||
var insertionIndex = 0;
|
||||
for (var i = entries.length - 1; i >= 0; i--) {
|
||||
let insertionIndex = 0;
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
if (entries[i].time <= time) {
|
||||
insertionIndex = i + 1;
|
||||
break;
|
||||
@ -40,7 +40,7 @@ export class StylesCollection {
|
||||
}
|
||||
|
||||
getByIndex(property: string, index: number): StylesCollectionEntry {
|
||||
var items = this.styles[property];
|
||||
const items = this.styles[property];
|
||||
if (isPresent(items)) {
|
||||
return index >= items.length ? null : items[index];
|
||||
}
|
||||
@ -48,9 +48,9 @@ export class StylesCollection {
|
||||
}
|
||||
|
||||
indexOfAtOrBeforeTime(property: string, time: number): number {
|
||||
var entries = this.styles[property];
|
||||
const entries = this.styles[property];
|
||||
if (isPresent(entries)) {
|
||||
for (var i = entries.length - 1; i >= 0; i--) {
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
if (entries[i].time <= time) return i;
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ export function assertArrayOfStrings(identifier: string, value: any) {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new Error(`Expected '${identifier}' to be an array of strings.`);
|
||||
}
|
||||
for (var i = 0; i < value.length; i += 1) {
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
if (typeof value[i] !== 'string') {
|
||||
throw new Error(`Expected '${identifier}' to be an array of strings.`);
|
||||
}
|
||||
|
@ -376,9 +376,9 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
|
||||
entryComponents?: CompileIdentifierMetadata[],
|
||||
template?: CompileTemplateMetadata
|
||||
} = {}): CompileDirectiveMetadata {
|
||||
var hostListeners: {[key: string]: string} = {};
|
||||
var hostProperties: {[key: string]: string} = {};
|
||||
var hostAttributes: {[key: string]: string} = {};
|
||||
const hostListeners: {[key: string]: string} = {};
|
||||
const hostProperties: {[key: string]: string} = {};
|
||||
const hostAttributes: {[key: string]: string} = {};
|
||||
if (isPresent(host)) {
|
||||
Object.keys(host).forEach(key => {
|
||||
const value = host[key];
|
||||
@ -392,21 +392,21 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
|
||||
}
|
||||
});
|
||||
}
|
||||
var inputsMap: {[key: string]: string} = {};
|
||||
const inputsMap: {[key: string]: string} = {};
|
||||
if (isPresent(inputs)) {
|
||||
inputs.forEach((bindConfig: string) => {
|
||||
// canonical syntax: `dirProp: elProp`
|
||||
// if there is no `:`, use dirProp = elProp
|
||||
var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
|
||||
const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
|
||||
inputsMap[parts[0]] = parts[1];
|
||||
});
|
||||
}
|
||||
var outputsMap: {[key: string]: string} = {};
|
||||
const outputsMap: {[key: string]: string} = {};
|
||||
if (isPresent(outputs)) {
|
||||
outputs.forEach((bindConfig: string) => {
|
||||
// canonical syntax: `dirProp: elProp`
|
||||
// if there is no `:`, use dirProp = elProp
|
||||
var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
|
||||
const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
|
||||
outputsMap[parts[0]] = parts[1];
|
||||
});
|
||||
}
|
||||
@ -516,7 +516,7 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
|
||||
*/
|
||||
export function createHostComponentMeta(compMeta: CompileDirectiveMetadata):
|
||||
CompileDirectiveMetadata {
|
||||
var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
|
||||
const template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
|
||||
return CompileDirectiveMetadata.create({
|
||||
type: new CompileTypeMetadata({
|
||||
reference: Object,
|
||||
|
@ -142,7 +142,7 @@ function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions {
|
||||
}
|
||||
|
||||
function _lastDefined<T>(args: T[]): T {
|
||||
for (var i = args.length - 1; i >= 0; i--) {
|
||||
for (let i = args.length - 1; i >= 0; i--) {
|
||||
if (args[i] !== undefined) {
|
||||
return args[i];
|
||||
}
|
||||
@ -151,7 +151,7 @@ function _lastDefined<T>(args: T[]): T {
|
||||
}
|
||||
|
||||
function _mergeArrays(parts: any[][]): any[] {
|
||||
let result: any[] = [];
|
||||
const result: any[] = [];
|
||||
parts.forEach((part) => part && result.push(...part));
|
||||
return result;
|
||||
}
|
||||
|
@ -30,7 +30,7 @@ export function createCheckBindingField(builder: ClassBuilder): CheckBindingFiel
|
||||
export function createCheckBindingStmt(
|
||||
evalResult: ConvertPropertyBindingResult, fieldExpr: o.ReadPropExpr,
|
||||
throwOnChangeVar: o.Expression, actions: o.Statement[]): o.Statement[] {
|
||||
var condition: o.Expression = o.importExpr(resolveIdentifier(Identifiers.checkBinding)).callFn([
|
||||
let condition: o.Expression = o.importExpr(resolveIdentifier(Identifiers.checkBinding)).callFn([
|
||||
throwOnChangeVar, fieldExpr, evalResult.currValExpr
|
||||
]);
|
||||
if (evalResult.forceUpdate) {
|
||||
|
@ -58,7 +58,7 @@ export function convertPropertyBinding(
|
||||
}
|
||||
|
||||
if (visitor.needsValueUnwrapper) {
|
||||
var initValueUnwrapperStmt = VAL_UNWRAPPER_VAR.callMethod('reset', []).toStmt();
|
||||
const initValueUnwrapperStmt = VAL_UNWRAPPER_VAR.callMethod('reset', []).toStmt();
|
||||
stmts.push(initValueUnwrapperStmt);
|
||||
}
|
||||
stmts.push(currValExpr.set(outputExpr).toDeclStmt(null, [o.StmtModifier.Final]));
|
||||
@ -86,14 +86,14 @@ export function convertActionBinding(
|
||||
}
|
||||
const visitor =
|
||||
new _AstToIrVisitor(builder, nameResolver, implicitReceiver, null, bindingId, true);
|
||||
let actionStmts: o.Statement[] = [];
|
||||
const actionStmts: o.Statement[] = [];
|
||||
flattenStatements(action.visit(visitor, _Mode.Statement), actionStmts);
|
||||
prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
|
||||
var lastIndex = actionStmts.length - 1;
|
||||
var preventDefaultVar: o.ReadVarExpr = null;
|
||||
const lastIndex = actionStmts.length - 1;
|
||||
let preventDefaultVar: o.ReadVarExpr = null;
|
||||
if (lastIndex >= 0) {
|
||||
var lastStatement = actionStmts[lastIndex];
|
||||
var returnExpr = convertStmtIntoExpression(lastStatement);
|
||||
const lastStatement = actionStmts[lastIndex];
|
||||
const returnExpr = convertStmtIntoExpression(lastStatement);
|
||||
if (returnExpr) {
|
||||
// Note: We need to cast the result of the method call to dynamic,
|
||||
// as it might be a void method!
|
||||
@ -112,7 +112,7 @@ export function convertActionBinding(
|
||||
*/
|
||||
export function createSharedBindingVariablesIfNeeded(stmts: o.Statement[]): o.Statement[] {
|
||||
const unwrapperStmts: o.Statement[] = [];
|
||||
var readVars = o.findReadVarNames(stmts);
|
||||
const readVars = o.findReadVarNames(stmts);
|
||||
if (readVars.has(VAL_UNWRAPPER_VAR.name)) {
|
||||
unwrapperStmts.push(
|
||||
VAL_UNWRAPPER_VAR
|
||||
@ -175,7 +175,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
|
||||
private bindingId: string, private isAction: boolean) {}
|
||||
|
||||
visitBinary(ast: cdAst.Binary, mode: _Mode): any {
|
||||
var op: o.BinaryOperator;
|
||||
let op: o.BinaryOperator;
|
||||
switch (ast.operation) {
|
||||
case '+':
|
||||
op = o.BinaryOperator.Plus;
|
||||
@ -303,7 +303,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
|
||||
}
|
||||
|
||||
visitLiteralMap(ast: cdAst.LiteralMap, mode: _Mode): any {
|
||||
let parts: any[] = [];
|
||||
const parts: any[] = [];
|
||||
for (let i = 0; i < ast.keys.length; i++) {
|
||||
parts.push([ast.keys[i], this.visit(ast.values[i], _Mode.Expression)]);
|
||||
}
|
||||
@ -330,9 +330,9 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
|
||||
} else {
|
||||
const args = this.visitAll(ast.args, _Mode.Expression);
|
||||
let result: any = null;
|
||||
let receiver = this.visit(ast.receiver, _Mode.Expression);
|
||||
const receiver = this.visit(ast.receiver, _Mode.Expression);
|
||||
if (receiver === this._implicitReceiver) {
|
||||
var varExpr = this._getLocal(ast.name);
|
||||
const varExpr = this._getLocal(ast.name);
|
||||
if (isPresent(varExpr)) {
|
||||
result = varExpr.callFn(args);
|
||||
}
|
||||
@ -354,7 +354,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
|
||||
return this.convertSafeAccess(ast, leftMostSafe, mode);
|
||||
} else {
|
||||
let result: any = null;
|
||||
var receiver = this.visit(ast.receiver, _Mode.Expression);
|
||||
const receiver = this.visit(ast.receiver, _Mode.Expression);
|
||||
if (receiver === this._implicitReceiver) {
|
||||
result = this._getLocal(ast.name);
|
||||
}
|
||||
@ -366,9 +366,9 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
|
||||
}
|
||||
|
||||
visitPropertyWrite(ast: cdAst.PropertyWrite, mode: _Mode): any {
|
||||
let receiver: o.Expression = this.visit(ast.receiver, _Mode.Expression);
|
||||
const receiver: o.Expression = this.visit(ast.receiver, _Mode.Expression);
|
||||
if (receiver === this._implicitReceiver) {
|
||||
var varExpr = this._getLocal(ast.name);
|
||||
const varExpr = this._getLocal(ast.name);
|
||||
if (isPresent(varExpr)) {
|
||||
throw new Error('Cannot assign to a reference or variable!');
|
||||
}
|
||||
@ -580,11 +580,11 @@ function createCachedLiteralArray(builder: ClassBuilder, values: o.Expression[])
|
||||
if (values.length === 0) {
|
||||
return o.importExpr(resolveIdentifier(Identifiers.EMPTY_ARRAY));
|
||||
}
|
||||
var proxyExpr = o.THIS_EXPR.prop(`_arr_${builder.fields.length}`);
|
||||
var proxyParams: o.FnParam[] = [];
|
||||
var proxyReturnEntries: o.Expression[] = [];
|
||||
for (var i = 0; i < values.length; i++) {
|
||||
var paramName = `p${i}`;
|
||||
const proxyExpr = o.THIS_EXPR.prop(`_arr_${builder.fields.length}`);
|
||||
const proxyParams: o.FnParam[] = [];
|
||||
const proxyReturnEntries: o.Expression[] = [];
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
const paramName = `p${i}`;
|
||||
proxyParams.push(new o.FnParam(paramName));
|
||||
proxyReturnEntries.push(o.variable(paramName));
|
||||
}
|
||||
@ -605,7 +605,7 @@ function createCachedLiteralMap(
|
||||
const proxyParams: o.FnParam[] = [];
|
||||
const proxyReturnEntries: [string, o.Expression][] = [];
|
||||
const values: o.Expression[] = [];
|
||||
for (var i = 0; i < entries.length; i++) {
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const paramName = `p${i}`;
|
||||
proxyParams.push(new o.FnParam(paramName));
|
||||
proxyReturnEntries.push([entries[i][0], o.variable(paramName)]);
|
||||
|
@ -40,7 +40,7 @@ export function createPureProxy(
|
||||
fn: o.Expression, argCount: number, pureProxyProp: o.ReadPropExpr,
|
||||
builder: {fields: o.ClassField[], ctorStmts: {push: (stmt: o.Statement) => void}}) {
|
||||
builder.fields.push(new o.ClassField(pureProxyProp.name, null));
|
||||
var pureProxyId =
|
||||
const pureProxyId =
|
||||
argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null;
|
||||
if (!pureProxyId) {
|
||||
throw new Error(`Unsupported number of argument for pure functions: ${argCount}`);
|
||||
|
@ -53,7 +53,7 @@ export function writeToRenderer(
|
||||
.toStmt());
|
||||
break;
|
||||
case PropertyBindingType.Style:
|
||||
var strValue: o.Expression = renderValue.callMethod('toString', []);
|
||||
let strValue: o.Expression = renderValue.callMethod('toString', []);
|
||||
if (isPresent(boundProp.unit)) {
|
||||
strValue = strValue.plus(o.literal(boundProp.unit));
|
||||
}
|
||||
@ -84,8 +84,8 @@ function sanitizedValue(
|
||||
if (!securityContextExpression) {
|
||||
throw new Error(`internal error, no SecurityContext given ${boundProp.name}`);
|
||||
}
|
||||
let ctx = view.prop('viewUtils').prop('sanitizer');
|
||||
let args = [securityContextExpression, renderValue];
|
||||
const ctx = view.prop('viewUtils').prop('sanitizer');
|
||||
const args = [securityContextExpression, renderValue];
|
||||
return ctx.callMethod('sanitize', args);
|
||||
}
|
||||
|
||||
|
@ -96,7 +96,7 @@ export class CssBlockDefinitionRuleAst extends CssBlockRuleAst {
|
||||
location: ParseSourceSpan, public strValue: string, type: BlockType,
|
||||
public query: CssAtRulePredicateAst, block: CssBlockAst) {
|
||||
super(location, type, block);
|
||||
var firstCssToken: CssToken = query.tokens[0];
|
||||
const firstCssToken: CssToken = query.tokens[0];
|
||||
this.name = new CssToken(
|
||||
firstCssToken.index, firstCssToken.column, firstCssToken.line, CssTokenType.Identifier,
|
||||
this.strValue);
|
||||
@ -238,9 +238,9 @@ export class CssUnknownTokenListAst extends CssRuleAst {
|
||||
}
|
||||
|
||||
export function mergeTokens(tokens: CssToken[], separator: string = ''): CssToken {
|
||||
var mainToken = tokens[0];
|
||||
var str = mainToken.strValue;
|
||||
for (var i = 1; i < tokens.length; i++) {
|
||||
const mainToken = tokens[0];
|
||||
let str = mainToken.strValue;
|
||||
for (let i = 1; i < tokens.length; i++) {
|
||||
str += separator + tokens[i].strValue;
|
||||
}
|
||||
|
||||
|
@ -54,18 +54,18 @@ export function generateErrorMessage(
|
||||
|
||||
export function findProblemCode(
|
||||
input: string, errorValue: string, index: number, column: number): string {
|
||||
var endOfProblemLine = index;
|
||||
var current = charCode(input, index);
|
||||
let endOfProblemLine = index;
|
||||
let current = charCode(input, index);
|
||||
while (current > 0 && !isNewline(current)) {
|
||||
current = charCode(input, ++endOfProblemLine);
|
||||
}
|
||||
var choppedString = input.substring(0, endOfProblemLine);
|
||||
var pointerPadding = '';
|
||||
for (var i = 0; i < column; i++) {
|
||||
const choppedString = input.substring(0, endOfProblemLine);
|
||||
let pointerPadding = '';
|
||||
for (let i = 0; i < column; i++) {
|
||||
pointerPadding += ' ';
|
||||
}
|
||||
var pointerString = '';
|
||||
for (var i = 0; i < errorValue.length; i++) {
|
||||
let pointerString = '';
|
||||
for (let i = 0; i < errorValue.length; i++) {
|
||||
pointerString += '^';
|
||||
}
|
||||
return choppedString + '\n' + pointerPadding + pointerString + '\n';
|
||||
@ -185,16 +185,16 @@ export class CssScanner {
|
||||
}
|
||||
|
||||
consume(type: CssTokenType, value: string = null): LexedCssResult {
|
||||
var mode = this._currentMode;
|
||||
const mode = this._currentMode;
|
||||
|
||||
this.setMode(_trackWhitespace(mode) ? CssLexerMode.ALL_TRACK_WS : CssLexerMode.ALL);
|
||||
|
||||
var previousIndex = this.index;
|
||||
var previousLine = this.line;
|
||||
var previousColumn = this.column;
|
||||
const previousIndex = this.index;
|
||||
const previousLine = this.line;
|
||||
const previousColumn = this.column;
|
||||
|
||||
var next: CssToken;
|
||||
var output = this.scan();
|
||||
let next: CssToken;
|
||||
const output = this.scan();
|
||||
if (isPresent(output)) {
|
||||
// just incase the inner scan method returned an error
|
||||
if (isPresent(output.error)) {
|
||||
@ -209,7 +209,7 @@ export class CssScanner {
|
||||
next = new CssToken(this.index, this.column, this.line, CssTokenType.EOF, 'end of file');
|
||||
}
|
||||
|
||||
var isMatchingType: boolean = false;
|
||||
let isMatchingType: boolean = false;
|
||||
if (type == CssTokenType.IdentifierOrNumber) {
|
||||
// TODO (matsko): implement array traversal for lookup here
|
||||
isMatchingType = next.type == CssTokenType.Number || next.type == CssTokenType.Identifier;
|
||||
@ -221,9 +221,9 @@ export class CssScanner {
|
||||
// mode so that the parser can recover...
|
||||
this.setMode(mode);
|
||||
|
||||
var error: CssScannerError = null;
|
||||
let error: CssScannerError = null;
|
||||
if (!isMatchingType || (isPresent(value) && value != next.strValue)) {
|
||||
var errorMessage =
|
||||
let errorMessage =
|
||||
CssTokenType[next.type] + ' does not match expected ' + CssTokenType[type] + ' value';
|
||||
|
||||
if (isPresent(value)) {
|
||||
@ -241,15 +241,15 @@ export class CssScanner {
|
||||
|
||||
|
||||
scan(): LexedCssResult {
|
||||
var trackWS = _trackWhitespace(this._currentMode);
|
||||
const trackWS = _trackWhitespace(this._currentMode);
|
||||
if (this.index == 0 && !trackWS) { // first scan
|
||||
this.consumeWhitespace();
|
||||
}
|
||||
|
||||
var token = this._scan();
|
||||
const token = this._scan();
|
||||
if (token == null) return null;
|
||||
|
||||
var error = this._currentError;
|
||||
const error = this._currentError;
|
||||
this._currentError = null;
|
||||
|
||||
if (!trackWS) {
|
||||
@ -260,14 +260,14 @@ export class CssScanner {
|
||||
|
||||
/** @internal */
|
||||
_scan(): CssToken {
|
||||
var peek = this.peek;
|
||||
var peekPeek = this.peekPeek;
|
||||
let peek = this.peek;
|
||||
let peekPeek = this.peekPeek;
|
||||
if (peek == chars.$EOF) return null;
|
||||
|
||||
if (isCommentStart(peek, peekPeek)) {
|
||||
// even if comments are not tracked we still lex the
|
||||
// comment so we can move the pointer forward
|
||||
var commentToken = this.scanComment();
|
||||
const commentToken = this.scanComment();
|
||||
if (this._trackComments) {
|
||||
return commentToken;
|
||||
}
|
||||
@ -290,9 +290,9 @@ export class CssScanner {
|
||||
return this.scanCssValueFunction();
|
||||
}
|
||||
|
||||
var isModifier = peek == chars.$PLUS || peek == chars.$MINUS;
|
||||
var digitA = isModifier ? false : chars.isDigit(peek);
|
||||
var digitB = chars.isDigit(peekPeek);
|
||||
const isModifier = peek == chars.$PLUS || peek == chars.$MINUS;
|
||||
const digitA = isModifier ? false : chars.isDigit(peek);
|
||||
const digitB = chars.isDigit(peekPeek);
|
||||
if (digitA || (isModifier && (peekPeek == chars.$PERIOD || digitB)) ||
|
||||
(peek == chars.$PERIOD && digitB)) {
|
||||
return this.scanNumber();
|
||||
@ -319,9 +319,9 @@ export class CssScanner {
|
||||
return null;
|
||||
}
|
||||
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
var startingLine = this.line;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
const startingLine = this.line;
|
||||
|
||||
this.advance(); // /
|
||||
this.advance(); // *
|
||||
@ -336,18 +336,18 @@ export class CssScanner {
|
||||
this.advance(); // *
|
||||
this.advance(); // /
|
||||
|
||||
var str = this.input.substring(start, this.index);
|
||||
const str = this.input.substring(start, this.index);
|
||||
return new CssToken(start, startingColumn, startingLine, CssTokenType.Comment, str);
|
||||
}
|
||||
|
||||
scanWhitespace(): CssToken {
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
var startingLine = this.line;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
const startingLine = this.line;
|
||||
while (chars.isWhitespace(this.peek) && this.peek != chars.$EOF) {
|
||||
this.advance();
|
||||
}
|
||||
var str = this.input.substring(start, this.index);
|
||||
const str = this.input.substring(start, this.index);
|
||||
return new CssToken(start, startingColumn, startingLine, CssTokenType.Whitespace, str);
|
||||
}
|
||||
|
||||
@ -357,11 +357,11 @@ export class CssScanner {
|
||||
return null;
|
||||
}
|
||||
|
||||
var target = this.peek;
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
var startingLine = this.line;
|
||||
var previous = target;
|
||||
const target = this.peek;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
const startingLine = this.line;
|
||||
let previous = target;
|
||||
this.advance();
|
||||
|
||||
while (!isCharMatch(target, previous, this.peek)) {
|
||||
@ -377,17 +377,17 @@ export class CssScanner {
|
||||
}
|
||||
this.advance();
|
||||
|
||||
var str = this.input.substring(start, this.index);
|
||||
const str = this.input.substring(start, this.index);
|
||||
return new CssToken(start, startingColumn, startingLine, CssTokenType.String, str);
|
||||
}
|
||||
|
||||
scanNumber(): CssToken {
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
if (this.peek == chars.$PLUS || this.peek == chars.$MINUS) {
|
||||
this.advance();
|
||||
}
|
||||
var periodUsed = false;
|
||||
let periodUsed = false;
|
||||
while (chars.isDigit(this.peek) || this.peek == chars.$PERIOD) {
|
||||
if (this.peek == chars.$PERIOD) {
|
||||
if (periodUsed) {
|
||||
@ -397,7 +397,7 @@ export class CssScanner {
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
var strValue = this.input.substring(start, this.index);
|
||||
const strValue = this.input.substring(start, this.index);
|
||||
return new CssToken(start, startingColumn, this.line, CssTokenType.Number, strValue);
|
||||
}
|
||||
|
||||
@ -407,19 +407,19 @@ export class CssScanner {
|
||||
return null;
|
||||
}
|
||||
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
while (isIdentifierPart(this.peek)) {
|
||||
this.advance();
|
||||
}
|
||||
var strValue = this.input.substring(start, this.index);
|
||||
const strValue = this.input.substring(start, this.index);
|
||||
return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue);
|
||||
}
|
||||
|
||||
scanCssValueFunction(): CssToken {
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
var parenBalance = 1;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
let parenBalance = 1;
|
||||
while (this.peek != chars.$EOF && parenBalance > 0) {
|
||||
this.advance();
|
||||
if (this.peek == chars.$LPAREN) {
|
||||
@ -428,20 +428,20 @@ export class CssScanner {
|
||||
parenBalance--;
|
||||
}
|
||||
}
|
||||
var strValue = this.input.substring(start, this.index);
|
||||
const strValue = this.input.substring(start, this.index);
|
||||
return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue);
|
||||
}
|
||||
|
||||
scanCharacter(): CssToken {
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
if (this.assertCondition(
|
||||
isValidCssCharacter(this.peek, this._currentMode),
|
||||
charStr(this.peek) + ' is not a valid CSS character')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var c = this.input.substring(start, start + 1);
|
||||
const c = this.input.substring(start, start + 1);
|
||||
this.advance();
|
||||
|
||||
return new CssToken(start, startingColumn, this.line, CssTokenType.Character, c);
|
||||
@ -452,12 +452,12 @@ export class CssScanner {
|
||||
return null;
|
||||
}
|
||||
|
||||
var start = this.index;
|
||||
var startingColumn = this.column;
|
||||
const start = this.index;
|
||||
const startingColumn = this.column;
|
||||
this.advance();
|
||||
if (isIdentifierStart(this.peek, this.peekPeek)) {
|
||||
var ident = this.scanIdentifier();
|
||||
var strValue = '@' + ident.strValue;
|
||||
const ident = this.scanIdentifier();
|
||||
const strValue = '@' + ident.strValue;
|
||||
return new CssToken(start, startingColumn, this.line, CssTokenType.AtKeyword, strValue);
|
||||
} else {
|
||||
return this.scanCharacter();
|
||||
@ -473,12 +473,12 @@ export class CssScanner {
|
||||
}
|
||||
|
||||
error(message: string, errorTokenValue: string = null, doNotAdvance: boolean = false): CssToken {
|
||||
var index: number = this.index;
|
||||
var column: number = this.column;
|
||||
var line: number = this.line;
|
||||
const index: number = this.index;
|
||||
const column: number = this.column;
|
||||
const line: number = this.line;
|
||||
errorTokenValue = errorTokenValue || String.fromCharCode(this.peek);
|
||||
var invalidToken = new CssToken(index, column, line, CssTokenType.Invalid, errorTokenValue);
|
||||
var errorMessage =
|
||||
const invalidToken = new CssToken(index, column, line, CssTokenType.Invalid, errorTokenValue);
|
||||
const errorMessage =
|
||||
generateErrorMessage(this.input, message, errorTokenValue, index, line, column);
|
||||
if (!doNotAdvance) {
|
||||
this.advance();
|
||||
@ -501,7 +501,7 @@ function isCommentEnd(code: number, next: number): boolean {
|
||||
}
|
||||
|
||||
function isStringStart(code: number, next: number): boolean {
|
||||
var target = code;
|
||||
let target = code;
|
||||
if (target == chars.$BACKSLASH) {
|
||||
target = next;
|
||||
}
|
||||
@ -509,7 +509,7 @@ function isStringStart(code: number, next: number): boolean {
|
||||
}
|
||||
|
||||
function isIdentifierStart(code: number, next: number): boolean {
|
||||
var target = code;
|
||||
let target = code;
|
||||
if (target == chars.$MINUS) {
|
||||
target = next;
|
||||
}
|
||||
|
@ -93,16 +93,16 @@ export class CssParser {
|
||||
* @param url the name of the CSS file containing the CSS source code
|
||||
*/
|
||||
parse(css: string, url: string): ParsedCssResult {
|
||||
var lexer = new CssLexer();
|
||||
const lexer = new CssLexer();
|
||||
this._file = new ParseSourceFile(css, url);
|
||||
this._scanner = lexer.scan(css, false);
|
||||
|
||||
var ast = this._parseStyleSheet(EOF_DELIM_FLAG);
|
||||
const ast = this._parseStyleSheet(EOF_DELIM_FLAG);
|
||||
|
||||
var errors = this._errors;
|
||||
const errors = this._errors;
|
||||
this._errors = [];
|
||||
|
||||
var result = new ParsedCssResult(errors, ast);
|
||||
const result = new ParsedCssResult(errors, ast);
|
||||
this._file = null;
|
||||
this._scanner = null;
|
||||
return result;
|
||||
@ -110,15 +110,15 @@ export class CssParser {
|
||||
|
||||
/** @internal */
|
||||
_parseStyleSheet(delimiters: number): CssStyleSheetAst {
|
||||
var results: CssRuleAst[] = [];
|
||||
const results: CssRuleAst[] = [];
|
||||
this._scanner.consumeEmptyStatements();
|
||||
while (this._scanner.peek != chars.$EOF) {
|
||||
this._scanner.setMode(CssLexerMode.BLOCK);
|
||||
results.push(this._parseRule(delimiters));
|
||||
}
|
||||
var span: ParseSourceSpan = null;
|
||||
let span: ParseSourceSpan = null;
|
||||
if (results.length > 0) {
|
||||
var firstRule = results[0];
|
||||
const firstRule = results[0];
|
||||
// we collect the last token like so incase there was an
|
||||
// EOF token that was emitted sometime during the lexing
|
||||
span = this._generateSourceSpan(firstRule, this._lastToken);
|
||||
@ -136,11 +136,11 @@ export class CssParser {
|
||||
|
||||
/** @internal */
|
||||
_generateSourceSpan(start: CssToken|CssAst, end: CssToken|CssAst = null): ParseSourceSpan {
|
||||
var startLoc: ParseLocation;
|
||||
let startLoc: ParseLocation;
|
||||
if (start instanceof CssAst) {
|
||||
startLoc = start.location.start;
|
||||
} else {
|
||||
var token = start;
|
||||
let token = start;
|
||||
if (!isPresent(token)) {
|
||||
// the data here is invalid, however, if and when this does
|
||||
// occur, any other errors associated with this will be collected
|
||||
@ -153,9 +153,9 @@ export class CssParser {
|
||||
end = this._lastToken;
|
||||
}
|
||||
|
||||
var endLine: number;
|
||||
var endColumn: number;
|
||||
var endIndex: number;
|
||||
let endLine: number;
|
||||
let endColumn: number;
|
||||
let endIndex: number;
|
||||
if (end instanceof CssAst) {
|
||||
endLine = end.location.end.line;
|
||||
endColumn = end.location.end.col;
|
||||
@ -166,7 +166,7 @@ export class CssParser {
|
||||
endIndex = end.index;
|
||||
}
|
||||
|
||||
var endLoc = new ParseLocation(this._file, endIndex, endLine, endColumn);
|
||||
const endLoc = new ParseLocation(this._file, endIndex, endLine, endColumn);
|
||||
return new ParseSourceSpan(startLoc, endLoc);
|
||||
}
|
||||
|
||||
@ -224,21 +224,21 @@ export class CssParser {
|
||||
const start = this._getScannerIndex();
|
||||
|
||||
this._scanner.setMode(CssLexerMode.BLOCK);
|
||||
var token = this._scan();
|
||||
var startToken = token;
|
||||
const token = this._scan();
|
||||
const startToken = token;
|
||||
|
||||
this._assertCondition(
|
||||
token.type == CssTokenType.AtKeyword,
|
||||
`The CSS Rule ${token.strValue} is not a valid [@] rule.`, token);
|
||||
|
||||
var block: CssBlockAst;
|
||||
var type = this._resolveBlockType(token);
|
||||
var span: ParseSourceSpan;
|
||||
var tokens: CssToken[];
|
||||
var endToken: CssToken;
|
||||
var end: number;
|
||||
var strValue: string;
|
||||
var query: CssAtRulePredicateAst;
|
||||
let block: CssBlockAst;
|
||||
const type = this._resolveBlockType(token);
|
||||
let span: ParseSourceSpan;
|
||||
let tokens: CssToken[];
|
||||
let endToken: CssToken;
|
||||
let end: number;
|
||||
let strValue: string;
|
||||
let query: CssAtRulePredicateAst;
|
||||
switch (type) {
|
||||
case BlockType.Charset:
|
||||
case BlockType.Namespace:
|
||||
@ -324,23 +324,23 @@ export class CssParser {
|
||||
/** @internal */
|
||||
_parseSelectorRule(delimiters: number): CssRuleAst {
|
||||
const start = this._getScannerIndex();
|
||||
var selectors = this._parseSelectors(delimiters);
|
||||
var block = this._parseStyleBlock(delimiters);
|
||||
var ruleAst: CssRuleAst;
|
||||
var span: ParseSourceSpan;
|
||||
var startSelector = selectors[0];
|
||||
const selectors = this._parseSelectors(delimiters);
|
||||
const block = this._parseStyleBlock(delimiters);
|
||||
let ruleAst: CssRuleAst;
|
||||
let span: ParseSourceSpan;
|
||||
const startSelector = selectors[0];
|
||||
if (isPresent(block)) {
|
||||
span = this._generateSourceSpan(startSelector, block);
|
||||
ruleAst = new CssSelectorRuleAst(span, selectors, block);
|
||||
} else {
|
||||
var name = this._extractSourceContent(start, this._getScannerIndex() - 1);
|
||||
var innerTokens: CssToken[] = [];
|
||||
const name = this._extractSourceContent(start, this._getScannerIndex() - 1);
|
||||
const innerTokens: CssToken[] = [];
|
||||
selectors.forEach((selector: CssSelectorAst) => {
|
||||
selector.selectorParts.forEach((part: CssSimpleSelectorAst) => {
|
||||
part.tokens.forEach((token: CssToken) => { innerTokens.push(token); });
|
||||
});
|
||||
});
|
||||
var endToken = innerTokens[innerTokens.length - 1];
|
||||
const endToken = innerTokens[innerTokens.length - 1];
|
||||
span = this._generateSourceSpan(startSelector, endToken);
|
||||
ruleAst = new CssUnknownTokenListAst(span, name, innerTokens);
|
||||
}
|
||||
@ -353,8 +353,8 @@ export class CssParser {
|
||||
_parseSelectors(delimiters: number): CssSelectorAst[] {
|
||||
delimiters |= LBRACE_DELIM_FLAG | SEMICOLON_DELIM_FLAG;
|
||||
|
||||
var selectors: CssSelectorAst[] = [];
|
||||
var isParsingSelectors = true;
|
||||
const selectors: CssSelectorAst[] = [];
|
||||
let isParsingSelectors = true;
|
||||
while (isParsingSelectors) {
|
||||
selectors.push(this._parseSelector(delimiters));
|
||||
|
||||
@ -374,9 +374,9 @@ export class CssParser {
|
||||
|
||||
/** @internal */
|
||||
_scan(): CssToken {
|
||||
var output = this._scanner.scan();
|
||||
var token = output.token;
|
||||
var error = output.error;
|
||||
const output = this._scanner.scan();
|
||||
const token = output.token;
|
||||
const error = output.error;
|
||||
if (isPresent(error)) {
|
||||
this._error(error.rawMessage, token);
|
||||
}
|
||||
@ -389,9 +389,9 @@ export class CssParser {
|
||||
|
||||
/** @internal */
|
||||
_consume(type: CssTokenType, value: string = null): CssToken {
|
||||
var output = this._scanner.consume(type, value);
|
||||
var token = output.token;
|
||||
var error = output.error;
|
||||
const output = this._scanner.consume(type, value);
|
||||
const token = output.token;
|
||||
const error = output.error;
|
||||
if (isPresent(error)) {
|
||||
this._error(error.rawMessage, token);
|
||||
}
|
||||
@ -404,23 +404,23 @@ export class CssParser {
|
||||
delimiters |= RBRACE_DELIM_FLAG;
|
||||
this._scanner.setMode(CssLexerMode.KEYFRAME_BLOCK);
|
||||
|
||||
var startToken = this._consume(CssTokenType.Character, '{');
|
||||
const startToken = this._consume(CssTokenType.Character, '{');
|
||||
|
||||
var definitions: CssKeyframeDefinitionAst[] = [];
|
||||
const definitions: CssKeyframeDefinitionAst[] = [];
|
||||
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
definitions.push(this._parseKeyframeDefinition(delimiters));
|
||||
}
|
||||
|
||||
var endToken = this._consume(CssTokenType.Character, '}');
|
||||
const endToken = this._consume(CssTokenType.Character, '}');
|
||||
|
||||
var span = this._generateSourceSpan(startToken, endToken);
|
||||
const span = this._generateSourceSpan(startToken, endToken);
|
||||
return new CssBlockAst(span, definitions);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
_parseKeyframeDefinition(delimiters: number): CssKeyframeDefinitionAst {
|
||||
const start = this._getScannerIndex();
|
||||
var stepTokens: CssToken[] = [];
|
||||
const stepTokens: CssToken[] = [];
|
||||
delimiters |= LBRACE_DELIM_FLAG;
|
||||
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
stepTokens.push(this._parseKeyframeLabel(delimiters | COMMA_DELIM_FLAG));
|
||||
@ -428,9 +428,9 @@ export class CssParser {
|
||||
this._consume(CssTokenType.Character, ',');
|
||||
}
|
||||
}
|
||||
var stylesBlock = this._parseStyleBlock(delimiters | RBRACE_DELIM_FLAG);
|
||||
var span = this._generateSourceSpan(stepTokens[0], stylesBlock);
|
||||
var ast = new CssKeyframeDefinitionAst(span, stepTokens, stylesBlock);
|
||||
const stylesBlock = this._parseStyleBlock(delimiters | RBRACE_DELIM_FLAG);
|
||||
const span = this._generateSourceSpan(stepTokens[0], stylesBlock);
|
||||
const ast = new CssKeyframeDefinitionAst(span, stepTokens, stylesBlock);
|
||||
|
||||
this._scanner.setMode(CssLexerMode.BLOCK);
|
||||
return ast;
|
||||
@ -449,34 +449,34 @@ export class CssParser {
|
||||
delimiters &= ~COMMA_DELIM_FLAG;
|
||||
|
||||
// we keep the original value since we may use it to recurse when :not, :host are used
|
||||
var startingDelims = delimiters;
|
||||
const startingDelims = delimiters;
|
||||
|
||||
var startToken = this._consume(CssTokenType.Character, ':');
|
||||
var tokens = [startToken];
|
||||
const startToken = this._consume(CssTokenType.Character, ':');
|
||||
const tokens = [startToken];
|
||||
|
||||
if (this._scanner.peek == chars.$COLON) { // ::something
|
||||
tokens.push(this._consume(CssTokenType.Character, ':'));
|
||||
}
|
||||
|
||||
var innerSelectors: CssSelectorAst[] = [];
|
||||
const innerSelectors: CssSelectorAst[] = [];
|
||||
|
||||
this._scanner.setMode(CssLexerMode.PSEUDO_SELECTOR);
|
||||
|
||||
// host, host-context, lang, not, nth-child are all identifiers
|
||||
var pseudoSelectorToken = this._consume(CssTokenType.Identifier);
|
||||
var pseudoSelectorName = pseudoSelectorToken.strValue;
|
||||
const pseudoSelectorToken = this._consume(CssTokenType.Identifier);
|
||||
const pseudoSelectorName = pseudoSelectorToken.strValue;
|
||||
tokens.push(pseudoSelectorToken);
|
||||
|
||||
// host(), lang(), nth-child(), etc...
|
||||
if (this._scanner.peek == chars.$LPAREN) {
|
||||
this._scanner.setMode(CssLexerMode.PSEUDO_SELECTOR_WITH_ARGUMENTS);
|
||||
|
||||
var openParenToken = this._consume(CssTokenType.Character, '(');
|
||||
const openParenToken = this._consume(CssTokenType.Character, '(');
|
||||
tokens.push(openParenToken);
|
||||
|
||||
// :host(innerSelector(s)), :not(selector), etc...
|
||||
if (_pseudoSelectorSupportsInnerSelectors(pseudoSelectorName)) {
|
||||
var innerDelims = startingDelims | LPAREN_DELIM_FLAG | RPAREN_DELIM_FLAG;
|
||||
let innerDelims = startingDelims | LPAREN_DELIM_FLAG | RPAREN_DELIM_FLAG;
|
||||
if (pseudoSelectorName == 'not') {
|
||||
// the inner selector inside of :not(...) can only be one
|
||||
// CSS selector (no commas allowed) ... This is according
|
||||
@ -491,23 +491,23 @@ export class CssParser {
|
||||
} else {
|
||||
// this branch is for things like "en-us, 2k + 1, etc..."
|
||||
// which all end up in pseudoSelectors like :lang, :nth-child, etc..
|
||||
var innerValueDelims = delimiters | LBRACE_DELIM_FLAG | COLON_DELIM_FLAG |
|
||||
const innerValueDelims = delimiters | LBRACE_DELIM_FLAG | COLON_DELIM_FLAG |
|
||||
RPAREN_DELIM_FLAG | LPAREN_DELIM_FLAG;
|
||||
while (!characterContainsDelimiter(this._scanner.peek, innerValueDelims)) {
|
||||
var token = this._scan();
|
||||
const token = this._scan();
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
|
||||
var closeParenToken = this._consume(CssTokenType.Character, ')');
|
||||
const closeParenToken = this._consume(CssTokenType.Character, ')');
|
||||
tokens.push(closeParenToken);
|
||||
}
|
||||
|
||||
const end = this._getScannerIndex() - 1;
|
||||
var strValue = this._extractSourceContent(start, end);
|
||||
const strValue = this._extractSourceContent(start, end);
|
||||
|
||||
var endToken = tokens[tokens.length - 1];
|
||||
var span = this._generateSourceSpan(startToken, endToken);
|
||||
const endToken = tokens[tokens.length - 1];
|
||||
const span = this._generateSourceSpan(startToken, endToken);
|
||||
return new CssPseudoSelectorAst(span, strValue, pseudoSelectorName, tokens, innerSelectors);
|
||||
}
|
||||
|
||||
@ -518,21 +518,21 @@ export class CssParser {
|
||||
delimiters |= COMMA_DELIM_FLAG;
|
||||
|
||||
this._scanner.setMode(CssLexerMode.SELECTOR);
|
||||
var selectorCssTokens: CssToken[] = [];
|
||||
var pseudoSelectors: CssPseudoSelectorAst[] = [];
|
||||
const selectorCssTokens: CssToken[] = [];
|
||||
const pseudoSelectors: CssPseudoSelectorAst[] = [];
|
||||
|
||||
var previousToken: CssToken;
|
||||
let previousToken: CssToken;
|
||||
|
||||
var selectorPartDelimiters = delimiters | SPACE_DELIM_FLAG;
|
||||
var loopOverSelector = !characterContainsDelimiter(this._scanner.peek, selectorPartDelimiters);
|
||||
const selectorPartDelimiters = delimiters | SPACE_DELIM_FLAG;
|
||||
let loopOverSelector = !characterContainsDelimiter(this._scanner.peek, selectorPartDelimiters);
|
||||
|
||||
var hasAttributeError = false;
|
||||
let hasAttributeError = false;
|
||||
while (loopOverSelector) {
|
||||
var peek = this._scanner.peek;
|
||||
const peek = this._scanner.peek;
|
||||
|
||||
switch (peek) {
|
||||
case chars.$COLON:
|
||||
var innerPseudo = this._parsePseudoSelector(delimiters);
|
||||
let innerPseudo = this._parsePseudoSelector(delimiters);
|
||||
pseudoSelectors.push(innerPseudo);
|
||||
this._scanner.setMode(CssLexerMode.SELECTOR);
|
||||
break;
|
||||
@ -561,7 +561,7 @@ export class CssParser {
|
||||
continue;
|
||||
}
|
||||
|
||||
var token = this._scan();
|
||||
let token = this._scan();
|
||||
previousToken = token;
|
||||
selectorCssTokens.push(token);
|
||||
break;
|
||||
@ -578,18 +578,18 @@ export class CssParser {
|
||||
previousToken);
|
||||
}
|
||||
|
||||
var end = this._getScannerIndex() - 1;
|
||||
let end = this._getScannerIndex() - 1;
|
||||
|
||||
// this happens if the selector is not directly followed by
|
||||
// a comma or curly brace without a space in between
|
||||
let operator: CssToken = null;
|
||||
let operatorScanCount = 0;
|
||||
let lastOperatorToken: CssToken = null;
|
||||
if (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
var operator: CssToken = null;
|
||||
var operatorScanCount = 0;
|
||||
var lastOperatorToken: CssToken = null;
|
||||
while (operator == null && !characterContainsDelimiter(this._scanner.peek, delimiters) &&
|
||||
isSelectorOperatorCharacter(this._scanner.peek)) {
|
||||
var token = this._scan();
|
||||
var tokenOperator = token.strValue;
|
||||
let token = this._scan();
|
||||
const tokenOperator = token.strValue;
|
||||
operatorScanCount++;
|
||||
lastOperatorToken = token;
|
||||
if (tokenOperator != SPACE_OPERATOR) {
|
||||
@ -607,7 +607,7 @@ export class CssParser {
|
||||
lastOperatorToken.index, lastOperatorToken.column, lastOperatorToken.line,
|
||||
CssTokenType.Identifier, DEEP_OPERATOR_STR);
|
||||
} else {
|
||||
let text = SLASH_CHARACTER + deepToken.strValue + deepSlash.strValue;
|
||||
const text = SLASH_CHARACTER + deepToken.strValue + deepSlash.strValue;
|
||||
this._error(
|
||||
generateErrorMessage(
|
||||
this._getSourceContent(), `${text} is an invalid CSS operator`, text, index,
|
||||
@ -643,7 +643,7 @@ export class CssParser {
|
||||
|
||||
this._scanner.consumeWhitespace();
|
||||
|
||||
var strValue = this._extractSourceContent(start, end);
|
||||
const strValue = this._extractSourceContent(start, end);
|
||||
|
||||
// if we do come across one or more spaces inside of
|
||||
// the operators loop then an empty space is still a
|
||||
@ -654,8 +654,8 @@ export class CssParser {
|
||||
|
||||
// please note that `endToken` is reassigned multiple times below
|
||||
// so please do not optimize the if statements into if/elseif
|
||||
var startTokenOrAst: CssToken|CssAst = null;
|
||||
var endTokenOrAst: CssToken|CssAst = null;
|
||||
let startTokenOrAst: CssToken|CssAst = null;
|
||||
let endTokenOrAst: CssToken|CssAst = null;
|
||||
if (selectorCssTokens.length > 0) {
|
||||
startTokenOrAst = startTokenOrAst || selectorCssTokens[0];
|
||||
endTokenOrAst = selectorCssTokens[selectorCssTokens.length - 1];
|
||||
@ -669,7 +669,7 @@ export class CssParser {
|
||||
endTokenOrAst = operator;
|
||||
}
|
||||
|
||||
var span = this._generateSourceSpan(startTokenOrAst, endTokenOrAst);
|
||||
const span = this._generateSourceSpan(startTokenOrAst, endTokenOrAst);
|
||||
return new CssSimpleSelectorAst(span, selectorCssTokens, strValue, pseudoSelectors, operator);
|
||||
}
|
||||
|
||||
@ -678,15 +678,15 @@ export class CssParser {
|
||||
delimiters |= COMMA_DELIM_FLAG;
|
||||
this._scanner.setMode(CssLexerMode.SELECTOR);
|
||||
|
||||
var simpleSelectors: CssSimpleSelectorAst[] = [];
|
||||
const simpleSelectors: CssSimpleSelectorAst[] = [];
|
||||
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
simpleSelectors.push(this._parseSimpleSelector(delimiters));
|
||||
this._scanner.consumeWhitespace();
|
||||
}
|
||||
|
||||
var firstSelector = simpleSelectors[0];
|
||||
var lastSelector = simpleSelectors[simpleSelectors.length - 1];
|
||||
var span = this._generateSourceSpan(firstSelector, lastSelector);
|
||||
const firstSelector = simpleSelectors[0];
|
||||
const lastSelector = simpleSelectors[simpleSelectors.length - 1];
|
||||
const span = this._generateSourceSpan(firstSelector, lastSelector);
|
||||
return new CssSelectorAst(span, simpleSelectors);
|
||||
}
|
||||
|
||||
@ -697,11 +697,11 @@ export class CssParser {
|
||||
this._scanner.setMode(CssLexerMode.STYLE_VALUE);
|
||||
const start = this._getScannerIndex();
|
||||
|
||||
var tokens: CssToken[] = [];
|
||||
var wsStr = '';
|
||||
var previous: CssToken;
|
||||
const tokens: CssToken[] = [];
|
||||
let wsStr = '';
|
||||
let previous: CssToken;
|
||||
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
var token: CssToken;
|
||||
let token: CssToken;
|
||||
if (isPresent(previous) && previous.type == CssTokenType.Identifier &&
|
||||
this._scanner.peek == chars.$LPAREN) {
|
||||
token = this._consume(CssTokenType.Character, '(');
|
||||
@ -731,7 +731,7 @@ export class CssParser {
|
||||
const end = this._getScannerIndex() - 1;
|
||||
this._scanner.consumeWhitespace();
|
||||
|
||||
var code = this._scanner.peek;
|
||||
const code = this._scanner.peek;
|
||||
if (code == chars.$SEMICOLON) {
|
||||
this._consume(CssTokenType.Character, ';');
|
||||
} else if (code != chars.$RBRACE) {
|
||||
@ -742,18 +742,18 @@ export class CssParser {
|
||||
previous);
|
||||
}
|
||||
|
||||
var strValue = this._extractSourceContent(start, end);
|
||||
var startToken = tokens[0];
|
||||
var endToken = tokens[tokens.length - 1];
|
||||
var span = this._generateSourceSpan(startToken, endToken);
|
||||
const strValue = this._extractSourceContent(start, end);
|
||||
const startToken = tokens[0];
|
||||
const endToken = tokens[tokens.length - 1];
|
||||
const span = this._generateSourceSpan(startToken, endToken);
|
||||
return new CssStyleValueAst(span, tokens, strValue);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
_collectUntilDelim(delimiters: number, assertType: CssTokenType = null): CssToken[] {
|
||||
var tokens: CssToken[] = [];
|
||||
const tokens: CssToken[] = [];
|
||||
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
var val = isPresent(assertType) ? this._consume(assertType) : this._scan();
|
||||
const val = isPresent(assertType) ? this._consume(assertType) : this._scan();
|
||||
tokens.push(val);
|
||||
}
|
||||
return tokens;
|
||||
@ -765,20 +765,20 @@ export class CssParser {
|
||||
|
||||
this._scanner.setMode(CssLexerMode.BLOCK);
|
||||
|
||||
var startToken = this._consume(CssTokenType.Character, '{');
|
||||
const startToken = this._consume(CssTokenType.Character, '{');
|
||||
this._scanner.consumeEmptyStatements();
|
||||
|
||||
var results: CssRuleAst[] = [];
|
||||
const results: CssRuleAst[] = [];
|
||||
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
results.push(this._parseRule(delimiters));
|
||||
}
|
||||
|
||||
var endToken = this._consume(CssTokenType.Character, '}');
|
||||
const endToken = this._consume(CssTokenType.Character, '}');
|
||||
|
||||
this._scanner.setMode(CssLexerMode.BLOCK);
|
||||
this._scanner.consumeEmptyStatements();
|
||||
|
||||
var span = this._generateSourceSpan(startToken, endToken);
|
||||
const span = this._generateSourceSpan(startToken, endToken);
|
||||
return new CssBlockAst(span, results);
|
||||
}
|
||||
|
||||
@ -788,12 +788,12 @@ export class CssParser {
|
||||
|
||||
this._scanner.setMode(CssLexerMode.STYLE_BLOCK);
|
||||
|
||||
var startToken = this._consume(CssTokenType.Character, '{');
|
||||
const startToken = this._consume(CssTokenType.Character, '{');
|
||||
if (startToken.numValue != chars.$LBRACE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var definitions: CssDefinitionAst[] = [];
|
||||
const definitions: CssDefinitionAst[] = [];
|
||||
this._scanner.consumeEmptyStatements();
|
||||
|
||||
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
|
||||
@ -801,12 +801,12 @@ export class CssParser {
|
||||
this._scanner.consumeEmptyStatements();
|
||||
}
|
||||
|
||||
var endToken = this._consume(CssTokenType.Character, '}');
|
||||
const endToken = this._consume(CssTokenType.Character, '}');
|
||||
|
||||
this._scanner.setMode(CssLexerMode.STYLE_BLOCK);
|
||||
this._scanner.consumeEmptyStatements();
|
||||
|
||||
var span = this._generateSourceSpan(startToken, endToken);
|
||||
const span = this._generateSourceSpan(startToken, endToken);
|
||||
return new CssStylesBlockAst(span, definitions);
|
||||
}
|
||||
|
||||
@ -814,10 +814,10 @@ export class CssParser {
|
||||
_parseDefinition(delimiters: number): CssDefinitionAst {
|
||||
this._scanner.setMode(CssLexerMode.STYLE_BLOCK);
|
||||
|
||||
var prop = this._consume(CssTokenType.Identifier);
|
||||
var parseValue: boolean = false;
|
||||
var value: CssStyleValueAst = null;
|
||||
var endToken: CssToken|CssStyleValueAst = prop;
|
||||
let prop = this._consume(CssTokenType.Identifier);
|
||||
let parseValue: boolean = false;
|
||||
let value: CssStyleValueAst = null;
|
||||
let endToken: CssToken|CssStyleValueAst = prop;
|
||||
|
||||
// the colon value separates the prop from the style.
|
||||
// there are a few cases as to what could happen if it
|
||||
@ -830,13 +830,13 @@ export class CssParser {
|
||||
break;
|
||||
|
||||
default:
|
||||
var propStr = [prop.strValue];
|
||||
let propStr = [prop.strValue];
|
||||
if (this._scanner.peek != chars.$COLON) {
|
||||
// this will throw the error
|
||||
var nextValue = this._consume(CssTokenType.Character, ':');
|
||||
const nextValue = this._consume(CssTokenType.Character, ':');
|
||||
propStr.push(nextValue.strValue);
|
||||
|
||||
var remainingTokens = this._collectUntilDelim(
|
||||
const remainingTokens = this._collectUntilDelim(
|
||||
delimiters | COLON_DELIM_FLAG | SEMICOLON_DELIM_FLAG, CssTokenType.Identifier);
|
||||
if (remainingTokens.length > 0) {
|
||||
remainingTokens.forEach((token) => { propStr.push(token.strValue); });
|
||||
@ -865,7 +865,7 @@ export class CssParser {
|
||||
prop);
|
||||
}
|
||||
|
||||
var span = this._generateSourceSpan(prop, endToken);
|
||||
const span = this._generateSourceSpan(prop, endToken);
|
||||
return new CssDefinitionAst(span, prop, value);
|
||||
}
|
||||
|
||||
@ -880,8 +880,8 @@ export class CssParser {
|
||||
|
||||
/** @internal */
|
||||
_error(message: string, problemToken: CssToken) {
|
||||
var length = problemToken.strValue.length;
|
||||
var error = CssParseError.create(
|
||||
const length = problemToken.strValue.length;
|
||||
const error = CssParseError.create(
|
||||
this._file, 0, problemToken.line, problemToken.column, length, message);
|
||||
this._errors.push(error);
|
||||
}
|
||||
@ -891,9 +891,9 @@ export class CssParseError extends ParseError {
|
||||
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);
|
||||
const start = new ParseLocation(file, offset, line, col);
|
||||
const end = new ParseLocation(file, offset, line, col + length);
|
||||
const span = new ParseSourceSpan(start, end);
|
||||
return new CssParseError(span, 'CSS Parse Error: ' + errMsg);
|
||||
}
|
||||
|
||||
|
@ -52,7 +52,7 @@ export class DirectiveNormalizer {
|
||||
}
|
||||
|
||||
private _fetch(url: string): Promise<string> {
|
||||
var result = this._resourceLoaderCache.get(url);
|
||||
let result = this._resourceLoaderCache.get(url);
|
||||
if (!result) {
|
||||
result = this._resourceLoader.get(url);
|
||||
this._resourceLoaderCache.set(url, result);
|
||||
@ -91,7 +91,7 @@ export class DirectiveNormalizer {
|
||||
|
||||
normalizeTemplateAsync(prenomData: PrenormalizedTemplateMetadata):
|
||||
Promise<CompileTemplateMetadata> {
|
||||
let templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
|
||||
const templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
|
||||
return this._fetch(templateUrl)
|
||||
.then((value) => this.normalizeLoadedTemplate(prenomData, value, templateUrl));
|
||||
}
|
||||
@ -164,7 +164,7 @@ export class DirectiveNormalizer {
|
||||
return Promise
|
||||
.all(styleUrls.filter((styleUrl) => !loadedStylesheets.has(styleUrl))
|
||||
.map(styleUrl => this._fetch(styleUrl).then((loadedStyle) => {
|
||||
var stylesheet = this.normalizeStylesheet(
|
||||
const stylesheet = this.normalizeStylesheet(
|
||||
new CompileStylesheetMetadata({styles: [loadedStyle], moduleUrl: styleUrl}));
|
||||
loadedStylesheets.set(styleUrl, stylesheet);
|
||||
return this._loadMissingExternalStylesheets(
|
||||
@ -174,11 +174,11 @@ export class DirectiveNormalizer {
|
||||
}
|
||||
|
||||
normalizeStylesheet(stylesheet: CompileStylesheetMetadata): CompileStylesheetMetadata {
|
||||
var allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
|
||||
.map(url => this._urlResolver.resolve(stylesheet.moduleUrl, url));
|
||||
const allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
|
||||
.map(url => this._urlResolver.resolve(stylesheet.moduleUrl, url));
|
||||
|
||||
var allStyles = stylesheet.styles.map(style => {
|
||||
var styleWithImports = extractStyleUrls(this._urlResolver, stylesheet.moduleUrl, style);
|
||||
const allStyles = stylesheet.styles.map(style => {
|
||||
const styleWithImports = extractStyleUrls(this._urlResolver, stylesheet.moduleUrl, style);
|
||||
allStyleUrls.push(...styleWithImports.styleUrls);
|
||||
return styleWithImports.style;
|
||||
});
|
||||
@ -195,7 +195,7 @@ class TemplatePreparseVisitor implements html.Visitor {
|
||||
ngNonBindableStackCount: number = 0;
|
||||
|
||||
visitElement(ast: html.Element, context: any): any {
|
||||
var preparsedElement = preparseElement(ast);
|
||||
const preparsedElement = preparseElement(ast);
|
||||
switch (preparsedElement.type) {
|
||||
case PreparsedElementType.NG_CONTENT:
|
||||
if (this.ngNonBindableStackCount === 0) {
|
||||
@ -203,7 +203,7 @@ class TemplatePreparseVisitor implements html.Visitor {
|
||||
}
|
||||
break;
|
||||
case PreparsedElementType.STYLE:
|
||||
var textContent = '';
|
||||
let textContent = '';
|
||||
ast.children.forEach(child => {
|
||||
if (child instanceof html.Text) {
|
||||
textContent += child.value;
|
||||
|
@ -121,7 +121,7 @@ export class DirectiveResolver {
|
||||
mergedInputs.unshift(...directive.inputs);
|
||||
}
|
||||
|
||||
let mergedOutputs: string[] = outputs;
|
||||
const mergedOutputs: string[] = outputs;
|
||||
|
||||
if (directive.outputs) {
|
||||
const outputNames: string[] =
|
||||
|
@ -207,7 +207,7 @@ function addNgDoCheckMethod(builder: DirectiveWrapperBuilder) {
|
||||
|
||||
function addCheckInputMethod(input: string, builder: DirectiveWrapperBuilder) {
|
||||
const field = createCheckBindingField(builder);
|
||||
var onChangeStatements: o.Statement[] = [
|
||||
const onChangeStatements: o.Statement[] = [
|
||||
o.THIS_EXPR.prop(CHANGED_FIELD_NAME).set(o.literal(true)).toStmt(),
|
||||
o.THIS_EXPR.prop(CONTEXT_FIELD_NAME).prop(input).set(CURR_VALUE_VAR).toStmt(),
|
||||
];
|
||||
@ -219,7 +219,7 @@ function addCheckInputMethod(input: string, builder: DirectiveWrapperBuilder) {
|
||||
.toStmt());
|
||||
}
|
||||
|
||||
var methodBody: o.Statement[] = createCheckBindingStmt(
|
||||
const methodBody: o.Statement[] = createCheckBindingStmt(
|
||||
{currValExpr: CURR_VALUE_VAR, forceUpdate: FORCE_UPDATE_VAR, stmts: []}, field.expression,
|
||||
THROW_ON_CHANGE_VAR, onChangeStatements);
|
||||
builder.methods.push(new o.ClassMethod(
|
||||
@ -430,7 +430,7 @@ export class DirectiveWrapperExpressions {
|
||||
dirMeta: CompileDirectiveSummary, hostProps: BoundElementPropertyAst[], usedEvents: string[],
|
||||
dirWrapper: o.Expression, view: o.Expression, eventListener: o.Expression): o.Statement[] {
|
||||
let needsSubscribe = false;
|
||||
let eventFlags: o.Expression[] = [];
|
||||
const eventFlags: o.Expression[] = [];
|
||||
Object.keys(dirMeta.outputs).forEach((propName) => {
|
||||
const eventName = dirMeta.outputs[propName];
|
||||
const eventUsed = usedEvents.indexOf(eventName) > -1;
|
||||
|
@ -376,8 +376,8 @@ export class AstTransformer implements AstVisitor {
|
||||
}
|
||||
|
||||
visitAll(asts: any[]): any[] {
|
||||
var res = new Array(asts.length);
|
||||
for (var i = 0; i < asts.length; ++i) {
|
||||
const res = new Array(asts.length);
|
||||
for (let i = 0; i < asts.length; ++i) {
|
||||
res[i] = asts[i].visit(this);
|
||||
}
|
||||
return res;
|
||||
|
@ -137,7 +137,8 @@ class _Scanner {
|
||||
}
|
||||
|
||||
scanToken(): Token {
|
||||
var input = this.input, length = this.length, peek = this.peek, index = this.index;
|
||||
const input = this.input, length = this.length;
|
||||
let peek = this.peek, index = this.index;
|
||||
|
||||
// Skip whitespace.
|
||||
while (peek <= chars.$SPACE) {
|
||||
@ -160,7 +161,7 @@ class _Scanner {
|
||||
if (isIdentifierStart(peek)) return this.scanIdentifier();
|
||||
if (chars.isDigit(peek)) return this.scanNumber(index);
|
||||
|
||||
var start: number = index;
|
||||
const start: number = index;
|
||||
switch (peek) {
|
||||
case chars.$PERIOD:
|
||||
this.advance();
|
||||
@ -235,7 +236,7 @@ class _Scanner {
|
||||
start: number, one: string, twoCode: number, two: string, threeCode?: number,
|
||||
three?: string): Token {
|
||||
this.advance();
|
||||
var str: string = one;
|
||||
let str: string = one;
|
||||
if (this.peek == twoCode) {
|
||||
this.advance();
|
||||
str += two;
|
||||
@ -248,16 +249,16 @@ class _Scanner {
|
||||
}
|
||||
|
||||
scanIdentifier(): Token {
|
||||
var start: number = this.index;
|
||||
const start: number = this.index;
|
||||
this.advance();
|
||||
while (isIdentifierPart(this.peek)) this.advance();
|
||||
var str: string = this.input.substring(start, this.index);
|
||||
const str: string = this.input.substring(start, this.index);
|
||||
return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
|
||||
newIdentifierToken(start, str);
|
||||
}
|
||||
|
||||
scanNumber(start: number): Token {
|
||||
var simple: boolean = (this.index === start);
|
||||
let simple: boolean = (this.index === start);
|
||||
this.advance(); // Skip initial digit.
|
||||
while (true) {
|
||||
if (chars.isDigit(this.peek)) {
|
||||
@ -286,7 +287,7 @@ class _Scanner {
|
||||
|
||||
let buffer: string = '';
|
||||
let marker: number = this.index;
|
||||
let input: string = this.input;
|
||||
const input: string = this.input;
|
||||
|
||||
while (this.peek != quote) {
|
||||
if (this.peek == chars.$BACKSLASH) {
|
||||
@ -337,7 +338,7 @@ function isIdentifierStart(code: number): boolean {
|
||||
|
||||
export function isIdentifier(input: string): boolean {
|
||||
if (input.length == 0) return false;
|
||||
var scanner = new _Scanner(input);
|
||||
const scanner = new _Scanner(input);
|
||||
if (!isIdentifierStart(scanner.peek)) return false;
|
||||
scanner.advance();
|
||||
while (scanner.peek !== chars.$EOF) {
|
||||
|
@ -53,7 +53,7 @@ export class Parser {
|
||||
parseBinding(
|
||||
input: string, location: any,
|
||||
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ASTWithSource {
|
||||
var ast = this._parseBindingAst(input, location, interpolationConfig);
|
||||
const ast = this._parseBindingAst(input, location, interpolationConfig);
|
||||
return new ASTWithSource(ast, input, location, this.errors);
|
||||
}
|
||||
|
||||
@ -77,7 +77,7 @@ export class Parser {
|
||||
input: string, location: string, interpolationConfig: InterpolationConfig): AST {
|
||||
// Quotes expressions use 3rd-party expression language. We don't want to use
|
||||
// our lexer or parser for that, so we check for that ahead of time.
|
||||
var quote = this._parseQuote(input, location);
|
||||
const quote = this._parseQuote(input, location);
|
||||
|
||||
if (isPresent(quote)) {
|
||||
return quote;
|
||||
@ -94,11 +94,11 @@ export class Parser {
|
||||
|
||||
private _parseQuote(input: string, location: any): AST {
|
||||
if (isBlank(input)) return null;
|
||||
var prefixSeparatorIndex = input.indexOf(':');
|
||||
const prefixSeparatorIndex = input.indexOf(':');
|
||||
if (prefixSeparatorIndex == -1) return null;
|
||||
var prefix = input.substring(0, prefixSeparatorIndex).trim();
|
||||
const prefix = input.substring(0, prefixSeparatorIndex).trim();
|
||||
if (!isIdentifier(prefix)) return null;
|
||||
var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
|
||||
const uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
|
||||
return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
|
||||
}
|
||||
|
||||
@ -120,10 +120,10 @@ export class Parser {
|
||||
parseInterpolation(
|
||||
input: string, location: any,
|
||||
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ASTWithSource {
|
||||
let split = this.splitInterpolation(input, location, interpolationConfig);
|
||||
const split = this.splitInterpolation(input, location, interpolationConfig);
|
||||
if (split == null) return null;
|
||||
|
||||
let expressions: AST[] = [];
|
||||
const expressions: AST[] = [];
|
||||
|
||||
for (let i = 0; i < split.expressions.length; ++i) {
|
||||
const expressionText = split.expressions[i];
|
||||
@ -155,7 +155,7 @@ export class Parser {
|
||||
const offsets: number[] = [];
|
||||
let offset = 0;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
var part: string = parts[i];
|
||||
const part: string = parts[i];
|
||||
if (i % 2 === 0) {
|
||||
// fixed string
|
||||
strings.push(part);
|
||||
@ -189,7 +189,7 @@ export class Parser {
|
||||
}
|
||||
|
||||
private _commentStart(input: string): number {
|
||||
var outerQuote: number = null;
|
||||
let outerQuote: number = null;
|
||||
for (let i = 0; i < input.length - 1; i++) {
|
||||
const char = input.charCodeAt(i);
|
||||
const nextChar = input.charCodeAt(i + 1);
|
||||
@ -207,8 +207,8 @@ export class Parser {
|
||||
|
||||
private _checkNoInterpolation(
|
||||
input: string, location: any, interpolationConfig: InterpolationConfig): void {
|
||||
var regexp = _createInterpolateRegExp(interpolationConfig);
|
||||
var parts = input.split(regexp);
|
||||
const regexp = _createInterpolateRegExp(interpolationConfig);
|
||||
const parts = input.split(regexp);
|
||||
if (parts.length > 1) {
|
||||
this._reportError(
|
||||
`Got interpolation (${interpolationConfig.start}${interpolationConfig.end}) where expression was expected`,
|
||||
@ -220,8 +220,8 @@ export class Parser {
|
||||
|
||||
private _findInterpolationErrorColumn(
|
||||
parts: string[], partInErrIdx: number, interpolationConfig: InterpolationConfig): number {
|
||||
var errLocation = '';
|
||||
for (var j = 0; j < partInErrIdx; j++) {
|
||||
let errLocation = '';
|
||||
for (let j = 0; j < partInErrIdx; j++) {
|
||||
errLocation += j % 2 === 0 ?
|
||||
parts[j] :
|
||||
`${interpolationConfig.start}${parts[j]}${interpolationConfig.end}`;
|
||||
@ -244,7 +244,7 @@ export class _ParseAST {
|
||||
private offset: number) {}
|
||||
|
||||
peek(offset: number): Token {
|
||||
var i = this.index + offset;
|
||||
const i = this.index + offset;
|
||||
return i < this.tokens.length ? this.tokens[i] : EOF;
|
||||
}
|
||||
|
||||
@ -290,7 +290,7 @@ export class _ParseAST {
|
||||
}
|
||||
|
||||
expectIdentifierOrKeyword(): string {
|
||||
var n = this.next;
|
||||
const n = this.next;
|
||||
if (!n.isIdentifier() && !n.isKeyword()) {
|
||||
this.error(`Unexpected token ${n}, expected identifier or keyword`);
|
||||
return '';
|
||||
@ -300,7 +300,7 @@ export class _ParseAST {
|
||||
}
|
||||
|
||||
expectIdentifierOrKeywordOrString(): string {
|
||||
var n = this.next;
|
||||
const n = this.next;
|
||||
if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
|
||||
this.error(`Unexpected token ${n}, expected identifier, keyword, or string`);
|
||||
return '';
|
||||
@ -310,10 +310,10 @@ export class _ParseAST {
|
||||
}
|
||||
|
||||
parseChain(): AST {
|
||||
var exprs: AST[] = [];
|
||||
const exprs: AST[] = [];
|
||||
const start = this.inputIndex;
|
||||
while (this.index < this.tokens.length) {
|
||||
var expr = this.parsePipe();
|
||||
const expr = this.parsePipe();
|
||||
exprs.push(expr);
|
||||
|
||||
if (this.optionalCharacter(chars.$SEMICOLON)) {
|
||||
@ -332,15 +332,15 @@ export class _ParseAST {
|
||||
}
|
||||
|
||||
parsePipe(): AST {
|
||||
var result = this.parseExpression();
|
||||
let result = this.parseExpression();
|
||||
if (this.optionalOperator('|')) {
|
||||
if (this.parseAction) {
|
||||
this.error('Cannot have a pipe in an action expression');
|
||||
}
|
||||
|
||||
do {
|
||||
var name = this.expectIdentifierOrKeyword();
|
||||
var args: AST[] = [];
|
||||
const name = this.expectIdentifierOrKeyword();
|
||||
const args: AST[] = [];
|
||||
while (this.optionalCharacter(chars.$COLON)) {
|
||||
args.push(this.parseExpression());
|
||||
}
|
||||
@ -361,8 +361,8 @@ export class _ParseAST {
|
||||
const yes = this.parsePipe();
|
||||
let no: AST;
|
||||
if (!this.optionalCharacter(chars.$COLON)) {
|
||||
var end = this.inputIndex;
|
||||
var expression = this.input.substring(start, end);
|
||||
const end = this.inputIndex;
|
||||
const expression = this.input.substring(start, end);
|
||||
this.error(`Conditional expression ${expression} requires all 3 expressions`);
|
||||
no = new EmptyExpr(this.span(start));
|
||||
} else {
|
||||
@ -398,7 +398,7 @@ export class _ParseAST {
|
||||
// '==','!=','===','!=='
|
||||
let result = this.parseRelational();
|
||||
while (this.next.type == TokenType.Operator) {
|
||||
let operator = this.next.strValue;
|
||||
const operator = this.next.strValue;
|
||||
switch (operator) {
|
||||
case '==':
|
||||
case '===':
|
||||
@ -418,7 +418,7 @@ export class _ParseAST {
|
||||
// '<', '>', '<=', '>='
|
||||
let result = this.parseAdditive();
|
||||
while (this.next.type == TokenType.Operator) {
|
||||
let operator = this.next.strValue;
|
||||
const operator = this.next.strValue;
|
||||
switch (operator) {
|
||||
case '<':
|
||||
case '>':
|
||||
@ -591,7 +591,7 @@ export class _ParseAST {
|
||||
}
|
||||
|
||||
parseExpressionList(terminator: number): AST[] {
|
||||
let result: AST[] = [];
|
||||
const result: AST[] = [];
|
||||
if (!this.next.isCharacter(terminator)) {
|
||||
do {
|
||||
result.push(this.parsePipe());
|
||||
@ -601,14 +601,14 @@ export class _ParseAST {
|
||||
}
|
||||
|
||||
parseLiteralMap(): LiteralMap {
|
||||
let keys: string[] = [];
|
||||
let values: AST[] = [];
|
||||
const keys: string[] = [];
|
||||
const values: AST[] = [];
|
||||
const start = this.inputIndex;
|
||||
this.expectCharacter(chars.$LBRACE);
|
||||
if (!this.optionalCharacter(chars.$RBRACE)) {
|
||||
this.rbracesExpected++;
|
||||
do {
|
||||
var key = this.expectIdentifierOrKeywordOrString();
|
||||
const key = this.expectIdentifierOrKeywordOrString();
|
||||
keys.push(key);
|
||||
this.expectCharacter(chars.$COLON);
|
||||
values.push(this.parsePipe());
|
||||
@ -628,7 +628,7 @@ export class _ParseAST {
|
||||
const args = this.parseCallArguments();
|
||||
this.expectCharacter(chars.$RPAREN);
|
||||
this.rparensExpected--;
|
||||
let span = this.span(start);
|
||||
const span = this.span(start);
|
||||
return isSafe ? new SafeMethodCall(span, receiver, id, args) :
|
||||
new MethodCall(span, receiver, id, args);
|
||||
|
||||
@ -647,7 +647,7 @@ export class _ParseAST {
|
||||
return new EmptyExpr(this.span(start));
|
||||
}
|
||||
|
||||
let value = this.parseConditional();
|
||||
const value = this.parseConditional();
|
||||
return new PropertyWrite(this.span(start), receiver, id, value);
|
||||
} else {
|
||||
return new PropertyRead(this.span(start), receiver, id);
|
||||
@ -658,7 +658,7 @@ export class _ParseAST {
|
||||
|
||||
parseCallArguments(): BindingPipe[] {
|
||||
if (this.next.isCharacter(chars.$RPAREN)) return [];
|
||||
var positionals: AST[] = [];
|
||||
const positionals: AST[] = [];
|
||||
do {
|
||||
positionals.push(this.parsePipe());
|
||||
} while (this.optionalCharacter(chars.$COMMA));
|
||||
@ -683,16 +683,16 @@ export class _ParseAST {
|
||||
}
|
||||
|
||||
parseTemplateBindings(): TemplateBindingParseResult {
|
||||
let bindings: TemplateBinding[] = [];
|
||||
const bindings: TemplateBinding[] = [];
|
||||
let prefix: string = null;
|
||||
let warnings: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
while (this.index < this.tokens.length) {
|
||||
const start = this.inputIndex;
|
||||
const keyIsVar: boolean = this.peekKeywordLet();
|
||||
if (keyIsVar) {
|
||||
this.advance();
|
||||
}
|
||||
var key = this.expectTemplateBindingKey();
|
||||
let key = this.expectTemplateBindingKey();
|
||||
if (!keyIsVar) {
|
||||
if (prefix == null) {
|
||||
prefix = key;
|
||||
@ -701,8 +701,8 @@ export class _ParseAST {
|
||||
}
|
||||
}
|
||||
this.optionalCharacter(chars.$COLON);
|
||||
var name: string = null;
|
||||
var expression: ASTWithSource = null;
|
||||
let name: string = null;
|
||||
let expression: ASTWithSource = null;
|
||||
if (keyIsVar) {
|
||||
if (this.optionalOperator('=')) {
|
||||
name = this.expectTemplateBindingKey();
|
||||
@ -765,7 +765,7 @@ export class _ParseAST {
|
||||
|
||||
class SimpleExpressionChecker implements AstVisitor {
|
||||
static check(ast: AST): string[] {
|
||||
var s = new SimpleExpressionChecker();
|
||||
const s = new SimpleExpressionChecker();
|
||||
ast.visit(s);
|
||||
return s.errors;
|
||||
}
|
||||
|
@ -27,7 +27,8 @@ class _SerializerVisitor implements i18n.Visitor {
|
||||
}
|
||||
|
||||
visitIcu(icu: i18n.Icu, context: any): any {
|
||||
let strCases = Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`);
|
||||
const strCases =
|
||||
Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`);
|
||||
return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
|
||||
}
|
||||
|
||||
|
@ -19,7 +19,7 @@ export interface Serializer {
|
||||
// Generate a map of placeholder to content indexed by message ids
|
||||
export function extractPlaceholders(messageBundle: MessageBundle) {
|
||||
const messageMap = messageBundle.getMessageMap();
|
||||
let placeholders: {[id: string]: {[name: string]: string}} = {};
|
||||
const placeholders: {[id: string]: {[name: string]: string}} = {};
|
||||
|
||||
Object.keys(messageMap).forEach(msgId => {
|
||||
placeholders[msgId] = messageMap[msgId].placeholders;
|
||||
@ -31,7 +31,7 @@ export function extractPlaceholders(messageBundle: MessageBundle) {
|
||||
// Generate a map of placeholder to message ids indexed by message ids
|
||||
export function extractPlaceholderToIds(messageBundle: MessageBundle) {
|
||||
const messageMap = messageBundle.getMessageMap();
|
||||
let placeholderToIds: {[id: string]: {[name: string]: string}} = {};
|
||||
const placeholderToIds: {[id: string]: {[name: string]: string}} = {};
|
||||
|
||||
Object.keys(messageMap).forEach(msgId => {
|
||||
placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds;
|
||||
|
@ -41,7 +41,7 @@ export class Xliff implements Serializer {
|
||||
Object.keys(messageMap).forEach((id) => {
|
||||
const message = messageMap[id];
|
||||
|
||||
let transUnit = new xml.Tag(_UNIT_TAG, {id: id, datatype: 'html'});
|
||||
const transUnit = new xml.Tag(_UNIT_TAG, {id: id, datatype: 'html'});
|
||||
transUnit.children.push(
|
||||
new xml.CR(8), new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)),
|
||||
new xml.CR(8), new xml.Tag(_TARGET_TAG));
|
||||
@ -93,7 +93,7 @@ export class Xliff implements Serializer {
|
||||
|
||||
// Convert the string messages to html ast
|
||||
// TODO(vicb): map error message back to the original message in xtb
|
||||
let messageMap: {[id: string]: ml.Node[]} = {};
|
||||
const messageMap: {[id: string]: ml.Node[]} = {};
|
||||
const parseErrors: ParseError[] = [];
|
||||
|
||||
Object.keys(messages).forEach((id) => {
|
||||
|
@ -42,11 +42,11 @@ const _DOCTYPE = `<!ELEMENT messagebundle (msg)*>
|
||||
export class Xmb implements Serializer {
|
||||
write(messageMap: {[k: string]: i18n.Message}): string {
|
||||
const visitor = new _Visitor();
|
||||
let rootNode = new xml.Tag(_MESSAGES_TAG);
|
||||
const rootNode = new xml.Tag(_MESSAGES_TAG);
|
||||
|
||||
Object.keys(messageMap).forEach((id) => {
|
||||
const message = messageMap[id];
|
||||
let attrs: {[k: string]: string} = {id};
|
||||
const attrs: {[k: string]: string} = {id};
|
||||
|
||||
if (message.description) {
|
||||
attrs['desc'] = message.description;
|
||||
|
@ -43,7 +43,7 @@ export class Xtb implements Serializer {
|
||||
|
||||
// Convert the string messages to html ast
|
||||
// TODO(vicb): map error message back to the original message in xtb
|
||||
let messageMap: {[id: string]: ml.Node[]} = {};
|
||||
const messageMap: {[id: string]: ml.Node[]} = {};
|
||||
const parseErrors: ParseError[] = [];
|
||||
|
||||
Object.keys(messages).forEach((id) => {
|
||||
|
@ -11,11 +11,11 @@ import {ANALYZE_FOR_ENTRY_COMPONENTS, AnimationTransitionEvent, ChangeDetectionS
|
||||
import {CompileIdentifierMetadata, CompileTokenMetadata} from './compile_metadata';
|
||||
import {AnimationGroupPlayer, AnimationKeyframe, AnimationSequencePlayer, AnimationStyles, AnimationTransition, AppView, ChangeDetectorStatus, CodegenComponentFactoryResolver, ComponentRef_, DebugAppView, DebugContext, NgModuleInjector, NoOpAnimationPlayer, StaticNodeDebugInfo, TemplateRef_, UNINITIALIZED, ValueUnwrapper, ViewContainer, ViewType, balanceAnimationKeyframes, clearStyles, collectAndResolveStyles, devModeEqual, prepareFinalAnimationStyles, reflector, registerModuleFactory, renderStyles, view_utils} from './private_import_core';
|
||||
|
||||
var APP_VIEW_MODULE_URL = assetUrl('core', 'linker/view');
|
||||
var VIEW_UTILS_MODULE_URL = assetUrl('core', 'linker/view_utils');
|
||||
var CD_MODULE_URL = assetUrl('core', 'change_detection/change_detection');
|
||||
const APP_VIEW_MODULE_URL = assetUrl('core', 'linker/view');
|
||||
const VIEW_UTILS_MODULE_URL = assetUrl('core', 'linker/view_utils');
|
||||
const CD_MODULE_URL = assetUrl('core', 'change_detection/change_detection');
|
||||
|
||||
var ANIMATION_STYLE_UTIL_ASSET_URL = assetUrl('core', 'animation/animation_style_util');
|
||||
const ANIMATION_STYLE_UTIL_ASSET_URL = assetUrl('core', 'animation/animation_style_util');
|
||||
|
||||
export interface IdentifierSpec {
|
||||
name: string;
|
||||
|
@ -603,9 +603,9 @@ export class CompileMetadataResolver {
|
||||
private _getDependenciesMetadata(typeOrFunc: Type<any>|Function, dependencies: any[]):
|
||||
cpl.CompileDiDependencyMetadata[] {
|
||||
let hasUnknownDeps = false;
|
||||
let params = dependencies || this._reflector.parameters(typeOrFunc) || [];
|
||||
const params = dependencies || this._reflector.parameters(typeOrFunc) || [];
|
||||
|
||||
let dependenciesMetadata: cpl.CompileDiDependencyMetadata[] = params.map((param) => {
|
||||
const dependenciesMetadata: cpl.CompileDiDependencyMetadata[] = params.map((param) => {
|
||||
let isAttribute = false;
|
||||
let isHost = false;
|
||||
let isSelf = false;
|
||||
@ -651,7 +651,7 @@ export class CompileMetadataResolver {
|
||||
});
|
||||
|
||||
if (hasUnknownDeps) {
|
||||
let depsTokens =
|
||||
const depsTokens =
|
||||
dependenciesMetadata.map((dep) => dep ? stringify(dep.token) : '?').join(', ');
|
||||
throw new Error(
|
||||
`Can't resolve all parameters for ${stringify(typeOrFunc)}: (${depsTokens}).`);
|
||||
@ -690,7 +690,7 @@ export class CompileMetadataResolver {
|
||||
if (Array.isArray(provider)) {
|
||||
compileProvider = this._getProvidersMetadata(provider, targetEntryComponents, debugInfo);
|
||||
} else if (provider instanceof cpl.ProviderMeta) {
|
||||
let tokenMeta = this._getTokenMetadata(provider.token);
|
||||
const tokenMeta = this._getTokenMetadata(provider.token);
|
||||
if (tokenMeta.reference ===
|
||||
resolveIdentifierToken(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS).reference) {
|
||||
targetEntryComponents.push(...this._getEntryComponentsFromProvider(provider));
|
||||
@ -792,7 +792,7 @@ export class CompileMetadataResolver {
|
||||
|
||||
private _getQueryMetadata(q: Query, propertyName: string, typeOrFunc: Type<any>|Function):
|
||||
cpl.CompileQueryMetadata {
|
||||
var selectors: cpl.CompileTokenMetadata[];
|
||||
let selectors: cpl.CompileTokenMetadata[];
|
||||
if (typeof q.selector === 'string') {
|
||||
selectors =
|
||||
this._queryVarBindings(q.selector).map(varName => this._getTokenMetadata(varName));
|
||||
|
@ -67,9 +67,9 @@ export interface Visitor {
|
||||
}
|
||||
|
||||
export function visitAll(visitor: Visitor, nodes: Node[], context: any = null): any[] {
|
||||
let result: any[] = [];
|
||||
const result: any[] = [];
|
||||
|
||||
let visit = visitor.visit ?
|
||||
const visit = visitor.visit ?
|
||||
(ast: Node) => visitor.visit(ast, context) || ast.visit(visitor, context) :
|
||||
(ast: Node) => ast.visit(visitor, context);
|
||||
nodes.forEach(ast => {
|
||||
|
@ -102,7 +102,7 @@ function _expandPluralForm(ast: html.Expansion, errors: ParseError[]): html.Elem
|
||||
}
|
||||
|
||||
function _expandDefaultForm(ast: html.Expansion, errors: ParseError[]): html.Element {
|
||||
let children = ast.cases.map(c => {
|
||||
const children = ast.cases.map(c => {
|
||||
const expansionResult = expandNodes(c.expression);
|
||||
errors.push(...expansionResult.errors);
|
||||
|
||||
|
@ -321,23 +321,23 @@ class _Tokenizer {
|
||||
const start = this._getLocation();
|
||||
this._advance();
|
||||
if (this._attemptCharCode(chars.$HASH)) {
|
||||
let isHex = this._attemptCharCode(chars.$x) || this._attemptCharCode(chars.$X);
|
||||
let numberStart = this._getLocation().offset;
|
||||
const isHex = this._attemptCharCode(chars.$x) || this._attemptCharCode(chars.$X);
|
||||
const numberStart = this._getLocation().offset;
|
||||
this._attemptCharCodeUntilFn(isDigitEntityEnd);
|
||||
if (this._peek != chars.$SEMICOLON) {
|
||||
throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan());
|
||||
}
|
||||
this._advance();
|
||||
let strNum = this._input.substring(numberStart, this._index - 1);
|
||||
const strNum = this._input.substring(numberStart, this._index - 1);
|
||||
try {
|
||||
let charCode = parseInt(strNum, isHex ? 16 : 10);
|
||||
const charCode = parseInt(strNum, isHex ? 16 : 10);
|
||||
return String.fromCharCode(charCode);
|
||||
} catch (e) {
|
||||
let entity = this._input.substring(start.offset + 1, this._index - 1);
|
||||
const entity = this._input.substring(start.offset + 1, this._index - 1);
|
||||
throw this._createError(_unknownEntityErrorMsg(entity), this._getSpan(start));
|
||||
}
|
||||
} else {
|
||||
let startPosition = this._savePosition();
|
||||
const startPosition = this._savePosition();
|
||||
this._attemptCharCodeUntilFn(isNamedEntityEnd);
|
||||
if (this._peek != chars.$SEMICOLON) {
|
||||
this._restorePosition(startPosition);
|
||||
@ -420,7 +420,7 @@ class _Tokenizer {
|
||||
}
|
||||
|
||||
private _consumeTagOpen(start: ParseLocation) {
|
||||
let savedPos = this._savePosition();
|
||||
const savedPos = this._savePosition();
|
||||
let tagName: string;
|
||||
let lowercaseTagName: string;
|
||||
try {
|
||||
@ -490,18 +490,18 @@ class _Tokenizer {
|
||||
|
||||
private _consumeAttributeValue() {
|
||||
this._beginToken(TokenType.ATTR_VALUE);
|
||||
var value: string;
|
||||
let value: string;
|
||||
if (this._peek === chars.$SQ || this._peek === chars.$DQ) {
|
||||
var quoteChar = this._peek;
|
||||
const quoteChar = this._peek;
|
||||
this._advance();
|
||||
var parts: string[] = [];
|
||||
const parts: string[] = [];
|
||||
while (this._peek !== quoteChar) {
|
||||
parts.push(this._readChar(true));
|
||||
}
|
||||
value = parts.join('');
|
||||
this._advance();
|
||||
} else {
|
||||
var valueStart = this._index;
|
||||
const valueStart = this._index;
|
||||
this._requireCharCodeUntilFn(isNameEnd, 1);
|
||||
value = this._input.substring(valueStart, this._index);
|
||||
}
|
||||
@ -519,7 +519,7 @@ class _Tokenizer {
|
||||
private _consumeTagClose(start: ParseLocation) {
|
||||
this._beginToken(TokenType.TAG_CLOSE, start);
|
||||
this._attemptCharCodeUntilFn(isNotWhitespace);
|
||||
let prefixAndName = this._consumePrefixAndName();
|
||||
const prefixAndName = this._consumePrefixAndName();
|
||||
this._attemptCharCodeUntilFn(isNotWhitespace);
|
||||
this._requireCharCode(chars.$GT);
|
||||
this._endToken(prefixAndName);
|
||||
@ -539,7 +539,7 @@ class _Tokenizer {
|
||||
this._attemptCharCodeUntilFn(isNotWhitespace);
|
||||
|
||||
this._beginToken(TokenType.RAW_TEXT, this._getLocation());
|
||||
let type = this._readUntil(chars.$COMMA);
|
||||
const type = this._readUntil(chars.$COMMA);
|
||||
this._endToken([type], this._getLocation());
|
||||
this._requireCharCode(chars.$COMMA);
|
||||
this._attemptCharCodeUntilFn(isNotWhitespace);
|
||||
@ -623,7 +623,7 @@ class _Tokenizer {
|
||||
}
|
||||
|
||||
private _readUntil(char: number): string {
|
||||
let start = this._index;
|
||||
const start = this._index;
|
||||
this._attemptUntilChar(char);
|
||||
return this._input.substring(start, this._index);
|
||||
}
|
||||
@ -633,7 +633,7 @@ class _Tokenizer {
|
||||
this._index = position[1];
|
||||
this._column = position[2];
|
||||
this._line = position[3];
|
||||
let nbTokens = position[4];
|
||||
const nbTokens = position[4];
|
||||
if (nbTokens < this.tokens.length) {
|
||||
// remove any extra tokens
|
||||
this.tokens = this.tokens.slice(0, nbTokens);
|
||||
@ -696,10 +696,10 @@ function toUpperCaseCharCode(code: number): number {
|
||||
}
|
||||
|
||||
function mergeTextTokens(srcTokens: Token[]): Token[] {
|
||||
let dstTokens: Token[] = [];
|
||||
const dstTokens: Token[] = [];
|
||||
let lastDstToken: Token;
|
||||
for (let i = 0; i < srcTokens.length; i++) {
|
||||
let token = srcTokens[i];
|
||||
const token = srcTokens[i];
|
||||
if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
|
||||
lastDstToken.parts[0] += token.parts[0];
|
||||
lastDstToken.sourceSpan.end = token.sourceSpan.end;
|
||||
|
@ -121,7 +121,7 @@ class _TreeBuilder {
|
||||
|
||||
// read =
|
||||
while (this._peek.type === lex.TokenType.EXPANSION_CASE_VALUE) {
|
||||
let expCase = this._parseExpansionCase();
|
||||
const expCase = this._parseExpansionCase();
|
||||
if (!expCase) return; // error
|
||||
cases.push(expCase);
|
||||
}
|
||||
|
@ -35,32 +35,32 @@ export class NgModuleCompileResult {
|
||||
export class NgModuleCompiler {
|
||||
compile(ngModuleMeta: CompileNgModuleMetadata, extraProviders: CompileProviderMetadata[]):
|
||||
NgModuleCompileResult {
|
||||
var sourceFileName = isPresent(ngModuleMeta.type.moduleUrl) ?
|
||||
const sourceFileName = isPresent(ngModuleMeta.type.moduleUrl) ?
|
||||
`in NgModule ${ngModuleMeta.type.name} in ${ngModuleMeta.type.moduleUrl}` :
|
||||
`in NgModule ${ngModuleMeta.type.name}`;
|
||||
var sourceFile = new ParseSourceFile('', sourceFileName);
|
||||
var sourceSpan = new ParseSourceSpan(
|
||||
const sourceFile = new ParseSourceFile('', sourceFileName);
|
||||
const sourceSpan = new ParseSourceSpan(
|
||||
new ParseLocation(sourceFile, null, null, null),
|
||||
new ParseLocation(sourceFile, null, null, null));
|
||||
var deps: ComponentFactoryDependency[] = [];
|
||||
var bootstrapComponentFactories: CompileIdentifierMetadata[] = [];
|
||||
var entryComponentFactories =
|
||||
const deps: ComponentFactoryDependency[] = [];
|
||||
const bootstrapComponentFactories: CompileIdentifierMetadata[] = [];
|
||||
const entryComponentFactories =
|
||||
ngModuleMeta.transitiveModule.entryComponents.map((entryComponent) => {
|
||||
var id = new CompileIdentifierMetadata({name: entryComponent.name});
|
||||
const id = new CompileIdentifierMetadata({name: entryComponent.name});
|
||||
if (ngModuleMeta.bootstrapComponents.indexOf(entryComponent) > -1) {
|
||||
bootstrapComponentFactories.push(id);
|
||||
}
|
||||
deps.push(new ComponentFactoryDependency(entryComponent, id));
|
||||
return id;
|
||||
});
|
||||
var builder = new _InjectorBuilder(
|
||||
const builder = new _InjectorBuilder(
|
||||
ngModuleMeta, entryComponentFactories, bootstrapComponentFactories, sourceSpan);
|
||||
|
||||
var providerParser = new NgModuleProviderAnalyzer(ngModuleMeta, extraProviders, sourceSpan);
|
||||
const providerParser = new NgModuleProviderAnalyzer(ngModuleMeta, extraProviders, sourceSpan);
|
||||
providerParser.parse().forEach((provider) => builder.addProvider(provider));
|
||||
var injectorClass = builder.build();
|
||||
var ngModuleFactoryVar = `${ngModuleMeta.type.name}NgFactory`;
|
||||
var ngModuleFactoryStmt =
|
||||
const injectorClass = builder.build();
|
||||
const ngModuleFactoryVar = `${ngModuleMeta.type.name}NgFactory`;
|
||||
const ngModuleFactoryStmt =
|
||||
o.variable(ngModuleFactoryVar)
|
||||
.set(o.importExpr(resolveIdentifier(Identifiers.NgModuleFactory))
|
||||
.instantiate(
|
||||
@ -70,9 +70,9 @@ export class NgModuleCompiler {
|
||||
[o.importType(ngModuleMeta.type)], [o.TypeModifier.Const])))
|
||||
.toDeclStmt(null, [o.StmtModifier.Final]);
|
||||
|
||||
let stmts: o.Statement[] = [injectorClass, ngModuleFactoryStmt];
|
||||
const stmts: o.Statement[] = [injectorClass, ngModuleFactoryStmt];
|
||||
if (ngModuleMeta.id) {
|
||||
let registerFactoryStmt =
|
||||
const registerFactoryStmt =
|
||||
o.importExpr(resolveIdentifier(Identifiers.RegisterModuleFactoryFn))
|
||||
.callFn([o.literal(ngModuleMeta.id), o.variable(ngModuleFactoryVar)])
|
||||
.toStmt();
|
||||
@ -100,10 +100,10 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
private _sourceSpan: ParseSourceSpan) {}
|
||||
|
||||
addProvider(resolvedProvider: ProviderAst) {
|
||||
var providerValueExpressions =
|
||||
const providerValueExpressions =
|
||||
resolvedProvider.providers.map((provider) => this._getProviderValue(provider));
|
||||
var propName = `_${resolvedProvider.token.name}_${this._instances.size}`;
|
||||
var instance = this._createProviderProperty(
|
||||
const propName = `_${resolvedProvider.token.name}_${this._instances.size}`;
|
||||
const instance = this._createProviderProperty(
|
||||
propName, resolvedProvider, providerValueExpressions, resolvedProvider.multiProvider,
|
||||
resolvedProvider.eager);
|
||||
if (resolvedProvider.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
|
||||
@ -114,18 +114,17 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
}
|
||||
|
||||
build(): o.ClassStmt {
|
||||
let getMethodStmts: o.Statement[] = this._tokens.map((token) => {
|
||||
var providerExpr = this._instances.get(token.reference);
|
||||
const getMethodStmts: o.Statement[] = this._tokens.map((token) => {
|
||||
const providerExpr = this._instances.get(token.reference);
|
||||
return new o.IfStmt(
|
||||
InjectMethodVars.token.identical(createDiTokenExpression(token)),
|
||||
[new o.ReturnStatement(providerExpr)]);
|
||||
});
|
||||
var methods = [
|
||||
const methods = [
|
||||
new o.ClassMethod(
|
||||
'createInternal', [], this._createStmts.concat(
|
||||
new o.ReturnStatement(this._instances.get(this._ngModuleMeta.type.reference))
|
||||
), o.importType(this._ngModuleMeta.type)
|
||||
),
|
||||
'createInternal', [], this._createStmts.concat(new o.ReturnStatement(
|
||||
this._instances.get(this._ngModuleMeta.type.reference))),
|
||||
o.importType(this._ngModuleMeta.type)),
|
||||
new o.ClassMethod(
|
||||
'getInternal',
|
||||
[
|
||||
@ -134,19 +133,17 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
],
|
||||
getMethodStmts.concat([new o.ReturnStatement(InjectMethodVars.notFoundResult)]),
|
||||
o.DYNAMIC_TYPE),
|
||||
new o.ClassMethod(
|
||||
'destroyInternal', [], this._destroyStmts
|
||||
),
|
||||
new o.ClassMethod('destroyInternal', [], this._destroyStmts),
|
||||
];
|
||||
|
||||
var parentArgs = [
|
||||
const parentArgs = [
|
||||
o.variable(InjectorProps.parent.name),
|
||||
o.literalArr(
|
||||
this._entryComponentFactories.map((componentFactory) => o.importExpr(componentFactory))),
|
||||
o.literalArr(this._bootstrapComponentFactories.map(
|
||||
(componentFactory) => o.importExpr(componentFactory)))
|
||||
];
|
||||
var injClassName = `${this._ngModuleMeta.type.name}Injector`;
|
||||
const injClassName = `${this._ngModuleMeta.type.name}Injector`;
|
||||
return createClassStmt({
|
||||
name: injClassName,
|
||||
ctorParams: [new o.FnParam(
|
||||
@ -159,16 +156,16 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
}
|
||||
|
||||
private _getProviderValue(provider: CompileProviderMetadata): o.Expression {
|
||||
var result: o.Expression;
|
||||
let result: o.Expression;
|
||||
if (isPresent(provider.useExisting)) {
|
||||
result = this._getDependency(new CompileDiDependencyMetadata({token: provider.useExisting}));
|
||||
} else if (isPresent(provider.useFactory)) {
|
||||
var deps = provider.deps || provider.useFactory.diDeps;
|
||||
var depsExpr = deps.map((dep) => this._getDependency(dep));
|
||||
const deps = provider.deps || provider.useFactory.diDeps;
|
||||
const depsExpr = deps.map((dep) => this._getDependency(dep));
|
||||
result = o.importExpr(provider.useFactory).callFn(depsExpr);
|
||||
} else if (isPresent(provider.useClass)) {
|
||||
var deps = provider.deps || provider.useClass.diDeps;
|
||||
var depsExpr = deps.map((dep) => this._getDependency(dep));
|
||||
const deps = provider.deps || provider.useClass.diDeps;
|
||||
const depsExpr = deps.map((dep) => this._getDependency(dep));
|
||||
result =
|
||||
o.importExpr(provider.useClass).instantiate(depsExpr, o.importType(provider.useClass));
|
||||
} else {
|
||||
@ -181,8 +178,8 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
private _createProviderProperty(
|
||||
propName: string, provider: ProviderAst, providerValueExpressions: o.Expression[],
|
||||
isMulti: boolean, isEager: boolean): o.Expression {
|
||||
var resolvedProviderValueExpr: o.Expression;
|
||||
var type: o.Type;
|
||||
let resolvedProviderValueExpr: o.Expression;
|
||||
let type: o.Type;
|
||||
if (isMulti) {
|
||||
resolvedProviderValueExpr = o.literalArr(providerValueExpressions);
|
||||
type = new o.ArrayType(o.DYNAMIC_TYPE);
|
||||
@ -197,10 +194,10 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
this.fields.push(new o.ClassField(propName, type));
|
||||
this._createStmts.push(o.THIS_EXPR.prop(propName).set(resolvedProviderValueExpr).toStmt());
|
||||
} else {
|
||||
var internalField = `_${propName}`;
|
||||
const internalField = `_${propName}`;
|
||||
this.fields.push(new o.ClassField(internalField, type));
|
||||
// Note: Equals is important for JS so that it also checks the undefined case!
|
||||
var getterStmts = [
|
||||
const getterStmts = [
|
||||
new o.IfStmt(
|
||||
o.THIS_EXPR.prop(internalField).isBlank(),
|
||||
[o.THIS_EXPR.prop(internalField).set(resolvedProviderValueExpr).toStmt()]),
|
||||
@ -212,7 +209,7 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
}
|
||||
|
||||
private _getDependency(dep: CompileDiDependencyMetadata): o.Expression {
|
||||
var result: o.Expression = null;
|
||||
let result: o.Expression = null;
|
||||
if (dep.isValue) {
|
||||
result = o.literal(dep.value);
|
||||
}
|
||||
@ -228,7 +225,7 @@ class _InjectorBuilder implements ClassBuilder {
|
||||
}
|
||||
}
|
||||
if (!result) {
|
||||
var args = [createDiTokenExpression(dep.token)];
|
||||
const args = [createDiTokenExpression(dep.token)];
|
||||
if (dep.isOptional) {
|
||||
args.push(o.NULL_EXPR);
|
||||
}
|
||||
|
@ -78,7 +78,7 @@ export class EmitterVisitorContext {
|
||||
}
|
||||
|
||||
toSource(): any {
|
||||
var lines = this._lines;
|
||||
let lines = this._lines;
|
||||
if (lines[lines.length - 1].parts.length === 0) {
|
||||
lines = lines.slice(0, lines.length - 1);
|
||||
}
|
||||
@ -118,7 +118,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
ctx.print(`if (`);
|
||||
stmt.condition.visitExpression(this, ctx);
|
||||
ctx.print(`) {`);
|
||||
var hasElseCase = isPresent(stmt.falseCase) && stmt.falseCase.length > 0;
|
||||
const hasElseCase = isPresent(stmt.falseCase) && stmt.falseCase.length > 0;
|
||||
if (stmt.trueCase.length <= 1 && !hasElseCase) {
|
||||
ctx.print(` `);
|
||||
this.visitAllStatements(stmt.trueCase, ctx);
|
||||
@ -149,13 +149,13 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
return null;
|
||||
}
|
||||
visitCommentStmt(stmt: o.CommentStmt, ctx: EmitterVisitorContext): any {
|
||||
var lines = stmt.comment.split('\n');
|
||||
const lines = stmt.comment.split('\n');
|
||||
lines.forEach((line) => { ctx.println(`// ${line}`); });
|
||||
return null;
|
||||
}
|
||||
abstract visitDeclareVarStmt(stmt: o.DeclareVarStmt, ctx: EmitterVisitorContext): any;
|
||||
visitWriteVarExpr(expr: o.WriteVarExpr, ctx: EmitterVisitorContext): any {
|
||||
var lineWasEmpty = ctx.lineIsEmpty();
|
||||
const lineWasEmpty = ctx.lineIsEmpty();
|
||||
if (!lineWasEmpty) {
|
||||
ctx.print('(');
|
||||
}
|
||||
@ -167,7 +167,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
return null;
|
||||
}
|
||||
visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: EmitterVisitorContext): any {
|
||||
var lineWasEmpty = ctx.lineIsEmpty();
|
||||
const lineWasEmpty = ctx.lineIsEmpty();
|
||||
if (!lineWasEmpty) {
|
||||
ctx.print('(');
|
||||
}
|
||||
@ -182,7 +182,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
return null;
|
||||
}
|
||||
visitWritePropExpr(expr: o.WritePropExpr, ctx: EmitterVisitorContext): any {
|
||||
var lineWasEmpty = ctx.lineIsEmpty();
|
||||
const lineWasEmpty = ctx.lineIsEmpty();
|
||||
if (!lineWasEmpty) {
|
||||
ctx.print('(');
|
||||
}
|
||||
@ -196,7 +196,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
}
|
||||
visitInvokeMethodExpr(expr: o.InvokeMethodExpr, ctx: EmitterVisitorContext): any {
|
||||
expr.receiver.visitExpression(this, ctx);
|
||||
var name = expr.name;
|
||||
let name = expr.name;
|
||||
if (isPresent(expr.builtin)) {
|
||||
name = this.getBuiltinMethodName(expr.builtin);
|
||||
if (isBlank(name)) {
|
||||
@ -220,7 +220,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
return null;
|
||||
}
|
||||
visitReadVarExpr(ast: o.ReadVarExpr, ctx: EmitterVisitorContext): any {
|
||||
var varName = ast.name;
|
||||
let varName = ast.name;
|
||||
if (isPresent(ast.builtin)) {
|
||||
switch (ast.builtin) {
|
||||
case o.BuiltinVar.Super:
|
||||
@ -282,7 +282,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
abstract visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, context: any): any;
|
||||
|
||||
visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, ctx: EmitterVisitorContext): any {
|
||||
var opStr: string;
|
||||
let opStr: string;
|
||||
switch (ast.operator) {
|
||||
case o.BinaryOperator.Equals:
|
||||
opStr = '==';
|
||||
@ -354,7 +354,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
return null;
|
||||
}
|
||||
visitLiteralArrayExpr(ast: o.LiteralArrayExpr, ctx: EmitterVisitorContext): any {
|
||||
var useNewLine = ast.entries.length > 1;
|
||||
const useNewLine = ast.entries.length > 1;
|
||||
ctx.print(`[`, useNewLine);
|
||||
ctx.incIndent();
|
||||
this.visitAllExpressions(ast.entries, ctx, ',', useNewLine);
|
||||
@ -363,7 +363,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
return null;
|
||||
}
|
||||
visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: EmitterVisitorContext): any {
|
||||
var useNewLine = ast.entries.length > 1;
|
||||
const useNewLine = ast.entries.length > 1;
|
||||
ctx.print(`{`, useNewLine);
|
||||
ctx.incIndent();
|
||||
this.visitAllObjects(entry => {
|
||||
@ -385,7 +385,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
|
||||
visitAllObjects<T>(
|
||||
handler: (t: T) => void, expressions: T[], ctx: EmitterVisitorContext, separator: string,
|
||||
newLine: boolean = false): void {
|
||||
for (var i = 0; i < expressions.length; i++) {
|
||||
for (let i = 0; i < expressions.length; i++) {
|
||||
if (i > 0) {
|
||||
ctx.print(separator, newLine);
|
||||
}
|
||||
@ -406,7 +406,7 @@ export function escapeIdentifier(
|
||||
if (isBlank(input)) {
|
||||
return null;
|
||||
}
|
||||
var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match: string[]) => {
|
||||
const body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match: string[]) => {
|
||||
if (match[0] == '$') {
|
||||
return escapeDollar ? '\\$' : '$';
|
||||
} else if (match[0] == '\n') {
|
||||
@ -417,13 +417,13 @@ export function escapeIdentifier(
|
||||
return `\\${match[0]}`;
|
||||
}
|
||||
});
|
||||
let requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
|
||||
const requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
|
||||
return requiresQuotes ? `'${body}'` : body;
|
||||
}
|
||||
|
||||
function _createIndent(count: number): string {
|
||||
var res = '';
|
||||
for (var i = 0; i < count; i++) {
|
||||
let res = '';
|
||||
for (let i = 0; i < count; i++) {
|
||||
res += ' ';
|
||||
}
|
||||
return res;
|
||||
|
@ -92,7 +92,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
|
||||
return null;
|
||||
}
|
||||
visitInvokeFunctionExpr(expr: o.InvokeFunctionExpr, ctx: EmitterVisitorContext): string {
|
||||
var fnExpr = expr.fn;
|
||||
const fnExpr = expr.fn;
|
||||
if (fnExpr instanceof o.ReadVarExpr && fnExpr.builtin === o.BuiltinVar.Super) {
|
||||
ctx.currentClass.parent.visitExpression(this, ctx);
|
||||
ctx.print(`.call(this`);
|
||||
@ -133,7 +133,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
|
||||
ctx.decIndent();
|
||||
ctx.println(`} catch (${CATCH_ERROR_VAR.name}) {`);
|
||||
ctx.incIndent();
|
||||
var catchStmts =
|
||||
const catchStmts =
|
||||
[<o.Statement>CATCH_STACK_VAR.set(CATCH_ERROR_VAR.prop('stack')).toDeclStmt(null, [
|
||||
o.StmtModifier.Final
|
||||
])].concat(stmt.catchStmts);
|
||||
@ -148,7 +148,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
|
||||
}
|
||||
|
||||
getBuiltinMethodName(method: o.BuiltinMethod): string {
|
||||
var name: string;
|
||||
let name: string;
|
||||
switch (method) {
|
||||
case o.BuiltinMethod.ConcatArray:
|
||||
name = 'concat';
|
||||
|
@ -17,10 +17,10 @@ import {ImportGenerator} from './path_util';
|
||||
export class JavaScriptEmitter implements OutputEmitter {
|
||||
constructor(private _importGenerator: ImportGenerator) {}
|
||||
emitStatements(moduleUrl: string, stmts: o.Statement[], exportedVars: string[]): string {
|
||||
var converter = new JsEmitterVisitor(moduleUrl);
|
||||
var ctx = EmitterVisitorContext.createRoot(exportedVars);
|
||||
const converter = new JsEmitterVisitor(moduleUrl);
|
||||
const ctx = EmitterVisitorContext.createRoot(exportedVars);
|
||||
converter.visitAllStatements(stmts, ctx);
|
||||
var srcParts: string[] = [];
|
||||
const srcParts: string[] = [];
|
||||
converter.importsWithPrefixes.forEach((prefix, importedModuleUrl) => {
|
||||
// Note: can't write the real word for import as it screws up system.js auto detection...
|
||||
srcParts.push(
|
||||
@ -42,7 +42,7 @@ class JsEmitterVisitor extends AbstractJsEmitterVisitor {
|
||||
throw new Error(`Internal error: unknown identifier ${ast.value}`);
|
||||
}
|
||||
if (isPresent(ast.value.moduleUrl) && ast.value.moduleUrl != this._moduleUrl) {
|
||||
var prefix = this.importsWithPrefixes.get(ast.value.moduleUrl);
|
||||
let prefix = this.importsWithPrefixes.get(ast.value.moduleUrl);
|
||||
if (isBlank(prefix)) {
|
||||
prefix = `import${this.importsWithPrefixes.size}`;
|
||||
this.importsWithPrefixes.set(ast.value.moduleUrl, prefix);
|
||||
|
@ -626,7 +626,7 @@ export class ExpressionTransformer implements StatementVisitor, ExpressionVisito
|
||||
expr.value.visitExpression(this, context));
|
||||
}
|
||||
visitInvokeMethodExpr(ast: InvokeMethodExpr, context: any): any {
|
||||
var method = ast.builtin || ast.name;
|
||||
const method = ast.builtin || ast.name;
|
||||
return new InvokeMethodExpr(
|
||||
ast.receiver.visitExpression(this, context), method,
|
||||
this.visitAllExpressions(ast.args, context), ast.type);
|
||||
@ -841,7 +841,7 @@ export class RecursiveExpressionVisitor implements StatementVisitor, ExpressionV
|
||||
|
||||
export function replaceVarInExpression(
|
||||
varName: string, newValue: Expression, expression: Expression): Expression {
|
||||
var transformer = new _ReplaceVariableTransformer(varName, newValue);
|
||||
const transformer = new _ReplaceVariableTransformer(varName, newValue);
|
||||
return expression.visitExpression(transformer, null);
|
||||
}
|
||||
|
||||
@ -853,7 +853,7 @@ class _ReplaceVariableTransformer extends ExpressionTransformer {
|
||||
}
|
||||
|
||||
export function findReadVarNames(stmts: Statement[]): Set<string> {
|
||||
var finder = new _VariableFinder();
|
||||
const finder = new _VariableFinder();
|
||||
finder.visitAllStatements(stmts, null);
|
||||
return finder.varNames;
|
||||
}
|
||||
|
@ -13,21 +13,21 @@ import * as o from './output_ast';
|
||||
import {debugOutputAstAsTypeScript} from './ts_emitter';
|
||||
|
||||
export function interpretStatements(statements: o.Statement[], resultVar: string): any {
|
||||
var stmtsWithReturn = statements.concat([new o.ReturnStatement(o.variable(resultVar))]);
|
||||
var ctx = new _ExecutionContext(null, null, null, new Map<string, any>());
|
||||
var visitor = new StatementInterpreter();
|
||||
var result = visitor.visitAllStatements(stmtsWithReturn, ctx);
|
||||
const stmtsWithReturn = statements.concat([new o.ReturnStatement(o.variable(resultVar))]);
|
||||
const ctx = new _ExecutionContext(null, null, null, new Map<string, any>());
|
||||
const visitor = new StatementInterpreter();
|
||||
const result = visitor.visitAllStatements(stmtsWithReturn, ctx);
|
||||
return isPresent(result) ? result.value : null;
|
||||
}
|
||||
|
||||
function _executeFunctionStatements(
|
||||
varNames: string[], varValues: any[], statements: o.Statement[], ctx: _ExecutionContext,
|
||||
visitor: StatementInterpreter): any {
|
||||
var childCtx = ctx.createChildWihtLocalVars();
|
||||
for (var i = 0; i < varNames.length; i++) {
|
||||
const childCtx = ctx.createChildWihtLocalVars();
|
||||
for (let i = 0; i < varNames.length; i++) {
|
||||
childCtx.vars.set(varNames[i], varValues[i]);
|
||||
}
|
||||
var result = visitor.visitAllStatements(statements, childCtx);
|
||||
const result = visitor.visitAllStatements(statements, childCtx);
|
||||
return isPresent(result) ? result.value : null;
|
||||
}
|
||||
|
||||
@ -47,14 +47,14 @@ class ReturnValue {
|
||||
|
||||
function createDynamicClass(
|
||||
_classStmt: o.ClassStmt, _ctx: _ExecutionContext, _visitor: StatementInterpreter): Function {
|
||||
let propertyDescriptors: {[key: string]: any} = {};
|
||||
const propertyDescriptors: {[key: string]: any} = {};
|
||||
|
||||
_classStmt.getters.forEach((getter: o.ClassGetter) => {
|
||||
// Note: use `function` instead of arrow function to capture `this`
|
||||
propertyDescriptors[getter.name] = {
|
||||
configurable: false,
|
||||
get: function() {
|
||||
let instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
|
||||
const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
|
||||
return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
|
||||
}
|
||||
};
|
||||
@ -66,21 +66,21 @@ function createDynamicClass(
|
||||
writable: false,
|
||||
configurable: false,
|
||||
value: function(...args: any[]) {
|
||||
let instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
|
||||
const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
|
||||
return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
var ctorParamNames = _classStmt.constructorMethod.params.map(param => param.name);
|
||||
const ctorParamNames = _classStmt.constructorMethod.params.map(param => param.name);
|
||||
// Note: use `function` instead of arrow function to capture `this`
|
||||
var ctor = function(...args: any[]) {
|
||||
let instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
|
||||
const ctor = function(...args: any[]) {
|
||||
const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
|
||||
_classStmt.fields.forEach((field) => { this[field.name] = undefined; });
|
||||
_executeFunctionStatements(
|
||||
ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
|
||||
};
|
||||
var superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
|
||||
const superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
|
||||
ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
|
||||
return ctor;
|
||||
}
|
||||
@ -93,8 +93,8 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
return null;
|
||||
}
|
||||
visitWriteVarExpr(expr: o.WriteVarExpr, ctx: _ExecutionContext): any {
|
||||
var value = expr.value.visitExpression(this, ctx);
|
||||
var currCtx = ctx;
|
||||
const value = expr.value.visitExpression(this, ctx);
|
||||
let currCtx = ctx;
|
||||
while (currCtx != null) {
|
||||
if (currCtx.vars.has(expr.name)) {
|
||||
currCtx.vars.set(expr.name, value);
|
||||
@ -105,7 +105,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
throw new Error(`Not declared variable ${expr.name}`);
|
||||
}
|
||||
visitReadVarExpr(ast: o.ReadVarExpr, ctx: _ExecutionContext): any {
|
||||
var varName = ast.name;
|
||||
let varName = ast.name;
|
||||
if (isPresent(ast.builtin)) {
|
||||
switch (ast.builtin) {
|
||||
case o.BuiltinVar.Super:
|
||||
@ -122,7 +122,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
throw new Error(`Unknown builtin variable ${ast.builtin}`);
|
||||
}
|
||||
}
|
||||
var currCtx = ctx;
|
||||
let currCtx = ctx;
|
||||
while (currCtx != null) {
|
||||
if (currCtx.vars.has(varName)) {
|
||||
return currCtx.vars.get(varName);
|
||||
@ -132,23 +132,23 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
throw new Error(`Not declared variable ${varName}`);
|
||||
}
|
||||
visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: _ExecutionContext): any {
|
||||
var receiver = expr.receiver.visitExpression(this, ctx);
|
||||
var index = expr.index.visitExpression(this, ctx);
|
||||
var value = expr.value.visitExpression(this, ctx);
|
||||
const receiver = expr.receiver.visitExpression(this, ctx);
|
||||
const index = expr.index.visitExpression(this, ctx);
|
||||
const value = expr.value.visitExpression(this, ctx);
|
||||
receiver[index] = value;
|
||||
return value;
|
||||
}
|
||||
visitWritePropExpr(expr: o.WritePropExpr, ctx: _ExecutionContext): any {
|
||||
var receiver = expr.receiver.visitExpression(this, ctx);
|
||||
var value = expr.value.visitExpression(this, ctx);
|
||||
const receiver = expr.receiver.visitExpression(this, ctx);
|
||||
const value = expr.value.visitExpression(this, ctx);
|
||||
receiver[expr.name] = value;
|
||||
return value;
|
||||
}
|
||||
|
||||
visitInvokeMethodExpr(expr: o.InvokeMethodExpr, ctx: _ExecutionContext): any {
|
||||
var receiver = expr.receiver.visitExpression(this, ctx);
|
||||
var args = this.visitAllExpressions(expr.args, ctx);
|
||||
var result: any;
|
||||
const receiver = expr.receiver.visitExpression(this, ctx);
|
||||
const args = this.visitAllExpressions(expr.args, ctx);
|
||||
let result: any;
|
||||
if (isPresent(expr.builtin)) {
|
||||
switch (expr.builtin) {
|
||||
case o.BuiltinMethod.ConcatArray:
|
||||
@ -169,13 +169,13 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
return result;
|
||||
}
|
||||
visitInvokeFunctionExpr(stmt: o.InvokeFunctionExpr, ctx: _ExecutionContext): any {
|
||||
var args = this.visitAllExpressions(stmt.args, ctx);
|
||||
var fnExpr = stmt.fn;
|
||||
const args = this.visitAllExpressions(stmt.args, ctx);
|
||||
const fnExpr = stmt.fn;
|
||||
if (fnExpr instanceof o.ReadVarExpr && fnExpr.builtin === o.BuiltinVar.Super) {
|
||||
ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
|
||||
return null;
|
||||
} else {
|
||||
var fn = stmt.fn.visitExpression(this, ctx);
|
||||
const fn = stmt.fn.visitExpression(this, ctx);
|
||||
return fn.apply(null, args);
|
||||
}
|
||||
}
|
||||
@ -183,7 +183,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
return new ReturnValue(stmt.value.visitExpression(this, ctx));
|
||||
}
|
||||
visitDeclareClassStmt(stmt: o.ClassStmt, ctx: _ExecutionContext): any {
|
||||
var clazz = createDynamicClass(stmt, ctx, this);
|
||||
const clazz = createDynamicClass(stmt, ctx, this);
|
||||
ctx.vars.set(stmt.name, clazz);
|
||||
return null;
|
||||
}
|
||||
@ -191,7 +191,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
return stmt.expr.visitExpression(this, ctx);
|
||||
}
|
||||
visitIfStmt(stmt: o.IfStmt, ctx: _ExecutionContext): any {
|
||||
var condition = stmt.condition.visitExpression(this, ctx);
|
||||
const condition = stmt.condition.visitExpression(this, ctx);
|
||||
if (condition) {
|
||||
return this.visitAllStatements(stmt.trueCase, ctx);
|
||||
} else if (isPresent(stmt.falseCase)) {
|
||||
@ -203,7 +203,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
try {
|
||||
return this.visitAllStatements(stmt.bodyStmts, ctx);
|
||||
} catch (e) {
|
||||
var childCtx = ctx.createChildWihtLocalVars();
|
||||
const childCtx = ctx.createChildWihtLocalVars();
|
||||
childCtx.vars.set(CATCH_ERROR_VAR, e);
|
||||
childCtx.vars.set(CATCH_STACK_VAR, e.stack);
|
||||
return this.visitAllStatements(stmt.catchStmts, childCtx);
|
||||
@ -214,8 +214,8 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
}
|
||||
visitCommentStmt(stmt: o.CommentStmt, context?: any): any { return null; }
|
||||
visitInstantiateExpr(ast: o.InstantiateExpr, ctx: _ExecutionContext): any {
|
||||
var args = this.visitAllExpressions(ast.args, ctx);
|
||||
var clazz = ast.classExpr.visitExpression(this, ctx);
|
||||
const args = this.visitAllExpressions(ast.args, ctx);
|
||||
const clazz = ast.classExpr.visitExpression(this, ctx);
|
||||
return new clazz(...args);
|
||||
}
|
||||
visitLiteralExpr(ast: o.LiteralExpr, ctx: _ExecutionContext): any { return ast.value; }
|
||||
@ -237,17 +237,17 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
return ast.value.visitExpression(this, ctx);
|
||||
}
|
||||
visitFunctionExpr(ast: o.FunctionExpr, ctx: _ExecutionContext): any {
|
||||
var paramNames = ast.params.map((param) => param.name);
|
||||
const paramNames = ast.params.map((param) => param.name);
|
||||
return _declareFn(paramNames, ast.statements, ctx, this);
|
||||
}
|
||||
visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, ctx: _ExecutionContext): any {
|
||||
var paramNames = stmt.params.map((param) => param.name);
|
||||
const paramNames = stmt.params.map((param) => param.name);
|
||||
ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
|
||||
return null;
|
||||
}
|
||||
visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, ctx: _ExecutionContext): any {
|
||||
var lhs = () => ast.lhs.visitExpression(this, ctx);
|
||||
var rhs = () => ast.rhs.visitExpression(this, ctx);
|
||||
const lhs = () => ast.lhs.visitExpression(this, ctx);
|
||||
const rhs = () => ast.rhs.visitExpression(this, ctx);
|
||||
|
||||
switch (ast.operator) {
|
||||
case o.BinaryOperator.Equals:
|
||||
@ -285,21 +285,21 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
}
|
||||
}
|
||||
visitReadPropExpr(ast: o.ReadPropExpr, ctx: _ExecutionContext): any {
|
||||
var result: any;
|
||||
var receiver = ast.receiver.visitExpression(this, ctx);
|
||||
let result: any;
|
||||
const receiver = ast.receiver.visitExpression(this, ctx);
|
||||
result = receiver[ast.name];
|
||||
return result;
|
||||
}
|
||||
visitReadKeyExpr(ast: o.ReadKeyExpr, ctx: _ExecutionContext): any {
|
||||
var receiver = ast.receiver.visitExpression(this, ctx);
|
||||
var prop = ast.index.visitExpression(this, ctx);
|
||||
const receiver = ast.receiver.visitExpression(this, ctx);
|
||||
const prop = ast.index.visitExpression(this, ctx);
|
||||
return receiver[prop];
|
||||
}
|
||||
visitLiteralArrayExpr(ast: o.LiteralArrayExpr, ctx: _ExecutionContext): any {
|
||||
return this.visitAllExpressions(ast.entries, ctx);
|
||||
}
|
||||
visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: _ExecutionContext): any {
|
||||
var result = {};
|
||||
const result = {};
|
||||
ast.entries.forEach(
|
||||
(entry) => (result as any)[<string>entry[0]] =
|
||||
(<o.Expression>entry[1]).visitExpression(this, ctx));
|
||||
@ -311,9 +311,9 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
|
||||
}
|
||||
|
||||
visitAllStatements(statements: o.Statement[], ctx: _ExecutionContext): ReturnValue {
|
||||
for (var i = 0; i < statements.length; i++) {
|
||||
var stmt = statements[i];
|
||||
var val = stmt.visitStatement(this, ctx);
|
||||
for (let i = 0; i < statements.length; i++) {
|
||||
const stmt = statements[i];
|
||||
const val = stmt.visitStatement(this, ctx);
|
||||
if (val instanceof ReturnValue) {
|
||||
return val;
|
||||
}
|
||||
@ -328,5 +328,5 @@ function _declareFn(
|
||||
return (...args: any[]) => _executeFunctionStatements(varNames, args, statements, ctx, visitor);
|
||||
}
|
||||
|
||||
var CATCH_ERROR_VAR = 'error';
|
||||
var CATCH_STACK_VAR = 'stack';
|
||||
const CATCH_ERROR_VAR = 'error';
|
||||
const CATCH_STACK_VAR = 'stack';
|
||||
|
@ -28,8 +28,8 @@ function evalExpression(
|
||||
|
||||
export function jitStatements(
|
||||
sourceUrl: string, statements: o.Statement[], resultVar: string): any {
|
||||
var converter = new JitEmitterVisitor();
|
||||
var ctx = EmitterVisitorContext.createRoot([resultVar]);
|
||||
const converter = new JitEmitterVisitor();
|
||||
const ctx = EmitterVisitorContext.createRoot([resultVar]);
|
||||
converter.visitAllStatements(statements, ctx);
|
||||
return evalExpression(sourceUrl, resultVar, ctx.toSource(), converter.getArgs());
|
||||
}
|
||||
@ -39,20 +39,20 @@ class JitEmitterVisitor extends AbstractJsEmitterVisitor {
|
||||
private _evalArgValues: any[] = [];
|
||||
|
||||
getArgs(): {[key: string]: any} {
|
||||
var result: {[key: string]: any} = {};
|
||||
for (var i = 0; i < this._evalArgNames.length; i++) {
|
||||
const result: {[key: string]: any} = {};
|
||||
for (let i = 0; i < this._evalArgNames.length; i++) {
|
||||
result[this._evalArgNames[i]] = this._evalArgValues[i];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any {
|
||||
var value = ast.value.reference;
|
||||
var id = this._evalArgValues.indexOf(value);
|
||||
const value = ast.value.reference;
|
||||
let id = this._evalArgValues.indexOf(value);
|
||||
if (id === -1) {
|
||||
id = this._evalArgValues.length;
|
||||
this._evalArgValues.push(value);
|
||||
var name = isPresent(ast.value.name) ? sanitizeIdentifier(ast.value.name) : 'val';
|
||||
const name = isPresent(ast.value.name) ? sanitizeIdentifier(ast.value.name) : 'val';
|
||||
this._evalArgNames.push(sanitizeIdentifier(`jit_${name}${id}`));
|
||||
}
|
||||
ctx.print(this._evalArgNames[id]);
|
||||
|
@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
// asset:<package-name>/<realm>/<path-to-module>
|
||||
var _ASSET_URL_RE = /asset:([^\/]+)\/([^\/]+)\/(.+)/;
|
||||
const _ASSET_URL_RE = /asset:([^\/]+)\/([^\/]+)\/(.+)/;
|
||||
|
||||
/**
|
||||
* Interface that defines how import statements should be generated.
|
||||
|
@ -39,10 +39,10 @@ export function debugOutputAstAsTypeScript(ast: o.Statement | o.Expression | o.T
|
||||
export class TypeScriptEmitter implements OutputEmitter {
|
||||
constructor(private _importGenerator: ImportGenerator) {}
|
||||
emitStatements(moduleUrl: string, stmts: o.Statement[], exportedVars: string[]): string {
|
||||
var converter = new _TsEmitterVisitor(moduleUrl);
|
||||
var ctx = EmitterVisitorContext.createRoot(exportedVars);
|
||||
const converter = new _TsEmitterVisitor(moduleUrl);
|
||||
const ctx = EmitterVisitorContext.createRoot(exportedVars);
|
||||
converter.visitAllStatements(stmts, ctx);
|
||||
var srcParts: string[] = [];
|
||||
const srcParts: string[] = [];
|
||||
converter.importsWithPrefixes.forEach((prefix, importedModuleUrl) => {
|
||||
// Note: can't write the real word for import as it screws up system.js auto detection...
|
||||
srcParts.push(
|
||||
@ -233,7 +233,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
|
||||
ctx.decIndent();
|
||||
ctx.println(`} catch (${CATCH_ERROR_VAR.name}) {`);
|
||||
ctx.incIndent();
|
||||
var catchStmts =
|
||||
const catchStmts =
|
||||
[<o.Statement>CATCH_STACK_VAR.set(CATCH_ERROR_VAR.prop('stack')).toDeclStmt(null, [
|
||||
o.StmtModifier.Final
|
||||
])].concat(stmt.catchStmts);
|
||||
@ -244,7 +244,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
|
||||
}
|
||||
|
||||
visitBuiltintType(type: o.BuiltinType, ctx: EmitterVisitorContext): any {
|
||||
var typeStr: string;
|
||||
let typeStr: string;
|
||||
switch (type.name) {
|
||||
case o.BuiltinTypeName.Bool:
|
||||
typeStr = 'boolean';
|
||||
@ -290,7 +290,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
|
||||
}
|
||||
|
||||
getBuiltinMethodName(method: o.BuiltinMethod): string {
|
||||
var name: string;
|
||||
let name: string;
|
||||
switch (method) {
|
||||
case o.BuiltinMethod.ConcatArray:
|
||||
name = 'concat';
|
||||
@ -321,7 +321,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
|
||||
throw new Error(`Internal error: unknown identifier ${value}`);
|
||||
}
|
||||
if (isPresent(value.moduleUrl) && value.moduleUrl != this._moduleUrl) {
|
||||
var prefix = this.importsWithPrefixes.get(value.moduleUrl);
|
||||
let prefix = this.importsWithPrefixes.get(value.moduleUrl);
|
||||
if (isBlank(prefix)) {
|
||||
prefix = `import${this.importsWithPrefixes.size}`;
|
||||
this.importsWithPrefixes.set(value.moduleUrl, prefix);
|
||||
|
@ -41,17 +41,17 @@ export class ParseError {
|
||||
public level: ParseErrorLevel = ParseErrorLevel.FATAL) {}
|
||||
|
||||
toString(): string {
|
||||
var source = this.span.start.file.content;
|
||||
var ctxStart = this.span.start.offset;
|
||||
var contextStr = '';
|
||||
var details = '';
|
||||
const source = this.span.start.file.content;
|
||||
let ctxStart = this.span.start.offset;
|
||||
let contextStr = '';
|
||||
let details = '';
|
||||
if (isPresent(ctxStart)) {
|
||||
if (ctxStart > source.length - 1) {
|
||||
ctxStart = source.length - 1;
|
||||
}
|
||||
var ctxEnd = ctxStart;
|
||||
var ctxLen = 0;
|
||||
var ctxLines = 0;
|
||||
let ctxEnd = ctxStart;
|
||||
let ctxLen = 0;
|
||||
let ctxLines = 0;
|
||||
|
||||
while (ctxLen < 100 && ctxStart > 0) {
|
||||
ctxStart--;
|
||||
@ -75,7 +75,7 @@ export class ParseError {
|
||||
}
|
||||
}
|
||||
|
||||
let context = source.substring(ctxStart, this.span.start.offset) + '[ERROR ->]' +
|
||||
const context = source.substring(ctxStart, this.span.start.offset) + '[ERROR ->]' +
|
||||
source.substring(this.span.start.offset, ctxEnd + 1);
|
||||
contextStr = ` ("${context}")`;
|
||||
}
|
||||
|
@ -35,9 +35,9 @@ export class PipeResolver {
|
||||
* Return {@link Pipe} for a given `Type`.
|
||||
*/
|
||||
resolve(type: Type<any>, throwIfNotFound = true): Pipe {
|
||||
var metas = this._reflector.annotations(resolveForwardRef(type));
|
||||
const metas = this._reflector.annotations(resolveForwardRef(type));
|
||||
if (isPresent(metas)) {
|
||||
var annotation = metas.find(_isPipeMetadata);
|
||||
const annotation = metas.find(_isPipeMetadata);
|
||||
if (isPresent(annotation)) {
|
||||
return annotation;
|
||||
}
|
||||
|
@ -54,11 +54,11 @@ export class ProviderElementContext {
|
||||
refs: ReferenceAst[], private _sourceSpan: ParseSourceSpan) {
|
||||
this._attrs = {};
|
||||
attrs.forEach((attrAst) => this._attrs[attrAst.name] = attrAst.value);
|
||||
var directivesMeta = _directiveAsts.map(directiveAst => directiveAst.directive);
|
||||
const directivesMeta = _directiveAsts.map(directiveAst => directiveAst.directive);
|
||||
this._allProviders =
|
||||
_resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
|
||||
this._contentQueries = _getContentQueries(directivesMeta);
|
||||
var queriedTokens = new Map<any, boolean>();
|
||||
const queriedTokens = new Map<any, boolean>();
|
||||
Array.from(this._allProviders.values()).forEach((provider) => {
|
||||
this._addQueryReadsTo(provider.token, queriedTokens);
|
||||
});
|
||||
@ -91,8 +91,8 @@ export class ProviderElementContext {
|
||||
}
|
||||
|
||||
get transformedDirectiveAsts(): DirectiveAst[] {
|
||||
var sortedProviderTypes = this.transformProviders.map(provider => provider.token.identifier);
|
||||
var sortedDirectives = this._directiveAsts.slice();
|
||||
const sortedProviderTypes = this.transformProviders.map(provider => provider.token.identifier);
|
||||
const sortedDirectives = this._directiveAsts.slice();
|
||||
sortedDirectives.sort(
|
||||
(dir1, dir2) => sortedProviderTypes.indexOf(dir1.directive.type) -
|
||||
sortedProviderTypes.indexOf(dir2.directive.type));
|
||||
@ -111,10 +111,10 @@ export class ProviderElementContext {
|
||||
}
|
||||
|
||||
private _getQueriesFor(token: CompileTokenMetadata): CompileQueryMetadata[] {
|
||||
var result: CompileQueryMetadata[] = [];
|
||||
var currentEl: ProviderElementContext = this;
|
||||
var distance = 0;
|
||||
var queries: CompileQueryMetadata[];
|
||||
const result: CompileQueryMetadata[] = [];
|
||||
let currentEl: ProviderElementContext = this;
|
||||
let distance = 0;
|
||||
let queries: CompileQueryMetadata[];
|
||||
while (currentEl !== null) {
|
||||
queries = currentEl._contentQueries.get(token.reference);
|
||||
if (isPresent(queries)) {
|
||||
@ -136,7 +136,7 @@ export class ProviderElementContext {
|
||||
private _getOrCreateLocalProvider(
|
||||
requestingProviderType: ProviderAstType, token: CompileTokenMetadata,
|
||||
eager: boolean): ProviderAst {
|
||||
var resolvedProvider = this._allProviders.get(token.reference);
|
||||
const resolvedProvider = this._allProviders.get(token.reference);
|
||||
if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||
|
||||
requestingProviderType === ProviderAstType.PublicService) &&
|
||||
resolvedProvider.providerType === ProviderAstType.PrivateService) ||
|
||||
@ -145,7 +145,7 @@ export class ProviderElementContext {
|
||||
resolvedProvider.providerType === ProviderAstType.Builtin)) {
|
||||
return null;
|
||||
}
|
||||
var transformedProviderAst = this._transformedProviders.get(token.reference);
|
||||
let transformedProviderAst = this._transformedProviders.get(token.reference);
|
||||
if (isPresent(transformedProviderAst)) {
|
||||
return transformedProviderAst;
|
||||
}
|
||||
@ -155,12 +155,12 @@ export class ProviderElementContext {
|
||||
return null;
|
||||
}
|
||||
this._seenProviders.set(token.reference, true);
|
||||
var transformedProviders = resolvedProvider.providers.map((provider) => {
|
||||
var transformedUseValue = provider.useValue;
|
||||
var transformedUseExisting = provider.useExisting;
|
||||
var transformedDeps: CompileDiDependencyMetadata[];
|
||||
const transformedProviders = resolvedProvider.providers.map((provider) => {
|
||||
let transformedUseValue = provider.useValue;
|
||||
let transformedUseExisting = provider.useExisting;
|
||||
let transformedDeps: CompileDiDependencyMetadata[];
|
||||
if (isPresent(provider.useExisting)) {
|
||||
var existingDiDep = this._getDependency(
|
||||
const existingDiDep = this._getDependency(
|
||||
resolvedProvider.providerType,
|
||||
new CompileDiDependencyMetadata({token: provider.useExisting}), eager);
|
||||
if (isPresent(existingDiDep.token)) {
|
||||
@ -170,11 +170,11 @@ export class ProviderElementContext {
|
||||
transformedUseValue = existingDiDep.value;
|
||||
}
|
||||
} else if (isPresent(provider.useFactory)) {
|
||||
var deps = provider.deps || provider.useFactory.diDeps;
|
||||
const deps = provider.deps || provider.useFactory.diDeps;
|
||||
transformedDeps =
|
||||
deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep, eager));
|
||||
} else if (isPresent(provider.useClass)) {
|
||||
var deps = provider.deps || provider.useClass.diDeps;
|
||||
const deps = provider.deps || provider.useClass.diDeps;
|
||||
transformedDeps =
|
||||
deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep, eager));
|
||||
}
|
||||
@ -194,7 +194,7 @@ export class ProviderElementContext {
|
||||
requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata,
|
||||
eager: boolean = null): CompileDiDependencyMetadata {
|
||||
if (dep.isAttribute) {
|
||||
var attrValue = this._attrs[dep.token.value];
|
||||
const attrValue = this._attrs[dep.token.value];
|
||||
return new CompileDiDependencyMetadata(
|
||||
{isValue: true, value: attrValue == null ? null : attrValue});
|
||||
}
|
||||
@ -230,9 +230,9 @@ export class ProviderElementContext {
|
||||
private _getDependency(
|
||||
requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata,
|
||||
eager: boolean = null): CompileDiDependencyMetadata {
|
||||
var currElement: ProviderElementContext = this;
|
||||
var currEager: boolean = eager;
|
||||
var result: CompileDiDependencyMetadata = null;
|
||||
let currElement: ProviderElementContext = this;
|
||||
let currEager: boolean = eager;
|
||||
let result: CompileDiDependencyMetadata = null;
|
||||
if (!dep.isSkipSelf) {
|
||||
result = this._getLocalDependency(requestingProviderType, dep, eager);
|
||||
}
|
||||
@ -243,7 +243,7 @@ export class ProviderElementContext {
|
||||
} else {
|
||||
// check parent elements
|
||||
while (!result && isPresent(currElement._parent)) {
|
||||
var prevElement = currElement;
|
||||
const prevElement = currElement;
|
||||
currElement = currElement._parent;
|
||||
if (prevElement._isViewRoot) {
|
||||
currEager = false;
|
||||
@ -308,11 +308,11 @@ export class NgModuleProviderAnalyzer {
|
||||
}
|
||||
|
||||
private _getOrCreateLocalProvider(token: CompileTokenMetadata, eager: boolean): ProviderAst {
|
||||
var resolvedProvider = this._allProviders.get(token.reference);
|
||||
const resolvedProvider = this._allProviders.get(token.reference);
|
||||
if (!resolvedProvider) {
|
||||
return null;
|
||||
}
|
||||
var transformedProviderAst = this._transformedProviders.get(token.reference);
|
||||
let transformedProviderAst = this._transformedProviders.get(token.reference);
|
||||
if (isPresent(transformedProviderAst)) {
|
||||
return transformedProviderAst;
|
||||
}
|
||||
@ -322,12 +322,12 @@ export class NgModuleProviderAnalyzer {
|
||||
return null;
|
||||
}
|
||||
this._seenProviders.set(token.reference, true);
|
||||
var transformedProviders = resolvedProvider.providers.map((provider) => {
|
||||
var transformedUseValue = provider.useValue;
|
||||
var transformedUseExisting = provider.useExisting;
|
||||
var transformedDeps: CompileDiDependencyMetadata[];
|
||||
const transformedProviders = resolvedProvider.providers.map((provider) => {
|
||||
let transformedUseValue = provider.useValue;
|
||||
let transformedUseExisting = provider.useExisting;
|
||||
let transformedDeps: CompileDiDependencyMetadata[];
|
||||
if (isPresent(provider.useExisting)) {
|
||||
var existingDiDep = this._getDependency(
|
||||
const existingDiDep = this._getDependency(
|
||||
new CompileDiDependencyMetadata({token: provider.useExisting}), eager,
|
||||
resolvedProvider.sourceSpan);
|
||||
if (isPresent(existingDiDep.token)) {
|
||||
@ -337,11 +337,11 @@ export class NgModuleProviderAnalyzer {
|
||||
transformedUseValue = existingDiDep.value;
|
||||
}
|
||||
} else if (isPresent(provider.useFactory)) {
|
||||
var deps = provider.deps || provider.useFactory.diDeps;
|
||||
const deps = provider.deps || provider.useFactory.diDeps;
|
||||
transformedDeps =
|
||||
deps.map((dep) => this._getDependency(dep, eager, resolvedProvider.sourceSpan));
|
||||
} else if (isPresent(provider.useClass)) {
|
||||
var deps = provider.deps || provider.useClass.diDeps;
|
||||
const deps = provider.deps || provider.useClass.diDeps;
|
||||
transformedDeps =
|
||||
deps.map((dep) => this._getDependency(dep, eager, resolvedProvider.sourceSpan));
|
||||
}
|
||||
@ -360,7 +360,7 @@ export class NgModuleProviderAnalyzer {
|
||||
private _getDependency(
|
||||
dep: CompileDiDependencyMetadata, eager: boolean = null,
|
||||
requestorSourceSpan: ParseSourceSpan): CompileDiDependencyMetadata {
|
||||
var foundLocal = false;
|
||||
let foundLocal = false;
|
||||
if (!dep.isSkipSelf && isPresent(dep.token)) {
|
||||
// access the injector
|
||||
if (dep.token.reference === resolveIdentifierToken(Identifiers.Injector).reference ||
|
||||
@ -372,7 +372,7 @@ export class NgModuleProviderAnalyzer {
|
||||
foundLocal = true;
|
||||
}
|
||||
}
|
||||
var result: CompileDiDependencyMetadata = dep;
|
||||
let result: CompileDiDependencyMetadata = dep;
|
||||
if (dep.isSelf && !foundLocal) {
|
||||
if (dep.isOptional) {
|
||||
result = new CompileDiDependencyMetadata({isValue: true, value: null});
|
||||
@ -442,9 +442,9 @@ function _normalizeProviders(
|
||||
function _resolveProvidersFromDirectives(
|
||||
directives: CompileDirectiveSummary[], sourceSpan: ParseSourceSpan,
|
||||
targetErrors: ParseError[]): Map<any, ProviderAst> {
|
||||
var providersByToken = new Map<any, ProviderAst>();
|
||||
const providersByToken = new Map<any, ProviderAst>();
|
||||
directives.forEach((directive) => {
|
||||
var dirProvider = new CompileProviderMetadata(
|
||||
const dirProvider = new CompileProviderMetadata(
|
||||
{token: new CompileTokenMetadata({identifier: directive.type}), useClass: directive.type});
|
||||
_resolveProviders(
|
||||
[dirProvider],
|
||||
@ -453,7 +453,7 @@ function _resolveProvidersFromDirectives(
|
||||
});
|
||||
|
||||
// Note: directives need to be able to overwrite providers of a component!
|
||||
var directivesWithComponentFirst =
|
||||
const directivesWithComponentFirst =
|
||||
directives.filter(dir => dir.isComponent).concat(directives.filter(dir => !dir.isComponent));
|
||||
directivesWithComponentFirst.forEach((directive) => {
|
||||
_resolveProviders(
|
||||
@ -471,7 +471,7 @@ function _resolveProviders(
|
||||
sourceSpan: ParseSourceSpan, targetErrors: ParseError[],
|
||||
targetProvidersByToken: Map<any, ProviderAst>) {
|
||||
providers.forEach((provider) => {
|
||||
var resolvedProvider = targetProvidersByToken.get(provider.token.reference);
|
||||
let resolvedProvider = targetProvidersByToken.get(provider.token.reference);
|
||||
if (isPresent(resolvedProvider) && resolvedProvider.multiProvider !== provider.multi) {
|
||||
targetErrors.push(new ProviderError(
|
||||
`Mixing multi and non multi provider is not possible for token ${resolvedProvider.token.name}`,
|
||||
@ -497,7 +497,7 @@ function _resolveProviders(
|
||||
|
||||
|
||||
function _getViewQueries(component: CompileDirectiveMetadata): Map<any, CompileQueryMetadata[]> {
|
||||
var viewQueries = new Map<any, CompileQueryMetadata[]>();
|
||||
const viewQueries = new Map<any, CompileQueryMetadata[]>();
|
||||
if (isPresent(component.viewQueries)) {
|
||||
component.viewQueries.forEach((query) => _addQueryToTokenMap(viewQueries, query));
|
||||
}
|
||||
@ -506,7 +506,7 @@ function _getViewQueries(component: CompileDirectiveMetadata): Map<any, CompileQ
|
||||
|
||||
function _getContentQueries(directives: CompileDirectiveSummary[]):
|
||||
Map<any, CompileQueryMetadata[]> {
|
||||
var contentQueries = new Map<any, CompileQueryMetadata[]>();
|
||||
const contentQueries = new Map<any, CompileQueryMetadata[]>();
|
||||
directives.forEach(directive => {
|
||||
if (isPresent(directive.queries)) {
|
||||
directive.queries.forEach((query) => _addQueryToTokenMap(contentQueries, query));
|
||||
@ -517,7 +517,7 @@ function _getContentQueries(directives: CompileDirectiveSummary[]):
|
||||
|
||||
function _addQueryToTokenMap(map: Map<any, CompileQueryMetadata[]>, query: CompileQueryMetadata) {
|
||||
query.selectors.forEach((token: CompileTokenMetadata) => {
|
||||
var entry = map.get(token.reference);
|
||||
let entry = map.get(token.reference);
|
||||
if (!entry) {
|
||||
entry = [];
|
||||
map.set(token.reference, entry);
|
||||
|
@ -100,7 +100,7 @@ export class RuntimeCompiler implements Compiler {
|
||||
}
|
||||
|
||||
private _loadModules(mainModule: any, isSync: boolean): Promise<any> {
|
||||
var loadingPromises: Promise<any>[] = [];
|
||||
const loadingPromises: Promise<any>[] = [];
|
||||
const {ngModule, loading} = this._metadataResolver.loadNgModuleMetadata(mainModule, isSync);
|
||||
loadingPromises.push(loading);
|
||||
// Note: the loadingPromise for a module only includes the loading of the exported directives
|
||||
@ -122,7 +122,7 @@ export class RuntimeCompiler implements Compiler {
|
||||
// Always provide a bound Compiler
|
||||
const extraProviders = [this._metadataResolver.getProviderMetadata(new ProviderMeta(
|
||||
Compiler, {useFactory: () => new ModuleBoundCompiler(this, moduleMeta.type.reference)}))];
|
||||
var compileResult = this._ngModuleCompiler.compile(moduleMeta, extraProviders);
|
||||
const compileResult = this._ngModuleCompiler.compile(moduleMeta, extraProviders);
|
||||
compileResult.dependencies.forEach((dep) => {
|
||||
dep.placeholder.reference =
|
||||
this._assertComponentKnown(dep.comp.reference, true).proxyComponentFactory;
|
||||
@ -192,7 +192,7 @@ export class RuntimeCompiler implements Compiler {
|
||||
this._compiledNgModuleCache.delete(type);
|
||||
this._metadataResolver.clearCacheFor(type);
|
||||
this._compiledHostTemplateCache.delete(type);
|
||||
var compiledTemplate = this._compiledTemplateCache.get(type);
|
||||
const compiledTemplate = this._compiledTemplateCache.get(type);
|
||||
if (compiledTemplate) {
|
||||
this._compiledTemplateCache.delete(type);
|
||||
}
|
||||
@ -211,11 +211,11 @@ export class RuntimeCompiler implements Compiler {
|
||||
throw new Error(
|
||||
`Component ${stringify(compType)} is not part of any NgModule or the module has not been imported into your module.`);
|
||||
}
|
||||
var compiledTemplate = this._compiledHostTemplateCache.get(compType);
|
||||
let compiledTemplate = this._compiledHostTemplateCache.get(compType);
|
||||
if (!compiledTemplate) {
|
||||
var compMeta = this._metadataResolver.getDirectiveMetadata(compType);
|
||||
const compMeta = this._metadataResolver.getDirectiveMetadata(compType);
|
||||
assertComponent(compMeta);
|
||||
var hostMeta = createHostComponentMeta(compMeta);
|
||||
const hostMeta = createHostComponentMeta(compMeta);
|
||||
compiledTemplate = new CompiledTemplate(
|
||||
true, compMeta.selector, compMeta.type, hostMeta, ngModule, [compMeta.type]);
|
||||
this._compiledHostTemplateCache.set(compType, compiledTemplate);
|
||||
@ -225,7 +225,7 @@ export class RuntimeCompiler implements Compiler {
|
||||
|
||||
private _createCompiledTemplate(
|
||||
compMeta: CompileDirectiveMetadata, ngModule: CompileNgModuleMetadata): CompiledTemplate {
|
||||
var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
|
||||
let compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
|
||||
if (!compiledTemplate) {
|
||||
assertComponent(compMeta);
|
||||
compiledTemplate = new CompiledTemplate(
|
||||
@ -297,17 +297,17 @@ export class RuntimeCompiler implements Compiler {
|
||||
compileResult.dependencies.forEach((dep) => {
|
||||
let depTemplate: CompiledTemplate;
|
||||
if (dep instanceof ViewClassDependency) {
|
||||
let vfd = <ViewClassDependency>dep;
|
||||
const vfd = <ViewClassDependency>dep;
|
||||
depTemplate = this._assertComponentKnown(vfd.comp.reference, false);
|
||||
vfd.placeholder.reference = depTemplate.proxyViewClass;
|
||||
vfd.placeholder.name = `View_${vfd.comp.name}`;
|
||||
} else if (dep instanceof ComponentFactoryDependency) {
|
||||
let cfd = <ComponentFactoryDependency>dep;
|
||||
const cfd = <ComponentFactoryDependency>dep;
|
||||
depTemplate = this._assertComponentKnown(cfd.comp.reference, true);
|
||||
cfd.placeholder.reference = depTemplate.proxyComponentFactory;
|
||||
cfd.placeholder.name = `compFactory_${cfd.comp.name}`;
|
||||
} else if (dep instanceof DirectiveWrapperDependency) {
|
||||
let dwd = <DirectiveWrapperDependency>dep;
|
||||
const dwd = <DirectiveWrapperDependency>dep;
|
||||
dwd.placeholder.reference = this._assertDirectiveWrapper(dwd.dir.reference);
|
||||
}
|
||||
});
|
||||
@ -328,8 +328,8 @@ export class RuntimeCompiler implements Compiler {
|
||||
private _resolveStylesCompileResult(
|
||||
result: CompiledStylesheet, externalStylesheetsByModuleUrl: Map<string, CompiledStylesheet>) {
|
||||
result.dependencies.forEach((dep, i) => {
|
||||
var nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
|
||||
var nestedStylesArr = this._resolveAndEvalStylesCompileResult(
|
||||
const nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
|
||||
const nestedStylesArr = this._resolveAndEvalStylesCompileResult(
|
||||
nestedCompileResult, externalStylesheetsByModuleUrl);
|
||||
dep.valuePlaceholder.reference = nestedStylesArr;
|
||||
dep.valuePlaceholder.name = `importedStyles${i}`;
|
||||
|
@ -245,7 +245,7 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry {
|
||||
constructor() {
|
||||
super();
|
||||
SCHEMA.forEach(encodedType => {
|
||||
let type: {[property: string]: string} = {};
|
||||
const type: {[property: string]: string} = {};
|
||||
const [strType, strProperties] = encodedType.split('|');
|
||||
const properties = strProperties.split(',');
|
||||
const [typeNames, superName] = strType.split('^');
|
||||
@ -383,15 +383,15 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry {
|
||||
|
||||
normalizeAnimationStyleValue(camelCaseProp: string, userProvidedProp: string, val: string|number):
|
||||
{error: string, value: string} {
|
||||
var unit: string = '';
|
||||
var strVal = val.toString().trim();
|
||||
var errorMsg: string = null;
|
||||
let unit: string = '';
|
||||
const strVal = val.toString().trim();
|
||||
let errorMsg: string = null;
|
||||
|
||||
if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
|
||||
if (typeof val === 'number') {
|
||||
unit = 'px';
|
||||
} else {
|
||||
let valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
|
||||
const valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
|
||||
if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
|
||||
errorMsg = `Please provide a CSS unit value for ${userProvidedProp}:${val}`;
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ import {SecurityContext} from '@angular/core';
|
||||
export const SECURITY_SCHEMA: {[k: string]: SecurityContext} = {};
|
||||
|
||||
function registerContext(ctx: SecurityContext, specs: string[]) {
|
||||
for (let spec of specs) SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
|
||||
for (const spec of specs) SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
|
||||
}
|
||||
|
||||
// Case is insignificant below, all element and attribute names are lower-cased for lookup.
|
||||
|
@ -202,7 +202,7 @@ export class SelectorMatcher {
|
||||
}
|
||||
this._addTerminal(terminalValuesMap, value, selectable);
|
||||
} else {
|
||||
let partialMap = matcher._attrValuePartialMap;
|
||||
const partialMap = matcher._attrValuePartialMap;
|
||||
let partialValuesMap = partialMap.get(name);
|
||||
if (!partialValuesMap) {
|
||||
partialValuesMap = new Map<string, SelectorMatcher>();
|
||||
|
@ -287,7 +287,7 @@ export class ShadowCss {
|
||||
const parts = m[2].split(',');
|
||||
const r: string[] = [];
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
let p = parts[i].trim();
|
||||
const p = parts[i].trim();
|
||||
if (!p) break;
|
||||
r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
|
||||
}
|
||||
|
@ -29,8 +29,8 @@ export function isStyleUrlResolvable(url: string): boolean {
|
||||
*/
|
||||
export function extractStyleUrls(
|
||||
resolver: UrlResolver, baseUrl: string, cssText: string): StyleWithImports {
|
||||
var foundUrls: string[] = [];
|
||||
var modifiedCssText = cssText.replace(_cssImportRe, function(...m: string[]) {
|
||||
const foundUrls: string[] = [];
|
||||
const modifiedCssText = cssText.replace(_cssImportRe, function(...m: string[]) {
|
||||
const url = m[1] || m[2];
|
||||
if (!isStyleUrlResolvable(url)) {
|
||||
// Do not attempt to resolve non-package absolute URLs with URI scheme
|
||||
@ -42,5 +42,5 @@ export function extractStyleUrls(
|
||||
return new StyleWithImports(modifiedCssText, foundUrls);
|
||||
}
|
||||
|
||||
var _cssImportRe = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
|
||||
var _urlWithSchemaRe = /^([^:/?#]+):/;
|
||||
const _cssImportRe = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
|
||||
const _urlWithSchemaRe = /^([^:/?#]+):/;
|
||||
|
@ -251,7 +251,7 @@ export class BindingParser {
|
||||
let securityContexts: SecurityContext[];
|
||||
|
||||
if (parts.length === 1) {
|
||||
var partValue = parts[0];
|
||||
const partValue = parts[0];
|
||||
boundPropertyName = this._schemaRegistry.getMappedPropName(partValue);
|
||||
securityContexts = calcPossibleSecurityContexts(
|
||||
this._schemaRegistry, elementSelector, boundPropertyName, false);
|
||||
|
@ -122,8 +122,8 @@ export class TemplateParser {
|
||||
htmlAstWithErrors: ParseTreeResult, component: CompileDirectiveMetadata, template: string,
|
||||
directives: CompileDirectiveSummary[], pipes: CompilePipeSummary[], schemas: SchemaMetadata[],
|
||||
templateUrl: string): TemplateParseResult {
|
||||
var result: TemplateAst[];
|
||||
var errors = htmlAstWithErrors.errors;
|
||||
let result: TemplateAst[];
|
||||
const errors = htmlAstWithErrors.errors;
|
||||
if (htmlAstWithErrors.rootNodes.length > 0) {
|
||||
const uniqDirectives = removeSummaryDuplicates(directives);
|
||||
const uniqPipes = removeSummaryDuplicates(pipes);
|
||||
@ -819,9 +819,9 @@ function createElementCssSelector(elementName: string, matchableAttrs: string[][
|
||||
cssSelector.setElement(elNameNoNs);
|
||||
|
||||
for (let i = 0; i < matchableAttrs.length; i++) {
|
||||
let attrName = matchableAttrs[i][0];
|
||||
let attrNameNoNs = splitNsName(attrName)[1];
|
||||
let attrValue = matchableAttrs[i][1];
|
||||
const attrName = matchableAttrs[i][0];
|
||||
const attrNameNoNs = splitNsName(attrName)[1];
|
||||
const attrValue = matchableAttrs[i][1];
|
||||
|
||||
cssSelector.addAttribute(attrNameNoNs, attrValue);
|
||||
if (attrName.toLowerCase() == CLASS_ATTR) {
|
||||
|
@ -21,13 +21,13 @@ const NG_NON_BINDABLE_ATTR = 'ngNonBindable';
|
||||
const NG_PROJECT_AS = 'ngProjectAs';
|
||||
|
||||
export function preparseElement(ast: html.Element): PreparsedElement {
|
||||
var selectAttr: string = null;
|
||||
var hrefAttr: string = null;
|
||||
var relAttr: string = null;
|
||||
var nonBindable = false;
|
||||
var projectAs: string = null;
|
||||
let selectAttr: string = null;
|
||||
let hrefAttr: string = null;
|
||||
let relAttr: string = null;
|
||||
let nonBindable = false;
|
||||
let projectAs: string = null;
|
||||
ast.attrs.forEach(attr => {
|
||||
let lcAttrName = attr.name.toLowerCase();
|
||||
const lcAttrName = attr.name.toLowerCase();
|
||||
if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
|
||||
selectAttr = attr.value;
|
||||
} else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
|
||||
@ -43,8 +43,8 @@ export function preparseElement(ast: html.Element): PreparsedElement {
|
||||
}
|
||||
});
|
||||
selectAttr = normalizeNgContentSelect(selectAttr);
|
||||
var nodeName = ast.name.toLowerCase();
|
||||
var type = PreparsedElementType.OTHER;
|
||||
const nodeName = ast.name.toLowerCase();
|
||||
let type = PreparsedElementType.OTHER;
|
||||
if (splitNsName(nodeName)[1] == NG_CONTENT_ELEMENT) {
|
||||
type = PreparsedElementType.NG_CONTENT;
|
||||
} else if (nodeName == STYLE_ELEMENT) {
|
||||
|
@ -61,17 +61,17 @@ export class UrlResolver {
|
||||
* returned as is (ignoring the `baseUrl`)
|
||||
*/
|
||||
resolve(baseUrl: string, url: string): string {
|
||||
var resolvedUrl = url;
|
||||
let resolvedUrl = url;
|
||||
if (isPresent(baseUrl) && baseUrl.length > 0) {
|
||||
resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
|
||||
}
|
||||
var resolvedParts = _split(resolvedUrl);
|
||||
var prefix = this._packagePrefix;
|
||||
const resolvedParts = _split(resolvedUrl);
|
||||
let prefix = this._packagePrefix;
|
||||
if (isPresent(prefix) && isPresent(resolvedParts) &&
|
||||
resolvedParts[_ComponentIndex.Scheme] == 'package') {
|
||||
var path = resolvedParts[_ComponentIndex.Path];
|
||||
let path = resolvedParts[_ComponentIndex.Path];
|
||||
if (this._packagePrefix === _ASSET_SCHEME) {
|
||||
var pathSegements = path.split(/\//);
|
||||
const pathSegements = path.split(/\//);
|
||||
resolvedUrl = `asset:${pathSegements[0]}/lib/${pathSegements.slice(1).join('/')}`;
|
||||
} else {
|
||||
prefix = prefix.replace(/\/+$/, '');
|
||||
@ -87,7 +87,7 @@ export class UrlResolver {
|
||||
* Extract the scheme of a URL.
|
||||
*/
|
||||
export function getUrlScheme(url: string): string {
|
||||
var match = _split(url);
|
||||
const match = _split(url);
|
||||
return (match && match[_ComponentIndex.Scheme]) || '';
|
||||
}
|
||||
|
||||
@ -114,7 +114,7 @@ export function getUrlScheme(url: 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: string[] = [];
|
||||
const out: string[] = [];
|
||||
|
||||
if (isPresent(opt_scheme)) {
|
||||
out.push(opt_scheme + ':');
|
||||
@ -211,7 +211,7 @@ function _buildFromEncodedParts(
|
||||
* @type {!RegExp}
|
||||
* @internal
|
||||
*/
|
||||
var _splitRe = new RegExp(
|
||||
const _splitRe = new RegExp(
|
||||
'^' +
|
||||
'(?:' +
|
||||
'([^:/?#.]+)' + // scheme - ignore special characters
|
||||
@ -273,14 +273,14 @@ function _split(uri: string): Array<string|any> {
|
||||
function _removeDotSegments(path: string): string {
|
||||
if (path == '/') return '/';
|
||||
|
||||
var leadingSlash = path[0] == '/' ? '/' : '';
|
||||
var trailingSlash = path[path.length - 1] === '/' ? '/' : '';
|
||||
var segments = path.split('/');
|
||||
const leadingSlash = path[0] == '/' ? '/' : '';
|
||||
const trailingSlash = path[path.length - 1] === '/' ? '/' : '';
|
||||
const segments = path.split('/');
|
||||
|
||||
var out: string[] = [];
|
||||
var up = 0;
|
||||
for (var pos = 0; pos < segments.length; pos++) {
|
||||
var segment = segments[pos];
|
||||
const out: string[] = [];
|
||||
let up = 0;
|
||||
for (let pos = 0; pos < segments.length; pos++) {
|
||||
const segment = segments[pos];
|
||||
switch (segment) {
|
||||
case '':
|
||||
case '.':
|
||||
@ -313,7 +313,7 @@ function _removeDotSegments(path: string): string {
|
||||
* and then joins all the parts.
|
||||
*/
|
||||
function _joinAndCanonicalizePath(parts: any[]): string {
|
||||
var path = parts[_ComponentIndex.Path];
|
||||
let path = parts[_ComponentIndex.Path];
|
||||
path = isBlank(path) ? '' : _removeDotSegments(path);
|
||||
parts[_ComponentIndex.Path] = path;
|
||||
|
||||
@ -329,8 +329,8 @@ function _joinAndCanonicalizePath(parts: any[]): string {
|
||||
* @param to The URL to resolve.
|
||||
*/
|
||||
function _resolveUrl(base: string, url: string): string {
|
||||
var parts = _split(encodeURI(url));
|
||||
var baseParts = _split(base);
|
||||
const parts = _split(encodeURI(url));
|
||||
const baseParts = _split(base);
|
||||
|
||||
if (isPresent(parts[_ComponentIndex.Scheme])) {
|
||||
return _joinAndCanonicalizePath(parts);
|
||||
@ -338,7 +338,7 @@ function _resolveUrl(base: string, url: string): string {
|
||||
parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
|
||||
}
|
||||
|
||||
for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
|
||||
for (let i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
|
||||
if (isBlank(parts[i])) {
|
||||
parts[i] = baseParts[i];
|
||||
}
|
||||
@ -348,9 +348,9 @@ function _resolveUrl(base: string, url: string): string {
|
||||
return _joinAndCanonicalizePath(parts);
|
||||
}
|
||||
|
||||
var path = baseParts[_ComponentIndex.Path];
|
||||
let path = baseParts[_ComponentIndex.Path];
|
||||
if (isBlank(path)) path = '/';
|
||||
var index = path.lastIndexOf('/');
|
||||
const index = path.lastIndexOf('/');
|
||||
path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
|
||||
parts[_ComponentIndex.Path] = path;
|
||||
return _joinAndCanonicalizePath(parts);
|
||||
|
@ -67,7 +67,7 @@ export class ValueTransformer implements ValueVisitor {
|
||||
return arr.map(value => visitValue(value, this, context));
|
||||
}
|
||||
visitStringMap(map: {[key: string]: any}, context: any): any {
|
||||
var result: {[key: string]: any} = {};
|
||||
const result: {[key: string]: any} = {};
|
||||
Object.keys(map).forEach(key => { result[key] = visitValue(map[key], this, context); });
|
||||
return result;
|
||||
}
|
||||
|
@ -81,13 +81,13 @@ export class CompileElement extends CompileNode {
|
||||
}
|
||||
|
||||
private _createViewContainer() {
|
||||
var fieldName = `_vc_${this.nodeIndex}`;
|
||||
var parentNodeIndex = this.isRootElement() ? null : this.parent.nodeIndex;
|
||||
const fieldName = `_vc_${this.nodeIndex}`;
|
||||
const parentNodeIndex = this.isRootElement() ? null : this.parent.nodeIndex;
|
||||
// private is fine here as no child view will reference a ViewContainer
|
||||
this.view.fields.push(new o.ClassField(
|
||||
fieldName, o.importType(resolveIdentifier(Identifiers.ViewContainer)),
|
||||
[o.StmtModifier.Private]));
|
||||
var statement =
|
||||
const statement =
|
||||
o.THIS_EXPR.prop(fieldName)
|
||||
.set(o.importExpr(resolveIdentifier(Identifiers.ViewContainer)).instantiate([
|
||||
o.literal(this.nodeIndex), o.literal(parentNodeIndex), o.THIS_EXPR, this.renderNode
|
||||
@ -101,22 +101,22 @@ export class CompileElement extends CompileNode {
|
||||
}
|
||||
|
||||
private _createComponentFactoryResolver() {
|
||||
let entryComponents =
|
||||
const entryComponents =
|
||||
this.component.entryComponents.map((entryComponent: CompileIdentifierMetadata) => {
|
||||
var id = new CompileIdentifierMetadata({name: entryComponent.name});
|
||||
const id = new CompileIdentifierMetadata({name: entryComponent.name});
|
||||
this._targetDependencies.push(new ComponentFactoryDependency(entryComponent, id));
|
||||
return id;
|
||||
});
|
||||
if (!entryComponents || entryComponents.length === 0) {
|
||||
return;
|
||||
}
|
||||
var createComponentFactoryResolverExpr =
|
||||
const createComponentFactoryResolverExpr =
|
||||
o.importExpr(resolveIdentifier(Identifiers.CodegenComponentFactoryResolver)).instantiate([
|
||||
o.literalArr(entryComponents.map((entryComponent) => o.importExpr(entryComponent))),
|
||||
injectFromViewParentInjector(
|
||||
this.view, resolveIdentifierToken(Identifiers.ComponentFactoryResolver), false)
|
||||
]);
|
||||
var provider = new CompileProviderMetadata({
|
||||
const provider = new CompileProviderMetadata({
|
||||
token: resolveIdentifierToken(Identifiers.ComponentFactoryResolver),
|
||||
useValue: createComponentFactoryResolverExpr
|
||||
});
|
||||
@ -132,7 +132,7 @@ export class CompileElement extends CompileNode {
|
||||
this.compViewExpr = compViewExpr;
|
||||
this.contentNodesByNgContentIndex =
|
||||
new Array(this.component.template.ngContentSelectors.length);
|
||||
for (var i = 0; i < this.contentNodesByNgContentIndex.length; i++) {
|
||||
for (let i = 0; i < this.contentNodesByNgContentIndex.length; i++) {
|
||||
this.contentNodesByNgContentIndex[i] = [];
|
||||
}
|
||||
}
|
||||
@ -140,11 +140,11 @@ export class CompileElement extends CompileNode {
|
||||
setEmbeddedView(embeddedView: CompileView) {
|
||||
this.embeddedView = embeddedView;
|
||||
if (isPresent(embeddedView)) {
|
||||
var createTemplateRefExpr =
|
||||
const createTemplateRefExpr =
|
||||
o.importExpr(resolveIdentifier(Identifiers.TemplateRef_)).instantiate([
|
||||
o.THIS_EXPR, o.literal(this.nodeIndex), this.renderNode
|
||||
]);
|
||||
var provider = new CompileProviderMetadata({
|
||||
const provider = new CompileProviderMetadata({
|
||||
token: resolveIdentifierToken(Identifiers.TemplateRef),
|
||||
useValue: createTemplateRefExpr
|
||||
});
|
||||
@ -199,8 +199,8 @@ export class CompileElement extends CompileNode {
|
||||
return convertValueToOutputAst(provider.useValue);
|
||||
}
|
||||
});
|
||||
var propName = `_${resolvedProvider.token.name}_${this.nodeIndex}_${this.instances.size}`;
|
||||
var instance = createProviderProperty(
|
||||
const propName = `_${resolvedProvider.token.name}_${this.nodeIndex}_${this.instances.size}`;
|
||||
const instance = createProviderProperty(
|
||||
propName, resolvedProvider, providerValueExpressions, resolvedProvider.multiProvider,
|
||||
resolvedProvider.eager, this);
|
||||
if (isDirectiveWrapper) {
|
||||
@ -212,38 +212,38 @@ export class CompileElement extends CompileNode {
|
||||
}
|
||||
});
|
||||
|
||||
for (var i = 0; i < this._directives.length; i++) {
|
||||
var directive = this._directives[i];
|
||||
var directiveInstance = this.instances.get(identifierToken(directive.type).reference);
|
||||
for (let i = 0; i < this._directives.length; i++) {
|
||||
const directive = this._directives[i];
|
||||
const directiveInstance = this.instances.get(identifierToken(directive.type).reference);
|
||||
directive.queries.forEach((queryMeta) => { this._addQuery(queryMeta, directiveInstance); });
|
||||
}
|
||||
var queriesWithReads: _QueryWithRead[] = [];
|
||||
const queriesWithReads: _QueryWithRead[] = [];
|
||||
Array.from(this._resolvedProviders.values()).forEach((resolvedProvider) => {
|
||||
var queriesForProvider = this._getQueriesFor(resolvedProvider.token);
|
||||
const queriesForProvider = this._getQueriesFor(resolvedProvider.token);
|
||||
queriesWithReads.push(
|
||||
...queriesForProvider.map(query => new _QueryWithRead(query, resolvedProvider.token)));
|
||||
});
|
||||
Object.keys(this.referenceTokens).forEach(varName => {
|
||||
var token = this.referenceTokens[varName];
|
||||
var varValue: o.Expression;
|
||||
const token = this.referenceTokens[varName];
|
||||
let varValue: o.Expression;
|
||||
if (token) {
|
||||
varValue = this.instances.get(token.reference);
|
||||
} else {
|
||||
varValue = this.renderNode;
|
||||
}
|
||||
this.view.locals.set(varName, varValue);
|
||||
var varToken = new CompileTokenMetadata({value: varName});
|
||||
const varToken = new CompileTokenMetadata({value: varName});
|
||||
queriesWithReads.push(
|
||||
...this._getQueriesFor(varToken).map(query => new _QueryWithRead(query, varToken)));
|
||||
});
|
||||
queriesWithReads.forEach((queryWithRead) => {
|
||||
var value: o.Expression;
|
||||
let value: o.Expression;
|
||||
if (isPresent(queryWithRead.read.identifier)) {
|
||||
// query for an identifier
|
||||
value = this.instances.get(queryWithRead.read.reference);
|
||||
} else {
|
||||
// query for a reference
|
||||
var token = this.referenceTokens[queryWithRead.read.value];
|
||||
const token = this.referenceTokens[queryWithRead.read.value];
|
||||
if (isPresent(token)) {
|
||||
value = this.instances.get(token.reference);
|
||||
} else {
|
||||
@ -261,12 +261,12 @@ export class CompileElement extends CompileNode {
|
||||
// Note: afterChildren is called after recursing into children.
|
||||
// This is good so that an injector match in an element that is closer to a requesting element
|
||||
// matches first.
|
||||
var providerExpr = this.instances.get(resolvedProvider.token.reference);
|
||||
const providerExpr = this.instances.get(resolvedProvider.token.reference);
|
||||
// Note: view providers are only visible on the injector of that element.
|
||||
// This is not fully correct as the rules during codegen don't allow a directive
|
||||
// to get hold of a view provdier on the same element. We still do this semantic
|
||||
// as it simplifies our model to having only one runtime injector per element.
|
||||
var providerChildNodeCount =
|
||||
const providerChildNodeCount =
|
||||
resolvedProvider.providerType === ProviderAstType.PrivateService ? 0 : childNodeCount;
|
||||
this.view.injectorGetMethod.addStmt(createInjectInternalCondition(
|
||||
this.nodeIndex, providerChildNodeCount, resolvedProvider, providerExpr));
|
||||
@ -295,10 +295,10 @@ export class CompileElement extends CompileNode {
|
||||
}
|
||||
|
||||
private _getQueriesFor(token: CompileTokenMetadata): CompileQuery[] {
|
||||
var result: CompileQuery[] = [];
|
||||
var currentEl: CompileElement = this;
|
||||
var distance = 0;
|
||||
var queries: CompileQuery[];
|
||||
const result: CompileQuery[] = [];
|
||||
let currentEl: CompileElement = this;
|
||||
let distance = 0;
|
||||
let queries: CompileQuery[];
|
||||
while (!currentEl.isNull()) {
|
||||
queries = currentEl._queries.get(token.reference);
|
||||
if (isPresent(queries)) {
|
||||
@ -318,16 +318,17 @@ export class CompileElement extends CompileNode {
|
||||
|
||||
private _addQuery(queryMeta: CompileQueryMetadata, directiveInstance: o.Expression):
|
||||
CompileQuery {
|
||||
var propName = `_query_${queryMeta.selectors[0].name}_${this.nodeIndex}_${this._queryCount++}`;
|
||||
var queryList = createQueryList(queryMeta, directiveInstance, propName, this.view);
|
||||
var query = new CompileQuery(queryMeta, queryList, directiveInstance, this.view);
|
||||
const propName =
|
||||
`_query_${queryMeta.selectors[0].name}_${this.nodeIndex}_${this._queryCount++}`;
|
||||
const queryList = createQueryList(queryMeta, directiveInstance, propName, this.view);
|
||||
const query = new CompileQuery(queryMeta, queryList, directiveInstance, this.view);
|
||||
addQueryToTokenMap(this._queries, query);
|
||||
return query;
|
||||
}
|
||||
|
||||
private _getLocalDependency(
|
||||
requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata): o.Expression {
|
||||
var result: o.Expression = null;
|
||||
let result: o.Expression = null;
|
||||
if (isPresent(dep.token)) {
|
||||
// access builtins with special visibility
|
||||
if (!result) {
|
||||
@ -342,7 +343,7 @@ export class CompileElement extends CompileNode {
|
||||
}
|
||||
// access regular providers on the element
|
||||
if (!result) {
|
||||
let resolvedProvider = this._resolvedProviders.get(dep.token.reference);
|
||||
const resolvedProvider = this._resolvedProviders.get(dep.token.reference);
|
||||
// don't allow directives / public services to access private services.
|
||||
// only components and private services can access private services.
|
||||
if (resolvedProvider && (requestingProviderType === ProviderAstType.Directive ||
|
||||
@ -358,8 +359,8 @@ export class CompileElement extends CompileNode {
|
||||
|
||||
private _getDependency(requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata):
|
||||
o.Expression {
|
||||
var currElement: CompileElement = this;
|
||||
var result: o.Expression = null;
|
||||
let currElement: CompileElement = this;
|
||||
let result: o.Expression = null;
|
||||
if (dep.isValue) {
|
||||
result = o.literal(dep.value);
|
||||
}
|
||||
@ -386,7 +387,7 @@ export class CompileElement extends CompileNode {
|
||||
function createInjectInternalCondition(
|
||||
nodeIndex: number, childNodeCount: number, provider: ProviderAst,
|
||||
providerExpr: o.Expression): o.Statement {
|
||||
var indexCondition: o.Expression;
|
||||
let indexCondition: o.Expression;
|
||||
if (childNodeCount > 0) {
|
||||
indexCondition = o.literal(nodeIndex)
|
||||
.lowerEquals(InjectMethodVars.requestNodeIndex)
|
||||
@ -403,9 +404,9 @@ function createInjectInternalCondition(
|
||||
function createProviderProperty(
|
||||
propName: string, provider: ProviderAst, providerValueExpressions: o.Expression[],
|
||||
isMulti: boolean, isEager: boolean, compileElement: CompileElement): o.Expression {
|
||||
var view = compileElement.view;
|
||||
var resolvedProviderValueExpr: o.Expression;
|
||||
var type: o.Type;
|
||||
const view = compileElement.view;
|
||||
let resolvedProviderValueExpr: o.Expression;
|
||||
let type: o.Type;
|
||||
if (isMulti) {
|
||||
resolvedProviderValueExpr = o.literalArr(providerValueExpressions);
|
||||
type = new o.ArrayType(o.DYNAMIC_TYPE);
|
||||
@ -420,9 +421,9 @@ function createProviderProperty(
|
||||
view.fields.push(new o.ClassField(propName, type));
|
||||
view.createMethod.addStmt(o.THIS_EXPR.prop(propName).set(resolvedProviderValueExpr).toStmt());
|
||||
} else {
|
||||
var internalField = `_${propName}`;
|
||||
const internalField = `_${propName}`;
|
||||
view.fields.push(new o.ClassField(internalField, type));
|
||||
var getter = new CompileMethod(view);
|
||||
const getter = new CompileMethod(view);
|
||||
getter.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
|
||||
// Note: Equals is important for JS so that it also checks the undefined case!
|
||||
getter.addStmt(new o.IfStmt(
|
||||
|
@ -16,7 +16,7 @@ class _DebugState {
|
||||
constructor(public nodeIndex: number, public sourceAst: TemplateAst) {}
|
||||
}
|
||||
|
||||
var NULL_DEBUG_STATE = new _DebugState(null, null);
|
||||
const NULL_DEBUG_STATE = new _DebugState(null, null);
|
||||
|
||||
export class CompileMethod {
|
||||
private _newState: _DebugState = NULL_DEBUG_STATE;
|
||||
@ -33,7 +33,7 @@ export class CompileMethod {
|
||||
private _updateDebugContextIfNeeded() {
|
||||
if (this._newState.nodeIndex !== this._currState.nodeIndex ||
|
||||
this._newState.sourceAst !== this._currState.sourceAst) {
|
||||
var expr = this._updateDebugContext(this._newState);
|
||||
const expr = this._updateDebugContext(this._newState);
|
||||
if (isPresent(expr)) {
|
||||
this._bodyStatements.push(expr.toStmt());
|
||||
}
|
||||
@ -43,7 +43,7 @@ export class CompileMethod {
|
||||
private _updateDebugContext(newState: _DebugState): o.Expression {
|
||||
this._currState = this._newState = newState;
|
||||
if (this._debugEnabled) {
|
||||
var sourceLocation =
|
||||
const sourceLocation =
|
||||
isPresent(newState.sourceAst) ? newState.sourceAst.sourceSpan.start : null;
|
||||
|
||||
return o.THIS_EXPR.callMethod('debug', [
|
||||
@ -57,7 +57,7 @@ export class CompileMethod {
|
||||
}
|
||||
|
||||
resetDebugInfoExpr(nodeIndex: number, templateAst: TemplateAst): o.Expression {
|
||||
var res = this._updateDebugContext(new _DebugState(nodeIndex, templateAst));
|
||||
const res = this._updateDebugContext(new _DebugState(nodeIndex, templateAst));
|
||||
return res || o.NULL_EXPR;
|
||||
}
|
||||
|
||||
|
@ -17,9 +17,9 @@ import {getPropertyInView, injectFromViewParentInjector} from './util';
|
||||
|
||||
export class CompilePipe {
|
||||
static call(view: CompileView, name: string, args: o.Expression[]): o.Expression {
|
||||
var compView = view.componentView;
|
||||
var meta = _findPipeMeta(compView, name);
|
||||
var pipe: CompilePipe;
|
||||
const compView = view.componentView;
|
||||
const meta = _findPipeMeta(compView, name);
|
||||
let pipe: CompilePipe;
|
||||
if (meta.pure) {
|
||||
// pure pipes live on the component view
|
||||
pipe = compView.purePipes.get(name);
|
||||
@ -41,7 +41,7 @@ export class CompilePipe {
|
||||
|
||||
constructor(public view: CompileView, public meta: CompilePipeSummary) {
|
||||
this.instance = o.THIS_EXPR.prop(`_pipe_${meta.name}_${view.pipeCount++}`);
|
||||
var deps = this.meta.type.diDeps.map((diDep) => {
|
||||
const deps = this.meta.type.diDeps.map((diDep) => {
|
||||
if (diDep.token.reference ===
|
||||
resolveIdentifierToken(Identifiers.ChangeDetectorRef).reference) {
|
||||
return getPropertyInView(o.THIS_EXPR.prop('ref'), this.view, this.view.componentView);
|
||||
@ -60,9 +60,10 @@ export class CompilePipe {
|
||||
private _call(callingView: CompileView, args: o.Expression[]): o.Expression {
|
||||
if (this.meta.pure) {
|
||||
// PurePipeProxies live on the view that called them.
|
||||
var purePipeProxyInstance =
|
||||
const purePipeProxyInstance =
|
||||
o.THIS_EXPR.prop(`${this.instance.name}_${this._purePipeProxyCount++}`);
|
||||
var pipeInstanceSeenFromPureProxy = getPropertyInView(this.instance, callingView, this.view);
|
||||
const pipeInstanceSeenFromPureProxy =
|
||||
getPropertyInView(this.instance, callingView, this.view);
|
||||
createPureProxy(
|
||||
pipeInstanceSeenFromPureProxy.prop('transform')
|
||||
.callMethod(o.BuiltinMethod.Bind, [pipeInstanceSeenFromPureProxy]),
|
||||
@ -78,9 +79,9 @@ export class CompilePipe {
|
||||
}
|
||||
|
||||
function _findPipeMeta(view: CompileView, name: string): CompilePipeSummary {
|
||||
var pipeMeta: CompilePipeSummary = null;
|
||||
for (var i = view.pipeMetas.length - 1; i >= 0; i--) {
|
||||
var localPipeMeta = view.pipeMetas[i];
|
||||
let pipeMeta: CompilePipeSummary = null;
|
||||
for (let i = view.pipeMetas.length - 1; i >= 0; i--) {
|
||||
const localPipeMeta = view.pipeMetas[i];
|
||||
if (localPipeMeta.name == name) {
|
||||
pipeMeta = localPipeMeta;
|
||||
break;
|
||||
|
@ -31,23 +31,23 @@ export class CompileQuery {
|
||||
}
|
||||
|
||||
addValue(value: o.Expression, view: CompileView) {
|
||||
var currentView = view;
|
||||
var elPath: CompileElement[] = [];
|
||||
let currentView = view;
|
||||
const elPath: CompileElement[] = [];
|
||||
while (isPresent(currentView) && currentView !== this.view) {
|
||||
var parentEl = currentView.declarationElement;
|
||||
const parentEl = currentView.declarationElement;
|
||||
elPath.unshift(parentEl);
|
||||
currentView = parentEl.view;
|
||||
}
|
||||
var queryListForDirtyExpr = getPropertyInView(this.queryList, view, this.view);
|
||||
const queryListForDirtyExpr = getPropertyInView(this.queryList, view, this.view);
|
||||
|
||||
var viewValues = this._values;
|
||||
let viewValues = this._values;
|
||||
elPath.forEach((el) => {
|
||||
var last =
|
||||
const last =
|
||||
viewValues.values.length > 0 ? viewValues.values[viewValues.values.length - 1] : null;
|
||||
if (last instanceof ViewQueryValues && last.view === el.embeddedView) {
|
||||
viewValues = last;
|
||||
} else {
|
||||
var newViewValues = new ViewQueryValues(el.embeddedView, []);
|
||||
const newViewValues = new ViewQueryValues(el.embeddedView, []);
|
||||
viewValues.values.push(newViewValues);
|
||||
viewValues = newViewValues;
|
||||
}
|
||||
@ -65,10 +65,10 @@ export class CompileQuery {
|
||||
}
|
||||
|
||||
afterChildren(targetStaticMethod: CompileMethod, targetDynamicMethod: CompileMethod) {
|
||||
var values = createQueryValues(this._values);
|
||||
var updateStmts = [this.queryList.callMethod('reset', [o.literalArr(values)]).toStmt()];
|
||||
const values = createQueryValues(this._values);
|
||||
const updateStmts = [this.queryList.callMethod('reset', [o.literalArr(values)]).toStmt()];
|
||||
if (isPresent(this.ownerDirectiveExpression)) {
|
||||
var valueExpr = this.meta.first ? this.queryList.prop('first') : this.queryList;
|
||||
const valueExpr = this.meta.first ? this.queryList.prop('first') : this.queryList;
|
||||
updateStmts.push(
|
||||
this.ownerDirectiveExpression.prop(this.meta.propertyName).set(valueExpr).toStmt());
|
||||
}
|
||||
@ -100,7 +100,7 @@ function createQueryValues(viewValues: ViewQueryValues): o.Expression[] {
|
||||
|
||||
function mapNestedViews(
|
||||
viewContainer: o.Expression, view: CompileView, expressions: o.Expression[]): o.Expression {
|
||||
var adjustedExpressions: o.Expression[] = expressions.map(
|
||||
const adjustedExpressions: o.Expression[] = expressions.map(
|
||||
(expr) => o.replaceVarInExpression(o.THIS_EXPR.name, o.variable('nestedView'), expr));
|
||||
return viewContainer.callMethod('mapNestedViews', [
|
||||
o.variable(view.className),
|
||||
@ -115,7 +115,7 @@ export function createQueryList(
|
||||
compileView: CompileView): o.Expression {
|
||||
compileView.fields.push(new o.ClassField(
|
||||
propertyName, o.importType(resolveIdentifier(Identifiers.QueryList), [o.DYNAMIC_TYPE])));
|
||||
var expr = o.THIS_EXPR.prop(propertyName);
|
||||
const expr = o.THIS_EXPR.prop(propertyName);
|
||||
compileView.createMethod.addStmt(
|
||||
o.THIS_EXPR.prop(propertyName)
|
||||
.set(o.importExpr(resolveIdentifier(Identifiers.QueryList), [o.DYNAMIC_TYPE])
|
||||
@ -126,7 +126,7 @@ export function createQueryList(
|
||||
|
||||
export function addQueryToTokenMap(map: Map<any, CompileQuery[]>, query: CompileQuery) {
|
||||
query.meta.selectors.forEach((selector) => {
|
||||
var entry = map.get(selector.reference);
|
||||
let entry = map.get(selector.reference);
|
||||
if (!entry) {
|
||||
entry = [];
|
||||
map.set(selector.reference, entry);
|
||||
|
@ -111,13 +111,13 @@ export class CompileView implements NameResolver {
|
||||
this.componentContext =
|
||||
getPropertyInView(o.THIS_EXPR.prop('context'), this, this.componentView);
|
||||
|
||||
var viewQueries = new Map<any, CompileQuery[]>();
|
||||
const viewQueries = new Map<any, CompileQuery[]>();
|
||||
if (this.viewType === ViewType.COMPONENT) {
|
||||
var directiveInstance = o.THIS_EXPR.prop('context');
|
||||
const directiveInstance = o.THIS_EXPR.prop('context');
|
||||
this.component.viewQueries.forEach((queryMeta, queryIndex) => {
|
||||
var propName = `_viewQuery_${queryMeta.selectors[0].name}_${queryIndex}`;
|
||||
var queryList = createQueryList(queryMeta, directiveInstance, propName, this);
|
||||
var query = new CompileQuery(queryMeta, queryList, directiveInstance, this);
|
||||
const propName = `_viewQuery_${queryMeta.selectors[0].name}_${queryIndex}`;
|
||||
const queryList = createQueryList(queryMeta, directiveInstance, propName, this);
|
||||
const query = new CompileQuery(queryMeta, queryList, directiveInstance, this);
|
||||
addQueryToTokenMap(viewQueries, query);
|
||||
});
|
||||
}
|
||||
@ -138,8 +138,8 @@ export class CompileView implements NameResolver {
|
||||
if (name == EventHandlerVars.event.name) {
|
||||
return EventHandlerVars.event;
|
||||
}
|
||||
var currView: CompileView = this;
|
||||
var result = currView.locals.get(name);
|
||||
let currView: CompileView = this;
|
||||
let result = currView.locals.get(name);
|
||||
while (!result && isPresent(currView.declarationElement.view)) {
|
||||
currView = currView.declarationElement.view;
|
||||
result = currView.locals.get(name);
|
||||
|
@ -16,15 +16,15 @@ import {CompileElement} from './compile_element';
|
||||
import {CompileView} from './compile_view';
|
||||
import {DetectChangesVars} from './constants';
|
||||
|
||||
var STATE_IS_NEVER_CHECKED = o.THIS_EXPR.prop('numberOfChecks').identical(new o.LiteralExpr(0));
|
||||
var NOT_THROW_ON_CHANGES = o.not(DetectChangesVars.throwOnChange);
|
||||
const STATE_IS_NEVER_CHECKED = o.THIS_EXPR.prop('numberOfChecks').identical(new o.LiteralExpr(0));
|
||||
const NOT_THROW_ON_CHANGES = o.not(DetectChangesVars.throwOnChange);
|
||||
|
||||
export function bindDirectiveAfterContentLifecycleCallbacks(
|
||||
directiveMeta: CompileDirectiveSummary, directiveInstance: o.Expression,
|
||||
compileElement: CompileElement) {
|
||||
var view = compileElement.view;
|
||||
var lifecycleHooks = directiveMeta.type.lifecycleHooks;
|
||||
var afterContentLifecycleCallbacksMethod = view.afterContentLifecycleCallbacksMethod;
|
||||
const view = compileElement.view;
|
||||
const lifecycleHooks = directiveMeta.type.lifecycleHooks;
|
||||
const afterContentLifecycleCallbacksMethod = view.afterContentLifecycleCallbacksMethod;
|
||||
afterContentLifecycleCallbacksMethod.resetDebugInfo(
|
||||
compileElement.nodeIndex, compileElement.sourceAst);
|
||||
if (lifecycleHooks.indexOf(LifecycleHooks.AfterContentInit) !== -1) {
|
||||
@ -40,9 +40,9 @@ export function bindDirectiveAfterContentLifecycleCallbacks(
|
||||
export function bindDirectiveAfterViewLifecycleCallbacks(
|
||||
directiveMeta: CompileDirectiveSummary, directiveInstance: o.Expression,
|
||||
compileElement: CompileElement) {
|
||||
var view = compileElement.view;
|
||||
var lifecycleHooks = directiveMeta.type.lifecycleHooks;
|
||||
var afterViewLifecycleCallbacksMethod = view.afterViewLifecycleCallbacksMethod;
|
||||
const view = compileElement.view;
|
||||
const lifecycleHooks = directiveMeta.type.lifecycleHooks;
|
||||
const afterViewLifecycleCallbacksMethod = view.afterViewLifecycleCallbacksMethod;
|
||||
afterViewLifecycleCallbacksMethod.resetDebugInfo(
|
||||
compileElement.nodeIndex, compileElement.sourceAst);
|
||||
if (lifecycleHooks.indexOf(LifecycleHooks.AfterViewInit) !== -1) {
|
||||
@ -67,7 +67,7 @@ export function bindDirectiveWrapperLifecycleCallbacks(
|
||||
|
||||
export function bindInjectableDestroyLifecycleCallbacks(
|
||||
provider: ProviderAst, providerInstance: o.Expression, compileElement: CompileElement) {
|
||||
var onDestroyMethod = compileElement.view.destroyMethod;
|
||||
const onDestroyMethod = compileElement.view.destroyMethod;
|
||||
onDestroyMethod.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
|
||||
if (provider.providerType !== ProviderAstType.Directive &&
|
||||
provider.providerType !== ProviderAstType.Component &&
|
||||
@ -78,7 +78,7 @@ export function bindInjectableDestroyLifecycleCallbacks(
|
||||
|
||||
export function bindPipeDestroyLifecycleCallbacks(
|
||||
pipeMeta: CompilePipeSummary, pipeInstance: o.Expression, view: CompileView) {
|
||||
var onDestroyMethod = view.destroyMethod;
|
||||
const onDestroyMethod = view.destroyMethod;
|
||||
if (pipeMeta.type.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
|
||||
onDestroyMethod.addStmt(pipeInstance.callMethod('ngOnDestroy', []).toStmt());
|
||||
}
|
||||
|
@ -139,7 +139,7 @@ export function bindDirectiveInputs(
|
||||
});
|
||||
const isOnPushComp = directiveAst.directive.isComponent &&
|
||||
!isDefaultChangeDetectionStrategy(directiveAst.directive.changeDetection);
|
||||
let directiveDetectChangesExpr = DirectiveWrapperExpressions.ngDoCheck(
|
||||
const directiveDetectChangesExpr = DirectiveWrapperExpressions.ngDoCheck(
|
||||
directiveWrapperInstance, o.THIS_EXPR, compileElement.renderNode,
|
||||
DetectChangesVars.throwOnChange);
|
||||
const directiveDetectChangesStmt = isOnPushComp ?
|
||||
|
@ -21,8 +21,8 @@ export function getPropertyInView(
|
||||
if (callingView === definedView) {
|
||||
return property;
|
||||
} else {
|
||||
var viewProp: o.Expression = o.THIS_EXPR;
|
||||
var currView: CompileView = callingView;
|
||||
let viewProp: o.Expression = o.THIS_EXPR;
|
||||
let currView: CompileView = callingView;
|
||||
while (currView !== definedView && isPresent(currView.declarationElement.view)) {
|
||||
currView = currView.declarationElement.view;
|
||||
viewProp = viewProp.prop('parentView');
|
||||
@ -64,7 +64,7 @@ export function injectFromViewParentInjector(
|
||||
} else {
|
||||
viewExpr = o.THIS_EXPR.prop('parentView');
|
||||
}
|
||||
let args = [createDiTokenExpression(token), o.THIS_EXPR.prop('parentIndex')];
|
||||
const args = [createDiTokenExpression(token), o.THIS_EXPR.prop('parentIndex')];
|
||||
if (optional) {
|
||||
args.push(o.NULL_EXPR);
|
||||
}
|
||||
|
@ -30,14 +30,14 @@ const CLASS_ATTR = 'class';
|
||||
const STYLE_ATTR = 'style';
|
||||
const NG_CONTAINER_TAG = 'ng-container';
|
||||
|
||||
var parentRenderNodeVar = o.variable('parentRenderNode');
|
||||
var rootSelectorVar = o.variable('rootSelector');
|
||||
const parentRenderNodeVar = o.variable('parentRenderNode');
|
||||
const rootSelectorVar = o.variable('rootSelector');
|
||||
|
||||
export function buildView(
|
||||
view: CompileView, template: TemplateAst[],
|
||||
targetDependencies:
|
||||
Array<ViewClassDependency|ComponentFactoryDependency|DirectiveWrapperDependency>): number {
|
||||
var builderVisitor = new ViewBuilderVisitor(view, targetDependencies);
|
||||
const builderVisitor = new ViewBuilderVisitor(view, targetDependencies);
|
||||
const parentEl =
|
||||
view.declarationElement.isNull() ? view.declarationElement : view.declarationElement.parent;
|
||||
templateVisitAll(builderVisitor, template, parentEl);
|
||||
@ -68,10 +68,10 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
private _isRootNode(parent: CompileElement): boolean { return parent.view !== this.view; }
|
||||
|
||||
private _addRootNodeAndProject(node: CompileNode) {
|
||||
var projectedNode = _getOuterContainerOrSelf(node);
|
||||
var parent = projectedNode.parent;
|
||||
var ngContentIndex = (<any>projectedNode.sourceAst).ngContentIndex;
|
||||
var viewContainer =
|
||||
const projectedNode = _getOuterContainerOrSelf(node);
|
||||
const parent = projectedNode.parent;
|
||||
const ngContentIndex = (<any>projectedNode.sourceAst).ngContentIndex;
|
||||
const viewContainer =
|
||||
(node instanceof CompileElement && node.hasViewContainer) ? node.viewContainer : null;
|
||||
if (this._isRootNode(parent)) {
|
||||
if (this.view.viewType !== ViewType.COMPONENT) {
|
||||
@ -109,7 +109,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
const view = this.view;
|
||||
if (view.rootNodes.length === 0 ||
|
||||
view.rootNodes[view.rootNodes.length - 1].type !== CompileViewRootNodeType.Node) {
|
||||
var fieldName = `_el_${view.nodes.length}`;
|
||||
const fieldName = `_el_${view.nodes.length}`;
|
||||
view.fields.push(
|
||||
new o.ClassField(fieldName, o.importType(view.genConfig.renderTypes.renderElement)));
|
||||
view.createMethod.addStmt(o.THIS_EXPR.prop(fieldName)
|
||||
@ -129,12 +129,12 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
return this._visitText(ast, ast.value, parent);
|
||||
}
|
||||
private _visitText(ast: TemplateAst, value: string, parent: CompileElement): o.Expression {
|
||||
var fieldName = `_text_${this.view.nodes.length}`;
|
||||
const fieldName = `_text_${this.view.nodes.length}`;
|
||||
this.view.fields.push(
|
||||
new o.ClassField(fieldName, o.importType(this.view.genConfig.renderTypes.renderText)));
|
||||
var renderNode = o.THIS_EXPR.prop(fieldName);
|
||||
var compileNode = new CompileNode(parent, this.view, this.view.nodes.length, renderNode, ast);
|
||||
var createRenderNode =
|
||||
const renderNode = o.THIS_EXPR.prop(fieldName);
|
||||
const compileNode = new CompileNode(parent, this.view, this.view.nodes.length, renderNode, ast);
|
||||
const createRenderNode =
|
||||
o.THIS_EXPR.prop(fieldName)
|
||||
.set(ViewProperties.renderer.callMethod(
|
||||
'createText',
|
||||
@ -153,7 +153,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
// the projected nodes originate from a different view, so we don't
|
||||
// have debug information for them...
|
||||
this.view.createMethod.resetDebugInfo(null, ast);
|
||||
var parentRenderNode = this._getParentRenderNode(parent);
|
||||
const parentRenderNode = this._getParentRenderNode(parent);
|
||||
if (parentRenderNode !== o.NULL_EXPR) {
|
||||
this.view.createMethod.addStmt(
|
||||
o.THIS_EXPR.callMethod('projectNodes', [parentRenderNode, o.literal(ast.index)])
|
||||
@ -175,11 +175,11 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
}
|
||||
|
||||
visitElement(ast: ElementAst, parent: CompileElement): any {
|
||||
var nodeIndex = this.view.nodes.length;
|
||||
var createRenderNodeExpr: o.Expression;
|
||||
var debugContextExpr = this.view.createMethod.resetDebugInfoExpr(nodeIndex, ast);
|
||||
var directives = ast.directives.map(directiveAst => directiveAst.directive);
|
||||
var component = directives.find(directive => directive.isComponent);
|
||||
const nodeIndex = this.view.nodes.length;
|
||||
let createRenderNodeExpr: o.Expression;
|
||||
const debugContextExpr = this.view.createMethod.resetDebugInfoExpr(nodeIndex, ast);
|
||||
const directives = ast.directives.map(directiveAst => directiveAst.directive);
|
||||
const component = directives.find(directive => directive.isComponent);
|
||||
if (ast.name === NG_CONTAINER_TAG) {
|
||||
createRenderNodeExpr = ViewProperties.renderer.callMethod(
|
||||
'createTemplateAnchor', [this._getParentRenderNode(parent), debugContextExpr]);
|
||||
@ -201,20 +201,20 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
]);
|
||||
}
|
||||
}
|
||||
var fieldName = `_el_${nodeIndex}`;
|
||||
const fieldName = `_el_${nodeIndex}`;
|
||||
this.view.fields.push(
|
||||
new o.ClassField(fieldName, o.importType(this.view.genConfig.renderTypes.renderElement)));
|
||||
this.view.createMethod.addStmt(o.THIS_EXPR.prop(fieldName).set(createRenderNodeExpr).toStmt());
|
||||
|
||||
var renderNode = o.THIS_EXPR.prop(fieldName);
|
||||
const renderNode = o.THIS_EXPR.prop(fieldName);
|
||||
|
||||
var compileElement = new CompileElement(
|
||||
const compileElement = new CompileElement(
|
||||
parent, this.view, nodeIndex, renderNode, ast, component, directives, ast.providers,
|
||||
ast.hasViewContainer, false, ast.references, this.targetDependencies);
|
||||
this.view.nodes.push(compileElement);
|
||||
var compViewExpr: o.ReadPropExpr = null;
|
||||
let compViewExpr: o.ReadPropExpr = null;
|
||||
if (isPresent(component)) {
|
||||
let nestedComponentIdentifier =
|
||||
const nestedComponentIdentifier =
|
||||
new CompileIdentifierMetadata({name: getViewClassName(component, 0)});
|
||||
this.targetDependencies.push(
|
||||
new ViewClassDependency(component.type, nestedComponentIdentifier));
|
||||
@ -245,8 +245,8 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
}
|
||||
|
||||
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, parent: CompileElement): any {
|
||||
var nodeIndex = this.view.nodes.length;
|
||||
var fieldName = `_anchor_${nodeIndex}`;
|
||||
const nodeIndex = this.view.nodes.length;
|
||||
const fieldName = `_anchor_${nodeIndex}`;
|
||||
this.view.fields.push(
|
||||
new o.ClassField(fieldName, o.importType(this.view.genConfig.renderTypes.renderComment)));
|
||||
this.view.createMethod.addStmt(
|
||||
@ -258,19 +258,19 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
|
||||
this.view.createMethod.resetDebugInfoExpr(nodeIndex, ast)
|
||||
]))
|
||||
.toStmt());
|
||||
var renderNode = o.THIS_EXPR.prop(fieldName);
|
||||
const renderNode = o.THIS_EXPR.prop(fieldName);
|
||||
|
||||
var templateVariableBindings = ast.variables.map(
|
||||
const templateVariableBindings = ast.variables.map(
|
||||
varAst => [varAst.value.length > 0 ? varAst.value : IMPLICIT_TEMPLATE_VAR, varAst.name]);
|
||||
|
||||
var directives = ast.directives.map(directiveAst => directiveAst.directive);
|
||||
var compileElement = new CompileElement(
|
||||
const directives = ast.directives.map(directiveAst => directiveAst.directive);
|
||||
const compileElement = new CompileElement(
|
||||
parent, this.view, nodeIndex, renderNode, ast, null, directives, ast.providers,
|
||||
ast.hasViewContainer, true, ast.references, this.targetDependencies);
|
||||
this.view.nodes.push(compileElement);
|
||||
|
||||
this.nestedViewCount++;
|
||||
var embeddedView = new CompileView(
|
||||
const embeddedView = new CompileView(
|
||||
this.view.component, this.view.genConfig, this.view.pipeMetas, o.NULL_EXPR,
|
||||
this.view.animations, this.view.viewIndex + this.nestedViewCount, compileElement,
|
||||
templateVariableBindings);
|
||||
@ -355,7 +355,7 @@ function _mergeHtmlAndDirectiveAttrs(
|
||||
}
|
||||
|
||||
function _readHtmlAttrs(attrs: AttrAst[]): {[key: string]: string} {
|
||||
var htmlAttrs: {[key: string]: string} = {};
|
||||
const htmlAttrs: {[key: string]: string} = {};
|
||||
attrs.forEach((ast) => { htmlAttrs[ast.name] = ast.value; });
|
||||
return htmlAttrs;
|
||||
}
|
||||
@ -369,7 +369,7 @@ function mergeAttributeValue(attrName: string, attrValue1: string, attrValue2: s
|
||||
}
|
||||
|
||||
function createViewTopLevelStmts(view: CompileView, targetStatements: o.Statement[]) {
|
||||
var nodeDebugInfosVar: o.Expression = o.NULL_EXPR;
|
||||
let nodeDebugInfosVar: o.Expression = o.NULL_EXPR;
|
||||
if (view.genConfig.genDebugInfo) {
|
||||
nodeDebugInfosVar = o.variable(
|
||||
`nodeDebugInfos_${view.component.type.name}${view.viewIndex}`); // fix highlighting: `
|
||||
@ -384,7 +384,7 @@ function createViewTopLevelStmts(view: CompileView, targetStatements: o.Statemen
|
||||
}
|
||||
|
||||
|
||||
var renderCompTypeVar: o.ReadVarExpr =
|
||||
const renderCompTypeVar: o.ReadVarExpr =
|
||||
o.variable(`renderType_${view.component.type.name}`); // fix highlighting: `
|
||||
if (view.viewIndex === 0) {
|
||||
let templateUrlInfo: string;
|
||||
@ -407,15 +407,15 @@ function createViewTopLevelStmts(view: CompileView, targetStatements: o.Statemen
|
||||
.toDeclStmt(o.importType(resolveIdentifier(Identifiers.RenderComponentType))));
|
||||
}
|
||||
|
||||
var viewClass = createViewClass(view, renderCompTypeVar, nodeDebugInfosVar);
|
||||
const viewClass = createViewClass(view, renderCompTypeVar, nodeDebugInfosVar);
|
||||
targetStatements.push(viewClass);
|
||||
}
|
||||
|
||||
function createStaticNodeDebugInfo(node: CompileNode): o.Expression {
|
||||
var compileElement = node instanceof CompileElement ? node : null;
|
||||
var providerTokens: o.Expression[] = [];
|
||||
var componentToken: o.Expression = o.NULL_EXPR;
|
||||
var varTokenEntries: any[] = [];
|
||||
const compileElement = node instanceof CompileElement ? node : null;
|
||||
let providerTokens: o.Expression[] = [];
|
||||
let componentToken: o.Expression = o.NULL_EXPR;
|
||||
const varTokenEntries: any[] = [];
|
||||
if (isPresent(compileElement)) {
|
||||
providerTokens = compileElement.getProviderTokens();
|
||||
if (isPresent(compileElement.component)) {
|
||||
@ -441,7 +441,7 @@ function createStaticNodeDebugInfo(node: CompileNode): o.Expression {
|
||||
function createViewClass(
|
||||
view: CompileView, renderCompTypeVar: o.ReadVarExpr,
|
||||
nodeDebugInfosVar: o.Expression): o.ClassStmt {
|
||||
var viewConstructorArgs = [
|
||||
const viewConstructorArgs = [
|
||||
new o.FnParam(
|
||||
ViewConstructorVars.viewUtils.name, o.importType(resolveIdentifier(Identifiers.ViewUtils))),
|
||||
new o.FnParam(
|
||||
@ -450,7 +450,7 @@ function createViewClass(
|
||||
new o.FnParam(ViewConstructorVars.parentIndex.name, o.NUMBER_TYPE),
|
||||
new o.FnParam(ViewConstructorVars.parentElement.name, o.DYNAMIC_TYPE)
|
||||
];
|
||||
var superConstructorArgs = [
|
||||
const superConstructorArgs = [
|
||||
o.variable(view.className), renderCompTypeVar, ViewTypeEnum.fromValue(view.viewType),
|
||||
ViewConstructorVars.viewUtils, ViewConstructorVars.parentView, ViewConstructorVars.parentIndex,
|
||||
ViewConstructorVars.parentElement,
|
||||
@ -464,7 +464,7 @@ function createViewClass(
|
||||
'declaredViewContainer', o.importType(resolveIdentifier(Identifiers.ViewContainer))));
|
||||
superConstructorArgs.push(o.variable('declaredViewContainer'));
|
||||
}
|
||||
var viewMethods = [
|
||||
const viewMethods = [
|
||||
new o.ClassMethod(
|
||||
'createInternal', [new o.FnParam(rootSelectorVar.name, o.STRING_TYPE)],
|
||||
generateCreateMethod(view),
|
||||
@ -488,9 +488,9 @@ function createViewClass(
|
||||
generateVisitRootNodesMethod(view), generateVisitProjectableNodesMethod(view),
|
||||
generateCreateEmbeddedViewsMethod(view)
|
||||
].filter((method) => method.body.length > 0);
|
||||
var superClass = view.genConfig.genDebugInfo ? Identifiers.DebugAppView : Identifiers.AppView;
|
||||
const superClass = view.genConfig.genDebugInfo ? Identifiers.DebugAppView : Identifiers.AppView;
|
||||
|
||||
var viewClass = createClassStmt({
|
||||
const viewClass = createClassStmt({
|
||||
name: view.className,
|
||||
parent: o.importExpr(resolveIdentifier(superClass), [getContextType(view)]),
|
||||
parentArgs: superConstructorArgs,
|
||||
@ -512,8 +512,8 @@ function generateDestroyMethod(view: CompileView): o.Statement[] {
|
||||
}
|
||||
|
||||
function generateCreateMethod(view: CompileView): o.Statement[] {
|
||||
var parentRenderNodeExpr: o.Expression = o.NULL_EXPR;
|
||||
var parentRenderNodeStmts: any[] = [];
|
||||
let parentRenderNodeExpr: o.Expression = o.NULL_EXPR;
|
||||
let parentRenderNodeStmts: any[] = [];
|
||||
if (view.viewType === ViewType.COMPONENT) {
|
||||
parentRenderNodeExpr =
|
||||
ViewProperties.renderer.callMethod('createViewRoot', [o.THIS_EXPR.prop('parentElement')]);
|
||||
@ -522,7 +522,7 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
|
||||
.toDeclStmt(
|
||||
o.importType(view.genConfig.renderTypes.renderNode), [o.StmtModifier.Final])];
|
||||
}
|
||||
var resultExpr: o.Expression;
|
||||
let resultExpr: o.Expression;
|
||||
if (view.viewType === ViewType.HOST) {
|
||||
const hostEl = <CompileElement>view.nodes[0];
|
||||
resultExpr =
|
||||
@ -532,7 +532,7 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
|
||||
} else {
|
||||
resultExpr = o.NULL_EXPR;
|
||||
}
|
||||
let allNodesExpr: o.Expression =
|
||||
const allNodesExpr: o.Expression =
|
||||
ViewProperties.renderer.cast(o.DYNAMIC_TYPE)
|
||||
.prop('directRenderer')
|
||||
.conditional(o.NULL_EXPR, o.literalArr(view.nodes.map(node => node.renderNode)));
|
||||
@ -552,7 +552,7 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
|
||||
}
|
||||
|
||||
function generateDetectChangesMethod(view: CompileView): o.Statement[] {
|
||||
var stmts: any[] = [];
|
||||
const stmts: any[] = [];
|
||||
if (view.animationBindingsMethod.isEmpty() && view.detectChangesInInputsMethod.isEmpty() &&
|
||||
view.updateContentQueriesMethod.isEmpty() &&
|
||||
view.afterContentLifecycleCallbacksMethod.isEmpty() &&
|
||||
@ -568,7 +568,7 @@ function generateDetectChangesMethod(view: CompileView): o.Statement[] {
|
||||
viewContainer.callMethod('detectChangesInNestedViews', [DetectChangesVars.throwOnChange])
|
||||
.toStmt());
|
||||
});
|
||||
var afterContentStmts = view.updateContentQueriesMethod.finish().concat(
|
||||
const afterContentStmts = view.updateContentQueriesMethod.finish().concat(
|
||||
view.afterContentLifecycleCallbacksMethod.finish());
|
||||
if (afterContentStmts.length > 0) {
|
||||
stmts.push(new o.IfStmt(o.not(DetectChangesVars.throwOnChange), afterContentStmts));
|
||||
@ -577,14 +577,14 @@ function generateDetectChangesMethod(view: CompileView): o.Statement[] {
|
||||
view.viewChildren.forEach((viewChild) => {
|
||||
stmts.push(viewChild.callMethod('detectChanges', [DetectChangesVars.throwOnChange]).toStmt());
|
||||
});
|
||||
var afterViewStmts =
|
||||
const afterViewStmts =
|
||||
view.updateViewQueriesMethod.finish().concat(view.afterViewLifecycleCallbacksMethod.finish());
|
||||
if (afterViewStmts.length > 0) {
|
||||
stmts.push(new o.IfStmt(o.not(DetectChangesVars.throwOnChange), afterViewStmts));
|
||||
}
|
||||
|
||||
var varStmts: any[] = [];
|
||||
var readVars = o.findReadVarNames(stmts);
|
||||
const varStmts: any[] = [];
|
||||
const readVars = o.findReadVarNames(stmts);
|
||||
if (readVars.has(DetectChangesVars.changed.name)) {
|
||||
varStmts.push(DetectChangesVars.changed.set(o.literal(true)).toDeclStmt(o.BOOL_TYPE));
|
||||
}
|
||||
@ -613,7 +613,7 @@ function getContextType(view: CompileView): o.Type {
|
||||
}
|
||||
|
||||
function getChangeDetectionMode(view: CompileView): ChangeDetectorStatus {
|
||||
var mode: ChangeDetectorStatus;
|
||||
let mode: ChangeDetectorStatus;
|
||||
if (view.viewType === ViewType.COMPONENT) {
|
||||
mode = isDefaultChangeDetectionStrategy(view.component.changeDetection) ?
|
||||
ChangeDetectorStatus.CheckAlways :
|
||||
|
@ -16,8 +16,8 @@ import {ElementSchemaRegistry} from '../../src/schema/element_schema_registry';
|
||||
|
||||
export function main() {
|
||||
describe('RuntimeAnimationCompiler', () => {
|
||||
var resolver: CompileMetadataResolver;
|
||||
var parser: AnimationParser;
|
||||
let resolver: CompileMetadataResolver;
|
||||
let parser: AnimationParser;
|
||||
beforeEach(inject(
|
||||
[CompileMetadataResolver, ElementSchemaRegistry],
|
||||
(res: CompileMetadataResolver, schema: ElementSchemaRegistry) => {
|
||||
@ -27,19 +27,19 @@ export function main() {
|
||||
|
||||
const compiler = new AnimationCompiler();
|
||||
|
||||
var compileAnimations =
|
||||
const compileAnimations =
|
||||
(component: CompileDirectiveMetadata): AnimationEntryCompileResult[] => {
|
||||
const parsedAnimations = parser.parseComponent(component);
|
||||
return compiler.compile(component.type.name, parsedAnimations);
|
||||
};
|
||||
|
||||
var compileTriggers = (input: any[]) => {
|
||||
var entries: CompileAnimationEntryMetadata[] = input.map(entry => {
|
||||
var animationTriggerData = trigger(entry[0], entry[1]);
|
||||
const compileTriggers = (input: any[]) => {
|
||||
const entries: CompileAnimationEntryMetadata[] = input.map(entry => {
|
||||
const animationTriggerData = trigger(entry[0], entry[1]);
|
||||
return resolver.getAnimationEntryMetadata(animationTriggerData);
|
||||
});
|
||||
|
||||
var component = CompileDirectiveMetadata.create({
|
||||
const component = CompileDirectiveMetadata.create({
|
||||
type: new CompileTypeMetadata({name: 'myCmp'}),
|
||||
template: new CompileTemplateMetadata({animations: entries})
|
||||
});
|
||||
@ -47,18 +47,18 @@ export function main() {
|
||||
return compileAnimations(component);
|
||||
};
|
||||
|
||||
var compileSequence = (seq: AnimationMetadata) => {
|
||||
const compileSequence = (seq: AnimationMetadata) => {
|
||||
return compileTriggers([['myAnimation', [transition('state1 => state2', seq)]]]);
|
||||
};
|
||||
|
||||
it('should throw an exception containing all the inner animation parser errors', () => {
|
||||
var animation = sequence([
|
||||
const animation = sequence([
|
||||
style({'color': 'red'}), animate(1000, style({'font-size': '100px'})),
|
||||
style({'color': 'blue'}), animate(1000, style(':missing_state')), style({'color': 'gold'}),
|
||||
animate(1000, style('broken_state'))
|
||||
]);
|
||||
|
||||
var capturedErrorMessage: string;
|
||||
let capturedErrorMessage: string;
|
||||
try {
|
||||
compileSequence(animation);
|
||||
} catch (e) {
|
||||
|
@ -18,20 +18,20 @@ import {FILL_STYLE_FLAG, flattenStyles} from '../private_import_core';
|
||||
|
||||
export function main() {
|
||||
describe('parseAnimationEntry', () => {
|
||||
var combineStyles = (styles: AnimationStylesAst): {[key: string]: string | number} => {
|
||||
var flatStyles: {[key: string]: string | number} = {};
|
||||
const combineStyles = (styles: AnimationStylesAst): {[key: string]: string | number} => {
|
||||
const flatStyles: {[key: string]: string | number} = {};
|
||||
styles.styles.forEach(
|
||||
entry => Object.keys(entry).forEach(prop => { flatStyles[prop] = entry[prop]; }));
|
||||
return flatStyles;
|
||||
};
|
||||
|
||||
var collectKeyframeStyles =
|
||||
const collectKeyframeStyles =
|
||||
(keyframe: AnimationKeyframeAst): {[key: string]: string | number} =>
|
||||
combineStyles(keyframe.styles);
|
||||
|
||||
var collectStepStyles = (step: AnimationStepAst): {[key: string]: string | number}[] => {
|
||||
var keyframes = step.keyframes;
|
||||
var styles: {[key: string]: string | number}[] = [];
|
||||
const collectStepStyles = (step: AnimationStepAst): {[key: string]: string | number}[] => {
|
||||
const keyframes = step.keyframes;
|
||||
const styles: {[key: string]: string | number}[] = [];
|
||||
if (step.startingStyles.styles.length > 0) {
|
||||
styles.push(combineStyles(step.startingStyles));
|
||||
}
|
||||
@ -39,8 +39,8 @@ export function main() {
|
||||
return styles;
|
||||
};
|
||||
|
||||
var resolver: CompileMetadataResolver;
|
||||
var schema: ElementSchemaRegistry;
|
||||
let resolver: CompileMetadataResolver;
|
||||
let schema: ElementSchemaRegistry;
|
||||
beforeEach(inject(
|
||||
[CompileMetadataResolver, ElementSchemaRegistry],
|
||||
(res: CompileMetadataResolver, sch: ElementSchemaRegistry) => {
|
||||
@ -48,30 +48,30 @@ export function main() {
|
||||
schema = sch;
|
||||
}));
|
||||
|
||||
var parseAnimation = (data: AnimationMetadata[]) => {
|
||||
const parseAnimation = (data: AnimationMetadata[]) => {
|
||||
const entry = trigger('myAnimation', [transition('state1 => state2', sequence(data))]);
|
||||
const compiledAnimationEntry = resolver.getAnimationEntryMetadata(entry);
|
||||
const parser = new AnimationParser(schema);
|
||||
return parser.parseEntry(compiledAnimationEntry);
|
||||
};
|
||||
|
||||
var getAnimationAstFromEntryAst =
|
||||
const getAnimationAstFromEntryAst =
|
||||
(ast: AnimationEntryAst) => { return ast.stateTransitions[0].animation; };
|
||||
|
||||
var parseAnimationAst = (data: AnimationMetadata[]) =>
|
||||
const parseAnimationAst = (data: AnimationMetadata[]) =>
|
||||
getAnimationAstFromEntryAst(parseAnimation(data).ast);
|
||||
|
||||
var parseAnimationAndGetErrors = (data: AnimationMetadata[]) => parseAnimation(data).errors;
|
||||
const parseAnimationAndGetErrors = (data: AnimationMetadata[]) => parseAnimation(data).errors;
|
||||
|
||||
it('should merge repeated style steps into a single style ast step entry', () => {
|
||||
var ast = parseAnimationAst([
|
||||
const ast = parseAnimationAst([
|
||||
style({'color': 'black'}), style({'background': 'red'}), style({'opacity': '0'}),
|
||||
animate(1000, style({'color': 'white', 'background': 'black', 'opacity': '1'}))
|
||||
]);
|
||||
|
||||
expect(ast.steps.length).toEqual(1);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.startingStyles.styles[0])
|
||||
.toEqual({'color': 'black', 'background': 'red', 'opacity': '0'});
|
||||
|
||||
@ -83,22 +83,22 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should animate only the styles requested within an animation step', () => {
|
||||
var ast = parseAnimationAst([
|
||||
const ast = parseAnimationAst([
|
||||
style({'color': 'black', 'background': 'blue'}),
|
||||
animate(1000, style({'background': 'orange'}))
|
||||
]);
|
||||
|
||||
expect(ast.steps.length).toEqual(1);
|
||||
|
||||
var animateStep = <AnimationStepAst>ast.steps[0];
|
||||
var fromKeyframe = animateStep.keyframes[0].styles.styles[0];
|
||||
var toKeyframe = animateStep.keyframes[1].styles.styles[0];
|
||||
const animateStep = <AnimationStepAst>ast.steps[0];
|
||||
const fromKeyframe = animateStep.keyframes[0].styles.styles[0];
|
||||
const toKeyframe = animateStep.keyframes[1].styles.styles[0];
|
||||
expect(fromKeyframe).toEqual({'background': 'blue'});
|
||||
expect(toKeyframe).toEqual({'background': 'orange'});
|
||||
});
|
||||
|
||||
it('should populate the starting and duration times propertly', () => {
|
||||
var ast = parseAnimationAst([
|
||||
const ast = parseAnimationAst([
|
||||
style({'color': 'black', 'opacity': '1'}),
|
||||
animate(1000, style({'color': 'red'})),
|
||||
animate(4000, style({'color': 'yellow'})),
|
||||
@ -110,46 +110,46 @@ export function main() {
|
||||
|
||||
expect(ast.steps.length).toEqual(5);
|
||||
|
||||
var step1 = <AnimationStepAst>ast.steps[0];
|
||||
const step1 = <AnimationStepAst>ast.steps[0];
|
||||
expect(step1.playTime).toEqual(1000);
|
||||
expect(step1.startTime).toEqual(0);
|
||||
|
||||
var step2 = <AnimationStepAst>ast.steps[1];
|
||||
const step2 = <AnimationStepAst>ast.steps[1];
|
||||
expect(step2.playTime).toEqual(4000);
|
||||
expect(step2.startTime).toEqual(1000);
|
||||
|
||||
var seq = <AnimationSequenceAst>ast.steps[2];
|
||||
const seq = <AnimationSequenceAst>ast.steps[2];
|
||||
expect(seq.playTime).toEqual(2000);
|
||||
expect(seq.startTime).toEqual(5000);
|
||||
|
||||
var step4 = <AnimationStepAst>seq.steps[0];
|
||||
const step4 = <AnimationStepAst>seq.steps[0];
|
||||
expect(step4.playTime).toEqual(1000);
|
||||
expect(step4.startTime).toEqual(5000);
|
||||
|
||||
var step5 = <AnimationStepAst>seq.steps[1];
|
||||
const step5 = <AnimationStepAst>seq.steps[1];
|
||||
expect(step5.playTime).toEqual(1000);
|
||||
expect(step5.startTime).toEqual(6000);
|
||||
|
||||
var grp = <AnimationGroupAst>ast.steps[3];
|
||||
const grp = <AnimationGroupAst>ast.steps[3];
|
||||
expect(grp.playTime).toEqual(1000);
|
||||
expect(grp.startTime).toEqual(7000);
|
||||
|
||||
var step6 = <AnimationStepAst>grp.steps[0];
|
||||
const step6 = <AnimationStepAst>grp.steps[0];
|
||||
expect(step6.playTime).toEqual(500);
|
||||
expect(step6.startTime).toEqual(7000);
|
||||
|
||||
var step7 = <AnimationStepAst>grp.steps[1];
|
||||
const step7 = <AnimationStepAst>grp.steps[1];
|
||||
expect(step7.playTime).toEqual(1000);
|
||||
expect(step7.startTime).toEqual(7000);
|
||||
|
||||
var step8 = <AnimationStepAst>ast.steps[4];
|
||||
const step8 = <AnimationStepAst>ast.steps[4];
|
||||
expect(step8.playTime).toEqual(300);
|
||||
expect(step8.startTime).toEqual(8000);
|
||||
});
|
||||
|
||||
it('should apply the correct animate() styles when parallel animations are active and use the same properties',
|
||||
() => {
|
||||
var details = parseAnimation([
|
||||
const details = parseAnimation([
|
||||
style({'opacity': '0', 'color': 'red'}), group([
|
||||
sequence([
|
||||
animate(2000, style({'color': 'black'})),
|
||||
@ -162,47 +162,47 @@ export function main() {
|
||||
])
|
||||
]);
|
||||
|
||||
var errors = details.errors;
|
||||
const errors = details.errors;
|
||||
expect(errors.length).toEqual(0);
|
||||
|
||||
var ast = <AnimationSequenceAst>getAnimationAstFromEntryAst(details.ast);
|
||||
var g1 = <AnimationGroupAst>ast.steps[1];
|
||||
const ast = <AnimationSequenceAst>getAnimationAstFromEntryAst(details.ast);
|
||||
const g1 = <AnimationGroupAst>ast.steps[1];
|
||||
|
||||
var sq1 = <AnimationSequenceAst>g1.steps[0];
|
||||
var sq2 = <AnimationSequenceAst>g1.steps[1];
|
||||
const sq1 = <AnimationSequenceAst>g1.steps[0];
|
||||
const sq2 = <AnimationSequenceAst>g1.steps[1];
|
||||
|
||||
var sq1a1 = <AnimationStepAst>sq1.steps[0];
|
||||
const sq1a1 = <AnimationStepAst>sq1.steps[0];
|
||||
expect(collectStepStyles(sq1a1)).toEqual([{'color': 'red'}, {'color': 'black'}]);
|
||||
|
||||
var sq1a2 = <AnimationStepAst>sq1.steps[1];
|
||||
const sq1a2 = <AnimationStepAst>sq1.steps[1];
|
||||
expect(collectStepStyles(sq1a2)).toEqual([{'opacity': '0.8'}, {'opacity': '0.5'}]);
|
||||
|
||||
var sq2a1 = <AnimationStepAst>sq2.steps[0];
|
||||
const sq2a1 = <AnimationStepAst>sq2.steps[0];
|
||||
expect(collectStepStyles(sq2a1)).toEqual([{'opacity': '0'}, {'opacity': '0.8'}]);
|
||||
|
||||
var sq2a2 = <AnimationStepAst>sq2.steps[1];
|
||||
const sq2a2 = <AnimationStepAst>sq2.steps[1];
|
||||
expect(collectStepStyles(sq2a2)).toEqual([{'color': 'black'}, {'color': 'blue'}]);
|
||||
});
|
||||
|
||||
it('should throw errors when animations animate a CSS property at the same time', () => {
|
||||
var animation1 = parseAnimation([
|
||||
const animation1 = parseAnimation([
|
||||
style({'opacity': '0'}),
|
||||
group([animate(1000, style({'opacity': '1'})), animate(2000, style({'opacity': '0.5'}))])
|
||||
]);
|
||||
|
||||
var errors1 = animation1.errors;
|
||||
const errors1 = animation1.errors;
|
||||
expect(errors1.length).toEqual(1);
|
||||
expect(errors1[0].msg)
|
||||
.toContainError(
|
||||
'The animated CSS property "opacity" unexpectedly changes between steps "0ms" and "2000ms" at "1000ms"');
|
||||
|
||||
var animation2 = parseAnimation([
|
||||
const animation2 = parseAnimation([
|
||||
style({'color': 'red'}),
|
||||
group(
|
||||
[animate(5000, style({'color': 'blue'})), animate(2500, style({'color': 'black'}))])
|
||||
]);
|
||||
|
||||
var errors2 = animation2.errors;
|
||||
const errors2 = animation2.errors;
|
||||
expect(errors2.length).toEqual(1);
|
||||
expect(errors2[0].msg)
|
||||
.toContainError(
|
||||
@ -210,13 +210,13 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should return an error when an animation style contains an invalid timing value', () => {
|
||||
var errors = parseAnimationAndGetErrors(
|
||||
const errors = parseAnimationAndGetErrors(
|
||||
[style({'opacity': '0'}), animate('one second', style({'opacity': '1'}))]);
|
||||
expect(errors[0].msg).toContainError(`The provided timing value "one second" is invalid.`);
|
||||
});
|
||||
|
||||
it('should collect and return any errors collected when parsing the metadata', () => {
|
||||
var errors = parseAnimationAndGetErrors([
|
||||
const errors = parseAnimationAndGetErrors([
|
||||
style({'opacity': '0'}), animate('one second', style({'opacity': '1'})),
|
||||
style({'opacity': '0'}), animate('one second', null), style({'background': 'red'})
|
||||
]);
|
||||
@ -224,13 +224,13 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should normalize a series of keyframe styles into a list of offset steps', () => {
|
||||
var ast =
|
||||
const ast =
|
||||
parseAnimationAst([animate(1000, keyframes([
|
||||
style({'width': '0'}), style({'width': '25px'}),
|
||||
style({'width': '50px'}), style({'width': '75px'})
|
||||
]))]);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.keyframes.length).toEqual(4);
|
||||
|
||||
expect(step.keyframes[0].offset).toEqual(0);
|
||||
@ -240,13 +240,13 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should use an existing collection of offset steps if provided', () => {
|
||||
var ast = parseAnimationAst([animate(
|
||||
const ast = parseAnimationAst([animate(
|
||||
1000, keyframes([
|
||||
style({'height': '0', 'offset': 0}), style({'height': '25px', 'offset': 0.6}),
|
||||
style({'height': '50px', 'offset': 0.7}), style({'height': '75px', 'offset': 1})
|
||||
]))]);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.keyframes.length).toEqual(4);
|
||||
|
||||
expect(step.keyframes[0].offset).toEqual(0);
|
||||
@ -256,14 +256,14 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should sort the provided collection of steps that contain offsets', () => {
|
||||
var ast = parseAnimationAst([animate(
|
||||
const ast = parseAnimationAst([animate(
|
||||
1000, keyframes([
|
||||
style({'opacity': '0', 'offset': 0.9}), style({'opacity': '0.25', 'offset': 0}),
|
||||
style({'opacity': '0.50', 'offset': 1}),
|
||||
style({'opacity': '0.75', 'offset': 0.91})
|
||||
]))]);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.keyframes.length).toEqual(4);
|
||||
|
||||
expect(step.keyframes[0].offset).toEqual(0);
|
||||
@ -280,44 +280,44 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should throw an error if a partial amount of keyframes contain an offset', () => {
|
||||
var errors = parseAnimationAndGetErrors(
|
||||
const errors = parseAnimationAndGetErrors(
|
||||
[animate(1000, keyframes([
|
||||
style({'z-index': 0, 'offset': 0}), style({'z-index': 1}),
|
||||
style({'z-index': 2, 'offset': 1})
|
||||
]))]);
|
||||
|
||||
expect(errors.length).toEqual(1);
|
||||
var error = errors[0];
|
||||
const error = errors[0];
|
||||
|
||||
expect(error.msg).toMatch(/Not all style\(\) entries contain an offset/);
|
||||
});
|
||||
|
||||
it('should use an existing style used earlier in the animation sequence if not defined in the first keyframe',
|
||||
() => {
|
||||
var ast = parseAnimationAst([animate(
|
||||
const ast = parseAnimationAst([animate(
|
||||
1000,
|
||||
keyframes(
|
||||
[style({'color': 'red'}), style({'background': 'blue', 'color': 'white'})]))]);
|
||||
|
||||
var keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
var kf1 = keyframesStep.keyframes[0];
|
||||
var kf2 = keyframesStep.keyframes[1];
|
||||
const keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
const kf1 = keyframesStep.keyframes[0];
|
||||
const kf2 = keyframesStep.keyframes[1];
|
||||
|
||||
expect(flattenStyles(kf1.styles.styles))
|
||||
.toEqual({'color': 'red', 'background': FILL_STYLE_FLAG});
|
||||
});
|
||||
|
||||
it('should copy over any missing styles to the final keyframe if not already defined', () => {
|
||||
var ast = parseAnimationAst([animate(
|
||||
const ast = parseAnimationAst([animate(
|
||||
1000, keyframes([
|
||||
style({'color': 'white', 'borderColor': 'white'}),
|
||||
style({'color': 'red', 'background': 'blue'}), style({'background': 'blue'})
|
||||
]))]);
|
||||
|
||||
var keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
var kf1 = keyframesStep.keyframes[0];
|
||||
var kf2 = keyframesStep.keyframes[1];
|
||||
var kf3 = keyframesStep.keyframes[2];
|
||||
const keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
const kf1 = keyframesStep.keyframes[0];
|
||||
const kf2 = keyframesStep.keyframes[1];
|
||||
const kf3 = keyframesStep.keyframes[2];
|
||||
|
||||
expect(flattenStyles(kf3.styles.styles))
|
||||
.toEqual({'background': 'blue', 'color': 'red', 'borderColor': 'white'});
|
||||
@ -325,18 +325,18 @@ export function main() {
|
||||
|
||||
it('should create an initial keyframe if not detected and place all keyframes styles there',
|
||||
() => {
|
||||
var ast = parseAnimationAst([animate(
|
||||
const ast = parseAnimationAst([animate(
|
||||
1000, keyframes([
|
||||
style({'color': 'white', 'background': 'black', 'offset': 0.5}),
|
||||
style(
|
||||
{'color': 'orange', 'background': 'red', 'fontSize': '100px', 'offset': 1})
|
||||
]))]);
|
||||
|
||||
var keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
const keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
expect(keyframesStep.keyframes.length).toEqual(3);
|
||||
var kf1 = keyframesStep.keyframes[0];
|
||||
var kf2 = keyframesStep.keyframes[1];
|
||||
var kf3 = keyframesStep.keyframes[2];
|
||||
const kf1 = keyframesStep.keyframes[0];
|
||||
const kf2 = keyframesStep.keyframes[1];
|
||||
const kf3 = keyframesStep.keyframes[2];
|
||||
|
||||
expect(kf1.offset).toEqual(0);
|
||||
expect(flattenStyles(kf1.styles.styles)).toEqual({
|
||||
@ -348,26 +348,26 @@ export function main() {
|
||||
|
||||
it('should create an destination keyframe if not detected and place all keyframes styles there',
|
||||
() => {
|
||||
var ast = parseAnimationAst([animate(1000, keyframes([
|
||||
style({
|
||||
'color': 'white',
|
||||
'background': 'black',
|
||||
'transform': 'rotate(360deg)',
|
||||
'offset': 0
|
||||
}),
|
||||
style({
|
||||
'color': 'orange',
|
||||
'background': 'red',
|
||||
'fontSize': '100px',
|
||||
'offset': 0.5
|
||||
})
|
||||
]))]);
|
||||
const ast = parseAnimationAst([animate(1000, keyframes([
|
||||
style({
|
||||
'color': 'white',
|
||||
'background': 'black',
|
||||
'transform': 'rotate(360deg)',
|
||||
'offset': 0
|
||||
}),
|
||||
style({
|
||||
'color': 'orange',
|
||||
'background': 'red',
|
||||
'fontSize': '100px',
|
||||
'offset': 0.5
|
||||
})
|
||||
]))]);
|
||||
|
||||
var keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
const keyframesStep = <AnimationStepAst>ast.steps[0];
|
||||
expect(keyframesStep.keyframes.length).toEqual(3);
|
||||
var kf1 = keyframesStep.keyframes[0];
|
||||
var kf2 = keyframesStep.keyframes[1];
|
||||
var kf3 = keyframesStep.keyframes[2];
|
||||
const kf1 = keyframesStep.keyframes[0];
|
||||
const kf2 = keyframesStep.keyframes[1];
|
||||
const kf3 = keyframesStep.keyframes[2];
|
||||
|
||||
expect(kf3.offset).toEqual(1);
|
||||
expect(flattenStyles(kf3.styles.styles)).toEqual({
|
||||
@ -380,37 +380,37 @@ export function main() {
|
||||
|
||||
describe('easing / duration / delay', () => {
|
||||
it('should parse simple string-based values', () => {
|
||||
var ast = parseAnimationAst([animate('1s .5s ease-out', style({'opacity': '1'}))]);
|
||||
const ast = parseAnimationAst([animate('1s .5s ease-out', style({'opacity': '1'}))]);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.duration).toEqual(1000);
|
||||
expect(step.delay).toEqual(500);
|
||||
expect(step.easing).toEqual('ease-out');
|
||||
});
|
||||
|
||||
it('should parse a numeric duration value', () => {
|
||||
var ast = parseAnimationAst([animate(666, style({'opacity': '1'}))]);
|
||||
const ast = parseAnimationAst([animate(666, style({'opacity': '1'}))]);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.duration).toEqual(666);
|
||||
expect(step.delay).toEqual(0);
|
||||
expect(step.easing).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should parse an easing value without a delay', () => {
|
||||
var ast = parseAnimationAst([animate('5s linear', style({'opacity': '1'}))]);
|
||||
const ast = parseAnimationAst([animate('5s linear', style({'opacity': '1'}))]);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.duration).toEqual(5000);
|
||||
expect(step.delay).toEqual(0);
|
||||
expect(step.easing).toEqual('linear');
|
||||
});
|
||||
|
||||
it('should parse a complex easing value', () => {
|
||||
var ast =
|
||||
const ast =
|
||||
parseAnimationAst([animate('30ms cubic-bezier(0, 0,0, .69)', style({'opacity': '1'}))]);
|
||||
|
||||
var step = <AnimationStepAst>ast.steps[0];
|
||||
const step = <AnimationStepAst>ast.steps[0];
|
||||
expect(step.duration).toEqual(30);
|
||||
expect(step.delay).toEqual(0);
|
||||
expect(step.easing).toEqual('cubic-bezier(0, 0,0, .69)');
|
||||
|
@ -23,7 +23,7 @@ export function main() {
|
||||
|
||||
function createArgs(count: number): o.Expression[] {
|
||||
const result: o.Expression[] = [];
|
||||
for (var i = 0; i < count; i++) {
|
||||
for (let i = 0; i < count; i++) {
|
||||
result.push(o.NULL_EXPR);
|
||||
}
|
||||
return result;
|
||||
@ -40,19 +40,19 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should work for arrays of length 3 - 4', () => {
|
||||
for (var i = 3; i <= 4; i++) {
|
||||
for (let i = 3; i <= 4; i++) {
|
||||
check(i, Identifiers.inlineArrays[2]);
|
||||
}
|
||||
});
|
||||
|
||||
it('should work for arrays of length 5 - 8', () => {
|
||||
for (var i = 5; i <= 8; i++) {
|
||||
for (let i = 5; i <= 8; i++) {
|
||||
check(i, Identifiers.inlineArrays[3]);
|
||||
}
|
||||
});
|
||||
|
||||
it('should work for arrays of length 9 - 16', () => {
|
||||
for (var i = 9; i <= 16; i++) {
|
||||
for (let i = 9; i <= 16; i++) {
|
||||
check(i, Identifiers.inlineArrays[4]);
|
||||
}
|
||||
});
|
||||
|
@ -17,10 +17,10 @@ export function main() {
|
||||
const scanner = new CssLexer().scan(code, trackComments);
|
||||
scanner.setMode(mode);
|
||||
|
||||
var tokens: CssToken[] = [];
|
||||
var output = scanner.scan();
|
||||
const tokens: CssToken[] = [];
|
||||
let output = scanner.scan();
|
||||
while (output != null) {
|
||||
var error = output.error;
|
||||
const error = output.error;
|
||||
if (isPresent(error)) {
|
||||
throw new CssScannerError(error.token, error.rawMessage);
|
||||
}
|
||||
@ -33,31 +33,31 @@ export function main() {
|
||||
|
||||
describe('CssLexer', () => {
|
||||
it('should lex newline characters as whitespace when whitespace mode is on', () => {
|
||||
var newlines = ['\n', '\r\n', '\r', '\f'];
|
||||
const newlines = ['\n', '\r\n', '\r', '\f'];
|
||||
newlines.forEach((line) => {
|
||||
var token = tokenize(line, false, CssLexerMode.ALL_TRACK_WS)[0];
|
||||
const token = tokenize(line, false, CssLexerMode.ALL_TRACK_WS)[0];
|
||||
expect(token.type).toEqual(CssTokenType.Whitespace);
|
||||
});
|
||||
});
|
||||
|
||||
it('should combined newline characters as one newline token when whitespace mode is on', () => {
|
||||
var newlines = ['\n', '\r\n', '\r', '\f'].join('');
|
||||
var tokens = tokenize(newlines, false, CssLexerMode.ALL_TRACK_WS);
|
||||
const newlines = ['\n', '\r\n', '\r', '\f'].join('');
|
||||
const tokens = tokenize(newlines, false, CssLexerMode.ALL_TRACK_WS);
|
||||
expect(tokens.length).toEqual(1);
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Whitespace);
|
||||
});
|
||||
|
||||
it('should not consider whitespace or newline values at all when whitespace mode is off',
|
||||
() => {
|
||||
var newlines = ['\n', '\r\n', '\r', '\f'].join('');
|
||||
var tokens = tokenize(newlines);
|
||||
const newlines = ['\n', '\r\n', '\r', '\f'].join('');
|
||||
const tokens = tokenize(newlines);
|
||||
expect(tokens.length).toEqual(0);
|
||||
});
|
||||
|
||||
it('should lex simple selectors and their inner properties', () => {
|
||||
var cssCode = '\n' +
|
||||
const cssCode = '\n' +
|
||||
' .selector { my-prop: my-value; }\n';
|
||||
var tokens = tokenize(cssCode);
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Character);
|
||||
expect(tokens[0].strValue).toEqual('.');
|
||||
@ -85,11 +85,11 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should capture the column and line values for each token', () => {
|
||||
var cssCode = '#id {\n' +
|
||||
const cssCode = '#id {\n' +
|
||||
' prop:value;\n' +
|
||||
'}';
|
||||
|
||||
var tokens = tokenize(cssCode);
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
// #
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Character);
|
||||
@ -133,8 +133,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should lex quoted strings and escape accordingly', () => {
|
||||
var cssCode = 'prop: \'some { value } \\\' that is quoted\'';
|
||||
var tokens = tokenize(cssCode);
|
||||
const cssCode = 'prop: \'some { value } \\\' that is quoted\'';
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Identifier);
|
||||
expect(tokens[1].type).toEqual(CssTokenType.Character);
|
||||
@ -147,8 +147,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should lex numbers properly and set them as numbers', () => {
|
||||
var cssCode = '0 1 -2 3.0 -4.001';
|
||||
var tokens = tokenize(cssCode);
|
||||
const cssCode = '0 1 -2 3.0 -4.001';
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[0].strValue).toEqual('0');
|
||||
@ -167,8 +167,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should lex @keywords', () => {
|
||||
var cssCode = '@import()@something';
|
||||
var tokens = tokenize(cssCode);
|
||||
const cssCode = '@import()@something';
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.AtKeyword);
|
||||
expect(tokens[0].strValue).toEqual('@import');
|
||||
@ -184,8 +184,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should still lex a number even if it has a dimension suffix', () => {
|
||||
var cssCode = '40% is 40 percent';
|
||||
var tokens = tokenize(cssCode);
|
||||
const cssCode = '40% is 40 percent';
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Number);
|
||||
expect(tokens[0].strValue).toEqual('40');
|
||||
@ -201,8 +201,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should allow escaped character and unicode character-strings in CSS selectors', () => {
|
||||
var cssCode = '\\123456 .some\\thing \{\}';
|
||||
var tokens = tokenize(cssCode);
|
||||
const cssCode = '\\123456 .some\\thing \{\}';
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Identifier);
|
||||
expect(tokens[0].strValue).toEqual('\\123456');
|
||||
@ -213,8 +213,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should distinguish identifiers and numbers from special characters', () => {
|
||||
var cssCode = 'one*two=-4+three-4-equals_value$';
|
||||
var tokens = tokenize(cssCode);
|
||||
const cssCode = 'one*two=-4+three-4-equals_value$';
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].type).toEqual(CssTokenType.Identifier);
|
||||
expect(tokens[0].strValue).toEqual('one');
|
||||
@ -242,8 +242,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should filter out comments and whitespace by default', () => {
|
||||
var cssCode = '.selector /* comment */ { /* value */ }';
|
||||
var tokens = tokenize(cssCode);
|
||||
const cssCode = '.selector /* comment */ { /* value */ }';
|
||||
const tokens = tokenize(cssCode);
|
||||
|
||||
expect(tokens[0].strValue).toEqual('.');
|
||||
expect(tokens[1].strValue).toEqual('selector');
|
||||
@ -252,9 +252,9 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should track comments when the flag is set to true', () => {
|
||||
var cssCode = '.selector /* comment */ { /* value */ }';
|
||||
var trackComments = true;
|
||||
var tokens = tokenize(cssCode, trackComments, CssLexerMode.ALL_TRACK_WS);
|
||||
const cssCode = '.selector /* comment */ { /* value */ }';
|
||||
const trackComments = true;
|
||||
const tokens = tokenize(cssCode, trackComments, CssLexerMode.ALL_TRACK_WS);
|
||||
|
||||
expect(tokens[0].strValue).toEqual('.');
|
||||
expect(tokens[1].strValue).toEqual('selector');
|
||||
@ -273,9 +273,9 @@ export function main() {
|
||||
|
||||
describe('Selector Mode', () => {
|
||||
it('should throw an error if a selector is being parsed while in the wrong mode', () => {
|
||||
var cssCode = '.class > tag';
|
||||
const cssCode = '.class > tag';
|
||||
|
||||
var capturedMessage: string;
|
||||
let capturedMessage: string;
|
||||
try {
|
||||
tokenize(cssCode, false, CssLexerMode.STYLE_BLOCK);
|
||||
} catch (e) {
|
||||
@ -299,7 +299,7 @@ export function main() {
|
||||
it('should consider attribute selectors as valid input and throw when an invalid modifier is used',
|
||||
() => {
|
||||
function tokenizeAttr(modifier: string) {
|
||||
var cssCode = 'value' + modifier + '=\'something\'';
|
||||
const cssCode = 'value' + modifier + '=\'something\'';
|
||||
return tokenize(cssCode, false, CssLexerMode.ATTRIBUTE_SELECTOR);
|
||||
}
|
||||
|
||||
@ -338,8 +338,8 @@ export function main() {
|
||||
it('should validate pseudo selector identifiers with a reduced subset of valid characters',
|
||||
() => {
|
||||
function tokenizePseudo(code: string, withArgs = false): CssToken[] {
|
||||
var mode = withArgs ? CssLexerMode.PSEUDO_SELECTOR_WITH_ARGUMENTS :
|
||||
CssLexerMode.PSEUDO_SELECTOR;
|
||||
const mode = withArgs ? CssLexerMode.PSEUDO_SELECTOR_WITH_ARGUMENTS :
|
||||
CssLexerMode.PSEUDO_SELECTOR;
|
||||
return tokenize(code, false, mode);
|
||||
}
|
||||
|
||||
|
@ -13,7 +13,7 @@ import {BlockType, CssParseError, CssParser, CssToken, ParsedCssResult} from '..
|
||||
import {ParseLocation} from '../../src/parse_util';
|
||||
|
||||
export function assertTokens(tokens: CssToken[], valuesArr: string[]) {
|
||||
for (var i = 0; i < tokens.length; i++) {
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
expect(tokens[i].strValue == valuesArr[i]);
|
||||
}
|
||||
}
|
||||
@ -25,8 +25,8 @@ export function main() {
|
||||
}
|
||||
|
||||
function makeAst(css: string): CssStyleSheetAst {
|
||||
var output = parse(css);
|
||||
var errors = output.errors;
|
||||
const output = parse(css);
|
||||
const errors = output.errors;
|
||||
if (errors.length > 0) {
|
||||
throw new Error(errors.map((error: CssParseError) => error.msg).join(', '));
|
||||
}
|
||||
@ -34,45 +34,45 @@ export function main() {
|
||||
}
|
||||
|
||||
it('should parse CSS into a stylesheet Ast', () => {
|
||||
var styles = '.selector { prop: value123; }';
|
||||
const styles = '.selector { prop: value123; }';
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
expect(ast.rules.length).toEqual(1);
|
||||
|
||||
var rule = <CssSelectorRuleAst>ast.rules[0];
|
||||
var selector = rule.selectors[0];
|
||||
const rule = <CssSelectorRuleAst>ast.rules[0];
|
||||
const selector = rule.selectors[0];
|
||||
expect(selector.strValue).toEqual('.selector');
|
||||
|
||||
var block: CssBlockAst = rule.block;
|
||||
const block: CssBlockAst = rule.block;
|
||||
expect(block.entries.length).toEqual(1);
|
||||
|
||||
var definition = <CssDefinitionAst>block.entries[0];
|
||||
const definition = <CssDefinitionAst>block.entries[0];
|
||||
expect(definition.property.strValue).toEqual('prop');
|
||||
|
||||
var value = <CssStyleValueAst>definition.value;
|
||||
const value = <CssStyleValueAst>definition.value;
|
||||
expect(value.tokens[0].strValue).toEqual('value123');
|
||||
});
|
||||
|
||||
it('should parse multiple CSS selectors sharing the same set of styles', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
.class, #id, tag, [attr], key + value, * value, :-moz-any-link {
|
||||
prop: value123;
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
expect(ast.rules.length).toEqual(1);
|
||||
|
||||
var rule = <CssSelectorRuleAst>ast.rules[0];
|
||||
const rule = <CssSelectorRuleAst>ast.rules[0];
|
||||
expect(rule.selectors.length).toBe(7);
|
||||
|
||||
var classRule = rule.selectors[0];
|
||||
var idRule = rule.selectors[1];
|
||||
var tagRule = rule.selectors[2];
|
||||
var attrRule = rule.selectors[3];
|
||||
var plusOpRule = rule.selectors[4];
|
||||
var starOpRule = rule.selectors[5];
|
||||
var mozRule = rule.selectors[6];
|
||||
const classRule = rule.selectors[0];
|
||||
const idRule = rule.selectors[1];
|
||||
const tagRule = rule.selectors[2];
|
||||
const attrRule = rule.selectors[3];
|
||||
const plusOpRule = rule.selectors[4];
|
||||
const starOpRule = rule.selectors[5];
|
||||
const mozRule = rule.selectors[6];
|
||||
|
||||
assertTokens(classRule.selectorParts[0].tokens, ['.', 'class']);
|
||||
assertTokens(idRule.selectorParts[0].tokens, ['.', 'class']);
|
||||
@ -87,13 +87,13 @@ export function main() {
|
||||
|
||||
assertTokens(mozRule.selectorParts[0].pseudoSelectors[0].tokens, [':', '-moz-any-link']);
|
||||
|
||||
var style1 = <CssDefinitionAst>rule.block.entries[0];
|
||||
const style1 = <CssDefinitionAst>rule.block.entries[0];
|
||||
expect(style1.property.strValue).toEqual('prop');
|
||||
assertTokens(style1.value.tokens, ['value123']);
|
||||
});
|
||||
|
||||
it('should parse keyframe rules', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@keyframes rotateMe {
|
||||
from {
|
||||
transform: rotate(-360deg);
|
||||
@ -107,37 +107,37 @@ export function main() {
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
expect(ast.rules.length).toEqual(1);
|
||||
|
||||
var rule = <CssKeyframeRuleAst>ast.rules[0];
|
||||
const rule = <CssKeyframeRuleAst>ast.rules[0];
|
||||
expect(rule.name.strValue).toEqual('rotateMe');
|
||||
|
||||
var block = <CssBlockAst>rule.block;
|
||||
var fromRule = <CssKeyframeDefinitionAst>block.entries[0];
|
||||
const block = <CssBlockAst>rule.block;
|
||||
const fromRule = <CssKeyframeDefinitionAst>block.entries[0];
|
||||
|
||||
expect(fromRule.name.strValue).toEqual('from');
|
||||
var fromStyle = <CssDefinitionAst>(<CssBlockAst>fromRule.block).entries[0];
|
||||
const fromStyle = <CssDefinitionAst>(<CssBlockAst>fromRule.block).entries[0];
|
||||
expect(fromStyle.property.strValue).toEqual('transform');
|
||||
assertTokens(fromStyle.value.tokens, ['rotate', '(', '-360', 'deg', ')']);
|
||||
|
||||
var midRule = <CssKeyframeDefinitionAst>block.entries[1];
|
||||
const midRule = <CssKeyframeDefinitionAst>block.entries[1];
|
||||
|
||||
expect(midRule.name.strValue).toEqual('50%');
|
||||
var midStyle = <CssDefinitionAst>(<CssBlockAst>midRule.block).entries[0];
|
||||
const midStyle = <CssDefinitionAst>(<CssBlockAst>midRule.block).entries[0];
|
||||
expect(midStyle.property.strValue).toEqual('transform');
|
||||
assertTokens(midStyle.value.tokens, ['rotate', '(', '0', 'deg', ')']);
|
||||
|
||||
var toRule = <CssKeyframeDefinitionAst>block.entries[2];
|
||||
const toRule = <CssKeyframeDefinitionAst>block.entries[2];
|
||||
|
||||
expect(toRule.name.strValue).toEqual('to');
|
||||
var toStyle = <CssDefinitionAst>(<CssBlockAst>toRule.block).entries[0];
|
||||
const toStyle = <CssDefinitionAst>(<CssBlockAst>toRule.block).entries[0];
|
||||
expect(toStyle.property.strValue).toEqual('transform');
|
||||
assertTokens(toStyle.value.tokens, ['rotate', '(', '360', 'deg', ')']);
|
||||
});
|
||||
|
||||
it('should parse media queries into a stylesheet Ast', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@media all and (max-width:100px) {
|
||||
.selector {
|
||||
prop: value123;
|
||||
@ -145,40 +145,40 @@ export function main() {
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
expect(ast.rules.length).toEqual(1);
|
||||
|
||||
var rule = <CssMediaQueryRuleAst>ast.rules[0];
|
||||
const rule = <CssMediaQueryRuleAst>ast.rules[0];
|
||||
assertTokens(rule.query.tokens, ['all', 'and', '(', 'max-width', ':', '100', 'px', ')']);
|
||||
|
||||
var block = <CssBlockAst>rule.block;
|
||||
const block = <CssBlockAst>rule.block;
|
||||
expect(block.entries.length).toEqual(1);
|
||||
|
||||
var rule2 = <CssSelectorRuleAst>block.entries[0];
|
||||
const rule2 = <CssSelectorRuleAst>block.entries[0];
|
||||
expect(rule2.selectors[0].strValue).toEqual('.selector');
|
||||
|
||||
var block2 = <CssBlockAst>rule2.block;
|
||||
const block2 = <CssBlockAst>rule2.block;
|
||||
expect(block2.entries.length).toEqual(1);
|
||||
});
|
||||
|
||||
it('should parse inline CSS values', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@import url('remote.css');
|
||||
@charset "UTF-8";
|
||||
@namespace ng url(http://angular.io/namespace/ng);
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
|
||||
var importRule = <CssInlineRuleAst>ast.rules[0];
|
||||
const importRule = <CssInlineRuleAst>ast.rules[0];
|
||||
expect(importRule.type).toEqual(BlockType.Import);
|
||||
assertTokens(importRule.value.tokens, ['url', '(', 'remote', '.', 'css', ')']);
|
||||
|
||||
var charsetRule = <CssInlineRuleAst>ast.rules[1];
|
||||
const charsetRule = <CssInlineRuleAst>ast.rules[1];
|
||||
expect(charsetRule.type).toEqual(BlockType.Charset);
|
||||
assertTokens(charsetRule.value.tokens, ['UTF-8']);
|
||||
|
||||
var namespaceRule = <CssInlineRuleAst>ast.rules[2];
|
||||
const namespaceRule = <CssInlineRuleAst>ast.rules[2];
|
||||
expect(namespaceRule.type).toEqual(BlockType.Namespace);
|
||||
assertTokens(
|
||||
namespaceRule.value.tokens, ['ng', 'url', '(', 'http://angular.io/namespace/ng', ')']);
|
||||
@ -186,7 +186,7 @@ export function main() {
|
||||
|
||||
it('should parse CSS values that contain functions and leave the inner function data untokenized',
|
||||
() => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
.class {
|
||||
background: url(matias.css);
|
||||
animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
|
||||
@ -195,10 +195,10 @@ export function main() {
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
expect(ast.rules.length).toEqual(1);
|
||||
|
||||
var defs = (<CssSelectorRuleAst>ast.rules[0]).block.entries;
|
||||
const defs = (<CssSelectorRuleAst>ast.rules[0]).block.entries;
|
||||
expect(defs.length).toEqual(4);
|
||||
|
||||
assertTokens((<CssDefinitionAst>defs[0]).value.tokens, ['url', '(', 'matias.css', ')']);
|
||||
@ -212,7 +212,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should parse un-named block-level CSS values', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@font-face {
|
||||
font-family: "Matias";
|
||||
font-weight: bold;
|
||||
@ -224,19 +224,19 @@ export function main() {
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
|
||||
var fontFaceRule = <CssBlockRuleAst>ast.rules[0];
|
||||
const fontFaceRule = <CssBlockRuleAst>ast.rules[0];
|
||||
expect(fontFaceRule.type).toEqual(BlockType.FontFace);
|
||||
expect(fontFaceRule.block.entries.length).toEqual(3);
|
||||
|
||||
var viewportRule = <CssBlockRuleAst>ast.rules[1];
|
||||
const viewportRule = <CssBlockRuleAst>ast.rules[1];
|
||||
expect(viewportRule.type).toEqual(BlockType.Viewport);
|
||||
expect(viewportRule.block.entries.length).toEqual(2);
|
||||
});
|
||||
|
||||
it('should parse multiple levels of semicolons', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
;;;
|
||||
@import url('something something')
|
||||
;;;;;;;;
|
||||
@ -251,24 +251,24 @@ export function main() {
|
||||
;.selector2{prop:1}}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
|
||||
var importRule = <CssInlineRuleAst>ast.rules[0];
|
||||
const importRule = <CssInlineRuleAst>ast.rules[0];
|
||||
expect(importRule.type).toEqual(BlockType.Import);
|
||||
assertTokens(importRule.value.tokens, ['url', '(', 'something something', ')']);
|
||||
|
||||
var fontFaceRule = <CssBlockRuleAst>ast.rules[1];
|
||||
const fontFaceRule = <CssBlockRuleAst>ast.rules[1];
|
||||
expect(fontFaceRule.type).toEqual(BlockType.FontFace);
|
||||
expect(fontFaceRule.block.entries.length).toEqual(2);
|
||||
|
||||
var mediaQueryRule = <CssMediaQueryRuleAst>ast.rules[2];
|
||||
const mediaQueryRule = <CssMediaQueryRuleAst>ast.rules[2];
|
||||
assertTokens(
|
||||
mediaQueryRule.query.tokens, ['all', 'and', '(', 'max-width', ':', '100', 'px', ')']);
|
||||
expect(mediaQueryRule.block.entries.length).toEqual(2);
|
||||
});
|
||||
|
||||
it('should throw an error if an unknown @value block rule is parsed', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@matias { hello: there; }
|
||||
`;
|
||||
|
||||
@ -278,22 +278,22 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should parse empty rules', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
.empty-rule { }
|
||||
.somewhat-empty-rule { /* property: value; */ }
|
||||
.non-empty-rule { property: value; }
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
|
||||
var rules = ast.rules;
|
||||
const rules = ast.rules;
|
||||
expect((<CssSelectorRuleAst>rules[0]).block.entries.length).toEqual(0);
|
||||
expect((<CssSelectorRuleAst>rules[1]).block.entries.length).toEqual(0);
|
||||
expect((<CssSelectorRuleAst>rules[2]).block.entries.length).toEqual(1);
|
||||
});
|
||||
|
||||
it('should parse the @document rule', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@document url(http://www.w3.org/),
|
||||
url-prefix(http://www.w3.org/Style/),
|
||||
domain(mozilla.org),
|
||||
@ -314,18 +314,18 @@ export function main() {
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
|
||||
var rules = ast.rules;
|
||||
var documentRule = <CssBlockDefinitionRuleAst>rules[0];
|
||||
const rules = ast.rules;
|
||||
const documentRule = <CssBlockDefinitionRuleAst>rules[0];
|
||||
expect(documentRule.type).toEqual(BlockType.Document);
|
||||
|
||||
var rule = <CssSelectorRuleAst>documentRule.block.entries[0];
|
||||
const rule = <CssSelectorRuleAst>documentRule.block.entries[0];
|
||||
expect(rule.strValue).toEqual('body');
|
||||
});
|
||||
|
||||
it('should parse the @page rule', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@page one {
|
||||
.selector { prop: value; }
|
||||
}
|
||||
@ -334,89 +334,89 @@ export function main() {
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
|
||||
var rules = ast.rules;
|
||||
const rules = ast.rules;
|
||||
|
||||
var pageRule1 = <CssBlockDefinitionRuleAst>rules[0];
|
||||
const pageRule1 = <CssBlockDefinitionRuleAst>rules[0];
|
||||
expect(pageRule1.query.strValue).toEqual('@page one');
|
||||
expect(pageRule1.query.tokens[0].strValue).toEqual('one');
|
||||
expect(pageRule1.type).toEqual(BlockType.Page);
|
||||
|
||||
var pageRule2 = <CssBlockDefinitionRuleAst>rules[1];
|
||||
const pageRule2 = <CssBlockDefinitionRuleAst>rules[1];
|
||||
expect(pageRule2.query.strValue).toEqual('@page two');
|
||||
expect(pageRule2.query.tokens[0].strValue).toEqual('two');
|
||||
expect(pageRule2.type).toEqual(BlockType.Page);
|
||||
|
||||
var selectorOne = <CssSelectorRuleAst>pageRule1.block.entries[0];
|
||||
const selectorOne = <CssSelectorRuleAst>pageRule1.block.entries[0];
|
||||
expect(selectorOne.strValue).toEqual('.selector');
|
||||
|
||||
var selectorTwo = <CssSelectorRuleAst>pageRule2.block.entries[0];
|
||||
const selectorTwo = <CssSelectorRuleAst>pageRule2.block.entries[0];
|
||||
expect(selectorTwo.strValue).toEqual('.selector2');
|
||||
});
|
||||
|
||||
it('should parse the @supports rule', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
@supports (animation-name: "rotate") {
|
||||
a:hover { animation: rotate 1s; }
|
||||
}
|
||||
`;
|
||||
|
||||
var ast = makeAst(styles);
|
||||
const ast = makeAst(styles);
|
||||
|
||||
var rules = ast.rules;
|
||||
const rules = ast.rules;
|
||||
|
||||
var supportsRule = <CssBlockDefinitionRuleAst>rules[0];
|
||||
const supportsRule = <CssBlockDefinitionRuleAst>rules[0];
|
||||
assertTokens(supportsRule.query.tokens, ['(', 'animation-name', ':', 'rotate', ')']);
|
||||
expect(supportsRule.type).toEqual(BlockType.Supports);
|
||||
|
||||
var selectorOne = <CssSelectorRuleAst>supportsRule.block.entries[0];
|
||||
const selectorOne = <CssSelectorRuleAst>supportsRule.block.entries[0];
|
||||
expect(selectorOne.strValue).toEqual('a:hover');
|
||||
});
|
||||
|
||||
it('should collect multiple errors during parsing', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
.class$value { something: something }
|
||||
@custom { something: something }
|
||||
#id { cool^: value }
|
||||
`;
|
||||
|
||||
var output = parse(styles);
|
||||
const output = parse(styles);
|
||||
expect(output.errors.length).toEqual(3);
|
||||
});
|
||||
|
||||
it('should recover from selector errors and continue parsing', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
tag& { key: value; }
|
||||
.%tag { key: value; }
|
||||
#tag$ { key: value; }
|
||||
`;
|
||||
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
const ast = output.ast;
|
||||
|
||||
expect(errors.length).toEqual(3);
|
||||
|
||||
expect(ast.rules.length).toEqual(3);
|
||||
|
||||
var rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
const rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
expect(rule1.selectors[0].strValue).toEqual('tag&');
|
||||
expect(rule1.block.entries.length).toEqual(1);
|
||||
|
||||
var rule2 = <CssSelectorRuleAst>ast.rules[1];
|
||||
const rule2 = <CssSelectorRuleAst>ast.rules[1];
|
||||
expect(rule2.selectors[0].strValue).toEqual('.%tag');
|
||||
expect(rule2.block.entries.length).toEqual(1);
|
||||
|
||||
var rule3 = <CssSelectorRuleAst>ast.rules[2];
|
||||
const rule3 = <CssSelectorRuleAst>ast.rules[2];
|
||||
expect(rule3.selectors[0].strValue).toEqual('#tag$');
|
||||
expect(rule3.block.entries.length).toEqual(1);
|
||||
});
|
||||
|
||||
it('should throw an error when parsing invalid CSS Selectors', () => {
|
||||
var styles = '.class[[prop%=value}] { style: val; }';
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
const styles = '.class[[prop%=value}] { style: val; }';
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
|
||||
expect(errors.length).toEqual(3);
|
||||
|
||||
@ -428,17 +428,17 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should throw an error if an attribute selector is not closed properly', () => {
|
||||
var styles = '.class[prop=value { style: val; }';
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
const styles = '.class[prop=value { style: val; }';
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
|
||||
expect(errors[0].msg).toMatch(/Unbalanced CSS attribute selector at column 0:12/g);
|
||||
});
|
||||
|
||||
it('should throw an error if a pseudo function selector is not closed properly', () => {
|
||||
var styles = 'body:lang(en { key:value; }';
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
const styles = 'body:lang(en { key:value; }';
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
|
||||
expect(errors[0].msg)
|
||||
.toMatch(/Character does not match expected Character value \("{" should match "\)"\)/);
|
||||
@ -446,13 +446,13 @@ export function main() {
|
||||
|
||||
it('should raise an error when a semi colon is missing from a CSS style/pair that isn\'t the last entry',
|
||||
() => {
|
||||
var styles = `.class {
|
||||
const styles = `.class {
|
||||
color: red
|
||||
background: blue
|
||||
}`;
|
||||
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
|
||||
expect(errors.length).toEqual(1);
|
||||
|
||||
@ -461,62 +461,62 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should parse the inner value of a :not() pseudo-selector as a CSS selector', () => {
|
||||
var styles = `div:not(.ignore-this-div) {
|
||||
const styles = `div:not(.ignore-this-div) {
|
||||
prop: value;
|
||||
}`;
|
||||
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
const ast = output.ast;
|
||||
|
||||
expect(errors.length).toEqual(0);
|
||||
|
||||
var rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
const rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
expect(rule1.selectors.length).toEqual(1);
|
||||
|
||||
var simpleSelector = rule1.selectors[0].selectorParts[0];
|
||||
const simpleSelector = rule1.selectors[0].selectorParts[0];
|
||||
assertTokens(simpleSelector.tokens, ['div']);
|
||||
|
||||
var pseudoSelector = simpleSelector.pseudoSelectors[0];
|
||||
const pseudoSelector = simpleSelector.pseudoSelectors[0];
|
||||
expect(pseudoSelector.name).toEqual('not');
|
||||
assertTokens(pseudoSelector.tokens, ['.', 'ignore-this-div']);
|
||||
});
|
||||
|
||||
it('should parse the inner selectors of a :host-context selector', () => {
|
||||
var styles = `body > :host-context(.a, .b, .c:hover) {
|
||||
const styles = `body > :host-context(.a, .b, .c:hover) {
|
||||
prop: value;
|
||||
}`;
|
||||
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
const ast = output.ast;
|
||||
|
||||
expect(errors.length).toEqual(0);
|
||||
|
||||
var rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
const rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
expect(rule1.selectors.length).toEqual(1);
|
||||
|
||||
var simpleSelector = rule1.selectors[0].selectorParts[1];
|
||||
var innerSelectors = simpleSelector.pseudoSelectors[0].innerSelectors;
|
||||
const simpleSelector = rule1.selectors[0].selectorParts[1];
|
||||
const innerSelectors = simpleSelector.pseudoSelectors[0].innerSelectors;
|
||||
|
||||
assertTokens(innerSelectors[0].selectorParts[0].tokens, ['.', 'a']);
|
||||
assertTokens(innerSelectors[1].selectorParts[0].tokens, ['.', 'b']);
|
||||
|
||||
var finalSelector = innerSelectors[2].selectorParts[0];
|
||||
const finalSelector = innerSelectors[2].selectorParts[0];
|
||||
assertTokens(finalSelector.tokens, ['.', 'c', ':', 'hover']);
|
||||
assertTokens(finalSelector.pseudoSelectors[0].tokens, [':', 'hover']);
|
||||
});
|
||||
|
||||
it('should raise parse errors when CSS key/value pairs are invalid', () => {
|
||||
var styles = `.class {
|
||||
const styles = `.class {
|
||||
background color: value;
|
||||
color: value
|
||||
font-size;
|
||||
font-weight
|
||||
}`;
|
||||
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
|
||||
expect(errors.length).toEqual(4);
|
||||
|
||||
@ -535,30 +535,30 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should recover from CSS key/value parse errors', () => {
|
||||
var styles = `
|
||||
const styles = `
|
||||
.problem-class { background color: red; color: white; }
|
||||
.good-boy-class { background-color: red; color: white; }
|
||||
`;
|
||||
|
||||
var output = parse(styles);
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const ast = output.ast;
|
||||
|
||||
expect(ast.rules.length).toEqual(2);
|
||||
|
||||
var rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
const rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
expect(rule1.block.entries.length).toEqual(2);
|
||||
|
||||
var style1 = <CssDefinitionAst>rule1.block.entries[0];
|
||||
const style1 = <CssDefinitionAst>rule1.block.entries[0];
|
||||
expect(style1.property.strValue).toEqual('background color');
|
||||
assertTokens(style1.value.tokens, ['red']);
|
||||
|
||||
var style2 = <CssDefinitionAst>rule1.block.entries[1];
|
||||
const style2 = <CssDefinitionAst>rule1.block.entries[1];
|
||||
expect(style2.property.strValue).toEqual('color');
|
||||
assertTokens(style2.value.tokens, ['white']);
|
||||
});
|
||||
|
||||
describe('location offsets', () => {
|
||||
var styles: string;
|
||||
let styles: string;
|
||||
|
||||
function assertMatchesOffsetAndChar(
|
||||
location: ParseLocation, expectedOffset: number, expectedChar: string): void {
|
||||
@ -570,64 +570,64 @@ export function main() {
|
||||
styles = '.problem-class { border-top-right: 1px; color: white; }\n';
|
||||
styles += '#good-boy-rule_ { background-color: #fe4; color: teal; }';
|
||||
|
||||
var output = parse(styles);
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const ast = output.ast;
|
||||
assertMatchesOffsetAndChar(ast.location.start, 0, '.');
|
||||
assertMatchesOffsetAndChar(ast.location.end, 111, '}');
|
||||
|
||||
var rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
const rule1 = <CssSelectorRuleAst>ast.rules[0];
|
||||
assertMatchesOffsetAndChar(rule1.location.start, 0, '.');
|
||||
assertMatchesOffsetAndChar(rule1.location.end, 54, '}');
|
||||
|
||||
var rule2 = <CssSelectorRuleAst>ast.rules[1];
|
||||
const rule2 = <CssSelectorRuleAst>ast.rules[1];
|
||||
assertMatchesOffsetAndChar(rule2.location.start, 56, '#');
|
||||
assertMatchesOffsetAndChar(rule2.location.end, 111, '}');
|
||||
|
||||
var selector1 = rule1.selectors[0];
|
||||
const selector1 = rule1.selectors[0];
|
||||
assertMatchesOffsetAndChar(selector1.location.start, 0, '.');
|
||||
assertMatchesOffsetAndChar(selector1.location.end, 1, 'p'); // problem-class
|
||||
|
||||
var selector2 = rule2.selectors[0];
|
||||
const selector2 = rule2.selectors[0];
|
||||
assertMatchesOffsetAndChar(selector2.location.start, 56, '#');
|
||||
assertMatchesOffsetAndChar(selector2.location.end, 57, 'g'); // good-boy-rule_
|
||||
|
||||
var block1 = rule1.block;
|
||||
const block1 = rule1.block;
|
||||
assertMatchesOffsetAndChar(block1.location.start, 15, '{');
|
||||
assertMatchesOffsetAndChar(block1.location.end, 54, '}');
|
||||
|
||||
var block2 = rule2.block;
|
||||
const block2 = rule2.block;
|
||||
assertMatchesOffsetAndChar(block2.location.start, 72, '{');
|
||||
assertMatchesOffsetAndChar(block2.location.end, 111, '}');
|
||||
|
||||
var block1def1 = <CssDefinitionAst>block1.entries[0];
|
||||
const block1def1 = <CssDefinitionAst>block1.entries[0];
|
||||
assertMatchesOffsetAndChar(block1def1.location.start, 17, 'b'); // border-top-right
|
||||
assertMatchesOffsetAndChar(block1def1.location.end, 36, 'p'); // px
|
||||
|
||||
var block1def2 = <CssDefinitionAst>block1.entries[1];
|
||||
const block1def2 = <CssDefinitionAst>block1.entries[1];
|
||||
assertMatchesOffsetAndChar(block1def2.location.start, 40, 'c'); // color
|
||||
assertMatchesOffsetAndChar(block1def2.location.end, 47, 'w'); // white
|
||||
|
||||
var block2def1 = <CssDefinitionAst>block2.entries[0];
|
||||
const block2def1 = <CssDefinitionAst>block2.entries[0];
|
||||
assertMatchesOffsetAndChar(block2def1.location.start, 74, 'b'); // background-color
|
||||
assertMatchesOffsetAndChar(block2def1.location.end, 93, 'f'); // fe4
|
||||
|
||||
var block2def2 = <CssDefinitionAst>block2.entries[1];
|
||||
const block2def2 = <CssDefinitionAst>block2.entries[1];
|
||||
assertMatchesOffsetAndChar(block2def2.location.start, 98, 'c'); // color
|
||||
assertMatchesOffsetAndChar(block2def2.location.end, 105, 't'); // teal
|
||||
|
||||
var block1value1 = block1def1.value;
|
||||
const block1value1 = block1def1.value;
|
||||
assertMatchesOffsetAndChar(block1value1.location.start, 35, '1');
|
||||
assertMatchesOffsetAndChar(block1value1.location.end, 36, 'p');
|
||||
|
||||
var block1value2 = block1def2.value;
|
||||
const block1value2 = block1def2.value;
|
||||
assertMatchesOffsetAndChar(block1value2.location.start, 47, 'w');
|
||||
assertMatchesOffsetAndChar(block1value2.location.end, 47, 'w');
|
||||
|
||||
var block2value1 = block2def1.value;
|
||||
const block2value1 = block2def1.value;
|
||||
assertMatchesOffsetAndChar(block2value1.location.start, 92, '#');
|
||||
assertMatchesOffsetAndChar(block2value1.location.end, 93, 'f');
|
||||
|
||||
var block2value2 = block2def2.value;
|
||||
const block2value2 = block2def2.value;
|
||||
assertMatchesOffsetAndChar(block2value2.location.start, 105, 't');
|
||||
assertMatchesOffsetAndChar(block2value2.location.end, 105, 't');
|
||||
});
|
||||
@ -635,18 +635,18 @@ export function main() {
|
||||
it('should collect the source span location of each AST node with media query data', () => {
|
||||
styles = '@media (all and max-width: 100px) { a { display:none; } }';
|
||||
|
||||
var output = parse(styles);
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const ast = output.ast;
|
||||
|
||||
var mediaQuery = <CssMediaQueryRuleAst>ast.rules[0];
|
||||
const mediaQuery = <CssMediaQueryRuleAst>ast.rules[0];
|
||||
assertMatchesOffsetAndChar(mediaQuery.location.start, 0, '@');
|
||||
assertMatchesOffsetAndChar(mediaQuery.location.end, 56, '}');
|
||||
|
||||
var predicate = mediaQuery.query;
|
||||
const predicate = mediaQuery.query;
|
||||
assertMatchesOffsetAndChar(predicate.location.start, 0, '@');
|
||||
assertMatchesOffsetAndChar(predicate.location.end, 32, ')');
|
||||
|
||||
var rule = <CssSelectorRuleAst>mediaQuery.block.entries[0];
|
||||
const rule = <CssSelectorRuleAst>mediaQuery.block.entries[0];
|
||||
assertMatchesOffsetAndChar(rule.location.start, 36, 'a');
|
||||
assertMatchesOffsetAndChar(rule.location.end, 54, '}');
|
||||
});
|
||||
@ -657,18 +657,18 @@ export function main() {
|
||||
styles += '100% { transform: rotate(360deg) scale(2); }';
|
||||
styles += '}';
|
||||
|
||||
var output = parse(styles);
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const ast = output.ast;
|
||||
|
||||
var keyframes = <CssKeyframeRuleAst>ast.rules[0];
|
||||
const keyframes = <CssKeyframeRuleAst>ast.rules[0];
|
||||
assertMatchesOffsetAndChar(keyframes.location.start, 0, '@');
|
||||
assertMatchesOffsetAndChar(keyframes.location.end, 108, '}');
|
||||
|
||||
var step1 = <CssKeyframeDefinitionAst>keyframes.block.entries[0];
|
||||
const step1 = <CssKeyframeDefinitionAst>keyframes.block.entries[0];
|
||||
assertMatchesOffsetAndChar(step1.location.start, 30, 'f');
|
||||
assertMatchesOffsetAndChar(step1.location.end, 62, '}');
|
||||
|
||||
var step2 = <CssKeyframeDefinitionAst>keyframes.block.entries[1];
|
||||
const step2 = <CssKeyframeDefinitionAst>keyframes.block.entries[1];
|
||||
assertMatchesOffsetAndChar(step2.location.start, 64, '1');
|
||||
assertMatchesOffsetAndChar(step2.location.end, 107, '}');
|
||||
});
|
||||
@ -676,14 +676,14 @@ export function main() {
|
||||
it('should collect the source span location of each AST node with an inline rule', () => {
|
||||
styles = '@import url(something.css)';
|
||||
|
||||
var output = parse(styles);
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const ast = output.ast;
|
||||
|
||||
var rule = <CssInlineRuleAst>ast.rules[0];
|
||||
const rule = <CssInlineRuleAst>ast.rules[0];
|
||||
assertMatchesOffsetAndChar(rule.location.start, 0, '@');
|
||||
assertMatchesOffsetAndChar(rule.location.end, 25, ')');
|
||||
|
||||
var value = rule.value;
|
||||
const value = rule.value;
|
||||
assertMatchesOffsetAndChar(value.location.start, 8, 'u');
|
||||
assertMatchesOffsetAndChar(value.location.end, 25, ')');
|
||||
});
|
||||
@ -691,8 +691,8 @@ export function main() {
|
||||
it('should property collect the start/end locations with an invalid stylesheet', () => {
|
||||
styles = '#id { something: value';
|
||||
|
||||
var output = parse(styles);
|
||||
var ast = output.ast;
|
||||
const output = parse(styles);
|
||||
const ast = output.ast;
|
||||
|
||||
assertMatchesOffsetAndChar(ast.location.start, 0, '#');
|
||||
assertMatchesOffsetAndChar(ast.location.end, 22, undefined);
|
||||
@ -701,7 +701,7 @@ export function main() {
|
||||
|
||||
it('should parse minified CSS content properly', () => {
|
||||
// this code was taken from the angular.io webpage's CSS code
|
||||
var styles = `
|
||||
const styles = `
|
||||
.is-hidden{display:none!important}
|
||||
.is-visible{display:block!important}
|
||||
.is-visually-hidden{height:1px;width:1px;overflow:hidden;opacity:0.01;position:absolute;bottom:0;right:0;z-index:1}
|
||||
@ -712,17 +712,17 @@ export function main() {
|
||||
.grid-fluid .c1.na,.grid-fixed .c1.na,.grid-fluid .c2.na,.grid-fixed .c2.na,.grid-fluid .c3.na,.grid-fixed .c3.na,.grid-fluid .c4.na,.grid-fixed .c4.na,.grid-fluid .c5.na,.grid-fixed .c5.na,.grid-fluid .c6.na,.grid-fixed .c6.na,.grid-fluid .c7.na,.grid-fixed .c7.na,.grid-fluid .c8.na,.grid-fixed .c8.na,.grid-fluid .c9.na,.grid-fixed .c9.na,.grid-fluid .c10.na,.grid-fixed .c10.na,.grid-fluid .c11.na,.grid-fixed .c11.na,.grid-fluid .c12.na,.grid-fixed .c12.na{margin-right:0}
|
||||
`;
|
||||
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
expect(errors.length).toEqual(0);
|
||||
|
||||
var ast = output.ast;
|
||||
const ast = output.ast;
|
||||
expect(ast.rules.length).toEqual(8);
|
||||
});
|
||||
|
||||
it('should parse a snippet of keyframe code from animate.css properly', () => {
|
||||
// this code was taken from the angular.io webpage's CSS code
|
||||
var styles = `
|
||||
const styles = `
|
||||
@charset "UTF-8";
|
||||
|
||||
/*!
|
||||
@ -787,14 +787,14 @@ export function main() {
|
||||
}
|
||||
`;
|
||||
|
||||
var output = parse(styles);
|
||||
var errors = output.errors;
|
||||
const output = parse(styles);
|
||||
const errors = output.errors;
|
||||
expect(errors.length).toEqual(0);
|
||||
|
||||
var ast = output.ast;
|
||||
const ast = output.ast;
|
||||
expect(ast.rules.length).toEqual(6);
|
||||
|
||||
var finalRule = <CssBlockRuleAst>ast.rules[ast.rules.length - 1];
|
||||
const finalRule = <CssBlockRuleAst>ast.rules[ast.rules.length - 1];
|
||||
expect(finalRule.type).toEqual(BlockType.Keyframes);
|
||||
expect(finalRule.block.entries.length).toEqual(4);
|
||||
});
|
||||
|
@ -14,7 +14,7 @@ import {isPresent} from '../../src/facade/lang';
|
||||
|
||||
function _assertTokens(tokens: CssToken[], valuesArr: string[]): void {
|
||||
expect(tokens.length).toEqual(valuesArr.length);
|
||||
for (var i = 0; i < tokens.length; i++) {
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
expect(tokens[i].strValue == valuesArr[i]);
|
||||
}
|
||||
}
|
||||
@ -118,8 +118,8 @@ function _getCaptureAst(capture: any[], index = 0): CssAst {
|
||||
|
||||
export function main() {
|
||||
function parse(cssCode: string, ignoreErrors: boolean = false) {
|
||||
var output = new CssParser().parse(cssCode, 'some-fake-css-file.css');
|
||||
var errors = output.errors;
|
||||
const output = new CssParser().parse(cssCode, 'some-fake-css-file.css');
|
||||
const errors = output.errors;
|
||||
if (errors.length > 0 && !ignoreErrors) {
|
||||
throw new Error(errors.map((error: CssParseError) => error.msg).join(', '));
|
||||
}
|
||||
@ -127,11 +127,11 @@ export function main() {
|
||||
}
|
||||
|
||||
describe('CSS parsing and visiting', () => {
|
||||
var ast: CssStyleSheetAst;
|
||||
var context = {};
|
||||
let ast: CssStyleSheetAst;
|
||||
const context = {};
|
||||
|
||||
beforeEach(() => {
|
||||
var cssCode = `
|
||||
const cssCode = `
|
||||
.rule1 { prop1: value1 }
|
||||
.rule2 { prop2: value2 }
|
||||
|
||||
@ -154,168 +154,168 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should parse and visit a stylesheet', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssStyleSheet'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssStyleSheet'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var capture = captures[0];
|
||||
const capture = captures[0];
|
||||
expect(capture[0]).toEqual(ast);
|
||||
expect(capture[1]).toEqual(context);
|
||||
});
|
||||
|
||||
it('should parse and visit each of the stylesheet selectors', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssSelectorRule'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssSelectorRule'];
|
||||
|
||||
expect(captures.length).toEqual(3);
|
||||
|
||||
var rule1 = <CssSelectorRuleAst>_getCaptureAst(captures, 0);
|
||||
const rule1 = <CssSelectorRuleAst>_getCaptureAst(captures, 0);
|
||||
expect(rule1).toEqual(ast.rules[0]);
|
||||
|
||||
var firstSelector = rule1.selectors[0];
|
||||
var firstSimpleSelector = firstSelector.selectorParts[0];
|
||||
const firstSelector = rule1.selectors[0];
|
||||
const firstSimpleSelector = firstSelector.selectorParts[0];
|
||||
_assertTokens(firstSimpleSelector.tokens, ['.', 'rule1']);
|
||||
|
||||
var rule2 = <CssSelectorRuleAst>_getCaptureAst(captures, 1);
|
||||
const rule2 = <CssSelectorRuleAst>_getCaptureAst(captures, 1);
|
||||
expect(rule2).toEqual(ast.rules[1]);
|
||||
|
||||
var secondSelector = rule2.selectors[0];
|
||||
var secondSimpleSelector = secondSelector.selectorParts[0];
|
||||
const secondSelector = rule2.selectors[0];
|
||||
const secondSimpleSelector = secondSelector.selectorParts[0];
|
||||
_assertTokens(secondSimpleSelector.tokens, ['.', 'rule2']);
|
||||
|
||||
var rule3 = <CssSelectorRuleAst>_getCaptureAst(captures, 2);
|
||||
const rule3 = <CssSelectorRuleAst>_getCaptureAst(captures, 2);
|
||||
expect(rule3).toEqual((<CssMediaQueryRuleAst>ast.rules[2]).block.entries[0]);
|
||||
|
||||
var thirdSelector = rule3.selectors[0];
|
||||
var thirdSimpleSelector = thirdSelector.selectorParts[0];
|
||||
const thirdSelector = rule3.selectors[0];
|
||||
const thirdSimpleSelector = thirdSelector.selectorParts[0];
|
||||
_assertTokens(thirdSimpleSelector.tokens, ['#', 'rule3']);
|
||||
});
|
||||
|
||||
it('should parse and visit each of the stylesheet style key/value definitions', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssDefinition'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssDefinition'];
|
||||
|
||||
expect(captures.length).toEqual(5);
|
||||
|
||||
var def1 = <CssDefinitionAst>_getCaptureAst(captures, 0);
|
||||
const def1 = <CssDefinitionAst>_getCaptureAst(captures, 0);
|
||||
expect(def1.property.strValue).toEqual('prop1');
|
||||
expect(def1.value.tokens[0].strValue).toEqual('value1');
|
||||
|
||||
var def2 = <CssDefinitionAst>_getCaptureAst(captures, 1);
|
||||
const def2 = <CssDefinitionAst>_getCaptureAst(captures, 1);
|
||||
expect(def2.property.strValue).toEqual('prop2');
|
||||
expect(def2.value.tokens[0].strValue).toEqual('value2');
|
||||
|
||||
var def3 = <CssDefinitionAst>_getCaptureAst(captures, 2);
|
||||
const def3 = <CssDefinitionAst>_getCaptureAst(captures, 2);
|
||||
expect(def3.property.strValue).toEqual('prop3');
|
||||
expect(def3.value.tokens[0].strValue).toEqual('value3');
|
||||
|
||||
var def4 = <CssDefinitionAst>_getCaptureAst(captures, 3);
|
||||
const def4 = <CssDefinitionAst>_getCaptureAst(captures, 3);
|
||||
expect(def4.property.strValue).toEqual('prop4');
|
||||
expect(def4.value.tokens[0].strValue).toEqual('value4');
|
||||
|
||||
var def5 = <CssDefinitionAst>_getCaptureAst(captures, 4);
|
||||
const def5 = <CssDefinitionAst>_getCaptureAst(captures, 4);
|
||||
expect(def5.property.strValue).toEqual('prop5');
|
||||
expect(def5.value.tokens[0].strValue).toEqual('value5');
|
||||
});
|
||||
|
||||
it('should parse and visit the associated media query values', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssMediaQueryRule'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssMediaQueryRule'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var query1 = <CssMediaQueryRuleAst>_getCaptureAst(captures, 0);
|
||||
const query1 = <CssMediaQueryRuleAst>_getCaptureAst(captures, 0);
|
||||
_assertTokens(query1.query.tokens, ['all', 'and', '(', 'max-width', '100', 'px', ')']);
|
||||
expect(query1.block.entries.length).toEqual(1);
|
||||
});
|
||||
|
||||
it('should capture the media query predicate', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssAtRulePredicate'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssAtRulePredicate'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var predicate = <CssAtRulePredicateAst>_getCaptureAst(captures, 0);
|
||||
const predicate = <CssAtRulePredicateAst>_getCaptureAst(captures, 0);
|
||||
expect(predicate.strValue).toEqual('@media all (max-width: 100px)');
|
||||
});
|
||||
|
||||
it('should parse and visit the associated "@inline" rule values', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssInlineRule'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssInlineRule'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var inline1 = <CssInlineRuleAst>_getCaptureAst(captures, 0);
|
||||
const inline1 = <CssInlineRuleAst>_getCaptureAst(captures, 0);
|
||||
expect(inline1.type).toEqual(BlockType.Import);
|
||||
_assertTokens(inline1.value.tokens, ['url', '(', 'file.css', ')']);
|
||||
});
|
||||
|
||||
it('should parse and visit the keyframe blocks', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssKeyframeRule'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssKeyframeRule'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var keyframe1 = <CssKeyframeRuleAst>_getCaptureAst(captures, 0);
|
||||
const keyframe1 = <CssKeyframeRuleAst>_getCaptureAst(captures, 0);
|
||||
expect(keyframe1.name.strValue).toEqual('rotate');
|
||||
expect(keyframe1.block.entries.length).toEqual(2);
|
||||
});
|
||||
|
||||
it('should parse and visit the associated keyframe rules', () => {
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssKeyframeDefinition'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssKeyframeDefinition'];
|
||||
|
||||
expect(captures.length).toEqual(2);
|
||||
|
||||
var def1 = <CssKeyframeDefinitionAst>_getCaptureAst(captures, 0);
|
||||
const def1 = <CssKeyframeDefinitionAst>_getCaptureAst(captures, 0);
|
||||
_assertTokens(def1.steps, ['from']);
|
||||
expect(def1.block.entries.length).toEqual(1);
|
||||
|
||||
var def2 = <CssKeyframeDefinitionAst>_getCaptureAst(captures, 1);
|
||||
const def2 = <CssKeyframeDefinitionAst>_getCaptureAst(captures, 1);
|
||||
_assertTokens(def2.steps, ['50%', '100%']);
|
||||
expect(def2.block.entries.length).toEqual(1);
|
||||
});
|
||||
|
||||
it('should visit an unknown `@` rule', () => {
|
||||
var cssCode = `
|
||||
const cssCode = `
|
||||
@someUnknownRule param {
|
||||
one two three
|
||||
}
|
||||
`;
|
||||
ast = parse(cssCode, true);
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssUnknownRule'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssUnknownRule'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var rule = <CssUnknownRuleAst>_getCaptureAst(captures, 0);
|
||||
const rule = <CssUnknownRuleAst>_getCaptureAst(captures, 0);
|
||||
expect(rule.ruleName).toEqual('@someUnknownRule');
|
||||
|
||||
_assertTokens(rule.tokens, ['param', '{', 'one', 'two', 'three', '}']);
|
||||
});
|
||||
|
||||
it('should collect an invalid list of tokens before a valid selector', () => {
|
||||
var cssCode = 'one two three four five; selector { }';
|
||||
const cssCode = 'one two three four five; selector { }';
|
||||
ast = parse(cssCode, true);
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssUnknownTokenList'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssUnknownTokenList'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var rule = <CssUnknownTokenListAst>_getCaptureAst(captures, 0);
|
||||
const rule = <CssUnknownTokenListAst>_getCaptureAst(captures, 0);
|
||||
_assertTokens(rule.tokens, ['one', 'two', 'three', 'four', 'five']);
|
||||
});
|
||||
|
||||
it('should collect an invalid list of tokens after a valid selector', () => {
|
||||
var cssCode = 'selector { } six seven eight';
|
||||
const cssCode = 'selector { } six seven eight';
|
||||
ast = parse(cssCode, true);
|
||||
var visitor = new MyVisitor(ast, context);
|
||||
var captures = visitor.captures['visitCssUnknownTokenList'];
|
||||
const visitor = new MyVisitor(ast, context);
|
||||
const captures = visitor.captures['visitCssUnknownTokenList'];
|
||||
|
||||
expect(captures.length).toEqual(1);
|
||||
|
||||
var rule = <CssUnknownTokenListAst>_getCaptureAst(captures, 0);
|
||||
const rule = <CssUnknownTokenListAst>_getCaptureAst(captures, 0);
|
||||
_assertTokens(rule.tokens, ['six', 'seven', 'eight']);
|
||||
});
|
||||
});
|
||||
|
@ -38,7 +38,7 @@ export function main() {
|
||||
describe('normalizeTemplateSync', () => {
|
||||
it('should store the template',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
let template = normalizer.normalizeTemplateSync({
|
||||
const template = normalizer.normalizeTemplateSync({
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
encapsulation: null,
|
||||
@ -53,7 +53,7 @@ export function main() {
|
||||
|
||||
it('should resolve styles on the annotation against the moduleUrl',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
let template = normalizer.normalizeTemplateSync({
|
||||
const template = normalizer.normalizeTemplateSync({
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
encapsulation: null,
|
||||
@ -67,7 +67,7 @@ export function main() {
|
||||
|
||||
it('should resolve styles in the template against the moduleUrl',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
let template = normalizer.normalizeTemplateSync({
|
||||
const template = normalizer.normalizeTemplateSync({
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
encapsulation: null,
|
||||
@ -81,7 +81,7 @@ export function main() {
|
||||
|
||||
it('should use ViewEncapsulation.Emulated by default',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
let template = normalizer.normalizeTemplateSync({
|
||||
const template = normalizer.normalizeTemplateSync({
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
encapsulation: null,
|
||||
@ -98,7 +98,7 @@ export function main() {
|
||||
[CompilerConfig, DirectiveNormalizer],
|
||||
(config: CompilerConfig, normalizer: DirectiveNormalizer) => {
|
||||
config.defaultEncapsulation = ViewEncapsulation.None;
|
||||
let template = normalizer.normalizeTemplateSync({
|
||||
const template = normalizer.normalizeTemplateSync({
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
encapsulation: null,
|
||||
@ -255,7 +255,7 @@ export function main() {
|
||||
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
|
||||
resourceLoader: MockResourceLoader) => {
|
||||
resourceLoader.expect('package:some/module/cmp.html', 'a');
|
||||
var prenormMeta = {
|
||||
const prenormMeta = {
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
templateUrl: 'cmp.html',
|
||||
@ -279,8 +279,8 @@ export function main() {
|
||||
it('should store the viewEncapsulationin the result',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
|
||||
var viewEncapsulation = ViewEncapsulation.Native;
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const viewEncapsulation = ViewEncapsulation.Native;
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -294,7 +294,7 @@ export function main() {
|
||||
|
||||
it('should keep the template as html',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -308,7 +308,7 @@ export function main() {
|
||||
|
||||
it('should collect ngContent',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -322,7 +322,7 @@ export function main() {
|
||||
|
||||
it('should normalize ngContent wildcard selector',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -337,7 +337,7 @@ export function main() {
|
||||
|
||||
it('should collect top level styles in the template',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -351,7 +351,7 @@ export function main() {
|
||||
|
||||
it('should collect styles inside in elements',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -365,7 +365,7 @@ export function main() {
|
||||
|
||||
it('should collect styleUrls in the template',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -379,7 +379,7 @@ export function main() {
|
||||
|
||||
it('should collect styleUrls in elements',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -393,7 +393,7 @@ export function main() {
|
||||
|
||||
it('should ignore link elements with non stylesheet rel attribute',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -407,7 +407,7 @@ export function main() {
|
||||
|
||||
it('should ignore link elements with absolute urls but non package: scheme',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -421,7 +421,7 @@ export function main() {
|
||||
|
||||
it('should extract @import style urls into styleAbsUrl',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -436,7 +436,7 @@ export function main() {
|
||||
|
||||
it('should not resolve relative urls in inline styles',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -450,7 +450,7 @@ export function main() {
|
||||
|
||||
it('should resolve relative style urls in styleUrls',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -465,7 +465,7 @@ export function main() {
|
||||
|
||||
it('should resolve relative style urls in styleUrls with http directive url',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_HTTP_MODULE_URL,
|
||||
@ -480,7 +480,7 @@ export function main() {
|
||||
|
||||
it('should normalize ViewEncapsulation.Emulated to ViewEncapsulation.None if there are no styles nor stylesheets',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -494,7 +494,7 @@ export function main() {
|
||||
|
||||
it('should ignore ng-content in elements with ngNonBindable',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -509,7 +509,7 @@ export function main() {
|
||||
|
||||
it('should still collect <style> in elements with ngNonBindable',
|
||||
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
|
||||
var template = normalizer.normalizeLoadedTemplate(
|
||||
const template = normalizer.normalizeLoadedTemplate(
|
||||
{
|
||||
componentType: SomeComp,
|
||||
moduleUrl: SOME_MODULE_URL,
|
||||
@ -526,7 +526,7 @@ export function main() {
|
||||
|
||||
function programResourceLoaderSpy(spy: SpyResourceLoader, results: {[key: string]: string}) {
|
||||
spy.spy('get').and.callFake((url: string): Promise<any> => {
|
||||
var result = results[url];
|
||||
const result = results[url];
|
||||
if (result) {
|
||||
return Promise.resolve(result);
|
||||
} else {
|
||||
|
@ -15,7 +15,7 @@ import {ViewMetadata} from './private_import_core';
|
||||
|
||||
export function main() {
|
||||
describe('MockDirectiveResolver', () => {
|
||||
var dirResolver: MockDirectiveResolver;
|
||||
let dirResolver: MockDirectiveResolver;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule(
|
||||
@ -29,33 +29,33 @@ export function main() {
|
||||
describe('Directive overriding', () => {
|
||||
it('should fallback to the default DirectiveResolver when templates are not overridden',
|
||||
() => {
|
||||
var ngModule = dirResolver.resolve(SomeComponent);
|
||||
const ngModule = dirResolver.resolve(SomeComponent);
|
||||
expect(ngModule.selector).toEqual('cmp');
|
||||
});
|
||||
|
||||
it('should allow overriding the @Directive', () => {
|
||||
dirResolver.setDirective(SomeComponent, new Component({selector: 'someOtherSelector'}));
|
||||
var metadata = dirResolver.resolve(SomeComponent);
|
||||
const metadata = dirResolver.resolve(SomeComponent);
|
||||
expect(metadata.selector).toEqual('someOtherSelector');
|
||||
});
|
||||
});
|
||||
|
||||
describe('View overriding', () => {
|
||||
it('should fallback to the default ViewResolver when templates are not overridden', () => {
|
||||
var view = <Component>dirResolver.resolve(SomeComponent);
|
||||
const view = <Component>dirResolver.resolve(SomeComponent);
|
||||
expect(view.template).toEqual('template');
|
||||
});
|
||||
|
||||
it('should allow overriding the @View', () => {
|
||||
dirResolver.setView(SomeComponent, new ViewMetadata({template: 'overridden template'}));
|
||||
var view = <Component>dirResolver.resolve(SomeComponent);
|
||||
const view = <Component>dirResolver.resolve(SomeComponent);
|
||||
expect(view.template).toEqual('overridden template');
|
||||
});
|
||||
|
||||
it('should allow overriding a view after it has been resolved', () => {
|
||||
dirResolver.resolve(SomeComponent);
|
||||
dirResolver.setView(SomeComponent, new ViewMetadata({template: 'overridden template'}));
|
||||
var view = <Component>dirResolver.resolve(SomeComponent);
|
||||
const view = <Component>dirResolver.resolve(SomeComponent);
|
||||
expect(view.template).toEqual('overridden template');
|
||||
});
|
||||
});
|
||||
@ -63,21 +63,21 @@ export function main() {
|
||||
describe('inline template definition overriding', () => {
|
||||
it('should allow overriding the default template', () => {
|
||||
dirResolver.setInlineTemplate(SomeComponent, 'overridden template');
|
||||
var view = <Component>dirResolver.resolve(SomeComponent);
|
||||
const view = <Component>dirResolver.resolve(SomeComponent);
|
||||
expect(view.template).toEqual('overridden template');
|
||||
});
|
||||
|
||||
it('should allow overriding an overridden @View', () => {
|
||||
dirResolver.setView(SomeComponent, new ViewMetadata({template: 'overridden template'}));
|
||||
dirResolver.setInlineTemplate(SomeComponent, 'overridden template x 2');
|
||||
var view = <Component>dirResolver.resolve(SomeComponent);
|
||||
const view = <Component>dirResolver.resolve(SomeComponent);
|
||||
expect(view.template).toEqual('overridden template x 2');
|
||||
});
|
||||
|
||||
it('should allow overriding a view after it has been resolved', () => {
|
||||
dirResolver.resolve(SomeComponent);
|
||||
dirResolver.setInlineTemplate(SomeComponent, 'overridden template');
|
||||
var view = <Component>dirResolver.resolve(SomeComponent);
|
||||
const view = <Component>dirResolver.resolve(SomeComponent);
|
||||
expect(view.template).toEqual('overridden template');
|
||||
});
|
||||
});
|
||||
|
@ -62,19 +62,19 @@ export function main() {
|
||||
describe('lexer', () => {
|
||||
describe('token', () => {
|
||||
it('should tokenize a simple identifier', () => {
|
||||
var tokens: number[] = lex('j');
|
||||
const tokens: number[] = lex('j');
|
||||
expect(tokens.length).toEqual(1);
|
||||
expectIdentifierToken(tokens[0], 0, 'j');
|
||||
});
|
||||
|
||||
it('should tokenize "this"', () => {
|
||||
var tokens: number[] = lex('this');
|
||||
const tokens: number[] = lex('this');
|
||||
expect(tokens.length).toEqual(1);
|
||||
expectKeywordToken(tokens[0], 0, 'this');
|
||||
});
|
||||
|
||||
it('should tokenize a dotted identifier', () => {
|
||||
var tokens: number[] = lex('j.k');
|
||||
const tokens: number[] = lex('j.k');
|
||||
expect(tokens.length).toEqual(3);
|
||||
expectIdentifierToken(tokens[0], 0, 'j');
|
||||
expectCharacterToken(tokens[1], 1, '.');
|
||||
@ -82,20 +82,20 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize an operator', () => {
|
||||
var tokens: number[] = lex('j-k');
|
||||
const tokens: number[] = lex('j-k');
|
||||
expect(tokens.length).toEqual(3);
|
||||
expectOperatorToken(tokens[1], 1, '-');
|
||||
});
|
||||
|
||||
it('should tokenize an indexed operator', () => {
|
||||
var tokens: number[] = lex('j[k]');
|
||||
const tokens: number[] = lex('j[k]');
|
||||
expect(tokens.length).toEqual(4);
|
||||
expectCharacterToken(tokens[1], 1, '[');
|
||||
expectCharacterToken(tokens[3], 3, ']');
|
||||
});
|
||||
|
||||
it('should tokenize numbers', () => {
|
||||
var tokens: number[] = lex('88');
|
||||
const tokens: number[] = lex('88');
|
||||
expect(tokens.length).toEqual(1);
|
||||
expectNumberToken(tokens[0], 0, 88);
|
||||
});
|
||||
@ -110,7 +110,7 @@ export function main() {
|
||||
() => { expectStringToken(lex('"a\\""')[0], 0, 'a"'); });
|
||||
|
||||
it('should tokenize a string', () => {
|
||||
var tokens: Token[] = lex('j-a.bc[22]+1.3|f:\'a\\\'c\':"d\\"e"');
|
||||
const tokens: Token[] = lex('j-a.bc[22]+1.3|f:\'a\\\'c\':"d\\"e"');
|
||||
expectIdentifierToken(tokens[0], 0, 'j');
|
||||
expectOperatorToken(tokens[1], 1, '-');
|
||||
expectIdentifierToken(tokens[2], 2, 'a');
|
||||
@ -130,39 +130,39 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize undefined', () => {
|
||||
var tokens: Token[] = lex('undefined');
|
||||
const tokens: Token[] = lex('undefined');
|
||||
expectKeywordToken(tokens[0], 0, 'undefined');
|
||||
expect(tokens[0].isKeywordUndefined()).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore whitespace', () => {
|
||||
var tokens: Token[] = lex('a \t \n \r b');
|
||||
const tokens: Token[] = lex('a \t \n \r b');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectIdentifierToken(tokens[1], 8, 'b');
|
||||
});
|
||||
|
||||
it('should tokenize quoted string', () => {
|
||||
var str = '[\'\\\'\', "\\""]';
|
||||
var tokens: Token[] = lex(str);
|
||||
const str = '[\'\\\'\', "\\""]';
|
||||
const tokens: Token[] = lex(str);
|
||||
expectStringToken(tokens[1], 1, '\'');
|
||||
expectStringToken(tokens[3], 7, '"');
|
||||
});
|
||||
|
||||
it('should tokenize escaped quoted string', () => {
|
||||
var str = '"\\"\\n\\f\\r\\t\\v\\u00A0"';
|
||||
var tokens: Token[] = lex(str);
|
||||
const str = '"\\"\\n\\f\\r\\t\\v\\u00A0"';
|
||||
const tokens: Token[] = lex(str);
|
||||
expect(tokens.length).toEqual(1);
|
||||
expect(tokens[0].toString()).toEqual('"\n\f\r\t\v\u00A0');
|
||||
});
|
||||
|
||||
it('should tokenize unicode', () => {
|
||||
var tokens: Token[] = lex('"\\u00A0"');
|
||||
const tokens: Token[] = lex('"\\u00A0"');
|
||||
expect(tokens.length).toEqual(1);
|
||||
expect(tokens[0].toString()).toEqual('\u00a0');
|
||||
});
|
||||
|
||||
it('should tokenize relation', () => {
|
||||
var tokens: Token[] = lex('! == != < > <= >= === !==');
|
||||
const tokens: Token[] = lex('! == != < > <= >= === !==');
|
||||
expectOperatorToken(tokens[0], 0, '!');
|
||||
expectOperatorToken(tokens[1], 2, '==');
|
||||
expectOperatorToken(tokens[2], 5, '!=');
|
||||
@ -175,7 +175,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize statements', () => {
|
||||
var tokens: Token[] = lex('a;b;');
|
||||
const tokens: Token[] = lex('a;b;');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectCharacterToken(tokens[1], 1, ';');
|
||||
expectIdentifierToken(tokens[2], 2, 'b');
|
||||
@ -183,19 +183,19 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should tokenize function invocation', () => {
|
||||
var tokens: Token[] = lex('a()');
|
||||
const tokens: Token[] = lex('a()');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectCharacterToken(tokens[1], 1, '(');
|
||||
expectCharacterToken(tokens[2], 2, ')');
|
||||
});
|
||||
|
||||
it('should tokenize simple method invocations', () => {
|
||||
var tokens: Token[] = lex('a.method()');
|
||||
const tokens: Token[] = lex('a.method()');
|
||||
expectIdentifierToken(tokens[2], 2, 'method');
|
||||
});
|
||||
|
||||
it('should tokenize method invocation', () => {
|
||||
var tokens: Token[] = lex('a.b.c (d) - e.f()');
|
||||
const tokens: Token[] = lex('a.b.c (d) - e.f()');
|
||||
expectIdentifierToken(tokens[0], 0, 'a');
|
||||
expectCharacterToken(tokens[1], 1, '.');
|
||||
expectIdentifierToken(tokens[2], 2, 'b');
|
||||
|
@ -49,28 +49,28 @@ export function main() {
|
||||
}
|
||||
|
||||
function checkInterpolation(exp: string, expected?: string) {
|
||||
var ast = parseInterpolation(exp);
|
||||
const ast = parseInterpolation(exp);
|
||||
if (isBlank(expected)) expected = exp;
|
||||
expect(unparse(ast)).toEqual(expected);
|
||||
validate(ast);
|
||||
}
|
||||
|
||||
function checkBinding(exp: string, expected?: string) {
|
||||
var ast = parseBinding(exp);
|
||||
const ast = parseBinding(exp);
|
||||
if (isBlank(expected)) expected = exp;
|
||||
expect(unparse(ast)).toEqual(expected);
|
||||
validate(ast);
|
||||
}
|
||||
|
||||
function checkAction(exp: string, expected?: string) {
|
||||
var ast = parseAction(exp);
|
||||
const ast = parseAction(exp);
|
||||
if (isBlank(expected)) expected = exp;
|
||||
expect(unparse(ast)).toEqual(expected);
|
||||
validate(ast);
|
||||
}
|
||||
|
||||
function expectError(ast: {errors: ParserError[]}, message: string) {
|
||||
for (var error of ast.errors) {
|
||||
for (const error of ast.errors) {
|
||||
if (error.message.indexOf(message) >= 0) {
|
||||
return;
|
||||
}
|
||||
@ -344,7 +344,7 @@ export function main() {
|
||||
() => { expect(keys(parseTemplateBindings('a'))).toEqual(['a']); });
|
||||
|
||||
it('should only allow identifier, string, or keyword including dashes as keys', () => {
|
||||
var bindings = parseTemplateBindings('a:\'b\'');
|
||||
let bindings = parseTemplateBindings('a:\'b\'');
|
||||
expect(keys(bindings)).toEqual(['a']);
|
||||
|
||||
bindings = parseTemplateBindings('\'a\':\'b\'');
|
||||
@ -363,7 +363,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should detect expressions as value', () => {
|
||||
var bindings = parseTemplateBindings('a:b');
|
||||
let bindings = parseTemplateBindings('a:b');
|
||||
expect(exprSources(bindings)).toEqual(['b']);
|
||||
|
||||
bindings = parseTemplateBindings('a:1+1');
|
||||
@ -371,12 +371,12 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should detect names as value', () => {
|
||||
var bindings = parseTemplateBindings('a:let b');
|
||||
const bindings = parseTemplateBindings('a:let b');
|
||||
expect(keyValues(bindings)).toEqual(['a', 'let b=\$implicit']);
|
||||
});
|
||||
|
||||
it('should allow space and colon as separators', () => {
|
||||
var bindings = parseTemplateBindings('a:b');
|
||||
let bindings = parseTemplateBindings('a:b');
|
||||
expect(keys(bindings)).toEqual(['a']);
|
||||
expect(exprSources(bindings)).toEqual(['b']);
|
||||
|
||||
@ -386,24 +386,24 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should allow multiple pairs', () => {
|
||||
var bindings = parseTemplateBindings('a 1 b 2');
|
||||
const bindings = parseTemplateBindings('a 1 b 2');
|
||||
expect(keys(bindings)).toEqual(['a', 'aB']);
|
||||
expect(exprSources(bindings)).toEqual(['1 ', '2']);
|
||||
});
|
||||
|
||||
it('should store the sources in the result', () => {
|
||||
var bindings = parseTemplateBindings('a 1,b 2');
|
||||
const bindings = parseTemplateBindings('a 1,b 2');
|
||||
expect(bindings[0].expression.source).toEqual('1');
|
||||
expect(bindings[1].expression.source).toEqual('2');
|
||||
});
|
||||
|
||||
it('should store the passed-in location', () => {
|
||||
var bindings = parseTemplateBindings('a 1,b 2', 'location');
|
||||
const bindings = parseTemplateBindings('a 1,b 2', 'location');
|
||||
expect(bindings[0].expression.location).toEqual('location');
|
||||
});
|
||||
|
||||
it('should support let notation', () => {
|
||||
var bindings = parseTemplateBindings('let i');
|
||||
let bindings = parseTemplateBindings('let i');
|
||||
expect(keyValues(bindings)).toEqual(['let i=\$implicit']);
|
||||
|
||||
bindings = parseTemplateBindings('let i');
|
||||
@ -431,8 +431,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should parse pipes', () => {
|
||||
var bindings = parseTemplateBindings('key value|pipe');
|
||||
var ast = bindings[0].expression.ast;
|
||||
const bindings = parseTemplateBindings('key value|pipe');
|
||||
const ast = bindings[0].expression.ast;
|
||||
expect(ast).toBeAnInstanceOf(BindingPipe);
|
||||
});
|
||||
|
||||
@ -450,9 +450,9 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support a prefix', () => {
|
||||
var source = 'let person of people';
|
||||
var prefix = 'ngFor';
|
||||
var bindings = parseTemplateBindings(source, null, prefix);
|
||||
const source = 'let person of people';
|
||||
const prefix = 'ngFor';
|
||||
const bindings = parseTemplateBindings(source, null, prefix);
|
||||
expect(keyValues(bindings)).toEqual([
|
||||
'ngFor', 'let person=$implicit', 'ngForOf=people in null'
|
||||
]);
|
||||
@ -466,15 +466,15 @@ export function main() {
|
||||
() => { expect(parseInterpolation('nothing')).toBe(null); });
|
||||
|
||||
it('should parse no prefix/suffix interpolation', () => {
|
||||
var ast = parseInterpolation('{{a}}').ast as Interpolation;
|
||||
const ast = parseInterpolation('{{a}}').ast as Interpolation;
|
||||
expect(ast.strings).toEqual(['', '']);
|
||||
expect(ast.expressions.length).toEqual(1);
|
||||
expect(ast.expressions[0].name).toEqual('a');
|
||||
});
|
||||
|
||||
it('should parse prefix/suffix with multiple interpolation', () => {
|
||||
var originalExp = 'before {{ a }} middle {{ b }} after';
|
||||
var ast = parseInterpolation(originalExp).ast;
|
||||
const originalExp = 'before {{ a }} middle {{ b }} after';
|
||||
const ast = parseInterpolation(originalExp).ast;
|
||||
expect(unparse(ast)).toEqual(originalExp);
|
||||
validate(ast);
|
||||
});
|
||||
@ -532,7 +532,7 @@ export function main() {
|
||||
|
||||
describe('parseSimpleBinding', () => {
|
||||
it('should parse a field access', () => {
|
||||
var p = parseSimpleBinding('name');
|
||||
const p = parseSimpleBinding('name');
|
||||
expect(unparse(p)).toEqual('name');
|
||||
validate(p);
|
||||
});
|
||||
@ -563,7 +563,7 @@ export function main() {
|
||||
|
||||
describe('error recovery', () => {
|
||||
function recover(text: string, expected?: string) {
|
||||
let expr = validate(parseAction(text));
|
||||
const expr = validate(parseAction(text));
|
||||
expect(unparse(expr)).toEqual(expected || text);
|
||||
}
|
||||
it('should be able to recover from an extra paren', () => recover('((a)))', 'a'));
|
||||
|
@ -40,7 +40,7 @@ class Unparser implements AstVisitor {
|
||||
}
|
||||
|
||||
visitChain(ast: Chain, context: any) {
|
||||
var len = ast.expressions.length;
|
||||
const len = ast.expressions.length;
|
||||
for (let i = 0; i < len; i++) {
|
||||
this._visit(ast.expressions[i]);
|
||||
this._expression += i == len - 1 ? ';' : '; ';
|
||||
@ -69,7 +69,7 @@ class Unparser implements AstVisitor {
|
||||
visitFunctionCall(ast: FunctionCall, context: any) {
|
||||
this._visit(ast.target);
|
||||
this._expression += '(';
|
||||
var isFirst = true;
|
||||
let isFirst = true;
|
||||
ast.args.forEach(arg => {
|
||||
if (!isFirst) this._expression += ', ';
|
||||
isFirst = false;
|
||||
@ -108,7 +108,7 @@ class Unparser implements AstVisitor {
|
||||
|
||||
visitLiteralArray(ast: LiteralArray, context: any) {
|
||||
this._expression += '[';
|
||||
var isFirst = true;
|
||||
let isFirst = true;
|
||||
ast.expressions.forEach(expression => {
|
||||
if (!isFirst) this._expression += ', ';
|
||||
isFirst = false;
|
||||
@ -120,7 +120,7 @@ class Unparser implements AstVisitor {
|
||||
|
||||
visitLiteralMap(ast: LiteralMap, context: any) {
|
||||
this._expression += '{';
|
||||
var isFirst = true;
|
||||
let isFirst = true;
|
||||
for (let i = 0; i < ast.keys.length; i++) {
|
||||
if (!isFirst) this._expression += ', ';
|
||||
isFirst = false;
|
||||
@ -142,7 +142,7 @@ class Unparser implements AstVisitor {
|
||||
visitMethodCall(ast: MethodCall, context: any) {
|
||||
this._visit(ast.receiver);
|
||||
this._expression += ast.receiver instanceof ImplicitReceiver ? `${ast.name}(` : `.${ast.name}(`;
|
||||
var isFirst = true;
|
||||
let isFirst = true;
|
||||
ast.args.forEach(arg => {
|
||||
if (!isFirst) this._expression += ', ';
|
||||
isFirst = false;
|
||||
@ -164,7 +164,7 @@ class Unparser implements AstVisitor {
|
||||
visitSafeMethodCall(ast: SafeMethodCall, context: any) {
|
||||
this._visit(ast.receiver);
|
||||
this._expression += `?.${ast.name}(`;
|
||||
var isFirst = true;
|
||||
let isFirst = true;
|
||||
ast.args.forEach(arg => {
|
||||
if (!isFirst) this._expression += ', ';
|
||||
isFirst = false;
|
||||
|
@ -21,7 +21,7 @@ class ASTValidator extends RecursiveAstVisitor {
|
||||
validate(ast: AST, cb: () => void): void {
|
||||
if (!inSpan(ast.span, this.parentSpan)) {
|
||||
if (this.parentSpan) {
|
||||
let parentSpan = this.parentSpan as ParseSpan;
|
||||
const parentSpan = this.parentSpan as ParseSpan;
|
||||
throw Error(
|
||||
`Invalid AST span [expected (${ast.span.start}, ${ast.span.end}) to be in (${parentSpan.start}, ${parentSpan.end}) for ${unparse(ast)}`);
|
||||
} else {
|
||||
|
@ -81,17 +81,17 @@ export function main(): void {
|
||||
let htmlParser: HtmlParser;
|
||||
|
||||
function toXliff(html: string): string {
|
||||
let catalog = new MessageBundle(new HtmlParser, [], {});
|
||||
const catalog = new MessageBundle(new HtmlParser, [], {});
|
||||
catalog.updateFromTemplate(html, '', DEFAULT_INTERPOLATION_CONFIG);
|
||||
return catalog.write(serializer);
|
||||
}
|
||||
|
||||
function loadAsText(template: string, xliff: string): {[id: string]: string} {
|
||||
let messageBundle = new MessageBundle(htmlParser, [], {});
|
||||
const messageBundle = new MessageBundle(htmlParser, [], {});
|
||||
messageBundle.updateFromTemplate(template, 'url', DEFAULT_INTERPOLATION_CONFIG);
|
||||
|
||||
const asAst = serializer.load(xliff, 'url', messageBundle);
|
||||
let asText: {[id: string]: string} = {};
|
||||
const asText: {[id: string]: string} = {};
|
||||
Object.keys(asAst).forEach(id => { asText[id] = serializeNodes(asAst[id]).join(''); });
|
||||
|
||||
return asText;
|
||||
|
@ -62,7 +62,7 @@ export function main(): void {
|
||||
}
|
||||
|
||||
function toXmb(html: string): string {
|
||||
let catalog = new MessageBundle(new HtmlParser, [], {});
|
||||
const catalog = new MessageBundle(new HtmlParser, [], {});
|
||||
const serializer = new Xmb();
|
||||
|
||||
catalog.updateFromTemplate(html, '', DEFAULT_INTERPOLATION_CONFIG);
|
||||
|
@ -20,11 +20,11 @@ export function main(): void {
|
||||
let htmlParser: HtmlParser;
|
||||
|
||||
function loadAsText(template: string, xtb: string): {[id: string]: string} {
|
||||
let messageBundle = new MessageBundle(htmlParser, [], {});
|
||||
const messageBundle = new MessageBundle(htmlParser, [], {});
|
||||
messageBundle.updateFromTemplate(template, 'url', DEFAULT_INTERPOLATION_CONFIG);
|
||||
|
||||
const asAst = serializer.load(xtb, 'url', messageBundle);
|
||||
let asText: {[id: string]: string} = {};
|
||||
const asText: {[id: string]: string} = {};
|
||||
Object.keys(asAst).forEach(id => { asText[id] = serializeNodes(asAst[id]).join(''); });
|
||||
|
||||
return asText;
|
||||
|
@ -12,7 +12,7 @@ import {getHtmlTagDefinition} from '@angular/compiler/src/ml_parser/html_tags';
|
||||
|
||||
export function main() {
|
||||
describe('Node serializer', () => {
|
||||
var parser: HtmlParser;
|
||||
let parser: HtmlParser;
|
||||
|
||||
beforeEach(() => { parser = new HtmlParser(); });
|
||||
|
||||
|
@ -12,7 +12,7 @@ import {ParseLocation} from '../../src/parse_util';
|
||||
|
||||
export function humanizeDom(parseResult: ParseTreeResult, addSourceSpan: boolean = false): any[] {
|
||||
if (parseResult.errors.length > 0) {
|
||||
var errorString = parseResult.errors.join('\n');
|
||||
const errorString = parseResult.errors.join('\n');
|
||||
throw new Error(`Unexpected parse errors:\n${errorString}`);
|
||||
}
|
||||
|
||||
@ -24,7 +24,7 @@ export function humanizeDomSourceSpans(parseResult: ParseTreeResult): any[] {
|
||||
}
|
||||
|
||||
export function humanizeNodes(nodes: html.Node[], addSourceSpan: boolean = false): any[] {
|
||||
var humanizer = new _Humanizer(addSourceSpan);
|
||||
const humanizer = new _Humanizer(addSourceSpan);
|
||||
html.visitAll(humanizer, nodes);
|
||||
return humanizer.result;
|
||||
}
|
||||
@ -40,7 +40,7 @@ class _Humanizer implements html.Visitor {
|
||||
constructor(private includeSourceSpan: boolean){};
|
||||
|
||||
visitElement(element: html.Element, context: any): any {
|
||||
var res = this._appendContext(element, [html.Element, element.name, this.elDepth++]);
|
||||
const res = this._appendContext(element, [html.Element, element.name, this.elDepth++]);
|
||||
this.result.push(res);
|
||||
html.visitAll(this, element.attrs);
|
||||
html.visitAll(this, element.children);
|
||||
@ -48,22 +48,22 @@ class _Humanizer implements html.Visitor {
|
||||
}
|
||||
|
||||
visitAttribute(attribute: html.Attribute, context: any): any {
|
||||
var res = this._appendContext(attribute, [html.Attribute, attribute.name, attribute.value]);
|
||||
const res = this._appendContext(attribute, [html.Attribute, attribute.name, attribute.value]);
|
||||
this.result.push(res);
|
||||
}
|
||||
|
||||
visitText(text: html.Text, context: any): any {
|
||||
var res = this._appendContext(text, [html.Text, text.value, this.elDepth]);
|
||||
const res = this._appendContext(text, [html.Text, text.value, this.elDepth]);
|
||||
this.result.push(res);
|
||||
}
|
||||
|
||||
visitComment(comment: html.Comment, context: any): any {
|
||||
var res = this._appendContext(comment, [html.Comment, comment.value, this.elDepth]);
|
||||
const res = this._appendContext(comment, [html.Comment, comment.value, this.elDepth]);
|
||||
this.result.push(res);
|
||||
}
|
||||
|
||||
visitExpansion(expansion: html.Expansion, context: any): any {
|
||||
var res = this._appendContext(
|
||||
const res = this._appendContext(
|
||||
expansion, [html.Expansion, expansion.switchValue, expansion.type, this.elDepth++]);
|
||||
this.result.push(res);
|
||||
html.visitAll(this, expansion.cases);
|
||||
@ -71,7 +71,7 @@ class _Humanizer implements html.Visitor {
|
||||
}
|
||||
|
||||
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any {
|
||||
var res =
|
||||
const res =
|
||||
this._appendContext(expansionCase, [html.ExpansionCase, expansionCase.value, this.elDepth]);
|
||||
this.result.push(res);
|
||||
}
|
||||
|
@ -16,7 +16,7 @@ import {humanizeDom, humanizeDomSourceSpans, humanizeLineColumn} from './ast_spe
|
||||
|
||||
export function main() {
|
||||
describe('HtmlParser', () => {
|
||||
var parser: HtmlParser;
|
||||
let parser: HtmlParser;
|
||||
|
||||
beforeEach(() => { parser = new HtmlParser(); });
|
||||
|
||||
@ -193,7 +193,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should match closing tags case sensitive', () => {
|
||||
let errors = parser.parse('<DiV><P></p></dIv>', 'TestComp').errors;
|
||||
const errors = parser.parse('<DiV><P></p></dIv>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(2);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['p', 'Unexpected closing tag "p"', '0:8'],
|
||||
@ -279,7 +279,7 @@ export function main() {
|
||||
|
||||
describe('expansion forms', () => {
|
||||
it('should parse out expansion forms', () => {
|
||||
let parsed = parser.parse(
|
||||
const parsed = parser.parse(
|
||||
`<div>before{messages.length, plural, =0 {You have <b>no</b> messages} =1 {One {{message}}}}after</div>`,
|
||||
'TestComp', true);
|
||||
|
||||
@ -291,7 +291,7 @@ export function main() {
|
||||
[html.ExpansionCase, '=1', 2],
|
||||
[html.Text, 'after', 1],
|
||||
]);
|
||||
let cases = (<any>parsed.rootNodes[0]).children[1].cases;
|
||||
const cases = (<any>parsed.rootNodes[0]).children[1].cases;
|
||||
|
||||
expect(humanizeDom(new ParseTreeResult(cases[0].expression, []))).toEqual([
|
||||
[html.Text, 'You have ', 0],
|
||||
@ -305,14 +305,14 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should parse out nested expansion forms', () => {
|
||||
let parsed = parser.parse(
|
||||
const parsed = parser.parse(
|
||||
`{messages.length, plural, =0 { {p.gender, select, male {m}} }}`, 'TestComp', true);
|
||||
expect(humanizeDom(parsed)).toEqual([
|
||||
[html.Expansion, 'messages.length', 'plural', 0],
|
||||
[html.ExpansionCase, '=0', 1],
|
||||
]);
|
||||
|
||||
let firstCase = (<any>parsed.rootNodes[0]).cases[0];
|
||||
const firstCase = (<any>parsed.rootNodes[0]).cases[0];
|
||||
|
||||
expect(humanizeDom(new ParseTreeResult(firstCase.expression, []))).toEqual([
|
||||
[html.Expansion, 'p.gender', 'select', 0],
|
||||
@ -322,21 +322,21 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should error when expansion form is not closed', () => {
|
||||
let p = parser.parse(`{messages.length, plural, =0 {one}`, 'TestComp', true);
|
||||
const p = parser.parse(`{messages.length, plural, =0 {one}`, 'TestComp', true);
|
||||
expect(humanizeErrors(p.errors)).toEqual([
|
||||
[null, 'Invalid ICU message. Missing \'}\'.', '0:34']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should error when expansion case is not closed', () => {
|
||||
let p = parser.parse(`{messages.length, plural, =0 {one`, 'TestComp', true);
|
||||
const p = parser.parse(`{messages.length, plural, =0 {one`, 'TestComp', true);
|
||||
expect(humanizeErrors(p.errors)).toEqual([
|
||||
[null, 'Invalid ICU message. Missing \'}\'.', '0:29']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should error when invalid html in the case', () => {
|
||||
let p = parser.parse(`{messages.length, plural, =0 {<b/>}`, 'TestComp', true);
|
||||
const p = parser.parse(`{messages.length, plural, =0 {<b/>}`, 'TestComp', true);
|
||||
expect(humanizeErrors(p.errors)).toEqual([
|
||||
['b', 'Only void and foreign elements can be self closed "b"', '0:30']
|
||||
]);
|
||||
@ -358,7 +358,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should set the start and end source spans', () => {
|
||||
let node = <html.Element>parser.parse('<div>a</div>', 'TestComp').rootNodes[0];
|
||||
const node = <html.Element>parser.parse('<div>a</div>', 'TestComp').rootNodes[0];
|
||||
|
||||
expect(node.startSourceSpan.start.offset).toEqual(0);
|
||||
expect(node.startSourceSpan.end.offset).toEqual(5);
|
||||
@ -456,19 +456,19 @@ export function main() {
|
||||
|
||||
describe('errors', () => {
|
||||
it('should report unexpected closing tags', () => {
|
||||
let errors = parser.parse('<div></p></div>', 'TestComp').errors;
|
||||
const errors = parser.parse('<div></p></div>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors)).toEqual([['p', 'Unexpected closing tag "p"', '0:5']]);
|
||||
});
|
||||
|
||||
it('should report subsequent open tags without proper close tag', () => {
|
||||
let errors = parser.parse('<div</div>', 'TestComp').errors;
|
||||
const errors = parser.parse('<div</div>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors)).toEqual([['div', 'Unexpected closing tag "div"', '0:4']]);
|
||||
});
|
||||
|
||||
it('should report closing tag for void elements', () => {
|
||||
let errors = parser.parse('<input></input>', 'TestComp').errors;
|
||||
const errors = parser.parse('<input></input>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['input', 'Void elements do not have end tags "input"', '0:7']
|
||||
@ -476,7 +476,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should report self closing html element', () => {
|
||||
let errors = parser.parse('<p />', 'TestComp').errors;
|
||||
const errors = parser.parse('<p />', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['p', 'Only void and foreign elements can be self closed "p"', '0:0']
|
||||
@ -484,7 +484,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should report self closing custom element', () => {
|
||||
let errors = parser.parse('<my-cmp />', 'TestComp').errors;
|
||||
const errors = parser.parse('<my-cmp />', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
['my-cmp', 'Only void and foreign elements can be self closed "my-cmp"', '0:0']
|
||||
@ -492,7 +492,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should also report lexer errors', () => {
|
||||
let errors = parser.parse('<!-err--><div></p></div>', 'TestComp').errors;
|
||||
const errors = parser.parse('<!-err--><div></p></div>', 'TestComp').errors;
|
||||
expect(errors.length).toEqual(2);
|
||||
expect(humanizeErrors(errors)).toEqual([
|
||||
[TokenType.COMMENT_START, 'Unexpected character "e"', '0:3'],
|
||||
|
@ -738,11 +738,11 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should include 2 lines of context in message', () => {
|
||||
let src = '111\n222\n333\nE\n444\n555\n666\n';
|
||||
let file = new ParseSourceFile(src, 'file://');
|
||||
let location = new ParseLocation(file, 12, 123, 456);
|
||||
let span = new ParseSourceSpan(location, location);
|
||||
let error = new lex.TokenError('**ERROR**', null, span);
|
||||
const src = '111\n222\n333\nE\n444\n555\n666\n';
|
||||
const file = new ParseSourceFile(src, 'file://');
|
||||
const location = new ParseLocation(file, 12, 123, 456);
|
||||
const span = new ParseSourceSpan(location, location);
|
||||
const error = new lex.TokenError('**ERROR**', null, span);
|
||||
expect(error.toString())
|
||||
.toEqual(`**ERROR** ("\n222\n333\n[ERROR ->]E\n444\n555\n"): file://@123:456`);
|
||||
});
|
||||
@ -766,7 +766,7 @@ export function main() {
|
||||
function tokenizeWithoutErrors(
|
||||
input: string, tokenizeExpansionForms: boolean = false,
|
||||
interpolationConfig?: InterpolationConfig): lex.Token[] {
|
||||
var tokenizeResult = lex.tokenize(
|
||||
const tokenizeResult = lex.tokenize(
|
||||
input, 'someUrl', getHtmlTagDefinition, tokenizeExpansionForms, interpolationConfig);
|
||||
|
||||
if (tokenizeResult.errors.length > 0) {
|
||||
|
@ -12,7 +12,7 @@ import {MockNgModuleResolver} from '../testing/index';
|
||||
|
||||
export function main() {
|
||||
describe('MockNgModuleResolver', () => {
|
||||
var ngModuleResolver: MockNgModuleResolver;
|
||||
let ngModuleResolver: MockNgModuleResolver;
|
||||
|
||||
beforeEach(inject([Injector], (injector: Injector) => {
|
||||
ngModuleResolver = new MockNgModuleResolver(injector);
|
||||
@ -21,14 +21,14 @@ export function main() {
|
||||
describe('NgModule overriding', () => {
|
||||
it('should fallback to the default NgModuleResolver when templates are not overridden',
|
||||
() => {
|
||||
var ngModule = ngModuleResolver.resolve(SomeNgModule);
|
||||
const ngModule = ngModuleResolver.resolve(SomeNgModule);
|
||||
expect(ngModule.declarations).toEqual([SomeDirective]);
|
||||
});
|
||||
|
||||
it('should allow overriding the @NgModule', () => {
|
||||
ngModuleResolver.setNgModule(
|
||||
SomeNgModule, new NgModule({declarations: [SomeOtherDirective]}));
|
||||
var ngModule = ngModuleResolver.resolve(SomeNgModule);
|
||||
const ngModule = ngModuleResolver.resolve(SomeNgModule);
|
||||
expect(ngModule.declarations).toEqual([SomeOtherDirective]);
|
||||
});
|
||||
});
|
||||
|
@ -30,12 +30,12 @@ class SimpleClass {}
|
||||
|
||||
export function main() {
|
||||
describe('NgModuleResolver', () => {
|
||||
var resolver: NgModuleResolver;
|
||||
let resolver: NgModuleResolver;
|
||||
|
||||
beforeEach(() => { resolver = new NgModuleResolver(); });
|
||||
|
||||
it('should read out the metadata from the class', () => {
|
||||
var moduleMetadata = resolver.resolve(SomeModule);
|
||||
const moduleMetadata = resolver.resolve(SomeModule);
|
||||
expect(moduleMetadata).toEqual(new NgModule({
|
||||
declarations: [SomeClass1],
|
||||
imports: [SomeClass2],
|
||||
|
@ -13,13 +13,13 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_in
|
||||
|
||||
import {SimpleJsImportGenerator} from './output_emitter_util';
|
||||
|
||||
var someModuleUrl = 'asset:somePackage/lib/somePath';
|
||||
var anotherModuleUrl = 'asset:somePackage/lib/someOtherPath';
|
||||
const someModuleUrl = 'asset:somePackage/lib/somePath';
|
||||
const anotherModuleUrl = 'asset:somePackage/lib/someOtherPath';
|
||||
|
||||
var sameModuleIdentifier =
|
||||
const sameModuleIdentifier =
|
||||
new CompileIdentifierMetadata({name: 'someLocalId', moduleUrl: someModuleUrl});
|
||||
|
||||
var externalModuleIdentifier =
|
||||
const externalModuleIdentifier =
|
||||
new CompileIdentifierMetadata({name: 'someExternalId', moduleUrl: anotherModuleUrl});
|
||||
|
||||
export function main() {
|
||||
@ -28,8 +28,8 @@ export function main() {
|
||||
// - declaring fields
|
||||
|
||||
describe('JavaScriptEmitter', () => {
|
||||
var emitter: JavaScriptEmitter;
|
||||
var someVar: o.ReadVarExpr;
|
||||
let emitter: JavaScriptEmitter;
|
||||
let someVar: o.ReadVarExpr;
|
||||
|
||||
beforeEach(() => {
|
||||
emitter = new JavaScriptEmitter(new SimpleJsImportGenerator());
|
||||
@ -120,8 +120,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support operators', () => {
|
||||
var lhs = o.variable('lhs');
|
||||
var rhs = o.variable('rhs');
|
||||
const lhs = o.variable('lhs');
|
||||
const rhs = o.variable('rhs');
|
||||
expect(emitStmt(o.not(someVar).toStmt())).toEqual('!someVar;');
|
||||
expect(
|
||||
emitStmt(someVar.conditional(o.variable('trueCase'), o.variable('falseCase')).toStmt()))
|
||||
@ -173,8 +173,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support if stmt', () => {
|
||||
var trueCase = o.variable('trueCase').callFn([]).toStmt();
|
||||
var falseCase = o.variable('falseCase').callFn([]).toStmt();
|
||||
const trueCase = o.variable('trueCase').callFn([]).toStmt();
|
||||
const falseCase = o.variable('falseCase').callFn([]).toStmt();
|
||||
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase]))).toEqual([
|
||||
'if (cond) { trueCase(); }'
|
||||
].join('\n'));
|
||||
@ -184,8 +184,9 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support try/catch', () => {
|
||||
var bodyStmt = o.variable('body').callFn([]).toStmt();
|
||||
var catchStmt = o.variable('catchFn').callFn([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]).toStmt();
|
||||
const bodyStmt = o.variable('body').callFn([]).toStmt();
|
||||
const catchStmt =
|
||||
o.variable('catchFn').callFn([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]).toStmt();
|
||||
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt]))).toEqual([
|
||||
'try {', ' body();', '} catch (error) {', ' var stack = error.stack;',
|
||||
' catchFn(error,stack);', '}'
|
||||
@ -196,7 +197,7 @@ export function main() {
|
||||
() => { expect(emitStmt(new o.ThrowStmt(someVar))).toEqual('throw someVar;'); });
|
||||
|
||||
describe('classes', () => {
|
||||
var callSomeMethod: o.Statement;
|
||||
let callSomeMethod: o.Statement;
|
||||
|
||||
beforeEach(() => { callSomeMethod = o.THIS_EXPR.callMethod('someMethod', []).toStmt(); });
|
||||
|
||||
@ -217,7 +218,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support declaring constructors', () => {
|
||||
var superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt();
|
||||
const superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt();
|
||||
expect(emitStmt(
|
||||
new o.ClassStmt('SomeClass', null, [], [], new o.ClassMethod(null, [], []), [])))
|
||||
.toEqual(['function SomeClass() {', '}'].join('\n'));
|
||||
|
@ -20,15 +20,15 @@ export function getExpressions(): any {
|
||||
|
||||
// Generator
|
||||
export function emit() {
|
||||
var emitter = new JavaScriptEmitter(new SimpleJsImportGenerator());
|
||||
var emittedCode = emitter.emitStatements(
|
||||
const emitter = new JavaScriptEmitter(new SimpleJsImportGenerator());
|
||||
const emittedCode = emitter.emitStatements(
|
||||
assetUrl('compiler', 'output/output_emitter_codegen_untyped', 'test'), codegenStmts,
|
||||
codegenExportsVars);
|
||||
return emittedCode;
|
||||
}
|
||||
|
||||
export function main(args: string[]) {
|
||||
var emittedCode = emit();
|
||||
const emittedCode = emit();
|
||||
// debug: console.error(emittedCode);
|
||||
print(emittedCode);
|
||||
}
|
||||
|
@ -20,7 +20,7 @@ import * as untyped from './output_emitter_codegen_untyped';
|
||||
import {ExternalClass, codegenStmts} from './output_emitter_util';
|
||||
|
||||
export function main() {
|
||||
var outputDefs: any[] /** TODO #9100 */ = [];
|
||||
const outputDefs: any[] /** TODO #9100 */ = [];
|
||||
outputDefs.push({
|
||||
'getExpressions': () => interpretStatements(codegenStmts, 'getExpressions'),
|
||||
'name': 'interpreted'
|
||||
@ -43,7 +43,7 @@ export function main() {
|
||||
describe('output emitter', () => {
|
||||
outputDefs.forEach((outputDef) => {
|
||||
describe(`${outputDef['name']}`, () => {
|
||||
var expressions: {[k: string]: any};
|
||||
let expressions: {[k: string]: any};
|
||||
beforeEach(() => { expressions = outputDef['getExpressions']()(); });
|
||||
|
||||
it('should support literals', () => {
|
||||
@ -109,9 +109,9 @@ export function main() {
|
||||
});
|
||||
|
||||
describe('operators', () => {
|
||||
var ops: {[k: string]: Function};
|
||||
var aObj: any;
|
||||
var bObj: any;
|
||||
let ops: {[k: string]: Function};
|
||||
let aObj: any;
|
||||
let bObj: any;
|
||||
|
||||
beforeEach(() => {
|
||||
ops = expressions['operators'];
|
||||
@ -184,7 +184,7 @@ export function main() {
|
||||
it('should support catching errors', () => {
|
||||
function someOperation() { throw new Error('Boom!'); }
|
||||
|
||||
var errorAndStack = expressions['catchError'](someOperation);
|
||||
const errorAndStack = expressions['catchError'](someOperation);
|
||||
expect(errorAndStack[0].message).toEqual('Boom!');
|
||||
// Somehow we don't get stacktraces on ios7...
|
||||
if (!browserDetection.isIOS7 && !browserDetection.isIE) {
|
||||
|
@ -20,22 +20,22 @@ export class ExternalClass {
|
||||
someMethod(a: any /** TODO #9100 */) { return {'param': a, 'data': this.data}; }
|
||||
}
|
||||
|
||||
var testDataIdentifier = new CompileIdentifierMetadata({
|
||||
const testDataIdentifier = new CompileIdentifierMetadata({
|
||||
name: 'ExternalClass',
|
||||
moduleUrl: `asset:@angular/lib/compiler/test/output/output_emitter_util`,
|
||||
reference: ExternalClass
|
||||
});
|
||||
|
||||
var eventEmitterIdentifier = new CompileIdentifierMetadata(
|
||||
const eventEmitterIdentifier = new CompileIdentifierMetadata(
|
||||
{name: 'EventEmitter', moduleUrl: assetUrl('core'), reference: EventEmitter});
|
||||
|
||||
var enumIdentifier = new CompileIdentifierMetadata({
|
||||
const enumIdentifier = new CompileIdentifierMetadata({
|
||||
name: 'ViewType.HOST',
|
||||
moduleUrl: assetUrl('core', 'linker/view_type'),
|
||||
reference: ViewType.HOST
|
||||
});
|
||||
|
||||
var baseErrorIdentifier = new CompileIdentifierMetadata(
|
||||
const baseErrorIdentifier = new CompileIdentifierMetadata(
|
||||
{name: 'BaseError', moduleUrl: assetUrl('core', 'facade/errors'), reference: BaseError});
|
||||
|
||||
export var codegenExportsVars = [
|
||||
@ -43,7 +43,7 @@ export var codegenExportsVars = [
|
||||
];
|
||||
|
||||
|
||||
var _getExpressionsStmts: o.Statement[] = [
|
||||
const _getExpressionsStmts: o.Statement[] = [
|
||||
o.variable('readVar').set(o.literal('someValue')).toDeclStmt(),
|
||||
|
||||
o.variable('changedVar').set(o.literal('initialValue')).toDeclStmt(),
|
||||
@ -254,7 +254,7 @@ function createOperatorFn(op: o.BinaryOperator) {
|
||||
|
||||
export class SimpleJsImportGenerator implements ImportGenerator {
|
||||
getImportPath(moduleUrlStr: string, importedUrlStr: string): string {
|
||||
var importedAssetUrl = ImportGenerator.parseAssetUrl(importedUrlStr);
|
||||
const importedAssetUrl = ImportGenerator.parseAssetUrl(importedUrlStr);
|
||||
if (importedAssetUrl) {
|
||||
return `${importedAssetUrl.packageName}/${importedAssetUrl.modulePath}`;
|
||||
} else {
|
||||
|
@ -13,13 +13,13 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_in
|
||||
|
||||
import {SimpleJsImportGenerator} from './output_emitter_util';
|
||||
|
||||
var someModuleUrl = 'asset:somePackage/lib/somePath';
|
||||
var anotherModuleUrl = 'asset:somePackage/lib/someOtherPath';
|
||||
const someModuleUrl = 'asset:somePackage/lib/somePath';
|
||||
const anotherModuleUrl = 'asset:somePackage/lib/someOtherPath';
|
||||
|
||||
var sameModuleIdentifier =
|
||||
const sameModuleIdentifier =
|
||||
new CompileIdentifierMetadata({name: 'someLocalId', moduleUrl: someModuleUrl});
|
||||
|
||||
var externalModuleIdentifier =
|
||||
const externalModuleIdentifier =
|
||||
new CompileIdentifierMetadata({name: 'someExternalId', moduleUrl: anotherModuleUrl});
|
||||
|
||||
export function main() {
|
||||
@ -28,8 +28,8 @@ export function main() {
|
||||
// - final fields
|
||||
|
||||
describe('TypeScriptEmitter', () => {
|
||||
var emitter: TypeScriptEmitter;
|
||||
var someVar: o.ReadVarExpr;
|
||||
let emitter: TypeScriptEmitter;
|
||||
let someVar: o.ReadVarExpr;
|
||||
|
||||
beforeEach(() => {
|
||||
emitter = new TypeScriptEmitter(new SimpleJsImportGenerator());
|
||||
@ -121,8 +121,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support operators', () => {
|
||||
var lhs = o.variable('lhs');
|
||||
var rhs = o.variable('rhs');
|
||||
const lhs = o.variable('lhs');
|
||||
const rhs = o.variable('rhs');
|
||||
expect(emitStmt(someVar.cast(o.INT_TYPE).toStmt())).toEqual('(<number>someVar);');
|
||||
expect(emitStmt(o.not(someVar).toStmt())).toEqual('!someVar;');
|
||||
expect(
|
||||
@ -173,8 +173,8 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support if stmt', () => {
|
||||
var trueCase = o.variable('trueCase').callFn([]).toStmt();
|
||||
var falseCase = o.variable('falseCase').callFn([]).toStmt();
|
||||
const trueCase = o.variable('trueCase').callFn([]).toStmt();
|
||||
const falseCase = o.variable('falseCase').callFn([]).toStmt();
|
||||
expect(emitStmt(new o.IfStmt(o.variable('cond'), [trueCase]))).toEqual([
|
||||
'if (cond) { trueCase(); }'
|
||||
].join('\n'));
|
||||
@ -184,8 +184,9 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support try/catch', () => {
|
||||
var bodyStmt = o.variable('body').callFn([]).toStmt();
|
||||
var catchStmt = o.variable('catchFn').callFn([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]).toStmt();
|
||||
const bodyStmt = o.variable('body').callFn([]).toStmt();
|
||||
const catchStmt =
|
||||
o.variable('catchFn').callFn([o.CATCH_ERROR_VAR, o.CATCH_STACK_VAR]).toStmt();
|
||||
expect(emitStmt(new o.TryCatchStmt([bodyStmt], [catchStmt]))).toEqual([
|
||||
'try {', ' body();', '} catch (error) {', ' const stack:any = error.stack;',
|
||||
' catchFn(error,stack);', '}'
|
||||
@ -196,7 +197,7 @@ export function main() {
|
||||
() => { expect(emitStmt(new o.ThrowStmt(someVar))).toEqual('throw someVar;'); });
|
||||
|
||||
describe('classes', () => {
|
||||
var callSomeMethod: o.Statement;
|
||||
let callSomeMethod: o.Statement;
|
||||
|
||||
beforeEach(() => { callSomeMethod = o.THIS_EXPR.callMethod('someMethod', []).toStmt(); });
|
||||
|
||||
@ -211,7 +212,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support declaring constructors', () => {
|
||||
var superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt();
|
||||
const superCall = o.SUPER_EXPR.callFn([o.variable('someParam')]).toStmt();
|
||||
expect(emitStmt(
|
||||
new o.ClassStmt('SomeClass', null, [], [], new o.ClassMethod(null, [], []), [])))
|
||||
.toEqual(['class SomeClass {', ' constructor() {', ' }', '}'].join('\n'));
|
||||
@ -292,7 +293,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support builtin types', () => {
|
||||
var writeVarExpr = o.variable('a').set(o.NULL_EXPR);
|
||||
const writeVarExpr = o.variable('a').set(o.NULL_EXPR);
|
||||
expect(emitStmt(writeVarExpr.toDeclStmt(o.DYNAMIC_TYPE)))
|
||||
.toEqual('var a:any = (null as any);');
|
||||
expect(emitStmt(writeVarExpr.toDeclStmt(o.BOOL_TYPE)))
|
||||
@ -308,7 +309,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support external types', () => {
|
||||
var writeVarExpr = o.variable('a').set(o.NULL_EXPR);
|
||||
const writeVarExpr = o.variable('a').set(o.NULL_EXPR);
|
||||
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(sameModuleIdentifier))))
|
||||
.toEqual('var a:someLocalId = (null as any);');
|
||||
expect(emitStmt(writeVarExpr.toDeclStmt(o.importType(externalModuleIdentifier)))).toEqual([
|
||||
@ -318,7 +319,7 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should support combined types', () => {
|
||||
var writeVarExpr = o.variable('a').set(o.NULL_EXPR);
|
||||
const writeVarExpr = o.variable('a').set(o.NULL_EXPR);
|
||||
expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(null))))
|
||||
.toEqual('var a:any[] = (null as any);');
|
||||
expect(emitStmt(writeVarExpr.toDeclStmt(new o.ArrayType(o.INT_TYPE))))
|
||||
|
@ -12,20 +12,20 @@ import {MockPipeResolver} from '../testing/index';
|
||||
|
||||
export function main() {
|
||||
describe('MockPipeResolver', () => {
|
||||
var pipeResolver: MockPipeResolver;
|
||||
let pipeResolver: MockPipeResolver;
|
||||
|
||||
beforeEach(inject(
|
||||
[Injector], (injector: Injector) => { pipeResolver = new MockPipeResolver(injector); }));
|
||||
|
||||
describe('Pipe overriding', () => {
|
||||
it('should fallback to the default PipeResolver when templates are not overridden', () => {
|
||||
var pipe = pipeResolver.resolve(SomePipe);
|
||||
const pipe = pipeResolver.resolve(SomePipe);
|
||||
expect(pipe.name).toEqual('somePipe');
|
||||
});
|
||||
|
||||
it('should allow overriding the @Pipe', () => {
|
||||
pipeResolver.setPipe(SomePipe, new Pipe({name: 'someOtherName'}));
|
||||
var pipe = pipeResolver.resolve(SomePipe);
|
||||
const pipe = pipeResolver.resolve(SomePipe);
|
||||
expect(pipe.name).toEqual('someOtherName');
|
||||
});
|
||||
});
|
||||
|
@ -12,7 +12,7 @@ import {isPresent} from '../src/facade/lang';
|
||||
|
||||
export function main() {
|
||||
describe('MockResourceLoader', () => {
|
||||
var resourceLoader: MockResourceLoader;
|
||||
let resourceLoader: MockResourceLoader;
|
||||
|
||||
beforeEach(() => { resourceLoader = new MockResourceLoader(); });
|
||||
|
||||
@ -43,8 +43,8 @@ export function main() {
|
||||
|
||||
it('should return a response from the definitions',
|
||||
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
|
||||
var url = '/foo';
|
||||
var response = 'bar';
|
||||
const url = '/foo';
|
||||
const response = 'bar';
|
||||
resourceLoader.when(url, response);
|
||||
expectResponse(resourceLoader.get(url), url, response, () => async.done());
|
||||
resourceLoader.flush();
|
||||
@ -52,8 +52,8 @@ export function main() {
|
||||
|
||||
it('should return an error from the definitions',
|
||||
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
|
||||
var url = '/foo';
|
||||
var response: string = null;
|
||||
const url = '/foo';
|
||||
const response: string = null;
|
||||
resourceLoader.when(url, response);
|
||||
expectResponse(resourceLoader.get(url), url, response, () => async.done());
|
||||
resourceLoader.flush();
|
||||
@ -61,8 +61,8 @@ export function main() {
|
||||
|
||||
it('should return a response from the expectations',
|
||||
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
|
||||
var url = '/foo';
|
||||
var response = 'bar';
|
||||
const url = '/foo';
|
||||
const response = 'bar';
|
||||
resourceLoader.expect(url, response);
|
||||
expectResponse(resourceLoader.get(url), url, response, () => async.done());
|
||||
resourceLoader.flush();
|
||||
@ -70,16 +70,16 @@ export function main() {
|
||||
|
||||
it('should return an error from the expectations',
|
||||
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
|
||||
var url = '/foo';
|
||||
var response: string = null;
|
||||
const url = '/foo';
|
||||
const response: string = null;
|
||||
resourceLoader.expect(url, response);
|
||||
expectResponse(resourceLoader.get(url), url, response, () => async.done());
|
||||
resourceLoader.flush();
|
||||
}));
|
||||
|
||||
it('should not reuse expectations', () => {
|
||||
var url = '/foo';
|
||||
var response = 'bar';
|
||||
const url = '/foo';
|
||||
const response = 'bar';
|
||||
resourceLoader.expect(url, response);
|
||||
resourceLoader.get(url);
|
||||
resourceLoader.get(url);
|
||||
@ -88,7 +88,7 @@ export function main() {
|
||||
|
||||
it('should return expectations before definitions',
|
||||
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
|
||||
var url = '/foo';
|
||||
const url = '/foo';
|
||||
resourceLoader.when(url, 'when');
|
||||
resourceLoader.expect(url, 'expect');
|
||||
expectResponse(resourceLoader.get(url), url, 'expect');
|
||||
|
@ -164,7 +164,7 @@ export function main() {
|
||||
compiler.compileModuleAsync(SomeModule);
|
||||
tick();
|
||||
|
||||
let ngModuleFactory = compiler.compileModuleSync(SomeModule);
|
||||
const ngModuleFactory = compiler.compileModuleSync(SomeModule);
|
||||
expect(ngModuleFactory).toBeTruthy();
|
||||
}));
|
||||
});
|
||||
|
@ -58,7 +58,7 @@ export function extractSchema(): Map<string, string[]> {
|
||||
const svgText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
|
||||
|
||||
const descMap: Map<string, string[]> = new Map();
|
||||
let visited: {[name: string]: boolean} = {};
|
||||
const visited: {[name: string]: boolean} = {};
|
||||
|
||||
// HTML top level
|
||||
extractProperties(Node, element, visited, descMap, ELEMENT_IF, '');
|
||||
@ -179,7 +179,7 @@ function extractProperties(
|
||||
const props: string[] = descMap.has(fullName) ? descMap.get(fullName) : [];
|
||||
|
||||
const prototype = type.prototype;
|
||||
let keys = Object.getOwnPropertyNames(prototype);
|
||||
const keys = Object.getOwnPropertyNames(prototype);
|
||||
|
||||
keys.sort();
|
||||
keys.forEach((name) => {
|
||||
|
@ -105,7 +105,7 @@ export function main() {
|
||||
it('should select by attr name only once if the value is from the DOM', () => {
|
||||
matcher.addSelectables(s1 = CssSelector.parse('[some-decor]'), 1);
|
||||
|
||||
let elementSelector = new CssSelector();
|
||||
const elementSelector = new CssSelector();
|
||||
const element = el('<div attr></div>');
|
||||
const empty = getDOM().getAttribute(element, 'attr');
|
||||
elementSelector.addAttribute('some-decor', empty);
|
||||
@ -164,7 +164,7 @@ export function main() {
|
||||
it('should select by many attributes and independent of the value', () => {
|
||||
matcher.addSelectables(s1 = CssSelector.parse('input[type=text][control]'), 1);
|
||||
|
||||
let cssSelector = new CssSelector();
|
||||
const cssSelector = new CssSelector();
|
||||
cssSelector.setElement('input');
|
||||
cssSelector.addAttribute('type', 'text');
|
||||
cssSelector.addAttribute('control', 'one');
|
||||
|
@ -11,38 +11,38 @@ import {UrlResolver} from '@angular/compiler/src/url_resolver';
|
||||
|
||||
export function main() {
|
||||
describe('extractStyleUrls', () => {
|
||||
var urlResolver: UrlResolver;
|
||||
let urlResolver: UrlResolver;
|
||||
|
||||
beforeEach(() => { urlResolver = new UrlResolver(); });
|
||||
|
||||
it('should not resolve "url()" urls', () => {
|
||||
var css = `
|
||||
const css = `
|
||||
.foo {
|
||||
background-image: url("double.jpg");
|
||||
background-image: url('simple.jpg');
|
||||
background-image: url(noquote.jpg);
|
||||
}`;
|
||||
var resolvedCss = extractStyleUrls(urlResolver, 'http://ng.io', css).style;
|
||||
const resolvedCss = extractStyleUrls(urlResolver, 'http://ng.io', css).style;
|
||||
expect(resolvedCss).toEqual(css);
|
||||
});
|
||||
|
||||
it('should extract "@import" urls', () => {
|
||||
var css = `
|
||||
const css = `
|
||||
@import '1.css';
|
||||
@import "2.css";
|
||||
`;
|
||||
var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
const styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls).toEqual(['http://ng.io/1.css', 'http://ng.io/2.css']);
|
||||
});
|
||||
|
||||
it('should extract "@import url()" urls', () => {
|
||||
var css = `
|
||||
const css = `
|
||||
@import url('3.css');
|
||||
@import url("4.css");
|
||||
@import url(5.css);
|
||||
`;
|
||||
var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
const styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls).toEqual([
|
||||
'http://ng.io/3.css', 'http://ng.io/4.css', 'http://ng.io/5.css'
|
||||
@ -50,18 +50,18 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should extract "@import urls and keep rules in the same line', () => {
|
||||
var css = `@import url('some.css');div {color: red};`;
|
||||
var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
const css = `@import url('some.css');div {color: red};`;
|
||||
const styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual('div {color: red};');
|
||||
expect(styleWithImports.styleUrls).toEqual(['http://ng.io/some.css']);
|
||||
});
|
||||
|
||||
it('should extract media query in "@import"', () => {
|
||||
var css = `
|
||||
const css = `
|
||||
@import 'print1.css' print;
|
||||
@import url(print2.css) print;
|
||||
`;
|
||||
var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
const styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual('');
|
||||
expect(styleWithImports.styleUrls).toEqual([
|
||||
'http://ng.io/print1.css', 'http://ng.io/print2.css'
|
||||
@ -69,15 +69,15 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should leave absolute non-package @import urls intact', () => {
|
||||
var css = `@import url('http://server.com/some.css');`;
|
||||
var styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
const css = `@import url('http://server.com/some.css');`;
|
||||
const styleWithImports = extractStyleUrls(urlResolver, 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual(`@import url('http://server.com/some.css');`);
|
||||
expect(styleWithImports.styleUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should resolve package @import urls', () => {
|
||||
var css = `@import url('package:a/b/some.css');`;
|
||||
var styleWithImports = extractStyleUrls(new FakeUrlResolver(), 'http://ng.io', css);
|
||||
const css = `@import url('package:a/b/some.css');`;
|
||||
const styleWithImports = extractStyleUrls(new FakeUrlResolver(), 'http://ng.io', css);
|
||||
expect(styleWithImports.style.trim()).toEqual(``);
|
||||
expect(styleWithImports.styleUrls).toEqual(['fake_resolved_url']);
|
||||
});
|
||||
|
@ -32,11 +32,11 @@ const MOCK_SCHEMA_REGISTRY = [{
|
||||
}];
|
||||
|
||||
export function main() {
|
||||
var ngIf: CompileDirectiveSummary;
|
||||
var parse: (
|
||||
let ngIf: CompileDirectiveSummary;
|
||||
let parse: (
|
||||
template: string, directives: CompileDirectiveSummary[], pipes?: CompilePipeSummary[],
|
||||
schemas?: SchemaMetadata[]) => TemplateAst[];
|
||||
var console: ArrayConsole;
|
||||
let console: ArrayConsole;
|
||||
|
||||
function commonBeforeEach() {
|
||||
beforeEach(() => {
|
||||
@ -44,9 +44,9 @@ export function main() {
|
||||
TestBed.configureCompiler({providers: [{provide: Console, useValue: console}]});
|
||||
});
|
||||
beforeEach(inject([TemplateParser], (parser: TemplateParser) => {
|
||||
var someAnimation = new CompileAnimationEntryMetadata('someAnimation', []);
|
||||
var someTemplate = new CompileTemplateMetadata({animations: [someAnimation]});
|
||||
var component = CompileDirectiveMetadata.create({
|
||||
const someAnimation = new CompileAnimationEntryMetadata('someAnimation', []);
|
||||
const someTemplate = new CompileTemplateMetadata({animations: [someAnimation]});
|
||||
const component = CompileDirectiveMetadata.create({
|
||||
selector: 'root',
|
||||
template: someTemplate,
|
||||
type: new CompileTypeMetadata(
|
||||
@ -232,8 +232,8 @@ export function main() {
|
||||
|
||||
describe('security context', () => {
|
||||
function secContext(tpl: string): SecurityContext {
|
||||
let ast = parse(tpl, []);
|
||||
let propBinding = (<ElementAst>ast[0]).inputs[0];
|
||||
const ast = parse(tpl, []);
|
||||
const propBinding = (<ElementAst>ast[0]).inputs[0];
|
||||
return propBinding.securityContext;
|
||||
}
|
||||
|
||||
@ -465,7 +465,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
it('should not issue a warning when host attributes contain a valid property-bound animation trigger',
|
||||
() => {
|
||||
const animationEntries = [new CompileAnimationEntryMetadata('prop', [])];
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -484,7 +484,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should throw descriptive error when a host binding is not a string expression', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'broken',
|
||||
@ -500,7 +500,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should throw descriptive error when a host event is not a string expression', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'broken',
|
||||
@ -568,17 +568,17 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
|
||||
it('should allow events on explicit embedded templates that are emitted by a directive',
|
||||
() => {
|
||||
var dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'template',
|
||||
outputs: ['e'],
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
const dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'template',
|
||||
outputs: ['e'],
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
})
|
||||
})
|
||||
})
|
||||
.toSummary();
|
||||
.toSummary();
|
||||
expect(humanizeTplAst(parse('<template (e)="f"></template>', [dirA]))).toEqual([
|
||||
[EmbeddedTemplateAst],
|
||||
[BoundEventAst, 'e', null, 'f'],
|
||||
@ -611,36 +611,36 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
describe('directives', () => {
|
||||
it('should order directives by the directives array in the View and match them only once',
|
||||
() => {
|
||||
var dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
const dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
})
|
||||
})
|
||||
})
|
||||
.toSummary();
|
||||
var dirB = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[b]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirB',
|
||||
reference: {} as Type<any>
|
||||
.toSummary();
|
||||
const dirB = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[b]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirB',
|
||||
reference: {} as Type<any>
|
||||
})
|
||||
})
|
||||
})
|
||||
.toSummary();
|
||||
var dirC = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[c]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirC',
|
||||
reference: {} as Type<any>
|
||||
.toSummary();
|
||||
const dirC = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[c]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirC',
|
||||
reference: {} as Type<any>
|
||||
})
|
||||
})
|
||||
})
|
||||
.toSummary();
|
||||
.toSummary();
|
||||
expect(humanizeTplAst(parse('<div a c b a b>', [dirA, dirB, dirC]))).toEqual([
|
||||
[ElementAst, 'div'], [AttrAst, 'a', ''], [AttrAst, 'c', ''], [AttrAst, 'b', ''],
|
||||
[AttrAst, 'a', ''], [AttrAst, 'b', ''], [DirectiveAst, dirA],
|
||||
@ -649,7 +649,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should locate directives in property bindings', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a=b]',
|
||||
@ -657,7 +657,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
|
||||
})
|
||||
.toSummary();
|
||||
var dirB =
|
||||
const dirB =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[b]',
|
||||
@ -673,7 +673,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should locate directives in event bindings', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -688,7 +688,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should parse directive host properties', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -704,7 +704,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should parse directive host listeners', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -719,7 +719,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should parse directive properties', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -735,7 +735,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should parse renamed directive properties', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -751,7 +751,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should parse literal directive properties', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -767,7 +767,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should favor explicit bound properties over literal properties', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -784,7 +784,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should support optional directive properties', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -801,7 +801,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
describe('providers', () => {
|
||||
var nextProviderId: number;
|
||||
let nextProviderId: number;
|
||||
|
||||
function createToken(value: string): CompileTokenMetadata {
|
||||
let token: CompileTokenMetadata;
|
||||
@ -818,17 +818,17 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
}
|
||||
|
||||
function createDep(value: string): CompileDiDependencyMetadata {
|
||||
var isOptional = false;
|
||||
let isOptional = false;
|
||||
if (value.startsWith('optional:')) {
|
||||
isOptional = true;
|
||||
value = value.substring(9);
|
||||
}
|
||||
var isSelf = false;
|
||||
let isSelf = false;
|
||||
if (value.startsWith('self:')) {
|
||||
isSelf = true;
|
||||
value = value.substring(5);
|
||||
}
|
||||
var isHost = false;
|
||||
let isHost = false;
|
||||
if (value.startsWith('host:')) {
|
||||
isHost = true;
|
||||
value = value.substring(5);
|
||||
@ -861,7 +861,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
deps?: string[],
|
||||
queries?: string[]
|
||||
} = {}): CompileDirectiveSummary {
|
||||
var isComponent = !selector.startsWith('[');
|
||||
const isComponent = !selector.startsWith('[');
|
||||
return CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: selector,
|
||||
@ -884,96 +884,96 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
beforeEach(() => { nextProviderId = 0; });
|
||||
|
||||
it('should provide a component', () => {
|
||||
var comp = createDir('my-comp');
|
||||
var elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0];
|
||||
const comp = createDir('my-comp');
|
||||
const elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0];
|
||||
expect(elAst.providers.length).toBe(1);
|
||||
expect(elAst.providers[0].providerType).toBe(ProviderAstType.Component);
|
||||
expect(elAst.providers[0].providers[0].useClass).toBe(comp.type);
|
||||
});
|
||||
|
||||
it('should provide a directive', () => {
|
||||
var dirA = createDir('[dirA]');
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0];
|
||||
const dirA = createDir('[dirA]');
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0];
|
||||
expect(elAst.providers.length).toBe(1);
|
||||
expect(elAst.providers[0].providerType).toBe(ProviderAstType.Directive);
|
||||
expect(elAst.providers[0].providers[0].useClass).toBe(dirA.type);
|
||||
});
|
||||
|
||||
it('should use the public providers of a directive', () => {
|
||||
var provider = createProvider('service');
|
||||
var dirA = createDir('[dirA]', {providers: [provider]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0];
|
||||
const provider = createProvider('service');
|
||||
const dirA = createDir('[dirA]', {providers: [provider]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0];
|
||||
expect(elAst.providers.length).toBe(2);
|
||||
expect(elAst.providers[1].providerType).toBe(ProviderAstType.PublicService);
|
||||
expect(elAst.providers[1].providers).toEqual([provider]);
|
||||
});
|
||||
|
||||
it('should use the private providers of a component', () => {
|
||||
var provider = createProvider('service');
|
||||
var comp = createDir('my-comp', {viewProviders: [provider]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0];
|
||||
const provider = createProvider('service');
|
||||
const comp = createDir('my-comp', {viewProviders: [provider]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0];
|
||||
expect(elAst.providers.length).toBe(2);
|
||||
expect(elAst.providers[1].providerType).toBe(ProviderAstType.PrivateService);
|
||||
expect(elAst.providers[1].providers).toEqual([provider]);
|
||||
});
|
||||
|
||||
it('should support multi providers', () => {
|
||||
var provider0 = createProvider('service0', {multi: true});
|
||||
var provider1 = createProvider('service1', {multi: true});
|
||||
var provider2 = createProvider('service0', {multi: true});
|
||||
var dirA = createDir('[dirA]', {providers: [provider0, provider1]});
|
||||
var dirB = createDir('[dirB]', {providers: [provider2]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA dirB>', [dirA, dirB])[0];
|
||||
const provider0 = createProvider('service0', {multi: true});
|
||||
const provider1 = createProvider('service1', {multi: true});
|
||||
const provider2 = createProvider('service0', {multi: true});
|
||||
const dirA = createDir('[dirA]', {providers: [provider0, provider1]});
|
||||
const dirB = createDir('[dirB]', {providers: [provider2]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA dirB>', [dirA, dirB])[0];
|
||||
expect(elAst.providers.length).toBe(4);
|
||||
expect(elAst.providers[2].providers).toEqual([provider0, provider2]);
|
||||
expect(elAst.providers[3].providers).toEqual([provider1]);
|
||||
});
|
||||
|
||||
it('should overwrite non multi providers', () => {
|
||||
var provider1 = createProvider('service0');
|
||||
var provider2 = createProvider('service1');
|
||||
var provider3 = createProvider('service0');
|
||||
var dirA = createDir('[dirA]', {providers: [provider1, provider2]});
|
||||
var dirB = createDir('[dirB]', {providers: [provider3]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA dirB>', [dirA, dirB])[0];
|
||||
const provider1 = createProvider('service0');
|
||||
const provider2 = createProvider('service1');
|
||||
const provider3 = createProvider('service0');
|
||||
const dirA = createDir('[dirA]', {providers: [provider1, provider2]});
|
||||
const dirB = createDir('[dirB]', {providers: [provider3]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA dirB>', [dirA, dirB])[0];
|
||||
expect(elAst.providers.length).toBe(4);
|
||||
expect(elAst.providers[2].providers).toEqual([provider3]);
|
||||
expect(elAst.providers[3].providers).toEqual([provider2]);
|
||||
});
|
||||
|
||||
it('should overwrite component providers by directive providers', () => {
|
||||
var compProvider = createProvider('service0');
|
||||
var dirProvider = createProvider('service0');
|
||||
var comp = createDir('my-comp', {providers: [compProvider]});
|
||||
var dirA = createDir('[dirA]', {providers: [dirProvider]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<my-comp dirA>', [dirA, comp])[0];
|
||||
const compProvider = createProvider('service0');
|
||||
const dirProvider = createProvider('service0');
|
||||
const comp = createDir('my-comp', {providers: [compProvider]});
|
||||
const dirA = createDir('[dirA]', {providers: [dirProvider]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<my-comp dirA>', [dirA, comp])[0];
|
||||
expect(elAst.providers.length).toBe(3);
|
||||
expect(elAst.providers[2].providers).toEqual([dirProvider]);
|
||||
});
|
||||
|
||||
it('should overwrite view providers by directive providers', () => {
|
||||
var viewProvider = createProvider('service0');
|
||||
var dirProvider = createProvider('service0');
|
||||
var comp = createDir('my-comp', {viewProviders: [viewProvider]});
|
||||
var dirA = createDir('[dirA]', {providers: [dirProvider]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<my-comp dirA>', [dirA, comp])[0];
|
||||
const viewProvider = createProvider('service0');
|
||||
const dirProvider = createProvider('service0');
|
||||
const comp = createDir('my-comp', {viewProviders: [viewProvider]});
|
||||
const dirA = createDir('[dirA]', {providers: [dirProvider]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<my-comp dirA>', [dirA, comp])[0];
|
||||
expect(elAst.providers.length).toBe(3);
|
||||
expect(elAst.providers[2].providers).toEqual([dirProvider]);
|
||||
});
|
||||
|
||||
it('should overwrite directives by providers', () => {
|
||||
var dirProvider = createProvider('type:my-comp');
|
||||
var comp = createDir('my-comp', {providers: [dirProvider]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0];
|
||||
const dirProvider = createProvider('type:my-comp');
|
||||
const comp = createDir('my-comp', {providers: [dirProvider]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0];
|
||||
expect(elAst.providers.length).toBe(1);
|
||||
expect(elAst.providers[0].providers).toEqual([dirProvider]);
|
||||
});
|
||||
|
||||
it('if mixing multi and non multi providers', () => {
|
||||
var provider0 = createProvider('service0');
|
||||
var provider1 = createProvider('service0', {multi: true});
|
||||
var dirA = createDir('[dirA]', {providers: [provider0]});
|
||||
var dirB = createDir('[dirB]', {providers: [provider1]});
|
||||
const provider0 = createProvider('service0');
|
||||
const provider1 = createProvider('service0', {multi: true});
|
||||
const dirA = createDir('[dirA]', {providers: [provider0]});
|
||||
const dirB = createDir('[dirB]', {providers: [provider1]});
|
||||
expect(() => parse('<div dirA dirB>', [dirA, dirB]))
|
||||
.toThrowError(
|
||||
`Template parse errors:\n` +
|
||||
@ -981,11 +981,11 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should sort providers by their DI order', () => {
|
||||
var provider0 = createProvider('service0', {deps: ['type:[dir2]']});
|
||||
var provider1 = createProvider('service1');
|
||||
var dir2 = createDir('[dir2]', {deps: ['service1']});
|
||||
var comp = createDir('my-comp', {providers: [provider0, provider1]});
|
||||
var elAst: ElementAst = <ElementAst>parse('<my-comp dir2>', [comp, dir2])[0];
|
||||
const provider0 = createProvider('service0', {deps: ['type:[dir2]']});
|
||||
const provider1 = createProvider('service1');
|
||||
const dir2 = createDir('[dir2]', {deps: ['service1']});
|
||||
const comp = createDir('my-comp', {providers: [provider0, provider1]});
|
||||
const elAst: ElementAst = <ElementAst>parse('<my-comp dir2>', [comp, dir2])[0];
|
||||
expect(elAst.providers.length).toBe(4);
|
||||
expect(elAst.providers[0].providers[0].useClass).toEqual(comp.type);
|
||||
expect(elAst.providers[1].providers).toEqual([provider1]);
|
||||
@ -994,11 +994,11 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should sort directives by their DI order', () => {
|
||||
var dir0 = createDir('[dir0]', {deps: ['type:my-comp']});
|
||||
var dir1 = createDir('[dir1]', {deps: ['type:[dir0]']});
|
||||
var dir2 = createDir('[dir2]', {deps: ['type:[dir1]']});
|
||||
var comp = createDir('my-comp');
|
||||
var elAst: ElementAst =
|
||||
const dir0 = createDir('[dir0]', {deps: ['type:my-comp']});
|
||||
const dir1 = createDir('[dir1]', {deps: ['type:[dir0]']});
|
||||
const dir2 = createDir('[dir2]', {deps: ['type:[dir1]']});
|
||||
const comp = createDir('my-comp');
|
||||
const elAst: ElementAst =
|
||||
<ElementAst>parse('<my-comp dir2 dir0 dir1>', [comp, dir2, dir0, dir1])[0];
|
||||
expect(elAst.providers.length).toBe(4);
|
||||
expect(elAst.directives[0].directive).toBe(comp);
|
||||
@ -1008,11 +1008,11 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should mark directives and dependencies of directives as eager', () => {
|
||||
var provider0 = createProvider('service0');
|
||||
var provider1 = createProvider('service1');
|
||||
var dirA =
|
||||
const provider0 = createProvider('service0');
|
||||
const provider1 = createProvider('service1');
|
||||
const dirA =
|
||||
createDir('[dirA]', {providers: [provider0, provider1], deps: ['service0']});
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0];
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0];
|
||||
expect(elAst.providers.length).toBe(3);
|
||||
expect(elAst.providers[0].providers).toEqual([provider0]);
|
||||
expect(elAst.providers[0].eager).toBe(true);
|
||||
@ -1023,11 +1023,11 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should mark dependencies on parent elements as eager', () => {
|
||||
var provider0 = createProvider('service0');
|
||||
var provider1 = createProvider('service1');
|
||||
var dirA = createDir('[dirA]', {providers: [provider0, provider1]});
|
||||
var dirB = createDir('[dirB]', {deps: ['service0']});
|
||||
var elAst: ElementAst =
|
||||
const provider0 = createProvider('service0');
|
||||
const provider1 = createProvider('service1');
|
||||
const dirA = createDir('[dirA]', {providers: [provider0, provider1]});
|
||||
const dirB = createDir('[dirB]', {deps: ['service0']});
|
||||
const elAst: ElementAst =
|
||||
<ElementAst>parse('<div dirA><div dirB></div></div>', [dirA, dirB])[0];
|
||||
expect(elAst.providers.length).toBe(3);
|
||||
expect(elAst.providers[0].providers[0].useClass).toEqual(dirA.type);
|
||||
@ -1039,11 +1039,11 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should mark queried providers as eager', () => {
|
||||
var provider0 = createProvider('service0');
|
||||
var provider1 = createProvider('service1');
|
||||
var dirA =
|
||||
const provider0 = createProvider('service0');
|
||||
const provider1 = createProvider('service1');
|
||||
const dirA =
|
||||
createDir('[dirA]', {providers: [provider0, provider1], queries: ['service0']});
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0];
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0];
|
||||
expect(elAst.providers.length).toBe(3);
|
||||
expect(elAst.providers[0].providers[0].useClass).toEqual(dirA.type);
|
||||
expect(elAst.providers[0].eager).toBe(true);
|
||||
@ -1054,10 +1054,10 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should not mark dependencies accross embedded views as eager', () => {
|
||||
var provider0 = createProvider('service0');
|
||||
var dirA = createDir('[dirA]', {providers: [provider0]});
|
||||
var dirB = createDir('[dirB]', {deps: ['service0']});
|
||||
var elAst: ElementAst =
|
||||
const provider0 = createProvider('service0');
|
||||
const dirA = createDir('[dirA]', {providers: [provider0]});
|
||||
const dirB = createDir('[dirB]', {deps: ['service0']});
|
||||
const elAst: ElementAst =
|
||||
<ElementAst>parse('<div dirA><div *ngIf dirB></div></div>', [dirA, dirB])[0];
|
||||
expect(elAst.providers.length).toBe(2);
|
||||
expect(elAst.providers[0].providers[0].useClass).toEqual(dirA.type);
|
||||
@ -1067,29 +1067,29 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should report missing @Self() deps as errors', () => {
|
||||
var dirA = createDir('[dirA]', {deps: ['self:provider0']});
|
||||
const dirA = createDir('[dirA]', {deps: ['self:provider0']});
|
||||
expect(() => parse('<div dirA></div>', [dirA]))
|
||||
.toThrowError(
|
||||
'Template parse errors:\nNo provider for provider0 ("[ERROR ->]<div dirA></div>"): TestComp@0:0');
|
||||
});
|
||||
|
||||
it('should change missing @Self() that are optional to nulls', () => {
|
||||
var dirA = createDir('[dirA]', {deps: ['optional:self:provider0']});
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0];
|
||||
const dirA = createDir('[dirA]', {deps: ['optional:self:provider0']});
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0];
|
||||
expect(elAst.providers[0].providers[0].deps[0].isValue).toBe(true);
|
||||
expect(elAst.providers[0].providers[0].deps[0].value).toBe(null);
|
||||
});
|
||||
|
||||
it('should report missing @Host() deps as errors', () => {
|
||||
var dirA = createDir('[dirA]', {deps: ['host:provider0']});
|
||||
const dirA = createDir('[dirA]', {deps: ['host:provider0']});
|
||||
expect(() => parse('<div dirA></div>', [dirA]))
|
||||
.toThrowError(
|
||||
'Template parse errors:\nNo provider for provider0 ("[ERROR ->]<div dirA></div>"): TestComp@0:0');
|
||||
});
|
||||
|
||||
it('should change missing @Host() that are optional to nulls', () => {
|
||||
var dirA = createDir('[dirA]', {deps: ['optional:host:provider0']});
|
||||
var elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0];
|
||||
const dirA = createDir('[dirA]', {deps: ['optional:host:provider0']});
|
||||
const elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0];
|
||||
expect(elAst.providers[0].providers[0].deps[0].isValue).toBe(true);
|
||||
expect(elAst.providers[0].providers[0].deps[0].value).toBe(null);
|
||||
});
|
||||
@ -1118,7 +1118,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
|
||||
});
|
||||
|
||||
it('should assign references to directives via exportAs', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -1165,7 +1165,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
|
||||
});
|
||||
|
||||
it('should assign references with empty value to components', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -1185,7 +1185,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
|
||||
});
|
||||
|
||||
it('should not locate directives in references', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -1235,7 +1235,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
|
||||
});
|
||||
|
||||
it('should not locate directives in variables', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -1281,7 +1281,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
|
||||
|
||||
describe('directives', () => {
|
||||
it('should locate directives in property bindings', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a=b]',
|
||||
@ -1290,16 +1290,16 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
|
||||
inputs: ['a']
|
||||
})
|
||||
.toSummary();
|
||||
var dirB = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[b]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirB',
|
||||
reference: {} as Type<any>
|
||||
const dirB = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[b]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirB',
|
||||
reference: {} as Type<any>
|
||||
})
|
||||
})
|
||||
})
|
||||
.toSummary();
|
||||
.toSummary();
|
||||
expect(humanizeTplAst(parse('<div template="a b" b>', [dirA, dirB]))).toEqual([
|
||||
[EmbeddedTemplateAst], [DirectiveAst, dirA],
|
||||
[BoundDirectivePropertyAst, 'a', 'b'], [ElementAst, 'div'], [AttrAst, 'b', ''],
|
||||
@ -1308,32 +1308,32 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
|
||||
});
|
||||
|
||||
it('should not locate directives in variables', () => {
|
||||
var dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
const dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
})
|
||||
})
|
||||
})
|
||||
.toSummary();
|
||||
.toSummary();
|
||||
expect(humanizeTplAst(parse('<div template="let a=b">', [dirA]))).toEqual([
|
||||
[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']
|
||||
]);
|
||||
});
|
||||
|
||||
it('should not locate directives in references', () => {
|
||||
var dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
const dirA = CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
type: new CompileTypeMetadata({
|
||||
moduleUrl: someModuleUrl,
|
||||
name: 'DirA',
|
||||
reference: {} as Type<any>
|
||||
})
|
||||
})
|
||||
})
|
||||
.toSummary();
|
||||
.toSummary();
|
||||
expect(humanizeTplAst(parse('<div ref-a>', [dirA]))).toEqual([
|
||||
[ElementAst, 'div'], [ReferenceAst, 'a', null]
|
||||
]);
|
||||
@ -1358,7 +1358,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
|
||||
});
|
||||
|
||||
describe('content projection', () => {
|
||||
var compCounter: number;
|
||||
let compCounter: number;
|
||||
beforeEach(() => { compCounter = 0; });
|
||||
|
||||
function createComp(
|
||||
@ -1555,7 +1555,7 @@ Can't bind to 'invalidProp' since it isn't a known property of 'div'. ("<div [ER
|
||||
});
|
||||
|
||||
it('should report invalid host property names', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -1575,7 +1575,7 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 ("<div [
|
||||
|
||||
it('should not throw on invalid property names if the property is used by a directive',
|
||||
() => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -1588,7 +1588,7 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 ("<div [
|
||||
});
|
||||
|
||||
it('should not allow more than 1 component per element', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -1598,7 +1598,7 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 ("<div [
|
||||
template: new CompileTemplateMetadata({ngContentSelectors: []})
|
||||
})
|
||||
.toSummary();
|
||||
var dirB =
|
||||
const dirB =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -1618,7 +1618,7 @@ Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 ("<div [
|
||||
|
||||
it('should not allow components or element bindings nor dom events on explicit embedded templates',
|
||||
() => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -1636,7 +1636,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
});
|
||||
|
||||
it('should not allow components or element bindings on inline embedded templates', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -1737,7 +1737,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
|
||||
describe('source spans', () => {
|
||||
it('should support ng-content', () => {
|
||||
var parsed = parse('<ng-content select="a">', []);
|
||||
const parsed = parse('<ng-content select="a">', []);
|
||||
expect(humanizeTplAstSourceSpans(parsed)).toEqual([
|
||||
[NgContentAst, '<ng-content select="a">']
|
||||
]);
|
||||
@ -1797,7 +1797,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
});
|
||||
|
||||
it('should support directive', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[a]',
|
||||
@ -1805,7 +1805,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
{moduleUrl: someModuleUrl, name: 'DirA', reference: {} as Type<any>})
|
||||
})
|
||||
.toSummary();
|
||||
var comp =
|
||||
const comp =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -1822,7 +1822,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
});
|
||||
|
||||
it('should support directive in namespace', () => {
|
||||
var tagSel =
|
||||
const tagSel =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'circle',
|
||||
@ -1830,7 +1830,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
{moduleUrl: someModuleUrl, name: 'elDir', reference: {} as Type<any>})
|
||||
})
|
||||
.toSummary();
|
||||
var attrSel =
|
||||
const attrSel =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: '[href]',
|
||||
@ -1852,7 +1852,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
});
|
||||
|
||||
it('should support directive property', () => {
|
||||
var dirA =
|
||||
const dirA =
|
||||
CompileDirectiveMetadata
|
||||
.create({
|
||||
selector: 'div',
|
||||
@ -1910,7 +1910,7 @@ Property binding a not used by any directive on an embedded template. Make sure
|
||||
|
||||
describe('pipes', () => {
|
||||
it('should allow pipes that have been defined as dependencies', () => {
|
||||
var testPipe =
|
||||
const testPipe =
|
||||
new CompilePipeMetadata({
|
||||
name: 'test',
|
||||
type: new CompileTypeMetadata(
|
||||
@ -1982,12 +1982,12 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||
private interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG){};
|
||||
|
||||
visitNgContent(ast: NgContentAst, context: any): any {
|
||||
var res = [NgContentAst];
|
||||
const res = [NgContentAst];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
return null;
|
||||
}
|
||||
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
|
||||
var res = [EmbeddedTemplateAst];
|
||||
const res = [EmbeddedTemplateAst];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
templateVisitAll(this, ast.attrs);
|
||||
templateVisitAll(this, ast.outputs);
|
||||
@ -1998,7 +1998,7 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||
return null;
|
||||
}
|
||||
visitElement(ast: ElementAst, context: any): any {
|
||||
var res = [ElementAst, ast.name];
|
||||
const res = [ElementAst, ast.name];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
templateVisitAll(this, ast.attrs);
|
||||
templateVisitAll(this, ast.inputs);
|
||||
@ -2009,22 +2009,23 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||
return null;
|
||||
}
|
||||
visitReference(ast: ReferenceAst, context: any): any {
|
||||
var res = [ReferenceAst, ast.name, ast.value];
|
||||
const res = [ReferenceAst, ast.name, ast.value];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
return null;
|
||||
}
|
||||
visitVariable(ast: VariableAst, context: any): any {
|
||||
var res = [VariableAst, ast.name, ast.value];
|
||||
const res = [VariableAst, ast.name, ast.value];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
return null;
|
||||
}
|
||||
visitEvent(ast: BoundEventAst, context: any): any {
|
||||
var res = [BoundEventAst, ast.name, ast.target, unparse(ast.handler, this.interpolationConfig)];
|
||||
const res =
|
||||
[BoundEventAst, ast.name, ast.target, unparse(ast.handler, this.interpolationConfig)];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
return null;
|
||||
}
|
||||
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
|
||||
var res = [
|
||||
const res = [
|
||||
BoundElementPropertyAst, ast.type, ast.name, unparse(ast.value, this.interpolationConfig),
|
||||
ast.unit
|
||||
];
|
||||
@ -2032,22 +2033,22 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||
return null;
|
||||
}
|
||||
visitAttr(ast: AttrAst, context: any): any {
|
||||
var res = [AttrAst, ast.name, ast.value];
|
||||
const res = [AttrAst, ast.name, ast.value];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
return null;
|
||||
}
|
||||
visitBoundText(ast: BoundTextAst, context: any): any {
|
||||
var res = [BoundTextAst, unparse(ast.value, this.interpolationConfig)];
|
||||
const res = [BoundTextAst, unparse(ast.value, this.interpolationConfig)];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
return null;
|
||||
}
|
||||
visitText(ast: TextAst, context: any): any {
|
||||
var res = [TextAst, ast.value];
|
||||
const res = [TextAst, ast.value];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
return null;
|
||||
}
|
||||
visitDirective(ast: DirectiveAst, context: any): any {
|
||||
var res = [DirectiveAst, ast.directive];
|
||||
const res = [DirectiveAst, ast.directive];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
templateVisitAll(this, ast.inputs);
|
||||
templateVisitAll(this, ast.hostProperties);
|
||||
@ -2055,7 +2056,7 @@ class TemplateHumanizer implements TemplateAstVisitor {
|
||||
return null;
|
||||
}
|
||||
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
|
||||
var res = [
|
||||
const res = [
|
||||
BoundDirectivePropertyAst, ast.directiveName, unparse(ast.value, this.interpolationConfig)
|
||||
];
|
||||
this.result.push(this._appendContext(ast, res));
|
||||
@ -2074,7 +2075,7 @@ function sourceInfo(ast: TemplateAst): string {
|
||||
}
|
||||
|
||||
function humanizeContentProjection(templateAsts: TemplateAst[]): any[] {
|
||||
var humanizer = new TemplateContentProjectionHumanizer();
|
||||
const humanizer = new TemplateContentProjectionHumanizer();
|
||||
templateVisitAll(humanizer, templateAsts);
|
||||
return humanizer.result;
|
||||
}
|
||||
|
@ -13,7 +13,7 @@ import {PreparsedElement, PreparsedElementType, preparseElement} from '../../src
|
||||
|
||||
export function main() {
|
||||
describe('preparseElement', () => {
|
||||
var htmlParser: HtmlParser;
|
||||
let htmlParser: HtmlParser;
|
||||
beforeEach(inject([HtmlParser], (_htmlParser: HtmlParser) => { htmlParser = _htmlParser; }));
|
||||
|
||||
function preparse(html: string): PreparsedElement {
|
||||
|
@ -11,7 +11,7 @@ import {beforeEach, describe, expect, inject, it} from '@angular/core/testing/te
|
||||
|
||||
export function main() {
|
||||
describe('UrlResolver', () => {
|
||||
var resolver = new UrlResolver();
|
||||
let resolver = new UrlResolver();
|
||||
|
||||
describe('absolute base url', () => {
|
||||
it('should add a relative path to the base url', () => {
|
||||
@ -107,7 +107,7 @@ export function main() {
|
||||
});
|
||||
|
||||
describe('asset urls', () => {
|
||||
var resolver: UrlResolver;
|
||||
let resolver: UrlResolver;
|
||||
beforeEach(() => { resolver = createOfflineCompileUrlResolver(); });
|
||||
|
||||
it('should resolve package: urls into asset: urls', () => {
|
||||
|
@ -151,8 +151,8 @@ export class MockDirectiveResolver extends DirectiveResolver {
|
||||
|
||||
function flattenArray(tree: any[], out: Array<Type<any>|any[]>): void {
|
||||
if (!isPresent(tree)) return;
|
||||
for (var i = 0; i < tree.length; i++) {
|
||||
var item = resolveForwardRef(tree[i]);
|
||||
for (let i = 0; i < tree.length; i++) {
|
||||
const item = resolveForwardRef(tree[i]);
|
||||
if (Array.isArray(item)) {
|
||||
flattenArray(item, out);
|
||||
} else {
|
||||
|
@ -46,7 +46,7 @@ export class MetadataOverrider {
|
||||
|
||||
function removeMetadata(metadata: StringMap, remove: any, references: Map<any, string>) {
|
||||
const removeObjects = new Set<string>();
|
||||
for (let prop in remove) {
|
||||
for (const prop in remove) {
|
||||
const removeValue = remove[prop];
|
||||
if (removeValue instanceof Array) {
|
||||
removeValue.forEach(
|
||||
@ -56,7 +56,7 @@ function removeMetadata(metadata: StringMap, remove: any, references: Map<any, s
|
||||
}
|
||||
}
|
||||
|
||||
for (let prop in metadata) {
|
||||
for (const prop in metadata) {
|
||||
const propValue = metadata[prop];
|
||||
if (propValue instanceof Array) {
|
||||
metadata[prop] = propValue.filter(
|
||||
@ -70,7 +70,7 @@ function removeMetadata(metadata: StringMap, remove: any, references: Map<any, s
|
||||
}
|
||||
|
||||
function addMetadata(metadata: StringMap, add: any) {
|
||||
for (let prop in add) {
|
||||
for (const prop in add) {
|
||||
const addValue = add[prop];
|
||||
const propValue = metadata[prop];
|
||||
if (propValue != null && propValue instanceof Array) {
|
||||
@ -82,7 +82,7 @@ function addMetadata(metadata: StringMap, add: any) {
|
||||
}
|
||||
|
||||
function setMetadata(metadata: StringMap, set: any) {
|
||||
for (let prop in set) {
|
||||
for (const prop in set) {
|
||||
metadata[prop] = set[prop];
|
||||
}
|
||||
}
|
||||
@ -121,7 +121,7 @@ function _valueProps(obj: any): string[] {
|
||||
let proto = obj;
|
||||
while (proto = Object.getPrototypeOf(proto)) {
|
||||
Object.keys(proto).forEach((protoProp) => {
|
||||
var desc = Object.getOwnPropertyDescriptor(proto, protoProp);
|
||||
const desc = Object.getOwnPropertyDescriptor(proto, protoProp);
|
||||
if (!protoProp.startsWith('_') && desc && 'get' in desc) {
|
||||
props.push(protoProp);
|
||||
}
|
||||
|
@ -34,7 +34,7 @@ export class MockPipeResolver extends PipeResolver {
|
||||
* `PipeResolver`, see `setPipe`.
|
||||
*/
|
||||
resolve(type: Type<any>, throwIfNotFound = true): Pipe {
|
||||
var metadata = this._pipes.get(type);
|
||||
let metadata = this._pipes.get(type);
|
||||
if (!metadata) {
|
||||
metadata = super.resolve(type, throwIfNotFound);
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user