@real-router/react 0.37.8 → 0.38.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 +7 -6
- package/dist/cjs/{Await-BlAgOU-r.d.ts → Await-C1cvOY2U.d.ts} +1 -1
- package/dist/cjs/{Await-BlAgOU-r.d.ts.map → Await-C1cvOY2U.d.ts.map} +1 -1
- package/dist/cjs/{HttpStatusProvider-BgspYBOz.d.ts → HttpStatusProvider-vxiMth62.d.ts} +1 -1
- package/dist/cjs/{HttpStatusProvider-BgspYBOz.d.ts.map → HttpStatusProvider-vxiMth62.d.ts.map} +1 -1
- package/dist/cjs/{RouterErrorBoundary-cv6g6fyL.d.ts → RouterErrorBoundary-CacrxUKq.d.ts} +1 -1
- package/dist/cjs/{RouterErrorBoundary-cv6g6fyL.d.ts.map → RouterErrorBoundary-CacrxUKq.d.ts.map} +1 -1
- package/dist/cjs/{RouterProvider-aGzPGMdt.d.ts → RouterProvider-BKRTJidB.d.ts} +3 -3
- package/dist/cjs/{RouterProvider-aGzPGMdt.d.ts.map → RouterProvider-BKRTJidB.d.ts.map} +1 -1
- package/dist/cjs/{RouterProvider-mCkAm3kI.js → RouterProvider-CSxQyRg4.js} +2 -2
- package/dist/cjs/RouterProvider-CSxQyRg4.js.map +1 -0
- package/dist/cjs/RouterProviderCore-Bo1mRyVZ.js +2 -0
- package/dist/cjs/RouterProviderCore-Bo1mRyVZ.js.map +1 -0
- package/dist/cjs/{createHttpStatusSink-DT-Ec9Jq.js → createHttpStatusSink-CrJYxt4F.js} +2 -2
- package/dist/cjs/createHttpStatusSink-CrJYxt4F.js.map +1 -0
- package/dist/cjs/index.d.ts +4 -4
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/index.react-server.d.ts +2 -2
- package/dist/cjs/ink.d.ts +3 -3
- package/dist/cjs/ink.js +1 -1
- package/dist/cjs/ink.js.map +1 -1
- package/dist/cjs/legacy.d.ts +3 -3
- package/dist/cjs/legacy.js +1 -1
- package/dist/cjs/legacy.ssr.d.ts +2 -2
- package/dist/cjs/legacy.ssr.js +1 -1
- package/dist/cjs/ssr.d.ts +3 -3
- package/dist/cjs/ssr.js +1 -1
- package/dist/cjs/ssr.js.map +1 -1
- package/dist/cjs/ssr.react-server.d.ts +2 -2
- package/dist/cjs/{useDeferred-C2EfkbjK.d.ts → useDeferred-vxGvmdkN.d.ts} +1 -1
- package/dist/cjs/useDeferred-vxGvmdkN.d.ts.map +1 -0
- package/dist/cjs/{useRoute-D2vAzKWM.js → useRoute-cwvI_vQa.js} +1 -1
- package/dist/cjs/{useRoute-D2vAzKWM.js.map → useRoute-cwvI_vQa.js.map} +1 -1
- package/dist/cjs/{useRouteEnter-BMee5rPb.d.ts → useRouteEnter-DPy48OUb.d.ts} +1 -1
- package/dist/cjs/{useRouteEnter-BMee5rPb.d.ts.map → useRouteEnter-DPy48OUb.d.ts.map} +1 -1
- package/dist/cjs/{useRouterTransition-DC4JuM-k.d.ts → useRouterTransition-v0sri3EI.d.ts} +2 -2
- package/dist/cjs/{useRouterTransition-DC4JuM-k.d.ts.map → useRouterTransition-v0sri3EI.d.ts.map} +1 -1
- package/dist/esm/{Await-BlAgOU-r.d.mts → Await-imAt8sxf.d.mts} +1 -1
- package/dist/esm/{Await-BlAgOU-r.d.mts.map → Await-imAt8sxf.d.mts.map} +1 -1
- package/dist/esm/{HttpStatusProvider-BgspYBOz.d.mts → HttpStatusProvider-baKExhAC.d.mts} +1 -1
- package/dist/esm/{HttpStatusProvider-BgspYBOz.d.mts.map → HttpStatusProvider-baKExhAC.d.mts.map} +1 -1
- package/dist/esm/{RouterErrorBoundary-cv6g6fyL.d.mts → RouterErrorBoundary-mrfP832K.d.mts} +1 -1
- package/dist/esm/{RouterErrorBoundary-cv6g6fyL.d.mts.map → RouterErrorBoundary-mrfP832K.d.mts.map} +1 -1
- package/dist/esm/{RouterProvider--oNOnNfV.d.mts → RouterProvider-JAcMzFW_.d.mts} +3 -3
- package/dist/esm/{RouterProvider--oNOnNfV.d.mts.map → RouterProvider-JAcMzFW_.d.mts.map} +1 -1
- package/dist/esm/{RouterProvider-DgJycm0h.mjs → RouterProvider-LiVYuzMt.mjs} +2 -2
- package/dist/esm/RouterProvider-LiVYuzMt.mjs.map +1 -0
- package/dist/esm/RouterProviderCore-CEpbHZE7.mjs +2 -0
- package/dist/esm/RouterProviderCore-CEpbHZE7.mjs.map +1 -0
- package/dist/esm/{createHttpStatusSink-D3tbAjzC.mjs → createHttpStatusSink-D7Zq43u7.mjs} +2 -2
- package/dist/esm/{createHttpStatusSink-D3tbAjzC.mjs.map → createHttpStatusSink-D7Zq43u7.mjs.map} +1 -1
- package/dist/esm/index.d.mts +4 -4
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/index.react-server.d.mts +2 -2
- package/dist/esm/ink.d.mts +3 -3
- package/dist/esm/ink.mjs +1 -1
- package/dist/esm/ink.mjs.map +1 -1
- package/dist/esm/legacy.d.mts +3 -3
- package/dist/esm/legacy.mjs +1 -1
- package/dist/esm/legacy.ssr.d.mts +2 -2
- package/dist/esm/legacy.ssr.mjs +1 -1
- package/dist/esm/ssr.d.mts +3 -3
- package/dist/esm/ssr.mjs +1 -1
- package/dist/esm/ssr.mjs.map +1 -1
- package/dist/esm/ssr.react-server.d.mts +2 -2
- package/dist/esm/{useDeferred-C2EfkbjK.d.mts → useDeferred-bFMRFRsa.d.mts} +1 -1
- package/dist/esm/useDeferred-bFMRFRsa.d.mts.map +1 -0
- package/dist/esm/{useRoute-5MF3j-9P.mjs → useRoute-DdVdBFFb.mjs} +1 -1
- package/dist/esm/{useRoute-5MF3j-9P.mjs.map → useRoute-DdVdBFFb.mjs.map} +1 -1
- package/dist/esm/{useRouteEnter-BMee5rPb.d.mts → useRouteEnter-DMA3UB9O.d.mts} +1 -1
- package/dist/esm/{useRouteEnter-BMee5rPb.d.mts.map → useRouteEnter-DMA3UB9O.d.mts.map} +1 -1
- package/dist/esm/{useRouterTransition-8mqn_pj3.d.mts → useRouterTransition-QPsImlic.d.mts} +2 -2
- package/dist/esm/{useRouterTransition-8mqn_pj3.d.mts.map → useRouterTransition-QPsImlic.d.mts.map} +1 -1
- package/package.json +6 -6
- package/dist/cjs/RouterProvider-mCkAm3kI.js.map +0 -1
- package/dist/cjs/RouterProviderCore-C9Xvihrw.js +0 -2
- package/dist/cjs/RouterProviderCore-C9Xvihrw.js.map +0 -1
- package/dist/cjs/createHttpStatusSink-DT-Ec9Jq.js.map +0 -1
- package/dist/cjs/useDeferred-C2EfkbjK.d.ts.map +0 -1
- package/dist/esm/RouterProvider-DgJycm0h.mjs.map +0 -1
- package/dist/esm/RouterProviderCore-DaqIZrwX.mjs +0 -2
- package/dist/esm/RouterProviderCore-DaqIZrwX.mjs.map +0 -1
- package/dist/esm/useDeferred-C2EfkbjK.d.mts.map +0 -1
package/dist/esm/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Activity as e,Children as t,Fragment as n,Suspense as r,isValidElement as i,useEffect as a,useLayoutEffect as o,useMemo as s,useRef as c,useState as l}from"react";import{UNKNOWN_ROUTE as u,events as d}from"@real-router/core";import{startsWithSegment as f}from"@real-router/route-utils";import{Fragment as p,jsx as m}from"react/jsx-runtime";import{a as h,h as g,i as _,m as v,n as y,r as b}from"./RouterProviderCore-CEpbHZE7.mjs";import{n as x,t as S}from"./RouterProvider-LiVYuzMt.mjs";import{t as C}from"./useRoute-DdVdBFFb.mjs";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:f(e,t)}function M(e,n){t.forEach(e,e=>{i(e)&&(A.has(e.type)?n.push(e):M(e.props.children,n))})}function N(t,i,a,o,s){let c=s===void 0?t:m(r,{fallback:s,children:t});return a?m(e,{mode:o,children:c},i):m(n,{children:c},i)}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,r,i){i.selfFound&&t===r?e.push(N(i.selfChildren,`__route-view-self__`,!1,`visible`,i.selfFallback)):t===u&&i.notFoundChildren!==null&&e.push(m(n,{children:i.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}=v(e),r=c(null);r.current??=new Set;let i=r.current,o=s(()=>{let e=[];return M(t,e),e},[t]),l=n?.name??null,{rendered:u,activatedName:d}=s(()=>{if(l===null)return{rendered:[],activatedName:null};let t=L(o,l,e,i);return{rendered:t.rendered,activatedName:t.activatedName}},[o,l,e,i]);return a(()=>{d!==null&&i.add(d)},[d,i]),u.length>0?m(p,{children:u}):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,r,i=!1,a=t=>{let n=e.buildUrl;if(n!==void 0)try{let e=t.context?.url?.hash,r=n(t.name,t.params,t.search,e?{hash:e}:void 0);return r===void 0?void 0:new URL(r,globalThis.location.href).href}catch{return}},o=()=>{let t=e.getState();return t!==void 0&&a(t)===globalThis.location.href},s=()=>{o()?n===void 0&&(t=!1):n===void 0?t=!0:r=globalThis.location.href};globalThis.addEventListener(`popstate`,s);let c=E(e),l=()=>{n=void 0,t=r!==void 0,i=t,r=void 0},u=[c.addEventListener(d.TRANSITION_START,e=>{n=e,t&&!i&&o()&&(t=!1)}),c.addEventListener(d.TRANSITION_SUCCESS,l),c.addEventListener(d.TRANSITION_ERROR,e=>{if(n===void 0||e?.context===n.context){l();return}let t=e===void 0?void 0:a(e);(t===void 0||t===r)&&(r=void 0)}),c.addEventListener(d.TRANSITION_CANCEL,l),e.subscribeLeave(()=>{document.documentElement.dataset.navDirection=t?`back`:`forward`,t=!1})];return{destroy:()=>{for(let e of u)e();globalThis.removeEventListener(`popstate`,s),delete document.documentElement.dataset.navDirection}}}function H(e,t){let n=g(),r=c(e),i=t?.skipSameRoute??!0;o(()=>{r.current=e}),a(()=>n.subscribeLeave(T(e=>r.current(e),{skipSameRoute:i})),[n,i])}function U(e,t){let{route:n,previousRoute:r}=C(),i=c(e),[s]=l(()=>w()),u=t?.skipSameRoute??!0;o(()=>{i.current=e}),a(()=>{let e=s(n,r,u);e&&i.current(e)},[s,n,r,u])}export{x as Link,z as RouteView,h as RouterErrorBoundary,S as RouterProvider,V as createDirectionTracker,_ as useNavigator,C as useRoute,U as useRouteEnter,H as useRouteExit,v as useRouteNode,b as useRouteUtils,g as useRouter,y as useRouterTransition};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["useRoute","RouterErrorBoundary","useRouter","useNavigator","useRouteNode","useRouterTransition","useRouteUtils","Link","RouterProvider","Fragment$1","Match","Self","NotFound","MARKER_TYPES","isSegmentMatch","fullSegmentName","exact","routeName","startsWithSegment","collectElements","Children","children","isValidElement","child","result","renderSlotElement","content","fallback","slotChildren","jsx","Suspense","keepAlive","Activity","key","Fragment","recordFallback","slots","processMatch","matchProps","nodeName","segment","alreadyActive","hasBeenActivated","appendFallback","rendered","UNKNOWN_ROUTE","buildRenderList","activatedName","elements","RouteViewRoot","hasBeenActivatedRef","useRef","useMemo","collected","route","useEffect","RouteView","NOOP_INSTANCE","createDirectionTracker","popstateFlag","inFlight","replay","passedOn","hrefOf","buildUrl","router","hash","state","url","landsOnRouterState","onPopstate","api","getPluginApi","onSettled","unsubs","events","toState","href","unsub","useRouteExit","handlerRef","handler","skipSameRoute","options","useLayoutEffect","guardLeaveListener","context","useRouteEnter","gate","useState","createRouteEnterGate","previousRoute"],"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 { Params, Router, SearchParams, State } from \"@real-router/core\";\n\ntype BuildUrl = (\n name: string,\n params: Params,\n search?: SearchParams,\n options?: { hash?: string },\n) => string | undefined;\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 * - A `popstate` that arrives while a transition is in flight arms the\n * flag of the transition after it, which is the one a URL plugin starts\n * for it.\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 // The `toState` the transition in flight was announced with.\n let inFlight: State | undefined;\n // The address of a popstate that arrived while a transition was in flight.\n // A URL plugin starts its traversal after that transition, so its flag is\n // kept apart from the one the transition in flight may own.\n let replay: string | undefined;\n // The last transition passed the flag on.\n let passedOn = 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\n // The address the URL plugin prints a state at, or `undefined` without\n // one, or when its `buildUrl` throws or answers none.\n const hrefOf = (state: State): string | undefined => {\n const buildUrl = router.buildUrl as BuildUrl | undefined;\n\n if (buildUrl === undefined) {\n return undefined;\n }\n\n try {\n const hash = (state.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n const url = buildUrl(\n state.name,\n state.params,\n state.search,\n hash ? { hash } : undefined,\n );\n\n return url === undefined\n ? undefined\n : new URL(url, globalThis.location.href).href;\n } catch {\n return undefined;\n }\n };\n\n // ⚑ A traversal onto the URL of the router's own state starts no\n // transition: a URL plugin's return after a refused Back or Forward\n // (#2740), or a Back onto an entry holding that state. The URL comes from\n // the URL plugin's `buildUrl`; without one, every popstate arms the flag.\n const landsOnRouterState = (): boolean => {\n const state = router.getState();\n\n return state !== undefined && hrefOf(state) === globalThis.location.href;\n };\n\n const onPopstate = (): void => {\n if (landsOnRouterState()) {\n // The URL plugin returns after a traversal it refused or one a guard\n // cancelled quietly, and drops the popstate that waited behind it, so\n // the flag that popstate's replay would have spent ends here.\n if (inFlight === undefined) {\n popstateFlag = false;\n }\n\n return;\n }\n\n if (inFlight === undefined) {\n popstateFlag = true;\n } else {\n replay = globalThis.location.href;\n }\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 // The flag of a popstate that arrived during the transition passes to the\n // next one; the transition's own, unspent, ends with it.\n const onSettled = (): void => {\n inFlight = undefined;\n popstateFlag = replay !== undefined;\n passedOn = popstateFlag;\n replay = undefined;\n };\n\n // Core also reports a refusal that starts no transition on\n // `TRANSITION_ERROR`, and may do so while another transition runs. A\n // transition's own error carries a `toState` with that transition's\n // `context`, so another one does not settle it (#2779). With nothing in\n // flight every error settles: the `SAME_STATES` arc above spends the flag\n // that way.\n const onError = (toState: State | undefined): void => {\n if (inFlight === undefined || toState?.context === inFlight.context) {\n onSettled();\n\n return;\n }\n\n // A popstate that arrived while the transition runs may be the one this\n // refusal answers: a URL plugin handles a popstate that arrives during a\n // programmatic transition on the spot. It is, unless the refusal names\n // another address.\n const href = toState === undefined ? undefined : hrefOf(toState);\n\n if (href === undefined || href === replay) {\n replay = undefined;\n }\n };\n\n const unsubs = [\n api.addEventListener(events.TRANSITION_START, (toState: State) => {\n inFlight = toState;\n\n // A flag armed between transitions that finds the router's address is a\n // return's: it landed before the write of a navigation committed on its\n // way, so its popstate read another address (#2879). A History plugin\n // starts a traversal within its popstate, at the address that popstate\n // read. A flag passed on is left alone: the plugin can write the router's\n // URL over the entry its replay reached.\n if (popstateFlag && !passedOn && landsOnRouterState()) {\n popstateFlag = false;\n }\n }),\n api.addEventListener(events.TRANSITION_SUCCESS, onSettled),\n api.addEventListener(events.TRANSITION_ERROR, onError),\n api.addEventListener(events.TRANSITION_CANCEL, onSettled),\n router.subscribeLeave(() => {\n document.documentElement.dataset.navDirection = popstateFlag\n ? \"back\"\n : \"forward\";\n popstateFlag = 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** (a value that\n * is not an `Error` arrives wrapped in one) and emits `TRANSITION_ERROR` —\n * it is NOT re-coded to `TRANSITION_CANCELLED` (that arises when the\n * navigation's `signal` aborts: a superseding navigation, `stop()`,\n * `dispose()`, or an external `opts.signal`). A handler that rejects with a\n * `RouterError(TRANSITION_CANCELLED)` itself cancels the navigation quietly:\n * `navigate()` rejects with that error and the router emits\n * `TRANSITION_CANCEL` instead (#2787). A handler that rejects with the\n * error the router ended ANOTHER navigation with — it awaited that\n * navigation's work — fails this one with `CANNOT_DEACTIVATE` (#2786).\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":"A,kqBAEA,SAAgBU,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgBC,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgBC,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAMC,EAAqC,IAAI,IAAI,CAACH,EAAOC,EAAMC,CAAQ,CAAC,EAgB1E,SAASE,EACP,EACA,EACA,EACS,CAST,OARIC,IAAoB,GACf,GAGLC,EACKC,IAAcF,EAGhBG,EAAkBD,EAAWF,CAAe,CACrD,CAEA,SAAgBI,EACd,EACA,EACM,CAYNC,EAAS,QAAQC,EAAW,GAAU,CAC/BC,EAAeC,CAAK,IAIrBV,EAAa,IAAIU,EAAM,IAAI,EAC7BC,EAAO,KAAKD,CAAK,EAEjBJ,EACGI,EAAM,MAA2C,SAClDC,CACF,EAEJ,CAAC,CACH,CAEA,SAASC,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAMC,EACJC,IAAa,IAAA,GACXC,EAEAC,EAACC,EAAD,CAAoB,WAAW,SAAAF,CAAuB,CAAA,EAW1D,OARIG,EAEAF,EAACG,EAAD,CAAgB,OACb,SAAAN,CACO,EAFiBO,CAEj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ACnEa,EAAU,EAEV,MACF,CAMA,IAAMI,EAAOD,IAAY,IAAA,GAAY,IAAA,GAAYb,EAAOa,CAAO,GAE3DC,IAAS,IAAA,IAAaA,IAAShB,KACjC,EAAS,IAAA,GAEb,CAiBuD,EACrDU,EAAI,iBAAiBI,EAAO,kBAAmBF,CAAS,EACxDR,EAAO,mBAAqB,CAC1B,SAAS,gBAAgB,QAAQ,aAAeN,EAC5C,OACA,UACJ,EAAe,EACjB,CAAC,CACH,EAEA,MAAO,CACL,YAAe,CACb,IAAK,IAAMmB,KAASJ,EAClBI,EAAM,EAGR,WAAW,oBAAoB,WAAYR,CAAU,EACrD,OAAO,SAAS,gBAAgB,QAAQ,YAC1C,CACF,CACF,CClEA,SAAgBS,EACd,EACA,EACM,CACN,IAAMd,EAAS/D,EAAU,EACnB8E,EAAa7B,EAAO8B,CAAO,EAC3BC,EAAgBC,GAAS,eAAiB,GAQhDC,MAAsB,CACpB,EAAW,QAAUH,CACvB,CAAC,EAED1B,MAKSU,EAAO,eACZoB,EAAoB,GAAYL,EAAW,QAAQM,CAAO,EAAG,CAC3D,eACF,CAAC,CACH,EACC,CAACrB,EAAQiB,CAAa,CAAC,CAC5B,CCtEA,SAAgBK,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBvF,EAAS,EACpCgF,EAAa7B,EAAO8B,CAAO,EAW3B,CAACO,GAAQC,MAAeC,EAAqB,CAAC,EAC9CR,EAAgBC,GAAS,eAAiB,GAKhDC,MAAsB,CACpB,EAAW,QAAUH,CACvB,CAAC,EAED1B,MAAgB,CACd,IAAM+B,EAAUE,EAAKlC,EAAOqC,EAAeT,CAAa,EAEpDI,GACFN,EAAW,QAAQM,CAAO,CAE9B,EAAG,CAACE,EAAMlC,EAAOqC,EAAeT,CAAa,CAAC,CAChD,C"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["Activity","Children","Fragment","Suspense","isValidElement","useEffect","useLayoutEffect","useMemo","useRef","useState","UNKNOWN_ROUTE","events","startsWithSegment","Fragment$1","jsx","RouterErrorBoundary","useRouter","useNavigator","useRouteNode","useRouterTransition","useRouteUtils","Link","RouterProvider","useRoute","createRouteEnterGate","guardLeaveListener","getPluginApi","Match","_props","Self","NotFound","MARKER_TYPES","isSegmentMatch","routeName","fullSegmentName","exact","collectElements","children","result","child","renderSlotElement","slotChildren","key","keepAlive","mode","fallback","content","recordFallback","slots","processMatch","nodeName","hasBeenActivated","alreadyActive","matchProps","segment","appendFallback","rendered","buildRenderList","elements","activatedName","RouteViewRoot","route","hasBeenActivatedRef","collected","RouteView","NOOP_INSTANCE","createDirectionTracker","router","popstateFlag","inFlight","replay","passedOn","hrefOf","state","buildUrl","hash","url","landsOnRouterState","onPopstate","api","onSettled","unsubs","toState","href","unsub","useRouteExit","handler","options","handlerRef","skipSameRoute","context","useRouteEnter","previousRoute","gate"],"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 { Params, Router, SearchParams, State } from \"@real-router/core\";\n\ntype BuildUrl = (\n name: string,\n params: Params,\n search?: SearchParams,\n options?: { hash?: string },\n) => string | undefined;\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 * - A `popstate` that arrives while a transition is in flight arms the\n * flag of the transition after it, which is the one a URL plugin starts\n * for it.\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 // The `toState` the transition in flight was announced with.\n let inFlight: State | undefined;\n // The address of a popstate that arrived while a transition was in flight.\n // A URL plugin starts its traversal after that transition, so its flag is\n // kept apart from the one the transition in flight may own.\n let replay: string | undefined;\n // The last transition passed the flag on.\n let passedOn = 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\n // The address the URL plugin prints a state at, or `undefined` without\n // one, or when its `buildUrl` throws or answers none.\n const hrefOf = (state: State): string | undefined => {\n const buildUrl = router.buildUrl as BuildUrl | undefined;\n\n if (buildUrl === undefined) {\n return undefined;\n }\n\n try {\n const hash = (state.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n const url = buildUrl(\n state.name,\n state.params,\n state.search,\n hash ? { hash } : undefined,\n );\n\n return url === undefined\n ? undefined\n : new URL(url, globalThis.location.href).href;\n } catch {\n return undefined;\n }\n };\n\n // ⚑ A traversal onto the URL of the router's own state starts no\n // transition: a URL plugin's return after a refused Back or Forward\n // (#2740), or a Back onto an entry holding that state. The URL comes from\n // the URL plugin's `buildUrl`; without one, every popstate arms the flag.\n const landsOnRouterState = (): boolean => {\n const state = router.getState();\n\n return state !== undefined && hrefOf(state) === globalThis.location.href;\n };\n\n const onPopstate = (): void => {\n if (landsOnRouterState()) {\n // The URL plugin returns after a traversal it refused or one a guard\n // cancelled quietly, and drops the popstate that waited behind it, so\n // the flag that popstate's replay would have spent ends here.\n if (inFlight === undefined) {\n popstateFlag = false;\n }\n\n return;\n }\n\n if (inFlight === undefined) {\n popstateFlag = true;\n } else {\n replay = globalThis.location.href;\n }\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 // The flag of a popstate that arrived during the transition passes to the\n // next one; the transition's own, unspent, ends with it.\n const onSettled = (): void => {\n inFlight = undefined;\n popstateFlag = replay !== undefined;\n passedOn = popstateFlag;\n replay = undefined;\n };\n\n // Core also reports a refusal that starts no transition on\n // `TRANSITION_ERROR`, and may do so while another transition runs. A\n // transition's own error carries a `toState` with that transition's\n // `context`, so another one does not settle it (#2779). With nothing in\n // flight every error settles: the `SAME_STATES` arc above spends the flag\n // that way.\n const onError = (toState: State | undefined): void => {\n if (inFlight === undefined || toState?.context === inFlight.context) {\n onSettled();\n\n return;\n }\n\n // A popstate that arrived while the transition runs may be the one this\n // refusal answers: a URL plugin handles a popstate that arrives during a\n // programmatic transition on the spot. It is, unless the refusal names\n // another address.\n const href = toState === undefined ? undefined : hrefOf(toState);\n\n if (href === undefined || href === replay) {\n replay = undefined;\n }\n };\n\n const unsubs = [\n api.addEventListener(events.TRANSITION_START, (toState: State) => {\n inFlight = toState;\n\n // A flag armed between transitions that finds the router's address is a\n // return's: it landed before the write of a navigation committed on its\n // way, so its popstate read another address (#2879). A History plugin\n // starts a traversal within its popstate, at the address that popstate\n // read. A flag passed on is left alone: the plugin can write the router's\n // URL over the entry its replay reached.\n if (popstateFlag && !passedOn && landsOnRouterState()) {\n popstateFlag = false;\n }\n }),\n api.addEventListener(events.TRANSITION_SUCCESS, onSettled),\n api.addEventListener(events.TRANSITION_ERROR, onError),\n api.addEventListener(events.TRANSITION_CANCEL, onSettled),\n router.subscribeLeave(() => {\n document.documentElement.dataset.navDirection = popstateFlag\n ? \"back\"\n : \"forward\";\n popstateFlag = 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** (a value that\n * is not an `Error` arrives wrapped in one) and emits `TRANSITION_ERROR` —\n * it is NOT re-coded to `TRANSITION_CANCELLED` (that arises when the\n * navigation's `signal` aborts: a superseding navigation, `stop()`,\n * `dispose()`, or an external `opts.signal`). A handler that rejects with a\n * `RouterError(TRANSITION_CANCELLED)` itself cancels the navigation quietly:\n * `navigate()` rejects with that error and the router emits\n * `TRANSITION_CANCEL` instead (#2787). A handler that rejects with the\n * error the router ended ANOTHER navigation with — it awaited that\n * navigation's work — fails this one with `CANNOT_DEACTIVATE` (#2786).\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":"A,kqBAEA,SAAgB2B,EAAMC,EAA0B,CAC9C,OAAO,IACT,CAEAD,EAAM,YAAc,kBAEpB,SAAgBE,EAAKD,EAAyB,CAC5C,OAAO,IACT,CAEAC,EAAK,YAAc,iBAEnB,SAAgBC,EAASF,EAA6B,CACpD,OAAO,IACT,CAEAE,EAAS,YAAc,qBCTvB,MAAMC,EAAqC,IAAI,IAAI,CAACJ,EAAOE,EAAMC,CAAQ,CAAC,EAgB1E,SAASE,EACPC,EACAC,EACAC,EACS,CAST,OARID,IAAoB,GACf,GAGLC,EACKF,IAAcC,EAGhBtB,EAAkBqB,EAAWC,CAAe,CACrD,CAEA,SAAgBE,EACdC,EACAC,EACM,CAYNrC,EAAS,QAAQoC,EAAWE,GAAU,CAC/BnC,EAAemC,CAAK,IAIrBR,EAAa,IAAIQ,EAAM,IAAI,EAC7BD,EAAO,KAAKC,CAAK,EAEjBH,EACGG,EAAM,MAA2C,SAClDD,CACF,EAEJ,CAAC,CACH,CAEA,SAASE,EACPC,EACAC,EACAC,EACAC,EACAC,EACc,CACd,IAAMC,EACJD,IAAa,IAAA,GACXJ,EAEA3B,EAACX,EAAD,CAAoB0C,WAAW,SAA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AW,QAAQE,CAAO,CAE9B,EAAG,CAACG,EAAMhC,EAAO+B,EAAeH,CAAa,CAAC,CAChD,C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as
|
|
1
|
+
import { n as RouterErrorBoundaryProps, r as LinkProps } from "./RouterErrorBoundary-mrfP832K.mjs";
|
|
2
|
+
import { a as RouteExitContext, d as NotFoundProps, f as RouteViewProps, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-DMA3UB9O.mjs";
|
|
3
3
|
import { Navigator } from "@real-router/core";
|
|
4
4
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
5
5
|
export type { LinkProps, Navigator, RouteEnterContext, RouteEnterHandler, RouteExitContext, RouteExitHandler, MatchProps as RouteViewMatchProps, NotFoundProps as RouteViewNotFoundProps, RouteViewProps, SelfProps as RouteViewSelfProps, RouterErrorBoundaryProps, RouterTransitionSnapshot, UseRouteEnterOptions, UseRouteExitOptions };
|
package/dist/esm/ink.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as RouterErrorBoundaryProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-cv6g6fyL.mjs";
|
|
2
|
-
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-8mqn_pj3.mjs";
|
|
3
|
-
import { FC, ReactNode } from "react";
|
|
4
1
|
import { NavigationOptions, Navigator, Params, Router, SearchParams } from "@real-router/core";
|
|
2
|
+
import { FC, ReactNode } from "react";
|
|
3
|
+
import { n as RouterErrorBoundaryProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-mrfP832K.mjs";
|
|
4
|
+
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-QPsImlic.mjs";
|
|
5
5
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
6
6
|
interface InkLinkProps<P extends Params = Params> {
|
|
7
7
|
routeName: string;
|
package/dist/esm/ink.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Text as e,useFocus as t,useInput as n}from"ink";import{memo as r}from"react";import{n as i,r as a,t as o}from"./useRoute-DdVdBFFb.mjs";import{a as s,d as c,h as l,i as u,m as d,n as f,o as p,r as m,t as h}from"./RouterProviderCore-CEpbHZE7.mjs";import{jsx as g}from"react/jsx-runtime";function _(e,t,n,r,i){return e?n??r??i:t?r??i:i}function v(e,t){return e.routeName===t.routeName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.color===t.color&&e.activeColor===t.activeColor&&e.focusColor===t.focusColor&&e.inverse===t.inverse&&e.activeInverse===t.activeInverse&&e.focusInverse===t.focusInverse&&e.id===t.id&&e.autoFocus===t.autoFocus&&e.onSelect===t.onSelect&&e.children===t.children&&c(e.routeParams,t.routeParams)&&c(e.routeSearch,t.routeSearch)&&c(e.routeOptions,t.routeOptions)}const y=r(({routeName:r,routeParams:o,routeSearch:s,routeOptions:c=i,activeStrict:u=!1,ignoreQueryParams:d=!0,color:f,activeColor:m,focusColor:h,inverse:v,activeInverse:y,focusInverse:b,id:x,autoFocus:S,onSelect:C,children:w})=>{let T=l(),{isFocused:E}=t({...x!==void 0&&{id:x},...S!==void 0&&{autoFocus:S}}),D=p(r,o,s,u,d),O=o??a;n((e,t)=>{if(t.return){try{C?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}T.navigate(r,O,s,c).catch(()=>{})}},{isActive:E});let k=_(E,D,h,m,f),A=_(E,D,b,y,v),j={};return k!==void 0&&(j.color=k),A!==void 0&&(j.inverse=A),g(e,{...j,children:w})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>g(h,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,s as RouterErrorBoundary,u as useNavigator,o as useRoute,d as useRouteNode,m as useRouteUtils,l as useRouter,f as useRouterTransition};
|
|
2
2
|
//# sourceMappingURL=ink.mjs.map
|
package/dist/esm/ink.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ink.mjs","names":["EMPTY_OPTIONS","EMPTY_PARAMS","useRoute","RouterErrorBoundary","shallowEqual","useRouter","useNavigator","useRouteNode","useRouterTransition","useIsActiveRoute","useRouteUtils","RouterProviderCore","pickPriority","isFocused","focusValue","activeValue","baseValue","
|
|
1
|
+
{"version":3,"file":"ink.mjs","names":["Text","useFocus","useInput","memo","EMPTY_OPTIONS","EMPTY_PARAMS","useRoute","RouterErrorBoundary","shallowEqual","useRouter","useNavigator","useRouteNode","useRouterTransition","useIsActiveRoute","useRouteUtils","RouterProviderCore","jsx","pickPriority","isFocused","isRouteActive","focusValue","activeValue","baseValue","areInkLinkPropsEqual","prev","next","InkLink","routeName","routeParams","routeSearch","routeOptions","activeStrict","ignoreQueryParams","color","activeColor","focusColor","inverse","activeInverse","focusInverse","id","autoFocus","onSelect","children","router","paramsForNav","_input","key","error","finalColor","finalInverse","textProps","InkRouterProvider"],"sources":["../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"sourcesContent":["import { Text, useFocus, useInput } from \"ink\";\nimport { memo } from \"react\";\n\nimport { EMPTY_OPTIONS, EMPTY_PARAMS } from \"../constants\";\nimport { shallowEqual } from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { InkLinkProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\n/**\n * Pick the most specific value across focus / active / base priority.\n * Focus wins over active; active wins over base. Each layer falls through\n * to the next when its value is undefined, matching the original explicit\n * if/else cascade for both `color` and `inverse`.\n */\nfunction pickPriority<T>(\n isFocused: boolean,\n isRouteActive: boolean,\n focusValue: T | undefined,\n activeValue: T | undefined,\n baseValue: T | undefined,\n): T | undefined {\n if (isFocused) {\n return focusValue ?? activeValue ?? baseValue;\n }\n\n if (isRouteActive) {\n return activeValue ?? baseValue;\n }\n\n return baseValue;\n}\n\nfunction areInkLinkPropsEqual(\n prev: Readonly<InkLinkProps>,\n next: Readonly<InkLinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.color === next.color &&\n prev.activeColor === next.activeColor &&\n prev.focusColor === next.focusColor &&\n prev.inverse === next.inverse &&\n prev.activeInverse === next.activeInverse &&\n prev.focusInverse === next.focusInverse &&\n prev.id === next.id &&\n prev.autoFocus === next.autoFocus &&\n prev.onSelect === next.onSelect &&\n prev.children === next.children &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeSearch, next.routeSearch) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst InkLinkImpl: FC<InkLinkProps> = ({\n routeName,\n routeParams,\n routeSearch,\n routeOptions = EMPTY_OPTIONS,\n activeStrict = false,\n ignoreQueryParams = true,\n color,\n activeColor,\n focusColor,\n inverse,\n activeInverse,\n focusInverse,\n id,\n autoFocus,\n onSelect,\n children,\n}) => {\n const router = useRouter();\n const { isFocused } = useFocus({\n ...(id !== undefined && { id }),\n ...(autoFocus !== undefined && { autoFocus }),\n });\n\n // Pass `routeParams` straight through (possibly `undefined`) so a no-params\n // `<InkLink>` and a manual `useIsActiveRoute(routeName)` share ONE cached\n // active-route source — `createActiveRouteSource` keys `undefined` as \"\" but\n // EMPTY_PARAMS ({}) as \"{}\", so defaulting before the call would split the\n // same question into a second eager subscription (#776).\n const isRouteActive = useIsActiveRoute(\n routeName,\n routeParams,\n routeSearch,\n activeStrict,\n ignoreQueryParams,\n );\n\n // Navigation needs a concrete params object — default here only.\n const paramsForNav = routeParams ?? EMPTY_PARAMS;\n\n // No useCallback: `useInput` consumes the handler via its own internal\n // ref; a stable identity provides no cache-bail-out benefit here. Same\n // reasoning as Link's handleClick.\n useInput(\n (_input, key) => {\n if (key.return) {\n // Isolate a throwing `onSelect`: unlike the DOM `<Link>` (where the\n // browser contains event-listener exceptions), an uncaught throw here\n // escapes into ink's stdin handler → `uncaughtException` crashes a real\n // CLI, and it also swallows the navigation below. Log and still\n // navigate — mirrors `route-announcer`'s consumer-callback isolation.\n try {\n onSelect?.();\n } catch (error) {\n console.error(\n \"[real-router] InkLink onSelect threw; proceeding with navigation.\",\n error,\n );\n }\n // Query channel at position 3 (RFC-4 M2 / #1548) — from `routeSearch`;\n // options at position 4.\n router\n .navigate(routeName, paramsForNav, routeSearch, routeOptions)\n .catch(() => {});\n }\n },\n { isActive: isFocused },\n );\n\n const finalColor = pickPriority(\n isFocused,\n isRouteActive,\n focusColor,\n activeColor,\n color,\n );\n const finalInverse = pickPriority(\n isFocused,\n isRouteActive,\n focusInverse,\n activeInverse,\n inverse,\n );\n\n const textProps: { color?: string; inverse?: boolean } = {};\n\n if (finalColor !== undefined) {\n textProps.color = finalColor;\n }\n\n if (finalInverse !== undefined) {\n textProps.inverse = finalInverse;\n }\n\n return <Text {...textProps}>{children}</Text>;\n};\n\nexport const InkLink: FC<InkLinkProps> = memo(\n InkLinkImpl,\n areInkLinkPropsEqual,\n);\n\nInkLink.displayName = \"InkLink\";\n","import { RouterProviderCore } from \"../RouterProviderCore\";\n\nimport type { InkRouterProviderProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\n// Composes the DOM-free RouterProviderCore (not the full RouterProvider) so the\n// terminal /ink chunk never pulls in the scroll-spy / view-transitions /\n// announcer / scroll-restore factories — none can run without a DOM (#800).\nexport const InkRouterProvider: FC<InkRouterProviderProps> = ({\n router,\n children,\n}) => <RouterProviderCore router={router}>{children}</RouterProviderCore>;\n"],"mappings":"A,oSAiBA,SAASiB,EACPC,EACAC,EACAC,EACAC,EACAC,EACe,CASf,OARIJ,EACKE,GAAcC,GAAeC,EAGlCH,EACKE,GAAeC,EAGjBA,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,EACMgB,EAAehC,EACnBC,EACAC,EACAmB,EACAD,EACAD,CACF,EAEMc,EAAmD,CAAC,EAU1D,OARIF,IAAe,IAAA,KACjBE,EAAU,MAAQF,GAGhBC,IAAiB,IAAA,KACnBC,EAAU,QAAUD,GAGfjC,EAAChB,EAAD,CAAM,GAAIkD,EAAYR,UAAe,CAAA,CAC9C,EAIEnB,CACF,EAEAG,EAAQ,YAAc,UCzJtB,MAAayB,GAAiD,CAC5DR,SACAD,cACI1B,EAACD,EAAD,CAA4B4B,SAASD,UAA6B,CAAA,E"}
|
package/dist/esm/legacy.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-
|
|
1
|
+
import { i as Link, t as RouterProvider } from "./RouterProvider-JAcMzFW_.mjs";
|
|
2
|
+
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-mrfP832K.mjs";
|
|
3
|
+
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-QPsImlic.mjs";
|
|
4
4
|
import { Navigator } from "@real-router/core";
|
|
5
5
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
6
6
|
export { Link, type LinkProps, type Navigator, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, useNavigator, useRoute, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
|
package/dist/esm/legacy.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{n as e,t}from"./RouterProvider-LiVYuzMt.mjs";import{a as n,h as r,i,m as a,n as o,r as s}from"./RouterProviderCore-CEpbHZE7.mjs";import{t as c}from"./useRoute-DdVdBFFb.mjs";export{e as Link,n as RouterErrorBoundary,t as RouterProvider,i as useNavigator,c as useRoute,a as useRouteNode,s as useRouteUtils,r as useRouter,o as useRouterTransition};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as HttpStatusCode, c as StreamedProps, d as ClientOnly, f as ClientOnlyProps, i as createHttpStatusSink, l as ServerOnly, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, s as Streamed, t as HttpStatusProvider, u as ServerOnlyProps } from "./HttpStatusProvider-
|
|
2
|
-
import { t as useDeferred } from "./useDeferred-
|
|
1
|
+
import { a as HttpStatusCode, c as StreamedProps, d as ClientOnly, f as ClientOnlyProps, i as createHttpStatusSink, l as ServerOnly, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, s as Streamed, t as HttpStatusProvider, u as ServerOnlyProps } from "./HttpStatusProvider-baKExhAC.mjs";
|
|
2
|
+
import { t as useDeferred } from "./useDeferred-bFMRFRsa.mjs";
|
|
3
3
|
export { ClientOnly, type ClientOnlyProps, HttpStatusCode, type HttpStatusCodeProps, HttpStatusProvider, type HttpStatusProviderProps, type HttpStatusSink, ServerOnly, type ServerOnlyProps, Streamed, type StreamedProps, createHttpStatusSink, useDeferred };
|
package/dist/esm/legacy.ssr.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{s as ClientOnly,n as HttpStatusCode,r as HttpStatusProvider,o as ServerOnly,i as Streamed,t as createHttpStatusSink,a as useDeferred}from"./createHttpStatusSink-
|
|
1
|
+
export{s as ClientOnly,n as HttpStatusCode,r as HttpStatusProvider,o as ServerOnly,i as Streamed,t as createHttpStatusSink,a as useDeferred}from"./createHttpStatusSink-D7Zq43u7.mjs";
|
package/dist/esm/ssr.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as HttpStatusCode, c as StreamedProps, d as ClientOnly, f as ClientOnlyProps, i as createHttpStatusSink, l as ServerOnly, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, s as Streamed, t as HttpStatusProvider, u as ServerOnlyProps } from "./HttpStatusProvider-
|
|
2
|
-
import { t as
|
|
3
|
-
import {
|
|
1
|
+
import { a as HttpStatusCode, c as StreamedProps, d as ClientOnly, f as ClientOnlyProps, i as createHttpStatusSink, l as ServerOnly, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, s as Streamed, t as HttpStatusProvider, u as ServerOnlyProps } from "./HttpStatusProvider-baKExhAC.mjs";
|
|
2
|
+
import { n as AwaitProps, t as Await } from "./Await-imAt8sxf.mjs";
|
|
3
|
+
import { t as useDeferred } from "./useDeferred-bFMRFRsa.mjs";
|
|
4
4
|
export { Await, type AwaitProps, ClientOnly, type ClientOnlyProps, HttpStatusCode, type HttpStatusCodeProps, HttpStatusProvider, type HttpStatusProviderProps, type HttpStatusSink, ServerOnly, type ServerOnlyProps, Streamed, type StreamedProps, createHttpStatusSink, useDeferred };
|
package/dist/esm/ssr.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./createHttpStatusSink-
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./createHttpStatusSink-D7Zq43u7.mjs";import{use as s}from"react";function c({name:t,children:n}){return n(s(e(t)))}export{c as Await,a as ClientOnly,n as HttpStatusCode,i as HttpStatusProvider,r as ServerOnly,t as Streamed,o as createHttpStatusSink,e as useDeferred};
|
|
2
2
|
//# sourceMappingURL=ssr.mjs.map
|
package/dist/esm/ssr.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr.mjs","names":["useDeferred","Streamed","ServerOnly","HttpStatusProvider","ClientOnly","createHttpStatusSink","
|
|
1
|
+
{"version":3,"file":"ssr.mjs","names":["useDeferred","Streamed","ServerOnly","HttpStatusProvider","ClientOnly","createHttpStatusSink","use","Await","name","children","HttpStatusCode"],"sources":["../../src/components/Await.tsx"],"sourcesContent":["import { use } from \"react\";\n\nimport { useDeferred } from \"../hooks/useDeferred\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface AwaitProps<T> {\n /** Deferred key declared in the loader's `defer({ deferred: { <name>: ... } })`. */\n readonly name: string;\n /** Render the resolved value. Suspends while pending; throws inside the\n * nearest Error Boundary on rejection. */\n readonly children: (value: T) => ReactNode;\n}\n\n/**\n * Ergonomic wrapper around `useDeferred(name)` + React 19's `use(promise)`.\n *\n * ```tsx\n * <Suspense fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Suspense>\n * ```\n *\n * Equivalent to:\n *\n * ```tsx\n * function Inner() {\n * const reviews = use(useDeferred<Review[]>(\"reviews\"));\n * return <ReviewList items={reviews} />;\n * }\n * ```\n *\n * Pick `<Await>` for cross-adapter consistency with the SvelteKit\n * `{#await}` / Solid `<Await/>` shape; pick the inline `use(useDeferred(...))`\n * form if you prefer one fewer abstraction.\n */\nexport function Await<T = unknown>({\n name,\n children,\n}: AwaitProps<T>): ReactNode {\n const value = use(useDeferred<T>(name));\n\n return children(value);\n}\n"],"mappings":"A,yHAsCA,SAAgBO,EAAmB,CACjCC,OACAC,YAC2B,CAG3B,OAAOA,EAFOH,EAAIN,EAAeQ,CAAI,CAEjB,CAAC,CACvB,C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { c as StreamedProps, f as ClientOnlyProps, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, u as ServerOnlyProps } from "./HttpStatusProvider-
|
|
2
|
-
import { n as AwaitProps } from "./Await-
|
|
1
|
+
import { c as StreamedProps, f as ClientOnlyProps, n as HttpStatusProviderProps, o as HttpStatusCodeProps, r as HttpStatusSink, u as ServerOnlyProps } from "./HttpStatusProvider-baKExhAC.mjs";
|
|
2
|
+
import { n as AwaitProps } from "./Await-imAt8sxf.mjs";
|
|
3
3
|
export type { AwaitProps, ClientOnlyProps, HttpStatusCodeProps, HttpStatusProviderProps, HttpStatusSink, ServerOnlyProps, StreamedProps };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useDeferred-bFMRFRsa.d.mts","names":[],"sources":["../../src/hooks/useDeferred.tsx"],"mappings":";;;;;;;;;;;;;;;;;;;iBA0BgB,YAAY,aAAa,cAAc,QAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createContext as e,useContext as t}from"react";const n=e(null),r=e(null),i=e(null),a=Object.freeze({}),o=Object.freeze({}),s=new Promise(()=>{}),c=()=>{let e=t(n);if(!e)throw Error(`useRoute must be used within a RouterProvider`);if(!e.route)throw Error(`useRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?`);return e};export{i as a,s as i,o as n,n as o,a as r,r as s,c as t};
|
|
2
|
-
//# sourceMappingURL=useRoute-
|
|
2
|
+
//# sourceMappingURL=useRoute-DdVdBFFb.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRoute-
|
|
1
|
+
{"version":3,"file":"useRoute-DdVdBFFb.mjs","names":["createContext","useContext","RouteContext","RouterContext","NavigatorContext","EMPTY_PARAMS","EMPTY_OPTIONS","NEVER_PROMISE","useRoute","routeContext"],"sources":["../../src/context.ts","../../src/constants.ts","../../src/hooks/useRoute.tsx"],"sourcesContent":["import { createContext } from \"react\";\n\nimport type { RouteContext as RouteContextType } from \"./types\";\nimport type { Router, Navigator } from \"@real-router/core\";\n\n// All three contexts use the `<T | null>` shape with a `null` default. Hooks\n// (useRouter / useRoute / useNavigator) treat a `null` read as\n// \"RouterProvider missing\" and throw — this surfaces wiring mistakes loudly\n// instead of letting consumers chase an undefined router instance.\nexport const RouteContext = createContext<RouteContextType | null>(null);\n\nexport const RouterContext = createContext<Router | null>(null);\n\nexport const NavigatorContext = createContext<Navigator | null>(null);\n","export const EMPTY_PARAMS = Object.freeze({});\n\nexport const EMPTY_OPTIONS = Object.freeze({});\n\n// Singleton forever-pending promise — module-scope so `useDeferred(unknownKey)`\n// returns a stable reference across calls (Suspense boundary doesn't retry).\nexport const NEVER_PROMISE = new Promise<never>(() => {\n // Intentionally never resolves — surfaces a forever-pending Suspense boundary\n // when a key is requested that the loader never declared.\n});\n","import { useContext } from \"react\";\n\nimport { RouteContext } from \"../context\";\n\nimport type { RouteContext as RouteContextType } from \"../types\";\nimport type { Params, State } from \"@real-router/core\";\n\n/**\n * Return shape of `useRoute<P>()` — the context with `route` narrowed to\n * `State<P>` (non-nullable). Promoting the intersection to a named alias\n * keeps the function signature and the cast site in sync.\n */\ntype RouteHookResult<P extends Params = Params> = Omit<\n RouteContextType<P>,\n \"route\"\n> & { route: State<P> };\n\nexport const useRoute = <P extends Params = Params>(): RouteHookResult<P> => {\n const routeContext = useContext(RouteContext);\n\n if (!routeContext) {\n throw new Error(\"useRoute must be used within a RouterProvider\");\n }\n\n if (!routeContext.route) {\n throw new Error(\n \"useRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?\",\n );\n }\n\n return routeContext as RouteHookResult<P>;\n};\n"],"mappings":"A,sDASA,MAAaE,EAAeF,EAAuC,IAAI,EAE1DG,EAAgBH,EAA6B,IAAI,EAEjDI,EAAmBJ,EAAgC,IAAI,ECbvDK,EAAe,OAAO,OAAO,CAAC,CAAC,EAE/BC,EAAgB,OAAO,OAAO,CAAC,CAAC,EAIhCC,EAAgB,IAAI,YAAqB,CAGtD,CAAC,ECQYC,MAAgE,CAC3E,IAAMC,EAAeR,EAAWC,CAAY,EAE5C,GAAI,CAACO,EACH,MAAU,MAAM,+CAA+C,EAGjE,GAAI,CAACA,EAAa,MAChB,MAAU,MACR,mIACF,EAGF,OAAOA,CACT,E"}
|
|
@@ -290,4 +290,4 @@ interface UseRouteEnterOptions {
|
|
|
290
290
|
*/
|
|
291
291
|
declare function useRouteEnter(handler: RouteEnterHandler, options?: UseRouteEnterOptions): void;
|
|
292
292
|
export { RouteExitContext as a, useRouteExit as c, NotFoundProps as d, RouteViewProps as f, useRouteEnter as i, RouteView as l, RouteEnterHandler as n, RouteExitHandler as o, SelfProps as p, UseRouteEnterOptions as r, UseRouteExitOptions as s, RouteEnterContext as t, MatchProps as u };
|
|
293
|
-
//# sourceMappingURL=useRouteEnter-
|
|
293
|
+
//# sourceMappingURL=useRouteEnter-DMA3UB9O.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRouteEnter-
|
|
1
|
+
{"version":3,"file":"useRouteEnter-DMA3UB9O.d.mts","names":[],"sources":["../../src/components/modern/RouteView/types.ts","../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"mappings":";;UAEiB;;WAEN;;WAEA,UAAU;;UAGJ;;WAEN;;WAEA;;WAEA;;WAEA,WAAW;;WAEX,UAAU;;UAGJ;;;;;;;WAON,WAAW;;WAEX,UAAU;;UAGJ;;WAEN,UAAU;;iBClCL,MAAM,QAAQ;kBAAd;;;iBAMA,KAAK,QAAQ;kBAAb;;;iBAMA,SAAS,QAAQ;kBAAjB;;;iBCLP,gBACP,UACA,YACC,SAAS,kBAAkB;kBAHrB;;;cAgFI,kBAAS;;;;;UClFL;;EAEf,OAAO;;EAEP,WAAW;;;;;;;;EAQX,QAAQ;;UAGO;;;;;;EAMf;;KAGU,oBACV,SAAS,4BACC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmHI,aACd,SAAS,kBACT,UAAU;UC/IK;;EAEf,OAAO;;EAEP,eAAe;;KAGL,qBAAqB,SAAS;UAEzB;;;;;;EAMf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqFc,cACd,SAAS,mBACT,UAAU"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as RouteContext } from "./RouterErrorBoundary-
|
|
1
|
+
import { i as RouteContext } from "./RouterErrorBoundary-mrfP832K.mjs";
|
|
2
2
|
import { Navigator, Params, Router, State } from "@real-router/core";
|
|
3
3
|
import { RouteUtils } from "@real-router/route-utils";
|
|
4
4
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
@@ -40,4 +40,4 @@ declare const useRoute: <P extends Params = Params>() => RouteHookResult<P>;
|
|
|
40
40
|
declare function useRouteNode(nodeName: string): RouteContext;
|
|
41
41
|
declare function useRouterTransition(): RouterTransitionSnapshot;
|
|
42
42
|
export { useNavigator as a, useRouteUtils as i, useRouteNode as n, useRouter as o, useRoute as r, useRouterTransition as t };
|
|
43
|
-
//# sourceMappingURL=useRouterTransition-
|
|
43
|
+
//# sourceMappingURL=useRouterTransition-QPsImlic.d.mts.map
|
package/dist/esm/{useRouterTransition-8mqn_pj3.d.mts.map → useRouterTransition-QPsImlic.d.mts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRouterTransition-
|
|
1
|
+
{"version":3,"file":"useRouterTransition-QPsImlic.d.mts","names":["RouteContextType"],"sources":["../../src/hooks/useRouter.tsx","../../src/hooks/useNavigator.tsx","../../src/hooks/useRouteUtils.tsx","../../src/hooks/useRoute.tsx","../../src/hooks/useRouteNode.tsx","../../src/hooks/useRouterTransition.tsx"],"mappings":";;;;cAMa,iBAAgB;cCAhB,oBAAmB;;;;;;;;;;;;;;;;;;;;;;;;cCwBnB,qBAAoB;;;;;;KClB5B,gBAAgB,UAAU,SAAS,UAAU,KAChDA,aAAiB;EAEb,OAAO,MAAM;;cAEN,WAAY,UAAU,SAAS,aAAW,gBAAgB;iBCTvD,aAAa,mBAAmB;iBCDhC,uBAAuB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@real-router/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.38.0",
|
|
4
4
|
"type": "commonjs",
|
|
5
5
|
"description": "React integration for Real-Router",
|
|
6
6
|
"main": "./dist/cjs/index.js",
|
|
@@ -119,10 +119,10 @@
|
|
|
119
119
|
"@real-router/sources": "^0.17.0"
|
|
120
120
|
},
|
|
121
121
|
"devDependencies": {
|
|
122
|
-
"@real-router/browser-plugin": "^0.28.
|
|
123
|
-
"@real-router/core": "^0.
|
|
124
|
-
"@real-router/memory-plugin": "^0.7.
|
|
125
|
-
"@real-router/validation-plugin": "^0.
|
|
122
|
+
"@real-router/browser-plugin": "^0.28.1",
|
|
123
|
+
"@real-router/core": "^0.172.0",
|
|
124
|
+
"@real-router/memory-plugin": "^0.7.1",
|
|
125
|
+
"@real-router/validation-plugin": "^0.43.0",
|
|
126
126
|
"@testing-library/dom": "~10.4.1",
|
|
127
127
|
"@testing-library/jest-dom": "~7.0.1",
|
|
128
128
|
"@testing-library/react": "~16.3.2",
|
|
@@ -132,7 +132,7 @@
|
|
|
132
132
|
"vitest-react-profiler": "1.12.0"
|
|
133
133
|
},
|
|
134
134
|
"peerDependencies": {
|
|
135
|
-
"@real-router/core": ">=0.
|
|
135
|
+
"@real-router/core": ">=0.172.0",
|
|
136
136
|
"@types/react": ">=18.0.0",
|
|
137
137
|
"@types/react-dom": ">=18.0.0",
|
|
138
138
|
"ink": ">=7.0.0",
|