Skip to content

Commit 1221857

Browse files
committed
feat(bootstraping): application bootstrapping implementation.
Entry-point to bootstrapping is a rootComponent. The bootstrapping method, uses the component's selector to find the insertion element in the DOM, and attaches the component in its ShadowRoot.
1 parent f0d6464 commit 1221857

File tree

8 files changed

+271
-7
lines changed

8 files changed

+271
-7
lines changed

modules/core/src/application.js

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import {Injector, bind} from 'di/di';
2+
import {Type, FIELD, isBlank, isPresent, BaseException} from 'facade/lang';
3+
import {DOM, Element} from 'facade/dom';
4+
import {Compiler} from './compiler/compiler';
5+
import {ProtoView} from './compiler/view';
6+
import {ClosureMap} from 'change_detection/parser/closure_map';
7+
import {Parser} from 'change_detection/parser/parser';
8+
import {Lexer} from 'change_detection/parser/lexer';
9+
import {ChangeDetector} from 'change_detection/change_detector';
10+
import {WatchGroup} from 'change_detection/watch_group';
11+
import {TemplateLoader} from './compiler/template_loader';
12+
import {Reflector} from './compiler/reflector';
13+
import {AnnotatedType} from './compiler/annotated_type';
14+
import {ListWrapper} from 'facade/collection';
15+
16+
var _rootInjector: Injector;
17+
18+
// Contains everything that is safe to share between applications.
19+
var _rootBindings = [Compiler, TemplateLoader, Reflector, Parser, Lexer, ClosureMap];
20+
21+
export var appViewToken = new Object();
22+
export var appWatchGroupToken = new Object();
23+
export var appElementToken = new Object();
24+
export var appComponentAnnotatedTypeToken = new Object();
25+
export var appDocumentToken = new Object();
26+
27+
// Exported only for tests that need to overwrite default document binding.
28+
export function documentDependentBindings(appComponentType) {
29+
return [
30+
bind(appComponentAnnotatedTypeToken).toFactory((reflector) => {
31+
// TODO(rado): inspect annotation here and warn if there are bindings,
32+
// lightDomServices, and other component annotations that are skipped
33+
// for bootstrapping components.
34+
return reflector.annotatedType(appComponentType);
35+
}, [Reflector]),
36+
37+
bind(appElementToken).toFactory((appComponentAnnotatedType, appDocument) => {
38+
var selector = appComponentAnnotatedType.annotation.selector;
39+
var element = DOM.querySelector(appDocument, selector);
40+
if (isBlank(element)) {
41+
throw new BaseException(`The app selector "${selector}" did not match any elements`);
42+
}
43+
return element;
44+
}, [appComponentAnnotatedTypeToken, appDocumentToken]),
45+
46+
bind(appViewToken).toAsyncFactory((compiler, injector, appElement,
47+
appComponentAnnotatedType) => {
48+
return compiler.compile(appComponentAnnotatedType.type, null).then(
49+
(protoView) => {
50+
var appProtoView = ProtoView.createRootProtoView(protoView,
51+
appElement, appComponentAnnotatedType);
52+
// The light Dom of the app element is not considered part of
53+
// the angular application. Thus the context and lightDomInjector are
54+
// empty.
55+
return appProtoView.instantiate(new Object(), injector, null, true);
56+
});
57+
}, [Compiler, Injector, appElementToken, appComponentAnnotatedTypeToken]),
58+
59+
bind(appWatchGroupToken).toFactory((rootView) => rootView.watchGroup,
60+
[appViewToken]),
61+
bind(ChangeDetector).toFactory((appWatchGroup) =>
62+
new ChangeDetector(appWatchGroup), [appWatchGroupToken])
63+
];
64+
}
65+
66+
function _injectorBindings(appComponentType) {
67+
return ListWrapper.concat([bind(appDocumentToken).toValue(DOM.defaultDoc())],
68+
documentDependentBindings(appComponentType));
69+
}
70+
71+
// Multiple calls to this method are allowed. Each application would only share
72+
// _rootInjector, which is not user-configurable by design, thus safe to share.
73+
export function bootstrap(appComponentType: Type, bindings=null) {
74+
// TODO(rado): prepopulate template cache, so applications with only
75+
// index.html and main.js are possible.
76+
if (isBlank(_rootInjector)) _rootInjector = new Injector(_rootBindings);
77+
var appInjector = _rootInjector.createChild(_injectorBindings(
78+
appComponentType));
79+
if (isPresent(bindings)) appInjector = appInjector.createChild(bindings);
80+
return appInjector.asyncGet(ChangeDetector).then((cd) => {
81+
// TODO(rado): replace with zone.
82+
cd.detectChanges();
83+
return appInjector;
84+
});
85+
}

modules/core/src/compiler/compiler.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {CompileElement} from './pipeline/compile_element';
1313
import {createDefaultSteps} from './pipeline/default_steps';
1414
import {TemplateLoader} from './template_loader';
1515
import {AnnotatedType} from './annotated_type';
16+
import {Component} from '../annotations/component';
1617

1718
/**
1819
* The compiler loads and translates the html templates of components into
@@ -28,7 +29,8 @@ export class Compiler {
2829
}
2930

3031
createSteps(component:AnnotatedType):List<CompileStep> {
31-
var directives = component.annotation.template.directives;
32+
var annotation: Component = component.annotation;
33+
var directives = annotation.template.directives;
3234
var annotatedDirectives = ListWrapper.create();
3335
for (var i=0; i<directives.length; i++) {
3436
ListWrapper.push(annotatedDirectives, this._reflector.annotatedType(directives[i]));
@@ -51,7 +53,8 @@ export class Compiler {
5153
// - templateRoot string
5254
// - precompiled template
5355
// - ProtoView
54-
templateRoot = DOM.createTemplate(component.annotation.template.inline);
56+
var annotation: Component = component.annotation;
57+
templateRoot = DOM.createTemplate(annotation.template.inline);
5558
}
5659
var pipeline = new CompilePipeline(this.createSteps(component));
5760
var compileElements = pipeline.process(templateRoot);

modules/core/src/compiler/view.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,9 @@ export class ProtoView {
8383
this.elementsWithBindingCount = 0;
8484
}
8585

86-
instantiate(context, lightDomAppInjector:Injector, hostElementInjector: ElementInjector):View {
87-
var clone = DOM.clone(this.element);
86+
instantiate(context, lightDomAppInjector:Injector,
87+
hostElementInjector: ElementInjector, inPlace:boolean = false):View {
88+
var clone = inPlace ? this.element : DOM.clone(this.element);
8889
var elements;
8990
if (clone instanceof TemplateElement) {
9091
elements = ListWrapper.clone(DOM.querySelectorAll(clone.content, `.${NG_BINDING_CLASS}`));
@@ -260,6 +261,20 @@ export class ProtoView {
260261
}
261262
return injectors;
262263
}
264+
265+
// Create a rootView as if the compiler encountered <rootcmp></rootcmp>,
266+
// and the component template is already compiled into protoView.
267+
// Used for bootstrapping.
268+
static createRootProtoView(protoView: ProtoView,
269+
insertionElement, rootComponentAnnotatedType: AnnotatedType): ProtoView {
270+
var rootProtoView = new ProtoView(insertionElement, new ProtoWatchGroup());
271+
var binder = rootProtoView.bindElement(
272+
new ProtoElementInjector(null, 0, [rootComponentAnnotatedType.type], true));
273+
binder.componentDirective = rootComponentAnnotatedType;
274+
binder.nestedProtoView = protoView;
275+
DOM.addClass(insertionElement, 'ng-binding');
276+
return rootProtoView;
277+
}
263278
}
264279

265280
export class ElementPropertyMemento {

modules/core/src/core.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ export * from './annotations/directive';
55
export * from './annotations/component';
66
export * from './annotations/template_config';
77

8+
export * from './application';
9+
810
export * from 'change_detection/change_detector';
911
export * from 'change_detection/watch_group';
1012
export * from 'change_detection/record';
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import {describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach} from 'test_lib/test_lib';
2+
import {bootstrap, appDocumentToken, appElementToken, documentDependentBindings}
3+
from 'core/application';
4+
import {Component} from 'core/annotations/component';
5+
import {DOM} from 'facade/dom';
6+
import {ListWrapper} from 'facade/collection';
7+
import {PromiseWrapper} from 'facade/async';
8+
import {bind} from 'di/di';
9+
import {TemplateConfig} from 'core/annotations/template_config';
10+
11+
@Component({
12+
selector: 'hello-app',
13+
template: new TemplateConfig({
14+
inline: '{{greeting}} world!',
15+
directives: []
16+
})
17+
})
18+
class HelloRootCmp {
19+
constructor() {
20+
this.greeting = 'hello';
21+
}
22+
}
23+
24+
@Component({
25+
selector: 'hello-app-2',
26+
template: new TemplateConfig({
27+
inline: '{{greeting}} world, again!',
28+
directives: []
29+
})
30+
})
31+
class HelloRootCmp2 {
32+
constructor() {
33+
this.greeting = 'hello';
34+
}
35+
}
36+
37+
export function main() {
38+
var fakeDoc, el, el2;
39+
40+
beforeEach(() => {
41+
fakeDoc = DOM.createHtmlDocument();
42+
el = DOM.createElement('hello-app', fakeDoc);
43+
el2 = DOM.createElement('hello-app-2', fakeDoc);
44+
DOM.appendChild(fakeDoc.body, el);
45+
DOM.appendChild(fakeDoc.body, el2);
46+
});
47+
48+
function testBindings(appComponentType) {
49+
return ListWrapper.concat([bind(appDocumentToken).toValue(fakeDoc),
50+
], documentDependentBindings(appComponentType));
51+
}
52+
53+
describe('bootstrap factory method', () => {
54+
it('should throw if no element is found', (done) => {
55+
var injectorPromise = bootstrap(HelloRootCmp);
56+
PromiseWrapper.then(injectorPromise, null, (reason) => {
57+
expect(reason.message).toContain(
58+
'The app selector "hello-app" did not match any elements');
59+
done();
60+
});
61+
});
62+
63+
it('should create an injector promise', () => {
64+
var injectorPromise = bootstrap(HelloRootCmp, testBindings(HelloRootCmp));
65+
expect(injectorPromise).not.toBe(null);
66+
});
67+
68+
it('should resolve an injector promise and contain bindings', (done) => {
69+
var injectorPromise = bootstrap(HelloRootCmp, testBindings(HelloRootCmp));
70+
injectorPromise.then((injector) => {
71+
expect(injector.get(appElementToken)).toBe(el);
72+
done();
73+
});
74+
});
75+
76+
it('should display hello world', (done) => {
77+
var injectorPromise = bootstrap(HelloRootCmp, testBindings(HelloRootCmp));
78+
injectorPromise.then((injector) => {
79+
expect(injector.get(appElementToken)
80+
.shadowRoot.childNodes[0].nodeValue).toEqual('hello world!');
81+
done();
82+
});
83+
});
84+
85+
it('should support multiple calls to bootstrap', (done) => {
86+
var injectorPromise1 = bootstrap(HelloRootCmp, testBindings(HelloRootCmp));
87+
var injectorPromise2 = bootstrap(HelloRootCmp2, testBindings(HelloRootCmp2));
88+
PromiseWrapper.all([injectorPromise1, injectorPromise2]).then((injectors) => {
89+
expect(injectors[0].get(appElementToken)
90+
.shadowRoot.childNodes[0].nodeValue).toEqual('hello world!');
91+
expect(injectors[1].get(appElementToken)
92+
.shadowRoot.childNodes[0].nodeValue).toEqual('hello world, again!');
93+
done();
94+
});
95+
});
96+
});
97+
}

modules/core/test/compiler/view_spec.js

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,15 @@ import {View} from 'core/compiler/view';
1717

1818
export function main() {
1919
describe('view', function() {
20-
var parser, closureMap;
20+
var parser, closureMap, someComponentDirective;
2121

22-
beforeEach( () => {
22+
beforeEach(() => {
2323
closureMap = new ClosureMap();
2424
parser = new Parser(new Lexer(), closureMap);
25+
someComponentDirective = new Reflector().annotatedType(SomeComponent);
2526
});
2627

28+
2729
describe('ProtoView.instantiate', function() {
2830

2931
function createCollectDomNodesTestCases(useTemplateElement:boolean) {
@@ -92,6 +94,22 @@ export function main() {
9294
});
9395
}
9496

97+
describe('inplace instantiation', () => {
98+
it('should be supported.', () => {
99+
var template = createElement('<div></div>')
100+
var view = new ProtoView(template, new ProtoWatchGroup())
101+
.instantiate(null, null, null, true);
102+
expect(view.nodes[0]).toBe(template);
103+
});
104+
105+
it('should be off by default.', () => {
106+
var template = createElement('<div></div>')
107+
var view = new ProtoView(template, new ProtoWatchGroup())
108+
.instantiate(null, null, null);
109+
expect(view.nodes[0]).not.toBe(template);
110+
});
111+
});
112+
95113
describe('collect dom nodes with a regular element as root', () => {
96114
createCollectDomNodesTestCases(false);
97115
});
@@ -158,7 +176,7 @@ export function main() {
158176
function createComponentWithSubPV(subProtoView) {
159177
var pv = new ProtoView(createElement('<cmp class="ng-binding"></cmp>'), new ProtoWatchGroup());
160178
var binder = pv.bindElement(new ProtoElementInjector(null, 0, [SomeComponent], true));
161-
binder.componentDirective = new Reflector().annotatedType(SomeComponent);
179+
binder.componentDirective = someComponentDirective;
162180
binder.nestedProtoView = subProtoView;
163181
return pv;
164182
}
@@ -253,7 +271,26 @@ export function main() {
253271
expect(view.elementInjectors[0].get(SomeDirective).prop).toEqual('buz');
254272
});
255273
});
274+
});
275+
276+
describe('protoView createRootProtoView', () => {
277+
var el, pv;
278+
beforeEach(() => {
279+
el = DOM.createElement('div');
280+
pv = new ProtoView(createElement('<div>hi</div>'), new ProtoWatchGroup());
281+
});
256282

283+
it('should create the root component when instantiated', () => {
284+
var rootProtoView = ProtoView.createRootProtoView(pv, el, someComponentDirective);
285+
var view = rootProtoView.instantiate(null, new Injector([]), null, true);
286+
expect(view.rootElementInjectors[0].get(SomeComponent)).not.toBe(null);
287+
});
288+
289+
it('should inject the protoView into the shadowDom', () => {
290+
var rootProtoView = ProtoView.createRootProtoView(pv, el, someComponentDirective);
291+
var view = rootProtoView.instantiate(null, new Injector([]), null, true);
292+
expect(el.shadowRoot.childNodes[0].childNodes[0].nodeValue).toEqual('hi');
293+
});
257294
});
258295
});
259296
}

modules/facade/src/dom.dart

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ class DOM {
1717
static query(selector) {
1818
return document.querySelector(selector);
1919
}
20+
static Element querySelector(el, String selector) {
21+
return el.querySelector(selector);
22+
}
2023
static ElementList querySelectorAll(el, String selector) {
2124
return el.querySelectorAll(selector);
2225
}
@@ -52,6 +55,10 @@ class DOM {
5255
t.setInnerHtml(html, treeSanitizer:identitySanitizer);
5356
return t;
5457
}
58+
static createElement(tagName, [doc=null]) {
59+
if (doc == null) doc = document;
60+
return doc.createElement(tagName);
61+
}
5562
static clone(Node node) {
5663
return node.clone(true);
5764
}
@@ -82,4 +89,10 @@ class DOM {
8289
static Node templateAwareRoot(Element el) {
8390
return el is TemplateElement ? el.content : el;
8491
}
92+
static HtmlDocument createHtmlDocument() {
93+
return document.implementation.createHtmlDocument('fakeTitle');
94+
}
95+
static HtmlDocument defaultDoc() {
96+
return document;
97+
}
8598
}

modules/facade/src/dom.es6

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ export class DOM {
1313
static query(selector) {
1414
return document.querySelector(selector);
1515
}
16+
static querySelector(el, selector:string):Node {
17+
return el.querySelector(selector);
18+
}
1619
static querySelectorAll(el, selector:string):NodeList {
1720
return el.querySelectorAll(selector);
1821
}
@@ -48,6 +51,9 @@ export class DOM {
4851
t.innerHTML = html;
4952
return t;
5053
}
54+
static createElement(tagName, doc=document) {
55+
return doc.createElement(tagName);
56+
}
5157
static clone(node:Node) {
5258
return node.cloneNode(true);
5359
}
@@ -84,4 +90,10 @@ export class DOM {
8490
static templateAwareRoot(el:Element):Node {
8591
return el instanceof TemplateElement ? el.content : el;
8692
}
93+
static createHtmlDocument() {
94+
return document.implementation.createHTMLDocument();
95+
}
96+
static defaultDoc() {
97+
return document;
98+
}
8799
}

0 commit comments

Comments
 (0)