@real-router/preact 0.6.0 → 0.8.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.
@@ -0,0 +1,155 @@
1
+ import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
2
+
3
+ import { useRoute } from "./useRoute";
4
+
5
+ import type { State } from "@real-router/core";
6
+
7
+ export interface RouteEnterContext {
8
+ /** The route that was just activated. */
9
+ route: State;
10
+ /** The route that was active immediately before this navigation. */
11
+ previousRoute: State;
12
+ }
13
+
14
+ export type RouteEnterHandler = (context: RouteEnterContext) => void;
15
+
16
+ export interface UseRouteEnterOptions {
17
+ /**
18
+ * Skip the handler when `route.name === previousRoute.name`
19
+ * (sort/filter/query-only navigations on the same route). Default:
20
+ * `true`. Symmetric with `useRouteExit`'s same-name option.
21
+ */
22
+ skipSameRoute?: boolean;
23
+ }
24
+
25
+ /**
26
+ * Fire `handler` once when the component mounts as a result of a
27
+ * navigation. Mirror of `useRouteExit` for the entry side.
28
+ *
29
+ * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:
30
+ *
31
+ * - **Skip-initial**: handler is skipped when there is no
32
+ * `previousRoute` (i.e. first-load mount). Most consumers want to
33
+ * fire side effects only on real navigations, not on hydration.
34
+ * - **Same-route skip** (default): handler is skipped when
35
+ * `route.name === previousRoute.name`. Sort/filter/query-only
36
+ * navigations re-run the effect (because `route` reference changes
37
+ * in `useRoute`'s snapshot), but they are not "entries" in the
38
+ * animation / analytics sense — the component instance has stayed
39
+ * mounted throughout. Opt out with `skipSameRoute: false` when
40
+ * the handler legitimately needs to fire on every navigation
41
+ * (e.g. analytics tracking each query-param flip).
42
+ * - **Latest-handler ref**: the handler can change identity on every
43
+ * render without re-running the effect — the registered wrapper
44
+ * dispatches to whatever `handlerRef.current` points to.
45
+ * - **Mount-time `route` / `previousRoute` snapshot**: the handler
46
+ * receives the values that were live at the moment of mount, not
47
+ * the latest ones (which may have moved on if the user navigated
48
+ * again before the effect drained).
49
+ *
50
+ * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from
51
+ * `@real-router/sources` (Preact polyfill: useState + useEffect, same
52
+ * post-commit semantics), so by the time the new component's effect
53
+ * runs, the snapshot is the post-commit one. This is the reason we can
54
+ * read mount-time context from `useRoute()` instead of subscribing to
55
+ * `router.subscribe` directly (which fires before Preact schedules a
56
+ * re-render — the well-known race in distributed components).
57
+ *
58
+ * Note: Preact does not expose a `StrictMode` equivalent, so the
59
+ * `lastHandledRouteRef` guard exists primarily for defensive symmetry
60
+ * with the React implementation. It is harmless in Preact.
61
+ *
62
+ * @example Direction-aware entry animation
63
+ * ```tsx
64
+ * useRouteEnter(({ route }) => {
65
+ * const direction = route.context.browser?.direction;
66
+ * ref.current?.classList.add(
67
+ * direction === "back" ? "slide-from-left" : "slide-from-right",
68
+ * );
69
+ * });
70
+ * ```
71
+ *
72
+ * @example Source-aware focus management
73
+ * ```tsx
74
+ * useRouteEnter(({ route }) => {
75
+ * if (route.context.browser?.source === "navigate") {
76
+ * headingRef.current?.focus();
77
+ * }
78
+ * });
79
+ * ```
80
+ *
81
+ * @example Analytics page-enter event (skip-initial built-in)
82
+ * ```tsx
83
+ * useRouteEnter(({ route, previousRoute }) => {
84
+ * analytics.track("page_enter", {
85
+ * route: route.name,
86
+ * from: previousRoute.name,
87
+ * });
88
+ * });
89
+ * ```
90
+ *
91
+ * @example Reading rich transition metadata via `route.transition`
92
+ * ```tsx
93
+ * useRouteEnter(({ route }) => {
94
+ * // route.transition: TransitionMeta — populated by core for every state
95
+ * if (route.transition.redirected) {
96
+ * showToast(`Redirected from ${route.transition.from}`);
97
+ * }
98
+ * if (route.transition.segments.activated.includes("products")) {
99
+ * // products subtree just became active (could be products or
100
+ * // products.detail). Useful for subtree-scoped side effects.
101
+ * }
102
+ * });
103
+ * ```
104
+ */
105
+ export function useRouteEnter(
106
+ handler: RouteEnterHandler,
107
+ options?: UseRouteEnterOptions,
108
+ ): void {
109
+ const { route, previousRoute } = useRoute();
110
+ const handlerRef = useRef(handler);
111
+ const lastHandledRouteRef = useRef<State | null>(null);
112
+ const skipSameRoute = options?.skipSameRoute ?? true;
113
+
114
+ // Keep the latest handler reference accessible without re-running
115
+ // the effect. useLayoutEffect (synchronous, post-render, pre-paint)
116
+ // updates the ref before the effect can read it.
117
+ useLayoutEffect(() => {
118
+ handlerRef.current = handler;
119
+ });
120
+
121
+ useEffect(() => {
122
+ // Early-exit guards, top-down:
123
+ //
124
+ // - **Defensive**: `route` / `previousRoute` may be undefined
125
+ // during SSR or pre-start hydration. Not testable from vitest
126
+ // (tests start the router before render), so v8-ignored.
127
+ // - **Skip-initial**: `state.transition.from` is undefined only
128
+ // for the very first state committed by `router.start()`.
129
+ // - **Skip-same-route**: query-only navigations have
130
+ // `transition.from === route.name`. Opt-out via
131
+ // `skipSameRoute: false`.
132
+ // - **Defensive dedupe**: same `route` ref between effect
133
+ // cleanup + re-run. Preact has no StrictMode, but we keep the
134
+ // guard for parity with React; v8-ignored.
135
+ /* v8 ignore start */
136
+ if (!route) {
137
+ return;
138
+ }
139
+ /* v8 ignore stop */
140
+ if (!route.transition.from) {
141
+ return;
142
+ }
143
+ if (skipSameRoute && route.transition.from === route.name) {
144
+ return;
145
+ }
146
+ /* v8 ignore start */
147
+ if (lastHandledRouteRef.current === route || !previousRoute) {
148
+ return;
149
+ }
150
+ /* v8 ignore stop */
151
+
152
+ lastHandledRouteRef.current = route;
153
+ handlerRef.current({ route, previousRoute });
154
+ }, [route, previousRoute, skipSameRoute]);
155
+ }
@@ -0,0 +1,159 @@
1
+ import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
2
+
3
+ import { useRouter } from "./useRouter";
4
+
5
+ import type { State } from "@real-router/core";
6
+
7
+ export interface RouteExitContext {
8
+ /** The route being left. */
9
+ route: State;
10
+ /** The route being navigated to. */
11
+ nextRoute: State;
12
+ /**
13
+ * AbortSignal that fires when this navigation is superseded by a later
14
+ * one (rapid clicks). Already filtered: when the handler runs,
15
+ * `signal.aborted` is guaranteed to be `false`. Use
16
+ * `signal.addEventListener("abort", cleanup, { once: true })` for
17
+ * cleanup that must run on cancellation.
18
+ */
19
+ signal: AbortSignal;
20
+ }
21
+
22
+ export interface UseRouteExitOptions {
23
+ /**
24
+ * Skip the handler when `route.name === nextRoute.name`
25
+ * (sort/filter/query-only navigations on the same route). Default:
26
+ * `true`.
27
+ */
28
+ skipSameRoute?: boolean;
29
+ }
30
+
31
+ export type RouteExitHandler = (
32
+ context: RouteExitContext,
33
+ ) => void | Promise<void>;
34
+
35
+ /**
36
+ * Subscribe to the router's leave-window with the universal guards baked
37
+ * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
38
+ * boilerplate every time:
39
+ *
40
+ * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
41
+ * when the handler would run (rapid navigation superseded a slower
42
+ * one), the handler is skipped entirely. `signal.addEventListener(
43
+ * "abort", ...)` does not fire retroactively, so without this guard
44
+ * downstream cleanup would never trigger.
45
+ * - **Same-route skip**: by default, `route.name === nextRoute.name`
46
+ * short-circuits the handler — query-only navigations (sort, filter,
47
+ * pagination) skip the work. Opt out with `skipSameRoute: false`.
48
+ * - **Stable handler reference**: the handler can change identity on
49
+ * every render without causing resubscription — internal ref keeps
50
+ * the latest handler accessible to the long-lived subscription.
51
+ *
52
+ * Returns nothing — the subscription's lifecycle is bound to the
53
+ * component's mount.
54
+ *
55
+ * If the handler returns a Promise, the router blocks on it. If the
56
+ * Promise resolves, navigation proceeds. If it rejects, the router emits
57
+ * `TRANSITION_CANCELLED` (existing core behavior, no change here).
58
+ *
59
+ * @example Animation
60
+ * ```tsx
61
+ * const ref = useRef<HTMLDivElement>(null);
62
+ *
63
+ * useRouteExit(async ({ signal }) => {
64
+ * const el = ref.current;
65
+ * if (!el) return;
66
+ * el.classList.add("fade-out");
67
+ * const cleanup = () => el.classList.remove("fade-out");
68
+ * signal.addEventListener("abort", cleanup, { once: true });
69
+ * try {
70
+ * el.getBoundingClientRect(); // style flush
71
+ * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
72
+ * } finally {
73
+ * cleanup();
74
+ * }
75
+ * });
76
+ * ```
77
+ *
78
+ * @example Auto-save form draft
79
+ * ```tsx
80
+ * useRouteExit(async ({ signal }) => {
81
+ * if (formState.dirty) await api.saveDraft(formState, { signal });
82
+ * });
83
+ * ```
84
+ *
85
+ * @example Cancel inflight requests
86
+ * ```tsx
87
+ * useRouteExit(() => {
88
+ * inflightController.abort();
89
+ * });
90
+ * ```
91
+ *
92
+ * @example Library-coordinated exit (motion / framer-motion)
93
+ * ```tsx
94
+ * const exitResolverRef = useRef<(() => void) | null>(null);
95
+ *
96
+ * useRouteExit(({ signal }) => {
97
+ * return new Promise<void>((resolve) => {
98
+ * exitResolverRef.current = resolve;
99
+ * signal.addEventListener("abort", () => resolve(), { once: true });
100
+ * });
101
+ * });
102
+ *
103
+ * const onExitComplete = () => exitResolverRef.current?.();
104
+ * // pass onExitComplete to <AnimatePresence>
105
+ * ```
106
+ *
107
+ * @example Reading rich transition metadata via `nextRoute.transition`
108
+ * ```tsx
109
+ * useRouteExit(({ route, nextRoute }) => {
110
+ * // nextRoute.transition: TransitionMeta — preview of the upcoming nav
111
+ * if (nextRoute.transition.segments.deactivated.includes("products")) {
112
+ * // leaving the products subtree entirely — flush product-related caches
113
+ * productCache.clear();
114
+ * }
115
+ * if (nextRoute.transition.redirected) {
116
+ * // skip animation when navigation arrived via redirect
117
+ * return;
118
+ * }
119
+ * });
120
+ * ```
121
+ */
122
+ export function useRouteExit(
123
+ handler: RouteExitHandler,
124
+ options?: UseRouteExitOptions,
125
+ ): void {
126
+ const router = useRouter();
127
+ const handlerRef = useRef(handler);
128
+ const skipSameRoute = options?.skipSameRoute ?? true;
129
+
130
+ // Keep the latest handler accessible to the subscription without
131
+ // resubscribing on every render — the subscription registers the
132
+ // wrapper once and dispatches to whatever ref points to.
133
+ // useLayoutEffect (synchronous, post-render, pre-paint) updates the
134
+ // ref before the browser can dispatch any router events that could
135
+ // observe a stale closure.
136
+ useLayoutEffect(() => {
137
+ handlerRef.current = handler;
138
+ });
139
+
140
+ useEffect(() => {
141
+ return router.subscribeLeave(({ route, nextRoute, signal }) => {
142
+ if (skipSameRoute && route.name === nextRoute.name) {
143
+ return;
144
+ }
145
+
146
+ // Reentrant abort: signal is already aborted when listener fires
147
+ // (e.g. a newer navigate superseded this one before subscribeLeave
148
+ // even ran). addEventListener("abort", ...) does not fire
149
+ // retroactively, so we skip the handler entirely — any cleanup the
150
+ // handler would have wired via abort listener must not run because
151
+ // the corresponding `add` work never happened.
152
+ if (signal.aborted) {
153
+ return;
154
+ }
155
+
156
+ return handlerRef.current({ route, nextRoute, signal });
157
+ });
158
+ }, [router, skipSameRoute]);
159
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,10 @@ export { useRouteNode } from "./hooks/useRouteNode";
18
18
 
19
19
  export { useRouterTransition } from "./hooks/useRouterTransition";
20
20
 
21
+ export { useRouteExit } from "./hooks/useRouteExit";
22
+
23
+ export { useRouteEnter } from "./hooks/useRouteEnter";
24
+
21
25
  // Context
22
26
  export { RouterProvider } from "./RouterProvider";
23
27
 
@@ -31,9 +35,22 @@ export type { RouterErrorBoundaryProps } from "./components/RouterErrorBoundary"
31
35
  export type {
32
36
  RouteViewProps,
33
37
  RouteViewMatchProps,
38
+ RouteViewSelfProps,
34
39
  RouteViewNotFoundProps,
35
40
  } from "./components/RouteView";
36
41
 
42
+ export type {
43
+ RouteExitContext,
44
+ RouteExitHandler,
45
+ UseRouteExitOptions,
46
+ } from "./hooks/useRouteExit";
47
+
48
+ export type {
49
+ RouteEnterContext,
50
+ RouteEnterHandler,
51
+ UseRouteEnterOptions,
52
+ } from "./hooks/useRouteEnter";
53
+
37
54
  export type { Navigator } from "@real-router/core";
38
55
 
39
56
  export type { RouterTransitionSnapshot } from "@real-router/sources";