@real-router/preact 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.
@@ -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
 
@@ -35,6 +39,18 @@ export type {
35
39
  RouteViewNotFoundProps,
36
40
  } from "./components/RouteView";
37
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
+
38
54
  export type { Navigator } from "@real-router/core";
39
55
 
40
56
  export type { RouterTransitionSnapshot } from "@real-router/sources";