@native-router/react 1.6.0 → 1.6.2
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 +10 -1
- package/dist/components/Link.cjs +2 -0
- package/dist/components/Link.cjs.map +1 -0
- package/dist/components/Link.js +3 -0
- package/dist/components/Link.js.map +1 -0
- package/dist/components/NavLink.cjs +2 -0
- package/dist/components/NavLink.cjs.map +1 -0
- package/dist/components/NavLink.js +3 -0
- package/dist/components/NavLink.js.map +1 -0
- package/dist/components/PrefetchLink.cjs +2 -0
- package/dist/components/PrefetchLink.cjs.map +1 -0
- package/dist/components/PrefetchLink.js +3 -0
- package/dist/components/PrefetchLink.js.map +1 -0
- package/dist/components/RouteErrorBoundary.cjs +2 -0
- package/dist/components/RouteErrorBoundary.cjs.map +1 -0
- package/dist/components/RouteErrorBoundary.js +2 -0
- package/dist/components/RouteErrorBoundary.js.map +1 -0
- package/dist/components/Router.cjs +2 -0
- package/dist/components/Router.cjs.map +1 -0
- package/dist/components/Router.js +4 -0
- package/dist/components/Router.js.map +1 -0
- package/dist/components/ScrollRestoration.cjs +2 -0
- package/dist/components/ScrollRestoration.cjs.map +1 -0
- package/dist/components/ScrollRestoration.js +2 -0
- package/dist/components/ScrollRestoration.js.map +1 -0
- package/dist/components/TypedLink.cjs +2 -0
- package/dist/components/TypedLink.cjs.map +1 -0
- package/dist/components/TypedLink.js +3 -0
- package/dist/components/TypedLink.js.map +1 -0
- package/dist/components/link-behavior.cjs +2 -0
- package/dist/components/link-behavior.cjs.map +1 -0
- package/dist/components/link-behavior.js +2 -0
- package/dist/components/link-behavior.js.map +1 -0
- package/dist/context.cjs +2 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.js +4 -0
- package/dist/context.js.map +1 -0
- package/dist/create-routes.cjs +2 -0
- package/dist/create-routes.cjs.map +1 -0
- package/dist/create-routes.js +2 -0
- package/dist/create-routes.js.map +1 -0
- package/dist/index.cjs +1 -2
- package/dist/index.js +1 -6
- package/dist/resolve-view.cjs +2 -0
- package/dist/resolve-view.cjs.map +1 -0
- package/dist/resolve-view.js +3 -0
- package/dist/resolve-view.js.map +1 -0
- package/dist/server.cjs +2 -1
- package/dist/server.cjs.map +1 -0
- package/dist/server.js +3 -1
- package/dist/server.js.map +1 -0
- package/dist/ssr.cjs +2 -0
- package/dist/ssr.cjs.map +1 -0
- package/dist/ssr.js +2 -0
- package/dist/ssr.js.map +1 -0
- package/dist/types/index.d.ts +0 -1
- package/dist/types/server.d.ts +11 -1
- package/dist/types/ssr.d.ts +3 -11
- package/dist/types/types.d.ts +1 -1
- package/dist/use-blocker.cjs +2 -0
- package/dist/use-blocker.cjs.map +1 -0
- package/dist/use-blocker.js +2 -0
- package/dist/use-blocker.js.map +1 -0
- package/dist/use-search-params.cjs +2 -0
- package/dist/use-search-params.cjs.map +1 -0
- package/dist/use-search-params.js +2 -0
- package/dist/use-search-params.js.map +1 -0
- package/package.json +9 -5
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/ssr-873l9jA-.js +0 -8
- package/dist/ssr-873l9jA-.js.map +0 -1
- package/dist/ssr-C-Bgsx5W.cjs +0 -2
- package/dist/ssr-C-Bgsx5W.cjs.map +0 -1
package/dist/server.cjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./resolve-view.cjs"),r=require("./components/Router.cjs");let t=require("history"),i=require("react/jsx-runtime"),o=require("@native-router/core"),n=require("@native-router/core/util");function s(t,n,s){return(0,o.resolve)(t,n).then(o=>{const a=e.getViewData(o),u=t.history.location.state?.index||0;return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(r.Router,{router:t,children:o}),(0,i.jsx)("script",{...s?.scriptAttributes,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`window.${s?.hydrateKey||"_nativeRouterReactSSRData"} = ${c={data:a,location:n,index:u},JSON.stringify(c).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};`}})]});var c})}exports.resolveServerView=function(r,i,{scriptAttributes:a,hydrateKey:u,...c}={}){const l=(0,o.create)(r,(0,t.createMemoryHistory)({initialEntries:[i]}),e.resolveViewServer,c);return s(l,(0,n.isString)(i)?(0,o.toLocation)(l,i):i,{scriptAttributes:a,hydrateKey:u})},exports.resolveServerViewBase=s;
|
|
2
|
+
//# sourceMappingURL=server.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.cjs","names":[],"sources":["../src/server.tsx"],"sourcesContent":["import {createMemoryHistory} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve, toLocation} from '@native-router/core';\nimport type {\n HistoryState,\n Location,\n Options,\n RouterInstance\n} from '@native-router/core';\nimport {isString} from '@native-router/core/util';\nimport {Router} from './components/Router';\nimport {getViewData, resolveViewServer} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Serialize the SSR payload for embedding in a script element.\n * `JSON.stringify` does not escape `<`, U+2028 and U+2029,\n * so route data like `</script>` would break out of the script element.\n * @param payload the payload to serialize\n * @returns the escaped JSON string\n */\nfunction serializePayload(payload: {\n data?: any[];\n location: Location;\n index: number;\n}) {\n return JSON.stringify(payload)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\nexport function resolveServerViewBase(\n router: RouterInstance<Route, ReactNode>,\n location: Location,\n options?: {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n }\n) {\n return resolve<Route, ReactNode>(router, location).then((view) => {\n const data = getViewData(view as ReactElement);\n const index =\n (router.history.location.state as HistoryState | undefined)?.index || 0;\n return (\n <>\n <Router router={router}>{view}</Router>\n <script\n {...options?.scriptAttributes}\n suppressHydrationWarning\n // eslint-disable-next-line @eslint-react/dom-no-dangerously-set-innerhtml -- serialized state for hydration\n dangerouslySetInnerHTML={{\n __html: `window.${\n options?.hydrateKey || defaultHydrateKey\n } = ${serializePayload({data, location, index})};`\n }}\n />\n </>\n );\n });\n}\n\nexport function resolveServerView(\n routes: Route | Route[],\n location: Location | string,\n {\n scriptAttributes,\n hydrateKey,\n ...options\n }: Options<ReactElement> & {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n } = {}\n) {\n const router = create(\n routes,\n createMemoryHistory({initialEntries: [location]}),\n resolveViewServer,\n options\n );\n\n return resolveServerViewBase(\n router,\n isString(location) ? toLocation(router, location) : location,\n {\n scriptAttributes,\n hydrateKey\n }\n );\n}\n"],"mappings":"6QAkCA,SAAgB,EACd,EACA,EACA,GAKA,OAAA,EAAO,EAAA,SAA0B,EAAQ,GAAU,KAAM,IACvD,MAAM,EAAO,EAAA,YAAY,GACnB,EACH,EAAO,QAAQ,SAAS,OAAoC,OAAS,EACxE,OACE,EAAA,EAAA,MAAA,EAAA,SAAA,CAAA,SAAA,EACE,EAAA,EAAA,KAAC,EAAA,OAAD,CAAgB,SAAS,SAAA,KACzB,EAAA,EAAA,KAAC,SAAD,IACM,GAAS,iBACb,0BAAA,EAEA,wBAAyB,CACvB,OAAQ,UACN,GAAS,YAzCG,iCASA,EAiCS,CAAC,OAAM,WAAU,SA5B3C,KAAK,UAAU,GACnB,QAAQ,KAAM,WACd,QAAQ,UAAW,WACnB,QAAQ,UAAW,oBARxB,IAA0B,GAuC1B,2BAEA,SACE,EACA,GACA,iBACE,EAAA,WACA,KACG,GAID,CAAC,GAEL,MAAM,GAAA,EAAS,EAAA,QACb,GAAA,EACA,EAAA,qBAAoB,CAAC,eAAgB,CAAC,KACtC,EAAA,kBACA,GAGF,OAAO,EACL,GAAA,EACA,EAAA,UAAS,IAAQ,EAAI,EAAA,YAAW,EAAQ,GAAY,EACpD,CACE,mBACA,cAGN"}
|
package/dist/server.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{getViewData as t,resolveViewServer as r}from"./resolve-view.js";import{Router as e}from"./components/Router.js";import{createMemoryHistory as i}from"history";import{Fragment as o,jsx as n,jsxs as a}from"react/jsx-runtime";import{create as s,resolve as u,toLocation as c}from"@native-router/core";import{isString as p}from"@native-router/core/util";function m(r,i,s){return u(r,i).then(u=>{const c=t(u),p=r.history.location.state?.index||0;/* @__PURE__ */
|
|
2
|
+
return a(o,{children:[/* @__PURE__ */n(e,{router:r,children:u}),/* @__PURE__ */n("script",{...s?.scriptAttributes,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`window.${s?.hydrateKey||"_nativeRouterReactSSRData"} = ${m={data:c,location:i,index:p},JSON.stringify(m).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};`}})]});var m})}function l(t,e,{scriptAttributes:o,hydrateKey:n,...a}={}){const u=s(t,i({initialEntries:[e]}),r,a);return m(u,p(e)?c(u,e):e,{scriptAttributes:o,hydrateKey:n})}export{l as resolveServerView,m as resolveServerViewBase};
|
|
3
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","names":[],"sources":["../src/server.tsx"],"sourcesContent":["import {createMemoryHistory} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve, toLocation} from '@native-router/core';\nimport type {\n HistoryState,\n Location,\n Options,\n RouterInstance\n} from '@native-router/core';\nimport {isString} from '@native-router/core/util';\nimport {Router} from './components/Router';\nimport {getViewData, resolveViewServer} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Serialize the SSR payload for embedding in a script element.\n * `JSON.stringify` does not escape `<`, U+2028 and U+2029,\n * so route data like `</script>` would break out of the script element.\n * @param payload the payload to serialize\n * @returns the escaped JSON string\n */\nfunction serializePayload(payload: {\n data?: any[];\n location: Location;\n index: number;\n}) {\n return JSON.stringify(payload)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\nexport function resolveServerViewBase(\n router: RouterInstance<Route, ReactNode>,\n location: Location,\n options?: {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n }\n) {\n return resolve<Route, ReactNode>(router, location).then((view) => {\n const data = getViewData(view as ReactElement);\n const index =\n (router.history.location.state as HistoryState | undefined)?.index || 0;\n return (\n <>\n <Router router={router}>{view}</Router>\n <script\n {...options?.scriptAttributes}\n suppressHydrationWarning\n // eslint-disable-next-line @eslint-react/dom-no-dangerously-set-innerhtml -- serialized state for hydration\n dangerouslySetInnerHTML={{\n __html: `window.${\n options?.hydrateKey || defaultHydrateKey\n } = ${serializePayload({data, location, index})};`\n }}\n />\n </>\n );\n });\n}\n\nexport function resolveServerView(\n routes: Route | Route[],\n location: Location | string,\n {\n scriptAttributes,\n hydrateKey,\n ...options\n }: Options<ReactElement> & {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n } = {}\n) {\n const router = create(\n routes,\n createMemoryHistory({initialEntries: [location]}),\n resolveViewServer,\n options\n );\n\n return resolveServerViewBase(\n router,\n isString(location) ? toLocation(router, location) : location,\n {\n scriptAttributes,\n hydrateKey\n }\n );\n}\n"],"mappings":"mWAkCA,SAAgB,EACd,EACA,EACA,GAKA,OAAO,EAA0B,EAAQ,GAAU,KAAM,IACvD,MAAM,EAAO,EAAY,GACnB,EACH,EAAO,QAAQ,SAAS,OAAoC,OAAS;AACxE,OACE,EAAA,EAAA,CAAA,SAAA,gBACE,EAAC,EAAD,CAAgB,SAAS,SAAA,mBACzB,EAAC,SAAD,IACM,GAAS,iBACb,0BAAA,EAEA,wBAAyB,CACvB,OAAQ,UACN,GAAS,YAzCG,iCASA,EAiCS,CAAC,OAAM,WAAU,SA5B3C,KAAK,UAAU,GACnB,QAAQ,KAAM,WACd,QAAQ,UAAW,WACnB,QAAQ,UAAW,oBARxB,IAA0B,GAuC1B,CAEA,SAAgB,EACd,EACA,GACA,iBACE,EAAA,WACA,KACG,GAID,CAAC,GAEL,MAAM,EAAS,EACb,EACA,EAAoB,CAAC,eAAgB,CAAC,KACtC,EACA,GAGF,OAAO,EACL,EACA,EAAS,GAAY,EAAW,EAAQ,GAAY,EACpD,CACE,mBACA,cAGN"}
|
package/dist/ssr.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./resolve-view.cjs");let t=require("history"),r=require("@native-router/core");exports.hydrate=function(o,a){const{data:i,location:c,index:n=0}=window[a?.hydrateKey||"_nativeRouterReactSSRData"],s=(0,t.createBrowserHistory)();s.replace((0,t.createPath)(s.location),{index:n});const l=(0,r.create)(o,s,e.createHydrateResolveView(i),a);return(0,r.resolve)(l,c).then(t=>(l.viewStack[0]=t,l.resolveView=e.default,{view:t,router:l}))};
|
|
2
|
+
//# sourceMappingURL=ssr.cjs.map
|
package/dist/ssr.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssr.cjs","names":[],"sources":["../src/ssr.tsx"],"sourcesContent":["import {createBrowserHistory, createPath} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve} from '@native-router/core';\nimport type {Location, Options, RouterInstance} from '@native-router/core';\nimport defaultResolveView, {createHydrateResolveView} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Hydrate the SSR result of {@link resolveServerView} on the client.\n * The router is bound to the browser history(aligned with the index\n * in the SSR payload), so navigation after hydration updates the address bar.\n * @param routes routes config, must match the server side\n * @param options options, `hydrateKey` must match the server side\n * @returns the resolved view and the router instance, for example:\n * `const {router} = await hydrate(routes);`\n * `hydrateRoot(root, <Router router={router}/>)`\n * @group Methods\n */\nexport function hydrate(\n routes: Route | Route[],\n options?: Options<ReactElement> & {\n hydrateKey?: string;\n }\n): Promise<{view: ReactNode; router: RouterInstance<Route, ReactNode>}> {\n const {\n data,\n location,\n index = 0\n } = (window as any)[options?.hydrateKey || defaultHydrateKey] as {\n data: any[];\n location: Location;\n index?: number;\n };\n const history = createBrowserHistory();\n history.replace(createPath(history.location), {index});\n const router = create<Route, ReactNode>(\n routes,\n history,\n createHydrateResolveView(data),\n options\n );\n return resolve<Route, ReactNode>(router, location).then((view) => {\n // Seed the resolved view into the view stack: one-shot resolves do\n // not enter it, but `getCurrentView(router)` must return the view\n // for the hydration render. With the stack seeded, a plain\n // `<Router router={router}/>` renders the store view — its first\n // (hydration) render matches the server HTML and later navigations\n // update through the same store.\n router.viewStack[0] = view;\n // The payload-backed resolver only covers the initial chain; every\n // later navigation resolves through the default resolver and runs\n // its own data loaders.\n router.resolveView = defaultResolveView;\n return {view, router};\n });\n}\n"],"mappings":"mLAoBA,SACE,EACA,GAIA,MAAM,KACJ,EAAA,SACA,EAAA,MACA,EAAQ,GACL,OAAe,GAAS,YAvBL,6BA4BlB,GAAA,EAAU,EAAA,wBAChB,EAAQ,SAAA,EAAQ,EAAA,YAAW,EAAQ,UAAW,CAAC,UAC/C,MAAM,GAAA,EAAS,EAAA,QACb,EACA,EACA,EAAA,yBAAyB,GACzB,GAEF,OAAA,EAAO,EAAA,SAA0B,EAAQ,GAAU,KAAM,IAOvD,EAAO,UAAU,GAAK,EAItB,EAAO,YAAc,EAAA,QACd,CAAC,OAAM,WAElB"}
|
package/dist/ssr.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import e,{createHydrateResolveView as o}from"./resolve-view.js";import{createBrowserHistory as t,createPath as r}from"history";import{create as i,resolve as n}from"@native-router/core";function a(a,c){const{data:v,location:m,index:s=0}=window[c?.hydrateKey||"_nativeRouterReactSSRData"],w=t();w.replace(r(w.location),{index:s});const d=i(a,w,o(v),c);return n(d,m).then(o=>(d.viewStack[0]=o,d.resolveView=e,{view:o,router:d}))}export{a as hydrate};
|
|
2
|
+
//# sourceMappingURL=ssr.js.map
|
package/dist/ssr.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssr.js","names":[],"sources":["../src/ssr.tsx"],"sourcesContent":["import {createBrowserHistory, createPath} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve} from '@native-router/core';\nimport type {Location, Options, RouterInstance} from '@native-router/core';\nimport defaultResolveView, {createHydrateResolveView} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Hydrate the SSR result of {@link resolveServerView} on the client.\n * The router is bound to the browser history(aligned with the index\n * in the SSR payload), so navigation after hydration updates the address bar.\n * @param routes routes config, must match the server side\n * @param options options, `hydrateKey` must match the server side\n * @returns the resolved view and the router instance, for example:\n * `const {router} = await hydrate(routes);`\n * `hydrateRoot(root, <Router router={router}/>)`\n * @group Methods\n */\nexport function hydrate(\n routes: Route | Route[],\n options?: Options<ReactElement> & {\n hydrateKey?: string;\n }\n): Promise<{view: ReactNode; router: RouterInstance<Route, ReactNode>}> {\n const {\n data,\n location,\n index = 0\n } = (window as any)[options?.hydrateKey || defaultHydrateKey] as {\n data: any[];\n location: Location;\n index?: number;\n };\n const history = createBrowserHistory();\n history.replace(createPath(history.location), {index});\n const router = create<Route, ReactNode>(\n routes,\n history,\n createHydrateResolveView(data),\n options\n );\n return resolve<Route, ReactNode>(router, location).then((view) => {\n // Seed the resolved view into the view stack: one-shot resolves do\n // not enter it, but `getCurrentView(router)` must return the view\n // for the hydration render. With the stack seeded, a plain\n // `<Router router={router}/>` renders the store view — its first\n // (hydration) render matches the server HTML and later navigations\n // update through the same store.\n router.viewStack[0] = view;\n // The payload-backed resolver only covers the initial chain; every\n // later navigation resolves through the default resolver and runs\n // its own data loaders.\n router.resolveView = defaultResolveView;\n return {view, router};\n });\n}\n"],"mappings":"yLAoBA,SAAgB,EACd,EACA,GAIA,MAAM,KACJ,EAAA,SACA,EAAA,MACA,EAAQ,GACL,OAAe,GAAS,YAvBL,6BA4BlB,EAAU,IAChB,EAAQ,QAAQ,EAAW,EAAQ,UAAW,CAAC,UAC/C,MAAM,EAAS,EACb,EACA,EACA,EAAyB,GACzB,GAEF,OAAO,EAA0B,EAAQ,GAAU,KAAM,IAOvD,EAAO,UAAU,GAAK,EAItB,EAAO,YAAc,EACd,CAAC,OAAM,WAElB"}
|
package/dist/types/index.d.ts
CHANGED
package/dist/types/server.d.ts
CHANGED
|
@@ -1 +1,11 @@
|
|
|
1
|
-
|
|
1
|
+
import { ReactElement, ReactNode } from 'react';
|
|
2
|
+
import type { Location, Options, RouterInstance } from '@native-router/core';
|
|
3
|
+
import type { Route } from './types';
|
|
4
|
+
export declare function resolveServerViewBase(router: RouterInstance<Route, ReactNode>, location: Location, options?: {
|
|
5
|
+
scriptAttributes?: Record<string, string>;
|
|
6
|
+
hydrateKey?: string;
|
|
7
|
+
}): Promise<import("react").JSX.Element>;
|
|
8
|
+
export declare function resolveServerView(routes: Route | Route[], location: Location | string, { scriptAttributes, hydrateKey, ...options }?: Options<ReactElement> & {
|
|
9
|
+
scriptAttributes?: Record<string, string>;
|
|
10
|
+
hydrateKey?: string;
|
|
11
|
+
}): Promise<import("react").JSX.Element>;
|
package/dist/types/ssr.d.ts
CHANGED
|
@@ -1,14 +1,6 @@
|
|
|
1
1
|
import { ReactElement, ReactNode } from 'react';
|
|
2
|
-
import type {
|
|
2
|
+
import type { Options, RouterInstance } from '@native-router/core';
|
|
3
3
|
import type { Route } from './types';
|
|
4
|
-
export declare function resolveServerViewBase(router: RouterInstance<Route, ReactNode>, location: Location, options?: {
|
|
5
|
-
scriptAttributes?: Record<string, string>;
|
|
6
|
-
hydrateKey?: string;
|
|
7
|
-
}): Promise<import("react").JSX.Element>;
|
|
8
|
-
export declare function resolveServerView(routes: Route | Route[], location: Location | string, { scriptAttributes, hydrateKey, ...options }?: Options<ReactElement> & {
|
|
9
|
-
scriptAttributes?: Record<string, string>;
|
|
10
|
-
hydrateKey?: string;
|
|
11
|
-
}): Promise<import("react").JSX.Element>;
|
|
12
4
|
/**
|
|
13
5
|
* Hydrate the SSR result of {@link resolveServerView} on the client.
|
|
14
6
|
* The router is bound to the browser history(aligned with the index
|
|
@@ -16,8 +8,8 @@ export declare function resolveServerView(routes: Route | Route[], location: Loc
|
|
|
16
8
|
* @param routes routes config, must match the server side
|
|
17
9
|
* @param options options, `hydrateKey` must match the server side
|
|
18
10
|
* @returns the resolved view and the router instance, for example:
|
|
19
|
-
* `const {
|
|
20
|
-
* `hydrateRoot(root, <Router router={router}
|
|
11
|
+
* `const {router} = await hydrate(routes);`
|
|
12
|
+
* `hydrateRoot(root, <Router router={router}/>)`
|
|
21
13
|
* @group Methods
|
|
22
14
|
*/
|
|
23
15
|
export declare function hydrate(routes: Route | Route[], options?: Options<ReactElement> & {
|
package/dist/types/types.d.ts
CHANGED
|
@@ -170,7 +170,7 @@ export type WithSearch<C, S> = Omit<C, 'search'> & {
|
|
|
170
170
|
* @group Types
|
|
171
171
|
* @category Route
|
|
172
172
|
*/
|
|
173
|
-
export type SearchRoutesOf<T> = T extends readonly
|
|
173
|
+
export type SearchRoutesOf<T> = T extends readonly unknown[] ? {
|
|
174
174
|
-readonly [K in keyof T]: SearchRoutesOf<T[K]>;
|
|
175
175
|
} : T extends Route ? T extends {
|
|
176
176
|
data?: infer Data;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./components/Router.cjs");let r=require("react"),t=require("@native-router/core");exports.useBlocker=function(u){const c=e.useRouter(),o=(0,r.useRef)(u);o.current=u,(0,r.useEffect)(()=>(0,t.setBlocker)(c,(e,r)=>o.current(e,r)),[c])};
|
|
2
|
+
//# sourceMappingURL=use-blocker.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-blocker.cjs","names":[],"sources":["../src/use-blocker.ts"],"sourcesContent":["import {useEffect, useRef} from 'react';\nimport {setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): void {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n useEffect(\n () => setBlocker(router, (to, from) => fnRef.current(to, from)),\n [router]\n );\n}\n"],"mappings":"sHA4BA,SAA2B,GACzB,MAAM,EAAS,EAAA,YACT,GAAA,EAAQ,EAAA,QAAO,GAGrB,EAAM,QAAU,GAChB,EAAA,EAAA,WAAA,KAAA,EACQ,EAAA,YAAW,EAAA,CAAS,EAAI,IAAS,EAAM,QAAQ,EAAI,IACzD,CAAC,GAEL"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{useRouter as r}from"./components/Router.js";import{useEffect as o,useRef as t}from"react";import{setBlocker as e}from"@native-router/core";function n(n){const c=r(),m=t(n);m.current=n,o(()=>e(c,(r,o)=>m.current(r,o)),[c])}export{n as useBlocker};
|
|
2
|
+
//# sourceMappingURL=use-blocker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-blocker.js","names":[],"sources":["../src/use-blocker.ts"],"sourcesContent":["import {useEffect, useRef} from 'react';\nimport {setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): void {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n useEffect(\n () => setBlocker(router, (to, from) => fnRef.current(to, from)),\n [router]\n );\n}\n"],"mappings":"kJA4BA,SAAgB,EAAW,GACzB,MAAM,EAAS,IACT,EAAQ,EAAO,GAGrB,EAAM,QAAU,EAChB,EAAA,IACQ,EAAW,EAAA,CAAS,EAAI,IAAS,EAAM,QAAQ,EAAI,IACzD,CAAC,GAEL"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./components/Router.cjs");let r=require("react"),t=require("@native-router/core"),n=require("use-sync-external-store/shim");function a(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,r])=>(Array.isArray(r)?r:[r]).map(r=>`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`).join("&")).join("&")}function o(e,r,n){const{history:a}=e,{pathname:o,hash:c}=a.location,s=o+(r?`?${r}`:"")+c;return n?.replace?(0,t.resolveEntry)(e,(0,t.toLocation)(e,s)).then(r=>(0,t.commitReplace)(e,r.task,r.location)):(0,t.navigate)(e,s)}exports.useSearch=function(a){const o=e.useRouter(),c=(0,r.useCallback)(e=>o.history.listen(()=>e()),[o]),s=(0,r.useCallback)(()=>o.history.location.search,[o]),u=(0,r.useCallback)(()=>"",[]),i=(0,n.useSyncExternalStore)(c,s,u);return a?(0,t.parseSearchSync)(a,i):(0,t.parseSearchInput)(i)},exports.useSearchParams=function(){const t=e.useRouter(),a=(0,r.useCallback)(e=>t.history.listen(()=>e()),[t]),c=(0,r.useCallback)(()=>t.history.location.search,[t]),s=(0,r.useCallback)(()=>"",[]);return[new URLSearchParams((0,n.useSyncExternalStore)(a,c,s)),(0,r.useCallback)((e,r)=>{const{history:n}=t,a="function"==typeof e?e(new URLSearchParams(n.location.search)):e;return o(t,a.toString(),r)},[t])]},exports.useSetSearch=function(n){const c=e.useRouter();return(0,r.useCallback)((e,r)=>{const{history:s}=c,u="function"==typeof e?e((0,t.parseSearchInput)(s.location.search)):e,i=(0,t.parseSearchSync)(n,a(u));return o(c,a(i),r)},[c,n])};
|
|
2
|
+
//# sourceMappingURL=use-search-params.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-search-params.cjs","names":[],"sources":["../src/use-search-params.ts"],"sourcesContent":["import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n"],"mappings":"6IA2IA,SAAS,EAAgB,GACvB,OAAO,OAAO,QAAQ,GACnB,OAAA,EAAQ,CAAG,KAAW,SACtB,IAAA,EAAM,EAAK,MACT,MAAM,QAAQ,GAAS,EAAQ,CAAC,IAC9B,IACE,GAAM,GAAG,mBAAmB,MAAQ,mBAAmB,OAAO,OAEhE,KAAK,MAET,KAAK,IACV,CAEA,SAAS,EACP,EACA,EACA,GAEA,MAAM,QAAC,GAAW,GACZ,SAAC,EAAA,KAAU,GAAQ,EAAQ,SAC3B,E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EAAQ,EAAgB,IAI1D,OAAO,EACL,EACA,EAAgB,GAChB,IAGJ,CAAC,EAAQ,GAEb"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{useRouter as t}from"./components/Router.js";import{useCallback as o}from"react";import{commitReplace as n,navigate as r,parseSearchInput as e,parseSearchSync as i,resolveEntry as c,toLocation as s}from"@native-router/core";import{useSyncExternalStore as a}from"use-sync-external-store/shim";function h(){const n=t(),r=o(t=>n.history.listen(()=>t()),[n]),e=o(()=>n.history.location.search,[n]),i=o(()=>"",[]);return[new URLSearchParams(a(r,e,i)),o((t,o)=>{const{history:r}=n,e="function"==typeof t?t(new URLSearchParams(r.location.search)):t;return f(n,e.toString(),o)},[n])]}function u(n){const r=t();return o((t,o)=>{const{history:c}=r,s="function"==typeof t?t(e(c.location.search)):t,a=i(n,m(s));return f(r,m(a),o)},[r,n])}function m(t){return Object.entries(t).filter(([,t])=>null!=t).map(([t,o])=>(Array.isArray(o)?o:[o]).map(o=>`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`).join("&")).join("&")}function f(t,o,e){const{history:i}=t,{pathname:a,hash:h}=i.location,u=a+(o?`?${o}`:"")+h;return e?.replace?c(t,s(t,u)).then(o=>n(t,o.task,o.location)):r(t,u)}function p(n){const r=t(),c=o(t=>r.history.listen(()=>t()),[r]),s=o(()=>r.history.location.search,[r]),h=o(()=>"",[]),u=a(c,s,h);return n?i(n,u):e(u)}export{p as useSearch,h as useSearchParams,u as useSetSearch};
|
|
2
|
+
//# sourceMappingURL=use-search-params.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-search-params.js","names":[],"sources":["../src/use-search-params.ts"],"sourcesContent":["import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n"],"mappings":"0SA4CA,SAAgB,IACd,MAAM,EAAS,IAIT,EAAY,EACf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,CAAC,IAGG,EAAoB,EAAA,IAAkB,GAAI,IAE1C,EAAS,EACb,EACA,EACA,GAGF,OAAO,EAAS,EAAgB,EAAQ,GAAU,EAAiB,EACrE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@native-router/react",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -8,6 +8,11 @@
|
|
|
8
8
|
"import": "./dist/index.js",
|
|
9
9
|
"require": "./dist/index.cjs"
|
|
10
10
|
},
|
|
11
|
+
"./ssr": {
|
|
12
|
+
"types": "./dist/types/ssr.d.ts",
|
|
13
|
+
"import": "./dist/ssr.js",
|
|
14
|
+
"require": "./dist/ssr.cjs"
|
|
15
|
+
},
|
|
11
16
|
"./server": {
|
|
12
17
|
"types": "./dist/types/server.d.ts",
|
|
13
18
|
"import": "./dist/server.js",
|
|
@@ -73,17 +78,16 @@
|
|
|
73
78
|
"@babel/preset-typescript": "^8.0.1",
|
|
74
79
|
"@eslint-react/eslint-plugin": "^5.18.6",
|
|
75
80
|
"@eslint/js": "^10.0.1",
|
|
76
|
-
"@linaria/babel-preset": "^5.0.4",
|
|
77
81
|
"@linaria/core": "^8.2.0",
|
|
78
|
-
"@linaria/vite": "^5.0.4",
|
|
79
82
|
"@testing-library/dom": "^10.4.1",
|
|
80
83
|
"@testing-library/react": "^16.3.2",
|
|
81
|
-
"@types/node": "^26.
|
|
84
|
+
"@types/node": "^26.4.0",
|
|
82
85
|
"@types/react": "^19.2.18",
|
|
83
86
|
"@types/react-dom": "^19.2.5",
|
|
84
87
|
"@vitejs/plugin-react": "^6.1.0",
|
|
85
88
|
"@vitest/coverage-v8": "^4.1.11",
|
|
86
89
|
"@vitest/ui": "^4.1.11",
|
|
90
|
+
"@wyw-in-js/vite": "^2.4.3",
|
|
87
91
|
"babel-plugin-transform-jsx-class": "^0.1.3",
|
|
88
92
|
"babel-plugin-transform-jsx-condition": "^0.1.3",
|
|
89
93
|
"babel-runtime-jsx-plus": "^0.1.5",
|
|
@@ -109,7 +113,7 @@
|
|
|
109
113
|
"react-dom": "^19.2.8",
|
|
110
114
|
"rollup-plugin-type-as-json-schema": "^0.2.6",
|
|
111
115
|
"semantic-release": "^25.0.9",
|
|
112
|
-
"terser": "^5.
|
|
116
|
+
"terser": "^5.51.0",
|
|
113
117
|
"tsc-alias": "^1.9.2",
|
|
114
118
|
"typedoc": "^0.28.20",
|
|
115
119
|
"typedoc-plugin-mark-react-functional-components": "^0.2.2",
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../src/components/link-behavior.ts","../src/components/Link.tsx","../src/components/NavLink.tsx","../src/components/PrefetchLink.tsx","../src/components/ScrollRestoration.tsx","../src/components/TypedLink.tsx","../src/create-routes.js","../src/use-search-params.ts","../src/use-blocker.ts"],"sourcesContent":["/**\n * Checks whether a click on an anchor should be intercepted and handled as an\n * in-app navigation, following the standard link interception semantics of\n * react-router/wouter: plain left clicks only.\n *\n * The browser keeps the default behavior whenever this returns `false`, so\n * modified clicks, middle clicks and links to other browsing contexts open in\n * a new tab/window as the user expects.\n *\n * @param e The click event to inspect.\n * @param target The anchor's `target` attribute, if any.\n * @param rel The anchor's `rel` attribute, if any.\n * @group Components\n */\n\nexport function shouldNavigate(\n e: {\n button: number;\n defaultPrevented: boolean;\n metaKey: boolean;\n ctrlKey: boolean;\n shiftKey: boolean;\n altKey: boolean;\n },\n target?: string,\n rel?: string\n): boolean {\n return (\n !e.defaultPrevented &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.shiftKey &&\n !e.altKey &&\n target !== '_blank' &&\n target !== '_parent' &&\n target !== '_top' &&\n !(rel ?? '').split(/\\s+/).includes('external')\n );\n}\n","import {createHref, navigate} from '@native-router/core';\nimport type {AsLinkProps, LinkProps} from '@@/types';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n// The implementation works on the loose shape; the typed signature is\n// attached below so the `as` generic is not threaded through forwardRef's\n// typings(the same pattern TypedLink uses for its discriminated union).\ntype LinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link for navigate in app.\n *\n * Pass an `as` component to render through it instead of the plain anchor:\n * the computed `href` and the navigation-aware click handling are injected,\n * the component's non-conflicting props are accepted directly on the link\n * and its conflicting ones go through `asProps`(see {@link AsLinkProps}).\n * The component should forward its ref and spread the rest props onto the\n * DOM element it renders.\n * @param props\n * @group Components\n */\nfunction LinkImpl(\n {to, as, asProps, onClick, ...rest}: LinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n lockRef.current = true;\n navigate(router, to)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n // `aria-current` is NavLink's active-state injection(or a plain anchor\n // attribute on the others): a managed key, so it is injected after\n // asProps like href/onClick instead of traveling through the rest.\n const {'aria-current': ariaCurrent, ...anchorProps} = rest;\n return (\n <A\n {...anchorProps}\n {...asProps}\n ref={ref}\n href={createHref(router, to)}\n onClick={handleClick}\n aria-current={ariaCurrent}\n />\n );\n}\n\n// Two call signatures, generic first: call sites resolve through the `as`\n// generic, while the plain non-generic signature placed LAST is what\n// `ComponentProps<typeof Link>`-style helpers read — without it the\n// uninstantiated generic collapses to its `ElementType` constraint and the\n// ref becomes required `any`. The tail signature is exactly the pre-`as`\n// public shape. The displayName slot keeps the component name settable\n// despite the cast(the forwardRef wrapper shows its own name otherwise).\nconst Link = forwardRef(LinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nLink.displayName = 'Link';\n\nexport default Link;\n","import {toLocation} from '@native-router/core';\nimport type {AsLinkProps, NavLinkProps, NavLinkState} from '@@/types';\nimport {\n forwardRef,\n useCallback,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './Router';\nimport Link from './Link';\n\ntype NavLinkImplProps = NavLinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n// Internal delegation to Link with the implementation-loose `as` shape;\n// the public generic typing lives on both components' public signatures.\nconst LooseLink = Link as (props: any) => ReactElement | null;\n\n/**\n * Link that knows whether its target matches the current location.\n *\n * Active rules(aligned with react-router's `NavLink`):\n *\n * - `target` is the pathname of `toLocation(router, to)`(baseUrl prepended),\n * `current` is `router.history.location.pathname`; both are lowercased\n * unless `caseSensitive` is set.\n * - `isExactActive`: `current === target`.\n * - `isActive`: `isExactActive` when `end` is set, otherwise `current` equals\n * `target` or starts with `target` plus a trailing `/`(so `to=\"/\"` is active\n * for every path).\n *\n * While active the anchor renders `aria-current={ariaCurrent ?? 'page'}` and\n * `className`/`style`/`children` receive the active state when given as\n * functions. Click behavior is delegated to {@link Link}, inheriting the\n * modified-click guard and the double-click lock.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}): the active-state callbacks, the computed\n * `className`/`style` and the injected `aria-current` flow to it like any\n * other prop.\n * @param props\n * @group Components\n */\nfunction NavLinkImpl(\n {\n to,\n end = false,\n caseSensitive = false,\n className,\n style,\n ariaCurrent,\n children,\n as,\n asProps,\n ...rest\n }: NavLinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n // Subscribe to the history location so the active state stays in sync even\n // when rendered outside the routed view(e.g. a nav bar beside <View />).\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n const getSnapshot = useCallback(\n () => router.history.location.pathname,\n [router]\n );\n const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const target = toLocation(router, to).pathname;\n const [currentPath, targetPath] = caseSensitive\n ? [current, target]\n : [current.toLowerCase(), target.toLowerCase()];\n\n const isExactActive = currentPath === targetPath;\n // A root `to=\"/\"` normalizes to the \"/\" prefix and matches every path.\n const isActive =\n end || isExactActive\n ? isExactActive\n : currentPath.startsWith(\n targetPath.endsWith('/') ? targetPath : `${targetPath}/`\n );\n\n const state: NavLinkState = {isActive, isExactActive};\n\n return (\n <LooseLink\n to={to}\n {...rest}\n as={as}\n asProps={asProps}\n ref={ref}\n className={typeof className === 'function' ? className(state) : className}\n style={typeof style === 'function' ? style(state) : style}\n aria-current={isActive ? (ariaCurrent ?? 'page') : undefined}\n >\n {typeof children === 'function' ? children(state) : children}\n </LooseLink>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst NavLink = forwardRef(NavLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<NavLinkProps, A>\n ): ReactElement | null;\n (props: NavLinkProps): ReactElement | null;\n displayName?: string;\n};\n\nNavLink.displayName = 'NavLink';\n\nexport default NavLink;\n","import {commit, createHref, preload} from '@native-router/core';\nimport type {ResolvedEntry} from '@native-router/core';\nimport type {AsLinkProps, LinkProps, Route} from '@@/types';\nimport {\n createContext,\n forwardRef,\n MouseEvent,\n ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\ntype PrefetchLinkContext = {loading: boolean; error?: Error; view?: ReactNode};\n\nconst Context = createContext<PrefetchLinkContext>({loading: false});\n\n/**\n * Get the prefetch context. Use for render a preview view.\n * @group Hooks\n */\nexport function usePrefetch() {\n return useContext(Context);\n}\n\ntype PrefetchLinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link with prefetch support.\n *\n * The `prefetch` prop controls when the target view is resolved:\n * - `'intent'` (default): prefetch on hover or focus.\n * - `'render'`: prefetch as soon as the link mounts.\n * - `'viewport'`: prefetch when the link scrolls into the viewport.\n * - `'none'`: never prefetch; the target is resolved on click.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}); every strategy keeps working. The `viewport`\n * strategy observes the DOM node the component forwards its ref to, so a\n * component that does not forward the ref down to a DOM element never\n * triggers a viewport prefetch.\n * @param props\n * @group Components\n */\nfunction PrefetchLinkImpl(\n {\n to,\n prefetch = 'intent',\n children,\n as,\n asProps,\n onClick,\n ...rest\n }: PrefetchLinkImplProps,\n forwardedRef: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const anchorRef = useRef<HTMLAnchorElement>(null);\n const entryRef = useRef<Promise<ResolvedEntry<ReactNode>> | undefined>(\n undefined\n );\n const failedRef = useRef(false);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error>();\n const [view, setView] = useState<ReactNode>();\n\n // Feed both the internal viewport-observation ref and the user's ref.\n const setAnchorRef = useCallback(\n (node: HTMLAnchorElement | null) => {\n anchorRef.current = node;\n if (typeof forwardedRef === 'function') forwardedRef(node);\n else if (forwardedRef) forwardedRef.current = node;\n },\n [forwardedRef]\n );\n\n function prefetchIt(): Promise<ResolvedEntry<ReactNode>> {\n setLoading(true);\n setError(undefined);\n failedRef.current = false;\n // Route guards(redirect/beforeLoad) run before the view resolves; the\n // stored entry carries the terminal location, so prefetch, preview and\n // commit all agree on the final target. preload() caches the entry at\n // the router level(keyed by pathname+search, TTL bounded), so repeated\n // prefetches of the same target share one resolution and the entry is\n // evicted once committed.\n const entryPromise = preload<Route, ReactNode>(router, to);\n entryRef.current = entryPromise;\n // The derived chain carries the loading/error/view state and handles\n // the rejection of the entry task, so a prefetched task that is never\n // committed does not surface as a global unhandledrejection. Failure is\n // tracked in `failedRef` instead of relying on the rejected task itself.\n entryPromise\n .then((entry) => entry.task)\n .then(\n (v) => setView(v),\n (e) => {\n setError(e);\n failedRef.current = true;\n }\n )\n .finally(() => setLoading(false));\n return entryPromise;\n }\n\n function handlePrefetch() {\n if (entryRef.current) return;\n prefetchIt();\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n // A stored entry that already failed can never be committed\n // successfully, so resolve the target again before committing.\n const stored = entryRef.current;\n const entryPromise = !stored || failedRef.current ? prefetchIt() : stored;\n // The terminal location of the entry is committed, not the link target.\n entryPromise\n .then((entry) => commit(router, entry.task, entry.location))\n .catch(() => undefined)\n .finally(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n });\n }\n\n // Reset every piece of prefetch state when the target changes, so a stale\n // error or preview from the previous target is not rendered for the new one.\n useEffect(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n setLoading(false);\n setError(undefined);\n setView(undefined);\n }, [to, router]);\n\n useEffect(() => {\n if (prefetch === 'render') {\n handlePrefetch();\n return undefined;\n }\n if (prefetch !== 'viewport') return undefined;\n const el = anchorRef.current;\n if (!el || typeof IntersectionObserver === 'undefined') return undefined;\n // eslint-disable-next-line compat/compat -- guarded above at runtime\n const observer = new IntersectionObserver((entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return;\n observer.disconnect();\n handlePrefetch();\n });\n observer.observe(el);\n return () => observer.disconnect();\n // `location` and `handlePrefetch` are derived from these deps.\n }, [prefetch, to, router]);\n\n const linkContext = useMemo(\n () => ({loading, error, view}),\n [loading, error, view]\n );\n\n // Hover/focus are intent signals only; 'render', 'viewport' and 'none'\n // never prefetch on interaction.\n const intentHandlers =\n prefetch === 'intent'\n ? {onMouseEnter: handlePrefetch, onFocus: handlePrefetch}\n : undefined;\n\n const A = (as ?? 'a') as ElementType;\n\n return (\n <Context.Provider value={linkContext}>\n <A\n {...rest}\n {...intentHandlers}\n {...asProps}\n ref={setAnchorRef}\n href={createHref(router, to)}\n onClick={handleClick}\n >\n {children}\n </A>\n </Context.Provider>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst PrefetchLink = forwardRef(PrefetchLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nPrefetchLink.displayName = 'PrefetchLink';\n\nexport default PrefetchLink;\n","import {createPath} from 'history';\nimport type {HistoryState} from '@native-router/core';\nimport {useEffect, useRef} from 'react';\nimport {useRouter} from './Router';\n\n/** Saved scroll offset of one history stack slot. */\ntype ScrollPosition = {x: number; y: number};\n\ntype ScrollRestorationProps = {\n /**\n * Scroll a freshly pushed(or replaced) entry back to the top, like a full\n * page load. Set to false to keep the current offset across forward\n * navigations(e.g. feed-style \"load more\" pages). POP always restores the\n * saved offset, regardless of this flag.\n * @default true\n */\n resetOnPush?: boolean;\n};\n\n/**\n * Restore the window scroll position across history navigations.\n *\n * The router restores views from the in-memory `viewStack`: on back/forward\n * the view is reused without re-fetching its data, but the browser has\n * already left the old document position and a remounted DOM starts at the\n * top by default. Mount `<ScrollRestoration />` anywhere inside\n * {@link Router}(typically in the root layout) to fill that gap:\n *\n * - the scroll offset of every visited entry is remembered, keyed by the\n * absolute history index(`history.location.state.index` — the same key\n * `viewStack` is keyed by). Like `viewStack`, the map is in-memory and\n * session scoped: after a page reload there is nothing to restore and the\n * browser's own restoration takes over.\n * - `history.scrollRestoration` is taken over as `manual`(the browser's\n * own `auto` restoration would race the restore and pre-scroll while the\n * left entry's offset is still being read), making the component solely\n * responsible for restoration; the takeover is session scoped and not\n * reverted on unmount, like `viewStack`.\n * - POP restores the saved offset of the landed entry(`0,0` when none was\n * saved, e.g. forward-past-the-end or post-reload entries).\n * - PUSH and REPLACE scroll a fresh entry back to the top when\n * `resetOnPush` is set(default). Internal re-commits of the very same\n * entry(the core listener's POP sync, `refresh`, listen bootstrap) never\n * touch the scroll.\n *\n * Renders nothing. SSR safe: it only subscribes in an effect and only when\n * `window` exists.\n * @param props\n * @group Components\n */\nexport default function ScrollRestoration({\n resetOnPush = true\n}: ScrollRestorationProps) {\n const router = useRouter();\n // Positions survive effect re-runs(resetOnPush changes) on purpose.\n const positionsRef = useRef(new Map<number, ScrollPosition>());\n const lastIndexRef = useRef(-1);\n const lastPathRef = useRef('');\n\n useEffect(() => {\n if (typeof window === 'undefined') return undefined;\n\n // The browser's own `auto` restoration races this component's restore\n // (it can pre-scroll within the microtask window where the left entry's\n // offset is still being read), so take full control for the session.\n if (window.history.scrollRestoration) {\n window.history.scrollRestoration = 'manual';\n }\n\n const positions = positionsRef.current;\n const readIndex = (state: unknown) =>\n (state as HistoryState | undefined)?.index || 0;\n\n lastIndexRef.current = readIndex(router.history.location.state);\n lastPathRef.current = createPath(router.history.location);\n\n let scheduled = false;\n let sawPop = false;\n let active = true;\n\n const unlisten = router.history.listen(({action}) => {\n // The core listener re-commits a landed POP entry with an internal\n // REPLACE(stack serialization sync), and listener registration order\n // decides whether that REPLACE reaches us before or after the POP\n // itself. Collapse the whole synchronous event storm and decide once,\n // from the final history state, in a microtask — no layout has\n // scrolled yet at that point, so saving the left entry's offset\n // still reads the pre-navigation scroll.\n sawPop ||= action === 'POP';\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n if (!active) return;\n const popped = sawPop;\n sawPop = false;\n const {location} = router.history;\n const index = readIndex(location.state);\n const path = createPath(location);\n const lastIndex = lastIndexRef.current;\n\n if (index !== lastIndex) {\n // The entry we just left keeps its scroll offset.\n positions.set(lastIndex, {x: window.scrollX, y: window.scrollY});\n }\n\n if (popped) {\n const saved = positions.get(index) ?? {x: 0, y: 0};\n window.scrollTo(saved.x, saved.y);\n positions.set(index, saved);\n } else if (\n resetOnPush &&\n (index !== lastIndex || path !== lastPathRef.current)\n ) {\n // A fresh forward entry, or the current entry rewritten to a\n // different location(a replace navigation) — start at the top.\n window.scrollTo(0, 0);\n positions.set(index, {x: 0, y: 0});\n }\n // Anything else is an internal re-commit of the same entry: keep\n // the current scroll.\n\n lastIndexRef.current = index;\n lastPathRef.current = path;\n });\n });\n\n return () => {\n active = false;\n unlisten();\n };\n }, [router, resetOnPush]);\n\n return null;\n}\n","import {createHref, navigate} from '@native-router/core';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport type {AsLinkProps, TypedLinkProps} from '@@/types';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n/**\n * Interpolate params into a path pattern: `:name` segments take a\n * string, `*name` wildcards a string array(joined with `/`), both\n * percent-encoded; everything else — including `\\` escapes — is static\n * text. The grammar matches the core matcher's(the ASCII identifier\n * scanner the type-level `ExtractPathParams` models).\n * @throws when a required param is missing or empty — the click-time\n * params check of {@link TypedLink}\n */\nfunction interpolatePath(\n pattern: string,\n params: Record<string, string | string[]>\n): string {\n return pattern.replace(\n /\\\\.|[:*]([A-Za-z_$][A-Za-z0-9_$]*)/g,\n (match, name?: string) => {\n if (name === undefined) return match;\n const value = params[name];\n if (value === undefined || value.length === 0) {\n throw new Error(\n `Missing param \"${name}\" for the path pattern \"${pattern}\"`\n );\n }\n return (Array.isArray(value) ? value : [value])\n .map(encodeURIComponent)\n .join('/');\n }\n );\n}\n\n/**\n * Link whose `to` is narrowed to a route table's path patterns and whose\n * `params` is checked against the exact pattern's param segments. Give\n * it the pattern union as its type argument:\n *\n * ```tsx\n * const routes = createRoutes({children: [{path: '/users/:id'}, ...]});\n *\n * <TypedLink<RoutePaths<typeof routes>> to=\"/users/:id\" params={{id: '7'}}>\n * User 7\n * </TypedLink>\n * ```\n *\n * A `to` outside the table, a missing required param or a wrong param\n * shape is a compile error; at click time the params are interpolated\n * into the pattern and a missing required param throws instead of\n * navigating(the type-level check's runtime backstop).\n *\n * Without the type argument the component degrades to a plain `Link`:\n * any path, params optional. Click interception follows {@link Link}\n * — only plain primary-button clicks are intercepted.\n *\n * An `as` component can be layered on top(`asProps`/flattened `as`-props\n * per {@link AsLinkProps}); give both type arguments to keep the pattern\n * narrowing: `<TypedLink<Paths, typeof MyLink> ... />`.\n * @group Components\n * @param props `to`(a pattern of the table), `params`(per the pattern)\n * and the usual anchor attributes\n */\n// The implementation works on the loose shape; the typed signature is\n// attached below so discriminated-union props need not be destructured\n// across the union.\nfunction TypedLinkImpl(\n {\n to,\n params,\n onClick,\n as,\n asProps,\n ...rest\n }: {\n to: string;\n params?: Record<string, string | string[]>;\n as?: ElementType;\n asProps?: Record<string, unknown>;\n } & Omit<TypedLinkProps, 'to' | 'params' | 'prefetch' | 'href'>,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n // The href shows the interpolated target; when a required param is\n // missing the raw pattern stays and the click-time check below blocks\n // the navigation.\n let href: string = to;\n try {\n href = interpolatePath(to, params ?? {});\n } catch {\n // Programming error the types already flag; surfaced on click.\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n // Click-time params check per the pattern's param segments: a missing\n // required param throws instead of navigating.\n const target = interpolatePath(to, params ?? {});\n lockRef.current = true;\n navigate(router, target)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n return (\n <A\n {...rest}\n {...asProps}\n ref={ref}\n href={createHref(router, href)}\n onClick={handleClick}\n />\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link);\n// the tail keeps the pre-`as` discriminated-union shape.\nconst TypedLink = forwardRef(TypedLinkImpl) as {\n <Paths extends string = string, A extends ElementType = 'a'>(\n props: AsLinkProps<TypedLinkProps<Paths>, A>\n ): ReactElement | null;\n <Paths extends string = string>(\n props: TypedLinkProps<Paths>\n ): ReactElement | null;\n displayName?: string;\n};\n\nTypedLink.displayName = 'TypedLink';\n\nexport default TypedLink;\n","/**\n * Identity function with `satisfies` semantics: the table is checked\n * against `Route` while every `path` keeps its string-literal type, so\n * `RoutePaths<typeof routes>` can extract the full pattern union for\n * `TypedLink`. An `as Route` assertion does the opposite — it widens\n * every `path` to `string` and gives up the literals.\n *\n * ```tsx\n * const routes = createRoutes({\n * children: [\n * {path: '/', component: () => import('./Home')},\n * {path: '/users/:id', component: () => import('./UserProfile')}\n * ]\n * });\n * // type AppPaths = '/' | '/users/:id'\n * type AppPaths = RoutePaths<typeof routes>;\n * ```\n *\n * Zero runtime cost: the function returns its argument unchanged and\n * tree-shakes away.\n * @group Methods\n * @category Route\n * @param routes the route table, a route object or an array of them\n * @returns the very same route table, literal types preserved\n */\nexport function createRoutes(\n // The `const` modifier keeps every `path` a string literal(through\n // arbitrary nesting) while the parameter is still checked against\n // `Route` — the `satisfies` semantics an `as Route` assertion lacks:\n // the assertion widens every `path` to `string` instead.\n routes\n) {\n return routes;\n}\n","import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n","import {useEffect, useRef} from 'react';\nimport {setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): void {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n useEffect(\n () => setBlocker(router, (to, from) => fnRef.current(to, from)),\n [router]\n );\n}\n"],"mappings":"+PAeA,SAAgB,EACd,EAQA,EACA,GAEA,QACG,EAAE,kBACU,IAAb,EAAE,QACD,EAAE,SACF,EAAE,SACF,EAAE,UACF,EAAE,QACQ,WAAX,GACW,YAAX,GACW,SAAX,IACE,GAAO,IAAI,MAAM,OAAO,SAAS,YAEvC,CCoDA,IAAM,GAAA,EAAO,EAAA,YA1Db,UACE,GAAC,EAAA,G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AO,QAAQ,SAAS,OAC9B,CAAC,IAGG,GAAA,EAAoB,EAAA,aAAA,IAAkB,GAAI,IAE1C,GAAA,EAAS,EAAA,sBACb,EACA,EACA,GAGF,OAAO,GAAA,EAAS,EAAA,iBAAgB,EAAQ,IAAM,EAAI,EAAA,kBAAiB,EACrE,0BAtLA,WACE,MAAM,EAAS,EAAA,YAIT,GAAA,EAAY,EAAA,aACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAIG,GAAA,EAAc,EAAA,aAAA,IACZ,EAAO,QAAQ,SAAS,OAC9B,CAAC,IAGG,GAAA,EAAoB,EAAA,aAAA,IAAkB,GAAI,IAoBhD,MAAO,CAAC,IAjBiB,iBAAA,EACvB,EAAA,sBAAqB,EAAW,EAAa,KAgBvC,EAbgB,EAAA,aAAA,CACrB,EAAM,KACL,MAAM,QAAC,GAAW,EACZ,EACY,mBAAT,EAEH,EAAK,IAAI,gBAAgB,EAAQ,SAAS,SAC1C,EACN,OAAO,EAAU,EAAQ,EAAO,WAAY,IAE9C,CAAC,IAIL,uBA0BA,SACE,GAKA,MAAM,EAAS,EAAA,YAEf,OAAA,EAAO,EAAA,aAAA,CACJ,EAAM,KACL,MAAM,QAAC,GAAW,EACZ,EACY,mBAAT,EACH,GAAA,EAAK,EAAA,kBAAiB,EAAQ,SAAS,SACvC,EAIA,GAAA,EAAY,EAAA,iBAAgB,EAAQ,EAAgB,IAI1D,OAAO,EACL,EACA,EAAgB,GAChB,IAGJ,CAAC,EAAQ,GAEb"}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/components/link-behavior.ts","../src/components/Link.tsx","../src/components/NavLink.tsx","../src/components/PrefetchLink.tsx","../src/components/ScrollRestoration.tsx","../src/components/TypedLink.tsx","../src/create-routes.js","../src/use-search-params.ts","../src/use-blocker.ts"],"sourcesContent":["/**\n * Checks whether a click on an anchor should be intercepted and handled as an\n * in-app navigation, following the standard link interception semantics of\n * react-router/wouter: plain left clicks only.\n *\n * The browser keeps the default behavior whenever this returns `false`, so\n * modified clicks, middle clicks and links to other browsing contexts open in\n * a new tab/window as the user expects.\n *\n * @param e The click event to inspect.\n * @param target The anchor's `target` attribute, if any.\n * @param rel The anchor's `rel` attribute, if any.\n * @group Components\n */\n\nexport function shouldNavigate(\n e: {\n button: number;\n defaultPrevented: boolean;\n metaKey: boolean;\n ctrlKey: boolean;\n shiftKey: boolean;\n altKey: boolean;\n },\n target?: string,\n rel?: string\n): boolean {\n return (\n !e.defaultPrevented &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.shiftKey &&\n !e.altKey &&\n target !== '_blank' &&\n target !== '_parent' &&\n target !== '_top' &&\n !(rel ?? '').split(/\\s+/).includes('external')\n );\n}\n","import {createHref, navigate} from '@native-router/core';\nimport type {AsLinkProps, LinkProps} from '@@/types';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n// The implementation works on the loose shape; the typed signature is\n// attached below so the `as` generic is not threaded through forwardRef's\n// typings(the same pattern TypedLink uses for its discriminated union).\ntype LinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link for navigate in app.\n *\n * Pass an `as` component to render through it instead of the plain anchor:\n * the computed `href` and the navigation-aware click handling are injected,\n * the component's non-conflicting props are accepted directly on the link\n * and its conflicting ones go through `asProps`(see {@link AsLinkProps}).\n * The component should forward its ref and spread the rest props onto the\n * DOM element it renders.\n * @param props\n * @group Components\n */\nfunction LinkImpl(\n {to, as, asProps, onClick, ...rest}: LinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n lockRef.current = true;\n navigate(router, to)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n // `aria-current` is NavLink's active-state injection(or a plain anchor\n // attribute on the others): a managed key, so it is injected after\n // asProps like href/onClick instead of traveling through the rest.\n const {'aria-current': ariaCurrent, ...anchorProps} = rest;\n return (\n <A\n {...anchorProps}\n {...asProps}\n ref={ref}\n href={createHref(router, to)}\n onClick={handleClick}\n aria-current={ariaCurrent}\n />\n );\n}\n\n// Two call signatures, generic first: call sites resolve through the `as`\n// generic, while the plain non-generic signature placed LAST is what\n// `ComponentProps<typeof Link>`-style helpers read — without it the\n// uninstantiated generic collapses to its `ElementType` constraint and the\n// ref becomes required `any`. The tail signature is exactly the pre-`as`\n// public shape. The displayName slot keeps the component name settable\n// despite the cast(the forwardRef wrapper shows its own name otherwise).\nconst Link = forwardRef(LinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nLink.displayName = 'Link';\n\nexport default Link;\n","import {toLocation} from '@native-router/core';\nimport type {AsLinkProps, NavLinkProps, NavLinkState} from '@@/types';\nimport {\n forwardRef,\n useCallback,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './Router';\nimport Link from './Link';\n\ntype NavLinkImplProps = NavLinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n// Internal delegation to Link with the implementation-loose `as` shape;\n// the public generic typing lives on both components' public signatures.\nconst LooseLink = Link as (props: any) => ReactElement | null;\n\n/**\n * Link that knows whether its target matches the current location.\n *\n * Active rules(aligned with react-router's `NavLink`):\n *\n * - `target` is the pathname of `toLocation(router, to)`(baseUrl prepended),\n * `current` is `router.history.location.pathname`; both are lowercased\n * unless `caseSensitive` is set.\n * - `isExactActive`: `current === target`.\n * - `isActive`: `isExactActive` when `end` is set, otherwise `current` equals\n * `target` or starts with `target` plus a trailing `/`(so `to=\"/\"` is active\n * for every path).\n *\n * While active the anchor renders `aria-current={ariaCurrent ?? 'page'}` and\n * `className`/`style`/`children` receive the active state when given as\n * functions. Click behavior is delegated to {@link Link}, inheriting the\n * modified-click guard and the double-click lock.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}): the active-state callbacks, the computed\n * `className`/`style` and the injected `aria-current` flow to it like any\n * other prop.\n * @param props\n * @group Components\n */\nfunction NavLinkImpl(\n {\n to,\n end = false,\n caseSensitive = false,\n className,\n style,\n ariaCurrent,\n children,\n as,\n asProps,\n ...rest\n }: NavLinkImplProps,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n // Subscribe to the history location so the active state stays in sync even\n // when rendered outside the routed view(e.g. a nav bar beside <View />).\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n const getSnapshot = useCallback(\n () => router.history.location.pathname,\n [router]\n );\n const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const target = toLocation(router, to).pathname;\n const [currentPath, targetPath] = caseSensitive\n ? [current, target]\n : [current.toLowerCase(), target.toLowerCase()];\n\n const isExactActive = currentPath === targetPath;\n // A root `to=\"/\"` normalizes to the \"/\" prefix and matches every path.\n const isActive =\n end || isExactActive\n ? isExactActive\n : currentPath.startsWith(\n targetPath.endsWith('/') ? targetPath : `${targetPath}/`\n );\n\n const state: NavLinkState = {isActive, isExactActive};\n\n return (\n <LooseLink\n to={to}\n {...rest}\n as={as}\n asProps={asProps}\n ref={ref}\n className={typeof className === 'function' ? className(state) : className}\n style={typeof style === 'function' ? style(state) : style}\n aria-current={isActive ? (ariaCurrent ?? 'page') : undefined}\n >\n {typeof children === 'function' ? children(state) : children}\n </LooseLink>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst NavLink = forwardRef(NavLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<NavLinkProps, A>\n ): ReactElement | null;\n (props: NavLinkProps): ReactElement | null;\n displayName?: string;\n};\n\nNavLink.displayName = 'NavLink';\n\nexport default NavLink;\n","import {commit, createHref, preload} from '@native-router/core';\nimport type {ResolvedEntry} from '@native-router/core';\nimport type {AsLinkProps, LinkProps, Route} from '@@/types';\nimport {\n createContext,\n forwardRef,\n MouseEvent,\n ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ElementType,\n type ReactElement,\n type Ref\n} from 'react';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\ntype PrefetchLinkContext = {loading: boolean; error?: Error; view?: ReactNode};\n\nconst Context = createContext<PrefetchLinkContext>({loading: false});\n\n/**\n * Get the prefetch context. Use for render a preview view.\n * @group Hooks\n */\nexport function usePrefetch() {\n return useContext(Context);\n}\n\ntype PrefetchLinkImplProps = LinkProps & {\n as?: ElementType;\n asProps?: Record<string, unknown>;\n};\n\n/**\n * Link with prefetch support.\n *\n * The `prefetch` prop controls when the target view is resolved:\n * - `'intent'` (default): prefetch on hover or focus.\n * - `'render'`: prefetch as soon as the link mounts.\n * - `'viewport'`: prefetch when the link scrolls into the viewport.\n * - `'none'`: never prefetch; the target is resolved on click.\n *\n * Pass an `as` component to render through it instead of the plain anchor\n * (see {@link AsLinkProps}); every strategy keeps working. The `viewport`\n * strategy observes the DOM node the component forwards its ref to, so a\n * component that does not forward the ref down to a DOM element never\n * triggers a viewport prefetch.\n * @param props\n * @group Components\n */\nfunction PrefetchLinkImpl(\n {\n to,\n prefetch = 'intent',\n children,\n as,\n asProps,\n onClick,\n ...rest\n }: PrefetchLinkImplProps,\n forwardedRef: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const anchorRef = useRef<HTMLAnchorElement>(null);\n const entryRef = useRef<Promise<ResolvedEntry<ReactNode>> | undefined>(\n undefined\n );\n const failedRef = useRef(false);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error>();\n const [view, setView] = useState<ReactNode>();\n\n // Feed both the internal viewport-observation ref and the user's ref.\n const setAnchorRef = useCallback(\n (node: HTMLAnchorElement | null) => {\n anchorRef.current = node;\n if (typeof forwardedRef === 'function') forwardedRef(node);\n else if (forwardedRef) forwardedRef.current = node;\n },\n [forwardedRef]\n );\n\n function prefetchIt(): Promise<ResolvedEntry<ReactNode>> {\n setLoading(true);\n setError(undefined);\n failedRef.current = false;\n // Route guards(redirect/beforeLoad) run before the view resolves; the\n // stored entry carries the terminal location, so prefetch, preview and\n // commit all agree on the final target. preload() caches the entry at\n // the router level(keyed by pathname+search, TTL bounded), so repeated\n // prefetches of the same target share one resolution and the entry is\n // evicted once committed.\n const entryPromise = preload<Route, ReactNode>(router, to);\n entryRef.current = entryPromise;\n // The derived chain carries the loading/error/view state and handles\n // the rejection of the entry task, so a prefetched task that is never\n // committed does not surface as a global unhandledrejection. Failure is\n // tracked in `failedRef` instead of relying on the rejected task itself.\n entryPromise\n .then((entry) => entry.task)\n .then(\n (v) => setView(v),\n (e) => {\n setError(e);\n failedRef.current = true;\n }\n )\n .finally(() => setLoading(false));\n return entryPromise;\n }\n\n function handlePrefetch() {\n if (entryRef.current) return;\n prefetchIt();\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n // A stored entry that already failed can never be committed\n // successfully, so resolve the target again before committing.\n const stored = entryRef.current;\n const entryPromise = !stored || failedRef.current ? prefetchIt() : stored;\n // The terminal location of the entry is committed, not the link target.\n entryPromise\n .then((entry) => commit(router, entry.task, entry.location))\n .catch(() => undefined)\n .finally(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n });\n }\n\n // Reset every piece of prefetch state when the target changes, so a stale\n // error or preview from the previous target is not rendered for the new one.\n useEffect(() => {\n entryRef.current = undefined;\n failedRef.current = false;\n setLoading(false);\n setError(undefined);\n setView(undefined);\n }, [to, router]);\n\n useEffect(() => {\n if (prefetch === 'render') {\n handlePrefetch();\n return undefined;\n }\n if (prefetch !== 'viewport') return undefined;\n const el = anchorRef.current;\n if (!el || typeof IntersectionObserver === 'undefined') return undefined;\n // eslint-disable-next-line compat/compat -- guarded above at runtime\n const observer = new IntersectionObserver((entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return;\n observer.disconnect();\n handlePrefetch();\n });\n observer.observe(el);\n return () => observer.disconnect();\n // `location` and `handlePrefetch` are derived from these deps.\n }, [prefetch, to, router]);\n\n const linkContext = useMemo(\n () => ({loading, error, view}),\n [loading, error, view]\n );\n\n // Hover/focus are intent signals only; 'render', 'viewport' and 'none'\n // never prefetch on interaction.\n const intentHandlers =\n prefetch === 'intent'\n ? {onMouseEnter: handlePrefetch, onFocus: handlePrefetch}\n : undefined;\n\n const A = (as ?? 'a') as ElementType;\n\n return (\n <Context.Provider value={linkContext}>\n <A\n {...rest}\n {...intentHandlers}\n {...asProps}\n ref={setAnchorRef}\n href={createHref(router, to)}\n onClick={handleClick}\n >\n {children}\n </A>\n </Context.Provider>\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link).\nconst PrefetchLink = forwardRef(PrefetchLinkImpl) as {\n <A extends ElementType = 'a'>(\n props: AsLinkProps<LinkProps, A>\n ): ReactElement | null;\n (props: LinkProps): ReactElement | null;\n displayName?: string;\n};\n\nPrefetchLink.displayName = 'PrefetchLink';\n\nexport default PrefetchLink;\n","import {createPath} from 'history';\nimport type {HistoryState} from '@native-router/core';\nimport {useEffect, useRef} from 'react';\nimport {useRouter} from './Router';\n\n/** Saved scroll offset of one history stack slot. */\ntype ScrollPosition = {x: number; y: number};\n\ntype ScrollRestorationProps = {\n /**\n * Scroll a freshly pushed(or replaced) entry back to the top, like a full\n * page load. Set to false to keep the current offset across forward\n * navigations(e.g. feed-style \"load more\" pages). POP always restores the\n * saved offset, regardless of this flag.\n * @default true\n */\n resetOnPush?: boolean;\n};\n\n/**\n * Restore the window scroll position across history navigations.\n *\n * The router restores views from the in-memory `viewStack`: on back/forward\n * the view is reused without re-fetching its data, but the browser has\n * already left the old document position and a remounted DOM starts at the\n * top by default. Mount `<ScrollRestoration />` anywhere inside\n * {@link Router}(typically in the root layout) to fill that gap:\n *\n * - the scroll offset of every visited entry is remembered, keyed by the\n * absolute history index(`history.location.state.index` — the same key\n * `viewStack` is keyed by). Like `viewStack`, the map is in-memory and\n * session scoped: after a page reload there is nothing to restore and the\n * browser's own restoration takes over.\n * - `history.scrollRestoration` is taken over as `manual`(the browser's\n * own `auto` restoration would race the restore and pre-scroll while the\n * left entry's offset is still being read), making the component solely\n * responsible for restoration; the takeover is session scoped and not\n * reverted on unmount, like `viewStack`.\n * - POP restores the saved offset of the landed entry(`0,0` when none was\n * saved, e.g. forward-past-the-end or post-reload entries).\n * - PUSH and REPLACE scroll a fresh entry back to the top when\n * `resetOnPush` is set(default). Internal re-commits of the very same\n * entry(the core listener's POP sync, `refresh`, listen bootstrap) never\n * touch the scroll.\n *\n * Renders nothing. SSR safe: it only subscribes in an effect and only when\n * `window` exists.\n * @param props\n * @group Components\n */\nexport default function ScrollRestoration({\n resetOnPush = true\n}: ScrollRestorationProps) {\n const router = useRouter();\n // Positions survive effect re-runs(resetOnPush changes) on purpose.\n const positionsRef = useRef(new Map<number, ScrollPosition>());\n const lastIndexRef = useRef(-1);\n const lastPathRef = useRef('');\n\n useEffect(() => {\n if (typeof window === 'undefined') return undefined;\n\n // The browser's own `auto` restoration races this component's restore\n // (it can pre-scroll within the microtask window where the left entry's\n // offset is still being read), so take full control for the session.\n if (window.history.scrollRestoration) {\n window.history.scrollRestoration = 'manual';\n }\n\n const positions = positionsRef.current;\n const readIndex = (state: unknown) =>\n (state as HistoryState | undefined)?.index || 0;\n\n lastIndexRef.current = readIndex(router.history.location.state);\n lastPathRef.current = createPath(router.history.location);\n\n let scheduled = false;\n let sawPop = false;\n let active = true;\n\n const unlisten = router.history.listen(({action}) => {\n // The core listener re-commits a landed POP entry with an internal\n // REPLACE(stack serialization sync), and listener registration order\n // decides whether that REPLACE reaches us before or after the POP\n // itself. Collapse the whole synchronous event storm and decide once,\n // from the final history state, in a microtask — no layout has\n // scrolled yet at that point, so saving the left entry's offset\n // still reads the pre-navigation scroll.\n sawPop ||= action === 'POP';\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n if (!active) return;\n const popped = sawPop;\n sawPop = false;\n const {location} = router.history;\n const index = readIndex(location.state);\n const path = createPath(location);\n const lastIndex = lastIndexRef.current;\n\n if (index !== lastIndex) {\n // The entry we just left keeps its scroll offset.\n positions.set(lastIndex, {x: window.scrollX, y: window.scrollY});\n }\n\n if (popped) {\n const saved = positions.get(index) ?? {x: 0, y: 0};\n window.scrollTo(saved.x, saved.y);\n positions.set(index, saved);\n } else if (\n resetOnPush &&\n (index !== lastIndex || path !== lastPathRef.current)\n ) {\n // A fresh forward entry, or the current entry rewritten to a\n // different location(a replace navigation) — start at the top.\n window.scrollTo(0, 0);\n positions.set(index, {x: 0, y: 0});\n }\n // Anything else is an internal re-commit of the same entry: keep\n // the current scroll.\n\n lastIndexRef.current = index;\n lastPathRef.current = path;\n });\n });\n\n return () => {\n active = false;\n unlisten();\n };\n }, [router, resetOnPush]);\n\n return null;\n}\n","import {createHref, navigate} from '@native-router/core';\nimport {\n forwardRef,\n useRef,\n type ElementType,\n type MouseEvent,\n type ReactElement,\n type Ref\n} from 'react';\nimport type {AsLinkProps, TypedLinkProps} from '@@/types';\nimport {useRouter} from './Router';\nimport {shouldNavigate} from './link-behavior';\n\n/**\n * Interpolate params into a path pattern: `:name` segments take a\n * string, `*name` wildcards a string array(joined with `/`), both\n * percent-encoded; everything else — including `\\` escapes — is static\n * text. The grammar matches the core matcher's(the ASCII identifier\n * scanner the type-level `ExtractPathParams` models).\n * @throws when a required param is missing or empty — the click-time\n * params check of {@link TypedLink}\n */\nfunction interpolatePath(\n pattern: string,\n params: Record<string, string | string[]>\n): string {\n return pattern.replace(\n /\\\\.|[:*]([A-Za-z_$][A-Za-z0-9_$]*)/g,\n (match, name?: string) => {\n if (name === undefined) return match;\n const value = params[name];\n if (value === undefined || value.length === 0) {\n throw new Error(\n `Missing param \"${name}\" for the path pattern \"${pattern}\"`\n );\n }\n return (Array.isArray(value) ? value : [value])\n .map(encodeURIComponent)\n .join('/');\n }\n );\n}\n\n/**\n * Link whose `to` is narrowed to a route table's path patterns and whose\n * `params` is checked against the exact pattern's param segments. Give\n * it the pattern union as its type argument:\n *\n * ```tsx\n * const routes = createRoutes({children: [{path: '/users/:id'}, ...]});\n *\n * <TypedLink<RoutePaths<typeof routes>> to=\"/users/:id\" params={{id: '7'}}>\n * User 7\n * </TypedLink>\n * ```\n *\n * A `to` outside the table, a missing required param or a wrong param\n * shape is a compile error; at click time the params are interpolated\n * into the pattern and a missing required param throws instead of\n * navigating(the type-level check's runtime backstop).\n *\n * Without the type argument the component degrades to a plain `Link`:\n * any path, params optional. Click interception follows {@link Link}\n * — only plain primary-button clicks are intercepted.\n *\n * An `as` component can be layered on top(`asProps`/flattened `as`-props\n * per {@link AsLinkProps}); give both type arguments to keep the pattern\n * narrowing: `<TypedLink<Paths, typeof MyLink> ... />`.\n * @group Components\n * @param props `to`(a pattern of the table), `params`(per the pattern)\n * and the usual anchor attributes\n */\n// The implementation works on the loose shape; the typed signature is\n// attached below so discriminated-union props need not be destructured\n// across the union.\nfunction TypedLinkImpl(\n {\n to,\n params,\n onClick,\n as,\n asProps,\n ...rest\n }: {\n to: string;\n params?: Record<string, string | string[]>;\n as?: ElementType;\n asProps?: Record<string, unknown>;\n } & Omit<TypedLinkProps, 'to' | 'params' | 'prefetch' | 'href'>,\n ref: Ref<HTMLAnchorElement>\n) {\n const router = useRouter();\n const lockRef = useRef(false);\n\n // The href shows the interpolated target; when a required param is\n // missing the raw pattern stays and the click-time check below blocks\n // the navigation.\n let href: string = to;\n try {\n href = interpolatePath(to, params ?? {});\n } catch {\n // Programming error the types already flag; surfaced on click.\n }\n\n function handleClick(e: MouseEvent<HTMLAnchorElement>) {\n // The user's onClick runs first with the same event; calling\n // e.preventDefault() there suppresses the navigation entirely.\n onClick?.(e);\n // Modified clicks, other buttons and links to another browsing context\n // keep the browser default behavior (open in new tab/window, etc).\n // asProps overrides the base anchor attributes at runtime, so the guard\n // judges the effective target/rel — the ones actually rendered.\n if (\n !shouldNavigate(\n e,\n (asProps?.target as string | undefined) ?? rest.target,\n (asProps?.rel as string | undefined) ?? rest.rel\n )\n )\n return;\n e.preventDefault();\n\n if (lockRef.current) return;\n // Click-time params check per the pattern's param segments: a missing\n // required param throws instead of navigating.\n const target = interpolatePath(to, params ?? {});\n lockRef.current = true;\n navigate(router, target)\n .catch(() => undefined)\n .finally(() => {\n lockRef.current = false;\n });\n }\n\n const A = (as ?? 'a') as ElementType;\n return (\n <A\n {...rest}\n {...asProps}\n ref={ref}\n href={createHref(router, href)}\n onClick={handleClick}\n />\n );\n}\n\n// Generic first for call sites, plain tail for ComponentProps(see Link);\n// the tail keeps the pre-`as` discriminated-union shape.\nconst TypedLink = forwardRef(TypedLinkImpl) as {\n <Paths extends string = string, A extends ElementType = 'a'>(\n props: AsLinkProps<TypedLinkProps<Paths>, A>\n ): ReactElement | null;\n <Paths extends string = string>(\n props: TypedLinkProps<Paths>\n ): ReactElement | null;\n displayName?: string;\n};\n\nTypedLink.displayName = 'TypedLink';\n\nexport default TypedLink;\n","/**\n * Identity function with `satisfies` semantics: the table is checked\n * against `Route` while every `path` keeps its string-literal type, so\n * `RoutePaths<typeof routes>` can extract the full pattern union for\n * `TypedLink`. An `as Route` assertion does the opposite — it widens\n * every `path` to `string` and gives up the literals.\n *\n * ```tsx\n * const routes = createRoutes({\n * children: [\n * {path: '/', component: () => import('./Home')},\n * {path: '/users/:id', component: () => import('./UserProfile')}\n * ]\n * });\n * // type AppPaths = '/' | '/users/:id'\n * type AppPaths = RoutePaths<typeof routes>;\n * ```\n *\n * Zero runtime cost: the function returns its argument unchanged and\n * tree-shakes away.\n * @group Methods\n * @category Route\n * @param routes the route table, a route object or an array of them\n * @returns the very same route table, literal types preserved\n */\nexport function createRoutes(\n // The `const` modifier keeps every `path` a string literal(through\n // arbitrary nesting) while the parameter is still checked against\n // `Route` — the `satisfies` semantics an `as Route` assertion lacks:\n // the assertion widens every `path` to `string` instead.\n routes\n) {\n return routes;\n}\n","import {useCallback} from 'react';\nimport {\n commitReplace,\n navigate,\n parseSearchInput,\n parseSearchSync,\n resolveEntry,\n toLocation\n} from '@native-router/core';\nimport type {\n SearchInput,\n SearchOutputOf,\n StandardSchemaV1\n} from '@native-router/core';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport {useRouter} from './components/Router';\n\ntype SetSearchParams = (\n next: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams),\n opts?: {replace?: boolean}\n) => Promise<void> | void;\n\n/**\n * Read and write the search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as the Router Component), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; a fresh `URLSearchParams` view is derived from that string\n * on each render.\n *\n * The setter navigates like any other route change: by default the new\n * search is pushed onto the history stack(mainstream react-router\n * semantics), pass `{replace: true}` to rewrite the current entry instead.\n * Since the search is part of the location, every write re-resolves the\n * matched route, so route `data` fetchers(see {@link useData}) observe the\n * new search on the next {@link useData} read.\n *\n * @group Hooks\n * @returns [searchParams, setSearchParams] - the current search params and\n * the setter(functional updates receive the live previous params); the\n * setter returns a `Promise<void>` that resolves once the navigation\n * commits, so callers may optionally `await` it\n */\nexport function useSearchParams(): [URLSearchParams, SetSearchParams] {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a URLSearchParams instance) to keep the\n // snapshot reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n const searchParams = new URLSearchParams(\n useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n );\n\n const setSearchParams = useCallback<SetSearchParams>(\n (next, opts) => {\n const {history} = router;\n const params =\n typeof next === 'function'\n ? // eslint-disable-next-line compat/compat -- URLSearchParams support is the app's polyfill concern, not bundled\n next(new URLSearchParams(history.location.search))\n : next;\n return setSearch(router, params.toString(), opts);\n },\n [router]\n );\n\n return [searchParams, setSearchParams];\n}\n\n/**\n * Write the search params of the current location through a schema, the\n * setter-side twin of `useSearch(schema)`: the next value is serialized\n * to a query string, degraded with `parseSearchInput` and validated by\n * the SAME schema before any navigation happens. A schema that rejects\n * the value throws its issues(`SearchError`) without touching the\n * location; the value the schema would default or coerce on the read\n * side never gets silently written.\n *\n * Synchronous schemas only(the `useSearch` flavor); an async `validate`\n * rejects without navigating.\n *\n * The navigation semantics follow `useSearchParams`' setter: push by\n * default, `{replace: true}` rewrites the current entry, guards run,\n * and the returned `Promise<void>` resolves once the navigation commits.\n *\n * @group Hooks\n * @param schema a Standard Schema validator of the search — must\n * validate synchronously\n * @returns the schema-aware setter; functional updates receive the live\n * previous params\n * @throws {SearchError} when `schema` rejects the next value, before\n * any navigation\n */\nexport function useSetSearch<S extends StandardSchemaV1>(\n schema: S\n): (\n next: SearchInput | ((prev: SearchInput) => SearchInput),\n opts?: {replace?: boolean}\n) => Promise<void> | void {\n const router = useRouter();\n\n return useCallback(\n (next, opts) => {\n const {history} = router;\n const input =\n typeof next === 'function'\n ? next(parseSearchInput(history.location.search))\n : next;\n // Validate the whole next value — not a diff — the same way a\n // navigation to the resulting URL would: parseSearchSync throws\n // SearchError with the schema's issues, and no navigation happens.\n const validated = parseSearchSync(schema, stringifySearch(input));\n // The schema output is authoritative: defaults applied and values\n // coerced to strings, so a partially-filled input still writes the\n // fully-defaulted query.\n return setSearch(\n router,\n stringifySearch(validated as Record<string, unknown>),\n opts\n );\n },\n [router, schema]\n );\n}\n\nfunction stringifySearch(input: Record<string, unknown>): string {\n return Object.entries(input)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) =>\n (Array.isArray(value) ? value : [value])\n .map(\n (v) => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n .join('&')\n )\n .join('&');\n}\n\nfunction setSearch(\n router: ReturnType<typeof useRouter>,\n qs: string,\n opts?: {replace?: boolean}\n): Promise<void> | void {\n const {history} = router;\n const {pathname, hash} = history.location;\n const to = pathname + (qs ? `?${qs}` : '') + hash;\n if (opts?.replace) {\n // Route guards run like any other navigation(align with the push\n // branch): the entry carries the terminal location, so a redirect\n // replaces the current entry with its final target.\n return resolveEntry(router, toLocation(router, to)).then((entry) =>\n commitReplace(router, entry.task, entry.location)\n );\n }\n return navigate(router, to);\n}\n\n/**\n * Read the parsed search params of the current location.\n *\n * The raw `location.search` string is subscribed via\n * `useSyncExternalStore`(same source as {@link useSearchParams}), so every\n * location change(push, replace or pop) re-renders the component with the\n * latest params; the parse itself runs on each render.\n *\n * Without a schema the hook degrades to the raw input object of\n * `parseSearchInput` — strings, arrays for repeated keys\n * (`{page: '2', tag: ['a', 'b']}`). With a schema — any zod/valibot/\n * arktype schema, see the route {@link Route.search search field} — the\n * returned object is the schema's parsed output, so coercion and defaults\n * apply, e.g. `useSearch(pageSchema).page` is a number.\n *\n * Prefer declaring the schema once on the route: its `data` loader then\n * receives a parsed `ctx.search` during resolve, and an invalid search\n * fails the navigation through the existing error channels instead of\n * throwing during render.\n *\n * @group Hooks\n * @param schema an optional Standard Schema validator of the search; it\n * must validate synchronously\n * @returns the parsed search params of the current location\n * @throws {SearchError} when `schema` rejects the current search\n */\nexport function useSearch<S extends StandardSchemaV1>(\n schema: S\n): SearchOutputOf<S>;\nexport function useSearch(): SearchInput;\nexport function useSearch(schema?: StandardSchemaV1): unknown {\n const router = useRouter();\n\n // Subscribe to the raw history(not the core view listener): search must\n // update on ANY location change, including same-view re-resolves.\n const subscribe = useCallback(\n (onStoreChange: () => void) => router.history.listen(() => onStoreChange()),\n [router]\n );\n // Snapshot the raw string(never a parsed object) to keep the snapshot\n // reference stable between renders.\n const getSnapshot = useCallback(\n () => router.history.location.search,\n [router]\n );\n // There is no meaningful search during SSR.\n const getServerSnapshot = useCallback(() => '', []);\n\n const search = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n );\n\n return schema ? parseSearchSync(schema, search) : parseSearchInput(search);\n}\n","import {useEffect, useRef} from 'react';\nimport {setBlocker} from '@native-router/core';\nimport type {BlockerFn} from '@native-router/core';\nimport {useRouter} from './components/Router';\n\n/**\n * Block navigations away from the current page while the component is\n * mounted — the unsaved-changes guard.\n *\n * The predicate is the core `setBlocker` veto: `(to, from) => boolean`\n * over path strings(including search and hash), asked synchronously at\n * the head of every navigation and before a history POP lands. Return\n * `false` to veto: a vetoed navigation never starts and a vetoed POP is\n * rewound. `refresh` and guard redirects are never blocked; the effect\n * releases the blocker on unmount, so the guard lives exactly as long\n * as the guarding component.\n *\n * The predicate is stored in a ref and re-synced on every render, so a\n * navigation is always asked the latest closure — a `confirmed` flag it\n * captured works without re-registering anything. SSR-safe: nothing\n * here touches `window`, and the registration itself is an effect that\n * never runs on the server.\n *\n * @group Hooks\n * @param fn blocker predicate; `to` is the target path, `from` the\n * current path\n * @see {@link setBlocker}\n */\nexport function useBlocker(fn: BlockerFn): void {\n const router = useRouter();\n const fnRef = useRef(fn);\n // Always ask the latest closure: re-rendering with new state must not\n // require re-registering the blocker.\n fnRef.current = fn;\n useEffect(\n () => setBlocker(router, (to, from) => fnRef.current(to, from)),\n [router]\n );\n}\n"],"mappings":"kmBAeA,SAAgB,EACd,EAQA,EACA,GAEA,QACG,EAAE,kBACU,IAAb,EAAE,QACD,EAAE,SACF,EAAE,SACF,EAAE,UACF,EAAE,QACQ,WAAX,GACW,YAAX,GACW,SAAX,IACE,GAAO,IAAI,MAAM,OAAO,SAAS,YAEvC,CCoDA,IAAM,EAAO,EA1Db,UACE,GAAC,EAAA,GAAI,EAAA,QAAI,EAAA,QAAS,KAAY,GAC9B,GAEA,MAAM,EAAS,IACT,EAAU,GAAO,GA6BjB,EAAK,GAAM,KAIV,eAAgB,KAAgB,GAAe;AACtD,OACE,EAAC,EAAD,IACM,KACA,EACC,MACL,KAAM,EAAW,EAAQ,GACzB,QAtCJ,SAAqB,GAGnB,IAAU,GAMP,EACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,OAIjD,EAAE,iBAEE,EAAQ,UACZ,EAAQ,SAAU,EAClB,EAAS,EAAQ,GACd,MAAA,QACA,QAAA,KACC,EAAQ,SAAU,KAExB,EAcI,eAAc,GAGpB,GAiBA,EAAK,YAAc,OC/EnB,IAAM,EAAY,EAwFlB,IAAM,EAAU,EA7DhB,UACE,GACE,EAAA,IACA,GAAM,EAAA,cACN,GAAgB,EAAA,UAChB,EAAA,MACA,EAAA,YACA,EAAA,SACA,EAAA,GACA,EAAA,QACA,KACG,GAEL,GAEA,MAAM,EAAS,IAGT,EAAY,EACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAEG,E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,OAEhE,KAAK,MAET,KAAK,IACV,CAEA,SAAS,EACP,EACA,EACA,GAEA,MAAM,QAAC,GAAW,GACZ,SAAC,EAAA,KAAU,GAAQ,EAAQ,SAC3B,EAAK,GAAY,EAAK,IAAI,IAAO,IAAM,EAC7C,OAAI,GAAM,QAID,EAAa,EAAQ,EAAW,EAAQ,IAAK,KAAM,GACxD,EAAc,EAAQ,EAAM,KAAM,EAAM,WAGrC,EAAS,EAAQ,EAC1B,CAgCA,SAAgB,EAAU,GACxB,MAAM,EAAS,IAIT,EAAY,EACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAIG,EAAc,EAAA,IACZ,EAAO,QAAQ,SAAS,OAC9B,CAAC,IAGG,EAAoB,EAAA,IAAkB,GAAI,IAE1C,EAAS,EACb,EACA,EACA,GAGF,OAAO,EAAS,EAAgB,EAAQ,GAAU,EAAiB,EACrE,CCtMA,SAAgB,EAAW,GACzB,MAAM,EAAS,IACT,EAAQ,EAAO,GAGrB,EAAM,QAAU,EAChB,EAAA,IACQ,EAAW,EAAA,CAAS,EAAI,IAAS,EAAM,QAAQ,EAAI,IACzD,CAAC,GAEL,CHwHA,EAAU,YAAc"}
|
package/dist/ssr-873l9jA-.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{Component as r,createContext as e,useCallback as n,useContext as t,useEffect as o,useMemo as i,useRef as a,useState as u}from"react";import{createBrowserHistory as c,createHashHistory as s,createMemoryHistory as l,createPath as d}from"history";import{Fragment as h,jsx as f,jsxs as v}from"react/jsx-runtime";import{create as m,getCurrentView as p,listen as g,match as y,mergeMatchedParams as w,parseSearch as x,parseSearchInput as P,resolve as b,setOptions as C,toLocation as A}from"@native-router/core";import{isString as E,splitProps as R,uniqId as S}from"@native-router/core/util";import{useSyncExternalStore as k}from"use-sync-external-store/shim";var K=e(null);function $(r){/* @__PURE__ */
|
|
2
|
-
return f(K.Provider,{...r})}function H(){return t(K)}var I=e(null);function L(){const r=H(),e=t(I);return r??e}var V=e([void 0,{}]);function _(){return t(V)}function D(){return _()[1]}function M({children:r,name:e,data:n}){const t=D(),o=i(()=>[n,e?{...t,[e]:n}:t],[n,e,t]);/* @__PURE__ */
|
|
3
|
-
return f(V.Provider,{value:o,children:r})}var U=e(void 0);function W(){return t(U)}function j(r){const[e,n]=_();return r?n[r]:e}var F=e(void 0);function J(){return t(F)}var N=class extends r{state={};static getDerivedStateFromError(r){return{error:r}}render(){const{error:r}=this.state;if(!r)return this.props.children;const{route:e,ctx:n,router:t}=this.props,o=e.errorComponent;if(o)/* @__PURE__ */return f(o,{error:r,ctx:{...n,phase:"render"}});const i=t.errorHandler?.(r);if(i instanceof Promise)throw i.catch(()=>{}),r;if(void 0!==i)return i;throw r}};function O(r,e){return z(r,e,(r,e)=>r?.(e))}var T=/* @__PURE__ */new WeakMap;function q(r,e){const n=new Array(r.length);return z(r,e,(r,e)=>Promise.resolve(r?.(e)).then(r=>n[e.index]=r)).then(r=>(T.set(r,n),r))}function z(r,{router:e,location:n,signal:t},o){return Promise.all(r.map(({route:i},a)=>{const u={matched:r,params:w(r,a),index:a,router:e,location:n,search:P(n.search),signal:t??(new AbortController).signal};return Promise.all([i.search?x(i.search,n.search).then(r=>(u.search=r,o(i.data,u))):o(i.data,u),function(){if(!i.component)return L;const r=i.component(u);return Promise.resolve(r).then(r=>"default"in r?r.default:r)}()]).then(([r,n])=>/* @__PURE__ */f(N,{route:i,ctx:u,router:e,children:/* @__PURE__ */f(M,{data:r,name:i.name,children:/* @__PURE__ */f(U.Provider,{value:u,children:/* @__PURE__ */f(n,{})})})},`${a}:${i.path??""}`),r=>{if(!i.errorComponent)throw r;/* @__PURE__ */
|
|
4
|
-
return f(M,{data:void 0,name:i.name,children:/* @__PURE__ */f(U.Provider,{value:u,children:/* @__PURE__ */f(i.errorComponent,{error:r,ctx:u})})})})})).then(r=>r.reverse().reduce((r,e)=>/* @__PURE__ */f($,{value:r,children:e})))}var B=e(null);function G({router:r,children:e}){const o=a(p(r)),i=n(e=>g(r,r=>{o.current=r,e()}),[r]),u=n(()=>o.current,[]),c=n(()=>p(r),[r]),s=k(i,u,c),l=t(F),d=null==s&&"pending"===l?.status?function(r,e){const{resolving:n}=r,t=n?y(r,n.pathname):void 0;if(!t)return null;for(let o=t.length-1;o>=0;o--){const r=t[o].route.pendingComponent;if(r)/* @__PURE__ */return f(r,{},e)}return null}(r,l.key):null;/* @__PURE__ */
|
|
5
|
-
return f(B.Provider,{value:r,children:void 0===e?s??d:/* @__PURE__ */f($,{value:s,children:/* @__PURE__ */f(I.Provider,{value:d,children:e})})})}function Q(r,e,{resolveView:n=O,...t}={}){return m(r,e,n,t)}function X({routes:r,children:e,...n},t){const[a,c]=R(n,["baseUrl","currentView"]),{baseUrl:s,currentView:l}=a,[d,h]=u(),v=i(()=>Q(r,t(),{...n,onLoadingChange(r){h(r&&{key:S(),status:r})}}),[r,t,s,l]);o(()=>{C(v,{...c,onLoadingChange(r){h(r&&{key:S(),status:r})}})},[v,c]);const m=i(()=>/* @__PURE__ */f(G,{router:v,children:e}),[v,e]);/* @__PURE__ */
|
|
6
|
-
return f(F.Provider,{value:d,children:m})}function Y(r){return X(r,c)}function Z(r){return X(r,s)}function rr({initialEntries:r,initialIndex:e,...n}){return X(n,i(()=>()=>l({initialEntries:r,initialIndex:e}),[r,e]))}function er(){const r=t(B);if(!r)throw new Error("useRouter() must be used within a <Router> component");return r}var nr="_nativeRouterReactSSRData";function tr(r,e,n){return b(r,e).then(t=>{const o=function(r){return T.get(r)}(t),i=r.history.location.state?.index||0;/* @__PURE__ */
|
|
7
|
-
return v(h,{children:[/* @__PURE__ */f(G,{router:r,children:t}),/* @__PURE__ */f("script",{...n?.scriptAttributes,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:`window.${n?.hydrateKey||nr} = ${a={data:o,location:e,index:i},JSON.stringify(a).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};`}})]});var a})}function or(r,e,{scriptAttributes:n,hydrateKey:t,...o}={}){const i=m(r,l({initialEntries:[e]}),q,o);return tr(i,E(e)?A(i,e):e,{scriptAttributes:n,hydrateKey:t})}function ir(r,e){const{data:n,location:t,index:o=0}=window[e?.hydrateKey||nr],i=c();i.replace(d(i.location),{index:o});const a=m(r,i,function(r){return(e,n)=>z(e,n,(e,n)=>r[n.index])}(n),e);return b(a,t).then(r=>({view:r,router:a}))}export{rr as a,er as c,j as d,J as f,H as h,Y as i,O as l,D as m,or as n,G as o,W as p,Z as r,Q as s,ir as t,L as u};
|
|
8
|
-
//# sourceMappingURL=ssr-873l9jA-.js.map
|
package/dist/ssr-873l9jA-.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ssr-873l9jA-.js","names":[],"sources":["../src/context.tsx","../src/components/RouteErrorBoundary.tsx","../src/resolve-view.tsx","../src/components/Router.tsx","../src/ssr.tsx"],"sourcesContent":["import {createContext, ReactNode, useContext, useMemo} from 'react';\nimport type {Context, LoadStatus, Route} from './types';\n\nconst ViewContext = createContext<ReactNode>(null);\n\nexport function ViewProvider(props: {children: ReactNode; value: ReactNode}) {\n return <ViewContext.Provider {...props} />;\n}\n\n/**\n * @group Hooks\n * @see {@link View View Component}\n */\nexport function useView() {\n return useContext(ViewContext);\n}\n\n/**\n * Route-level pending skeleton(`pendingComponent` of the nearest matched\n * ancestor), set by the Router only while a navigation is pending with no\n * previous view to retain(cold start, refresh, re-navigation after an\n * error); `null` otherwise, so in-app navigation keeps the previous view.\n * @see {@link Route.pendingComponent}\n */\nexport const PendingContext = createContext<ReactNode>(null);\n\n/**\n * Used for route component to render child route component.\n * It just render the return of {@link useView}, falling back to the\n * route-level pending skeleton when the view slot is empty.\n * @group Components\n */\nexport function View() {\n const view = useView();\n const pending = useContext(PendingContext);\n return view ?? pending;\n}\n\nconst DataContext = createContext<[any, Record<string, any>]>([undefined, {}]);\n\nfunction useDataContext() {\n return useContext(DataContext);\n}\n\n/**\n * Get the named data map of the resolved route levels: an object keyed by\n * each ancestor's `name`, holding its resolved `data`. The current level\n * is included only when it declares a `name`.\n *\n * Give the generic the expected map shape to read values type-safely:\n * `useNamedData<{user: User}>()`.\n * @group Hooks\n */\nexport function useNamedData<T = Record<string, unknown>>() {\n return useDataContext()[1] as T;\n}\n\nexport function DataProvider({\n children,\n name,\n data\n}: {\n children: ReactNode;\n data: any;\n name?: string;\n}) {\n const namedData = useNamedData();\n const value = useMemo(\n () => [data, name ? {...namedData, [name]: data} : namedData] as [any, any],\n [data, name, namedData]\n );\n return <DataContext.Provider value={value}>{children}</DataContext.Provider>;\n}\n\nexport const MatchedContext = createContext<Context<Route> | undefined>(\n undefined\n);\n\n/**\n * @group Hooks\n */\nexport function useMatched() {\n return useContext(MatchedContext)!;\n}\n\n/**\n * Get the resolved `data` of the current route level, or the named data\n * of an ancestor level when `name` is given.\n *\n * Give the generic the expected data type to read it type-safely without\n * a cast: `useData<Article>()` → `Article | undefined`.\n * @group Hooks\n */\nexport function useData<T = unknown>(name?: string): T | undefined {\n const [data, namedData] = useDataContext();\n return (name ? namedData[name] : data) as T | undefined;\n}\n\nexport const LoadingContext = createContext<LoadStatus | undefined>(undefined);\n\n/**\n * @group Hooks\n */\nexport function useLoading() {\n return useContext(LoadingContext);\n}\n","import {Component, type ReactNode} from 'react';\nimport type {Context, Route} from '@@/types';\nimport type {RouterInstance} from '@native-router/core';\n\ntype Props = {\n route: Route;\n ctx: Context<Route>;\n router: RouterInstance<Route, ReactNode>;\n children: ReactNode;\n};\n\ntype State = {error?: Error};\n\n/**\n * Route-level render error boundary: catches errors thrown while the\n * level's component subtree renders and shows the route's\n * `errorComponent` with `ctx.phase === 'render'` — the render-phase\n * twin of the resolve-phase fallback in resolve-view. Just like the\n * browser renders an error page for any failed load, no rendering error\n * of a resolved view should crash past its route.\n *\n * Without a route `errorComponent` the error goes to the global\n * `errorHandler`: a returned view renders in place, while the default\n * handler(plain rejection) and async fallbacks rethrow, resurfacing the\n * error up the React tree like any unhandled error.\n */\nexport default class RouteErrorBoundary extends Component<Props, State> {\n state: State = {};\n\n static getDerivedStateFromError(error: Error): State {\n return {error};\n }\n\n render() {\n const {error} = this.state;\n if (!error) return this.props.children;\n const {route, ctx, router} = this.props;\n const ErrorComponent = route.errorComponent;\n if (ErrorComponent) {\n return <ErrorComponent error={error} ctx={{...ctx, phase: 'render'}} />;\n }\n // No route-level fallback: hand the error to the global errorHandler.\n // An async fallback cannot render synchronously; observe its rejection\n // and resurface the error itself instead.\n const fallback = router.errorHandler?.(error);\n if (fallback instanceof Promise) {\n fallback.catch(() => undefined);\n throw error;\n }\n if (fallback !== undefined) return fallback;\n throw error;\n }\n}\n","import type {ComponentType, ReactElement} from 'react';\nimport type {Context, ResolveViewContext, Route} from '@@/types';\nimport {\n mergeMatchedParams,\n parseSearch,\n parseSearchInput\n} from '@native-router/core';\nimport type {Matched} from '@native-router/core';\nimport {DataProvider, MatchedContext, View, ViewProvider} from './context';\nimport RouteErrorBoundary from './components/RouteErrorBoundary';\n\n/**\n * The default implementation of resolve view\n * @param matched the matched result\n * @param viewContext resolved view context\n * @returns the resolve view\n * @see {@link create router->create}\n */\nexport default function resolveView(\n matched: Matched<Route>[],\n ctx: ResolveViewContext<Route>\n) {\n return resolveViewBase(matched, ctx, (data, dataCtx) => data?.(dataCtx));\n}\n\nconst viewDataMap = new WeakMap<ReactElement, any[]>();\n\nexport function resolveViewServer(\n matched: Matched<Route>[],\n ctx: ResolveViewContext<Route>\n) {\n const dataResults = new Array(matched.length);\n return resolveViewBase(matched, ctx, (data, dataCtx) =>\n Promise.resolve(data?.(dataCtx)).then(\n (result) => (dataResults[dataCtx.index] = result)\n )\n ).then((view) => {\n viewDataMap.set(view, dataResults);\n return view;\n });\n}\n\nexport function createHydrateResolveView(data: any[]) {\n return (matched: Matched<Route>[], ctx: ResolveViewContext<Route>) =>\n resolveViewBase(matched, ctx, (_, dataCtx) => data[dataCtx.index]);\n}\n\nexport function getViewData(view: ReactElement) {\n return viewDataMap.get(view);\n}\n\nfunction resolveViewBase(\n matched: Matched<Route>[],\n {router, location, signal}: ResolveViewContext<Route>,\n resolveData: (\n dataFetcher: ((ctx: Context<Route>) => any) | undefined,\n ctx: Context<Route>\n ) => any\n) {\n return Promise.all(\n matched.map(({route}, index) => {\n // `search` starts as the degraded input and is upgraded to the\n // schema output before the data fetcher runs below; schema outputs\n // are user-typed(`Route<P, S>`), so the property stays `any` here.\n const ctx: Context<Route, Record<string, string>, any> = {\n matched: matched!,\n params: mergeMatchedParams(matched, index),\n index,\n router,\n location,\n search: parseSearchInput(location.search),\n // The chain's abort signal(navigation-superseded/cancelled) is\n // forwarded to every level's loader; a hand-rolled resolveView\n // context without one still yields a never-aborting signal.\n signal: signal ?? new AbortController().signal\n };\n function resolveComponent(): ComponentType | Promise<ComponentType> {\n if (!route.component) return View;\n const r = route.component(ctx);\n return Promise.resolve(r).then((m) => ('default' in m ? m.default : m));\n }\n\n // The level's search schema runs before its data fetcher: the parsed\n // output replaces the degraded input in `ctx.search`, and a rejected\n // validation fails the level exactly like a data error.\n const resolveDataWithSearch = () =>\n route.search\n ? parseSearch(route.search, location.search).then((search) => {\n ctx.search = search;\n return resolveData(route.data, ctx);\n })\n : resolveData(route.data, ctx);\n\n // A level that fails to resolve (search, data or component) is\n // replaced by its route-level errorComponent when configured;\n // otherwise the error bubbles up to the global errorHandler as before.\n return Promise.all([resolveDataWithSearch(), resolveComponent()]).then(\n ([data, C]) => (\n // The boundary is the render-phase twin of the resolve-phase\n // fallback below: a component that throws while rendering is\n // caught here and rendered through the same route errorComponent\n // (with ctx.phase === 'render'), instead of crashing past the\n // route to the React root.\n // Keyed by the level's path so React never reuses one route's\n // boundary fiber for another's at the same slot: a retained\n // error state would otherwise leak across routes when the\n // tree diff lands the same position(the class instance — and\n // its `state.error` — survives the prop change, and React\n // replays the cached error during the swap). The level index\n // only disambiguates same-path levels of one chain.\n\n <RouteErrorBoundary\n // eslint-disable-next-line @eslint-react/no-array-index-key -- not a list key: a per-level boundary identity (path + level)\n key={`${index}:${route.path ?? ''}`}\n route={route}\n ctx={ctx}\n router={router}\n >\n <DataProvider data={data} name={route.name}>\n <MatchedContext.Provider value={ctx}>\n <C />\n </MatchedContext.Provider>\n </DataProvider>\n </RouteErrorBoundary>\n ),\n (error: Error) => {\n if (!route.errorComponent) throw error;\n return (\n <DataProvider data={undefined} name={route.name}>\n <MatchedContext.Provider value={ctx}>\n <route.errorComponent error={error} ctx={ctx} />\n </MatchedContext.Provider>\n </DataProvider>\n );\n }\n );\n })\n ).then((views) =>\n views\n .reverse()\n .reduce((acc, view) => <ViewProvider value={acc}>{view}</ViewProvider>)\n );\n}\n","import {\n ReactNode,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState\n} from 'react';\nimport {\n History,\n createBrowserHistory,\n createHashHistory,\n createMemoryHistory,\n MemoryHistoryOptions\n} from 'history';\nimport type {LoadStatus, Route} from '@@/types';\nimport {LoadingContext, PendingContext, ViewProvider} from '@@/context';\nimport {\n create,\n getCurrentView,\n listen,\n match,\n setOptions\n} from '@native-router/core';\nimport type {Options, ResolveView, RouterInstance} from '@native-router/core';\nimport {splitProps, uniqId} from '@native-router/core/util';\nimport {useSyncExternalStore} from 'use-sync-external-store/shim';\nimport defaultResolve from '@@/resolve-view';\n\nconst RouterContext = createContext<RouterInstance<Route, ReactNode> | null>(\n null\n);\n\ntype Props = {\n children?: ReactNode;\n routes: Route[] | Route;\n resolveView?: typeof defaultResolve;\n} & Omit<Options<ReactNode>, 'onLoadingChange'>;\n\n/**\n * Base Router Component.\n * @group Components\n */\nexport function Router({\n router,\n children\n}: {\n children?: ReactNode;\n router: RouterInstance<Route, ReactNode>;\n}) {\n const viewRef = useRef<ReactNode>(getCurrentView(router));\n const subscribe = useCallback(\n (onStoreChange: () => void) =>\n listen(router, (view) => {\n viewRef.current = view;\n onStoreChange();\n }),\n [router]\n );\n const getSnapshot = useCallback(() => viewRef.current, []);\n // `getServerSnapshot` is required by the native implementation when the\n // Router is rendered inside server-rendered content(e.g. resolveServerView).\n const getServerSnapshot = useCallback(() => getCurrentView(router), [router]);\n const view = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n // Route-level pending skeleton, only when no previous view is retained\n // (cold start, refresh, re-navigation after an error); in-app navigation\n // keeps the old view by design, the global loading signal already\n // covers that phase. Reading LoadingContext here also re-renders the\n // Router on every loading transition.\n const loading = useContext(LoadingContext);\n const pending =\n view == null && loading?.status === 'pending'\n ? resolvePendingView(router, loading.key)\n : null;\n\n return (\n <RouterContext.Provider value={router}>\n {children === undefined ? (\n (view ?? pending)\n ) : (\n <ViewProvider value={view}>\n <PendingContext.Provider value={pending}>\n {children}\n </PendingContext.Provider>\n </ViewProvider>\n )}\n </RouterContext.Provider>\n );\n}\n\n/**\n * Render the `pendingComponent` of the nearest matched ancestor of the\n * resolving location, walked deepest first(the resolving route's own\n * included). Keyed by the loading episode so a new pending phase remounts\n * the skeleton(stateful shimmer animations restart). Guards may still\n * redirect the resolution away; until then the initially matched chain\n * is the best — and only — answer available.\n */\nfunction resolvePendingView(\n router: RouterInstance<Route, ReactNode>,\n key: number\n) {\n const {resolving} = router;\n const matched = resolving ? match(router, resolving.pathname) : undefined;\n if (!matched) return null;\n for (let i = matched.length - 1; i >= 0; i--) {\n const Pending = matched[i].route.pendingComponent;\n if (Pending) return <Pending key={key} />;\n }\n return null;\n}\n\nexport function createRouter(\n routes: Route | Route[],\n history: History,\n {\n resolveView = defaultResolve,\n ...options\n }: Options<ReactNode> & {resolveView?: ResolveView<Route, ReactNode>} = {}\n): RouterInstance<Route, ReactNode> {\n return create(routes, history, resolveView, options);\n}\n\nfunction useNewRouter(\n {routes, children, ...options}: Props,\n createHistory: () => History\n) {\n const [tracked, rest] = splitProps(options, ['baseUrl', 'currentView']);\n const {baseUrl, currentView} = tracked;\n const [loading, setLoading] = useState<LoadStatus>();\n // Initial options are baked in at creation: the cold-start resolve fires\n // from the subscribe effect(children effects run first) before the\n // setOptions effect below runs, and the default errorHandler would let\n // listen's refresh().catch(noop) swallow a first failure, leaving the\n // view blank forever.\n const router = useMemo(\n () =>\n createRouter(routes, createHistory(), {\n ...options,\n onLoadingChange(status) {\n setLoading(status && {key: uniqId(), status});\n }\n }),\n // Only the tracked options belong to the deps: option updates flow\n // through the setOptions effect below instead of recreating the router.\n [routes, createHistory, baseUrl, currentView]\n );\n\n // Options are refreshed on every commit, so `onLoadingChange` and the\n // callback options always see the latest closure.\n useEffect(() => {\n setOptions(router, {\n ...rest,\n onLoadingChange(status) {\n setLoading(status && {key: uniqId(), status});\n }\n });\n }, [router, rest]);\n\n const r = useMemo(\n () => <Router router={router}>{children}</Router>,\n [router, children]\n );\n\n return <LoadingContext.Provider value={loading}>{r}</LoadingContext.Provider>;\n}\n\n/**\n * History mode Router Component.\n * @group Components\n */\nexport function HistoryRouter(props: Props) {\n return useNewRouter(props, createBrowserHistory);\n}\n\n/**\n * Hash mode Router Component.\n * @group Components\n */\nexport function HashRouter(props: Props) {\n return useNewRouter(props, createHashHistory);\n}\n\n/**\n * Memory mode Router Component.\n * @group Components\n */\nexport function MemoryRouter({\n initialEntries,\n initialIndex,\n ...props\n}: Props & MemoryHistoryOptions) {\n const createHistory = useMemo(\n () => () => createMemoryHistory({initialEntries, initialIndex}),\n [initialEntries, initialIndex]\n );\n return useNewRouter(props, createHistory);\n}\n\n/**\n * Get Router instance.\n * @group Hooks\n * @returns Router Instance\n */\nexport function useRouter() {\n const router = useContext(RouterContext);\n if (!router) {\n throw new Error('useRouter() must be used within a <Router> component');\n }\n return router;\n}\n","import {createBrowserHistory, createMemoryHistory, createPath} from 'history';\nimport {ReactElement, ReactNode} from 'react';\nimport {create, resolve, toLocation} from '@native-router/core';\nimport type {\n HistoryState,\n Location,\n Options,\n RouterInstance\n} from '@native-router/core';\nimport {isString} from '@native-router/core/util';\nimport {Router} from './components/Router';\nimport {\n createHydrateResolveView,\n getViewData,\n resolveViewServer\n} from './resolve-view';\nimport type {Route} from './types';\n\nconst defaultHydrateKey = '_nativeRouterReactSSRData';\n\n/**\n * Serialize the SSR payload for embedding in a script element.\n * `JSON.stringify` does not escape `<`, U+2028 and U+2029,\n * so route data like `</script>` would break out of the script element.\n * @param payload the payload to serialize\n * @returns the escaped JSON string\n */\nfunction serializePayload(payload: {\n data?: any[];\n location: Location;\n index: number;\n}) {\n return JSON.stringify(payload)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\nexport function resolveServerViewBase(\n router: RouterInstance<Route, ReactNode>,\n location: Location,\n options?: {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n }\n) {\n return resolve<Route, ReactNode>(router, location).then((view) => {\n const data = getViewData(view as ReactElement);\n const index =\n (router.history.location.state as HistoryState | undefined)?.index || 0;\n return (\n <>\n <Router router={router}>{view}</Router>\n <script\n {...options?.scriptAttributes}\n suppressHydrationWarning\n // eslint-disable-next-line @eslint-react/dom-no-dangerously-set-innerhtml -- serialized state for hydration\n dangerouslySetInnerHTML={{\n __html: `window.${\n options?.hydrateKey || defaultHydrateKey\n } = ${serializePayload({data, location, index})};`\n }}\n />\n </>\n );\n });\n}\n\nexport function resolveServerView(\n routes: Route | Route[],\n location: Location | string,\n {\n scriptAttributes,\n hydrateKey,\n ...options\n }: Options<ReactElement> & {\n scriptAttributes?: Record<string, string>;\n hydrateKey?: string;\n } = {}\n) {\n const router = create(\n routes,\n createMemoryHistory({initialEntries: [location]}),\n resolveViewServer,\n options\n );\n\n return resolveServerViewBase(\n router,\n isString(location) ? toLocation(router, location) : location,\n {\n scriptAttributes,\n hydrateKey\n }\n );\n}\n\n/**\n * Hydrate the SSR result of {@link resolveServerView} on the client.\n * The router is bound to the browser history(aligned with the index\n * in the SSR payload), so navigation after hydration updates the address bar.\n * @param routes routes config, must match the server side\n * @param options options, `hydrateKey` must match the server side\n * @returns the resolved view and the router instance, for example:\n * `const {view, router} = await hydrate(routes);`\n * `hydrateRoot(root, <Router router={router}>{view}</Router>)`\n * @group Methods\n */\nexport function hydrate(\n routes: Route | Route[],\n options?: Options<ReactElement> & {\n hydrateKey?: string;\n }\n): Promise<{view: ReactNode; router: RouterInstance<Route, ReactNode>}> {\n const {\n data,\n location,\n index = 0\n } = (window as any)[options?.hydrateKey || defaultHydrateKey] as {\n data: any[];\n location: Location;\n index?: number;\n };\n const history = createBrowserHistory();\n history.replace(createPath(history.location), {index});\n const router = create(\n routes,\n history,\n createHydrateResolveView(data),\n options\n );\n return resolve<Route, ReactNode>(router, location).then((view) => ({\n view,\n router\n }));\n}\n"],"mappings":"mpBAGA,IAAM,EAAc,EAAyB,MAE7C,SAAgB,EAAa;AAC3B,OAAO,EAAC,EAAY,SAAb,IAA0B,GACnC,CAMA,SAAgB,IACd,OAAO,EAAW,EACpB,CASA,IAAa,EAAiB,EAAyB,MAQvD,SAAgB,IACd,MAAM,EAAO,IACP,EAAU,EAAW,GAC3B,OAAO,GAAQ,CACjB,CAEA,IAAM,EAAc,EAA0C,MAAC,EAAW,CAAC,IAE3E,SAAS,IACP,OAAO,EAAW,EACpB,CAWA,SAAgB,IACd,OAAO,IAAiB,EAC1B,CAEA,SAAgB,GAAa,SAC3B,EAAA,KACA,EAAA,KACA,IAMA,MAAM,EAAY,IACZ,EAAQ,EAAA,IACN,CAAC,EAAM,EAAO,IAAI,EAAY,CAAA,GAAO,GAAQ,GACnD,CAAC,EAAM,EAAM;AAEf,OAAO,EAAC,EAAY,SAAb,CAA6B,QAAQ,YAC9C,CAEA,IAAa,EAAiB,OAC5B,GAMF,SAAgB,IACd,OAAO,EAAW,EACpB,CAUA,SAAgB,EAAqB,GACnC,MAAO,EAAM,GAAa,IAC1B,OAAQ,EAAO,EAAU,GAAQ,CACnC,CAEA,IAAa,EAAiB,OAAsC,GAKpE,SAAgB,IACd,OAAO,EAAW,EACpB,CC/EA,IAAqB,EAArB,cAAgD,EAC9C,MAAe,CAAC,EAEhB,+BAAO,CAAyB,G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