@real-router/react 0.36.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -1
- package/dist/cjs/{RouterProvider-iwUCDuSG.d.ts → RouterProvider-Cwy46Oyd.d.ts} +29 -2
- package/dist/cjs/RouterProvider-Cwy46Oyd.d.ts.map +1 -0
- package/dist/cjs/index.d.ts +2 -2
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/legacy.d.ts +1 -1
- package/dist/esm/{RouterProvider-CVcC8wop.d.mts → RouterProvider-BixslYdB.d.mts} +29 -2
- package/dist/esm/RouterProvider-BixslYdB.d.mts.map +1 -0
- package/dist/esm/index.d.mts +2 -2
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/legacy.d.mts +1 -1
- package/package.json +5 -5
- package/dist/cjs/RouterProvider-iwUCDuSG.d.ts.map +0 -1
- package/dist/esm/RouterProvider-CVcC8wop.d.mts.map +0 -1
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ npm install @real-router/react @real-router/core @real-router/browser-plugin
|
|
|
26
26
|
| `@real-router/react/ink` | 19.2+ | Terminal (Ink 7+) | Hooks, `InkRouterProvider`, `InkLink` — no `Link`, no `RouteView`, no `announceNavigation`. **ESM-only** (`import` only): ink itself is ESM-only with top-level await, so a `require`-able build of this entry cannot exist |
|
|
27
27
|
| `@real-router/react` (`react-server` condition) | 19+ | RSC bundler | **Type-only** re-exports for Server Components — no client runtime. Same condition applies to `/ssr` for prop types. |
|
|
28
28
|
|
|
29
|
-
All client entries share the same underlying hook code. `/legacy` excludes React 19.2 `<Activity>`; `/ink` excludes DOM-bound primitives (`<a>`-based `Link`, `announceNavigation`) and replaces them with keyboard-driven terminal equivalents. The `/ssr` split keeps server-only prop types out of the client TypeScript context for apps that don't touch SSR (bundle cost is ≈ 0 thanks to `"sideEffects": false`).
|
|
29
|
+
All client entries share the same underlying hook code. `/legacy` excludes React 19.2 `<Activity>`; `/ink` excludes DOM-bound primitives (`<a>`-based `Link`, `announceNavigation`) and replaces them with keyboard-driven terminal equivalents. The `/ssr` split keeps server-only prop types out of the client TypeScript context for apps that don't touch SSR (bundle cost is ≈ 0 thanks to `"sideEffects": false`). Reaching `/ink` from CommonJS means `await import("@real-router/react/ink")`, which resolves and type-checks; `require()` cannot.
|
|
30
30
|
|
|
31
31
|
The root export resolves to a **type-only entry** when bundlers apply the `react-server` condition (Vite RSC, Webpack RSC, Turbopack, Parcel) — Server Components can import public API types without pulling client-only code into the server bundle. Per-request data fetching is handled by [@real-router/rsc-server-plugin](https://www.npmjs.com/package/@real-router/rsc-server-plugin), not this entry. See [RSC Integration wiki guide](https://github.com/greydragon888/real-router/wiki/RSC-Integration).
|
|
32
32
|
|
|
@@ -516,6 +516,29 @@ Opt-in animated route transitions via the browser's [View Transitions API](https
|
|
|
516
516
|
|
|
517
517
|
No-op on unsupported browsers (Firefox as of 2026-04, SSR). Customization is pure CSS via `::view-transition-*` pseudo-elements and `view-transition-name` for hero morphs. See [View Transitions guide](https://github.com/greydragon888/real-router/wiki/View-Transitions) for patterns.
|
|
518
518
|
|
|
519
|
+
## Navigation Direction
|
|
520
|
+
|
|
521
|
+
`createDirectionTracker(router)` writes `data-nav-direction="forward" | "back"` on `<html>` on every leave, so exit and entry animations can key off the direction. Install it **before** `router.usePlugin(browserPluginFactory())`: both listen to `popstate`, and the tracker has to see the event first.
|
|
522
|
+
|
|
523
|
+
```ts
|
|
524
|
+
import { browserPluginFactory } from "@real-router/browser-plugin";
|
|
525
|
+
import { createRouter } from "@real-router/core";
|
|
526
|
+
import { createDirectionTracker } from "@real-router/react";
|
|
527
|
+
|
|
528
|
+
const router = createRouter(routes);
|
|
529
|
+
|
|
530
|
+
createDirectionTracker(router); // before usePlugin
|
|
531
|
+
router.usePlugin(browserPluginFactory());
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
```css
|
|
535
|
+
html[data-nav-direction="back"] .page {
|
|
536
|
+
animation-name: slide-in-from-left;
|
|
537
|
+
}
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
`destroy()` removes the listener and the attribute. Without a `document` (SSR) it returns a no-op instance. The argument must be a live `Router`: the tracker follows its transitions through `getPluginApi`. The API is unstable — it may change in a minor release. Live demo: [`examples/web/react/animation-examples/route-animations/`](../../examples/web/react/animation-examples/route-animations/). Recipes: [Routing Animations guide](https://github.com/greydragon888/real-router/wiki/Routing-Animations).
|
|
541
|
+
|
|
519
542
|
## Documentation
|
|
520
543
|
|
|
521
544
|
Full documentation: [Wiki](https://github.com/greydragon888/real-router/wiki)
|
|
@@ -4,6 +4,33 @@ import { NavigationOptions, NavigationTarget, Params, Router, SearchParams, Stat
|
|
|
4
4
|
//#region src/components/Link.d.ts
|
|
5
5
|
declare const Link: FC<LinkProps>;
|
|
6
6
|
//#endregion
|
|
7
|
+
//#region ../../shared/dom-utils/direction-tracker.d.ts
|
|
8
|
+
interface DirectionTracker {
|
|
9
|
+
destroy: () => void;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Track navigation direction (forward / back) and write it to
|
|
13
|
+
* `<html data-nav-direction>` on every leave. CSS / JS readers consume
|
|
14
|
+
* the attribute via `html[data-nav-direction="back"]` selectors or
|
|
15
|
+
* `document.documentElement.dataset.navDirection`.
|
|
16
|
+
*
|
|
17
|
+
* Mechanism-agnostic — works identically whether downstream UI uses CSS
|
|
18
|
+
* `@keyframes`, View Transitions pseudo-elements, or library state
|
|
19
|
+
* (motion's `motion.div initial={{ x: ... }}`).
|
|
20
|
+
*
|
|
21
|
+
* Implementation:
|
|
22
|
+
* - On install, set `data-nav-direction="forward"` baseline.
|
|
23
|
+
* - Attach a `popstate` listener that flips an internal flag to
|
|
24
|
+
* `true`. Browser back/forward navigation triggers popstate; user
|
|
25
|
+
* clicks on `<Link>` / programmatic `router.navigate(...)` do not.
|
|
26
|
+
* - On every `subscribeLeave`, write
|
|
27
|
+
* `popstateFlag ? "back" : "forward"` and reset the flag.
|
|
28
|
+
*
|
|
29
|
+
* Returns `{ destroy }` to clean up the listener and clear the dataset
|
|
30
|
+
* attribute.
|
|
31
|
+
*/
|
|
32
|
+
declare function createDirectionTracker(router: Router): DirectionTracker;
|
|
33
|
+
//#endregion
|
|
7
34
|
//#region ../../shared/dom-utils/route-announcer.d.ts
|
|
8
35
|
interface RouteAnnouncerOptions {
|
|
9
36
|
prefix?: string;
|
|
@@ -121,5 +148,5 @@ interface RouteProviderProps {
|
|
|
121
148
|
*/
|
|
122
149
|
declare const RouterProvider: FC<RouteProviderProps>;
|
|
123
150
|
//#endregion
|
|
124
|
-
export { Link as n, RouterProvider as t };
|
|
125
|
-
//# sourceMappingURL=RouterProvider-
|
|
151
|
+
export { Link as i, DirectionTracker as n, createDirectionTracker as r, RouterProvider as t };
|
|
152
|
+
//# sourceMappingURL=RouterProvider-Cwy46Oyd.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RouterProvider-Cwy46Oyd.d.ts","names":[],"sources":["../../src/components/Link.tsx","../../../../shared/dom-utils/direction-tracker.ts","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../src/RouterProvider.tsx"],"mappings":";;;;cAmKa,MAAM,GAAG;;;UC9JL;EACf;;;;;;;;;;;;;;;;;;;;;;;iBA8Bc,uBAAuB,QAAQ,SAAS;;;UC3BvC;EACf;EACA,uBAAuB,OAAO;;;;KCUpB;UAEK;EACf,OAAO;EACP;EACA,yBAAyB;;;;;;;;;;;;;EAazB,WAAW;;;;;;;;EAQX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCLe;;;;;;EAMf;;;;;;EAOA;;;;;;;;;;EAWA,yBAAyB;;;;UChDV;EACf,QAAQ;EACR,UAAU;EACV,+BAA+B;EAC/B,oBAAoB;EACpB,YAAY;EACZ;;;;;;;;;cAUW,gBAAgB,GAAG"}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
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-BDNrSg2k.js";
|
|
2
2
|
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-DZI_DkW5.js";
|
|
3
|
-
import {
|
|
3
|
+
import { i as Link, n as DirectionTracker, r as createDirectionTracker, t as RouterProvider } from "./RouterProvider-Cwy46Oyd.js";
|
|
4
4
|
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-aiJ9iE62.js";
|
|
5
5
|
import { Navigator } from "@real-router/core";
|
|
6
6
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
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 };
|
|
7
|
+
export { type DirectionTracker, 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, createDirectionTracker, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-ClTv62BJ.js"),n=require("./RouterProvider-29CNS0pw.js");let r=require("react"),i=require("@real-router/core"),a=require("@real-router/route-utils"),o=require("react/jsx-runtime"),s=require("@real-router/sources");function
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-ClTv62BJ.js"),n=require("./RouterProvider-29CNS0pw.js");let r=require("react"),i=require("@real-router/core"),a=require("@real-router/route-utils"),o=require("react/jsx-runtime"),s=require("@real-router/sources"),c=require("@real-router/core/api");function l(e){return null}l.displayName=`RouteView.Match`;function u(e){return null}u.displayName=`RouteView.Self`;function d(e){return null}d.displayName=`RouteView.NotFound`;const f=new Set([l,u,d]);function p(e,t,n){return t===``?!1:n?e===t:(0,a.startsWithSegment)(e,t)}function m(e,t){r.Children.forEach(e,e=>{(0,r.isValidElement)(e)&&(f.has(e.type)?t.push(e):m(e.props.children,t))})}function h(e,t,n,i,a){let s=a===void 0?e:(0,o.jsx)(r.Suspense,{fallback:a,children:e});return n?(0,o.jsx)(r.Activity,{mode:i,children:s},t):(0,o.jsx)(r.Fragment,{children:s},t)}function g(e,t){return e.type===d?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===u&&(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0)}function _(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&&p(t,u,s)?{rendered:h(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:h(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function v(e,t,n,a){if(a.selfFound&&t===n){e.push(h(a.selfChildren,`__route-view-self__`,!1,`visible`,a.selfFallback));return}t===i.UNKNOWN_ROUTE&&a.notFoundChildren!==null&&e.push((0,o.jsx)(r.Fragment,{children:a.notFoundChildren},`__route-view-not-found__`))}function y(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null,notFoundFound:!1},a=null,o=[];for(let s of e){if(g(s,i))continue;let e=_(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&v(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function b({nodeName:e,children:n}){let{route:i}=t.m(e),a=(0,r.useRef)(null);a.current??=new Set;let s=a.current,c=(0,r.useMemo)(()=>{let e=[];return m(n,e),e},[n]),l=i?.name??null,{rendered:u,activatedName:d}=(0,r.useMemo)(()=>{if(l===null)return{rendered:[],activatedName:null};let t=y(c,l,e,s);return{rendered:t.rendered,activatedName:t.activatedName}},[c,l,e,s]);return(0,r.useEffect)(()=>{d!==null&&s.add(d)},[d,s]),u.length>0?(0,o.jsx)(o.Fragment,{children:u}):null}b.displayName=`RouteView`;const x=Object.assign(b,{Match:l,Self:u,NotFound:d}),S=Object.freeze({destroy:()=>{}});function C(e){if(typeof document>`u`)return S;let t=!1;document.documentElement.dataset.navDirection=`forward`;let n=!1,r=!1,a=()=>{t=!0,r=n};globalThis.addEventListener(`popstate`,a);let o=(0,c.getPluginApi)(e),s=()=>{if(n=!1,r){r=!1;return}t=!1},l=[o.addEventListener(i.events.TRANSITION_START,()=>{n=!0}),o.addEventListener(i.events.TRANSITION_SUCCESS,s),o.addEventListener(i.events.TRANSITION_ERROR,s),o.addEventListener(i.events.TRANSITION_CANCEL,s),e.subscribeLeave(()=>{document.documentElement.dataset.navDirection=t?`back`:`forward`,t=!1,r=!1})];return{destroy:()=>{for(let e of l)e();globalThis.removeEventListener(`popstate`,a),delete document.documentElement.dataset.navDirection}}}function w(e,n){let i=t.h(),a=(0,r.useRef)(e),o=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{a.current=e}),(0,r.useEffect)(()=>i.subscribeLeave((0,s.guardLeaveListener)(e=>a.current(e),{skipSameRoute:o})),[i,o])}function T(t,n){let{route:i,previousRoute:a}=e.t(),o=(0,r.useRef)(t),[c]=(0,r.useState)(()=>(0,s.createRouteEnterGate)()),l=n?.skipSameRoute??!0;(0,r.useLayoutEffect)(()=>{o.current=t}),(0,r.useEffect)(()=>{let e=c(i,a,l);e&&o.current(e)},[c,i,a,l])}exports.Link=n.n,exports.RouteView=x,exports.RouterErrorBoundary=t.a,exports.RouterProvider=n.t,exports.createDirectionTracker=C,exports.useNavigator=t.i,exports.useRoute=e.t,exports.useRouteEnter=T,exports.useRouteExit=w,exports.useRouteNode=t.m,exports.useRouteUtils=t.r,exports.useRouter=t.h,exports.useRouterTransition=t.n;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["startsWithSegment","isValidElement","Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRef","useMemo","useRouter","useRef","guardLeaveListener","useRoute","useRef","useState","createRouteEnterGate"],"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\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n notFoundFound: boolean;\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 (MARKER_TYPES.has(child.type)) {\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 // First-wins: subsequent <NotFound> elements are ignored, symmetric with\n // <Self> below (#1220). Before this guard the assignment was unconditional\n // (last-wins), contradicting the documented Self-symmetric contract.\n if (!slots.notFoundFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n slots.notFoundFound = true;\n }\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: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\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 // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\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 activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\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: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n notFoundFound: false,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\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 activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, 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 // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\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 const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n // `hasBeenActivated` is a ref-held Set (L15-20), mutated post-commit in this\n // effect — the concurrent-safe pattern #1251 established. @eslint-react's\n // experimental `immutability` rule (detection widened in v5.17) flags the ref\n // mutation and suggests state, which would defeat the ref's whole purpose\n // (re-render-free activation tracking). Intentional exception, scoped here.\n /* eslint-disable @eslint-react/immutability -- intentional post-commit ref-Set mutation, see #1251 */\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n /* eslint-enable @eslint-react/immutability */\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 { guardLeaveListener } from \"@real-router/sources\";\nimport { 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\n * rejects `navigate()` with the handler's **original error** and emits\n * `TRANSITION_ERROR` — it is NOT re-coded to `TRANSITION_CANCELLED`\n * (that arises only when the navigation's `signal` aborts: a superseding\n * navigation, `stop()`, `dispose()`, or an external `opts.signal`).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\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 Detecting that you are leaving a subtree\n * ```tsx\n * const inProducts = (name: string) =>\n * name === \"products\" || name.startsWith(\"products.\");\n *\n * useRouteExit(({ route, nextRoute }) => {\n * if (inProducts(route.name) && !inProducts(nextRoute.name)) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * });\n * ```\n *\n * ⚠ Do NOT read `nextRoute.transition` here. `nextRoute` is the PENDING target,\n * and the pipeline gives it the neutral default — empty `segments`, optional\n * flags `undefined` — so the example this replaced read `[]` and `undefined`\n * whatever the navigation was. (It threw outright until real-router#1976\n * attached the field.) The real metadata is written at the COMMIT: read it in\n * `router.subscribe`, `onTransitionSuccess`, or `getState()`.\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 // The same-route + reentrant-abort guards and the Promise passthrough\n // live in the shared listener (@real-router/sources, #1435). The ref-thunk\n // keeps the latest handler reachable from the long-lived subscription\n // without resubscribing on every render.\n return router.subscribeLeave(\n guardLeaveListener((context) => handlerRef.current(context), {\n skipSameRoute,\n }),\n );\n }, [router, skipSameRoute]);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef, useState } 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 * // ⚠ NOT `transition.redirected` — the router never sets it (it only ever\n * // carries what a caller passed as `{ redirected: true }`), so branching on\n * // it here is silently dead for a `forwardTo` or a guard redirect.\n * // `from` needs no check: this hook does not fire without one.\n * showToast(`Arrived from ${route.transition.from}`);\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 // The canonical enter-guard set + `lastHandledRoute` dedupe live in the\n // shared gate (@real-router/sources, #1435). Created once via useState's\n // lazy initializer so its dedupe state is stable across StrictMode's effect\n // re-runs — `skipSameRoute` is threaded per-call, so an options flip never\n // forces a fresh gate (which would reset the dedupe). `useState`, not a ref:\n // the gate must be created once and stay stable, and a ref write during\n // render is disallowed (@eslint-react/refs); the gate is never re-set, so no\n // re-render is triggered. The gate owns skip-initial / same-route /\n // StrictMode-dedupe / the `!previousRoute` guard — the sole defense of the\n // non-nullable `RouteEnterContext.previousRoute` contract (#1218 PC1/PC2).\n const [gate] = useState(() => createRouteEnterGate());\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 const context = gate(route, previousRoute, skipSameRoute);\n\n if (context) {\n handlerRef.current(context);\n }\n }, [gate, route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"kWAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EAgB1E,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,GAGvB,EAAOA,EAAAA,kBAAAA,CAAkB,EAAW,CAAe,CACrD,CAEA,SAAgB,EACd,EACA,EACM,CAYN,EAAA,SAAS,QAAQ,EAAW,GAAU,EAChC,EAACC,EAAAA,eAAAA,CAAe,CAAK,IAIrB,EAAa,IAAI,EAAM,IAAI,EAC7B,EAAO,KAAK,CAAK,EAEjB,EACG,EAAM,MAA2C,SAClD,CACF,EAEJ,CAAC,CACH,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAM,EACJ,IAAa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AC,EAGhC,EAAS,OAAS,GACb,EAAA,EAAA,IAAA,CAAA,EAAA,SAAA,CAAA,SAAG,CAAW,CAAA,EAGhB,IACT,CAEA,EAAc,YAAc,YAE5B,MAAa,EAAY,OAAO,OAAO,EAAe,CACpD,QACA,OACA,UACF,CAAC,ECiDD,SAAgB,EACd,EACA,EACM,CACN,IAAM,EAASC,EAAAA,EAAU,EACnB,GAAA,EAAaC,EAAAA,OAAAA,CAAO,CAAO,EAC3B,EAAgB,GAAS,eAAiB,IAQhD,EAAA,EAAA,gBAAA,KAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,GAED,EAAA,EAAA,UAAA,KAKS,EAAO,gBAAA,EACZC,EAAAA,mBAAAA,CAAoB,GAAY,EAAW,QAAQ,CAAO,EAAG,CAC3D,eACF,CAAC,CACH,EACC,CAAC,EAAQ,CAAa,CAAC,CAC5B,CChEA,SAAgB,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBC,EAAAA,EAAS,EACpC,GAAA,EAAaC,EAAAA,OAAAA,CAAO,CAAO,EAW3B,CAAC,IAAA,EAAQC,EAAAA,SAAAA,MAAAA,EAAeC,EAAAA,qBAAAA,CAAqB,CAAC,EAC9C,EAAgB,GAAS,eAAiB,IAKhD,EAAA,EAAA,gBAAA,KAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,GAED,EAAA,EAAA,UAAA,KAAgB,CACd,IAAM,EAAU,EAAK,EAAO,EAAe,CAAa,EAEpD,GACF,EAAW,QAAQ,CAAO,CAE9B,EAAG,CAAC,EAAM,EAAO,EAAe,CAAa,CAAC,CAChD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["startsWithSegment","isValidElement","Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRef","useMemo","getPluginApi","events","useRouter","useRef","guardLeaveListener","useRoute","useRef","useState","createRouteEnterGate"],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../../../shared/dom-utils/direction-tracker.ts","../../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\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n notFoundFound: boolean;\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 (MARKER_TYPES.has(child.type)) {\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 // First-wins: subsequent <NotFound> elements are ignored, symmetric with\n // <Self> below (#1220). Before this guard the assignment was unconditional\n // (last-wins), contradicting the documented Self-symmetric contract.\n if (!slots.notFoundFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n slots.notFoundFound = true;\n }\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: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\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 // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\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 activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\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: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n notFoundFound: false,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\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 activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, 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 // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\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 const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n // `hasBeenActivated` is a ref-held Set (L15-20), mutated post-commit in this\n // effect — the concurrent-safe pattern #1251 established. @eslint-react's\n // experimental `immutability` rule (detection widened in v5.17) flags the ref\n // mutation and suggests state, which would defeat the ref's whole purpose\n // (re-render-free activation tracking). Intentional exception, scoped here.\n /* eslint-disable @eslint-react/immutability -- intentional post-commit ref-Set mutation, see #1251 */\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n /* eslint-enable @eslint-react/immutability */\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 { events } from \"@real-router/core\";\nimport { getPluginApi } from \"@real-router/core/api\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport interface DirectionTracker {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: DirectionTracker = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n/**\n * Track navigation direction (forward / back) and write it to\n * `<html data-nav-direction>` on every leave. CSS / JS readers consume\n * the attribute via `html[data-nav-direction=\"back\"]` selectors or\n * `document.documentElement.dataset.navDirection`.\n *\n * Mechanism-agnostic — works identically whether downstream UI uses CSS\n * `@keyframes`, View Transitions pseudo-elements, or library state\n * (motion's `motion.div initial={{ x: ... }}`).\n *\n * Implementation:\n * - On install, set `data-nav-direction=\"forward\"` baseline.\n * - Attach a `popstate` listener that flips an internal flag to\n * `true`. Browser back/forward navigation triggers popstate; user\n * clicks on `<Link>` / programmatic `router.navigate(...)` do not.\n * - On every `subscribeLeave`, write\n * `popstateFlag ? \"back\" : \"forward\"` and reset the flag.\n *\n * Returns `{ destroy }` to clean up the listener and clear the dataset\n * attribute.\n */\nexport function createDirectionTracker(router: Router): DirectionTracker {\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n let popstateFlag = false;\n\n document.documentElement.dataset.navDirection = \"forward\";\n\n let transitionInFlight = false;\n let armedMidTransition = false;\n\n // ⚑ The flag is SPENT by the transition it belongs to, whether or not that\n // transition reaches a leave phase (#1924). It is armed by any `popstate` on\n // `globalThis`, not only one the router consumes, so `history.back()` onto an\n // entry that resolves to the current state — core answers `SAME_STATES`, and\n // measured, that arc emits `TRANSITION_ERROR` with no `TRANSITION_START` and\n // no leave — would otherwise leave it armed indefinitely and publish the next\n // FORWARD navigation as \"back\".\n //\n // ⚠ A clock has no correct value to be set to. The leave phase is separated\n // from its popstate by every deactivation guard, and a guard may await\n // anything; the plugin also DEFERS a popstate that arrives during an\n // in-flight transition and replays it from that transition's `finally`. The\n // gap has no upper bound. Measured on the obvious choice: a task-boundary\n // expiry disarms a live navigation on ONE async `canDeactivate`.\n const onPopstate = (): void => {\n popstateFlag = true;\n // A deferred event belongs to the replay, not to the transition running\n // now, so that transition's terminal event must not spend it.\n armedMidTransition = transitionInFlight;\n };\n\n // IMPORTANT — listener-ordering: `popstate` fires on `window`, which\n // has no DOM descendants, so capture phase is moot. Listeners are\n // dispatched in registration order. To beat the browser-plugin's own\n // popstate handler, this tracker must be installed **before**\n // `router.usePlugin(browserPluginFactory())` in user code. Otherwise\n // the plugin's handler runs first and synchronously fires\n // `subscribeLeave` while `popstateFlag` is still `false`.\n globalThis.addEventListener(\"popstate\", onPopstate);\n\n const api = getPluginApi(router);\n\n const onSettled = (): void => {\n transitionInFlight = false;\n\n if (armedMidTransition) {\n armedMidTransition = false;\n\n return;\n }\n\n popstateFlag = false;\n };\n\n const unsubs = [\n api.addEventListener(events.TRANSITION_START, () => {\n transitionInFlight = true;\n }),\n api.addEventListener(events.TRANSITION_SUCCESS, onSettled),\n api.addEventListener(events.TRANSITION_ERROR, onSettled),\n api.addEventListener(events.TRANSITION_CANCEL, onSettled),\n router.subscribeLeave(() => {\n document.documentElement.dataset.navDirection = popstateFlag\n ? \"back\"\n : \"forward\";\n popstateFlag = false;\n armedMidTransition = false;\n }),\n ];\n\n return {\n destroy: () => {\n for (const unsub of unsubs) {\n unsub();\n }\n\n globalThis.removeEventListener(\"popstate\", onPopstate);\n delete document.documentElement.dataset.navDirection;\n },\n };\n}\n","import { guardLeaveListener } from \"@real-router/sources\";\nimport { 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\n * rejects `navigate()` with the handler's **original error** and emits\n * `TRANSITION_ERROR` — it is NOT re-coded to `TRANSITION_CANCELLED`\n * (that arises only when the navigation's `signal` aborts: a superseding\n * navigation, `stop()`, `dispose()`, or an external `opts.signal`).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\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 Detecting that you are leaving a subtree\n * ```tsx\n * const inProducts = (name: string) =>\n * name === \"products\" || name.startsWith(\"products.\");\n *\n * useRouteExit(({ route, nextRoute }) => {\n * if (inProducts(route.name) && !inProducts(nextRoute.name)) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * });\n * ```\n *\n * ⚠ Do NOT read `nextRoute.transition` here. `nextRoute` is the PENDING target,\n * and the pipeline gives it the neutral default — empty `segments`, optional\n * flags `undefined` — so the example this replaced read `[]` and `undefined`\n * whatever the navigation was. (It threw outright until real-router#1976\n * attached the field.) The real metadata is written at the COMMIT: read it in\n * `router.subscribe`, `onTransitionSuccess`, or `getState()`.\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 // The same-route + reentrant-abort guards and the Promise passthrough\n // live in the shared listener (@real-router/sources, #1435). The ref-thunk\n // keeps the latest handler reachable from the long-lived subscription\n // without resubscribing on every render.\n return router.subscribeLeave(\n guardLeaveListener((context) => handlerRef.current(context), {\n skipSameRoute,\n }),\n );\n }, [router, skipSameRoute]);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef, useState } 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 * // ⚠ NOT `transition.redirected` — the router never sets it (it only ever\n * // carries what a caller passed as `{ redirected: true }`), so branching on\n * // it here is silently dead for a `forwardTo` or a guard redirect.\n * // `from` needs no check: this hook does not fire without one.\n * showToast(`Arrived from ${route.transition.from}`);\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 // The canonical enter-guard set + `lastHandledRoute` dedupe live in the\n // shared gate (@real-router/sources, #1435). Created once via useState's\n // lazy initializer so its dedupe state is stable across StrictMode's effect\n // re-runs — `skipSameRoute` is threaded per-call, so an options flip never\n // forces a fresh gate (which would reset the dedupe). `useState`, not a ref:\n // the gate must be created once and stay stable, and a ref write during\n // render is disallowed (@eslint-react/refs); the gate is never re-set, so no\n // re-render is triggered. The gate owns skip-initial / same-route /\n // StrictMode-dedupe / the `!previousRoute` guard — the sole defense of the\n // non-nullable `RouteEnterContext.previousRoute` contract (#1218 PC1/PC2).\n const [gate] = useState(() => createRouteEnterGate());\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 const context = gate(route, previousRoute, skipSameRoute);\n\n if (context) {\n handlerRef.current(context);\n }\n }, [gate, route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"qYAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EAgB1E,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,GAGvB,EAAOA,EAAAA,kBAAAA,CAAkB,EAAW,CAAe,CACrD,CAEA,SAAgB,EACd,EACA,EACM,CAYN,EAAA,SAAS,QAAQ,EAAW,GAAU,EAChC,EAACC,EAAAA,eAAAA,CAAe,CAAK,IAIrB,EAAa,IAAI,EAAM,IAAI,EAC7B,EAAO,KAAK,CAAK,EAEjB,EACG,EAAM,MAA2C,SAClD,CACF,EAEJ,CAAC,CACH,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAM,EACJ,IAAa,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AAA,gBAAA,KAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,GAED,EAAA,EAAA,UAAA,KAKS,EAAO,gBAAA,EACZC,EAAAA,mBAAAA,CAAoB,GAAY,EAAW,QAAQ,CAAO,EAAG,CAC3D,eACF,CAAC,CACH,EACC,CAAC,EAAQ,CAAa,CAAC,CAC5B,CChEA,SAAgB,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBC,EAAAA,EAAS,EACpC,GAAA,EAAaC,EAAAA,OAAAA,CAAO,CAAO,EAW3B,CAAC,IAAA,EAAQC,EAAAA,SAAAA,MAAAA,EAAeC,EAAAA,qBAAAA,CAAqB,CAAC,EAC9C,EAAgB,GAAS,eAAiB,IAKhD,EAAA,EAAA,gBAAA,KAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,GAED,EAAA,EAAA,UAAA,KAAgB,CACd,IAAM,EAAU,EAAK,EAAO,EAAe,CAAa,EAEpD,GACF,EAAW,QAAQ,CAAO,CAE9B,EAAG,CAAC,EAAM,EAAO,EAAe,CAAa,CAAC,CAChD"}
|
package/dist/cjs/legacy.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-DZI_DkW5.js";
|
|
2
|
-
import {
|
|
2
|
+
import { i as Link, t as RouterProvider } from "./RouterProvider-Cwy46Oyd.js";
|
|
3
3
|
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-aiJ9iE62.js";
|
|
4
4
|
import { Navigator } from "@real-router/core";
|
|
5
5
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
@@ -4,6 +4,33 @@ import { NavigationOptions, NavigationTarget, Params, Router, SearchParams, Stat
|
|
|
4
4
|
//#region src/components/Link.d.ts
|
|
5
5
|
declare const Link: FC<LinkProps>;
|
|
6
6
|
//#endregion
|
|
7
|
+
//#region ../../shared/dom-utils/direction-tracker.d.ts
|
|
8
|
+
interface DirectionTracker {
|
|
9
|
+
destroy: () => void;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Track navigation direction (forward / back) and write it to
|
|
13
|
+
* `<html data-nav-direction>` on every leave. CSS / JS readers consume
|
|
14
|
+
* the attribute via `html[data-nav-direction="back"]` selectors or
|
|
15
|
+
* `document.documentElement.dataset.navDirection`.
|
|
16
|
+
*
|
|
17
|
+
* Mechanism-agnostic — works identically whether downstream UI uses CSS
|
|
18
|
+
* `@keyframes`, View Transitions pseudo-elements, or library state
|
|
19
|
+
* (motion's `motion.div initial={{ x: ... }}`).
|
|
20
|
+
*
|
|
21
|
+
* Implementation:
|
|
22
|
+
* - On install, set `data-nav-direction="forward"` baseline.
|
|
23
|
+
* - Attach a `popstate` listener that flips an internal flag to
|
|
24
|
+
* `true`. Browser back/forward navigation triggers popstate; user
|
|
25
|
+
* clicks on `<Link>` / programmatic `router.navigate(...)` do not.
|
|
26
|
+
* - On every `subscribeLeave`, write
|
|
27
|
+
* `popstateFlag ? "back" : "forward"` and reset the flag.
|
|
28
|
+
*
|
|
29
|
+
* Returns `{ destroy }` to clean up the listener and clear the dataset
|
|
30
|
+
* attribute.
|
|
31
|
+
*/
|
|
32
|
+
declare function createDirectionTracker(router: Router): DirectionTracker;
|
|
33
|
+
//#endregion
|
|
7
34
|
//#region ../../shared/dom-utils/route-announcer.d.ts
|
|
8
35
|
interface RouteAnnouncerOptions {
|
|
9
36
|
prefix?: string;
|
|
@@ -121,5 +148,5 @@ interface RouteProviderProps {
|
|
|
121
148
|
*/
|
|
122
149
|
declare const RouterProvider: FC<RouteProviderProps>;
|
|
123
150
|
//#endregion
|
|
124
|
-
export { Link as n, RouterProvider as t };
|
|
125
|
-
//# sourceMappingURL=RouterProvider-
|
|
151
|
+
export { Link as i, DirectionTracker as n, createDirectionTracker as r, RouterProvider as t };
|
|
152
|
+
//# sourceMappingURL=RouterProvider-BixslYdB.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RouterProvider-BixslYdB.d.mts","names":[],"sources":["../../src/components/Link.tsx","../../../../shared/dom-utils/direction-tracker.ts","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../src/RouterProvider.tsx"],"mappings":";;;;cAmKa,MAAM,GAAG;;;UC9JL;EACf;;;;;;;;;;;;;;;;;;;;;;;iBA8Bc,uBAAuB,QAAQ,SAAS;;;UC3BvC;EACf;EACA,uBAAuB,OAAO;;;;KCUpB;UAEK;EACf,OAAO;EACP;EACA,yBAAyB;;;;;;;;;;;;;EAazB,WAAW;;;;;;;;EAQX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCLe;;;;;;EAMf;;;;;;EAOA;;;;;;;;;;EAWA,yBAAyB;;;;UChDV;EACf,QAAQ;EACR,UAAU;EACV,+BAA+B;EAC/B,oBAAoB;EACpB,YAAY;EACZ;;;;;;;;;cAUW,gBAAgB,GAAG"}
|
package/dist/esm/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
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-BDNrSg2k.mjs";
|
|
2
2
|
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-DZI_DkW5.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { i as Link, n as DirectionTracker, r as createDirectionTracker, t as RouterProvider } from "./RouterProvider-BixslYdB.mjs";
|
|
4
4
|
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-YvPtN5pW.mjs";
|
|
5
5
|
import { Navigator } from "@real-router/core";
|
|
6
6
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
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 };
|
|
7
|
+
export { type DirectionTracker, 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, createDirectionTracker, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,h as n,i as r,m as i,n as a,r as o}from"./RouterProviderCore-BQA-I4NQ.mjs";import{n as s,t as c}from"./RouterProvider-BDUET4Ke.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 _,useState as v}from"react";import{UNKNOWN_ROUTE as y}from"@real-router/core";import{startsWithSegment as
|
|
1
|
+
import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,h as n,i as r,m as i,n as a,r as o}from"./RouterProviderCore-BQA-I4NQ.mjs";import{n as s,t as c}from"./RouterProvider-BDUET4Ke.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 _,useState as v}from"react";import{UNKNOWN_ROUTE as y,events as b}from"@real-router/core";import{startsWithSegment as x}from"@real-router/route-utils";import{Fragment as S,jsx as C}from"react/jsx-runtime";import{createRouteEnterGate as w,guardLeaveListener as T}from"@real-router/sources";import{getPluginApi as E}from"@real-router/core/api";function D(e){return null}D.displayName=`RouteView.Match`;function O(e){return null}O.displayName=`RouteView.Self`;function k(e){return null}k.displayName=`RouteView.NotFound`;const A=new Set([D,O,k]);function j(e,t,n){return t===``?!1:n?e===t:x(e,t)}function M(e,t){u.forEach(e,e=>{p(e)&&(A.has(e.type)?t.push(e):M(e.props.children,t))})}function N(e,t,n,r,i){let a=i===void 0?e:C(f,{fallback:i,children:e});return n?C(l,{mode:r,children:a},t):C(d,{children:a},t)}function P(e,t){return e.type===k?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===O&&(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0)}function F(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&&j(t,u,s)?{rendered:N(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:N(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function I(e,t,n,r){if(r.selfFound&&t===n){e.push(N(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===y&&r.notFoundChildren!==null&&e.push(C(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function L(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null,notFoundFound:!1},a=null,o=[];for(let s of e){if(P(s,i))continue;let e=F(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&I(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function R({nodeName:e,children:t}){let{route:n}=i(e),r=_(null);r.current??=new Set;let a=r.current,o=g(()=>{let e=[];return M(t,e),e},[t]),s=n?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=L(o,s,e,a);return{rendered:t.rendered,activatedName:t.activatedName}},[o,s,e,a]);return m(()=>{l!==null&&a.add(l)},[l,a]),c.length>0?C(S,{children:c}):null}R.displayName=`RouteView`;const z=Object.assign(R,{Match:D,Self:O,NotFound:k}),B=Object.freeze({destroy:()=>{}});function V(e){if(typeof document>`u`)return B;let t=!1;document.documentElement.dataset.navDirection=`forward`;let n=!1,r=!1,i=()=>{t=!0,r=n};globalThis.addEventListener(`popstate`,i);let a=E(e),o=()=>{if(n=!1,r){r=!1;return}t=!1},s=[a.addEventListener(b.TRANSITION_START,()=>{n=!0}),a.addEventListener(b.TRANSITION_SUCCESS,o),a.addEventListener(b.TRANSITION_ERROR,o),a.addEventListener(b.TRANSITION_CANCEL,o),e.subscribeLeave(()=>{document.documentElement.dataset.navDirection=t?`back`:`forward`,t=!1,r=!1})];return{destroy:()=>{for(let e of s)e();globalThis.removeEventListener(`popstate`,i),delete document.documentElement.dataset.navDirection}}}function H(e,t){let r=n(),i=_(e),a=t?.skipSameRoute??!0;h(()=>{i.current=e}),m(()=>r.subscribeLeave(T(e=>i.current(e),{skipSameRoute:a})),[r,a])}function U(t,n){let{route:r,previousRoute:i}=e(),a=_(t),[o]=v(()=>w()),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{let e=o(r,i,s);e&&a.current(e)},[o,r,i,s])}export{s as Link,z as RouteView,t as RouterErrorBoundary,c as RouterProvider,V as createDirectionTracker,r as useNavigator,e as useRoute,U as useRouteEnter,H as useRouteExit,i as useRouteNode,o as useRouteUtils,n as useRouter,a as useRouterTransition};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -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\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n notFoundFound: boolean;\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 (MARKER_TYPES.has(child.type)) {\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 // First-wins: subsequent <NotFound> elements are ignored, symmetric with\n // <Self> below (#1220). Before this guard the assignment was unconditional\n // (last-wins), contradicting the documented Self-symmetric contract.\n if (!slots.notFoundFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n slots.notFoundFound = true;\n }\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: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\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 // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\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 activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\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: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n notFoundFound: false,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\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 activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, 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 // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\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 const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n // `hasBeenActivated` is a ref-held Set (L15-20), mutated post-commit in this\n // effect — the concurrent-safe pattern #1251 established. @eslint-react's\n // experimental `immutability` rule (detection widened in v5.17) flags the ref\n // mutation and suggests state, which would defeat the ref's whole purpose\n // (re-render-free activation tracking). Intentional exception, scoped here.\n /* eslint-disable @eslint-react/immutability -- intentional post-commit ref-Set mutation, see #1251 */\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n /* eslint-enable @eslint-react/immutability */\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 { guardLeaveListener } from \"@real-router/sources\";\nimport { 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\n * rejects `navigate()` with the handler's **original error** and emits\n * `TRANSITION_ERROR` — it is NOT re-coded to `TRANSITION_CANCELLED`\n * (that arises only when the navigation's `signal` aborts: a superseding\n * navigation, `stop()`, `dispose()`, or an external `opts.signal`).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\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 Detecting that you are leaving a subtree\n * ```tsx\n * const inProducts = (name: string) =>\n * name === \"products\" || name.startsWith(\"products.\");\n *\n * useRouteExit(({ route, nextRoute }) => {\n * if (inProducts(route.name) && !inProducts(nextRoute.name)) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * });\n * ```\n *\n * ⚠ Do NOT read `nextRoute.transition` here. `nextRoute` is the PENDING target,\n * and the pipeline gives it the neutral default — empty `segments`, optional\n * flags `undefined` — so the example this replaced read `[]` and `undefined`\n * whatever the navigation was. (It threw outright until real-router#1976\n * attached the field.) The real metadata is written at the COMMIT: read it in\n * `router.subscribe`, `onTransitionSuccess`, or `getState()`.\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 // The same-route + reentrant-abort guards and the Promise passthrough\n // live in the shared listener (@real-router/sources, #1435). The ref-thunk\n // keeps the latest handler reachable from the long-lived subscription\n // without resubscribing on every render.\n return router.subscribeLeave(\n guardLeaveListener((context) => handlerRef.current(context), {\n skipSameRoute,\n }),\n );\n }, [router, skipSameRoute]);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef, useState } 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 * // ⚠ NOT `transition.redirected` — the router never sets it (it only ever\n * // carries what a caller passed as `{ redirected: true }`), so branching on\n * // it here is silently dead for a `forwardTo` or a guard redirect.\n * // `from` needs no check: this hook does not fire without one.\n * showToast(`Arrived from ${route.transition.from}`);\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 // The canonical enter-guard set + `lastHandledRoute` dedupe live in the\n // shared gate (@real-router/sources, #1435). Created once via useState's\n // lazy initializer so its dedupe state is stable across StrictMode's effect\n // re-runs — `skipSameRoute` is threaded per-call, so an options flip never\n // forces a fresh gate (which would reset the dedupe). `useState`, not a ref:\n // the gate must be created once and stay stable, and a ref write during\n // render is disallowed (@eslint-react/refs); the gate is never re-set, so no\n // re-render is triggered. The gate owns skip-initial / same-route /\n // StrictMode-dedupe / the `!previousRoute` guard — the sole defense of the\n // non-nullable `RouteEnterContext.previousRoute` contract (#1218 PC1/PC2).\n const [gate] = useState(() => createRouteEnterGate());\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 const context = gate(route, previousRoute, skipSameRoute);\n\n if (context) {\n handlerRef.current(context);\n }\n }, [gate, route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"imBAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,C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Ae,EAAO,aAAc,CAC1E,EAAG,CAAC,EAAU,EAAW,EAAU,CAAgB,CAAC,EAwBpD,OAXA,MAAgB,CACV,IAAkB,MACpB,EAAiB,IAAI,CAAa,CAEtC,EAAG,CAAC,EAAe,CAAgB,CAAC,EAGhC,EAAS,OAAS,EACb,EAAA,EAAA,CAAA,SAAG,CAAW,CAAA,EAGhB,IACT,CAEA,EAAc,YAAc,YAE5B,MAAa,EAAY,OAAO,OAAO,EAAe,CACpD,QACA,OACA,UACF,CAAC,ECiDD,SAAgB,EACd,EACA,EACM,CACN,IAAM,EAAS,EAAU,EACnB,EAAa,EAAO,CAAO,EAC3B,EAAgB,GAAS,eAAiB,GAQhD,MAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,EAED,MAKS,EAAO,eACZ,EAAoB,GAAY,EAAW,QAAQ,CAAO,EAAG,CAC3D,eACF,CAAC,CACH,EACC,CAAC,EAAQ,CAAa,CAAC,CAC5B,CChEA,SAAgB,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkB,EAAS,EACpC,EAAa,EAAO,CAAO,EAW3B,CAAC,GAAQ,MAAe,EAAqB,CAAC,EAC9C,EAAgB,GAAS,eAAiB,GAKhD,MAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,EAED,MAAgB,CACd,IAAM,EAAU,EAAK,EAAO,EAAe,CAAa,EAEpD,GACF,EAAW,QAAQ,CAAO,CAE9B,EAAG,CAAC,EAAM,EAAO,EAAe,CAAa,CAAC,CAChD"}
|
|
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","../../../../shared/dom-utils/direction-tracker.ts","../../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\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n notFoundFound: boolean;\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 (MARKER_TYPES.has(child.type)) {\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 // First-wins: subsequent <NotFound> elements are ignored, symmetric with\n // <Self> below (#1220). Before this guard the assignment was unconditional\n // (last-wins), contradicting the documented Self-symmetric contract.\n if (!slots.notFoundFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n slots.notFoundFound = true;\n }\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: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\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 // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\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 activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\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: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n notFoundFound: false,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\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 activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, 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 // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\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 const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n // `hasBeenActivated` is a ref-held Set (L15-20), mutated post-commit in this\n // effect — the concurrent-safe pattern #1251 established. @eslint-react's\n // experimental `immutability` rule (detection widened in v5.17) flags the ref\n // mutation and suggests state, which would defeat the ref's whole purpose\n // (re-render-free activation tracking). Intentional exception, scoped here.\n /* eslint-disable @eslint-react/immutability -- intentional post-commit ref-Set mutation, see #1251 */\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n /* eslint-enable @eslint-react/immutability */\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 { events } from \"@real-router/core\";\nimport { getPluginApi } from \"@real-router/core/api\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport interface DirectionTracker {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: DirectionTracker = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n/**\n * Track navigation direction (forward / back) and write it to\n * `<html data-nav-direction>` on every leave. CSS / JS readers consume\n * the attribute via `html[data-nav-direction=\"back\"]` selectors or\n * `document.documentElement.dataset.navDirection`.\n *\n * Mechanism-agnostic — works identically whether downstream UI uses CSS\n * `@keyframes`, View Transitions pseudo-elements, or library state\n * (motion's `motion.div initial={{ x: ... }}`).\n *\n * Implementation:\n * - On install, set `data-nav-direction=\"forward\"` baseline.\n * - Attach a `popstate` listener that flips an internal flag to\n * `true`. Browser back/forward navigation triggers popstate; user\n * clicks on `<Link>` / programmatic `router.navigate(...)` do not.\n * - On every `subscribeLeave`, write\n * `popstateFlag ? \"back\" : \"forward\"` and reset the flag.\n *\n * Returns `{ destroy }` to clean up the listener and clear the dataset\n * attribute.\n */\nexport function createDirectionTracker(router: Router): DirectionTracker {\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n let popstateFlag = false;\n\n document.documentElement.dataset.navDirection = \"forward\";\n\n let transitionInFlight = false;\n let armedMidTransition = false;\n\n // ⚑ The flag is SPENT by the transition it belongs to, whether or not that\n // transition reaches a leave phase (#1924). It is armed by any `popstate` on\n // `globalThis`, not only one the router consumes, so `history.back()` onto an\n // entry that resolves to the current state — core answers `SAME_STATES`, and\n // measured, that arc emits `TRANSITION_ERROR` with no `TRANSITION_START` and\n // no leave — would otherwise leave it armed indefinitely and publish the next\n // FORWARD navigation as \"back\".\n //\n // ⚠ A clock has no correct value to be set to. The leave phase is separated\n // from its popstate by every deactivation guard, and a guard may await\n // anything; the plugin also DEFERS a popstate that arrives during an\n // in-flight transition and replays it from that transition's `finally`. The\n // gap has no upper bound. Measured on the obvious choice: a task-boundary\n // expiry disarms a live navigation on ONE async `canDeactivate`.\n const onPopstate = (): void => {\n popstateFlag = true;\n // A deferred event belongs to the replay, not to the transition running\n // now, so that transition's terminal event must not spend it.\n armedMidTransition = transitionInFlight;\n };\n\n // IMPORTANT — listener-ordering: `popstate` fires on `window`, which\n // has no DOM descendants, so capture phase is moot. Listeners are\n // dispatched in registration order. To beat the browser-plugin's own\n // popstate handler, this tracker must be installed **before**\n // `router.usePlugin(browserPluginFactory())` in user code. Otherwise\n // the plugin's handler runs first and synchronously fires\n // `subscribeLeave` while `popstateFlag` is still `false`.\n globalThis.addEventListener(\"popstate\", onPopstate);\n\n const api = getPluginApi(router);\n\n const onSettled = (): void => {\n transitionInFlight = false;\n\n if (armedMidTransition) {\n armedMidTransition = false;\n\n return;\n }\n\n popstateFlag = false;\n };\n\n const unsubs = [\n api.addEventListener(events.TRANSITION_START, () => {\n transitionInFlight = true;\n }),\n api.addEventListener(events.TRANSITION_SUCCESS, onSettled),\n api.addEventListener(events.TRANSITION_ERROR, onSettled),\n api.addEventListener(events.TRANSITION_CANCEL, onSettled),\n router.subscribeLeave(() => {\n document.documentElement.dataset.navDirection = popstateFlag\n ? \"back\"\n : \"forward\";\n popstateFlag = false;\n armedMidTransition = false;\n }),\n ];\n\n return {\n destroy: () => {\n for (const unsub of unsubs) {\n unsub();\n }\n\n globalThis.removeEventListener(\"popstate\", onPopstate);\n delete document.documentElement.dataset.navDirection;\n },\n };\n}\n","import { guardLeaveListener } from \"@real-router/sources\";\nimport { 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\n * rejects `navigate()` with the handler's **original error** and emits\n * `TRANSITION_ERROR` — it is NOT re-coded to `TRANSITION_CANCELLED`\n * (that arises only when the navigation's `signal` aborts: a superseding\n * navigation, `stop()`, `dispose()`, or an external `opts.signal`).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\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 Detecting that you are leaving a subtree\n * ```tsx\n * const inProducts = (name: string) =>\n * name === \"products\" || name.startsWith(\"products.\");\n *\n * useRouteExit(({ route, nextRoute }) => {\n * if (inProducts(route.name) && !inProducts(nextRoute.name)) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * });\n * ```\n *\n * ⚠ Do NOT read `nextRoute.transition` here. `nextRoute` is the PENDING target,\n * and the pipeline gives it the neutral default — empty `segments`, optional\n * flags `undefined` — so the example this replaced read `[]` and `undefined`\n * whatever the navigation was. (It threw outright until real-router#1976\n * attached the field.) The real metadata is written at the COMMIT: read it in\n * `router.subscribe`, `onTransitionSuccess`, or `getState()`.\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 // The same-route + reentrant-abort guards and the Promise passthrough\n // live in the shared listener (@real-router/sources, #1435). The ref-thunk\n // keeps the latest handler reachable from the long-lived subscription\n // without resubscribing on every render.\n return router.subscribeLeave(\n guardLeaveListener((context) => handlerRef.current(context), {\n skipSameRoute,\n }),\n );\n }, [router, skipSameRoute]);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef, useState } 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 * // ⚠ NOT `transition.redirected` — the router never sets it (it only ever\n * // carries what a caller passed as `{ redirected: true }`), so branching on\n * // it here is silently dead for a `forwardTo` or a guard redirect.\n * // `from` needs no check: this hook does not fire without one.\n * showToast(`Arrived from ${route.transition.from}`);\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 // The canonical enter-guard set + `lastHandledRoute` dedupe live in the\n // shared gate (@real-router/sources, #1435). Created once via useState's\n // lazy initializer so its dedupe state is stable across StrictMode's effect\n // re-runs — `skipSameRoute` is threaded per-call, so an options flip never\n // forces a fresh gate (which would reset the dedupe). `useState`, not a ref:\n // the gate must be created once and stay stable, and a ref write during\n // render is disallowed (@eslint-react/refs); the gate is never re-set, so no\n // re-render is triggered. The gate owns skip-initial / same-route /\n // StrictMode-dedupe / the `!previousRoute` guard — the sole defense of the\n // non-nullable `RouteEnterContext.previousRoute` contract (#1218 PC1/PC2).\n const [gate] = useState(() => createRouteEnterGate());\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 const context = gate(route, previousRoute, skipSameRoute);\n\n if (context) {\n handlerRef.current(context);\n }\n }, [gate, route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"kqBAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EAgB1E,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,EAGhB,EAAkB,EAAW,CAAe,CACrD,CAEA,SAAgB,EACd,EACA,EACM,CAYN,EAAS,QAAQ,EAAW,GAAU,CAC/B,EAAe,CAAK,IAIrB,EAAa,IAAI,EAAM,IAAI,EAC7B,EAAO,KAAK,CAAK,EAEjB,EACG,EAAM,MAA2C,SAClD,CACF,EAEJ,CAAC,CACH,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAM,EACJ,IAAa,IAAA,GACX,EAEA,EAAC,EAAD,CAAoB,WAAW,SAAA,CAAuB,CAAA,EAW1D,OARI,EAEA,EAAC,EAAD,CAAgB,OACb,SAAA,CACO,EAFiB,CAEjB,EAIP,EAAC,EAAD,CAAA,SAAqB,CAAkB,EAAxB,CAAwB,CAChD,CAEA,SAAS,EAAe,EAAqB,EAA+B,CAwB1E,OAvBI,EA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
|
|
1
1
|
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-DZI_DkW5.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { i as Link, t as RouterProvider } from "./RouterProvider-BixslYdB.mjs";
|
|
3
3
|
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-YvPtN5pW.mjs";
|
|
4
4
|
import { Navigator } from "@real-router/core";
|
|
5
5
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@real-router/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.37.0",
|
|
4
4
|
"type": "commonjs",
|
|
5
5
|
"description": "React integration for Real-Router",
|
|
6
6
|
"main": "./dist/cjs/index.js",
|
|
@@ -120,10 +120,10 @@
|
|
|
120
120
|
},
|
|
121
121
|
"devDependencies": {
|
|
122
122
|
"@real-router/browser-plugin": "^0.25.0",
|
|
123
|
-
"@real-router/core": "^0.
|
|
124
|
-
"@real-router/validation-plugin": "^0.
|
|
123
|
+
"@real-router/core": "^0.148.0",
|
|
124
|
+
"@real-router/validation-plugin": "^0.30.0",
|
|
125
125
|
"@testing-library/dom": "~10.4.1",
|
|
126
|
-
"@testing-library/jest-dom": "~
|
|
126
|
+
"@testing-library/jest-dom": "~7.0.1",
|
|
127
127
|
"@testing-library/react": "~16.3.2",
|
|
128
128
|
"@testing-library/user-event": "~14.6.1",
|
|
129
129
|
"ink": "7.1.1",
|
|
@@ -131,7 +131,7 @@
|
|
|
131
131
|
"vitest-react-profiler": "1.12.0"
|
|
132
132
|
},
|
|
133
133
|
"peerDependencies": {
|
|
134
|
-
"@real-router/core": ">=0.
|
|
134
|
+
"@real-router/core": ">=0.148.0",
|
|
135
135
|
"@types/react": ">=18.0.0",
|
|
136
136
|
"@types/react-dom": ">=18.0.0",
|
|
137
137
|
"ink": ">=7.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"RouterProvider-iwUCDuSG.d.ts","names":[],"sources":["../../src/components/Link.tsx","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../src/RouterProvider.tsx"],"mappings":";;;;cAmKa,MAAM,GAAG;;;UC1JL;EACf;EACA,uBAAuB,OAAO;;;;KCUpB;UAEK;EACf,OAAO;EACP;EACA,yBAAyB;;;;;;;;;;;;;EAazB,WAAW;;;;;;;;EAQX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCLe;;;;;;EAMf;;;;;;EAOA;;;;;;;;;;EAWA,yBAAyB;;;;UChDV;EACf,QAAQ;EACR,UAAU;EACV,+BAA+B;EAC/B,oBAAoB;EACpB,YAAY;EACZ;;;;;;;;;cAUW,gBAAgB,GAAG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"RouterProvider-CVcC8wop.d.mts","names":[],"sources":["../../src/components/Link.tsx","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../src/RouterProvider.tsx"],"mappings":";;;;cAmKa,MAAM,GAAG;;;UC1JL;EACf;EACA,uBAAuB,OAAO;;;;KCUpB;UAEK;EACf,OAAO;EACP;EACA,yBAAyB;;;;;;;;;;;;;EAazB,WAAW;;;;;;;;EAQX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UCLe;;;;;;EAMf;;;;;;EAOA;;;;;;;;;;EAWA,yBAAyB;;;;UChDV;EACf,QAAQ;EACR,UAAU;EACV,+BAA+B;EAC/B,oBAAoB;EACpB,YAAY;EACZ;;;;;;;;;cAUW,gBAAgB,GAAG"}
|