refactor(compiler): remove `AppElement.initComponent`

This commit is contained in:
Tobias Bosch 2016-11-01 08:21:39 -07:00 committed by vikerman
parent 953cb50fa5
commit 13533d2a30
14 changed files with 80 additions and 53 deletions

View File

@ -6,10 +6,10 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ANALYZE_FOR_ENTRY_COMPONENTS, AnimationTransitionEvent, ChangeDetectionStrategy, ChangeDetectorRef, ComponentFactory, ComponentFactoryResolver, ElementRef, Injector, LOCALE_ID, NgModuleFactory, QueryList, RenderComponentType, Renderer, SecurityContext, SimpleChange, TRANSLATIONS_FORMAT, TemplateRef, ViewContainerRef, ViewEncapsulation} from '@angular/core';
import {ANALYZE_FOR_ENTRY_COMPONENTS, AnimationTransitionEvent, ChangeDetectionStrategy, ChangeDetectorRef, ComponentFactory, ComponentFactoryResolver, ComponentRef, ElementRef, Injector, LOCALE_ID, NgModuleFactory, QueryList, RenderComponentType, Renderer, SecurityContext, SimpleChange, TRANSLATIONS_FORMAT, TemplateRef, ViewContainerRef, ViewEncapsulation} from '@angular/core';
import {CompileIdentifierMetadata, CompileTokenMetadata} from './compile_metadata';
import {AnimationGroupPlayer, AnimationKeyframe, AnimationSequencePlayer, AnimationStyles, AnimationTransition, AppElement, AppView, ChangeDetectorStatus, CodegenComponentFactoryResolver, DebugAppView, DebugContext, NgModuleInjector, NoOpAnimationPlayer, StaticNodeDebugInfo, TemplateRef_, UNINITIALIZED, ValueUnwrapper, ViewType, balanceAnimationKeyframes, clearStyles, collectAndResolveStyles, devModeEqual, prepareFinalAnimationStyles, reflector, registerModuleFactory, renderStyles, view_utils} from './private_import_core';
import {AnimationGroupPlayer, AnimationKeyframe, AnimationSequencePlayer, AnimationStyles, AnimationTransition, AppElement, AppView, ChangeDetectorStatus, CodegenComponentFactoryResolver, ComponentRef_, DebugAppView, DebugContext, NgModuleInjector, NoOpAnimationPlayer, StaticNodeDebugInfo, TemplateRef_, UNINITIALIZED, ValueUnwrapper, ViewType, balanceAnimationKeyframes, clearStyles, collectAndResolveStyles, devModeEqual, prepareFinalAnimationStyles, reflector, registerModuleFactory, renderStyles, view_utils} from './private_import_core';
var APP_VIEW_MODULE_URL = assetUrl('core', 'linker/view');
var VIEW_UTILS_MODULE_URL = assetUrl('core', 'linker/view_utils');
@ -96,6 +96,16 @@ export class Identifiers {
runtime: ComponentFactory,
moduleUrl: assetUrl('core', 'linker/component_factory')
};
static ComponentRef_: IdentifierSpec = {
name: 'ComponentRef_',
runtime: ComponentRef_,
moduleUrl: assetUrl('core', 'linker/component_factory')
};
static ComponentRef: IdentifierSpec = {
name: 'ComponentRef',
runtime: ComponentRef,
moduleUrl: assetUrl('core', 'linker/component_factory')
};
static NgModuleFactory: IdentifierSpec = {
name: 'NgModuleFactory',
runtime: NgModuleFactory,

View File

@ -21,6 +21,7 @@ export type AppElement = typeof r._AppElement;
export const AppElement: typeof r.AppElement = r.AppElement;
export const CodegenComponentFactoryResolver: typeof r.CodegenComponentFactoryResolver =
r.CodegenComponentFactoryResolver;
export const ComponentRef_: typeof r.ComponentRef_ = r.ComponentRef_;
export const AppView: typeof r.AppView = r.AppView;
export const DebugAppView: typeof r.DebugAppView = r.DebugAppView;
export const NgModuleInjector: typeof r.NgModuleInjector = r.NgModuleInjector;

View File

@ -39,7 +39,7 @@ export class CompileElement extends CompileNode {
return new CompileElement(null, null, null, null, null, null, [], [], false, false, [], []);
}
private _compViewExpr: o.Expression = null;
public compViewExpr: o.Expression = null;
public appElement: o.ReadPropExpr;
public elementRef: o.Expression;
public injector: o.Expression;
@ -131,7 +131,7 @@ export class CompileElement extends CompileNode {
}
setComponentView(compViewExpr: o.Expression) {
this._compViewExpr = compViewExpr;
this.compViewExpr = compViewExpr;
this.contentNodesByNgContentIndex =
new Array(this.component.template.ngContentSelectors.length);
for (var i = 0; i < this.contentNodesByNgContentIndex.length; i++) {
@ -254,12 +254,6 @@ export class CompileElement extends CompileNode {
queryWithRead.query.addValue(value, this.view);
}
});
if (isPresent(this.component)) {
var compExpr = isPresent(this.getComponent()) ? this.getComponent() : o.NULL_EXPR;
this.view.createMethod.addStmt(
this.appElement.callMethod('initComponent', [compExpr, this._compViewExpr]).toStmt());
}
}
afterChildren(childNodeCount: number) {
@ -340,7 +334,7 @@ export class CompileElement extends CompileNode {
if (dep.token.reference ===
resolveIdentifierToken(Identifiers.ChangeDetectorRef).reference) {
if (requestingProviderType === ProviderAstType.Component) {
return this._compViewExpr.prop('ref');
return this.compViewExpr.prop('ref');
} else {
return getPropertyInView(o.THIS_EXPR.prop('ref'), this.view, this.view.componentView);
}

View File

@ -83,8 +83,7 @@ function generateHandleEventMethod(
const hasComponentHostListener =
directives.some((dirAst) => dirAst.hostEvents.some((event) => dirAst.directive.isComponent));
const markPathToRootStart =
hasComponentHostListener ? compileElement.appElement.prop('componentView') : o.THIS_EXPR;
const markPathToRootStart = hasComponentHostListener ? compileElement.compViewExpr : o.THIS_EXPR;
const handleEventStmts = new CompileMethod(compileElement.view);
handleEventStmts.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
handleEventStmts.push(markPathToRootStart.callMethod('markPathToRootAsCheckOnce', []).toStmt());

View File

@ -61,7 +61,7 @@ export function bindDirectiveWrapperLifecycleCallbacks(
DirectiveWrapperExpressions.ngOnDestroy(dir.directive, directiveWrapperIntance));
compileElement.view.detachMethod.addStmts(DirectiveWrapperExpressions.ngOnDetach(
dir.hostProperties, directiveWrapperIntance, o.THIS_EXPR,
compileElement.component ? compileElement.appElement.prop('componentView') : o.THIS_EXPR,
compileElement.compViewExpr ? compileElement.compViewExpr : o.THIS_EXPR,
compileElement.renderNode));
}

View File

@ -110,7 +110,7 @@ export function bindDirectiveHostProps(
compileElement.view.detectChangesRenderPropertiesMethod.addStmts(
DirectiveWrapperExpressions.checkHost(
directiveAst.hostProperties, directiveWrapperInstance, o.THIS_EXPR,
compileElement.component ? compileElement.appElement.prop('componentView') : o.THIS_EXPR,
compileElement.compViewExpr ? compileElement.compViewExpr : o.THIS_EXPR,
compileElement.renderNode, DetectChangesVars.throwOnChange, runtimeSecurityCtxExprs));
}
@ -147,9 +147,9 @@ export function bindDirectiveInputs(
directiveWrapperInstance, o.THIS_EXPR, compileElement.renderNode,
DetectChangesVars.throwOnChange);
const directiveDetectChangesStmt = isOnPushComp ?
new o.IfStmt(directiveDetectChangesExpr, [compileElement.appElement.prop('componentView')
.callMethod('markAsCheckOnce', [])
.toStmt()]) :
new o.IfStmt(
directiveDetectChangesExpr,
[compileElement.compViewExpr.callMethod('markAsCheckOnce', []).toStmt()]) :
directiveDetectChangesExpr.toStmt();
detectChangesInInputsMethod.addStmt(directiveDetectChangesStmt);
}

View File

@ -457,7 +457,7 @@ function createViewClass(
var viewMethods = [
new o.ClassMethod(
'createInternal', [new o.FnParam(rootSelectorVar.name, o.STRING_TYPE)],
generateCreateMethod(view), o.importType(resolveIdentifier(Identifiers.AppElement))),
generateCreateMethod(view), o.importType(resolveIdentifier(Identifiers.ComponentRef))),
new o.ClassMethod(
'injectorGetInternal',
[
@ -562,7 +562,10 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
}
var resultExpr: o.Expression;
if (view.viewType === ViewType.HOST) {
resultExpr = (<CompileElement>view.nodes[0]).appElement;
const hostEl = <CompileElement>view.nodes[0];
resultExpr = o.importExpr(resolveIdentifier(Identifiers.ComponentRef_)).instantiate([
o.literal(hostEl.nodeIndex), o.THIS_EXPR, hostEl.renderNode, hostEl.getComponent()
]);
} else {
resultExpr = o.NULL_EXPR;
}

View File

@ -20,6 +20,7 @@ import * as console from './console';
import * as debug from './debug/debug_renderer';
import * as reflective_provider from './di/reflective_provider';
import {ComponentStillLoadingError} from './linker/compiler';
import * as component_factory from './linker/component_factory';
import * as component_factory_resolver from './linker/component_factory_resolver';
import * as debug_context from './linker/debug_context';
import * as element from './linker/element';
@ -56,6 +57,7 @@ export var __core_private__: {
_MethodFn?: reflection_types.MethodFn;
CodegenComponentFactoryResolver:
typeof component_factory_resolver.CodegenComponentFactoryResolver,
ComponentRef_: typeof component_factory.ComponentRef_,
_CodegenComponentFactoryResolver?: component_factory_resolver.CodegenComponentFactoryResolver,
AppElement: typeof element.AppElement, _AppElement?: element.AppElement,
AppView: typeof view.AppView, _AppView?: view.AppView<any>,
@ -112,6 +114,7 @@ export var __core_private__: {
LIFECYCLE_HOOKS_VALUES: lifecycle_hooks.LIFECYCLE_HOOKS_VALUES,
ReflectorReader: reflector_reader.ReflectorReader,
CodegenComponentFactoryResolver: component_factory_resolver.CodegenComponentFactoryResolver,
ComponentRef_: component_factory.ComponentRef_,
AppElement: element.AppElement,
AppView: view.AppView,
DebugAppView: view.DebugAppView,

View File

@ -55,7 +55,7 @@ export abstract class ComponentRef<C> {
/**
* The component type.
*/
get componentType(): Type<any> { return unimplemented(); }
get componentType(): Type<C> { return unimplemented(); }
/**
* Destroys the component instance and all of the data structures associated with it.
@ -69,15 +69,19 @@ export abstract class ComponentRef<C> {
}
export class ComponentRef_<C> extends ComponentRef<C> {
constructor(private _hostElement: AppElement, private _componentType: Type<any>) { super(); }
get location(): ElementRef { return this._hostElement.elementRef; }
get injector(): Injector { return this._hostElement.injector; }
get instance(): C { return this._hostElement.component; };
get hostView(): ViewRef { return this._hostElement.parentView.ref; };
get changeDetectorRef(): ChangeDetectorRef { return this._hostElement.parentView.ref; };
get componentType(): Type<any> { return this._componentType; }
constructor(
private _index: number, private _parentView: AppView<any>, private _nativeElement: any,
private _component: C) {
super();
}
get location(): ElementRef { return new ElementRef(this._nativeElement); }
get injector(): Injector { return this._parentView.injector(this._index); }
get instance(): C { return this._component; };
get hostView(): ViewRef { return this._parentView.ref; };
get changeDetectorRef(): ChangeDetectorRef { return this._parentView.ref; };
get componentType(): Type<C> { return <any>this._component.constructor; }
destroy(): void { this._hostElement.parentView.detachAndDestroy(); }
destroy(): void { this._parentView.detachAndDestroy(); }
onDestroy(callback: Function): void { this.hostView.onDestroy(callback); }
}
@ -107,6 +111,9 @@ export class ComponentFactory<C> {
}
// Note: Host views don't need a declarationAppElement!
var hostView: AppView<any> = this._viewFactory(vu, injector, null);
// TODO: implement this in the View class directly?!
// (behind a `if (this.type === ViewType.HOST)`)
// TODO: and pass the projectableNodes into `createHostView`
hostView.visitProjectableNodesInternal =
(nodeIndex: number, ngContentIndex: number, cb: any, ctx: any) => {
const nodes = projectableNodes[ngContentIndex] || [];
@ -114,7 +121,6 @@ export class ComponentFactory<C> {
cb(nodes[i], ctx);
}
};
var hostElement = hostView.create(EMPTY_CONTEXT, rootSelectorOrNode);
return new ComponentRef_<C>(hostElement, this._componentType);
return hostView.createHostView(rootSelectorOrNode);
}
}

View File

@ -23,9 +23,6 @@ import {ViewType} from './view_type';
*/
export class AppElement {
public nestedViews: AppView<any>[];
public componentView: AppView<any>;
public component: any;
constructor(
public index: number, public parentIndex: number, public parentView: AppView<any>,
@ -35,11 +32,6 @@ export class AppElement {
get vcRef(): ViewContainerRef_ { return new ViewContainerRef_(this); }
initComponent(component: any, view: AppView<any>) {
this.component = component;
this.componentView = view;
}
get parentInjector(): Injector { return this.parentView.injector(this.parentIndex); }
get injector(): Injector { return this.parentView.injector(this.index); }

View File

@ -48,7 +48,7 @@ export class TemplateRef_<C> extends TemplateRef<C> {
createEmbeddedView(context: C): EmbeddedViewRef<C> {
var view: AppView<C> = this._viewFactory(
this._appElement.parentView.viewUtils, this._appElement.parentInjector, this._appElement);
view.create(context || <any>{}, null);
view.create(context || <any>{});
return view.ref;
}

View File

@ -14,6 +14,7 @@ import {WtfScopeFn, wtfCreateScope, wtfLeave} from '../profile/profile';
import {RenderComponentType, RenderDebugInfo, Renderer} from '../render/api';
import {AnimationViewContext} from './animation_view_context';
import {ComponentRef} from './component_factory';
import {DebugContext, StaticNodeDebugInfo} from './debug_context';
import {AppElement} from './element';
import {ElementInjector} from './element_injector';
@ -24,6 +25,11 @@ import {ViewUtils, addToArray} from './view_utils';
var _scope_check: WtfScopeFn = wtfCreateScope(`AppView#check(ascii id)`);
/**
* @experimental
*/
const EMPTY_CONTEXT = new Object();
/**
* Cost of making objects: http://jsperf.com/instantiate-size-of-object
*
@ -65,17 +71,22 @@ export abstract class AppView<T> {
get destroyed(): boolean { return this.cdMode === ChangeDetectorStatus.Destroyed; }
create(context: T, rootSelectorOrNode: string|any): AppElement {
create(context: T) {
this.context = context;
return this.createInternal(null);
}
createHostView(rootSelectorOrNode: string|any): ComponentRef<any> {
this.context = <any>EMPTY_CONTEXT;
this._hasExternalHostElement = isPresent(rootSelectorOrNode);
return this.createInternal(rootSelectorOrNode);
}
/**
* Overwritten by implementations.
* Returns the AppElement for the host element for ViewType.HOST.
* Returns the ComponentRef for the host element for ViewType.HOST.
*/
createInternal(rootSelectorOrNode: string|any): AppElement { return null; }
createInternal(rootSelectorOrNode: string|any): ComponentRef<any> { return null; }
init(lastRootNode: any, allNodes: any[], disposables: Function[]) {
this.lastRootNode = lastRootNode;
@ -268,10 +279,20 @@ export class DebugAppView<T> extends AppView<T> {
super(clazz, componentType, type, viewUtils, parentInjector, declarationAppElement, cdMode);
}
create(context: T, rootSelectorOrNode: string|any): AppElement {
create(context: T) {
this._resetDebug();
try {
return super.create(context, rootSelectorOrNode);
return super.create(context);
} catch (e) {
this._rethrowWithContext(e);
throw e;
}
}
createHostView(rootSelectorOrNode: string|any): ComponentRef<any> {
this._resetDebug();
try {
return super.createHostView(rootSelectorOrNode);
} catch (e) {
this._rethrowWithContext(e);
throw e;

View File

@ -32,14 +32,13 @@ class _View_TreeComponent_Host0 extends import1.AppView<any> {
_View_TreeComponent_Host0, renderType_TreeComponent_Host, import6.ViewType.HOST, viewUtils,
parentInjector, declarationEl, import7.ChangeDetectorStatus.CheckAlways);
}
createInternal(rootSelector: string): import2.AppElement {
createInternal(rootSelector: string): import9.ComponentRef<any> {
this._el_0 = import4.selectOrCreateRenderHostElement(
this.renderer, 'tree', import4.EMPTY_INLINE_ARRAY, rootSelector, (null as any));
this._vc_0 = new import2.AppElement(0, (null as any), this, this._el_0);
this._TreeComponent_0_4 = new _View_TreeComponent0(this._el_0);
this._vc_0.initComponent(this._TreeComponent_0_4.context, <any>this._TreeComponent_0_4);
this.init([].concat([this._el_0]), [this._el_0], []);
return this._vc_0;
return new import9.ComponentRef_(0, this, this._el_0, this._TreeComponent_0_4.context);
}
detectChangesInternal(throwOnChange: boolean): void {
this._TreeComponent_0_4.detectChangesInternal(throwOnChange);

View File

@ -35,17 +35,16 @@ class _View_TreeRootComponent_Host0 extends import1.AppView<any> {
_View_TreeRootComponent_Host0, renderType_TreeRootComponent_Host, import6.ViewType.HOST,
viewUtils, parentInjector, declarationEl, import7.ChangeDetectorStatus.CheckAlways);
}
createInternal(rootSelector: string): import2.AppElement {
createInternal(rootSelector: string): import9.ComponentRef<any> {
this._el_0 = import4.selectOrCreateRenderHostElement(
this.renderer, 'tree', import4.EMPTY_INLINE_ARRAY, rootSelector, (null as any));
this._appEl_0 = new import2.AppElement(0, (null as any), this, this._el_0);
this._TreeRootComponent_0_4_View =
viewFactory_TreeRootComponent0(this.viewUtils, this.injector(0), this._appEl_0);
this._TreeRootComponent_0_4 = new import3.TreeRootComponent();
this._appEl_0.initComponent(this._TreeRootComponent_0_4, this._TreeRootComponent_0_4_View);
this._TreeRootComponent_0_4_View.create(this._TreeRootComponent_0_4, (null as any));
this.init([].concat([this._el_0]), [this._el_0], []);
return this._appEl_0;
return new import9.ComponentRef_(0, this, this._el_0, this._TreeRootComponent_0_4);
}
detectChangesInternal(throwOnChange: boolean): void {
this._TreeRootComponent_0_4_View.detectChangesInternal(throwOnChange);
@ -85,7 +84,7 @@ class _View_TreeRootComponent0 extends import1.AppView<import3.TreeRootComponent
_View_TreeRootComponent0, renderType_TreeRootComponent, import6.ViewType.COMPONENT,
viewUtils, parentInjector, declarationEl, import7.ChangeDetectorStatus.CheckAlways);
}
createInternal(rootSelector: string): import2.AppElement {
createInternal(rootSelector: string): import9.ComponentRef<any> {
const parentRenderNode: any =
this.renderer.createViewRoot(this.declarationAppElement.nativeElement);
this._anchor_0 = this.renderer.createTemplateAnchor(parentRenderNode, (null as any));
@ -135,7 +134,7 @@ class _View_TreeRootComponent1 extends import1.AppView<any> {
_View_TreeRootComponent1, renderType_TreeRootComponent, import6.ViewType.EMBEDDED,
viewUtils, parentInjector, declarationEl, import7.ChangeDetectorStatus.CheckAlways);
}
createInternal(rootSelector: string): import2.AppElement {
createInternal(rootSelector: string): import9.ComponentRef<any> {
this._el_0 = this.renderer.createElement((null as any), 'tree0', (null as any));
this._TreeComponent0_0_4View = new import13.View_TreeTreeComponent(maxDepth - 1, this._el_0);
this.init([].concat([this._el_0]), [this._el_0], []);