forked from emberjs/ember.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instance.js
488 lines (392 loc) · 14.3 KB
/
instance.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/**
@module @ember/application
*/
import { get, set, computed } from '@ember/-internals/metal';
import * as environment from '@ember/-internals/browser-environment';
import EngineInstance from '@ember/engine/instance';
import { renderSettled } from '@ember/-internals/glimmer';
/**
The `ApplicationInstance` encapsulates all of the stateful aspects of a
running `Application`.
At a high-level, we break application boot into two distinct phases:
* Definition time, where all of the classes, templates, and other
dependencies are loaded (typically in the browser).
* Run time, where we begin executing the application once everything
has loaded.
Definition time can be expensive and only needs to happen once since it is
an idempotent operation. For example, between test runs and FastBoot
requests, the application stays the same. It is only the state that we want
to reset.
That state is what the `ApplicationInstance` manages: it is responsible for
creating the container that contains all application state, and disposing of
it once the particular test run or FastBoot request has finished.
@public
@class ApplicationInstance
@extends EngineInstance
*/
const ApplicationInstance = EngineInstance.extend({
/**
The `Application` for which this is an instance.
@property {Application} application
@private
*/
application: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
@private
@property {Object} customEvents
*/
customEvents: null,
/**
The root DOM element of the Application as an element or a
CSS selector.
@private
@property {String|DOMElement} rootElement
*/
rootElement: null,
init() {
this._super(...arguments);
this.application._watchInstance(this);
// Register this instance in the per-instance registry.
//
// Why do we need to register the instance in the first place?
// Because we need a good way for the root route (a.k.a ApplicationRoute)
// to notify us when it has created the root-most view. That view is then
// appended to the rootElement, in the case of apps, to the fixture harness
// in tests, or rendered to a string in the case of FastBoot.
this.register('-application-instance:main', this, { instantiate: false });
},
/**
Overrides the base `EngineInstance._bootSync` method with concerns relevant
to booting application (instead of engine) instances.
This method should only contain synchronous boot concerns. Asynchronous
boot concerns should eventually be moved to the `boot` method, which
returns a promise.
Until all boot code has been made asynchronous, we need to continue to
expose this method for use *internally* in places where we need to boot an
instance synchronously.
@private
*/
_bootSync(options) {
if (this._booted) {
return this;
}
options = new BootOptions(options);
this.setupRegistry(options);
if (options.rootElement) {
this.rootElement = options.rootElement;
} else {
this.rootElement = this.application.rootElement;
}
if (options.location) {
set(this.router, 'location', options.location);
}
this.application.runInstanceInitializers(this);
if (options.isInteractive) {
this.setupEventDispatcher();
}
this._booted = true;
return this;
},
setupRegistry(options) {
this.constructor.setupRegistry(this.__registry__, options);
},
router: computed(function () {
return this.lookup('router:main');
}).readOnly(),
/**
This hook is called by the root-most Route (a.k.a. the ApplicationRoute)
when it has finished creating the root View. By default, we simply take the
view and append it to the `rootElement` specified on the Application.
In cases like FastBoot and testing, we can override this hook and implement
custom behavior, such as serializing to a string and sending over an HTTP
socket rather than appending to DOM.
@param view {Ember.View} the root-most view
@deprecated
@private
*/
didCreateRootView(view) {
view.appendTo(this.rootElement);
},
/**
Tells the router to start routing. The router will ask the location for the
current URL of the page to determine the initial URL to start routing to.
To start the app at a specific URL, call `handleURL` instead.
@private
*/
startRouting() {
this.router.startRouting();
},
/**
Sets up the router, initializing the child router and configuring the
location before routing begins.
Because setup should only occur once, multiple calls to `setupRouter`
beyond the first call have no effect.
This is commonly used in order to confirm things that rely on the router
are functioning properly from tests that are primarily rendering related.
For example, from within [ember-qunit](https://github.com/emberjs/ember-qunit)'s
`setupRenderingTest` calling `this.owner.setupRouter()` would allow that
rendering test to confirm that any `<LinkTo></LinkTo>`'s that are rendered
have the correct URL.
@public
*/
setupRouter() {
this.router.setupRouter();
},
/**
Directs the router to route to a particular URL. This is useful in tests,
for example, to tell the app to start at a particular URL.
@param url {String} the URL the router should route to
@private
*/
handleURL(url) {
this.setupRouter();
return this.router.handleURL(url);
},
/**
@private
*/
setupEventDispatcher() {
let dispatcher = this.lookup('event_dispatcher:main');
let applicationCustomEvents = get(this.application, 'customEvents');
let instanceCustomEvents = get(this, 'customEvents');
let customEvents = Object.assign({}, applicationCustomEvents, instanceCustomEvents);
dispatcher.setup(customEvents, this.rootElement);
return dispatcher;
},
/**
Returns the current URL of the app instance. This is useful when your
app does not update the browsers URL bar (i.e. it uses the `'none'`
location adapter).
@public
@return {String} the current URL
*/
getURL() {
return this.router.url;
},
// `instance.visit(url)` should eventually replace `instance.handleURL()`;
// the test helpers can probably be switched to use this implementation too
/**
Navigate the instance to a particular URL. This is useful in tests, for
example, or to tell the app to start at a particular URL. This method
returns a promise that resolves with the app instance when the transition
is complete, or rejects if the transion was aborted due to an error.
@public
@param url {String} the destination URL
@return {Promise<ApplicationInstance>}
*/
visit(url) {
this.setupRouter();
let bootOptions = this.__container__.lookup('-environment:main');
let router = this.router;
let handleTransitionResolve = () => {
if (!bootOptions.options.shouldRender) {
// No rendering is needed, and routing has completed, simply return.
return this;
} else {
// Ensure that the visit promise resolves when all rendering has completed
return renderSettled().then(() => this);
}
};
let handleTransitionReject = (error) => {
if (error.error) {
throw error.error;
} else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) {
return router._routerMicrolib.activeTransition.then(
handleTransitionResolve,
handleTransitionReject
);
} else if (error.name === 'TransitionAborted') {
throw new Error(error.message);
} else {
throw error;
}
};
let location = get(router, 'location');
// Keeps the location adapter's internal URL in-sync
location.setURL(url);
// getURL returns the set url with the rootURL stripped off
return router
.handleURL(location.getURL())
.then(handleTransitionResolve, handleTransitionReject);
},
willDestroy() {
this._super(...arguments);
this.application._unwatchInstance(this);
},
});
ApplicationInstance.reopenClass({
/**
@private
@method setupRegistry
@param {Registry} registry
@param {BootOptions} options
*/
setupRegistry(registry, options = {}) {
if (!options.toEnvironment) {
options = new BootOptions(options);
}
registry.register('-environment:main', options.toEnvironment(), {
instantiate: false,
});
registry.register('service:-document', options.document, {
instantiate: false,
});
this._super(registry, options);
},
});
/**
A list of boot-time configuration options for customizing the behavior of
an `ApplicationInstance`.
This is an interface class that exists purely to document the available
options; you do not need to construct it manually. Simply pass a regular
JavaScript object containing the desired options into methods that require
one of these options object:
```javascript
MyApp.visit("/", { location: "none", rootElement: "#container" });
```
Not all combinations of the supported options are valid. See the documentation
on `Application#visit` for the supported configurations.
Internal, experimental or otherwise unstable flags are marked as private.
@class BootOptions
@namespace ApplicationInstance
@public
*/
class BootOptions {
constructor(options = {}) {
/**
Interactive mode: whether we need to set up event delegation and invoke
lifecycle callbacks on Components.
@property isInteractive
@type boolean
@default auto-detected
@private
*/
this.isInteractive = environment.hasDOM; // This default is overridable below
/**
@property _renderMode
@type string
@default false
@private
*/
this._renderMode = options._renderMode;
/**
Run in a full browser environment.
When this flag is set to `false`, it will disable most browser-specific
and interactive features. Specifically:
* It does not use `jQuery` to append the root view; the `rootElement`
(either specified as a subsequent option or on the application itself)
must already be an `Element` in the given `document` (as opposed to a
string selector).
* It does not set up an `EventDispatcher`.
* It does not run any `Component` lifecycle hooks (such as `didInsertElement`).
* It sets the `location` option to `"none"`. (If you would like to use
the location adapter specified in the app's router instead, you can also
specify `{ location: null }` to specifically opt-out.)
@property isBrowser
@type boolean
@default auto-detected
@public
*/
if (options.isBrowser !== undefined) {
this.isBrowser = Boolean(options.isBrowser);
} else {
this.isBrowser = environment.hasDOM;
}
if (!this.isBrowser) {
this.isInteractive = false;
this.location = 'none';
}
/**
Disable rendering completely.
When this flag is set to `false`, it will disable the entire rendering
pipeline. Essentially, this puts the app into "routing-only" mode. No
templates will be rendered, and no Components will be created.
@property shouldRender
@type boolean
@default true
@public
*/
if (options.shouldRender !== undefined) {
this.shouldRender = Boolean(options.shouldRender);
} else {
this.shouldRender = true;
}
if (!this.shouldRender) {
this.isInteractive = false;
}
/**
If present, render into the given `Document` object instead of the
global `window.document` object.
In practice, this is only useful in non-browser environment or in
non-interactive mode, because Ember's `jQuery` dependency is
implicitly bound to the current document, causing event delegation
to not work properly when the app is rendered into a foreign
document object (such as an iframe's `contentDocument`).
In non-browser mode, this could be a "`Document`-like" object as
Ember only interact with a small subset of the DOM API in non-
interactive mode. While the exact requirements have not yet been
formalized, the `SimpleDOM` library's implementation is known to
work.
@property document
@type Document
@default the global `document` object
@public
*/
if (options.document) {
this.document = options.document;
} else {
this.document = typeof document !== 'undefined' ? document : null;
}
/**
If present, overrides the application's `rootElement` property on
the instance. This is useful for testing environment, where you
might want to append the root view to a fixture area.
In non-browser mode, because Ember does not have access to jQuery,
this options must be specified as a DOM `Element` object instead of
a selector string.
See the documentation on `Application`'s `rootElement` for
details.
@property rootElement
@type String|Element
@default null
@public
*/
if (options.rootElement) {
this.rootElement = options.rootElement;
}
// Set these options last to give the user a chance to override the
// defaults from the "combo" options like `isBrowser` (although in
// practice, the resulting combination is probably invalid)
/**
If present, overrides the router's `location` property with this
value. This is useful for environments where trying to modify the
URL would be inappropriate.
@property location
@type string
@default null
@public
*/
if (options.location !== undefined) {
this.location = options.location;
}
if (options.isInteractive !== undefined) {
this.isInteractive = Boolean(options.isInteractive);
}
}
toEnvironment() {
// Do we really want to assign all of this!?
let env = Object.assign({}, environment);
// For compatibility with existing code
env.hasDOM = this.isBrowser;
env.isInteractive = this.isInteractive;
env._renderMode = this._renderMode;
env.options = this;
return env;
}
}
export default ApplicationInstance;