@real-router/react 0.24.1 → 0.25.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.
Files changed (123) hide show
  1. package/README.md +127 -7
  2. package/dist/cjs/Await-whr-pcvo.d.ts +41 -0
  3. package/dist/cjs/Await-whr-pcvo.d.ts.map +1 -0
  4. package/dist/cjs/HttpStatusProvider-Dh6cMr95.d.ts +143 -0
  5. package/dist/cjs/HttpStatusProvider-Dh6cMr95.d.ts.map +1 -0
  6. package/dist/cjs/Link-BspioC76.js +2 -0
  7. package/dist/cjs/Link-BspioC76.js.map +1 -0
  8. package/dist/cjs/RouterErrorBoundary-BlJmaoyr.d.ts +47 -0
  9. package/dist/cjs/RouterErrorBoundary-BlJmaoyr.d.ts.map +1 -0
  10. package/dist/cjs/{RouterProvider-Bj1_NbpA.d.ts → RouterProvider-DvC9mViF.d.ts} +2 -2
  11. package/dist/cjs/RouterProvider-DvC9mViF.d.ts.map +1 -0
  12. package/dist/cjs/RouterProvider-fJvMO5Tc.js +2 -0
  13. package/dist/cjs/RouterProvider-fJvMO5Tc.js.map +1 -0
  14. package/dist/cjs/createHttpStatusSink-D_6IiR5E.js +2 -0
  15. package/dist/cjs/createHttpStatusSink-D_6IiR5E.js.map +1 -0
  16. package/dist/cjs/index.d.ts +6 -281
  17. package/dist/cjs/index.js +1 -1
  18. package/dist/cjs/index.js.map +1 -1
  19. package/dist/cjs/index.react-server.d.ts +5 -0
  20. package/dist/cjs/index.react-server.js +0 -0
  21. package/dist/cjs/ink.d.ts +2 -1
  22. package/dist/cjs/ink.d.ts.map +1 -1
  23. package/dist/cjs/ink.js +1 -1
  24. package/dist/cjs/ink.js.map +1 -1
  25. package/dist/cjs/legacy.d.ts +3 -2
  26. package/dist/cjs/legacy.js +1 -1
  27. package/dist/cjs/legacy.ssr.d.ts +3 -0
  28. package/dist/cjs/legacy.ssr.js +1 -0
  29. package/dist/cjs/ssr.d.ts +4 -0
  30. package/dist/cjs/ssr.js +2 -0
  31. package/dist/cjs/ssr.js.map +1 -0
  32. package/dist/cjs/ssr.react-server.d.ts +3 -0
  33. package/dist/cjs/ssr.react-server.js +0 -0
  34. package/dist/cjs/useDeferred-DE5YUsfa.d.ts +24 -0
  35. package/dist/cjs/useDeferred-DE5YUsfa.d.ts.map +1 -0
  36. package/dist/cjs/useRoute-Dudo2K_0.js +2 -0
  37. package/dist/cjs/useRoute-Dudo2K_0.js.map +1 -0
  38. package/dist/cjs/useRouteEnter-gfy65W0D.d.ts +279 -0
  39. package/dist/cjs/useRouteEnter-gfy65W0D.d.ts.map +1 -0
  40. package/dist/cjs/useRouterTransition-BfayPs0h.d.ts +56 -0
  41. package/dist/cjs/useRouterTransition-BfayPs0h.d.ts.map +1 -0
  42. package/dist/esm/Await-qSmJ-ZuN.d.mts +41 -0
  43. package/dist/esm/Await-qSmJ-ZuN.d.mts.map +1 -0
  44. package/dist/esm/HttpStatusProvider-Cy9GSANm.d.mts +143 -0
  45. package/dist/esm/HttpStatusProvider-Cy9GSANm.d.mts.map +1 -0
  46. package/dist/esm/Link-BQol2GYb.mjs +2 -0
  47. package/dist/esm/Link-BQol2GYb.mjs.map +1 -0
  48. package/dist/esm/RouterErrorBoundary-C-MH_yrP.d.mts +47 -0
  49. package/dist/esm/RouterErrorBoundary-C-MH_yrP.d.mts.map +1 -0
  50. package/dist/esm/{RouterProvider-Dr3X_vbc.d.mts → RouterProvider-D_ZlPVAC.d.mts} +2 -2
  51. package/dist/esm/RouterProvider-D_ZlPVAC.d.mts.map +1 -0
  52. package/dist/esm/RouterProvider-a9y9bqji.mjs +2 -0
  53. package/dist/esm/RouterProvider-a9y9bqji.mjs.map +1 -0
  54. package/dist/esm/createHttpStatusSink-BXWVamHE.mjs +2 -0
  55. package/dist/esm/createHttpStatusSink-BXWVamHE.mjs.map +1 -0
  56. package/dist/esm/index.d.mts +6 -281
  57. package/dist/esm/index.mjs +1 -1
  58. package/dist/esm/index.mjs.map +1 -1
  59. package/dist/esm/index.react-server.d.mts +5 -0
  60. package/dist/esm/index.react-server.mjs +0 -0
  61. package/dist/esm/ink.d.mts +2 -1
  62. package/dist/esm/ink.d.mts.map +1 -1
  63. package/dist/esm/ink.mjs +1 -1
  64. package/dist/esm/ink.mjs.map +1 -1
  65. package/dist/esm/legacy.d.mts +3 -2
  66. package/dist/esm/legacy.mjs +1 -1
  67. package/dist/esm/legacy.ssr.d.mts +3 -0
  68. package/dist/esm/legacy.ssr.mjs +1 -0
  69. package/dist/esm/ssr.d.mts +4 -0
  70. package/dist/esm/ssr.mjs +2 -0
  71. package/dist/esm/ssr.mjs.map +1 -0
  72. package/dist/esm/ssr.react-server.d.mts +3 -0
  73. package/dist/esm/ssr.react-server.mjs +0 -0
  74. package/dist/esm/useDeferred-B5Qy7ttQ.d.mts +24 -0
  75. package/dist/esm/useDeferred-B5Qy7ttQ.d.mts.map +1 -0
  76. package/dist/esm/useRoute-Bta1jyl2.mjs +2 -0
  77. package/dist/esm/useRoute-Bta1jyl2.mjs.map +1 -0
  78. package/dist/esm/useRouteEnter-CxjYofFa.d.mts +279 -0
  79. package/dist/esm/useRouteEnter-CxjYofFa.d.mts.map +1 -0
  80. package/dist/esm/useRouterTransition-CI1P95ZQ.d.mts +56 -0
  81. package/dist/esm/useRouterTransition-CI1P95ZQ.d.mts.map +1 -0
  82. package/package.json +46 -4
  83. package/src/components/Await.tsx +46 -0
  84. package/src/components/ClientOnly.tsx +25 -0
  85. package/src/components/HttpStatusCode.tsx +66 -0
  86. package/src/components/HttpStatusProvider.tsx +26 -0
  87. package/src/components/InkLink.tsx +44 -22
  88. package/src/components/Link.tsx +32 -36
  89. package/src/components/RouterErrorBoundary.tsx +21 -6
  90. package/src/components/ServerOnly.tsx +26 -0
  91. package/src/components/Streamed.tsx +30 -0
  92. package/src/components/modern/RouteView/RouteView.tsx +9 -3
  93. package/src/components/modern/RouteView/helpers.tsx +26 -16
  94. package/src/constants.ts +7 -8
  95. package/src/context.ts +4 -2
  96. package/src/hooks/useDeferred.tsx +34 -0
  97. package/src/hooks/useIsActiveRoute.tsx +17 -9
  98. package/src/hooks/useNavigator.tsx +0 -2
  99. package/src/hooks/useRoute.tsx +10 -7
  100. package/src/hooks/useRouter.tsx +0 -2
  101. package/src/index.react-server.ts +33 -0
  102. package/src/index.ts +5 -0
  103. package/src/legacy.ssr.ts +35 -0
  104. package/src/legacy.ts +4 -0
  105. package/src/ssr.react-server.ts +21 -0
  106. package/src/ssr.ts +43 -0
  107. package/src/utils/createHttpStatusSink.ts +27 -0
  108. package/dist/cjs/Link-DYvAnJlk.js +0 -2
  109. package/dist/cjs/Link-DYvAnJlk.js.map +0 -1
  110. package/dist/cjs/RouterProvider-Bj1_NbpA.d.ts.map +0 -1
  111. package/dist/cjs/RouterProvider-CfBNR-k7.js +0 -2
  112. package/dist/cjs/RouterProvider-CfBNR-k7.js.map +0 -1
  113. package/dist/cjs/index.d.ts.map +0 -1
  114. package/dist/cjs/useRouterTransition-BYit_9Mt.d.ts +0 -92
  115. package/dist/cjs/useRouterTransition-BYit_9Mt.d.ts.map +0 -1
  116. package/dist/esm/Link-C7upxMc8.mjs +0 -2
  117. package/dist/esm/Link-C7upxMc8.mjs.map +0 -1
  118. package/dist/esm/RouterProvider-CS2ZoONm.mjs +0 -2
  119. package/dist/esm/RouterProvider-CS2ZoONm.mjs.map +0 -1
  120. package/dist/esm/RouterProvider-Dr3X_vbc.d.mts.map +0 -1
  121. package/dist/esm/index.d.mts.map +0 -1
  122. package/dist/esm/useRouterTransition-B65Wvngj.d.mts +0 -92
  123. package/dist/esm/useRouterTransition-B65Wvngj.d.mts.map +0 -1
@@ -1,282 +1,7 @@
1
- import { a as useNavigator, c as RouterErrorBoundaryProps, i as useRouteUtils, l as LinkProps, n as useRouteNode, o as useRouter, r as useRoute, s as RouterErrorBoundary, t as useRouterTransition } from "./useRouterTransition-B65Wvngj.mjs";
2
- import { n as Link, t as RouterProvider } from "./RouterProvider-Dr3X_vbc.mjs";
3
- import { ReactElement, ReactNode } from "react";
4
- import { Navigator, State } from "@real-router/core";
1
+ import { a as RouteExitContext, c as useRouteExit, d as NotFoundProps, f as RouteViewProps, i as useRouteEnter, l as RouteView, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-CxjYofFa.mjs";
2
+ import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-C-MH_yrP.mjs";
3
+ import { n as Link, t as RouterProvider } from "./RouterProvider-D_ZlPVAC.mjs";
4
+ import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-CI1P95ZQ.mjs";
5
+ import { Navigator } from "@real-router/core";
5
6
  import { RouterTransitionSnapshot } from "@real-router/sources";
6
-
7
- //#region src/components/modern/RouteView/types.d.ts
8
- interface RouteViewProps {
9
- /** Route tree node name to subscribe to. "" for root. */
10
- readonly nodeName: string;
11
- /** <RouteView.Match>, <RouteView.Self>, and <RouteView.NotFound> elements. */
12
- readonly children: ReactNode;
13
- }
14
- interface MatchProps {
15
- /** Route segment to match against. */
16
- readonly segment: string;
17
- /** Exact match only (no descendants). Defaults to false. */
18
- readonly exact?: boolean;
19
- /** Preserve component state when deactivated (React Activity). Defaults to false. */
20
- readonly keepAlive?: boolean;
21
- /** Fallback content to show while children are suspended. */
22
- readonly fallback?: ReactNode;
23
- /** Content to render when matched. */
24
- readonly children: ReactNode;
25
- }
26
- interface SelfProps {
27
- /**
28
- * Fallback content to show while children are suspended.
29
- *
30
- * Symmetric with `<RouteView.Match fallback>` — wraps children in
31
- * `<Suspense>` when defined.
32
- */
33
- readonly fallback?: ReactNode;
34
- /** Content to render when the active route name equals the parent RouteView's nodeName. */
35
- readonly children: ReactNode;
36
- }
37
- interface NotFoundProps {
38
- /** Content to render on UNKNOWN_ROUTE. */
39
- readonly children: ReactNode;
40
- }
41
- //#endregion
42
- //#region src/components/modern/RouteView/components.d.ts
43
- declare function Match(_props: MatchProps): null;
44
- declare namespace Match {
45
- var displayName: string;
46
- }
47
- declare function Self(_props: SelfProps): null;
48
- declare namespace Self {
49
- var displayName: string;
50
- }
51
- declare function NotFound(_props: NotFoundProps): null;
52
- declare namespace NotFound {
53
- var displayName: string;
54
- }
55
- //#endregion
56
- //#region src/components/modern/RouteView/RouteView.d.ts
57
- declare function RouteViewRoot({
58
- nodeName,
59
- children
60
- }: Readonly<RouteViewProps>): ReactElement | null;
61
- declare namespace RouteViewRoot {
62
- var displayName: string;
63
- }
64
- declare const RouteView: typeof RouteViewRoot & {
65
- Match: typeof Match;
66
- Self: typeof Self;
67
- NotFound: typeof NotFound;
68
- };
69
- //#endregion
70
- //#region src/hooks/useRouteExit.d.ts
71
- interface RouteExitContext {
72
- /** The route being left. */
73
- route: State;
74
- /** The route being navigated to. */
75
- nextRoute: State;
76
- /**
77
- * AbortSignal that fires when this navigation is superseded by a later
78
- * one (rapid clicks). Already filtered: when the handler runs,
79
- * `signal.aborted` is guaranteed to be `false`. Use
80
- * `signal.addEventListener("abort", cleanup, { once: true })` for
81
- * cleanup that must run on cancellation.
82
- */
83
- signal: AbortSignal;
84
- }
85
- interface UseRouteExitOptions {
86
- /**
87
- * Skip the handler when `route.name === nextRoute.name`
88
- * (sort/filter/query-only navigations on the same route). Default:
89
- * `true`.
90
- */
91
- skipSameRoute?: boolean;
92
- }
93
- type RouteExitHandler = (context: RouteExitContext) => void | Promise<void>;
94
- /**
95
- * Subscribe to the router's leave-window with the universal guards baked
96
- * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
97
- * boilerplate every time:
98
- *
99
- * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
100
- * when the handler would run (rapid navigation superseded a slower
101
- * one), the handler is skipped entirely. `signal.addEventListener(
102
- * "abort", ...)` does not fire retroactively, so without this guard
103
- * downstream cleanup would never trigger.
104
- * - **Same-route skip**: by default, `route.name === nextRoute.name`
105
- * short-circuits the handler — query-only navigations (sort, filter,
106
- * pagination) skip the work. Opt out with `skipSameRoute: false`.
107
- * - **Stable handler reference**: the handler can change identity on
108
- * every render without causing resubscription — internal ref keeps
109
- * the latest handler accessible to the long-lived subscription.
110
- *
111
- * Returns nothing — the subscription's lifecycle is bound to the
112
- * component's mount.
113
- *
114
- * If the handler returns a Promise, the router blocks on it. If the
115
- * Promise resolves, navigation proceeds. If it rejects, the router emits
116
- * `TRANSITION_CANCELLED` (existing core behavior, no change here).
117
- *
118
- * @example Animation
119
- * ```tsx
120
- * const ref = useRef<HTMLDivElement>(null);
121
- *
122
- * useRouteExit(async ({ signal }) => {
123
- * const el = ref.current;
124
- * if (!el) return;
125
- * el.classList.add("fade-out");
126
- * const cleanup = () => el.classList.remove("fade-out");
127
- * signal.addEventListener("abort", cleanup, { once: true });
128
- * try {
129
- * el.getBoundingClientRect(); // style flush
130
- * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
131
- * } finally {
132
- * cleanup();
133
- * }
134
- * });
135
- * ```
136
- *
137
- * @example Auto-save form draft
138
- * ```tsx
139
- * useRouteExit(async ({ signal }) => {
140
- * if (formState.dirty) await api.saveDraft(formState, { signal });
141
- * });
142
- * ```
143
- *
144
- * @example Cancel inflight requests
145
- * ```tsx
146
- * useRouteExit(() => {
147
- * inflightController.abort();
148
- * });
149
- * ```
150
- *
151
- * @example Library-coordinated exit (motion / framer-motion)
152
- * ```tsx
153
- * const exitResolverRef = useRef<(() => void) | null>(null);
154
- *
155
- * useRouteExit(({ signal }) => {
156
- * return new Promise<void>((resolve) => {
157
- * exitResolverRef.current = resolve;
158
- * signal.addEventListener("abort", () => resolve(), { once: true });
159
- * });
160
- * });
161
- *
162
- * const onExitComplete = () => exitResolverRef.current?.();
163
- * // pass onExitComplete to <AnimatePresence>
164
- * ```
165
- *
166
- * @example Reading rich transition metadata via `nextRoute.transition`
167
- * ```tsx
168
- * useRouteExit(({ route, nextRoute }) => {
169
- * // nextRoute.transition: TransitionMeta — preview of the upcoming nav
170
- * if (nextRoute.transition.segments.deactivated.includes("products")) {
171
- * // leaving the products subtree entirely — flush product-related caches
172
- * productCache.clear();
173
- * }
174
- * if (nextRoute.transition.redirected) {
175
- * // skip animation when navigation arrived via redirect
176
- * return;
177
- * }
178
- * });
179
- * ```
180
- */
181
- declare function useRouteExit(handler: RouteExitHandler, options?: UseRouteExitOptions): void;
182
- //#endregion
183
- //#region src/hooks/useRouteEnter.d.ts
184
- interface RouteEnterContext {
185
- /** The route that was just activated. */
186
- route: State;
187
- /** The route that was active immediately before this navigation. */
188
- previousRoute: State;
189
- }
190
- type RouteEnterHandler = (context: RouteEnterContext) => void;
191
- interface UseRouteEnterOptions {
192
- /**
193
- * Skip the handler when `route.name === previousRoute.name`
194
- * (sort/filter/query-only navigations on the same route). Default:
195
- * `true`. Symmetric with `useRouteExit`'s same-name option.
196
- */
197
- skipSameRoute?: boolean;
198
- }
199
- /**
200
- * Fire `handler` once when the component mounts as a result of a
201
- * navigation. Mirror of `useRouteExit` for the entry side.
202
- *
203
- * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:
204
- *
205
- * - **Skip-initial**: handler is skipped when there is no
206
- * `previousRoute` (i.e. first-load mount). Most consumers want to
207
- * fire side effects only on real navigations, not on hydration.
208
- * - **Same-route skip** (default): handler is skipped when
209
- * `route.name === previousRoute.name`. Sort/filter/query-only
210
- * navigations re-run the effect (because `route` reference changes
211
- * in `useRoute`'s snapshot), but they are not "entries" in the
212
- * animation / analytics sense — the component instance has stayed
213
- * mounted throughout. Opt out with `skipSameRoute: false` when
214
- * the handler legitimately needs to fire on every navigation
215
- * (e.g. analytics tracking each query-param flip).
216
- * - **StrictMode double-mount immunity**: in dev, React's StrictMode
217
- * runs every effect twice to surface bugs. Without a guard,
218
- * analytics fire twice, animations restart, focus jumps. The hook
219
- * tracks the last-handled `route` reference and short-circuits the
220
- * second pass.
221
- * - **Latest-handler ref**: the handler can change identity on every
222
- * render without re-running the effect — the registered wrapper
223
- * dispatches to whatever `handlerRef.current` points to.
224
- * - **Mount-time `route` / `previousRoute` snapshot**: the handler
225
- * receives the values that were live at the moment of mount, not
226
- * the latest ones (which may have moved on if the user navigated
227
- * again before the effect drained).
228
- *
229
- * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from
230
- * `@real-router/sources`, so by the time the new component's effect
231
- * runs, the snapshot is the post-commit one. This is the reason we can
232
- * read mount-time context from `useRoute()` instead of subscribing to
233
- * `router.subscribe` directly (which fires before React schedules a
234
- * re-render — the well-known race in distributed components).
235
- *
236
- * @example Direction-aware entry animation
237
- * ```tsx
238
- * useRouteEnter(({ route }) => {
239
- * const direction = route.context.browser?.direction;
240
- * ref.current?.classList.add(
241
- * direction === "back" ? "slide-from-left" : "slide-from-right",
242
- * );
243
- * });
244
- * ```
245
- *
246
- * @example Source-aware focus management
247
- * ```tsx
248
- * useRouteEnter(({ route }) => {
249
- * if (route.context.browser?.source === "navigate") {
250
- * headingRef.current?.focus();
251
- * }
252
- * });
253
- * ```
254
- *
255
- * @example Analytics page-enter event (skip-initial built-in)
256
- * ```tsx
257
- * useRouteEnter(({ route, previousRoute }) => {
258
- * analytics.track("page_enter", {
259
- * route: route.name,
260
- * from: previousRoute.name,
261
- * });
262
- * });
263
- * ```
264
- *
265
- * @example Reading rich transition metadata via `route.transition`
266
- * ```tsx
267
- * useRouteEnter(({ route }) => {
268
- * // route.transition: TransitionMeta — populated by core for every state
269
- * if (route.transition.redirected) {
270
- * showToast(`Redirected from ${route.transition.from}`);
271
- * }
272
- * if (route.transition.segments.activated.includes("products")) {
273
- * // products subtree just became active (could be products or
274
- * // products.detail). Useful for subtree-scoped side effects.
275
- * }
276
- * });
277
- * ```
278
- */
279
- declare function useRouteEnter(handler: RouteEnterHandler, options?: UseRouteEnterOptions): void;
280
- //#endregion
281
- export { Link, type LinkProps, type Navigator, type RouteEnterContext, type RouteEnterHandler, type RouteExitContext, type RouteExitHandler, RouteView, type MatchProps as RouteViewMatchProps, type NotFoundProps as RouteViewNotFoundProps, type RouteViewProps, type SelfProps as RouteViewSelfProps, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, type UseRouteEnterOptions, type UseRouteExitOptions, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
282
- //# sourceMappingURL=index.d.mts.map
7
+ export { Link, type LinkProps, type Navigator, type RouteEnterContext, type RouteEnterHandler, type RouteExitContext, type RouteExitHandler, RouteView, type MatchProps as RouteViewMatchProps, type NotFoundProps as RouteViewNotFoundProps, type RouteViewProps, type SelfProps as RouteViewSelfProps, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, type UseRouteEnterOptions, type UseRouteExitOptions, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
@@ -1,2 +1,2 @@
1
- import{a as e,g as t,h as n,i as r,n as i,o as a,r as o,t as s}from"./RouterProvider-CS2ZoONm.mjs";import{t as c}from"./Link-C7upxMc8.mjs";import{Activity as l,Children as u,Fragment as d,Suspense as f,isValidElement as p,useEffect as m,useLayoutEffect as h,useMemo as g,useRef as _}from"react";import{UNKNOWN_ROUTE as v}from"@real-router/core";import{startsWithSegment as y}from"@real-router/route-utils";import{Fragment as b,jsx as x}from"react/jsx-runtime";function S(e){return null}S.displayName=`RouteView.Match`;function C(e){return null}C.displayName=`RouteView.Self`;function w(e){return null}w.displayName=`RouteView.NotFound`;function T(e,t,n){return t===``?!1:n?e===t:y(e,t)}function E(e,t){for(let n of u.toArray(e))p(n)&&(n.type===S||n.type===C||n.type===w?t.push(n):E(n.props.children,t))}function D(e,t,n,r,i){let a=i===void 0?e:x(f,{fallback:i,children:e});return n?x(l,{mode:r,children:a},t):x(d,{children:a},t)}function O(e,t){return e.type===w?(t.notFoundChildren=e.props.children,!0):e.type===C?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function k(e,t,n,r,i){let{segment:a,exact:o=!1,keepAlive:s=!1,fallback:c}=e.props,l=n?`${n}.${a}`:a;return!i&&T(t,l,o)?(r.add(l),{rendered:D(e.props.children,l,s,`visible`,c),matched:!0}):s&&r.has(l)?{rendered:D(e.props.children,l,s,`hidden`,c),matched:!1}:{rendered:null,matched:!1}}function A(e,t,n,r){if(r.selfFound&&t===n){e.push(D(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===v&&r.notFoundChildren!==null&&e.push(x(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function j(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null},a=!1,o=[];for(let s of e){if(O(s,i))continue;let e=k(s,t,n,r,a);e.matched&&(a=!0),e.rendered!==null&&o.push(e.rendered)}return a||A(o,t,n,i),{rendered:o,activeMatchFound:a}}function M({nodeName:e,children:t}){let{route:r}=n(e),i=_(null);i.current??=new Set;let a=g(()=>{let e=[];return E(t,e),e},[t]);if(!r)return null;let{rendered:o}=j(a,r.name,e,i.current);return o.length>0?x(b,{children:o}):null}M.displayName=`RouteView`;const N=Object.assign(M,{Match:S,Self:C,NotFound:w});function P(e,n){let r=t(),i=_(e),a=n?.skipSameRoute??!0;h(()=>{i.current=e}),m(()=>r.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(a&&e.name===t.name)&&!n.aborted)return i.current({route:e,nextRoute:t,signal:n})}),[r,a])}function F(e,t){let{route:n,previousRoute:r}=o(),i=_(e),a=_(null),s=t?.skipSameRoute??!0;h(()=>{i.current=e}),m(()=>{n.transition.from&&(s&&n.transition.from===n.name||a.current===n||!r||(a.current=n,i.current({route:n,previousRoute:r})))},[n,r,s])}export{c as Link,N as RouteView,a as RouterErrorBoundary,s as RouterProvider,e as useNavigator,o as useRoute,F as useRouteEnter,P as useRouteExit,n as useRouteNode,r as useRouteUtils,t as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-Bta1jyl2.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o,t as s}from"./RouterProvider-a9y9bqji.mjs";import{t as c}from"./Link-BQol2GYb.mjs";import{Activity as l,Children as u,Fragment as d,Suspense as f,isValidElement as p,useEffect as m,useLayoutEffect as h,useMemo as g,useRef as _}from"react";import{UNKNOWN_ROUTE as v}from"@real-router/core";import{startsWithSegment as y}from"@real-router/route-utils";import{Fragment as b,jsx as x}from"react/jsx-runtime";function S(e){return null}S.displayName=`RouteView.Match`;function C(e){return null}C.displayName=`RouteView.Self`;function w(e){return null}w.displayName=`RouteView.NotFound`;function T(e,t,n){return t===``?!1:n?e===t:y(e,t)}function E(e,t){u.forEach(e,e=>{p(e)&&(e.type===S||e.type===C||e.type===w?t.push(e):E(e.props.children,t))})}function D(e,t,n,r,i){let a=i===void 0?e:x(f,{fallback:i,children:e});return n?x(l,{mode:r,children:a},t):x(d,{children:a},t)}function O(e,t){return e.type===w?(t.notFoundChildren=e.props.children,!0):e.type===C?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function k(e,t,n,r,i){let a=e.props,{segment:o,exact:s=!1,keepAlive:c=!1,fallback:l}=a,u=n?`${n}.${o}`:o;return!i&&T(t,u,s)?(r.add(u),{rendered:D(a.children,u,c,`visible`,l),matched:!0}):c&&r.has(u)?{rendered:D(a.children,u,c,`hidden`,l),matched:!1}:{rendered:null,matched:!1}}function A(e,t,n,r){if(r.selfFound&&t===n){e.push(D(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===v&&r.notFoundChildren!==null&&e.push(x(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function j(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null},a=!1,o=[];for(let s of e){if(O(s,i))continue;let e=k(s,t,n,r,a);e.matched&&(a=!0),e.rendered!==null&&o.push(e.rendered)}return a||A(o,t,n,i),{rendered:o,activeMatchFound:a}}function M({nodeName:e,children:t}){let{route:r}=n(e),i=_(null);i.current??=new Set;let a=g(()=>{let e=[];return E(t,e),e},[t]);if(!r)return null;let{rendered:o}=j(a,r.name,e,i.current);return o.length>0?x(b,{children:o}):null}M.displayName=`RouteView`;const N=Object.assign(M,{Match:S,Self:C,NotFound:w});function P(e,t){let n=a(),r=_(e),i=t?.skipSameRoute??!0;h(()=>{r.current=e}),m(()=>n.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(i&&e.name===t.name)&&!n.aborted)return r.current({route:e,nextRoute:t,signal:n})}),[n,i])}function F(t,n){let{route:r,previousRoute:i}=e(),a=_(t),o=_(null),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{r.transition.from&&(s&&r.transition.from===r.name||o.current===r||!i||(o.current=r,a.current({route:r,previousRoute:i})))},[r,i,s])}export{c as Link,N as RouteView,t as RouterErrorBoundary,s as RouterProvider,r as useNavigator,e as useRoute,F as useRouteEnter,P as useRouteExit,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n}\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // eslint-disable-next-line @eslint-react/no-children-to-array\n for (const child of Children.toArray(children)) {\n if (!isValidElement(child)) {\n continue;\n }\n\n if (\n child.type === Match ||\n child.type === Self ||\n child.type === NotFound\n ) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n }\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; matched: boolean } {\n const {\n segment,\n exact = false,\n keepAlive = false,\n fallback,\n } = child.props as MatchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n hasBeenActivated.add(fullSegmentName);\n\n return {\n rendered: renderSlotElement(\n (child.props as MatchProps).children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n matched: true,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n (child.props as MatchProps).children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n matched: false,\n };\n }\n\n return { rendered: null, matched: false };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n \"__route-view-self__\",\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key=\"__route-view-not-found__\">\n {slots.notFoundChildren}\n </Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n): { rendered: ReactElement[]; activeMatchFound: boolean } {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n };\n let activeMatchFound = false;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activeMatchFound,\n );\n\n if (result.matched) {\n activeMatchFound = true;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (!activeMatchFound) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound };\n}\n","import { useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n\n // Skip the Children.toArray + collectElements traversal when children\n // reference is unchanged. children only changes when the parent re-renders\n // with a new ReactNode, so this caches the steady-state.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n if (!route) {\n return null;\n }\n\n const { rendered } = buildRenderList(\n elements,\n route.name,\n nodeName,\n // eslint-disable-next-line @eslint-react/refs -- stable Set ref read for keepAlive tracking (never reassigned)\n hasBeenActivatedRef.current,\n );\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not testable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start */\n if (lastHandledRouteRef.current === route || !previousRoute) {\n return;\n }\n /* v8 ignore stop */\n\n lastHandledRouteRef.current = route;\n handlerRef.current({ route, previousRoute });\n }, [route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n}\n\n// Fixed keys used by appendFallback to distinguish the Self / NotFound\n// render slots from user-supplied <Match> children. Match render slots key\n// off `fullSegmentName` instead — these two are the only synthetic keys.\nconst SELF_KEY = \"__route-view-self__\";\nconst NOT_FOUND_KEY = \"__route-view-not-found__\";\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // Recurses into Fragment-like wrappers (anything that isn't Match / Self /\n // NotFound) to flatten the slot tree. No explicit depth guard: typical\n // RouteView shape is `<RouteView><Match/>...<NotFound/></RouteView>` —\n // depth ≤ 3 in real apps. A pathological hand-written tree of N Fragments\n // recurses N times; the call stack, not this function, is the bound.\n //\n // `Children.forEach` iterates without `Children.toArray`'s array allocation\n // and per-child clone-with-synthetic-key step. We don't read child.key here\n // (Match/Self/NotFound carry their own segment-derived keys further down),\n // so the cheaper iterator is functionally equivalent.\n // eslint-disable-next-line @eslint-react/no-children-for-each -- intentional: collectElements is a render-hot pipeline; toArray's array+key clone is wasteful here\n Children.forEach(children, (child) => {\n if (!isValidElement(child)) {\n return;\n }\n\n if (\n child.type === Match ||\n child.type === Self ||\n child.type === NotFound\n ) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n });\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; matched: boolean } {\n const matchProps = child.props as MatchProps;\n const { segment, exact = false, keepAlive = false, fallback } = matchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n hasBeenActivated.add(fullSegmentName);\n\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n matched: true,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n matched: false,\n };\n }\n\n return { rendered: null, matched: false };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n SELF_KEY,\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key={NOT_FOUND_KEY}>{slots.notFoundChildren}</Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n): { rendered: ReactElement[]; activeMatchFound: boolean } {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n };\n let activeMatchFound = false;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activeMatchFound,\n );\n\n if (result.matched) {\n activeMatchFound = true;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (!activeMatchFound) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound };\n}\n","import { useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n\n // Skip the Children.forEach + collectElements traversal when the children\n // reference is unchanged. The common SPA case is a stable JSX tree across\n // re-renders, so the cache hits on every render except the first.\n //\n // Streaming SSR caveat: with `renderToReadableStream`, React may invoke\n // RouteView multiple times across chunks with a fresh `children` reference\n // each time. The useMemo misses on each new render and the traversal runs\n // again — this is the expected SSR cost; the alternative would be build-\n // time codegen of the static route tree, which is out of scope here.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n if (!route) {\n return null;\n }\n\n const { rendered } = buildRenderList(\n elements,\n route.name,\n nodeName,\n // eslint-disable-next-line @eslint-react/refs -- stable Set ref read for keepAlive tracking (never reassigned)\n hasBeenActivatedRef.current,\n );\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not testable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start */\n if (lastHandledRouteRef.current === route || !previousRoute) {\n return;\n }\n /* v8 ignore stop */\n\n lastHandledRouteRef.current = route;\n handlerRef.current({ route, previousRoute });\n }, [route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"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"}
@@ -0,0 +1,5 @@
1
+ import { a as RouteExitContext, d as NotFoundProps, f as RouteViewProps, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-CxjYofFa.mjs";
2
+ import { n as RouterErrorBoundaryProps, r as LinkProps } from "./RouterErrorBoundary-C-MH_yrP.mjs";
3
+ import { Navigator } from "@real-router/core";
4
+ import { RouterTransitionSnapshot } from "@real-router/sources";
5
+ export { type LinkProps, type Navigator, type RouteEnterContext, type RouteEnterHandler, type RouteExitContext, type RouteExitHandler, type MatchProps as RouteViewMatchProps, type NotFoundProps as RouteViewNotFoundProps, type RouteViewProps, type SelfProps as RouteViewSelfProps, type RouterErrorBoundaryProps, type RouterTransitionSnapshot, type UseRouteEnterOptions, type UseRouteExitOptions };
File without changes
@@ -1,4 +1,5 @@
1
- import { a as useNavigator, c as RouterErrorBoundaryProps, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, s as RouterErrorBoundary, t as useRouterTransition } from "./useRouterTransition-B65Wvngj.mjs";
1
+ import { n as RouterErrorBoundaryProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-C-MH_yrP.mjs";
2
+ import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-CI1P95ZQ.mjs";
2
3
  import { FC, ReactNode } from "react";
3
4
  import { NavigationOptions, Navigator, Params, Router } from "@real-router/core";
4
5
  import { RouterTransitionSnapshot } from "@real-router/sources";
@@ -1 +1 @@
1
- {"version":3,"file":"ink.d.mts","names":[],"sources":["../../src/ink-types.ts","../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"mappings":";;;;;;UAGiB,YAAA,WAAuB,MAAA,GAAS,MAAA;EAC/C,SAAA;EACA,WAAA,GAAc,CAAA;EACd,YAAA,GAAe,iBAAA;EACf,YAAA;EACA,iBAAA;EACA,QAAA,GAAW,SAAA;EACX,KAAA;EACA,WAAA;EACA,UAAA;EACA,OAAA;EACA,aAAA;EACA,YAAA;EACA,EAAA;EACA,SAAA;EACA,QAAA;AAAA;AAAA,UAGe,sBAAA;EACf,MAAA,EAAQ,MAAA;EACR,QAAA,GAAW,SAAA;AAAA;;;cCmFA,OAAA,EAAS,EAAA,CAAG,YAAA;;;cCrGZ,iBAAA,EAAmB,EAAA,CAAG,sBAAA"}
1
+ {"version":3,"file":"ink.d.mts","names":[],"sources":["../../src/ink-types.ts","../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"mappings":";;;;;;;UAGiB,YAAA,WAAuB,MAAA,GAAS,MAAA;EAC/C,SAAA;EACA,WAAA,GAAc,CAAA;EACd,YAAA,GAAe,iBAAA;EACf,YAAA;EACA,iBAAA;EACA,QAAA,GAAW,SAAA;EACX,KAAA;EACA,WAAA;EACA,UAAA;EACA,OAAA;EACA,aAAA;EACA,YAAA;EACA,EAAA;EACA,SAAA;EACA,QAAA;AAAA;AAAA,UAGe,sBAAA;EACf,MAAA,EAAQ,MAAA;EACR,QAAA,GAAW,SAAA;AAAA;;;cCyGA,OAAA,EAAS,EAAA,CAAG,YAAA;;;cC3HZ,iBAAA,EAAmB,EAAA,CAAG,sBAAA"}
package/dist/esm/ink.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{a as e,d as t,g as n,h as r,i,m as a,n as o,o as s,p as c,r as l,s as u,t as d}from"./RouterProvider-CS2ZoONm.mjs";import{memo as f,useCallback as p}from"react";import{jsx as m}from"react/jsx-runtime";import{Text as h,useFocus as g,useInput as _}from"ink";function v(e,n){return e.routeName===n.routeName&&e.activeStrict===n.activeStrict&&e.ignoreQueryParams===n.ignoreQueryParams&&e.color===n.color&&e.activeColor===n.activeColor&&e.focusColor===n.focusColor&&e.inverse===n.inverse&&e.activeInverse===n.activeInverse&&e.focusInverse===n.focusInverse&&e.id===n.id&&e.autoFocus===n.autoFocus&&e.onSelect===n.onSelect&&e.children===n.children&&t(e.routeParams,n.routeParams)&&t(e.routeOptions,n.routeOptions)}const y=f(({routeName:e,routeParams:t=a,routeOptions:r=c,activeStrict:i=!1,ignoreQueryParams:o=!0,color:s,activeColor:l,focusColor:d,inverse:f,activeInverse:v,focusInverse:y,id:b,autoFocus:x,onSelect:S,children:C})=>{let w=n(),{isFocused:T}=g({...b!==void 0&&{id:b},...x!==void 0&&{autoFocus:x}}),E=u(e,t,i,o),D=p(()=>{S?.(),w.navigate(e,t,r).catch(()=>{})},[S,w,e,t,r]);_((e,t)=>{t.return&&D()},{isActive:T});let O=s;T?O=d??l??s:E&&(O=l??s);let k=f;T?k=y??v??f:E&&(k=v??f);let A={};return O!==void 0&&(A.color=O),k!==void 0&&(A.inverse=k),m(h,{...A,children:C})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>m(d,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,s as RouterErrorBoundary,e as useNavigator,l as useRoute,r as useRouteNode,i as useRouteUtils,n as useRouter,o as useRouterTransition};
1
+ import{n as e,r as t,t as n}from"./useRoute-Bta1jyl2.mjs";import{a as r,f as i,i as a,n as o,o as s,p as c,r as l,t as u,u as d}from"./RouterProvider-a9y9bqji.mjs";import{memo as f}from"react";import{jsx as p}from"react/jsx-runtime";import{Text as m,useFocus as h,useInput as g}from"ink";function _(e,t,n,r,i){return e?n??r??i:t?r??i:i}function v(e,t){return e.routeName===t.routeName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.color===t.color&&e.activeColor===t.activeColor&&e.focusColor===t.focusColor&&e.inverse===t.inverse&&e.activeInverse===t.activeInverse&&e.focusInverse===t.focusInverse&&e.id===t.id&&e.autoFocus===t.autoFocus&&e.onSelect===t.onSelect&&e.children===t.children&&d(e.routeParams,t.routeParams)&&d(e.routeOptions,t.routeOptions)}const y=f(({routeName:n,routeParams:r=t,routeOptions:i=e,activeStrict:a=!1,ignoreQueryParams:o=!0,color:l,activeColor:u,focusColor:d,inverse:f,activeInverse:v,focusInverse:y,id:b,autoFocus:x,onSelect:S,children:C})=>{let w=c(),{isFocused:T}=h({...b!==void 0&&{id:b},...x!==void 0&&{autoFocus:x}}),E=s(n,r,a,o);g((e,t)=>{t.return&&(S?.(),w.navigate(n,r,i).catch(()=>{}))},{isActive:T});let D=_(T,E,d,u,l),O=_(T,E,y,v,f),k={};return D!==void 0&&(k.color=D),O!==void 0&&(k.inverse=O),p(m,{...k,children:C})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>p(u,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,r as RouterErrorBoundary,a as useNavigator,n as useRoute,i as useRouteNode,l as useRouteUtils,c as useRouter,o as useRouterTransition};
2
2
  //# sourceMappingURL=ink.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ink.mjs","names":[],"sources":["../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"sourcesContent":["import { Text, useFocus, useInput } from \"ink\";\nimport { memo, useCallback } from \"react\";\n\nimport { EMPTY_OPTIONS, EMPTY_PARAMS } from \"../constants\";\nimport { shallowEqual } from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { InkLinkProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\nfunction areInkLinkPropsEqual(\n prev: Readonly<InkLinkProps>,\n next: Readonly<InkLinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.color === next.color &&\n prev.activeColor === next.activeColor &&\n prev.focusColor === next.focusColor &&\n prev.inverse === next.inverse &&\n prev.activeInverse === next.activeInverse &&\n prev.focusInverse === next.focusInverse &&\n prev.id === next.id &&\n prev.autoFocus === next.autoFocus &&\n prev.onSelect === next.onSelect &&\n prev.children === next.children &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst InkLinkImpl: FC<InkLinkProps> = ({\n routeName,\n routeParams = EMPTY_PARAMS,\n routeOptions = EMPTY_OPTIONS,\n activeStrict = false,\n ignoreQueryParams = true,\n color,\n activeColor,\n focusColor,\n inverse,\n activeInverse,\n focusInverse,\n id,\n autoFocus,\n onSelect,\n children,\n}) => {\n const router = useRouter();\n const { isFocused } = useFocus({\n ...(id !== undefined && { id }),\n ...(autoFocus !== undefined && { autoFocus }),\n });\n const isRouteActive = useIsActiveRoute(\n routeName,\n routeParams,\n activeStrict,\n ignoreQueryParams,\n );\n\n const activate = useCallback(() => {\n onSelect?.();\n router.navigate(routeName, routeParams, routeOptions).catch(() => {});\n }, [onSelect, router, routeName, routeParams, routeOptions]);\n\n useInput(\n (_input, key) => {\n if (key.return) {\n activate();\n }\n },\n { isActive: isFocused },\n );\n\n let finalColor = color;\n\n if (isFocused) {\n finalColor = focusColor ?? activeColor ?? color;\n } else if (isRouteActive) {\n finalColor = activeColor ?? color;\n }\n\n let finalInverse = inverse;\n\n if (isFocused) {\n finalInverse = focusInverse ?? activeInverse ?? inverse;\n } else if (isRouteActive) {\n finalInverse = activeInverse ?? inverse;\n }\n\n const textProps: { color?: string; inverse?: boolean } = {};\n\n if (finalColor !== undefined) {\n textProps.color = finalColor;\n }\n\n if (finalInverse !== undefined) {\n textProps.inverse = finalInverse;\n }\n\n return <Text {...textProps}>{children}</Text>;\n};\n\nexport const InkLink: FC<InkLinkProps> = memo(\n InkLinkImpl,\n areInkLinkPropsEqual,\n);\n\nInkLink.displayName = \"InkLink\";\n","import { RouterProvider } from \"../RouterProvider\";\n\nimport type { InkRouterProviderProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\nexport const InkRouterProvider: FC<InkRouterProviderProps> = ({\n router,\n children,\n}) => <RouterProvider router={router}>{children}</RouterProvider>;\n"],"mappings":"uQAWA,SAAS,EACP,EACA,EACS,CACT,OACE,EAAK,YAAc,EAAK,WACxB,EAAK,eAAiB,EAAK,cAC3B,EAAK,oBAAsB,EAAK,mBAChC,EAAK,QAAU,EAAK,OACpB,EAAK,cAAgB,EAAK,aAC1B,EAAK,aAAe,EAAK,YACzB,EAAK,UAAY,EAAK,SACtB,EAAK,gBAAkB,EAAK,eAC5B,EAAK,eAAiB,EAAK,cAC3B,EAAK,KAAO,EAAK,IACjB,EAAK,YAAc,EAAK,WACxB,EAAK,WAAa,EAAK,UACvB,EAAK,WAAa,EAAK,UACvB,EAAa,EAAK,YAAa,EAAK,YAAY,EAChD,EAAa,EAAK,aAAc,EAAK,aAAa,CA4EtD,MAAa,EAA4B,GAxEF,CACrC,YACA,cAAc,EACd,eAAe,EACf,eAAe,GACf,oBAAoB,GACpB,QACA,cACA,aACA,UACA,gBACA,eACA,KACA,YACA,WACA,cACI,CACJ,IAAM,EAAS,GAAW,CACpB,CAAE,aAAc,EAAS,CAC7B,GAAI,IAAO,IAAA,IAAa,CAAE,KAAI,CAC9B,GAAI,IAAc,IAAA,IAAa,CAAE,YAAW,CAC7C,CAAC,CACI,EAAgB,EACpB,EACA,EACA,EACA,EACD,CAEK,EAAW,MAAkB,CACjC,KAAY,CACZ,EAAO,SAAS,EAAW,EAAa,EAAa,CAAC,UAAY,GAAG,EACpE,CAAC,EAAU,EAAQ,EAAW,EAAa,EAAa,CAAC,CAE5D,GACG,EAAQ,IAAQ,CACX,EAAI,QACN,GAAU,EAGd,CAAE,SAAU,EAAW,CACxB,CAED,IAAI,EAAa,EAEb,EACF,EAAa,GAAc,GAAe,EACjC,IACT,EAAa,GAAe,GAG9B,IAAI,EAAe,EAEf,EACF,EAAe,GAAgB,GAAiB,EACvC,IACT,EAAe,GAAiB,GAGlC,IAAM,EAAmD,EAAE,CAU3D,OARI,IAAe,IAAA,KACjB,EAAU,MAAQ,GAGhB,IAAiB,IAAA,KACnB,EAAU,QAAU,GAGf,EAAC,EAAD,CAAM,GAAI,EAAY,WAAgB,CAAA,EAK7C,EACD,CAED,EAAQ,YAAc,UC1GtB,MAAa,GAAiD,CAC5D,SACA,cACI,EAAC,EAAD,CAAwB,SAAS,WAA0B,CAAA"}
1
+ {"version":3,"file":"ink.mjs","names":[],"sources":["../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"sourcesContent":["import { Text, useFocus, useInput } from \"ink\";\nimport { memo } from \"react\";\n\nimport { EMPTY_OPTIONS, EMPTY_PARAMS } from \"../constants\";\nimport { shallowEqual } from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { InkLinkProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\n/**\n * Pick the most specific value across focus / active / base priority.\n * Focus wins over active; active wins over base. Each layer falls through\n * to the next when its value is undefined, matching the original explicit\n * if/else cascade for both `color` and `inverse`.\n */\nfunction pickPriority<T>(\n isFocused: boolean,\n isRouteActive: boolean,\n focusValue: T | undefined,\n activeValue: T | undefined,\n baseValue: T | undefined,\n): T | undefined {\n if (isFocused) {\n return focusValue ?? activeValue ?? baseValue;\n }\n\n if (isRouteActive) {\n return activeValue ?? baseValue;\n }\n\n return baseValue;\n}\n\nfunction areInkLinkPropsEqual(\n prev: Readonly<InkLinkProps>,\n next: Readonly<InkLinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.color === next.color &&\n prev.activeColor === next.activeColor &&\n prev.focusColor === next.focusColor &&\n prev.inverse === next.inverse &&\n prev.activeInverse === next.activeInverse &&\n prev.focusInverse === next.focusInverse &&\n prev.id === next.id &&\n prev.autoFocus === next.autoFocus &&\n prev.onSelect === next.onSelect &&\n prev.children === next.children &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst InkLinkImpl: FC<InkLinkProps> = ({\n routeName,\n routeParams = EMPTY_PARAMS,\n routeOptions = EMPTY_OPTIONS,\n activeStrict = false,\n ignoreQueryParams = true,\n color,\n activeColor,\n focusColor,\n inverse,\n activeInverse,\n focusInverse,\n id,\n autoFocus,\n onSelect,\n children,\n}) => {\n const router = useRouter();\n const { isFocused } = useFocus({\n ...(id !== undefined && { id }),\n ...(autoFocus !== undefined && { autoFocus }),\n });\n const isRouteActive = useIsActiveRoute(\n routeName,\n routeParams,\n activeStrict,\n ignoreQueryParams,\n );\n\n // No useCallback: `useInput` consumes the handler via its own internal\n // ref; a stable identity provides no cache-bail-out benefit here. Same\n // reasoning as Link's handleClick.\n useInput(\n (_input, key) => {\n if (key.return) {\n onSelect?.();\n router.navigate(routeName, routeParams, routeOptions).catch(() => {});\n }\n },\n { isActive: isFocused },\n );\n\n const finalColor = pickPriority(\n isFocused,\n isRouteActive,\n focusColor,\n activeColor,\n color,\n );\n const finalInverse = pickPriority(\n isFocused,\n isRouteActive,\n focusInverse,\n activeInverse,\n inverse,\n );\n\n const textProps: { color?: string; inverse?: boolean } = {};\n\n if (finalColor !== undefined) {\n textProps.color = finalColor;\n }\n\n if (finalInverse !== undefined) {\n textProps.inverse = finalInverse;\n }\n\n return <Text {...textProps}>{children}</Text>;\n};\n\nexport const InkLink: FC<InkLinkProps> = memo(\n InkLinkImpl,\n areInkLinkPropsEqual,\n);\n\nInkLink.displayName = \"InkLink\";\n","import { RouterProvider } from \"../RouterProvider\";\n\nimport type { InkRouterProviderProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\nexport const InkRouterProvider: FC<InkRouterProviderProps> = ({\n router,\n children,\n}) => <RouterProvider router={router}>{children}</RouterProvider>;\n"],"mappings":"gSAiBA,SAAS,EACP,EACA,EACA,EACA,EACA,EACe,CASf,OARI,EACK,GAAc,GAAe,EAGlC,EACK,GAAe,EAGjB,EAGT,SAAS,EACP,EACA,EACS,CACT,OACE,EAAK,YAAc,EAAK,WACxB,EAAK,eAAiB,EAAK,cAC3B,EAAK,oBAAsB,EAAK,mBAChC,EAAK,QAAU,EAAK,OACpB,EAAK,cAAgB,EAAK,aAC1B,EAAK,aAAe,EAAK,YACzB,EAAK,UAAY,EAAK,SACtB,EAAK,gBAAkB,EAAK,eAC5B,EAAK,eAAiB,EAAK,cAC3B,EAAK,KAAO,EAAK,IACjB,EAAK,YAAc,EAAK,WACxB,EAAK,WAAa,EAAK,UACvB,EAAK,WAAa,EAAK,UACvB,EAAa,EAAK,YAAa,EAAK,YAAY,EAChD,EAAa,EAAK,aAAc,EAAK,aAAa,CA0EtD,MAAa,EAA4B,GAtEF,CACrC,YACA,cAAc,EACd,eAAe,EACf,eAAe,GACf,oBAAoB,GACpB,QACA,cACA,aACA,UACA,gBACA,eACA,KACA,YACA,WACA,cACI,CACJ,IAAM,EAAS,GAAW,CACpB,CAAE,aAAc,EAAS,CAC7B,GAAI,IAAO,IAAA,IAAa,CAAE,KAAI,CAC9B,GAAI,IAAc,IAAA,IAAa,CAAE,YAAW,CAC7C,CAAC,CACI,EAAgB,EACpB,EACA,EACA,EACA,EACD,CAKD,GACG,EAAQ,IAAQ,CACX,EAAI,SACN,KAAY,CACZ,EAAO,SAAS,EAAW,EAAa,EAAa,CAAC,UAAY,GAAG,GAGzE,CAAE,SAAU,EAAW,CACxB,CAED,IAAM,EAAa,EACjB,EACA,EACA,EACA,EACA,EACD,CACK,EAAe,EACnB,EACA,EACA,EACA,EACA,EACD,CAEK,EAAmD,EAAE,CAU3D,OARI,IAAe,IAAA,KACjB,EAAU,MAAQ,GAGhB,IAAiB,IAAA,KACnB,EAAU,QAAU,GAGf,EAAC,EAAD,CAAM,GAAI,EAAY,WAAgB,CAAA,EAK7C,EACD,CAED,EAAQ,YAAc,UChItB,MAAa,GAAiD,CAC5D,SACA,cACI,EAAC,EAAD,CAAwB,SAAS,WAA0B,CAAA"}
@@ -1,5 +1,6 @@
1
- import { a as useNavigator, c as RouterErrorBoundaryProps, i as useRouteUtils, l as LinkProps, n as useRouteNode, o as useRouter, r as useRoute, s as RouterErrorBoundary, t as useRouterTransition } from "./useRouterTransition-B65Wvngj.mjs";
2
- import { n as Link, t as RouterProvider } from "./RouterProvider-Dr3X_vbc.mjs";
1
+ import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-C-MH_yrP.mjs";
2
+ import { n as Link, t as RouterProvider } from "./RouterProvider-D_ZlPVAC.mjs";
3
+ import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-CI1P95ZQ.mjs";
3
4
  import { Navigator } from "@real-router/core";
4
5
  import { RouterTransitionSnapshot } from "@real-router/sources";
5
6
  export { Link, type LinkProps, type Navigator, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, useNavigator, useRoute, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
@@ -1 +1 @@
1
- import{a as e,g as t,h as n,i as r,n as i,o as a,r as o,t as s}from"./RouterProvider-CS2ZoONm.mjs";import{t as c}from"./Link-C7upxMc8.mjs";export{c as Link,a as RouterErrorBoundary,s as RouterProvider,e as useNavigator,o as useRoute,n as useRouteNode,r as useRouteUtils,t as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-Bta1jyl2.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o,t as s}from"./RouterProvider-a9y9bqji.mjs";import{t as c}from"./Link-BQol2GYb.mjs";export{c as Link,t as RouterErrorBoundary,s as RouterProvider,r as useNavigator,e as useRoute,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
@@ -0,0 +1,3 @@
1
+ import { a as HttpStatusCode, c as StreamedProps, d as ClientOnly, f as ClientOnlyProps, i as createHttpStatusSink, l as ServerOnly, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, s as Streamed, t as HttpStatusProvider, u as ServerOnlyProps } from "./HttpStatusProvider-Cy9GSANm.mjs";
2
+ import { t as useDeferred } from "./useDeferred-B5Qy7ttQ.mjs";
3
+ export { ClientOnly, type ClientOnlyProps, HttpStatusCode, type HttpStatusCodeProps, HttpStatusProvider, type HttpStatusProviderProps, type HttpStatusSink, ServerOnly, type ServerOnlyProps, Streamed, type StreamedProps, createHttpStatusSink, useDeferred };
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./createHttpStatusSink-BXWVamHE.mjs";export{a as ClientOnly,n as HttpStatusCode,i as HttpStatusProvider,r as ServerOnly,t as Streamed,o as createHttpStatusSink,e as useDeferred};
@@ -0,0 +1,4 @@
1
+ import { a as HttpStatusCode, c as StreamedProps, d as ClientOnly, f as ClientOnlyProps, i as createHttpStatusSink, l as ServerOnly, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, s as Streamed, t as HttpStatusProvider, u as ServerOnlyProps } from "./HttpStatusProvider-Cy9GSANm.mjs";
2
+ import { t as useDeferred } from "./useDeferred-B5Qy7ttQ.mjs";
3
+ import { n as AwaitProps, t as Await } from "./Await-qSmJ-ZuN.mjs";
4
+ export { Await, type AwaitProps, ClientOnly, type ClientOnlyProps, HttpStatusCode, type HttpStatusCodeProps, HttpStatusProvider, type HttpStatusProviderProps, type HttpStatusSink, ServerOnly, type ServerOnlyProps, Streamed, type StreamedProps, createHttpStatusSink, useDeferred };
@@ -0,0 +1,2 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./createHttpStatusSink-BXWVamHE.mjs";import{use as s}from"react";function c({name:t,children:n}){return n(s(e(t)))}export{c as Await,a as ClientOnly,n as HttpStatusCode,i as HttpStatusProvider,r as ServerOnly,t as Streamed,o as createHttpStatusSink,e as useDeferred};
2
+ //# sourceMappingURL=ssr.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr.mjs","names":[],"sources":["../../src/components/Await.tsx"],"sourcesContent":["import { use } from \"react\";\n\nimport { useDeferred } from \"../hooks/useDeferred\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface AwaitProps<T> {\n /** Deferred key declared in the loader's `defer({ deferred: { <name>: ... } })`. */\n readonly name: string;\n /** Render the resolved value. Suspends while pending; throws inside the\n * nearest Error Boundary on rejection. */\n readonly children: (value: T) => ReactNode;\n}\n\n/**\n * Ergonomic wrapper around `useDeferred(name)` + React 19's `use(promise)`.\n *\n * ```tsx\n * <Suspense fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Suspense>\n * ```\n *\n * Equivalent to:\n *\n * ```tsx\n * function Inner() {\n * const reviews = use(useDeferred<Review[]>(\"reviews\"));\n * return <ReviewList items={reviews} />;\n * }\n * ```\n *\n * Pick `<Await>` for cross-adapter consistency with the SvelteKit\n * `{#await}` / Solid `<Await/>` shape; pick the inline `use(useDeferred(...))`\n * form if you prefer one fewer abstraction.\n */\nexport function Await<T = unknown>({\n name,\n children,\n}: AwaitProps<T>): ReactNode {\n const value = use(useDeferred<T>(name));\n\n return children(value);\n}\n"],"mappings":"yHAsCA,SAAgB,EAAmB,CACjC,OACA,YAC2B,CAG3B,OAAO,EAFO,EAAI,EAAe,EAAK,CAEjB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { c as StreamedProps, f as ClientOnlyProps, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, u as ServerOnlyProps } from "./HttpStatusProvider-Cy9GSANm.mjs";
2
+ import { n as AwaitProps } from "./Await-qSmJ-ZuN.mjs";
3
+ export { type AwaitProps, type ClientOnlyProps, type HttpStatusCodeProps, type HttpStatusProviderProps, type HttpStatusSink, type ServerOnlyProps, type StreamedProps };
File without changes
@@ -0,0 +1,24 @@
1
+ //#region src/hooks/useDeferred.d.ts
2
+ /**
3
+ * Read a deferred promise published by `defer({ deferred: { <key>: Promise } })`
4
+ * inside an SSR data loader.
5
+ *
6
+ * - **Server render**: returns the actual loader-returned promise. Combine
7
+ * with `<Suspense>` + `use(promise)` for native streaming via React 19's
8
+ * `renderToReadableStream`.
9
+ * - **Post-hydration**: returns a registry-backed promise; the inline
10
+ * `<script>__rrDefer__("key", json)</script>` tags emitted by the server
11
+ * stream resolve it. `use()` returns synchronously once the registry
12
+ * settles.
13
+ * - **Unknown key**: returns a never-resolving promise — Suspense boundary
14
+ * stays in fallback. This surfaces consumer/loader key drift as a visible
15
+ * loading state instead of a silent runtime error.
16
+ *
17
+ * The hook subscribes to `RouteContext`, so it re-runs on every navigation.
18
+ * Promise reference identity is stable across renders within the same
19
+ * navigation — `use()` will not re-suspend on rerenders.
20
+ */
21
+ declare function useDeferred<T = unknown>(key: string): Promise<T>;
22
+ //#endregion
23
+ export { useDeferred as t };
24
+ //# sourceMappingURL=useDeferred-B5Qy7ttQ.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDeferred-B5Qy7ttQ.d.mts","names":[],"sources":["../../src/hooks/useDeferred.tsx"],"mappings":";;AA0BA;;;;;;;;;;;;;;;;;;iBAAgB,WAAA,aAAA,CAAyB,GAAA,WAAc,OAAA,CAAQ,CAAA"}
@@ -0,0 +1,2 @@
1
+ import{createContext as e,useContext as t}from"react";const n=e(null),r=e(null),i=e(null),a=Object.freeze({}),o=Object.freeze({}),s=new Promise(()=>{}),c=()=>{let e=t(n);if(!e)throw Error(`useRoute must be used within a RouterProvider`);if(!e.route)throw Error(`useRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?`);return e};export{i as a,s as i,o as n,n as o,a as r,r as s,c as t};
2
+ //# sourceMappingURL=useRoute-Bta1jyl2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRoute-Bta1jyl2.mjs","names":[],"sources":["../../src/context.ts","../../src/constants.ts","../../src/hooks/useRoute.tsx"],"sourcesContent":["import { createContext } from \"react\";\n\nimport type { RouteContext as RouteContextType } from \"./types\";\nimport type { Router, Navigator } from \"@real-router/core\";\n\n// All three contexts use the `<T | null>` shape with a `null` default. Hooks\n// (useRouter / useRoute / useNavigator) treat a `null` read as\n// \"RouterProvider missing\" and throw — this surfaces wiring mistakes loudly\n// instead of letting consumers chase an undefined router instance.\nexport const RouteContext = createContext<RouteContextType | null>(null);\n\nexport const RouterContext = createContext<Router | null>(null);\n\nexport const NavigatorContext = createContext<Navigator | null>(null);\n","export const EMPTY_PARAMS = Object.freeze({});\n\nexport const EMPTY_OPTIONS = Object.freeze({});\n\n// Singleton forever-pending promise — module-scope so `useDeferred(unknownKey)`\n// returns a stable reference across calls (Suspense boundary doesn't retry).\nexport const NEVER_PROMISE = new Promise<never>(() => {\n // Intentionally never resolves — surfaces a forever-pending Suspense boundary\n // when a key is requested that the loader never declared.\n});\n","import { useContext } from \"react\";\n\nimport { RouteContext } from \"../context\";\n\nimport type { RouteContext as RouteContextType } from \"../types\";\nimport type { Params, State } from \"@real-router/core\";\n\n/**\n * Return shape of `useRoute<P>()` — the context with `route` narrowed to\n * `State<P>` (non-nullable). Promoting the intersection to a named alias\n * keeps the function signature and the cast site in sync.\n */\ntype RouteHookResult<P extends Params = Params> = Omit<\n RouteContextType<P>,\n \"route\"\n> & { route: State<P> };\n\nexport const useRoute = <P extends Params = Params>(): RouteHookResult<P> => {\n const routeContext = useContext(RouteContext);\n\n if (!routeContext) {\n throw new Error(\"useRoute must be used within a RouterProvider\");\n }\n\n if (!routeContext.route) {\n throw new Error(\n \"useRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?\",\n );\n }\n\n return routeContext as RouteHookResult<P>;\n};\n"],"mappings":"sDASA,MAAa,EAAe,EAAuC,KAAK,CAE3D,EAAgB,EAA6B,KAAK,CAElD,EAAmB,EAAgC,KAAK,CCbxD,EAAe,OAAO,OAAO,EAAE,CAAC,CAEhC,EAAgB,OAAO,OAAO,EAAE,CAAC,CAIjC,EAAgB,IAAI,YAAqB,GAGpD,CCQW,MAAgE,CAC3E,IAAM,EAAe,EAAW,EAAa,CAE7C,GAAI,CAAC,EACH,MAAU,MAAM,gDAAgD,CAGlE,GAAI,CAAC,EAAa,MAChB,MAAU,MACR,oIACD,CAGH,OAAO"}