@tanstack/react-router 1.156.0 → 1.157.1
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/dist/cjs/Asset.cjs +2 -1
- package/dist/cjs/Asset.cjs.map +1 -1
- package/dist/cjs/Match.cjs +2 -2
- package/dist/cjs/Match.cjs.map +1 -1
- package/dist/cjs/Matches.cjs +2 -2
- package/dist/cjs/Matches.cjs.map +1 -1
- package/dist/cjs/ScriptOnce.cjs +2 -1
- package/dist/cjs/ScriptOnce.cjs.map +1 -1
- package/dist/cjs/link.cjs +10 -13
- package/dist/cjs/link.cjs.map +1 -1
- package/dist/cjs/scroll-restoration.cjs +1 -1
- package/dist/cjs/scroll-restoration.cjs.map +1 -1
- package/dist/esm/Asset.js +2 -1
- package/dist/esm/Asset.js.map +1 -1
- package/dist/esm/Match.js +3 -3
- package/dist/esm/Match.js.map +1 -1
- package/dist/esm/Matches.js +3 -3
- package/dist/esm/Matches.js.map +1 -1
- package/dist/esm/ScriptOnce.js +2 -1
- package/dist/esm/ScriptOnce.js.map +1 -1
- package/dist/esm/link.js +10 -13
- package/dist/esm/link.js.map +1 -1
- package/dist/esm/scroll-restoration.js +2 -2
- package/dist/esm/scroll-restoration.js.map +1 -1
- package/package.json +2 -2
- package/src/Asset.tsx +2 -1
- package/src/Match.tsx +3 -2
- package/src/Matches.tsx +4 -3
- package/src/ScriptOnce.tsx +2 -1
- package/src/link.tsx +20 -15
- package/src/scroll-restoration.tsx +2 -1
package/dist/cjs/Asset.cjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const jsxRuntime = require("react/jsx-runtime");
|
|
4
4
|
const React = require("react");
|
|
5
|
+
const routerCore = require("@tanstack/router-core");
|
|
5
6
|
const useRouter = require("./useRouter.cjs");
|
|
6
7
|
function _interopNamespaceDefault(e) {
|
|
7
8
|
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
|
|
@@ -120,7 +121,7 @@ function Script({
|
|
|
120
121
|
}
|
|
121
122
|
return void 0;
|
|
122
123
|
}, [attrs, children]);
|
|
123
|
-
if (!router.isServer) {
|
|
124
|
+
if (!(routerCore.isServer ?? router.isServer)) {
|
|
124
125
|
const { src, ...rest } = attrs || {};
|
|
125
126
|
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
126
127
|
"script",
|
package/dist/cjs/Asset.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Asset.cjs","sources":["../../src/Asset.tsx"],"sourcesContent":["import * as React from 'react'\nimport { useRouter } from './useRouter'\nimport type { RouterManagedTag } from '@tanstack/router-core'\n\ninterface ScriptAttrs {\n [key: string]: string | boolean | undefined\n src?: string\n suppressHydrationWarning?: boolean\n}\n\nexport function Asset({\n tag,\n attrs,\n children,\n nonce,\n}: RouterManagedTag & { nonce?: string }): React.ReactElement | null {\n switch (tag) {\n case 'title':\n return (\n <title {...attrs} suppressHydrationWarning>\n {children}\n </title>\n )\n case 'meta':\n return <meta {...attrs} suppressHydrationWarning />\n case 'link':\n return <link {...attrs} nonce={nonce} suppressHydrationWarning />\n case 'style':\n return (\n <style\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children as string }}\n nonce={nonce}\n />\n )\n case 'script':\n return <Script attrs={attrs}>{children}</Script>\n default:\n return null\n }\n}\n\nfunction Script({\n attrs,\n children,\n}: {\n attrs?: ScriptAttrs\n children?: string\n}) {\n const router = useRouter()\n\n React.useEffect(() => {\n if (attrs?.src) {\n const normSrc = (() => {\n try {\n const base = document.baseURI || window.location.href\n return new URL(attrs.src, base).href\n } catch {\n return attrs.src\n }\n })()\n const existingScript = Array.from(\n document.querySelectorAll('script[src]'),\n ).find((el) => (el as HTMLScriptElement).src === normSrc)\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n if (typeof children === 'string') {\n const typeAttr =\n typeof attrs?.type === 'string' ? attrs.type : 'text/javascript'\n const nonceAttr =\n typeof attrs?.nonce === 'string' ? attrs.nonce : undefined\n const existingScript = Array.from(\n document.querySelectorAll('script:not([src])'),\n ).find((el) => {\n if (!(el instanceof HTMLScriptElement)) return false\n const sType = el.getAttribute('type') ?? 'text/javascript'\n const sNonce = el.getAttribute('nonce') ?? undefined\n return (\n el.textContent === children &&\n sType === typeAttr &&\n sNonce === nonceAttr\n )\n })\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n script.textContent = children\n\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n return undefined\n }, [attrs, children])\n\n if (!router.isServer) {\n const { src, ...rest } = attrs || {}\n // render an empty script on the client just to avoid hydration errors\n return (\n <script\n suppressHydrationWarning\n dangerouslySetInnerHTML={{ __html: '' }}\n {...rest}\n ></script>\n )\n }\n\n if (attrs?.src && typeof attrs.src === 'string') {\n return <script {...attrs} suppressHydrationWarning />\n }\n\n if (typeof children === 'string') {\n return (\n <script\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children }}\n suppressHydrationWarning\n />\n )\n }\n\n return null\n}\n"],"names":["jsx","useRouter","React"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Asset.cjs","sources":["../../src/Asset.tsx"],"sourcesContent":["import * as React from 'react'\nimport { isServer } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport type { RouterManagedTag } from '@tanstack/router-core'\n\ninterface ScriptAttrs {\n [key: string]: string | boolean | undefined\n src?: string\n suppressHydrationWarning?: boolean\n}\n\nexport function Asset({\n tag,\n attrs,\n children,\n nonce,\n}: RouterManagedTag & { nonce?: string }): React.ReactElement | null {\n switch (tag) {\n case 'title':\n return (\n <title {...attrs} suppressHydrationWarning>\n {children}\n </title>\n )\n case 'meta':\n return <meta {...attrs} suppressHydrationWarning />\n case 'link':\n return <link {...attrs} nonce={nonce} suppressHydrationWarning />\n case 'style':\n return (\n <style\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children as string }}\n nonce={nonce}\n />\n )\n case 'script':\n return <Script attrs={attrs}>{children}</Script>\n default:\n return null\n }\n}\n\nfunction Script({\n attrs,\n children,\n}: {\n attrs?: ScriptAttrs\n children?: string\n}) {\n const router = useRouter()\n\n React.useEffect(() => {\n if (attrs?.src) {\n const normSrc = (() => {\n try {\n const base = document.baseURI || window.location.href\n return new URL(attrs.src, base).href\n } catch {\n return attrs.src\n }\n })()\n const existingScript = Array.from(\n document.querySelectorAll('script[src]'),\n ).find((el) => (el as HTMLScriptElement).src === normSrc)\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n if (typeof children === 'string') {\n const typeAttr =\n typeof attrs?.type === 'string' ? attrs.type : 'text/javascript'\n const nonceAttr =\n typeof attrs?.nonce === 'string' ? attrs.nonce : undefined\n const existingScript = Array.from(\n document.querySelectorAll('script:not([src])'),\n ).find((el) => {\n if (!(el instanceof HTMLScriptElement)) return false\n const sType = el.getAttribute('type') ?? 'text/javascript'\n const sNonce = el.getAttribute('nonce') ?? undefined\n return (\n el.textContent === children &&\n sType === typeAttr &&\n sNonce === nonceAttr\n )\n })\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n script.textContent = children\n\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n return undefined\n }, [attrs, children])\n\n if (!(isServer ?? router.isServer)) {\n const { src, ...rest } = attrs || {}\n // render an empty script on the client just to avoid hydration errors\n return (\n <script\n suppressHydrationWarning\n dangerouslySetInnerHTML={{ __html: '' }}\n {...rest}\n ></script>\n )\n }\n\n if (attrs?.src && typeof attrs.src === 'string') {\n return <script {...attrs} suppressHydrationWarning />\n }\n\n if (typeof children === 'string') {\n return (\n <script\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children }}\n suppressHydrationWarning\n />\n )\n }\n\n return null\n}\n"],"names":["jsx","useRouter","React","isServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWO,SAAS,MAAM;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAqE;AACnE,UAAQ,KAAA;AAAA,IACN,KAAK;AACH,4CACG,SAAA,EAAO,GAAG,OAAO,0BAAwB,MACvC,UACH;AAAA,IAEJ,KAAK;AACH,aAAOA,2BAAAA,IAAC,QAAA,EAAM,GAAG,OAAO,0BAAwB,MAAC;AAAA,IACnD,KAAK;AACH,4CAAQ,QAAA,EAAM,GAAG,OAAO,OAAc,0BAAwB,MAAC;AAAA,IACjE,KAAK;AACH,aACEA,2BAAAA;AAAAA,QAAC;AAAA,QAAA;AAAA,UACE,GAAG;AAAA,UACJ,yBAAyB,EAAE,QAAQ,SAAA;AAAA,UACnC;AAAA,QAAA;AAAA,MAAA;AAAA,IAGN,KAAK;AAC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AAA;AAAA,IAAA;AAAA,EAG9B;AAEA,SAAO;AACT;;"}
|
package/dist/cjs/Match.cjs
CHANGED
|
@@ -178,7 +178,7 @@ const MatchInner = React__namespace.memo(function MatchInnerImpl({
|
|
|
178
178
|
if (pendingMinMs) {
|
|
179
179
|
const routerMatch = router.getMatch(match.id);
|
|
180
180
|
if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
|
|
181
|
-
if (!router.isServer) {
|
|
181
|
+
if (!(routerCore.isServer ?? router.isServer)) {
|
|
182
182
|
const minPendingPromise = routerCore.createControlledPromise();
|
|
183
183
|
routerMatch._nonReactive.minPendingPromise = minPendingPromise;
|
|
184
184
|
setTimeout(() => {
|
|
@@ -199,7 +199,7 @@ const MatchInner = React__namespace.memo(function MatchInnerImpl({
|
|
|
199
199
|
throw router.getMatch(match.id)?._nonReactive.loadPromise;
|
|
200
200
|
}
|
|
201
201
|
if (match.status === "error") {
|
|
202
|
-
if (router.isServer) {
|
|
202
|
+
if (routerCore.isServer ?? router.isServer) {
|
|
203
203
|
const RouteErrorComponent = (route.options.errorComponent ?? router.options.defaultErrorComponent) || CatchBoundary.ErrorComponent;
|
|
204
204
|
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
205
205
|
RouteErrorComponent,
|
package/dist/cjs/Match.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Match.cjs","sources":["../../src/Match.tsx"],"sourcesContent":["import * as React from 'react'\nimport invariant from 'tiny-invariant'\nimport warning from 'tiny-warning'\nimport {\n createControlledPromise,\n getLocationChangeInfo,\n isNotFound,\n isRedirect,\n rootRouteId,\n} from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { CatchNotFound } from './not-found'\nimport { matchContext } from './matchContext'\nimport { SafeFragment } from './SafeFragment'\nimport { renderRouteNotFound } from './renderRouteNotFound'\nimport { ScrollRestoration } from './scroll-restoration'\nimport { ClientOnly } from './ClientOnly'\nimport type {\n AnyRoute,\n ParsedLocation,\n RootRouteOptions,\n} from '@tanstack/router-core'\n\nexport const Match = React.memo(function MatchImpl({\n matchId,\n}: {\n matchId: string\n}) {\n const router = useRouter()\n const matchState = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)\n invariant(\n match,\n `Could not find match for matchId \"${matchId}\". Please file an issue!`,\n )\n return {\n routeId: match.routeId,\n ssr: match.ssr,\n _displayPending: match._displayPending,\n }\n },\n structuralSharing: true as any,\n })\n\n const route: AnyRoute = router.routesById[matchState.routeId]\n\n const PendingComponent =\n route.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n const routeErrorComponent =\n route.options.errorComponent ?? router.options.defaultErrorComponent\n\n const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch\n\n const routeNotFoundComponent = route.isRoot\n ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component\n (route.options.notFoundComponent ??\n router.options.notFoundRoute?.options.component)\n : route.options.notFoundComponent\n\n const resolvedNoSsr =\n matchState.ssr === false || matchState.ssr === 'data-only'\n const ResolvedSuspenseBoundary =\n // If we're on the root route, allow forcefully wrapping in suspense\n (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) &&\n (route.options.wrapInSuspense ??\n PendingComponent ??\n ((route.options.errorComponent as any)?.preload || resolvedNoSsr))\n ? React.Suspense\n : SafeFragment\n\n const ResolvedCatchBoundary = routeErrorComponent\n ? CatchBoundary\n : SafeFragment\n\n const ResolvedNotFoundBoundary = routeNotFoundComponent\n ? CatchNotFound\n : SafeFragment\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const parentRouteId = useRouterState({\n select: (s) => {\n const index = s.matches.findIndex((d) => d.id === matchId)\n return s.matches[index - 1]?.routeId as string\n },\n })\n\n const ShellComponent = route.isRoot\n ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)\n : SafeFragment\n return (\n <ShellComponent>\n <matchContext.Provider value={matchId}>\n <ResolvedSuspenseBoundary fallback={pendingElement}>\n <ResolvedCatchBoundary\n getResetKey={() => resetKey}\n errorComponent={routeErrorComponent || ErrorComponent}\n onCatch={(error, errorInfo) => {\n // Forward not found errors (we don't want to show the error component for these)\n if (isNotFound(error)) throw error\n warning(false, `Error in route match: ${matchId}`)\n routeOnCatch?.(error, errorInfo)\n }}\n >\n <ResolvedNotFoundBoundary\n fallback={(error) => {\n // If the current not found handler doesn't exist or it has a\n // route ID which doesn't match the current route, rethrow the error\n if (\n !routeNotFoundComponent ||\n (error.routeId && error.routeId !== matchState.routeId) ||\n (!error.routeId && !route.isRoot)\n )\n throw error\n\n return React.createElement(routeNotFoundComponent, error as any)\n }}\n >\n {resolvedNoSsr || matchState._displayPending ? (\n <ClientOnly fallback={pendingElement}>\n <MatchInner matchId={matchId} />\n </ClientOnly>\n ) : (\n <MatchInner matchId={matchId} />\n )}\n </ResolvedNotFoundBoundary>\n </ResolvedCatchBoundary>\n </ResolvedSuspenseBoundary>\n </matchContext.Provider>\n {parentRouteId === rootRouteId && router.options.scrollRestoration ? (\n <>\n <OnRendered />\n <ScrollRestoration />\n </>\n ) : null}\n </ShellComponent>\n )\n})\n\n// On Rendered can't happen above the root layout because it actually\n// renders a dummy dom element to track the rendered state of the app.\n// We render a script tag with a key that changes based on the current\n// location state.__TSR_key. Also, because it's below the root layout, it\n// allows us to fire onRendered events even after a hydration mismatch\n// error that occurred above the root layout (like bad head/link tags,\n// which is common).\nfunction OnRendered() {\n const router = useRouter()\n\n const prevLocationRef = React.useRef<undefined | ParsedLocation<{}>>(\n undefined,\n )\n\n return (\n <script\n key={router.latestLocation.state.__TSR_key}\n suppressHydrationWarning\n ref={(el) => {\n if (\n el &&\n (prevLocationRef.current === undefined ||\n prevLocationRef.current.href !== router.latestLocation.href)\n ) {\n router.emit({\n type: 'onRendered',\n ...getLocationChangeInfo(router.state),\n })\n prevLocationRef.current = router.latestLocation\n }\n }}\n />\n )\n}\n\nexport const MatchInner = React.memo(function MatchInnerImpl({\n matchId,\n}: {\n matchId: string\n}): any {\n const router = useRouter()\n\n const { match, key, routeId } = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)!\n const routeId = match.routeId as string\n\n const remountFn =\n (router.routesById[routeId] as AnyRoute).options.remountDeps ??\n router.options.defaultRemountDeps\n const remountDeps = remountFn?.({\n routeId,\n loaderDeps: match.loaderDeps,\n params: match._strictParams,\n search: match._strictSearch,\n })\n const key = remountDeps ? JSON.stringify(remountDeps) : undefined\n\n return {\n key,\n routeId,\n match: {\n id: match.id,\n status: match.status,\n error: match.error,\n invalid: match.invalid,\n _forcePending: match._forcePending,\n _displayPending: match._displayPending,\n },\n }\n },\n structuralSharing: true as any,\n })\n\n const route = router.routesById[routeId] as AnyRoute\n\n const out = React.useMemo(() => {\n const Comp = route.options.component ?? router.options.defaultComponent\n if (Comp) {\n return <Comp key={key} />\n }\n return <Outlet />\n }, [key, route.options.component, router.options.defaultComponent])\n\n if (match._displayPending) {\n throw router.getMatch(match.id)?._nonReactive.displayPendingPromise\n }\n\n if (match._forcePending) {\n throw router.getMatch(match.id)?._nonReactive.minPendingPromise\n }\n\n // see also hydrate() in packages/router-core/src/ssr/ssr-client.ts\n if (match.status === 'pending') {\n // We're pending, and if we have a minPendingMs, we need to wait for it\n const pendingMinMs =\n route.options.pendingMinMs ?? router.options.defaultPendingMinMs\n if (pendingMinMs) {\n const routerMatch = router.getMatch(match.id)\n if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {\n // Create a promise that will resolve after the minPendingMs\n if (!router.isServer) {\n const minPendingPromise = createControlledPromise<void>()\n\n routerMatch._nonReactive.minPendingPromise = minPendingPromise\n\n setTimeout(() => {\n minPendingPromise.resolve()\n // We've handled the minPendingPromise, so we can delete it\n routerMatch._nonReactive.minPendingPromise = undefined\n }, pendingMinMs)\n }\n }\n }\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'notFound') {\n invariant(isNotFound(match.error), 'Expected a notFound error')\n return renderRouteNotFound(router, route, match.error)\n }\n\n if (match.status === 'redirected') {\n // Redirects should be handled by the router transition. If we happen to\n // encounter a redirect here, it's a bug. Let's warn, but render nothing.\n invariant(isRedirect(match.error), 'Expected a redirect error')\n\n // warning(\n // false,\n // 'Tried to render a redirected route match! This is a weird circumstance, please file an issue!',\n // )\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'error') {\n // If we're on the server, we need to use React's new and super\n // wonky api for throwing errors from a server side render inside\n // of a suspense boundary. This is the only way to get\n // renderToPipeableStream to not hang indefinitely.\n // We'll serialize the error and rethrow it on the client.\n if (router.isServer) {\n const RouteErrorComponent =\n (route.options.errorComponent ??\n router.options.defaultErrorComponent) ||\n ErrorComponent\n return (\n <RouteErrorComponent\n error={match.error as any}\n reset={undefined as any}\n info={{\n componentStack: '',\n }}\n />\n )\n }\n\n throw match.error\n }\n\n return out\n})\n\n/**\n * Render the next child match in the route tree. Typically used inside\n * a route component to render nested routes.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent\n */\nexport const Outlet = React.memo(function OutletImpl() {\n const router = useRouter()\n const matchId = React.useContext(matchContext)\n const routeId = useRouterState({\n select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,\n })\n\n const route = router.routesById[routeId]!\n\n const parentGlobalNotFound = useRouterState({\n select: (s) => {\n const matches = s.matches\n const parentMatch = matches.find((d) => d.id === matchId)\n invariant(\n parentMatch,\n `Could not find parent match for matchId \"${matchId}\"`,\n )\n return parentMatch.globalNotFound\n },\n })\n\n const childMatchId = useRouterState({\n select: (s) => {\n const matches = s.matches\n const index = matches.findIndex((d) => d.id === matchId)\n return matches[index + 1]?.id\n },\n })\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n if (parentGlobalNotFound) {\n return renderRouteNotFound(router, route, undefined)\n }\n\n if (!childMatchId) {\n return null\n }\n\n const nextMatch = <Match matchId={childMatchId} />\n\n if (routeId === rootRouteId) {\n return (\n <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense>\n )\n }\n\n return nextMatch\n})\n"],"names":["React","useRouter","useRouterState","jsx","SafeFragment","CatchBoundary","CatchNotFound","matchContext","ErrorComponent","isNotFound","ClientOnly","rootRouteId","jsxs","Fragment","ScrollRestoration","getLocationChangeInfo","match","routeId","key","createControlledPromise","renderRouteNotFound","isRedirect"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,QAAQA,iBAAM,KAAK,SAAS,UAAU;AAAA,EACjD;AACF,GAEG;AACD,QAAM,SAASC,UAAAA,UAAA;AACf,QAAM,aAAaC,eAAAA,eAAe;AAAA,IAChC,QAAQ,CAAC,MAAM;AACb,YAAM,QAAQ,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACpD;AAAA,QACE;AAAA,QACA,qCAAqC,OAAO;AAAA,MAAA;AAE9C,aAAO;AAAA,QACL,SAAS,MAAM;AAAA,QACf,KAAK,MAAM;AAAA,QACX,iBAAiB,MAAM;AAAA,MAAA;AAAA,IAE3B;AAAA,IACA,mBAAmB;AAAA,EAAA,CACpB;AAED,QAAM,QAAkB,OAAO,WAAW,WAAW,OAAO;AAE5D,QAAM,mBACJ,MAAM,QAAQ,oBAAoB,OAAO,QAAQ;AAEnD,QAAM,iBAAiB,mBAAmBC,2BAAAA,IAAC,kBAAA,CAAA,CAAiB,IAAK;AAEjE,QAAM,sBACJ,MAAM,QAAQ,kBAAkB,OAAO,QAAQ;AAEjD,QAAM,eAAe,MAAM,QAAQ,WAAW,OAAO,QAAQ;AAE7D,QAAM,yBAAyB,MAAM;AAAA;AAAA,IAEhC,MAAM,QAAQ,qBACf,OAAO,QAAQ,eAAe,QAAQ;AAAA,MACtC,MAAM,QAAQ;AAElB,QAAM,gBACJ,WAAW,QAAQ,SAAS,WAAW,Q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O,WAAW,OAAO;AAEvC,QAAM,uBAAuBA,eAAAA,eAAe;AAAA,IAC1C,QAAQ,CAAC,MAAM;AACb,YAAM,UAAU,EAAE;AAClB,YAAM,cAAc,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACxD;AAAA,QACE;AAAA,QACA,4CAA4C,OAAO;AAAA,MAAA;AAErD,aAAO,YAAY;AAAA,IACrB;AAAA,EAAA,CACD;AAED,QAAM,eAAeA,eAAAA,eAAe;AAAA,IAClC,QAAQ,CAAC,MAAM;AACb,YAAM,UAAU,EAAE;AAClB,YAAM,QAAQ,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,OAAO;AACvD,aAAO,QAAQ,QAAQ,CAAC,GAAG;AAAA,IAC7B;AAAA,EAAA,CACD;AAED,QAAM,iBAAiB,OAAO,QAAQ,yDACnC,OAAO,QAAQ,yBAAf,CAAA,CAAuC,IACtC;AAEJ,MAAI,sBAAsB;AACxB,WAAOkB,wCAAoB,QAAQ,OAAO,MAAS;AAAA,EACrD;AAEA,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,YAAYjB,2BAAAA,IAAC,OAAA,EAAM,SAAS,aAAA,CAAc;AAEhD,MAAI,YAAYQ,WAAAA,aAAa;AAC3B,0CACGX,iBAAM,UAAN,EAAe,UAAU,gBAAiB,UAAA,WAAU;AAAA,EAEzD;AAEA,SAAO;AACT,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"Match.cjs","sources":["../../src/Match.tsx"],"sourcesContent":["import * as React from 'react'\nimport invariant from 'tiny-invariant'\nimport warning from 'tiny-warning'\nimport {\n createControlledPromise,\n getLocationChangeInfo,\n isNotFound,\n isRedirect,\n isServer,\n rootRouteId,\n} from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { CatchNotFound } from './not-found'\nimport { matchContext } from './matchContext'\nimport { SafeFragment } from './SafeFragment'\nimport { renderRouteNotFound } from './renderRouteNotFound'\nimport { ScrollRestoration } from './scroll-restoration'\nimport { ClientOnly } from './ClientOnly'\nimport type {\n AnyRoute,\n ParsedLocation,\n RootRouteOptions,\n} from '@tanstack/router-core'\n\nexport const Match = React.memo(function MatchImpl({\n matchId,\n}: {\n matchId: string\n}) {\n const router = useRouter()\n const matchState = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)\n invariant(\n match,\n `Could not find match for matchId \"${matchId}\". Please file an issue!`,\n )\n return {\n routeId: match.routeId,\n ssr: match.ssr,\n _displayPending: match._displayPending,\n }\n },\n structuralSharing: true as any,\n })\n\n const route: AnyRoute = router.routesById[matchState.routeId]\n\n const PendingComponent =\n route.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n const routeErrorComponent =\n route.options.errorComponent ?? router.options.defaultErrorComponent\n\n const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch\n\n const routeNotFoundComponent = route.isRoot\n ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component\n (route.options.notFoundComponent ??\n router.options.notFoundRoute?.options.component)\n : route.options.notFoundComponent\n\n const resolvedNoSsr =\n matchState.ssr === false || matchState.ssr === 'data-only'\n const ResolvedSuspenseBoundary =\n // If we're on the root route, allow forcefully wrapping in suspense\n (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) &&\n (route.options.wrapInSuspense ??\n PendingComponent ??\n ((route.options.errorComponent as any)?.preload || resolvedNoSsr))\n ? React.Suspense\n : SafeFragment\n\n const ResolvedCatchBoundary = routeErrorComponent\n ? CatchBoundary\n : SafeFragment\n\n const ResolvedNotFoundBoundary = routeNotFoundComponent\n ? CatchNotFound\n : SafeFragment\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const parentRouteId = useRouterState({\n select: (s) => {\n const index = s.matches.findIndex((d) => d.id === matchId)\n return s.matches[index - 1]?.routeId as string\n },\n })\n\n const ShellComponent = route.isRoot\n ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)\n : SafeFragment\n return (\n <ShellComponent>\n <matchContext.Provider value={matchId}>\n <ResolvedSuspenseBoundary fallback={pendingElement}>\n <ResolvedCatchBoundary\n getResetKey={() => resetKey}\n errorComponent={routeErrorComponent || ErrorComponent}\n onCatch={(error, errorInfo) => {\n // Forward not found errors (we don't want to show the error component for these)\n if (isNotFound(error)) throw error\n warning(false, `Error in route match: ${matchId}`)\n routeOnCatch?.(error, errorInfo)\n }}\n >\n <ResolvedNotFoundBoundary\n fallback={(error) => {\n // If the current not found handler doesn't exist or it has a\n // route ID which doesn't match the current route, rethrow the error\n if (\n !routeNotFoundComponent ||\n (error.routeId && error.routeId !== matchState.routeId) ||\n (!error.routeId && !route.isRoot)\n )\n throw error\n\n return React.createElement(routeNotFoundComponent, error as any)\n }}\n >\n {resolvedNoSsr || matchState._displayPending ? (\n <ClientOnly fallback={pendingElement}>\n <MatchInner matchId={matchId} />\n </ClientOnly>\n ) : (\n <MatchInner matchId={matchId} />\n )}\n </ResolvedNotFoundBoundary>\n </ResolvedCatchBoundary>\n </ResolvedSuspenseBoundary>\n </matchContext.Provider>\n {parentRouteId === rootRouteId && router.options.scrollRestoration ? (\n <>\n <OnRendered />\n <ScrollRestoration />\n </>\n ) : null}\n </ShellComponent>\n )\n})\n\n// On Rendered can't happen above the root layout because it actually\n// renders a dummy dom element to track the rendered state of the app.\n// We render a script tag with a key that changes based on the current\n// location state.__TSR_key. Also, because it's below the root layout, it\n// allows us to fire onRendered events even after a hydration mismatch\n// error that occurred above the root layout (like bad head/link tags,\n// which is common).\nfunction OnRendered() {\n const router = useRouter()\n\n const prevLocationRef = React.useRef<undefined | ParsedLocation<{}>>(\n undefined,\n )\n\n return (\n <script\n key={router.latestLocation.state.__TSR_key}\n suppressHydrationWarning\n ref={(el) => {\n if (\n el &&\n (prevLocationRef.current === undefined ||\n prevLocationRef.current.href !== router.latestLocation.href)\n ) {\n router.emit({\n type: 'onRendered',\n ...getLocationChangeInfo(router.state),\n })\n prevLocationRef.current = router.latestLocation\n }\n }}\n />\n )\n}\n\nexport const MatchInner = React.memo(function MatchInnerImpl({\n matchId,\n}: {\n matchId: string\n}): any {\n const router = useRouter()\n\n const { match, key, routeId } = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)!\n const routeId = match.routeId as string\n\n const remountFn =\n (router.routesById[routeId] as AnyRoute).options.remountDeps ??\n router.options.defaultRemountDeps\n const remountDeps = remountFn?.({\n routeId,\n loaderDeps: match.loaderDeps,\n params: match._strictParams,\n search: match._strictSearch,\n })\n const key = remountDeps ? JSON.stringify(remountDeps) : undefined\n\n return {\n key,\n routeId,\n match: {\n id: match.id,\n status: match.status,\n error: match.error,\n invalid: match.invalid,\n _forcePending: match._forcePending,\n _displayPending: match._displayPending,\n },\n }\n },\n structuralSharing: true as any,\n })\n\n const route = router.routesById[routeId] as AnyRoute\n\n const out = React.useMemo(() => {\n const Comp = route.options.component ?? router.options.defaultComponent\n if (Comp) {\n return <Comp key={key} />\n }\n return <Outlet />\n }, [key, route.options.component, router.options.defaultComponent])\n\n if (match._displayPending) {\n throw router.getMatch(match.id)?._nonReactive.displayPendingPromise\n }\n\n if (match._forcePending) {\n throw router.getMatch(match.id)?._nonReactive.minPendingPromise\n }\n\n // see also hydrate() in packages/router-core/src/ssr/ssr-client.ts\n if (match.status === 'pending') {\n // We're pending, and if we have a minPendingMs, we need to wait for it\n const pendingMinMs =\n route.options.pendingMinMs ?? router.options.defaultPendingMinMs\n if (pendingMinMs) {\n const routerMatch = router.getMatch(match.id)\n if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {\n // Create a promise that will resolve after the minPendingMs\n if (!(isServer ?? router.isServer)) {\n const minPendingPromise = createControlledPromise<void>()\n\n routerMatch._nonReactive.minPendingPromise = minPendingPromise\n\n setTimeout(() => {\n minPendingPromise.resolve()\n // We've handled the minPendingPromise, so we can delete it\n routerMatch._nonReactive.minPendingPromise = undefined\n }, pendingMinMs)\n }\n }\n }\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'notFound') {\n invariant(isNotFound(match.error), 'Expected a notFound error')\n return renderRouteNotFound(router, route, match.error)\n }\n\n if (match.status === 'redirected') {\n // Redirects should be handled by the router transition. If we happen to\n // encounter a redirect here, it's a bug. Let's warn, but render nothing.\n invariant(isRedirect(match.error), 'Expected a redirect error')\n\n // warning(\n // false,\n // 'Tried to render a redirected route match! This is a weird circumstance, please file an issue!',\n // )\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'error') {\n // If we're on the server, we need to use React's new and super\n // wonky api for throwing errors from a server side render inside\n // of a suspense boundary. This is the only way to get\n // renderToPipeableStream to not hang indefinitely.\n // We'll serialize the error and rethrow it on the client.\n if (isServer ?? router.isServer) {\n const RouteErrorComponent =\n (route.options.errorComponent ??\n router.options.defaultErrorComponent) ||\n ErrorComponent\n return (\n <RouteErrorComponent\n error={match.error as any}\n reset={undefined as any}\n info={{\n componentStack: '',\n }}\n />\n )\n }\n\n throw match.error\n }\n\n return out\n})\n\n/**\n * Render the next child match in the route tree. Typically used inside\n * a route component to render nested routes.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent\n */\nexport const Outlet = React.memo(function OutletImpl() {\n const router = useRouter()\n const matchId = React.useContext(matchContext)\n const routeId = useRouterState({\n select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,\n })\n\n const route = router.routesById[routeId]!\n\n const parentGlobalNotFound = useRouterState({\n select: (s) => {\n const matches = s.matches\n const parentMatch = matches.find((d) => d.id === matchId)\n invariant(\n parentMatch,\n `Could not find parent match for matchId \"${matchId}\"`,\n )\n return parentMatch.globalNotFound\n },\n })\n\n const childMatchId = useRouterState({\n select: (s) => {\n const matches = s.matches\n const index = matches.findIndex((d) => d.id === matchId)\n return matches[index + 1]?.id\n },\n })\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n if (parentGlobalNotFound) {\n return renderRouteNotFound(router, route, undefined)\n }\n\n if (!childMatchId) {\n return null\n }\n\n const nextMatch = <Match matchId={childMatchId} />\n\n if (routeId === rootRouteId) {\n return (\n <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense>\n )\n }\n\n return nextMatch\n})\n"],"names":["React","useRouter","useRouterState","jsx","SafeFragment","CatchBoundary","CatchNotFound","matchContext","ErrorComponent","isNotFound","ClientOnly","rootRouteId","jsxs","Fragment","ScrollRestoration","getLocationChangeInfo","match","routeId","key","isServer","createControlledPromise","renderRouteNotFound","isRedirect"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BO,MAAM,QAAQA,iBAAM,KAAK,SAAS,UAAU;AAAA,EACjD;AACF,GAEG;AACD,QAAM,SAASC,UAAAA,UAAA;AACf,QAAM,aAAaC,eAAAA,eAAe;AAAA,IAChC,QAAQ,CAAC,MAAM;AACb,YAAM,QAAQ,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACpD;AAAA,QACE;AAAA,QACA,qCAAqC,OAAO;AAAA,MAAA;AAE9C,aAAO;AAAA,QACL,SAAS,MAAM;AAAA,QACf,KAAK,MAAM;AAAA,QACX,iBAAiB,MAAM;AAAA,MAAA;AAAA,IAE3B;AAAA,IACA,mBAAmB;AAAA,EAAA,CACpB;AAED,QAAM,QAAkB,OAAO,WAAW,WAAW,OAAO;AAE5D,QAAM,mBACJ,MAAM,QAAQ,oBAAoB,OAAO,QAAQ;AAEnD,QAAM,iBAAiB,mBAAmBC,2BAAAA,IAAC,kBAAA,CAAA,CAAiB,IAAK;AAEjE,QAAM,sBACJ,MAAM,QAAQ,kBAAkB,OAAO,QAAQ;AAEjD,QAAM,eAAe,MAAM,QAAQ,WAAW,OAAO,QAAQ;AAE7D,QAAM,yBAAyB,MAAM;AAAA;AAAA,IAEhC,MAAM,QAAQ,qBACf,OAAO,QA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C7B,QAAQ,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,GAAG;AAAA,EAAA,CACzD;AAED,QAAM,QAAQ,OAAO,WAAW,OAAO;AAEvC,QAAM,uBAAuBA,eAAAA,eAAe;AAAA,IAC1C,QAAQ,CAAC,MAAM;AACb,YAAM,UAAU,EAAE;AAClB,YAAM,cAAc,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACxD;AAAA,QACE;AAAA,QACA,4CAA4C,OAAO;AAAA,MAAA;AAErD,aAAO,YAAY;AAAA,IACrB;AAAA,EAAA,CACD;AAED,QAAM,eAAeA,eAAAA,eAAe;AAAA,IAClC,QAAQ,CAAC,MAAM;AACb,YAAM,UAAU,EAAE;AAClB,YAAM,QAAQ,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,OAAO;AACvD,aAAO,QAAQ,QAAQ,CAAC,GAAG;AAAA,IAC7B;AAAA,EAAA,CACD;AAED,QAAM,iBAAiB,OAAO,QAAQ,yDACnC,OAAO,QAAQ,yBAAf,CAAA,CAAuC,IACtC;AAEJ,MAAI,sBAAsB;AACxB,WAAOmB,wCAAoB,QAAQ,OAAO,MAAS;AAAA,EACrD;AAEA,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,YAAYlB,2BAAAA,IAAC,OAAA,EAAM,SAAS,aAAA,CAAc;AAEhD,MAAI,YAAYQ,WAAAA,aAAa;AAC3B,0CACGX,iBAAM,UAAN,EAAe,UAAU,gBAAiB,UAAA,WAAU;AAAA,EAEzD;AAEA,SAAO;AACT,CAAC;;;;"}
|
package/dist/cjs/Matches.cjs
CHANGED
|
@@ -33,9 +33,9 @@ function Matches() {
|
|
|
33
33
|
const rootRoute = router.routesById[routerCore.rootRouteId];
|
|
34
34
|
const PendingComponent = rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent;
|
|
35
35
|
const pendingElement = PendingComponent ? /* @__PURE__ */ jsxRuntime.jsx(PendingComponent, {}) : null;
|
|
36
|
-
const ResolvedSuspense = router.isServer || typeof document !== "undefined" && router.ssr ? SafeFragment.SafeFragment : React__namespace.Suspense;
|
|
36
|
+
const ResolvedSuspense = (routerCore.isServer ?? router.isServer) || typeof document !== "undefined" && router.ssr ? SafeFragment.SafeFragment : React__namespace.Suspense;
|
|
37
37
|
const inner = /* @__PURE__ */ jsxRuntime.jsxs(ResolvedSuspense, { fallback: pendingElement, children: [
|
|
38
|
-
!router.isServer && /* @__PURE__ */ jsxRuntime.jsx(Transitioner.Transitioner, {}),
|
|
38
|
+
!(routerCore.isServer ?? router.isServer) && /* @__PURE__ */ jsxRuntime.jsx(Transitioner.Transitioner, {}),
|
|
39
39
|
/* @__PURE__ */ jsxRuntime.jsx(MatchesInner, {})
|
|
40
40
|
] });
|
|
41
41
|
return router.options.InnerWrap ? /* @__PURE__ */ jsxRuntime.jsx(router.options.InnerWrap, { children: inner }) : inner;
|
package/dist/cjs/Matches.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Matches.cjs","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { rootRouteId } from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRoute,\n AnyRouter,\n DeepPartial,\n Expand,\n MakeOptionalPathParams,\n MakeOptionalSearchParams,\n MakeRouteMatchUnion,\n MaskOptions,\n MatchRouteOptions,\n NoInfer,\n RegisteredRouter,\n ResolveRelativePath,\n ResolveRoute,\n RouteByPath,\n RouterState,\n ToSubOptionsProps,\n} from '@tanstack/router-core'\n\ndeclare module '@tanstack/router-core' {\n export interface RouteMatchExtensions {\n meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>\n links?: Array<React.JSX.IntrinsicElements['link'] | undefined>\n scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>\n headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n }\n}\n\n/**\n * Internal component that renders the router's active match tree with\n * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.\n */\nexport function Matches() {\n const router = useRouter()\n const rootRoute: AnyRoute = router.routesById[rootRouteId]\n\n const PendingComponent =\n rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n router.isServer || (typeof document !== 'undefined' && router.ssr)\n ? SafeFragment\n : React.Suspense\n\n const inner = (\n <ResolvedSuspense fallback={pendingElement}>\n {!router.isServer && <Transitioner />}\n <MatchesInner />\n </ResolvedSuspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const router = useRouter()\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const matchComponent = matchId ? <Match matchId={matchId} /> : null\n\n return (\n <matchContext.Provider value={matchId}>\n {router.options.disableGlobalCatchBoundary ? (\n matchComponent\n ) : (\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchComponent}\n </CatchBoundary>\n )}\n </matchContext.Provider>\n )\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = ToSubOptionsProps<TRouter, TFrom, TTo> &\n DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &\n DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &\n MaskOptions<TRouter, TMaskFrom, TMaskTo> &\n MatchRouteOptions\n\n/**\n * Create a matcher function for testing locations against route definitions.\n *\n * The returned function accepts standard navigation options (`to`, `params`,\n * `search`, etc.) and returns either `false` (no match) or the matched params\n * object when the route matches the current or pending location.\n *\n * Useful for conditional rendering and active UI states.\n *\n * @returns A `matchRoute(options)` function that returns `false` or params.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook\n */\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],\n structuralSharing: true as any,\n })\n\n return React.useCallback(\n <\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => React.ReactNode)\n | React.ReactNode\n}\n\n/**\n * Component that conditionally renders its children based on whether a route\n * matches the provided `from`/`to` options. If `children` is a function, it\n * receives the matched params object.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent\n */\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any) as boolean\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport interface UseMatchesBaseOptions<\n TRouter extends AnyRouter,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n matches: Array<MakeRouteMatchUnion<TRouter>>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n}\n\nexport type UseMatchesResult<\n TRouter extends AnyRouter,\n TSelected,\n> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected\n\nexport function useMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n return useRouterState({\n select: (state: RouterState<TRouter['routeTree']>) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>)\n : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any) as UseMatchesResult<TRouter, TSelected>\n}\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @returns The array of matches (or the selected value).\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\nexport function useParentMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n\n/**\n * Read the array of active route matches that are children of the current\n * match (or selected parent) in the match tree.\n */\nexport function useChildMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n"],"names":["useRouter","rootRouteId","jsx","SafeFragment","React","jsxs","Transitioner","useRouterState","Match","matchContext","CatchBoundary","ErrorComponent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CO,SAAS,UAAU;AACxB,QAAM,SAASA,UAAAA,UAAA;AACf,QAAM,YAAsB,OAAO,WAAWC,sBAAW;AAEzD,QAAM,mBACJ,UAAU,QAAQ,oBAAoB,OAAO,QAAQ;AAEvD,QA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QAChB,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc,IAAI;AAAA,MAAA;AAEtD,aAAO,MAAM,SAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"Matches.cjs","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { isServer, rootRouteId } from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRoute,\n AnyRouter,\n DeepPartial,\n Expand,\n MakeOptionalPathParams,\n MakeOptionalSearchParams,\n MakeRouteMatchUnion,\n MaskOptions,\n MatchRouteOptions,\n NoInfer,\n RegisteredRouter,\n ResolveRelativePath,\n ResolveRoute,\n RouteByPath,\n RouterState,\n ToSubOptionsProps,\n} from '@tanstack/router-core'\n\ndeclare module '@tanstack/router-core' {\n export interface RouteMatchExtensions {\n meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>\n links?: Array<React.JSX.IntrinsicElements['link'] | undefined>\n scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>\n headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n }\n}\n\n/**\n * Internal component that renders the router's active match tree with\n * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.\n */\nexport function Matches() {\n const router = useRouter()\n const rootRoute: AnyRoute = router.routesById[rootRouteId]\n\n const PendingComponent =\n rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n (isServer ?? router.isServer) ||\n (typeof document !== 'undefined' && router.ssr)\n ? SafeFragment\n : React.Suspense\n\n const inner = (\n <ResolvedSuspense fallback={pendingElement}>\n {!(isServer ?? router.isServer) && <Transitioner />}\n <MatchesInner />\n </ResolvedSuspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const router = useRouter()\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const matchComponent = matchId ? <Match matchId={matchId} /> : null\n\n return (\n <matchContext.Provider value={matchId}>\n {router.options.disableGlobalCatchBoundary ? (\n matchComponent\n ) : (\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchComponent}\n </CatchBoundary>\n )}\n </matchContext.Provider>\n )\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = ToSubOptionsProps<TRouter, TFrom, TTo> &\n DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &\n DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &\n MaskOptions<TRouter, TMaskFrom, TMaskTo> &\n MatchRouteOptions\n\n/**\n * Create a matcher function for testing locations against route definitions.\n *\n * The returned function accepts standard navigation options (`to`, `params`,\n * `search`, etc.) and returns either `false` (no match) or the matched params\n * object when the route matches the current or pending location.\n *\n * Useful for conditional rendering and active UI states.\n *\n * @returns A `matchRoute(options)` function that returns `false` or params.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook\n */\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],\n structuralSharing: true as any,\n })\n\n return React.useCallback(\n <\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => React.ReactNode)\n | React.ReactNode\n}\n\n/**\n * Component that conditionally renders its children based on whether a route\n * matches the provided `from`/`to` options. If `children` is a function, it\n * receives the matched params object.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent\n */\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any) as boolean\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport interface UseMatchesBaseOptions<\n TRouter extends AnyRouter,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n matches: Array<MakeRouteMatchUnion<TRouter>>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n}\n\nexport type UseMatchesResult<\n TRouter extends AnyRouter,\n TSelected,\n> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected\n\nexport function useMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n return useRouterState({\n select: (state: RouterState<TRouter['routeTree']>) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>)\n : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any) as UseMatchesResult<TRouter, TSelected>\n}\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @returns The array of matches (or the selected value).\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\nexport function useParentMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n\n/**\n * Read the array of active route matches that are children of the current\n * match (or selected parent) in the match tree.\n */\nexport function useChildMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n"],"names":["useRouter","rootRouteId","jsx","isServer","SafeFragment","React","jsxs","Transitioner","useRouterState","Match","matchContext","CatchBoundary","ErrorComponent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CO,SAAS,UAAU;AACxB,QAAM,SAASA,UAAAA,UAAA;AACf,QAAM,YAAsB,OAAO,WAAWC,sBAAW;AAEzD,QAAM,mBACJ,UAAU,QAAQ,oBAAoB,OAAO,QAAQ;AAEvD,QAAM,iBAAiB,mBAAmBC,2BAAAA,IAAC,kBAAA,CAAA,CAAiB,IAAK;AAGjE,QAAM,oBACHC,uBAAY,OAAO,aACnB,OAAO,aAAa,eAAe,OAAO,MACvCC,aAAAA,eACAC,iBAAM;AAEZ,QAAM,QACJC,2BAAAA,KAAC,kBAAA,EAAiB,UAAU,gBACzB,UAAA;AAAA,IAAA,EAAEH,WAAAA,YAAY,OAAO,aAAaD,2BAAAA,IAACK,aAAAA,cAAA,EAAa;AAAA,mCAChD,cAAA,CAAA,CAAa;AAAA,EAAA,GAChB;AAGF,SAAO,OAAO,QAAQ,YACpBL,2BAAAA,IAAC,OAAO,QAAQ,WAA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Aa,cAAA;AACnB,QAAM,SAAS,WAAW,KAAY;AAEtC,MAAI,OAAO,MAAM,aAAa,YAAY;AACxC,WAAQ,MAAM,SAAiB,MAAM;AAAA,EACvC;AAEA,SAAO,SAAS,MAAM,WAAW;AACnC;AAiBO,SAAS,WAKd,MAEsC;AACtC,SAAOG,8BAAe;AAAA,IACpB,QAAQ,CAAC,UAA6C;AACpD,YAAM,UAAU,MAAM;AACtB,aAAO,MAAM,SACT,KAAK,OAAO,OAA8C,IAC1D;AAAA,IACN;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;AAkBO,SAAS,iBAKd,MAEsC;AACtC,QAAM,iBAAiBH,iBAAM,WAAWK,yBAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB;AAAA,QACA,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc;AAAA,MAAA;AAElD,aAAO,MAAM,SAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;AAMO,SAAS,gBAKd,MAEsC;AACtC,QAAM,iBAAiBL,iBAAM,WAAWK,yBAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc,IAAI;AAAA,MAAA;AAEtD,aAAO,MAAM,SAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;;;;;;;"}
|
package/dist/cjs/ScriptOnce.cjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const jsxRuntime = require("react/jsx-runtime");
|
|
4
|
+
const routerCore = require("@tanstack/router-core");
|
|
4
5
|
const useRouter = require("./useRouter.cjs");
|
|
5
6
|
function ScriptOnce({ children }) {
|
|
6
7
|
const router = useRouter.useRouter();
|
|
7
|
-
if (!router.isServer) {
|
|
8
|
+
if (!(routerCore.isServer ?? router.isServer)) {
|
|
8
9
|
return null;
|
|
9
10
|
}
|
|
10
11
|
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ScriptOnce.cjs","sources":["../../src/ScriptOnce.tsx"],"sourcesContent":["import { useRouter } from './useRouter'\n\n/**\n * Server-only helper to emit a script tag exactly once during SSR.\n */\nexport function ScriptOnce({ children }: { children: string }) {\n const router = useRouter()\n if (!router.isServer) {\n return null\n }\n\n return (\n <script\n nonce={router.options.ssr?.nonce}\n dangerouslySetInnerHTML={{\n __html: children + ';document.currentScript.remove()',\n }}\n />\n )\n}\n"],"names":["useRouter","jsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ScriptOnce.cjs","sources":["../../src/ScriptOnce.tsx"],"sourcesContent":["import { isServer } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\n\n/**\n * Server-only helper to emit a script tag exactly once during SSR.\n */\nexport function ScriptOnce({ children }: { children: string }) {\n const router = useRouter()\n if (!(isServer ?? router.isServer)) {\n return null\n }\n\n return (\n <script\n nonce={router.options.ssr?.nonce}\n dangerouslySetInnerHTML={{\n __html: children + ';document.currentScript.remove()',\n }}\n />\n )\n}\n"],"names":["useRouter","isServer","jsx"],"mappings":";;;;;AAMO,SAAS,WAAW,EAAE,YAAkC;AAC7D,QAAM,SAASA,UAAAA,UAAA;AACf,MAAI,EAAEC,WAAAA,YAAY,OAAO,WAAW;AAClC,WAAO;AAAA,EACT;AAEA,SACEC,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC,OAAO,OAAO,QAAQ,KAAK;AAAA,MAC3B,yBAAyB;AAAA,QACvB,QAAQ,WAAW;AAAA,MAAA;AAAA,IACrB;AAAA,EAAA;AAGN;;"}
|
package/dist/cjs/link.cjs
CHANGED
|
@@ -96,21 +96,18 @@ function useLinkProps(options, forwardedRef) {
|
|
|
96
96
|
() => router.buildLocation({ ..._options }),
|
|
97
97
|
[router, _options]
|
|
98
98
|
);
|
|
99
|
+
const hrefOptionPublicHref = next.maskedLocation ? next.maskedLocation.publicHref : next.publicHref;
|
|
100
|
+
const hrefOptionExternal = next.maskedLocation ? next.maskedLocation.external : next.external;
|
|
99
101
|
const hrefOption = React__namespace.useMemo(() => {
|
|
100
|
-
if (disabled)
|
|
101
|
-
|
|
102
|
+
if (disabled) return void 0;
|
|
103
|
+
if (hrefOptionExternal) {
|
|
104
|
+
return { href: hrefOptionPublicHref, external: true };
|
|
102
105
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
} else {
|
|
109
|
-
external = true;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return { href, external };
|
|
113
|
-
}, [disabled, next.maskedLocation, next.url, router.origin, router.history]);
|
|
106
|
+
return {
|
|
107
|
+
href: router.history.createHref(hrefOptionPublicHref) || "/",
|
|
108
|
+
external: false
|
|
109
|
+
};
|
|
110
|
+
}, [disabled, hrefOptionExternal, hrefOptionPublicHref, router.history]);
|
|
114
111
|
const externalLink = React__namespace.useMemo(() => {
|
|
115
112
|
if (hrefOption?.external) {
|
|
116
113
|
if (routerCore.isDangerousProtocol(hrefOption.href)) {
|
package/dist/cjs/link.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.cjs","sources":["../../src/link.tsx"],"sourcesContent":["import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n deepEqual,\n exactPathTest,\n functionalUpdate,\n isDangerousProtocol,\n preloadWarning,\n removeTrailingSlash,\n} from '@tanstack/router-core'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\n\nimport { useForwardedRef, useIntersectionObserver } from './utils'\n\nimport { useHydrated } from './ClientOnly'\nimport type {\n AnyRouter,\n Constrain,\n LinkOptions,\n RegisteredRouter,\n RoutePaths,\n} from '@tanstack/router-core'\nimport type { ReactNode } from 'react'\nimport type {\n ValidateLinkOptions,\n ValidateLinkOptionsArray,\n} from './typePrimitives'\n\n/**\n * Build anchor-like props for declarative navigation and preloading.\n *\n * Returns stable `href`, event handlers and accessibility props derived from\n * router options and active state. Used internally by `Link` and custom links.\n *\n * Options cover `to`, `params`, `search`, `hash`, `state`, `preload`,\n * `activeProps`, `inactiveProps`, and more.\n *\n * @returns React anchor props suitable for `<a>` or custom components.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook\n */\nexport function useLinkProps<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n forwardedRef?: React.ForwardedRef<Element>,\n): React.ComponentPropsWithRef<'a'> {\n const router = useRouter()\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n const hasRenderFetched = React.useRef(false)\n const innerRef = useForwardedRef(forwardedRef)\n const isHydrated = useHydrated()\n\n const {\n // custom props\n activeProps,\n inactiveProps,\n activeOptions,\n to,\n preload: userPreload,\n preloadDelay: userPreloadDelay,\n hashScrollIntoView,\n replace,\n startTransition,\n resetScroll,\n viewTransition,\n // element props\n children,\n target,\n disabled,\n style,\n className,\n onClick,\n onFocus,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n ignoreBlocker,\n // prevent these from being returned\n params: _params,\n search: _search,\n hash: _hash,\n state: _state,\n mask: _mask,\n reloadDocument: _reloadDocument,\n unsafeRelative: _unsafeRelative,\n from: _from,\n _fromLocation,\n ...propsSafeToSpread\n } = options\n\n // subscribe to search params to re-build location if it changes\n const currentSearch = useRouterState({\n select: (s) => s.location.search,\n structuralSharing: true as any,\n })\n\n const from = options.from\n\n const _options = React.useMemo(\n () => {\n return { ...options, from }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n router,\n currentSearch,\n from,\n options._fromLocation,\n options.hash,\n options.to,\n options.search,\n options.params,\n options.state,\n options.mask,\n options.unsafeRelative,\n ],\n )\n\n const next = React.useMemo(\n () => router.buildLocation({ ..._options } as any),\n [router, _options],\n )\n\n const hrefOption = React.useMemo(() => {\n if (disabled) {\n return undefined\n }\n let href = next.maskedLocation\n ? next.maskedLocation.url.href\n : next.url.href\n\n let external = false\n if (router.origin) {\n if (href.startsWith(router.origin)) {\n href = router.history.createHref(href.replace(router.origin, '')) || '/'\n } else {\n external = true\n }\n }\n return { href, external }\n }, [disabled, next.maskedLocation, next.url, router.origin, router.history])\n\n const externalLink = React.useMemo(() => {\n if (hrefOption?.external) {\n // Block dangerous protocols for external links\n if (isDangerousProtocol(hrefOption.href)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `Blocked Link with dangerous protocol: ${hrefOption.href}`,\n )\n }\n return undefined\n }\n return hrefOption.href\n }\n const isSafeInternal =\n typeof to === 'string' &&\n to.charCodeAt(0) === 47 && // '/'\n to.charCodeAt(1) !== 47 // but not '//'\n if (isSafeInternal) return undefined\n try {\n new URL(to as any)\n // Block dangerous protocols like javascript:, data:, vbscript:\n if (isDangerousProtocol(to as string)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`Blocked Link with dangerous protocol: ${to}`)\n }\n return undefined\n }\n return to\n } catch {}\n return undefined\n }, [to, hrefOption])\n\n const preload =\n options.reloadDocument || externalLink\n ? false\n : (userPreload ?? router.options.defaultPreload)\n const preloadDelay =\n userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0\n\n const isActive = useRouterState({\n select: (s) => {\n if (externalLink) return false\n if (activeOptions?.exact) {\n const testExact = exactPathTest(\n s.location.pathname,\n next.pathname,\n router.basepath,\n )\n if (!testExact) {\n return false\n }\n } else {\n const currentPathSplit = removeTrailingSlash(\n s.location.pathname,\n router.basepath,\n )\n const nextPathSplit = removeTrailingSlash(\n next.pathname,\n router.basepath,\n )\n\n const pathIsFuzzyEqual =\n currentPathSplit.startsWith(nextPathSplit) &&\n (currentPathSplit.length === nextPathSplit.length ||\n currentPathSplit[nextPathSplit.length] === '/')\n\n if (!pathIsFuzzyEqual) {\n return false\n }\n }\n\n if (activeOptions?.includeSearch ?? true) {\n const searchTest = deepEqual(s.location.search, next.search, {\n partial: !activeOptions?.exact,\n ignoreUndefined: !activeOptions?.explicitUndefined,\n })\n if (!searchTest) {\n return false\n }\n }\n\n if (activeOptions?.includeHash) {\n return isHydrated && s.location.hash === next.hash\n }\n return true\n },\n })\n\n const doPreload = React.useCallback(() => {\n router.preloadRoute({ ..._options } as any).catch((err) => {\n console.warn(err)\n console.warn(preloadWarning)\n })\n }, [router, _options])\n\n const preloadViewportIoCallback = React.useCallback(\n (entry: IntersectionObserverEntry | undefined) => {\n if (entry?.isIntersecting) {\n doPreload()\n }\n },\n [doPreload],\n )\n\n useIntersectionObserver(\n innerRef,\n preloadViewportIoCallback,\n intersectionObserverOptions,\n { disabled: !!disabled || !(preload === 'viewport') },\n )\n\n React.useEffect(() => {\n if (hasRenderFetched.current) {\n return\n }\n if (!disabled && preload === 'render') {\n doPreload()\n hasRenderFetched.current = true\n }\n }, [disabled, doPreload, preload])\n\n // The click handler\n const handleClick = (e: React.MouseEvent) => {\n // Check actual element's target attribute as fallback\n const elementTarget = (\n e.currentTarget as HTMLAnchorElement | SVGAElement\n ).getAttribute('target')\n const effectiveTarget = target !== undefined ? target : elementTarget\n\n if (\n !disabled &&\n !isCtrlEvent(e) &&\n !e.defaultPrevented &&\n (!effectiveTarget || effectiveTarget === '_self') &&\n e.button === 0\n ) {\n e.preventDefault()\n\n flushSync(() => {\n setIsTransitioning(true)\n })\n\n const unsub = router.subscribe('onResolved', () => {\n unsub()\n setIsTransitioning(false)\n })\n\n // All is well? Navigate!\n // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing\n router.navigate({\n ..._options,\n replace,\n resetScroll,\n hashScrollIntoView,\n startTransition,\n viewTransition,\n ignoreBlocker,\n })\n }\n }\n\n if (externalLink) {\n return {\n ...propsSafeToSpread,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n href: externalLink,\n ...(children && { children }),\n ...(target && { target }),\n ...(disabled && { disabled }),\n ...(style && { style }),\n ...(className && { className }),\n ...(onClick && { onClick }),\n ...(onFocus && { onFocus }),\n ...(onMouseEnter && { onMouseEnter }),\n ...(onMouseLeave && { onMouseLeave }),\n ...(onTouchStart && { onTouchStart }),\n }\n }\n\n // The click handler\n const handleFocus = (_: React.MouseEvent) => {\n if (disabled) return\n if (preload) {\n doPreload()\n }\n }\n\n const handleTouchStart = handleFocus\n\n const handleEnter = (e: React.MouseEvent) => {\n if (disabled || !preload) return\n\n if (!preloadDelay) {\n doPreload()\n } else {\n const eventTarget = e.target\n if (timeoutMap.has(eventTarget)) {\n return\n }\n const id = setTimeout(() => {\n timeoutMap.delete(eventTarget)\n doPreload()\n }, preloadDelay)\n timeoutMap.set(eventTarget, id)\n }\n }\n\n const handleLeave = (e: React.MouseEvent) => {\n if (disabled || !preload || !preloadDelay) return\n const eventTarget = e.target\n const id = timeoutMap.get(eventTarget)\n if (id) {\n clearTimeout(id)\n timeoutMap.delete(eventTarget)\n }\n }\n\n // Get the active props\n const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive\n ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT)\n : STATIC_EMPTY_OBJECT\n\n // Get the inactive props\n const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =\n isActive\n ? STATIC_EMPTY_OBJECT\n : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT)\n\n const resolvedClassName = [\n className,\n resolvedActiveProps.className,\n resolvedInactiveProps.className,\n ]\n .filter(Boolean)\n .join(' ')\n\n const resolvedStyle = (style ||\n resolvedActiveProps.style ||\n resolvedInactiveProps.style) && {\n ...style,\n ...resolvedActiveProps.style,\n ...resolvedInactiveProps.style,\n }\n\n return {\n ...propsSafeToSpread,\n ...resolvedActiveProps,\n ...resolvedInactiveProps,\n href: hrefOption?.href,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n onClick: composeHandlers([onClick, handleClick]),\n onFocus: composeHandlers([onFocus, handleFocus]),\n onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),\n onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),\n onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),\n disabled: !!disabled,\n target,\n ...(resolvedStyle && { style: resolvedStyle }),\n ...(resolvedClassName && { className: resolvedClassName }),\n ...(disabled && STATIC_DISABLED_PROPS),\n ...(isActive && STATIC_ACTIVE_PROPS),\n ...(isTransitioning && STATIC_TRANSITIONING_PROPS),\n }\n}\n\nconst STATIC_EMPTY_OBJECT = {}\nconst STATIC_ACTIVE_OBJECT = { className: 'active' }\nconst STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true }\nconst STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' }\nconst STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' }\n\nconst timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>()\n\nconst intersectionObserverOptions: IntersectionObserverInit = {\n rootMargin: '100px',\n}\n\nconst composeHandlers =\n (handlers: Array<undefined | React.EventHandler<any>>) =>\n (e: React.SyntheticEvent) => {\n for (const handler of handlers) {\n if (!handler) continue\n if (e.defaultPrevented) return\n handler(e)\n }\n }\n\ntype UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements\n ? React.JSX.IntrinsicElements[TComp]\n : TComp extends React.ComponentType<any>\n ? React.ComponentPropsWithoutRef<TComp> &\n React.RefAttributes<React.ComponentRef<TComp>>\n : never\n\nexport type UseLinkPropsOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n UseLinkReactProps<'a'>\n\nexport type ActiveLinkOptions<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n ActiveLinkOptionProps<TComp>\n\ntype ActiveLinkProps<TComp> = Partial<\n LinkComponentReactProps<TComp> & {\n [key: `data-${string}`]: unknown\n }\n>\n\nexport interface ActiveLinkOptionProps<TComp = 'a'> {\n /**\n * A function that returns additional props for the `active` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n /**\n * A function that returns additional props for the `inactive` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n}\n\nexport type LinkProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n LinkPropsChildren\n\nexport interface LinkPropsChildren {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | React.ReactNode\n | ((state: {\n isActive: boolean\n isTransitioning: boolean\n }) => React.ReactNode)\n}\n\ntype LinkComponentReactProps<TComp> = Omit<\n UseLinkReactProps<TComp>,\n keyof CreateLinkProps\n>\n\nexport type LinkComponentProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkComponentReactProps<TComp> &\n LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type CreateLinkProps = LinkProps<\n any,\n any,\n string,\n string,\n string,\n string\n>\n\nexport type LinkComponent<\n in out TComp,\n in out TDefaultFrom extends string = string,\n> = <\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = TDefaultFrom,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n) => React.ReactElement\n\nexport interface LinkComponentRoute<\n in out TDefaultFrom extends string = string,\n> {\n defaultFrom: TDefaultFrom;\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n props: LinkComponentProps<\n 'a',\n TRouter,\n this['defaultFrom'],\n TTo,\n this['defaultFrom'],\n TMaskTo\n >,\n ): React.ReactElement\n}\n\n/**\n * Creates a typed Link-like component that preserves TanStack Router's\n * navigation semantics and type-safety while delegating rendering to the\n * provided host component.\n *\n * Useful for integrating design system anchors/buttons while keeping\n * router-aware props (eg. `to`, `params`, `search`, `preload`).\n *\n * @param Comp The host component to render (eg. a design-system Link/Button)\n * @returns A router-aware component with the same API as `Link`.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link\n */\nexport function createLink<const TComp>(\n Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,\n): LinkComponent<TComp> {\n return React.forwardRef(function CreatedLink(props, ref) {\n return <Link {...(props as any)} _asChild={Comp} ref={ref} />\n }) as any\n}\n\n/**\n * A strongly-typed anchor component for declarative navigation.\n * Handles path, search, hash and state updates with optional route preloading\n * and active-state styling.\n *\n * Props:\n * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)\n * - `preloadDelay`: Delay in ms before preloading on hover\n * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive\n * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation\n * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation\n * - `ignoreBlocker`: Bypass registered blockers\n *\n * @returns An anchor-like element that navigates without full page reloads.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent\n */\nexport const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(\n (props, ref) => {\n const { _asChild, ...rest } = props\n const { type: _type, ...linkProps } = useLinkProps(rest as any, ref)\n\n const children =\n typeof rest.children === 'function'\n ? rest.children({\n isActive: (linkProps as any)['data-status'] === 'active',\n })\n : rest.children\n\n if (!_asChild) {\n // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop\n // @ts-expect-error\n const { disabled: _, ...rest } = linkProps\n return React.createElement('a', rest, children)\n }\n return React.createElement(_asChild, linkProps, children)\n },\n) as any\n\nfunction isCtrlEvent(e: React.MouseEvent) {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)\n}\n\nexport type LinkOptionsFnOptions<\n TOptions,\n TComp,\n TRouter extends AnyRouter = RegisteredRouter,\n> =\n TOptions extends ReadonlyArray<any>\n ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>\n : ValidateLinkOptions<TRouter, TOptions, string, TComp>\n\nexport type LinkOptionsFn<TComp> = <\n const TOptions,\n TRouter extends AnyRouter = RegisteredRouter,\n>(\n options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,\n) => TOptions\n\n/**\n * Validate and reuse navigation options for `Link`, `navigate` or `redirect`.\n * Accepts a literal options object and returns it typed for later spreading.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\nexport const linkOptions: LinkOptionsFn<'a'> = (options) => {\n return options as any\n}\n\n/**\n * Type-check a literal object for use with `Link`, `navigate` or `redirect`.\n * Use to validate and reuse navigation options across your app.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\n"],"names":["useRouter","React","useForwardedRef","useHydrated","useRouterState","isDangerousProtocol","exactPathTest","removeTrailingSlash","deepEqual","preloadWarning","useIntersectionObserver","flushSync","functionalUpdate","rest"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,SAAS,aAOd,SACA,cACkC;AAClC,QAAM,SAASA,UAAAA,UAAA;AACf,QAAM,CAAC,iBAAiB,kBAAkB,IAAIC,iBAAM,SAAS,KAAK;AAClE,QAAM,mBAAmBA,iBAAM,OAAO,KAAK;AAC3C,QAAM,WAAWC,MAAAA,gBAAgB,YAAY;AAC7C,QAAM,aAAaC,WAAAA,YAAA;AAEnB,QAAM;AAAA;AAAA,IAEJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,IACN,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,MAAM;AAAA,IACN;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAGJ,QAAM,gBAAgBC,eAAAA,eAAe;AAAA,IACnC,QAAQ,CAAC,MAAM,EAAE,SAAS;AAAA,IAC1B,mBAAmB;AAAA,EAAA,CACpB;AAED,QAAM,OAAO,QAAQ;AAErB,QAAM,WAAWH,iBAAM;AAAA,IACrB,MAAM;AACJ,aAAO,EAAE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AsB,gBAAA;AAE3D,MAAM,iCAAiB,QAAA;AAEvB,MAAM,8BAAwD;AAAA,EAC5D,YAAY;AACd;AAEA,MAAM,kBACJ,CAAC,aACD,CAAC,MAA4B;AAC3B,aAAW,WAAW,UAAU;AAC9B,QAAI,CAAC,QAAS;AACd,QAAI,EAAE,iBAAkB;AACxB,YAAQ,CAAC;AAAA,EACX;AACF;AAwIK,SAAS,WACd,MACsB;AACtB,SAAOX,iBAAM,WAAW,SAAS,YAAY,OAAO,KAAK;AACvD,0CAAQ,MAAA,EAAM,GAAI,OAAe,UAAU,MAAM,KAAU;AAAA,EAC7D,CAAC;AACH;AAkBO,MAAM,OAA2BA,iBAAM;AAAA,EAC5C,CAAC,OAAO,QAAQ;AACd,UAAM,EAAE,UAAU,GAAG,KAAA,IAAS;AAC9B,UAAM,EAAE,MAAM,OAAO,GAAG,cAAc,aAAa,MAAa,GAAG;AAEnE,UAAM,WACJ,OAAO,KAAK,aAAa,aACrB,KAAK,SAAS;AAAA,MACZ,UAAW,UAAkB,aAAa,MAAM;AAAA,IAAA,CACjD,IACD,KAAK;AAEX,QAAI,CAAC,UAAU;AAGb,YAAM,EAAE,UAAU,GAAG,GAAGY,UAAS;AACjC,aAAOZ,iBAAM,cAAc,KAAKY,OAAM,QAAQ;AAAA,IAChD;AACA,WAAOZ,iBAAM,cAAc,UAAU,WAAW,QAAQ;AAAA,EAC1D;AACF;AAEA,SAAS,YAAY,GAAqB;AACxC,SAAO,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE;AACpD;AAyBO,MAAM,cAAkC,CAAC,YAAY;AAC1D,SAAO;AACT;;;;;"}
|
|
1
|
+
{"version":3,"file":"link.cjs","sources":["../../src/link.tsx"],"sourcesContent":["import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n deepEqual,\n exactPathTest,\n functionalUpdate,\n isDangerousProtocol,\n preloadWarning,\n removeTrailingSlash,\n} from '@tanstack/router-core'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\n\nimport { useForwardedRef, useIntersectionObserver } from './utils'\n\nimport { useHydrated } from './ClientOnly'\nimport type {\n AnyRouter,\n Constrain,\n LinkOptions,\n RegisteredRouter,\n RoutePaths,\n} from '@tanstack/router-core'\nimport type { ReactNode } from 'react'\nimport type {\n ValidateLinkOptions,\n ValidateLinkOptionsArray,\n} from './typePrimitives'\n\n/**\n * Build anchor-like props for declarative navigation and preloading.\n *\n * Returns stable `href`, event handlers and accessibility props derived from\n * router options and active state. Used internally by `Link` and custom links.\n *\n * Options cover `to`, `params`, `search`, `hash`, `state`, `preload`,\n * `activeProps`, `inactiveProps`, and more.\n *\n * @returns React anchor props suitable for `<a>` or custom components.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook\n */\nexport function useLinkProps<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n forwardedRef?: React.ForwardedRef<Element>,\n): React.ComponentPropsWithRef<'a'> {\n const router = useRouter()\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n const hasRenderFetched = React.useRef(false)\n const innerRef = useForwardedRef(forwardedRef)\n const isHydrated = useHydrated()\n\n const {\n // custom props\n activeProps,\n inactiveProps,\n activeOptions,\n to,\n preload: userPreload,\n preloadDelay: userPreloadDelay,\n hashScrollIntoView,\n replace,\n startTransition,\n resetScroll,\n viewTransition,\n // element props\n children,\n target,\n disabled,\n style,\n className,\n onClick,\n onFocus,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n ignoreBlocker,\n // prevent these from being returned\n params: _params,\n search: _search,\n hash: _hash,\n state: _state,\n mask: _mask,\n reloadDocument: _reloadDocument,\n unsafeRelative: _unsafeRelative,\n from: _from,\n _fromLocation,\n ...propsSafeToSpread\n } = options\n\n // subscribe to search params to re-build location if it changes\n const currentSearch = useRouterState({\n select: (s) => s.location.search,\n structuralSharing: true as any,\n })\n\n const from = options.from\n\n const _options = React.useMemo(\n () => {\n return { ...options, from }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n router,\n currentSearch,\n from,\n options._fromLocation,\n options.hash,\n options.to,\n options.search,\n options.params,\n options.state,\n options.mask,\n options.unsafeRelative,\n ],\n )\n\n const next = React.useMemo(\n () => router.buildLocation({ ..._options } as any),\n [router, _options],\n )\n\n // Use publicHref - it contains the correct href for display\n // When a rewrite changes the origin, publicHref is the full URL\n // Otherwise it's the origin-stripped path\n // This avoids constructing URL objects in the hot path\n const hrefOptionPublicHref = next.maskedLocation\n ? next.maskedLocation.publicHref\n : next.publicHref\n const hrefOptionExternal = next.maskedLocation\n ? next.maskedLocation.external\n : next.external\n const hrefOption = React.useMemo(() => {\n if (disabled) return undefined\n\n // Full URL means rewrite changed the origin - treat as external-like\n if (hrefOptionExternal) {\n return { href: hrefOptionPublicHref, external: true }\n }\n\n return {\n href: router.history.createHref(hrefOptionPublicHref) || '/',\n external: false,\n }\n }, [disabled, hrefOptionExternal, hrefOptionPublicHref, router.history])\n\n const externalLink = React.useMemo(() => {\n if (hrefOption?.external) {\n // Block dangerous protocols for external links\n if (isDangerousProtocol(hrefOption.href)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `Blocked Link with dangerous protocol: ${hrefOption.href}`,\n )\n }\n return undefined\n }\n return hrefOption.href\n }\n const isSafeInternal =\n typeof to === 'string' &&\n to.charCodeAt(0) === 47 && // '/'\n to.charCodeAt(1) !== 47 // but not '//'\n if (isSafeInternal) return undefined\n try {\n new URL(to as any)\n // Block dangerous protocols like javascript:, data:, vbscript:\n if (isDangerousProtocol(to as string)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`Blocked Link with dangerous protocol: ${to}`)\n }\n return undefined\n }\n return to\n } catch {}\n return undefined\n }, [to, hrefOption])\n\n const preload =\n options.reloadDocument || externalLink\n ? false\n : (userPreload ?? router.options.defaultPreload)\n const preloadDelay =\n userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0\n\n const isActive = useRouterState({\n select: (s) => {\n if (externalLink) return false\n if (activeOptions?.exact) {\n const testExact = exactPathTest(\n s.location.pathname,\n next.pathname,\n router.basepath,\n )\n if (!testExact) {\n return false\n }\n } else {\n const currentPathSplit = removeTrailingSlash(\n s.location.pathname,\n router.basepath,\n )\n const nextPathSplit = removeTrailingSlash(\n next.pathname,\n router.basepath,\n )\n\n const pathIsFuzzyEqual =\n currentPathSplit.startsWith(nextPathSplit) &&\n (currentPathSplit.length === nextPathSplit.length ||\n currentPathSplit[nextPathSplit.length] === '/')\n\n if (!pathIsFuzzyEqual) {\n return false\n }\n }\n\n if (activeOptions?.includeSearch ?? true) {\n const searchTest = deepEqual(s.location.search, next.search, {\n partial: !activeOptions?.exact,\n ignoreUndefined: !activeOptions?.explicitUndefined,\n })\n if (!searchTest) {\n return false\n }\n }\n\n if (activeOptions?.includeHash) {\n return isHydrated && s.location.hash === next.hash\n }\n return true\n },\n })\n\n const doPreload = React.useCallback(() => {\n router.preloadRoute({ ..._options } as any).catch((err) => {\n console.warn(err)\n console.warn(preloadWarning)\n })\n }, [router, _options])\n\n const preloadViewportIoCallback = React.useCallback(\n (entry: IntersectionObserverEntry | undefined) => {\n if (entry?.isIntersecting) {\n doPreload()\n }\n },\n [doPreload],\n )\n\n useIntersectionObserver(\n innerRef,\n preloadViewportIoCallback,\n intersectionObserverOptions,\n { disabled: !!disabled || !(preload === 'viewport') },\n )\n\n React.useEffect(() => {\n if (hasRenderFetched.current) {\n return\n }\n if (!disabled && preload === 'render') {\n doPreload()\n hasRenderFetched.current = true\n }\n }, [disabled, doPreload, preload])\n\n // The click handler\n const handleClick = (e: React.MouseEvent) => {\n // Check actual element's target attribute as fallback\n const elementTarget = (\n e.currentTarget as HTMLAnchorElement | SVGAElement\n ).getAttribute('target')\n const effectiveTarget = target !== undefined ? target : elementTarget\n\n if (\n !disabled &&\n !isCtrlEvent(e) &&\n !e.defaultPrevented &&\n (!effectiveTarget || effectiveTarget === '_self') &&\n e.button === 0\n ) {\n e.preventDefault()\n\n flushSync(() => {\n setIsTransitioning(true)\n })\n\n const unsub = router.subscribe('onResolved', () => {\n unsub()\n setIsTransitioning(false)\n })\n\n // All is well? Navigate!\n // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing\n router.navigate({\n ..._options,\n replace,\n resetScroll,\n hashScrollIntoView,\n startTransition,\n viewTransition,\n ignoreBlocker,\n })\n }\n }\n\n if (externalLink) {\n return {\n ...propsSafeToSpread,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n href: externalLink,\n ...(children && { children }),\n ...(target && { target }),\n ...(disabled && { disabled }),\n ...(style && { style }),\n ...(className && { className }),\n ...(onClick && { onClick }),\n ...(onFocus && { onFocus }),\n ...(onMouseEnter && { onMouseEnter }),\n ...(onMouseLeave && { onMouseLeave }),\n ...(onTouchStart && { onTouchStart }),\n }\n }\n\n // The click handler\n const handleFocus = (_: React.MouseEvent) => {\n if (disabled) return\n if (preload) {\n doPreload()\n }\n }\n\n const handleTouchStart = handleFocus\n\n const handleEnter = (e: React.MouseEvent) => {\n if (disabled || !preload) return\n\n if (!preloadDelay) {\n doPreload()\n } else {\n const eventTarget = e.target\n if (timeoutMap.has(eventTarget)) {\n return\n }\n const id = setTimeout(() => {\n timeoutMap.delete(eventTarget)\n doPreload()\n }, preloadDelay)\n timeoutMap.set(eventTarget, id)\n }\n }\n\n const handleLeave = (e: React.MouseEvent) => {\n if (disabled || !preload || !preloadDelay) return\n const eventTarget = e.target\n const id = timeoutMap.get(eventTarget)\n if (id) {\n clearTimeout(id)\n timeoutMap.delete(eventTarget)\n }\n }\n\n // Get the active props\n const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive\n ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT)\n : STATIC_EMPTY_OBJECT\n\n // Get the inactive props\n const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =\n isActive\n ? STATIC_EMPTY_OBJECT\n : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT)\n\n const resolvedClassName = [\n className,\n resolvedActiveProps.className,\n resolvedInactiveProps.className,\n ]\n .filter(Boolean)\n .join(' ')\n\n const resolvedStyle = (style ||\n resolvedActiveProps.style ||\n resolvedInactiveProps.style) && {\n ...style,\n ...resolvedActiveProps.style,\n ...resolvedInactiveProps.style,\n }\n\n return {\n ...propsSafeToSpread,\n ...resolvedActiveProps,\n ...resolvedInactiveProps,\n href: hrefOption?.href,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n onClick: composeHandlers([onClick, handleClick]),\n onFocus: composeHandlers([onFocus, handleFocus]),\n onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),\n onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),\n onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),\n disabled: !!disabled,\n target,\n ...(resolvedStyle && { style: resolvedStyle }),\n ...(resolvedClassName && { className: resolvedClassName }),\n ...(disabled && STATIC_DISABLED_PROPS),\n ...(isActive && STATIC_ACTIVE_PROPS),\n ...(isTransitioning && STATIC_TRANSITIONING_PROPS),\n }\n}\n\nconst STATIC_EMPTY_OBJECT = {}\nconst STATIC_ACTIVE_OBJECT = { className: 'active' }\nconst STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true }\nconst STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' }\nconst STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' }\n\nconst timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>()\n\nconst intersectionObserverOptions: IntersectionObserverInit = {\n rootMargin: '100px',\n}\n\nconst composeHandlers =\n (handlers: Array<undefined | React.EventHandler<any>>) =>\n (e: React.SyntheticEvent) => {\n for (const handler of handlers) {\n if (!handler) continue\n if (e.defaultPrevented) return\n handler(e)\n }\n }\n\ntype UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements\n ? React.JSX.IntrinsicElements[TComp]\n : TComp extends React.ComponentType<any>\n ? React.ComponentPropsWithoutRef<TComp> &\n React.RefAttributes<React.ComponentRef<TComp>>\n : never\n\nexport type UseLinkPropsOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n UseLinkReactProps<'a'>\n\nexport type ActiveLinkOptions<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n ActiveLinkOptionProps<TComp>\n\ntype ActiveLinkProps<TComp> = Partial<\n LinkComponentReactProps<TComp> & {\n [key: `data-${string}`]: unknown\n }\n>\n\nexport interface ActiveLinkOptionProps<TComp = 'a'> {\n /**\n * A function that returns additional props for the `active` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n /**\n * A function that returns additional props for the `inactive` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n}\n\nexport type LinkProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n LinkPropsChildren\n\nexport interface LinkPropsChildren {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | React.ReactNode\n | ((state: {\n isActive: boolean\n isTransitioning: boolean\n }) => React.ReactNode)\n}\n\ntype LinkComponentReactProps<TComp> = Omit<\n UseLinkReactProps<TComp>,\n keyof CreateLinkProps\n>\n\nexport type LinkComponentProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkComponentReactProps<TComp> &\n LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type CreateLinkProps = LinkProps<\n any,\n any,\n string,\n string,\n string,\n string\n>\n\nexport type LinkComponent<\n in out TComp,\n in out TDefaultFrom extends string = string,\n> = <\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = TDefaultFrom,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n) => React.ReactElement\n\nexport interface LinkComponentRoute<\n in out TDefaultFrom extends string = string,\n> {\n defaultFrom: TDefaultFrom;\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n props: LinkComponentProps<\n 'a',\n TRouter,\n this['defaultFrom'],\n TTo,\n this['defaultFrom'],\n TMaskTo\n >,\n ): React.ReactElement\n}\n\n/**\n * Creates a typed Link-like component that preserves TanStack Router's\n * navigation semantics and type-safety while delegating rendering to the\n * provided host component.\n *\n * Useful for integrating design system anchors/buttons while keeping\n * router-aware props (eg. `to`, `params`, `search`, `preload`).\n *\n * @param Comp The host component to render (eg. a design-system Link/Button)\n * @returns A router-aware component with the same API as `Link`.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link\n */\nexport function createLink<const TComp>(\n Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,\n): LinkComponent<TComp> {\n return React.forwardRef(function CreatedLink(props, ref) {\n return <Link {...(props as any)} _asChild={Comp} ref={ref} />\n }) as any\n}\n\n/**\n * A strongly-typed anchor component for declarative navigation.\n * Handles path, search, hash and state updates with optional route preloading\n * and active-state styling.\n *\n * Props:\n * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)\n * - `preloadDelay`: Delay in ms before preloading on hover\n * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive\n * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation\n * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation\n * - `ignoreBlocker`: Bypass registered blockers\n *\n * @returns An anchor-like element that navigates without full page reloads.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent\n */\nexport const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(\n (props, ref) => {\n const { _asChild, ...rest } = props\n const { type: _type, ...linkProps } = useLinkProps(rest as any, ref)\n\n const children =\n typeof rest.children === 'function'\n ? rest.children({\n isActive: (linkProps as any)['data-status'] === 'active',\n })\n : rest.children\n\n if (!_asChild) {\n // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop\n // @ts-expect-error\n const { disabled: _, ...rest } = linkProps\n return React.createElement('a', rest, children)\n }\n return React.createElement(_asChild, linkProps, children)\n },\n) as any\n\nfunction isCtrlEvent(e: React.MouseEvent) {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)\n}\n\nexport type LinkOptionsFnOptions<\n TOptions,\n TComp,\n TRouter extends AnyRouter = RegisteredRouter,\n> =\n TOptions extends ReadonlyArray<any>\n ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>\n : ValidateLinkOptions<TRouter, TOptions, string, TComp>\n\nexport type LinkOptionsFn<TComp> = <\n const TOptions,\n TRouter extends AnyRouter = RegisteredRouter,\n>(\n options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,\n) => TOptions\n\n/**\n * Validate and reuse navigation options for `Link`, `navigate` or `redirect`.\n * Accepts a literal options object and returns it typed for later spreading.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\nexport const linkOptions: LinkOptionsFn<'a'> = (options) => {\n return options as any\n}\n\n/**\n * Type-check a literal object for use with `Link`, `navigate` or `redirect`.\n * Use to validate and reuse navigation options across your app.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\n"],"names":["useRouter","React","useForwardedRef","useHydrated","useRouterState","isDangerousProtocol","exactPathTest","removeTrailingSlash","deepEqual","preloadWarning","useIntersectionObserver","flushSync","functionalUpdate","rest"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCO,SAAS,aAOd,SACA,cACkC;AAClC,QAAM,SAASA,UAAAA,UAAA;AACf,QAAM,CAAC,iBAAiB,kBAAkB,IAAIC,iBAAM,SAAS,KAAK;AAClE,QAAM,mBAAmBA,iBAAM,OAAO,KAAK;AAC3C,QAAM,WAAWC,MAAAA,gBAAgB,YAAY;AAC7C,QAAM,aAAaC,WAAAA,YAAA;AAEnB,QAAM;AAAA;AAAA,IAEJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,IACN,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,MAAM;AAAA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@@ const useRouter = require("./useRouter.cjs");
|
|
|
6
6
|
const ScriptOnce = require("./ScriptOnce.cjs");
|
|
7
7
|
function ScrollRestoration() {
|
|
8
8
|
const router = useRouter.useRouter();
|
|
9
|
-
if (!router.isScrollRestoring || !router.isServer) {
|
|
9
|
+
if (!router.isScrollRestoring || !(routerCore.isServer ?? router.isServer)) {
|
|
10
10
|
return null;
|
|
11
11
|
}
|
|
12
12
|
if (typeof router.options.scrollRestoration === "function") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import {\n defaultGetScrollRestorationKey,\n escapeHtml,\n restoreScroll,\n storageKey,\n} from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\n\nexport function ScrollRestoration() {\n const router = useRouter()\n if (!router.isScrollRestoring || !router.isServer) {\n return null\n }\n if (typeof router.options.scrollRestoration === 'function') {\n const shouldRestore = router.options.scrollRestoration({\n location: router.latestLocation,\n })\n if (!shouldRestore) {\n return null\n }\n }\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n const userKey = getKey(router.latestLocation)\n const resolvedKey =\n userKey !== defaultGetScrollRestorationKey(router.latestLocation)\n ? userKey\n : undefined\n\n const restoreScrollOptions: Parameters<typeof restoreScroll>[0] = {\n storageKey,\n shouldScrollRestoration: true,\n }\n if (resolvedKey) {\n restoreScrollOptions.key = resolvedKey\n }\n\n return (\n <ScriptOnce\n children={`(${restoreScroll.toString()})(${escapeHtml(JSON.stringify(restoreScrollOptions))})`}\n />\n )\n}\n"],"names":["useRouter","defaultGetScrollRestorationKey","storageKey","jsx","ScriptOnce","restoreScroll","escapeHtml"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import {\n defaultGetScrollRestorationKey,\n escapeHtml,\n isServer,\n restoreScroll,\n storageKey,\n} from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\n\nexport function ScrollRestoration() {\n const router = useRouter()\n if (!router.isScrollRestoring || !(isServer ?? router.isServer)) {\n return null\n }\n if (typeof router.options.scrollRestoration === 'function') {\n const shouldRestore = router.options.scrollRestoration({\n location: router.latestLocation,\n })\n if (!shouldRestore) {\n return null\n }\n }\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n const userKey = getKey(router.latestLocation)\n const resolvedKey =\n userKey !== defaultGetScrollRestorationKey(router.latestLocation)\n ? userKey\n : undefined\n\n const restoreScrollOptions: Parameters<typeof restoreScroll>[0] = {\n storageKey,\n shouldScrollRestoration: true,\n }\n if (resolvedKey) {\n restoreScrollOptions.key = resolvedKey\n }\n\n return (\n <ScriptOnce\n children={`(${restoreScroll.toString()})(${escapeHtml(JSON.stringify(restoreScrollOptions))})`}\n />\n )\n}\n"],"names":["useRouter","isServer","defaultGetScrollRestorationKey","storageKey","jsx","ScriptOnce","restoreScroll","escapeHtml"],"mappings":";;;;;;AAUO,SAAS,oBAAoB;AAClC,QAAM,SAASA,UAAAA,UAAA;AACf,MAAI,CAAC,OAAO,qBAAqB,EAAEC,WAAAA,YAAY,OAAO,WAAW;AAC/D,WAAO;AAAA,EACT;AACA,MAAI,OAAO,OAAO,QAAQ,sBAAsB,YAAY;AAC1D,UAAM,gBAAgB,OAAO,QAAQ,kBAAkB;AAAA,MACrD,UAAU,OAAO;AAAA,IAAA,CAClB;AACD,QAAI,CAAC,eAAe;AAClB,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,SACJ,OAAO,QAAQ,2BAA2BC,WAAAA;AAC5C,QAAM,UAAU,OAAO,OAAO,cAAc;AAC5C,QAAM,cACJ,YAAYA,WAAAA,+BAA+B,OAAO,cAAc,IAC5D,UACA;AAEN,QAAM,uBAA4D;AAAA,IAAA,YAChEC,WAAAA;AAAAA,IACA,yBAAyB;AAAA,EAAA;AAE3B,MAAI,aAAa;AACf,yBAAqB,MAAM;AAAA,EAC7B;AAEA,SACEC,2BAAAA;AAAAA,IAACC,WAAAA;AAAAA,IAAA;AAAA,MACC,UAAU,IAAIC,WAAAA,cAAc,SAAA,CAAU,KAAKC,WAAAA,WAAW,KAAK,UAAU,oBAAoB,CAAC,CAAC;AAAA,IAAA;AAAA,EAAA;AAGjG;;"}
|
package/dist/esm/Asset.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { jsx } from "react/jsx-runtime";
|
|
2
2
|
import * as React from "react";
|
|
3
|
+
import { isServer } from "@tanstack/router-core";
|
|
3
4
|
import { useRouter } from "./useRouter.js";
|
|
4
5
|
function Asset({
|
|
5
6
|
tag,
|
|
@@ -101,7 +102,7 @@ function Script({
|
|
|
101
102
|
}
|
|
102
103
|
return void 0;
|
|
103
104
|
}, [attrs, children]);
|
|
104
|
-
if (!router.isServer) {
|
|
105
|
+
if (!(isServer ?? router.isServer)) {
|
|
105
106
|
const { src, ...rest } = attrs || {};
|
|
106
107
|
return /* @__PURE__ */ jsx(
|
|
107
108
|
"script",
|
package/dist/esm/Asset.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Asset.js","sources":["../../src/Asset.tsx"],"sourcesContent":["import * as React from 'react'\nimport { useRouter } from './useRouter'\nimport type { RouterManagedTag } from '@tanstack/router-core'\n\ninterface ScriptAttrs {\n [key: string]: string | boolean | undefined\n src?: string\n suppressHydrationWarning?: boolean\n}\n\nexport function Asset({\n tag,\n attrs,\n children,\n nonce,\n}: RouterManagedTag & { nonce?: string }): React.ReactElement | null {\n switch (tag) {\n case 'title':\n return (\n <title {...attrs} suppressHydrationWarning>\n {children}\n </title>\n )\n case 'meta':\n return <meta {...attrs} suppressHydrationWarning />\n case 'link':\n return <link {...attrs} nonce={nonce} suppressHydrationWarning />\n case 'style':\n return (\n <style\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children as string }}\n nonce={nonce}\n />\n )\n case 'script':\n return <Script attrs={attrs}>{children}</Script>\n default:\n return null\n }\n}\n\nfunction Script({\n attrs,\n children,\n}: {\n attrs?: ScriptAttrs\n children?: string\n}) {\n const router = useRouter()\n\n React.useEffect(() => {\n if (attrs?.src) {\n const normSrc = (() => {\n try {\n const base = document.baseURI || window.location.href\n return new URL(attrs.src, base).href\n } catch {\n return attrs.src\n }\n })()\n const existingScript = Array.from(\n document.querySelectorAll('script[src]'),\n ).find((el) => (el as HTMLScriptElement).src === normSrc)\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n if (typeof children === 'string') {\n const typeAttr =\n typeof attrs?.type === 'string' ? attrs.type : 'text/javascript'\n const nonceAttr =\n typeof attrs?.nonce === 'string' ? attrs.nonce : undefined\n const existingScript = Array.from(\n document.querySelectorAll('script:not([src])'),\n ).find((el) => {\n if (!(el instanceof HTMLScriptElement)) return false\n const sType = el.getAttribute('type') ?? 'text/javascript'\n const sNonce = el.getAttribute('nonce') ?? undefined\n return (\n el.textContent === children &&\n sType === typeAttr &&\n sNonce === nonceAttr\n )\n })\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n script.textContent = children\n\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n return undefined\n }, [attrs, children])\n\n if (!router.isServer) {\n const { src, ...rest } = attrs || {}\n // render an empty script on the client just to avoid hydration errors\n return (\n <script\n suppressHydrationWarning\n dangerouslySetInnerHTML={{ __html: '' }}\n {...rest}\n ></script>\n )\n }\n\n if (attrs?.src && typeof attrs.src === 'string') {\n return <script {...attrs} suppressHydrationWarning />\n }\n\n if (typeof children === 'string') {\n return (\n <script\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children }}\n suppressHydrationWarning\n />\n )\n }\n\n return null\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"Asset.js","sources":["../../src/Asset.tsx"],"sourcesContent":["import * as React from 'react'\nimport { isServer } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport type { RouterManagedTag } from '@tanstack/router-core'\n\ninterface ScriptAttrs {\n [key: string]: string | boolean | undefined\n src?: string\n suppressHydrationWarning?: boolean\n}\n\nexport function Asset({\n tag,\n attrs,\n children,\n nonce,\n}: RouterManagedTag & { nonce?: string }): React.ReactElement | null {\n switch (tag) {\n case 'title':\n return (\n <title {...attrs} suppressHydrationWarning>\n {children}\n </title>\n )\n case 'meta':\n return <meta {...attrs} suppressHydrationWarning />\n case 'link':\n return <link {...attrs} nonce={nonce} suppressHydrationWarning />\n case 'style':\n return (\n <style\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children as string }}\n nonce={nonce}\n />\n )\n case 'script':\n return <Script attrs={attrs}>{children}</Script>\n default:\n return null\n }\n}\n\nfunction Script({\n attrs,\n children,\n}: {\n attrs?: ScriptAttrs\n children?: string\n}) {\n const router = useRouter()\n\n React.useEffect(() => {\n if (attrs?.src) {\n const normSrc = (() => {\n try {\n const base = document.baseURI || window.location.href\n return new URL(attrs.src, base).href\n } catch {\n return attrs.src\n }\n })()\n const existingScript = Array.from(\n document.querySelectorAll('script[src]'),\n ).find((el) => (el as HTMLScriptElement).src === normSrc)\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n if (typeof children === 'string') {\n const typeAttr =\n typeof attrs?.type === 'string' ? attrs.type : 'text/javascript'\n const nonceAttr =\n typeof attrs?.nonce === 'string' ? attrs.nonce : undefined\n const existingScript = Array.from(\n document.querySelectorAll('script:not([src])'),\n ).find((el) => {\n if (!(el instanceof HTMLScriptElement)) return false\n const sType = el.getAttribute('type') ?? 'text/javascript'\n const sNonce = el.getAttribute('nonce') ?? undefined\n return (\n el.textContent === children &&\n sType === typeAttr &&\n sNonce === nonceAttr\n )\n })\n\n if (existingScript) {\n return\n }\n\n const script = document.createElement('script')\n script.textContent = children\n\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n if (\n key !== 'suppressHydrationWarning' &&\n value !== undefined &&\n value !== false\n ) {\n script.setAttribute(\n key,\n typeof value === 'boolean' ? '' : String(value),\n )\n }\n }\n }\n\n document.head.appendChild(script)\n\n return () => {\n if (script.parentNode) {\n script.parentNode.removeChild(script)\n }\n }\n }\n\n return undefined\n }, [attrs, children])\n\n if (!(isServer ?? router.isServer)) {\n const { src, ...rest } = attrs || {}\n // render an empty script on the client just to avoid hydration errors\n return (\n <script\n suppressHydrationWarning\n dangerouslySetInnerHTML={{ __html: '' }}\n {...rest}\n ></script>\n )\n }\n\n if (attrs?.src && typeof attrs.src === 'string') {\n return <script {...attrs} suppressHydrationWarning />\n }\n\n if (typeof children === 'string') {\n return (\n <script\n {...attrs}\n dangerouslySetInnerHTML={{ __html: children }}\n suppressHydrationWarning\n />\n )\n }\n\n return null\n}\n"],"names":[],"mappings":";;;;AAWO,SAAS,MAAM;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAqE;AACnE,UAAQ,KAAA;AAAA,IACN,KAAK;AACH,iCACG,SAAA,EAAO,GAAG,OAAO,0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,EAGV;AAEA,MAAI,OAAO,OAAO,OAAO,MAAM,QAAQ,UAAU;AAC/C,WAAO,oBAAC,UAAA,EAAQ,GAAG,OAAO,0BAAwB,MAAC;AAAA,EACrD;AAEA,MAAI,OAAO,aAAa,UAAU;AAChC,WACE;AAAA,MAAC;AAAA,MAAA;AAAA,QACE,GAAG;AAAA,QACJ,yBAAyB,EAAE,QAAQ,SAAA;AAAA,QACnC,0BAAwB;AAAA,MAAA;AAAA,IAAA;AAAA,EAG9B;AAEA,SAAO;AACT;"}
|
package/dist/esm/Match.js
CHANGED
|
@@ -2,7 +2,7 @@ import { jsxs, jsx, Fragment } from "react/jsx-runtime";
|
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
import invariant from "tiny-invariant";
|
|
4
4
|
import warning from "tiny-warning";
|
|
5
|
-
import { isNotFound, rootRouteId, createControlledPromise, isRedirect, getLocationChangeInfo } from "@tanstack/router-core";
|
|
5
|
+
import { isNotFound, rootRouteId, isServer, createControlledPromise, isRedirect, getLocationChangeInfo } from "@tanstack/router-core";
|
|
6
6
|
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
|
|
7
7
|
import { useRouterState } from "./useRouterState.js";
|
|
8
8
|
import { useRouter } from "./useRouter.js";
|
|
@@ -159,7 +159,7 @@ const MatchInner = React.memo(function MatchInnerImpl({
|
|
|
159
159
|
if (pendingMinMs) {
|
|
160
160
|
const routerMatch = router.getMatch(match.id);
|
|
161
161
|
if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
|
|
162
|
-
if (!router.isServer) {
|
|
162
|
+
if (!(isServer ?? router.isServer)) {
|
|
163
163
|
const minPendingPromise = createControlledPromise();
|
|
164
164
|
routerMatch._nonReactive.minPendingPromise = minPendingPromise;
|
|
165
165
|
setTimeout(() => {
|
|
@@ -180,7 +180,7 @@ const MatchInner = React.memo(function MatchInnerImpl({
|
|
|
180
180
|
throw router.getMatch(match.id)?._nonReactive.loadPromise;
|
|
181
181
|
}
|
|
182
182
|
if (match.status === "error") {
|
|
183
|
-
if (router.isServer) {
|
|
183
|
+
if (isServer ?? router.isServer) {
|
|
184
184
|
const RouteErrorComponent = (route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent;
|
|
185
185
|
return /* @__PURE__ */ jsx(
|
|
186
186
|
RouteErrorComponent,
|
package/dist/esm/Match.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Match.js","sources":["../../src/Match.tsx"],"sourcesContent":["import * as React from 'react'\nimport invariant from 'tiny-invariant'\nimport warning from 'tiny-warning'\nimport {\n createControlledPromise,\n getLocationChangeInfo,\n isNotFound,\n isRedirect,\n rootRouteId,\n} from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { CatchNotFound } from './not-found'\nimport { matchContext } from './matchContext'\nimport { SafeFragment } from './SafeFragment'\nimport { renderRouteNotFound } from './renderRouteNotFound'\nimport { ScrollRestoration } from './scroll-restoration'\nimport { ClientOnly } from './ClientOnly'\nimport type {\n AnyRoute,\n ParsedLocation,\n RootRouteOptions,\n} from '@tanstack/router-core'\n\nexport const Match = React.memo(function MatchImpl({\n matchId,\n}: {\n matchId: string\n}) {\n const router = useRouter()\n const matchState = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)\n invariant(\n match,\n `Could not find match for matchId \"${matchId}\". Please file an issue!`,\n )\n return {\n routeId: match.routeId,\n ssr: match.ssr,\n _displayPending: match._displayPending,\n }\n },\n structuralSharing: true as any,\n })\n\n const route: AnyRoute = router.routesById[matchState.routeId]\n\n const PendingComponent =\n route.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n const routeErrorComponent =\n route.options.errorComponent ?? router.options.defaultErrorComponent\n\n const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch\n\n const routeNotFoundComponent = route.isRoot\n ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component\n (route.options.notFoundComponent ??\n router.options.notFoundRoute?.options.component)\n : route.options.notFoundComponent\n\n const resolvedNoSsr =\n matchState.ssr === false || matchState.ssr === 'data-only'\n const ResolvedSuspenseBoundary =\n // If we're on the root route, allow forcefully wrapping in suspense\n (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) &&\n (route.options.wrapInSuspense ??\n PendingComponent ??\n ((route.options.errorComponent as any)?.preload || resolvedNoSsr))\n ? React.Suspense\n : SafeFragment\n\n const ResolvedCatchBoundary = routeErrorComponent\n ? CatchBoundary\n : SafeFragment\n\n const ResolvedNotFoundBoundary = routeNotFoundComponent\n ? CatchNotFound\n : SafeFragment\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const parentRouteId = useRouterState({\n select: (s) => {\n const index = s.matches.findIndex((d) => d.id === matchId)\n return s.matches[index - 1]?.routeId as string\n },\n })\n\n const ShellComponent = route.isRoot\n ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)\n : SafeFragment\n return (\n <ShellComponent>\n <matchContext.Provider value={matchId}>\n <ResolvedSuspenseBoundary fallback={pendingElement}>\n <ResolvedCatchBoundary\n getResetKey={() => resetKey}\n errorComponent={routeErrorComponent || ErrorComponent}\n onCatch={(error, errorInfo) => {\n // Forward not found errors (we don't want to show the error component for these)\n if (isNotFound(error)) throw error\n warning(false, `Error in route match: ${matchId}`)\n routeOnCatch?.(error, errorInfo)\n }}\n >\n <ResolvedNotFoundBoundary\n fallback={(error) => {\n // If the current not found handler doesn't exist or it has a\n // route ID which doesn't match the current route, rethrow the error\n if (\n !routeNotFoundComponent ||\n (error.routeId && error.routeId !== matchState.routeId) ||\n (!error.routeId && !route.isRoot)\n )\n throw error\n\n return React.createElement(routeNotFoundComponent, error as any)\n }}\n >\n {resolvedNoSsr || matchState._displayPending ? (\n <ClientOnly fallback={pendingElement}>\n <MatchInner matchId={matchId} />\n </ClientOnly>\n ) : (\n <MatchInner matchId={matchId} />\n )}\n </ResolvedNotFoundBoundary>\n </ResolvedCatchBoundary>\n </ResolvedSuspenseBoundary>\n </matchContext.Provider>\n {parentRouteId === rootRouteId && router.options.scrollRestoration ? (\n <>\n <OnRendered />\n <ScrollRestoration />\n </>\n ) : null}\n </ShellComponent>\n )\n})\n\n// On Rendered can't happen above the root layout because it actually\n// renders a dummy dom element to track the rendered state of the app.\n// We render a script tag with a key that changes based on the current\n// location state.__TSR_key. Also, because it's below the root layout, it\n// allows us to fire onRendered events even after a hydration mismatch\n// error that occurred above the root layout (like bad head/link tags,\n// which is common).\nfunction OnRendered() {\n const router = useRouter()\n\n const prevLocationRef = React.useRef<undefined | ParsedLocation<{}>>(\n undefined,\n )\n\n return (\n <script\n key={router.latestLocation.state.__TSR_key}\n suppressHydrationWarning\n ref={(el) => {\n if (\n el &&\n (prevLocationRef.current === undefined ||\n prevLocationRef.current.href !== router.latestLocation.href)\n ) {\n router.emit({\n type: 'onRendered',\n ...getLocationChangeInfo(router.state),\n })\n prevLocationRef.current = router.latestLocation\n }\n }}\n />\n )\n}\n\nexport const MatchInner = React.memo(function MatchInnerImpl({\n matchId,\n}: {\n matchId: string\n}): any {\n const router = useRouter()\n\n const { match, key, routeId } = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)!\n const routeId = match.routeId as string\n\n const remountFn =\n (router.routesById[routeId] as AnyRoute).options.remountDeps ??\n router.options.defaultRemountDeps\n const remountDeps = remountFn?.({\n routeId,\n loaderDeps: match.loaderDeps,\n params: match._strictParams,\n search: match._strictSearch,\n })\n const key = remountDeps ? JSON.stringify(remountDeps) : undefined\n\n return {\n key,\n routeId,\n match: {\n id: match.id,\n status: match.status,\n error: match.error,\n invalid: match.invalid,\n _forcePending: match._forcePending,\n _displayPending: match._displayPending,\n },\n }\n },\n structuralSharing: true as any,\n })\n\n const route = router.routesById[routeId] as AnyRoute\n\n const out = React.useMemo(() => {\n const Comp = route.options.component ?? router.options.defaultComponent\n if (Comp) {\n return <Comp key={key} />\n }\n return <Outlet />\n }, [key, route.options.component, router.options.defaultComponent])\n\n if (match._displayPending) {\n throw router.getMatch(match.id)?._nonReactive.displayPendingPromise\n }\n\n if (match._forcePending) {\n throw router.getMatch(match.id)?._nonReactive.minPendingPromise\n }\n\n // see also hydrate() in packages/router-core/src/ssr/ssr-client.ts\n if (match.status === 'pending') {\n // We're pending, and if we have a minPendingMs, we need to wait for it\n const pendingMinMs =\n route.options.pendingMinMs ?? router.options.defaultPendingMinMs\n if (pendingMinMs) {\n const routerMatch = router.getMatch(match.id)\n if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {\n // Create a promise that will resolve after the minPendingMs\n if (!router.isServer) {\n const minPendingPromise = createControlledPromise<void>()\n\n routerMatch._nonReactive.minPendingPromise = minPendingPromise\n\n setTimeout(() => {\n minPendingPromise.resolve()\n // We've handled the minPendingPromise, so we can delete it\n routerMatch._nonReactive.minPendingPromise = undefined\n }, pendingMinMs)\n }\n }\n }\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'notFound') {\n invariant(isNotFound(match.error), 'Expected a notFound error')\n return renderRouteNotFound(router, route, match.error)\n }\n\n if (match.status === 'redirected') {\n // Redirects should be handled by the router transition. If we happen to\n // encounter a redirect here, it's a bug. Let's warn, but render nothing.\n invariant(isRedirect(match.error), 'Expected a redirect error')\n\n // warning(\n // false,\n // 'Tried to render a redirected route match! This is a weird circumstance, please file an issue!',\n // )\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'error') {\n // If we're on the server, we need to use React's new and super\n // wonky api for throwing errors from a server side render inside\n // of a suspense boundary. This is the only way to get\n // renderToPipeableStream to not hang indefinitely.\n // We'll serialize the error and rethrow it on the client.\n if (router.isServer) {\n const RouteErrorComponent =\n (route.options.errorComponent ??\n router.options.defaultErrorComponent) ||\n ErrorComponent\n return (\n <RouteErrorComponent\n error={match.error as any}\n reset={undefined as any}\n info={{\n componentStack: '',\n }}\n />\n )\n }\n\n throw match.error\n }\n\n return out\n})\n\n/**\n * Render the next child match in the route tree. Typically used inside\n * a route component to render nested routes.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent\n */\nexport const Outlet = React.memo(function OutletImpl() {\n const router = useRouter()\n const matchId = React.useContext(matchContext)\n const routeId = useRouterState({\n select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,\n })\n\n const route = router.routesById[routeId]!\n\n const parentGlobalNotFound = useRouterState({\n select: (s) => {\n const matches = s.matches\n const parentMatch = matches.find((d) => d.id === matchId)\n invariant(\n parentMatch,\n `Could not find parent match for matchId \"${matchId}\"`,\n )\n return parentMatch.globalNotFound\n },\n })\n\n const childMatchId = useRouterState({\n select: (s) => {\n const matches = s.matches\n const index = matches.findIndex((d) => d.id === matchId)\n return matches[index + 1]?.id\n },\n })\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n if (parentGlobalNotFound) {\n return renderRouteNotFound(router, route, undefined)\n }\n\n if (!childMatchId) {\n return null\n }\n\n const nextMatch = <Match matchId={childMatchId} />\n\n if (routeId === rootRouteId) {\n return (\n <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense>\n )\n }\n\n return nextMatch\n})\n"],"names":["match","routeId","key"],"mappings":";;;;;;;;;;;;;;AAyBO,MAAM,QAAQ,MAAM,KAAK,SAAS,UAAU;AAAA,EACjD;AACF,GAEG;AACD,QAAM,SAAS,UAAA;AACf,QAAM,aAAa,eAAe;AAAA,IAChC,QAAQ,CAAC,MAAM;AACb,YAAM,QAAQ,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACpD;AAAA,QACE;AAAA,QACA,qCAAqC,OAAO;AAAA,MAAA;AAE9C,aAAO;AAAA,QACL,SAAS,MAAM;AAAA,QACf,KAAK,MAAM;AAAA,QACX,iBAAiB,MAAM;AAAA,MAAA;AAAA,IAE3B;AAAA,IACA,mBAAmB;AAAA,EAAA,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AAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,GAAG;AAAA,EAAA,CACzD;AAED,QAAM,QAAQ,OAAO,WAAW,OAAO;AAEvC,QAAM,uBAAuB,eAAe;AAAA,IAC1C,QAAQ,CAAC,MAAM;AACb,YAAM,UAAU,EAAE;AAClB,YAAM,cAAc,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACxD;AAAA,QACE;AAAA,QACA,4CAA4C,OAAO;AAAA,MAAA;AAErD,aAAO,YAAY;AAAA,IACrB;AAAA,EAAA,CACD;AAED,QAAM,eAAe,eAAe;AAAA,IAClC,QAAQ,CAAC,MAAM;AACb,YAAM,UAAU,EAAE;AAClB,YAAM,QAAQ,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,OAAO;AACvD,aAAO,QAAQ,QAAQ,CAAC,GAAG;AAAA,IAC7B;AAAA,EAAA,CACD;AAED,QAAM,iBAAiB,OAAO,QAAQ,8CACnC,OAAO,QAAQ,yBAAf,CAAA,CAAuC,IACtC;AAEJ,MAAI,sBAAsB;AACxB,WAAO,oBAAoB,QAAQ,OAAO,MAAS;AAAA,EACrD;AAEA,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,oBAAC,OAAA,EAAM,SAAS,aAAA,CAAc;AAEhD,MAAI,YAAY,aAAa;AAC3B,+BACG,MAAM,UAAN,EAAe,UAAU,gBAAiB,UAAA,WAAU;AAAA,EAEzD;AAEA,SAAO;AACT,CAAC;"}
|
|
1
|
+
{"version":3,"file":"Match.js","sources":["../../src/Match.tsx"],"sourcesContent":["import * as React from 'react'\nimport invariant from 'tiny-invariant'\nimport warning from 'tiny-warning'\nimport {\n createControlledPromise,\n getLocationChangeInfo,\n isNotFound,\n isRedirect,\n isServer,\n rootRouteId,\n} from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { CatchNotFound } from './not-found'\nimport { matchContext } from './matchContext'\nimport { SafeFragment } from './SafeFragment'\nimport { renderRouteNotFound } from './renderRouteNotFound'\nimport { ScrollRestoration } from './scroll-restoration'\nimport { ClientOnly } from './ClientOnly'\nimport type {\n AnyRoute,\n ParsedLocation,\n RootRouteOptions,\n} from '@tanstack/router-core'\n\nexport const Match = React.memo(function MatchImpl({\n matchId,\n}: {\n matchId: string\n}) {\n const router = useRouter()\n const matchState = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)\n invariant(\n match,\n `Could not find match for matchId \"${matchId}\". Please file an issue!`,\n )\n return {\n routeId: match.routeId,\n ssr: match.ssr,\n _displayPending: match._displayPending,\n }\n },\n structuralSharing: true as any,\n })\n\n const route: AnyRoute = router.routesById[matchState.routeId]\n\n const PendingComponent =\n route.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n const routeErrorComponent =\n route.options.errorComponent ?? router.options.defaultErrorComponent\n\n const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch\n\n const routeNotFoundComponent = route.isRoot\n ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component\n (route.options.notFoundComponent ??\n router.options.notFoundRoute?.options.component)\n : route.options.notFoundComponent\n\n const resolvedNoSsr =\n matchState.ssr === false || matchState.ssr === 'data-only'\n const ResolvedSuspenseBoundary =\n // If we're on the root route, allow forcefully wrapping in suspense\n (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) &&\n (route.options.wrapInSuspense ??\n PendingComponent ??\n ((route.options.errorComponent as any)?.preload || resolvedNoSsr))\n ? React.Suspense\n : SafeFragment\n\n const ResolvedCatchBoundary = routeErrorComponent\n ? CatchBoundary\n : SafeFragment\n\n const ResolvedNotFoundBoundary = routeNotFoundComponent\n ? CatchNotFound\n : SafeFragment\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const parentRouteId = useRouterState({\n select: (s) => {\n const index = s.matches.findIndex((d) => d.id === matchId)\n return s.matches[index - 1]?.routeId as string\n },\n })\n\n const ShellComponent = route.isRoot\n ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)\n : SafeFragment\n return (\n <ShellComponent>\n <matchContext.Provider value={matchId}>\n <ResolvedSuspenseBoundary fallback={pendingElement}>\n <ResolvedCatchBoundary\n getResetKey={() => resetKey}\n errorComponent={routeErrorComponent || ErrorComponent}\n onCatch={(error, errorInfo) => {\n // Forward not found errors (we don't want to show the error component for these)\n if (isNotFound(error)) throw error\n warning(false, `Error in route match: ${matchId}`)\n routeOnCatch?.(error, errorInfo)\n }}\n >\n <ResolvedNotFoundBoundary\n fallback={(error) => {\n // If the current not found handler doesn't exist or it has a\n // route ID which doesn't match the current route, rethrow the error\n if (\n !routeNotFoundComponent ||\n (error.routeId && error.routeId !== matchState.routeId) ||\n (!error.routeId && !route.isRoot)\n )\n throw error\n\n return React.createElement(routeNotFoundComponent, error as any)\n }}\n >\n {resolvedNoSsr || matchState._displayPending ? (\n <ClientOnly fallback={pendingElement}>\n <MatchInner matchId={matchId} />\n </ClientOnly>\n ) : (\n <MatchInner matchId={matchId} />\n )}\n </ResolvedNotFoundBoundary>\n </ResolvedCatchBoundary>\n </ResolvedSuspenseBoundary>\n </matchContext.Provider>\n {parentRouteId === rootRouteId && router.options.scrollRestoration ? (\n <>\n <OnRendered />\n <ScrollRestoration />\n </>\n ) : null}\n </ShellComponent>\n )\n})\n\n// On Rendered can't happen above the root layout because it actually\n// renders a dummy dom element to track the rendered state of the app.\n// We render a script tag with a key that changes based on the current\n// location state.__TSR_key. Also, because it's below the root layout, it\n// allows us to fire onRendered events even after a hydration mismatch\n// error that occurred above the root layout (like bad head/link tags,\n// which is common).\nfunction OnRendered() {\n const router = useRouter()\n\n const prevLocationRef = React.useRef<undefined | ParsedLocation<{}>>(\n undefined,\n )\n\n return (\n <script\n key={router.latestLocation.state.__TSR_key}\n suppressHydrationWarning\n ref={(el) => {\n if (\n el &&\n (prevLocationRef.current === undefined ||\n prevLocationRef.current.href !== router.latestLocation.href)\n ) {\n router.emit({\n type: 'onRendered',\n ...getLocationChangeInfo(router.state),\n })\n prevLocationRef.current = router.latestLocation\n }\n }}\n />\n )\n}\n\nexport const MatchInner = React.memo(function MatchInnerImpl({\n matchId,\n}: {\n matchId: string\n}): any {\n const router = useRouter()\n\n const { match, key, routeId } = useRouterState({\n select: (s) => {\n const match = s.matches.find((d) => d.id === matchId)!\n const routeId = match.routeId as string\n\n const remountFn =\n (router.routesById[routeId] as AnyRoute).options.remountDeps ??\n router.options.defaultRemountDeps\n const remountDeps = remountFn?.({\n routeId,\n loaderDeps: match.loaderDeps,\n params: match._strictParams,\n search: match._strictSearch,\n })\n const key = remountDeps ? JSON.stringify(remountDeps) : undefined\n\n return {\n key,\n routeId,\n match: {\n id: match.id,\n status: match.status,\n error: match.error,\n invalid: match.invalid,\n _forcePending: match._forcePending,\n _displayPending: match._displayPending,\n },\n }\n },\n structuralSharing: true as any,\n })\n\n const route = router.routesById[routeId] as AnyRoute\n\n const out = React.useMemo(() => {\n const Comp = route.options.component ?? router.options.defaultComponent\n if (Comp) {\n return <Comp key={key} />\n }\n return <Outlet />\n }, [key, route.options.component, router.options.defaultComponent])\n\n if (match._displayPending) {\n throw router.getMatch(match.id)?._nonReactive.displayPendingPromise\n }\n\n if (match._forcePending) {\n throw router.getMatch(match.id)?._nonReactive.minPendingPromise\n }\n\n // see also hydrate() in packages/router-core/src/ssr/ssr-client.ts\n if (match.status === 'pending') {\n // We're pending, and if we have a minPendingMs, we need to wait for it\n const pendingMinMs =\n route.options.pendingMinMs ?? router.options.defaultPendingMinMs\n if (pendingMinMs) {\n const routerMatch = router.getMatch(match.id)\n if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {\n // Create a promise that will resolve after the minPendingMs\n if (!(isServer ?? router.isServer)) {\n const minPendingPromise = createControlledPromise<void>()\n\n routerMatch._nonReactive.minPendingPromise = minPendingPromise\n\n setTimeout(() => {\n minPendingPromise.resolve()\n // We've handled the minPendingPromise, so we can delete it\n routerMatch._nonReactive.minPendingPromise = undefined\n }, pendingMinMs)\n }\n }\n }\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'notFound') {\n invariant(isNotFound(match.error), 'Expected a notFound error')\n return renderRouteNotFound(router, route, match.error)\n }\n\n if (match.status === 'redirected') {\n // Redirects should be handled by the router transition. If we happen to\n // encounter a redirect here, it's a bug. Let's warn, but render nothing.\n invariant(isRedirect(match.error), 'Expected a redirect error')\n\n // warning(\n // false,\n // 'Tried to render a redirected route match! This is a weird circumstance, please file an issue!',\n // )\n throw router.getMatch(match.id)?._nonReactive.loadPromise\n }\n\n if (match.status === 'error') {\n // If we're on the server, we need to use React's new and super\n // wonky api for throwing errors from a server side render inside\n // of a suspense boundary. This is the only way to get\n // renderToPipeableStream to not hang indefinitely.\n // We'll serialize the error and rethrow it on the client.\n if (isServer ?? router.isServer) {\n const RouteErrorComponent =\n (route.options.errorComponent ??\n router.options.defaultErrorComponent) ||\n ErrorComponent\n return (\n <RouteErrorComponent\n error={match.error as any}\n reset={undefined as any}\n info={{\n componentStack: '',\n }}\n />\n )\n }\n\n throw match.error\n }\n\n return out\n})\n\n/**\n * Render the next child match in the route tree. Typically used inside\n * a route component to render nested routes.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent\n */\nexport const Outlet = React.memo(function OutletImpl() {\n const router = useRouter()\n const matchId = React.useContext(matchContext)\n const routeId = useRouterState({\n select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,\n })\n\n const route = router.routesById[routeId]!\n\n const parentGlobalNotFound = useRouterState({\n select: (s) => {\n const matches = s.matches\n const parentMatch = matches.find((d) => d.id === matchId)\n invariant(\n parentMatch,\n `Could not find parent match for matchId \"${matchId}\"`,\n )\n return parentMatch.globalNotFound\n },\n })\n\n const childMatchId = useRouterState({\n select: (s) => {\n const matches = s.matches\n const index = matches.findIndex((d) => d.id === matchId)\n return matches[index + 1]?.id\n },\n })\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n if (parentGlobalNotFound) {\n return renderRouteNotFound(router, route, undefined)\n }\n\n if (!childMatchId) {\n return null\n }\n\n const nextMatch = <Match matchId={childMatchId} />\n\n if (routeId === rootRouteId) {\n return (\n <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense>\n )\n }\n\n return nextMatch\n})\n"],"names":["match","routeId","key"],"mappings":";;;;;;;;;;;;;;AA0BO,MAAM,QAAQ,MAAM,KAAK,SAAS,UAAU;AAAA,EACjD;AACF,GAEG;AACD,QAAM,SAAS,UAAA;AACf,QAAM,aAAa,eAAe;AAAA,IAChC,QAAQ,CAAC,MAAM;AACb,YAAM,QAAQ,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACpD;AAAA,QACE;AAAA,QACA,qCAAqC,OAAO;AAAA,MAAA;AAE9C,aAAO;AAAA,QACL,SAAS,MAAM;AAAA,QACf,KAAK,MAAM;AAAA,QACX,iBAAiB,MAAM;AAAA,MAAA;AAAA,IAE3B;AAAA,IACA,mBAAmB;AAAA,EAAA,CACpB;AAED,QAAM,QAAkB,OAAO,WAAW,WAAW,OAAO;AAE5D,QAAM,mBACJ,MAAM,QAAQ,oBAAoB,OAAO,QAAQ;AAEnD,QAAM,iBAAiB,mBAAmB,oBAAC,kBAAA,CAAA,CAAiB,IAAK;AAEjE,QAAM,sBACJ,MAAM,QAAQ,kBAAkB,OAAO,QAAQ;AAEjD,QAAM,eAAe,MAAM,QAAQ,WAAW,OAAO,QAAQ;AAE7D,QAAM,yBAAyB,MAAM;AAAA;AAAA,IAEhC,MAAM,QAAQ,qBACf,OAAO,QAAQ,eAAe,QAAQ;AAAA,MACtC,MAAM,QAAQ;AAElB,QAAM,gBACJ,WAAW,QAAQ,SAAS,WAAW,QAAQ;AACjD,QAAM;AAAA;AAAA,KAEH,CAAC,MAAM,UAAU,MAA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AAM,EAAE,OAAO,OAAO;AACvD,aAAO,QAAQ,QAAQ,CAAC,GAAG;AAAA,IAC7B;AAAA,EAAA,CACD;AAED,QAAM,iBAAiB,OAAO,QAAQ,8CACnC,OAAO,QAAQ,yBAAf,CAAA,CAAuC,IACtC;AAEJ,MAAI,sBAAsB;AACxB,WAAO,oBAAoB,QAAQ,OAAO,MAAS;AAAA,EACrD;AAEA,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,oBAAC,OAAA,EAAM,SAAS,aAAA,CAAc;AAEhD,MAAI,YAAY,aAAa;AAC3B,+BACG,MAAM,UAAN,EAAe,UAAU,gBAAiB,UAAA,WAAU;AAAA,EAEzD;AAEA,SAAO;AACT,CAAC;"}
|
package/dist/esm/Matches.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jsxs, jsx } from "react/jsx-runtime";
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
import warning from "tiny-warning";
|
|
4
|
-
import { rootRouteId } from "@tanstack/router-core";
|
|
4
|
+
import { rootRouteId, isServer } from "@tanstack/router-core";
|
|
5
5
|
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
|
|
6
6
|
import { useRouterState } from "./useRouterState.js";
|
|
7
7
|
import { useRouter } from "./useRouter.js";
|
|
@@ -14,9 +14,9 @@ function Matches() {
|
|
|
14
14
|
const rootRoute = router.routesById[rootRouteId];
|
|
15
15
|
const PendingComponent = rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent;
|
|
16
16
|
const pendingElement = PendingComponent ? /* @__PURE__ */ jsx(PendingComponent, {}) : null;
|
|
17
|
-
const ResolvedSuspense = router.isServer || typeof document !== "undefined" && router.ssr ? SafeFragment : React.Suspense;
|
|
17
|
+
const ResolvedSuspense = (isServer ?? router.isServer) || typeof document !== "undefined" && router.ssr ? SafeFragment : React.Suspense;
|
|
18
18
|
const inner = /* @__PURE__ */ jsxs(ResolvedSuspense, { fallback: pendingElement, children: [
|
|
19
|
-
!router.isServer && /* @__PURE__ */ jsx(Transitioner, {}),
|
|
19
|
+
!(isServer ?? router.isServer) && /* @__PURE__ */ jsx(Transitioner, {}),
|
|
20
20
|
/* @__PURE__ */ jsx(MatchesInner, {})
|
|
21
21
|
] });
|
|
22
22
|
return router.options.InnerWrap ? /* @__PURE__ */ jsx(router.options.InnerWrap, { children: inner }) : inner;
|
package/dist/esm/Matches.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Matches.js","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { rootRouteId } from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRoute,\n AnyRouter,\n DeepPartial,\n Expand,\n MakeOptionalPathParams,\n MakeOptionalSearchParams,\n MakeRouteMatchUnion,\n MaskOptions,\n MatchRouteOptions,\n NoInfer,\n RegisteredRouter,\n ResolveRelativePath,\n ResolveRoute,\n RouteByPath,\n RouterState,\n ToSubOptionsProps,\n} from '@tanstack/router-core'\n\ndeclare module '@tanstack/router-core' {\n export interface RouteMatchExtensions {\n meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>\n links?: Array<React.JSX.IntrinsicElements['link'] | undefined>\n scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>\n headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n }\n}\n\n/**\n * Internal component that renders the router's active match tree with\n * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.\n */\nexport function Matches() {\n const router = useRouter()\n const rootRoute: AnyRoute = router.routesById[rootRouteId]\n\n const PendingComponent =\n rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n router.isServer || (typeof document !== 'undefined' && router.ssr)\n ? SafeFragment\n : React.Suspense\n\n const inner = (\n <ResolvedSuspense fallback={pendingElement}>\n {!router.isServer && <Transitioner />}\n <MatchesInner />\n </ResolvedSuspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const router = useRouter()\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const matchComponent = matchId ? <Match matchId={matchId} /> : null\n\n return (\n <matchContext.Provider value={matchId}>\n {router.options.disableGlobalCatchBoundary ? (\n matchComponent\n ) : (\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchComponent}\n </CatchBoundary>\n )}\n </matchContext.Provider>\n )\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = ToSubOptionsProps<TRouter, TFrom, TTo> &\n DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &\n DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &\n MaskOptions<TRouter, TMaskFrom, TMaskTo> &\n MatchRouteOptions\n\n/**\n * Create a matcher function for testing locations against route definitions.\n *\n * The returned function accepts standard navigation options (`to`, `params`,\n * `search`, etc.) and returns either `false` (no match) or the matched params\n * object when the route matches the current or pending location.\n *\n * Useful for conditional rendering and active UI states.\n *\n * @returns A `matchRoute(options)` function that returns `false` or params.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook\n */\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],\n structuralSharing: true as any,\n })\n\n return React.useCallback(\n <\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => React.ReactNode)\n | React.ReactNode\n}\n\n/**\n * Component that conditionally renders its children based on whether a route\n * matches the provided `from`/`to` options. If `children` is a function, it\n * receives the matched params object.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent\n */\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any) as boolean\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport interface UseMatchesBaseOptions<\n TRouter extends AnyRouter,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n matches: Array<MakeRouteMatchUnion<TRouter>>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n}\n\nexport type UseMatchesResult<\n TRouter extends AnyRouter,\n TSelected,\n> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected\n\nexport function useMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n return useRouterState({\n select: (state: RouterState<TRouter['routeTree']>) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>)\n : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any) as UseMatchesResult<TRouter, TSelected>\n}\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @returns The array of matches (or the selected value).\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\nexport function useParentMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n\n/**\n * Read the array of active route matches that are children of the current\n * match (or selected parent) in the match tree.\n */\nexport function useChildMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n"],"names":[],"mappings":";;;;;;;;;;;AA+CO,SAAS,UAAU;AACxB,QAAM,SAAS,UAAA;AACf,QAAM,YAAsB,OAAO,WAAW,WAAW;AAEzD,QAAM,mBACJ,UAAU,QAAQ,oBAAoB,OAAO,QAAQ;AAEvD,QAAM,iBAAiB,mBAAmB,oBAAC,kBAAA,CAAA,CAAiB,IAAK;AAGjE,QAAM,mBACJ,OAAO,YAAa,OAAO,aAAa,eAAe,OAAO,MAC1D,eACA,MAAM;AAEZ,QAAM,QACJ,qBAAC,kBAAA,EAAiB,UAAU,gBACzB,UAAA;AAAA,IAAA,CAAC,OAAO,YAAY,oBAAC,cAAA,CAAA,CAAa;AAAA,wBAClC,cAAA,CAAA,CAAa;AAAA,EAAA,GAChB;AAGF,SAAO,OAAO,QAAQ,YACpB,oBAAC,OAAO,QAAQ,WAAf,EAA0B,UAAA,MAAA,CAAM,IAEjC;AAEJ;AAEA,SAAS,eAAe;AACtB,QAAM,SAAS,UAAA;AACf,QAAM,UAAU,eAAe;AA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AAAA,IACpB,QAAQ,CAAC,UAA6C;AACpD,YAAM,UAAU,MAAM;AACtB,aAAO,MAAM,SACT,KAAK,OAAO,OAA8C,IAC1D;AAAA,IACN;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;AAkBO,SAAS,iBAKd,MAEsC;AACtC,QAAM,iBAAiB,MAAM,WAAW,YAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB;AAAA,QACA,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc;AAAA,MAAA;AAElD,aAAO,MAAM,SAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;AAMO,SAAS,gBAKd,MAEsC;AACtC,QAAM,iBAAiB,MAAM,WAAW,YAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAiD;AACxD,gBAAU,QAAQ;AAAA,QAChB,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc,IAAI;AAAA,MAAA;AAEtD,aAAO,MAAM,SAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;"}
|
|
1
|
+
{"version":3,"file":"Matches.js","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { isServer, rootRouteId } from '@tanstack/router-core'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRoute,\n AnyRouter,\n DeepPartial,\n Expand,\n MakeOptionalPathParams,\n MakeOptionalSearchParams,\n MakeRouteMatchUnion,\n MaskOptions,\n MatchRouteOptions,\n NoInfer,\n RegisteredRouter,\n ResolveRelativePath,\n ResolveRoute,\n RouteByPath,\n RouterState,\n ToSubOptionsProps,\n} from '@tanstack/router-core'\n\ndeclare module '@tanstack/router-core' {\n export interface RouteMatchExtensions {\n meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>\n links?: Array<React.JSX.IntrinsicElements['link'] | undefined>\n scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>\n headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>\n }\n}\n\n/**\n * Internal component that renders the router's active match tree with\n * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.\n */\nexport function Matches() {\n const router = useRouter()\n const rootRoute: AnyRoute = router.routesById[rootRouteId]\n\n const PendingComponent =\n rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent\n\n const pendingElement = PendingComponent ? <PendingComponent /> : null\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n (isServer ?? router.isServer) ||\n (typeof document !== 'undefined' && router.ssr)\n ? SafeFragment\n : React.Suspense\n\n const inner = (\n <ResolvedSuspense fallback={pendingElement}>\n {!(isServer ?? router.isServer) && <Transitioner />}\n <MatchesInner />\n </ResolvedSuspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const router = useRouter()\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n const matchComponent = matchId ? <Match matchId={matchId} /> : null\n\n return (\n <matchContext.Provider value={matchId}>\n {router.options.disableGlobalCatchBoundary ? (\n matchComponent\n ) : (\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchComponent}\n </CatchBoundary>\n )}\n </matchContext.Provider>\n )\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = ToSubOptionsProps<TRouter, TFrom, TTo> &\n DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> &\n DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> &\n MaskOptions<TRouter, TMaskFrom, TMaskTo> &\n MatchRouteOptions\n\n/**\n * Create a matcher function for testing locations against route definitions.\n *\n * The returned function accepts standard navigation options (`to`, `params`,\n * `search`, etc.) and returns either `false` (no match) or the matched params\n * object when the route matches the current or pending location.\n *\n * Useful for conditional rendering and active UI states.\n *\n * @returns A `matchRoute(options)` function that returns `false` or params.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook\n */\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation?.href, s.status],\n structuralSharing: true as any,\n })\n\n return React.useCallback(\n <\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => React.ReactNode)\n | React.ReactNode\n}\n\n/**\n * Component that conditionally renders its children based on whether a route\n * matches the provided `from`/`to` options. If `children` is a function, it\n * receives the matched params object.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent\n */\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any) as boolean\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport interface UseMatchesBaseOptions<\n TRouter extends AnyRouter,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n matches: Array<MakeRouteMatchUnion<TRouter>>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n}\n\nexport type UseMatchesResult<\n TRouter extends AnyRouter,\n TSelected,\n> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected\n\nexport function useMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n return useRouterState({\n select: (state: RouterState<TRouter['routeTree']>) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>)\n : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any) as UseMatchesResult<TRouter, TSelected>\n}\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @returns The array of matches (or the selected value).\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\n\n/**\n * Read the full array of active route matches or select a derived subset.\n *\n * Useful for debugging, breadcrumbs, or aggregating metadata across matches.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook\n */\nexport function useParentMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n\n/**\n * Read the array of active route matches that are children of the current\n * match (or selected parent) in the match tree.\n */\nexport function useChildMatches<\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n): UseMatchesResult<TRouter, TSelected> {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select ? opts.select(matches) : matches\n },\n structuralSharing: opts?.structuralSharing,\n } as any)\n}\n"],"names":[],"mappings":";;;;;;;;;;;AA+CO,SAAS,UAAU;AACxB,QAAM,SAAS,UAAA;AACf,QA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,cAAc,IAAI;AAAA,MAAA;AAEtD,aAAO,MAAM,SAAS,KAAK,OAAO,OAAO,IAAI;AAAA,IAC/C;AAAA,IACA,mBAAmB,MAAM;AAAA,EAAA,CACnB;AACV;"}
|
package/dist/esm/ScriptOnce.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { jsx } from "react/jsx-runtime";
|
|
2
|
+
import { isServer } from "@tanstack/router-core";
|
|
2
3
|
import { useRouter } from "./useRouter.js";
|
|
3
4
|
function ScriptOnce({ children }) {
|
|
4
5
|
const router = useRouter();
|
|
5
|
-
if (!router.isServer) {
|
|
6
|
+
if (!(isServer ?? router.isServer)) {
|
|
6
7
|
return null;
|
|
7
8
|
}
|
|
8
9
|
return /* @__PURE__ */ jsx(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ScriptOnce.js","sources":["../../src/ScriptOnce.tsx"],"sourcesContent":["import { useRouter } from './useRouter'\n\n/**\n * Server-only helper to emit a script tag exactly once during SSR.\n */\nexport function ScriptOnce({ children }: { children: string }) {\n const router = useRouter()\n if (!router.isServer) {\n return null\n }\n\n return (\n <script\n nonce={router.options.ssr?.nonce}\n dangerouslySetInnerHTML={{\n __html: children + ';document.currentScript.remove()',\n }}\n />\n )\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ScriptOnce.js","sources":["../../src/ScriptOnce.tsx"],"sourcesContent":["import { isServer } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\n\n/**\n * Server-only helper to emit a script tag exactly once during SSR.\n */\nexport function ScriptOnce({ children }: { children: string }) {\n const router = useRouter()\n if (!(isServer ?? router.isServer)) {\n return null\n }\n\n return (\n <script\n nonce={router.options.ssr?.nonce}\n dangerouslySetInnerHTML={{\n __html: children + ';document.currentScript.remove()',\n }}\n />\n )\n}\n"],"names":[],"mappings":";;;AAMO,SAAS,WAAW,EAAE,YAAkC;AAC7D,QAAM,SAAS,UAAA;AACf,MAAI,EAAE,YAAY,OAAO,WAAW;AAClC,WAAO;AAAA,EACT;AAEA,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,OAAO,OAAO,QAAQ,KAAK;AAAA,MAC3B,yBAAyB;AAAA,QACvB,QAAQ,WAAW;AAAA,MAAA;AAAA,IACrB;AAAA,EAAA;AAGN;"}
|
package/dist/esm/link.js
CHANGED
|
@@ -77,21 +77,18 @@ function useLinkProps(options, forwardedRef) {
|
|
|
77
77
|
() => router.buildLocation({ ..._options }),
|
|
78
78
|
[router, _options]
|
|
79
79
|
);
|
|
80
|
+
const hrefOptionPublicHref = next.maskedLocation ? next.maskedLocation.publicHref : next.publicHref;
|
|
81
|
+
const hrefOptionExternal = next.maskedLocation ? next.maskedLocation.external : next.external;
|
|
80
82
|
const hrefOption = React.useMemo(() => {
|
|
81
|
-
if (disabled)
|
|
82
|
-
|
|
83
|
+
if (disabled) return void 0;
|
|
84
|
+
if (hrefOptionExternal) {
|
|
85
|
+
return { href: hrefOptionPublicHref, external: true };
|
|
83
86
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
} else {
|
|
90
|
-
external = true;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return { href, external };
|
|
94
|
-
}, [disabled, next.maskedLocation, next.url, router.origin, router.history]);
|
|
87
|
+
return {
|
|
88
|
+
href: router.history.createHref(hrefOptionPublicHref) || "/",
|
|
89
|
+
external: false
|
|
90
|
+
};
|
|
91
|
+
}, [disabled, hrefOptionExternal, hrefOptionPublicHref, router.history]);
|
|
95
92
|
const externalLink = React.useMemo(() => {
|
|
96
93
|
if (hrefOption?.external) {
|
|
97
94
|
if (isDangerousProtocol(hrefOption.href)) {
|
package/dist/esm/link.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.js","sources":["../../src/link.tsx"],"sourcesContent":["import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n deepEqual,\n exactPathTest,\n functionalUpdate,\n isDangerousProtocol,\n preloadWarning,\n removeTrailingSlash,\n} from '@tanstack/router-core'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\n\nimport { useForwardedRef, useIntersectionObserver } from './utils'\n\nimport { useHydrated } from './ClientOnly'\nimport type {\n AnyRouter,\n Constrain,\n LinkOptions,\n RegisteredRouter,\n RoutePaths,\n} from '@tanstack/router-core'\nimport type { ReactNode } from 'react'\nimport type {\n ValidateLinkOptions,\n ValidateLinkOptionsArray,\n} from './typePrimitives'\n\n/**\n * Build anchor-like props for declarative navigation and preloading.\n *\n * Returns stable `href`, event handlers and accessibility props derived from\n * router options and active state. Used internally by `Link` and custom links.\n *\n * Options cover `to`, `params`, `search`, `hash`, `state`, `preload`,\n * `activeProps`, `inactiveProps`, and more.\n *\n * @returns React anchor props suitable for `<a>` or custom components.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook\n */\nexport function useLinkProps<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n forwardedRef?: React.ForwardedRef<Element>,\n): React.ComponentPropsWithRef<'a'> {\n const router = useRouter()\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n const hasRenderFetched = React.useRef(false)\n const innerRef = useForwardedRef(forwardedRef)\n const isHydrated = useHydrated()\n\n const {\n // custom props\n activeProps,\n inactiveProps,\n activeOptions,\n to,\n preload: userPreload,\n preloadDelay: userPreloadDelay,\n hashScrollIntoView,\n replace,\n startTransition,\n resetScroll,\n viewTransition,\n // element props\n children,\n target,\n disabled,\n style,\n className,\n onClick,\n onFocus,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n ignoreBlocker,\n // prevent these from being returned\n params: _params,\n search: _search,\n hash: _hash,\n state: _state,\n mask: _mask,\n reloadDocument: _reloadDocument,\n unsafeRelative: _unsafeRelative,\n from: _from,\n _fromLocation,\n ...propsSafeToSpread\n } = options\n\n // subscribe to search params to re-build location if it changes\n const currentSearch = useRouterState({\n select: (s) => s.location.search,\n structuralSharing: true as any,\n })\n\n const from = options.from\n\n const _options = React.useMemo(\n () => {\n return { ...options, from }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n router,\n currentSearch,\n from,\n options._fromLocation,\n options.hash,\n options.to,\n options.search,\n options.params,\n options.state,\n options.mask,\n options.unsafeRelative,\n ],\n )\n\n const next = React.useMemo(\n () => router.buildLocation({ ..._options } as any),\n [router, _options],\n )\n\n const hrefOption = React.useMemo(() => {\n if (disabled) {\n return undefined\n }\n let href = next.maskedLocation\n ? next.maskedLocation.url.href\n : next.url.href\n\n let external = false\n if (router.origin) {\n if (href.startsWith(router.origin)) {\n href = router.history.createHref(href.replace(router.origin, '')) || '/'\n } else {\n external = true\n }\n }\n return { href, external }\n }, [disabled, next.maskedLocation, next.url, router.origin, router.history])\n\n const externalLink = React.useMemo(() => {\n if (hrefOption?.external) {\n // Block dangerous protocols for external links\n if (isDangerousProtocol(hrefOption.href)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `Blocked Link with dangerous protocol: ${hrefOption.href}`,\n )\n }\n return undefined\n }\n return hrefOption.href\n }\n const isSafeInternal =\n typeof to === 'string' &&\n to.charCodeAt(0) === 47 && // '/'\n to.charCodeAt(1) !== 47 // but not '//'\n if (isSafeInternal) return undefined\n try {\n new URL(to as any)\n // Block dangerous protocols like javascript:, data:, vbscript:\n if (isDangerousProtocol(to as string)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`Blocked Link with dangerous protocol: ${to}`)\n }\n return undefined\n }\n return to\n } catch {}\n return undefined\n }, [to, hrefOption])\n\n const preload =\n options.reloadDocument || externalLink\n ? false\n : (userPreload ?? router.options.defaultPreload)\n const preloadDelay =\n userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0\n\n const isActive = useRouterState({\n select: (s) => {\n if (externalLink) return false\n if (activeOptions?.exact) {\n const testExact = exactPathTest(\n s.location.pathname,\n next.pathname,\n router.basepath,\n )\n if (!testExact) {\n return false\n }\n } else {\n const currentPathSplit = removeTrailingSlash(\n s.location.pathname,\n router.basepath,\n )\n const nextPathSplit = removeTrailingSlash(\n next.pathname,\n router.basepath,\n )\n\n const pathIsFuzzyEqual =\n currentPathSplit.startsWith(nextPathSplit) &&\n (currentPathSplit.length === nextPathSplit.length ||\n currentPathSplit[nextPathSplit.length] === '/')\n\n if (!pathIsFuzzyEqual) {\n return false\n }\n }\n\n if (activeOptions?.includeSearch ?? true) {\n const searchTest = deepEqual(s.location.search, next.search, {\n partial: !activeOptions?.exact,\n ignoreUndefined: !activeOptions?.explicitUndefined,\n })\n if (!searchTest) {\n return false\n }\n }\n\n if (activeOptions?.includeHash) {\n return isHydrated && s.location.hash === next.hash\n }\n return true\n },\n })\n\n const doPreload = React.useCallback(() => {\n router.preloadRoute({ ..._options } as any).catch((err) => {\n console.warn(err)\n console.warn(preloadWarning)\n })\n }, [router, _options])\n\n const preloadViewportIoCallback = React.useCallback(\n (entry: IntersectionObserverEntry | undefined) => {\n if (entry?.isIntersecting) {\n doPreload()\n }\n },\n [doPreload],\n )\n\n useIntersectionObserver(\n innerRef,\n preloadViewportIoCallback,\n intersectionObserverOptions,\n { disabled: !!disabled || !(preload === 'viewport') },\n )\n\n React.useEffect(() => {\n if (hasRenderFetched.current) {\n return\n }\n if (!disabled && preload === 'render') {\n doPreload()\n hasRenderFetched.current = true\n }\n }, [disabled, doPreload, preload])\n\n // The click handler\n const handleClick = (e: React.MouseEvent) => {\n // Check actual element's target attribute as fallback\n const elementTarget = (\n e.currentTarget as HTMLAnchorElement | SVGAElement\n ).getAttribute('target')\n const effectiveTarget = target !== undefined ? target : elementTarget\n\n if (\n !disabled &&\n !isCtrlEvent(e) &&\n !e.defaultPrevented &&\n (!effectiveTarget || effectiveTarget === '_self') &&\n e.button === 0\n ) {\n e.preventDefault()\n\n flushSync(() => {\n setIsTransitioning(true)\n })\n\n const unsub = router.subscribe('onResolved', () => {\n unsub()\n setIsTransitioning(false)\n })\n\n // All is well? Navigate!\n // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing\n router.navigate({\n ..._options,\n replace,\n resetScroll,\n hashScrollIntoView,\n startTransition,\n viewTransition,\n ignoreBlocker,\n })\n }\n }\n\n if (externalLink) {\n return {\n ...propsSafeToSpread,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n href: externalLink,\n ...(children && { children }),\n ...(target && { target }),\n ...(disabled && { disabled }),\n ...(style && { style }),\n ...(className && { className }),\n ...(onClick && { onClick }),\n ...(onFocus && { onFocus }),\n ...(onMouseEnter && { onMouseEnter }),\n ...(onMouseLeave && { onMouseLeave }),\n ...(onTouchStart && { onTouchStart }),\n }\n }\n\n // The click handler\n const handleFocus = (_: React.MouseEvent) => {\n if (disabled) return\n if (preload) {\n doPreload()\n }\n }\n\n const handleTouchStart = handleFocus\n\n const handleEnter = (e: React.MouseEvent) => {\n if (disabled || !preload) return\n\n if (!preloadDelay) {\n doPreload()\n } else {\n const eventTarget = e.target\n if (timeoutMap.has(eventTarget)) {\n return\n }\n const id = setTimeout(() => {\n timeoutMap.delete(eventTarget)\n doPreload()\n }, preloadDelay)\n timeoutMap.set(eventTarget, id)\n }\n }\n\n const handleLeave = (e: React.MouseEvent) => {\n if (disabled || !preload || !preloadDelay) return\n const eventTarget = e.target\n const id = timeoutMap.get(eventTarget)\n if (id) {\n clearTimeout(id)\n timeoutMap.delete(eventTarget)\n }\n }\n\n // Get the active props\n const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive\n ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT)\n : STATIC_EMPTY_OBJECT\n\n // Get the inactive props\n const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =\n isActive\n ? STATIC_EMPTY_OBJECT\n : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT)\n\n const resolvedClassName = [\n className,\n resolvedActiveProps.className,\n resolvedInactiveProps.className,\n ]\n .filter(Boolean)\n .join(' ')\n\n const resolvedStyle = (style ||\n resolvedActiveProps.style ||\n resolvedInactiveProps.style) && {\n ...style,\n ...resolvedActiveProps.style,\n ...resolvedInactiveProps.style,\n }\n\n return {\n ...propsSafeToSpread,\n ...resolvedActiveProps,\n ...resolvedInactiveProps,\n href: hrefOption?.href,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n onClick: composeHandlers([onClick, handleClick]),\n onFocus: composeHandlers([onFocus, handleFocus]),\n onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),\n onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),\n onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),\n disabled: !!disabled,\n target,\n ...(resolvedStyle && { style: resolvedStyle }),\n ...(resolvedClassName && { className: resolvedClassName }),\n ...(disabled && STATIC_DISABLED_PROPS),\n ...(isActive && STATIC_ACTIVE_PROPS),\n ...(isTransitioning && STATIC_TRANSITIONING_PROPS),\n }\n}\n\nconst STATIC_EMPTY_OBJECT = {}\nconst STATIC_ACTIVE_OBJECT = { className: 'active' }\nconst STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true }\nconst STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' }\nconst STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' }\n\nconst timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>()\n\nconst intersectionObserverOptions: IntersectionObserverInit = {\n rootMargin: '100px',\n}\n\nconst composeHandlers =\n (handlers: Array<undefined | React.EventHandler<any>>) =>\n (e: React.SyntheticEvent) => {\n for (const handler of handlers) {\n if (!handler) continue\n if (e.defaultPrevented) return\n handler(e)\n }\n }\n\ntype UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements\n ? React.JSX.IntrinsicElements[TComp]\n : TComp extends React.ComponentType<any>\n ? React.ComponentPropsWithoutRef<TComp> &\n React.RefAttributes<React.ComponentRef<TComp>>\n : never\n\nexport type UseLinkPropsOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n UseLinkReactProps<'a'>\n\nexport type ActiveLinkOptions<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n ActiveLinkOptionProps<TComp>\n\ntype ActiveLinkProps<TComp> = Partial<\n LinkComponentReactProps<TComp> & {\n [key: `data-${string}`]: unknown\n }\n>\n\nexport interface ActiveLinkOptionProps<TComp = 'a'> {\n /**\n * A function that returns additional props for the `active` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n /**\n * A function that returns additional props for the `inactive` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n}\n\nexport type LinkProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n LinkPropsChildren\n\nexport interface LinkPropsChildren {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | React.ReactNode\n | ((state: {\n isActive: boolean\n isTransitioning: boolean\n }) => React.ReactNode)\n}\n\ntype LinkComponentReactProps<TComp> = Omit<\n UseLinkReactProps<TComp>,\n keyof CreateLinkProps\n>\n\nexport type LinkComponentProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkComponentReactProps<TComp> &\n LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type CreateLinkProps = LinkProps<\n any,\n any,\n string,\n string,\n string,\n string\n>\n\nexport type LinkComponent<\n in out TComp,\n in out TDefaultFrom extends string = string,\n> = <\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = TDefaultFrom,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n) => React.ReactElement\n\nexport interface LinkComponentRoute<\n in out TDefaultFrom extends string = string,\n> {\n defaultFrom: TDefaultFrom;\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n props: LinkComponentProps<\n 'a',\n TRouter,\n this['defaultFrom'],\n TTo,\n this['defaultFrom'],\n TMaskTo\n >,\n ): React.ReactElement\n}\n\n/**\n * Creates a typed Link-like component that preserves TanStack Router's\n * navigation semantics and type-safety while delegating rendering to the\n * provided host component.\n *\n * Useful for integrating design system anchors/buttons while keeping\n * router-aware props (eg. `to`, `params`, `search`, `preload`).\n *\n * @param Comp The host component to render (eg. a design-system Link/Button)\n * @returns A router-aware component with the same API as `Link`.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link\n */\nexport function createLink<const TComp>(\n Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,\n): LinkComponent<TComp> {\n return React.forwardRef(function CreatedLink(props, ref) {\n return <Link {...(props as any)} _asChild={Comp} ref={ref} />\n }) as any\n}\n\n/**\n * A strongly-typed anchor component for declarative navigation.\n * Handles path, search, hash and state updates with optional route preloading\n * and active-state styling.\n *\n * Props:\n * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)\n * - `preloadDelay`: Delay in ms before preloading on hover\n * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive\n * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation\n * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation\n * - `ignoreBlocker`: Bypass registered blockers\n *\n * @returns An anchor-like element that navigates without full page reloads.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent\n */\nexport const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(\n (props, ref) => {\n const { _asChild, ...rest } = props\n const { type: _type, ...linkProps } = useLinkProps(rest as any, ref)\n\n const children =\n typeof rest.children === 'function'\n ? rest.children({\n isActive: (linkProps as any)['data-status'] === 'active',\n })\n : rest.children\n\n if (!_asChild) {\n // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop\n // @ts-expect-error\n const { disabled: _, ...rest } = linkProps\n return React.createElement('a', rest, children)\n }\n return React.createElement(_asChild, linkProps, children)\n },\n) as any\n\nfunction isCtrlEvent(e: React.MouseEvent) {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)\n}\n\nexport type LinkOptionsFnOptions<\n TOptions,\n TComp,\n TRouter extends AnyRouter = RegisteredRouter,\n> =\n TOptions extends ReadonlyArray<any>\n ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>\n : ValidateLinkOptions<TRouter, TOptions, string, TComp>\n\nexport type LinkOptionsFn<TComp> = <\n const TOptions,\n TRouter extends AnyRouter = RegisteredRouter,\n>(\n options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,\n) => TOptions\n\n/**\n * Validate and reuse navigation options for `Link`, `navigate` or `redirect`.\n * Accepts a literal options object and returns it typed for later spreading.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\nexport const linkOptions: LinkOptionsFn<'a'> = (options) => {\n return options as any\n}\n\n/**\n * Type-check a literal object for use with `Link`, `navigate` or `redirect`.\n * Use to validate and reuse navigation options across your app.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\n"],"names":["rest"],"mappings":";;;;;;;;AAyCO,SAAS,aAOd,SACA,cACkC;AAClC,QAAM,SAAS,UAAA;AACf,QAAM,CAAC,iBAAiB,kBAAkB,IAAI,MAAM,SAAS,KAAK;AAClE,QAAM,mBAAmB,MAAM,OAAO,KAAK;AAC3C,QAAM,WAAW,gBAAgB,YAAY;AAC7C,QAAM,aAAa,YAAA;AAEnB,QAAM;AAAA;AAAA,IAEJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,IACN,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,MAAM;AAAA,IACN;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAGJ,QAAM,gBAAgB,eAAe;AAAA,IACnC,QAAQ,CAAC,MAAM,EAAE,SAAS;AAAA,IAC1B,mBAAmB;AAAA,EAAA,CACpB;AAED,QAAM,OAAO,QAAQ;AAErB,QAAM,WAAW,MAAM;AAAA,IACrB,MAAM;AACJ,aAAO,EAAE,GAAG,SAAS,KAAA;AAA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,aAAW,WAAW,UAAU;AAC9B,QAAI,CAAC,QAAS;AACd,QAAI,EAAE,iBAAkB;AACxB,YAAQ,CAAC;AAAA,EACX;AACF;AAwIK,SAAS,WACd,MACsB;AACtB,SAAO,MAAM,WAAW,SAAS,YAAY,OAAO,KAAK;AACvD,+BAAQ,MAAA,EAAM,GAAI,OAAe,UAAU,MAAM,KAAU;AAAA,EAC7D,CAAC;AACH;AAkBO,MAAM,OAA2B,MAAM;AAAA,EAC5C,CAAC,OAAO,QAAQ;AACd,UAAM,EAAE,UAAU,GAAG,KAAA,IAAS;AAC9B,UAAM,EAAE,MAAM,OAAO,GAAG,cAAc,aAAa,MAAa,GAAG;AAEnE,UAAM,WACJ,OAAO,KAAK,aAAa,aACrB,KAAK,SAAS;AAAA,MACZ,UAAW,UAAkB,aAAa,MAAM;AAAA,IAAA,CACjD,IACD,KAAK;AAEX,QAAI,CAAC,UAAU;AAGb,YAAM,EAAE,UAAU,GAAG,GAAGA,UAAS;AACjC,aAAO,MAAM,cAAc,KAAKA,OAAM,QAAQ;AAAA,IAChD;AACA,WAAO,MAAM,cAAc,UAAU,WAAW,QAAQ;AAAA,EAC1D;AACF;AAEA,SAAS,YAAY,GAAqB;AACxC,SAAO,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE;AACpD;AAyBO,MAAM,cAAkC,CAAC,YAAY;AAC1D,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"link.js","sources":["../../src/link.tsx"],"sourcesContent":["import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n deepEqual,\n exactPathTest,\n functionalUpdate,\n isDangerousProtocol,\n preloadWarning,\n removeTrailingSlash,\n} from '@tanstack/router-core'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\n\nimport { useForwardedRef, useIntersectionObserver } from './utils'\n\nimport { useHydrated } from './ClientOnly'\nimport type {\n AnyRouter,\n Constrain,\n LinkOptions,\n RegisteredRouter,\n RoutePaths,\n} from '@tanstack/router-core'\nimport type { ReactNode } from 'react'\nimport type {\n ValidateLinkOptions,\n ValidateLinkOptionsArray,\n} from './typePrimitives'\n\n/**\n * Build anchor-like props for declarative navigation and preloading.\n *\n * Returns stable `href`, event handlers and accessibility props derived from\n * router options and active state. Used internally by `Link` and custom links.\n *\n * Options cover `to`, `params`, `search`, `hash`, `state`, `preload`,\n * `activeProps`, `inactiveProps`, and more.\n *\n * @returns React anchor props suitable for `<a>` or custom components.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook\n */\nexport function useLinkProps<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = string,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n forwardedRef?: React.ForwardedRef<Element>,\n): React.ComponentPropsWithRef<'a'> {\n const router = useRouter()\n const [isTransitioning, setIsTransitioning] = React.useState(false)\n const hasRenderFetched = React.useRef(false)\n const innerRef = useForwardedRef(forwardedRef)\n const isHydrated = useHydrated()\n\n const {\n // custom props\n activeProps,\n inactiveProps,\n activeOptions,\n to,\n preload: userPreload,\n preloadDelay: userPreloadDelay,\n hashScrollIntoView,\n replace,\n startTransition,\n resetScroll,\n viewTransition,\n // element props\n children,\n target,\n disabled,\n style,\n className,\n onClick,\n onFocus,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n ignoreBlocker,\n // prevent these from being returned\n params: _params,\n search: _search,\n hash: _hash,\n state: _state,\n mask: _mask,\n reloadDocument: _reloadDocument,\n unsafeRelative: _unsafeRelative,\n from: _from,\n _fromLocation,\n ...propsSafeToSpread\n } = options\n\n // subscribe to search params to re-build location if it changes\n const currentSearch = useRouterState({\n select: (s) => s.location.search,\n structuralSharing: true as any,\n })\n\n const from = options.from\n\n const _options = React.useMemo(\n () => {\n return { ...options, from }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n router,\n currentSearch,\n from,\n options._fromLocation,\n options.hash,\n options.to,\n options.search,\n options.params,\n options.state,\n options.mask,\n options.unsafeRelative,\n ],\n )\n\n const next = React.useMemo(\n () => router.buildLocation({ ..._options } as any),\n [router, _options],\n )\n\n // Use publicHref - it contains the correct href for display\n // When a rewrite changes the origin, publicHref is the full URL\n // Otherwise it's the origin-stripped path\n // This avoids constructing URL objects in the hot path\n const hrefOptionPublicHref = next.maskedLocation\n ? next.maskedLocation.publicHref\n : next.publicHref\n const hrefOptionExternal = next.maskedLocation\n ? next.maskedLocation.external\n : next.external\n const hrefOption = React.useMemo(() => {\n if (disabled) return undefined\n\n // Full URL means rewrite changed the origin - treat as external-like\n if (hrefOptionExternal) {\n return { href: hrefOptionPublicHref, external: true }\n }\n\n return {\n href: router.history.createHref(hrefOptionPublicHref) || '/',\n external: false,\n }\n }, [disabled, hrefOptionExternal, hrefOptionPublicHref, router.history])\n\n const externalLink = React.useMemo(() => {\n if (hrefOption?.external) {\n // Block dangerous protocols for external links\n if (isDangerousProtocol(hrefOption.href)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `Blocked Link with dangerous protocol: ${hrefOption.href}`,\n )\n }\n return undefined\n }\n return hrefOption.href\n }\n const isSafeInternal =\n typeof to === 'string' &&\n to.charCodeAt(0) === 47 && // '/'\n to.charCodeAt(1) !== 47 // but not '//'\n if (isSafeInternal) return undefined\n try {\n new URL(to as any)\n // Block dangerous protocols like javascript:, data:, vbscript:\n if (isDangerousProtocol(to as string)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`Blocked Link with dangerous protocol: ${to}`)\n }\n return undefined\n }\n return to\n } catch {}\n return undefined\n }, [to, hrefOption])\n\n const preload =\n options.reloadDocument || externalLink\n ? false\n : (userPreload ?? router.options.defaultPreload)\n const preloadDelay =\n userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0\n\n const isActive = useRouterState({\n select: (s) => {\n if (externalLink) return false\n if (activeOptions?.exact) {\n const testExact = exactPathTest(\n s.location.pathname,\n next.pathname,\n router.basepath,\n )\n if (!testExact) {\n return false\n }\n } else {\n const currentPathSplit = removeTrailingSlash(\n s.location.pathname,\n router.basepath,\n )\n const nextPathSplit = removeTrailingSlash(\n next.pathname,\n router.basepath,\n )\n\n const pathIsFuzzyEqual =\n currentPathSplit.startsWith(nextPathSplit) &&\n (currentPathSplit.length === nextPathSplit.length ||\n currentPathSplit[nextPathSplit.length] === '/')\n\n if (!pathIsFuzzyEqual) {\n return false\n }\n }\n\n if (activeOptions?.includeSearch ?? true) {\n const searchTest = deepEqual(s.location.search, next.search, {\n partial: !activeOptions?.exact,\n ignoreUndefined: !activeOptions?.explicitUndefined,\n })\n if (!searchTest) {\n return false\n }\n }\n\n if (activeOptions?.includeHash) {\n return isHydrated && s.location.hash === next.hash\n }\n return true\n },\n })\n\n const doPreload = React.useCallback(() => {\n router.preloadRoute({ ..._options } as any).catch((err) => {\n console.warn(err)\n console.warn(preloadWarning)\n })\n }, [router, _options])\n\n const preloadViewportIoCallback = React.useCallback(\n (entry: IntersectionObserverEntry | undefined) => {\n if (entry?.isIntersecting) {\n doPreload()\n }\n },\n [doPreload],\n )\n\n useIntersectionObserver(\n innerRef,\n preloadViewportIoCallback,\n intersectionObserverOptions,\n { disabled: !!disabled || !(preload === 'viewport') },\n )\n\n React.useEffect(() => {\n if (hasRenderFetched.current) {\n return\n }\n if (!disabled && preload === 'render') {\n doPreload()\n hasRenderFetched.current = true\n }\n }, [disabled, doPreload, preload])\n\n // The click handler\n const handleClick = (e: React.MouseEvent) => {\n // Check actual element's target attribute as fallback\n const elementTarget = (\n e.currentTarget as HTMLAnchorElement | SVGAElement\n ).getAttribute('target')\n const effectiveTarget = target !== undefined ? target : elementTarget\n\n if (\n !disabled &&\n !isCtrlEvent(e) &&\n !e.defaultPrevented &&\n (!effectiveTarget || effectiveTarget === '_self') &&\n e.button === 0\n ) {\n e.preventDefault()\n\n flushSync(() => {\n setIsTransitioning(true)\n })\n\n const unsub = router.subscribe('onResolved', () => {\n unsub()\n setIsTransitioning(false)\n })\n\n // All is well? Navigate!\n // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing\n router.navigate({\n ..._options,\n replace,\n resetScroll,\n hashScrollIntoView,\n startTransition,\n viewTransition,\n ignoreBlocker,\n })\n }\n }\n\n if (externalLink) {\n return {\n ...propsSafeToSpread,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n href: externalLink,\n ...(children && { children }),\n ...(target && { target }),\n ...(disabled && { disabled }),\n ...(style && { style }),\n ...(className && { className }),\n ...(onClick && { onClick }),\n ...(onFocus && { onFocus }),\n ...(onMouseEnter && { onMouseEnter }),\n ...(onMouseLeave && { onMouseLeave }),\n ...(onTouchStart && { onTouchStart }),\n }\n }\n\n // The click handler\n const handleFocus = (_: React.MouseEvent) => {\n if (disabled) return\n if (preload) {\n doPreload()\n }\n }\n\n const handleTouchStart = handleFocus\n\n const handleEnter = (e: React.MouseEvent) => {\n if (disabled || !preload) return\n\n if (!preloadDelay) {\n doPreload()\n } else {\n const eventTarget = e.target\n if (timeoutMap.has(eventTarget)) {\n return\n }\n const id = setTimeout(() => {\n timeoutMap.delete(eventTarget)\n doPreload()\n }, preloadDelay)\n timeoutMap.set(eventTarget, id)\n }\n }\n\n const handleLeave = (e: React.MouseEvent) => {\n if (disabled || !preload || !preloadDelay) return\n const eventTarget = e.target\n const id = timeoutMap.get(eventTarget)\n if (id) {\n clearTimeout(id)\n timeoutMap.delete(eventTarget)\n }\n }\n\n // Get the active props\n const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive\n ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT)\n : STATIC_EMPTY_OBJECT\n\n // Get the inactive props\n const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =\n isActive\n ? STATIC_EMPTY_OBJECT\n : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT)\n\n const resolvedClassName = [\n className,\n resolvedActiveProps.className,\n resolvedInactiveProps.className,\n ]\n .filter(Boolean)\n .join(' ')\n\n const resolvedStyle = (style ||\n resolvedActiveProps.style ||\n resolvedInactiveProps.style) && {\n ...style,\n ...resolvedActiveProps.style,\n ...resolvedInactiveProps.style,\n }\n\n return {\n ...propsSafeToSpread,\n ...resolvedActiveProps,\n ...resolvedInactiveProps,\n href: hrefOption?.href,\n ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],\n onClick: composeHandlers([onClick, handleClick]),\n onFocus: composeHandlers([onFocus, handleFocus]),\n onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),\n onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),\n onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),\n disabled: !!disabled,\n target,\n ...(resolvedStyle && { style: resolvedStyle }),\n ...(resolvedClassName && { className: resolvedClassName }),\n ...(disabled && STATIC_DISABLED_PROPS),\n ...(isActive && STATIC_ACTIVE_PROPS),\n ...(isTransitioning && STATIC_TRANSITIONING_PROPS),\n }\n}\n\nconst STATIC_EMPTY_OBJECT = {}\nconst STATIC_ACTIVE_OBJECT = { className: 'active' }\nconst STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true }\nconst STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' }\nconst STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' }\n\nconst timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>()\n\nconst intersectionObserverOptions: IntersectionObserverInit = {\n rootMargin: '100px',\n}\n\nconst composeHandlers =\n (handlers: Array<undefined | React.EventHandler<any>>) =>\n (e: React.SyntheticEvent) => {\n for (const handler of handlers) {\n if (!handler) continue\n if (e.defaultPrevented) return\n handler(e)\n }\n }\n\ntype UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements\n ? React.JSX.IntrinsicElements[TComp]\n : TComp extends React.ComponentType<any>\n ? React.ComponentPropsWithoutRef<TComp> &\n React.RefAttributes<React.ComponentRef<TComp>>\n : never\n\nexport type UseLinkPropsOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n UseLinkReactProps<'a'>\n\nexport type ActiveLinkOptions<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n ActiveLinkOptionProps<TComp>\n\ntype ActiveLinkProps<TComp> = Partial<\n LinkComponentReactProps<TComp> & {\n [key: `data-${string}`]: unknown\n }\n>\n\nexport interface ActiveLinkOptionProps<TComp = 'a'> {\n /**\n * A function that returns additional props for the `active` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n /**\n * A function that returns additional props for the `inactive` state of this link.\n * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)\n */\n inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)\n}\n\nexport type LinkProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &\n LinkPropsChildren\n\nexport interface LinkPropsChildren {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | React.ReactNode\n | ((state: {\n isActive: boolean\n isTransitioning: boolean\n }) => React.ReactNode)\n}\n\ntype LinkComponentReactProps<TComp> = Omit<\n UseLinkReactProps<TComp>,\n keyof CreateLinkProps\n>\n\nexport type LinkComponentProps<\n TComp = 'a',\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = '.',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = LinkComponentReactProps<TComp> &\n LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type CreateLinkProps = LinkProps<\n any,\n any,\n string,\n string,\n string,\n string\n>\n\nexport type LinkComponent<\n in out TComp,\n in out TDefaultFrom extends string = string,\n> = <\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string = TDefaultFrom,\n const TTo extends string | undefined = undefined,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n) => React.ReactElement\n\nexport interface LinkComponentRoute<\n in out TDefaultFrom extends string = string,\n> {\n defaultFrom: TDefaultFrom;\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n props: LinkComponentProps<\n 'a',\n TRouter,\n this['defaultFrom'],\n TTo,\n this['defaultFrom'],\n TMaskTo\n >,\n ): React.ReactElement\n}\n\n/**\n * Creates a typed Link-like component that preserves TanStack Router's\n * navigation semantics and type-safety while delegating rendering to the\n * provided host component.\n *\n * Useful for integrating design system anchors/buttons while keeping\n * router-aware props (eg. `to`, `params`, `search`, `preload`).\n *\n * @param Comp The host component to render (eg. a design-system Link/Button)\n * @returns A router-aware component with the same API as `Link`.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link\n */\nexport function createLink<const TComp>(\n Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,\n): LinkComponent<TComp> {\n return React.forwardRef(function CreatedLink(props, ref) {\n return <Link {...(props as any)} _asChild={Comp} ref={ref} />\n }) as any\n}\n\n/**\n * A strongly-typed anchor component for declarative navigation.\n * Handles path, search, hash and state updates with optional route preloading\n * and active-state styling.\n *\n * Props:\n * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)\n * - `preloadDelay`: Delay in ms before preloading on hover\n * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive\n * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation\n * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation\n * - `ignoreBlocker`: Bypass registered blockers\n *\n * @returns An anchor-like element that navigates without full page reloads.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent\n */\nexport const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(\n (props, ref) => {\n const { _asChild, ...rest } = props\n const { type: _type, ...linkProps } = useLinkProps(rest as any, ref)\n\n const children =\n typeof rest.children === 'function'\n ? rest.children({\n isActive: (linkProps as any)['data-status'] === 'active',\n })\n : rest.children\n\n if (!_asChild) {\n // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop\n // @ts-expect-error\n const { disabled: _, ...rest } = linkProps\n return React.createElement('a', rest, children)\n }\n return React.createElement(_asChild, linkProps, children)\n },\n) as any\n\nfunction isCtrlEvent(e: React.MouseEvent) {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)\n}\n\nexport type LinkOptionsFnOptions<\n TOptions,\n TComp,\n TRouter extends AnyRouter = RegisteredRouter,\n> =\n TOptions extends ReadonlyArray<any>\n ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>\n : ValidateLinkOptions<TRouter, TOptions, string, TComp>\n\nexport type LinkOptionsFn<TComp> = <\n const TOptions,\n TRouter extends AnyRouter = RegisteredRouter,\n>(\n options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,\n) => TOptions\n\n/**\n * Validate and reuse navigation options for `Link`, `navigate` or `redirect`.\n * Accepts a literal options object and returns it typed for later spreading.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\nexport const linkOptions: LinkOptionsFn<'a'> = (options) => {\n return options as any\n}\n\n/**\n * Type-check a literal object for use with `Link`, `navigate` or `redirect`.\n * Use to validate and reuse navigation options across your app.\n * @example\n * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions\n */\n"],"names":["rest"],"mappings":";;;;;;;;AAyCO,SAAS,aAOd,SACA,cACkC;AAClC,QAAM,SAAS,UAAA;AACf,QAAM,CAAC,iBAAiB,kBAAkB,IAAI,MAAM,SAAS,KAAK;AAClE,QAAM,mBAAmB,MAAM,OAAO,KAAK;AAC3C,QAAM,WAAW,gBAAgB,YAAY;AAC7C,QAAM,aAAa,YAAA;AAEnB,QAAM;AAAA;AAAA,IAEJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAEA,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,IACN,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,MAAM;AAAA,IACN;AAAA,IACA,GAAG;AAAA,EAAA,IACD;AAGJ,QAAM,gBAAgB,eAAe;AAAA,IACnC,QAAQ,CAAC,MAAM,EAAE,SAAS;AAAA,IAC1B,mBAAmB;AAAA,EAAA,CACpB;AAED,QAAM,OAAO,QAAQ;AAErB,QAAM,WAAW,MAAM;AAAA,IACrB,MAAM;AACJ,aAAO,EAAE,GAAG,SAAS,KAAA;AAAA,IACvB;AAAA;AAAA,IAEA;AAAA,MACE;AAAA,MACA;AAAA,MACA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WACd,MACsB;AACtB,SAAO,MAAM,WAAW,SAAS,YAAY,OAAO,KAAK;AACvD,+BAAQ,MAAA,EAAM,GAAI,OAAe,UAAU,MAAM,KAAU;AAAA,EAC7D,CAAC;AACH;AAkBO,MAAM,OAA2B,MAAM;AAAA,EAC5C,CAAC,OAAO,QAAQ;AACd,UAAM,EAAE,UAAU,GAAG,KAAA,IAAS;AAC9B,UAAM,EAAE,MAAM,OAAO,GAAG,cAAc,aAAa,MAAa,GAAG;AAEnE,UAAM,WACJ,OAAO,KAAK,aAAa,aACrB,KAAK,SAAS;AAAA,MACZ,UAAW,UAAkB,aAAa,MAAM;AAAA,IAAA,CACjD,IACD,KAAK;AAEX,QAAI,CAAC,UAAU;AAGb,YAAM,EAAE,UAAU,GAAG,GAAGA,UAAS;AACjC,aAAO,MAAM,cAAc,KAAKA,OAAM,QAAQ;AAAA,IAChD;AACA,WAAO,MAAM,cAAc,UAAU,WAAW,QAAQ;AAAA,EAC1D;AACF;AAEA,SAAS,YAAY,GAAqB;AACxC,SAAO,CAAC,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE;AACpD;AAyBO,MAAM,cAAkC,CAAC,YAAY;AAC1D,SAAO;AACT;"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { jsx } from "react/jsx-runtime";
|
|
2
|
-
import { defaultGetScrollRestorationKey, restoreScroll, escapeHtml, storageKey } from "@tanstack/router-core";
|
|
2
|
+
import { isServer, defaultGetScrollRestorationKey, restoreScroll, escapeHtml, storageKey } from "@tanstack/router-core";
|
|
3
3
|
import { useRouter } from "./useRouter.js";
|
|
4
4
|
import { ScriptOnce } from "./ScriptOnce.js";
|
|
5
5
|
function ScrollRestoration() {
|
|
6
6
|
const router = useRouter();
|
|
7
|
-
if (!router.isScrollRestoring || !router.isServer) {
|
|
7
|
+
if (!router.isScrollRestoring || !(isServer ?? router.isServer)) {
|
|
8
8
|
return null;
|
|
9
9
|
}
|
|
10
10
|
if (typeof router.options.scrollRestoration === "function") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scroll-restoration.js","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import {\n defaultGetScrollRestorationKey,\n escapeHtml,\n restoreScroll,\n storageKey,\n} from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\n\nexport function ScrollRestoration() {\n const router = useRouter()\n if (!router.isScrollRestoring || !router.isServer) {\n return null\n }\n if (typeof router.options.scrollRestoration === 'function') {\n const shouldRestore = router.options.scrollRestoration({\n location: router.latestLocation,\n })\n if (!shouldRestore) {\n return null\n }\n }\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n const userKey = getKey(router.latestLocation)\n const resolvedKey =\n userKey !== defaultGetScrollRestorationKey(router.latestLocation)\n ? userKey\n : undefined\n\n const restoreScrollOptions: Parameters<typeof restoreScroll>[0] = {\n storageKey,\n shouldScrollRestoration: true,\n }\n if (resolvedKey) {\n restoreScrollOptions.key = resolvedKey\n }\n\n return (\n <ScriptOnce\n children={`(${restoreScroll.toString()})(${escapeHtml(JSON.stringify(restoreScrollOptions))})`}\n />\n )\n}\n"],"names":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"scroll-restoration.js","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import {\n defaultGetScrollRestorationKey,\n escapeHtml,\n isServer,\n restoreScroll,\n storageKey,\n} from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\n\nexport function ScrollRestoration() {\n const router = useRouter()\n if (!router.isScrollRestoring || !(isServer ?? router.isServer)) {\n return null\n }\n if (typeof router.options.scrollRestoration === 'function') {\n const shouldRestore = router.options.scrollRestoration({\n location: router.latestLocation,\n })\n if (!shouldRestore) {\n return null\n }\n }\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n const userKey = getKey(router.latestLocation)\n const resolvedKey =\n userKey !== defaultGetScrollRestorationKey(router.latestLocation)\n ? userKey\n : undefined\n\n const restoreScrollOptions: Parameters<typeof restoreScroll>[0] = {\n storageKey,\n shouldScrollRestoration: true,\n }\n if (resolvedKey) {\n restoreScrollOptions.key = resolvedKey\n }\n\n return (\n <ScriptOnce\n children={`(${restoreScroll.toString()})(${escapeHtml(JSON.stringify(restoreScrollOptions))})`}\n />\n )\n}\n"],"names":[],"mappings":";;;;AAUO,SAAS,oBAAoB;AAClC,QAAM,SAAS,UAAA;AACf,MAAI,CAAC,OAAO,qBAAqB,EAAE,YAAY,OAAO,WAAW;AAC/D,WAAO;AAAA,EACT;AACA,MAAI,OAAO,OAAO,QAAQ,sBAAsB,YAAY;AAC1D,UAAM,gBAAgB,OAAO,QAAQ,kBAAkB;AAAA,MACrD,UAAU,OAAO;AAAA,IAAA,CAClB;AACD,QAAI,CAAC,eAAe;AAClB,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,SACJ,OAAO,QAAQ,2BAA2B;AAC5C,QAAM,UAAU,OAAO,OAAO,cAAc;AAC5C,QAAM,cACJ,YAAY,+BAA+B,OAAO,cAAc,IAC5D,UACA;AAEN,QAAM,uBAA4D;AAAA,IAChE;AAAA,IACA,yBAAyB;AAAA,EAAA;AAE3B,MAAI,aAAa;AACf,yBAAqB,MAAM;AAAA,EAC7B;AAEA,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,UAAU,IAAI,cAAc,SAAA,CAAU,KAAK,WAAW,KAAK,UAAU,oBAAoB,CAAC,CAAC;AAAA,IAAA;AAAA,EAAA;AAGjG;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/react-router",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.157.1",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
"tiny-invariant": "^1.3.3",
|
|
83
83
|
"tiny-warning": "^1.0.3",
|
|
84
84
|
"@tanstack/history": "1.154.14",
|
|
85
|
-
"@tanstack/router-core": "1.
|
|
85
|
+
"@tanstack/router-core": "1.157.1"
|
|
86
86
|
},
|
|
87
87
|
"devDependencies": {
|
|
88
88
|
"@testing-library/jest-dom": "^6.6.3",
|
package/src/Asset.tsx
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as React from 'react'
|
|
2
|
+
import { isServer } from '@tanstack/router-core'
|
|
2
3
|
import { useRouter } from './useRouter'
|
|
3
4
|
import type { RouterManagedTag } from '@tanstack/router-core'
|
|
4
5
|
|
|
@@ -143,7 +144,7 @@ function Script({
|
|
|
143
144
|
return undefined
|
|
144
145
|
}, [attrs, children])
|
|
145
146
|
|
|
146
|
-
if (!router.isServer) {
|
|
147
|
+
if (!(isServer ?? router.isServer)) {
|
|
147
148
|
const { src, ...rest } = attrs || {}
|
|
148
149
|
// render an empty script on the client just to avoid hydration errors
|
|
149
150
|
return (
|
package/src/Match.tsx
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
getLocationChangeInfo,
|
|
7
7
|
isNotFound,
|
|
8
8
|
isRedirect,
|
|
9
|
+
isServer,
|
|
9
10
|
rootRouteId,
|
|
10
11
|
} from '@tanstack/router-core'
|
|
11
12
|
import { CatchBoundary, ErrorComponent } from './CatchBoundary'
|
|
@@ -246,7 +247,7 @@ export const MatchInner = React.memo(function MatchInnerImpl({
|
|
|
246
247
|
const routerMatch = router.getMatch(match.id)
|
|
247
248
|
if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
|
|
248
249
|
// Create a promise that will resolve after the minPendingMs
|
|
249
|
-
if (!router.isServer) {
|
|
250
|
+
if (!(isServer ?? router.isServer)) {
|
|
250
251
|
const minPendingPromise = createControlledPromise<void>()
|
|
251
252
|
|
|
252
253
|
routerMatch._nonReactive.minPendingPromise = minPendingPromise
|
|
@@ -285,7 +286,7 @@ export const MatchInner = React.memo(function MatchInnerImpl({
|
|
|
285
286
|
// of a suspense boundary. This is the only way to get
|
|
286
287
|
// renderToPipeableStream to not hang indefinitely.
|
|
287
288
|
// We'll serialize the error and rethrow it on the client.
|
|
288
|
-
if (router.isServer) {
|
|
289
|
+
if (isServer ?? router.isServer) {
|
|
289
290
|
const RouteErrorComponent =
|
|
290
291
|
(route.options.errorComponent ??
|
|
291
292
|
router.options.defaultErrorComponent) ||
|
package/src/Matches.tsx
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as React from 'react'
|
|
2
2
|
import warning from 'tiny-warning'
|
|
3
|
-
import { rootRouteId } from '@tanstack/router-core'
|
|
3
|
+
import { isServer, rootRouteId } from '@tanstack/router-core'
|
|
4
4
|
import { CatchBoundary, ErrorComponent } from './CatchBoundary'
|
|
5
5
|
import { useRouterState } from './useRouterState'
|
|
6
6
|
import { useRouter } from './useRouter'
|
|
@@ -56,13 +56,14 @@ export function Matches() {
|
|
|
56
56
|
|
|
57
57
|
// Do not render a root Suspense during SSR or hydrating from SSR
|
|
58
58
|
const ResolvedSuspense =
|
|
59
|
-
|
|
59
|
+
(isServer ?? router.isServer) ||
|
|
60
|
+
(typeof document !== 'undefined' && router.ssr)
|
|
60
61
|
? SafeFragment
|
|
61
62
|
: React.Suspense
|
|
62
63
|
|
|
63
64
|
const inner = (
|
|
64
65
|
<ResolvedSuspense fallback={pendingElement}>
|
|
65
|
-
{!router.isServer && <Transitioner />}
|
|
66
|
+
{!(isServer ?? router.isServer) && <Transitioner />}
|
|
66
67
|
<MatchesInner />
|
|
67
68
|
</ResolvedSuspense>
|
|
68
69
|
)
|
package/src/ScriptOnce.tsx
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isServer } from '@tanstack/router-core'
|
|
1
2
|
import { useRouter } from './useRouter'
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -5,7 +6,7 @@ import { useRouter } from './useRouter'
|
|
|
5
6
|
*/
|
|
6
7
|
export function ScriptOnce({ children }: { children: string }) {
|
|
7
8
|
const router = useRouter()
|
|
8
|
-
if (!router.isServer) {
|
|
9
|
+
if (!(isServer ?? router.isServer)) {
|
|
9
10
|
return null
|
|
10
11
|
}
|
|
11
12
|
|
package/src/link.tsx
CHANGED
|
@@ -126,24 +126,29 @@ export function useLinkProps<
|
|
|
126
126
|
[router, _options],
|
|
127
127
|
)
|
|
128
128
|
|
|
129
|
+
// Use publicHref - it contains the correct href for display
|
|
130
|
+
// When a rewrite changes the origin, publicHref is the full URL
|
|
131
|
+
// Otherwise it's the origin-stripped path
|
|
132
|
+
// This avoids constructing URL objects in the hot path
|
|
133
|
+
const hrefOptionPublicHref = next.maskedLocation
|
|
134
|
+
? next.maskedLocation.publicHref
|
|
135
|
+
: next.publicHref
|
|
136
|
+
const hrefOptionExternal = next.maskedLocation
|
|
137
|
+
? next.maskedLocation.external
|
|
138
|
+
: next.external
|
|
129
139
|
const hrefOption = React.useMemo(() => {
|
|
130
|
-
if (disabled)
|
|
131
|
-
|
|
140
|
+
if (disabled) return undefined
|
|
141
|
+
|
|
142
|
+
// Full URL means rewrite changed the origin - treat as external-like
|
|
143
|
+
if (hrefOptionExternal) {
|
|
144
|
+
return { href: hrefOptionPublicHref, external: true }
|
|
132
145
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
:
|
|
136
|
-
|
|
137
|
-
let external = false
|
|
138
|
-
if (router.origin) {
|
|
139
|
-
if (href.startsWith(router.origin)) {
|
|
140
|
-
href = router.history.createHref(href.replace(router.origin, '')) || '/'
|
|
141
|
-
} else {
|
|
142
|
-
external = true
|
|
143
|
-
}
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
href: router.history.createHref(hrefOptionPublicHref) || '/',
|
|
149
|
+
external: false,
|
|
144
150
|
}
|
|
145
|
-
|
|
146
|
-
}, [disabled, next.maskedLocation, next.url, router.origin, router.history])
|
|
151
|
+
}, [disabled, hrefOptionExternal, hrefOptionPublicHref, router.history])
|
|
147
152
|
|
|
148
153
|
const externalLink = React.useMemo(() => {
|
|
149
154
|
if (hrefOption?.external) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
defaultGetScrollRestorationKey,
|
|
3
3
|
escapeHtml,
|
|
4
|
+
isServer,
|
|
4
5
|
restoreScroll,
|
|
5
6
|
storageKey,
|
|
6
7
|
} from '@tanstack/router-core'
|
|
@@ -9,7 +10,7 @@ import { ScriptOnce } from './ScriptOnce'
|
|
|
9
10
|
|
|
10
11
|
export function ScrollRestoration() {
|
|
11
12
|
const router = useRouter()
|
|
12
|
-
if (!router.isScrollRestoring || !router.isServer) {
|
|
13
|
+
if (!router.isScrollRestoring || !(isServer ?? router.isServer)) {
|
|
13
14
|
return null
|
|
14
15
|
}
|
|
15
16
|
if (typeof router.options.scrollRestoration === 'function') {
|