-
-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathplatform-common.ts
382 lines (319 loc) · 12.4 KB
/
platform-common.ts
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
// Initial imports and polyfills
import "tns-core-modules/globals";
// Require application early to work around a circular import
import "tns-core-modules/application";
import "./zone-js/dist/zone-nativescript";
import "./polyfills/array";
import "./polyfills/console";
import { profile, uptime } from "tns-core-modules/profiling";
import "./dom-adapter";
import {
Type,
Injector,
CompilerOptions,
PlatformRef,
NgModuleFactory,
NgModuleRef,
EventEmitter,
Sanitizer,
InjectionToken,
StaticProvider,
} from "@angular/core";
import { DOCUMENT } from "@angular/common";
import { bootstrapLog, bootstrapLogError, isLogEnabled } from "./trace";
import { defaultPageFactoryProvider, setRootPage, PageFactory, PAGE_FACTORY } from "./platform-providers";
import { AppHostView } from "./app-host-view";
import {
setCssFileName,
run as applicationRun,
_resetRootView as applicationRerun,
on,
launchEvent,
LaunchEventData,
exitEvent,
ApplicationEventData,
} from "tns-core-modules/application";
import { TextView } from "tns-core-modules/ui/text-view";
import "nativescript-intl";
import { Color, View } from "tns-core-modules/ui/core/view/view";
import { Frame } from "tns-core-modules/ui/frame";
export const onBeforeLivesync = new EventEmitter<NgModuleRef<any>>();
export const onAfterLivesync = new EventEmitter<{ moduleRef?: NgModuleRef<any>; error?: Error }>();
let lastBootstrappedModule: WeakRef<NgModuleRef<any>>;
type BootstrapperAction = () => Promise<NgModuleRef<any>>;
// Work around a TS bug requiring an import of OpaqueToken without using it
if ((<any>global).___TS_UNUSED) {
(() => {
return InjectionToken;
})();
}
// tslint:disable:max-line-length
/**
* Options to be passed when HMR is enabled
*/
export interface HmrOptions {
/**
* A factory function that returns either Module type or NgModuleFactory type.
* This needs to be a factory function as the types will change when modules are replaced.
*/
moduleTypeFactory?: () => Type<any> | NgModuleFactory<any>;
/**
* A livesync callback that will be called instead of the original livesync.
* It gives the HMR a hook to apply the module replacement.
* @param bootstrapPlatform - A bootstrap callback to be called after HMR is done. It will bootstrap a new angular app within the exisiting platform, using the moduleTypeFactory to get the Module or NgModuleFactory to be used.
*/
livesyncCallback: (bootstrapPlatform: () => void) => void;
}
// tslint:enable:max-line-length
export interface AppOptions {
bootInExistingPage?: boolean;
cssFile?: string;
startPageActionBarHidden?: boolean;
createFrameOnBootstrap?: boolean;
hmrOptions?: HmrOptions;
}
export type PlatformFactory = (extraProviders?: StaticProvider[]) => PlatformRef;
export class NativeScriptSanitizer extends Sanitizer {
sanitize(_context: any, value: string): string {
return value;
}
}
export class NativeScriptDocument {
// Required by the AnimationDriver
public body: any = {
isOverride: true,
};
createElement(tag: string) {
throw new Error("NativeScriptDocument is not DOM Document. There is no createElement() method.");
}
}
export const COMMON_PROVIDERS = [
defaultPageFactoryProvider,
{ provide: Sanitizer, useClass: NativeScriptSanitizer, deps: [] },
{ provide: DOCUMENT, useClass: NativeScriptDocument, deps: [] },
];
export class NativeScriptPlatformRef extends PlatformRef {
private _bootstrapper: BootstrapperAction;
constructor(private platform: PlatformRef, private appOptions: AppOptions = {}) {
super();
}
@profile
bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>): Promise<NgModuleRef<M>> {
this._bootstrapper = () => {
let bootstrapFactory = moduleFactory;
if (this.appOptions.hmrOptions) {
bootstrapFactory = <NgModuleFactory<M>>this.appOptions.hmrOptions.moduleTypeFactory();
}
return this.platform.bootstrapModuleFactory(bootstrapFactory);
};
this.bootstrapApp();
return null; // Make the compiler happy
}
@profile
bootstrapModule<M>(
moduleType: Type<M>,
compilerOptions: CompilerOptions | CompilerOptions[] = []
): Promise<NgModuleRef<M>> {
this._bootstrapper = () => {
let bootstrapType = moduleType;
if (this.appOptions.hmrOptions) {
bootstrapType = <Type<M>>this.appOptions.hmrOptions.moduleTypeFactory();
}
return this.platform.bootstrapModule(bootstrapType, compilerOptions);
};
this.bootstrapApp();
return null; // Make the compiler happy
}
@profile
private bootstrapApp() {
(<any>global).__onLiveSyncCore = () => {
if (this.appOptions.hmrOptions) {
this.appOptions.hmrOptions.livesyncCallback(() => this._livesync());
} else {
this._livesync();
}
};
if (this.appOptions && typeof this.appOptions.cssFile === "string") {
setCssFileName(this.appOptions.cssFile);
}
this.bootstrapNativeScriptApp();
}
onDestroy(callback: () => void): void {
this.platform.onDestroy(callback);
}
get injector(): Injector {
return this.platform.injector;
}
destroy(): void {
this.platform.destroy();
}
get destroyed(): boolean {
return this.platform.destroyed;
}
@profile
private bootstrapNativeScriptApp() {
const autoCreateFrame = !!this.appOptions.createFrameOnBootstrap;
let tempAppHostView: AppHostView;
let rootContent: View;
if (autoCreateFrame) {
const { page, frame } = this.createFrameAndPage(false);
setRootPage(page);
rootContent = frame;
} else {
// Create a temp page for root of the renderer
tempAppHostView = new AppHostView();
setRootPage(<any>tempAppHostView);
}
if (isLogEnabled()) {
bootstrapLog("NativeScriptPlatform bootstrap started.");
}
const launchCallback = profile(
"nativescript-angular/platform-common.launchCallback",
(args: LaunchEventData) => {
if (isLogEnabled()) {
bootstrapLog("Application launch event fired");
}
let bootstrapPromiseCompleted = false;
this._bootstrapper().then(
moduleRef => {
bootstrapPromiseCompleted = true;
if (isLogEnabled()) {
bootstrapLog(`Angular bootstrap bootstrap done. uptime: ${uptime()}`);
}
if (!autoCreateFrame) {
rootContent = tempAppHostView.content;
}
lastBootstrappedModule = new WeakRef(moduleRef);
},
err => {
bootstrapPromiseCompleted = true;
const errorMessage = err.message + "\n\n" + err.stack;
if (isLogEnabled()) {
bootstrapLogError("ERROR BOOTSTRAPPING ANGULAR");
}
if (isLogEnabled()) {
bootstrapLogError(errorMessage);
}
rootContent = this.createErrorUI(errorMessage);
}
);
if (isLogEnabled()) {
bootstrapLog("bootstrapAction called, draining micro tasks queue. Root: " + rootContent);
}
(<any>global).Zone.drainMicroTaskQueue();
if (isLogEnabled()) {
bootstrapLog("bootstrapAction called, draining micro tasks queue finished! Root: " + rootContent);
}
if (!bootstrapPromiseCompleted) {
const errorMessage = "Bootstrap promise didn't resolve";
if (isLogEnabled()) {
bootstrapLogError(errorMessage);
}
rootContent = this.createErrorUI(errorMessage);
}
args.root = rootContent;
}
);
const exitCallback = profile(
"nativescript-angular/platform-common.exitCallback", (args: ApplicationEventData) => {
const androidActivity = args.android;
if (androidActivity && !androidActivity.isFinishing()) {
// Exit event was triggered as a part of a restart of the app.
return;
}
const lastModuleRef = lastBootstrappedModule ? lastBootstrappedModule.get() : null;
if (lastModuleRef) {
// Make sure the module is only destroyed once
lastBootstrappedModule = null;
lastModuleRef.destroy();
}
if (!autoCreateFrame) {
rootContent = null;
}
}
);
on(launchEvent, launchCallback);
on(exitEvent, exitCallback);
applicationRun();
}
@profile
public _livesync() {
if (isLogEnabled()) {
bootstrapLog("Angular livesync started.");
}
const lastModuleRef = lastBootstrappedModule ? lastBootstrappedModule.get() : null;
onBeforeLivesync.next(lastModuleRef);
if (lastModuleRef) {
lastModuleRef.destroy();
}
const autoCreateFrame = !!this.appOptions.createFrameOnBootstrap;
let tempAppHostView: AppHostView;
let rootContent: View;
if (autoCreateFrame) {
const { page, frame } = this.createFrameAndPage(true);
setRootPage(page);
rootContent = frame;
} else {
// Create a temp page for root of the renderer
tempAppHostView = new AppHostView();
setRootPage(<any>tempAppHostView);
}
let bootstrapPromiseCompleted = false;
this._bootstrapper().then(
moduleRef => {
bootstrapPromiseCompleted = true;
if (isLogEnabled()) {
bootstrapLog("Angular livesync done.");
}
onAfterLivesync.next({ moduleRef });
if (!autoCreateFrame) {
rootContent = tempAppHostView.content;
}
lastBootstrappedModule = new WeakRef(moduleRef);
},
error => {
bootstrapPromiseCompleted = true;
if (isLogEnabled()) {
bootstrapLogError("ERROR LIVESYNC BOOTSTRAPPING ANGULAR");
}
const errorMessage = error.message + "\n\n" + error.stack;
if (isLogEnabled()) {
bootstrapLogError(errorMessage);
}
rootContent = this.createErrorUI(errorMessage);
onAfterLivesync.next({ error });
}
);
if (isLogEnabled()) {
bootstrapLog("livesync bootstrapAction called, draining micro tasks queue. Root: " + rootContent);
}
(<any>global).Zone.drainMicroTaskQueue();
if (isLogEnabled()) {
bootstrapLog("livesync bootstrapAction called, draining micro tasks queue finished! Root: " + rootContent);
}
if (!bootstrapPromiseCompleted) {
const result = "Livesync bootstrap promise didn't resolve";
if (isLogEnabled()) {
bootstrapLogError(result);
}
rootContent = this.createErrorUI(result);
onAfterLivesync.next({ error: new Error(result) });
}
applicationRerun({
create: () => rootContent,
});
}
private createErrorUI(message: string): View {
const errorTextBox = new TextView();
errorTextBox.text = message;
errorTextBox.color = new Color("red");
return errorTextBox;
}
private createFrameAndPage(isLivesync: boolean) {
const frame = new Frame();
const pageFactory: PageFactory = this.platform.injector.get(PAGE_FACTORY);
const page = pageFactory({ isBootstrap: true, isLivesync });
frame.navigate({ create: () => { return page; } });
return { page, frame };
}
}