@xzsv/router 0.0.0-stage → 0.2.2

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.
@@ -0,0 +1,694 @@
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
+ }): RouterApi<T> {
189
+ log.debug('createRouter')
190
+ routes = config.routes
191
+ transitionsConfig = config.transitions
192
+
193
+ // Fresh run: clear state from any previous router instance (tests, HMR,
194
+ // remounts). Leftover trees would otherwise leak into the first
195
+ // navigation as phantom in/out nodes and strand the cycle mid-swap.
196
+ navigationId++
197
+ navigationAbort?.abort()
198
+ navigationAbort = null
199
+ pendingNavigation = null
200
+ isFirstNavigation = true
201
+ phase.value = 'idle'
202
+ params.value = {}
203
+ componentTree.value = { a: [], b: [], eq: 0 }
204
+ cycle.value = 'a'
205
+ cycle.from = 'a'
206
+ preloadedPaths.clear()
207
+ for (const key of Object.keys(mountedComponents)) delete mountedComponents[key]
208
+ nodeElements.clear()
209
+
210
+ if (
211
+ import.meta.env?.DEV
212
+ && !import.meta.env?.SSR
213
+ && typeof window !== 'undefined'
214
+ ) {
215
+ validateRoutes(routes)
216
+ }
217
+
218
+ preloadOnHover(routes)
219
+
220
+ // utils.isActive takes the current pathname as an argument so it stays
221
+ // pure; the API version closes over the reactive `location` state, so
222
+ // reads from templates/effects re-evaluate when navigation happens
223
+ // (globalThis.location is NOT a reactive read).
224
+ const isActiveApi = (path: string, params?: Record<string, string>) => isActive(location.pathname, path, params)
225
+ isActiveApi.startsWith = (path: string, params?: Record<string, string>) =>
226
+ isActive.startsWith(location.pathname, path, params)
227
+
228
+ return {
229
+ p: constructPath,
230
+ C: componentTree,
231
+ MC: mountedComponents,
232
+ navigate,
233
+ preload: preloadRoute,
234
+ isActive: isActiveApi,
235
+ phase,
236
+ route: {
237
+ get params() {
238
+ return params.value
239
+ },
240
+ get pathname() {
241
+ return location.pathname as any
242
+ },
243
+ get search() {
244
+ return location.search
245
+ },
246
+ get state() {
247
+ return location.state
248
+ },
249
+ get hash() {
250
+ return location.hash
251
+ },
252
+ get phase() {
253
+ return phase.value
254
+ },
255
+ },
256
+ }
257
+ }
258
+
259
+ // ============================================================================
260
+ // Route-node transitions
261
+ // ============================================================================
262
+
263
+ /**
264
+ * Svelte 5.29 attachment for route component root elements. Place it on
265
+ * the root element of pages (and any layout you want animated — nodes in
266
+ * the shared-eq range never fire, so persistent layouts stay put). The
267
+ * router dispatches `transitions.enter/leave` to registered elements and
268
+ * awaits settle before the outgoing tree unmounts.
269
+ */
270
+ export function routeNode(el: HTMLElement): (() => void) | undefined {
271
+ const node = getContext<RouteNodeCtx | undefined>(routeNodeKey)
272
+ if (!node) {
273
+ log.warn('routeNode attachment used outside a route component — ignoring')
274
+ return
275
+ }
276
+ const id = `${node.depth} ${node.key}`
277
+ let els = nodeElements.get(id)
278
+ if (!els) {
279
+ els = new Set()
280
+ nodeElements.set(id, els)
281
+ }
282
+ els.add(el)
283
+ return () => {
284
+ const set = nodeElements.get(id)
285
+ if (!set) return
286
+ set.delete(el)
287
+ if (set.size === 0) nodeElements.delete(id)
288
+ }
289
+ }
290
+
291
+ function elementsFor(id: string): HTMLElement[] {
292
+ return [...(nodeElements.get(id) ?? [])]
293
+ }
294
+
295
+ /**
296
+ * Dual-fill the tree, dispatch enter/leave to every registered element of
297
+ * the in/out nodes, then wait for returned promises (bounded by timeoutMs)
298
+ * before finalize unmounts the outgoing side.
299
+ */
300
+ async function runTransitions(from: string, to: string): Promise<void> {
301
+ if (!transitionsConfig) return
302
+ const { enter, leave, timeoutMs = 1000 } = transitionsConfig
303
+
304
+ cycle.fill()
305
+ await tick()
306
+
307
+ const { in: inKeys, out: outKeys } = getCompKeys(componentTree.value, cycle)
308
+ const jobs: Promise<unknown>[] = []
309
+
310
+ const dispatch = (fn: TransitionFn | undefined, ids: string[]): void => {
311
+ if (!fn) return
312
+ for (const id of ids) {
313
+ const [depth, key] = id.split(' ')
314
+ const info: RouteNodeInfo = {
315
+ depth: Number(depth),
316
+ key: Number(key),
317
+ from,
318
+ to,
319
+ }
320
+ for (const el of elementsFor(id)) {
321
+ const result = fn(el, info)
322
+ if (result) {
323
+ jobs.push(
324
+ Promise.resolve(result).catch((err) => {
325
+ log.error(`transition callback failed for ${to}: ${String(err)}`)
326
+ }),
327
+ )
328
+ }
329
+ }
330
+ }
331
+ }
332
+ dispatch(enter, inKeys)
333
+ dispatch(leave, outKeys)
334
+
335
+ if (jobs.length === 0) return
336
+
337
+ const startedAt = performance.now()
338
+ await new Promise<void>((resolve) => {
339
+ const timer = setTimeout(() => {
340
+ log.warn(`transitions settle timed out after ${timeoutMs}ms — finalizing`)
341
+ resolve()
342
+ }, timeoutMs)
343
+ Promise.allSettled(jobs).then(() => {
344
+ clearTimeout(timer)
345
+ resolve()
346
+ })
347
+ })
348
+ log.debug(
349
+ `transitions settled in ${Math.round(performance.now() - startedAt)}ms (${jobs.length} jobs, ${to})`,
350
+ )
351
+ }
352
+
353
+ /**
354
+ * Navigate to a route
355
+ */
356
+ function navigate(path: string | number, options: NavigateOptions = {}) {
357
+ if (typeof path === 'number') {
358
+ navigationId++
359
+ navigationAbort?.abort()
360
+ globalThis.history.go(path)
361
+ return
362
+ }
363
+
364
+ onNavigate(path, options)
365
+ }
366
+
367
+ const preloadedPaths = new Set<string>()
368
+
369
+ /**
370
+ * Programmatically resolve (and warm) a route's components — the same work
371
+ * hover-preloading does for `data-preload` anchors, callable from
372
+ * pointerdown/focus handlers, idle callbacks, or boot sequences. Deduped
373
+ * per path; a failed preload is retried on the next call.
374
+ */
375
+ export function preloadRoute(path: string): Promise<void> {
376
+ if (!routes) return Promise.resolve()
377
+ const { match, layouts } = matchRoute(path, routes)
378
+ if (!match) return Promise.resolve()
379
+ if (preloadedPaths.has(path)) return Promise.resolve()
380
+
381
+ return resolveRouteComponents([...layouts, match]).then(
382
+ () => {
383
+ preloadedPaths.add(path)
384
+ },
385
+ (err) => {
386
+ log.error(`preload failed for ${path}: ${String(err)}`)
387
+ },
388
+ )
389
+ }
390
+
391
+ /**
392
+ * Main navigation handler
393
+ */
394
+ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
395
+ log.debug('onNavigate', { path, options })
396
+ // Prevent HMR from triggering navigation
397
+ if (!path && location.pathname === globalThis.location.pathname) {
398
+ if (isFirstNavigation) {
399
+ isFirstNavigation = false
400
+ } else {
401
+ return
402
+ }
403
+ }
404
+
405
+ if (!routes || Object.keys(routes).length === 0) {
406
+ throw new Error(
407
+ 'Router has no routes. Call createRouter({ routes }) in a module that is imported before <Router> mounts.',
408
+ )
409
+ }
410
+
411
+ if (phase.value !== 'idle') {
412
+ // Supersede: invalidate the in-flight navigation (it abandons at
413
+ // its next checkpoint) and stash this request to run once it
414
+ // unwinds. Last write wins.
415
+ navigationId++
416
+ navigationAbort?.abort()
417
+ pendingNavigation = { path, options }
418
+ if (cycle.isDual) cycle.value = cycle.first
419
+ return
420
+ }
421
+
422
+ const abortCtrl = new AbortController()
423
+ navigationAbort = abortCtrl
424
+ const signal = abortCtrl.signal
425
+
426
+ // Generation token: any navigation started after this one (supersede,
427
+ // hook redirect, popstate) bumps `navigationId`, and this pipeline
428
+ // abandons at its next checkpoint. Replaces the old stack-sniffing.
429
+ const myId = ++navigationId
430
+ const isStale = () => myId !== navigationId
431
+
432
+ const prevComponentTree = componentTree.value
433
+
434
+ const revertLoading = () => {
435
+ cycle.value = cycle.from
436
+ componentTree.value = prevComponentTree
437
+ }
438
+
439
+ // Match the route
440
+ let matchPath = path || globalThis.location.pathname
441
+ if (base.name && matchPath.startsWith(base.name)) {
442
+ matchPath = matchPath.slice(base.name.length) || '/'
443
+ }
444
+ let from = location.pathname
445
+
446
+ const {
447
+ match,
448
+ layouts,
449
+ hooks,
450
+ params: newParams,
451
+ } = matchRoute(matchPath, routes)
452
+
453
+ // Skip hooks if bypass is enabled
454
+ if (options.bypass) {
455
+ updateNavigation(path, newParams, options)
456
+ return
457
+ }
458
+
459
+ // ========================================================================
460
+ // beforeLoad Hook
461
+ // ========================================================================
462
+ try {
463
+ phase.value = 'beforeLoad'
464
+ await tick()
465
+
466
+ for (const { beforeLoad } of hooks) {
467
+ try {
468
+ await beforeLoad?.(
469
+ {
470
+ cycle,
471
+ match,
472
+ params: newParams,
473
+ from,
474
+ to: matchPath,
475
+ signal,
476
+ } as Parameters<NonNullable<Hooks['beforeLoad']>>[0],
477
+ )
478
+ } catch (err) {
479
+ if (!isStale()) revertLoading()
480
+ return
481
+ }
482
+ }
483
+
484
+ if (isStale()) {
485
+ log.debug(`navigation to ${matchPath} superseded (beforeLoad)`)
486
+ return
487
+ }
488
+
489
+ // ========================================================================
490
+ // Resolve Components
491
+ // ========================================================================
492
+ const routeComponents = await resolveRouteComponents(
493
+ match ? [...layouts, match] : layouts,
494
+ )
495
+
496
+ componentTree.value = calculateTree({
497
+ prev: componentTree.value,
498
+ next: routeComponents,
499
+ cycle,
500
+ params: newParams,
501
+ mountedComponents,
502
+ })
503
+
504
+ // ========================================================================
505
+ // duringLoad Hook
506
+ // ========================================================================
507
+ phase.value = 'duringLoad'
508
+ await tick()
509
+
510
+ for (const { duringLoad } of hooks) {
511
+ try {
512
+ await duringLoad?.({
513
+ cycle,
514
+ componentTree: componentTree.value,
515
+ mountedComponents,
516
+ keys: getCompKeys(componentTree.value, cycle),
517
+ from,
518
+ to: matchPath,
519
+ signal,
520
+ })
521
+ } catch (err) {
522
+ if (!isStale()) revertLoading()
523
+ return
524
+ }
525
+ }
526
+
527
+ if (isStale()) {
528
+ log.debug(`navigation to ${matchPath} superseded (duringLoad)`)
529
+ // calculateTree already replaced the tree above; undo it so the
530
+ // superseding navigation starts from the settled previous tree.
531
+ revertLoading()
532
+ return
533
+ }
534
+
535
+ // ========================================================================
536
+ // Update Navigation
537
+ // ========================================================================
538
+ updateNavigation(path, newParams, options)
539
+
540
+ // ========================================================================
541
+ // duringRender Hook
542
+ // ========================================================================
543
+ phase.value = 'duringRender'
544
+ await tick()
545
+
546
+ for (const { duringRender } of hooks) {
547
+ try {
548
+ await duringRender?.({
549
+ cycle,
550
+ componentTree: componentTree.value,
551
+ mountedComponents,
552
+ keys: getCompKeys(componentTree.value, cycle),
553
+ from,
554
+ to: matchPath,
555
+ signal,
556
+ })
557
+ } catch (err) {
558
+ log.error({ message: 'SVR ERROR duringRender', err })
559
+ // Continue even if duringRender fails
560
+ }
561
+ }
562
+
563
+ await runTransitions(from, matchPath)
564
+ if (isStale()) {
565
+ log.debug(`navigation to ${matchPath} superseded (transitions)`)
566
+ // The URL already points at the incoming side (updateNavigation ran),
567
+ // so collapse onto it instead of leaving the tree dual forever.
568
+ if (cycle.isDual) cycle.value = cycle.first
569
+ return
570
+ }
571
+ if (cycle.value.length === 1) cycle.fill()
572
+ cycle.finalize()
573
+ cycle.finalize()
574
+
575
+ // ========================================================================
576
+ // afterRender Hook
577
+ // ========================================================================
578
+ phase.value = 'afterRender'
579
+ await tick()
580
+
581
+ for (const { afterRender } of hooks) {
582
+ try {
583
+ afterRender?.({
584
+ cycle,
585
+ componentTree: componentTree.value,
586
+ mountedComponents,
587
+ keys: getCompKeys(componentTree.value, cycle),
588
+ from,
589
+ to: matchPath,
590
+ signal,
591
+ })
592
+ } catch (err) {
593
+ // Continue even if afterRender fails
594
+ }
595
+ }
596
+ } finally {
597
+ cycle.from = cycle.first
598
+
599
+ if (navigationAbort === abortCtrl) navigationAbort = null
600
+
601
+ phase.value = 'idle'
602
+ cleanMountedComponents(mountedComponents, componentTree)
603
+
604
+ // Process deferred navigation
605
+ if (pendingNavigation) {
606
+ const pn = pendingNavigation
607
+ pendingNavigation = null
608
+ // Use microtask to avoid re-entrancy
609
+ queueMicrotask(() => onNavigate(pn.path, pn.options))
610
+ }
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Update browser history and location state
616
+ */
617
+ function updateNavigation(
618
+ path: string | undefined,
619
+ newParams: Record<string, string>,
620
+ options: NavigateOptions,
621
+ ) {
622
+ if (path) {
623
+ if (options.search) path += options.search
624
+ if (options.hash) path += options.hash
625
+
626
+ const historyMethod = options.replace ? 'replaceState' : 'pushState'
627
+ const to = base.name ? join(base.name, path) : path
628
+ globalThis.history[historyMethod](options.state || {}, '', to)
629
+ }
630
+
631
+ params.value = newParams || {}
632
+ syncSearchParams()
633
+ Object.assign(location, getLocation())
634
+
635
+ if (options.scrollToTop !== false) {
636
+ window.scrollTo({
637
+ top: 0,
638
+ left: 0,
639
+ ...(options.scrollToTop !== undefined ? { behavior: options.scrollToTop } : {}),
640
+ })
641
+ }
642
+ }
643
+
644
+ /**
645
+ * Global click handler to intercept anchor clicks
646
+ */
647
+ export function onGlobalClick(event: Event) {
648
+ if (!(event.target instanceof HTMLElement)) return
649
+
650
+ const anchor = event.target.closest('a')
651
+ if (!anchor) return
652
+
653
+ if (anchor.hasAttribute('target') || anchor.hasAttribute('download')) return
654
+
655
+ const url = new URL(anchor.href)
656
+ const currentOrigin = globalThis.location.origin
657
+ if (url.origin !== currentOrigin) return
658
+
659
+ event.preventDefault()
660
+
661
+ const { replace, state, scrollToTop } = anchor.dataset
662
+ onNavigate(url.pathname, {
663
+ replace: replace === '' || replace === 'true',
664
+ search: url.search,
665
+ ...(state !== undefined ? { state } : {}),
666
+ hash: url.hash,
667
+ scrollToTop: scrollToTop === 'false' ? false : (scrollToTop as ScrollBehavior),
668
+ })
669
+ }
670
+
671
+ /**
672
+ * Svelte action to add active class to links
673
+ */
674
+ export const isActiveLink: Action<
675
+ HTMLAnchorElement,
676
+ { className?: string; startsWith?: boolean } | undefined
677
+ > = (node, { className = 'is-active', startsWith = false } = {}) => {
678
+ if (node.tagName !== 'A') {
679
+ throw new Error('isActiveLink can only be used on <a> elements')
680
+ }
681
+
682
+ $effect(() => {
683
+ const pathname = new URL(node.href).pathname
684
+ if (
685
+ startsWith
686
+ ? location.pathname.startsWith(pathname)
687
+ : location.pathname === pathname
688
+ ) {
689
+ node.classList.add(className)
690
+ } else {
691
+ node.classList.remove(className)
692
+ }
693
+ })
694
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ interface ImportMeta {
2
+ readonly env?: { readonly DEV?: boolean; readonly SSR?: boolean }
3
+ }