@xzsv/router 0.2.2 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xzsv/router",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "author": "Umar Alfarouk",
6
6
  "description": "Client-side router for Svelte 5: dual-tree rendering, persistent layouts, lazy routes, navigation hooks",
package/src/Link.svelte CHANGED
@@ -8,7 +8,7 @@ global click interception (the same `data-*` protocol as plain anchors),
8
8
  so Link stays declarative.
9
9
  -->
10
10
  <script lang='ts'>
11
- import { location } from './create.svelte.ts'
11
+ import { base, location } from './create.svelte.ts'
12
12
  import type { LinkProps } from './types.ts'
13
13
  import { constructPath, isActive, q } from './utils.ts'
14
14
 
@@ -31,13 +31,21 @@ so Link stays declarative.
31
31
  const searchString = $derived(
32
32
  typeof search === 'string' ? search : search === undefined ? '' : q(search),
33
33
  )
34
- const href = $derived(constructPath(to, params) + searchString + (hash ?? ''))
34
+ const href = $derived(
35
+ (base.name ?? '') + constructPath(to, params) + searchString + (hash ?? ''),
36
+ )
37
+
38
+ // location.pathname includes the base; route paths do not.
39
+ const pathname = $derived(
40
+ base.name && location.pathname.startsWith(base.name)
41
+ ? location.pathname.slice(base.name.length) || '/'
42
+ : location.pathname,
43
+ )
35
44
 
36
- // Reads the reactive module location so active state tracks navigation.
37
45
  const active = $derived(
38
46
  startsWith
39
- ? isActive.startsWith(location.pathname, to, params)
40
- : isActive(location.pathname, to, params),
47
+ ? isActive.startsWith(pathname, to, params)
48
+ : isActive(pathname, to, params),
41
49
  )
42
50
 
43
51
  const classes = $derived(
@@ -185,10 +185,17 @@ function updateUrlSearchParams(options?: { replace?: boolean }) {
185
185
  export function createRouter<T extends Routes>(config: {
186
186
  routes: T
187
187
  transitions?: Transitions
188
+ /** URL prefix stripped from route matching and prepended to hrefs. */
189
+ base?: string
188
190
  }): RouterApi<T> {
189
191
  log.debug('createRouter')
190
192
  routes = config.routes
191
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
192
199
 
193
200
  // Fresh run: clear state from any previous router instance (tests, HMR,
194
201
  // remounts). Leftover trees would otherwise leak into the first
@@ -215,15 +222,22 @@ export function createRouter<T extends Routes>(config: {
215
222
  validateRoutes(routes)
216
223
  }
217
224
 
218
- preloadOnHover(routes)
225
+ preloadOnHover(routes, base.name)
219
226
 
220
227
  // utils.isActive takes the current pathname as an argument so it stays
221
228
  // pure; the API version closes over the reactive `location` state, so
222
229
  // reads from templates/effects re-evaluate when navigation happens
223
230
  // (globalThis.location is NOT a reactive read).
224
- const isActiveApi = (path: string, params?: Record<string, string>) => isActive(location.pathname, path, params)
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)
225
239
  isActiveApi.startsWith = (path: string, params?: Record<string, string>) =>
226
- isActive.startsWith(location.pathname, path, params)
240
+ isActive.startsWith(strippedPathname(), path, params)
227
241
 
228
242
  return {
229
243
  p: constructPath,
@@ -299,38 +313,69 @@ function elementsFor(id: string): HTMLElement[] {
299
313
  */
300
314
  async function runTransitions(from: string, to: string): Promise<void> {
301
315
  if (!transitionsConfig) return
302
- const { enter, leave, timeoutMs = 1000 } = transitionsConfig
316
+ const { enter, leave, timeoutMs = 1000, viewTransition = false } = transitionsConfig
303
317
 
304
- cycle.fill()
305
- await tick()
306
-
307
- const { in: inKeys, out: outKeys } = getCompKeys(componentTree.value, cycle)
308
318
  const jobs: Promise<unknown>[] = []
309
319
 
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
- )
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
+ }
328
347
  }
329
348
  }
330
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()
331
378
  }
332
- dispatch(enter, inKeys)
333
- dispatch(leave, outKeys)
334
379
 
335
380
  if (jobs.length === 0) return
336
381
 
@@ -353,7 +398,7 @@ async function runTransitions(from: string, to: string): Promise<void> {
353
398
  /**
354
399
  * Navigate to a route
355
400
  */
356
- function navigate(path: string | number, options: NavigateOptions = {}) {
401
+ function go(path: string | number, options: NavigateOptions) {
357
402
  if (typeof path === 'number') {
358
403
  navigationId++
359
404
  navigationAbort?.abort()
@@ -364,6 +409,19 @@ function navigate(path: string | number, options: NavigateOptions = {}) {
364
409
  onNavigate(path, options)
365
410
  }
366
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
+
367
425
  const preloadedPaths = new Set<string>()
368
426
 
369
427
  /**
@@ -374,6 +432,9 @@ const preloadedPaths = new Set<string>()
374
432
  */
375
433
  export function preloadRoute(path: string): Promise<void> {
376
434
  if (!routes) return Promise.resolve()
435
+ if (base.name && path.startsWith(base.name)) {
436
+ path = path.slice(base.name.length) || '/'
437
+ }
377
438
  const { match, layouts } = matchRoute(path, routes)
378
439
  if (!match) return Promise.resolve()
379
440
  if (preloadedPaths.has(path)) return Promise.resolve()
@@ -408,14 +469,16 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
408
469
  )
409
470
  }
410
471
 
411
- if (phase.value !== 'idle') {
472
+ if (phase.value !== 'idle' && phase.value !== 'error') {
412
473
  // Supersede: invalidate the in-flight navigation (it abandons at
413
474
  // its next checkpoint) and stash this request to run once it
414
- // unwinds. Last write wins.
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).
415
479
  navigationId++
416
480
  navigationAbort?.abort()
417
481
  pendingNavigation = { path, options }
418
- if (cycle.isDual) cycle.value = cycle.first
419
482
  return
420
483
  }
421
484
 
@@ -428,6 +491,7 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
428
491
  // abandons at its next checkpoint. Replaces the old stack-sniffing.
429
492
  const myId = ++navigationId
430
493
  const isStale = () => myId !== navigationId
494
+ let errored = false
431
495
 
432
496
  const prevComponentTree = componentTree.value
433
497
 
@@ -450,9 +514,11 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
450
514
  params: newParams,
451
515
  } = matchRoute(matchPath, routes)
452
516
 
453
- // Skip hooks if bypass is enabled
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).
454
520
  if (options.bypass) {
455
- updateNavigation(path, newParams, options)
521
+ updateNavigation(path ? matchPath : undefined, newParams, options)
456
522
  return
457
523
  }
458
524
 
@@ -476,6 +542,8 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
476
542
  } as Parameters<NonNullable<Hooks['beforeLoad']>>[0],
477
543
  )
478
544
  } catch (err) {
545
+ errored = true
546
+ log.error(`beforeLoad hook failed for ${matchPath}: ${String(err)}`)
479
547
  if (!isStale()) revertLoading()
480
548
  return
481
549
  }
@@ -519,6 +587,8 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
519
587
  signal,
520
588
  })
521
589
  } catch (err) {
590
+ errored = true
591
+ log.error(`duringLoad hook failed for ${matchPath}: ${String(err)}`)
522
592
  if (!isStale()) revertLoading()
523
593
  return
524
594
  }
@@ -535,7 +605,7 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
535
605
  // ========================================================================
536
606
  // Update Navigation
537
607
  // ========================================================================
538
- updateNavigation(path, newParams, options)
608
+ updateNavigation(path ? matchPath : undefined, newParams, options)
539
609
 
540
610
  // ========================================================================
541
611
  // duringRender Hook
@@ -555,7 +625,7 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
555
625
  signal,
556
626
  })
557
627
  } catch (err) {
558
- log.error({ message: 'SVR ERROR duringRender', err })
628
+ log.error(`SVR ERROR duringRender: ${String(err)}`)
559
629
  // Continue even if duringRender fails
560
630
  }
561
631
  }
@@ -590,15 +660,22 @@ export async function onNavigate(path?: string, options: NavigateOptions = {}) {
590
660
  signal,
591
661
  })
592
662
  } catch (err) {
663
+ log.error(`SVR ERROR afterRender: ${String(err)}`)
593
664
  // Continue even if afterRender fails
594
665
  }
595
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()
596
673
  } finally {
597
674
  cycle.from = cycle.first
598
675
 
599
676
  if (navigationAbort === abortCtrl) navigationAbort = null
600
677
 
601
- phase.value = 'idle'
678
+ phase.value = errored ? 'error' : 'idle'
602
679
  cleanMountedComponents(mountedComponents, componentTree)
603
680
 
604
681
  // Process deferred navigation
package/src/types.ts CHANGED
@@ -49,6 +49,13 @@ export type Transitions = {
49
49
  enter?: TransitionFn
50
50
  leave?: TransitionFn
51
51
  timeoutMs?: number
52
+ /**
53
+ * Wrap the tree swap in a same-document View Transition
54
+ * (`document.startViewTransition`) when available, letting
55
+ * `::view-transition-*` CSS animate the handoff. Falls back to a plain
56
+ * swap where the API is missing. Off by default.
57
+ */
58
+ viewTransition?: boolean
52
59
  }
53
60
 
54
61
  /**
@@ -232,6 +239,12 @@ export type Phase =
232
239
  | 'duringLoad'
233
240
  | 'duringRender'
234
241
  | 'afterRender'
242
+ /**
243
+ * A navigation failed: a hook threw, or route resolution errored. The
244
+ * URL still points at the previous route. Treat it like idle — the
245
+ * next navigation proceeds normally.
246
+ */
247
+ | 'error'
235
248
 
236
249
  /**
237
250
  * Type utilities for extracting route paths and params
package/src/utils.ts CHANGED
@@ -507,7 +507,7 @@ export function cleanMountedComponents(
507
507
  /**
508
508
  * Setup preloading on hover for links
509
509
  */
510
- export function preloadOnHover(routes: Routes): void {
510
+ export function preloadOnHover(routes: Routes, baseName?: string): void {
511
511
  const linkSet = new Set<Element>()
512
512
 
513
513
  const observer = new MutationObserver(() => {
@@ -522,7 +522,11 @@ export function preloadOnHover(routes: Routes): void {
522
522
  const href = link.getAttribute('href')
523
523
  if (!href) return
524
524
 
525
- const { match, layouts } = matchRoute(href, routes)
525
+ let path = new URL(href, globalThis.location.origin).pathname
526
+ if (baseName && path.startsWith(baseName)) {
527
+ path = path.slice(baseName.length) || '/'
528
+ }
529
+ const { match, layouts } = matchRoute(path, routes)
526
530
  resolveRouteComponents(match ? [...layouts, match] : layouts)
527
531
  })
528
532
  }