@xzsv/router 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +110 -2
- package/package.json +30 -4
- package/src/Link.svelte +70 -0
- package/src/Recursive.svelte +87 -0
- package/src/RouteNode.svelte +19 -0
- package/src/Router.svelte +57 -0
- package/src/create.svelte.ts +771 -0
- package/src/env.d.ts +3 -0
- package/src/index.ts +47 -0
- package/src/log.ts +6 -0
- package/src/route-node-context.ts +6 -0
- package/src/types.ts +364 -0
- package/src/utils.ts +549 -0
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
import { getContext, tick } from 'svelte'
|
|
2
|
+
import type { Action } from 'svelte/action'
|
|
3
|
+
import { SvelteURLSearchParams } from 'svelte/reactivity'
|
|
4
|
+
import { log } from './log.ts'
|
|
5
|
+
import { type RouteNodeCtx, routeNodeKey } from './route-node-context.ts'
|
|
6
|
+
import type {
|
|
7
|
+
ComponentTree,
|
|
8
|
+
Cycle,
|
|
9
|
+
Hooks,
|
|
10
|
+
Location,
|
|
11
|
+
NavigateOptions,
|
|
12
|
+
Phase,
|
|
13
|
+
RouteNodeInfo,
|
|
14
|
+
RouterApi,
|
|
15
|
+
Routes,
|
|
16
|
+
TransitionFn,
|
|
17
|
+
Transitions,
|
|
18
|
+
} from './types.ts'
|
|
19
|
+
import {
|
|
20
|
+
calculateTree,
|
|
21
|
+
cleanMountedComponents,
|
|
22
|
+
constructPath,
|
|
23
|
+
getCompKeys,
|
|
24
|
+
getLocation,
|
|
25
|
+
isActive,
|
|
26
|
+
join,
|
|
27
|
+
matchRoute,
|
|
28
|
+
preloadOnHover,
|
|
29
|
+
resolveRouteComponents,
|
|
30
|
+
validateRoutes,
|
|
31
|
+
} from './utils.ts'
|
|
32
|
+
|
|
33
|
+
// ============================================================================
|
|
34
|
+
// Global State
|
|
35
|
+
// ============================================================================
|
|
36
|
+
|
|
37
|
+
let routes: Routes
|
|
38
|
+
|
|
39
|
+
export const componentTree: ComponentTree = $state({
|
|
40
|
+
value: { a: [], b: [], eq: 0 },
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
export const cycle: Cycle = $state({
|
|
44
|
+
value: 'a' as 'a' | 'ba' | 'b' | 'ab',
|
|
45
|
+
from: 'a',
|
|
46
|
+
|
|
47
|
+
get to() {
|
|
48
|
+
return this.from === 'a' ? 'b' : 'a'
|
|
49
|
+
},
|
|
50
|
+
get first() {
|
|
51
|
+
return this.value[0] as 'a' | 'b'
|
|
52
|
+
},
|
|
53
|
+
get second() {
|
|
54
|
+
return this.value[1] as 'a' | 'b' | undefined
|
|
55
|
+
},
|
|
56
|
+
get chars() {
|
|
57
|
+
return this.value.split('') as ReadonlyArray<('a' | 'b')>
|
|
58
|
+
},
|
|
59
|
+
get isSingle(): boolean {
|
|
60
|
+
return this.value.length === 1
|
|
61
|
+
},
|
|
62
|
+
get isDual(): boolean {
|
|
63
|
+
return this.value.length === 2
|
|
64
|
+
},
|
|
65
|
+
get filled(): 'ab' | 'ba' {
|
|
66
|
+
return this.to + this.from as 'ab' | 'ba'
|
|
67
|
+
},
|
|
68
|
+
|
|
69
|
+
fill(): void {
|
|
70
|
+
this.value = this.filled
|
|
71
|
+
},
|
|
72
|
+
finalize(): void {
|
|
73
|
+
this.value = this.to
|
|
74
|
+
},
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
export const params: { value: Record<string, string> } = $state({ value: {} })
|
|
78
|
+
|
|
79
|
+
export const phase: { value: Phase } = $state({ value: 'idle' })
|
|
80
|
+
|
|
81
|
+
export const location: Location = $state(getLocation())
|
|
82
|
+
|
|
83
|
+
export const base: { name?: string | undefined } = { name: undefined }
|
|
84
|
+
|
|
85
|
+
export const mountedComponents: Record<string, any> = $state({})
|
|
86
|
+
|
|
87
|
+
let isFirstNavigation = $state(true)
|
|
88
|
+
let navigationId = 0
|
|
89
|
+
let navigationAbort: AbortController | null = null
|
|
90
|
+
let pendingNavigation: { path: string | undefined; options: NavigateOptions } | null = null
|
|
91
|
+
let transitionsConfig: Transitions | undefined
|
|
92
|
+
const nodeElements = new Map<string, Set<HTMLElement>>()
|
|
93
|
+
|
|
94
|
+
// ============================================================================
|
|
95
|
+
// Search Params
|
|
96
|
+
// ============================================================================
|
|
97
|
+
|
|
98
|
+
let searchParams = new SvelteURLSearchParams(globalThis.location.search)
|
|
99
|
+
|
|
100
|
+
export const searchParamsProxy = {
|
|
101
|
+
append(name: string, value: string, options?: { replace?: boolean }) {
|
|
102
|
+
searchParams.append(name, value)
|
|
103
|
+
updateUrlSearchParams(options)
|
|
104
|
+
},
|
|
105
|
+
delete(name: string, value?: string, options?: { replace?: boolean }) {
|
|
106
|
+
searchParams.delete(name, value)
|
|
107
|
+
updateUrlSearchParams(options)
|
|
108
|
+
},
|
|
109
|
+
entries() {
|
|
110
|
+
return searchParams.entries()
|
|
111
|
+
},
|
|
112
|
+
forEach(...args: Parameters<URLSearchParams['forEach']>) {
|
|
113
|
+
return searchParams.forEach(...args)
|
|
114
|
+
},
|
|
115
|
+
get(...args: Parameters<URLSearchParams['get']>) {
|
|
116
|
+
return searchParams.get(...args)
|
|
117
|
+
},
|
|
118
|
+
getAll(...args: Parameters<URLSearchParams['getAll']>) {
|
|
119
|
+
return searchParams.getAll(...args)
|
|
120
|
+
},
|
|
121
|
+
has(...args: Parameters<URLSearchParams['has']>) {
|
|
122
|
+
return searchParams.has(...args)
|
|
123
|
+
},
|
|
124
|
+
keys() {
|
|
125
|
+
return searchParams.keys()
|
|
126
|
+
},
|
|
127
|
+
set(name: string, value: string, options?: { replace?: boolean }) {
|
|
128
|
+
searchParams.set(name, value)
|
|
129
|
+
updateUrlSearchParams(options)
|
|
130
|
+
},
|
|
131
|
+
sort(options?: { replace?: boolean }) {
|
|
132
|
+
searchParams.sort()
|
|
133
|
+
updateUrlSearchParams(options)
|
|
134
|
+
},
|
|
135
|
+
toString() {
|
|
136
|
+
return searchParams.toString()
|
|
137
|
+
},
|
|
138
|
+
values() {
|
|
139
|
+
return searchParams.values()
|
|
140
|
+
},
|
|
141
|
+
get size() {
|
|
142
|
+
return searchParams.size
|
|
143
|
+
},
|
|
144
|
+
[Symbol.iterator]() {
|
|
145
|
+
return searchParams[Symbol.iterator]()
|
|
146
|
+
},
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function syncSearchParams() {
|
|
150
|
+
const newSearchParams = new URLSearchParams(globalThis.location.search)
|
|
151
|
+
if (searchParams.toString() === newSearchParams.toString()) {
|
|
152
|
+
return
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Mutate the existing instance rather than replacing it: readers hold a
|
|
156
|
+
// reactive dependency on this instance's version signal, so a fresh
|
|
157
|
+
// instance would leave them stale.
|
|
158
|
+
for (const key of [...searchParams.keys()]) {
|
|
159
|
+
searchParams.delete(key)
|
|
160
|
+
}
|
|
161
|
+
for (const [key, value] of newSearchParams.entries()) {
|
|
162
|
+
searchParams.append(key, value)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function updateUrlSearchParams(options?: { replace?: boolean }) {
|
|
167
|
+
let url = globalThis.location.origin + globalThis.location.pathname
|
|
168
|
+
if (searchParams.size > 0) {
|
|
169
|
+
url += '?' + searchParams.toString()
|
|
170
|
+
}
|
|
171
|
+
globalThis.history[options?.replace ? 'replaceState' : 'pushState'](
|
|
172
|
+
{},
|
|
173
|
+
'',
|
|
174
|
+
url,
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ============================================================================
|
|
179
|
+
// Router API
|
|
180
|
+
// ============================================================================
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Create a new router instance
|
|
184
|
+
*/
|
|
185
|
+
export function createRouter<T extends Routes>(config: {
|
|
186
|
+
routes: T
|
|
187
|
+
transitions?: Transitions
|
|
188
|
+
/** URL prefix stripped from route matching and prepended to hrefs. */
|
|
189
|
+
base?: string
|
|
190
|
+
}): RouterApi<T> {
|
|
191
|
+
log.debug('createRouter')
|
|
192
|
+
routes = config.routes
|
|
193
|
+
transitionsConfig = config.transitions
|
|
194
|
+
// Set base BEFORE anything renders: Link hrefs read it during
|
|
195
|
+
// initial render, long before <Router> onMount could (ISSUES #7).
|
|
196
|
+
base.name = config.base
|
|
197
|
+
? config.base.startsWith('/') ? config.base : `/${config.base}`
|
|
198
|
+
: undefined
|
|
199
|
+
|
|
200
|
+
// Fresh run: clear state from any previous router instance (tests, HMR,
|
|
201
|
+
// remounts). Leftover trees would otherwise leak into the first
|
|
202
|
+
// navigation as phantom in/out nodes and strand the cycle mid-swap.
|
|
203
|
+
navigationId++
|
|
204
|
+
navigationAbort?.abort()
|
|
205
|
+
navigationAbort = null
|
|
206
|
+
pendingNavigation = null
|
|
207
|
+
isFirstNavigation = true
|
|
208
|
+
phase.value = 'idle'
|
|
209
|
+
params.value = {}
|
|
210
|
+
componentTree.value = { a: [], b: [], eq: 0 }
|
|
211
|
+
cycle.value = 'a'
|
|
212
|
+
cycle.from = 'a'
|
|
213
|
+
preloadedPaths.clear()
|
|
214
|
+
for (const key of Object.keys(mountedComponents)) delete mountedComponents[key]
|
|
215
|
+
nodeElements.clear()
|
|
216
|
+
|
|
217
|
+
if (
|
|
218
|
+
import.meta.env?.DEV
|
|
219
|
+
&& !import.meta.env?.SSR
|
|
220
|
+
&& typeof window !== 'undefined'
|
|
221
|
+
) {
|
|
222
|
+
validateRoutes(routes)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
preloadOnHover(routes, base.name)
|
|
226
|
+
|
|
227
|
+
// utils.isActive takes the current pathname as an argument so it stays
|
|
228
|
+
// pure; the API version closes over the reactive `location` state, so
|
|
229
|
+
// reads from templates/effects re-evaluate when navigation happens
|
|
230
|
+
// (globalThis.location is NOT a reactive read).
|
|
231
|
+
// location.pathname includes the base; route matching does not.
|
|
232
|
+
const strippedPathname = () => {
|
|
233
|
+
if (base.name && location.pathname.startsWith(base.name)) {
|
|
234
|
+
return location.pathname.slice(base.name.length) || '/'
|
|
235
|
+
}
|
|
236
|
+
return location.pathname
|
|
237
|
+
}
|
|
238
|
+
const isActiveApi = (path: string, params?: Record<string, string>) => isActive(strippedPathname(), path, params)
|
|
239
|
+
isActiveApi.startsWith = (path: string, params?: Record<string, string>) =>
|
|
240
|
+
isActive.startsWith(strippedPathname(), path, params)
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
p: constructPath,
|
|
244
|
+
C: componentTree,
|
|
245
|
+
MC: mountedComponents,
|
|
246
|
+
navigate,
|
|
247
|
+
preload: preloadRoute,
|
|
248
|
+
isActive: isActiveApi,
|
|
249
|
+
phase,
|
|
250
|
+
route: {
|
|
251
|
+
get params() {
|
|
252
|
+
return params.value
|
|
253
|
+
},
|
|
254
|
+
get pathname() {
|
|
255
|
+
return location.pathname as any
|
|
256
|
+
},
|
|
257
|
+
get search() {
|
|
258
|
+
return location.search
|
|
259
|
+
},
|
|
260
|
+
get state() {
|
|
261
|
+
return location.state
|
|
262
|
+
},
|
|
263
|
+
get hash() {
|
|
264
|
+
return location.hash
|
|
265
|
+
},
|
|
266
|
+
get phase() {
|
|
267
|
+
return phase.value
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// ============================================================================
|
|
274
|
+
// Route-node transitions
|
|
275
|
+
// ============================================================================
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Svelte 5.29 attachment for route component root elements. Place it on
|
|
279
|
+
* the root element of pages (and any layout you want animated — nodes in
|
|
280
|
+
* the shared-eq range never fire, so persistent layouts stay put). The
|
|
281
|
+
* router dispatches `transitions.enter/leave` to registered elements and
|
|
282
|
+
* awaits settle before the outgoing tree unmounts.
|
|
283
|
+
*/
|
|
284
|
+
export function routeNode(el: HTMLElement): (() => void) | undefined {
|
|
285
|
+
const node = getContext<RouteNodeCtx | undefined>(routeNodeKey)
|
|
286
|
+
if (!node) {
|
|
287
|
+
log.warn('routeNode attachment used outside a route component — ignoring')
|
|
288
|
+
return
|
|
289
|
+
}
|
|
290
|
+
const id = `${node.depth} ${node.key}`
|
|
291
|
+
let els = nodeElements.get(id)
|
|
292
|
+
if (!els) {
|
|
293
|
+
els = new Set()
|
|
294
|
+
nodeElements.set(id, els)
|
|
295
|
+
}
|
|
296
|
+
els.add(el)
|
|
297
|
+
return () => {
|
|
298
|
+
const set = nodeElements.get(id)
|
|
299
|
+
if (!set) return
|
|
300
|
+
set.delete(el)
|
|
301
|
+
if (set.size === 0) nodeElements.delete(id)
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function elementsFor(id: string): HTMLElement[] {
|
|
306
|
+
return [...(nodeElements.get(id) ?? [])]
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Dual-fill the tree, dispatch enter/leave to every registered element of
|
|
311
|
+
* the in/out nodes, then wait for returned promises (bounded by timeoutMs)
|
|
312
|
+
* before finalize unmounts the outgoing side.
|
|
313
|
+
*/
|
|
314
|
+
async function runTransitions(from: string, to: string): Promise<void> {
|
|
315
|
+
if (!transitionsConfig) return
|
|
316
|
+
const { enter, leave, timeoutMs = 1000, viewTransition = false } = transitionsConfig
|
|
317
|
+
|
|
318
|
+
const jobs: Promise<unknown>[] = []
|
|
319
|
+
|
|
320
|
+
const applyAndCollect = async (): Promise<void> => {
|
|
321
|
+
cycle.fill()
|
|
322
|
+
await tick()
|
|
323
|
+
|
|
324
|
+
const { in: inKeys, out: outKeys } = getCompKeys(componentTree.value, cycle)
|
|
325
|
+
let dispatched = 0
|
|
326
|
+
|
|
327
|
+
const dispatch = (fn: TransitionFn | undefined, ids: string[]): void => {
|
|
328
|
+
if (!fn) return
|
|
329
|
+
for (const id of ids) {
|
|
330
|
+
const [depth, key] = id.split(' ')
|
|
331
|
+
const info: RouteNodeInfo = {
|
|
332
|
+
depth: Number(depth),
|
|
333
|
+
key: Number(key),
|
|
334
|
+
from,
|
|
335
|
+
to,
|
|
336
|
+
}
|
|
337
|
+
for (const el of elementsFor(id)) {
|
|
338
|
+
dispatched++
|
|
339
|
+
const result = fn(el, info)
|
|
340
|
+
if (result) {
|
|
341
|
+
jobs.push(
|
|
342
|
+
Promise.resolve(result).catch((err) => {
|
|
343
|
+
log.error(`transition callback failed for ${to}: ${String(err)}`)
|
|
344
|
+
}),
|
|
345
|
+
)
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
dispatch(enter, inKeys)
|
|
351
|
+
dispatch(leave, outKeys)
|
|
352
|
+
|
|
353
|
+
// Configured transitions with nothing registered means every
|
|
354
|
+
// animation silently no-ops — almost always a missing
|
|
355
|
+
// {@attach routeNode} on a page root.
|
|
356
|
+
if (
|
|
357
|
+
(enter || leave)
|
|
358
|
+
&& (inKeys.length > 0 || outKeys.length > 0)
|
|
359
|
+
&& dispatched === 0
|
|
360
|
+
) {
|
|
361
|
+
log.warn(
|
|
362
|
+
'transitions are configured, but no routeNode elements were found for this navigation — add {@attach routeNode} to the root element of pages you want animated',
|
|
363
|
+
)
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (
|
|
368
|
+
viewTransition
|
|
369
|
+
&& typeof document !== 'undefined'
|
|
370
|
+
&& typeof document.startViewTransition === 'function'
|
|
371
|
+
) {
|
|
372
|
+
// Same-document View Transition: the dual-tree fill is the DOM
|
|
373
|
+
// mutation; `::view-transition-*` CSS does the animating. Falls back
|
|
374
|
+
// to a plain swap when the API is missing (happy-dom, old engines).
|
|
375
|
+
document.startViewTransition(() => applyAndCollect())
|
|
376
|
+
} else {
|
|
377
|
+
await applyAndCollect()
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (jobs.length === 0) return
|
|
381
|
+
|
|
382
|
+
const startedAt = performance.now()
|
|
383
|
+
await new Promise<void>((resolve) => {
|
|
384
|
+
const timer = setTimeout(() => {
|
|
385
|
+
log.warn(`transitions settle timed out after ${timeoutMs}ms — finalizing`)
|
|
386
|
+
resolve()
|
|
387
|
+
}, timeoutMs)
|
|
388
|
+
Promise.allSettled(jobs).then(() => {
|
|
389
|
+
clearTimeout(timer)
|
|
390
|
+
resolve()
|
|
391
|
+
})
|
|
392
|
+
})
|
|
393
|
+
log.debug(
|
|
394
|
+
`transitions settled in ${Math.round(performance.now() - startedAt)}ms (${jobs.length} jobs, ${to})`,
|
|
395
|
+
)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Navigate to a route
|
|
400
|
+
*/
|
|
401
|
+
function go(path: string | number, options: NavigateOptions) {
|
|
402
|
+
if (typeof path === 'number') {
|
|
403
|
+
navigationId++
|
|
404
|
+
navigationAbort?.abort()
|
|
405
|
+
globalThis.history.go(path)
|
|
406
|
+
return
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
onNavigate(path, options)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function navigate(path: string | number, options: NavigateOptions = {}) {
|
|
413
|
+
// Navigation requested from inside an effect (mount-time guards, auth
|
|
414
|
+
// redirects) must not run synchronously: superseding writes reactive
|
|
415
|
+
// state, which would re-trigger the very effect that called us — an
|
|
416
|
+
// infinite busy-loop. Defer past the effect flush instead.
|
|
417
|
+
if ($effect.tracking()) {
|
|
418
|
+
queueMicrotask(() => go(path, options))
|
|
419
|
+
return
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
go(path, options)
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const preloadedPaths = new Set<string>()
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Programmatically resolve (and warm) a route's components — the same work
|
|
429
|
+
* hover-preloading does for `data-preload` anchors, callable from
|
|
430
|
+
* pointerdown/focus handlers, idle callbacks, or boot sequences. Deduped
|
|
431
|
+
* per path; a failed preload is retried on the next call.
|
|
432
|
+
*/
|
|
433
|
+
export function preloadRoute(path: string): Promise<void> {
|
|
434
|
+
if (!routes) return Promise.resolve()
|
|
435
|
+
if (base.name && path.startsWith(base.name)) {
|
|
436
|
+
path = path.slice(base.name.length) || '/'
|
|
437
|
+
}
|
|
438
|
+
const { match, layouts } = matchRoute(path, routes)
|
|
439
|
+
if (!match) return Promise.resolve()
|
|
440
|
+
if (preloadedPaths.has(path)) return Promise.resolve()
|
|
441
|
+
|
|
442
|
+
return resolveRouteComponents([...layouts, match]).then(
|
|
443
|
+
() => {
|
|
444
|
+
preloadedPaths.add(path)
|
|
445
|
+
},
|
|
446
|
+
(err) => {
|
|
447
|
+
log.error(`preload failed for ${path}: ${String(err)}`)
|
|
448
|
+
},
|
|
449
|
+
)
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Main navigation handler
|
|
454
|
+
*/
|
|
455
|
+
export async function onNavigate(path?: string, options: NavigateOptions = {}) {
|
|
456
|
+
log.debug('onNavigate', { path, options })
|
|
457
|
+
// Prevent HMR from triggering navigation
|
|
458
|
+
if (!path && location.pathname === globalThis.location.pathname) {
|
|
459
|
+
if (isFirstNavigation) {
|
|
460
|
+
isFirstNavigation = false
|
|
461
|
+
} else {
|
|
462
|
+
return
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
if (!routes || Object.keys(routes).length === 0) {
|
|
467
|
+
throw new Error(
|
|
468
|
+
'Router has no routes. Call createRouter({ routes }) in a module that is imported before <Router> mounts.',
|
|
469
|
+
)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (phase.value !== 'idle' && phase.value !== 'error') {
|
|
473
|
+
// Supersede: invalidate the in-flight navigation (it abandons at
|
|
474
|
+
// its next checkpoint) and stash this request to run once it
|
|
475
|
+
// unwinds. Last write wins. No cycle writes here — every pipeline
|
|
476
|
+
// exit path reverts or collapses on its own, and writing reactive
|
|
477
|
+
// state synchronously from an effect-context caller would
|
|
478
|
+
// re-trigger that caller (the ko26 busy-loop).
|
|
479
|
+
navigationId++
|
|
480
|
+
navigationAbort?.abort()
|
|
481
|
+
pendingNavigation = { path, options }
|
|
482
|
+
return
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const abortCtrl = new AbortController()
|
|
486
|
+
navigationAbort = abortCtrl
|
|
487
|
+
const signal = abortCtrl.signal
|
|
488
|
+
|
|
489
|
+
// Generation token: any navigation started after this one (supersede,
|
|
490
|
+
// hook redirect, popstate) bumps `navigationId`, and this pipeline
|
|
491
|
+
// abandons at its next checkpoint. Replaces the old stack-sniffing.
|
|
492
|
+
const myId = ++navigationId
|
|
493
|
+
const isStale = () => myId !== navigationId
|
|
494
|
+
let errored = false
|
|
495
|
+
|
|
496
|
+
const prevComponentTree = componentTree.value
|
|
497
|
+
|
|
498
|
+
const revertLoading = () => {
|
|
499
|
+
cycle.value = cycle.from
|
|
500
|
+
componentTree.value = prevComponentTree
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// Match the route
|
|
504
|
+
let matchPath = path || globalThis.location.pathname
|
|
505
|
+
if (base.name && matchPath.startsWith(base.name)) {
|
|
506
|
+
matchPath = matchPath.slice(base.name.length) || '/'
|
|
507
|
+
}
|
|
508
|
+
let from = location.pathname
|
|
509
|
+
|
|
510
|
+
const {
|
|
511
|
+
match,
|
|
512
|
+
layouts,
|
|
513
|
+
hooks,
|
|
514
|
+
params: newParams,
|
|
515
|
+
} = matchRoute(matchPath, routes)
|
|
516
|
+
|
|
517
|
+
// Skip hooks if bypass is enabled. Pass the stripped matchPath so
|
|
518
|
+
// updateNavigation joins the base exactly once (URL-sourced paths
|
|
519
|
+
// arrive base-prefixed; navigate() paths do not).
|
|
520
|
+
if (options.bypass) {
|
|
521
|
+
updateNavigation(path ? matchPath : undefined, newParams, options)
|
|
522
|
+
return
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ========================================================================
|
|
526
|
+
// beforeLoad Hook
|
|
527
|
+
// ========================================================================
|
|
528
|
+
try {
|
|
529
|
+
phase.value = 'beforeLoad'
|
|
530
|
+
await tick()
|
|
531
|
+
|
|
532
|
+
for (const { beforeLoad } of hooks) {
|
|
533
|
+
try {
|
|
534
|
+
await beforeLoad?.(
|
|
535
|
+
{
|
|
536
|
+
cycle,
|
|
537
|
+
match,
|
|
538
|
+
params: newParams,
|
|
539
|
+
from,
|
|
540
|
+
to: matchPath,
|
|
541
|
+
signal,
|
|
542
|
+
} as Parameters<NonNullable<Hooks['beforeLoad']>>[0],
|
|
543
|
+
)
|
|
544
|
+
} catch (err) {
|
|
545
|
+
errored = true
|
|
546
|
+
log.error(`beforeLoad hook failed for ${matchPath}: ${String(err)}`)
|
|
547
|
+
if (!isStale()) revertLoading()
|
|
548
|
+
return
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (isStale()) {
|
|
553
|
+
log.debug(`navigation to ${matchPath} superseded (beforeLoad)`)
|
|
554
|
+
return
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// ========================================================================
|
|
558
|
+
// Resolve Components
|
|
559
|
+
// ========================================================================
|
|
560
|
+
const routeComponents = await resolveRouteComponents(
|
|
561
|
+
match ? [...layouts, match] : layouts,
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
componentTree.value = calculateTree({
|
|
565
|
+
prev: componentTree.value,
|
|
566
|
+
next: routeComponents,
|
|
567
|
+
cycle,
|
|
568
|
+
params: newParams,
|
|
569
|
+
mountedComponents,
|
|
570
|
+
})
|
|
571
|
+
|
|
572
|
+
// ========================================================================
|
|
573
|
+
// duringLoad Hook
|
|
574
|
+
// ========================================================================
|
|
575
|
+
phase.value = 'duringLoad'
|
|
576
|
+
await tick()
|
|
577
|
+
|
|
578
|
+
for (const { duringLoad } of hooks) {
|
|
579
|
+
try {
|
|
580
|
+
await duringLoad?.({
|
|
581
|
+
cycle,
|
|
582
|
+
componentTree: componentTree.value,
|
|
583
|
+
mountedComponents,
|
|
584
|
+
keys: getCompKeys(componentTree.value, cycle),
|
|
585
|
+
from,
|
|
586
|
+
to: matchPath,
|
|
587
|
+
signal,
|
|
588
|
+
})
|
|
589
|
+
} catch (err) {
|
|
590
|
+
errored = true
|
|
591
|
+
log.error(`duringLoad hook failed for ${matchPath}: ${String(err)}`)
|
|
592
|
+
if (!isStale()) revertLoading()
|
|
593
|
+
return
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if (isStale()) {
|
|
598
|
+
log.debug(`navigation to ${matchPath} superseded (duringLoad)`)
|
|
599
|
+
// calculateTree already replaced the tree above; undo it so the
|
|
600
|
+
// superseding navigation starts from the settled previous tree.
|
|
601
|
+
revertLoading()
|
|
602
|
+
return
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// ========================================================================
|
|
606
|
+
// Update Navigation
|
|
607
|
+
// ========================================================================
|
|
608
|
+
updateNavigation(path ? matchPath : undefined, newParams, options)
|
|
609
|
+
|
|
610
|
+
// ========================================================================
|
|
611
|
+
// duringRender Hook
|
|
612
|
+
// ========================================================================
|
|
613
|
+
phase.value = 'duringRender'
|
|
614
|
+
await tick()
|
|
615
|
+
|
|
616
|
+
for (const { duringRender } of hooks) {
|
|
617
|
+
try {
|
|
618
|
+
await duringRender?.({
|
|
619
|
+
cycle,
|
|
620
|
+
componentTree: componentTree.value,
|
|
621
|
+
mountedComponents,
|
|
622
|
+
keys: getCompKeys(componentTree.value, cycle),
|
|
623
|
+
from,
|
|
624
|
+
to: matchPath,
|
|
625
|
+
signal,
|
|
626
|
+
})
|
|
627
|
+
} catch (err) {
|
|
628
|
+
log.error(`SVR ERROR duringRender: ${String(err)}`)
|
|
629
|
+
// Continue even if duringRender fails
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
await runTransitions(from, matchPath)
|
|
634
|
+
if (isStale()) {
|
|
635
|
+
log.debug(`navigation to ${matchPath} superseded (transitions)`)
|
|
636
|
+
// The URL already points at the incoming side (updateNavigation ran),
|
|
637
|
+
// so collapse onto it instead of leaving the tree dual forever.
|
|
638
|
+
if (cycle.isDual) cycle.value = cycle.first
|
|
639
|
+
return
|
|
640
|
+
}
|
|
641
|
+
if (cycle.value.length === 1) cycle.fill()
|
|
642
|
+
cycle.finalize()
|
|
643
|
+
cycle.finalize()
|
|
644
|
+
|
|
645
|
+
// ========================================================================
|
|
646
|
+
// afterRender Hook
|
|
647
|
+
// ========================================================================
|
|
648
|
+
phase.value = 'afterRender'
|
|
649
|
+
await tick()
|
|
650
|
+
|
|
651
|
+
for (const { afterRender } of hooks) {
|
|
652
|
+
try {
|
|
653
|
+
afterRender?.({
|
|
654
|
+
cycle,
|
|
655
|
+
componentTree: componentTree.value,
|
|
656
|
+
mountedComponents,
|
|
657
|
+
keys: getCompKeys(componentTree.value, cycle),
|
|
658
|
+
from,
|
|
659
|
+
to: matchPath,
|
|
660
|
+
signal,
|
|
661
|
+
})
|
|
662
|
+
} catch (err) {
|
|
663
|
+
log.error(`SVR ERROR afterRender: ${String(err)}`)
|
|
664
|
+
// Continue even if afterRender fails
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
} catch (err) {
|
|
668
|
+
// Anything thrown outside a hook's own try/catch (failing lazy
|
|
669
|
+
// chunk, calculateTree, updateNavigation) fails the navigation.
|
|
670
|
+
errored = true
|
|
671
|
+
log.error(`navigation to ${matchPath} failed: ${String(err)}`)
|
|
672
|
+
if (!isStale()) revertLoading()
|
|
673
|
+
} finally {
|
|
674
|
+
cycle.from = cycle.first
|
|
675
|
+
|
|
676
|
+
if (navigationAbort === abortCtrl) navigationAbort = null
|
|
677
|
+
|
|
678
|
+
phase.value = errored ? 'error' : 'idle'
|
|
679
|
+
cleanMountedComponents(mountedComponents, componentTree)
|
|
680
|
+
|
|
681
|
+
// Process deferred navigation
|
|
682
|
+
if (pendingNavigation) {
|
|
683
|
+
const pn = pendingNavigation
|
|
684
|
+
pendingNavigation = null
|
|
685
|
+
// Use microtask to avoid re-entrancy
|
|
686
|
+
queueMicrotask(() => onNavigate(pn.path, pn.options))
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Update browser history and location state
|
|
693
|
+
*/
|
|
694
|
+
function updateNavigation(
|
|
695
|
+
path: string | undefined,
|
|
696
|
+
newParams: Record<string, string>,
|
|
697
|
+
options: NavigateOptions,
|
|
698
|
+
) {
|
|
699
|
+
if (path) {
|
|
700
|
+
if (options.search) path += options.search
|
|
701
|
+
if (options.hash) path += options.hash
|
|
702
|
+
|
|
703
|
+
const historyMethod = options.replace ? 'replaceState' : 'pushState'
|
|
704
|
+
const to = base.name ? join(base.name, path) : path
|
|
705
|
+
globalThis.history[historyMethod](options.state || {}, '', to)
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
params.value = newParams || {}
|
|
709
|
+
syncSearchParams()
|
|
710
|
+
Object.assign(location, getLocation())
|
|
711
|
+
|
|
712
|
+
if (options.scrollToTop !== false) {
|
|
713
|
+
window.scrollTo({
|
|
714
|
+
top: 0,
|
|
715
|
+
left: 0,
|
|
716
|
+
...(options.scrollToTop !== undefined ? { behavior: options.scrollToTop } : {}),
|
|
717
|
+
})
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* Global click handler to intercept anchor clicks
|
|
723
|
+
*/
|
|
724
|
+
export function onGlobalClick(event: Event) {
|
|
725
|
+
if (!(event.target instanceof HTMLElement)) return
|
|
726
|
+
|
|
727
|
+
const anchor = event.target.closest('a')
|
|
728
|
+
if (!anchor) return
|
|
729
|
+
|
|
730
|
+
if (anchor.hasAttribute('target') || anchor.hasAttribute('download')) return
|
|
731
|
+
|
|
732
|
+
const url = new URL(anchor.href)
|
|
733
|
+
const currentOrigin = globalThis.location.origin
|
|
734
|
+
if (url.origin !== currentOrigin) return
|
|
735
|
+
|
|
736
|
+
event.preventDefault()
|
|
737
|
+
|
|
738
|
+
const { replace, state, scrollToTop } = anchor.dataset
|
|
739
|
+
onNavigate(url.pathname, {
|
|
740
|
+
replace: replace === '' || replace === 'true',
|
|
741
|
+
search: url.search,
|
|
742
|
+
...(state !== undefined ? { state } : {}),
|
|
743
|
+
hash: url.hash,
|
|
744
|
+
scrollToTop: scrollToTop === 'false' ? false : (scrollToTop as ScrollBehavior),
|
|
745
|
+
})
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* Svelte action to add active class to links
|
|
750
|
+
*/
|
|
751
|
+
export const isActiveLink: Action<
|
|
752
|
+
HTMLAnchorElement,
|
|
753
|
+
{ className?: string; startsWith?: boolean } | undefined
|
|
754
|
+
> = (node, { className = 'is-active', startsWith = false } = {}) => {
|
|
755
|
+
if (node.tagName !== 'A') {
|
|
756
|
+
throw new Error('isActiveLink can only be used on <a> elements')
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
$effect(() => {
|
|
760
|
+
const pathname = new URL(node.href).pathname
|
|
761
|
+
if (
|
|
762
|
+
startsWith
|
|
763
|
+
? location.pathname.startsWith(pathname)
|
|
764
|
+
: location.pathname === pathname
|
|
765
|
+
) {
|
|
766
|
+
node.classList.add(className)
|
|
767
|
+
} else {
|
|
768
|
+
node.classList.remove(className)
|
|
769
|
+
}
|
|
770
|
+
})
|
|
771
|
+
}
|