@real-router/react 0.28.3 → 0.28.5

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.
@@ -1,2 +1,2 @@
1
- import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-C1SlyYEz.mjs";import{n as s,t as c}from"./RouterProvider-CvVKMEfC.mjs";import{Activity as l,Children as u,Fragment as d,Suspense as f,isValidElement as p,useEffect as m,useLayoutEffect as h,useMemo as g,useRef as _}from"react";import{UNKNOWN_ROUTE as v}from"@real-router/core";import{startsWithSegment as y}from"@real-router/route-utils";import{Fragment as b,jsx as x}from"react/jsx-runtime";function S(e){return null}S.displayName=`RouteView.Match`;function C(e){return null}C.displayName=`RouteView.Self`;function w(e){return null}w.displayName=`RouteView.NotFound`;const T=new Set([S,C,w]);function E(e,t,n){return t===``?!1:n?e===t:y(e,t)}function D(e,t){u.forEach(e,e=>{p(e)&&(T.has(e.type)?t.push(e):D(e.props.children,t))})}function O(e,t,n,r,i){let a=i===void 0?e:x(f,{fallback:i,children:e});return n?x(l,{mode:r,children:a},t):x(d,{children:a},t)}function k(e,t){return e.type===w?(t.notFoundChildren=e.props.children,!0):e.type===C?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function A(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&&E(t,u,s)?(r.add(u),{rendered:O(a.children,u,c,`visible`,l),matched:!0}):c&&r.has(u)?{rendered:O(a.children,u,c,`hidden`,l),matched:!1}:{rendered:null,matched:!1}}function j(e,t,n,r){if(r.selfFound&&t===n){e.push(O(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===v&&r.notFoundChildren!==null&&e.push(x(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function M(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null},a=!1,o=[];for(let s of e){if(k(s,i))continue;let e=A(s,t,n,r,a);e.matched&&(a=!0),e.rendered!==null&&o.push(e.rendered)}return a||j(o,t,n,i),{rendered:o,activeMatchFound:a}}function N({nodeName:e,children:t}){let{route:r}=n(e),i=_(null);i.current??=new Set;let a=g(()=>{let e=[];return D(t,e),e},[t]);if(!r)return null;let{rendered:o}=M(a,r.name,e,i.current);return o.length>0?x(b,{children:o}):null}N.displayName=`RouteView`;const P=Object.assign(N,{Match:S,Self:C,NotFound:w});function F(e,t){let n=a(),r=_(e),i=t?.skipSameRoute??!0;h(()=>{r.current=e}),m(()=>n.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(i&&e.name===t.name)&&!n.aborted)return r.current({route:e,nextRoute:t,signal:n})}),[n,i])}function I(t,n){let{route:r,previousRoute:i}=e(),a=_(t),o=_(null),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{r.transition.from&&(s&&r.transition.from===r.name||o.current===r||!i||(o.current=r,a.current({route:r,previousRoute:i})))},[r,i,s])}export{s as Link,P as RouteView,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,I as useRouteEnter,F as useRouteExit,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-DOMeY1Ch.mjs";import{n as s,t as c}from"./RouterProvider-BdbHnUwc.mjs";import{Activity as l,Children as u,Fragment as d,Suspense as f,isValidElement as p,useEffect as m,useLayoutEffect as h,useMemo as g,useRef as _}from"react";import{UNKNOWN_ROUTE as v}from"@real-router/core";import{startsWithSegment as y}from"@real-router/route-utils";import{Fragment as b,jsx as x}from"react/jsx-runtime";function S(e){return null}S.displayName=`RouteView.Match`;function C(e){return null}C.displayName=`RouteView.Self`;function w(e){return null}w.displayName=`RouteView.NotFound`;const T=new Set([S,C,w]);function E(e,t,n){return t===``?!1:n?e===t:y(e,t)}function D(e,t){u.forEach(e,e=>{p(e)&&(T.has(e.type)?t.push(e):D(e.props.children,t))})}function O(e,t,n,r,i){let a=i===void 0?e:x(f,{fallback:i,children:e});return n?x(l,{mode:r,children:a},t):x(d,{children:a},t)}function k(e,t){return e.type===w?(t.notFoundChildren=e.props.children,!0):e.type===C?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function A(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&&E(t,u,s)?{rendered:O(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:O(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function j(e,t,n,r){if(r.selfFound&&t===n){e.push(O(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===v&&r.notFoundChildren!==null&&e.push(x(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function M(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null},a=null,o=[];for(let s of e){if(k(s,i))continue;let e=A(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&j(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function N({nodeName:e,children:t}){let{route:r}=n(e),i=_(null);i.current??=new Set;let a=i.current,o=g(()=>{let e=[];return D(t,e),e},[t]),s=r?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=M(o,s,e,a);return{rendered:t.rendered,activatedName:t.activatedName}},[o,s,e,a]);return m(()=>{l!==null&&a.add(l)},[l,a]),c.length>0?x(b,{children:c}):null}N.displayName=`RouteView`;const P=Object.assign(N,{Match:S,Self:C,NotFound:w});function F(e,t){let n=a(),r=_(e),i=t?.skipSameRoute??!0;h(()=>{r.current=e}),m(()=>n.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(i&&e.name===t.name)&&!n.aborted)return r.current({route:e,nextRoute:t,signal:n})}),[n,i])}function I(t,n){let{route:r,previousRoute:i}=e(),a=_(t),o=_(null),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{r.transition.from&&(s&&r.transition.from===r.name||o.current===r||!i||(o.current=r,a.current({route:r,previousRoute:i})))},[r,i,s])}export{s as Link,P as RouteView,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,I as useRouteEnter,F as useRouteExit,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\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}\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 slots.notFoundChildren = (child.props as NotFoundProps).children;\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; matched: boolean } {\n const matchProps = child.props as MatchProps;\n const { segment, exact = false, keepAlive = false, fallback } = matchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n hasBeenActivated.add(fullSegmentName);\n\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n matched: true,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n matched: false,\n };\n }\n\n return { rendered: null, matched: false };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n SELF_KEY,\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key={NOT_FOUND_KEY}>{slots.notFoundChildren}</Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: Set<string>,\n): { rendered: ReactElement[]; activeMatchFound: boolean } {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n };\n let activeMatchFound = false;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activeMatchFound,\n );\n\n if (result.matched) {\n activeMatchFound = true;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (!activeMatchFound) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound };\n}\n","import { useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n\n // Skip the Children.forEach + collectElements traversal when the children\n // reference is unchanged. The common SPA case is a stable JSX tree across\n // re-renders, so the cache hits on every render except the first.\n //\n // Streaming SSR caveat: with `renderToReadableStream`, React may invoke\n // RouteView multiple times across chunks with a fresh `children` reference\n // each time. The useMemo misses on each new render and the traversal runs\n // again — this is the expected SSR cost; the alternative would be build-\n // time codegen of the static route tree, which is out of scope here.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n if (!route) {\n return null;\n }\n\n const { rendered } = buildRenderList(\n elements,\n route.name,\n nodeName,\n // eslint-disable-next-line @eslint-react/refs -- stable Set ref read for keepAlive tracking (never reassigned)\n hasBeenActivatedRef.current,\n );\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not testable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start */\n if (lastHandledRouteRef.current === route || !previousRoute) {\n return;\n }\n /* v8 ignore stop */\n\n lastHandledRouteRef.current = route;\n handlerRef.current({ route, previousRoute });\n }, [route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"+fAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EAe1E,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,EAGhB,EAAkB,EAAW,CAAe,CACrD,CAEA,SAAgB,EACd,EACA,EACM,CAYN,EAAS,QAAQ,EAAW,GAAU,CAC/B,EAAe,CAAK,IAIrB,EAAa,IAAI,EAAM,IAAI,EAC7B,EAAO,KAAK,CAAK,EAEjB,EACG,EAAM,MAA2C,SAClD,CACF,EAEJ,CAAC,CACH,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAM,EACJ,IAAa,IAAA,GACX,EAEA,EAAC,EAAD,CAAoB,oBAAW,CAAuB,CAAA,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,EAAgB,GAAS,eAAiB,GAKhD,MAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,EAED,MAAgB,CAYT,EAAM,WAAW,OAGlB,GAAiB,EAAM,WAAW,OAAS,EAAM,MAIjD,EAAoB,UAAY,GAAS,CAAC,IAK9C,EAAoB,QAAU,EAC9B,EAAW,QAAQ,CAAE,QAAO,eAAc,CAAC,GAC7C,EAAG,CAAC,EAAO,EAAe,CAAa,CAAC,CAC1C"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n}\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 slots.notFoundChildren = (child.props as NotFoundProps).children;\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: 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 };\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 useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it rejects, the router emits\n * `TRANSITION_CANCELLED` (existing core behavior, no change here).\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```tsx\n * useRouteExit(({ route, nextRoute }) => {\n * // nextRoute.transition: TransitionMeta — preview of the upcoming nav\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) {\n * // skip animation when navigation arrived via redirect\n * return;\n * }\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n return router.subscribeLeave(({ route, nextRoute, signal }) => {\n if (skipSameRoute && route.name === nextRoute.name) {\n return;\n }\n\n // Reentrant abort: signal is already aborted when listener fires\n // (e.g. a newer navigate superseded this one before subscribeLeave\n // even ran). addEventListener(\"abort\", ...) does not fire\n // retroactively, so we skip the handler entirely — any cleanup the\n // handler would have wired via abort listener must not run because\n // the corresponding `add` work never happened.\n if (signal.aborted) {\n return;\n }\n\n return handlerRef.current({ route, nextRoute, signal });\n });\n }, [router, skipSameRoute]);\n}\n","import { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n const lastHandledRouteRef = useRef<State | null>(null);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // Early-exit guards, top-down:\n //\n // - **Skip-initial**: `state.transition.from` is undefined only\n // for the very first state committed by `router.start()`.\n // - **Skip-same-route**: query-only navigations have\n // `transition.from === route.name`. Opt-out via\n // `skipSameRoute: false`.\n // - **StrictMode dedupe**: same `route` ref between effect\n // cleanup + re-run in dev's strict pass. Not testable from\n // vitest (`NODE_ENV === \"test\"` disables React's strict-mode\n // double-run), so v8-ignored.\n if (!route.transition.from) {\n return;\n }\n if (skipSameRoute && route.transition.from === route.name) {\n return;\n }\n /* v8 ignore start */\n if (lastHandledRouteRef.current === route || !previousRoute) {\n return;\n }\n /* v8 ignore stop */\n\n lastHandledRouteRef.current = route;\n handlerRef.current({ route, previousRoute });\n }, [route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"+fAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EAe1E,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,EAGhB,EAAkB,EAAW,CAAe,CACrD,CAEA,SAAgB,EACd,EACA,EACM,CAYN,EAAS,QAAQ,EAAW,GAAU,CAC/B,EAAe,CAAK,IAIrB,EAAa,IAAI,EAAM,IAAI,EAC7B,EAAO,KAAK,CAAK,EAEjB,EACG,EAAM,MAA2C,SAClD,CACF,EAEJ,CAAC,CACH,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAM,EACJ,IAAa,IAAA,GACX,EAEA,EAAC,EAAD,CAAoB,oBAAW,CAAuB,CAAA,EAW1D,OARI,EAEA,EAAC,EAAD,CAAgB,gBACb,CACO,EAFiB,CAEjB,EAIP,EAAC,EAAD,CAAA,SAAqB,CAAkB,EAAxB,CAAwB,CAChD,CAEA,SAAS,EAAe,EAAqB,EAA+B,CAkB1E,OAjBI,EAAM,OAAS,GACjB,EAAM,iBAAoB,EAAM,MAAwB,SAEjD,IAGL,EAAM,OAAS,GAEjB,AAGE,EAAM,aAFN,EAAM,aAAgB,EAAM,MAAoB,SAChD,EAAM,aAAgB,EAAM,MAAoB,SAC9B,IAGb,IAGF,EACT,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACiE,CACjE,IAAM,EAAa,EAAM,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M,WAAW,OAGlB,GAAiB,EAAM,WAAW,OAAS,EAAM,MAIjD,EAAoB,UAAY,GAAS,CAAC,IAK9C,EAAoB,QAAU,EAC9B,EAAW,QAAQ,CAAE,QAAO,eAAc,CAAC,GAC7C,EAAG,CAAC,EAAO,EAAe,CAAa,CAAC,CAC1C"}
package/dist/esm/ink.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e,r as t,t as n}from"./useRoute-5MF3j-9P.mjs";import{a as r,f as i,i as a,n as o,o as s,p as c,r as l,t as u,u as d}from"./RouterProviderCore-C1SlyYEz.mjs";import{memo as f}from"react";import{jsx as p}from"react/jsx-runtime";import{Text as m,useFocus as h,useInput as g}from"ink";function _(e,t,n,r,i){return e?n??r??i:t?r??i:i}function v(e,t){return e.routeName===t.routeName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.color===t.color&&e.activeColor===t.activeColor&&e.focusColor===t.focusColor&&e.inverse===t.inverse&&e.activeInverse===t.activeInverse&&e.focusInverse===t.focusInverse&&e.id===t.id&&e.autoFocus===t.autoFocus&&e.onSelect===t.onSelect&&e.children===t.children&&d(e.routeParams,t.routeParams)&&d(e.routeOptions,t.routeOptions)}const y=f(({routeName:n,routeParams:r,routeOptions:i=e,activeStrict:a=!1,ignoreQueryParams:o=!0,color:l,activeColor:u,focusColor:d,inverse:f,activeInverse:v,focusInverse:y,id:b,autoFocus:x,onSelect:S,children:C})=>{let w=c(),{isFocused:T}=h({...b!==void 0&&{id:b},...x!==void 0&&{autoFocus:x}}),E=s(n,r,a,o),D=r??t;g((e,t)=>{if(t.return){try{S?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}w.navigate(n,D,i).catch(()=>{})}},{isActive:T});let O=_(T,E,d,u,l),k=_(T,E,y,v,f),A={};return O!==void 0&&(A.color=O),k!==void 0&&(A.inverse=k),p(m,{...A,children:C})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>p(u,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,r as RouterErrorBoundary,a as useNavigator,n as useRoute,i as useRouteNode,l as useRouteUtils,c as useRouter,o as useRouterTransition};
1
+ import{n as e,r as t,t as n}from"./useRoute-5MF3j-9P.mjs";import{a as r,f as i,i as a,n as o,o as s,p as c,r as l,t as u,u as d}from"./RouterProviderCore-DOMeY1Ch.mjs";import{memo as f}from"react";import{jsx as p}from"react/jsx-runtime";import{Text as m,useFocus as h,useInput as g}from"ink";function _(e,t,n,r,i){return e?n??r??i:t?r??i:i}function v(e,t){return e.routeName===t.routeName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.color===t.color&&e.activeColor===t.activeColor&&e.focusColor===t.focusColor&&e.inverse===t.inverse&&e.activeInverse===t.activeInverse&&e.focusInverse===t.focusInverse&&e.id===t.id&&e.autoFocus===t.autoFocus&&e.onSelect===t.onSelect&&e.children===t.children&&d(e.routeParams,t.routeParams)&&d(e.routeOptions,t.routeOptions)}const y=f(({routeName:n,routeParams:r,routeOptions:i=e,activeStrict:a=!1,ignoreQueryParams:o=!0,color:l,activeColor:u,focusColor:d,inverse:f,activeInverse:v,focusInverse:y,id:b,autoFocus:x,onSelect:S,children:C})=>{let w=c(),{isFocused:T}=h({...b!==void 0&&{id:b},...x!==void 0&&{autoFocus:x}}),E=s(n,r,a,o),D=r??t;g((e,t)=>{if(t.return){try{S?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}w.navigate(n,D,i).catch(()=>{})}},{isActive:T});let O=_(T,E,d,u,l),k=_(T,E,y,v,f),A={};return O!==void 0&&(A.color=O),k!==void 0&&(A.inverse=k),p(m,{...A,children:C})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>p(u,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,r as RouterErrorBoundary,a as useNavigator,n as useRoute,i as useRouteNode,l as useRouteUtils,c as useRouter,o as useRouterTransition};
2
2
  //# sourceMappingURL=ink.mjs.map
@@ -1 +1 @@
1
- import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-C1SlyYEz.mjs";import{n as s,t as c}from"./RouterProvider-CvVKMEfC.mjs";export{s as Link,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-DOMeY1Ch.mjs";import{n as s,t as c}from"./RouterProvider-BdbHnUwc.mjs";export{s as Link,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
@@ -1 +1 @@
1
- {"version":3,"file":"useRouteEnter-CqO9sPPD.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,cAAA;;WAEN,QAAA;EAFM;EAAA,SAIN,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,UAAA;EALN;EAAA,SAOA,OAAA;EALU;EAAA,SAOV,KAAA;EAPmB;EAAA,SASnB,SAAA;EANgB;EAAA,SAQhB,QAAA,GAAW,SAAA;EAEQ;EAAA,SAAnB,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,SAAA;EALN;;;;;AAEmB;EAFnB,SAYA,QAAA,GAAW,SAAA;EAPI;EAAA,SASf,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,aAAA;EALK;EAAA,SAOX,QAAA,EAAU,SAAS;AAAA;;;iBClCd,KAAA,CAAM,MAAkB,EAAV,UAAU;AAAA,kBAAxB,KAAA;EAAA,IAAK,WAAA;AAAA;AAAA,iBAML,IAAA,CAAK,MAAiB,EAAT,SAAS;AAAA,kBAAtB,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":[],"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,cAAA;;WAEN,QAAA;EAFM;EAAA,SAIN,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,UAAA;EALN;EAAA,SAOA,OAAA;EALU;EAAA,SAOV,KAAA;EAPmB;EAAA,SASnB,SAAA;EANgB;EAAA,SAQhB,QAAA,GAAW,SAAA;EAEQ;EAAA,SAAnB,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,SAAA;EALN;;;;;AAEmB;EAFnB,SAYA,QAAA,GAAW,SAAA;EAPI;EAAA,SASf,QAAA,EAAU,SAAS;AAAA;AAAA,UAGb,aAAA;EALK;EAAA,SAOX,QAAA,EAAU,SAAS;AAAA;;;iBClCd,KAAA,CAAM,MAAkB,EAAV,UAAU;AAAA,kBAAxB,KAAA;EAAA,IAAK,WAAA;AAAA;AAAA,iBAML,IAAA,CAAK,MAAiB,EAAT,SAAS;AAAA,kBAAtB,IAAA;EAAA,IAAI,WAAA;AAAA;AAAA,iBAMJ,QAAA,CAAS,MAAqB,EAAb,aAAa;AAAA,kBAA9B,QAAA;EAAA,IAAQ,WAAA;AAAA;;;iBCLf,aAAA;EACP,QAAA;EACA;AAAA,GACC,QAAA,CAAS,cAAA,IAAkB,YAAA;AAAA,kBAHrB,aAAA;EAAA,IAAa,WAAA;AAAA;AAAA,cAyET,SAAA,SAAS,aAAA;;;;;;;UC5EL,gBAAA;;EAEf,KAAA,EAAO,KAAA;EHNQ;EGQf,SAAA,EAAW,KAAA;;;;;;;AHJiB;EGY5B,MAAA,EAAQ,WAAA;AAAA;AAAA,UAGO,mBAAA;EHFa;;;;;EGQ5B,aAAa;AAAA;AAAA,KAGH,gBAAA,IACV,OAAA,EAAS,gBAAA,YACC,OAAO;;AHbW;AAG9B;;;;;;;;;AAS8B;AAG9B;;;;AAE8B;;;;AClC9B;;;;AAAwC;;;;;;AAMxC;;;;AAAsC;;;;;;AAMtC;;;;AAA8C;;;;;;;;;ACPJ;;;;;;;;;;;;;;;;;;AAKA;AAAA;;;;;AAsE1C;;;;;;;;;;iBCuCgB,YAAA,CACd,OAAA,EAAS,gBAAA,EACT,OAAA,GAAU,mBAAmB;;;UCrHd,iBAAA;;EAEf,KAAA,EAAO,KAAA;EJNQ;EIQf,aAAA,EAAe,KAAK;AAAA;AAAA,KAGV,iBAAA,IAAqB,OAA0B,EAAjB,iBAAiB;AAAA,UAE1C,oBAAA;EJTN;;;AAAmB;AAG9B;EIYE,aAAa;AAAA;;;;;;;;;;AJFe;AAG9B;;;;;;;;;AAS8B;AAG9B;;;;AAE8B;;;;AClC9B;;;;AAAwC;;;;;;AAMxC;;;;AAAsC;;;;;;AAMtC;;;;AAA8C;;;;;;;;;ACPJ;;;;;;;;;;;;;;;;;;AAKA;iBE4F1B,aAAA,CACd,OAAA,EAAS,iBAAA,EACT,OAAA,GAAU,oBAAoB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-router/react",
3
- "version": "0.28.3",
3
+ "version": "0.28.5",
4
4
  "type": "commonjs",
5
5
  "description": "React integration for Real-Router",
6
6
  "main": "./dist/cjs/index.js",
@@ -117,9 +117,9 @@
117
117
  "license": "MIT",
118
118
  "sideEffects": false,
119
119
  "dependencies": {
120
- "@real-router/core": "^0.63.0",
121
120
  "@real-router/sources": "^0.10.2",
122
- "@real-router/route-utils": "^0.2.5"
121
+ "@real-router/core": "^0.63.2",
122
+ "@real-router/route-utils": "^0.2.6"
123
123
  },
124
124
  "devDependencies": {
125
125
  "@testing-library/dom": "10.4.1",
@@ -1,2 +0,0 @@
1
- const e=require("./useRoute-D2vAzKWM.js");let t=require("react"),n=require("@real-router/core"),r=require("@real-router/route-utils"),i=require("react/jsx-runtime"),a=require("@real-router/sources"),o=require("@real-router/core/api");const s=()=>{let n=(0,t.useContext)(e.s);if(!n)throw Error(`useRouter must be used within a RouterProvider`);return n};function c(e){let r=s(),i=(0,t.useMemo)(()=>(0,a.createRouteNodeSource)(r,e),[r,e]),o=(0,t.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),c=(0,n.getNavigator)(r);return(0,t.useMemo)(()=>({navigator:c,route:o.route,previousRoute:o.previousRoute}),[c,o])}function l(e){return e.button===0&&!e.metaKey&&!e.altKey&&!e.ctrlKey&&!e.shiftKey}const u=/%[\dA-Fa-f]{2}/;function d(e){if(u.test(e))try{return encodeURI(decodeURIComponent(e)).replaceAll(`#`,`%23`)}catch{}return encodeURI(e).replaceAll(`#`,`%23`)}function f(e,t,n,r){try{let i=r?.hash,a;i!==void 0&&(a=i.startsWith(`#`)?i.slice(1):i);let o=e.buildUrl;if(o){let e=o(t,n,a===void 0?void 0:{hash:a});if(typeof e==`string`&&e.length>0)return e}let s=e.buildPath(t,n);if(typeof s!=`string`||s.length===0){console.error(`[real-router] Route "${t}" yielded an empty path. The element will render without an href attribute.`);return}return a?`${s}#${d(a)}`:s}catch{console.error(`[real-router] Route "${t}" is not defined. The element will render without an href attribute.`);return}}function p(e,t,n,r,i){let a={...i};r!==void 0&&(a.hash=r);let o=e.getState();if(o?.name===t&&v(o.params,n)){let e=o.context?.url?.hash??``;e!==(r??e)&&(a.force=!0,a.hashChange=!0)}return e.navigate(t,n,a)}const m=/\s/,h=/\S+/g;function g(e){return m.test(e)?e.match(h)??[]:[e]}function _(e,t,n){if(e&&t){let e=g(t);if(e.length===0)return n??void 0;if(!n)return e.join(` `);let r=g(n),i=new Set(r);for(let t of e)i.has(t)||(i.add(t),r.push(t));return r.join(` `)}return n??void 0}function v(e,t){if(Object.is(e,t))return!0;if(!e||!t)return!1;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;let r=e,i=t;for(let e of n)if(!Object.prototype.hasOwnProperty.call(t,e)||!Object.is(r[e],i[e]))return!1;return!0}function y(e,n,r=!1,i=!0,o){let c=s(),l=(0,t.useMemo)(()=>(0,a.createActiveRouteSource)(c,e,n,{strict:r,ignoreQueryParams:i,...o!==void 0&&{hash:o}}),[c,e,n,r,i,o]);return(0,t.useSyncExternalStore)(l.subscribe,l.getSnapshot,l.getSnapshot)}function b({children:e,fallback:n,onError:r}){let o=s(),c=(0,t.useMemo)(()=>(0,a.createDismissableError)(o),[o]),l=(0,t.useSyncExternalStore)(c.subscribe,c.getSnapshot,c.getSnapshot),u=(0,t.useRef)(r);return(0,t.useLayoutEffect)(()=>{u.current=r}),(0,t.useEffect)(()=>{l.error&&u.current?.(l.error,l.toRoute,l.fromRoute)},[l.version]),(0,i.jsxs)(i.Fragment,{children:[e,l.error?n(l.error,l.resetError):null]})}const x=()=>{let n=(0,t.useContext)(e.a);if(!n)throw Error(`useNavigator must be used within a RouterProvider`);return n},S=()=>(0,r.getRouteUtils)((0,o.getPluginApi)(s()).getTree());function C(){let e=(0,a.getTransitionSource)(s());return(0,t.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot)}const w=({router:r,children:o})=>{let s=(0,t.useMemo)(()=>(0,n.getNavigator)(r),[r]),c=(0,t.useMemo)(()=>(0,a.createRouteSource)(r),[r]);(0,t.useEffect)(()=>{(0,a.primeErrorSource)(r)},[r]);let l=(0,t.useSyncExternalStore)(c.subscribe,c.getSnapshot,c.getSnapshot),u=(0,t.useMemo)(()=>({navigator:s,route:l.route,previousRoute:l.previousRoute}),[s,l]);return(0,i.jsx)(e.s.Provider,{value:r,children:(0,i.jsx)(e.a.Provider,{value:s,children:(0,i.jsx)(e.o.Provider,{value:u,children:o})})})};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return v}});
2
- //# sourceMappingURL=RouterProviderCore-B0sjqCWG.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RouterProviderCore-B0sjqCWG.js","names":["RouterContext","NavigatorContext","RouterContext","NavigatorContext","RouteContext"],"sources":["../../src/hooks/useRouter.tsx","../../src/hooks/useRouteNode.tsx","../../../../shared/dom-utils/link-utils.ts","../../src/hooks/useIsActiveRoute.tsx","../../src/components/RouterErrorBoundary.tsx","../../src/hooks/useNavigator.tsx","../../src/hooks/useRouteUtils.tsx","../../src/hooks/useRouterTransition.tsx","../../src/RouterProviderCore.tsx"],"sourcesContent":["import { useContext } from \"react\";\n\nimport { RouterContext } from \"../context\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport const useRouter = (): Router => {\n const router = useContext(RouterContext);\n\n if (!router) {\n throw new Error(\"useRouter must be used within a RouterProvider\");\n }\n\n return router;\n};\n","import { getNavigator } from \"@real-router/core\";\nimport { createRouteNodeSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteContext } from \"../types\";\n\nexport function useRouteNode(nodeName: string): RouteContext {\n const router = useRouter();\n\n const store = useMemo(\n () => createRouteNodeSource(router, nodeName),\n [router, nodeName],\n );\n\n // Use snapshot reference directly. createRouteNodeSource via stabilizeState\n // returns the SAME snapshot when the node-relevant state did not change,\n // so memoization on `[navigator, snapshot]` preserves identity for consumers.\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot, // SSR: router returns same state on server and client\n );\n\n // getNavigator is WeakMap-cached in core; additional useMemo is redundant.\n const navigator = getNavigator(router);\n\n return useMemo(\n (): RouteContext => ({\n navigator,\n route: snapshot.route,\n previousRoute: snapshot.previousRoute,\n }),\n [navigator, snapshot],\n );\n}\n","import type {\n NavigationOptions,\n Params,\n Router,\n State,\n} from \"@real-router/core\";\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n// Matches a single percent-escape triple (`%` + two hex digits). Used as\n// the \"already-encoded\" probe in `encodeFragmentInline` below — see the\n// idempotency rationale there.\nconst PERCENT_ESCAPE_PROBE = /%[\\dA-Fa-f]{2}/;\n\n/**\n * RFC 3986 fragment encoding: preserve sub-delims (`&`, `=`, `?`, `:`),\n * encode space, `%`, control chars, non-ASCII via encodeURI; defensively\n * escape `#` (encodeURI does not). Mirrors `encodeHashFragment` in\n * `shared/browser-env/url-context.ts` — duplicated here because the\n * shared/dom-utils symlink graph does not reach shared/browser-env.\n *\n * **Idempotency for pre-encoded input (audit-2026-05-17 §5 MEDIUM E.1).**\n * The doc-comment on `<Link hash>` says the value is a \"decoded fragment\n * without leading #\". But realistic consumers copy hashes out of\n * `location.hash` (which is percent-encoded) and pass them back, so the\n * naive `encodeURI(\"%20\")` would double-encode into `\"%2520\"` and break\n * anchor lookup. We detect a percent-escape triple in the input and, if\n * present, decode + re-encode for idempotency. Malformed `%XX` (e.g.\n * `\"%2\"` or `\"%ZZ\"`) makes `decodeURIComponent` throw — in that case we\n * fall through to plain `encodeURI`, which never throws.\n */\nfunction encodeFragmentInline(decoded: string): string {\n if (PERCENT_ESCAPE_PROBE.test(decoded)) {\n try {\n const roundtrip = decodeURIComponent(decoded);\n\n return encodeURI(roundtrip).replaceAll(\"#\", \"%23\");\n } catch {\n // Malformed `%XX` — fall through to the plain encoding path.\n // encodeURI does not throw on malformed escapes; it treats the\n // `%` as a literal and percent-encodes it (`%2` → `%252`).\n }\n }\n\n return encodeURI(decoded).replaceAll(\"#\", \"%23\");\n}\n\ntype BuildUrlFn = (\n name: string,\n params: Params,\n options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is an options object so the contract stays\n * extensible. The `hash` option is a decoded fragment without leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively (leading \"#\" stripped).\n * Frozen API: previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n options?: { hash?: string },\n): string | undefined {\n try {\n const rawHash = options?.hash;\n let normHash: string | undefined;\n\n if (rawHash !== undefined) {\n normHash = rawHash.startsWith(\"#\") ? rawHash.slice(1) : rawHash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n if (\n current?.name === routeName &&\n shallowEqual(current.params, routeParams)\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n return router.navigate(routeName, routeParams, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\n// `value` is always a truthy class string: both call sites narrow it first\n// (`if (isActive && activeClassName)` / `if (!baseClassName) return …`), so the\n// former `if (!value) return []` guard was unreachable dead code (#809).\nfunction parseTokens(value: string): string[] {\n // Hot-path fast-path (audit-2026-05-17 §8b #1): >99% of active-class\n // inputs at `<Link>` emit are single-token strings like `\"active\"` or\n // `\"is-current\"` — no whitespace, no leading/trailing pad. Skip the\n // regex match and Array result allocation: a literal `[value]` works\n // because the slow-path `match(/\\S+/g)` would return exactly `[value]`\n // for the same input. PBT lock: linkUtils.properties.ts Invariant 13.\n if (!WHITESPACE_PROBE.test(value)) {\n return [value];\n }\n\n return value.match(WHITESPACE_SPLIT) ?? [];\n}\n\nexport function buildActiveClassName(\n isActive: boolean,\n activeClassName: string | undefined,\n baseClassName: string | undefined,\n): string | undefined {\n if (isActive && activeClassName) {\n const activeTokens = parseTokens(activeClassName);\n\n if (activeTokens.length === 0) {\n return baseClassName ?? undefined;\n }\n if (!baseClassName) {\n return activeTokens.join(\" \");\n }\n\n const baseTokens = parseTokens(baseClassName);\n const seen = new Set(baseTokens);\n\n for (const token of activeTokens) {\n if (seen.has(token)) {\n continue;\n }\n\n seen.add(token);\n baseTokens.push(token);\n }\n\n return baseTokens.join(\" \");\n }\n\n return baseClassName ?? undefined;\n}\n\n/**\n * One-level structural equality using `Object.is` per key.\n *\n * **String-keyed properties only (Mini-sprint E.3 — audit-5 §4.2 #3).**\n * Implementation walks `Object.keys()` which by spec returns only\n * enumerable own STRING keys. Symbol-keyed properties — created via\n * `obj[Symbol(\"brand\")] = value` or `{ [Symbol(...)]: value }` — are\n * NOT compared. Two records that differ only in a Symbol-keyed value\n * will compare as equal.\n *\n * This is intentional: route params and Link options are documented as\n * string-keyed primitives (string | number | boolean) — Symbol-keyed\n * metadata (e.g. brand markers, private state) doesn't belong in a\n * cache-key comparison. Switching to `Reflect.ownKeys()` would extend\n * the contract to symbols at the cost of one extra allocation per call\n * (Reflect.ownKeys composes string-keys + symbol-keys arrays). If a\n * consumer relies on symbol-keyed metadata for navigation\n * disambiguation, they should encode it into a string key instead.\n *\n * Mirrors React's `shallowEqual` (packages/shared/shallowEqual.js) in\n * both the string-keys-only semantics and the `hasOwnProperty` guard\n * below.\n */\nexport function shallowEqual(\n prev: object | undefined,\n next: object | undefined,\n): boolean {\n if (Object.is(prev, next)) {\n return true;\n }\n if (!prev || !next) {\n return false;\n }\n\n const prevKeys = Object.keys(prev);\n\n if (prevKeys.length !== Object.keys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import { createActiveRouteSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { Params } from \"@real-router/core\";\n\nexport function useIsActiveRoute(\n routeName: string,\n params?: Params,\n strict = false,\n ignoreQueryParams = true,\n hash?: string,\n): boolean {\n const router = useRouter();\n\n // createActiveRouteSource is per-router + canonical-args cached in\n // @real-router/sources, so passing params by reference is safe — equivalent\n // param shapes hit the same cache entry regardless of key order. The\n // `hash` argument (#532) is part of the cache key when defined: a Link\n // pointing to `/settings#account` shares its source only with other\n // consumers using the same routeName + params + hash.\n //\n // The useMemo wrap skips `canonicalJson(params)` + cache lookup on every\n // render when all primitive deps and the `params` reference are stable —\n // the common case once memo()+shallowEqual has bailed out further up\n // (or when the parent re-renders for a non-Link reason). For inline\n // `params={{id:1}}` the dep changes per render and the lookup still\n // runs, but that path was already the slow path before this memo.\n // exactOptionalPropertyTypes forbids `{ hash: undefined }` literally, so\n // we conditionally spread the key only when the caller passed a value.\n const store = useMemo(\n () =>\n createActiveRouteSource(router, routeName, params, {\n strict,\n ignoreQueryParams,\n ...(hash !== undefined && { hash }),\n }),\n [router, routeName, params, strict, ignoreQueryParams, hash],\n );\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { createDismissableError } from \"@real-router/sources\";\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { RouterError, State } from \"@real-router/core\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nexport interface RouterErrorBoundaryProps {\n readonly children: ReactNode;\n readonly fallback: (error: RouterError, resetError: () => void) => ReactNode;\n readonly onError?: (\n error: RouterError,\n toRoute: State | null,\n fromRoute: State | null,\n ) => void;\n}\n\nexport function RouterErrorBoundary({\n children,\n fallback,\n onError,\n}: RouterErrorBoundaryProps): ReactElement {\n const router = useRouter();\n // Per-router cached in @real-router/sources — the WeakMap lookup is cheap,\n // but useMemo avoids it entirely on stable-router re-renders (the common\n // case for boundaries mounted in app shells).\n const store = useMemo(() => createDismissableError(router), [router]);\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n\n const onErrorRef = useRef(onError);\n\n // \"Latest ref\" pattern shared with useRouteEnter/useRouteExit: sync the\n // callback to the ref via useLayoutEffect (synchronous, post-render,\n // pre-paint) so the snapshot effect below reads the freshest callback\n // without listing `onError` as a dep — and StrictMode's double-effect\n // pass writes the same value twice harmlessly.\n useLayoutEffect(() => {\n onErrorRef.current = onError;\n });\n\n useEffect(() => {\n if (snapshot.error) {\n onErrorRef.current?.(\n snapshot.error,\n snapshot.toRoute,\n snapshot.fromRoute,\n );\n }\n // eslint-disable-next-line @eslint-react/exhaustive-deps -- onError tracked via ref, snapshot fields accessed inside callback\n }, [snapshot.version]);\n\n return (\n <>\n {children}\n {snapshot.error ? fallback(snapshot.error, snapshot.resetError) : null}\n </>\n );\n}\n","import { useContext } from \"react\";\n\nimport { NavigatorContext } from \"../context\";\n\nimport type { Navigator } from \"@real-router/core\";\n\nexport const useNavigator = (): Navigator => {\n const navigator = useContext(NavigatorContext);\n\n if (!navigator) {\n throw new Error(\"useNavigator must be used within a RouterProvider\");\n }\n\n return navigator;\n};\n","import { getPluginApi } from \"@real-router/core/api\";\nimport { getRouteUtils } from \"@real-router/route-utils\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteUtils } from \"@real-router/route-utils\";\n\n/**\n * Returns a pre-computed {@link RouteUtils} instance for the current router.\n *\n * `getRouteUtils` is WeakMap-cached per `RouteTreeNode` inside\n * `@real-router/route-utils`, so the same router always returns the same\n * `RouteUtils` instance across renders — no local cache needed in the adapter.\n *\n * @returns RouteUtils instance with pre-computed chains and siblings\n *\n * @example\n * ```tsx\n * const utils = useRouteUtils();\n *\n * utils.getChain(\"users.profile\");\n * // → [\"users\", \"users.profile\"]\n *\n * utils.getSiblings(\"users\");\n * // → [\"admin\"]\n *\n * utils.isDescendantOf(\"users.profile\", \"users\");\n * // → true\n * ```\n */\nexport const useRouteUtils = (): RouteUtils => {\n const router = useRouter();\n\n return getRouteUtils(getPluginApi(router).getTree());\n};\n","import { getTransitionSource } from \"@real-router/sources\";\nimport { useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouterTransitionSnapshot } from \"@real-router/sources\";\n\nexport function useRouterTransition(): RouterTransitionSnapshot {\n const router = useRouter();\n const store = getTransitionSource(router);\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { getNavigator } from \"@real-router/core\";\nimport { createRouteSource, primeErrorSource } from \"@real-router/sources\";\nimport { useEffect, useMemo, useSyncExternalStore } from \"react\";\n\nimport { NavigatorContext, RouteContext, RouterContext } from \"./context\";\n\nimport type { Router } from \"@real-router/core\";\nimport type { FC, ReactNode } from \"react\";\n\nexport interface RouterProviderCoreProps {\n router: Router;\n children: ReactNode;\n}\n\n/**\n * DOM-free provider core: router / route / navigator contexts plus the\n * `useSyncExternalStore` subscription wiring, with **no** dom-utils dependency.\n *\n * Split out of `RouterProvider` (#800) so the terminal `/ink` entry can compose\n * only this: `InkRouterProvider` renders `RouterProviderCore` directly, keeping\n * the scroll-spy / view-transitions / announcer / scroll-restore factories — all\n * structurally unreachable in a terminal — out of the chunk reachable from\n * `dist/esm/ink.mjs`. The DOM-aware `RouterProvider` wraps this core and layers\n * the opt-in DOM-feature effects on top.\n */\nexport const RouterProviderCore: FC<RouterProviderCoreProps> = ({\n router,\n children,\n}) => {\n const navigator = useMemo(() => getNavigator(router), [router]);\n\n // useSyncExternalStore manages the router subscription lifecycle:\n // subscribe connects to router on first listener, unsubscribes on last.\n // This is Strict Mode safe — no useEffect cleanup needed.\n //\n // Caveat (#765): that same first-listener/last-listener contract opens a\n // stale window if THIS Provider is mounted under a React <Activity> /\n // keepAlive boundary — hiding detaches the subscription, a navigation while\n // hidden is missed, and re-show replays createRouteSource's stale snapshot\n // (createRouteSource does not reconcile on re-subscribe). Keep RouterProvider\n // ABOVE any Activity boundary — see the \"Keep RouterProvider above any\n // <Activity> / keepAlive boundary\" gotcha in CLAUDE.md.\n const store = useMemo(() => createRouteSource(router), [router]);\n\n // #778 P2: eagerly create the per-router error source so a navigation error\n // that fires BEFORE a RouterErrorBoundary mounts (a lazy app shell, a failed\n // boot navigation) is still captured. The boundary's createDismissableError\n // reuses this cached source and catches up (#765); without it the error source\n // is created lazily on boundary mount — after the error — and never sees it.\n useEffect(() => {\n primeErrorSource(router);\n }, [router]);\n // Use snapshot reference directly. createRouteSource via stabilizeState\n // returns the SAME snapshot reference when route.path is unchanged, so\n // useMemo below sees stable deps for idempotent navigations and\n // RouteContext consumers do not re-render.\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot, // SSR: router returns same state on server and client\n );\n\n const routeContextValue = useMemo(\n () => ({\n navigator,\n route: snapshot.route,\n previousRoute: snapshot.previousRoute,\n }),\n [navigator, snapshot],\n );\n\n return (\n <RouterContext.Provider value={router}>\n <NavigatorContext.Provider value={navigator}>\n <RouteContext.Provider value={routeContextValue}>\n {children}\n </RouteContext.Provider>\n </NavigatorContext.Provider>\n </RouterContext.Provider>\n );\n};\n"],"mappings":"0OAMA,MAAa,MAA0B,CACrC,IAAM,GAAA,EAAA,EAAA,WAAA,CAAoBA,EAAAA,CAAa,EAEvC,GAAI,CAAC,EACH,MAAU,MAAM,gDAAgD,EAGlE,OAAO,CACT,ECNA,SAAgB,EAAa,EAAgC,CAC3D,IAAM,EAAS,EAAU,EAEnB,GAAA,EAAA,EAAA,QAAA,MAAA,EAAA,EAAA,sBAAA,CACwB,EAAQ,CAAQ,EAC5C,CAA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,CACT,ECgBa,OAGX,EAAA,EAAA,cAAA,EAAA,EAAA,EAAA,aAAA,CAFe,EAEwB,CAAC,CAAC,CAAC,QAAQ,CAAC,EC1BrD,SAAgB,GAAgD,CAE9D,IAAM,GAAA,EAAA,EAAA,oBAAA,CADS,EACwB,CAAC,EAExC,OAAA,EAAA,EAAA,qBAAA,CACE,EAAM,UACN,EAAM,YACN,EAAM,WACR,CACF,CCSA,MAAa,GAAmD,CAC9D,SACA,cACI,CACJ,IAAM,GAAA,EAAA,EAAA,QAAA,MAAA,EAAA,EAAA,aAAA,CAAuC,CAAM,EAAG,CAAC,CAAM,CAAC,EAaxD,GAAA,EAAA,EAAA,QAAA,MAAA,EAAA,EAAA,kBAAA,CAAwC,CAAM,EAAG,CAAC,CAAM,CAAC,GAO/D,EAAA,EAAA,UAAA,KAAgB,EACd,EAAA,EAAA,iBAAA,CAAiB,CAAM,CACzB,EAAG,CAAC,CAAM,CAAC,EAKX,IAAM,GAAA,EAAA,EAAA,qBAAA,CACJ,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAEM,GAAA,EAAA,EAAA,QAAA,MACG,CACL,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,aAC1B,GACA,CAAC,EAAW,CAAQ,CACtB,EAEA,OACE,EAAA,EAAA,IAAA,CAACC,EAAAA,EAAc,SAAf,CAAwB,MAAO,YAC7B,EAAA,EAAA,IAAA,CAACC,EAAAA,EAAiB,SAAlB,CAA2B,MAAO,YAChC,EAAA,EAAA,IAAA,CAACC,EAAAA,EAAa,SAAd,CAAuB,MAAO,EAC3B,UACoB,CAAA,CACE,CAAA,CACL,CAAA,CAE5B"}
@@ -1,2 +0,0 @@
1
- import{a as e,o as t,s as n}from"./useRoute-5MF3j-9P.mjs";import{useContext as r,useEffect as i,useLayoutEffect as a,useMemo as o,useRef as s,useSyncExternalStore as c}from"react";import{getNavigator as l}from"@real-router/core";import{getRouteUtils as u}from"@real-router/route-utils";import{Fragment as d,jsx as f,jsxs as p}from"react/jsx-runtime";import{createActiveRouteSource as m,createDismissableError as h,createRouteNodeSource as g,createRouteSource as _,getTransitionSource as v,primeErrorSource as y}from"@real-router/sources";import{getPluginApi as b}from"@real-router/core/api";const x=()=>{let e=r(n);if(!e)throw Error(`useRouter must be used within a RouterProvider`);return e};function S(e){let t=x(),n=o(()=>g(t,e),[t,e]),r=c(n.subscribe,n.getSnapshot,n.getSnapshot),i=l(t);return o(()=>({navigator:i,route:r.route,previousRoute:r.previousRoute}),[i,r])}function C(e){return e.button===0&&!e.metaKey&&!e.altKey&&!e.ctrlKey&&!e.shiftKey}const w=/%[\dA-Fa-f]{2}/;function T(e){if(w.test(e))try{return encodeURI(decodeURIComponent(e)).replaceAll(`#`,`%23`)}catch{}return encodeURI(e).replaceAll(`#`,`%23`)}function E(e,t,n,r){try{let i=r?.hash,a;i!==void 0&&(a=i.startsWith(`#`)?i.slice(1):i);let o=e.buildUrl;if(o){let e=o(t,n,a===void 0?void 0:{hash:a});if(typeof e==`string`&&e.length>0)return e}let s=e.buildPath(t,n);if(typeof s!=`string`||s.length===0){console.error(`[real-router] Route "${t}" yielded an empty path. The element will render without an href attribute.`);return}return a?`${s}#${T(a)}`:s}catch{console.error(`[real-router] Route "${t}" is not defined. The element will render without an href attribute.`);return}}function D(e,t,n,r,i){let a={...i};r!==void 0&&(a.hash=r);let o=e.getState();if(o?.name===t&&M(o.params,n)){let e=o.context?.url?.hash??``;e!==(r??e)&&(a.force=!0,a.hashChange=!0)}return e.navigate(t,n,a)}const O=/\s/,k=/\S+/g;function A(e){return O.test(e)?e.match(k)??[]:[e]}function j(e,t,n){if(e&&t){let e=A(t);if(e.length===0)return n??void 0;if(!n)return e.join(` `);let r=A(n),i=new Set(r);for(let t of e)i.has(t)||(i.add(t),r.push(t));return r.join(` `)}return n??void 0}function M(e,t){if(Object.is(e,t))return!0;if(!e||!t)return!1;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;let r=e,i=t;for(let e of n)if(!Object.prototype.hasOwnProperty.call(t,e)||!Object.is(r[e],i[e]))return!1;return!0}function N(e,t,n=!1,r=!0,i){let a=x(),s=o(()=>m(a,e,t,{strict:n,ignoreQueryParams:r,...i!==void 0&&{hash:i}}),[a,e,t,n,r,i]);return c(s.subscribe,s.getSnapshot,s.getSnapshot)}function P({children:e,fallback:t,onError:n}){let r=x(),l=o(()=>h(r),[r]),u=c(l.subscribe,l.getSnapshot,l.getSnapshot),f=s(n);return a(()=>{f.current=n}),i(()=>{u.error&&f.current?.(u.error,u.toRoute,u.fromRoute)},[u.version]),p(d,{children:[e,u.error?t(u.error,u.resetError):null]})}const F=()=>{let t=r(e);if(!t)throw Error(`useNavigator must be used within a RouterProvider`);return t},I=()=>u(b(x()).getTree());function L(){let e=v(x());return c(e.subscribe,e.getSnapshot,e.getSnapshot)}const R=({router:r,children:a})=>{let s=o(()=>l(r),[r]),u=o(()=>_(r),[r]);i(()=>{y(r)},[r]);let d=c(u.subscribe,u.getSnapshot,u.getSnapshot),p=o(()=>({navigator:s,route:d.route,previousRoute:d.previousRoute}),[s,d]);return f(n.Provider,{value:r,children:f(e.Provider,{value:s,children:f(t.Provider,{value:p,children:a})})})};export{P as a,E as c,C as d,S as f,F as i,D as l,L as n,N as o,x as p,I as r,j as s,R as t,M as u};
2
- //# sourceMappingURL=RouterProviderCore-C1SlyYEz.mjs.map