Skip to content

Add core code necessary to support ng-upgrade via ui-router-ng1-to-ng2 #2675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 6, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export * from "./state/module";
export * from "./transition/module";
export * from "./url/module";
export * from "./view/module";
export * from "./globals";

export { UIRouter } from "./router";
4 changes: 2 additions & 2 deletions src/ng1/viewDirective.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** @module ng1_directives */ /** for typedoc */
"use strict";
import {extend, map, unnestR, filter} from "../common/common";
import {isDefined, isFunction} from "../common/predicates";
import {isDefined, isFunction, isString} from "../common/predicates";
import {trace} from "../common/trace";
import {ActiveUIView} from "../view/interface";
import {Ng1ViewConfig} from "./viewsBuilder";
Expand Down Expand Up @@ -357,7 +357,7 @@ function $ViewDirectiveFill ( $compile, $controller, $transitions, $view,
}

// Wait for the component to appear in the DOM
if (cfg.viewDecl.component) {
if (isString(cfg.viewDecl.component)) {
let cmp = cfg.viewDecl.component;
let kebobName = kebobString(cmp);
let getComponentController = () => {
Expand Down
3 changes: 2 additions & 1 deletion src/ng1/viewsBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export function ng1ViewsBuilder(state: State) {
config.templateProvider = ['$injector', function($injector) {
const resolveFor = key => config.bindings && config.bindings[key] || key;
const prefix = angular.version.minor >= 3 ? "::" : "";
let attrs = getComponentInputs($injector, config.component).map(key => `${kebobString(key)}='${prefix}$resolve.${resolveFor(key)}'`).join(" ");
let attrs = getComponentInputs($injector, config.component)
.map(key => `${kebobString(key)}='${prefix}$resolve.${resolveFor(key)}'`).join(" ");
let kebobName = kebobString(config.component);
return `<${kebobName} ${attrs}></${kebobName}>`;
}];
Expand Down
27 changes: 27 additions & 0 deletions src/ng2/componentUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {InputMetadata, ComponentMetadata} from "angular2/core";

export const ng2ComponentInputs = (ng2CompClass) => {
/** Get "@Input('foo') _foo" inputs */
let props = Reflect['getMetadata']('propMetadata', ng2CompClass);
let _props = Object.keys(props || {})
// -> { string, anno[] } tuples
.map(key => ({ key, annoArr: props[key] }))
// -> to { string, anno } tuples
.reduce((acc, tuple) => acc.concat(tuple.annoArr.map(anno => ({ key: tuple.key, anno }))), [])
// Only Inputs
.filter(tuple => tuple.anno instanceof InputMetadata)
// If they have a bindingPropertyName, i.e. "@Input('foo') _foo", then foo, else _foo
.map(tuple => ({ resolve: tuple.anno.bindingPropertyName || tuple.key, prop: tuple.key }));

/** Get "inputs: ['foo']" inputs */
let inputs = Reflect['getMetadata']('annotations', ng2CompClass)
// Find the ComponentMetadata class annotation
.filter(x => x instanceof ComponentMetadata && !!x.inputs)
// Get the .inputs string array
.map(x => x.inputs)
// Flatten
.reduce((acc, arr) => acc.concat(arr), [])
.map(input => ({ resolve: input, prop: input }));

return _props.concat(inputs);
};
4 changes: 1 addition & 3 deletions src/ng2/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,7 @@ export const UIROUTER_PROVIDERS: Provider[] = [

provide(UIRouterGlobals, { useFactory: (r: UIRouter) => { return r.globals; }, deps: [UIRouter]}),

provide(UiView.INJECT.context, { useFactory: (r: StateRegistry) => { return r.root(); }, deps: [StateRegistry]} ),

provide(UiView.INJECT.fqn, { useValue: null })
provide(UiView.PARENT_INJECT, { useFactory: (r: StateRegistry) => { return { fqn: null, context: r.root() } }, deps: [StateRegistry]} )

];

7 changes: 3 additions & 4 deletions src/ng2/uiSref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import {Directive, Inject, Input} from "angular2/core";
import {Optional} from "angular2/core";
import {ElementRef} from "angular2/core";
import {Renderer} from "angular2/core";
import {UiView} from "./uiView";
import {ViewContext} from "../view/interface";
import {UiView, ParentUiViewInject} from "./uiView";
import {extend} from "../common/common";

/** @hidden */
Expand Down Expand Up @@ -69,7 +68,7 @@ export class UiSref {

constructor(
private _router: UIRouter,
@Inject(UiView.INJECT.context) public context: ViewContext,
@Inject(UiView.PARENT_INJECT) public parent: ParentUiViewInject,
@Optional() private _anchorUiSref: AnchorUiSref
) { }

Expand All @@ -88,7 +87,7 @@ export class UiSref {
}

getOptions() {
let defOpts = { relative: this.context.name, inherit: true };
let defOpts = { relative: this.parent && this.parent.context && this.parent.context.name, inherit: true };
return extend(defOpts, this.options || {});
}

Expand Down
52 changes: 32 additions & 20 deletions src/ng2/uiView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {trace} from "../common/trace";
import {Inject} from "angular2/core";
import {ViewContext, ViewConfig} from "../view/interface";
import {Ng2ViewDeclaration} from "./interface";
import {ng2ComponentInputs} from "./componentUtil";

/** @hidden */
let id = 0;
Expand All @@ -23,6 +24,12 @@ const getProviders = (injector) => {
return providers;
};

// These are provide()d as the string UiView.PARENT_INJECT
export interface ParentUiViewInject {
context: ViewContext;
fqn: string;
}

/**
* A UI-Router viewport directive, which is filled in by a view (component) on a state.
*
Expand Down Expand Up @@ -84,44 +91,39 @@ const getProviders = (injector) => {
// <div style="padding: 1em; border: 1px solid lightgrey;">
//
// <div #content style="color: lightgrey; font-size: smaller;">
// <div>ui-view #{{uiViewData.id}} created by '{{ parentContext.name || "(root)" }}' state</div>
// <div>name: (absolute) '{{uiViewData.fqn}}' (contextual) '{{uiViewData.name}}@{{parentContext.name}}' </div>
// <div>currently filled by: '{{(uiViewData.config && uiViewData.config.viewDecl.$context) || 'empty...'}}'</div>
// <div>ui-view #{{uiViewData?.id}} created by '{{ parentContext?.name || "(root)" }}' state</div>
// <div>name: (absolute) '{{uiViewData?.fqn}}' (contextual) '{{uiViewData?.name}}@{{parentContext?.name}}' </div>
// <div>currently filled by: '{{(uiViewData?.config && uiViewData?.config?.viewDecl?.$context) || 'empty...'}}'</div>
// </div>
//
// </div>`
})
export class UiView {
@Input() name: string;
@Input() set 'ui-view'(val) { this.name = val; }

@Input('ui-view') set _name(val) { this.name = val; }
componentRef: ComponentRef;
deregister: Function;
uiViewData: any = {};

static INJECT = {
fqn: "UiView.parentFQN",
context: "UiView.parentContext"
};
static PARENT_INJECT = "UiView.PARENT_INJECT";

constructor(
public router: UIRouter,
@Inject(UiView.INJECT.context) public parentContext: ViewContext,
@Inject(UiView.INJECT.fqn) public parentFqn: string,
@Inject(UiView.PARENT_INJECT) public parent: ParentUiViewInject,
public dcl: DynamicComponentLoader,
public elementRef: ElementRef,
public injector: Injector
) { }

ngOnInit() {
let parentFqn = this.parentFqn;
let parentFqn = this.parent.fqn;
let name = this.name || '$default';

this.uiViewData = {
id: id++,
name: name,
fqn: parentFqn ? parentFqn + "." + name : name,
creationContext: this.parentContext,
creationContext: this.parent.context,
configUpdated: this.viewConfigUpdated.bind(this),
config: undefined
};
Expand All @@ -131,10 +133,11 @@ export class UiView {

disposeLast() {
if (this.componentRef) this.componentRef.dispose();
this.componentRef = null;
}

ngOnDestroy() {
this.deregister();
if (this.deregister) this.deregister();
this.disposeLast();
}

Expand All @@ -159,17 +162,26 @@ export class UiView {
let rc = config.node.resolveContext;
let resolvables = rc.getResolvables();
let rawProviders = Object.keys(resolvables).map(key => provide(key, { useValue: resolvables[key].data }));
rawProviders.push(provide(UiView.INJECT.context, { useValue: config.viewDecl.$context }));
rawProviders.push(provide(UiView.INJECT.fqn, { useValue: uiViewData.fqn }));
rawProviders.push(provide(UiView.PARENT_INJECT, { useValue: { context: config.viewDecl.$context, fqn: uiViewData.fqn } }));
let providers = Injector.resolve(rawProviders);

let exclusions = [UiView.INJECT.context, UiView.INJECT.fqn];
let exclusions = [UiView.PARENT_INJECT];
providers = getProviders(injector).filter(x => exclusions.indexOf(x.key.displayName) === -1).concat(providers);

// The 'controller' should be a Component class
// TODO: pull from 'component' declaration, do not require template.
let component = <Type> viewDecl.component;
dcl.loadIntoLocation(component, elementRef, "content", providers).then(ref => this.componentRef = ref);
dcl.loadIntoLocation(component, elementRef, "content", providers).then(ref => {
this.componentRef = ref;

// TODO: wire uiCanExit and uiOnParamsChanged callbacks

// Set resolve data to matching @Input("prop")
let inputs = ng2ComponentInputs(component);
let bindings = viewDecl['bindings'] || {};

inputs.map(tuple => ({ prop: tuple.prop, resolve: bindings[tuple.prop] || tuple.resolve }))
.filter(tuple => resolvables[tuple.resolve] !== undefined)
.forEach(tuple => { ref.instance[tuple.prop] = resolvables[tuple.resolve].data });
});
}
}