From 126fda2613b1ad87ff62591bb1d3a23cd8f369a1 Mon Sep 17 00:00:00 2001 From: Tobias Bosch Date: Mon, 27 Feb 2017 23:08:19 -0800 Subject: [PATCH] perf: delete pre-view-engine core, compiler, platform-browser, etc code (#14788) After the introduction of the view engine, we can drop a lot of code that is not used any more. This should reduce the size of the app bundles because a lot of this code was not being properly tree-shaken by today's tools even though it was dead code. --- .../compiler/src/animation/animation_ast.ts | 109 -- .../src/animation/animation_compiler.ts | 391 ------ .../src/animation/animation_parser.ts | 605 ---------- .../src/animation/styles_collection.ts | 59 - modules/@angular/compiler/src/aot/compiler.ts | 67 +- .../compiler/src/aot/compiler_factory.ts | 11 +- .../compiler/src/aot/compiler_options.ts | 1 - .../@angular/compiler/src/compile_metadata.ts | 20 +- modules/@angular/compiler/src/compiler.ts | 4 +- .../src/compiler_util/binding_util.ts | 31 - .../src/compiler_util/expression_converter.ts | 126 -- .../src/compiler_util/identifier_util.ts | 57 - .../compiler/src/compiler_util/render_util.ts | 153 --- modules/@angular/compiler/src/config.ts | 42 +- .../src/directive_wrapper_compiler.ts | 461 ------- modules/@angular/compiler/src/identifiers.ts | 178 +-- modules/@angular/compiler/src/jit/compiler.ts | 44 +- .../compiler/src/jit/compiler_factory.ts | 24 +- .../compiler/src/metadata_resolver.ts | 15 +- .../compiler/src/ng_module_compiler.ts | 9 +- .../src/template_parser/binding_parser.ts | 8 +- .../src/template_parser/template_ast.ts | 4 +- .../src/template_parser/template_parser.ts | 42 +- .../src/view_compiler/compile_element.ts | 402 ------- .../src/view_compiler/compile_method.ts | 81 -- .../src/view_compiler/compile_pipe.ts | 94 -- .../src/view_compiler/compile_query.ts | 133 -- .../src/view_compiler/compile_view.ts | 176 --- .../compiler/src/view_compiler/constants.ts | 49 - .../compiler/src/view_compiler/deps.ts | 31 - .../src/view_compiler/event_binder.ts | 135 --- .../src/view_compiler/lifecycle_binder.ts | 85 -- .../src/view_compiler/property_binder.ts | 146 --- .../src/view_compiler/query_binder.ts | 57 - .../compiler/src/view_compiler/util.ts | 75 -- .../compiler/src/view_compiler/view_binder.ts | 113 -- .../src/view_compiler/view_builder.ts | 697 ----------- .../src/view_compiler/view_compiler.ts | 1067 ++++++++++++++++- .../compiler/src/view_compiler_next/README.md | 5 - .../src/view_compiler_next/view_compiler.ts | 1064 ---------------- .../compiler/test/aot/compiler_spec.ts | 14 - .../compiler_util/identifier_util_spec.ts | 63 - .../template_parser/template_parser_spec.ts | 4 +- .../compiler/test/view_compiler/util_spec.ts | 65 - .../core/src/animation/animation_constants.ts | 12 - .../src/animation/animation_group_player.ts | 110 -- .../core/src/animation/animation_keyframe.ts | 23 - .../animation_metadata_wrapped.ts | 0 .../core/src/animation/animation_player.ts | 75 -- .../core/src/animation/animation_queue.ts | 51 - .../animation/animation_sequence_player.ts | 117 -- .../src/animation/animation_style_util.ts | 128 -- .../core/src/animation/animation_styles.ts | 25 - .../src/animation/animation_transition.ts | 40 - .../animation/animation_transition_event.ts | 64 - .../src/{animation_next => animation}/dsl.ts | 0 .../@angular/core/src/animation/metadata.ts | 644 ---------- .../core/src/animation/view_animation_map.ts | 62 - .../@angular/core/src/application_module.ts | 4 - modules/@angular/core/src/application_ref.ts | 1 - .../core/src/codegen_private_exports.ts | 18 +- modules/@angular/core/src/core.ts | 23 +- .../@angular/core/src/core_private_export.ts | 13 - .../@angular/core/src/debug/debug_renderer.ts | 161 --- .../core/src/linker/animation_view_context.ts | 57 - .../core/src/linker/component_factory.ts | 52 +- .../@angular/core/src/linker/debug_context.ts | 80 -- .../core/src/linker/element_injector.ts | 18 - modules/@angular/core/src/linker/errors.ts | 81 -- .../@angular/core/src/linker/template_ref.ts | 20 - modules/@angular/core/src/linker/view.ts | 472 -------- .../core/src/linker/view_container.ts | 132 -- .../core/src/linker/view_container_ref.ts | 100 +- modules/@angular/core/src/linker/view_ref.ts | 47 - modules/@angular/core/src/linker/view_type.ts | 17 - .../@angular/core/src/linker/view_utils.ts | 736 ------------ .../@angular/core/src/metadata/directives.ts | 3 +- modules/@angular/core/src/metadata/view.ts | 6 +- modules/@angular/core/src/render/api.ts | 8 +- modules/@angular/core/src/view/index.ts | 4 +- modules/@angular/core/src/view/refs.ts | 22 +- modules/@angular/core/src/view/util.ts | 53 + .../active_animations_players_map_spec.ts | 76 -- .../animation/animation_group_player_spec.ts | 204 ---- ..._spec.ts => animation_integration_spec.ts} | 17 - .../test/animation/animation_player_spec.ts | 45 - .../test/animation/animation_queue_spec.ts | 143 --- .../animation_sequence_player_spec.ts | 226 ---- .../animation/animation_style_util_spec.ts | 148 --- .../@angular/core/test/error_handler_spec.ts | 11 +- .../linker/animation_view_context_spec.ts | 62 - .../change_detection_integration_spec.ts | 41 - .../direct_rendering_integration_spec.ts | 185 --- .../entry_components_integration_spec.ts | 14 - .../core/test/linker/integration_spec.ts | 25 +- .../linker/projection_integration_spec.ts | 14 - .../test/linker/query_integration_spec.ts | 14 - .../linker/view_injector_integration_spec.ts | 14 - .../core/testing/mock_animation_player.ts | 115 -- .../core/testing/private_export_testing.ts | 1 - .../@angular/core/testing/testing_internal.ts | 1 - .../test/noop_animations_module_spec.ts | 12 +- .../@angular/platform-browser/src/browser.ts | 15 +- .../src/dom/animation_driver.ts | 33 - .../src/dom/debug/ng_probe.ts | 22 +- .../src/dom/dom_animate_player.ts | 19 - .../platform-browser/src/dom/dom_renderer.ts | 306 +---- .../src/dom/web_animations_driver.ts | 81 -- .../src/dom/web_animations_player.ts | 200 --- .../platform-browser/src/platform-browser.ts | 1 - .../platform-browser/src/private_export.ts | 3 +- .../test/animation/animation_renderer_spec.ts | 10 +- .../test/dom/web_animations_driver_spec.ts | 124 -- .../test/dom/web_animations_player_spec.ts | 263 ---- .../platform-browser/testing/browser.ts | 6 +- .../testing/mock_animation_driver.ts | 52 - .../testing/mock_dom_animate_player.ts | 49 - .../@angular/platform-server/src/server.ts | 11 +- .../platform-server/src/server_renderer.ts | 254 +--- .../platform-server/test/integration_spec.ts | 20 - .../src/web_workers/shared/messaging_api.ts | 3 - .../src/web_workers/shared/serializer.ts | 2 - .../src/web_workers/ui/renderer.ts | 232 +--- .../src/web_workers/worker/renderer.ts | 376 +----- .../platform-webworker/src/worker_app.ts | 4 +- .../platform-webworker/src/worker_render.ts | 12 +- .../worker/renderer_integration_spec.ts | 218 ---- .../worker/renderer_v2_integration_spec.ts | 45 +- modules/benchmarks/e2e_test/tree_perf.ts | 26 - modules/benchmarks/e2e_test/tree_spec.ts | 20 - modules/benchmarks/src/tree/ng2_ftl/README.md | 168 --- .../src/tree/ng2_ftl/app.ngfactory.ts | 328 ----- .../benchmarks/src/tree/ng2_ftl/ftl_util.ts | 221 ---- .../benchmarks/src/tree/ng2_ftl/index.html | 26 - modules/benchmarks/src/tree/ng2_ftl/index.ts | 49 - .../src/tree/ng2_ftl/ng_if.ngfactory.ts | 20 - .../src/tree/ng2_ftl/tree.ngfactory.ts | 126 -- modules/benchmarks/src/tree/ng2_ftl/tree.ts | 13 - .../src/tree/ng2_ftl/tree_host.ngfactory.ts | 57 - .../src/tree/ng2_static_ftl/README.md | 79 -- .../src/tree/ng2_static_ftl/app.ngfactory.ts | 328 ----- .../benchmarks/src/tree/ng2_static_ftl/app.ts | 9 - .../src/tree/ng2_static_ftl/ftl_util.ts | 38 - .../src/tree/ng2_static_ftl/index.html | 26 - .../src/tree/ng2_static_ftl/index.ts | 49 - .../src/tree/ng2_static_ftl/tree.ts | 15 - .../ng2_static_ftl/tree_branch.ngfactory.ts | 75 -- .../ng2_static_ftl/tree_leaf.ngfactory.ts | 55 - .../ng2_static_ftl/tree_root.ngfactory.ts | 141 --- tools/public_api_guard/core/typings/core.d.ts | 49 +- .../typings/platform-browser.d.ts | 6 - 151 files changed, 1284 insertions(+), 14865 deletions(-) delete mode 100644 modules/@angular/compiler/src/animation/animation_ast.ts delete mode 100644 modules/@angular/compiler/src/animation/animation_compiler.ts delete mode 100644 modules/@angular/compiler/src/animation/animation_parser.ts delete mode 100644 modules/@angular/compiler/src/animation/styles_collection.ts delete mode 100644 modules/@angular/compiler/src/compiler_util/binding_util.ts delete mode 100644 modules/@angular/compiler/src/compiler_util/identifier_util.ts delete mode 100644 modules/@angular/compiler/src/compiler_util/render_util.ts delete mode 100644 modules/@angular/compiler/src/directive_wrapper_compiler.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/compile_element.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/compile_method.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/compile_pipe.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/compile_query.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/compile_view.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/constants.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/deps.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/event_binder.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/lifecycle_binder.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/property_binder.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/query_binder.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/util.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/view_binder.ts delete mode 100644 modules/@angular/compiler/src/view_compiler/view_builder.ts delete mode 100644 modules/@angular/compiler/src/view_compiler_next/README.md delete mode 100644 modules/@angular/compiler/src/view_compiler_next/view_compiler.ts delete mode 100644 modules/@angular/compiler/test/compiler_util/identifier_util_spec.ts delete mode 100644 modules/@angular/compiler/test/view_compiler/util_spec.ts delete mode 100644 modules/@angular/core/src/animation/animation_constants.ts delete mode 100644 modules/@angular/core/src/animation/animation_group_player.ts delete mode 100644 modules/@angular/core/src/animation/animation_keyframe.ts rename modules/@angular/core/src/{animation_next => animation}/animation_metadata_wrapped.ts (100%) delete mode 100644 modules/@angular/core/src/animation/animation_player.ts delete mode 100644 modules/@angular/core/src/animation/animation_queue.ts delete mode 100644 modules/@angular/core/src/animation/animation_sequence_player.ts delete mode 100644 modules/@angular/core/src/animation/animation_style_util.ts delete mode 100644 modules/@angular/core/src/animation/animation_styles.ts delete mode 100644 modules/@angular/core/src/animation/animation_transition.ts delete mode 100644 modules/@angular/core/src/animation/animation_transition_event.ts rename modules/@angular/core/src/{animation_next => animation}/dsl.ts (100%) delete mode 100644 modules/@angular/core/src/animation/metadata.ts delete mode 100644 modules/@angular/core/src/animation/view_animation_map.ts delete mode 100644 modules/@angular/core/src/debug/debug_renderer.ts delete mode 100644 modules/@angular/core/src/linker/animation_view_context.ts delete mode 100644 modules/@angular/core/src/linker/debug_context.ts delete mode 100644 modules/@angular/core/src/linker/element_injector.ts delete mode 100644 modules/@angular/core/src/linker/errors.ts delete mode 100644 modules/@angular/core/src/linker/view.ts delete mode 100644 modules/@angular/core/src/linker/view_container.ts delete mode 100644 modules/@angular/core/src/linker/view_type.ts delete mode 100644 modules/@angular/core/src/linker/view_utils.ts delete mode 100644 modules/@angular/core/test/animation/active_animations_players_map_spec.ts delete mode 100644 modules/@angular/core/test/animation/animation_group_player_spec.ts rename modules/@angular/core/test/animation/{animation_integration_next_spec.ts => animation_integration_spec.ts} (97%) delete mode 100644 modules/@angular/core/test/animation/animation_player_spec.ts delete mode 100644 modules/@angular/core/test/animation/animation_queue_spec.ts delete mode 100644 modules/@angular/core/test/animation/animation_sequence_player_spec.ts delete mode 100644 modules/@angular/core/test/animation/animation_style_util_spec.ts delete mode 100644 modules/@angular/core/test/linker/animation_view_context_spec.ts delete mode 100644 modules/@angular/core/test/linker/direct_rendering_integration_spec.ts delete mode 100644 modules/@angular/core/testing/mock_animation_player.ts delete mode 100644 modules/@angular/platform-browser/src/dom/animation_driver.ts delete mode 100644 modules/@angular/platform-browser/src/dom/dom_animate_player.ts delete mode 100644 modules/@angular/platform-browser/src/dom/web_animations_driver.ts delete mode 100644 modules/@angular/platform-browser/src/dom/web_animations_player.ts delete mode 100644 modules/@angular/platform-browser/test/dom/web_animations_driver_spec.ts delete mode 100644 modules/@angular/platform-browser/test/dom/web_animations_player_spec.ts delete mode 100644 modules/@angular/platform-browser/testing/mock_animation_driver.ts delete mode 100644 modules/@angular/platform-browser/testing/mock_dom_animate_player.ts delete mode 100644 modules/@angular/platform-webworker/test/web_workers/worker/renderer_integration_spec.ts delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/README.md delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/app.ngfactory.ts delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/ftl_util.ts delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/index.html delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/index.ts delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/ng_if.ngfactory.ts delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/tree.ngfactory.ts delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/tree.ts delete mode 100644 modules/benchmarks/src/tree/ng2_ftl/tree_host.ngfactory.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/README.md delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/app.ngfactory.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/app.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/ftl_util.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/index.html delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/index.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/tree.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/tree_branch.ngfactory.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/tree_leaf.ngfactory.ts delete mode 100644 modules/benchmarks/src/tree/ng2_static_ftl/tree_root.ngfactory.ts diff --git a/modules/@angular/compiler/src/animation/animation_ast.ts b/modules/@angular/compiler/src/animation/animation_ast.ts deleted file mode 100644 index f45a3bc596648..0000000000000 --- a/modules/@angular/compiler/src/animation/animation_ast.ts +++ /dev/null @@ -1,109 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import {StaticSymbol} from '../aot/static_symbol'; - -export abstract class AnimationAst { - public startTime: number = 0; - public playTime: number = 0; - abstract visit(visitor: AnimationAstVisitor, context: any): any; -} - -export abstract class AnimationStateAst extends AnimationAst { - abstract visit(visitor: AnimationAstVisitor, context: any): any; -} - -export interface AnimationAstVisitor { - visitAnimationEntry(ast: AnimationEntryAst, context: any): any; - visitAnimationStateDeclaration(ast: AnimationStateDeclarationAst, context: any): any; - visitAnimationStateTransition(ast: AnimationStateTransitionAst, context: any): any; - visitAnimationStep(ast: AnimationStepAst, context: any): any; - visitAnimationSequence(ast: AnimationSequenceAst, context: any): any; - visitAnimationGroup(ast: AnimationGroupAst, context: any): any; - visitAnimationKeyframe(ast: AnimationKeyframeAst, context: any): any; - visitAnimationStyles(ast: AnimationStylesAst, context: any): any; -} - -export class AnimationEntryAst extends AnimationAst { - constructor( - public name: string, public stateDeclarations: AnimationStateDeclarationAst[], - public stateTransitions: AnimationStateTransitionAst[]) { - super(); - } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationEntry(this, context); - } -} - -export class AnimationStateDeclarationAst extends AnimationStateAst { - constructor(public stateName: string, public styles: AnimationStylesAst) { super(); } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationStateDeclaration(this, context); - } -} - -export class AnimationStateTransitionExpression { - constructor(public fromState: string, public toState: string) {} -} - -export class AnimationStateTransitionFnExpression extends AnimationStateTransitionExpression { - constructor(public fn: Function|StaticSymbol) { super(null, null); } -} - -export class AnimationStateTransitionAst extends AnimationStateAst { - constructor( - public stateChanges: AnimationStateTransitionExpression[], - public animation: AnimationWithStepsAst) { - super(); - } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationStateTransition(this, context); - } -} - -export class AnimationStepAst extends AnimationAst { - constructor( - public startingStyles: AnimationStylesAst, public keyframes: AnimationKeyframeAst[], - public duration: number, public delay: number, public easing: string) { - super(); - } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationStep(this, context); - } -} - -export class AnimationStylesAst extends AnimationAst { - constructor(public styles: Array<{[key: string]: string | number}>) { super(); } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationStyles(this, context); - } -} - -export class AnimationKeyframeAst extends AnimationAst { - constructor(public offset: number, public styles: AnimationStylesAst) { super(); } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationKeyframe(this, context); - } -} - -export abstract class AnimationWithStepsAst extends AnimationAst { - constructor(public steps: AnimationAst[]) { super(); } -} - -export class AnimationGroupAst extends AnimationWithStepsAst { - constructor(steps: AnimationAst[]) { super(steps); } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationGroup(this, context); - } -} - -export class AnimationSequenceAst extends AnimationWithStepsAst { - constructor(steps: AnimationAst[]) { super(steps); } - visit(visitor: AnimationAstVisitor, context: any): any { - return visitor.visitAnimationSequence(this, context); - } -} diff --git a/modules/@angular/compiler/src/animation/animation_compiler.ts b/modules/@angular/compiler/src/animation/animation_compiler.ts deleted file mode 100644 index 9c7ce7ddedc20..0000000000000 --- a/modules/@angular/compiler/src/animation/animation_compiler.ts +++ /dev/null @@ -1,391 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - - -import {ɵANY_STATE, ɵDEFAULT_STATE, ɵEMPTY_STATE} from '@angular/core'; - -import {isPresent} from '../facade/lang'; -import {Identifiers, createIdentifier} from '../identifiers'; -import * as o from '../output/output_ast'; - -import {AnimationAst, AnimationAstVisitor, AnimationEntryAst, AnimationGroupAst, AnimationKeyframeAst, AnimationSequenceAst, AnimationStateDeclarationAst, AnimationStateTransitionAst, AnimationStateTransitionFnExpression, AnimationStepAst, AnimationStylesAst} from './animation_ast'; - -export class AnimationEntryCompileResult { - constructor(public name: string, public statements: o.Statement[], public fnExp: o.Expression) {} -} - -export class AnimationCompiler { - compile(factoryNamePrefix: string, parsedAnimations: AnimationEntryAst[]): - AnimationEntryCompileResult[] { - return parsedAnimations.map(entry => { - const factoryName = `${factoryNamePrefix}_${entry.name}`; - const visitor = new _AnimationBuilder(entry.name, factoryName); - return visitor.build(entry); - }); - } -} - -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 _PREVIOUS_ANIMATION_PLAYERS = o.variable('previousPlayers'); -const _EMPTY_MAP = o.literalMap([]); -const _EMPTY_ARRAY = o.literalArr([]); - -class _AnimationBuilder implements AnimationAstVisitor { - private _fnVarName: string; - private _statesMapVarName: string; - private _statesMapVar: any; - - constructor(public animationName: string, factoryName: string) { - this._fnVarName = factoryName + '_factory'; - this._statesMapVarName = factoryName + '_states'; - this._statesMapVar = o.variable(this._statesMapVarName); - } - - visitAnimationStyles(ast: AnimationStylesAst, context: _AnimationBuilderContext): o.Expression { - const stylesArr: any[] = []; - if (context.isExpectingFirstStyleStep) { - stylesArr.push(_ANIMATION_START_STATE_STYLES_VAR); - context.isExpectingFirstStyleStep = false; - } - - ast.styles.forEach(entry => { - const entries = - Object.keys(entry).map((key): [string, o.Expression] => [key, o.literal(entry[key])]); - stylesArr.push(o.literalMap(entries, null, true)); - }); - - return o.importExpr(createIdentifier(Identifiers.AnimationStyles)).instantiate([ - o.importExpr(createIdentifier(Identifiers.collectAndResolveStyles)).callFn([ - _ANIMATION_COLLECTED_STYLES, o.literalArr(stylesArr) - ]) - ]); - } - - visitAnimationKeyframe(ast: AnimationKeyframeAst, context: _AnimationBuilderContext): - o.Expression { - return o.importExpr(createIdentifier(Identifiers.AnimationKeyframe)).instantiate([ - o.literal(ast.offset), ast.styles.visit(this, context) - ]); - } - - visitAnimationStep(ast: AnimationStepAst, context: _AnimationBuilderContext): o.Expression { - if (context.endStateAnimateStep === ast) { - return this._visitEndStateAnimation(ast, context); - } - - 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); - } - - /** @internal */ - _visitEndStateAnimation(ast: AnimationStepAst, context: _AnimationBuilderContext): o.Expression { - const startingStylesExpr = ast.startingStyles.visit(this, context); - const keyframeExpressions = ast.keyframes.map(keyframe => keyframe.visit(this, context)); - const keyframesExpr = - o.importExpr(createIdentifier(Identifiers.balanceAnimationKeyframes)).callFn([ - _ANIMATION_COLLECTED_STYLES, _ANIMATION_END_STATE_STYLES_VAR, - o.literalArr(keyframeExpressions) - ]); - - return this._callAnimateMethod(ast, startingStylesExpr, keyframesExpr, context); - } - - /** @internal */ - _callAnimateMethod( - ast: AnimationStepAst, startingStylesExpr: any, keyframesExpr: any, - context: _AnimationBuilderContext) { - let previousStylesValue: o.Expression = _EMPTY_ARRAY; - if (context.isExpectingFirstAnimateStep) { - previousStylesValue = _PREVIOUS_ANIMATION_PLAYERS; - context.isExpectingFirstAnimateStep = false; - } - context.totalTransitionTime += ast.duration + ast.delay; - return _ANIMATION_FACTORY_RENDERER_VAR.callMethod('animate', [ - _ANIMATION_FACTORY_ELEMENT_VAR, startingStylesExpr, keyframesExpr, o.literal(ast.duration), - o.literal(ast.delay), o.literal(ast.easing), previousStylesValue - ]); - } - - visitAnimationSequence(ast: AnimationSequenceAst, context: _AnimationBuilderContext): - o.Expression { - const playerExprs = ast.steps.map(step => step.visit(this, context)); - return o.importExpr(createIdentifier(Identifiers.AnimationSequencePlayer)).instantiate([ - o.literalArr(playerExprs) - ]); - } - - visitAnimationGroup(ast: AnimationGroupAst, context: _AnimationBuilderContext): o.Expression { - const playerExprs = ast.steps.map(step => step.visit(this, context)); - return o.importExpr(createIdentifier(Identifiers.AnimationGroupPlayer)).instantiate([ - o.literalArr(playerExprs) - ]); - } - - visitAnimationStateDeclaration( - ast: AnimationStateDeclarationAst, context: _AnimationBuilderContext): void { - 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); - } - - visitAnimationStateTransition( - ast: AnimationStateTransitionAst, context: _AnimationBuilderContext): any { - const steps = ast.animation.steps; - const lastStep = steps[steps.length - 1]; - if (_isEndStateAnimateStep(lastStep)) { - context.endStateAnimateStep = lastStep; - } - - context.totalTransitionTime = 0; - context.isExpectingFirstStyleStep = true; - context.isExpectingFirstAnimateStep = true; - - const stateChangePreconditions: o.Expression[] = []; - - ast.stateChanges.forEach(stateChange => { - if (stateChange instanceof AnimationStateTransitionFnExpression) { - stateChangePreconditions.push(o.importExpr({reference: stateChange.fn}).callFn([ - _ANIMATION_CURRENT_STATE_VAR, _ANIMATION_NEXT_STATE_VAR - ])); - } else { - stateChangePreconditions.push( - _compareToAnimationStateExpr(_ANIMATION_CURRENT_STATE_VAR, stateChange.fromState) - .and(_compareToAnimationStateExpr(_ANIMATION_NEXT_STATE_VAR, stateChange.toState))); - - if (stateChange.fromState != ɵANY_STATE) { - context.stateMap.registerState(stateChange.fromState); - } - - if (stateChange.toState != ɵANY_STATE) { - context.stateMap.registerState(stateChange.toState); - } - } - }); - - const animationPlayerExpr = ast.animation.visit(this, context); - - const reducedStateChangesPrecondition = stateChangePreconditions.reduce((a, b) => a.or(b)); - const precondition = - _ANIMATION_PLAYER_VAR.equals(o.NULL_EXPR).and(reducedStateChangesPrecondition); - - 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]); - } - - visitAnimationEntry(ast: AnimationEntryAst, context: _AnimationBuilderContext): any { - // visit each of the declarations first to build the context state map - ast.stateDeclarations.forEach(def => def.visit(this, context)); - - // this should always be defined even if the user overrides it - context.stateMap.registerState(ɵDEFAULT_STATE, {}); - - const statements: o.Statement[] = []; - statements.push(_PREVIOUS_ANIMATION_PLAYERS - .set(_ANIMATION_FACTORY_VIEW_CONTEXT.callMethod( - 'getAnimationPlayers', - [ - _ANIMATION_FACTORY_ELEMENT_VAR, - _ANIMATION_NEXT_STATE_VAR.equals(o.literal(ɵEMPTY_STATE)) - .conditional(o.NULL_EXPR, o.literal(this.animationName)) - ])) - .toDeclStmt()); - - statements.push(_ANIMATION_COLLECTED_STYLES.set(_EMPTY_MAP).toDeclStmt()); - statements.push(_ANIMATION_PLAYER_VAR.set(o.NULL_EXPR).toDeclStmt()); - statements.push(_ANIMATION_TIME_VAR.set(o.literal(0)).toDeclStmt()); - - statements.push( - _ANIMATION_DEFAULT_STATE_VAR.set(this._statesMapVar.key(o.literal(ɵDEFAULT_STATE))) - .toDeclStmt()); - - statements.push( - _ANIMATION_START_STATE_STYLES_VAR.set(this._statesMapVar.key(_ANIMATION_CURRENT_STATE_VAR)) - .toDeclStmt()); - - statements.push(new o.IfStmt( - _ANIMATION_START_STATE_STYLES_VAR.equals(o.NULL_EXPR), - [_ANIMATION_START_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()])); - - statements.push( - _ANIMATION_END_STATE_STYLES_VAR.set(this._statesMapVar.key(_ANIMATION_NEXT_STATE_VAR)) - .toDeclStmt()); - - statements.push(new o.IfStmt( - _ANIMATION_END_STATE_STYLES_VAR.equals(o.NULL_EXPR), - [_ANIMATION_END_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()])); - - const RENDER_STYLES_FN = o.importExpr(createIdentifier(Identifiers.renderStyles)); - - ast.stateTransitions.forEach(transAst => statements.push(transAst.visit(this, context))); - - // this check ensures that the animation factory always returns a player - // so that the onDone callback can be used for tracking - statements.push(new o.IfStmt( - _ANIMATION_PLAYER_VAR.equals(o.NULL_EXPR), - [_ANIMATION_PLAYER_VAR - .set(o.importExpr(createIdentifier(Identifiers.NoOpAnimationPlayer)).instantiate([])) - .toStmt()])); - - // once complete we want to apply the styles on the element - // since the destination state's values should persist once - // the animation sequence has completed. - statements.push( - _ANIMATION_PLAYER_VAR - .callMethod( - 'onDone', - [o - .fn([], - [ - _ANIMATION_PLAYER_VAR.callMethod('destroy', []).toStmt(), - RENDER_STYLES_FN - .callFn([ - _ANIMATION_FACTORY_ELEMENT_VAR, _ANIMATION_FACTORY_RENDERER_VAR, - o.importExpr( - createIdentifier(Identifiers.prepareFinalAnimationStyles)) - .callFn( - [ - _ANIMATION_START_STATE_STYLES_VAR, - _ANIMATION_END_STATE_STYLES_VAR - ]) - ]) - .toStmt() - ])]) - .toStmt()); - - statements.push(o.importExpr(createIdentifier(Identifiers.AnimationSequencePlayer)) - .instantiate([_PREVIOUS_ANIMATION_PLAYERS]) - .callMethod('destroy', []) - .toStmt()); - - // before we start any animation we want to clear out the starting - // styles from the element's style property (since they were placed - // there at the end of the last animation - statements.push(RENDER_STYLES_FN - .callFn([ - _ANIMATION_FACTORY_ELEMENT_VAR, _ANIMATION_FACTORY_RENDERER_VAR, - o.importExpr(createIdentifier(Identifiers.clearStyles)) - .callFn([_ANIMATION_START_STATE_STYLES_VAR]) - ]) - .toStmt()); - - statements.push(_ANIMATION_FACTORY_VIEW_CONTEXT - .callMethod( - 'queueAnimation', - [ - _ANIMATION_FACTORY_ELEMENT_VAR, o.literal(this.animationName), - _ANIMATION_PLAYER_VAR - ]) - .toStmt()); - - statements.push(new o.ReturnStatement( - o.importExpr(createIdentifier(Identifiers.AnimationTransition)).instantiate([ - _ANIMATION_PLAYER_VAR, _ANIMATION_FACTORY_ELEMENT_VAR, o.literal(this.animationName), - _ANIMATION_CURRENT_STATE_VAR, _ANIMATION_NEXT_STATE_VAR, _ANIMATION_TIME_VAR - ]))); - - return o.fn( - [ - new o.FnParam( - _ANIMATION_FACTORY_VIEW_VAR.name, - o.importType(createIdentifier(Identifiers.AppView), [o.DYNAMIC_TYPE])), - new o.FnParam(_ANIMATION_FACTORY_ELEMENT_VAR.name, o.DYNAMIC_TYPE), - new o.FnParam(_ANIMATION_CURRENT_STATE_VAR.name, o.DYNAMIC_TYPE), - new o.FnParam(_ANIMATION_NEXT_STATE_VAR.name, o.DYNAMIC_TYPE) - ], - statements, o.importType(createIdentifier(Identifiers.AnimationTransition))); - } - - build(ast: AnimationAst): AnimationEntryCompileResult { - const context = new _AnimationBuilderContext(); - const fnStatement = ast.visit(this, context).toDeclStmt(this._fnVarName); - const fnVariable = o.variable(this._fnVarName); - - const lookupMap: any[] = []; - Object.keys(context.stateMap.states).forEach(stateName => { - const value = context.stateMap.states[stateName]; - let variableValue = _EMPTY_MAP; - if (isPresent(value)) { - const styleMap: any[] = []; - Object.keys(value).forEach(key => { styleMap.push([key, o.literal(value[key])]); }); - variableValue = o.literalMap(styleMap, null, true); - } - lookupMap.push([stateName, variableValue]); - }); - - const compiledStatesMapStmt = - this._statesMapVar.set(o.literalMap(lookupMap, null, true)).toDeclStmt(); - const statements: o.Statement[] = [compiledStatesMapStmt, fnStatement]; - - return new AnimationEntryCompileResult(this.animationName, statements, fnVariable); - } -} - -class _AnimationBuilderContext { - stateMap = new _AnimationBuilderStateMap(); - endStateAnimateStep: AnimationStepAst = null; - isExpectingFirstStyleStep = false; - isExpectingFirstAnimateStep = false; - totalTransitionTime = 0; -} - -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 { - const existingEntry = this._states[name]; - if (!existingEntry) { - this._states[name] = value; - } - } -} - -function _compareToAnimationStateExpr(value: o.Expression, animationState: string): o.Expression { - const emptyStateLiteral = o.literal(ɵEMPTY_STATE); - switch (animationState) { - case ɵEMPTY_STATE: - return value.equals(emptyStateLiteral); - - case ɵANY_STATE: - return o.literal(true); - - default: - return value.equals(o.literal(animationState)); - } -} - -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) { - 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; -} - -function _getStylesArray(obj: any): {[key: string]: any}[] { - return obj.styles.styles; -} diff --git a/modules/@angular/compiler/src/animation/animation_parser.ts b/modules/@angular/compiler/src/animation/animation_parser.ts deleted file mode 100644 index 96f5fef3136e5..0000000000000 --- a/modules/@angular/compiler/src/animation/animation_parser.ts +++ /dev/null @@ -1,605 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import {ɵANY_STATE, ɵFILL_STYLE_FLAG} from '@angular/core'; - -import {StaticSymbol} from '../aot/static_symbol'; -import {CompileAnimationAnimateMetadata, CompileAnimationEntryMetadata, CompileAnimationGroupMetadata, CompileAnimationKeyframesSequenceMetadata, CompileAnimationMetadata, CompileAnimationSequenceMetadata, CompileAnimationStateDeclarationMetadata, CompileAnimationStateTransitionMetadata, CompileAnimationStyleMetadata, CompileAnimationWithStepsMetadata, CompileDirectiveMetadata, identifierName} from '../compile_metadata'; -import {StringMapWrapper} from '../facade/collection'; -import {isBlank, isPresent} from '../facade/lang'; -import {CompilerInjectable} from '../injectable'; -import {ParseError} from '../parse_util'; -import {ElementSchemaRegistry} from '../schema/element_schema_registry'; - -import {AnimationAst, AnimationEntryAst, AnimationGroupAst, AnimationKeyframeAst, AnimationSequenceAst, AnimationStateDeclarationAst, AnimationStateTransitionAst, AnimationStateTransitionExpression, AnimationStateTransitionFnExpression, AnimationStepAst, AnimationStylesAst, AnimationWithStepsAst} from './animation_ast'; -import {StylesCollection} from './styles_collection'; - -const _INITIAL_KEYFRAME = 0; -const _TERMINAL_KEYFRAME = 1; -const _ONE_SECOND = 1000; - -declare type Styles = { - [key: string]: string | number -}; - -export class AnimationParseError extends ParseError { - constructor(message: string) { super(null, message); } - toString(): string { return `${this.msg}`; } -} - -export class AnimationEntryParseResult { - constructor(public ast: AnimationEntryAst, public errors: AnimationParseError[]) {} -} - -@CompilerInjectable() -export class AnimationParser { - constructor(private _schema: ElementSchemaRegistry) {} - - parseComponent(component: CompileDirectiveMetadata): AnimationEntryAst[] { - const errors: string[] = []; - const componentName = identifierName(component.type); - const animationTriggerNames = new Set(); - const asts = component.template.animations.map(entry => { - const result = this.parseEntry(entry); - const ast = result.ast; - const triggerName = ast.name; - if (animationTriggerNames.has(triggerName)) { - result.errors.push(new AnimationParseError( - `The animation trigger "${triggerName}" has already been registered for the ${componentName} component`)); - } else { - animationTriggerNames.add(triggerName); - } - if (result.errors.length > 0) { - let errorMessage = - `- Unable to parse the animation sequence for "${triggerName}" on the ${componentName} component due to the following errors:`; - result.errors.forEach( - (error: AnimationParseError) => { errorMessage += '\n-- ' + error.msg; }); - errors.push(errorMessage); - } - return ast; - }); - - if (errors.length > 0) { - const errorString = errors.join('\n'); - throw new Error(`Animation parse errors:\n${errorString}`); - } - - return asts; - } - - parseEntry(entry: CompileAnimationEntryMetadata): AnimationEntryParseResult { - const errors: AnimationParseError[] = []; - const stateStyles: {[key: string]: AnimationStylesAst} = {}; - const transitions: CompileAnimationStateTransitionMetadata[] = []; - - const stateDeclarationAsts: AnimationStateDeclarationAst[] = []; - entry.definitions.forEach(def => { - if (def instanceof CompileAnimationStateDeclarationMetadata) { - _parseAnimationDeclarationStates(def, this._schema, errors).forEach(ast => { - stateDeclarationAsts.push(ast); - stateStyles[ast.stateName] = ast.styles; - }); - } else { - transitions.push(def); - } - }); - - const stateTransitionAsts = transitions.map( - transDef => _parseAnimationStateTransition(transDef, stateStyles, this._schema, errors)); - - const ast = new AnimationEntryAst(entry.name, stateDeclarationAsts, stateTransitionAsts); - return new AnimationEntryParseResult(ast, errors); - } -} - -function _parseAnimationDeclarationStates( - stateMetadata: CompileAnimationStateDeclarationMetadata, schema: ElementSchemaRegistry, - errors: AnimationParseError[]): AnimationStateDeclarationAst[] { - 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)); -} - -function _parseAnimationStateTransition( - transitionStateMetadata: CompileAnimationStateTransitionMetadata, - stateStyles: {[key: string]: AnimationStylesAst}, schema: ElementSchemaRegistry, - errors: AnimationParseError[]): AnimationStateTransitionAst { - const styles = new StylesCollection(); - const transitionExprs: AnimationStateTransitionExpression[] = []; - const stateChangeExpr = transitionStateMetadata.stateChangeExpr; - const transitionStates: Array = typeof stateChangeExpr == 'string' ? - (stateChangeExpr).split(/\s*,\s*/) : - [stateChangeExpr]; - transitionStates.forEach( - expr => transitionExprs.push(..._parseAnimationTransitionExpr(expr, 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); - } - - const stepsAst: AnimationWithStepsAst = (animationAst instanceof AnimationWithStepsAst) ? - animationAst : - new AnimationSequenceAst([animationAst]); - - return new AnimationStateTransitionAst(transitionExprs, stepsAst); -} - -function _parseAnimationAlias(alias: string, errors: AnimationParseError[]): string { - switch (alias) { - case ':enter': - return 'void => *'; - case ':leave': - return '* => void'; - default: - errors.push( - new AnimationParseError(`the transition alias value "${alias}" is not supported`)); - return '* => *'; - } -} - -function _parseAnimationTransitionExpr( - transitionValue: string | Function | StaticSymbol, - errors: AnimationParseError[]): AnimationStateTransitionExpression[] { - const expressions: AnimationStateTransitionExpression[] = []; - if (typeof transitionValue == 'string') { - let eventStr = transitionValue; - if (eventStr[0] == ':') { - eventStr = _parseAnimationAlias(eventStr, errors); - } - 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; - } - - const fromState = match[1]; - const separator = match[2]; - const toState = match[3]; - expressions.push(new AnimationStateTransitionExpression(fromState, toState)); - - const isFullAnyStateExpr = fromState == ɵANY_STATE && toState == ɵANY_STATE; - if (separator[0] == '<' && !isFullAnyStateExpr) { - expressions.push(new AnimationStateTransitionExpression(toState, fromState)); - } - } else { - expressions.push( - new AnimationStateTransitionFnExpression(transitionValue)); - } - return expressions; -} - -function _normalizeAnimationEntry(entry: CompileAnimationMetadata | CompileAnimationMetadata[]): - CompileAnimationMetadata { - return Array.isArray(entry) ? new CompileAnimationSequenceMetadata(entry) : entry; -} - -function _normalizeStyleMetadata( - entry: CompileAnimationStyleMetadata, stateStyles: {[key: string]: AnimationStylesAst}, - schema: ElementSchemaRegistry, errors: AnimationParseError[], - permitStateReferences: boolean): {[key: string]: string | number}[] { - const offset = entry.offset; - if (offset > 1 || offset < 0) { - errors.push(new AnimationParseError(`Offset values for animations must be between 0 and 1`)); - } - - const normalizedStyles: {[key: string]: string | number}[] = []; - entry.styles.forEach(styleEntry => { - if (typeof styleEntry === 'string') { - if (permitStateReferences) { - normalizedStyles.push(..._resolveStylesFromState(styleEntry, stateStyles, errors)); - } else { - errors.push(new AnimationParseError( - `State based animations cannot contain references to other states`)); - } - } else { - const stylesObj = styleEntry; - const normalizedStylesObj: Styles = {}; - Object.keys(stylesObj).forEach(propName => { - const normalizedProp = schema.normalizeAnimationStyleProperty(propName); - const normalizedOutput = - schema.normalizeAnimationStyleValue(normalizedProp, propName, stylesObj[propName]); - const normalizationError = normalizedOutput['error']; - if (normalizationError) { - errors.push(new AnimationParseError(normalizationError)); - } - normalizedStylesObj[normalizedProp] = normalizedOutput['value']; - }); - normalizedStyles.push(normalizedStylesObj); - } - }); - return normalizedStyles; -} - -function _normalizeStyleSteps( - entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst}, - schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata { - const steps = _normalizeStyleStepEntry(entry, stateStyles, schema, errors); - return (entry instanceof CompileAnimationGroupMetadata) ? - new CompileAnimationGroupMetadata(steps) : - new CompileAnimationSequenceMetadata(steps); -} - -function _mergeAnimationStyles( - stylesList: any[], newItem: {[key: string]: string | number} | string) { - if (typeof newItem === 'object' && newItem !== null && stylesList.length > 0) { - 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); - return; - } - } - stylesList.push(newItem); -} - -function _normalizeStyleStepEntry( - entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst}, - schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata[] { - let steps: CompileAnimationMetadata[]; - if (entry instanceof CompileAnimationWithStepsMetadata) { - steps = entry.steps; - } else { - return [entry]; - } - - 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 - // or when the first style step is run. We want to concatenate all subsequent - // style steps together into a single style step such that we have the correct - // starting keyframe data to pass into the animation player. - if (!isPresent(combinedStyles)) { - combinedStyles = []; - } - _normalizeStyleMetadata( - step, stateStyles, schema, errors, true) - .forEach(entry => { _mergeAnimationStyles(combinedStyles, entry); }); - } else { - // it is important that we create a metadata entry of the combined styles - // before we go on an process the animate, sequence or group metadata steps. - // This will ensure that the AST will have the previous styles painted on - // screen before any further animations that use the styles take place. - if (isPresent(combinedStyles)) { - newSteps.push(new CompileAnimationStyleMetadata(0, combinedStyles)); - combinedStyles = null; - } - - if (step instanceof CompileAnimationAnimateMetadata) { - // we do not recurse into CompileAnimationAnimateMetadata since - // those style steps are not going to be squashed - const animateStyleValue = (step).styles; - if (animateStyleValue instanceof CompileAnimationStyleMetadata) { - animateStyleValue.styles = - _normalizeStyleMetadata(animateStyleValue, stateStyles, schema, errors, true); - } else if (animateStyleValue instanceof CompileAnimationKeyframesSequenceMetadata) { - animateStyleValue.steps.forEach(step => { - step.styles = _normalizeStyleMetadata(step, stateStyles, schema, errors, true); - }); - } - } else if (step instanceof CompileAnimationWithStepsMetadata) { - const innerSteps = _normalizeStyleStepEntry(step, stateStyles, schema, errors); - step = step instanceof CompileAnimationGroupMetadata ? - new CompileAnimationGroupMetadata(innerSteps) : - new CompileAnimationSequenceMetadata(innerSteps); - } - - newSteps.push(step); - } - }); - - // this happens when only styles were animated within the sequence - if (isPresent(combinedStyles)) { - newSteps.push(new CompileAnimationStyleMetadata(0, combinedStyles)); - } - - return newSteps; -} - - -function _resolveStylesFromState( - stateName: string, stateStyles: {[key: string]: AnimationStylesAst}, - errors: AnimationParseError[]) { - const styles: Styles[] = []; - if (stateName[0] != ':') { - errors.push(new AnimationParseError(`Animation states via styles must be prefixed with a ":"`)); - } else { - 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}"`)); - } else { - value.styles.forEach(stylesEntry => { - if (typeof stylesEntry === 'object' && stylesEntry !== null) { - styles.push(stylesEntry as Styles); - } - }); - } - } - return styles; -} - -class _AnimationTimings { - constructor(public duration: number, public delay: number, public easing: string) {} -} - -function _parseAnimationKeyframes( - keyframeSequence: CompileAnimationKeyframesSequenceMetadata, currentTime: number, - collectedStyles: StylesCollection, stateStyles: {[key: string]: AnimationStylesAst}, - errors: AnimationParseError[]): AnimationKeyframeAst[] { - const totalEntries = keyframeSequence.steps.length; - let totalOffsets = 0; - keyframeSequence.steps.forEach(step => totalOffsets += (isPresent(step.offset) ? 1 : 0)); - - if (totalOffsets > 0 && totalOffsets < totalEntries) { - errors.push(new AnimationParseError( - `Not all style() entries contain an offset for the provided keyframe()`)); - totalOffsets = totalEntries; - } - - 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 => { - let offset = styleMetadata.offset; - const keyframeStyles: Styles = {}; - styleMetadata.styles.forEach(entry => { - Object.keys(entry).forEach(prop => { - if (prop != 'offset') { - keyframeStyles[prop] = (entry as Styles)[prop]; - } - }); - }); - - if (isPresent(offset)) { - doSortKeyframes = doSortKeyframes || (offset < lastOffset); - } else { - offset = index == limit ? _TERMINAL_KEYFRAME : (margin * index); - } - - rawKeyframes.push([offset, keyframeStyles]); - lastOffset = offset; - index++; - }); - - if (doSortKeyframes) { - rawKeyframes.sort((a, b) => a[0] <= b[0] ? -1 : 1); - } - - let firstKeyframe = rawKeyframes[0]; - if (firstKeyframe[0] != _INITIAL_KEYFRAME) { - rawKeyframes.splice(0, 0, firstKeyframe = [_INITIAL_KEYFRAME, {}]); - } - - const firstKeyframeStyles = firstKeyframe[1]; - limit = rawKeyframes.length - 1; - let lastKeyframe = rawKeyframes[limit]; - if (lastKeyframe[0] != _TERMINAL_KEYFRAME) { - rawKeyframes.push(lastKeyframe = [_TERMINAL_KEYFRAME, {}]); - limit++; - } - - const lastKeyframeStyles = lastKeyframe[1]; - for (let i = 1; i <= limit; i++) { - const entry = rawKeyframes[i]; - const styles = entry[1]; - - Object.keys(styles).forEach(prop => { - if (!isPresent(firstKeyframeStyles[prop])) { - firstKeyframeStyles[prop] = ɵFILL_STYLE_FLAG; - } - }); - } - - for (let i = limit - 1; i >= 0; i--) { - const entry = rawKeyframes[i]; - const styles = entry[1]; - - Object.keys(styles).forEach(prop => { - if (!isPresent(lastKeyframeStyles[prop])) { - lastKeyframeStyles[prop] = styles[prop]; - } - }); - } - - return rawKeyframes.map( - entry => new AnimationKeyframeAst(entry[0], new AnimationStylesAst([entry[1]]))); -} - -function _parseTransitionAnimation( - entry: CompileAnimationMetadata, currentTime: number, collectedStyles: StylesCollection, - stateStyles: {[key: string]: AnimationStylesAst}, errors: AnimationParseError[]): AnimationAst { - let ast: any /** TODO #9100 */; - let playTime = 0; - const startingTime = currentTime; - if (entry instanceof CompileAnimationWithStepsMetadata) { - 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... - const time = isGroup ? startingTime : currentTime; - if (entry instanceof CompileAnimationStyleMetadata) { - entry.styles.forEach(stylesEntry => { - // by this point we know that we only have stringmap values - const map = stylesEntry as Styles; - Object.keys(map).forEach( - prop => { collectedStyles.insertAtTime(prop, time, map[prop]); }); - }); - previousStyles = entry.styles; - return; - } - - const innerAst = _parseTransitionAnimation(entry, time, collectedStyles, stateStyles, errors); - if (isPresent(previousStyles)) { - if (entry instanceof CompileAnimationWithStepsMetadata) { - const startingStyles = new AnimationStylesAst(previousStyles); - steps.push(new AnimationStepAst(startingStyles, [], 0, 0, '')); - } else { - const innerStep = innerAst; - innerStep.startingStyles.styles.push(...previousStyles); - } - previousStyles = null; - } - - const astDuration = innerAst.playTime; - currentTime += astDuration; - playTime += astDuration; - maxDuration = Math.max(astDuration, maxDuration); - steps.push(innerAst); - }); - if (isPresent(previousStyles)) { - const startingStyles = new AnimationStylesAst(previousStyles); - steps.push(new AnimationStepAst(startingStyles, [], 0, 0, '')); - } - if (isGroup) { - ast = new AnimationGroupAst(steps); - playTime = maxDuration; - currentTime = startingTime + playTime; - } else { - ast = new AnimationSequenceAst(steps); - } - } else if (entry instanceof CompileAnimationAnimateMetadata) { - const timings = _parseTimeExpression(entry.timings, errors); - const styles = entry.styles; - - let keyframes: any /** TODO #9100 */; - if (styles instanceof CompileAnimationKeyframesSequenceMetadata) { - keyframes = - _parseAnimationKeyframes(styles, currentTime, collectedStyles, stateStyles, errors); - } else { - const styleData = styles; - const offset = _TERMINAL_KEYFRAME; - const styleAst = new AnimationStylesAst(styleData.styles as Styles[]); - const keyframe = new AnimationKeyframeAst(offset, styleAst); - keyframes = [keyframe]; - } - - ast = new AnimationStepAst( - new AnimationStylesAst([]), keyframes, timings.duration, timings.delay, timings.easing); - playTime = timings.duration + timings.delay; - currentTime += playTime; - - keyframes.forEach( - (keyframe: any /** TODO #9100 */) => keyframe.styles.styles.forEach( - (entry: any /** TODO #9100 */) => Object.keys(entry).forEach( - prop => { collectedStyles.insertAtTime(prop, currentTime, entry[prop]); }))); - } else { - // if the code reaches this stage then an error - // has already been populated within the _normalizeStyleSteps() - // operation... - ast = new AnimationStepAst(null, [], 0, 0, ''); - } - - ast.playTime = playTime; - ast.startTime = startingTime; - return ast; -} - -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) { - const keyframes = ast.keyframes; - if (keyframes.length == 1) { - const endKeyframe = keyframes[0]; - const startKeyframe = _createStartKeyframeFromEndKeyframe( - endKeyframe, ast.startTime, ast.playTime, collectedStyles, errors); - ast.keyframes = [startKeyframe, endKeyframe]; - } - } else if (ast instanceof AnimationWithStepsAst) { - ast.steps.forEach(entry => _fillAnimationAstStartingKeyframes(entry, collectedStyles, errors)); - } -} - -function _parseTimeExpression( - exp: string | number, errors: AnimationParseError[]): _AnimationTimings { - 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) { - errors.push(new AnimationParseError(`The provided timing value "${exp}" is invalid.`)); - return new _AnimationTimings(0, 0, null); - } - - let durationMatch = parseFloat(matches[1]); - const durationUnit = matches[2]; - if (durationUnit == 's') { - durationMatch *= _ONE_SECOND; - } - duration = Math.floor(durationMatch); - - const delayMatch = matches[3]; - const delayUnit = matches[4]; - if (isPresent(delayMatch)) { - let delayVal: number = parseFloat(delayMatch); - if (isPresent(delayUnit) && delayUnit == 's') { - delayVal *= _ONE_SECOND; - } - delay = Math.floor(delayVal); - } - - const easingVal = matches[5]; - if (!isBlank(easingVal)) { - easing = easingVal; - } - } else { - duration = exp; - } - - return new _AnimationTimings(duration, delay, easing); -} - -function _createStartKeyframeFromEndKeyframe( - endKeyframe: AnimationKeyframeAst, startTime: number, duration: number, - collectedStyles: StylesCollection, errors: AnimationParseError[]): AnimationKeyframeAst { - 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; - - 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); - value = resultEntry.value; - nextEntry = collectedStyles.getByIndex(prop, resultIndex + 1); - } else { - // this is a flag that the runtime code uses to pass - // in a value either from the state declaration styles - // or using the AUTO_STYLE value (e.g. getComputedStyle) - value = ɵFILL_STYLE_FLAG; - } - - if (isPresent(nextEntry) && !nextEntry.matches(endTime, val)) { - errors.push(new AnimationParseError( - `The animated CSS property "${prop}" unexpectedly changes between steps "${resultEntry.time}ms" and "${endTime}ms" at "${nextEntry.time}ms"`)); - } - - values[prop] = value; - }); - }); - - return new AnimationKeyframeAst(_INITIAL_KEYFRAME, new AnimationStylesAst([values])); -} diff --git a/modules/@angular/compiler/src/animation/styles_collection.ts b/modules/@angular/compiler/src/animation/styles_collection.ts deleted file mode 100644 index aaec776001495..0000000000000 --- a/modules/@angular/compiler/src/animation/styles_collection.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import {isPresent} from '../facade/lang'; - -export class StylesCollectionEntry { - constructor(public time: number, public value: string|number) {} - - matches(time: number, value: string|number): boolean { - return time == this.time && value == this.value; - } -} - -export class StylesCollection { - styles: {[key: string]: StylesCollectionEntry[]} = {}; - - insertAtTime(property: string, time: number, value: string|number) { - 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 - let insertionIndex = 0; - for (let i = entries.length - 1; i >= 0; i--) { - if (entries[i].time <= time) { - insertionIndex = i + 1; - break; - } - } - - entries.splice(insertionIndex, 0, tuple); - } - - getByIndex(property: string, index: number): StylesCollectionEntry { - const items = this.styles[property]; - if (isPresent(items)) { - return index >= items.length ? null : items[index]; - } - return null; - } - - indexOfAtOrBeforeTime(property: string, time: number): number { - const entries = this.styles[property]; - if (isPresent(entries)) { - for (let i = entries.length - 1; i >= 0; i--) { - if (entries[i].time <= time) return i; - } - } - return null; - } -} diff --git a/modules/@angular/compiler/src/aot/compiler.ts b/modules/@angular/compiler/src/aot/compiler.ts index c1d0c349c4708..0e41d6e7d0464 100644 --- a/modules/@angular/compiler/src/aot/compiler.ts +++ b/modules/@angular/compiler/src/aot/compiler.ts @@ -6,11 +6,8 @@ * found in the LICENSE file at https://angular.io/license */ -import {AnimationCompiler} from '../animation/animation_compiler'; -import {AnimationParser} from '../animation/animation_parser'; import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, componentFactoryName, createHostComponentMeta, identifierName} from '../compile_metadata'; import {CompilerConfig} from '../config'; -import {DirectiveWrapperCompiler} from '../directive_wrapper_compiler'; import {ListWrapper} from '../facade/collection'; import {Identifiers, createIdentifier, createIdentifierToken} from '../identifiers'; import {CompileMetadataResolver} from '../metadata_resolver'; @@ -31,17 +28,13 @@ import {serializeSummaries} from './summary_serializer'; import {ngfactoryFilePath, splitTypescriptSuffix, summaryFileName} from './util'; export class AotCompiler { - private _animationCompiler = new AnimationCompiler(); - constructor( private _config: CompilerConfig, private _host: AotCompilerHost, private _metadataResolver: CompileMetadataResolver, private _templateParser: TemplateParser, private _styleCompiler: StyleCompiler, private _viewCompiler: ViewCompiler, - private _dirWrapperCompiler: DirectiveWrapperCompiler, private _ngModuleCompiler: NgModuleCompiler, private _outputEmitter: OutputEmitter, private _summaryResolver: SummaryResolver, private _localeId: string, - private _translationFormat: string, private _animationParser: AnimationParser, - private _symbolResolver: StaticSymbolResolver) {} + private _translationFormat: string, private _symbolResolver: StaticSymbolResolver) {} clearCache() { this._metadataResolver.clearCache(); } @@ -78,12 +71,6 @@ export class AotCompiler { exportedVars.push( ...ngModules.map((ngModuleType) => this._compileModule(ngModuleType, statements))); - // compile directive wrappers - if (!this._config.useViewEngine) { - exportedVars.push(...directives.map( - (directiveType) => this._compileDirectiveWrapper(directiveType, statements))); - } - // compile components directives.forEach((dirType) => { const compMeta = this._metadataResolver.getDirectiveMetadata(dirType); @@ -165,15 +152,6 @@ export class AotCompiler { return appCompileResult.ngModuleFactoryVar; } - private _compileDirectiveWrapper(directiveType: StaticSymbol, targetStatements: o.Statement[]): - string { - const dirMeta = this._metadataResolver.getDirectiveMetadata(directiveType); - const dirCompileResult = this._dirWrapperCompiler.compile(dirMeta); - - targetStatements.push(...dirCompileResult.statements); - return dirCompileResult.dirWrapperClassVar; - } - private _compileComponentFactory( compMeta: CompileDirectiveMetadata, ngModule: CompileNgModuleMetadata, fileSuffix: string, targetStatements: o.Statement[]): string { @@ -185,35 +163,18 @@ export class AotCompiler { hostMeta, ngModule, [compMeta.type], null, fileSuffix, targetStatements) .viewClassVar; const compFactoryVar = componentFactoryName(compMeta.type.reference); - if (this._config.useViewEngine) { - targetStatements.push( - o.variable(compFactoryVar) - .set(o.importExpr(createIdentifier(Identifiers.createComponentFactory)).callFn([ - o.literal(compMeta.selector), - o.importExpr(compMeta.type), - o.variable(hostViewFactoryVar), - ])) - .toDeclStmt( - o.importType( - createIdentifier(Identifiers.ComponentFactory), [o.importType(compMeta.type)], - [o.TypeModifier.Const]), - [o.StmtModifier.Final])); - } else { - targetStatements.push( - o.variable(compFactoryVar) - .set(o.importExpr(createIdentifier(Identifiers.ComponentFactory), [o.importType( - compMeta.type)]) - .instantiate( - [ - o.literal(compMeta.selector), - o.variable(hostViewFactoryVar), - o.importExpr(compMeta.type), - ], - o.importType( - createIdentifier(Identifiers.ComponentFactory), - [o.importType(compMeta.type)], [o.TypeModifier.Const]))) - .toDeclStmt(null, [o.StmtModifier.Final])); - } + targetStatements.push( + o.variable(compFactoryVar) + .set(o.importExpr(createIdentifier(Identifiers.createComponentFactory)).callFn([ + o.literal(compMeta.selector), + o.importExpr(compMeta.type), + o.variable(hostViewFactoryVar), + ])) + .toDeclStmt( + o.importType( + createIdentifier(Identifiers.ComponentFactory), [o.importType(compMeta.type)], + [o.TypeModifier.Const]), + [o.StmtModifier.Final])); return compFactoryVar; } @@ -232,7 +193,7 @@ export class AotCompiler { identifierName(compMeta.type)); const stylesExpr = componentStyles ? o.variable(componentStyles.stylesVar) : o.literalArr([]); const viewResult = - this._viewCompiler.compileComponent(compMeta, parsedTemplate, stylesExpr, usedPipes, null); + this._viewCompiler.compileComponent(compMeta, parsedTemplate, stylesExpr, usedPipes); if (componentStyles) { targetStatements.push( ..._resolveStyleStatements(this._symbolResolver, componentStyles, fileSuffix)); diff --git a/modules/@angular/compiler/src/aot/compiler_factory.ts b/modules/@angular/compiler/src/aot/compiler_factory.ts index 8283ff47417ac..7c68979232c02 100644 --- a/modules/@angular/compiler/src/aot/compiler_factory.ts +++ b/modules/@angular/compiler/src/aot/compiler_factory.ts @@ -7,11 +7,9 @@ */ import {MissingTranslationStrategy, ViewEncapsulation, ɵConsole as Console} from '@angular/core'; -import {AnimationParser} from '../animation/animation_parser'; import {CompilerConfig} from '../config'; import {DirectiveNormalizer} from '../directive_normalizer'; import {DirectiveResolver} from '../directive_resolver'; -import {DirectiveWrapperCompiler} from '../directive_wrapper_compiler'; import {Lexer} from '../expression_parser/lexer'; import {Parser} from '../expression_parser/parser'; import {I18NHtmlParser} from '../i18n/i18n_html_parser'; @@ -26,7 +24,6 @@ import {StyleCompiler} from '../style_compiler'; import {TemplateParser} from '../template_parser/template_parser'; import {createOfflineCompileUrlResolver} from '../url_resolver'; import {ViewCompiler} from '../view_compiler/view_compiler'; -import {ViewCompilerNext} from '../view_compiler_next/view_compiler'; import {AotCompiler} from './compiler'; import {AotCompilerHost} from './compiler_host'; @@ -61,7 +58,6 @@ export function createAotCompiler(compilerHost: AotCompilerHost, options: AotCom defaultEncapsulation: ViewEncapsulation.Emulated, logBindingUpdate: false, useJit: false, - useViewEngine: options.useViewEngine, enableLegacyTemplate: options.enableLegacyTemplate !== false, }); const normalizer = new DirectiveNormalizer( @@ -81,13 +77,10 @@ export function createAotCompiler(compilerHost: AotCompilerHost, options: AotCom compilerHost.fileNameToModuleName(fileName, containingFilePath), getTypeArity: (symbol: StaticSymbol) => symbolResolver.getTypeArity(symbol) }; - const viewCompiler = config.useViewEngine ? new ViewCompilerNext(config, elementSchemaRegistry) : - new ViewCompiler(config, elementSchemaRegistry); + const viewCompiler = new ViewCompiler(config, elementSchemaRegistry); const compiler = new AotCompiler( config, compilerHost, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, - new DirectiveWrapperCompiler(config, expressionParser, elementSchemaRegistry, console), new NgModuleCompiler(), new TypeScriptEmitter(importResolver), summaryResolver, - options.locale, options.i18nFormat, new AnimationParser(elementSchemaRegistry), - symbolResolver); + options.locale, options.i18nFormat, symbolResolver); return {compiler, reflector: staticReflector}; } diff --git a/modules/@angular/compiler/src/aot/compiler_options.ts b/modules/@angular/compiler/src/aot/compiler_options.ts index adafef9916ec6..624e592c54007 100644 --- a/modules/@angular/compiler/src/aot/compiler_options.ts +++ b/modules/@angular/compiler/src/aot/compiler_options.ts @@ -11,6 +11,5 @@ export interface AotCompilerOptions { locale?: string; i18nFormat?: string; translations?: string; - useViewEngine?: boolean; enableLegacyTemplate?: boolean; } diff --git a/modules/@angular/compiler/src/compile_metadata.ts b/modules/@angular/compiler/src/compile_metadata.ts index d5cdc5a59ba4d..913255b659a77 100644 --- a/modules/@angular/compiler/src/compile_metadata.ts +++ b/modules/@angular/compiler/src/compile_metadata.ts @@ -313,7 +313,6 @@ export interface CompileDirectiveSummary extends CompileTypeSummary { entryComponents: CompileEntryComponentMetadata[]; changeDetection: ChangeDetectionStrategy; template: CompileTemplateSummary; - wrapperType: StaticSymbol|ProxyClass; componentViewType: StaticSymbol|ProxyClass; rendererType: StaticSymbol|RendererTypeV2; componentFactory: StaticSymbol|ComponentFactory; @@ -325,8 +324,8 @@ export interface CompileDirectiveSummary extends CompileTypeSummary { export class CompileDirectiveMetadata { static create( {isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, host, - providers, viewProviders, queries, viewQueries, entryComponents, template, wrapperType, - componentViewType, rendererType, componentFactory}: { + providers, viewProviders, queries, viewQueries, entryComponents, template, componentViewType, + rendererType, componentFactory}: { isHost?: boolean, type?: CompileTypeMetadata, isComponent?: boolean, @@ -342,7 +341,6 @@ export class CompileDirectiveMetadata { viewQueries?: CompileQueryMetadata[], entryComponents?: CompileEntryComponentMetadata[], template?: CompileTemplateMetadata, - wrapperType?: StaticSymbol|ProxyClass, componentViewType?: StaticSymbol|ProxyClass, rendererType?: StaticSymbol|RendererTypeV2, componentFactory?: StaticSymbol|ComponentFactory, @@ -397,7 +395,6 @@ export class CompileDirectiveMetadata { viewQueries, entryComponents, template, - wrapperType, componentViewType, rendererType, componentFactory, @@ -422,16 +419,14 @@ export class CompileDirectiveMetadata { template: CompileTemplateMetadata; - wrapperType: StaticSymbol|ProxyClass; componentViewType: StaticSymbol|ProxyClass; rendererType: StaticSymbol|RendererTypeV2; componentFactory: StaticSymbol|ComponentFactory; - constructor({isHost, type, isComponent, selector, exportAs, - changeDetection, inputs, outputs, hostListeners, hostProperties, - hostAttributes, providers, viewProviders, queries, viewQueries, - entryComponents, template, wrapperType, componentViewType, rendererType, - componentFactory}: { + constructor({isHost, type, isComponent, selector, exportAs, + changeDetection, inputs, outputs, hostListeners, hostProperties, + hostAttributes, providers, viewProviders, queries, viewQueries, + entryComponents, template, componentViewType, rendererType, componentFactory}: { isHost?: boolean, type?: CompileTypeMetadata, isComponent?: boolean, @@ -449,7 +444,6 @@ export class CompileDirectiveMetadata { viewQueries?: CompileQueryMetadata[], entryComponents?: CompileEntryComponentMetadata[], template?: CompileTemplateMetadata, - wrapperType?: StaticSymbol|ProxyClass, componentViewType?: StaticSymbol|ProxyClass, rendererType?: StaticSymbol|RendererTypeV2, componentFactory?: StaticSymbol|ComponentFactory, @@ -472,7 +466,6 @@ export class CompileDirectiveMetadata { this.entryComponents = _normalizeArray(entryComponents); this.template = template; - this.wrapperType = wrapperType; this.componentViewType = componentViewType; this.rendererType = rendererType; this.componentFactory = componentFactory; @@ -497,7 +490,6 @@ export class CompileDirectiveMetadata { entryComponents: this.entryComponents, changeDetection: this.changeDetection, template: this.template && this.template.toSummary(), - wrapperType: this.wrapperType, componentViewType: this.componentViewType, rendererType: this.rendererType, componentFactory: this.componentFactory diff --git a/modules/@angular/compiler/src/compiler.ts b/modules/@angular/compiler/src/compiler.ts index 5745badaee3c4..8001bfd1d7634 100644 --- a/modules/@angular/compiler/src/compiler.ts +++ b/modules/@angular/compiler/src/compiler.ts @@ -24,7 +24,7 @@ export {VERSION} from './version'; export * from './template_parser/template_ast'; export {TEMPLATE_TRANSFORMS} from './template_parser/template_parser'; -export {CompilerConfig, RenderTypes} from './config'; +export {CompilerConfig} from './config'; export * from './compile_metadata'; export * from './aot/compiler_factory'; export * from './aot/compiler'; @@ -57,7 +57,6 @@ export * from './ml_parser/html_tags'; export * from './ml_parser/interpolation_config'; export * from './ml_parser/tags'; export {NgModuleCompiler} from './ng_module_compiler'; -export {DirectiveWrapperCompiler} from './directive_wrapper_compiler'; export * from './output/path_util'; export * from './output/ts_emitter'; export * from './parse_util'; @@ -66,6 +65,5 @@ export * from './selector'; export * from './style_compiler'; export * from './template_parser/template_parser'; export {ViewCompiler} from './view_compiler/view_compiler'; -export {AnimationParser} from './animation/animation_parser'; export {isSyntaxError, syntaxError} from './util'; // This file only reexports content of the `src` folder. Keep it that way. diff --git a/modules/@angular/compiler/src/compiler_util/binding_util.ts b/modules/@angular/compiler/src/compiler_util/binding_util.ts deleted file mode 100644 index a2e475303c341..0000000000000 --- a/modules/@angular/compiler/src/compiler_util/binding_util.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import {ClassBuilder} from '../output/class_builder'; -import * as o from '../output/output_ast'; - -export class CheckBindingField { - constructor(public expression: o.ReadPropExpr, public bindingId: string) {} -} - -export function createCheckBindingField(builder: ClassBuilder): CheckBindingField { - const bindingId = `${builder.fields.length}`; - const fieldExpr = createBindFieldExpr(bindingId); - // private is fine here as no child view will reference the cached value... - builder.fields.push(new o.ClassField(fieldExpr.name, null, [o.StmtModifier.Private])); - builder.ctorStmts.push(o.THIS_EXPR.prop(fieldExpr.name).set(o.literal(undefined)).toStmt()); - return new CheckBindingField(fieldExpr, bindingId); -} - -function createBindFieldExpr(bindingId: string): o.ReadPropExpr { - return o.THIS_EXPR.prop(`_expr_${bindingId}`); -} - -export function isFirstViewCheck(view: o.Expression): o.Expression { - return o.not(view.prop('numberOfChecks')); -} \ No newline at end of file diff --git a/modules/@angular/compiler/src/compiler_util/expression_converter.ts b/modules/@angular/compiler/src/compiler_util/expression_converter.ts index 1d45cb95a66a5..8dfa1a7f18df0 100644 --- a/modules/@angular/compiler/src/compiler_util/expression_converter.ts +++ b/modules/@angular/compiler/src/compiler_util/expression_converter.ts @@ -10,13 +10,8 @@ import * as cdAst from '../expression_parser/ast'; import {isBlank} from '../facade/lang'; import {Identifiers, createIdentifier} from '../identifiers'; -import {ClassBuilder} from '../output/class_builder'; import * as o from '../output/output_ast'; -import {createPureProxy} from './identifier_util'; - -const VAL_UNWRAPPER_VAR = o.variable(`valUnwrapper`); - export class EventHandlerVars { static event = o.variable('$event'); } export interface LocalResolver { getLocal(name: string): o.Expression; } @@ -116,73 +111,6 @@ export function convertPropertyBinding( return new ConvertPropertyBindingResult(stmts, currValExpr); } - -export class LegacyConvertPropertyBindingResult implements ConvertPropertyBindingResult { - constructor( - public stmts: o.Statement[], public currValExpr: o.Expression, - public forceUpdate: o.Expression) {} -} - -export interface LegacyNameResolver { - callPipe(name: string, input: o.Expression, args: o.Expression[]): o.Expression; - getLocal(name: string): o.Expression; -} - -/** - * Converts the given expression AST into an executable output AST, assuming the expression is - * used in a property binding. - */ -export function legacyConvertPropertyBinding( - builder: ClassBuilder, nameResolver: LegacyNameResolver, implicitReceiver: o.Expression, - expression: cdAst.AST, bindingId: string): LegacyConvertPropertyBindingResult { - if (!nameResolver) { - nameResolver = new LegacyDefaultNameResolver(); - } - let needsValueUnwrapper = false; - const expressionWithoutBuiltins = convertBuiltins( - { - createLiteralArrayConverter: (argCount: number) => { - return (args: o.Expression[]) => legacyCreateCachedLiteralArray(builder, args); - }, - createLiteralMapConverter: (keys: string[]) => { - return (args: o.Expression[]) => legacyCreateCachedLiteralMap( - builder, <[string, o.Expression][]>keys.map((key, i) => [key, args[i]])); - }, - createPipeConverter: (name: string) => { - needsValueUnwrapper = true; - return (args: o.Expression[]) => VAL_UNWRAPPER_VAR.callMethod( - 'unwrap', [nameResolver.callPipe(name, args[0], args.slice(1))]); - } - }, - expression); - - const {stmts, currValExpr} = - convertPropertyBinding(nameResolver, implicitReceiver, expressionWithoutBuiltins, bindingId); - let forceUpdate: o.Expression = null; - if (needsValueUnwrapper) { - const initValueUnwrapperStmt = VAL_UNWRAPPER_VAR.callMethod('reset', []).toStmt(); - stmts.unshift(initValueUnwrapperStmt); - forceUpdate = VAL_UNWRAPPER_VAR.prop('hasWrappedValue'); - } - return new LegacyConvertPropertyBindingResult(stmts, currValExpr, forceUpdate); -} - -/** - * Creates variables that are shared by multiple calls to `convertActionBinding` / - * `convertPropertyBinding` - */ -export function legacyCreateSharedBindingVariablesIfNeeded(stmts: o.Statement[]): o.Statement[] { - const unwrapperStmts: o.Statement[] = []; - const readVars = o.findReadVarNames(stmts); - if (readVars.has(VAL_UNWRAPPER_VAR.name)) { - unwrapperStmts.push( - VAL_UNWRAPPER_VAR - .set(o.importExpr(createIdentifier(Identifiers.ValueUnwrapper)).instantiate([])) - .toDeclStmt(null, [o.StmtModifier.Final])); - } - return unwrapperStmts; -} - function convertBuiltins(converterFactory: BuiltinConverterFactory, ast: cdAst.AST): cdAst.AST { const visitor = new _BuiltinAstConverter(converterFactory); return ast.visit(visitor); @@ -649,50 +577,6 @@ function flattenStatements(arg: any, output: o.Statement[]) { } } -function legacyCreateCachedLiteralArray( - builder: ClassBuilder, values: o.Expression[]): o.Expression { - if (values.length === 0) { - return o.importExpr(createIdentifier(Identifiers.EMPTY_ARRAY)); - } - 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)); - } - createPureProxy( - o.fn( - proxyParams, [new o.ReturnStatement(o.literalArr(proxyReturnEntries))], - new o.ArrayType(o.DYNAMIC_TYPE)), - values.length, proxyExpr, builder); - return proxyExpr.callFn(values); -} - -function legacyCreateCachedLiteralMap( - builder: ClassBuilder, entries: [string, o.Expression][]): o.Expression { - if (entries.length === 0) { - return o.importExpr(createIdentifier(Identifiers.EMPTY_MAP)); - } - const proxyExpr = o.THIS_EXPR.prop(`_map_${builder.fields.length}`); - const proxyParams: o.FnParam[] = []; - const proxyReturnEntries: [string, o.Expression][] = []; - const values: o.Expression[] = []; - 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)]); - values.push(entries[i][1]); - } - createPureProxy( - o.fn( - proxyParams, [new o.ReturnStatement(o.literalMap(proxyReturnEntries))], - new o.MapType(o.DYNAMIC_TYPE)), - entries.length, proxyExpr, builder); - return proxyExpr.callFn(values); -} - class DefaultLocalResolver implements LocalResolver { getLocal(name: string): o.Expression { if (name === EventHandlerVars.event.name) { @@ -702,16 +586,6 @@ class DefaultLocalResolver implements LocalResolver { } } -class LegacyDefaultNameResolver implements LegacyNameResolver { - callPipe(name: string, input: o.Expression, args: o.Expression[]): o.Expression { return null; } - getLocal(name: string): o.Expression { - if (name === EventHandlerVars.event.name) { - return EventHandlerVars.event; - } - return null; - } -} - function createCurrValueExpr(bindingId: string): o.ReadVarExpr { return o.variable(`currVal_${bindingId}`); // fix syntax highlighting: ` } diff --git a/modules/@angular/compiler/src/compiler_util/identifier_util.ts b/modules/@angular/compiler/src/compiler_util/identifier_util.ts deleted file mode 100644 index 85362141ce710..0000000000000 --- a/modules/@angular/compiler/src/compiler_util/identifier_util.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import {CompileTokenMetadata} from '../compile_metadata'; -import {isPresent} from '../facade/lang'; -import {IdentifierSpec, Identifiers, createEnumIdentifier, createIdentifier} from '../identifiers'; -import * as o from '../output/output_ast'; - -export function createDiTokenExpression(token: CompileTokenMetadata): o.Expression { - if (isPresent(token.value)) { - return o.literal(token.value); - } else { - return o.importExpr(token.identifier); - } -} - -export function createInlineArray(values: o.Expression[]): o.Expression { - if (values.length === 0) { - return o.importExpr(createIdentifier(Identifiers.EMPTY_INLINE_ARRAY)); - } - const log2 = Math.log(values.length) / Math.log(2); - const index = Math.ceil(log2); - const identifierSpec = index < Identifiers.inlineArrays.length ? Identifiers.inlineArrays[index] : - Identifiers.InlineArrayDynamic; - const identifier = createIdentifier(identifierSpec); - return o.importExpr(identifier).instantiate([ - o.literal(values.length) - ].concat(values)); -} - -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)); - const pureProxyId = - argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null; - if (!pureProxyId) { - throw new Error(`Unsupported number of argument for pure functions: ${argCount}`); - } - builder.ctorStmts.push(o.THIS_EXPR.prop(pureProxyProp.name) - .set(o.importExpr(createIdentifier(pureProxyId)).callFn([fn])) - .toStmt()); -} - -export function createEnumExpression(enumType: IdentifierSpec, enumValue: any): o.Expression { - const enumName = - Object.keys(enumType.runtime).find((propName) => enumType.runtime[propName] === enumValue); - if (!enumName) { - throw new Error(`Unknown enum value ${enumValue} in ${enumType.name}`); - } - return o.importExpr(createEnumIdentifier(enumType, enumName)); -} diff --git a/modules/@angular/compiler/src/compiler_util/render_util.ts b/modules/@angular/compiler/src/compiler_util/render_util.ts deleted file mode 100644 index e2d30c5d29fa8..0000000000000 --- a/modules/@angular/compiler/src/compiler_util/render_util.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import {SecurityContext, ɵEMPTY_STATE as EMPTY_ANIMATION_STATE} from '@angular/core'; -import {Identifiers, createIdentifier} from '../identifiers'; -import * as o from '../output/output_ast'; -import {BoundElementPropertyAst, BoundEventAst, PropertyBindingType} from '../template_parser/template_ast'; - -import {isFirstViewCheck} from './binding_util'; -import {LegacyConvertPropertyBindingResult} from './expression_converter'; -import {createEnumExpression} from './identifier_util'; - -export function createCheckRenderBindingStmt( - view: o.Expression, renderElement: o.Expression, boundProp: BoundElementPropertyAst, - oldValue: o.ReadPropExpr, evalResult: LegacyConvertPropertyBindingResult, - securityContextExpression?: o.Expression): o.Statement[] { - const checkStmts: o.Statement[] = [...evalResult.stmts]; - const securityContext = calcSecurityContext(boundProp, securityContextExpression); - switch (boundProp.type) { - case PropertyBindingType.Property: - checkStmts.push(o.importExpr(createIdentifier(Identifiers.checkRenderProperty)) - .callFn([ - view, renderElement, o.literal(boundProp.name), oldValue, - oldValue.set(evalResult.currValExpr), - evalResult.forceUpdate || o.literal(false), securityContext - ]) - .toStmt()); - break; - case PropertyBindingType.Attribute: - checkStmts.push(o.importExpr(createIdentifier(Identifiers.checkRenderAttribute)) - .callFn([ - view, renderElement, o.literal(boundProp.name), oldValue, - oldValue.set(evalResult.currValExpr), - evalResult.forceUpdate || o.literal(false), securityContext - ]) - .toStmt()); - break; - case PropertyBindingType.Class: - checkStmts.push( - o.importExpr(createIdentifier(Identifiers.checkRenderClass)) - .callFn([ - view, renderElement, o.literal(boundProp.name), oldValue, - oldValue.set(evalResult.currValExpr), evalResult.forceUpdate || o.literal(false) - ]) - .toStmt()); - break; - case PropertyBindingType.Style: - checkStmts.push( - o.importExpr(createIdentifier(Identifiers.checkRenderStyle)) - .callFn([ - view, renderElement, o.literal(boundProp.name), o.literal(boundProp.unit), oldValue, - oldValue.set(evalResult.currValExpr), evalResult.forceUpdate || o.literal(false), - securityContext - ]) - .toStmt()); - break; - case PropertyBindingType.Animation: - throw new Error('Illegal state: Should not come here!'); - } - return checkStmts; -} - -function calcSecurityContext( - boundProp: BoundElementPropertyAst, securityContextExpression?: o.Expression): o.Expression { - if (boundProp.securityContext === SecurityContext.NONE) { - return o.NULL_EXPR; // No sanitization needed. - } - if (!boundProp.needsRuntimeSecurityContext) { - securityContextExpression = - createEnumExpression(Identifiers.SecurityContext, boundProp.securityContext); - } - if (!securityContextExpression) { - throw new Error(`internal error, no SecurityContext given ${boundProp.name}`); - } - return securityContextExpression; -} - -export function createCheckAnimationBindingStmts( - view: o.Expression, componentView: o.Expression, boundProp: BoundElementPropertyAst, - boundOutputs: BoundEventAst[], eventListener: o.Expression, renderElement: o.Expression, - oldValue: o.ReadPropExpr, evalResult: LegacyConvertPropertyBindingResult) { - const detachStmts: o.Statement[] = []; - const updateStmts: o.Statement[] = []; - - const animationName = boundProp.name; - - const animationFnExpr = - componentView.prop('componentType').prop('animations').key(o.literal(animationName)); - - // it's important to normalize the void value as `void` explicitly - // so that the styles data can be obtained from the stringmap - const emptyStateValue = o.literal(EMPTY_ANIMATION_STATE); - const animationTransitionVar = o.variable('animationTransition_' + animationName); - - updateStmts.push( - animationTransitionVar - .set(animationFnExpr.callFn([ - view, renderElement, isFirstViewCheck(view).conditional(emptyStateValue, oldValue), - evalResult.currValExpr - ])) - .toDeclStmt()); - updateStmts.push(oldValue.set(evalResult.currValExpr).toStmt()); - - detachStmts.push(animationTransitionVar - .set(animationFnExpr.callFn( - [view, renderElement, evalResult.currValExpr, emptyStateValue])) - .toDeclStmt()); - - const registerStmts: o.Statement[] = []; - const animationStartMethodExists = boundOutputs.find( - event => event.isAnimation && event.name == animationName && event.phase == 'start'); - if (animationStartMethodExists) { - registerStmts.push( - animationTransitionVar - .callMethod( - 'onStart', - [eventListener.callMethod( - o.BuiltinMethod.Bind, - [view, o.literal(BoundEventAst.calcFullName(animationName, null, 'start'))])]) - .toStmt()); - } - - const animationDoneMethodExists = boundOutputs.find( - event => event.isAnimation && event.name == animationName && event.phase == 'done'); - if (animationDoneMethodExists) { - registerStmts.push( - animationTransitionVar - .callMethod( - 'onDone', - [eventListener.callMethod( - o.BuiltinMethod.Bind, - [view, o.literal(BoundEventAst.calcFullName(animationName, null, 'done'))])]) - .toStmt()); - } - - updateStmts.push(...registerStmts); - detachStmts.push(...registerStmts); - - const checkUpdateStmts: o.Statement[] = [ - ...evalResult.stmts, - new o.IfStmt( - o.importExpr(createIdentifier(Identifiers.checkBinding)).callFn([ - view, oldValue, evalResult.currValExpr, evalResult.forceUpdate || o.literal(false) - ]), - updateStmts) - ]; - const checkDetachStmts: o.Statement[] = [...evalResult.stmts, ...detachStmts]; - return {checkUpdateStmts, checkDetachStmts}; -} diff --git a/modules/@angular/compiler/src/config.ts b/modules/@angular/compiler/src/config.ts index db9d65aa3c969..50f2ca74f9e22 100644 --- a/modules/@angular/compiler/src/config.ts +++ b/modules/@angular/compiler/src/config.ts @@ -12,47 +12,32 @@ import {CompileIdentifierMetadata} from './compile_metadata'; import {Identifiers, createIdentifier} from './identifiers'; -/** - * Temporal switch for the compiler to use the new view engine, - * until it is fully integrated. - * - * Only works in Jit for now. - */ -export const USE_VIEW_ENGINE = new InjectionToken('UseViewEngine'); - export class CompilerConfig { - public renderTypes: RenderTypes; public defaultEncapsulation: ViewEncapsulation; // Whether to support the `