@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Umar Alfarouk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # @xzsv/router
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Client-side router for Svelte 5 with **dual-tree rendering**: two component
4
+ trees (A/B) alternate per navigation, so shared layouts stay mounted while
5
+ only the differing segments transition — both visible simultaneously for
6
+ cross-fades. Successor of the `svr`/Arc experiments.
7
+
8
+ - Nested routes and layouts (root-first collection)
9
+ - Dynamic params (`/posts/:id`) and wildcards (`*rest`, `(*rest)` to break
10
+ out of layouts)
11
+ - Lazy routes (`() => import('./Page.svelte')`), hover preloading via
12
+ `data-preload`
13
+ - Navigation hooks: `beforeLoad` / `duringLoad` / `duringRender` /
14
+ `afterRender` — await data or assets before render, hold the old tree
15
+ while it animates out
16
+ - Router-orchestrated transitions: `enter`/`leave` per route-node element
17
+ (`routeNode` attachment) with promise-based settle and a timeout guard
18
+ - Reactive `searchParams` (SvelteURLSearchParams proxy), `isActive` /
19
+ `isActive.startsWith` / `isActiveLink` action
20
+ - Abort signals + deferred navigation (rapid clicks land on the last target)
21
+
22
+ ## Usage
23
+
24
+ ```ts
25
+ // routes.svelte.ts
26
+ import { createRouter } from '@xzsv/router'
27
+ import Layout from './Layout.svelte'
28
+ import Home from './pages/Home.svelte'
29
+
30
+ export const router = createRouter({
31
+ routes: {
32
+ layout: Layout, // persistent across navigations
33
+ '/': Home,
34
+ '/posts/:id': () => import('./pages/Post.svelte'),
35
+ '*rest': () => import('./pages/NotFound.svelte'),
36
+ },
37
+ })
38
+ ```
39
+
40
+ ```svelte
41
+ <!-- App.svelte -->
42
+ <script>
43
+ import { Router } from '@xzsv/router'
44
+ </script>
45
+ <Router />
46
+ ```
47
+
48
+ Plain `<a href>` clicks are intercepted automatically. `router.navigate('/x')`
49
+ for programmatic use; `router.route.params` / `.pathname` are reactive.
50
+
51
+ ### Transitions
52
+
53
+ Pass `transitions` to `createRouter` for router-orchestrated, per-element
54
+ animations: `enter`/`leave` fire on the root elements of route nodes
55
+ (pages/layouts) carrying the `routeNode` attachment — only for nodes past
56
+ the equality point, so persistent layouts never animate. Return a promise
57
+ to hold the dual-tree swap until it settles; `timeoutMs` (default 1000)
58
+ bounds the wait so a stuck callback can't freeze navigation.
59
+
60
+ ```svelte
61
+ <!-- pages/Home.svelte -->
62
+ <script>
63
+ import { routeNode } from '@xzsv/router'
64
+ </script>
65
+ <div class="page" {@attach routeNode}>…</div>
66
+ ```
67
+
68
+ ```ts
69
+ createRouter({
70
+ routes: { … },
71
+ transitions: {
72
+ enter: (el) => animateIn(el),
73
+ leave: (el) => animateOut(el), // return a promise → router awaits
74
+ timeoutMs: 1000,
75
+ },
76
+ })
77
+ ```
78
+
79
+ The cycle walks `a → ab → b` (or `b → ba → a`): both trees are mounted
80
+ until `finalize`, which happens only after all enter/leave promises settle.
81
+ Without `transitions`, or under a superseded navigation, the swap is
82
+ instant. A `duringRender` hook still works for bespoke cases but should
83
+ not scrape DOM — the router now owns fill/settle/finalize.
84
+
85
+ ## Behavior
86
+
87
+ - First navigation fills the empty tree, then flips the cycle.
88
+ - Rapid navigations while busy supersede the in-flight pipeline (it
89
+ abandons at its next checkpoint) and coalesce to the last target;
90
+ in-flight hooks receive an aborted `signal`. Hook-initiated
91
+ `navigate()` calls (redirects) supersede too.
92
+ - `createRouter` resets any previous instance's state — remounts, HMR and
93
+ tests start from a clean run.
94
+ - `popstate` (back/forward) routes like a normal navigation.
95
+ - Anchors with `target`/`download`, or cross-origin, are left to the browser.
96
+ - `scrollToTop` defaults on; pass `navigate(path, { scrollToTop: false })` to
97
+ keep position.
98
+
99
+ ## Logging
100
+
101
+ LogTape category `["xzsv", "router"]` — `debug` for navigation steps and
102
+ trees. Silent unless the app configures LogTape; the library never calls
103
+ `configure` itself. See https://logtape.org/
104
+
105
+ ## Notes
106
+
107
+ - One router per app (module-level state), intended for client-rendered
108
+ Svelte apps; SSR is out of scope.
109
+ - Route matching priority: static > dynamic > wildcard.
110
+ - Explicit `.ts`/`.svelte.ts` import extensions; requires
111
+ `allowImportingTsExtensions` + a bundler that honors it (Vite/Bun).
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@xzsv/router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2",
4
+ "license": "MIT",
5
+ "author": "Umar Alfarouk",
6
+ "description": "Client-side router for Svelte 5: dual-tree rendering, persistent layouts, lazy routes, navigation hooks",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "src"
14
+ ],
15
+ "scripts": {
16
+ "check": "tsc --noEmit && svelte-check-native --tsconfig ./tsconfig.json",
17
+ "test": "bun test --conditions browser"
18
+ },
19
+ "peerDependencies": {
20
+ "svelte": "^5.29.0"
21
+ },
22
+ "dependencies": {
23
+ "@logtape/logtape": "^2.0.5"
24
+ },
25
+ "devDependencies": {
26
+ "@happy-dom/global-registrator": "^20.11.2",
27
+ "happy-dom": "^20.11.2",
28
+ "svelte": "^5.56.9",
29
+ "svelte-check-native": "^1.4.0",
30
+ "typescript": "^7.0.2"
31
+ }
32
+ }
@@ -0,0 +1,62 @@
1
+ <!--
2
+ @component
3
+ Typed anchor for internal navigation. Renders the right `href`, keeps
4
+ `aria-current` in sync with the reactive location, and applies
5
+ active/inactive classes — so nav bars stop hand-rolling
6
+ `router.isActive(x) ? a : b`. Navigation itself flows through the router's
7
+ global click interception (the same `data-*` protocol as plain anchors),
8
+ so Link stays declarative.
9
+ -->
10
+ <script lang='ts'>
11
+ import { location } from './create.svelte.ts'
12
+ import type { LinkProps } from './types.ts'
13
+ import { constructPath, isActive, q } from './utils.ts'
14
+
15
+ let {
16
+ to,
17
+ params,
18
+ search,
19
+ hash,
20
+ replace,
21
+ scrollToTop,
22
+ startsWith = false,
23
+ activeClass,
24
+ inactiveClass,
25
+ preload = true,
26
+ class: className = '',
27
+ children,
28
+ ...rest
29
+ }: LinkProps = $props()
30
+
31
+ const searchString = $derived(
32
+ typeof search === 'string' ? search : search === undefined ? '' : q(search),
33
+ )
34
+ const href = $derived(constructPath(to, params) + searchString + (hash ?? ''))
35
+
36
+ // Reads the reactive module location so active state tracks navigation.
37
+ const active = $derived(
38
+ startsWith
39
+ ? isActive.startsWith(location.pathname, to, params)
40
+ : isActive(location.pathname, to, params),
41
+ )
42
+
43
+ const classes = $derived(
44
+ [className, active ? activeClass : inactiveClass]
45
+ .filter(Boolean)
46
+ .join(' '),
47
+ )
48
+ </script>
49
+
50
+ <a
51
+ href={href}
52
+ class={classes || undefined}
53
+ aria-current={active ? 'page' : undefined}
54
+ data-preload={preload ? '' : undefined}
55
+ data-replace={replace ? '' : undefined}
56
+ data-scroll-to-top={scrollToTop === undefined
57
+ ? undefined
58
+ : scrollToTop === false
59
+ ? 'false'
60
+ : scrollToTop}
61
+ {...rest}
62
+ >{@render children()}</a>
@@ -0,0 +1,87 @@
1
+ <!--
2
+ @component
3
+ Recursive component renderer for nested routes with dual-tree rendering
4
+ -->
5
+ <script lang='ts'>
6
+ import { cycle, mountedComponents } from './create.svelte.ts'
7
+ import Recursive from './Recursive.svelte'
8
+ import RouteNode from './RouteNode.svelte'
9
+ import type { ComponentTree } from './types.ts'
10
+ import { fnv1a } from './utils.ts'
11
+ const cycleChars = $derived(cycle.value.split('') as ReadonlyArray<'a' | 'b'>)
12
+
13
+ type Props = {
14
+ tree: ComponentTree['value']
15
+ depth?: number
16
+ }
17
+
18
+ const { tree, depth = 0 }: Props = $props()
19
+
20
+ // Determine which components to render at this depth.
21
+ // `tree` is already sliced relative to this level, so index [0];
22
+ // `tree.eq` is likewise relative (decremented once per level): >= 0
23
+ // means this level is inside the shared-equality range.
24
+ const firstComponents = $derived.by(() => {
25
+ if (tree.a.length === 0 && tree.b.length === 0) {
26
+ return []
27
+ }
28
+
29
+ // Within the equality range, only show one component
30
+ if (tree.eq >= 0) {
31
+ const currentCycle = cycleChars[0] ?? 'a'
32
+ return [{ ...tree[currentCycle][0]!, ab: 'a' as 'a' | 'b' }]
33
+ }
34
+
35
+ // During transition, show components from both trees
36
+ const components = cycleChars.map((ab) => ({
37
+ ab,
38
+ obj: tree[ab as 'a' | 'b'][0],
39
+ }))
40
+ .filter((x, idx, arr) => {
41
+ // Filter out undefined and duplicates
42
+ return x.obj && arr.findIndex((item) => item.obj === x.obj) === idx
43
+ })
44
+ .map((x) => ({
45
+ ab: x.ab,
46
+ C: x.obj!.C,
47
+ key: x.obj!.key,
48
+ params: x.obj!.params,
49
+ }))
50
+
51
+ return components
52
+ })
53
+
54
+ // Create tree for next depth level
55
+ const restTree = $derived({
56
+ a: tree.a?.slice(1),
57
+ b: tree.b?.slice(1),
58
+ eq: tree.eq - 1,
59
+ })
60
+
61
+ // A single-sided view of restTree for one half of the transition
62
+ function otherTreeFor(ab: 'a' | 'b'): ComponentTree['value'] {
63
+ const other = ab === 'a' ? 'b' : 'a'
64
+ return {
65
+ [ab]: restTree[ab],
66
+ [other]: [],
67
+ eq: tree.eq - 1,
68
+ } as unknown as ComponentTree['value']
69
+ }
70
+ </script>
71
+
72
+ {#each firstComponents as { C, ab, key, params } (`${depth} ${key} ${
73
+ import.meta.env?.DEV ? JSON.stringify(params ?? null) : fnv1a(JSON.stringify(params ?? null))
74
+ }`)}
75
+ <RouteNode value={{ depth, key }}>
76
+ <C bind:this={mountedComponents[`${depth} ${key}`]}>
77
+ {#if restTree.a?.length > 0 || restTree.b?.length > 0}
78
+ <Recursive
79
+ tree={tree.eq >= 0
80
+ ? restTree
81
+ : otherTreeFor(ab)}
82
+ depth={depth + 1}
83
+ />
84
+ {/if}
85
+ </C>
86
+ </RouteNode>
87
+ {/each}
@@ -0,0 +1,19 @@
1
+ <!--
2
+ @component
3
+ Context provider marking which route-tree node a component belongs to.
4
+ Renders no DOM — the `routeNode` attachment reads this context to
5
+ register elements for enter/leave transitions.
6
+ -->
7
+ <script lang="ts">
8
+ import { setContext, type Snippet } from 'svelte'
9
+ import { routeNodeKey, type RouteNodeCtx } from './route-node-context.ts'
10
+
11
+ let { value, children }: { value: RouteNodeCtx; children: Snippet } =
12
+ $props()
13
+
14
+ // The node identity (depth/key) is fixed for a given tree node — init-only by design.
15
+ // svelte-ignore state_referenced_locally
16
+ setContext(routeNodeKey, value)
17
+ </script>
18
+
19
+ {@render children()}
@@ -0,0 +1,57 @@
1
+ <!--
2
+ @component
3
+ Main router component that sets up navigation listeners and renders the component tree
4
+ -->
5
+ <script lang='ts'>
6
+ import { onMount } from 'svelte'
7
+ import {
8
+ base,
9
+ componentTree,
10
+ onGlobalClick,
11
+ onNavigate,
12
+ } from './create.svelte.ts'
13
+ import Recursive from './Recursive.svelte'
14
+ import { join } from './utils.ts'
15
+
16
+ type Props = {
17
+ /**
18
+ * Base path for the router (optional)
19
+ * @example "/app" or "app"
20
+ */
21
+ base?: string
22
+ }
23
+
24
+ const { base: basename }: Props = $props()
25
+
26
+ // Setup event listeners
27
+ $effect(() => {
28
+ const handlePopState = () => onNavigate()
29
+ const handleClick = (e: MouseEvent) => onGlobalClick(e)
30
+
31
+ globalThis.addEventListener('popstate', handlePopState)
32
+ globalThis.addEventListener('click', handleClick)
33
+
34
+ return () => {
35
+ globalThis.removeEventListener('popstate', handlePopState)
36
+ globalThis.removeEventListener('click', handleClick)
37
+ }
38
+ })
39
+
40
+ // Initial navigation
41
+ onMount(() => {
42
+ // Setup base path
43
+ if (basename) {
44
+ base.name = (basename.startsWith('/') ? '' : '/') + basename
45
+ const url = new URL(globalThis.location.href)
46
+
47
+ if (!url.pathname.startsWith(base.name)) {
48
+ url.pathname = join(base.name, url.pathname)
49
+ history.replaceState(history.state || {}, '', url.href)
50
+ }
51
+ }
52
+
53
+ onNavigate()
54
+ })
55
+ </script>
56
+
57
+ <Recursive tree={componentTree.value} />