@real-router/solid 0.7.0 → 0.9.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
@@ -68,6 +68,8 @@ All hooks that subscribe to route state return `Accessor<T>` — call the access
68
68
  | `useRouterTransition()` | `Accessor<RouterTransitionSnapshot>` | On transition start/end |
69
69
  | `useRouteStore()` | `RouteState` (store) | Granular — per-property |
70
70
  | `useRouteNodeStore(name)` | `RouteState` (store) | Granular — per-property, node-scoped |
71
+ | `useRouteExit(handler, options?)` | `void` — wraps `subscribeLeave` with abort + same-route guards | Never (handler captured at hook call) |
72
+ | `useRouteEnter(handler, options?)` | `void` — fires once on nav-driven mount via `useRoute()` + `transition.from` | Never (handler captured at hook call) |
71
73
 
72
74
  ### Store-Based Hooks (Granular Reactivity)
73
75
 
@@ -137,8 +139,39 @@ function GlobalProgress() {
137
139
  </Show>
138
140
  );
139
141
  }
142
+
143
+ // useRouteExit — exit animations, draft autosave, AbortSignal-aware cleanup
144
+ function FadeOut() {
145
+ let ref: HTMLDivElement | undefined;
146
+ useRouteExit(async ({ signal }) => {
147
+ if (!ref) return;
148
+ ref.classList.add("fade-out");
149
+ const cleanup = () => ref!.classList.remove("fade-out");
150
+ signal.addEventListener("abort", cleanup, { once: true });
151
+ ref.getBoundingClientRect(); // style flush
152
+ await Promise.allSettled(ref.getAnimations().map((a) => a.finished));
153
+ cleanup();
154
+ });
155
+ return <div ref={ref}>...</div>;
156
+ }
157
+
158
+ // useRouteEnter — page-enter analytics, focus management, entry animations
159
+ function PageEnterAnalytics() {
160
+ useRouteEnter(({ route, previousRoute }) => {
161
+ analytics.track("page_enter", {
162
+ route: route.name,
163
+ from: previousRoute.name,
164
+ });
165
+ });
166
+ return null;
167
+ }
140
168
  ```
141
169
 
170
+ > **Solid handler-reactivity:** components run once, so `handler` is captured at
171
+ > hook-call time. To vary behavior over time, read signals **inside** the
172
+ > handler body. See [CLAUDE.md](./CLAUDE.md) → "useRouteExit / useRouteEnter
173
+ > Handler Is Captured At Init".
174
+
142
175
  ## Components
143
176
 
144
177
  ### `<Link>`
@@ -332,12 +365,24 @@ Opt-in preservation of scroll position across navigations:
332
365
 
333
366
  Restores scroll on back/forward, scrolls to top (or `#hash`) on push. Three modes: `"restore"` (default), `"top"`, `"manual"`. Custom containers via `scrollContainer: () => HTMLElement | null`. Options are read once on mount — changing the prop at runtime does not reconfigure the utility (Solid `onMount` is non-reactive). See [Scroll Restoration guide](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) for details.
334
367
 
368
+ ## View Transitions
369
+
370
+ Opt-in animated route transitions via the browser's [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API):
371
+
372
+ ```tsx
373
+ <RouterProvider router={router} viewTransitions>
374
+ {/* Your app */}
375
+ </RouterProvider>
376
+ ```
377
+
378
+ No-op on unsupported browsers (Firefox as of 2026-04, SSR). Prop is read once on mount (Solid `onMount` is non-reactive) — if you need toggle, unmount/remount the provider. Customization is pure CSS via `::view-transition-*` pseudo-elements and `view-transition-name` for hero morphs. See [View Transitions guide](https://github.com/greydragon888/real-router/wiki/View-Transitions) for patterns.
379
+
335
380
  ## Documentation
336
381
 
337
382
  Full documentation: [Wiki](https://github.com/greydragon888/real-router/wiki)
338
383
 
339
- - [RouterProvider](https://github.com/greydragon888/real-router/wiki/RouterProvider) · [RouteView](https://github.com/greydragon888/real-router/wiki/RouteView) · [RouterErrorBoundary](https://github.com/greydragon888/real-router/wiki/RouterErrorBoundary) · [Link](https://github.com/greydragon888/real-router/wiki/Link) · [Scroll Restoration](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration)
340
- - [useRouter](https://github.com/greydragon888/real-router/wiki/useRouter) · [useRoute](https://github.com/greydragon888/real-router/wiki/useRoute) · [useRouteNode](https://github.com/greydragon888/real-router/wiki/useRouteNode) · [useNavigator](https://github.com/greydragon888/real-router/wiki/useNavigator) · [useRouteUtils](https://github.com/greydragon888/real-router/wiki/useRouteUtils) · [useRouterTransition](https://github.com/greydragon888/real-router/wiki/useRouterTransition)
384
+ - [RouterProvider](https://github.com/greydragon888/real-router/wiki/RouterProvider) · [RouteView](https://github.com/greydragon888/real-router/wiki/RouteView) · [RouterErrorBoundary](https://github.com/greydragon888/real-router/wiki/RouterErrorBoundary) · [Link](https://github.com/greydragon888/real-router/wiki/Link) · [Scroll Restoration](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) · [View Transitions](https://github.com/greydragon888/real-router/wiki/View-Transitions)
385
+ - [useRouter](https://github.com/greydragon888/real-router/wiki/useRouter) · [useRoute](https://github.com/greydragon888/real-router/wiki/useRoute) · [useRouteNode](https://github.com/greydragon888/real-router/wiki/useRouteNode) · [useNavigator](https://github.com/greydragon888/real-router/wiki/useNavigator) · [useRouteUtils](https://github.com/greydragon888/real-router/wiki/useRouteUtils) · [useRouterTransition](https://github.com/greydragon888/real-router/wiki/useRouterTransition) · [useRouteExit](https://github.com/greydragon888/real-router/wiki/useRouteExit) · [useRouteEnter](https://github.com/greydragon888/real-router/wiki/useRouteEnter)
341
386
 
342
387
  ## Examples
343
388
 
@@ -90,7 +90,9 @@ declare const useNavigator: () => Navigator;
90
90
 
91
91
  declare const useRouteUtils: () => RouteUtils;
92
92
 
93
- declare const useRoute: <P extends Params = Params>() => Accessor<RouteState<P>>;
93
+ declare const useRoute: <P extends Params = Params>() => Accessor<Omit<RouteState<P>, "route"> & {
94
+ route: State<P>;
95
+ }>;
94
96
 
95
97
  declare function useRouteNode(nodeName: string): Accessor<RouteState>;
96
98
 
@@ -100,6 +102,170 @@ declare function useRouteNodeStore(nodeName: string): RouteState;
100
102
 
101
103
  declare function useRouterTransition(): Accessor<RouterTransitionSnapshot>;
102
104
 
105
+ interface RouteExitContext {
106
+ /** The route being left. */
107
+ route: State;
108
+ /** The route being navigated to. */
109
+ nextRoute: State;
110
+ /**
111
+ * AbortSignal that fires when this navigation is superseded by a later
112
+ * one (rapid clicks). Already filtered: when the handler runs,
113
+ * `signal.aborted` is guaranteed to be `false`. Use
114
+ * `signal.addEventListener("abort", cleanup, { once: true })` for
115
+ * cleanup that must run on cancellation.
116
+ */
117
+ signal: AbortSignal;
118
+ }
119
+ interface UseRouteExitOptions {
120
+ /**
121
+ * Skip the handler when `route.name === nextRoute.name`
122
+ * (sort/filter/query-only navigations on the same route). Default:
123
+ * `true`.
124
+ */
125
+ skipSameRoute?: boolean;
126
+ }
127
+ type RouteExitHandler = (context: RouteExitContext) => void | Promise<void>;
128
+ /**
129
+ * Subscribe to the router's leave-window with the universal guards baked
130
+ * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
131
+ * boilerplate every time:
132
+ *
133
+ * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
134
+ * when the handler would run (rapid navigation superseded a slower
135
+ * one), the handler is skipped entirely. `signal.addEventListener(
136
+ * "abort", ...)` does not fire retroactively, so without this guard
137
+ * downstream cleanup would never trigger.
138
+ * - **Same-route skip**: by default, `route.name === nextRoute.name`
139
+ * short-circuits the handler — query-only navigations (sort, filter,
140
+ * pagination) skip the work. Opt out with `skipSameRoute: false`.
141
+ *
142
+ * Returns nothing — the subscription's lifecycle is bound to the
143
+ * component via `onCleanup`.
144
+ *
145
+ * If the handler returns a Promise, the router blocks on it. If the
146
+ * Promise resolves, navigation proceeds. If it rejects, the router emits
147
+ * `TRANSITION_CANCELLED`.
148
+ *
149
+ * **Handler reactivity (Solid)**: Solid components run **once** at mount;
150
+ * `handler` is captured in closure at the call site. If you need
151
+ * different behavior across renders, derive it from a signal inside the
152
+ * handler body — do not rely on swapping the handler reference.
153
+ *
154
+ * @example Animation
155
+ * ```tsx
156
+ * let ref: HTMLDivElement | undefined;
157
+ *
158
+ * useRouteExit(async ({ signal }) => {
159
+ * const el = ref;
160
+ * if (!el) return;
161
+ * el.classList.add("fade-out");
162
+ * const cleanup = () => el.classList.remove("fade-out");
163
+ * signal.addEventListener("abort", cleanup, { once: true });
164
+ * try {
165
+ * el.getBoundingClientRect(); // style flush
166
+ * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
167
+ * } finally {
168
+ * cleanup();
169
+ * }
170
+ * });
171
+ * ```
172
+ *
173
+ * @example Auto-save form draft
174
+ * ```tsx
175
+ * useRouteExit(async ({ signal }) => {
176
+ * if (formState.dirty) await api.saveDraft(formState, { signal });
177
+ * });
178
+ * ```
179
+ *
180
+ * @example Reading rich transition metadata via `nextRoute.transition`
181
+ * ```tsx
182
+ * useRouteExit(({ route, nextRoute }) => {
183
+ * if (nextRoute.transition.segments.deactivated.includes("products")) {
184
+ * productCache.clear();
185
+ * }
186
+ * if (nextRoute.transition.redirected) {
187
+ * return;
188
+ * }
189
+ * });
190
+ * ```
191
+ */
192
+ declare function useRouteExit(handler: RouteExitHandler, options?: UseRouteExitOptions): void;
193
+
194
+ interface RouteEnterContext {
195
+ /** The route that was just activated. */
196
+ route: State;
197
+ /** The route that was active immediately before this navigation. */
198
+ previousRoute: State;
199
+ }
200
+ type RouteEnterHandler = (context: RouteEnterContext) => void;
201
+ interface UseRouteEnterOptions {
202
+ /**
203
+ * Skip the handler when `route.name === previousRoute.name`
204
+ * (sort/filter/query-only navigations on the same route). Default:
205
+ * `true`. Symmetric with `useRouteExit`'s same-name option.
206
+ */
207
+ skipSameRoute?: boolean;
208
+ }
209
+ /**
210
+ * Fire `handler` once when the component mounts as a result of a
211
+ * navigation. Mirror of `useRouteExit` for the entry side.
212
+ *
213
+ * What this hook covers that an ad-hoc `createEffect` + `useRoute()`
214
+ * doesn't:
215
+ *
216
+ * - **Skip-initial**: handler is skipped when there is no
217
+ * `transition.from` (i.e. first-load mount). Most consumers want to
218
+ * fire side effects only on real navigations, not on hydration.
219
+ * - **Same-route skip** (default): handler is skipped when
220
+ * `route.transition.from === route.name`. Sort/filter/query-only
221
+ * navigations re-trigger the effect (because the `route` reference
222
+ * changes), but they are not "entries" in the animation / analytics
223
+ * sense — the component instance has stayed mounted throughout.
224
+ * Opt out with `skipSameRoute: false`.
225
+ * - **Mount-time `route` / `previousRoute` snapshot**: the handler
226
+ * receives the values that were live at the moment of effect
227
+ * activation, not the latest ones (which may have moved on if the
228
+ * user navigated again before the effect drained).
229
+ *
230
+ * **Handler reactivity (Solid)**: Solid components run **once** at mount;
231
+ * `handler` is captured in closure when the hook is called. If you need
232
+ * different behavior across renders, derive it from a signal inside the
233
+ * handler body — do not rely on swapping the handler reference.
234
+ *
235
+ * @example Direction-aware entry animation
236
+ * ```tsx
237
+ * useRouteEnter(({ route }) => {
238
+ * const direction = route.context.browser?.direction;
239
+ * ref?.classList.add(
240
+ * direction === "back" ? "slide-from-left" : "slide-from-right",
241
+ * );
242
+ * });
243
+ * ```
244
+ *
245
+ * @example Analytics page-enter event (skip-initial built-in)
246
+ * ```tsx
247
+ * useRouteEnter(({ route, previousRoute }) => {
248
+ * analytics.track("page_enter", {
249
+ * route: route.name,
250
+ * from: previousRoute.name,
251
+ * });
252
+ * });
253
+ * ```
254
+ *
255
+ * @example Reading rich transition metadata via `route.transition`
256
+ * ```tsx
257
+ * useRouteEnter(({ route }) => {
258
+ * if (route.transition.redirected) {
259
+ * showToast(`Redirected from ${route.transition.from}`);
260
+ * }
261
+ * if (route.transition.segments.activated.includes("products")) {
262
+ * // products subtree just became active
263
+ * }
264
+ * });
265
+ * ```
266
+ */
267
+ declare function useRouteEnter(handler: RouteEnterHandler, options?: UseRouteEnterOptions): void;
268
+
103
269
  type ScrollRestorationMode = "restore" | "top" | "manual";
104
270
  interface ScrollRestorationOptions {
105
271
  mode?: ScrollRestorationMode | undefined;
@@ -111,6 +277,7 @@ interface RouteProviderProps {
111
277
  router: Router;
112
278
  announceNavigation?: boolean;
113
279
  scrollRestoration?: ScrollRestorationOptions;
280
+ viewTransitions?: boolean;
114
281
  }
115
282
  declare function RouterProvider(props: ParentProps<RouteProviderProps>): JSX.Element;
116
283
 
@@ -126,5 +293,5 @@ declare function createSignalFromSource<T>(source: RouterSource<T>): Accessor<T>
126
293
 
127
294
  declare function createStoreFromSource<T extends object>(source: RouterSource<T>): T;
128
295
 
129
- export { Link, RouteContext, RouteView, RouterContext, RouterErrorBoundary, RouterProvider, createSignalFromSource, createStoreFromSource, link, useNavigator, useRoute, useRouteNode, useRouteNodeStore, useRouteStore, useRouteUtils, useRouter, useRouterTransition };
130
- export type { LinkDirectiveOptions, LinkProps, RouteState, MatchProps as RouteViewMatchProps, NotFoundProps as RouteViewNotFoundProps, RouteViewProps, SelfProps as RouteViewSelfProps, RouterErrorBoundaryProps };
296
+ export { Link, RouteContext, RouteView, RouterContext, RouterErrorBoundary, RouterProvider, createSignalFromSource, createStoreFromSource, link, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteNodeStore, useRouteStore, useRouteUtils, useRouter, useRouterTransition };
297
+ export type { LinkDirectiveOptions, LinkProps, RouteEnterContext, RouteEnterHandler, RouteExitContext, RouteExitHandler, RouteState, MatchProps as RouteViewMatchProps, NotFoundProps as RouteViewNotFoundProps, RouteViewProps, SelfProps as RouteViewSelfProps, RouterErrorBoundaryProps, UseRouteEnterOptions, UseRouteExitOptions };
package/dist/cjs/index.js CHANGED
@@ -319,7 +319,7 @@ function removeAnnouncer() {
319
319
  document.querySelector(`[${ANNOUNCER_ATTR}]`)?.remove();
320
320
  }
321
321
  function resolveText(route, prefix, getCustomText, h1) {
322
- const h1Text = h1?.textContent.trim() ?? "";
322
+ const h1Text = (h1?.textContent ?? "").trim();
323
323
  const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX) ? "" : route.name;
324
324
  const rawText = h1Text || document.title || routeName || globalThis.location.pathname;
325
325
  return `${prefix}${rawText}`;
@@ -337,14 +337,14 @@ function manageFocus(h1) {
337
337
  }
338
338
 
339
339
  const STORAGE_KEY = "real-router:scroll";
340
- const NOOP_INSTANCE = Object.freeze({
340
+ const NOOP_INSTANCE$1 = Object.freeze({
341
341
  destroy: () => {
342
342
  /* no-op */
343
343
  }
344
344
  });
345
345
  function createScrollRestoration(router, options) {
346
346
  if (typeof globalThis.window === "undefined") {
347
- return NOOP_INSTANCE;
347
+ return NOOP_INSTANCE$1;
348
348
  }
349
349
  const mode = options?.mode ?? "restore";
350
350
 
@@ -352,7 +352,7 @@ function createScrollRestoration(router, options) {
352
352
  // don't subscribe, don't register pagehide — leave the browser's native
353
353
  // auto-restore intact for the app to override if it wants to.
354
354
  if (mode === "manual") {
355
- return NOOP_INSTANCE;
355
+ return NOOP_INSTANCE$1;
356
356
  }
357
357
  const anchorEnabled = options?.anchorScrolling ?? true;
358
358
  const getContainer = options?.scrollContainer;
@@ -493,6 +493,128 @@ function canonicalReplacer(_key, val) {
493
493
  return val;
494
494
  }
495
495
 
496
+ const NOOP_INSTANCE = Object.freeze({
497
+ destroy: () => {
498
+ /* no-op */
499
+ }
500
+ });
501
+ function createViewTransitions(router) {
502
+ if (typeof document === "undefined" || typeof document.startViewTransition !== "function") {
503
+ return NOOP_INSTANCE;
504
+ }
505
+ let closeVT = null;
506
+ let currentVT = null;
507
+ // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to
508
+ // distinguish "benign cleanup abort" (router's async path aborts its own
509
+ // controller in a finally block after successful navigation) from "real
510
+ // cancellation" (concurrent navigate, guard rejection, dispose).
511
+ let successFired = false;
512
+ const resolveAndClear = () => {
513
+ closeVT?.();
514
+ closeVT = null;
515
+ };
516
+ const offLeave = router.subscribeLeave(({
517
+ signal
518
+ }) => {
519
+ // Reentrant abort: signal already aborted when we're called. Open no VT
520
+ // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()
521
+ // after leave resolves. addEventListener("abort", ...) does not re-fire
522
+ // for past events, so skipping startViewTransition is the safe path.
523
+ if (signal.aborted) {
524
+ return;
525
+ }
526
+ successFired = false;
527
+ resolveAndClear();
528
+
529
+ // Return a Promise so the router awaits until the browser invokes
530
+ // updateCallback. This ensures old DOM snapshot is captured BEFORE the
531
+ // router commits the new state — giving correct exit→state→entry
532
+ // ordering (vs fire-and-forget, where URL changes before VT captures).
533
+ return new Promise(resolveLeave => {
534
+ // Capture the resolver synchronously BEFORE startViewTransition() is
535
+ // called. The browser invokes updateCallback in a later task, but
536
+ // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we
537
+ // captured `resolve` inside the callback, subscribe would see closeVT
538
+ // still null and skip resolving — the deferred would hang for 4s
539
+ // until the VT API aborts with TimeoutError.
540
+ const deferred = new Promise(resolve => {
541
+ closeVT = resolve;
542
+ });
543
+ signal.addEventListener("abort", () => {
544
+ if (successFired) {
545
+ // Router's async path (#finishAsyncNavigation) aborts its own
546
+ // controller in a finally block AFTER completeTransition (and
547
+ // thus AFTER subscribe fired). This is cleanup, not
548
+ // cancellation — VT is progressing normally, do nothing.
549
+ return;
550
+ }
551
+
552
+ // Real cancellation (concurrent navigate, dispose). Resolve the
553
+ // deferred so updateCallback can complete, skip the VT so no
554
+ // stale animation leaks, and unblock the router if the abort
555
+ // fires before updateCallback was invoked.
556
+ resolveAndClear();
557
+ currentVT?.skipTransition?.();
558
+ resolveLeave();
559
+ }, {
560
+ once: true
561
+ });
562
+ try {
563
+ currentVT = document.startViewTransition(() => {
564
+ // Resolving here unblocks the router at the moment the browser
565
+ // enters updateCallback — by spec, old DOM snapshot is captured
566
+ // before this callback runs. Router now proceeds through
567
+ // activation guards and setState; the VT animation waits on
568
+ // `deferred`, which is resolved from router.subscribe after a
569
+ // task-queue tick (see NOTE on setTimeout below).
570
+ resolveLeave();
571
+ return deferred;
572
+ });
573
+ } catch {
574
+ // Defensive: spec says startViewTransition doesn't throw under
575
+ // normal conditions, but Chromium has had edge cases (detached
576
+ // document, extension interference). Clean up and unblock router.
577
+ resolveAndClear();
578
+ resolveLeave();
579
+ }
580
+ });
581
+ });
582
+ const offSuccess = router.subscribe(() => {
583
+ const resolver = closeVT;
584
+ successFired = true;
585
+ closeVT = null;
586
+ if (resolver === null) {
587
+ currentVT = null;
588
+ } else {
589
+ // CRITICAL: CANNOT use requestAnimationFrame here. When the router
590
+ // takes the async path (leave returned a Promise), subscribe fires
591
+ // AFTER the browser has already transitioned VT into the
592
+ // "update-callback-called" phase. In that phase Chromium sets
593
+ // rendering suppression to true, which ALSO blocks rAF callbacks.
594
+ // rAF would never fire → deferred never resolves → browser aborts
595
+ // vt.ready with TimeoutError after 4s (observed in Chromium).
596
+ //
597
+ // setTimeout runs on the task queue independent of the rendering
598
+ // pipeline, so it fires regardless of suppression. React's scheduler
599
+ // uses MessageChannel tasks, which are queued before our setTimeout,
600
+ // so the new DOM is committed by the time our callback runs.
601
+ setTimeout(() => {
602
+ resolver();
603
+ currentVT = null;
604
+ }, 0);
605
+ }
606
+ });
607
+ return {
608
+ destroy: () => {
609
+ offLeave();
610
+ offSuccess();
611
+ currentVT?.skipTransition?.();
612
+ currentVT = null;
613
+ resolveAndClear();
614
+ }
615
+ };
616
+ }
617
+
496
618
  function shouldNavigate(evt) {
497
619
  return evt.button === 0 && !evt.metaKey && !evt.altKey && !evt.ctrlKey && !evt.shiftKey;
498
620
  }
@@ -680,6 +802,9 @@ const useRoute = () => {
680
802
  if (!routeSignal) {
681
803
  throw new Error("useRoute must be used within a RouterProvider");
682
804
  }
805
+ if (!routeSignal().route) {
806
+ throw new Error("useRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?");
807
+ }
683
808
  return routeSignal;
684
809
  };
685
810
 
@@ -710,6 +835,198 @@ function useRouterTransition() {
710
835
  return createSignalFromSource(source);
711
836
  }
712
837
 
838
+ /**
839
+ * Subscribe to the router's leave-window with the universal guards baked
840
+ * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
841
+ * boilerplate every time:
842
+ *
843
+ * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
844
+ * when the handler would run (rapid navigation superseded a slower
845
+ * one), the handler is skipped entirely. `signal.addEventListener(
846
+ * "abort", ...)` does not fire retroactively, so without this guard
847
+ * downstream cleanup would never trigger.
848
+ * - **Same-route skip**: by default, `route.name === nextRoute.name`
849
+ * short-circuits the handler — query-only navigations (sort, filter,
850
+ * pagination) skip the work. Opt out with `skipSameRoute: false`.
851
+ *
852
+ * Returns nothing — the subscription's lifecycle is bound to the
853
+ * component via `onCleanup`.
854
+ *
855
+ * If the handler returns a Promise, the router blocks on it. If the
856
+ * Promise resolves, navigation proceeds. If it rejects, the router emits
857
+ * `TRANSITION_CANCELLED`.
858
+ *
859
+ * **Handler reactivity (Solid)**: Solid components run **once** at mount;
860
+ * `handler` is captured in closure at the call site. If you need
861
+ * different behavior across renders, derive it from a signal inside the
862
+ * handler body — do not rely on swapping the handler reference.
863
+ *
864
+ * @example Animation
865
+ * ```tsx
866
+ * let ref: HTMLDivElement | undefined;
867
+ *
868
+ * useRouteExit(async ({ signal }) => {
869
+ * const el = ref;
870
+ * if (!el) return;
871
+ * el.classList.add("fade-out");
872
+ * const cleanup = () => el.classList.remove("fade-out");
873
+ * signal.addEventListener("abort", cleanup, { once: true });
874
+ * try {
875
+ * el.getBoundingClientRect(); // style flush
876
+ * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
877
+ * } finally {
878
+ * cleanup();
879
+ * }
880
+ * });
881
+ * ```
882
+ *
883
+ * @example Auto-save form draft
884
+ * ```tsx
885
+ * useRouteExit(async ({ signal }) => {
886
+ * if (formState.dirty) await api.saveDraft(formState, { signal });
887
+ * });
888
+ * ```
889
+ *
890
+ * @example Reading rich transition metadata via `nextRoute.transition`
891
+ * ```tsx
892
+ * useRouteExit(({ route, nextRoute }) => {
893
+ * if (nextRoute.transition.segments.deactivated.includes("products")) {
894
+ * productCache.clear();
895
+ * }
896
+ * if (nextRoute.transition.redirected) {
897
+ * return;
898
+ * }
899
+ * });
900
+ * ```
901
+ */
902
+ function useRouteExit(handler, options) {
903
+ const router = useRouter();
904
+ const skipSameRoute = options?.skipSameRoute ?? true;
905
+ const off = router.subscribeLeave(({
906
+ route,
907
+ nextRoute,
908
+ signal
909
+ }) => {
910
+ if (skipSameRoute && route.name === nextRoute.name) {
911
+ return;
912
+ }
913
+
914
+ // Reentrant abort: signal is already aborted when listener fires
915
+ // (e.g. a newer navigate superseded this one before subscribeLeave
916
+ // even ran). addEventListener("abort", ...) does not fire
917
+ // retroactively, so we skip the handler entirely.
918
+ if (signal.aborted) {
919
+ return;
920
+ }
921
+ return handler({
922
+ route,
923
+ nextRoute,
924
+ signal
925
+ });
926
+ });
927
+ solidJs.onCleanup(off);
928
+ }
929
+
930
+ /**
931
+ * Fire `handler` once when the component mounts as a result of a
932
+ * navigation. Mirror of `useRouteExit` for the entry side.
933
+ *
934
+ * What this hook covers that an ad-hoc `createEffect` + `useRoute()`
935
+ * doesn't:
936
+ *
937
+ * - **Skip-initial**: handler is skipped when there is no
938
+ * `transition.from` (i.e. first-load mount). Most consumers want to
939
+ * fire side effects only on real navigations, not on hydration.
940
+ * - **Same-route skip** (default): handler is skipped when
941
+ * `route.transition.from === route.name`. Sort/filter/query-only
942
+ * navigations re-trigger the effect (because the `route` reference
943
+ * changes), but they are not "entries" in the animation / analytics
944
+ * sense — the component instance has stayed mounted throughout.
945
+ * Opt out with `skipSameRoute: false`.
946
+ * - **Mount-time `route` / `previousRoute` snapshot**: the handler
947
+ * receives the values that were live at the moment of effect
948
+ * activation, not the latest ones (which may have moved on if the
949
+ * user navigated again before the effect drained).
950
+ *
951
+ * **Handler reactivity (Solid)**: Solid components run **once** at mount;
952
+ * `handler` is captured in closure when the hook is called. If you need
953
+ * different behavior across renders, derive it from a signal inside the
954
+ * handler body — do not rely on swapping the handler reference.
955
+ *
956
+ * @example Direction-aware entry animation
957
+ * ```tsx
958
+ * useRouteEnter(({ route }) => {
959
+ * const direction = route.context.browser?.direction;
960
+ * ref?.classList.add(
961
+ * direction === "back" ? "slide-from-left" : "slide-from-right",
962
+ * );
963
+ * });
964
+ * ```
965
+ *
966
+ * @example Analytics page-enter event (skip-initial built-in)
967
+ * ```tsx
968
+ * useRouteEnter(({ route, previousRoute }) => {
969
+ * analytics.track("page_enter", {
970
+ * route: route.name,
971
+ * from: previousRoute.name,
972
+ * });
973
+ * });
974
+ * ```
975
+ *
976
+ * @example Reading rich transition metadata via `route.transition`
977
+ * ```tsx
978
+ * useRouteEnter(({ route }) => {
979
+ * if (route.transition.redirected) {
980
+ * showToast(`Redirected from ${route.transition.from}`);
981
+ * }
982
+ * if (route.transition.segments.activated.includes("products")) {
983
+ * // products subtree just became active
984
+ * }
985
+ * });
986
+ * ```
987
+ */
988
+ function useRouteEnter(handler, options) {
989
+ const routeState = useRoute();
990
+ const skipSameRoute = options?.skipSameRoute ?? true;
991
+ let lastHandledRoute = null;
992
+ solidJs.createEffect(() => {
993
+ const {
994
+ route,
995
+ previousRoute
996
+ } = routeState();
997
+
998
+ // Early-exit guards, top-down:
999
+ //
1000
+ // - **Skip-initial**: `state.transition.from` is undefined only
1001
+ // for the very first state committed by `router.start()`.
1002
+ // - **Skip-same-route**: query-only navigations have
1003
+ // `transition.from === route.name`. Opt-out via
1004
+ // `skipSameRoute: false`.
1005
+ // - **Defensive dedupe + missing `previousRoute`**: same `route`
1006
+ // ref between effect activations is unexpected on Solid (effects
1007
+ // run once per dependency change); `!previousRoute` is unreachable
1008
+ // once `transition.from` is set (the two are populated together by
1009
+ // core). Both kept for parity with React; v8-ignored.
1010
+ if (!route.transition.from) {
1011
+ return;
1012
+ }
1013
+ if (skipSameRoute && route.transition.from === route.name) {
1014
+ return;
1015
+ }
1016
+ /* v8 ignore start */
1017
+ if (lastHandledRoute === route || !previousRoute) {
1018
+ return;
1019
+ }
1020
+ /* v8 ignore stop */
1021
+
1022
+ lastHandledRoute = route;
1023
+ handler({
1024
+ route,
1025
+ previousRoute
1026
+ });
1027
+ });
1028
+ }
1029
+
713
1030
  function isRouteActive(linkRouteName, currentRouteName) {
714
1031
  return currentRouteName === linkRouteName || currentRouteName.startsWith(`${linkRouteName}.`);
715
1032
  }
@@ -732,6 +1049,15 @@ function RouterProvider(props) {
732
1049
  sr.destroy();
733
1050
  });
734
1051
  });
1052
+ solidJs.onMount(() => {
1053
+ if (!props.viewTransitions) {
1054
+ return;
1055
+ }
1056
+ const vt = createViewTransitions(props.router);
1057
+ solidJs.onCleanup(() => {
1058
+ vt.destroy();
1059
+ });
1060
+ });
735
1061
  const navigator = core.getNavigator(props.router);
736
1062
  const routeSource = sources.createRouteSource(props.router);
737
1063
  const routeSignal = createSignalFromSource(routeSource);
@@ -766,6 +1092,8 @@ exports.createStoreFromSource = createStoreFromSource;
766
1092
  exports.link = link;
767
1093
  exports.useNavigator = useNavigator;
768
1094
  exports.useRoute = useRoute;
1095
+ exports.useRouteEnter = useRouteEnter;
1096
+ exports.useRouteExit = useRouteExit;
769
1097
  exports.useRouteNode = useRouteNode;
770
1098
  exports.useRouteNodeStore = useRouteNodeStore;
771
1099
  exports.useRouteStore = useRouteStore;