-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
client.js
1331 lines (1117 loc) · 32.3 KB
/
client.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
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 { onMount, tick } from 'svelte';
import { writable } from 'svelte/store';
import { coalesce_to_error } from '../../utils/error.js';
import { normalize } from '../load.js';
import { normalize_path } from '../../utils/url.js';
import {
create_updated_store,
find_anchor,
get_base_uri,
get_href,
notifiable_store,
scroll_state
} from './utils.js';
import { lock_fetch, unlock_fetch, initial_fetch, native_fetch } from './fetcher.js';
import { parse } from './parse.js';
import Root from '__GENERATED__/root.svelte';
import { components, dictionary, matchers } from '__GENERATED__/client-manifest.js';
const SCROLL_KEY = 'sveltekit:scroll';
const INDEX_KEY = 'sveltekit:index';
const routes = parse(components, dictionary, matchers);
// we import the root layout/error components eagerly, so that
// connectivity errors after initialisation don't nuke the app
const default_layout = components[0]();
const default_error = components[1]();
const root_stuff = {};
// We track the scroll position associated with each history entry in sessionStorage,
// rather than on history.state itself, because when navigation is driven by
// popstate it's too late to update the scroll position associated with the
// state we're navigating from
/** @typedef {{ x: number, y: number }} ScrollPosition */
/** @type {Record<number, ScrollPosition>} */
let scroll_positions = {};
try {
scroll_positions = JSON.parse(sessionStorage[SCROLL_KEY]);
} catch {
// do nothing
}
/** @param {number} index */
function update_scroll_positions(index) {
scroll_positions[index] = scroll_state();
}
/**
* @param {{
* target: Element;
* session: App.Session;
* base: string;
* trailing_slash: import('types').TrailingSlash;
* }} opts
* @returns {import('./types').Client}
*/
export function create_client({ target, session, base, trailing_slash }) {
/** @type {Map<string, import('./types').NavigationResult>} */
const cache = new Map();
/** @type {Array<((href: string) => boolean)>} */
const invalidated = [];
const stores = {
url: notifiable_store({}),
page: notifiable_store({}),
navigating: writable(/** @type {import('types').Navigation | null} */ (null)),
session: writable(session),
updated: create_updated_store()
};
/** @type {{id: string | null, promise: Promise<import('./types').NavigationResult | undefined> | null}} */
const load_cache = {
id: null,
promise: null
};
const callbacks = {
/** @type {Array<(opts: { from: URL, to: URL | null, cancel: () => void }) => void>} */
before_navigate: [],
/** @type {Array<(opts: { from: URL | null, to: URL }) => void>} */
after_navigate: []
};
/** @type {import('./types').NavigationState} */
let current = {
branch: [],
error: null,
session_id: 0,
stuff: root_stuff,
// @ts-ignore - we need the initial value to be null
url: null
};
let started = false;
let autoscroll = true;
let updating = false;
let session_id = 1;
/** @type {Promise<void> | null} */
let invalidating = null;
/** @type {import('svelte').SvelteComponent} */
let root;
/** @type {App.Session} */
let $session;
let ready = false;
stores.session.subscribe(async (value) => {
$session = value;
if (!ready) return;
session_id += 1;
update(new URL(location.href), [], true);
});
ready = true;
let router_enabled = true;
// keeping track of the history index in order to prevent popstate navigation events if needed
let current_history_index = history.state?.[INDEX_KEY];
if (!current_history_index) {
// we use Date.now() as an offset so that cross-document navigations
// within the app don't result in data loss
current_history_index = Date.now();
// create initial history entry, so we can return here
history.replaceState(
{ ...history.state, [INDEX_KEY]: current_history_index },
'',
location.href
);
}
// if we reload the page, or Cmd-Shift-T back to it,
// recover scroll position
const scroll = scroll_positions[current_history_index];
if (scroll) {
history.scrollRestoration = 'manual';
scrollTo(scroll.x, scroll.y);
}
let hash_navigating = false;
/** @type {import('types').Page} */
let page;
/** @type {{}} */
let token;
/**
* @param {string} href
* @param {{ noscroll?: boolean; replaceState?: boolean; keepfocus?: boolean; state?: any }} opts
* @param {string[]} redirect_chain
*/
async function goto(
href,
{ noscroll = false, replaceState = false, keepfocus = false, state = {} },
redirect_chain
) {
const url = new URL(href, get_base_uri(document));
if (router_enabled) {
return navigate({
url,
scroll: noscroll ? scroll_state() : null,
keepfocus,
redirect_chain,
details: {
state,
replaceState
},
accepted: () => {},
blocked: () => {}
});
}
await native_navigation(url);
}
/** @param {URL} url */
async function prefetch(url) {
const intent = get_navigation_intent(url);
if (!intent) {
throw new Error('Attempted to prefetch a URL that does not belong to this app');
}
load_cache.promise = load_route(intent, false);
load_cache.id = intent.id;
return load_cache.promise;
}
/**
* Returns `true` if update completes, `false` if it is aborted
* @param {URL} url
* @param {string[]} redirect_chain
* @param {boolean} no_cache
* @param {{hash?: string, scroll: { x: number, y: number } | null, keepfocus: boolean, details: { replaceState: boolean, state: any } | null}} [opts]
* @param {() => void} [callback]
*/
async function update(url, redirect_chain, no_cache, opts, callback) {
const intent = get_navigation_intent(url);
const current_token = (token = {});
let navigation_result = intent && (await load_route(intent, no_cache));
if (
!navigation_result &&
url.origin === location.origin &&
url.pathname === location.pathname
) {
// this could happen in SPA fallback mode if the user navigated to
// `/non-existent-page`. if we fall back to reloading the page, it
// will create an infinite loop. so whereas we normally handle
// unknown routes by going to the server, in this special case
// we render a client-side error page instead
navigation_result = await load_root_error_page({
status: 404,
error: new Error(`Not found: ${url.pathname}`),
url,
routeId: null
});
}
if (!navigation_result) {
await native_navigation(url);
return false; // unnecessary, but TypeScript prefers it this way
}
// abort if user navigated during update
if (token !== current_token) return false;
invalidated.length = 0;
if (navigation_result.redirect) {
if (redirect_chain.length > 10 || redirect_chain.includes(url.pathname)) {
navigation_result = await load_root_error_page({
status: 500,
error: new Error('Redirect loop'),
url,
routeId: null
});
} else {
if (router_enabled) {
goto(new URL(navigation_result.redirect, url).href, {}, [
...redirect_chain,
url.pathname
]);
} else {
await native_navigation(new URL(navigation_result.redirect, location.href));
}
return false;
}
} else if (navigation_result.props?.page?.status >= 400) {
const updated = await stores.updated.check();
if (updated) {
await native_navigation(url);
}
}
updating = true;
if (opts && opts.details) {
const { details } = opts;
const change = details.replaceState ? 0 : 1;
details.state[INDEX_KEY] = current_history_index += change;
history[details.replaceState ? 'replaceState' : 'pushState'](details.state, '', url);
}
if (started) {
current = navigation_result.state;
if (navigation_result.props.page) {
navigation_result.props.page.url = url;
}
root.$set(navigation_result.props);
} else {
initialize(navigation_result);
}
// opts must be passed if we're navigating
if (opts) {
const { scroll, keepfocus } = opts;
if (!keepfocus) {
// Reset page selection and focus
// We try to mimic browsers' behaviour as closely as possible by targeting the
// first scrollable region, but unfortunately it's not a perfect match — e.g.
// shift-tabbing won't immediately cycle up from the end of the page on Chromium
// See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area
const root = document.body;
const tabindex = root.getAttribute('tabindex');
getSelection()?.removeAllRanges();
root.tabIndex = -1;
root.focus({ preventScroll: true });
// restore `tabindex` as to prevent `root` from stealing input from elements
if (tabindex !== null) {
root.setAttribute('tabindex', tabindex);
} else {
root.removeAttribute('tabindex');
}
}
// need to render the DOM before we can scroll to the rendered elements
await tick();
if (autoscroll) {
const deep_linked = url.hash && document.getElementById(url.hash.slice(1));
if (scroll) {
scrollTo(scroll.x, scroll.y);
} else if (deep_linked) {
// Here we use `scrollIntoView` on the element instead of `scrollTo`
// because it natively supports the `scroll-margin` and `scroll-behavior`
// CSS properties.
deep_linked.scrollIntoView();
} else {
scrollTo(0, 0);
}
}
} else {
// in this case we're simply invalidating
await tick();
}
load_cache.promise = null;
load_cache.id = null;
autoscroll = true;
if (navigation_result.props.page) {
page = navigation_result.props.page;
}
const leaf_node = navigation_result.state.branch[navigation_result.state.branch.length - 1];
router_enabled = leaf_node?.module.router !== false;
if (callback) callback();
updating = false;
}
/** @param {import('./types').NavigationResult} result */
function initialize(result) {
current = result.state;
const style = document.querySelector('style[data-sveltekit]');
if (style) style.remove();
page = result.props.page;
root = new Root({
target,
props: { ...result.props, stores },
hydrate: true
});
if (router_enabled) {
const navigation = { from: null, to: new URL(location.href) };
callbacks.after_navigate.forEach((fn) => fn(navigation));
}
started = true;
}
/**
*
* @param {{
* url: URL;
* params: Record<string, string>;
* stuff: Record<string, any>;
* branch: Array<import('./types').BranchNode | undefined>;
* status: number;
* error: Error | null;
* routeId: string | null;
* }} opts
*/
async function get_navigation_result_from_branch({
url,
params,
stuff,
branch,
status,
error,
routeId
}) {
const filtered = /** @type {import('./types').BranchNode[] } */ (branch.filter(Boolean));
const redirect = filtered.find((f) => f.loaded?.redirect);
/** @type {import('./types').NavigationResult} */
const result = {
redirect: redirect?.loaded?.redirect,
state: {
url,
params,
branch,
error,
stuff,
session_id
},
props: {
components: filtered.map((node) => node.module.default)
}
};
for (let i = 0; i < filtered.length; i += 1) {
const loaded = filtered[i].loaded;
result.props[`props_${i}`] = loaded ? await loaded.props : null;
}
const page_changed =
!current.url ||
url.href !== current.url.href ||
current.error !== error ||
current.stuff !== stuff;
if (page_changed) {
result.props.page = { error, params, routeId, status, stuff, url };
// TODO remove this for 1.0
/**
* @param {string} property
* @param {string} replacement
*/
const print_error = (property, replacement) => {
Object.defineProperty(result.props.page, property, {
get: () => {
throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
}
});
};
print_error('origin', 'origin');
print_error('path', 'pathname');
print_error('query', 'searchParams');
}
const leaf = filtered[filtered.length - 1];
const load_cache = leaf?.loaded?.cache;
if (load_cache) {
const key = url.pathname + url.search; // omit hash
let ready = false;
const clear = () => {
if (cache.get(key) === result) {
cache.delete(key);
}
unsubscribe();
clearTimeout(timeout);
};
const timeout = setTimeout(clear, load_cache.maxage * 1000);
const unsubscribe = stores.session.subscribe(() => {
if (ready) clear();
});
ready = true;
cache.set(key, result);
}
return result;
}
/**
* @param {{
* status?: number;
* error?: Error;
* module: import('types').CSRComponent;
* url: URL;
* params: Record<string, string>;
* stuff: Record<string, any>;
* props?: Record<string, any>;
* routeId: string | null;
* }} options
*/
async function load_node({ status, error, module, url, params, stuff, props, routeId }) {
/** @type {import('./types').BranchNode} */
const node = {
module,
uses: {
params: new Set(),
url: false,
session: false,
stuff: false,
dependencies: new Set()
},
loaded: null,
stuff
};
/** @param dep {string} */
function add_dependency(dep) {
const { href } = new URL(dep, url);
node.uses.dependencies.add(href);
}
if (props) {
// shadow endpoint props means we need to mark this URL as a dependency of itself
node.uses.dependencies.add(url.href);
}
/** @type {Record<string, string>} */
const uses_params = {};
for (const key in params) {
Object.defineProperty(uses_params, key, {
get() {
node.uses.params.add(key);
return params[key];
},
enumerable: true
});
}
const session = $session;
if (module.load) {
/** @type {import('types').LoadEvent} */
const load_input = {
routeId,
params: uses_params,
props: props || {},
get url() {
node.uses.url = true;
return new Proxy(url, {
get: (target, property) => {
if (property === 'hash') {
throw new Error(
'url.hash is inaccessible from load. Consider accessing hash from the page store within the script tag of your component.'
);
}
return Reflect.get(target, property, target);
}
});
},
get session() {
node.uses.session = true;
return session;
},
get stuff() {
node.uses.stuff = true;
return { ...stuff };
},
async fetch(resource, init) {
let requested;
if (typeof resource === 'string') {
requested = resource;
} else {
requested = resource.url;
// we're not allowed to modify the received `Request` object, so in order
// to fixup relative urls we create a new equivalent `init` object instead
init = {
// the request body must be consumed in memory until browsers
// implement streaming request bodies and/or the body getter
body:
resource.method === 'GET' || resource.method === 'HEAD'
? undefined
: await resource.blob(),
cache: resource.cache,
credentials: resource.credentials,
headers: resource.headers,
integrity: resource.integrity,
keepalive: resource.keepalive,
method: resource.method,
mode: resource.mode,
redirect: resource.redirect,
referrer: resource.referrer,
referrerPolicy: resource.referrerPolicy,
signal: resource.signal,
...init
};
}
// we must fixup relative urls so they are resolved from the target page
const normalized = new URL(requested, url).href;
add_dependency(normalized);
// prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be normalized
return started ? native_fetch(normalized, init) : initial_fetch(requested, init);
},
status: status ?? null,
error: error ?? null
};
if (import.meta.env.DEV) {
// TODO remove this for 1.0
Object.defineProperty(load_input, 'page', {
get: () => {
throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
}
});
}
let loaded;
if (import.meta.env.DEV) {
try {
lock_fetch();
loaded = await module.load.call(null, load_input);
} finally {
unlock_fetch();
}
} else {
loaded = await module.load.call(null, load_input);
}
if (!loaded) {
throw new Error('load function must return a value');
}
node.loaded = normalize(loaded);
if (node.loaded.stuff) node.stuff = node.loaded.stuff;
if (node.loaded.dependencies) {
node.loaded.dependencies.forEach(add_dependency);
}
} else if (props) {
node.loaded = normalize({ props });
}
return node;
}
/**
* @param {import('./types').NavigationIntent} intent
* @param {boolean} no_cache
*/
async function load_route({ id, url, params, route }, no_cache) {
if (load_cache.id === id && load_cache.promise) {
return load_cache.promise;
}
if (!no_cache) {
const cached = cache.get(id);
if (cached) return cached;
}
const { a, b, has_shadow } = route;
const changed = current.url && {
url: id !== current.url.pathname + current.url.search,
params: Object.keys(params).filter((key) => current.params[key] !== params[key]),
session: session_id !== current.session_id
};
/** @type {Array<import('./types').BranchNode | undefined>} */
let branch = [];
/** @type {Record<string, any>} */
let stuff = root_stuff;
let stuff_changed = false;
/** @type {number | undefined} */
let status = 200;
/** @type {Error | null} */
let error = null;
// preload modules to avoid waterfall, but handle rejections
// so they don't get reported to Sentry et al (we don't need
// to act on the failures at this point)
a.forEach((loader) => loader().catch(() => {}));
load: for (let i = 0; i < a.length; i += 1) {
/** @type {import('./types').BranchNode | undefined} */
let node;
try {
if (!a[i]) continue;
const module = await a[i]();
const previous = current.branch[i];
const changed_since_last_render =
!previous ||
module !== previous.module ||
(changed.url && previous.uses.url) ||
changed.params.some((param) => previous.uses.params.has(param)) ||
(changed.session && previous.uses.session) ||
Array.from(previous.uses.dependencies).some((dep) => invalidated.some((fn) => fn(dep))) ||
(stuff_changed && previous.uses.stuff);
if (changed_since_last_render) {
/** @type {Record<string, any>} */
let props = {};
const is_shadow_page = has_shadow && i === a.length - 1;
if (is_shadow_page) {
const res = await native_fetch(
`${url.pathname}${url.pathname.endsWith('/') ? '' : '/'}__data.json${url.search}`,
{
headers: {
'x-sveltekit-load': 'true'
}
}
);
if (res.ok) {
const redirect = res.headers.get('x-sveltekit-location');
if (redirect) {
return {
redirect,
props: {},
state: current
};
}
props = res.status === 204 ? {} : await res.json();
} else {
status = res.status;
error = new Error('Failed to load data');
}
}
if (!error) {
node = await load_node({
module,
url,
params,
props,
stuff,
routeId: route.id
});
}
if (node) {
if (is_shadow_page) {
node.uses.url = true;
}
if (node.loaded) {
if (node.loaded.error) {
status = node.loaded.status;
error = node.loaded.error;
}
if (node.loaded.redirect) {
return {
redirect: node.loaded.redirect,
props: {},
state: current
};
}
if (node.loaded.stuff) {
stuff_changed = true;
}
}
}
} else {
node = previous;
}
} catch (e) {
status = 500;
error = coalesce_to_error(e);
}
if (error) {
while (i--) {
if (b[i]) {
let error_loaded;
/** @type {import('./types').BranchNode | undefined} */
let node_loaded;
let j = i;
while (!(node_loaded = branch[j])) {
j -= 1;
}
try {
error_loaded = await load_node({
status,
error,
module: await b[i](),
url,
params,
stuff: node_loaded.stuff,
routeId: route.id
});
if (error_loaded?.loaded?.error) {
continue;
}
if (error_loaded?.loaded?.stuff) {
stuff = {
...stuff,
...error_loaded.loaded.stuff
};
}
branch = branch.slice(0, j + 1).concat(error_loaded);
break load;
} catch (e) {
continue;
}
}
}
return await load_root_error_page({
status,
error,
url,
routeId: route.id
});
} else {
if (node?.loaded?.stuff) {
stuff = {
...stuff,
...node.loaded.stuff
};
}
branch.push(node);
}
}
return await get_navigation_result_from_branch({
url,
params,
stuff,
branch,
status,
error,
routeId: route.id
});
}
/**
* @param {{
* status: number;
* error: Error;
* url: URL;
* routeId: string | null
* }} opts
*/
async function load_root_error_page({ status, error, url, routeId }) {
/** @type {Record<string, string>} */
const params = {}; // error page does not have params
const root_layout = await load_node({
module: await default_layout,
url,
params,
stuff: {},
routeId
});
const root_error = await load_node({
status,
error,
module: await default_error,
url,
params,
stuff: (root_layout && root_layout.loaded && root_layout.loaded.stuff) || {},
routeId
});
return await get_navigation_result_from_branch({
url,
params,
stuff: {
...root_layout?.loaded?.stuff,
...root_error?.loaded?.stuff
},
branch: [root_layout, root_error],
status,
error,
routeId
});
}
/** @param {URL} url */
function get_navigation_intent(url) {
if (url.origin !== location.origin || !url.pathname.startsWith(base)) return;
const path = decodeURI(url.pathname.slice(base.length) || '/');
for (const route of routes) {
const params = route.exec(path);
if (params) {
/** @type {import('./types').NavigationIntent} */
const intent = {
id: url.pathname + url.search,
route,
params,
url
};
return intent;
}
}
}
/**
* @param {{
* url: URL;
* scroll: { x: number, y: number } | null;
* keepfocus: boolean;
* redirect_chain: string[];
* details: {
* replaceState: boolean;
* state: any;
* } | null;
* accepted: () => void;
* blocked: () => void;
* }} opts
*/
async function navigate({ url, scroll, keepfocus, redirect_chain, details, accepted, blocked }) {
const from = current.url;
let should_block = false;
const navigation = {
from,
to: url,
cancel: () => (should_block = true)
};
callbacks.before_navigate.forEach((fn) => fn(navigation));
if (should_block) {
blocked();
return;
}
const pathname = normalize_path(url.pathname, trailing_slash);
const normalized = new URL(url.origin + pathname + url.search + url.hash);
update_scroll_positions(current_history_index);
accepted();
if (started) {
stores.navigating.set({
from: current.url,
to: normalized
});
}
await update(
normalized,
redirect_chain,
false,
{
scroll,
keepfocus,
details
},
() => {
const navigation = { from, to: normalized };
callbacks.after_navigate.forEach((fn) => fn(navigation));
stores.navigating.set(null);
}
);
}
/**
* Loads `href` the old-fashioned way, with a full page reload.
* Returns a `Promise` that never resolves (to prevent any
* subsequent work, e.g. history manipulation, from happening)
* @param {URL} url
*/
function native_navigation(url) {
location.href = url.href;
return new Promise(() => {});
}
if (import.meta.hot) {
import.meta.hot.on('vite:beforeUpdate', () => {
if (current.error) location.reload();
});
}
return {
after_navigate: (fn) => {
onMount(() => {
callbacks.after_navigate.push(fn);
return () => {