Repository navigation
Expand file tree
/
Copy pathnavigator.js
More file actions
executable file
·382 lines (328 loc) · 11.4 KB
/
Copy pathnavigator.js
File metadata and controls
executable file
·382 lines (328 loc) · 11.4 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
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
import { each, isArray, isEqual, isPlainObject, noop } from '@semantic-ui/utils';
import { IS_NAVIGATOR } from './internal-helpers/identity.js';
// the platform seam: window.navigation projected as plain fields, the verbs, the filter, and the
// moments handed to the router by name. nothing here decides a route or holds one
export class Navigator {
// brand navigator
get [IS_NAVIGATOR]() {
return true;
}
static [Symbol.hasInstance](value) {
return !!value?.[IS_NAVIGATOR];
}
constructor(router) {
this.router = router;
// per instance, so two routers on one page never claim each other's navigations
this.infoKey = Symbol('nav-router/info');
this.attached = false;
this.entry = null;
this.entries = [];
this.activation = null;
this.transition = null;
this.handleNavigate = (event) => this.onNavigate(event);
this.handleEntryChange = (event) => this.onEntryChange(event);
this.handleSuccess = (event) => this.onSuccess(event);
this.handleError = (event) => this.onError(event);
this.handlePageShow = (event) => this.onPageShow(event);
}
/*******************************
Lifecycle
*******************************/
attach() {
if (this.attached) {
return;
}
const nav = globalThis.navigation;
if (nav) {
nav.addEventListener('navigate', this.handleNavigate);
nav.addEventListener('currententrychange', this.handleEntryChange);
nav.addEventListener('navigatesuccess', this.handleSuccess);
nav.addEventListener('navigateerror', this.handleError);
}
if (globalThis.window) {
globalThis.window.addEventListener('pageshow', this.handlePageShow);
}
this.attached = true;
this.updateEntries();
// a back or forward pressed before this listener existed left activation and currentEntry apart
if (nav?.activation?.entry?.key && nav.currentEntry?.key && nav.activation.entry.key !== nav.currentEntry.key) {
this.onEntryChange({ navigationType: 'traverse', from: nav.activation.entry });
}
}
detach() {
if (!this.attached) {
return;
}
const nav = globalThis.navigation;
if (nav) {
nav.removeEventListener('navigate', this.handleNavigate);
nav.removeEventListener('currententrychange', this.handleEntryChange);
nav.removeEventListener('navigatesuccess', this.handleSuccess);
nav.removeEventListener('navigateerror', this.handleError);
}
if (globalThis.window) {
globalThis.window.removeEventListener('pageshow', this.handlePageShow);
}
this.attached = false;
}
/*******************************
Platform Reads
*******************************/
// the platform's current truth, re-read at every moment that can move it
updateEntries() {
const nav = globalThis.navigation;
this.entry = nav?.currentEntry ?? null;
this.entries = nav?.entries?.() ?? [];
this.activation = nav?.activation ?? null;
each(this.entries, (entry) => {
// the entry's own handler slot, so binding again binds once
if (entry) {
entry.ondispose = () => this.onDispose(entry);
}
});
}
// back inside the app: the previous entry is same-document and one of ours
get canGoBack() {
const nav = globalThis.navigation;
if (!nav?.canGoBack) {
return false;
}
const currentIndex = nav.currentEntry?.index ?? -1;
if (currentIndex > 0) {
const previous = (nav.entries?.() ?? [])[currentIndex - 1];
if (!previous || previous.sameDocument === false) {
return false;
}
if (previous.url && !this.router.match(previous.url)) {
return false;
}
}
return true;
}
get canGoForward() {
return Boolean(globalThis.navigation?.canGoForward);
}
/*******************************
Platform Writes
*******************************/
navigate(url, { state, info, history = 'auto', resetScroll = true, resetFocus = true } = {}) {
const nav = globalThis.navigation;
if (!nav) {
return this.documentLoad(
() => (history === 'replace' ? globalThis.location.replace(url) : globalThis.location.assign(url)),
);
}
// a replace without state would wipe the entry's memory, and auto becomes a replace on the same url
const sameUrl = history === 'auto' && globalThis.location
&& new URL(url, globalThis.location.href).href === nav.currentEntry?.url;
const resolvedState = state === undefined && (history === 'replace' || sameUrl)
? nav.currentEntry?.getState?.()
: state;
return this.catchNavigation(
nav.navigate(url, {
state: resolvedState,
info: this.tagInfo(info, { resetScroll, resetFocus }),
history,
}),
);
}
reload({ state, info } = {}) {
const nav = globalThis.navigation;
if (!nav) {
return this.documentLoad(() => globalThis.location.reload());
}
const resolvedState = state === undefined ? nav.currentEntry?.getState?.() : state;
return this.catchNavigation(
nav.reload({
state: resolvedState,
info: this.tagInfo(info, { reload: true, resetScroll: false, resetFocus: false }),
}),
);
}
back(fallbackUrl) {
if (this.canGoBack) {
return this.catchNavigation(globalThis.navigation.back());
}
return this.navigate(fallbackUrl ?? (this.router.config.base || '/'), { history: 'push' });
}
forward() {
if (this.canGoForward) {
return this.catchNavigation(globalThis.navigation.forward());
}
return this.catchNavigation();
}
traverseTo(key, { info } = {}) {
return this.catchNavigation(
globalThis.navigation?.traverseTo?.(key, {
info: this.tagInfo(info, { traverse: true }),
}),
);
}
tagInfo(info, meta) {
return {
...(isPlainObject(info) ? info : (info !== undefined ? { value: info } : {})),
[this.infoKey]: meta,
};
}
// the platform marks finished as handled and committed not, so both are caught here
catchNavigation(result) {
if (!result) {
return { committed: Promise.resolve(), finished: Promise.resolve() };
}
result.committed?.catch(noop);
result.finished?.catch(noop);
return result;
}
// the platform's own shape for a navigation that leaves the document: promises that never settle
documentLoad(load) {
load();
return { committed: new Promise(noop), finished: new Promise(noop) };
}
deferNavigate(url, options) {
const timer = setTimeout(() => {
this.router.timers.delete(timer);
this.navigate(url, options);
}, 0);
this.router.timers.add(timer);
}
/*******************************
Scroll Memory
*******************************/
// the platform restores the viewport and nothing else. the containers router.config.restoreScroll
// names ride the entry's state, saved on the way out and put back on a traverse
saveScroll() {
const selectors = this.router.config.restoreScroll;
const nav = globalThis.navigation;
if (!selectors || !globalThis.document || !nav?.currentEntry) {
return;
}
const offsets = {};
each(isArray(selectors) ? selectors : [selectors], (selector) => {
const element = globalThis.document.querySelector(selector);
if (element) {
offsets[selector] = { top: element.scrollTop, left: element.scrollLeft };
}
});
nav.updateCurrentEntry({ state: { ...(nav.currentEntry.getState?.() ?? {}), scroll: offsets } });
}
restoreScroll(entry) {
const saved = entry?.getState?.()?.scroll;
if (!saved || !globalThis.document) {
return;
}
each(saved, (offset, selector) => {
const element = globalThis.document.querySelector(selector);
if (element && offset) {
element.scrollTop = offset.top ?? 0;
element.scrollLeft = offset.left ?? 0;
}
});
}
/*******************************
Interception
*******************************/
onNavigate(event) {
if (!this.shouldIntercept(event)) {
return;
}
const matched = this.router.match(event.destination.url);
if (!matched) {
return;
}
const { current } = this.router;
const isSameRoute = current?.route === matched.route && isEqual(current?.params, matched.params);
if (event.hashChange && isSameRoute && isEqual(current?.query, matched.query)) {
return;
}
// the entry being left is still currentEntry here and not after commit
this.saveScroll();
const meta = event.info?.[this.infoKey];
const isQueryOnlyChange = isSameRoute && !isEqual(current?.query, matched.query);
const resetScroll = isQueryOnlyChange ? false : (meta?.resetScroll ?? true);
const resetFocus = isQueryOnlyChange ? false : (meta?.resetFocus ?? true);
this.transition = {
navigationType: event.navigationType,
from: this.entry,
destination: event.destination,
url: matched.url,
};
this.router.intercepted(matched, event);
let work = null;
let precommitRan = false;
const getWork = () => (work ??= this.router.begin(matched, event));
const interceptOptions = {
scroll: resetScroll ? 'after-transition' : 'manual',
focusReset: resetFocus ? 'after-transition' : 'manual',
handler: () => this.router.afterCommit(getWork(), event, { precommitRan }),
};
if (event.cancelable) {
interceptOptions.precommitHandler = (controller) => {
precommitRan = true;
return this.router.beforeCommit(getWork(), event, controller);
};
}
// intercept before any route code runs, so a throwing cascade can never leave the navigation to the browser
event.intercept(interceptOptions);
getWork();
}
shouldIntercept(event) {
if (!event?.canIntercept || event.downloadRequest != null || event.formData != null) {
return false;
}
if (this.isExternalLink(event)) {
return false;
}
const origin = globalThis.location?.origin;
if (origin) {
try {
if (new URL(event.destination.url, origin).origin !== origin) {
return false;
}
}
catch {
return false;
}
}
const meta = event.info?.[this.infoKey];
if (event.navigationType === 'reload' && !meta?.reload) {
return false;
}
// a same-url write tagged by someone else is theirs to intercept, React's transition indicator among them
const isForeign = event.info !== undefined && event.info !== null && !meta;
if (isForeign && event.destination.url === globalThis.location?.href) {
return false;
}
return true;
}
// a link marked rel="external" leaves the app, even for a url on this origin that a route would match
isExternalLink(event) {
return Boolean(event?.sourceElement?.relList?.contains('external'));
}
/*******************************
Moments
*******************************/
onEntryChange(event) {
this.updateEntries();
this.router.entryChanged(this.entry, event);
}
onSuccess(event) {
this.transition = null;
this.router.settled(event);
}
onError(event) {
this.transition = null;
this.router.failed(event?.error ?? event, event);
}
onPageShow(event) {
if (!event?.persisted) {
return;
}
// the document came back intact: re-read the platform, re-run nothing
this.updateEntries();
this.router.restored();
}
onDispose(entry) {
this.router.disposed(entry);
}
}
export const createNavigator = (router) => new Navigator(router);