@real-router/svelte 0.13.13 → 0.14.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/README.md CHANGED
@@ -63,16 +63,16 @@ All composables must be called during component initialization (not inside `$eff
63
63
 
64
64
  `useRoute()` returns a **non-nullable** `route.current` (typed as `State<P>`) and throws when the router has no active state (unstarted, stopped, disposed). `useRouteNode(name)` keeps its nullable `current` — node inactivity is a legitimate business state, not a lifecycle error.
65
65
 
66
- | Composable | Returns | Reactive? |
67
- | ----------------------- | --------------------------------------------------------------- | ------------------------------------------ |
68
- | `useRouter()` | `Router` | Never |
69
- | `useNavigator()` | `Navigator` | Never (stable ref, safe to use directly) |
70
- | `useRoute()` | `{ navigator, route: { current: State<P> }, previousRoute: { current } }` — throws if no active state | `.current` on every navigation |
71
- | `useRouteNode(name)` | `{ navigator, route: { current }, previousRoute: { current } }` | `.current` when node activates/deactivates |
72
- | `useRouteUtils()` | `RouteUtils` | Never |
73
- | `useRouterTransition()` | `{ current: RouterTransitionSnapshot }` | `.current` on transition start/end |
74
- | `useRouteExit(handler, options?)` | `void` — wraps `subscribeLeave` with abort + same-route guards | Never (handler captured at init) |
75
- | `useRouteEnter(handler, options?)` | `void` — fires once on nav-driven mount via `$effect` + `transition.from` | Never (handler captured at init) |
66
+ | Composable | Returns | Reactive? |
67
+ | ---------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------ |
68
+ | `useRouter()` | `Router` | Never |
69
+ | `useNavigator()` | `Navigator` | Never (stable ref, safe to use directly) |
70
+ | `useRoute()` | `{ navigator, route: { current: State<P> }, previousRoute: { current } }` — throws if no active state | `.current` on every navigation |
71
+ | `useRouteNode(name)` | `{ navigator, route: { current }, previousRoute: { current } }` | `.current` when node activates/deactivates |
72
+ | `useRouteUtils()` | `RouteUtils` | Never |
73
+ | `useRouterTransition()` | `{ current: RouterTransitionSnapshot }` | `.current` on transition start/end |
74
+ | `useRouteExit(handler, options?)` | `void` — wraps `subscribeLeave` with abort + same-route guards | Never (handler captured at init) |
75
+ | `useRouteEnter(handler, options?)` | `void` — fires once on nav-driven mount via `$effect` + `transition.from` | Never (handler captured at init) |
76
76
 
77
77
  ```svelte
78
78
  <!-- useRouteNode — updates only when "users.*" changes -->
@@ -178,17 +178,17 @@ Navigation link with automatic active state detection. Uses `$derived` for href
178
178
 
179
179
  **Props:**
180
180
 
181
- | Prop | Type | Default | Description |
182
- | ------------------- | ------------------- | ----------- | --------------------------------------- |
183
- | `routeName` | `string` | required | Target route name |
184
- | `routeParams` | `Params` | `undefined` | Route parameters (omitted → `undefined`, shares one active-route source with `useIsActiveRoute(name)`, #776) |
185
- | `routeOptions` | `NavigationOptions` | `{}` | Navigation options (replace, etc.) |
186
- | `class` | `string` | `undefined` | CSS class |
187
- | `activeClassName` | `string` | `"active"` | Class added when route is active |
188
- | `activeStrict` | `boolean` | `false` | Exact match only (no ancestor matching) |
189
- | `ignoreQueryParams` | `boolean` | `true` | Query params don't affect active state |
190
- | `hash` | `string` | `undefined` | URL fragment (decoded). Tri-state: undefined preserves, `""` clears, value sets. (#532) |
191
- | `target` | `string` | `undefined` | Link target (`_blank`, etc.) |
181
+ | Prop | Type | Default | Description |
182
+ | ------------------- | --------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------- |
183
+ | `routeName` | `string` | required | Target route name |
184
+ | `routeParams` | `Params` | `undefined` | Route parameters (omitted → `undefined`, shares one active-route source with `useIsActiveRoute(name)`, #776) |
185
+ | `routeOptions` | `NavigationOptions` | `{}` | Navigation options (replace, etc.) |
186
+ | `class` | `string` | `undefined` | CSS class |
187
+ | `activeClassName` | `string` | `"active"` | Class added when route is active |
188
+ | `activeStrict` | `boolean` | `false` | Exact match only (no ancestor matching) |
189
+ | `ignoreQueryParams` | `boolean` | `true` | Query params don't affect active state |
190
+ | `hash` | `string` | `undefined` | URL fragment (decoded). Tri-state: undefined preserves, `""` clears, value sets. (#532) |
191
+ | `target` | `string` | `undefined` | Link target (`_blank`, etc.) |
192
192
  | `onclick` | `(evt: MouseEvent) => void` | `undefined` | Custom click handler. Runs **before** the navigation logic — call `evt.preventDefault()` to suppress navigation. |
193
193
 
194
194
  All other props are spread onto the `<a>` element.
@@ -243,12 +243,12 @@ Declarative route matching. Renders the snippet whose name matches the active ro
243
243
 
244
244
  **Props:**
245
245
 
246
- | Prop | Type | Description |
247
- | ----------- | --------- | -------------------------------------------------------------------------------------------- |
248
- | `nodeName` | `string` | Route node to match against. `""` for root. |
249
- | `self` | `Snippet` | Rendered when the active route is exactly `nodeName` (no descendant segments) |
250
- | `notFound` | `Snippet` | Rendered when route is `UNKNOWN_ROUTE` |
251
- | `[segment]` | `Snippet` | Named snippet matching a route segment |
246
+ | Prop | Type | Description |
247
+ | ----------- | --------- | ----------------------------------------------------------------------------- |
248
+ | `nodeName` | `string` | Route node to match against. `""` for root. |
249
+ | `self` | `Snippet` | Rendered when the active route is exactly `nodeName` (no descendant segments) |
250
+ | `notFound` | `Snippet` | Rendered when route is `UNKNOWN_ROUTE` |
251
+ | `[segment]` | `Snippet` | Named snippet matching a route segment |
252
252
 
253
253
  Snippet names must be valid JavaScript identifiers and match the first segment of the active route after `nodeName`. For a route `users.profile` with `nodeName=""`, the snippet named `users` matches.
254
254
 
@@ -463,6 +463,22 @@ Enable screen reader announcements for route changes:
463
463
 
464
464
  When enabled, a visually hidden `aria-live` region announces each navigation. Focus moves to the first `<h1>` on the new page. See [Accessibility guide](https://github.com/greydragon888/real-router/wiki/Accessibility) for details.
465
465
 
466
+ `announceNavigation` also accepts a `RouteAnnouncerOptions` object to customize the announced text:
467
+
468
+ | Option | Type | Description |
469
+ | --------------------- | ------------------- | --------------------------------------------------------------------------------------------------- |
470
+ | `prefix` | `string` | Prefix prepended to the resolved text (default `"Navigated to "`) |
471
+ | `getAnnouncementText` | `(route) => string` | Full custom text; overrides the default `h1 → title → route-name` chain (falls back on empty/throw) |
472
+
473
+ ```svelte
474
+ <RouterProvider
475
+ {router}
476
+ announceNavigation={{ getAnnouncementText: (route) => `Now on ${route.name}` }}
477
+ >
478
+ {/* Your app */}
479
+ </RouterProvider>
480
+ ```
481
+
466
482
  ## Scroll Restoration
467
483
 
468
484
  Opt-in preservation of scroll position across navigations:
@@ -13,7 +13,11 @@
13
13
  import { createRouteContext } from "./createRouteContext.svelte";
14
14
  import { NAVIGATOR_KEY, ROUTE_KEY, ROUTER_KEY } from "./context";
15
15
 
16
- import type { ScrollRestorationOptions, ScrollSpyOptions } from "./dom-utils";
16
+ import type {
17
+ RouteAnnouncerOptions,
18
+ ScrollRestorationOptions,
19
+ ScrollSpyOptions,
20
+ } from "./dom-utils";
17
21
  import type { Router } from "@real-router/core";
18
22
  import type { Snippet } from "svelte";
19
23
 
@@ -27,15 +31,35 @@
27
31
  }: {
28
32
  router: Router;
29
33
  children: Snippet;
30
- announceNavigation?: boolean | undefined;
34
+ announceNavigation?: boolean | RouteAnnouncerOptions | undefined;
31
35
  scrollRestoration?: ScrollRestorationOptions | undefined;
32
36
  scrollSpy?: ScrollSpyOptions | undefined;
33
37
  viewTransitions?: boolean | undefined;
34
38
  } = $props();
35
39
 
40
+ // `announceNavigation` accepts `true` (default announcer) or a
41
+ // `RouteAnnouncerOptions` object (`{ prefix, getAnnouncementText }`) for
42
+ // custom announcement text. Derive primitives (enabled + prefix) so inline
43
+ // `{ getAnnouncementText }` identity churn (new object ref, same prefix)
44
+ // doesn't re-create the announcer — mirrors the scrollRestoration pattern
45
+ // below. getAnnouncementText is read once via `untrack`, captured by the
46
+ // utility (same rationale as scrollContainer).
47
+ const anEnabled = $derived(
48
+ announceNavigation !== false && announceNavigation !== undefined,
49
+ );
50
+ const anPrefix = $derived(
51
+ typeof announceNavigation === "object"
52
+ ? announceNavigation.prefix
53
+ : undefined,
54
+ );
55
+
36
56
  $effect(() => {
37
- if (!announceNavigation) return;
38
- const announcer = createRouteAnnouncer(router);
57
+ if (!anEnabled) return;
58
+ void anPrefix;
59
+ const options = untrack(() =>
60
+ typeof announceNavigation === "object" ? announceNavigation : undefined,
61
+ );
62
+ const announcer = createRouteAnnouncer(router, options);
39
63
  return () => announcer.destroy();
40
64
  });
41
65
 
@@ -1,10 +1,10 @@
1
- import type { ScrollRestorationOptions, ScrollSpyOptions } from "./dom-utils";
1
+ import type { RouteAnnouncerOptions, ScrollRestorationOptions, ScrollSpyOptions } from "./dom-utils";
2
2
  import type { Router } from "@real-router/core";
3
3
  import type { Snippet } from "svelte";
4
4
  type $$ComponentProps = {
5
5
  router: Router;
6
6
  children: Snippet;
7
- announceNavigation?: boolean | undefined;
7
+ announceNavigation?: boolean | RouteAnnouncerOptions | undefined;
8
8
  scrollRestoration?: ScrollRestorationOptions | undefined;
9
9
  scrollSpy?: ScrollSpyOptions | undefined;
10
10
  viewTransitions?: boolean | undefined;
@@ -1,8 +1,38 @@
1
- import { createActiveRouteSource } from "@real-router/sources";
1
+ import { createActiveNameSelector, createActiveRouteSource, } from "@real-router/sources";
2
+ import { createSubscriber } from "svelte/reactivity";
2
3
  import { createReactiveSource } from "../createReactiveSource.svelte";
3
4
  import { useRouter } from "./useRouter.svelte";
4
5
  export function useIsActiveRoute(routeName, params, strict, ignoreQueryParams, hash) {
5
6
  const router = useRouter();
7
+ // Fast path (#1099) — the default-options `<Link>`: non-strict matching,
8
+ // query params ignored, no custom `params`, no `hash`. Use the per-router
9
+ // shared `ActiveNameSelector`: ONE `router.subscribe` handle serves any
10
+ // number of distinct-`routeName` links, instead of a per-link
11
+ // `createActiveRouteSource` (which allocates a `BaseSource` AND opens its own
12
+ // router subscription for every link). This mirrors the Solid adapter's
13
+ // `routeSelector` fast path and removes ~4 ms / 1000 links from the
14
+ // link-build mount — the per-link source setup was the bulk of the Svelte
15
+ // `<Link>`'s extra cost over the Solid adapter.
16
+ //
17
+ // Equivalence: the selector's `isActive` is exactly non-strict,
18
+ // query-ignoring, name-only matching — identical to
19
+ // `createActiveRouteSource(router, name, undefined, { strict: false,
20
+ // ignoreQueryParams: true })`. Any deviation from these defaults falls to the
21
+ // slow path below, whose cache handles the full argument surface (custom
22
+ // params, strict, `ignoreQueryParams: false`, hash-aware #532).
23
+ if (params === undefined &&
24
+ !strict &&
25
+ ignoreQueryParams &&
26
+ hash === undefined) {
27
+ const selector = createActiveNameSelector(router);
28
+ const subscribe = createSubscriber((update) => selector.subscribe(routeName, update));
29
+ return {
30
+ get current() {
31
+ subscribe();
32
+ return selector.isActive(routeName);
33
+ },
34
+ };
35
+ }
6
36
  // The `hash` argument (#532) participates in the cache key when defined.
7
37
  // exactOptionalPropertyTypes forbids `{ hash: undefined }` literally — we
8
38
  // conditionally include the key only when a value is provided.
@@ -291,9 +291,12 @@ export function createScrollRestoration(router, options) {
291
291
  globalThis.addEventListener("pagehide", onPageHide);
292
292
  return {
293
293
  destroy: () => {
294
- if (destroyed) {
295
- return;
296
- }
294
+ // No `if (destroyed) return` guard: every teardown below is idempotent —
295
+ // `unsubscribe()` is a `set.delete` in the core EventEmitter, DOM
296
+ // `removeEventListener` is spec-idempotent, and the history assignment is
297
+ // a plain re-set. There is no ref-count to protect (unlike
298
+ // route-announcer's shared announcer element), so a double `destroy()` is
299
+ // harmless. `destroyed = true` still gates any pending restore rAF / retry.
297
300
  destroyed = true;
298
301
  unsubscribe();
299
302
  globalThis.removeEventListener("pagehide", onPageHide);
@@ -370,9 +370,14 @@ export function createScrollSpy(router, options) {
370
370
  if (cooldown.active) {
371
371
  return;
372
372
  }
373
- if (observers.pending.size === 0) {
374
- return;
375
- }
373
+ // No `if (pending.size === 0) return` fast-path: `pending` is never empty
374
+ // here via any real path (a real IntersectionObserver always delivers ≥1
375
+ // entry, so `handleIntersection` populates `pending` before scheduling; the
376
+ // mutation reconcile that could drop entries runs at MUTATION_DEBOUNCE_MS
377
+ // 250 > RAF_DEBOUNCE_MS 150, i.e. always AFTER the flush). And an empty map
378
+ // is already handled identically below — `pickTopmost(∅)` is `null` → the
379
+ // `if (!picked) return` guard — so the fast-path was both unreachable and
380
+ // redundant.
376
381
  // Successful flush consumes the merged snapshot. We clear so that the
377
382
  // next debounce window starts fresh; an anchor that is still
378
383
  // intersecting will only stay observable if IO emits another event for
@@ -393,7 +398,11 @@ export function createScrollSpy(router, options) {
393
398
  if (!state) {
394
399
  return;
395
400
  }
396
- const currentHash = getUrlContext(state)?.hash ?? "";
401
+ // `getUrlContext` is guaranteed present here (the URL-plugin detector
402
+ // silences the spy otherwise), so `?.` only satisfies the `| undefined`
403
+ // slice type. `newHash` is a non-empty id (guarded above), so it can never
404
+ // equal an absent hash — no `?? ""` normalization needed for the compare.
405
+ const currentHash = getUrlContext(state)?.hash;
397
406
  if (newHash === currentHash) {
398
407
  return;
399
408
  }
@@ -437,9 +446,12 @@ export function createScrollSpy(router, options) {
437
446
  });
438
447
  return {
439
448
  destroy() {
440
- if (destroyed) {
441
- return;
442
- }
449
+ // No `if (destroyed) return` idempotency guard: every subsystem teardown
450
+ // below is itself idempotent (null-guarded timers, `set.delete` on the
451
+ // router unsubscribe, spec-idempotent `IntersectionObserver.disconnect`),
452
+ // and `destroy()` is not a hot path — so a redundant guard would only add
453
+ // an unreachable branch. `destroyed = true` is still set to gate any
454
+ // late-arriving IO/router callback via `isStopped()`.
443
455
  destroyed = true;
444
456
  // Unsubscribe FIRST to prevent late-arriving router transition
445
457
  // callback from calling `cooldown.start()` on a half-destroyed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-router/svelte",
3
- "version": "0.13.13",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "description": "Svelte 5 integration for Real-Router",
6
6
  "svelte": "./dist/index.js",
@@ -48,7 +48,7 @@
48
48
  "license": "MIT",
49
49
  "sideEffects": false,
50
50
  "dependencies": {
51
- "@real-router/core": "^0.62.2",
51
+ "@real-router/core": "^0.62.3",
52
52
  "@real-router/route-utils": "^0.2.5",
53
53
  "@real-router/sources": "^0.10.1"
54
54
  },
@@ -60,10 +60,10 @@
60
60
  "@testing-library/user-event": "14.6.1",
61
61
  "eslint-plugin-svelte": "3.19.0",
62
62
  "rimraf": "6.1.3",
63
- "svelte": "5.56.3",
63
+ "svelte": "5.56.4",
64
64
  "svelte-check": "4.6.0",
65
65
  "svelte-eslint-parser": "1.8.0",
66
- "@real-router/browser-plugin": "^0.17.14"
66
+ "@real-router/browser-plugin": "^0.18.1"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "svelte": ">=5.7.0"