@real-router/react 0.37.7 → 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 +7 -7
- 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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createHttpStatusSink-CrJYxt4F.js","names":["useState","useEffect","useState","useEffect","useRoute","NEVER_PROMISE","Suspense","createContext","useContext","require_useRoute","react","react_jsx_runtime","ClientOnly","children","fallback","mounted","setMounted","ServerOnly","useDeferred","key","route","Streamed","HttpStatusContext","HttpStatusProvider","sink","HttpStatusCode","code","createHttpStatusSink"],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/hooks/useDeferred.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusProvider.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ClientOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ClientOnly({\n children,\n fallback = null,\n}: ClientOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the fallback branch, client matches\n // it on first paint, then this effect flips state to swap in the children.\n // The intentional re-render is what makes the markup match across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? children : fallback;\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ServerOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ServerOnly({\n children,\n fallback = null,\n}: ServerOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the children branch, client matches\n // it on first paint, then this effect flips state to swap in the fallback\n // (or hide entirely). The intentional re-render keeps markup consistent\n // across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? fallback : children;\n}\n","import { NEVER_PROMISE } from \"../constants\";\nimport { useRoute } from \"./useRoute\";\n\ninterface DeferredContext {\n ssrDataDeferred?: Record<string, Promise<unknown>>;\n}\n\n/**\n * Read a deferred promise published by `defer({ deferred: { <key>: Promise } })`\n * inside an SSR data loader.\n *\n * - **Server render**: returns the actual loader-returned promise. Combine\n * with `<Suspense>` + `use(promise)` for native streaming via React 19's\n * `renderToReadableStream`.\n * - **Post-hydration**: returns a registry-backed promise; the inline\n * `<script>__rrDefer__(\"key\", json)</script>` tags emitted by the server\n * stream resolve it. `use()` returns synchronously once the registry\n * settles.\n * - **Unknown key**: returns a never-resolving promise — Suspense boundary\n * stays in fallback. This surfaces consumer/loader key drift as a visible\n * loading state instead of a silent runtime error.\n *\n * The hook subscribes to `RouteContext`, so it re-runs on every navigation.\n * Promise reference identity is stable across renders within the same\n * navigation — `use()` will not re-suspend on rerenders.\n */\nexport function useDeferred<T = unknown>(key: string): Promise<T> {\n const { route } = useRoute();\n const context = route.context as DeferredContext;\n const deferred = context.ssrDataDeferred;\n const promise = deferred?.[key];\n\n return (promise ?? NEVER_PROMISE) as Promise<T>;\n}\n","import { Suspense } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface StreamedProps {\n /** Shown while any descendant `use(promise)` / `<Await>` is pending. */\n readonly fallback: ReactNode;\n readonly children: ReactNode;\n}\n\n/**\n * Cross-adapter alias for `<Suspense fallback={…}>`. Pairs with `<Await>`\n * for symmetry with `<Streamed>` boundaries in the SvelteKit / Solid\n * deferred-data conventions.\n *\n * ```tsx\n * <Streamed fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Streamed>\n * ```\n *\n * The component is a thin wrapper around React's native `<Suspense>` — no\n * additional behaviour. Use plain `<Suspense>` directly if you don't need\n * the cross-framework naming alignment.\n */\nexport function Streamed({ fallback, children }: StreamedProps): ReactNode {\n return <Suspense fallback={fallback}>{children}</Suspense>;\n}\n","import { createContext } from \"react\";\n\nimport type { HttpStatusSink } from \"../utils/createHttpStatusSink\";\nimport type { ReactNode } from \"react\";\n\nexport const HttpStatusContext = createContext<HttpStatusSink | null>(null);\n\nexport interface HttpStatusProviderProps {\n readonly sink: HttpStatusSink;\n readonly children: ReactNode;\n}\n\nexport function HttpStatusProvider({\n sink,\n children,\n}: HttpStatusProviderProps): ReactNode {\n // `<HttpStatusContext.Provider value>` (not the React 19 `<HttpStatusContext value>`\n // shorthand) — same component file is exported via `/legacy/ssr` for React 18\n // consumers, where the shorthand throws \"Element type is invalid: expected\n // a string but got: object\".\n return (\n <HttpStatusContext.Provider value={sink}>\n {children}\n </HttpStatusContext.Provider>\n );\n}\n","import { useContext } from \"react\";\n\nimport { HttpStatusContext } from \"./HttpStatusProvider\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface HttpStatusCodeProps {\n /** HTTP status to apply to the response. Common values: 404, 410, 451, 503. */\n readonly code: number;\n}\n\n/**\n * Render-time HTTP status declaration. Mount inside a route component (typical\n * use case: a glob `*` route's NotFound page) when the status is decided by\n * the rendered tree rather than a loader.\n *\n * Writes `code` to the nearest `<HttpStatusProvider>`'s sink during render and\n * returns `null`. With no provider mounted (the standard client-side case)\n * the component is a silent no-op — same component tree hydrates without\n * touching the DOM or warning about mismatches.\n *\n * Loader-driven errors (`LoaderNotFound` → 404, `LoaderRedirect` → 30x) keep\n * working as before; this component covers render-time decisions only.\n *\n * Last write wins when several `<HttpStatusCode />` instances mount in the\n * same render pass — sink reflects the last component that ran.\n *\n * ```tsx\n * // entry-server.tsx\n * import { renderToString } from \"react-dom/server\";\n * import { createHttpStatusSink, HttpStatusProvider } from \"@real-router/react/ssr\";\n *\n * const sink = createHttpStatusSink();\n * const html = renderToString(\n * <HttpStatusProvider sink={sink}>\n * <RouterProvider router={router}>\n * <App />\n * </RouterProvider>\n * </HttpStatusProvider>,\n * );\n * response.status(sink.code ?? 200).send(html);\n * ```\n *\n * **Streaming SSR (`renderToReadableStream`):** the response status MUST be\n * sent before the first body byte flushes. If `<HttpStatusCode />` is mounted\n * inside a late-resolving `<Suspense>` boundary, the sink write may happen\n * AFTER the headers are already on the wire — the override is then lost.\n * Either mount the component in the shell (above every `<Suspense>` that\n * could delay it) or `await stream.allReady` before reading `sink.code`\n * (which forfeits streaming benefits). For non-streaming SSR\n * (`renderToString`) there is no such ordering concern.\n *\n * **Valid `code` range:** Node's `res.end()` throws `Invalid status code` on\n * `NaN`, `0`, negative values, or values `> 999` — this surfaces as a 5xx /\n * dropped connection, not silent corruption. Pass a real HTTP status integer\n * (commonly 4xx/5xx; 100-999 is what Node accepts).\n */\nexport function HttpStatusCode({ code }: HttpStatusCodeProps): ReactNode {\n const sink = useContext(HttpStatusContext);\n\n if (sink) {\n // Dev-only validation: Node's `res.end()` throws `Invalid status code` on\n // NaN / 0 / negative / non-integer / >999. Surface the bad value at the\n // source so the consumer can fix the routing logic, instead of waiting\n // for the server to crash mid-response. Production builds (Vite, esbuild,\n // tsdown all replace `process.env.NODE_ENV !== \"production\"` with `false`)\n // strip the check.\n if (\n process.env.NODE_ENV !== \"production\" &&\n (!Number.isInteger(code) || code < 100 || code > 999)\n ) {\n console.error(\n `[real-router] <HttpStatusCode code={${String(code)}} /> received an invalid HTTP status code. Node's res.end() rejects values that are not an integer in [100, 999] — pass a real HTTP status (commonly 4xx/5xx).`,\n );\n }\n\n sink.code = code;\n }\n\n return null;\n}\n","/**\n * Render-scoped HTTP status sink. Created per request on the server, passed to\n * `<HttpStatusProvider sink={...}>`, and read after `renderToString` /\n * `renderToReadableStream` to apply the value to the HTTP response.\n *\n * Last write wins: if the rendered tree mounts more than one\n * `<HttpStatusCode />`, the value reflects the last component that ran during\n * the render pass.\n *\n * No-op on the client — `<HttpStatusCode />` reads the optional context and\n * skips the write when no provider is mounted, so the same component tree can\n * be hydrated without changing behaviour.\n *\n * Constraints:\n * - **Per-request only.** Don't share a sink across requests; the rendered\n * tree mutates `code` in place. Module-level singletons leak status\n * between concurrent requests.\n * - **Don't `Object.freeze` the sink.** The component writes to `.code`;\n * freezing makes the assignment throw under ESM strict mode.\n */\nexport interface HttpStatusSink {\n code: number | undefined;\n}\n\nexport function createHttpStatusSink(): HttpStatusSink {\n return { code: undefined };\n}\n"],"mappings":"A,gGASA,SAAgBY,EAAW,CACzBC,WACAC,WAAW,MACkB,CAC7B,GAAM,CAACC,EAASC,IAAA,EAAchB,EAAAA,SAAAA,CAAS,EAAK,EAU5C,OARAC,EAAAA,EAAAA,UAAAA,KAAgB,CAKde,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEED,EAAUF,EAAWC,CAC9B,CCfA,SAAgBG,EAAW,CACzBJ,WACAC,WAAW,MACkB,CAC7B,GAAM,CAACC,EAASC,IAAA,EAAcd,EAAAA,SAAAA,CAAS,EAAK,EAW5C,OATAC,EAAAA,EAAAA,UAAAA,KAAgB,CAMda,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEED,EAAUD,EAAWD,CAC9B,CCCA,SAAgBK,EAAyBC,EAAyB,CAChE,GAAM,CAAEC,SAAUhB,EAAAA,EAAS,EAK3B,OAJgBgB,EAAM,QACG,kBACED,IAERd,EAAAA,CACrB,CCNA,SAAgBgB,EAAS,CAAEP,WAAUD,YAAsC,CACzE,OAAO,EAAAF,EAAA,IAAA,CAACL,EAAAA,SAAD,CAAoBQ,WAAWD,UAAmB,CAAA,CAC3D,CCxBA,MAAaS,GAAA,EAAoBf,EAAAA,cAAAA,CAAqC,IAAI,EAO1E,SAAgBgB,EAAmB,CACjCC,OACAX,YACqC,CAKrC,OACE,EAAAF,EAAA,IAAA,CAACW,EAAkB,SAAnB,CAA4B,MAAOE,EAChCX,UACyB,CAAA,CAEhC,CCgCA,SAAgBY,EAAe,CAAEC,QAAwC,CACvE,IAAMF,GAAA,EAAOhB,EAAAA,WAAAA,CAAWc,CAAiB,EAqBzC,OAnBIE,IAQA,QAAQ,IAAI,WAAa,eACxB,CAAC,OAAO,UAAUE,CAAI,GAAKA,EAAO,KAAOA,EAAO,MAEjD,QAAQ,MACN,uCAAuC,OAAOA,CAAI,EAAE,+JACtD,EAGFF,EAAK,KAAOE,GAGP,IACT,CCxDA,SAAgBC,GAAuC,CACrD,MAAO,CAAE,KAAM,IAAA,EAAU,CAC3B,C"}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as RouteExitContext, c as useRouteExit, d as NotFoundProps, f as RouteViewProps, i as useRouteEnter, l as RouteView, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-BMee5rPb.js";
|
|
2
|
-
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-cv6g6fyL.js";
|
|
3
|
-
import { i as Link, n as DirectionTracker, r as createDirectionTracker, t as RouterProvider } from "./RouterProvider-aGzPGMdt.js";
|
|
4
|
-
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-DC4JuM-k.js";
|
|
5
1
|
import { Navigator } from "@real-router/core";
|
|
6
2
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
3
|
+
import { a as RouteExitContext, c as useRouteExit, d as NotFoundProps, f as RouteViewProps, i as useRouteEnter, l as RouteView, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-DPy48OUb.js";
|
|
4
|
+
import { i as Link, n as DirectionTracker, r as createDirectionTracker, t as RouterProvider } from "./RouterProvider-BKRTJidB.js";
|
|
5
|
+
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-CacrxUKq.js";
|
|
6
|
+
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-v0sri3EI.js";
|
|
7
7
|
export { type DirectionTracker, Link, type LinkProps, type Navigator, type RouteEnterContext, type RouteEnterHandler, type RouteExitContext, type RouteExitHandler, RouteView, type MatchProps as RouteViewMatchProps, type NotFoundProps as RouteViewNotFoundProps, type RouteViewProps, type SelfProps as RouteViewSelfProps, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, type UseRouteEnterOptions, type UseRouteExitOptions, createDirectionTracker, useNavigator, useRoute, useRouteEnter, useRouteExit, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react"),t=require("@real-router/core"),n=require("@real-router/route-utils"),r=require("react/jsx-runtime");const i=require("./RouterProviderCore-Bo1mRyVZ.js"),a=require("./RouterProvider-CSxQyRg4.js"),o=require("./useRoute-cwvI_vQa.js");let s=require("@real-router/sources"),c=require("@real-router/core/api");function l(e){return null}l.displayName=`RouteView.Match`;function u(e){return null}u.displayName=`RouteView.Self`;function d(e){return null}d.displayName=`RouteView.NotFound`;const f=new Set([l,u,d]);function p(e,t,r){return t===``?!1:r?e===t:(0,n.startsWithSegment)(e,t)}function m(t,n){e.Children.forEach(t,t=>{(0,e.isValidElement)(t)&&(f.has(t.type)?n.push(t):m(t.props.children,n))})}function h(t,n,i,a,o){let s=o===void 0?t:(0,r.jsx)(e.Suspense,{fallback:o,children:t});return i?(0,r.jsx)(e.Activity,{mode:a,children:s},n):(0,r.jsx)(e.Fragment,{children:s},n)}function g(e,t){return e.type===d?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===u&&(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0)}function _(e,t,n,r,i){let a=e.props,{segment:o,exact:s=!1,keepAlive:c=!1,fallback:l}=a,u=n?`${n}.${o}`:o;return!i&&p(t,u,s)?{rendered:h(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:h(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function v(n,i,a,o){o.selfFound&&i===a?n.push(h(o.selfChildren,`__route-view-self__`,!1,`visible`,o.selfFallback)):i===t.UNKNOWN_ROUTE&&o.notFoundChildren!==null&&n.push((0,r.jsx)(e.Fragment,{children:o.notFoundChildren},`__route-view-not-found__`))}function y(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null,notFoundFound:!1},a=null,o=[];for(let s of e){if(g(s,i))continue;let e=_(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&v(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function b({nodeName:t,children:n}){let{route:a}=i.m(t),o=(0,e.useRef)(null);o.current??=new Set;let s=o.current,c=(0,e.useMemo)(()=>{let e=[];return m(n,e),e},[n]),l=a?.name??null,{rendered:u,activatedName:d}=(0,e.useMemo)(()=>{if(l===null)return{rendered:[],activatedName:null};let e=y(c,l,t,s);return{rendered:e.rendered,activatedName:e.activatedName}},[c,l,t,s]);return(0,e.useEffect)(()=>{d!==null&&s.add(d)},[d,s]),u.length>0?(0,r.jsx)(r.Fragment,{children:u}):null}b.displayName=`RouteView`;const x=Object.assign(b,{Match:l,Self:u,NotFound:d}),S=Object.freeze({destroy:()=>{}});exports.Link=a.n,exports.RouteView=x,exports.RouterErrorBoundary=i.a,exports.RouterProvider=a.t,exports.createDirectionTracker=function(e){if(typeof document>`u`)return S;let n=!1;document.documentElement.dataset.navDirection=`forward`;let r,i,a=!1,o=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}},s=()=>{let t=e.getState();return t!==void 0&&o(t)===globalThis.location.href},l=()=>{s()?r===void 0&&(n=!1):r===void 0?n=!0:i=globalThis.location.href};globalThis.addEventListener(`popstate`,l);let u=(0,c.getPluginApi)(e),d=()=>{r=void 0,n=i!==void 0,a=n,i=void 0},f=[u.addEventListener(t.events.TRANSITION_START,e=>{r=e,n&&!a&&s()&&(n=!1)}),u.addEventListener(t.events.TRANSITION_SUCCESS,d),u.addEventListener(t.events.TRANSITION_ERROR,e=>{if(r===void 0||e?.context===r.context){d();return}let t=e===void 0?void 0:o(e);(t===void 0||t===i)&&(i=void 0)}),u.addEventListener(t.events.TRANSITION_CANCEL,d),e.subscribeLeave(()=>{document.documentElement.dataset.navDirection=n?`back`:`forward`,n=!1})];return{destroy:()=>{for(let e of f)e();globalThis.removeEventListener(`popstate`,l),delete document.documentElement.dataset.navDirection}}},exports.useNavigator=i.i,exports.useRoute=o.t,exports.useRouteEnter=function(t,n){let{route:r,previousRoute:i}=o.t(),a=(0,e.useRef)(t),[c]=(0,e.useState)(()=>(0,s.createRouteEnterGate)()),l=n?.skipSameRoute??!0;(0,e.useLayoutEffect)(()=>{a.current=t}),(0,e.useEffect)(()=>{let e=c(r,i,l);e&&a.current(e)},[c,r,i,l])},exports.useRouteExit=function(t,n){let r=i.h(),a=(0,e.useRef)(t),o=n?.skipSameRoute??!0;(0,e.useLayoutEffect)(()=>{a.current=t}),(0,e.useEffect)(()=>r.subscribeLeave((0,s.guardLeaveListener)(e=>a.current(e),{skipSameRoute:o})),[r,o])},exports.useRouteNode=i.m,exports.useRouteUtils=i.r,exports.useRouter=i.h,exports.useRouterTransition=i.n;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["startsWithSegment","isValidElement","Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRef","useMemo","getPluginApi","events","useRouter","useRef","guardLeaveListener","useRoute","useRef","useState","createRouteEnterGate","require_useRoute","require_RouterProviderCore","require_RouterProvider","react","_real_router_core","_real_router_route_utils","react_jsx_runtime","_real_router_sources","_real_router_core_api","Match","Self","NotFound","MARKER_TYPES","isSegmentMatch","fullSegmentName","exact","routeName","collectElements","children","child","result","renderSlotElement","content","fallback","slotChildren","keepAlive","key","recordFallback","slots","processMatch","matchProps","nodeName","segment","alreadyActive","hasBeenActivated","appendFallback","rendered","buildRenderList","activatedName","elements","RouteViewRoot","hasBeenActivatedRef","collected","route","RouteView","NOOP_INSTANCE","createDirectionTracker","popstateFlag","inFlight","replay","passedOn","hrefOf","buildUrl","router","hash","state","url","landsOnRouterState","onPopstate","api","onSettled","unsubs","toState","href","unsub","useRouteExit","handlerRef","handler","skipSameRoute","options","context","useRouteEnter","gate","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,qYAEA,SAAgB2B,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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AAM,EAGR,WAAW,oBAAoB,WAAYN,CAAU,EACrD,OAAO,SAAS,gBAAgB,QAAQ,YAC1C,CACF,CACF,CClEA,SAAgBO,EACd,EACA,EACM,CACN,IAAMZ,EAAS5D,EAAAA,EAAU,EACnByE,GAAA,EAAaxE,EAAAA,OAAAA,CAAOyE,CAAO,EAC3BC,EAAgBC,GAAS,eAAiB,IAQhD,EAAAlE,EAAA,gBAAA,KAAsB,CACpB,EAAW,QAAUgE,CACvB,CAAC,GAED,EAAAhE,EAAA,UAAA,KAKSkD,EAAO,gBAAA,EACZ1D,EAAAA,mBAAAA,CAAoB,GAAYuE,EAAW,QAAQI,CAAO,EAAG,CAC3D,eACF,CAAC,CACH,EACC,CAACjB,EAAQe,CAAa,CAAC,CAC5B,CCtEA,SAAgBG,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkB3E,EAAAA,EAAS,EACpCsE,GAAA,EAAarE,EAAAA,OAAAA,CAAOsE,CAAO,EAW3B,CAACK,IAAA,EAAQ1E,EAAAA,SAAAA,MAAAA,EAAeC,EAAAA,qBAAAA,CAAqB,CAAC,EAC9CqE,EAAgBC,GAAS,eAAiB,IAKhD,EAAAlE,EAAA,gBAAA,KAAsB,CACpB,EAAW,QAAUgE,CACvB,CAAC,GAED,EAAAhE,EAAA,UAAA,KAAgB,CACd,IAAMmE,EAAUE,EAAK7B,EAAO8B,EAAeL,CAAa,EAEpDE,GACFJ,EAAW,QAAQI,CAAO,CAE9B,EAAG,CAACE,EAAM7B,EAAO8B,EAAeL,CAAa,CAAC,CAChD,C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["startsWithSegment","Children","isValidElement","Suspense","Activity","Fragment","UNKNOWN_ROUTE","useRouteNode","useRef","useMemo","useEffect","getPluginApi","events","useRouter","useRef","useLayoutEffect","useEffect","guardLeaveListener","useRoute","useRef","useState","createRouteEnterGate","useLayoutEffect","useEffect","react","_real_router_core","_real_router_route_utils","react_jsx_runtime","require_RouterProviderCore","require_RouterProvider","require_useRoute","_real_router_sources","_real_router_core_api","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","router","popstateFlag","inFlight","replay","passedOn","hrefOf","state","buildUrl","hash","url","landsOnRouterState","onPopstate","api","onSettled","unsubs","toState","href","unsub","handler","options","previousRoute","handlerRef","gate","skipSameRoute","context"],"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,yYAEA,SAAgBiC,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,GAGvB,EAAOxC,EAAAA,kBAAAA,CAAkBuC,EAAWC,CAAe,CACrD,CAEA,SAAgBE,EACdC,EACAC,EACM,CAYN3C,EAAAA,SAAS,QAAQ0C,EAAWE,GAAU,EAChC,EAAC3C,EAAAA,eAAAA,CAAe2C,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,GAEA,EAAApB,EAAA,IAAA,CAACxB,EAAAA,SAAD,CAAoBgD,WAAW,SAAAJ,CAAuB,CAAA,EAW1D,OARIE,GAEA,EAAAtB,EAAA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AW,QAAQG,CAAO,CAE9B,EAAG,CAACF,EAAM3B,EAAOyB,EAAeG,CAAa,CAAC,CAChD,E,qBDQA,SACEL,EACAC,EACM,CACN,IAAMnB,EAAS3D,EAAAA,EAAU,EACnBgF,GAAA,EAAa/E,EAAAA,OAAAA,CAAO4E,CAAO,EAC3BK,EAAgBJ,GAAS,eAAiB,IAQhD5E,EAAAA,EAAAA,gBAAAA,KAAsB,CACpB8E,EAAW,QAAUH,CACvB,CAAC,GAED1E,EAAAA,EAAAA,UAAAA,KAKSwD,EAAO,gBAAA,EACZvD,EAAAA,mBAAAA,CAAoB+E,GAAYH,EAAW,QAAQG,CAAO,EAAG,CAC3DD,eACF,CAAC,CACH,EACC,CAACvB,EAAQuB,CAAa,CAAC,CAC5B,E"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as RouteExitContext, d as NotFoundProps, f as RouteViewProps, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-BMee5rPb.js";
|
|
2
|
-
import { n as RouterErrorBoundaryProps, r as LinkProps } from "./RouterErrorBoundary-cv6g6fyL.js";
|
|
3
1
|
import { Navigator } from "@real-router/core";
|
|
4
2
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
3
|
+
import { n as RouterErrorBoundaryProps, r as LinkProps } from "./RouterErrorBoundary-CacrxUKq.js";
|
|
4
|
+
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-DPy48OUb.js";
|
|
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/cjs/ink.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { n as RouterErrorBoundaryProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-cv6g6fyL.js";
|
|
2
|
-
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-DC4JuM-k.js";
|
|
3
|
-
import { FC, ReactNode } from "react";
|
|
4
1
|
import { NavigationOptions, Navigator, Params, Router, SearchParams } from "@real-router/core";
|
|
2
|
+
import { FC, ReactNode } from "react";
|
|
5
3
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
4
|
+
import { n as RouterErrorBoundaryProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-CacrxUKq.js";
|
|
5
|
+
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-v0sri3EI.js";
|
|
6
6
|
interface InkLinkProps<P extends Params = Params> {
|
|
7
7
|
routeName: string;
|
|
8
8
|
routeParams?: P;
|
package/dist/cjs/ink.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("ink"),t=require("react");const n=require("./useRoute-cwvI_vQa.js"),r=require("./RouterProviderCore-Bo1mRyVZ.js");let i=require("react/jsx-runtime");function a(e,t,n,r,i){return e?n??r??i:t?r??i:i}function o(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&&r.d(e.routeParams,t.routeParams)&&r.d(e.routeSearch,t.routeSearch)&&r.d(e.routeOptions,t.routeOptions)}const s=(0,t.memo)(({routeName:t,routeParams:o,routeSearch:s,routeOptions:c=n.n,activeStrict:l=!1,ignoreQueryParams:u=!0,color:d,activeColor:f,focusColor:p,inverse:m,activeInverse:h,focusInverse:g,id:_,autoFocus:v,onSelect:y,children:b})=>{let x=r.h(),{isFocused:S}=(0,e.useFocus)({..._!==void 0&&{id:_},...v!==void 0&&{autoFocus:v}}),C=r.o(t,o,s,l,u),w=o??n.r;(0,e.useInput)((e,n)=>{if(n.return){try{y?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}x.navigate(t,w,s,c).catch(()=>{})}},{isActive:S});let T=a(S,C,p,f,d),E=a(S,C,g,h,m),D={};return T!==void 0&&(D.color=T),E!==void 0&&(D.inverse=E),(0,i.jsx)(e.Text,{...D,children:b})},o);s.displayName=`InkLink`;const c=({router:e,children:t})=>(0,i.jsx)(r.t,{router:e,children:t});exports.InkLink=s,exports.InkRouterProvider=c,exports.RouterErrorBoundary=r.a,exports.useNavigator=r.i,exports.useRoute=n.t,exports.useRouteNode=r.m,exports.useRouteUtils=r.r,exports.useRouter=r.h,exports.useRouterTransition=r.n;
|
|
2
2
|
//# sourceMappingURL=ink.js.map
|
package/dist/cjs/ink.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ink.js","names":["shallowEqual","EMPTY_OPTIONS","useRouter","useFocus","useIsActiveRoute","EMPTY_PARAMS","Text","memo","RouterProviderCore","
|
|
1
|
+
{"version":3,"file":"ink.js","names":["shallowEqual","EMPTY_OPTIONS","useRouter","useFocus","useIsActiveRoute","EMPTY_PARAMS","useInput","Text","memo","RouterProviderCore","ink","react","require_useRoute","require_RouterProviderCore","react_jsx_runtime","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,sOAiBA,SAASe,EACPC,EACAC,EACAC,EACAC,EACAC,EACe,CASf,OARIJ,EACKE,GAAcC,GAAeC,EAGlCH,EACKE,GAAeC,EAGjBA,CACT,CAEA,SAASC,EACPC,EACAC,EACS,CACT,OACED,EAAK,YAAcC,EAAK,WACxBD,EAAK,eAAiBC,EAAK,cAC3BD,EAAK,oBAAsBC,EAAK,mBAChCD,EAAK,QAAUC,EAAK,OACpBD,EAAK,cAAgBC,EAAK,aAC1BD,EAAK,aAAeC,EAAK,YACzBD,EAAK,UAAYC,EAAK,SACtBD,EAAK,gBAAkBC,EAAK,eAC5BD,EAAK,eAAiBC,EAAK,cAC3BD,EAAK,KAAOC,EAAK,IACjBD,EAAK,YAAcC,EAAK,WACxBD,EAAK,WAAaC,EAAK,UACvBD,EAAK,WAAaC,EAAK,UACvBvB,EAAAA,EAAasB,EAAK,YAAaC,EAAK,WAAW,GAC/CvB,EAAAA,EAAasB,EAAK,YAAaC,EAAK,WAAW,GAC/CvB,EAAAA,EAAasB,EAAK,aAAcC,EAAK,YAAY,CAErD,CAmGA,MAAaC,GAAA,EAA4BhB,EAAAA,KAAAA,EAjGF,CACrCiB,YACAC,cACAC,cACAC,eAAe3B,EAAAA,EACf4B,eAAe,GACfC,oBAAoB,GACpBC,QACAC,cACAC,aACAC,UACAC,gBACAC,eACAC,KACAC,YACAC,WACAC,cACI,CACJ,IAAMC,EAASvC,EAAAA,EAAU,EACnB,CAAEc,cAAA,EAAcb,EAAAA,SAAAA,CAAS,CAC7B,GAAIkC,IAAO,IAAA,IAAa,CAAEA,IAAG,EAC7B,GAAIC,IAAc,IAAA,IAAa,CAAEA,WAAU,CAC7C,CAAC,EAOKrB,EAAgBb,EAAAA,EACpBqB,EACAC,EACAC,EACAE,EACAC,CACF,EAGMY,EAAehB,GAAerB,EAAAA,GAKpCC,EAAAA,EAAAA,SAAAA,EACGqC,EAAQC,IAAQ,CACf,GAAIA,EAAI,OAAQ,CAMd,GAAI,CACFL,IAAW,CACb,OAASM,EAAO,CACd,QAAQ,MACN,oEACAA,CACF,CACF,CAGAJ,EACG,SAAShB,EAAWiB,EAAcf,EAAaC,CAAY,CAAC,CAC5D,UAAY,CAAC,CAAC,CACnB,CACF,EACA,CAAE,SAAUZ,CAAU,CACxB,EAEA,IAAM8B,EAAa/B,EACjBC,EACAC,EACAgB,EACAD,EACAD,CACF,EACMgB,EAAehC,EACnBC,EACAC,EACAmB,EACAD,EACAD,CACF,EAEMc,EAAmD,CAAC,EAU1D,OARIF,IAAe,IAAA,KACjBE,EAAU,MAAQF,GAGhBC,IAAiB,IAAA,KACnBC,EAAU,QAAUD,IAGf,EAAAjC,EAAA,IAAA,CAACP,EAAAA,KAAD,CAAM,GAAIyC,EAAYR,UAAe,CAAA,CAC9C,EAIEnB,CACF,EAEAG,EAAQ,YAAc,UCzJtB,MAAayB,GAAiD,CAC5DR,SACAD,eACI,EAAA1B,EAAA,IAAA,CAACL,EAAAA,EAAD,CAA4BgC,SAASD,UAA6B,CAAA,E"}
|
package/dist/cjs/legacy.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-cv6g6fyL.js";
|
|
2
|
-
import { i as Link, t as RouterProvider } from "./RouterProvider-aGzPGMdt.js";
|
|
3
|
-
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-DC4JuM-k.js";
|
|
4
1
|
import { Navigator } from "@real-router/core";
|
|
5
2
|
import { RouterTransitionSnapshot } from "@real-router/sources";
|
|
3
|
+
import { i as Link, t as RouterProvider } from "./RouterProvider-BKRTJidB.js";
|
|
4
|
+
import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-CacrxUKq.js";
|
|
5
|
+
import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-v0sri3EI.js";
|
|
6
6
|
export { Link, type LinkProps, type Navigator, RouterErrorBoundary, type RouterErrorBoundaryProps, RouterProvider, type RouterTransitionSnapshot, useNavigator, useRoute, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
|
package/dist/cjs/legacy.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RouterProvider-CSxQyRg4.js"),t=require("./RouterProviderCore-Bo1mRyVZ.js"),n=require("./useRoute-cwvI_vQa.js");exports.Link=e.n,exports.RouterErrorBoundary=t.a,exports.RouterProvider=e.t,exports.useNavigator=t.i,exports.useRoute=n.t,exports.useRouteNode=t.m,exports.useRouteUtils=t.r,exports.useRouter=t.h,exports.useRouterTransition=t.n;
|
package/dist/cjs/legacy.ssr.d.ts
CHANGED
|
@@ -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-vxiMth62.js";
|
|
2
|
+
import { t as useDeferred } from "./useDeferred-vxGvmdkN.js";
|
|
3
3
|
export { ClientOnly, type ClientOnlyProps, HttpStatusCode, type HttpStatusCodeProps, HttpStatusProvider, type HttpStatusProviderProps, type HttpStatusSink, ServerOnly, type ServerOnlyProps, Streamed, type StreamedProps, createHttpStatusSink, useDeferred };
|
package/dist/cjs/legacy.ssr.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./createHttpStatusSink-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./createHttpStatusSink-CrJYxt4F.js");exports.ClientOnly=e.s,exports.HttpStatusCode=e.n,exports.HttpStatusProvider=e.r,exports.ServerOnly=e.o,exports.Streamed=e.i,exports.createHttpStatusSink=e.t,exports.useDeferred=e.a;
|
package/dist/cjs/ssr.d.ts
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-vxiMth62.js";
|
|
2
|
+
import { n as AwaitProps, t as Await } from "./Await-C1cvOY2U.js";
|
|
3
|
+
import { t as useDeferred } from "./useDeferred-vxGvmdkN.js";
|
|
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/cjs/ssr.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./createHttpStatusSink-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./createHttpStatusSink-CrJYxt4F.js");let t=require("react");exports.Await=function({name:n,children:r}){return r((0,t.use)(e.a(n)))},exports.ClientOnly=e.s,exports.HttpStatusCode=e.n,exports.HttpStatusProvider=e.r,exports.ServerOnly=e.o,exports.Streamed=e.i,exports.createHttpStatusSink=e.t,exports.useDeferred=e.a;
|
|
2
2
|
//# sourceMappingURL=ssr.js.map
|
package/dist/cjs/ssr.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr.js","names":["use","useDeferred","require_createHttpStatusSink","react","
|
|
1
|
+
{"version":3,"file":"ssr.js","names":["use","useDeferred","require_createHttpStatusSink","react","name","children"],"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,8JAsCA,SAAmC,CACjCI,OACAC,YAC2B,CAG3B,OAAOA,GAAA,EAFOL,EAAAA,IAAAA,CAAIC,EAAAA,EAAeG,CAAI,CAEjB,CAAC,CACvB,E"}
|
|
@@ -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-vxiMth62.js";
|
|
2
|
+
import { n as AwaitProps } from "./Await-C1cvOY2U.js";
|
|
3
3
|
export type { AwaitProps, ClientOnlyProps, HttpStatusCodeProps, HttpStatusProviderProps, HttpStatusSink, ServerOnlyProps, StreamedProps };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useDeferred-vxGvmdkN.d.ts","names":[],"sources":["../../src/hooks/useDeferred.tsx"],"mappings":";;;;;;;;;;;;;;;;;;;iBA0BgB,YAAY,aAAa,cAAc,QAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
let e=require("react");const t=(0,e.createContext)(null),n=(0,e.createContext)(null),r=(0,e.createContext)(null),i=Object.freeze({}),a=Object.freeze({}),o=new Promise(()=>{}),s=()=>{let n=(0,e.useContext)(t);if(!n)throw Error(`useRoute must be used within a RouterProvider`);if(!n.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 n};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
2
|
-
//# sourceMappingURL=useRoute-
|
|
2
|
+
//# sourceMappingURL=useRoute-cwvI_vQa.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRoute-
|
|
1
|
+
{"version":3,"file":"useRoute-cwvI_vQa.js","names":["createContext","useContext","react","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,uBASA,MAAaG,GAAA,EAAeH,EAAAA,cAAAA,CAAuC,IAAI,EAE1DI,GAAA,EAAgBJ,EAAAA,cAAAA,CAA6B,IAAI,EAEjDK,GAAA,EAAmBL,EAAAA,cAAAA,CAAgC,IAAI,ECbvDM,EAAe,OAAO,OAAO,CAAC,CAAC,EAE/BC,EAAgB,OAAO,OAAO,CAAC,CAAC,EAIhCC,EAAgB,IAAI,YAAqB,CAGtD,CAAC,ECQYC,MAAgE,CAC3E,IAAMC,GAAA,EAAeT,EAAAA,WAAAA,CAAWE,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-DPy48OUb.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRouteEnter-
|
|
1
|
+
{"version":3,"file":"useRouteEnter-DPy48OUb.d.ts","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-CacrxUKq.js";
|
|
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-v0sri3EI.d.ts.map
|
package/dist/cjs/{useRouterTransition-DC4JuM-k.d.ts.map → useRouterTransition-v0sri3EI.d.ts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRouterTransition-
|
|
1
|
+
{"version":3,"file":"useRouterTransition-v0sri3EI.d.ts","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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Await-
|
|
1
|
+
{"version":3,"file":"Await-imAt8sxf.d.mts","names":[],"sources":["../../src/components/Await.tsx"],"mappings":";UAMiB,WAAW;;WAEjB;;;WAGA,WAAW,OAAO,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2BnB,MAAM,eACpB,MACA,YACC,WAAW,KAAK"}
|
|
@@ -113,4 +113,4 @@ interface HttpStatusProviderProps {
|
|
|
113
113
|
}
|
|
114
114
|
declare function HttpStatusProvider({ sink, children }: HttpStatusProviderProps): ReactNode;
|
|
115
115
|
export { HttpStatusCode as a, StreamedProps as c, ClientOnly as d, ClientOnlyProps as f, createHttpStatusSink as i, ServerOnly as l, HttpStatusProviderProps as n, HttpStatusCodeProps as o, HttpStatusSink as r, Streamed as s, HttpStatusProvider as t, ServerOnlyProps as u };
|
|
116
|
-
//# sourceMappingURL=HttpStatusProvider-
|
|
116
|
+
//# sourceMappingURL=HttpStatusProvider-baKExhAC.d.mts.map
|
package/dist/esm/{HttpStatusProvider-BgspYBOz.d.mts.map → HttpStatusProvider-baKExhAC.d.mts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpStatusProvider-
|
|
1
|
+
{"version":3,"file":"HttpStatusProvider-baKExhAC.d.mts","names":[],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts","../../src/components/HttpStatusProvider.tsx"],"mappings":";UAIiB;WACN,UAAU;WACV,WAAW;;iBAGN,aACd,UACA,YACC,kBAAkB;UCRJ;WACN,UAAU;WACV,WAAW;;iBAGN,aACd,UACA,YACC,kBAAkB;UCRJ;;WAEN,UAAU;WACV,UAAU;;;;;;;;;;;;;;;;;;;iBAoBL,WAAW,UAAU,YAAY,gBAAgB;UCrBhD;;WAEN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDK,iBAAiB,QAAQ,sBAAsB;;;;;;;;;;;;;;;;;;;;;UCrC9C;EACf;;iBAGc,wBAAwB;UCjBvB;WACN,MAAM;WACN,UAAU;;iBAGL,qBACd,MACA,YACC,0BAA0B"}
|
|
@@ -62,4 +62,4 @@ interface RouterErrorBoundaryProps {
|
|
|
62
62
|
}
|
|
63
63
|
declare function RouterErrorBoundary({ children, fallback, onError }: RouterErrorBoundaryProps): ReactElement;
|
|
64
64
|
export { RouteContext as i, RouterErrorBoundaryProps as n, LinkProps as r, RouterErrorBoundary as t };
|
|
65
|
-
//# sourceMappingURL=RouterErrorBoundary-
|
|
65
|
+
//# sourceMappingURL=RouterErrorBoundary-mrfP832K.d.mts.map
|
package/dist/esm/{RouterErrorBoundary-cv6g6fyL.d.mts.map → RouterErrorBoundary-mrfP832K.d.mts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RouterErrorBoundary-
|
|
1
|
+
{"version":3,"file":"RouterErrorBoundary-mrfP832K.d.mts","names":[],"sources":["../../src/types.ts","../../src/components/RouterErrorBoundary.tsx"],"mappings":";;UAUiB,WAAW,UAAU,SAAS;EAC7C,OAAO,MAAM;EACb,gBAAgB;;KAGN,aAAa,UAAU,SAAS,UAAU,WAAW;EAC/D,WAAW;;;;;;;UAQH,wBAAwB,eAAe;EAC/C,eAAe;EACf;EACA;EACA;;;;;;;;;;EAUA;EACA;EACA,UAAU,kBAAkB;EAC5B,cAAc,kBAAkB;;;UAIxB,iBAAiB,UAAU,SAAS;EAC5C;EACA,cAAc;;;;;;;EAOd,cAAc;EACd;;;;;;UAOQ,oBAAoB,UAAU,SAAS;EAC/C,IAAI,iBAAiB;EACrB;EACA;EACA;;KAGU,UAAU,UAAU,SAAS,UAAU,mBAChD,iBAAiB,KAAK,oBAAoB;UCxD5B;WACN,UAAU;WACV,WAAW,OAAO,aAAa,2BAA2B;WAC1D,WACP,OAAO,aACP,SAAS,cACT,WAAW;;iBAIC,sBACd,UACA,UACA,WACC,2BAA2B"}
|