diff --git a/modules/angular2/src/compiler/change_definition_factory.ts b/modules/angular2/src/compiler/change_definition_factory.ts index ab0ca2839a..893293bf09 100644 --- a/modules/angular2/src/compiler/change_definition_factory.ts +++ b/modules/angular2/src/compiler/change_definition_factory.ts @@ -3,11 +3,9 @@ import {isPresent, isBlank} from 'angular2/src/core/facade/lang'; import {reflector} from 'angular2/src/core/reflection/reflection'; import { - ChangeDetection, DirectiveIndex, BindingRecord, DirectiveRecord, - ProtoChangeDetector, ChangeDetectionStrategy, ChangeDetectorDefinition, ChangeDetectorGenConfig, diff --git a/modules/angular2/src/core/application_common.ts b/modules/angular2/src/core/application_common.ts index 718ef08bfe..251f346af3 100644 --- a/modules/angular2/src/core/application_common.ts +++ b/modules/angular2/src/core/application_common.ts @@ -12,8 +12,6 @@ import { import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter'; import {BrowserGetTestability} from 'angular2/src/core/testability/browser_testability'; import {DOM} from 'angular2/src/core/dom/dom_adapter'; -import {ViewLoader} from 'angular2/src/core/render/dom/compiler/view_loader'; -import {StyleInliner} from 'angular2/src/core/render/dom/compiler/style_inliner'; import {Promise, PromiseWrapper, PromiseCompleter} from 'angular2/src/core/facade/async'; import {XHR} from 'angular2/src/core/render/xhr'; import {XHRImpl} from 'angular2/src/core/render/xhr_impl'; @@ -31,15 +29,8 @@ import { DynamicComponentLoader } from 'angular2/src/core/compiler/dynamic_component_loader'; import {TestabilityRegistry, Testability} from 'angular2/src/core/testability/testability'; -import {Renderer, RenderCompiler} from 'angular2/src/core/render/api'; -import { - DomRenderer, - DOCUMENT, - DefaultDomCompiler, - APP_ID_RANDOM_BINDING, - MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE, - TemplateCloner -} from 'angular2/src/core/render/render'; +import {Renderer} from 'angular2/src/core/render/api'; +import {DomRenderer, DOCUMENT, APP_ID_RANDOM_BINDING} from 'angular2/src/core/render/render'; import {ElementSchemaRegistry} from 'angular2/src/core/render/dom/schema/element_schema_registry'; import { DomElementSchemaRegistry @@ -72,17 +63,11 @@ export function applicationDomBindings(): Array { DomRenderer, bind(Renderer).toAlias(DomRenderer), APP_ID_RANDOM_BINDING, - TemplateCloner, - bind(MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE).toValue(20), - DefaultDomCompiler, bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()), - bind(RenderCompiler).toAlias(DefaultDomCompiler), DomSharedStylesHost, bind(SharedStylesHost).toAlias(DomSharedStylesHost), - ViewLoader, EXCEPTION_BINDING, bind(XHR).toValue(new XHRImpl()), - StyleInliner, Testability, AnchorBasedAppRootUrl, bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl), diff --git a/modules/angular2/src/core/application_ref.ts b/modules/angular2/src/core/application_ref.ts index ac84d1586c..e267e32c29 100644 --- a/modules/angular2/src/core/application_ref.ts +++ b/modules/angular2/src/core/application_ref.ts @@ -21,10 +21,6 @@ import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle'; import { Parser, Lexer, - ChangeDetection, - DynamicChangeDetection, - JitChangeDetection, - PreGeneratedChangeDetection, IterableDiffers, defaultIterableDiffers, KeyValueDiffers, @@ -39,9 +35,7 @@ import {DEFAULT_PIPES} from 'angular2/src/core/pipes'; import {ViewResolver} from './compiler/view_resolver'; import {DirectiveResolver} from './compiler/directive_resolver'; import {PipeResolver} from './compiler/pipe_resolver'; -import {StyleUrlResolver} from 'angular2/src/core/render/dom/compiler/style_url_resolver'; import {UrlResolver} from 'angular2/src/core/services/url_resolver'; -import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper'; import { APP_ID_RANDOM_BINDING, } from 'angular2/src/core/render/render'; @@ -90,12 +84,6 @@ function _componentBindings(appComponentType: Type): Array { - var bestChangeDetection = new DynamicChangeDetection(); - if (PreGeneratedChangeDetection.isSupported()) { - bestChangeDetection = new PreGeneratedChangeDetection(); - } else if (JitChangeDetection.isSupported()) { - bestChangeDetection = new JitChangeDetection(); - } return [ Compiler, APP_ID_RANDOM_BINDING, @@ -109,12 +97,9 @@ export function applicationCommonBindings(): Array { DEFAULT_PIPES, bind(IterableDiffers).toValue(defaultIterableDiffers), bind(KeyValueDiffers).toValue(defaultKeyValueDiffers), - bind(ChangeDetection).toValue(bestChangeDetection), DirectiveResolver, UrlResolver, - StyleUrlResolver, PipeResolver, - ComponentUrlMapper, Parser, Lexer, DynamicComponentLoader, diff --git a/modules/angular2/src/core/change_detection/change_detection.ts b/modules/angular2/src/core/change_detection/change_detection.ts index 594711730c..7277c2150c 100644 --- a/modules/angular2/src/core/change_detection/change_detection.ts +++ b/modules/angular2/src/core/change_detection/change_detection.ts @@ -1,19 +1,8 @@ -import {JitProtoChangeDetector} from './jit_proto_change_detector'; -import {PregenProtoChangeDetector} from './pregen_proto_change_detector'; -import {DynamicProtoChangeDetector} from './proto_change_detector'; import {IterableDiffers, IterableDifferFactory} from './differs/iterable_differs'; import {DefaultIterableDifferFactory} from './differs/default_iterable_differ'; import {KeyValueDiffers, KeyValueDifferFactory} from './differs/keyvalue_differs'; import {DefaultKeyValueDifferFactory} from './differs/default_keyvalue_differ'; -import { - ChangeDetection, - ProtoChangeDetector, - ChangeDetectorDefinition, - ChangeDetectorGenConfig -} from './interfaces'; -import {Injector, Inject, Injectable, OpaqueToken, Optional, Binding} from 'angular2/src/core/di'; -import {StringMap, StringMapWrapper} from 'angular2/src/core/facade/collection'; -import {CONST, CONST_EXPR, isPresent, assertionsEnabled} from 'angular2/src/core/facade/lang'; +import {CONST, CONST_EXPR, isPresent} from 'angular2/src/core/facade/lang'; export { ASTWithSource, @@ -37,13 +26,13 @@ export { ProtoChangeDetector, ChangeDetector, ChangeDispatcher, - ChangeDetection, ChangeDetectorDefinition, DebugContext, ChangeDetectorGenConfig } from './interfaces'; export {ChangeDetectionStrategy, CHANGE_DECTION_STRATEGY_VALUES} from './constants'; export {DynamicProtoChangeDetector} from './proto_change_detector'; +export {JitProtoChangeDetector} from './jit_proto_change_detector'; export {BindingRecord, BindingTarget} from './binding_record'; export {DirectiveIndex, DirectiveRecord} from './directive_record'; export {DynamicChangeDetector} from './dynamic_change_detector'; @@ -68,98 +57,3 @@ export const iterableDiff: IterableDifferFactory[] = export const defaultIterableDiffers = CONST_EXPR(new IterableDiffers(iterableDiff)); export const defaultKeyValueDiffers = CONST_EXPR(new KeyValueDiffers(keyValDiff)); - -/** - * Map from {@link ChangeDetectorDefinition#id} to a factory method which takes a - * {@link Pipes} and a {@link ChangeDetectorDefinition} and generates a - * {@link ProtoChangeDetector} associated with the definition. - */ -// TODO(kegluneq): Use PregenProtoChangeDetectorFactory rather than Function once possible in -// dart2js. See https://github.com/dart-lang/sdk/issues/23630 for details. -export var preGeneratedProtoDetectors: StringMap = {}; - -/** - * Implements change detection using a map of pregenerated proto detectors. - */ -@Injectable() -export class PreGeneratedChangeDetection extends ChangeDetection { - _dynamicChangeDetection: ChangeDetection; - _protoChangeDetectorFactories: StringMap; - _genConfig: ChangeDetectorGenConfig; - - constructor(config?: ChangeDetectorGenConfig, - protoChangeDetectorsForTest?: StringMap) { - super(); - this._dynamicChangeDetection = new DynamicChangeDetection(); - this._protoChangeDetectorFactories = isPresent(protoChangeDetectorsForTest) ? - protoChangeDetectorsForTest : - preGeneratedProtoDetectors; - - this._genConfig = - isPresent(config) ? config : new ChangeDetectorGenConfig(assertionsEnabled(), - assertionsEnabled(), false, false); - } - - static isSupported(): boolean { return PregenProtoChangeDetector.isSupported(); } - - getProtoChangeDetector(id: string, definition: ChangeDetectorDefinition): ProtoChangeDetector { - if (StringMapWrapper.contains(this._protoChangeDetectorFactories, id)) { - return StringMapWrapper.get(this._protoChangeDetectorFactories, id)(definition); - } - return this._dynamicChangeDetection.getProtoChangeDetector(id, definition); - } - - get genConfig(): ChangeDetectorGenConfig { return this._genConfig; } - get generateDetectors(): boolean { return true; } -} - - -/** - * Implements change detection that does not require `eval()`. - * - * This is slower than {@link JitChangeDetection}. - */ -@Injectable() -export class DynamicChangeDetection extends ChangeDetection { - _genConfig: ChangeDetectorGenConfig; - - constructor(config?: ChangeDetectorGenConfig) { - super(); - this._genConfig = - isPresent(config) ? config : new ChangeDetectorGenConfig(assertionsEnabled(), - assertionsEnabled(), false, false); - } - - getProtoChangeDetector(id: string, definition: ChangeDetectorDefinition): ProtoChangeDetector { - return new DynamicProtoChangeDetector(definition); - } - - get genConfig(): ChangeDetectorGenConfig { return this._genConfig; } - get generateDetectors(): boolean { return true; } -} - -/** - * Implements faster change detection by generating source code. - * - * This requires `eval()`. For change detection that does not require `eval()`, see - * {@link DynamicChangeDetection} and {@link PreGeneratedChangeDetection}. - */ -@Injectable() -export class JitChangeDetection extends ChangeDetection { - _genConfig: ChangeDetectorGenConfig; - constructor(config?: ChangeDetectorGenConfig) { - super(); - this._genConfig = - isPresent(config) ? config : new ChangeDetectorGenConfig(assertionsEnabled(), - assertionsEnabled(), false, true); - } - - static isSupported(): boolean { return JitProtoChangeDetector.isSupported(); } - - getProtoChangeDetector(id: string, definition: ChangeDetectorDefinition): ProtoChangeDetector { - return new JitProtoChangeDetector(definition); - } - - get genConfig(): ChangeDetectorGenConfig { return this._genConfig; } - get generateDetectors(): boolean { return true; } -} diff --git a/modules/angular2/src/core/change_detection/interfaces.ts b/modules/angular2/src/core/change_detection/interfaces.ts index c2e5f5c0e8..6710f42814 100644 --- a/modules/angular2/src/core/change_detection/interfaces.ts +++ b/modules/angular2/src/core/change_detection/interfaces.ts @@ -1,46 +1,9 @@ -import {CONST} from 'angular2/src/core/facade/lang'; import {Locals} from './parser/locals'; import {BindingTarget, BindingRecord} from './binding_record'; import {DirectiveIndex, DirectiveRecord} from './directive_record'; import {ChangeDetectionStrategy} from './constants'; import {ChangeDetectorRef} from './change_detector_ref'; -/** - * Interface used by Angular to control the change detection strategy for an application. - * - * Angular implements the following change detection strategies by default: - * - * - {@link DynamicChangeDetection}: slower, but does not require `eval()`. - * - {@link JitChangeDetection}: faster, but requires `eval()`. - * - * In JavaScript, you should always use `JitChangeDetection`, unless you are in an environment that - *has - * [CSP](https://developer.mozilla.org/en-US/docs/Web/Security/CSP), such as a Chrome Extension. - * - * In Dart, use `DynamicChangeDetection` during development. The Angular transformer generates an - *analog to the - * `JitChangeDetection` strategy at compile time. - * - * - * See: {@link DynamicChangeDetection}, {@link JitChangeDetection}, - * {@link PreGeneratedChangeDetection} - * - * # Example - * ```javascript - * bootstrap(MyApp, [bind(ChangeDetection).toValue(new DynamicChangeDetection())]); - * ``` - */ -@CONST() -export class ChangeDetection { - getProtoChangeDetector(id: string, definition: ChangeDetectorDefinition): ProtoChangeDetector { - return null; - } - - get generateDetectors(): boolean { return null; } - - get genConfig(): ChangeDetectorGenConfig { return null; } -} - export class DebugContext { constructor(public element: any, public componentElement: any, public directive: any, public context: any, public locals: any, public injector: any) {} diff --git a/modules/angular2/src/core/compiler.ts b/modules/angular2/src/core/compiler.ts index 11be5c9879..add7d03e14 100644 --- a/modules/angular2/src/core/compiler.ts +++ b/modules/angular2/src/core/compiler.ts @@ -9,7 +9,6 @@ export { OnInit, DoCheck } from './compiler/interfaces'; -export {ComponentUrlMapper} from './compiler/component_url_mapper'; export {DirectiveResolver} from './compiler/directive_resolver'; export {Compiler} from './compiler/compiler'; export {AppViewManager} from './compiler/view_manager'; diff --git a/modules/angular2/src/core/compiler/element_injector.ts b/modules/angular2/src/core/compiler/element_injector.ts index 22faef99b8..7e5bee8e83 100644 --- a/modules/angular2/src/core/compiler/element_injector.ts +++ b/modules/angular2/src/core/compiler/element_injector.ts @@ -48,7 +48,6 @@ import { import {QueryList} from './query_list'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {SetterFn} from 'angular2/src/core/reflection/types'; -import {RenderDirectiveMetadata} from 'angular2/src/core/render/api'; import {EventConfig} from 'angular2/src/core/render/event_config'; import {PipeBinding} from '../pipes/pipe_binding'; @@ -128,17 +127,17 @@ export class DirectiveDependency extends Dependency { } export class DirectiveBinding extends ResolvedBinding { - constructor(key: Key, factory: Function, deps: Dependency[], - public metadata: RenderDirectiveMetadata, + public callOnDestroy: boolean; + + constructor(key: Key, factory: Function, deps: Dependency[], public metadata: DirectiveMetadata, public bindings: Array, public viewBindings: Array) { super(key, [new ResolvedFactory(factory, deps)], false); + this.callOnDestroy = hasLifecycleHook(LifecycleHooks.OnDestroy, key.token); } get displayName(): string { return this.key.displayName; } - get callOnDestroy(): boolean { return this.metadata.callOnDestroy; } - get queries(): QueryMetadataWithSetter[] { if (isBlank(this.metadata.queries)) return []; @@ -163,47 +162,11 @@ export class DirectiveBinding extends ResolvedBinding { var rb = resolveBinding(binding); var rf = rb.resolvedFactories[0]; var deps = rf.dependencies.map(DirectiveDependency.createFrom); - var token = binding.token; - var metadata = RenderDirectiveMetadata.create({ - id: stringify(binding.token), - type: meta instanceof ComponentMetadata ? RenderDirectiveMetadata.COMPONENT_TYPE : - RenderDirectiveMetadata.DIRECTIVE_TYPE, - selector: meta.selector, - compileChildren: true, - outputs: meta.outputs, - host: isPresent(meta.host) ? MapWrapper.createFromStringMap(meta.host) : null, - inputs: meta.inputs, - readAttributes: DirectiveBinding._readAttributes(deps), - queries: meta.queries, - - callOnDestroy: hasLifecycleHook(LifecycleHooks.OnDestroy, token), - callOnChanges: hasLifecycleHook(LifecycleHooks.OnChanges, token), - callDoCheck: hasLifecycleHook(LifecycleHooks.DoCheck, token), - callOnInit: hasLifecycleHook(LifecycleHooks.OnInit, token), - callAfterContentInit: hasLifecycleHook(LifecycleHooks.AfterContentInit, token), - callAfterContentChecked: hasLifecycleHook(LifecycleHooks.AfterContentChecked, token), - callAfterViewInit: hasLifecycleHook(LifecycleHooks.AfterViewInit, token), - callAfterViewChecked: hasLifecycleHook(LifecycleHooks.AfterViewChecked, token), - - changeDetection: meta instanceof ComponentMetadata ? meta.changeDetection : null, - - exportAs: meta.exportAs - }); var bindings = isPresent(meta.bindings) ? meta.bindings : []; var viewBindigs = meta instanceof ComponentMetadata && isPresent(meta.viewBindings) ? meta.viewBindings : []; - return new DirectiveBinding(rb.key, rf.factory, deps, metadata, bindings, viewBindigs); - } - - static _readAttributes(deps: DirectiveDependency[]): string[] { - var readAttributes = []; - deps.forEach(dep => { - if (isPresent(dep.attributeName)) { - readAttributes.push(dep.attributeName); - } - }); - return readAttributes; + return new DirectiveBinding(rb.key, rf.factory, deps, meta, bindings, viewBindigs); } static createFromType(type: Type, annotation: DirectiveMetadata): DirectiveBinding { @@ -502,7 +465,7 @@ export class ElementInjector extends TreeNode implements Depend if (dirDep.key.id === StaticKeys.instance().changeDetectorRefId) { // We provide the component's view change detector to components and // the surrounding component's change detector to directives. - if (dirBin.metadata.type === RenderDirectiveMetadata.COMPONENT_TYPE) { + if (dirBin.metadata instanceof ComponentMetadata) { var componentView = this._preBuiltObjects.view.getNestedView( this._preBuiltObjects.elementRef.boundElementIndex); return componentView.changeDetector.ref; diff --git a/modules/angular2/src/core/compiler/element_ref.ts b/modules/angular2/src/core/compiler/element_ref.ts index 43cfd8be3f..8100dbe7cd 100644 --- a/modules/angular2/src/core/compiler/element_ref.ts +++ b/modules/angular2/src/core/compiler/element_ref.ts @@ -29,24 +29,12 @@ export class ElementRef implements RenderElementRef { * This is used internally by the Angular framework to locate elements. */ boundElementIndex: number; - - /** - * @private - * - * TODO(tbosch): remove this when the new compiler lands - * Index of the element inside the `RenderViewRef`. - * - * This is used internally by the Angular framework to locate elements. - */ - renderBoundElementIndex: number; - /** * @private */ constructor(parentView: ViewRef, boundElementIndex: number, private _renderer: Renderer) { this.parentView = parentView; this.boundElementIndex = boundElementIndex; - this.renderBoundElementIndex = boundElementIndex; } /** diff --git a/modules/angular2/src/core/compiler/proto_view_factory.ts b/modules/angular2/src/core/compiler/proto_view_factory.ts index 9435043349..cbb2c55221 100644 --- a/modules/angular2/src/core/compiler/proto_view_factory.ts +++ b/modules/angular2/src/core/compiler/proto_view_factory.ts @@ -1,28 +1,7 @@ -import {ListWrapper, MapWrapper} from 'angular2/src/core/facade/collection'; +import {ListWrapper} from 'angular2/src/core/facade/collection'; import {isPresent, isBlank, Type, isArray, isNumber} from 'angular2/src/core/facade/lang'; -import {reflector} from 'angular2/src/core/reflection/reflection'; -import { - ChangeDetection, - DirectiveIndex, - BindingRecord, - DirectiveRecord, - ProtoChangeDetector, - ChangeDetectionStrategy, - ChangeDetectorDefinition, - ChangeDetectorGenConfig, - ASTWithSource -} from 'angular2/src/core/change_detection/change_detection'; - -import { - RenderDirectiveMetadata, - RenderElementBinder, - PropertyBindingType, - DirectiveBinder, - ProtoViewDto, - ViewType, - RenderProtoViewRef -} from 'angular2/src/core/render/api'; +import {ViewType, RenderProtoViewRef} from 'angular2/src/core/render/api'; import {Injectable, Binding, resolveForwardRef, Inject} from 'angular2/src/core/di'; @@ -344,272 +323,3 @@ function _flattenList(tree: any[], out: Array): void { } } } - - -export class BindingRecordsCreator { - _directiveRecordsMap: Map = new Map(); - - getEventBindingRecords(elementBinders: RenderElementBinder[], - allDirectiveMetadatas: RenderDirectiveMetadata[]): BindingRecord[] { - var res = []; - for (var boundElementIndex = 0; boundElementIndex < elementBinders.length; - boundElementIndex++) { - var renderElementBinder = elementBinders[boundElementIndex]; - - this._createTemplateEventRecords(res, renderElementBinder, boundElementIndex); - this._createHostEventRecords(res, renderElementBinder, allDirectiveMetadatas, - boundElementIndex); - } - return res; - } - - private _createTemplateEventRecords(res: BindingRecord[], - renderElementBinder: RenderElementBinder, - boundElementIndex: number): void { - renderElementBinder.eventBindings.forEach(eb => { - res.push(BindingRecord.createForEvent(eb.source, eb.fullName, boundElementIndex)); - }); - } - - private _createHostEventRecords(res: BindingRecord[], renderElementBinder: RenderElementBinder, - allDirectiveMetadatas: RenderDirectiveMetadata[], - boundElementIndex: number): void { - for (var i = 0; i < renderElementBinder.directives.length; ++i) { - var dir = renderElementBinder.directives[i]; - var directiveMetadata = allDirectiveMetadatas[dir.directiveIndex]; - var dirRecord = this._getDirectiveRecord(boundElementIndex, i, directiveMetadata); - dir.eventBindings.forEach(heb => { - res.push(BindingRecord.createForHostEvent(heb.source, heb.fullName, dirRecord)); - }); - } - } - - getPropertyBindingRecords(textBindings: ASTWithSource[], elementBinders: RenderElementBinder[], - allDirectiveMetadatas: RenderDirectiveMetadata[]): BindingRecord[] { - var bindings = []; - - this._createTextNodeRecords(bindings, textBindings); - for (var boundElementIndex = 0; boundElementIndex < elementBinders.length; - boundElementIndex++) { - var renderElementBinder = elementBinders[boundElementIndex]; - this._createElementPropertyRecords(bindings, boundElementIndex, renderElementBinder); - this._createDirectiveRecords(bindings, boundElementIndex, renderElementBinder.directives, - allDirectiveMetadatas); - } - - return bindings; - } - - getDirectiveRecords(elementBinders: RenderElementBinder[], - allDirectiveMetadatas: RenderDirectiveMetadata[]): DirectiveRecord[] { - var directiveRecords = []; - - for (var elementIndex = 0; elementIndex < elementBinders.length; ++elementIndex) { - var dirs = elementBinders[elementIndex].directives; - for (var dirIndex = 0; dirIndex < dirs.length; ++dirIndex) { - directiveRecords.push(this._getDirectiveRecord( - elementIndex, dirIndex, allDirectiveMetadatas[dirs[dirIndex].directiveIndex])); - } - } - - return directiveRecords; - } - - _createTextNodeRecords(bindings: BindingRecord[], textBindings: ASTWithSource[]) { - for (var i = 0; i < textBindings.length; i++) { - bindings.push(BindingRecord.createForTextNode(textBindings[i], i)); - } - } - - _createElementPropertyRecords(bindings: BindingRecord[], boundElementIndex: number, - renderElementBinder: RenderElementBinder) { - ListWrapper.forEach(renderElementBinder.propertyBindings, (binding) => { - if (binding.type === PropertyBindingType.PROPERTY) { - bindings.push(BindingRecord.createForElementProperty(binding.astWithSource, - boundElementIndex, binding.property)); - } else if (binding.type === PropertyBindingType.ATTRIBUTE) { - bindings.push(BindingRecord.createForElementAttribute(binding.astWithSource, - boundElementIndex, binding.property)); - } else if (binding.type === PropertyBindingType.CLASS) { - bindings.push(BindingRecord.createForElementClass(binding.astWithSource, boundElementIndex, - binding.property)); - } else if (binding.type === PropertyBindingType.STYLE) { - bindings.push(BindingRecord.createForElementStyle(binding.astWithSource, boundElementIndex, - binding.property, binding.unit)); - } - }); - } - - _createDirectiveRecords(bindings: BindingRecord[], boundElementIndex: number, - directiveBinders: DirectiveBinder[], - allDirectiveMetadatas: RenderDirectiveMetadata[]) { - for (var i = 0; i < directiveBinders.length; i++) { - var directiveBinder = directiveBinders[i]; - var directiveMetadata = allDirectiveMetadatas[directiveBinder.directiveIndex]; - var directiveRecord = this._getDirectiveRecord(boundElementIndex, i, directiveMetadata); - - // directive properties - MapWrapper.forEach(directiveBinder.propertyBindings, (astWithSource, propertyName) => { - // TODO: these setters should eventually be created by change detection, to make - // it monomorphic! - var setter = reflector.setter(propertyName); - bindings.push( - BindingRecord.createForDirective(astWithSource, propertyName, setter, directiveRecord)); - }); - - if (directiveRecord.callOnChanges) { - bindings.push(BindingRecord.createDirectiveOnChanges(directiveRecord)); - } - if (directiveRecord.callOnInit) { - bindings.push(BindingRecord.createDirectiveOnInit(directiveRecord)); - } - if (directiveRecord.callDoCheck) { - bindings.push(BindingRecord.createDirectiveDoCheck(directiveRecord)); - } - } - - for (var i = 0; i < directiveBinders.length; i++) { - var directiveBinder = directiveBinders[i]; - // host properties - ListWrapper.forEach(directiveBinder.hostPropertyBindings, (binding) => { - var dirIndex = new DirectiveIndex(boundElementIndex, i); - if (binding.type === PropertyBindingType.PROPERTY) { - bindings.push(BindingRecord.createForHostProperty(dirIndex, binding.astWithSource, - binding.property)); - } else if (binding.type === PropertyBindingType.ATTRIBUTE) { - bindings.push(BindingRecord.createForHostAttribute(dirIndex, binding.astWithSource, - binding.property)); - } else if (binding.type === PropertyBindingType.CLASS) { - bindings.push( - BindingRecord.createForHostClass(dirIndex, binding.astWithSource, binding.property)); - } else if (binding.type === PropertyBindingType.STYLE) { - bindings.push(BindingRecord.createForHostStyle(dirIndex, binding.astWithSource, - binding.property, binding.unit)); - } - }); - } - } - - _getDirectiveRecord(boundElementIndex: number, directiveIndex: number, - directiveMetadata: RenderDirectiveMetadata): DirectiveRecord { - var id = boundElementIndex * 100 + directiveIndex; - - if (!this._directiveRecordsMap.has(id)) { - this._directiveRecordsMap.set( - id, new DirectiveRecord({ - directiveIndex: new DirectiveIndex(boundElementIndex, directiveIndex), - callAfterContentInit: directiveMetadata.callAfterContentInit, - callAfterContentChecked: directiveMetadata.callAfterContentChecked, - callAfterViewInit: directiveMetadata.callAfterViewInit, - callAfterViewChecked: directiveMetadata.callAfterViewChecked, - callOnChanges: directiveMetadata.callOnChanges, - callDoCheck: directiveMetadata.callDoCheck, - callOnInit: directiveMetadata.callOnInit, - changeDetection: directiveMetadata.changeDetection - })); - } - - return this._directiveRecordsMap.get(id); - } -} - -/** - * Returns the data needed to create ChangeDetectors - * for the given ProtoView and all nested ProtoViews. - */ -export function getChangeDetectorDefinitions( - hostComponentMetadata: RenderDirectiveMetadata, rootRenderProtoView: ProtoViewDto, - allRenderDirectiveMetadata: RenderDirectiveMetadata[], genConfig: ChangeDetectorGenConfig): - ChangeDetectorDefinition[] { - var nestedPvsWithIndex = _collectNestedProtoViews(rootRenderProtoView); - var nestedPvVariableNames = _collectNestedProtoViewsVariableNames(nestedPvsWithIndex); - return _getChangeDetectorDefinitions(hostComponentMetadata, nestedPvsWithIndex, - nestedPvVariableNames, allRenderDirectiveMetadata, - genConfig); -} - -function _collectNestedProtoViews( - renderProtoView: ProtoViewDto, parentIndex: number = null, boundElementIndex = null, - result: RenderProtoViewWithIndex[] = null): RenderProtoViewWithIndex[] { - if (isBlank(result)) { - result = []; - } - // reserve the place in the array - result.push( - new RenderProtoViewWithIndex(renderProtoView, result.length, parentIndex, boundElementIndex)); - var currentIndex = result.length - 1; - var childBoundElementIndex = 0; - ListWrapper.forEach(renderProtoView.elementBinders, (elementBinder) => { - if (isPresent(elementBinder.nestedProtoView)) { - _collectNestedProtoViews(elementBinder.nestedProtoView, currentIndex, childBoundElementIndex, - result); - } - childBoundElementIndex++; - }); - return result; -} - -function _getChangeDetectorDefinitions( - hostComponentMetadata: RenderDirectiveMetadata, nestedPvsWithIndex: RenderProtoViewWithIndex[], - nestedPvVariableNames: string[][], allRenderDirectiveMetadata: RenderDirectiveMetadata[], - genConfig: ChangeDetectorGenConfig): ChangeDetectorDefinition[] { - return ListWrapper.map(nestedPvsWithIndex, (pvWithIndex) => { - var elementBinders = pvWithIndex.renderProtoView.elementBinders; - var bindingRecordsCreator = new BindingRecordsCreator(); - var propBindingRecords = bindingRecordsCreator.getPropertyBindingRecords( - pvWithIndex.renderProtoView.textBindings, elementBinders, allRenderDirectiveMetadata); - var eventBindingRecords = - bindingRecordsCreator.getEventBindingRecords(elementBinders, allRenderDirectiveMetadata); - var directiveRecords = - bindingRecordsCreator.getDirectiveRecords(elementBinders, allRenderDirectiveMetadata); - var strategyName = ChangeDetectionStrategy.Default; - if (pvWithIndex.renderProtoView.type === ViewType.COMPONENT) { - strategyName = hostComponentMetadata.changeDetection; - } - var id = _protoViewId(hostComponentMetadata, pvWithIndex); - var variableNames = nestedPvVariableNames[pvWithIndex.index]; - return new ChangeDetectorDefinition(id, strategyName, variableNames, propBindingRecords, - eventBindingRecords, directiveRecords, genConfig); - }); -} - -function _protoViewId(hostComponentMetadata: RenderDirectiveMetadata, - pvWithIndex: RenderProtoViewWithIndex): string { - var typeString; - if (pvWithIndex.renderProtoView.type === ViewType.COMPONENT) { - typeString = 'comp'; - } else if (pvWithIndex.renderProtoView.type === ViewType.HOST) { - typeString = 'host'; - } else { - typeString = 'embedded'; - } - return `${hostComponentMetadata.id}_${typeString}_${pvWithIndex.index}`; -} - -function _collectNestedProtoViewsVariableNames(nestedPvsWithIndex: RenderProtoViewWithIndex[]): - string[][] { - var nestedPvVariableNames = ListWrapper.createFixedSize(nestedPvsWithIndex.length); - ListWrapper.forEach(nestedPvsWithIndex, (pvWithIndex) => { - var parentVariableNames = - isPresent(pvWithIndex.parentIndex) ? nestedPvVariableNames[pvWithIndex.parentIndex] : null; - nestedPvVariableNames[pvWithIndex.index] = - _createVariableNames(parentVariableNames, pvWithIndex.renderProtoView); - }); - return nestedPvVariableNames; -} - -function _createVariableNames(parentVariableNames: string[], renderProtoView): string[] { - var res = isBlank(parentVariableNames) ? [] : ListWrapper.clone(parentVariableNames); - MapWrapper.forEach(renderProtoView.variableBindings, - (mappedName, varName) => { res.push(mappedName); }); - ListWrapper.forEach(renderProtoView.elementBinders, binder => { - MapWrapper.forEach(binder.variableBindings, - (mappedName: string, varName: string) => { res.push(mappedName); }); - }); - return res; -} - -class RenderProtoViewWithIndex { - constructor(public renderProtoView: ProtoViewDto, public index: number, - public parentIndex: number, public boundElementIndex: number) {} -} diff --git a/modules/angular2/src/core/render.ts b/modules/angular2/src/core/render.ts index d9851b909a..0449e46ab7 100644 --- a/modules/angular2/src/core/render.ts +++ b/modules/angular2/src/core/render.ts @@ -1,6 +1,5 @@ // Public API for render export { - RenderDirectiveMetadata, RenderEventDispatcher, Renderer, RenderElementRef, @@ -8,10 +7,8 @@ export { RenderProtoViewRef, RenderFragmentRef, RenderViewWithFragments, - ViewDefinition, DOCUMENT, APP_ID, - MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE, RenderTemplateCmd, RenderCommandVisitor, RenderTextCmd, diff --git a/modules/angular2/src/core/render/api.ts b/modules/angular2/src/core/render/api.ts index 55625da4be..4c1d74cb3b 100644 --- a/modules/angular2/src/core/render/api.ts +++ b/modules/angular2/src/core/render/api.ts @@ -1,103 +1,4 @@ -import {isPresent, isBlank, RegExpWrapper} from 'angular2/src/core/facade/lang'; -import {Promise} from 'angular2/src/core/facade/async'; -import {Map, MapWrapper, StringMap, StringMapWrapper} from 'angular2/src/core/facade/collection'; -import { - ASTWithSource, - ChangeDetectionStrategy -} from 'angular2/src/core/change_detection/change_detection'; - -/** - * General notes: - * - * The methods for creating / destroying views in this API are used in the AppViewHydrator - * and RenderViewHydrator as well. - * - * We are already parsing expressions on the render side: - * - this makes the ElementBinders more compact - * (e.g. no need to distinguish interpolations from regular expressions from literals) - * - allows to retrieve which properties should be accessed from the event - * by looking at the expression - * - we need the parse at least for the `template` attribute to match - * directives in it - * - render compiler is not on the critical path as - * its output will be stored in precompiled templates. - */ - -export class EventBinding { - constructor(public fullName: string, public source: ASTWithSource) {} -} - -export enum PropertyBindingType { - PROPERTY, - ATTRIBUTE, - CLASS, - STYLE -} - -export class ElementPropertyBinding { - constructor(public type: PropertyBindingType, public astWithSource: ASTWithSource, - public property: string, public unit: string = null) {} -} - -export class RenderElementBinder { - index: number; - parentIndex: number; - distanceToParent: number; - directives: DirectiveBinder[]; - nestedProtoView: ProtoViewDto; - propertyBindings: ElementPropertyBinding[]; - variableBindings: Map; - // Note: this contains a preprocessed AST - // that replaced the values that should be extracted from the element - // with a local name - eventBindings: EventBinding[]; - readAttributes: Map; - - constructor({index, parentIndex, distanceToParent, directives, nestedProtoView, propertyBindings, - variableBindings, eventBindings, readAttributes}: { - index?: number, - parentIndex?: number, - distanceToParent?: number, - directives?: DirectiveBinder[], - nestedProtoView?: ProtoViewDto, - propertyBindings?: ElementPropertyBinding[], - variableBindings?: Map, - eventBindings?: EventBinding[], - readAttributes?: Map - } = {}) { - this.index = index; - this.parentIndex = parentIndex; - this.distanceToParent = distanceToParent; - this.directives = directives; - this.nestedProtoView = nestedProtoView; - this.propertyBindings = propertyBindings; - this.variableBindings = variableBindings; - this.eventBindings = eventBindings; - this.readAttributes = readAttributes; - } -} - -export class DirectiveBinder { - // Index into the array of directives in the View instance - directiveIndex: number; - propertyBindings: Map; - // Note: this contains a preprocessed AST - // that replaced the values that should be extracted from the element - // with a local name - eventBindings: EventBinding[]; - hostPropertyBindings: ElementPropertyBinding[]; - constructor({directiveIndex, propertyBindings, eventBindings, hostPropertyBindings}: { - directiveIndex?: number, - propertyBindings?: Map, - eventBindings?: EventBinding[], - hostPropertyBindings?: ElementPropertyBinding[] - }) { - this.directiveIndex = directiveIndex; - this.propertyBindings = propertyBindings; - this.eventBindings = eventBindings; - this.hostPropertyBindings = hostPropertyBindings; - } -} +import {Map} from 'angular2/src/core/facade/collection'; export enum ViewType { // A view that contains the host element with bound component directive. @@ -111,176 +12,6 @@ export enum ViewType { EMBEDDED } -export class ProtoViewDto { - render: RenderProtoViewRef; - elementBinders: RenderElementBinder[]; - variableBindings: Map; - type: ViewType; - textBindings: ASTWithSource[]; - transitiveNgContentCount: number; - - constructor({render, elementBinders, variableBindings, type, textBindings, - transitiveNgContentCount}: { - render?: RenderProtoViewRef, - elementBinders?: RenderElementBinder[], - variableBindings?: Map, - type?: ViewType, - textBindings?: ASTWithSource[], - transitiveNgContentCount?: number - }) { - this.render = render; - this.elementBinders = elementBinders; - this.variableBindings = variableBindings; - this.type = type; - this.textBindings = textBindings; - this.transitiveNgContentCount = transitiveNgContentCount; - } -} - -export class RenderDirectiveMetadata { - static get DIRECTIVE_TYPE() { return 0; } - static get COMPONENT_TYPE() { return 1; } - id: any; - selector: string; - compileChildren: boolean; - outputs: string[]; - inputs: string[]; - readAttributes: string[]; - type: number; - callOnDestroy: boolean; - callOnChanges: boolean; - callDoCheck: boolean; - callOnInit: boolean; - callAfterContentInit: boolean; - callAfterContentChecked: boolean; - callAfterViewInit: boolean; - callAfterViewChecked: boolean; - changeDetection: ChangeDetectionStrategy; - exportAs: string; - hostListeners: Map; - hostProperties: Map; - hostAttributes: Map; - queries: StringMap; - // group 1: "property" from "[property]" - // group 2: "event" from "(event)" - private static _hostRegExp = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))$/g; - - constructor({id, selector, compileChildren, outputs, hostListeners, hostProperties, - hostAttributes, inputs, readAttributes, type, callOnDestroy, callOnChanges, - callDoCheck, callOnInit, callAfterContentInit, callAfterContentChecked, - callAfterViewInit, callAfterViewChecked, changeDetection, exportAs, queries}: { - id?: string, - selector?: string, - compileChildren?: boolean, - outputs?: string[], - hostListeners?: Map, - hostProperties?: Map, - hostAttributes?: Map, - inputs?: string[], - readAttributes?: string[], - type?: number, - callOnDestroy?: boolean, - callOnChanges?: boolean, - callDoCheck?: boolean, - callOnInit?: boolean, - callAfterContentInit?: boolean, - callAfterContentChecked?: boolean, - callAfterViewInit?: boolean, - callAfterViewChecked?: boolean, - changeDetection?: ChangeDetectionStrategy, - exportAs?: string, - queries?: StringMap - }) { - this.id = id; - this.selector = selector; - this.compileChildren = isPresent(compileChildren) ? compileChildren : true; - this.outputs = outputs; - this.hostListeners = hostListeners; - this.hostAttributes = hostAttributes; - this.hostProperties = hostProperties; - this.inputs = inputs; - this.readAttributes = readAttributes; - this.type = type; - this.callOnDestroy = callOnDestroy; - this.callOnChanges = callOnChanges; - this.callDoCheck = callDoCheck; - this.callOnInit = callOnInit; - this.callAfterContentInit = callAfterContentInit; - this.callAfterContentChecked = callAfterContentChecked; - this.callAfterViewInit = callAfterViewInit; - this.callAfterViewChecked = callAfterViewChecked; - this.changeDetection = changeDetection; - this.exportAs = exportAs; - this.queries = queries; - } - - static create({id, selector, compileChildren, outputs, host, inputs, readAttributes, type, - callOnDestroy, callOnChanges, callDoCheck, callOnInit, callAfterContentInit, - callAfterContentChecked, callAfterViewInit, callAfterViewChecked, changeDetection, - exportAs, queries}: { - id?: string, - selector?: string, - compileChildren?: boolean, - outputs?: string[], - host?: Map, - inputs?: string[], - readAttributes?: string[], - type?: number, - callOnDestroy?: boolean, - callOnChanges?: boolean, - callDoCheck?: boolean, - callOnInit?: boolean, - callAfterContentInit?: boolean, - callAfterContentChecked?: boolean, - callAfterViewInit?: boolean, - callAfterViewChecked?: boolean, - changeDetection?: ChangeDetectionStrategy, - exportAs?: string, - queries?: StringMap - }): RenderDirectiveMetadata { - let hostListeners = new Map(); - let hostProperties = new Map(); - let hostAttributes = new Map(); - - if (isPresent(host)) { - MapWrapper.forEach(host, (value: string, key: string) => { - var matches = RegExpWrapper.firstMatch(RenderDirectiveMetadata._hostRegExp, key); - if (isBlank(matches)) { - hostAttributes.set(key, value); - } else if (isPresent(matches[1])) { - hostProperties.set(matches[1], value); - } else if (isPresent(matches[2])) { - hostListeners.set(matches[2], value); - } - }); - } - - return new RenderDirectiveMetadata({ - id: id, - selector: selector, - compileChildren: compileChildren, - outputs: outputs, - hostListeners: hostListeners, - hostProperties: hostProperties, - hostAttributes: hostAttributes, - inputs: inputs, - readAttributes: readAttributes, - type: type, - callOnDestroy: callOnDestroy, - callOnChanges: callOnChanges, - callDoCheck: callDoCheck, - callOnInit: callOnInit, - callAfterContentInit: callAfterContentInit, - callAfterContentChecked: callAfterContentChecked, - callAfterViewInit: callAfterViewInit, - callAfterViewChecked: callAfterViewChecked, - changeDetection: changeDetection, - exportAs: exportAs, - queries: queries - }); - } -} - // An opaque reference to a render proto view export class RenderProtoViewRef {} @@ -312,86 +43,6 @@ export enum ViewEncapsulation { export var VIEW_ENCAPSULATION_VALUES = [ViewEncapsulation.Emulated, ViewEncapsulation.Native, ViewEncapsulation.None]; -export class ViewDefinition { - componentId: string; - templateAbsUrl: string; - template: string; - directives: RenderDirectiveMetadata[]; - styleAbsUrls: string[]; - styles: string[]; - encapsulation: ViewEncapsulation; - - constructor({componentId, templateAbsUrl, template, styleAbsUrls, styles, directives, - encapsulation}: { - componentId?: string, - templateAbsUrl?: string, - template?: string, - styleAbsUrls?: string[], - styles?: string[], - directives?: RenderDirectiveMetadata[], - encapsulation?: ViewEncapsulation - } = {}) { - this.componentId = componentId; - this.templateAbsUrl = templateAbsUrl; - this.template = template; - this.styleAbsUrls = styleAbsUrls; - this.styles = styles; - this.directives = directives; - this.encapsulation = isPresent(encapsulation) ? encapsulation : ViewEncapsulation.Emulated; - } -} - -export class RenderProtoViewMergeMapping { - constructor(public mergedProtoViewRef: RenderProtoViewRef, - // Number of fragments in the merged ProtoView. - // Fragments are stored in depth first order of nested ProtoViews. - public fragmentCount: number, - // Mapping from app element index to render element index. - // Mappings of nested ProtoViews are in depth first order, with all - // indices for one ProtoView in a consecutive block. - public mappedElementIndices: number[], - // Number of bound render element. - // Note: This could be more than the original ones - // as we might have bound a new element for projecting bound text nodes. - public mappedElementCount: number, - // Mapping from app text index to render text index. - // Mappings of nested ProtoViews are in depth first order, with all - // indices for one ProtoView in a consecutive block. - public mappedTextIndices: number[], - // Mapping from view index to app element index - public hostElementIndicesByViewIndex: number[], - // Number of contained views by view index - public nestedViewCountByViewIndex: number[]) {} -} - -export class RenderCompiler { - /** - * Creates a ProtoViewDto that contains a single nested component with the given componentId. - */ - compileHost(directiveMetadata: RenderDirectiveMetadata): Promise { return null; } - - /** - * Compiles a single DomProtoView. Non recursive so that - * we don't need to serialize all possible components over the wire, - * but only the needed ones based on previous calls. - */ - compile(view: ViewDefinition): Promise { return null; } - - /** - * Merges ProtoViews. - * The first entry of the array is the protoview into which all the other entries of the array - * should be merged. - * If the array contains other arrays, they will be merged before processing the parent array. - * The array must contain an entry for every component and embedded ProtoView of the first entry. - * @param protoViewRefs Array of ProtoViewRefs or nested - * @return the merge result - */ - mergeProtoViewsRecursively( - protoViewRefs: Array): Promise { - return null; - } -} - export interface RenderTemplateCmd { visit(visitor: RenderCommandVisitor, context: any): any; } export interface RenderBeginCmd extends RenderTemplateCmd { @@ -449,7 +100,7 @@ export interface RenderElementRef { * * This is used internally by the Angular framework to locate elements. */ - renderBoundElementIndex: number; + boundElementIndex: number; } export class Renderer { diff --git a/modules/angular2/src/core/render/dom/compiler/compile_control.ts b/modules/angular2/src/core/render/dom/compiler/compile_control.ts deleted file mode 100644 index bd64e58263..0000000000 --- a/modules/angular2/src/core/render/dom/compiler/compile_control.ts +++ /dev/null @@ -1,66 +0,0 @@ -import {isBlank} from 'angular2/src/core/facade/lang'; -import {CompileElement} from './compile_element'; -import {CompileStep} from './compile_step'; - -/** - * Controls the processing order of elements. - * Right now it only allows to add a parent element. - */ -export class CompileControl { - _currentStepIndex: number = 0; - _parent: CompileElement = null; - _results: any[] = null; - _additionalChildren: CompileElement[] = null; - _ignoreCurrentElement: boolean; - - constructor(public _steps: CompileStep[]) {} - - // only public so that it can be used by compile_pipeline - internalProcess(results: any[], startStepIndex: number, parent: CompileElement, - current: CompileElement): CompileElement[] { - this._results = results; - var previousStepIndex = this._currentStepIndex; - var previousParent = this._parent; - - this._ignoreCurrentElement = false; - - for (var i = startStepIndex; i < this._steps.length && !this._ignoreCurrentElement; i++) { - var step = this._steps[i]; - this._parent = parent; - this._currentStepIndex = i; - step.processElement(parent, current, this); - parent = this._parent; - } - - if (!this._ignoreCurrentElement) { - results.push(current); - } - - this._currentStepIndex = previousStepIndex; - this._parent = previousParent; - - var localAdditionalChildren = this._additionalChildren; - this._additionalChildren = null; - return localAdditionalChildren; - } - - addParent(newElement: CompileElement) { - this.internalProcess(this._results, this._currentStepIndex + 1, this._parent, newElement); - this._parent = newElement; - } - - addChild(element: CompileElement) { - if (isBlank(this._additionalChildren)) { - this._additionalChildren = []; - } - this._additionalChildren.push(element); - } - - /** - * Ignores the current element. - * - * When a step calls `ignoreCurrentElement`, no further steps are executed on the current - * element and no `CompileElement` is added to the result list. - */ - ignoreCurrentElement() { this._ignoreCurrentElement = true; } -} diff --git a/modules/angular2/src/core/render/dom/compiler/compile_element.ts b/modules/angular2/src/core/render/dom/compiler/compile_element.ts deleted file mode 100644 index a1acc44d94..0000000000 --- a/modules/angular2/src/core/render/dom/compiler/compile_element.ts +++ /dev/null @@ -1,109 +0,0 @@ -import {Map, ListWrapper, MapWrapper} from 'angular2/src/core/facade/collection'; -import {DOM} from 'angular2/src/core/dom/dom_adapter'; -import { - isBlank, - isPresent, - Type, - StringJoiner, - assertionsEnabled -} from 'angular2/src/core/facade/lang'; - -import {ProtoViewBuilder, ElementBinderBuilder} from '../view/proto_view_builder'; - -/** - * Collects all data that is needed to process an element - * in the compile process. Fields are filled - * by the CompileSteps starting out with the pure HTMLElement. - */ -export class CompileElement { - _attrs: Map = null; - _classList: string[] = null; - isViewRoot: boolean = false; - // inherited down to children if they don't have an own protoView - inheritedProtoView: ProtoViewBuilder = null; - distanceToInheritedBinder: number = 0; - // inherited down to children if they don't have an own elementBinder - inheritedElementBinder: ElementBinderBuilder = null; - compileChildren: boolean = true; - elementDescription: string; // e.g. '
' : used to provide context in case of - // error - - constructor(public element, compilationUnit: string = '') { - // description is calculated here as compilation steps may change the element - var tplDesc = assertionsEnabled() ? getElementDescription(element) : null; - if (compilationUnit !== '') { - this.elementDescription = compilationUnit; - if (isPresent(tplDesc)) this.elementDescription += ": " + tplDesc; - } else { - this.elementDescription = tplDesc; - } - } - - isBound(): boolean { - return isPresent(this.inheritedElementBinder) && this.distanceToInheritedBinder === 0; - } - - bindElement(): ElementBinderBuilder { - if (!this.isBound()) { - var parentBinder = this.inheritedElementBinder; - this.inheritedElementBinder = - this.inheritedProtoView.bindElement(this.element, this.elementDescription); - if (isPresent(parentBinder)) { - this.inheritedElementBinder.setParent(parentBinder, this.distanceToInheritedBinder); - } - this.distanceToInheritedBinder = 0; - } - return this.inheritedElementBinder; - } - - attrs(): Map { - if (isBlank(this._attrs)) { - this._attrs = DOM.attributeMap(this.element); - } - return this._attrs; - } - - classList(): string[] { - if (isBlank(this._classList)) { - this._classList = []; - var elClassList = DOM.classList(this.element); - for (var i = 0; i < elClassList.length; i++) { - this._classList.push(elClassList[i]); - } - } - return this._classList; - } -} - -// return an HTML representation of an element start tag - without its content -// this is used to give contextual information in case of errors -function getElementDescription(domElement): string { - var buf = new StringJoiner(); - var atts = DOM.attributeMap(domElement); - - buf.add("<"); - buf.add(DOM.tagName(domElement).toLowerCase()); - - // show id and class first to ease element identification - addDescriptionAttribute(buf, "id", atts.get("id")); - addDescriptionAttribute(buf, "class", atts.get("class")); - MapWrapper.forEach(atts, (attValue, attName) => { - if (attName !== "id" && attName !== "class") { - addDescriptionAttribute(buf, attName, attValue); - } - }); - - buf.add(">"); - return buf.toString(); -} - - -function addDescriptionAttribute(buffer: StringJoiner, attName: string, attValue) { - if (isPresent(attValue)) { - if (attValue.length === 0) { - buffer.add(' ' + attName); - } else { - buffer.add(' ' + attName + '="' + attValue + '"'); - } - } -} diff --git a/modules/angular2/src/core/render/dom/compiler/compile_pipeline.ts b/modules/angular2/src/core/render/dom/compiler/compile_pipeline.ts deleted file mode 100644 index 4a70f0659c..0000000000 --- a/modules/angular2/src/core/render/dom/compiler/compile_pipeline.ts +++ /dev/null @@ -1,63 +0,0 @@ -import {isPresent, isBlank} from 'angular2/src/core/facade/lang'; -import {DOM} from 'angular2/src/core/dom/dom_adapter'; -import {CompileElement} from './compile_element'; -import {CompileControl} from './compile_control'; -import {CompileStep} from './compile_step'; -import {ProtoViewBuilder} from '../view/proto_view_builder'; -import {ProtoViewDto, ViewType, ViewDefinition} from '../../api'; - -/** - * CompilePipeline for executing CompileSteps recursively for - * all elements in a template. - */ -export class CompilePipeline { - _control: CompileControl; - constructor(public steps: CompileStep[]) { this._control = new CompileControl(steps); } - - processStyles(styles: string[]): string[] { - return styles.map(style => { - this.steps.forEach(step => { style = step.processStyle(style); }); - return style; - }); - } - - processElements(rootElement: Element, protoViewType: ViewType, - viewDef: ViewDefinition): CompileElement[] { - var results: CompileElement[] = []; - var compilationCtxtDescription = viewDef.componentId; - var rootCompileElement = new CompileElement(rootElement, compilationCtxtDescription); - rootCompileElement.inheritedProtoView = - new ProtoViewBuilder(rootElement, protoViewType, viewDef.encapsulation); - rootCompileElement.isViewRoot = true; - this._processElement(results, null, rootCompileElement, compilationCtxtDescription); - return results; - } - - _processElement(results: CompileElement[], parent: CompileElement, current: CompileElement, - compilationCtxtDescription: string = '') { - var additionalChildren = this._control.internalProcess(results, 0, parent, current); - - if (current.compileChildren) { - var node = DOM.firstChild(DOM.templateAwareRoot(current.element)); - while (isPresent(node)) { - // compilation can potentially move the node, so we need to store the - // next sibling before recursing. - var nextNode = DOM.nextSibling(node); - if (DOM.isElementNode(node)) { - var childCompileElement = new CompileElement(node, compilationCtxtDescription); - childCompileElement.inheritedProtoView = current.inheritedProtoView; - childCompileElement.inheritedElementBinder = current.inheritedElementBinder; - childCompileElement.distanceToInheritedBinder = current.distanceToInheritedBinder + 1; - this._processElement(results, current, childCompileElement); - } - node = nextNode; - } - } - - if (isPresent(additionalChildren)) { - for (var i = 0; i < additionalChildren.length; i++) { - this._processElement(results, current, additionalChildren[i]); - } - } - } -} diff --git a/modules/angular2/src/core/render/dom/compiler/compile_step.ts b/modules/angular2/src/core/render/dom/compiler/compile_step.ts deleted file mode 100644 index cfe1b94b70..0000000000 --- a/modules/angular2/src/core/render/dom/compiler/compile_step.ts +++ /dev/null @@ -1,13 +0,0 @@ -import {CompileElement} from './compile_element'; -import * as compileControlModule from './compile_control'; - -/** - * One part of the compile process. - * Is guaranteed to be called in depth first order - */ -export interface CompileStep { - processElement(parent: CompileElement, current: CompileElement, - control: compileControlModule.CompileControl): void; - - processStyle(style: string): string; -} diff --git a/modules/angular2/src/core/render/dom/compiler/compile_step_factory.ts b/modules/angular2/src/core/render/dom/compiler/compile_step_factory.ts deleted file mode 100644 index fc7df50506..0000000000 --- a/modules/angular2/src/core/render/dom/compiler/compile_step_factory.ts +++ /dev/null @@ -1,27 +0,0 @@ -import {Parser} from 'angular2/src/core/change_detection/change_detection'; -import {ViewDefinition} from '../../api'; -import {CompileStep} from './compile_step'; -import {PropertyBindingParser} from './property_binding_parser'; -import {TextInterpolationParser} from './text_interpolation_parser'; -import {DirectiveParser} from './directive_parser'; -import {ViewSplitter} from './view_splitter'; -import {StyleEncapsulator} from './style_encapsulator'; - -export class CompileStepFactory { - createSteps(view: ViewDefinition): CompileStep[] { return null; } -} - -export class DefaultStepFactory extends CompileStepFactory { - private _componentUIDsCache = new Map(); - constructor(private _parser: Parser, private _appId: string) { super(); } - - createSteps(view: ViewDefinition): CompileStep[] { - return [ - new ViewSplitter(this._parser), - new PropertyBindingParser(this._parser), - new DirectiveParser(this._parser, view.directives), - new TextInterpolationParser(this._parser), - new StyleEncapsulator(this._appId, view, this._componentUIDsCache) - ]; - } -} diff --git a/modules/angular2/src/core/render/dom/compiler/compiler.ts b/modules/angular2/src/core/render/dom/compiler/compiler.ts deleted file mode 100644 index a68555689a..0000000000 --- a/modules/angular2/src/core/render/dom/compiler/compiler.ts +++ /dev/null @@ -1,133 +0,0 @@ -import {Injectable, Inject} from 'angular2/src/core/di'; - -import {PromiseWrapper, Promise} from 'angular2/src/core/facade/async'; -import {isPresent, isBlank} from 'angular2/src/core/facade/lang'; -import {DOM} from 'angular2/src/core/dom/dom_adapter'; - -import { - ViewDefinition, - ProtoViewDto, - ViewType, - RenderDirectiveMetadata, - RenderCompiler, - RenderProtoViewRef, - RenderProtoViewMergeMapping, - ViewEncapsulation -} from '../../api'; -import {CompilePipeline} from './compile_pipeline'; -import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions'; -import {ViewLoader, TemplateAndStyles} from 'angular2/src/core/render/dom/compiler/view_loader'; -import {CompileStepFactory, DefaultStepFactory} from './compile_step_factory'; -import {ElementSchemaRegistry} from '../schema/element_schema_registry'; -import {Parser} from 'angular2/src/core/change_detection/change_detection'; -import * as pvm from '../view/proto_view_merger'; -import {CssSelector} from './selector'; -import {DOCUMENT, APP_ID} from '../dom_tokens'; -import {SharedStylesHost} from '../view/shared_styles_host'; -import {prependAll} from '../util'; -import {TemplateCloner} from '../template_cloner'; - -/** - * The compiler loads and translates the html templates of components into - * nested ProtoViews. To decompose its functionality it uses - * the CompilePipeline and the CompileSteps. - */ -export class DomCompiler extends RenderCompiler { - constructor(private _schemaRegistry: ElementSchemaRegistry, - private _templateCloner: TemplateCloner, private _stepFactory: CompileStepFactory, - private _viewLoader: ViewLoader, private _sharedStylesHost: SharedStylesHost) { - super(); - } - - compile(view: ViewDefinition): Promise { - var tplPromise = this._viewLoader.load(view); - return PromiseWrapper.then( - tplPromise, (tplAndStyles: TemplateAndStyles) => - this._compileView(view, tplAndStyles, ViewType.COMPONENT), - (e) => { - throw new BaseException(`Failed to load the template for "${view.componentId}" : ${e}`); - return null; - }); - } - - compileHost(directiveMetadata: RenderDirectiveMetadata): Promise { - let hostViewDef = new ViewDefinition({ - componentId: directiveMetadata.id, - templateAbsUrl: null, template: null, - styles: null, - styleAbsUrls: null, - directives: [directiveMetadata], - encapsulation: ViewEncapsulation.None - }); - - let selector = CssSelector.parse(directiveMetadata.selector)[0]; - let hostTemplate = selector.getMatchingElementTemplate(); - let templateAndStyles = new TemplateAndStyles(hostTemplate, []); - - return this._compileView(hostViewDef, templateAndStyles, ViewType.HOST); - } - - mergeProtoViewsRecursively( - protoViewRefs: Array): Promise { - return PromiseWrapper.resolve( - pvm.mergeProtoViewsRecursively(this._templateCloner, protoViewRefs)); - } - - _compileView(viewDef: ViewDefinition, templateAndStyles: TemplateAndStyles, - protoViewType: ViewType): Promise { - if (viewDef.encapsulation === ViewEncapsulation.Emulated && - templateAndStyles.styles.length === 0) { - viewDef = this._normalizeViewEncapsulationIfThereAreNoStyles(viewDef); - } - var pipeline = new CompilePipeline(this._stepFactory.createSteps(viewDef)); - - var compiledStyles = pipeline.processStyles(templateAndStyles.styles); - var compileElements = pipeline.processElements( - this._createTemplateElm(templateAndStyles.template), protoViewType, viewDef); - if (viewDef.encapsulation === ViewEncapsulation.Native) { - prependAll(DOM.content(compileElements[0].element), - compiledStyles.map(style => DOM.createStyleElement(style))); - } else { - this._sharedStylesHost.addStyles(compiledStyles); - } - - return PromiseWrapper.resolve( - compileElements[0].inheritedProtoView.build(this._schemaRegistry, this._templateCloner)); - } - - _createTemplateElm(template: string) { - var templateElm = DOM.createTemplate(template); - var scriptTags = DOM.querySelectorAll(DOM.templateAwareRoot(templateElm), 'script'); - - for (var i = 0; i < scriptTags.length; i++) { - DOM.remove(scriptTags[i]); - } - - return templateElm; - } - - _normalizeViewEncapsulationIfThereAreNoStyles(viewDef: ViewDefinition): ViewDefinition { - if (viewDef.encapsulation === ViewEncapsulation.Emulated) { - return new ViewDefinition({ - componentId: viewDef.componentId, - templateAbsUrl: viewDef.templateAbsUrl, template: viewDef.template, - styleAbsUrls: viewDef.styleAbsUrls, - styles: viewDef.styles, - directives: viewDef.directives, - encapsulation: ViewEncapsulation.None - }); - } else { - return viewDef; - } - } -} - -@Injectable() -export class DefaultDomCompiler extends DomCompiler { - constructor(schemaRegistry: ElementSchemaRegistry, templateCloner: TemplateCloner, parser: Parser, - viewLoader: ViewLoader, sharedStylesHost: SharedStylesHost, - @Inject(APP_ID) appId: any) { - super(schemaRegistry, templateCloner, new DefaultStepFactory(parser, appId), viewLoader, - sharedStylesHost); - } -} diff --git a/modules/angular2/src/core/render/dom/compiler/directive_parser.ts b/modules/angular2/src/core/render/dom/compiler/directive_parser.ts deleted file mode 100644 index 4a410f5dcc..0000000000 --- a/modules/angular2/src/core/render/dom/compiler/directive_parser.ts +++ /dev/null @@ -1,174 +0,0 @@ -import {isPresent, isBlank, StringWrapper} from 'angular2/src/core/facade/lang'; -import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions'; -import {MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection'; -import {DOM} from 'angular2/src/core/dom/dom_adapter'; -import {Parser} from 'angular2/src/core/change_detection/change_detection'; - -import {SelectorMatcher, CssSelector} from 'angular2/src/core/render/dom/compiler/selector'; - -import {CompileStep} from './compile_step'; -import {CompileElement} from './compile_element'; -import {CompileControl} from './compile_control'; - -import {RenderDirectiveMetadata} from '../../api'; -import {dashCaseToCamelCase, camelCaseToDashCase} from '../util'; -import {EventConfig} from '../../event_config'; -import {DirectiveBuilder, ElementBinderBuilder} from '../view/proto_view_builder'; - -/** - * Parses the directives on a single element. Assumes ViewSplitter has already created - *