-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
1542 lines (1349 loc) · 51.3 KB
/
router.js
File metadata and controls
1542 lines (1349 loc) · 51.3 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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { getStateObj, diffState, notifyStateChange } from '@aegisjsproject/state';
export { url } from '@aegisjsproject/url/url.js';
import { onClick, onSubmit } from '@aegisjsproject/callback-registry/events.js';
const isModule = ! (document.currentScript instanceof HTMLScriptElement);
const SUPPORTS_IMPORTMAP = HTMLScriptElement.supports('importmap');
const ROUTES_REGISTRY = new Map();
const NO_BODY_METHODS = ['GET', 'HEAD', 'DELETE', 'OPTIONS'];
const DESC_SELECTOR = 'meta[name="description"], meta[itemprop="description"], meta[property="og:description"], meta[name="twitter:description"]';
const navObserver = new MutationObserver(entries => entries.forEach(entry => interceptNav(entry.target)));
const preloadObserver = new MutationObserver(entries => entries.forEach(_handlePreloadMutations));
const ROOT_ID = 'root';
const EVENT_TARGET = document;
const NAV_CLOSE_SYMBOL = Symbol.for('aegis:navigate:event:close');
const prefersReducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
let rootEl = document.getElementById(ROOT_ID) ?? document.body;
let rootSelector = '#' + ROOT_ID;
const SUPPORTS_TRUSTED_TYPES = 'trustedTypes' in globalThis;
const _isTrustedHTML = input => SUPPORTS_TRUSTED_TYPES && trustedTypes.isHTML(input);
function _handlePreloadMutations(target) {
if (target instanceof MutationRecord) {
_handlePreloadMutations(target.target);
} else if (target.tagName === 'A' && ! target.classList.contains('no-router') && ! target.hasAttribute(onClick)) {
preloadOnHover(target, target.dataset);
} else {
target.querySelectorAll(`a:not(.no-router, [${onClick}])`).forEach(a => preloadOnHover(a, a.dataset));
}
}
export const NAV_EVENT = 'aegis:navigate';
export const EVENT_TYPES = {
navigate: 'aegis:router:navigate',
back: 'aegis:router:back',
forward: 'aegis:router:forward',
reload: 'aegis:router:reload',
pop: 'aegis:router:pop',
go: 'aegis:router:go',
load: 'aegis:router:load',
submit: 'aegis:router:submit',
};
const DEFAULT_REASONS = [EVENT_TYPES.back, EVENT_TYPES.forward, EVENT_TYPES.navigate, EVENT_TYPES.submit, EVENT_TYPES.reload, EVENT_TYPES.go];
export class AegisNavigationEvent extends CustomEvent {
#reason;
#url;
#stack = new AsyncDisposableStack();
#controller = new AbortController();
#promises = [];
#errors = [];
constructor(name = NAV_EVENT, reason = 'unknown', { bubbles = false, cancelable = true, detail = {
oldState: getStateObj(),
oldURL: new URL(location.href),
} } = {}) {
super(name, { bubbles, cancelable, detail });
this.#reason = reason;
this.#url = location.href;
}
get aborted() {
return this.#controller.signal.aborted;
}
get disposed() {
return this.#stack.disposed;
}
get error() {
switch(this.#errors.length) {
case 0:
return null;
case 1:
return this.#errors[0];
default:
return new AggregateError(this.#errors);
}
}
get reason() {
return this.#reason;
}
get signal() {
return this.#controller.signal;
}
get stack() {
return this.#stack;
}
get url() {
return this.#url;
}
async [NAV_CLOSE_SYMBOL]() {
const result = await Promise.allSettled(this.#promises).then(results => {
this.#errors.push(...results.filter(result => result.status === 'rejected').map(result => result.reason));
return this.cancelable && this.defaultPrevented;
});
this.#controller.abort();
return result;
}
adopt(obj, callback) {
return this.#stack.adopt(obj, callback);
}
abort(reason) {
this.#controller.abort(reason);
}
defer(callback) {
this.#stack.defer(callback);
}
async disposeAsync() {
await this[Symbol.asyncDispose]();
}
use(obj) {
return this.#stack.use(obj);
}
waitUntil(promiseOrCallback, { signal } = {}) {
const { promise, resolve, reject } = Promise.withResolvers();
this.#promises.push(promise);
if (signal instanceof AbortSignal && ! signal.aborted) {
signal.addEventListener('abort', ({ target }) =>{
reject(target.reason);
if (this.cancelable && ! this.defaultPrevented) {
super.preventDefault();
}
}, {
once: true,
signal: this.#controller.signal,
});
}
if (this.#controller.signal.aborted) {
reject(this.#controller.signal.reason);
} else if (signal instanceof AbortSignal && signal.aborted) {
reject(signal.reason);
if (this.cancelable && ! this.defaultPrevented) {
super.preventDefault();
}
} else if (! this.defaultPrevented && promiseOrCallback instanceof Function) {
Promise.try(() => promiseOrCallback(this, {
signal: signal instanceof AbortSignal ? AbortSignal.any([signal, this.#controller.signal]) : this.#controller.signal,
timestamp: performance.now(),
stack: this.#stack,
})).then(resolve, reject);
} else if (! this.defaultPrevented && promiseOrCallback instanceof Promise) {
promiseOrCallback.then(resolve, reject);
}
}
[Symbol.toStringTag]() {
return 'NavigationEvent';
}
async [Symbol.asyncDispose]() {
if (! this.#controller.signal.aborted) {
this.#controller.abort(new DOMException('The stack of the event was disposed.', 'AbortError'));
}
if (! this.#stack.disposed) {
await this.#stack.disposeAsync();
}
}
static get defaultType() {
return NAV_EVENT;
}
static get reasons() {
return EVENT_TYPES;
}
}
// Need this to be "unsafe" to not be restrictive on what modifications can be made to a page
const policy = SUPPORTS_TRUSTED_TYPES
? trustedTypes.createPolicy('aegis-router#html', { createHTML: input => input })
: Object.freeze({ createPolicy: input => input });
async function _popstateHandler(event) {
const diff = diffState(event.state ?? {});
const navigate = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.pop, {
detail: { newState: event.state, oldState: null, oldURL: new URL(location.href), method: 'GET', formData: null },
});
try {
EVENT_TARGET.dispatchEvent(navigate);
if (! await navigate[NAV_CLOSE_SYMBOL]()) {
const old = history.scrollRestoration;
const [content] = await Promise.all([
getModule(new URL(location.href)),
notifyStateChange(diff),
]);
history.scrollRestoration = 'auto';
_updatePage(content);
history.scrollRestoration = old;
}
} finally {
requestAnimationFrame(navigate[Symbol.asyncDispose].bind(navigate));
}
};
function _addStyle(sheet) {
if (sheet instanceof CSSStyleSheet && ! document.adoptedStyleSheets.includes(sheet)) {
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
} else if (Array.isArray(sheet) && sheet.length !== 0) {
document.adoptedStyleSheets = [
...document.adoptedStyleSheets,
...sheet.filter(s => s instanceof CSSStyleSheet && ! document.adoptedStyleSheets.includes(s))
];
}
}
function _createMeta(props = {}) {
const meta = document.createElement('meta');
Object.entries(props).forEach(([key, val]) => meta.setAttribute(key, val));
return meta;
}
function _loadLink(href, {
relList = [],
crossOrigin = 'anonymous',
referrerPolicy = 'no-referrer',
fetchPriority = 'auto',
signal: passedSignal,
as,
integrity,
media,
type,
} = {}) {
const { promise, resolve, reject } = Promise.withResolvers();
const link = document.createElement('link');
if (passedSignal instanceof AbortSignal && passedSignal.aborted) {
reject(passedSignal.reason);
} else {
link.relList.add(...relList);
if (typeof fetchPriority === 'string') {
link.fetchPriority = fetchPriority;
}
if (typeof crossOrigin === 'string') {
link.crossOrigin = crossOrigin;
}
if (typeof type === 'string') {
link.type = type;
}
if (typeof media === 'string') {
link.media = media;
} else if (media instanceof MediaQueryList) {
link.media = media.media;
}
if (typeof as === 'string') {
link.as = as;
}
if (typeof integrity === 'string') {
link.integrity = integrity;
}
if (link.relList.contains('preload') || link.relList.contains('modulepreload')) {
const controller = new AbortController();
const signal = passedSignal instanceof AbortSignal ? AbortSignal.any([controller.signal, passedSignal]) : controller.signal;
if (passedSignal instanceof AbortSignal) {
passedSignal.addEventListener('abort', ({ target }) => {
reject(target.reason);
}, { signal: controller.signal, once: true });
}
link.referrerPolicy = referrerPolicy;
link.addEventListener('load', () => {
resolve();
controller.abort();
}, { signal });
link.addEventListener('error', () => {
reject(new DOMException(`Error loading ${href}`, 'NotFoundError'));
controller.abort();
}, { signal });
link.href = _resolveModule(href);
document.head.append(link);
return promise.then(() => link.remove()).catch(err => {
if (link.isConnected) {
link.remove();
}
reportError(err);
});
} else {
link.href = href;
document.head.append(link);
resolve();
return promise;
}
}
}
function _isModuleURL(src) {
switch(src[0]) {
case '/':
case '.':
return true;
case 'h':
return src.substring(0, '4') === 'http' && URL.canParse(src);
default:
return false;
}
}
function _resolveModule(src) {
if (_isModuleURL(src)) {
return URL.parse(src, document.baseURI);
} else if (! SUPPORTS_IMPORTMAP) {
throw new TypeError('Importmaps and module specifiers are not supported');
} else if (! isModule) {
throw new TypeError('Cannot resolve a module specifier outside of a module script.');
} else {
return import.meta.resolve(src);
}
}
function _getLinkStateData(a) {
const entries = Object.entries(a.dataset)
.filter(([name]) => name.startsWith('aegisState'))
.map(([name, value]) => [name[10].toLowerCase() + name.substring(11), value]);
return Object.fromEntries(entries);
}
function _interceptLinkClick(event) {
if (event.target.classList.contains('no-router') || event.target.hasAttribute(onClick)) {
event.target.removeEventListener(_interceptLinkClick);
} else if (
event.isTrusted
&& event.currentTarget.href.startsWith(location.origin)
&& ! (event.metaKey || event.ctrlKey || event.shiftKey)
) {
event.preventDefault();
const state = _getLinkStateData(event.currentTarget);
navigate(event.currentTarget.href, state, {
integrity: event.currentTarget.dataset.integrity,
cache: event.currentTarget.dataset.cache,
referrerPolicy: event.currentTarget.dataset.referrerPolicy,
});
}
}
async function _interceptFormSubmit(event) {
if (event.target.classList.contains('no-router') || event.target.hasAttribute(onSubmit)) {
event.target.removeEventListener('submit', _interceptFormSubmit);
} else if (event.isTrusted && event.target.action.startsWith(location.origin)) {
event.preventDefault();
const { target, submitter } = event;
const { method, action } = target;
const formData = new FormData(target);
const submit = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.submit, {
detail: { oldState: getStateObj(), oldURL: new URL(location.href), formData },
});
try {
if (submitter instanceof HTMLButtonElement) {
submitter.disabled = true;
}
EVENT_TARGET.dispatchEvent(submit);
if (await submit[NAV_CLOSE_SYMBOL]()) {
return;
} else if (NO_BODY_METHODS.includes(method.toUpperCase())) {
const url = new URL(action);
const params = new URLSearchParams(formData);
for (const [key, val] of params.entries()) {
url.searchParams.append(key, val);
}
await navigate(url, getStateObj(), { method });
} else {
await navigate(action, getStateObj(), { method, formData });
}
} finally {
if (submitter instanceof HTMLButtonElement) {
submitter.disabled = false;
}
requestAnimationFrame(submit[Symbol.asyncDispose].bind(submit));
}
}
}
async function _getHTML(url, { signal, method = 'GET', body, integrity, cache = 'default', referrerPolicy = 'no-referrer' } = {}) {
const resp = await fetch(url, {
method,
body: NO_BODY_METHODS.includes(method.toUpperCase()) ? null : body,
headers: { 'Accept': 'text/html' },
cache,
referrerPolicy,
integrity,
signal,
}).catch(err => err);
if (resp.ok) {
const html = await resp.text();
return Document.parseHTMLUnsafe(policy.createHTML(html));
} else if (resp instanceof Error) {
return resp;
} else {
return _get404(url, method, { signal });
}
}
function _updatePage(content) {
const timestamp = performance.now();
if (content instanceof Document) {
if (content.head.childElementCount !== 0) {
setTitle(content.title);
setDescription(content.querySelector(DESC_SELECTOR)?.content);
}
const contentEl = typeof rootSelector === 'string' ? content.body.querySelector(rootSelector) ?? content.body : content.body;
rootEl.replaceChildren(...contentEl.childNodes);
} else if (content instanceof HTMLTemplateElement) {
rootEl.replaceChildren(content.content);
} else if (content instanceof Function && content.prototype instanceof HTMLElement) {
rootEl.replaceChildren(new content({ state: getStateObj(), url: new URL(location.href), timestamp }));
} else if (content instanceof Node) {
rootEl.replaceChildren(content);
} else if (content instanceof Function) {
_updatePage(content());
} else if (typeof content === 'string') {
rootEl.setHTMLUnsafe(policy.createHTML(content));
} else if (_isTrustedHTML(content)) {
rootEl.setHTMLUnsafe(content);
} else if (content instanceof Error) {
reportError(content);
rootEl.textContent = content.message;
} else if (content instanceof URL) {
navigate(content);
} else if (! (content === null || typeof content === 'undefined')) {
rootEl.textContent = content;
}
const ev = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.load, { cancelable: false });
Promise.try(() => EVENT_TARGET.dispatchEvent(ev)).finally(ev[Symbol.asyncDispose].bind(ev));
if (history.scrollRestoration === 'manual') {
if (location.hash.length > 1) {
const target = document.getElementById(location.hash.substring(1)) ?? document.body;
target.scrollIntoView({ behavior: prefersReducedMotion.matches ? 'instant' : 'smooth' });
} else {
const autofocus = rootEl.querySelector('[autofocus]');
if (autofocus instanceof Element) {
autofocus.focus();
} else {
document.body.scrollIntoView({ behavior: prefersReducedMotion.matches ? 'instant' : 'smooth' });
}
}
}
}
async function _handleMetadata({ title, description } = {}, { state, matches, params, url, signal } = {}) {
if (typeof title === 'string') {
setTitle(title);
} else if (typeof title === 'function') {
setTitle(await title({ state, matches, params, url, signal }));
}
if (typeof description === 'string') {
setDescription(description);
} else if (typeof description === 'function') {
setDescription(await description({ state, matches, params, url, signal }));
}
}
async function _handleModule(moduleSrc, {
state = getStateObj(),
matches = {},
params = {},
stack,
signal,
...args
} = {}) {
const module = await Promise.try(() => {
if (moduleSrc instanceof Function) {
return moduleSrc(args);
} else if (typeof moduleSrc === 'string' || module instanceof URL) {
return _isModuleURL(moduleSrc)
? import(URL.parse(moduleSrc, document.baseURI))
: import(moduleSrc);
} else {
return new TypeError('Invalid module src.');
}
}).catch(err => err);
const url = new URL(location.href);
const timestamp = performance.now();
if (module instanceof URL) {
await navigate(module, state, args);
} else if (module instanceof Error) {
return module.message;
} else if (! ('default' in module)) {
return new Error(`${moduleSrc} has no default export.`);
} else if (module.default instanceof Function && module.default.prototype instanceof HTMLElement) {
if (typeof customElements.getName(module.default) !== 'string') {
customElements.define(
module.default[Symbol.for('tagName')] ?? `aegis-el-${crypto.randomUUID()}`,
module.default
);
}
if (typeof module.styles !== 'undefined') {
_addStyle(module.styles);
}
_handleMetadata(module, { state, matches, params, url, signal });
return new module.default({
url,
matches,
params,
state,
stack,
timestamp,
signal: getNavSignal({ signal }),
...args
});
} else if (module.default instanceof Function) {
if (typeof module.styles !== 'undefined') {
_addStyle(module.styles);
}
_handleMetadata(module, { state, matches, params, url, signal });
return await module.default({
url,
matches,
params,
state,
stack,
timestamp,
signal: getNavSignal({ signal }),
...args
});
} else if (module.default instanceof Node || module.default instanceof Error) {
if (typeof module.styles !== 'undefined') {
_addStyle(module.styles);
}
_handleMetadata(module, { state, matches, params, url, signal });
_updatePage(module.default);
} else if (module.default instanceof URL && module.default.origin === location.origin) {
navigate(module.default);
} else {
throw new TypeError(`${moduleSrc} has a missing or invalid default export.`);
}
}
let view404 = ({ url = location, method = 'GET' }) => {
const div = document.createElement('div');
const p = document.createElement('p');
const a = document.createElement('a');
p.textContent = `${method.toUpperCase()} ${url.href} [404 Not Found]`;
a.href = document.baseURI;
a.textContent = 'Go Home';
a.addEventListener('click', _interceptLinkClick);
div.append(p, a);
return div;
};
async function _get404(url = location, method = 'GET', { signal, formData, integrity } = {}) {
const timestamp = performance.now();
const stack = new AsyncDisposableStack();
try {
if (typeof view404 === 'string') {
return await _handleModule(view404, { url, matches: null, signal, method, formData, timestamp, integrity });
} else if (view404 instanceof Function) {
_updatePage(view404({ timestamp, state: getStateObj(), url, matches: null, signal, method, formData, integrity }));
}
} finally {
stack.disposeAsync();
}
}
/**
* Finds the matching URL pattern for a given input.
*
* @param {string|URL} input - The input URL or path.
* @returns {URLPattern|undefined} - The matching URL pattern, or undefined if no match is found.
*/
export const findPath = input => ROUTES_REGISTRY.keys().find(pattern => pattern.test(input));
/**
* Sets the 404 handler.
*
* @param {string} path - The path to the 404 handler module or the handler function itself.
*/
export const set404 = path => view404 = path;
/**
* Intercepts navigation events within a target element.
*
* @param {HTMLElement|ShadowRoot|string} target - The element to intercept navigation events on. Defaults to document.body.
* @param {Object} [options] - Optional options.
* @param {AbortSignal} [options.signal] - An AbortSignal to cancel the interception.
*/
export function interceptNav(target = document.body, { signal } = {}) {
if (typeof target === 'string') {
interceptNav(document.querySelector(target), { signal });
} else if (! (target instanceof HTMLElement || target instanceof ShadowRoot)) {
throw new TypeError('Cannot intercept navigation on a non-Element. Element or selector is required.');
} else if (target instanceof HTMLAnchorElement && ! target.classList.contains('no-router') && ! target.hasAttribute(onClick) && target.href.startsWith(location.origin)) {
target.addEventListener('click', _interceptLinkClick, { signal, passive: false });
} else if (target instanceof HTMLFormElement && ! target.classList.contains('no-router') && ! target.hasAttribute(onSubmit) && target.action.startsWith(location.origin)) {
target.addEventListener('submit', _interceptFormSubmit, { signal, passive: false });
target.querySelectorAll(`a[href]:not([rel~="external"], [download], .no-router, [${onClick}])`).forEach(el => {
if (el.href.startsWith(location.origin)) {
el.addEventListener('click', _interceptLinkClick, { passive: false, signal });
}
});
} else {
target.querySelectorAll(`a[href]:not([rel~="external"], [download], .no-router, [${onClick}])`).forEach(el => {
if (el.href.startsWith(location.origin)) {
el.addEventListener('click', _interceptLinkClick, { passive: false, signal });
}
});
target.querySelectorAll(`form:not(.no-router, [${onSubmit}])`).forEach(el => {
el.addEventListener('submit', _interceptFormSubmit, { passive: false, signal });
});
}
}
/**
* Sets the root element for the navigation system.
*
* @param {HTMLElement|string} target - The element to set as the root.
*/
export function setRoot(target, selector) {
if (target instanceof HTMLElement) {
rootEl = target;
rootSelector = typeof selector === 'string' ? selector : target.hasAttribute('id') ? `#${target.id}` : null;
if (typeof rootEl.ariaLive !== 'string') {
rootEl.ariaLive = 'assertive';;
}
} else if (typeof target === 'string') {
setRoot(document.querySelector(target), target);
} else {
throw new TypeError('Cannot set root to a non-html element.');
}
}
/**
* Observes links on an element for navigation.
*
* @param {HTMLElement|ShadowRoot|string} target - The element to observe links on. Defaults to document.body.
* @param {object} [options] - Optional options.
* @param {AbortSignal} [options.signal] - An AbortSignal to cancel the observation.
*/
export function observeLinksOn(target = document.body, { signal } = {}) {
if (signal instanceof AbortSignal && signal.aborted) {
throw signal.reason;
} else if (typeof target === 'string') {
observeLinksOn(document.querySelector(target), { signal });
} else if (target instanceof HTMLElement || target instanceof ShadowRoot) {
interceptNav(target, { signal });
navObserver.observe(target, { childList: true, subtree: true });
if (signal instanceof AbortSignal) {
signal.addEventListener('abort', () => navObserver.disconnect(), { once: true });
}
} else {
throw new TypeError('Cannot observe link on a non-Element. Requires an Element or selector.');
}
}
/**
* Creates a URLPattern object from the given path and base URL.
*
* @param {string|URL|URLPattern} path - The path to create the pattern from.
* @param {string} [baseURL=location.origin] - The base URL to use for relative paths. Defaults to the current origin.
* @returns {URLPattern|null} - The created URLPattern object, or `null` if the input is invalid.
*/
export function getURLPattern(path, baseURL = location.origin) {
if (path instanceof URLPattern) {
return path;
} else if (typeof path === 'string') {
return new URLPattern(path, baseURL);
} else if (path instanceof URL) {
return new URLPattern(path.href);
} else {
return null;
}
}
/**
* Extracts a specific parameter value from a URL path.
*
* @param {string|URL|URLPattern} path - The path to extract the parameter from.
* @param {string} param - The name of the parameter to extract.
* @param {object} [options] - Optional options.
* - `fallbackValue` {string} - The default value to return if the parameter is not found.
* - `baseURL` {string} - The base URL to use for relative paths.
* @returns {object} - An object with a `toString()` method to retrieve the parameter value as a string, and a `[Symbol.toPrimitive]()` method to convert it to a number or string.
*/
export function getURLPath(path, param, {
fallbackValue = '',
baseURL = location.origin,
} = {}) {
const pattern = getURLPattern(path, baseURL);
return Object.freeze({
toString() {
return pattern.exec(location.href)?.pathname.groups?.[param] ?? fallbackValue;
},
[Symbol.toPrimitive](hint = 'default') {
return hint === 'number' ? parseFloat(this.toString()) : this.toString();
}
});
}
/**
* Registers a URL pattern with its corresponding module source.
*
* @param {URLPattern|string|URL} path - The URL pattern or URL to register.
* @param {string|URL|Function} moduleSrc - The module source URL/specifier or a function.
*/
export async function registerPath(path, moduleSrc, {
preload = false,
signal,
baseURL = location.origin,
crossOrigin = 'anonymous',
referrerPolicy = 'no-referrer',
} = {}) {
if (signal instanceof AbortSignal && signal.aborted) {
throw signal.reason;
} else if (typeof path === 'string') {
await registerPath(new URLPattern(path, baseURL), moduleSrc, { preload, signal, crossOrigin, referrerPolicy });
} else if (path instanceof URL) {
await registerPath(new URLPattern(path.href), moduleSrc, { preload, baseURL, signal, crossOrigin, referrerPolicy });
} else if (! (typeof moduleSrc === 'string' || moduleSrc instanceof Function || moduleSrc instanceof URL)) {
throw new TypeError('Module source/handler must be a module specifier/url or handler function.');
} else if (path instanceof URLPattern) {
ROUTES_REGISTRY.set(path, moduleSrc);
if (preload && (typeof moduleSrc === 'string' || moduleSrc instanceof URL)) {
await preloadModule(moduleSrc, { signal, crossOrigin, referrerPolicy });
}
if (signal instanceof AbortSignal) {
signal.addEventListener('abort', clearPaths, { once: true });
}
} else {
throw new TypeError(`Could not convert ${path} to a URLPattern.`);
}
}
/**
* Clears all registered paths
*/
export function clearPaths() {
ROUTES_REGISTRY.clear();
}
/**
* Fetches a module or retrieves its content based on a URL or path.
*
* @param {URL|string|null} input - The URL, path, or null to throw an error. Defaults to `location`.
* @param {object} [options] - Optional options.
* @param {AbortSignal} [options.signal] - An AbortSignal to cancel the fetch.
* @param {string} [options.method] - The HTTP method to use for fetching the module. Defaults to 'GET'.
* @param {FormData} [options.formData] - The form data to send with the request. Defaults to a new FormData object.
* @returns {Promise<string|void>} - A promise that resolves with the module content or triggers navigation if a path match is found.
* @throws {Error} - Throws an error if the input is null or cannot be parsed as a URL.
*/
export async function getModule(input = location, {
method = 'GET',
state = getStateObj(),
formData = new FormData(),
cache = 'default',
referrerPolicy = 'no-referrer',
integrity,
signal,
} = {}) {
const timestamp = performance.now();
const stack = new AsyncDisposableStack();
try {
if (input === null) {
throw new Error('Invalid path.');
} else if (! (input instanceof URL)) {
return await getModule(URL.parse(input, document.baseURI), { signal, method, formData, state, stack, integrity, cache, referrerPolicy });
} else {
const match = findPath(input);
if (! (match instanceof URLPattern)) {
return await _getHTML(input, { method, signal: getNavSignal({ signal }), body: formData, state, stack, integrity, cache, referrerPolicy });
} else {
const handler = ROUTES_REGISTRY.get(match);
const matches = match.exec(input);
const params = typeof matches === 'object'
? {
...matches.protocol.groups, ...matches.username.groups, ...matches.password.groups, ...matches.hostname.groups,
...matches.port.groups, ...matches.pathname.groups, ...matches.search.groups, ...matches.hash.groups,
} : {};
delete params['0'];
return await _handleModule(handler, {
url: input,
matches,
params,
state,
stack,
method,
formData,
integrity,
timestamp,
});
}
}
} finally {
requestAnimationFrame(stack.disposeAsync.bind(stack));
}
}
/**
* Navigates to a new URL.
*
* @param {string|URL} url - The URL to navigate to.
* @param {object} [newState] - The new state object to push to the history.
* @param {object} [options] - Optional options.
* @param {AbortSignal} [options.signal] - An AbortSignal to cancel the navigation.
* @param {string} [options.method="GET"] - The HTTP method to use for the navigation.
* @param {FormData} [options.formData] - The form data to send with the request.
* @returns {Promise<any>} - A promise that resolves with the new content or `null` if navigation is cancelled.
*/
export async function navigate(url, newState = getStateObj(), {
signal,
method = 'GET',
cache = 'default',
referrerPolicy = 'no-referrer',
formData,
integrity,
scrollRestoration = null,
} = {}) {
if (url === null) {
throw new TypeError('URL cannot be null.');
} else if (signal instanceof AbortSignal && signal.aborted) {
throw signal.reason;
} else if (! (url instanceof URL)) {
return await navigate(URL.parse(url, document.baseURI), newState, { signal, method, cache, referrerPolicy, formData, integrity });
} else if (formData instanceof FormData && NO_BODY_METHODS.includes(method.toUpperCase())) {
const params = new URLSearchParams(formData);
for (const [key, val] of params) {
url.searchParams.append(key, val);
}
return await navigate(url, newState, { signal, method, cache, referrerPolicy, integrity });
} else if (url.href !== location.href) {
const oldState = getStateObj();
const navigate = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.navigate, {
detail: { newState, oldState, oldURL: new URL(location.href), newURL: url, method, formData },
});
try {
const diff = diffState(newState, oldState);
EVENT_TARGET.dispatchEvent(navigate);
if (! await navigate[NAV_CLOSE_SYMBOL]()) {
if (typeof scrollRestoration === 'string') {
history.scrollRestoration = scrollRestoration;
}
history.pushState(newState, '', url);
const content = await getModule(url, { signal, method, cache, referrerPolicy, formData, state: newState, integrity });
await notifyStateChange(diff);
_updatePage(content);
return content;
} else {
return null;
}
} catch(err) {
back();
reportError(err);
} finally {
requestAnimationFrame(navigate[Symbol.asyncDispose].bind(navigate));
}
}
}
/**
* Navigates back in the history.
*/
export async function back({ signal } = {}) {
const event = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.back);
EVENT_TARGET.dispatchEvent(event);
await event[NAV_CLOSE_SYMBOL]().then(async prevented => {
if (! prevented) {
history.back();
await whenNavigated({ signal, reasons: [EVENT_TYPES.load] });
}
}).finally(event[Symbol.asyncDispose].bind(event));
}
/**
* Navigates forward in the history.
*/
export async function forward({ signal } = {}) {
const event = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.forward);
EVENT_TARGET.dispatchEvent(event);
await event[NAV_CLOSE_SYMBOL]().then(async prevented => {
if (! prevented) {
history.forward();
await whenNavigated({ signal, reasons: [EVENT_TYPES.load] });
}
}).finally(event[Symbol.asyncDispose].bind(event));
}
/**
* Navigates to a specific history entry.
*
* @param {number} [delta=0] - The number of entries to go back or forward. 0 to reload.
*/
export async function go(delta = 0, { signal } = {}) {
const event = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.go);
EVENT_TARGET.dispatchEvent(event);
await event[NAV_CLOSE_SYMBOL]().then(async prevented => {
if (! prevented) {
history.go(delta);
await whenNavigated({ signal, reasons: [EVENT_TYPES.load] });
}
}).finally(event[Symbol.asyncDispose].bind(event));
}
/**
* Reloads the current page.
*/
export function reload() {
const event = new AegisNavigationEvent(NAV_EVENT, EVENT_TYPES.reload);
EVENT_TARGET.dispatchEvent(event);
event[NAV_CLOSE_SYMBOL]().then(prevented => {
if (! prevented) {
history.go(0);
}
}).finally(event[Symbol.asyncDispose].bind(event));
}
/**
* Adds a popstate listener to the window.
*
* @param {object} [options] - Optional options.
* @param {AbortSignal} [options.signal] - An AbortSignal to cancel the listener.