refactor(compiler): remove view factories, use view classes directly

This commit is contained in:
Tobias Bosch 2016-11-02 08:36:23 -07:00 committed by Vikram Subramanian
parent 7c5cc9bc41
commit 0e3d655220
12 changed files with 64 additions and 112 deletions

View File

@ -21,7 +21,7 @@ import {OutputEmitter} from './output/abstract_emitter';
import * as o from './output/output_ast';
import {CompiledStylesheet, StyleCompiler} from './style_compiler';
import {TemplateParser} from './template_parser/template_parser';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewCompileResult, ViewCompiler, ViewFactoryDependency} from './view_compiler/view_compiler';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewClassDependency, ViewCompileResult, ViewCompiler} from './view_compiler/view_compiler';
export class SourceModule {
constructor(public fileUrl: string, public moduleUrl: string, public source: string) {}
@ -278,7 +278,7 @@ export class OfflineCompiler {
}
compiledAnimations.forEach(entry => targetStatements.push(...entry.statements));
targetStatements.push(..._resolveViewStatements(viewResult));
return viewResult.viewFactoryVar;
return viewResult.viewClassVar;
}
private _codgenStyles(
@ -301,8 +301,8 @@ export class OfflineCompiler {
function _resolveViewStatements(compileResult: ViewCompileResult): o.Statement[] {
compileResult.dependencies.forEach((dep) => {
if (dep instanceof ViewFactoryDependency) {
const vfd = <ViewFactoryDependency>dep;
if (dep instanceof ViewClassDependency) {
const vfd = <ViewClassDependency>dep;
vfd.placeholder.moduleUrl = _ngfactoryModuleUrl(vfd.comp.moduleUrl);
} else if (dep instanceof ComponentFactoryDependency) {
const cfd = <ComponentFactoryDependency>dep;

View File

@ -24,7 +24,8 @@ import {ComponentStillLoadingError} from './private_import_core';
import {CompiledStylesheet, StyleCompiler} from './style_compiler';
import {TemplateParser} from './template_parser/template_parser';
import {SyncAsyncResult} from './util';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewCompiler, ViewFactoryDependency} from './view_compiler/view_compiler';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewClassDependency, ViewCompiler} from './view_compiler/view_compiler';
/**
@ -305,11 +306,11 @@ export class RuntimeCompiler implements Compiler {
template.viewPipes, compiledAnimations);
compileResult.dependencies.forEach((dep) => {
let depTemplate: CompiledTemplate;
if (dep instanceof ViewFactoryDependency) {
let vfd = <ViewFactoryDependency>dep;
if (dep instanceof ViewClassDependency) {
let vfd = <ViewClassDependency>dep;
depTemplate = this._assertComponentLoaded(vfd.comp.reference, false);
vfd.placeholder.reference = depTemplate.proxyViewFactory;
vfd.placeholder.name = `viewFactory_${vfd.comp.name}`;
vfd.placeholder.reference = depTemplate.proxyViewClass;
vfd.placeholder.name = `View_${vfd.comp.name}`;
} else if (dep instanceof ComponentFactoryDependency) {
let cfd = <ComponentFactoryDependency>dep;
depTemplate = this._assertComponentLoaded(cfd.comp.reference, true);
@ -323,15 +324,15 @@ export class RuntimeCompiler implements Compiler {
const statements = stylesCompileResult.componentStylesheet.statements
.concat(...compiledAnimations.map(ca => ca.statements))
.concat(compileResult.statements);
let factory: any;
let viewClass: any;
if (!this._compilerConfig.useJit) {
factory = interpretStatements(statements, compileResult.viewFactoryVar);
viewClass = interpretStatements(statements, compileResult.viewClassVar);
} else {
factory = jitStatements(
viewClass = jitStatements(
`/${template.ngModule.type.name}/${template.compType.name}/${template.isHost?'host':'component'}.ngfactory.js`,
statements, compileResult.viewFactoryVar);
statements, compileResult.viewClassVar);
}
template.compiled(factory);
template.compiled(viewClass);
}
private _resolveStylesCompileResult(
@ -358,8 +359,8 @@ export class RuntimeCompiler implements Compiler {
}
class CompiledTemplate {
private _viewFactory: Function = null;
proxyViewFactory: Function;
private _viewClass: Function = null;
proxyViewClass: Type<any>;
proxyComponentFactory: ComponentFactory<any>;
loading: Promise<any> = null;
private _normalizedCompMeta: CompileDirectiveMetadata = null;
@ -384,15 +385,16 @@ class CompiledTemplate {
this.viewDirectives.push(dirMeta);
}
});
this.proxyViewFactory = (...args: any[]) => {
if (!this._viewFactory) {
const self = this;
this.proxyViewClass = <any>function() {
if (!self._viewClass) {
throw new Error(
`Illegal state: CompiledTemplate for ${stringify(this.compType)} is not compiled yet!`);
`Illegal state: CompiledTemplate for ${stringify(self.compType)} is not compiled yet!`);
}
return this._viewFactory.apply(null, args);
return self._viewClass.apply(this, arguments);
};
this.proxyComponentFactory = isHost ?
new ComponentFactory<any>(selector, this.proxyViewFactory, compType.reference) :
new ComponentFactory<any>(selector, this.proxyViewClass, compType.reference) :
null;
if (_normalizeResult.syncResult) {
this._normalizedCompMeta = _normalizeResult.syncResult;
@ -411,8 +413,9 @@ class CompiledTemplate {
return this._normalizedCompMeta;
}
compiled(viewFactory: Function) {
this._viewFactory = viewFactory;
compiled(viewClass: Function) {
this._viewClass = viewClass;
this.proxyViewClass.prototype = viewClass.prototype;
this.isCompiled = true;
}

View File

@ -21,7 +21,7 @@ import {CompileMethod} from './compile_method';
import {CompileQuery, addQueryToTokenMap, createQueryList} from './compile_query';
import {CompileView, CompileViewRootNode} from './compile_view';
import {InjectMethodVars, ViewProperties} from './constants';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewFactoryDependency} from './deps';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewClassDependency} from './deps';
import {getPropertyInView, injectFromViewParentInjector} from './util';
export class CompileNode {
@ -60,7 +60,7 @@ export class CompileElement extends CompileNode {
private _resolvedProvidersArray: ProviderAst[], public hasViewContainer: boolean,
public hasEmbeddedView: boolean, references: ReferenceAst[],
private _targetDependencies:
Array<ViewFactoryDependency|ComponentFactoryDependency|DirectiveWrapperDependency>) {
Array<ViewClassDependency|ComponentFactoryDependency|DirectiveWrapperDependency>) {
super(parent, view, nodeIndex, renderNode, sourceAst);
this.referenceTokens = {};
references.forEach(ref => this.referenceTokens[ref.name] = ref.value);

View File

@ -21,7 +21,7 @@ import {CompileElement, CompileNode} from './compile_element';
import {CompileMethod} from './compile_method';
import {CompilePipe} from './compile_pipe';
import {CompileQuery, addQueryToTokenMap, createQueryList} from './compile_query';
import {getPropertyInView, getViewFactoryName} from './util';
import {getPropertyInView, getViewClassName} from './util';
export enum CompileViewRootNodeType {
Node,
@ -73,7 +73,7 @@ export class CompileView implements NameResolver {
public locals = new Map<string, o.Expression>();
public className: string;
public classType: o.Type;
public viewFactory: o.ReadVarExpr;
public classExpr: o.ReadVarExpr;
public literalArrayCount = 0;
public literalMapCount = 0;
@ -101,9 +101,9 @@ export class CompileView implements NameResolver {
this.detachMethod = new CompileMethod(this);
this.viewType = getViewType(component, viewIndex);
this.className = `_View_${component.type.name}${viewIndex}`;
this.className = getViewClassName(component, viewIndex);
this.classType = o.importType(new CompileIdentifierMetadata({name: this.className}));
this.viewFactory = o.variable(getViewFactoryName(component, viewIndex));
this.classExpr = o.variable(this.className);
if (this.viewType === ViewType.COMPONENT || this.viewType === ViewType.HOST) {
this.componentView = this;
} else {

View File

@ -8,7 +8,7 @@
import {CompileIdentifierMetadata} from '../compile_metadata';
export class ViewFactoryDependency {
export class ViewClassDependency {
constructor(
public comp: CompileIdentifierMetadata, public placeholder: CompileIdentifierMetadata) {}
}

View File

@ -71,9 +71,9 @@ export function injectFromViewParentInjector(
return viewExpr.callMethod('injectorGet', args);
}
export function getViewFactoryName(
export function getViewClassName(
component: CompileDirectiveMetadata, embeddedTemplateIndex: number): string {
return `viewFactory_${component.type.name}${embeddedTemplateIndex}`;
return `View_${component.type.name}${embeddedTemplateIndex}`;
}
export function getHandleEventMethodName(elementIndex: number): string {

View File

@ -22,8 +22,8 @@ import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventA
import {CompileElement, CompileNode} from './compile_element';
import {CompileView, CompileViewRootNode, CompileViewRootNodeType} from './compile_view';
import {ChangeDetectorStatusEnum, DetectChangesVars, InjectMethodVars, ViewConstructorVars, ViewEncapsulationEnum, ViewProperties, ViewTypeEnum} from './constants';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewFactoryDependency} from './deps';
import {getViewFactoryName} from './util';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewClassDependency} from './deps';
import {getViewClassName} from './util';
const IMPLICIT_TEMPLATE_VAR = '\$implicit';
const CLASS_ATTR = 'class';
@ -36,8 +36,7 @@ var rootSelectorVar = o.variable('rootSelector');
export function buildView(
view: CompileView, template: TemplateAst[],
targetDependencies:
Array<ViewFactoryDependency|ComponentFactoryDependency|DirectiveWrapperDependency>):
number {
Array<ViewClassDependency|ComponentFactoryDependency|DirectiveWrapperDependency>): number {
var builderVisitor = new ViewBuilderVisitor(view, targetDependencies);
const parentEl =
view.declarationElement.isNull() ? view.declarationElement : view.declarationElement.parent;
@ -64,7 +63,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
constructor(
public view: CompileView,
public targetDependencies:
Array<ViewFactoryDependency|ComponentFactoryDependency|DirectiveWrapperDependency>) {}
Array<ViewClassDependency|ComponentFactoryDependency|DirectiveWrapperDependency>) {}
private _isRootNode(parent: CompileElement): boolean { return parent.view !== this.view; }
@ -222,9 +221,9 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
var compViewExpr: o.ReadPropExpr = null;
if (isPresent(component)) {
let nestedComponentIdentifier =
new CompileIdentifierMetadata({name: getViewFactoryName(component, 0)});
new CompileIdentifierMetadata({name: getViewClassName(component, 0)});
this.targetDependencies.push(
new ViewFactoryDependency(component.type, nestedComponentIdentifier));
new ViewClassDependency(component.type, nestedComponentIdentifier));
compViewExpr = o.THIS_EXPR.prop(`compView_${nodeIndex}`); // fix highlighting: `
this.view.fields.push(new o.ClassField(
@ -234,7 +233,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
compileElement.setComponentView(compViewExpr);
this.view.createMethod.addStmt(
compViewExpr
.set(o.importExpr(nestedComponentIdentifier).callFn([
.set(o.importExpr(nestedComponentIdentifier).instantiate([
ViewProperties.viewUtils, o.THIS_EXPR, o.literal(nodeIndex), renderNode
]))
.toStmt());
@ -416,7 +415,6 @@ function createViewTopLevelStmts(view: CompileView, targetStatements: o.Statemen
var viewClass = createViewClass(view, renderCompTypeVar, nodeDebugInfosVar);
targetStatements.push(viewClass);
targetStatements.push(createViewFactory(view, viewClass));
}
function createStaticNodeDebugInfo(node: CompileNode): o.Expression {
@ -514,27 +512,6 @@ function generateDestroyMethod(view: CompileView): o.Statement[] {
return stmts;
}
function createViewFactory(view: CompileView, viewClass: o.ClassStmt): o.Statement {
var viewFactoryArgs = [
new o.FnParam(
ViewConstructorVars.viewUtils.name, o.importType(resolveIdentifier(Identifiers.ViewUtils))),
new o.FnParam(
ViewConstructorVars.parentView.name,
o.importType(resolveIdentifier(Identifiers.AppView), [o.DYNAMIC_TYPE])),
new o.FnParam(ViewConstructorVars.parentIndex.name, o.NUMBER_TYPE),
new o.FnParam(ViewConstructorVars.parentElement.name, o.DYNAMIC_TYPE)
];
return o
.fn(viewFactoryArgs,
[
new o.ReturnStatement(o.variable(viewClass.name)
.instantiate(viewClass.constructorMethod.params.map(
(param) => o.variable(param.name)))),
],
o.importType(resolveIdentifier(Identifiers.AppView), [getContextType(view)]))
.toDeclStmt(view.viewFactory.name, [o.StmtModifier.Final]);
}
function generateCreateMethod(view: CompileView): o.Statement[] {
var parentRenderNodeExpr: o.Expression = o.NULL_EXPR;
var parentRenderNodeStmts: any[] = [];
@ -709,7 +686,7 @@ function generateCreateEmbeddedViewsMethod(view: CompileView) {
const parentNodeIndex = node.isRootElement() ? null : node.parent.nodeIndex;
stmts.push(new o.IfStmt(
nodeIndexVar.equals(o.literal(node.nodeIndex)),
[new o.ReturnStatement(node.embeddedView.viewFactory.callFn([
[new o.ReturnStatement(node.embeddedView.classExpr.instantiate([
ViewProperties.viewUtils, o.THIS_EXPR, o.literal(node.nodeIndex), node.renderNode
]))]));
}

View File

@ -17,17 +17,17 @@ import {TemplateAst} from '../template_parser/template_ast';
import {CompileElement} from './compile_element';
import {CompileView} from './compile_view';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewFactoryDependency} from './deps';
import {ComponentFactoryDependency, DirectiveWrapperDependency, ViewClassDependency} from './deps';
import {bindView} from './view_binder';
import {buildView, finishView} from './view_builder';
export {ComponentFactoryDependency, DirectiveWrapperDependency, ViewFactoryDependency} from './deps';
export {ComponentFactoryDependency, DirectiveWrapperDependency, ViewClassDependency} from './deps';
export class ViewCompileResult {
constructor(
public statements: o.Statement[], public viewFactoryVar: string,
public statements: o.Statement[], public viewClassVar: string,
public dependencies:
Array<ViewFactoryDependency|ComponentFactoryDependency|DirectiveWrapperDependency>) {}
Array<ViewClassDependency|ComponentFactoryDependency|DirectiveWrapperDependency>) {}
}
@Injectable()
@ -39,7 +39,7 @@ export class ViewCompiler {
pipes: CompilePipeMetadata[],
compiledAnimations: AnimationEntryCompileResult[]): ViewCompileResult {
const dependencies:
Array<ViewFactoryDependency|ComponentFactoryDependency|DirectiveWrapperDependency> = [];
Array<ViewClassDependency|ComponentFactoryDependency|DirectiveWrapperDependency> = [];
const view = new CompileView(
component, this._genConfig, pipes, styles, compiledAnimations, 0,
CompileElement.createNull(), []);
@ -51,6 +51,6 @@ export class ViewCompiler {
bindView(view, template, this._schemaRegistry);
finishView(view, statements);
return new ViewCompileResult(statements, view.viewFactory.name, dependencies);
return new ViewCompileResult(statements, view.classExpr.name, dependencies);
}
}

View File

@ -96,7 +96,8 @@ const EMPTY_CONTEXT = new Object();
*/
export class ComponentFactory<C> {
constructor(
public selector: string, private _viewFactory: Function, private _componentType: Type<any>) {}
public selector: string, private _viewClass: Type<AppView<any>>,
private _componentType: Type<any>) {}
get componentType(): Type<any> { return this._componentType; }
@ -110,7 +111,7 @@ export class ComponentFactory<C> {
if (!projectableNodes) {
projectableNodes = [];
}
var hostView: AppView<any> = this._viewFactory(vu, null, null, null);
var hostView: AppView<any> = new this._viewClass(vu, null, null, null);
return hostView.createHostView(rootSelectorOrNode, injector, projectableNodes);
}
}

View File

@ -20,7 +20,8 @@ import * as import12 from '@angular/core/src/security';
import * as import3 from './tree';
import {_View_TreeComponent0} from './tree.ngfactory';
var renderType_TreeComponent_Host: import0.RenderComponentType = (null as any);
var renderType_TreeComponent_Host: import0.RenderComponentType =
import4.createRenderComponentType('', 0, import8.ViewEncapsulation.None, [], {});
class _View_TreeComponent_Host0 extends import1.AppView<any> {
_el_0: any;
_vc_0: import2.ViewContainer;
@ -51,15 +52,6 @@ class _View_TreeComponent_Host0 extends import1.AppView<any> {
return notFoundResult;
}
}
function viewFactory_TreeComponent_Host0(
viewUtils: import4.ViewUtils, parentView: import1.AppView<any>, parentIndex: number,
parentElement: any): import1.AppView<any> {
if ((renderType_TreeComponent_Host === (null as any))) {
(renderType_TreeComponent_Host =
import4.createRenderComponentType('', 0, import8.ViewEncapsulation.None, [], {}));
}
return new _View_TreeComponent_Host0(viewUtils, parentView, parentIndex, parentElement);
}
export const TreeComponentNgFactory: import9.ComponentFactory<import3.TreeComponent> =
new import9.ComponentFactory<import3.TreeComponent>(
'tree', viewFactory_TreeComponent_Host0, import3.TreeComponent);
'tree', _View_TreeComponent_Host0, import3.TreeComponent);

View File

@ -22,7 +22,8 @@ import * as import3 from './tree';
import * as import12 from './tree';
import * as import13 from './tree_branch.ngfactory';
var renderType_TreeRootComponent_Host: import0.RenderComponentType = (null as any);
var renderType_TreeRootComponent_Host: import0.RenderComponentType =
import4.createRenderComponentType('', 0, import8.ViewEncapsulation.None, [], {});
class _View_TreeRootComponent_Host0 extends import1.AppView<any> {
_el_0: any;
/*private*/ _appEl_0: import2.ViewContainer;
@ -41,7 +42,7 @@ class _View_TreeRootComponent_Host0 extends import1.AppView<any> {
this.renderer, 'tree', import4.EMPTY_INLINE_ARRAY, rootSelector, (null as any));
this._appEl_0 = new import2.ViewContainer(0, (null as any), this, this._el_0);
this._TreeRootComponent_0_4_View =
viewFactory_TreeRootComponent0(this.viewUtils, this, 0, this._el_0);
new _View_TreeRootComponent0(this.viewUtils, this, 0, this._el_0);
this._TreeRootComponent_0_4 = new import3.TreeRootComponent();
this._TreeRootComponent_0_4_View.create(this._TreeRootComponent_0_4, (null as any));
this.init([].concat([this._el_0]), [this._el_0], []);
@ -58,20 +59,13 @@ class _View_TreeRootComponent_Host0 extends import1.AppView<any> {
return notFoundResult;
}
}
function viewFactory_TreeRootComponent_Host0(
viewUtils: import4.ViewUtils, parentView: import1.AppView<any>, parentIndex: number,
parentElement: any): import1.AppView<any> {
if ((renderType_TreeRootComponent_Host === (null as any))) {
(renderType_TreeRootComponent_Host =
import4.createRenderComponentType('', 0, import8.ViewEncapsulation.None, [], {}));
}
return new _View_TreeRootComponent_Host0(viewUtils, parentView, parentIndex, parentElement);
}
export const TreeRootComponentNgFactory: import9.ComponentFactory<import3.TreeRootComponent> =
new import9.ComponentFactory<import3.TreeRootComponent>(
'tree', viewFactory_TreeRootComponent_Host0, import3.TreeRootComponent);
'tree', _View_TreeRootComponent_Host0, import3.TreeRootComponent);
const styles_TreeRootComponent: any[] = [];
var renderType_TreeRootComponent: import0.RenderComponentType = (null as any);
var renderType_TreeRootComponent: import0.RenderComponentType = import4.createRenderComponentType(
'/Users/tbosch/projects/conf-demos/ngc-demo/src/ng2_static/root_tree.ts class TreeRootComponent - inline template',
0, import8.ViewEncapsulation.None, styles_TreeRootComponent, {});
class _View_TreeRootComponent0 extends import1.AppView<import3.TreeRootComponent> {
_anchor_0: any;
/*private*/ _appEl_0: import2.ViewContainer;
@ -99,7 +93,7 @@ class _View_TreeRootComponent0 extends import1.AppView<import3.TreeRootComponent
createEmbeddedViewInternal(nodeIndex: number): import1.AppView<any> {
if (nodeIndex === 0) {
return viewFactory_TreeRootComponent1(this.viewUtils, this, 0, this._anchor_0);
return new _View_TreeRootComponent1(this.viewUtils, this, 0, this._anchor_0);
}
}
@ -121,16 +115,6 @@ class _View_TreeRootComponent0 extends import1.AppView<import3.TreeRootComponent
this._appEl_0.detectChangesInNestedViews(throwOnChange);
}
}
export function viewFactory_TreeRootComponent0(
viewUtils: import4.ViewUtils, parentView: import1.AppView<any>, parentIndex: number,
parentElement: any): import1.AppView<import3.TreeRootComponent> {
if ((renderType_TreeRootComponent === (null as any))) {
(renderType_TreeRootComponent = import4.createRenderComponentType(
'/Users/tbosch/projects/conf-demos/ngc-demo/src/ng2_static/root_tree.ts class TreeRootComponent - inline template',
0, import8.ViewEncapsulation.None, styles_TreeRootComponent, {}));
}
return new _View_TreeRootComponent0(viewUtils, parentView, parentIndex, parentElement);
}
class _View_TreeRootComponent1 extends import1.AppView<any> {
_el_0: any;
_TreeComponent0_0_4View: any;
@ -155,8 +139,3 @@ class _View_TreeRootComponent1 extends import1.AppView<any> {
}
visitRootNodesInternal(cb: any, context: any) { cb(this._el_0, context); }
}
function viewFactory_TreeRootComponent1(
viewUtils: import4.ViewUtils, parentView: import1.AppView<any>, parentIndex: number,
parentElement: any): import1.AppView<any> {
return new _View_TreeRootComponent1(viewUtils, parentView, parentIndex, parentElement);
}

View File

@ -247,7 +247,7 @@ export interface ComponentDecorator {
export declare class ComponentFactory<C> {
componentType: Type<any>;
selector: string;
constructor(selector: string, _viewFactory: Function, _componentType: Type<any>);
constructor(selector: string, _viewClass: Type<AppView<any>>, _componentType: Type<any>);
create(injector: Injector, projectableNodes?: any[][], rootSelectorOrNode?: string | any): ComponentRef<C>;
}