-
-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathsingle-spa-angular.ts
More file actions
188 lines (156 loc) · 7.49 KB
/
single-spa-angular.ts
File metadata and controls
188 lines (156 loc) · 7.49 KB
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
import type { ApplicationRef, NgModuleRef, NgZone } from '@angular/core';
import type { LifeCycles } from 'single-spa';
import { getContainerElementAndSetTemplate } from '@single-spa-community/angular/internals';
import { SingleSpaPlatformLocation } from './extra-providers';
import type { SingleSpaAngularOptions, BootstrappedSingleSpaAngularOptions } from './types';
const defaultOptions = {
// Required options that will be set by the library consumer.
NgZone: null!,
bootstrapFunction: null!,
template: null!,
// Optional options
Router: undefined,
domElementGetter: undefined, // only optional if you provide a domElementGetter as a custom prop
updateFunction: () => Promise.resolve(),
bootstrappedNgModuleRefOrAppRef: null,
};
// This will be provided through Terser global definitions by Angular CLI. This will
// help to tree-shake away the code unneeded for production bundles.
declare const ngDevMode: boolean;
const NG_DEV_MODE = typeof ngDevMode === 'undefined' || ngDevMode;
export function singleSpaAngular<T>(userOptions: SingleSpaAngularOptions<T>): LifeCycles<T> {
if (NG_DEV_MODE && typeof userOptions !== 'object') {
throw Error('single-spa-angular requires a configuration object');
}
const options: SingleSpaAngularOptions = {
...defaultOptions,
...userOptions,
};
if (NG_DEV_MODE && typeof options.bootstrapFunction !== 'function') {
throw Error('single-spa-angular must be passed an options.bootstrapFunction');
}
if (NG_DEV_MODE && typeof options.template !== 'string') {
throw Error('single-spa-angular must be passed options.template string');
}
if (NG_DEV_MODE && !options.NgZone) {
throw Error(`single-spa-angular must be passed the NgZone option`);
}
if (NG_DEV_MODE && options.Router && !options.NavigationStart) {
// We call `console.warn` except of throwing `new Error()` since this will not
// be a breaking change.
console.warn(`single-spa-angular must be passed the NavigationStart option`);
}
return {
bootstrap: bootstrap.bind(null, options as BootstrappedSingleSpaAngularOptions),
mount: mount.bind(null, options),
unmount: unmount.bind(null, options as BootstrappedSingleSpaAngularOptions),
update: options.updateFunction,
};
}
async function bootstrap(options: BootstrappedSingleSpaAngularOptions): Promise<void> {
// Angular provides an opportunity to develop `zone-less` application, where developers
// have to trigger change detection manually.
// See https://angular.io/guide/zone#noopzone
if (options.NgZone === 'noop') {
return;
}
// Note that we have to make it a noop function because it's a static property and not
// an instance property. We're unable to configure it for multiple apps when dependencies
// are shared and reference the same `NgZone` class. We can't determine where this function
// is being executed or under which application, making it difficult to assert whether this
// app is running under its zone.
options.NgZone.assertInAngularZone = () => {};
options.NgZone.assertNotInAngularZone = () => {};
options.routingEventListener = () => {
options.bootstrappedNgZone!.run(() => {
// See https://github.com/single-spa/single-spa-angular/issues/86
// Zone is unaware of the single-spa navigation change and so Angular change detection doesn't work
// unless we tell Zone that something happened
});
};
}
async function mount(
options: SingleSpaAngularOptions,
props: any,
): Promise<NgModuleRef<any> | ApplicationRef> {
getContainerElementAndSetTemplate(options, props);
const bootstrapPromise = options.bootstrapFunction(props);
if (NG_DEV_MODE && !(bootstrapPromise instanceof Promise)) {
throw Error(
`single-spa-angular: the options.bootstrapFunction must return a promise, but instead returned a '${typeof bootstrapPromise}' that is not a Promise`,
);
}
const ngModuleRefOrAppRef: NgModuleRef<any> | ApplicationRef = await bootstrapPromise;
if (NG_DEV_MODE) {
if (!ngModuleRefOrAppRef || typeof ngModuleRefOrAppRef.destroy !== 'function') {
throw Error(
`single-spa-angular: the options.bootstrapFunction returned a promise that did not resolve with a valid Angular module or ApplicationRef. Did you call platformBrowserDynamic().bootstrapModule() correctly?`,
);
}
}
const singleSpaPlatformLocation = ngModuleRefOrAppRef.injector.get(
SingleSpaPlatformLocation,
null,
);
const ngZoneEnabled = options.NgZone !== 'noop';
// The user has to provide `BrowserPlatformLocation` only if his application uses routing.
// So if he provided `Router` but didn't provide `BrowserPlatformLocation` then we have to inform him.
// Also `getSingleSpaExtraProviders()` function should be called only if the user doesn't use
// `zone-less` change detection, if `NgZone` is `noop` then we can skip it.
if (NG_DEV_MODE && ngZoneEnabled && options.Router && singleSpaPlatformLocation === null) {
throw new Error(`
single-spa-angular: could not retrieve extra providers from the platform injector. Did you call platformBrowserDynamic(getSingleSpaExtraProviders()).bootstrapModule()?
`);
}
const bootstrappedOptions = options as BootstrappedSingleSpaAngularOptions;
if (ngZoneEnabled) {
const ngZone: NgZone = ngModuleRefOrAppRef.injector.get(options.NgZone);
// `NgZone` can be enabled but routing may not be used thus `getSingleSpaExtraProviders()`
// function was not called.
if (singleSpaPlatformLocation !== null) {
skipLocationChangeOnNonImperativeRoutingTriggers(ngModuleRefOrAppRef, options);
}
bootstrappedOptions.bootstrappedNgZone = ngZone;
window.addEventListener('single-spa:routing-event', bootstrappedOptions.routingEventListener!);
}
bootstrappedOptions.bootstrappedNgModuleRefOrAppRef = ngModuleRefOrAppRef;
return ngModuleRefOrAppRef;
}
function unmount(options: BootstrappedSingleSpaAngularOptions): Promise<void> {
return Promise.resolve().then(() => {
if (options.routingEventListener) {
window.removeEventListener('single-spa:routing-event', options.routingEventListener);
}
options.bootstrappedNgModuleRefOrAppRef!.destroy();
options.bootstrappedNgModuleRefOrAppRef = null;
});
}
function skipLocationChangeOnNonImperativeRoutingTriggers(
ngModuleRefOrAppRef: NgModuleRef<any> | ApplicationRef,
options: SingleSpaAngularOptions,
): void {
const { NavigationStart, Router } = options;
if (!NavigationStart || !Router) {
// As discussed we don't do anything right now if the developer doesn't provide
// `options.NavigationStart` since this might be a breaking change.
return;
}
const router = ngModuleRefOrAppRef.injector.get(Router);
const subscription = router.events.subscribe((event: any) => {
if (event instanceof NavigationStart) {
const currentNavigation = router.getCurrentNavigation();
// This listener will be set up for each Angular application
// that has routing capabilities.
// We set `skipLocationChange` for each non-imperative navigation,
// Angular router checks under the hood if it has to change
// the browser URL or not.
// If `skipLocationChange` is truthy then Angular router will not call
// `setBrowserUrl()` which calls `history.replaceState()` and dispatches `popstate` event.
if (currentNavigation.trigger !== 'imperative') {
currentNavigation.extras.skipLocationChange = true;
currentNavigation.extras.replaceUrl = false;
}
}
});
ngModuleRefOrAppRef.onDestroy(() => subscription.unsubscribe());
}