@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/README.md
CHANGED
|
@@ -83,7 +83,7 @@ function Preview({visible}: {visible: boolean}) {
|
|
|
83
83
|
- Two error layers, both phases: global `errorHandler` prop on the Router, per-route `errorComponent` receiving `{error, ctx}` — `errorComponent` renders for resolve failures(loader/guard/search, no `ctx.phase`) AND for render errors thrown by the component subtree(`ctx.phase === 'render'`, caught by a route-level error boundary so a rendering crash never escapes past its route, like the browser's error page for any failed load)
|
|
84
84
|
- Route-level `pendingComponent` skeleton, shown only when no previous view can be retained (cold start, refresh, re-navigation after an error); the nearest matched ancestor's wins, and in-app navigation keeps the previous view instead
|
|
85
85
|
- Keeping the previous view during in-app navigation is an intentional design following browser-native semantics — see the Design Principles section of the core repository's README
|
|
86
|
-
- SSR: `resolveServerView` (from `@native-router/react/server`) renders the view plus an inline data payload; `hydrate` reuses that payload on the client with zero refetch
|
|
86
|
+
- SSR: `resolveServerView` (from `@native-router/react/server`) renders the view plus an inline data payload; `hydrate` (from `@native-router/react/ssr`) reuses that payload on the client with zero refetch
|
|
87
87
|
- Tree-shakable: `sideEffects: false` — unused components and hooks drop out of the bundle
|
|
88
88
|
|
|
89
89
|
## Matching semantics
|
|
@@ -141,6 +141,15 @@ The navigation semantics stay owned by the link: `href` is always the computed t
|
|
|
141
141
|
|
|
142
142
|
`PrefetchLink`'s strategies keep working through the `as` component; the `viewport` strategy observes the DOM node the component forwards its ref to, so a component that never forwards the ref down to a DOM element simply never triggers a viewport prefetch.
|
|
143
143
|
|
|
144
|
+
## Why `useData` is typed manually
|
|
145
|
+
|
|
146
|
+
`useData<T>()` annotations have no compile-time link to the route's `data` loader — the annotation *is* the contract. That is deliberate. Two closure schemes were evaluated (2026-08) and rejected:
|
|
147
|
+
|
|
148
|
+
- **A from-argument** (`useData('/articles/:slug')`, indexing a route-table map by path literal — TanStack's `useLoaderData({from})` shape). Rejected: it makes every view aware of the path it happens to be mounted under. Matching data to a view is the route configuration's job; a view should know what it renders, not where it is mounted.
|
|
149
|
+
- **A data-props protocol** — constrain `component` to `ComponentType<{data: D}>` and let `createRoutes` check the loader output against it at the config site. The check lands at the right layer, but deep children would then need prop drilling to reach the data.
|
|
150
|
+
|
|
151
|
+
What stays: path-agnostic views, no prop drilling, one local annotation. Revisit only if TypeScript or the library later offers a channel that couples neither paths nor props.
|
|
152
|
+
|
|
144
153
|
## Install
|
|
145
154
|
|
|
146
155
|
```bash
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./Router.cjs"),r=require("./link-behavior.cjs");let t=require("react"),a=require("react/jsx-runtime"),u=require("@native-router/core");var n=(0,t.forwardRef)(function({to:n,as:i,asProps:c,onClick:o,...s},l){const f=e.useRouter(),v=(0,t.useRef)(!1),q=i??"a",{"aria-current":d,...g}=s;return(0,a.jsx)(q,{...g,...c,ref:l,href:(0,u.createHref)(f,n),onClick:function(e){o?.(e),r.shouldNavigate(e,c?.target??s.target,c?.rel??s.rel)&&(e.preventDefault(),v.current||(v.current=!0,(0,u.navigate)(f,n).catch(()=>{}).finally(()=>{v.current=!1})))},"aria-current":d})});n.displayName="Link",exports.default=n;
|
|
2
|
+
//# sourceMappingURL=Link.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Link.cjs","names":[],"sources":["../../src/components/Link.tsx"],"sourcesContent":["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"],"mappings":"wJA2FA,IAAM,GAAA,EAAO,EAAA,YA1Db,UACE,GAAC,EAAA,GAAI,EAAA,QAAI,EAAA,QAAS,KAAY,GAC9B,GAEA,MAAM,EAAS,EAAA,YACT,GAAA,EAAU,EAAA,SAAO,GA6BjB,EAAK,GAAM,KAIV,eAAgB,KAAgB,GAAe,EACtD,OACE,EAAA,EAAA,KAAC,EAAD,IACM,KACA,EACC,MACL,MAAA,EAAM,EAAA,YAAW,EAAQ,GACzB,QAtCJ,SAAqB,GAGnB,IAAU,GAMP,EAAA,eACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,OAIjD,EAAE,iBAEE,EAAQ,UACZ,EAAQ,SAAU,GAClB,EAAA,EAAA,UAAS,EAAQ,GACd,MAAA,QACA,QAAA,KACC,EAAQ,SAAU,KAExB,EAcI,eAAc,GAGpB,GAiBA,EAAK,YAAc"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{useRouter as r}from"./Router.js";import{shouldNavigate as t}from"./link-behavior.js";import{forwardRef as e,useRef as o}from"react";import{jsx as a}from"react/jsx-runtime";import{createHref as n,navigate as i}from"@native-router/core";var c=e(function({to:e,as:c,asProps:u,onClick:f,...m},l){const p=r(),s=o(!1),k=c??"a",{"aria-current":v,...h}=m;/* @__PURE__ */
|
|
2
|
+
return a(k,{...h,...u,ref:l,href:n(p,e),onClick:function(r){f?.(r),t(r,u?.target??m.target,u?.rel??m.rel)&&(r.preventDefault(),s.current||(s.current=!0,i(p,e).catch(()=>{}).finally(()=>{s.current=!1})))},"aria-current":v})});c.displayName="Link";export{c as default};
|
|
3
|
+
//# sourceMappingURL=Link.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Link.js","names":[],"sources":["../../src/components/Link.tsx"],"sourcesContent":["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"],"mappings":"kPA2FA,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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./Router.cjs"),t=require("./Link.cjs");let r=require("react"),a=require("react/jsx-runtime"),s=require("@native-router/core"),i=require("use-sync-external-store/shim");var o=t.default;var n=(0,r.forwardRef)(function({to:t,end:n=!1,caseSensitive:c=!1,className:u,style:l,ariaCurrent:f,children:p,as:y,asProps:d,...h},v){const m=e.useRouter(),q=(0,r.useCallback)(e=>m.history.listen(()=>e()),[m]),x=(0,r.useCallback)(()=>m.history.location.pathname,[m]),C=(0,i.useSyncExternalStore)(q,x,x),L=(0,s.toLocation)(m,t).pathname,[j,k]=c?[C,L]:[C.toLowerCase(),L.toLowerCase()],N=j===k,w=n||N?N:j.startsWith(k.endsWith("/")?k:`${k}/`),R={isActive:w,isExactActive:N};return(0,a.jsx)(o,{to:t,...h,as:y,asProps:d,ref:v,className:"function"==typeof u?u(R):u,style:"function"==typeof l?l(R):l,"aria-current":w?f??"page":void 0,children:"function"==typeof p?p(R):p})});n.displayName="NavLink",exports.default=n;
|
|
2
|
+
//# sourceMappingURL=NavLink.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NavLink.cjs","names":[],"sources":["../../src/components/NavLink.tsx"],"sourcesContent":["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"],"mappings":"yLAoBA,IAAM,EAAY,EAAA,QAwFlB,IAAM,GAAA,EAAU,EAAA,YA7DhB,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,EAAA,YAGT,GAAA,EAAY,EAAA,aACf,GAA8B,EAAO,QAAQ,OAAA,IAAa,KAC3D,CAAC,IAEG,GAAA,EAAc,EAAA,aAAA,IACZ,EAAO,QAAQ,SAAS,SAC9B,CAAC,IAEG,GAAA,EAAU,EAAA,sBAAqB,EAAW,EAAa,GAEvD,GAAA,EAAS,EAAA,YAAW,EAAQ,GAAI,UAC/B,EAAa,GAAc,EAC9B,CAAC,EAAS,GACV,CAAC,EAAQ,cAAe,EAAO,eAE7B,EAAgB,IAAgB,EAEhC,EACJ,GAAO,EACH,EACA,EAAY,WACV,EAAW,SAAS,KAAO,EAAa,GAAG,MAG7C,EAAsB,CAAC,WAAU,iBAEvC,OACE,EAAA,EAAA,KAAC,EAAD,CACM,QACA,EACA,KACK,UACJ,MACL,UAAgC,mBAAd,EAA2B,EAAU,GAAS,EAChE,MAAwB,mBAAV,EAAuB,EAAM,GAAS,EACpD,eAAc,EAAY,GAAe,YAAU,EAElD,SAAoB,mBAAb,EAA0B,EAAS,GAAS,GAG1D,GAWA,EAAQ,YAAc"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{useRouter as t}from"./Router.js";import e from"./Link.js";import{forwardRef as r,useCallback as o}from"react";import{jsx as a}from"react/jsx-runtime";import{toLocation as s}from"@native-router/core";import{useSyncExternalStore as i}from"use-sync-external-store/shim";var n=e;var c=r(function({to:e,end:r=!1,caseSensitive:c=!1,className:m,style:p,ariaCurrent:f,children:u,as:l,asProps:h,...y},v){const d=t(),x=o(t=>d.history.listen(()=>t()),[d]),L=o(()=>d.history.location.pathname,[d]),N=i(x,L,L),j=s(d,e).pathname,[C,k]=c?[N,j]:[N.toLowerCase(),j.toLowerCase()],w=C===k,A=r||w?w:C.startsWith(k.endsWith("/")?k:`${k}/`),P={isActive:A,isExactActive:w};/* @__PURE__ */
|
|
2
|
+
return a(n,{to:e,...y,as:l,asProps:h,ref:v,className:"function"==typeof m?m(P):m,style:"function"==typeof p?p(P):p,"aria-current":A?f??"page":void 0,children:"function"==typeof u?u(P):u})});c.displayName="NavLink";export{c as default};
|
|
3
|
+
//# sourceMappingURL=NavLink.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NavLink.js","names":[],"sources":["../../src/components/NavLink.tsx"],"sourcesContent":["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"],"mappings":"kRAoBA,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,EAAc,EAAA,IACZ,EAAO,QAAQ,SAAS,SAC9B,CAAC,IAEG,EAAU,EAAqB,EAAW,EAAa,GAEvD,EAAS,EAAW,EAAQ,GAAI,UAC/B,EAAa,GAAc,EAC9B,CAAC,EAAS,GACV,CAAC,EAAQ,cAAe,EAAO,eAE7B,EAAgB,IAAgB,EAEhC,EACJ,GAAO,EACH,EACA,EAAY,WACV,EAAW,SAAS,KAAO,EAAa,GAAG,MAG7C,EAAsB,CAAC,WAAU;AAEvC,OACE,EAAC,EAAD,CACM,QACA,EACA,KACK,UACJ,MACL,UAAgC,mBAAd,EAA2B,EAAU,GAAS,EAChE,MAAwB,mBAAV,EAAuB,EAAM,GAAS,EACpD,eAAc,EAAY,GAAe,YAAU,EAElD,SAAoB,mBAAb,EAA0B,EAAS,GAAS,GAG1D,GAWA,EAAQ,YAAc"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./Router.cjs"),r=require("./link-behavior.cjs");let t=require("react"),n=require("react/jsx-runtime"),o=require("@native-router/core");var u=(0,t.createContext)({loading:!1});var c=(0,t.forwardRef)(function({to:c,prefetch:i="intent",children:s,as:a,asProps:f,onClick:l,...d},v){const h=e.useRouter(),p=(0,t.useRef)(null),k=(0,t.useRef)(void 0),x=(0,t.useRef)(!1),[g,m]=(0,t.useState)(!1),[R,b]=(0,t.useState)(),[j,q]=(0,t.useState)(),y=(0,t.useCallback)(e=>{p.current=e,"function"==typeof v?v(e):v&&(v.current=e)},[v]);function C(){m(!0),b(void 0),x.current=!1;const e=(0,o.preload)(h,c);return k.current=e,e.then(e=>e.task).then(e=>q(e),e=>{b(e),x.current=!0}).finally(()=>m(!1)),e}function w(){k.current||C()}(0,t.useEffect)(()=>{k.current=void 0,x.current=!1,m(!1),b(void 0),q(void 0)},[c,h]),(0,t.useEffect)(()=>{if("render"===i)return void w();if("viewport"!==i)return;const e=p.current;if(!e||"undefined"==typeof IntersectionObserver)return;const r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(r.disconnect(),w())});return r.observe(e),()=>r.disconnect()},[i,c,h]);const P=(0,t.useMemo)(()=>({loading:g,error:R,view:j}),[g,R,j]),E="intent"===i?{onMouseEnter:w,onFocus:w}:void 0,I=a??"a";return(0,n.jsx)(u.Provider,{value:P,children:(0,n.jsx)(I,{...d,...E,...f,ref:y,href:(0,o.createHref)(h,c),onClick:function(e){if(l?.(e),!r.shouldNavigate(e,f?.target??d.target,f?.rel??d.rel))return;e.preventDefault();const t=k.current;(!t||x.current?C():t).then(e=>(0,o.commit)(h,e.task,e.location)).catch(()=>{}).finally(()=>{k.current=void 0,x.current=!1})},children:s})})});c.displayName="PrefetchLink",exports.default=c,exports.usePrefetch=function(){return(0,t.useContext)(u)};
|
|
2
|
+
//# sourceMappingURL=PrefetchLink.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PrefetchLink.cjs","names":[],"sources":["../../src/components/PrefetchLink.tsx"],"sourcesContent":["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"],"mappings":"wJAuBA,IAAM,GAAA,EAAU,EAAA,eAAmC,CAAC,SAAS,IA6L7D,IAAM,GAAA,EAAe,EAAA,YA7JrB,UACE,GACE,EAAA,SACA,EAAW,SAAA,SACX,EAAA,GACA,EAAA,QACA,EAAA,QACA,KACG,GAEL,GAEA,MAAM,EAAS,EAAA,YACT,GAAA,EAAY,EAAA,QAA0B,MACtC,GAAA,EAAW,EAAA,aACf,GAEI,GAAA,EAAY,EAAA,SAAO,IAClB,EAAS,IAAA,EAAc,EAAA,WAAS,IAChC,EAAO,IAAA,EAAY,EAAA,aACnB,EAAM,IAAA,EAAW,EAAA,YAGlB,GAAA,EAAe,EAAA,aAClB,IACC,EAAU,QAAU,EACQ,mBAAjB,EAA6B,EAAa,GAC5C,IAAc,EAAa,QAAU,IAEhD,CAAC,IAGH,SAAS,IACP,GAAW,GACX,OAAS,GACT,EAAU,SAAU,EAOpB,MAAM,GAAA,EAAe,EAAA,SAA0B,EAAQ,GAgBvD,OAfA,EAAS,QAAU,EAKnB,EACG,KAAM,GAAU,EAAM,MACtB,KACE,GAAM,EAAQ,GACd,IACC,EAAS,GACT,EAAU,SAAU,IAGvB,QAAA,IAAc,GAAW,IACrB,CACT,CAEA,SAAS,IACH,EAAS,SACb,GACF,EAmCA,EAAA,EAAA,WAAA,KACE,EAAS,aAAU,EACnB,EAAU,SAAU,EACpB,GAAW,GACX,OAAS,GACT,OAAQ,IACP,CAAC,EAAI,KAER,EAAA,EAAA,WAAA,KACE,GAAiB,WAAb,EAEF,YADA,IAGF,GAAiB,aAAb,EAAyB,OAC7B,MAAM,EAAK,EAAU,QACrB,IAAK,GAAsC,oBAAzB,qBAAsC,OAExD,MAAM,EAAW,IAAI,qBAAsB,IACpC,EAAQ,KAAM,GAAU,EAAM,kBACnC,EAAS,aACT,OAGF,OADA,EAAS,QAAQ,GACjB,IAAa,EAAS,cAErB,CAAC,EAAU,EAAI,IAElB,MAAM,GAAA,EAAc,EAAA,SAAA,KAAA,CACV,UAAS,QAAO,SACxB,CAAC,EAAS,EAAO,IAKb,EACS,WAAb,EACI,CAAC,aAAc,EAAgB,QAAS,QACxC,EAEA,EAAK,GAAM,IAEjB,OACE,EAAA,EAAA,KAAC,EAAQ,SAAT,CAAkB,MAAO,EACvB,UAAA,EAAA,EAAA,KAAC,EAAD,IACM,KACA,KACA,EACJ,IAAK,EACL,MAAA,EAAM,EAAA,YAAW,EAAQ,GACzB,QAlFN,SAAqB,GAQnB,GALA,IAAU,IAMP,EAAA,eACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,KAG/C,OACF,EAAE,iBAGF,MAAM,EAAS,EAAS,UACF,GAAU,EAAU,QAAU,IAAe,GAGhE,KAAM,IAAA,EAAU,EAAA,QAAO,EAAQ,EAAM,KAAM,EAAM,WACjD,MAAA,QACA,QAAA,KACC,EAAS,aAAU,EACnB,EAAU,SAAU,GAE1B,EAuDO,cAIT,GAWA,EAAa,YAAc,qDA/L3B,WACE,OAAA,EAAO,EAAA,YAAW,EACpB"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{useRouter as r}from"./Router.js";import{shouldNavigate as e}from"./link-behavior.js";import{createContext as n,forwardRef as t,useCallback as o,useContext as i,useEffect as c,useMemo as u,useRef as s,useState as f}from"react";import{jsx as a}from"react/jsx-runtime";import{commit as d,createHref as l,preload as v}from"@native-router/core";var m=n({loading:!1});function p(){return i(m)}var h=t(function({to:n,prefetch:t="intent",children:i,as:p,asProps:h,onClick:k,...g},y){const b=r(),j=s(null),w=s(void 0),I=s(!1),[P,x]=f(!1),[C,O]=f(),[D,E]=f(),F=o(r=>{j.current=r,"function"==typeof y?y(r):y&&(y.current=r)},[y]);function L(){x(!0),O(void 0),I.current=!1;const r=v(b,n);return w.current=r,r.then(r=>r.task).then(r=>E(r),r=>{O(r),I.current=!0}).finally(()=>x(!1)),r}function M(){w.current||L()}c(()=>{w.current=void 0,I.current=!1,x(!1),O(void 0),E(void 0)},[n,b]),c(()=>{if("render"===t)return void M();if("viewport"!==t)return;const r=j.current;if(!r||"undefined"==typeof IntersectionObserver)return;const e=new IntersectionObserver(r=>{r.some(r=>r.isIntersecting)&&(e.disconnect(),M())});return e.observe(r),()=>e.disconnect()},[t,n,b]);const N=u(()=>({loading:P,error:C,view:D}),[P,C,D]),R="intent"===t?{onMouseEnter:M,onFocus:M}:void 0,q=p??"a";/* @__PURE__ */
|
|
2
|
+
return a(m.Provider,{value:N,children:/* @__PURE__ */a(q,{...g,...R,...h,ref:F,href:l(b,n),onClick:function(r){if(k?.(r),!e(r,h?.target??g.target,h?.rel??g.rel))return;r.preventDefault();const n=w.current;(!n||I.current?L():n).then(r=>d(b,r.task,r.location)).catch(()=>{}).finally(()=>{w.current=void 0,I.current=!1})},children:i})})});h.displayName="PrefetchLink";export{h as default,p as usePrefetch};
|
|
3
|
+
//# sourceMappingURL=PrefetchLink.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PrefetchLink.js","names":[],"sources":["../../src/components/PrefetchLink.tsx"],"sourcesContent":["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"],"mappings":"2VAuBA,IAAM,EAAU,EAAmC,CAAC,SAAS,IAM7D,SAAgB,IACd,OAAO,EAAW,EACpB,CAqLA,IAAM,EAAe,EA7JrB,UACE,GACE,EAAA,SACA,EAAW,SAAA,SACX,EAAA,GACA,EAAA,QACA,EAAA,QACA,KACG,GAEL,GAEA,MAAM,EAAS,IACT,EAAY,EAA0B,MACtC,EAAW,OACf,GAEI,EAAY,GAAO,IAClB,EAAS,GAAc,GAAS,IAChC,EAAO,GAAY,KACnB,EAAM,GAAW,IAGlB,EAAe,EAClB,IACC,EAAU,QAAU,EACQ,mBAAjB,EAA6B,EAAa,GAC5C,IAAc,EAAa,QAAU,IAEhD,CAAC,IAGH,SAAS,IACP,GAAW,GACX,OAAS,GACT,EAAU,SAAU,EAOpB,MAAM,EAAe,EAA0B,EAAQ,GAgBvD,OAfA,EAAS,QAAU,EAKnB,EACG,KAAM,GAAU,EAAM,MACtB,KACE,GAAM,EAAQ,GACd,IACC,EAAS,GACT,EAAU,SAAU,IAGvB,QAAA,IAAc,GAAW,IACrB,CACT,CAEA,SAAS,IACH,EAAS,SACb,GACF,CAmCA,EAAA,KACE,EAAS,aAAU,EACnB,EAAU,SAAU,EACpB,GAAW,GACX,OAAS,GACT,OAAQ,IACP,CAAC,EAAI,IAER,EAAA,KACE,GAAiB,WAAb,EAEF,YADA,IAGF,GAAiB,aAAb,EAAyB,OAC7B,MAAM,EAAK,EAAU,QACrB,IAAK,GAAsC,oBAAzB,qBAAsC,OAExD,MAAM,EAAW,IAAI,qBAAsB,IACpC,EAAQ,KAAM,GAAU,EAAM,kBACnC,EAAS,aACT,OAGF,OADA,EAAS,QAAQ,GACjB,IAAa,EAAS,cAErB,CAAC,EAAU,EAAI,IAElB,MAAM,EAAc,EAAA,KAAA,CACV,UAAS,QAAO,SACxB,CAAC,EAAS,EAAO,IAKb,EACS,WAAb,EACI,CAAC,aAAc,EAAgB,QAAS,QACxC,EAEA,EAAK,GAAM;AAEjB,OACE,EAAC,EAAQ,SAAT,CAAkB,MAAO,EACvB,wBAAA,EAAC,EAAD,IACM,KACA,KACA,EACJ,IAAK,EACL,KAAM,EAAW,EAAQ,GACzB,QAlFN,SAAqB,GAQnB,GALA,IAAU,IAMP,EACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,KAG/C,OACF,EAAE,iBAGF,MAAM,EAAS,EAAS,UACF,GAAU,EAAU,QAAU,IAAe,GAGhE,KAAM,GAAU,EAAO,EAAQ,EAAM,KAAM,EAAM,WACjD,MAAA,QACA,QAAA,KACC,EAAS,aAAU,EACnB,EAAU,SAAU,GAE1B,EAuDO,cAIT,GAWA,EAAa,YAAc"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let r=require("react"),e=require("react/jsx-runtime");var t=class extends r.Component{state={};static getDerivedStateFromError(r){return{error:r}}render(){const{error:r}=this.state;if(!r)return this.props.children;const{route:t,ctx:o,router:s}=this.props,n=t.errorComponent;if(n)return(0,e.jsx)(n,{error:r,ctx:{...o,phase:"render"}});const i=s.errorHandler?.(r);if(i instanceof Promise)throw i.catch(()=>{}),r;if(void 0!==i)return i;throw r}};exports.default=t;
|
|
2
|
+
//# sourceMappingURL=RouteErrorBoundary.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RouteErrorBoundary.cjs","names":[],"sources":["../../src/components/RouteErrorBoundary.tsx"],"sourcesContent":["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"],"mappings":"sDA0BA,IAAqB,EAArB,cAAgD,EAAA,UAC9C,MAAe,CAAC,EAEhB,+BAAO,CAAyB,GAC9B,MAAO,CAAC,QACV,CAEA,MAAA,GACE,MAAM,MAAC,GAAS,KAAK,MACrB,IAAK,EAAO,OAAO,KAAK,MAAM,SAC9B,MAAM,MAAC,EAAA,IAAO,EAAA,OAAK,GAAU,KAAK,MAC5B,EAAiB,EAAM,eAC7B,GAAI,EACF,OAAO,EAAA,EAAA,KAAC,EAAD,CAAuB,QAAO,IAAK,IAAI,EAAK,MAAO,YAK5D,MAAM,EAAW,EAAO,eAAe,GACvC,GAAI,aAAoB,QAEtB,MADA,EAAS,MAAA,QACH,EAER,QAAiB,IAAb,EAAwB,OAAO,EACnC,MAAM,CACR"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Component as r}from"react";import{jsx as t}from"react/jsx-runtime";var e=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:o,router:s}=this.props,n=e.errorComponent;if(n)/* @__PURE__ */return t(n,{error:r,ctx:{...o,phase:"render"}});const i=s.errorHandler?.(r);if(i instanceof Promise)throw i.catch(()=>{}),r;if(void 0!==i)return i;throw r}};export{e as default};
|
|
2
|
+
//# sourceMappingURL=RouteErrorBoundary.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RouteErrorBoundary.js","names":[],"sources":["../../src/components/RouteErrorBoundary.tsx"],"sourcesContent":["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"],"mappings":"0EA0BA,IAAqB,EAArB,cAAgD,EAC9C,MAAe,CAAC,EAEhB,+BAAO,CAAyB,GAC9B,MAAO,CAAC,QACV,CAEA,MAAA,GACE,MAAM,MAAC,GAAS,KAAK,MACrB,IAAK,EAAO,OAAO,KAAK,MAAM,SAC9B,MAAM,MAAC,EAAA,IAAO,EAAA,OAAK,GAAU,KAAK,MAC5B,EAAiB,EAAM,eAC7B,GAAI,iBACF,OAAO,EAAC,EAAD,CAAuB,QAAO,IAAK,IAAI,EAAK,MAAO,YAK5D,MAAM,EAAW,EAAO,eAAe,GACvC,GAAI,aAAoB,QAEtB,MADA,EAAS,MAAA,QACH,EAER,QAAiB,IAAb,EAAwB,OAAO,EACnC,MAAM,CACR"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../context.cjs"),r=require("../resolve-view.cjs");let t=require("react"),n=require("history"),o=require("react/jsx-runtime"),u=require("@native-router/core"),i=require("@native-router/core/util"),s=require("use-sync-external-store/shim");var c=(0,t.createContext)(null);function a({router:r,children:n}){const i=(0,t.useRef)((0,u.getCurrentView)(r)),a=(0,t.useCallback)(e=>(0,u.listen)(r,r=>{i.current=r,e()}),[r]),l=(0,t.useCallback)(()=>i.current,[]),d=(0,t.useCallback)(()=>(0,u.getCurrentView)(r),[r]),x=(0,s.useSyncExternalStore)(a,l,d),h=(0,t.useContext)(e.LoadingContext),v=null==x&&"pending"===h?.status?function(e,r){const{resolving:t}=e,n=t?(0,u.match)(e,t.pathname):void 0;if(!n)return null;for(let u=n.length-1;u>=0;u--){const e=n[u].route.pendingComponent;if(e)return(0,o.jsx)(e,{},r)}return null}(r,h.key):null;return(0,o.jsx)(c.Provider,{value:r,children:void 0===n?x??v:(0,o.jsx)(e.ViewProvider,{value:x,children:(0,o.jsx)(e.PendingContext.Provider,{value:v,children:n})})})}function l(e,t,{resolveView:n=r.default,...o}={}){return(0,u.create)(e,t,n,o)}function d({routes:r,children:n,...s},c){const[d,x]=(0,i.splitProps)(s,["baseUrl","currentView"]),{baseUrl:h,currentView:v}=d,[f,p]=(0,t.useState)(),C=(0,t.useMemo)(()=>l(r,c(),{...s,onLoadingChange(e){p(e&&{key:(0,i.uniqId)(),status:e})}}),[r,c,h,v]);(0,t.useEffect)(()=>{(0,u.setOptions)(C,{...x,onLoadingChange(e){p(e&&{key:(0,i.uniqId)(),status:e})}})},[C,x]);const g=(0,t.useMemo)(()=>(0,o.jsx)(a,{router:C,children:n}),[C,n]);return(0,o.jsx)(e.LoadingContext.Provider,{value:f,children:g})}exports.HashRouter=function(e){return d(e,n.createHashHistory)},exports.HistoryRouter=function(e){return d(e,n.createBrowserHistory)},exports.MemoryRouter=function({initialEntries:e,initialIndex:r,...o}){return d(o,(0,t.useMemo)(()=>()=>(0,n.createMemoryHistory)({initialEntries:e,initialIndex:r}),[e,r]))},exports.Router=a,exports.createRouter=l,exports.useRouter=function(){const e=(0,t.useContext)(c);if(!e)throw new Error("useRouter() must be used within a <Router> component");return e};
|
|
2
|
+
//# sourceMappingURL=Router.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Router.cjs","names":[],"sources":["../../src/components/Router.tsx"],"sourcesContent":["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"],"mappings":"+PA+BA,IAAM,GAAA,EAAgB,EAAA,eACpB,MAaF,SAAgB,GAAO,OACrB,EAAA,SACA,IAKA,MAAM,GAAA,EAAU,EAAA,SAAA,EAAkB,EAAA,gBAAe,IAC3C,GAAA,EAAY,EAAA,aACf,IAAA,EACC,EAAA,QAAO,EAAS,IACd,EAAQ,QAAU,EAClB,MAEJ,CAAC,IAEG,GAAA,EAAc,EAAA,aAAA,IAAkB,EAAQ,QAAS,IAGjD,GAAA,EAAoB,EAAA,aAAA,KAAA,EAAkB,EAAA,gBAAe,GAAS,CAAC,IAC/D,GAAA,EAAO,EAAA,sBAAqB,EAAW,EAAa,GAMpD,GAAA,EAAU,EAAA,YAAW,EAAA,gBACrB,EACI,MAAR,GAAoC,YAApB,GAAS,OA2B7B,SACE,EACA,GAEA,MAAM,UAAC,GAAa,EACd,EAAU,GAAA,EAAY,EAAA,OAAM,EAAQ,EAAU,eAAY,EAChE,IAAK,EAAS,OAAO,KACrB,IAAK,IAAI,EAAI,EAAQ,OAAS,EAAG,GAAK,EAAG,IAAK,CAC5C,MAAM,EAAU,EAAQ,GAAG,MAAM,iBACjC,GAAI,EAAS,OAAO,EAAA,EAAA,KAAC,EAAD,CAAoB,EAAN,EACpC,CACA,OAAO,IACT,CAtCQ,CAAmB,EAAQ,EAAQ,KACnC,KAEN,OACE,EAAA,EAAA,KAAC,EAAc,SAAf,CAAwB,MAAO,EAC5B,cAAa,IAAb,EACE,GAAQ,GAET,EAAA,EAAA,KAAC,EAAA,aAAD,CAAc,MAAO,EACnB,UAAA,EAAA,EAAA,KAAC,EAAA,eAAe,SAAhB,CAAyB,MAAO,EAC7B,gBAMb,CAwBA,SAAgB,EACd,EACA,GAEE,YAAA,EAAc,EAAA,WACX,GACmE,CAAC,GAEzE,OAAA,EAAO,EAAA,QAAO,EAAQ,EAAS,EAAa,EAC9C,CAEA,SAAS,GACP,OAAC,EAAA,SAAQ,KAAa,GACtB,GAEA,MAAO,EAAS,IAAA,EAAQ,EAAA,YAAW,EAAS,CAAC,UAAW,iBAClD,QAAC,EAAA,YAAS,GAAe,GACxB,EAAS,IAAA,EAAc,EAAA,YAMxB,GAAA,EAAS,EAAA,SAAA,IAEX,EAAa,EAAQ,IAAiB,IACjC,EACH,eAAA,CAAgB,GACd,EAAW,GAAU,CAAC,KAAA,EAAK,EAAA,UAAU,UACvC,IAIJ,CAAC,EAAQ,EAAe,EAAS,KAKnC,EAAA,EAAA,WAAA,MACE,EAAA,EAAA,YAAW,EAAQ,IACd,EACH,eAAA,CAAgB,GACd,EAAW,GAAU,CAAC,KAAA,EAAK,EAAA,UAAU,UACvC,KAED,CAAC,EAAQ,IAEZ,MAAM,GAAA,EAAI,EAAA,SAAA,KACF,EAAA,EAAA,KAAC,EAAD,CAAgB,SAAS,aAC/B,CAAC,EAAQ,IAGX,OAAO,EAAA,EAAA,KAAC,EAAA,eAAe,SAAhB,CAAyB,MAAO,EAAU,SAAA,GACnD,oBAcA,SAA2B,GACzB,OAAO,EAAa,EAAO,EAAA,kBAC7B,wBAVA,SAA8B,GAC5B,OAAO,EAAa,EAAO,EAAA,qBAC7B,uBAcA,UAA6B,eAC3B,EAAA,aACA,KACG,IAMH,OAAO,EAAa,GAAA,EAJE,EAAA,SAAA,IAAA,KAAA,EACR,EAAA,qBAAoB,CAAC,iBAAgB,iBACjD,CAAC,EAAgB,IAGrB,4DAOA,WACE,MAAM,GAAA,EAAS,EAAA,YAAW,GAC1B,IAAK,EACH,MAAM,IAAI,MAAM,wDAElB,OAAO,CACT"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{LoadingContext as r,PendingContext as n,ViewProvider as e}from"../context.js";import t from"../resolve-view.js";import{createContext as o,useCallback as i,useContext as u,useEffect as l,useMemo as c,useRef as s,useState as a}from"react";import{createBrowserHistory as m,createHashHistory as f,createMemoryHistory as d}from"history";import{jsx as v}from"react/jsx-runtime";import{create as h,getCurrentView as p,listen as g,match as w,setOptions as x}from"@native-router/core";import{splitProps as y,uniqId as b}from"@native-router/core/util";import{useSyncExternalStore as j}from"use-sync-external-store/shim";var k=o(null);function C({router:t,children:o}){const l=s(p(t)),c=i(r=>g(t,n=>{l.current=n,r()}),[t]),a=i(()=>l.current,[]),m=i(()=>p(t),[t]),f=j(c,a,m),d=u(r),h=null==f&&"pending"===d?.status?function(r,n){const{resolving:e}=r,t=e?w(r,e.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 v(r,{},n)}return null}(t,d.key):null;/* @__PURE__ */
|
|
2
|
+
return v(k.Provider,{value:t,children:void 0===o?f??h:/* @__PURE__ */v(e,{value:f,children:/* @__PURE__ */v(n.Provider,{value:h,children:o})})})}function E(r,n,{resolveView:e=t,...o}={}){return h(r,n,e,o)}function P({routes:n,children:e,...t},o){const[i,u]=y(t,["baseUrl","currentView"]),{baseUrl:s,currentView:m}=i,[f,d]=a(),h=c(()=>E(n,o(),{...t,onLoadingChange(r){d(r&&{key:b(),status:r})}}),[n,o,s,m]);l(()=>{x(h,{...u,onLoadingChange(r){d(r&&{key:b(),status:r})}})},[h,u]);const p=c(()=>/* @__PURE__ */v(C,{router:h,children:e}),[h,e]);/* @__PURE__ */
|
|
3
|
+
return v(r.Provider,{value:f,children:p})}function V(r){return P(r,m)}function I(r){return P(r,f)}function L({initialEntries:r,initialIndex:n,...e}){return P(e,c(()=>()=>d({initialEntries:r,initialIndex:n}),[r,n]))}function R(){const r=u(k);if(!r)throw new Error("useRouter() must be used within a <Router> component");return r}export{I as HashRouter,V as HistoryRouter,L as MemoryRouter,C as Router,E as createRouter,R as useRouter};
|
|
4
|
+
//# sourceMappingURL=Router.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Router.js","names":[],"sources":["../../src/components/Router.tsx"],"sourcesContent":["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"],"mappings":"ymBA+BA,IAAM,EAAgB,EACpB,MAaF,SAAgB,GAAO,OACrB,EAAA,SACA,IAKA,MAAM,EAAU,EAAkB,EAAe,IAC3C,EAAY,EACf,GACC,EAAO,EAAS,IACd,EAAQ,QAAU,EAClB,MAEJ,CAAC,IAEG,EAAc,EAAA,IAAkB,EAAQ,QAAS,IAGjD,EAAoB,EAAA,IAAkB,EAAe,GAAS,CAAC,IAC/D,EAAO,EAAqB,EAAW,EAAa,GAMpD,EAAU,EAAW,GACrB,EACI,MAAR,GAAoC,YAApB,GAAS,OA2B7B,SACE,EACA,GAEA,MAAM,UAAC,GAAa,EACd,EAAU,EAAY,EAAM,EAAQ,EAAU,eAAY,EAChE,IAAK,EAAS,OAAO,KACrB,IAAK,IAAI,EAAI,EAAQ,OAAS,EAAG,GAAK,EAAG,IAAK,CAC5C,MAAM,EAAU,EAAQ,GAAG,MAAM,iBACjC,GAAI,iBAAS,OAAO,EAAC,EAAD,CAAoB,EAAN,EACpC,CACA,OAAO,IACT,CAtCQ,CAAmB,EAAQ,EAAQ,KACnC;AAEN,OACE,EAAC,EAAc,SAAf,CAAwB,MAAO,EAC5B,cAAa,IAAb,EACE,GAAQ,iBAET,EAAC,EAAD,CAAc,MAAO,EACnB,wBAAA,EAAC,EAAe,SAAhB,CAAyB,MAAO,EAC7B,gBAMb,CAwBA,SAAgB,EACd,EACA,GAEE,YAAA,EAAc,KACX,GACmE,CAAC,GAEzE,OAAO,EAAO,EAAQ,EAAS,EAAa,EAC9C,CAEA,SAAS,GACP,OAAC,EAAA,SAAQ,KAAa,GACtB,GAEA,MAAO,EAAS,GAAQ,EAAW,EAAS,CAAC,UAAW,iBAClD,QAAC,EAAA,YAAS,GAAe,GACxB,EAAS,GAAc,IAMxB,EAAS,EAAA,IAEX,EAAa,EAAQ,IAAiB,IACjC,EACH,eAAA,CAAgB,GACd,EAAW,GAAU,CAAC,IAAK,IAAU,UACvC,IAIJ,CAAC,EAAQ,EAAe,EAAS,IAKnC,EAAA,KACE,EAAW,EAAQ,IACd,EACH,eAAA,CAAgB,GACd,EAAW,GAAU,CAAC,IAAK,IAAU,UACvC,KAED,CAAC,EAAQ,IAEZ,MAAM,EAAI,EAAA,mBACF,EAAC,EAAD,CAAgB,SAAS,aAC/B,CAAC,EAAQ;AAGX,OAAO,EAAC,EAAe,SAAhB,CAAyB,MAAO,EAAU,SAAA,GACnD,CAMA,SAAgB,EAAc,GAC5B,OAAO,EAAa,EAAO,EAC7B,CAMA,SAAgB,EAAW,GACzB,OAAO,EAAa,EAAO,EAC7B,CAMA,SAAgB,GAAa,eAC3B,EAAA,aACA,KACG,IAMH,OAAO,EAAa,EAJE,EAAA,IAAA,IACR,EAAoB,CAAC,iBAAgB,iBACjD,CAAC,EAAgB,IAGrB,CAOA,SAAgB,IACd,MAAM,EAAS,EAAW,GAC1B,IAAK,EACH,MAAM,IAAI,MAAM,wDAElB,OAAO,CACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const t=require("./Router.cjs");let e=require("react"),r=require("history");exports.default=function({resetOnPush:o=!0}){const n=t.useRouter(),s=(0,e.useRef)(new Map),c=(0,e.useRef)(-1),i=(0,e.useRef)("");return(0,e.useEffect)(()=>{if("undefined"==typeof window)return;window.history.scrollRestoration&&(window.history.scrollRestoration="manual");const t=s.current,e=t=>t?.index||0;c.current=e(n.history.location.state),i.current=(0,r.createPath)(n.history.location);let u=!1,l=!1,a=!0;const w=n.history.listen(({action:s})=>{l||="POP"===s,u||(u=!0,queueMicrotask(()=>{if(u=!1,!a)return;const s=l;l=!1;const{location:w}=n.history,f=e(w.state),y=(0,r.createPath)(w),d=c.current;if(f!==d&&t.set(d,{x:window.scrollX,y:window.scrollY}),s){const e=t.get(f)??{x:0,y:0};window.scrollTo(e.x,e.y),t.set(f,e)}else!o||f===d&&y===i.current||(window.scrollTo(0,0),t.set(f,{x:0,y:0}));c.current=f,i.current=y}))});return()=>{a=!1,w()}},[n,o]),null};
|
|
2
|
+
//# sourceMappingURL=ScrollRestoration.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ScrollRestoration.cjs","names":[],"sources":["../../src/components/ScrollRestoration.tsx"],"sourcesContent":["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"],"mappings":"4FAkDA,UAA0C,YACxC,GAAc,IAEd,MAAM,EAAS,EAAA,YAET,GAAA,EAAe,EAAA,QAAO,IAAI,KAC1B,GAAA,EAAe,EAAA,SAAO,GACtB,GAAA,EAAc,EAAA,QAAO,IA4E3B,OA1EA,EAAA,EAAA,WAAA,KACE,GAAsB,oBAAX,OAAwB,OAK/B,OAAO,QAAQ,oBACjB,OAAO,QAAQ,kBAAoB,UAGrC,MAAM,EAAY,EAAa,QACzB,EAAa,GAChB,GAAoC,OAAS,EAEhD,EAAa,QAAU,EAAU,EAAO,QAAQ,SAAS,OACzD,EAAY,SAAA,EAAU,EAAA,YAAW,EAAO,QAAQ,UAEhD,IAAI,GAAY,EACZ,GAAS,EACT,GAAS,EAEb,MAAM,EAAW,EAAO,QAAQ,OAAA,EAAS,aAQvC,IAAsB,QAAX,EACP,IACJ,GAAY,EACZ,eAAA,KAEE,GADA,GAAY,GACP,EAAQ,OACb,MAAM,EAAS,EACf,GAAS,EACT,MAAM,SAAC,GAAY,EAAO,QACpB,EAAQ,EAAU,EAAS,OAC3B,GAAA,EAAO,EAAA,YAAW,GAClB,EAAY,EAAa,QAO/B,GALI,IAAU,GAEZ,EAAU,IAAI,EAAW,CAAC,EAAG,OAAO,QAAS,EAAG,OAAO,UAGrD,EAAQ,CACV,MAAM,EAAQ,EAAU,IAAI,IAAU,CAAC,EAAG,EAAG,EAAG,GAChD,OAAO,SAAS,EAAM,EAAG,EAAM,GAC/B,EAAU,IAAI,EAAO,EACvB,MACE,GACC,IAAU,GAAa,IAAS,EAAY,UAI7C,OAAO,SAAS,EAAG,GACnB,EAAU,IAAI,EAAO,CAAC,EAAG,EAAG,EAAG,KAKjC,EAAa,QAAU,EACvB,EAAY,QAAU,OAI1B,MAAA,KACE,GAAS,EACT,MAED,CAAC,EAAQ,IAEL,IACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{useRouter as t}from"./Router.js";import{useEffect as o,useRef as r}from"react";import{createPath as n}from"history";function e({resetOnPush:e=!0}){const s=t(),i=r(/* @__PURE__ */new Map),c=r(-1),l=r("");return o(()=>{if("undefined"==typeof window)return;window.history.scrollRestoration&&(window.history.scrollRestoration="manual");const t=i.current,o=t=>t?.index||0;c.current=o(s.history.location.state),l.current=n(s.history.location);let r=!1,u=!1,a=!0;const w=s.history.listen(({action:i})=>{u||="POP"===i,r||(r=!0,queueMicrotask(()=>{if(r=!1,!a)return;const i=u;u=!1;const{location:w}=s.history,y=o(w.state),d=n(w),f=c.current;if(y!==f&&t.set(f,{x:window.scrollX,y:window.scrollY}),i){const o=t.get(y)??{x:0,y:0};window.scrollTo(o.x,o.y),t.set(y,o)}else!e||y===f&&d===l.current||(window.scrollTo(0,0),t.set(y,{x:0,y:0}));c.current=y,l.current=d}))});return()=>{a=!1,w()}},[s,e]),null}export{e as default};
|
|
2
|
+
//# sourceMappingURL=ScrollRestoration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ScrollRestoration.js","names":[],"sources":["../../src/components/ScrollRestoration.tsx"],"sourcesContent":["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"],"mappings":"2HAkDA,SAAwB,GAAkB,YACxC,GAAc,IAEd,MAAM,EAAS,IAET,EAAe,iBAAO,IAAI,KAC1B,EAAe,GAAO,GACtB,EAAc,EAAO,IA4E3B,OA1EA,EAAA,KACE,GAAsB,oBAAX,OAAwB,OAK/B,OAAO,QAAQ,oBACjB,OAAO,QAAQ,kBAAoB,UAGrC,MAAM,EAAY,EAAa,QACzB,EAAa,GAChB,GAAoC,OAAS,EAEhD,EAAa,QAAU,EAAU,EAAO,QAAQ,SAAS,OACzD,EAAY,QAAU,EAAW,EAAO,QAAQ,UAEhD,IAAI,GAAY,EACZ,GAAS,EACT,GAAS,EAEb,MAAM,EAAW,EAAO,QAAQ,OAAA,EAAS,aAQvC,IAAsB,QAAX,EACP,IACJ,GAAY,EACZ,eAAA,KAEE,GADA,GAAY,GACP,EAAQ,OACb,MAAM,EAAS,EACf,GAAS,EACT,MAAM,SAAC,GAAY,EAAO,QACpB,EAAQ,EAAU,EAAS,OAC3B,EAAO,EAAW,GAClB,EAAY,EAAa,QAO/B,GALI,IAAU,GAEZ,EAAU,IAAI,EAAW,CAAC,EAAG,OAAO,QAAS,EAAG,OAAO,UAGrD,EAAQ,CACV,MAAM,EAAQ,EAAU,IAAI,IAAU,CAAC,EAAG,EAAG,EAAG,GAChD,OAAO,SAAS,EAAM,EAAG,EAAM,GAC/B,EAAU,IAAI,EAAO,EACvB,MACE,GACC,IAAU,GAAa,IAAS,EAAY,UAI7C,OAAO,SAAS,EAAG,GACnB,EAAU,IAAI,EAAO,CAAC,EAAG,EAAG,EAAG,KAKjC,EAAa,QAAU,EACvB,EAAY,QAAU,OAI1B,MAAA,KACE,GAAS,EACT,MAED,CAAC,EAAQ,IAEL,IACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const r=require("./Router.cjs"),e=require("./link-behavior.cjs");let t=require("react"),n=require("react/jsx-runtime"),a=require("@native-router/core");function i(r,e){return r.replace(/\\.|[:*]([A-Za-z_$][A-Za-z0-9_$]*)/g,(t,n)=>{if(void 0===n)return t;const a=e[n];if(void 0===a||0===a.length)throw new Error(`Missing param "${n}" for the path pattern "${r}"`);return(Array.isArray(a)?a:[a]).map(encodeURIComponent).join("/")})}var o=(0,t.forwardRef)(function({to:o,params:u,onClick:c,as:s,asProps:f,...l},p){const h=r.useRouter(),d=(0,t.useRef)(!1);let v=o;try{v=i(o,u??{})}catch{}return(0,n.jsx)(s??"a",{...l,...f,ref:p,href:(0,a.createHref)(h,v),onClick:function(r){if(c?.(r),!e.shouldNavigate(r,f?.target??l.target,f?.rel??l.rel))return;if(r.preventDefault(),d.current)return;const t=i(o,u??{});d.current=!0,(0,a.navigate)(h,t).catch(()=>{}).finally(()=>{d.current=!1})}})});o.displayName="TypedLink",exports.default=o;
|
|
2
|
+
//# sourceMappingURL=TypedLink.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TypedLink.cjs","names":[],"sources":["../../src/components/TypedLink.tsx"],"sourcesContent":["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"],"mappings":"wJAsBA,SAAS,EACP,EACA,GAEA,OAAO,EAAQ,QACb,sCAAA,CACC,EAAO,KACN,QAAa,IAAT,EAAoB,OAAO,EAC/B,MAAM,EAAQ,EAAO,GACrB,QAAc,IAAV,GAAwC,IAAjB,EAAM,OAC/B,MAAM,IAAI,MACR,kBAAkB,4BAA+B,MAGrD,OAAQ,MAAM,QAAQ,GAAS,EAAQ,CAAC,IACrC,IAAI,oBACJ,KAAK,MAGd,CA2GA,IAAM,GAAA,EAAY,EAAA,YAzElB,UACE,GACE,EAAA,OACA,EAAA,QACA,EAAA,GACA,EAAA,QACA,KACG,GAOL,GAEA,MAAM,EAAS,EAAA,YACT,GAAA,EAAU,EAAA,SAAO,GAKvB,IAAI,EAAe,EACnB,IACE,EAAO,EAAgB,EAAI,GAAU,CAAC,EACxC,CAAA,MAEA,CAiCA,OACE,EAAA,EAAA,KAFS,GAAM,IAEf,IACM,KACA,EACC,MACL,MAAA,EAAM,EAAA,YAAW,EAAQ,GACzB,QArCJ,SAAqB,GAQnB,GALA,IAAU,IAMP,EAAA,eACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,KAG/C,OAGF,GAFA,EAAE,iBAEE,EAAQ,QAAS,OAGrB,MAAM,EAAS,EAAgB,EAAI,GAAU,CAAC,GAC9C,EAAQ,SAAU,GAClB,EAAA,EAAA,UAAS,EAAQ,GACd,MAAA,QACA,QAAA,KACC,EAAQ,SAAU,GAExB,GAYF,GAcA,EAAU,YAAc"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{useRouter as r}from"./Router.js";import{shouldNavigate as t}from"./link-behavior.js";import{forwardRef as e,useRef as n}from"react";import{jsx as o}from"react/jsx-runtime";import{createHref as a,navigate as i}from"@native-router/core";function c(r,t){return r.replace(/\\.|[:*]([A-Za-z_$][A-Za-z0-9_$]*)/g,(e,n)=>{if(void 0===n)return e;const o=t[n];if(void 0===o||0===o.length)throw new Error(`Missing param "${n}" for the path pattern "${r}"`);return(Array.isArray(o)?o:[o]).map(encodeURIComponent).join("/")})}var f=e(function({to:e,params:f,onClick:p,as:u,asProps:m,...s},l){const h=r(),d=n(!1);let v=e;try{v=c(e,f??{})}catch{}/* @__PURE__ */
|
|
2
|
+
return o(u??"a",{...s,...m,ref:l,href:a(h,v),onClick:function(r){if(p?.(r),!t(r,m?.target??s.target,m?.rel??s.rel))return;if(r.preventDefault(),d.current)return;const n=c(e,f??{});d.current=!0,i(h,n).catch(()=>{}).finally(()=>{d.current=!1})}})});f.displayName="TypedLink";export{f as default};
|
|
3
|
+
//# sourceMappingURL=TypedLink.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TypedLink.js","names":[],"sources":["../../src/components/TypedLink.tsx"],"sourcesContent":["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"],"mappings":"kPAsBA,SAAS,EACP,EACA,GAEA,OAAO,EAAQ,QACb,sCAAA,CACC,EAAO,KACN,QAAa,IAAT,EAAoB,OAAO,EAC/B,MAAM,EAAQ,EAAO,GACrB,QAAc,IAAV,GAAwC,IAAjB,EAAM,OAC/B,MAAM,IAAI,MACR,kBAAkB,4BAA+B,MAGrD,OAAQ,MAAM,QAAQ,GAAS,EAAQ,CAAC,IACrC,IAAI,oBACJ,KAAK,MAGd,CA2GA,IAAM,EAAY,EAzElB,UACE,GACE,EAAA,OACA,EAAA,QACA,EAAA,GACA,EAAA,QACA,KACG,GAOL,GAEA,MAAM,EAAS,IACT,EAAU,GAAO,GAKvB,IAAI,EAAe,EACnB,IACE,EAAO,EAAgB,EAAI,GAAU,CAAC,EACxC,CAAA,MAEA;AAiCA,OACE,EAFS,GAAM,IAEf,IACM,KACA,EACC,MACL,KAAM,EAAW,EAAQ,GACzB,QArCJ,SAAqB,GAQnB,GALA,IAAU,IAMP,EACC,EACC,GAAS,QAAiC,EAAK,OAC/C,GAAS,KAA8B,EAAK,KAG/C,OAGF,GAFA,EAAE,iBAEE,EAAQ,QAAS,OAGrB,MAAM,EAAS,EAAgB,EAAI,GAAU,CAAC,GAC9C,EAAQ,SAAU,EAClB,EAAS,EAAQ,GACd,MAAA,QACA,QAAA,KACC,EAAQ,SAAU,GAExB,GAYF,GAcA,EAAU,YAAc"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"link-behavior.cjs","names":[],"sources":["../../src/components/link-behavior.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"],"mappings":"uBAeA,SACE,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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"link-behavior.js","names":[],"sources":["../../src/components/link-behavior.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"],"mappings":"AAeA,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"}
|
package/dist/context.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let e=require("react"),t=require("react/jsx-runtime");var r=(0,e.createContext)(null);function n(){return(0,e.useContext)(r)}var o=(0,e.createContext)(null);var u=(0,e.createContext)([void 0,{}]);function s(){return(0,e.useContext)(u)}function a(){return s()[1]}var i=(0,e.createContext)(void 0);var x=(0,e.createContext)(void 0);exports.DataProvider=function({children:r,name:n,data:o}){const s=a(),i=(0,e.useMemo)(()=>[o,n?{...s,[n]:o}:s],[o,n,s]);return(0,t.jsx)(u.Provider,{value:i,children:r})},exports.LoadingContext=x,exports.MatchedContext=i,exports.PendingContext=o,exports.View=function(){const t=n(),r=(0,e.useContext)(o);return t??r},exports.ViewProvider=function(e){return(0,t.jsx)(r.Provider,{...e})},exports.useData=function(e){const[t,r]=s();return e?r[e]:t},exports.useLoading=function(){return(0,e.useContext)(x)},exports.useMatched=function(){return(0,e.useContext)(i)},exports.useNamedData=a,exports.useView=n;
|
|
2
|
+
//# sourceMappingURL=context.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.cjs","names":[],"sources":["../src/context.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"],"mappings":"sDAGA,IAAM,GAAA,EAAc,EAAA,eAAyB,MAU7C,SAAgB,IACd,OAAA,EAAO,EAAA,YAAW,EACpB,CASA,IAAa,GAAA,EAAiB,EAAA,eAAyB,MAcvD,IAAM,GAAA,EAAc,EAAA,eAA0C,MAAC,EAAW,CAAC,IAE3E,SAAS,IACP,OAAA,EAAO,EAAA,YAAW,EACpB,CAWA,SAAgB,IACd,OAAO,IAAiB,EAC1B,CAmBA,IAAa,GAAA,EAAiB,EAAA,oBAC5B,GAuBF,IAAa,GAAA,EAAiB,EAAA,oBAAsC,wBAzCpE,UAA6B,SAC3B,EAAA,KACA,EAAA,KACA,IAMA,MAAM,EAAY,IACZ,GAAA,EAAQ,EAAA,SAAA,IACN,CAAC,EAAM,EAAO,IAAI,EAAY,CAAA,GAAO,GAAQ,GACnD,CAAC,EAAM,EAAM,IAEf,OAAO,EAAA,EAAA,KAAC,EAAY,SAAb,CAA6B,QAAQ,YAC9C,0FAxCA,WACE,MAAM,EAAO,IACP,GAAA,EAAU,EAAA,YAAW,GAC3B,OAAO,GAAQ,CACjB,uBA/BA,SAA6B,GAC3B,OAAO,EAAA,EAAA,KAAC,EAAY,SAAb,IAA0B,GACnC,kBAsFA,SAAqC,GACnC,MAAO,EAAM,GAAa,IAC1B,OAAQ,EAAO,EAAU,GAAQ,CACnC,qBAOA,WACE,OAAA,EAAO,EAAA,YAAW,EACpB,qBAxBA,WACE,OAAA,EAAO,EAAA,YAAW,EACpB"}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{createContext as r,useContext as n,useMemo as t}from"react";import{jsx as o}from"react/jsx-runtime";var u=r(null);function e(r){/* @__PURE__ */
|
|
2
|
+
return o(u.Provider,{...r})}function i(){return n(u)}var c=r(null);function a(){const r=i(),t=n(c);return r??t}var f=r([void 0,{}]);function v(){return n(f)}function d(){return v()[1]}function l({children:r,name:n,data:u}){const e=d(),i=t(()=>[u,n?{...e,[n]:u}:e],[u,n,e]);/* @__PURE__ */
|
|
3
|
+
return o(f.Provider,{value:i,children:r})}var m=r(void 0);function s(){return n(m)}function p(r){const[n,t]=v();return r?t[r]:n}var h=r(void 0);function x(){return n(h)}export{l as DataProvider,h as LoadingContext,m as MatchedContext,c as PendingContext,a as View,e as ViewProvider,p as useData,x as useLoading,s as useMatched,d as useNamedData,i as useView};
|
|
4
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../src/context.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"],"mappings":"2GAGA,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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-routes.cjs","names":[],"sources":["../src/create-routes.js"],"sourcesContent":["/**\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"],"mappings":"qBAyBA,SAKE,GAEA,OAAO,CACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-routes.js","names":[],"sources":["../src/create-routes.js"],"sourcesContent":["/**\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"],"mappings":"AAyBA,SAAgB,EAKd,GAEA,OAAO,CACT"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./context.cjs"),r=require("./resolve-view.cjs"),t=require("./components/Router.cjs"),s=require("./components/Link.cjs"),o=require("./components/NavLink.cjs"),u=require("./components/PrefetchLink.cjs"),a=require("./components/ScrollRestoration.cjs"),c=require("./components/TypedLink.cjs"),p=require("./create-routes.cjs"),i=require("./use-search-params.cjs"),n=require("./use-blocker.cjs");exports.HashRouter=t.HashRouter,exports.HistoryRouter=t.HistoryRouter,exports.Link=s.default,exports.MemoryRouter=t.MemoryRouter,exports.NavLink=o.default,exports.PrefetchLink=u.default,exports.Router=t.Router,exports.ScrollRestoration=a.default,exports.TypedLink=c.default,exports.View=e.View,exports.createRouter=t.createRouter,exports.createRoutes=p.createRoutes,exports.defaultResolveView=r.default,exports.useBlocker=n.useBlocker,exports.useData=e.useData,exports.useLoading=e.useLoading,exports.useMatched=e.useMatched,exports.useNamedData=e.useNamedData,exports.usePrefetch=u.usePrefetch,exports.useRouter=t.useRouter,exports.useSearch=i.useSearch,exports.useSearchParams=i.useSearchParams,exports.useSetSearch=i.useSetSearch,exports.useView=e.useView;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
return x(u,{...f,...e,ref:c,href:R(s,t),onClick:function(r){o?.(r),_(r,e?.target??i.target,e?.rel??i.rel)&&(r.preventDefault(),a.current||(a.current=!0,$(s,t).catch(()=>{}).finally(()=>{a.current=!1})))},"aria-current":l})});K.displayName="Link";var M=K;var D=y(function({to:t,end:n=!1,caseSensitive:e=!1,className:o,style:i,ariaCurrent:c,children:s,as:a,asProps:u,...l},f){const h=r(),p=m(t=>h.history.listen(()=>t()),[h]),d=m(()=>h.history.location.pathname,[h]),y=U(p,d,d),v=S(h,t).pathname,[w,g]=e?[y,v]:[y.toLowerCase(),v.toLowerCase()],k=w===g,P=n||k?k:w.startsWith(g.endsWith("/")?g:`${g}/`),C={isActive:P,isExactActive:k};/* @__PURE__ */
|
|
3
|
-
return x(M,{to:t,...l,as:a,asProps:u,ref:f,className:"function"==typeof o?o(C):o,style:"function"==typeof i?i(C):i,"aria-current":P?c??"page":void 0,children:"function"==typeof s?s(C):s})});D.displayName="NavLink";var E=d({loading:!1});function T(){return v(E)}var z=y(function({to:t,prefetch:n="intent",children:e,as:o,asProps:i,onClick:c,...s},a){const u=r(),l=k(null),f=k(void 0),h=k(!1),[p,d]=P(!1),[y,v]=P(),[C,L]=P(),$=m(t=>{l.current=t,"function"==typeof a?a(t):a&&(a.current=t)},[a]);function N(){d(!0),v(void 0),h.current=!1;const r=j(u,t);return f.current=r,r.then(t=>t.task).then(t=>L(t),t=>{v(t),h.current=!0}).finally(()=>d(!1)),r}function b(){f.current||N()}w(()=>{f.current=void 0,h.current=!1,d(!1),v(void 0),L(void 0)},[t,u]),w(()=>{if("render"===n)return void b();if("viewport"!==n)return;const t=l.current;if(!t||"undefined"==typeof IntersectionObserver)return;const r=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&(r.disconnect(),b())});return r.observe(t),()=>r.disconnect()},[n,t,u]);const I=g(()=>({loading:p,error:y,view:C}),[p,y,C]),O="intent"===n?{onMouseEnter:b,onFocus:b}:void 0,S=o??"a";/* @__PURE__ */
|
|
4
|
-
return x(E.Provider,{value:I,children:/* @__PURE__ */x(S,{...s,...O,...i,ref:$,href:R(u,t),onClick:function(t){if(c?.(t),!_(t,i?.target??s.target,i?.rel??s.rel))return;t.preventDefault();const r=f.current;(!r||h.current?N():r).then(t=>A(u,t.task,t.location)).catch(()=>{}).finally(()=>{f.current=void 0,h.current=!1})},children:e})})});function W({resetOnPush:t=!0}){const n=r(),e=k(/* @__PURE__ */new Map),o=k(-1),i=k("");return w(()=>{if("undefined"==typeof window)return;window.history.scrollRestoration&&(window.history.scrollRestoration="manual");const r=e.current,c=t=>t?.index||0;o.current=c(n.history.location.state),i.current=C(n.history.location);let s=!1,a=!1,u=!0;const l=n.history.listen(({action:e})=>{a||="POP"===e,s||(s=!0,queueMicrotask(()=>{if(s=!1,!u)return;const e=a;a=!1;const{location:l}=n.history,f=c(l.state),h=C(l),p=o.current;if(f!==p&&r.set(p,{x:window.scrollX,y:window.scrollY}),e){const t=r.get(f)??{x:0,y:0};window.scrollTo(t.x,t.y),r.set(f,t)}else!t||f===p&&h===i.current||(window.scrollTo(0,0),r.set(f,{x:0,y:0}));o.current=f,i.current=h}))});return()=>{u=!1,l()}},[n,t]),null}function Z(t,r){return t.replace(/\\.|[:*]([A-Za-z_$][A-Za-z0-9_$]*)/g,(n,e)=>{if(void 0===e)return n;const o=r[e];if(void 0===o||0===o.length)throw new Error(`Missing param "${e}" for the path pattern "${t}"`);return(Array.isArray(o)?o:[o]).map(encodeURIComponent).join("/")})}z.displayName="PrefetchLink";var q=y(function({to:t,params:n,onClick:e,as:o,asProps:i,...c},s){const a=r(),u=k(!1);let l=t;try{l=Z(t,n??{})}catch{}/* @__PURE__ */
|
|
5
|
-
return x(o??"a",{...c,...i,ref:s,href:R(a,l),onClick:function(r){if(e?.(r),!_(r,i?.target??c.target,i?.rel??c.rel))return;if(r.preventDefault(),u.current)return;const o=Z(t,n??{});u.current=!0,$(a,o).catch(()=>{}).finally(()=>{u.current=!1})}})});function F(t){return t}function V(){const t=r(),n=m(r=>t.history.listen(()=>r()),[t]),e=m(()=>t.history.location.search,[t]),o=m(()=>"",[]);return[new URLSearchParams(U(n,e,o)),m((r,n)=>{const{history:e}=t,o="function"==typeof r?r(new URLSearchParams(e.location.search)):r;return B(t,o.toString(),n)},[t])]}function X(t){const n=r();return m((r,e)=>{const{history:o}=n,i="function"==typeof r?r(N(o.location.search)):r,c=b(t,Y(i));return B(n,Y(c),e)},[n,t])}function Y(t){return Object.entries(t).filter(([,t])=>null!=t).map(([t,r])=>(Array.isArray(r)?r:[r]).map(r=>`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`).join("&")).join("&")}function B(t,r,n){const{history:e}=t,{pathname:o,hash:i}=e.location,c=o+(r?`?${r}`:"")+i;return n?.replace?I(t,S(t,c)).then(r=>L(t,r.task,r.location)):$(t,c)}function G(t){const n=r(),e=m(t=>n.history.listen(()=>t()),[n]),o=m(()=>n.history.location.search,[n]),i=m(()=>"",[]),c=U(e,o,i);return t?b(t,c):N(c)}function H(t){const n=r(),e=k(t);e.current=t,w(()=>O(n,(t,r)=>e.current(t,r)),[n])}q.displayName="TypedLink";export{l as HashRouter,i as HistoryRouter,K as Link,t as MemoryRouter,D as NavLink,z as PrefetchLink,a as Router,W as ScrollRestoration,q as TypedLink,p as View,f as createRouter,F as createRoutes,c as defaultResolveView,h as hydrate,H as useBlocker,n as useData,e as useLoading,u as useMatched,s as useNamedData,T as usePrefetch,r as useRouter,G as useSearch,V as useSearchParams,X as useSetSearch,o as useView};
|
|
6
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
import{View as o,useData as r,useLoading as m,useMatched as e,useNamedData as t,useView as s}from"./context.js";import p from"./resolve-view.js";import{HashRouter as i,HistoryRouter as n,MemoryRouter as f,Router as c,createRouter as j,useRouter as a}from"./components/Router.js";import l from"./components/Link.js";import k from"./components/NavLink.js";import u,{usePrefetch as v}from"./components/PrefetchLink.js";import L from"./components/ScrollRestoration.js";import R from"./components/TypedLink.js";import{createRoutes as d}from"./create-routes.js";import{useSearch as h,useSearchParams as w,useSetSearch as x}from"./use-search-params.js";import{useBlocker as b}from"./use-blocker.js";export{i as HashRouter,n as HistoryRouter,l as Link,f as MemoryRouter,k as NavLink,u as PrefetchLink,c as Router,L as ScrollRestoration,R as TypedLink,o as View,j as createRouter,d as createRoutes,p as defaultResolveView,b as useBlocker,r as useData,m as useLoading,e as useMatched,t as useNamedData,v as usePrefetch,a as useRouter,h as useSearch,w as useSearchParams,x as useSetSearch,s as useView};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./context.cjs"),r=require("./components/RouteErrorBoundary.cjs");let t=require("react/jsx-runtime"),n=require("@native-router/core");var o=new WeakMap;function a(o,{router:a,location:i,signal:s},c){return Promise.all(o.map(({route:u},d)=>{const l={matched:o,params:(0,n.mergeMatchedParams)(o,d),index:d,router:a,location:i,search:(0,n.parseSearchInput)(i.search),signal:s??(new AbortController).signal};return Promise.all([u.search?(0,n.parseSearch)(u.search,i.search).then(e=>(l.search=e,c(u.data,l))):c(u.data,l),function(){if(!u.component)return e.View;const r=u.component(l);return Promise.resolve(r).then(e=>"default"in e?e.default:e)}()]).then(([n,o])=>(0,t.jsx)(r.default,{route:u,ctx:l,router:a,children:(0,t.jsx)(e.DataProvider,{data:n,name:u.name,children:(0,t.jsx)(e.MatchedContext.Provider,{value:l,children:(0,t.jsx)(o,{})})})},`${d}:${u.path??""}`),r=>{if(!u.errorComponent)throw r;return(0,t.jsx)(e.DataProvider,{data:void 0,name:u.name,children:(0,t.jsx)(e.MatchedContext.Provider,{value:l,children:(0,t.jsx)(u.errorComponent,{error:r,ctx:l})})})})})).then(r=>r.reverse().reduce((r,n)=>(0,t.jsx)(e.ViewProvider,{value:r,children:n})))}exports.createHydrateResolveView=function(e){return(r,t)=>a(r,t,(r,t)=>e[t.index])},exports.default=function(e,r){return a(e,r,(e,r)=>e?.(r))},exports.getViewData=function(e){return o.get(e)},exports.resolveViewServer=function(e,r){const t=new Array(e.length);return a(e,r,(e,r)=>Promise.resolve(e?.(r)).then(e=>t[r.index]=e)).then(e=>(o.set(e,t),e))};
|
|
2
|
+
//# sourceMappingURL=resolve-view.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-view.cjs","names":[],"sources":["../src/resolve-view.tsx"],"sourcesContent":["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"],"mappings":"sJAyBA,IAAM,EAAc,IAAI,QA0BxB,SAAS,EACP,GACA,OAAC,EAAA,SAAQ,EAAA,OAAU,GACnB,GAKA,OAAO,QAAQ,IACb,EAAQ,IAAA,EAAM,SAAQ,KAIpB,MAAM,EAAmD,CAC9C,UACT,QAAA,EAAQ,EAAA,oBAAmB,EAAS,GACpC,QACA,SACA,WACA,QAAA,EAAQ,EAAA,kBAAiB,EAAS,QAIlC,OAAQ,IAAU,IAAI,iBAAkB,QAsB1C,OAAO,QAAQ,IAAI,CAVjB,EAAM,QAAA,EACF,EAAA,aAAY,EAAM,OAAQ,EAAS,QAAQ,KAAM,IAC/C,EAAI,OAAS,EACN,EAAY,EAAM,KAAM,KAEjC,EAAY,EAAM,KAAM,GAf9B,WACE,IAAK,EAAM,UAAW,OAAO,EAAA,KAC7B,MAAM,EAAI,EAAM,UAAU,GAC1B,OAAO,QAAQ,QAAQ,GAAG,KAAM,GAAO,YAAa,EAAI,EAAE,QAAU,EACtE,CAgB6C,KAAqB,KAAA,EAC9D,EAAM,MAcN,EAAA,EAAA,KAAC,EAAA,QAAD,CAGS,QACF,MACG,SAER,UAAA,EAAA,EAAA,KAAC,EAAA,aAAD,CAAoB,OAAM,KAAM,EAAM,KACpC,UAAA,EAAA,EAAA,KAAC,EAAA,eAAe,SAAhB,CAAyB,MAAO,EAC9B,UAAA,EAAA,EAAA,KAAC,EAAD,CAAI,QAPH,GAAG,KAAS,EAAM,MAAQ,MAYlC,IACC,IAAK,EAAM,eAAgB,MAAM,EACjC,OACE,EAAA,EAAA,KAAC,EAAA,aAAD,CAAc,UAAM,EAAW,KAAM,EAAM,KACzC,UAAA,EAAA,EAAA,KAAC,EAAA,eAAe,SAAhB,CAAyB,MAAO,EAC9B,UAAA,EAAA,EAAA,KAAC,EAAM,eAAP,CAA6B,QAAY,iBAOrD,KAAM,GACN,EACG,UACA,OAAA,CAAQ,EAAK,KAAS,EAAA,EAAA,KAAC,EAAA,aAAD,CAAc,MAAO,EAAM,SAAA,KAExD,kCApGA,SAAyC,GACvC,MAAA,CAAQ,EAA2B,IACjC,EAAgB,EAAS,EAAA,CAAM,EAAG,IAAY,EAAK,EAAQ,OAC/D,kBA3BA,SACE,EACA,GAEA,OAAO,EAAgB,EAAS,EAAA,CAAM,EAAM,IAAY,IAAO,GACjE,sBAwBA,SAA4B,GAC1B,OAAO,EAAY,IAAI,EACzB,4BAtBA,SACE,EACA,GAEA,MAAM,EAAc,IAAI,MAAM,EAAQ,QACtC,OAAO,EAAgB,EAAS,EAAA,CAAM,EAAM,IAC1C,QAAQ,QAAQ,IAAO,IAAU,KAC9B,GAAY,EAAY,EAAQ,OAAS,IAE5C,KAAM,IACN,EAAY,IAAI,EAAM,GACf,GAEX"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{DataProvider as r,MatchedContext as e,View as n,ViewProvider as t}from"./context.js";import o from"./components/RouteErrorBoundary.js";import{jsx as a}from"react/jsx-runtime";import{mergeMatchedParams as i,parseSearch as c,parseSearchInput as u}from"@native-router/core";function l(r,e){return f(r,e,(r,e)=>r?.(e))}var s=/* @__PURE__ */new WeakMap;function m(r,e){const n=new Array(r.length);return f(r,e,(r,e)=>Promise.resolve(r?.(e)).then(r=>n[e.index]=r)).then(r=>(s.set(r,n),r))}function d(r){return(e,n)=>f(e,n,(e,n)=>r[n.index])}function h(r){return s.get(r)}function f(l,{router:s,location:m,signal:d},h){return Promise.all(l.map(({route:t},f)=>{const p={matched:l,params:i(l,f),index:f,router:s,location:m,search:u(m.search),signal:d??(new AbortController).signal};return Promise.all([t.search?c(t.search,m.search).then(r=>(p.search=r,h(t.data,p))):h(t.data,p),function(){if(!t.component)return n;const r=t.component(p);return Promise.resolve(r).then(r=>"default"in r?r.default:r)}()]).then(([n,i])=>/* @__PURE__ */a(o,{route:t,ctx:p,router:s,children:/* @__PURE__ */a(r,{data:n,name:t.name,children:/* @__PURE__ */a(e.Provider,{value:p,children:/* @__PURE__ */a(i,{})})})},`${f}:${t.path??""}`),n=>{if(!t.errorComponent)throw n;/* @__PURE__ */
|
|
2
|
+
return a(r,{data:void 0,name:t.name,children:/* @__PURE__ */a(e.Provider,{value:p,children:/* @__PURE__ */a(t.errorComponent,{error:n,ctx:p})})})})})).then(r=>r.reverse().reduce((r,e)=>/* @__PURE__ */a(t,{value:r,children:e})))}export{d as createHydrateResolveView,l as default,h as getViewData,m as resolveViewServer};
|
|
3
|
+
//# sourceMappingURL=resolve-view.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-view.js","names":[],"sources":["../src/resolve-view.tsx"],"sourcesContent":["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"],"mappings":"sRAkBA,SAAwB,EACtB,EACA,GAEA,OAAO,EAAgB,EAAS,EAAA,CAAM,EAAM,IAAY,IAAO,GACjE,CAEA,IAAM,iBAAc,IAAI,QAExB,SAAgB,EACd,EACA,GAEA,MAAM,EAAc,IAAI,MAAM,EAAQ,QACtC,OAAO,EAAgB,EAAS,EAAA,CAAM,EAAM,IAC1C,QAAQ,QAAQ,IAAO,IAAU,KAC9B,GAAY,EAAY,EAAQ,OAAS,IAE5C,KAAM,IACN,EAAY,IAAI,EAAM,GACf,GAEX,CAEA,SAAgB,EAAyB,GACvC,MAAA,CAAQ,EAA2B,IACjC,EAAgB,EAAS,EAAA,CAAM,EAAG,IAAY,EAAK,EAAQ,OAC/D,CAEA,SAAgB,EAAY,GAC1B,OAAO,EAAY,IAAI,EACzB,CAEA,SAAS,EACP,GACA,OAAC,EAAA,SAAQ,EAAA,OAAU,GACnB,GAKA,OAAO,QAAQ,IACb,EAAQ,IAAA,EAAM,SAAQ,KAIpB,MAAM,EAAmD,CAC9C,UACT,OAAQ,EAAmB,EAAS,GACpC,QACA,SACA,WACA,OAAQ,EAAiB,EAAS,QAIlC,OAAQ,IAAU,IAAI,iBAAkB,QAsB1C,OAAO,QAAQ,IAAI,CAVjB,EAAM,OACF,EAAY,EAAM,OAAQ,EAAS,QAAQ,KAAM,IAC/C,EAAI,OAAS,EACN,EAAY,EAAM,KAAM,KAEjC,EAAY,EAAM,KAAM,GAf9B,WACE,IAAK,EAAM,UAAW,OAAO,EAC7B,MAAM,EAAI,EAAM,UAAU,GAC1B,OAAO,QAAQ,QAAQ,GAAG,KAAM,GAAO,YAAa,EAAI,EAAE,QAAU,EACtE,CAgB6C,KAAqB,KAAA,EAC9D,EAAM,oBAcN,EAAC,EAAD,CAGS,QACF,MACG,SAER,wBAAA,EAAC,EAAD,CAAoB,OAAM,KAAM,EAAM,KACpC,wBAAA,EAAC,EAAe,SAAhB,CAAyB,MAAO,EAC9B,wBAAA,EAAC,EAAD,CAAI,QAPH,GAAG,KAAS,EAAM,MAAQ,MAYlC,IACC,IAAK,EAAM,eAAgB,MAAM;AACjC,OACE,EAAC,EAAD,CAAc,UAAM,EAAW,KAAM,EAAM,KACzC,wBAAA,EAAC,EAAe,SAAhB,CAAyB,MAAO,EAC9B,wBAAA,EAAC,EAAM,eAAP,CAA6B,QAAY,iBAOrD,KAAM,GACN,EACG,UACA,OAAA,CAAQ,EAAK,mBAAS,EAAC,EAAD,CAAc,MAAO,EAAM,SAAA,KAExD"}
|