-
Notifications
You must be signed in to change notification settings - Fork 25.6k
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
feat(upgrade): Bootstrap with ng2 in ng1 #3539
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import {Type, ComponentMetadata} from 'angular2/angular2'; | ||
import {stringify} from 'upgrade/src/util'; | ||
|
||
var COMPONENT_SELECTOR = /^[\w|-]*$/; | ||
var SKEWER_CASE = /-(\w)/g; | ||
|
||
interface Reflect { | ||
getOwnMetadata(name: string, type: Function): any; | ||
defineMetadata(name: string, value: any, cls: Type): void; | ||
} | ||
var Reflect: Reflect = <Reflect>(<any>window).Reflect; | ||
if (!(Reflect && (<any>Reflect)['getOwnMetadata'])) { | ||
throw 'reflect-metadata shim is required when using class decorators'; | ||
} | ||
|
||
export function getComponentSelector(type: Type): string { | ||
var selector = getTypeMetadata(type).selector; | ||
if (!selector.match(COMPONENT_SELECTOR)) { | ||
throw new Error('Only selectors matching element names are supported, got: ' + selector); | ||
} | ||
return selector.replace(SKEWER_CASE, (all, letter: string) => letter.toUpperCase()); | ||
} | ||
|
||
export function getTypeMetadata(type: Type): ComponentMetadata { | ||
var annotations = Reflect.getOwnMetadata('annotations', type) || []; | ||
for (var i = 0; i < annotations.length; i++) { | ||
var annotation = annotations[i]; | ||
if (annotation instanceof ComponentMetadata) return annotation; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You have to use DirectiveResolver here, otherwise the syntax sugar (e.g., property decorators) will not work. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. good catch, updated. |
||
} | ||
throw new Error("Missing @Component metadata on type: " + stringify(type)); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
///<reference path="../typings/angularjs/angular.d.ts"/> | ||
|
||
import { | ||
platform, | ||
PlatformRef, | ||
ApplicationRef, | ||
ComponentRef, | ||
bind, | ||
Directive, | ||
Component, | ||
Inject, | ||
View, | ||
Type, | ||
PlatformRef, | ||
ApplicationRef, | ||
ChangeDetectorRef, | ||
AppViewManager, | ||
NgZone, | ||
Injector, | ||
Compiler, | ||
ProtoViewRef, | ||
ElementRef, | ||
HostViewRef, | ||
ViewRef | ||
} from 'angular2/angular2'; | ||
import {applicationDomBindings} from 'angular2/src/core/application_common'; | ||
import {applicationCommonBindings} from "../../angular2/src/core/application_ref"; | ||
|
||
import {getComponentSelector} from './metadata'; | ||
import {onError} from './util'; | ||
export const INJECTOR = 'ng2.Injector'; | ||
export const APP_VIEW_MANAGER = 'ng2.AppViewManager'; | ||
export const NG2_COMPILER = 'ng2.Compiler'; | ||
export const NG2_ZONE = 'ng2.NgZone'; | ||
export const PROTO_VIEW_REF_MAP = 'ng2.ProtoViewRefMap'; | ||
|
||
const NG1_REQUIRE_INJECTOR_REF = '$' + INJECTOR + 'Controller'; | ||
const NG1_SCOPE = '$scope'; | ||
const NG1_COMPILE = '$compile'; | ||
const NG1_INJECTOR = '$injector'; | ||
const REQUIRE_INJECTOR = '^' + INJECTOR; | ||
|
||
var moduleCount: number = 0; | ||
const CAMEL_CASE = /([A-Z])/g; | ||
|
||
export function createUpgradeModule(): UpgradeModule { | ||
var prefix = `NG2_UPGRADE_m${moduleCount++}_`; | ||
return new UpgradeModule(prefix, angular.module(prefix, [])); | ||
} | ||
|
||
|
||
export class UpgradeModule { | ||
componentTypes: Array<Type> = []; | ||
|
||
constructor(public idPrefix: string, public ng1Module: angular.IModule) {} | ||
|
||
importNg2Component(type: Type): UpgradeModule { | ||
this.componentTypes.push(type); | ||
var selector: string = getComponentSelector(type); | ||
var factory: Function = ng1ComponentDirective(selector, type, `${this.idPrefix}${selector}_c`); | ||
this.ng1Module.directive(selector, <any[]>factory); | ||
return this; | ||
} | ||
|
||
exportAsNg2Component(name: string): Type { | ||
return Directive({ | ||
selector: name.replace(CAMEL_CASE, (all, next: string) => '-' + next.toLowerCase()) | ||
}) | ||
.Class({ | ||
constructor: [ | ||
new Inject(NG1_COMPILE), | ||
new Inject(NG1_SCOPE), | ||
ElementRef, | ||
function(compile: angular.ICompileService, scope: angular.IScope, | ||
elementRef: ElementRef) { compile(elementRef.nativeElement)(scope); } | ||
] | ||
}); | ||
} | ||
|
||
bootstrap(element: Element, modules?: any[], | ||
config?: angular.IAngularBootstrapConfig): UpgradeRef { | ||
var upgrade = new UpgradeRef(); | ||
var ng1Injector: angular.auto.IInjectorService = null; | ||
var bindings = [ | ||
applicationCommonBindings(), | ||
applicationDomBindings(), | ||
bind(NG1_INJECTOR).toFactory(() => ng1Injector), | ||
bind(NG1_COMPILE).toFactory(() => ng1Injector.get(NG1_COMPILE)) | ||
]; | ||
|
||
var platformRef: PlatformRef = platform(); | ||
var applicationRef: ApplicationRef = platformRef.application(bindings); | ||
var injector: Injector = applicationRef.injector; | ||
var ngZone: NgZone = injector.get(NgZone); | ||
var compiler: Compiler = injector.get(Compiler); | ||
this.compileNg2Components(compiler).then((protoViewRefMap: ProtoViewRefMap) => { | ||
ngZone.run(() => { | ||
this.ng1Module.value(INJECTOR, injector) | ||
.value(NG2_ZONE, ngZone) | ||
.value(NG2_COMPILER, compiler) | ||
.value(PROTO_VIEW_REF_MAP, protoViewRefMap) | ||
.value(APP_VIEW_MANAGER, injector.get(AppViewManager)) | ||
.run([ | ||
'$injector', | ||
'$rootScope', | ||
(injector: angular.auto.IInjectorService, rootScope: angular.IRootScopeService) => { | ||
ng1Injector = injector; | ||
ngZone.overrideOnTurnDone(() => rootScope.$apply()); | ||
} | ||
]); | ||
|
||
modules = modules ? [].concat(modules) : []; | ||
modules.push(this.idPrefix); | ||
angular.element(element).data(NG1_REQUIRE_INJECTOR_REF, injector); | ||
angular.bootstrap(element, modules, config); | ||
|
||
upgrade.readyFn && upgrade.readyFn(); | ||
}); | ||
}); | ||
return upgrade; | ||
} | ||
|
||
private compileNg2Components(compiler: Compiler): Promise<ProtoViewRefMap> { | ||
var promises: Array<Promise<ProtoViewRef>> = []; | ||
var types = this.componentTypes; | ||
for (var i = 0; i < types.length; i++) { | ||
promises.push(compiler.compileInHost(types[i])); | ||
} | ||
return Promise.all(promises).then((protoViews: Array<ProtoViewRef>) => { | ||
var protoViewRefMap: ProtoViewRefMap = {}; | ||
var types = this.componentTypes; | ||
for (var i = 0; i < protoViews.length; i++) { | ||
protoViewRefMap[getComponentSelector(types[i])] = protoViews[i]; | ||
} | ||
return protoViewRefMap; | ||
}, onError); | ||
} | ||
} | ||
|
||
interface ProtoViewRefMap { | ||
[selector: string]: ProtoViewRef | ||
} | ||
|
||
function ng1ComponentDirective(selector: string, type: Type, idPrefix: string): Function { | ||
directiveFactory.$inject = [PROTO_VIEW_REF_MAP, APP_VIEW_MANAGER]; | ||
function directiveFactory(protoViewRefMap: ProtoViewRefMap, viewManager: AppViewManager): | ||
angular.IDirective { | ||
var protoView: ProtoViewRef = protoViewRefMap[selector]; | ||
if (!protoView) throw new Error('Expecting ProtoViewRef for: ' + selector); | ||
var idCount = 0; | ||
return { | ||
restrict: 'E', | ||
require: REQUIRE_INJECTOR, | ||
link: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, | ||
parentInjector: any, transclude: angular.ITranscludeFunction): void => { | ||
var id = element[0].id = idPrefix + (idCount++); | ||
var childInjector = parentInjector.resolveAndCreateChild([bind(NG1_SCOPE).toValue(scope)]); | ||
var hostViewRef = viewManager.createRootHostView(protoView, '#' + id, childInjector); | ||
var changeDetector: ChangeDetectorRef = hostViewRef.changeDetectorRef; | ||
scope.$watch(() => changeDetector.detectChanges()); | ||
element.bind('$remove', () => viewManager.destroyRootHostView(hostViewRef)); | ||
} | ||
}; | ||
} | ||
return directiveFactory; | ||
} | ||
|
||
export class UpgradeRef { | ||
readyFn: Function; | ||
|
||
ready(fn: Function) { this.readyFn = fn; } | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
|
||
export function stringify(obj: any): string { | ||
if (typeof obj == 'function') return obj.name || obj.toString(); | ||
return '' + obj; | ||
} | ||
|
||
|
||
export function onError(e: any) { | ||
// TODO: (misko): We seem to not have a stack trace here! | ||
console.log(e, e.stack); | ||
throw e; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import { | ||
AsyncTestCompleter, | ||
beforeEach, | ||
ddescribe, | ||
describe, | ||
expect, | ||
iit, | ||
inject, | ||
it, | ||
xdescribe, | ||
xit, | ||
} from 'angular2/test_lib'; | ||
|
||
import {Component, View, Inject} from 'angular2/angular2'; | ||
import {createUpgradeModule, UpgradeModule, bootstrapHybrid} from 'upgrade/upgrade'; | ||
|
||
export function main() { | ||
describe('upgrade: ng1 to ng2', () => { | ||
it('should have angular 1 loaded', () => expect(angular.version.major).toBe(1)); | ||
|
||
it('should instantiate ng2 in ng1 template', inject([AsyncTestCompleter], (async) => { | ||
var element = html("<div>{{ 'ng1-' }}<ng2>~~</ng2>{{ '-ng1' }}</div>"); | ||
|
||
var upgradeModule: UpgradeModule = createUpgradeModule(); | ||
upgradeModule.importNg2Component(SimpleComponent); | ||
upgradeModule.bootstrap(element).ready(() => { | ||
expect(document.body.textContent).toEqual("ng1-NG2-ng1"); | ||
async.done(); | ||
}); | ||
})); | ||
|
||
it('should instantiate ng1 in ng2 template', inject([AsyncTestCompleter], (async) => { | ||
var element = html("<div>{{'ng1('}}<ng2-1></ng2-1>{{')'}}</div>"); | ||
|
||
ng1inNg2Module.bootstrap(element).ready(() => { | ||
expect(document.body.textContent).toEqual("ng1(ng2(ng1 WORKS!))"); | ||
async.done(); | ||
}); | ||
})); | ||
}); | ||
} | ||
|
||
@Component({selector: 'ng2'}) | ||
@View({template: `{{ 'NG2' }}`}) | ||
class SimpleComponent { | ||
} | ||
|
||
var ng1inNg2Module: UpgradeModule = createUpgradeModule(); | ||
|
||
@Component({selector: 'ng2-1'}) | ||
@View({ | ||
template: `{{ 'ng2(' }}<ng1></ng1>{{ ')' }}`, | ||
directives: [ng1inNg2Module.exportAsNg2Component('ng1')] | ||
}) | ||
class Ng2ContainsNg1 { | ||
} | ||
|
||
ng1inNg2Module.ng1Module.directive('ng1', () => { return {template: 'ng1 {{ "WORKS" }}!'}; }); | ||
ng1inNg2Module.importNg2Component(Ng2ContainsNg1); | ||
|
||
|
||
function html(html: string): Element { | ||
var body = document.body; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we use something like DOM.createHtmlDocument() here instead of the global object? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It has to be global DOM, otherwise the renderer can not get bootstrapped because we pass ids only (not reference). Would love to talk to @tbosch and redo this so that we don't have to do global. |
||
body.innerHTML = html; | ||
if (body.childNodes.length == 1 && body.firstChild instanceof HTMLElement) | ||
return <Element>body.firstChild; | ||
return body; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Every detector has a cached ref. Use _view.changeDetector.ref
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
thanks for the tip. fixed