Server: Phase 2 (REVIEW not respected yet)
This commit is contained in:
1 parent
5d16ded553
commit
142b47674d
4271 files changed
+1203269
No files matched your search
+6
@@ -0,0 +1,6 @@
|
||||
import { RouterManagedTag } from '@tanstack/router-core';
|
||||
import * as React from 'react';
|
||||
export declare function Asset(asset: RouterManagedTag & {
|
||||
nonce?: string;
|
||||
preventScriptHoist?: boolean;
|
||||
}): React.ReactElement | null;
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
"use client";
|
||||
import { useHydrated } from "./ClientOnly.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import * as React$1 from "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/Asset.tsx
|
||||
var INLINE_CSS_HYDRATION_ATTR = "data-tsr-inline-css";
|
||||
var noopScriptHandler = () => {};
|
||||
function setScriptAttrs(script, attrs) {
|
||||
if (!attrs) return;
|
||||
for (const [key, value] of Object.entries(attrs)) if (key !== "suppressHydrationWarning" && value !== void 0 && value !== false) script.setAttribute(key, typeof value === "boolean" ? "" : String(value));
|
||||
}
|
||||
function Asset(asset) {
|
||||
const { attrs, children, nonce, preventScriptHoist } = asset;
|
||||
const innerHTML = React$1.useMemo(() => children === void 0 ? void 0 : { __html: children }, [children]);
|
||||
switch (asset.tag) {
|
||||
case "title": return /* @__PURE__ */ jsx("title", {
|
||||
...attrs,
|
||||
suppressHydrationWarning: true,
|
||||
children
|
||||
});
|
||||
case "meta": return /* @__PURE__ */ jsx("meta", {
|
||||
...attrs,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
case "link": return /* @__PURE__ */ jsx("link", {
|
||||
...attrs,
|
||||
precedence: attrs?.precedence ?? (attrs?.rel === "stylesheet" ? "default" : void 0),
|
||||
nonce,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
case "style":
|
||||
if (asset.inlineCss && (process.env.TSS_INLINE_CSS_ENABLED === "true" || process.env.TSS_INLINE_CSS_ENABLED === void 0 && isServer)) return /* @__PURE__ */ jsx(InlineCssStyle, {
|
||||
attrs,
|
||||
nonce,
|
||||
children
|
||||
});
|
||||
return /* @__PURE__ */ jsx("style", {
|
||||
...attrs,
|
||||
dangerouslySetInnerHTML: innerHTML,
|
||||
nonce
|
||||
});
|
||||
case "script": return /* @__PURE__ */ jsx(Script, {
|
||||
attrs,
|
||||
preventScriptHoist,
|
||||
children
|
||||
});
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
function InlineCssStyle({ attrs, children, nonce }) {
|
||||
const isInlineCssPlaceholder = children === void 0;
|
||||
const [hydratedInlineCss] = React$1.useState(() => {
|
||||
if (!isInlineCssPlaceholder || typeof document === "undefined") return;
|
||||
return document.querySelector(`style[${INLINE_CSS_HYDRATION_ATTR}]`)?.textContent ?? void 0;
|
||||
});
|
||||
const html = isInlineCssPlaceholder ? hydratedInlineCss ?? "" : children ?? "";
|
||||
const innerHTML = React$1.useMemo(() => ({ __html: html }), [html]);
|
||||
return /* @__PURE__ */ jsx("style", {
|
||||
...attrs,
|
||||
[INLINE_CSS_HYDRATION_ATTR]: "",
|
||||
dangerouslySetInnerHTML: innerHTML,
|
||||
nonce,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
}
|
||||
function Script({ attrs, children, preventScriptHoist }) {
|
||||
const router = useRouter();
|
||||
const hydrated = useHydrated();
|
||||
const innerHTML = React$1.useMemo(() => children === void 0 ? void 0 : { __html: children }, [children]);
|
||||
const dataScript = typeof attrs?.type === "string" && attrs.type !== "" && attrs.type !== "text/javascript" && attrs.type !== "module";
|
||||
if (process.env.NODE_ENV !== "production" && attrs?.src && typeof children === "string" && children.trim().length) console.warn("[TanStack Router] <Script> received both `src` and `children`. The `children` content will be ignored. Remove `children` or remove `src`.");
|
||||
React$1.useEffect(() => {
|
||||
if (dataScript) return;
|
||||
if (attrs?.src) {
|
||||
const link = document.createElement("a");
|
||||
link.href = attrs.src;
|
||||
const normSrc = link.href;
|
||||
for (const el of document.scripts) if (el.src === normSrc) return;
|
||||
const script = document.createElement("script");
|
||||
setScriptAttrs(script, attrs);
|
||||
document.head.appendChild(script);
|
||||
return () => script.remove();
|
||||
}
|
||||
if (typeof children === "string") {
|
||||
const typeAttr = typeof attrs?.type === "string" ? attrs.type : "text/javascript";
|
||||
const nonceAttr = typeof attrs?.nonce === "string" ? attrs.nonce : void 0;
|
||||
for (const el of document.scripts) {
|
||||
if (el.hasAttribute("src")) continue;
|
||||
const sType = el.getAttribute("type") ?? "text/javascript";
|
||||
const sNonce = el.getAttribute("nonce") ?? void 0;
|
||||
if (el.textContent === children && sType === typeAttr && sNonce === nonceAttr) return;
|
||||
}
|
||||
const script = document.createElement("script");
|
||||
script.textContent = children;
|
||||
setScriptAttrs(script, attrs);
|
||||
document.head.appendChild(script);
|
||||
return () => script.remove();
|
||||
}
|
||||
}, [
|
||||
attrs,
|
||||
children,
|
||||
dataScript
|
||||
]);
|
||||
if (isServer ?? router.isServer) {
|
||||
if (attrs?.src) {
|
||||
if (!preventScriptHoist) return /* @__PURE__ */ jsx("script", {
|
||||
...attrs,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
return /* @__PURE__ */ jsx("script", {
|
||||
...attrs,
|
||||
onLoad: noopScriptHandler,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
}
|
||||
if (typeof children === "string") return /* @__PURE__ */ jsx("script", {
|
||||
...attrs,
|
||||
dangerouslySetInnerHTML: innerHTML,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
return null;
|
||||
}
|
||||
if (dataScript && typeof children === "string") return /* @__PURE__ */ jsx("script", {
|
||||
...attrs,
|
||||
suppressHydrationWarning: true,
|
||||
dangerouslySetInnerHTML: innerHTML
|
||||
});
|
||||
if (!hydrated) {
|
||||
if (attrs?.src) return /* @__PURE__ */ jsx("script", {
|
||||
...attrs,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
if (typeof children === "string") return /* @__PURE__ */ jsx("script", {
|
||||
...attrs,
|
||||
dangerouslySetInnerHTML: innerHTML,
|
||||
suppressHydrationWarning: true
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
//#endregion
|
||||
export { Asset };
|
||||
|
||||
//# sourceMappingURL=Asset.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"Asset.js","names":[],"sources":["../../src/Asset.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { useRouter } from './useRouter'\nimport { useHydrated } from './ClientOnly'\nimport type { RouterManagedTag } from '@tanstack/router-core'\n\nconst INLINE_CSS_HYDRATION_ATTR = 'data-tsr-inline-css'\n\ninterface ScriptAttrs {\n [key: string]: string | boolean | undefined\n src?: string\n suppressHydrationWarning?: boolean\n}\n\nconst noopScriptHandler = () => {}\n\nfunction setScriptAttrs(\n script: HTMLScriptElement,\n attrs: ScriptAttrs | undefined,\n) {\n if (!attrs) {\n return\n }\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(key, typeof value === 'boolean' ? '' : String(value))\n }\n }\n}\n\nexport function Asset(\n asset: RouterManagedTag & {\n nonce?: string\n preventScriptHoist?: boolean\n },\n): React.ReactElement | null {\n const { attrs, children, nonce, preventScriptHoist } = asset\n // React 19 compares this object by reference before assigning innerHTML.\n const innerHTML = React.useMemo(\n () => (children === undefined ? undefined : { __html: children }),\n [children],\n )\n\n switch (asset.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 (\n <link\n {...attrs}\n precedence={\n attrs?.precedence ??\n (attrs?.rel === 'stylesheet' ? 'default' : undefined)\n }\n nonce={nonce}\n suppressHydrationWarning\n />\n )\n case 'style':\n if (\n asset.inlineCss &&\n (process.env.TSS_INLINE_CSS_ENABLED === 'true' ||\n (process.env.TSS_INLINE_CSS_ENABLED === undefined && isServer))\n ) {\n return (\n <InlineCssStyle attrs={attrs} nonce={nonce}>\n {children}\n </InlineCssStyle>\n )\n }\n\n return (\n <style {...attrs} dangerouslySetInnerHTML={innerHTML} nonce={nonce} />\n )\n case 'script':\n return (\n <Script attrs={attrs} preventScriptHoist={preventScriptHoist}>\n {children}\n </Script>\n )\n default:\n return null\n }\n}\n\nfunction InlineCssStyle({\n attrs,\n children,\n nonce,\n}: {\n attrs?: Record<string, any>\n children?: RouterManagedTag['children']\n nonce?: string\n}) {\n const isInlineCssPlaceholder = children === undefined\n const [hydratedInlineCss] = React.useState(() => {\n if (!isInlineCssPlaceholder || typeof document === 'undefined') {\n return undefined\n }\n\n return (\n document.querySelector<HTMLStyleElement>(\n `style[${INLINE_CSS_HYDRATION_ATTR}]`,\n )?.textContent ?? undefined\n )\n })\n const html = isInlineCssPlaceholder\n ? (hydratedInlineCss ?? '')\n : (children ?? '')\n const innerHTML = React.useMemo(() => ({ __html: html }), [html])\n\n return (\n <style\n {...attrs}\n {...{ [INLINE_CSS_HYDRATION_ATTR]: '' }}\n dangerouslySetInnerHTML={innerHTML}\n nonce={nonce}\n suppressHydrationWarning\n />\n )\n}\n\nfunction Script({\n attrs,\n children,\n preventScriptHoist,\n}: {\n attrs?: ScriptAttrs\n children?: string\n preventScriptHoist?: boolean\n}) {\n const router = useRouter()\n const hydrated = useHydrated()\n const innerHTML = React.useMemo(\n () => (children === undefined ? undefined : { __html: children }),\n [children],\n )\n const dataScript =\n typeof attrs?.type === 'string' &&\n attrs.type !== '' &&\n attrs.type !== 'text/javascript' &&\n attrs.type !== 'module'\n\n if (\n process.env.NODE_ENV !== 'production' &&\n attrs?.src &&\n typeof children === 'string' &&\n children.trim().length\n ) {\n console.warn(\n '[TanStack Router] <Script> received both `src` and `children`. The `children` content will be ignored. Remove `children` or remove `src`.',\n )\n }\n\n React.useEffect(() => {\n if (dataScript) {\n return\n }\n\n if (attrs?.src) {\n // Anchors resolve relative URLs and preserve invalid URLs without throwing.\n const link = document.createElement('a')\n link.href = attrs.src\n const normSrc = link.href\n for (const el of document.scripts) {\n if (el.src === normSrc) {\n return\n }\n }\n\n const script = document.createElement('script')\n\n setScriptAttrs(script, attrs)\n\n document.head.appendChild(script)\n\n return () => script.remove()\n }\n\n if (typeof children === 'string') {\n const typeAttr =\n tLine truncated
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { ErrorRouteComponent } from './route.js';
|
||||
import { ErrorInfo } from 'react';
|
||||
import * as React from 'react';
|
||||
export declare class CatchBoundary extends React.Component<{
|
||||
getResetKey: () => unknown;
|
||||
children: React.ReactNode;
|
||||
errorComponent?: ErrorRouteComponent;
|
||||
onCatch?: (error: unknown, errorInfo: ErrorInfo) => void;
|
||||
}> {
|
||||
state: {
|
||||
error: [unknown] | 0;
|
||||
resetKey?: unknown;
|
||||
};
|
||||
static getDerivedStateFromProps(props: {
|
||||
getResetKey: () => unknown;
|
||||
}, state: {
|
||||
resetKey?: unknown;
|
||||
error: [unknown] | 0;
|
||||
}): {
|
||||
resetKey: unknown;
|
||||
error: number;
|
||||
} | {
|
||||
resetKey: unknown;
|
||||
error?: undefined;
|
||||
};
|
||||
static getDerivedStateFromError(error: unknown): {
|
||||
error: unknown[];
|
||||
};
|
||||
reset: () => void;
|
||||
componentDidCatch(error: unknown, errorInfo: ErrorInfo): void;
|
||||
render(): string | number | bigint | boolean | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | React.FunctionComponentElement<import('@tanstack/router-core').ErrorComponentProps> | null | undefined;
|
||||
}
|
||||
export declare function ErrorComponent({ error }: {
|
||||
error: unknown;
|
||||
}): import("react/jsx-runtime").JSX.Element;
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
"use client";
|
||||
import { wrapInNonRouteComponentContext } from "./nonRouteComponentContext.js";
|
||||
import * as React$1 from "react";
|
||||
import { jsx, jsxs } from "react/jsx-runtime";
|
||||
//#region src/CatchBoundary.tsx
|
||||
var CatchBoundary = class extends React$1.Component {
|
||||
constructor(..._args) {
|
||||
super(..._args);
|
||||
this.state = { error: 0 };
|
||||
this.reset = () => {
|
||||
this.setState({ error: 0 });
|
||||
};
|
||||
}
|
||||
static getDerivedStateFromProps(props, state) {
|
||||
const resetKey = props.getResetKey();
|
||||
if (state.error && state.resetKey !== resetKey) return {
|
||||
resetKey,
|
||||
error: 0
|
||||
};
|
||||
return { resetKey };
|
||||
}
|
||||
static getDerivedStateFromError(error) {
|
||||
return { error: [error] };
|
||||
}
|
||||
componentDidCatch(error, errorInfo) {
|
||||
this.props.onCatch?.(error, errorInfo);
|
||||
}
|
||||
render() {
|
||||
const error = this.state.error;
|
||||
if (error) {
|
||||
const element = React$1.createElement(this.props.errorComponent ?? ErrorComponent, {
|
||||
error: error[0],
|
||||
reset: this.reset
|
||||
});
|
||||
return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(element, "errorComponent") : element;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
};
|
||||
function ErrorComponent({ error }) {
|
||||
const [show, setShow] = React$1.useState(process.env.NODE_ENV !== "production");
|
||||
return /* @__PURE__ */ jsxs("div", {
|
||||
style: {
|
||||
padding: ".5rem",
|
||||
maxWidth: "100%"
|
||||
},
|
||||
children: [
|
||||
/* @__PURE__ */ jsxs("div", {
|
||||
style: {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: ".5rem"
|
||||
},
|
||||
children: [/* @__PURE__ */ jsx("strong", {
|
||||
style: { fontSize: "1rem" },
|
||||
children: "Something went wrong!"
|
||||
}), /* @__PURE__ */ jsx("button", {
|
||||
style: {
|
||||
appearance: "none",
|
||||
fontSize: ".6em",
|
||||
border: "1px solid currentColor",
|
||||
padding: ".1rem .2rem",
|
||||
fontWeight: "bold",
|
||||
borderRadius: ".25rem"
|
||||
},
|
||||
onClick: () => setShow((d) => !d),
|
||||
children: show ? "Hide Error" : "Show Error"
|
||||
})]
|
||||
}),
|
||||
/* @__PURE__ */ jsx("div", { style: { height: ".25rem" } }),
|
||||
show ? /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx("pre", {
|
||||
style: {
|
||||
fontSize: ".7em",
|
||||
border: "1px solid red",
|
||||
borderRadius: ".25rem",
|
||||
padding: ".3rem",
|
||||
color: "red",
|
||||
overflow: "auto"
|
||||
},
|
||||
children: error?.message ? /* @__PURE__ */ jsx("code", { children: error.message }) : null
|
||||
}) }) : null
|
||||
]
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { CatchBoundary, ErrorComponent };
|
||||
|
||||
//# sourceMappingURL=CatchBoundary.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"CatchBoundary.js","names":[],"sources":["../../src/CatchBoundary.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { wrapInNonRouteComponentContext } from './nonRouteComponentContext'\nimport type { ErrorRouteComponent } from './route'\nimport type { ErrorInfo } from 'react'\n\nexport class CatchBoundary extends React.Component<{\n getResetKey: () => unknown\n children: React.ReactNode\n errorComponent?: ErrorRouteComponent\n onCatch?: (error: unknown, errorInfo: ErrorInfo) => void\n}> {\n // Wrapping caught values keeps every possible thrown value truthy.\n state = { error: 0 } as { error: [unknown] | 0; resetKey?: unknown }\n\n static getDerivedStateFromProps(\n props: { getResetKey: () => unknown },\n state: { resetKey?: unknown; error: [unknown] | 0 },\n ) {\n const resetKey = props.getResetKey()\n\n if (state.error && state.resetKey !== resetKey) {\n return { resetKey, error: 0 }\n }\n\n return { resetKey }\n }\n static getDerivedStateFromError(error: unknown) {\n return { error: [error] }\n }\n reset = () => {\n this.setState({ error: 0 })\n }\n componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n this.props.onCatch?.(error, errorInfo)\n }\n render() {\n const error = this.state.error\n if (error) {\n const element = React.createElement(\n this.props.errorComponent ?? ErrorComponent,\n {\n error: error[0],\n reset: this.reset,\n },\n )\n\n return process.env.NODE_ENV !== 'production'\n ? wrapInNonRouteComponentContext(element, 'errorComponent')\n : element\n }\n\n return this.props.children\n }\n}\n\nexport function ErrorComponent({ error }: { error: unknown }) {\n const [show, setShow] = React.useState(process.env.NODE_ENV !== 'production')\n\n return (\n <div style={{ padding: '.5rem', maxWidth: '100%' }}>\n <div style={{ display: 'flex', alignItems: 'center', gap: '.5rem' }}>\n <strong style={{ fontSize: '1rem' }}>Something went wrong!</strong>\n <button\n style={{\n appearance: 'none',\n fontSize: '.6em',\n border: '1px solid currentColor',\n padding: '.1rem .2rem',\n fontWeight: 'bold',\n borderRadius: '.25rem',\n }}\n onClick={() => setShow((d) => !d)}\n >\n {show ? 'Hide Error' : 'Show Error'}\n </button>\n </div>\n <div style={{ height: '.25rem' }} />\n {show ? (\n <div>\n <pre\n style={{\n fontSize: '.7em',\n border: '1px solid red',\n borderRadius: '.25rem',\n padding: '.3rem',\n color: 'red',\n overflow: 'auto',\n }}\n >\n {(error as { message?: string } | null)?.message ? (\n <code>{(error as { message: string }).message}</code>\n ) : null}\n </pre>\n </div>\n ) : null}\n </div>\n )\n}\n"],"mappings":";;;;;AAOA,IAAa,gBAAb,cAAmC,QAAM,UAKtC;;;eAEO,EAAE,OAAO,EAAE;qBAiBL;GACZ,KAAK,SAAS,EAAE,OAAO,EAAE,CAAC;EAC5B;;CAjBA,OAAO,yBACL,OACA,OACA;EACA,MAAM,WAAW,MAAM,YAAY;EAEnC,IAAI,MAAM,SAAS,MAAM,aAAa,UACpC,OAAO;GAAE;GAAU,OAAO;EAAE;EAG9B,OAAO,EAAE,SAAS;CACpB;CACA,OAAO,yBAAyB,OAAgB;EAC9C,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE;CAC1B;CAIA,kBAAkB,OAAgB,WAAsB;EACtD,KAAK,MAAM,UAAU,OAAO,SAAS;CACvC;CACA,SAAS;EACP,MAAM,QAAQ,KAAK,MAAM;EACzB,IAAI,OAAO;GACT,MAAM,UAAU,QAAM,cACpB,KAAK,MAAM,kBAAkB,gBAC7B;IACE,OAAO,MAAM;IACb,OAAO,KAAK;GACd,CACF;GAEA,OAAA,QAAA,IAAA,aAAgC,eAC5B,+BAA+B,SAAS,gBAAgB,IACxD;EACN;EAEA,OAAO,KAAK,MAAM;CACpB;AACF;AAEA,SAAgB,eAAe,EAAE,SAA6B;CAC5D,MAAM,CAAC,MAAM,WAAW,QAAM,SAAA,QAAA,IAAA,aAAkC,YAAY;CAE5E,OACE,qBAAC,OAAD;EAAK,OAAO;GAAE,SAAS;GAAS,UAAU;EAAO;YAAjD;GACE,qBAAC,OAAD;IAAK,OAAO;KAAE,SAAS;KAAQ,YAAY;KAAU,KAAK;IAAQ;cAAlE,CACE,oBAAC,UAAD;KAAQ,OAAO,EAAE,UAAU,OAAO;eAAG;IAA6B,CAAA,GAClE,oBAAC,UAAD;KACE,OAAO;MACL,YAAY;MACZ,UAAU;MACV,QAAQ;MACR,SAAS;MACT,YAAY;MACZ,cAAc;KAChB;KACA,eAAe,SAAS,MAAM,CAAC,CAAC;eAE/B,OAAO,eAAe;IACjB,CAAA,CACL;;GACL,oBAAC,OAAD,EAAK,OAAO,EAAE,QAAQ,SAAS,EAAI,CAAA;GAClC,OACC,oBAAC,OAAD,EAAA,UACE,oBAAC,OAAD;IACE,OAAO;KACL,UAAU;KACV,QAAQ;KACR,cAAc;KACd,SAAS;KACT,OAAO;KACP,UAAU;IACZ;cAEE,OAAuC,UACvC,oBAAC,QAAD,EAAA,UAAQ,MAA8B,QAAc,CAAA,IAClD;GACD,CAAA,EACF,CAAA,IACH;EACD;;AAET"}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { default as React } from 'react';
|
||||
export interface ClientOnlyProps {
|
||||
/**
|
||||
* The children to render when the JS is loaded.
|
||||
*/
|
||||
children: React.ReactNode;
|
||||
/**
|
||||
* The fallback component to render if the JS is not yet loaded.
|
||||
*/
|
||||
fallback?: React.ReactNode;
|
||||
}
|
||||
/**
|
||||
* Render the children only after the JS has loaded client-side. Use an optional
|
||||
* fallback component if the JS is not yet loaded.
|
||||
*
|
||||
* @example
|
||||
* Render a Chart component if JS loads, renders a simple FakeChart
|
||||
* component server-side or if there is no JS. The FakeChart can have only the
|
||||
* UI without the behavior or be a loading spinner or skeleton.
|
||||
*
|
||||
* ```tsx
|
||||
* return (
|
||||
* <ClientOnly fallback={<FakeChart />}>
|
||||
* <Chart />
|
||||
* </ClientOnly>
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
export declare function ClientOnly({ children, fallback }: ClientOnlyProps): import("react/jsx-runtime").JSX.Element;
|
||||
/**
|
||||
* Return a boolean indicating if the JS has been hydrated already.
|
||||
* When doing Server-Side Rendering, the result will always be false.
|
||||
* When doing Client-Side Rendering, the result will always be false on the
|
||||
* first render and true from then on. Even if a new component renders it will
|
||||
* always start with true.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* // Disable a button that needs JS to work.
|
||||
* let hydrated = useHydrated()
|
||||
* return (
|
||||
* <button type="button" disabled={!hydrated} onClick={doSomethingCustom}>
|
||||
* Click me
|
||||
* </button>
|
||||
* )
|
||||
* ```
|
||||
* @returns True if the JS has been hydrated already, false otherwise.
|
||||
*/
|
||||
export declare function useHydrated(): boolean;
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
import React from "react";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/ClientOnly.tsx
|
||||
var getSnapshot = () => true;
|
||||
var getServerSnapshot = () => false;
|
||||
/**
|
||||
* Render the children only after the JS has loaded client-side. Use an optional
|
||||
* fallback component if the JS is not yet loaded.
|
||||
*
|
||||
* @example
|
||||
* Render a Chart component if JS loads, renders a simple FakeChart
|
||||
* component server-side or if there is no JS. The FakeChart can have only the
|
||||
* UI without the behavior or be a loading spinner or skeleton.
|
||||
*
|
||||
* ```tsx
|
||||
* return (
|
||||
* <ClientOnly fallback={<FakeChart />}>
|
||||
* <Chart />
|
||||
* </ClientOnly>
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
function ClientOnly({ children, fallback = null }) {
|
||||
return /* @__PURE__ */ jsx(React.Fragment, { children: useHydrated() ? children : fallback });
|
||||
}
|
||||
/**
|
||||
* Return a boolean indicating if the JS has been hydrated already.
|
||||
* When doing Server-Side Rendering, the result will always be false.
|
||||
* When doing Client-Side Rendering, the result will always be false on the
|
||||
* first render and true from then on. Even if a new component renders it will
|
||||
* always start with true.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* // Disable a button that needs JS to work.
|
||||
* let hydrated = useHydrated()
|
||||
* return (
|
||||
* <button type="button" disabled={!hydrated} onClick={doSomethingCustom}>
|
||||
* Click me
|
||||
* </button>
|
||||
* )
|
||||
* ```
|
||||
* @returns True if the JS has been hydrated already, false otherwise.
|
||||
*/
|
||||
function useHydrated() {
|
||||
return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
}
|
||||
function subscribe() {
|
||||
return () => {};
|
||||
}
|
||||
//#endregion
|
||||
export { ClientOnly, useHydrated };
|
||||
|
||||
//# sourceMappingURL=ClientOnly.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ClientOnly.js","names":[],"sources":["../../src/ClientOnly.tsx"],"sourcesContent":["'use client'\n\nimport React from 'react'\n\nconst getSnapshot = () => true\nconst getServerSnapshot = () => false\n\nexport interface ClientOnlyProps {\n /**\n * The children to render when the JS is loaded.\n */\n children: React.ReactNode\n /**\n * The fallback component to render if the JS is not yet loaded.\n */\n fallback?: React.ReactNode\n}\n\n/**\n * Render the children only after the JS has loaded client-side. Use an optional\n * fallback component if the JS is not yet loaded.\n *\n * @example\n * Render a Chart component if JS loads, renders a simple FakeChart\n * component server-side or if there is no JS. The FakeChart can have only the\n * UI without the behavior or be a loading spinner or skeleton.\n *\n * ```tsx\n * return (\n * <ClientOnly fallback={<FakeChart />}>\n * <Chart />\n * </ClientOnly>\n * )\n * ```\n */\nexport function ClientOnly({ children, fallback = null }: ClientOnlyProps) {\n return <React.Fragment>{useHydrated() ? children : fallback}</React.Fragment>\n}\n\n/**\n * Return a boolean indicating if the JS has been hydrated already.\n * When doing Server-Side Rendering, the result will always be false.\n * When doing Client-Side Rendering, the result will always be false on the\n * first render and true from then on. Even if a new component renders it will\n * always start with true.\n *\n * @example\n * ```tsx\n * // Disable a button that needs JS to work.\n * let hydrated = useHydrated()\n * return (\n * <button type=\"button\" disabled={!hydrated} onClick={doSomethingCustom}>\n * Click me\n * </button>\n * )\n * ```\n * @returns True if the JS has been hydrated already, false otherwise.\n */\nexport function useHydrated(): boolean {\n return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n}\n\nfunction subscribe() {\n return () => {\n // noop\n }\n}\n"],"mappings":";;;;AAIA,IAAM,oBAAoB;AAC1B,IAAM,0BAA0B;;;;;;;;;;;;;;;;;;AA8BhC,SAAgB,WAAW,EAAE,UAAU,WAAW,QAAyB;CACzE,OAAO,oBAAC,MAAM,UAAP,EAAA,UAAiB,YAAY,IAAI,WAAW,SAAyB,CAAA;AAC9E;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cAAuB;CACrC,OAAO,MAAM,qBAAqB,WAAW,aAAa,iBAAiB;AAC7E;AAEA,SAAS,YAAY;CACnB,aAAa,CAEb;AACF"}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { AssetCrossOriginConfig } from '@tanstack/router-core';
|
||||
export interface HeadContentProps {
|
||||
assetCrossOrigin?: AssetCrossOriginConfig;
|
||||
}
|
||||
/**
|
||||
* Render route-managed head tags (title, meta, links, styles, head scripts).
|
||||
* Place inside the document head of your app shell.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management
|
||||
*/
|
||||
export declare function HeadContent(props: HeadContentProps): import("react/jsx-runtime").JSX.Element;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { HeadContentProps } from './HeadContent.js';
|
||||
/**
|
||||
* Render route-managed head tags (title, meta, links, styles, head scripts).
|
||||
* Place inside the document head of your app shell.
|
||||
*
|
||||
* Development version: filters out dev styles link after hydration and
|
||||
* includes a fallback cleanup effect for hydration mismatch cases.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management
|
||||
*/
|
||||
export declare function HeadContent(props: HeadContentProps): import("react/jsx-runtime").JSX.Element;
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
import { useHydrated } from "./ClientOnly.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { Asset } from "./Asset.js";
|
||||
import { useTags } from "./headContentUtils.js";
|
||||
import { DEV_STYLES_ATTR } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
import { createElement } from "react";
|
||||
import { Fragment, jsx } from "react/jsx-runtime";
|
||||
//#region src/HeadContent.dev.tsx
|
||||
/**
|
||||
* Render route-managed head tags (title, meta, links, styles, head scripts).
|
||||
* Place inside the document head of your app shell.
|
||||
*
|
||||
* Development version: filters out dev styles link after hydration and
|
||||
* includes a fallback cleanup effect for hydration mismatch cases.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management
|
||||
*/
|
||||
function HeadContent(props) {
|
||||
const tags = useTags(props.assetCrossOrigin);
|
||||
const nonce = useRouter().options.ssr?.nonce;
|
||||
const hydrated = useHydrated();
|
||||
React$1.useEffect(() => {
|
||||
if (hydrated) document.querySelectorAll(`link[${DEV_STYLES_ATTR}]`).forEach((el) => el.remove());
|
||||
}, [hydrated]);
|
||||
return /* @__PURE__ */ jsx(Fragment, { children: (hydrated ? tags.filter((tag) => tag.tag !== "link" || tag.attrs?.[DEV_STYLES_ATTR] !== true) : tags).map((tag) => /* @__PURE__ */ createElement(Asset, {
|
||||
...tag,
|
||||
key: `tsr-meta-${JSON.stringify(tag)}`,
|
||||
nonce
|
||||
})) });
|
||||
}
|
||||
//#endregion
|
||||
export { HeadContent };
|
||||
|
||||
//# sourceMappingURL=HeadContent.dev.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"HeadContent.dev.js","names":[],"sources":["../../src/HeadContent.dev.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { DEV_STYLES_ATTR } from '@tanstack/router-core'\nimport { Asset } from './Asset'\nimport { useRouter } from './useRouter'\nimport { useHydrated } from './ClientOnly'\nimport { useTags } from './headContentUtils'\nimport type { HeadContentProps } from './HeadContent'\n\n/**\n * Render route-managed head tags (title, meta, links, styles, head scripts).\n * Place inside the document head of your app shell.\n *\n * Development version: filters out dev styles link after hydration and\n * includes a fallback cleanup effect for hydration mismatch cases.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management\n */\nexport function HeadContent(props: HeadContentProps) {\n const tags = useTags(props.assetCrossOrigin)\n const router = useRouter()\n const nonce = router.options.ssr?.nonce\n const hydrated = useHydrated()\n\n // Fallback cleanup for hydration mismatch cases\n // Runs when hydration completes to remove any orphaned dev styles links from DOM\n React.useEffect(() => {\n if (hydrated) {\n document\n .querySelectorAll(`link[${DEV_STYLES_ATTR}]`)\n .forEach((el) => el.remove())\n }\n }, [hydrated])\n\n // Filter out dev styles after hydration\n const filteredTags = hydrated\n ? tags.filter(\n (tag) => tag.tag !== 'link' || tag.attrs?.[DEV_STYLES_ATTR] !== true,\n )\n : tags\n\n return (\n <>\n {filteredTags.map((tag) => (\n <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} nonce={nonce} />\n ))}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YAAY,OAAyB;CACnD,MAAM,OAAO,QAAQ,MAAM,gBAAgB;CAE3C,MAAM,QADS,UACD,EAAO,QAAQ,KAAK;CAClC,MAAM,WAAW,YAAY;CAI7B,QAAM,gBAAgB;EACpB,IAAI,UACF,SACG,iBAAiB,QAAQ,gBAAgB,EAAE,EAC3C,SAAS,OAAO,GAAG,OAAO,CAAC;CAElC,GAAG,CAAC,QAAQ,CAAC;CASb,OACE,oBAAA,UAAA,EAAA,WAPmB,WACjB,KAAK,QACF,QAAQ,IAAI,QAAQ,UAAU,IAAI,QAAQ,qBAAqB,IAClE,IACA,MAIc,KAAK,QACjB,8BAAC,OAAD;EAAO,GAAI;EAAK,KAAK,YAAY,KAAK,UAAU,GAAG;EAAY;CAAQ,CAAA,CACxE,EACD,CAAA;AAEN"}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
"use client";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { Asset } from "./Asset.js";
|
||||
import { useTags } from "./headContentUtils.js";
|
||||
import { createElement } from "react";
|
||||
import { Fragment, jsx } from "react/jsx-runtime";
|
||||
//#region src/HeadContent.tsx
|
||||
/**
|
||||
* Render route-managed head tags (title, meta, links, styles, head scripts).
|
||||
* Place inside the document head of your app shell.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management
|
||||
*/
|
||||
function HeadContent(props) {
|
||||
const tags = useTags(props.assetCrossOrigin);
|
||||
const nonce = useRouter().options.ssr?.nonce;
|
||||
return /* @__PURE__ */ jsx(Fragment, { children: tags.map((tag) => /* @__PURE__ */ createElement(Asset, {
|
||||
...tag,
|
||||
key: `tsr-meta-${JSON.stringify(tag)}`,
|
||||
nonce
|
||||
})) });
|
||||
}
|
||||
//#endregion
|
||||
export { HeadContent };
|
||||
|
||||
//# sourceMappingURL=HeadContent.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"HeadContent.js","names":[],"sources":["../../src/HeadContent.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { Asset } from './Asset'\nimport { useRouter } from './useRouter'\nimport { useTags } from './headContentUtils'\nimport type { AssetCrossOriginConfig } from '@tanstack/router-core'\n\nexport interface HeadContentProps {\n assetCrossOrigin?: AssetCrossOriginConfig\n}\n\n/**\n * Render route-managed head tags (title, meta, links, styles, head scripts).\n * Place inside the document head of your app shell.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management\n */\nexport function HeadContent(props: HeadContentProps) {\n const tags = useTags(props.assetCrossOrigin)\n const router = useRouter()\n const nonce = router.options.ssr?.nonce\n return (\n <>\n {tags.map((tag) => (\n <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} nonce={nonce} />\n ))}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,SAAgB,YAAY,OAAyB;CACnD,MAAM,OAAO,QAAQ,MAAM,gBAAgB;CAE3C,MAAM,QADS,UACD,EAAO,QAAQ,KAAK;CAClC,OACE,oBAAA,UAAA,EAAA,UACG,KAAK,KAAK,QACT,8BAAC,OAAD;EAAO,GAAI;EAAK,KAAK,YAAY,KAAK,UAAU,GAAG;EAAY;CAAQ,CAAA,CACxE,EACD,CAAA;AAEN"}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { useRouter } from './useRouter.js';
|
||||
import { AnyRoute, AnyRouteMatch } from '@tanstack/router-core';
|
||||
import * as React from 'react';
|
||||
export declare function renderPending(router: ReturnType<typeof useRouter>, route?: AnyRoute): import("react/jsx-runtime").JSX.Element | null;
|
||||
export declare const Match: React.MemoExoticComponent<({ routeId, }: {
|
||||
routeId: string;
|
||||
}) => import("react/jsx-runtime").JSX.Element>;
|
||||
export declare const MatchInner: React.MemoExoticComponent<({ match, }: {
|
||||
match: AnyRouteMatch;
|
||||
}) => any>;
|
||||
/**
|
||||
* Render the next child match in the route tree. Typically used inside
|
||||
* a route component to render nested routes.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent
|
||||
*/
|
||||
export declare const Outlet: React.MemoExoticComponent<() => import("react/jsx-runtime").JSX.Element | null>;
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
"use client";
|
||||
import { nonRouteComponentContext, wrapInNonRouteComponentContext } from "./nonRouteComponentContext.js";
|
||||
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
|
||||
import { ClientOnly } from "./ClientOnly.js";
|
||||
import { matchContext } from "./matchContext.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { CatchNotFound } from "./not-found.js";
|
||||
import { SafeFragment } from "./SafeFragment.js";
|
||||
import { renderRouteNotFound } from "./renderRouteNotFound.js";
|
||||
import { ScrollRestoration } from "./scroll-restoration.js";
|
||||
import { isNotFound, rootRouteId } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { jsx, jsxs } from "react/jsx-runtime";
|
||||
import { useSelector } from "@tanstack/react-store";
|
||||
//#region src/Match.tsx
|
||||
function renderPending(router, route) {
|
||||
const PendingComponent = route?.options.pendingComponent ?? router.options.defaultPendingComponent;
|
||||
if (!PendingComponent) return null;
|
||||
const pendingElement = /* @__PURE__ */ jsx(PendingComponent, {});
|
||||
return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(pendingElement, "pendingComponent") : pendingElement;
|
||||
}
|
||||
var outletMatchSelectionEqual = (a, b) => a[0] === b[0] && a[1] === b[1];
|
||||
var canWrapInSuspense = (router, route, ssr) => !route.isRoot || route.options.shellComponent || route.options.wrapInSuspense || ssr === false || ssr === "data-only" || !((isServer ?? router.isServer) || router.ssr);
|
||||
var Match = React$1.memo(function MatchImpl({ routeId }) {
|
||||
const router = useRouter();
|
||||
if (isServer ?? router.isServer) return /* @__PURE__ */ jsx(MatchView, {
|
||||
router,
|
||||
match: router.stores.byRoute.get(routeId).get()
|
||||
});
|
||||
return /* @__PURE__ */ jsx(MatchView, {
|
||||
router,
|
||||
match: useSelector(router.stores.getMatchStore(routeId))
|
||||
});
|
||||
});
|
||||
function MatchView({ router, match }) {
|
||||
const route = router.routesById[match.routeId];
|
||||
const pendingElement = renderPending(router, route);
|
||||
const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent;
|
||||
const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch;
|
||||
const routeNotFoundComponent = route.isRoot ? route.options.notFoundComponent ?? router.options.notFoundRoute?.options.component : route.options.notFoundComponent;
|
||||
const resolvedNoSsr = match.ssr === false || match.ssr === "data-only";
|
||||
const ResolvedSuspenseBoundary = canWrapInSuspense(router, route, match.ssr) && (route.options.wrapInSuspense ?? pendingElement ?? (route.options.errorComponent?.preload || resolvedNoSsr)) ? React$1.Suspense : SafeFragment;
|
||||
const ResolvedCatchBoundary = routeErrorComponent ? CatchBoundary : SafeFragment;
|
||||
const ResolvedNotFoundBoundary = routeNotFoundComponent ? CatchNotFound : SafeFragment;
|
||||
return /* @__PURE__ */ jsxs(route.isRoot ? route.options.shellComponent ?? SafeFragment : SafeFragment, { children: [/* @__PURE__ */ jsx(matchContext.Provider, {
|
||||
value: match.routeId,
|
||||
children: /* @__PURE__ */ jsx(ResolvedSuspenseBoundary, {
|
||||
fallback: pendingElement,
|
||||
children: /* @__PURE__ */ jsx(ResolvedCatchBoundary, {
|
||||
getResetKey: () => match,
|
||||
errorComponent: routeErrorComponent,
|
||||
onCatch: (error, errorInfo) => {
|
||||
if (isNotFound(error)) {
|
||||
error.routeId ??= match.routeId;
|
||||
throw error;
|
||||
}
|
||||
if (process.env.NODE_ENV !== "production") console.warn(`Warning: Error in route match: ${match.id}`);
|
||||
routeOnCatch?.(error, errorInfo);
|
||||
},
|
||||
children: /* @__PURE__ */ jsx(ResolvedNotFoundBoundary, {
|
||||
fallback: (error) => {
|
||||
error.routeId ??= match.routeId;
|
||||
if (error.routeId !== match.routeId) throw error;
|
||||
const notFoundElement = React$1.createElement(routeNotFoundComponent, error);
|
||||
return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(notFoundElement, "notFoundComponent") : notFoundElement;
|
||||
},
|
||||
children: resolvedNoSsr ? /* @__PURE__ */ jsx(ClientOnly, {
|
||||
fallback: pendingElement,
|
||||
children: /* @__PURE__ */ jsx(MatchInner, { match })
|
||||
}) : /* @__PURE__ */ jsx(MatchInner, { match })
|
||||
})
|
||||
})
|
||||
})
|
||||
}), (isServer ?? router.isServer) && route.parentRoute?.id === rootRouteId && router.options.scrollRestoration ? /* @__PURE__ */ jsx(ScrollRestoration, {}) : null] });
|
||||
}
|
||||
var MatchInner = React$1.memo(function MatchInnerImpl({ match }) {
|
||||
const router = useRouter();
|
||||
const routeId = match.routeId;
|
||||
const route = router.routesById[routeId];
|
||||
const key = React$1.useMemo(() => {
|
||||
const remountDeps = (route.options.remountDeps ?? router.options.defaultRemountDeps)?.({
|
||||
routeId,
|
||||
loaderDeps: match.loaderDeps,
|
||||
params: match._strictParams,
|
||||
search: match._strictSearch
|
||||
});
|
||||
return remountDeps ? JSON.stringify(remountDeps) : void 0;
|
||||
}, [
|
||||
routeId,
|
||||
match.loaderDeps,
|
||||
match._strictParams,
|
||||
match._strictSearch,
|
||||
route.options.remountDeps,
|
||||
router.options.defaultRemountDeps
|
||||
]);
|
||||
const out = React$1.useMemo(() => {
|
||||
const Comp = route.options.component ?? router.options.defaultComponent;
|
||||
return Comp ? /* @__PURE__ */ jsx(Comp, {}, key) : /* @__PURE__ */ jsx(Outlet, {});
|
||||
}, [
|
||||
key,
|
||||
route.options.component,
|
||||
router.options.defaultComponent
|
||||
]);
|
||||
if (match.status === "pending") {
|
||||
if (router.ssr && !canWrapInSuspense(router, route, match.ssr)) return out;
|
||||
if (router._tx) throw router._tx[5];
|
||||
return renderPending(router, route);
|
||||
}
|
||||
if (match.status === "notFound") return renderRouteNotFound(router, route, match.error);
|
||||
if (match.status === "error") {
|
||||
if (isServer ?? router.isServer) {
|
||||
const errorElement = /* @__PURE__ */ jsx((route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent, {
|
||||
error: match.error,
|
||||
reset: void 0,
|
||||
info: { componentStack: "" }
|
||||
});
|
||||
return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(errorElement, "errorComponent") : errorElement;
|
||||
}
|
||||
throw match.error;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
/**
|
||||
* Render the next child match in the route tree. Typically used inside
|
||||
* a route component to render nested routes.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent
|
||||
*/
|
||||
var Outlet = React$1.memo(function OutletImpl() {
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
const nonRouteComponent = React$1.useContext(nonRouteComponentContext);
|
||||
if (nonRouteComponent) console.warn(`Warning: An <Outlet /> was rendered inside a ${nonRouteComponent}. <Outlet /> should only be rendered inside a route component.`);
|
||||
}
|
||||
const router = useRouter();
|
||||
const routeId = React$1.useContext(matchContext);
|
||||
let parentGlobalNotFound;
|
||||
let parentNotFoundError;
|
||||
let childRouteId;
|
||||
if (isServer ?? router.isServer) {
|
||||
const matches = router.stores.matches.get();
|
||||
const parentIndex = matches.findIndex((match) => match.routeId === routeId);
|
||||
const parentMatch = matches[parentIndex];
|
||||
parentGlobalNotFound = !!parentMatch._notFound;
|
||||
parentNotFoundError = parentMatch.error;
|
||||
childRouteId = matches[parentIndex + 1]?.routeId;
|
||||
} else {
|
||||
const parentMatchStore = router.stores.getMatchStore(routeId);
|
||||
[parentGlobalNotFound, parentNotFoundError] = useSelector(parentMatchStore, (match) => [!!match._notFound, match.error], { compare: outletMatchSelectionEqual });
|
||||
childRouteId = useSelector(router.stores.ids, (ids) => {
|
||||
return ids[ids.indexOf(routeId) + 1];
|
||||
});
|
||||
}
|
||||
if (parentGlobalNotFound) return renderRouteNotFound(router, router.routesById[routeId], parentNotFoundError);
|
||||
if (!childRouteId) return null;
|
||||
const nextMatch = /* @__PURE__ */ jsx(Match, { routeId: childRouteId });
|
||||
if (routeId === rootRouteId) return /* @__PURE__ */ jsx(React$1.Suspense, {
|
||||
fallback: renderPending(router),
|
||||
children: nextMatch
|
||||
});
|
||||
return nextMatch;
|
||||
});
|
||||
//#endregion
|
||||
export { Match, Outlet, renderPending };
|
||||
|
||||
//# sourceMappingURL=Match.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"Match.js","names":[],"sources":["../../src/Match.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { useSelector } from '@tanstack/react-store'\nimport { isNotFound, rootRouteId } from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\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 {\n nonRouteComponentContext,\n wrapInNonRouteComponentContext,\n} from './nonRouteComponentContext'\nimport type {\n AnyRoute,\n AnyRouteMatch,\n RootRouteOptions,\n} from '@tanstack/router-core'\n\nexport function renderPending(\n router: ReturnType<typeof useRouter>,\n route?: AnyRoute,\n) {\n const PendingComponent =\n route?.options.pendingComponent ?? router.options.defaultPendingComponent\n if (!PendingComponent) {\n return null\n }\n\n const pendingElement = <PendingComponent />\n return process.env.NODE_ENV !== 'production'\n ? wrapInNonRouteComponentContext(pendingElement, 'pendingComponent')\n : pendingElement\n}\n\ntype OutletMatchSelection = [\n parentGlobalNotFound: boolean,\n parentNotFoundError: unknown,\n]\n\nconst outletMatchSelectionEqual = (\n a: OutletMatchSelection,\n b: OutletMatchSelection,\n) => a[0] === b[0] && a[1] === b[1]\n\nconst canWrapInSuspense = (\n router: ReturnType<typeof useRouter>,\n route: AnyRoute,\n ssr: AnyRouteMatch['ssr'],\n) =>\n !route.isRoot ||\n (route.options as RootRouteOptions).shellComponent ||\n route.options.wrapInSuspense ||\n ssr === false ||\n ssr === 'data-only' ||\n !((isServer ?? router.isServer) || router.ssr)\n\nexport const Match = React.memo(function MatchImpl({\n routeId,\n}: {\n routeId: string\n}) {\n const router = useRouter()\n\n if (isServer ?? router.isServer) {\n const match = router.stores.byRoute.get(routeId)!.get()!\n return <MatchView router={router} match={match} />\n }\n\n const matchStore = router.stores.getMatchStore(routeId)\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const match = useSelector(matchStore)\n return <MatchView router={router} match={match!} />\n})\n\nfunction MatchView({\n router,\n match,\n}: {\n router: ReturnType<typeof useRouter>\n match: AnyRouteMatch\n}) {\n const route: AnyRoute = router.routesById[match.routeId]\n\n const pendingElement = renderPending(router, route)\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 _notFound 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 = match.ssr === false || match.ssr === 'data-only'\n // A root component may render the document itself. Only place its Suspense\n // boundary in pure CSR, inside an explicit shell, or when explicitly opted in.\n const ResolvedSuspenseBoundary =\n canWrapInSuspense(router, route, match.ssr) &&\n (route.options.wrapInSuspense ??\n pendingElement ??\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 ShellComponent = route.isRoot\n ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment)\n : SafeFragment\n return (\n <ShellComponent>\n <matchContext.Provider value={match.routeId}>\n <ResolvedSuspenseBoundary fallback={pendingElement}>\n <ResolvedCatchBoundary\n getResetKey={() => match}\n errorComponent={routeErrorComponent as any}\n onCatch={(error, errorInfo) => {\n // Forward not found errors (we don't want to show the error component for these)\n if (isNotFound(error)) {\n error.routeId ??= match.routeId\n throw error\n }\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`Warning: Error in route match: ${match.id}`)\n }\n routeOnCatch?.(error, errorInfo)\n }}\n >\n <ResolvedNotFoundBoundary\n fallback={(error) => {\n error.routeId ??= match.routeId\n\n if (error.routeId !== match.rouLine truncated
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { StructuralSharingOption, ValidateSelected } from './structuralSharing.js';
|
||||
import { AnyRouter, DeepPartial, Expand, MakeOptionalPathParams, MakeOptionalSearchParams, MakeRouteMatchUnion, MaskOptions, MatchRouteOptions, RegisteredRouter, ResolveRoute, ToSubOptionsProps } from '@tanstack/router-core';
|
||||
import * as React from 'react';
|
||||
declare module '@tanstack/router-core' {
|
||||
interface RouteMatchExtensions {
|
||||
meta?: Array<React.JSX.IntrinsicElements['meta'] | undefined>;
|
||||
links?: Array<React.JSX.IntrinsicElements['link'] | undefined>;
|
||||
scripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>;
|
||||
styles?: Array<React.JSX.IntrinsicElements['style'] | undefined>;
|
||||
headScripts?: Array<React.JSX.IntrinsicElements['script'] | undefined>;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Internal component that renders the router's active match tree with
|
||||
* suspense, error, and not-found boundaries. Rendered by `RouterProvider`.
|
||||
*/
|
||||
export declare function Matches(): import("react/jsx-runtime").JSX.Element;
|
||||
export type UseMatchRouteOptions<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = undefined, TMaskFrom extends string = TFrom, TMaskTo extends string = ''> = ToSubOptionsProps<TRouter, TFrom, TTo> & DeepPartial<MakeOptionalSearchParams<TRouter, TFrom, TTo>> & DeepPartial<MakeOptionalPathParams<TRouter, TFrom, TTo>> & MaskOptions<TRouter, TMaskFrom, TMaskTo> & MatchRouteOptions;
|
||||
/**
|
||||
* Create a matcher function for testing locations against route definitions.
|
||||
*
|
||||
* The returned function accepts standard navigation options (`to`, `params`,
|
||||
* `search`, etc.) and returns either `false` (no match) or the matched params
|
||||
* object when the route matches the current or pending location.
|
||||
*
|
||||
* Useful for conditional rendering and active UI states because it subscribes
|
||||
* the component to the router state used for matching. The returned function's
|
||||
* identity changes when that state changes. For imperative checks in event
|
||||
* handlers, get the router with `useRouter` and call `router.matchRoute(...)`
|
||||
* to avoid that subscription.
|
||||
*
|
||||
* @returns A `matchRoute(options)` function that returns `false` or params.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook
|
||||
*/
|
||||
export declare function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>(): <const TFrom extends string = string, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, const TMaskTo extends string = ''>(opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>) => false | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']>;
|
||||
export type MakeMatchRouteOptions<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = undefined, TMaskFrom extends string = TFrom, TMaskTo extends string = ''> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
|
||||
children?: ((params?: Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']>) => React.ReactNode) | React.ReactNode;
|
||||
};
|
||||
/**
|
||||
* Component that conditionally renders its children based on whether a route
|
||||
* matches the provided `from`/`to` options. If `children` is a function, it
|
||||
* receives the matched params object.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent
|
||||
*/
|
||||
export declare function MatchRoute<TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string = string, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, const TMaskTo extends string = ''>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any;
|
||||
export interface UseMatchesBaseOptions<TRouter extends AnyRouter, TSelected, TStructuralSharing> {
|
||||
select?: (matches: Array<MakeRouteMatchUnion<TRouter>>) => ValidateSelected<TRouter, TSelected, TStructuralSharing>;
|
||||
}
|
||||
export type UseMatchesResult<TRouter extends AnyRouter, TSelected> = unknown extends TSelected ? Array<MakeRouteMatchUnion<TRouter>> : TSelected;
|
||||
export declare function useMatches<TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean>(opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>): UseMatchesResult<TRouter, TSelected>;
|
||||
/**
|
||||
* Read the presented route matches above the current match, or select a
|
||||
* derived value from them.
|
||||
*/
|
||||
export declare function useParentMatches<TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean>(opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>): UseMatchesResult<TRouter, TSelected>;
|
||||
/**
|
||||
* Read the presented route matches below the current match, or select a
|
||||
* derived value from them.
|
||||
*/
|
||||
export declare function useChildMatches<TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean>(opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>): UseMatchesResult<TRouter, TSelected>;
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
"use client";
|
||||
import { useLayoutEffect } from "./utils.js";
|
||||
import { CatchBoundary } from "./CatchBoundary.js";
|
||||
import { matchContext } from "./matchContext.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { useStructuralSharing } from "./useMatch.js";
|
||||
import { Transitioner, settleOwner } from "./Transitioner.js";
|
||||
import { SafeFragment } from "./SafeFragment.js";
|
||||
import { Match, renderPending } from "./Match.js";
|
||||
import { rootRouteId } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
||||
import { useSelector } from "@tanstack/react-store";
|
||||
//#region src/Matches.tsx
|
||||
/**
|
||||
* Internal component that renders the router's active match tree with
|
||||
* suspense, error, and not-found boundaries. Rendered by `RouterProvider`.
|
||||
*/
|
||||
function Matches() {
|
||||
const router = useRouter();
|
||||
const rootRoute = router.routesById[rootRouteId];
|
||||
const pendingElement = renderPending(router, rootRoute);
|
||||
const ResolvedSuspense = (isServer ?? router.isServer) || router.ssr ? SafeFragment : React$1.Suspense;
|
||||
const inner = /* @__PURE__ */ jsxs(Fragment, { children: [!(isServer ?? router.isServer) && /* @__PURE__ */ jsx(Transitioner, { t: React$1.useState()[1] }), /* @__PURE__ */ jsx(ResolvedSuspense, {
|
||||
fallback: pendingElement,
|
||||
children: /* @__PURE__ */ jsx(MatchesInner, {})
|
||||
})] });
|
||||
return router.options.InnerWrap ? /* @__PURE__ */ jsx(router.options.InnerWrap, { children: inner }) : inner;
|
||||
}
|
||||
function MatchesInner() {
|
||||
const router = useRouter();
|
||||
const acknowledgement = router._rendered;
|
||||
const matches = isServer ?? router.isServer ? router.stores.matches.get() : useSelector(router.stores.matches, (value) => acknowledgement[0] ?? value);
|
||||
const match = matches[0];
|
||||
const routeId = match?.routeId;
|
||||
useLayoutEffect(() => {
|
||||
if (acknowledgement[0] === matches) settleOwner(acknowledgement, true);
|
||||
}, [acknowledgement, matches]);
|
||||
const matchComponent = routeId ? /* @__PURE__ */ jsx(Match, { routeId }) : null;
|
||||
return /* @__PURE__ */ jsx(matchContext.Provider, {
|
||||
value: routeId,
|
||||
children: router.options.disableGlobalCatchBoundary ? matchComponent : /* @__PURE__ */ jsx(CatchBoundary, {
|
||||
getResetKey: () => match,
|
||||
onCatch: process.env.NODE_ENV !== "production" ? (error) => {
|
||||
console.warn(`Warning: The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`);
|
||||
console.warn("Warning:", error);
|
||||
} : void 0,
|
||||
children: matchComponent
|
||||
})
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Create a matcher function for testing locations against route definitions.
|
||||
*
|
||||
* The returned function accepts standard navigation options (`to`, `params`,
|
||||
* `search`, etc.) and returns either `false` (no match) or the matched params
|
||||
* object when the route matches the current or pending location.
|
||||
*
|
||||
* Useful for conditional rendering and active UI states because it subscribes
|
||||
* the component to the router state used for matching. The returned function's
|
||||
* identity changes when that state changes. For imperative checks in event
|
||||
* handlers, get the router with `useRouter` and call `router.matchRoute(...)`
|
||||
* to avoid that subscription.
|
||||
*
|
||||
* @returns A `matchRoute(options)` function that returns `false` or params.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook
|
||||
*/
|
||||
function useMatchRoute() {
|
||||
const router = useRouter();
|
||||
if (isServer ?? router.isServer) return (opts) => {
|
||||
const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts;
|
||||
return router.matchRoute(rest, {
|
||||
pending,
|
||||
caseSensitive,
|
||||
fuzzy,
|
||||
includeSearch
|
||||
});
|
||||
};
|
||||
return React$1.useCallback((opts) => {
|
||||
const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts;
|
||||
return router.matchRoute(rest, {
|
||||
pending,
|
||||
caseSensitive,
|
||||
fuzzy,
|
||||
includeSearch
|
||||
});
|
||||
}, [
|
||||
router,
|
||||
useSelector(router.stores.location, (location) => location.href),
|
||||
useSelector(router.stores.resolvedLocation, (location) => location?.href),
|
||||
useSelector(router.stores.status)
|
||||
]);
|
||||
}
|
||||
/**
|
||||
* Component that conditionally renders its children based on whether a route
|
||||
* matches the provided `from`/`to` options. If `children` is a function, it
|
||||
* receives the matched params object.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/matchRouteComponent
|
||||
*/
|
||||
function MatchRoute(props) {
|
||||
const params = useMatchRoute()(props);
|
||||
if (typeof props.children === "function") return props.children(params);
|
||||
return params ? props.children : null;
|
||||
}
|
||||
function useMatches(opts) {
|
||||
const router = useRouter();
|
||||
if (isServer ?? router.isServer) {
|
||||
const matches = router.stores.matches.get();
|
||||
return opts?.select ? opts.select(matches) : matches;
|
||||
}
|
||||
return useSelector(router.stores.matches, useStructuralSharing(opts, router));
|
||||
}
|
||||
/**
|
||||
* Read the presented route matches above the current match, or select a
|
||||
* derived value from them.
|
||||
*/
|
||||
function useParentMatches(opts) {
|
||||
const contextRouteId = React$1.useContext(matchContext);
|
||||
return useMatches({
|
||||
select: (matches) => {
|
||||
matches = matches.slice(0, matches.findIndex((d) => d.routeId === contextRouteId));
|
||||
return opts?.select ? opts.select(matches) : matches;
|
||||
},
|
||||
structuralSharing: opts?.structuralSharing
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Read the presented route matches below the current match, or select a
|
||||
* derived value from them.
|
||||
*/
|
||||
function useChildMatches(opts) {
|
||||
const contextRouteId = React$1.useContext(matchContext);
|
||||
return useMatches({
|
||||
select: (matches) => {
|
||||
matches = matches.slice(matches.findIndex((d) => d.routeId === contextRouteId) + 1);
|
||||
return opts?.select ? opts.select(matches) : matches;
|
||||
},
|
||||
structuralSharing: opts?.structuralSharing
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { MatchRoute, Matches, useChildMatches, useMatchRoute, useMatches, useParentMatches };
|
||||
|
||||
//# sourceMappingURL=Matches.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"Matches.js","names":[],"sources":["../../src/Matches.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { useSelector } from '@tanstack/react-store'\nimport { rootRouteId } from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { CatchBoundary } from './CatchBoundary'\nimport { useRouter } from './useRouter'\nimport { useStructuralSharing } from './useMatch'\nimport { useLayoutEffect } from './utils'\nimport { Transitioner, settleOwner } from './Transitioner'\nimport { matchContext } from './matchContext'\nimport { Match, renderPending } 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 RegisteredRouter,\n ResolveRoute,\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 pendingElement = renderPending(router, rootRoute)\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n (isServer ?? router.isServer) || router.ssr ? SafeFragment : React.Suspense\n\n const inner = (\n <>\n {!(isServer ?? router.isServer) && (\n <Transitioner\n // The initial load publishes matches before MatchesInner's store\n // subscription is active. Storing the router here forces Matches to render\n // that first publication before paint. Later publications store the same\n // router object, so React skips the update.\n // eslint-disable-next-line react-hooks/rules-of-hooks -- server only, condition is static\n t={React.useState<AnyRouter>()[1]}\n />\n )}\n <ResolvedSuspense fallback={pendingElement}>\n <MatchesInner />\n </ResolvedSuspense>\n </>\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 acknowledgement = router._rendered!\n const matches =\n (isServer ?? router.isServer)\n ? router.stores.matches.get()\n : // eslint-disable-next-line react-hooks/rules-of-hooks\n useSelector(\n router.stores.matches,\n (value) => acknowledgement[0 /* offered */] ?? value,\n )\n const match = matches[0]\n const routeId = match?.routeId\n\n useLayoutEffect(() => {\n if (acknowledgement[0 /* offered */] === matches) {\n settleOwner(acknowledgement, true)\n }\n }, [acknowledgement, matches])\n\n const matchComponent = routeId ? <Match routeId={routeId} /> : null\n\n return (\n <matchContext.Provider value={routeId}>\n {router.options.disableGlobalCatchBoundary ? (\n matchComponent\n ) : (\n <CatchBoundary\n getResetKey={() => match}\n onCatch={\n process.env.NODE_ENV !== 'production'\n ? (error) => {\n console.warn(\n `Warning: The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n console.warn('Warning:', error)\n }\n : undefined\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` (Line truncated
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { AnyRouter, RegisteredRouter, RouterOptions } from '@tanstack/router-core';
|
||||
import * as React from 'react';
|
||||
/**
|
||||
* Low-level provider that places the router into React context and optionally
|
||||
* updates router options from props. Most apps should use `RouterProvider`.
|
||||
*/
|
||||
export declare function RouterContextProvider<TRouter extends AnyRouter = RegisteredRouter, TDehydrated extends Record<string, any> = Record<string, any>>({ router, children, ...rest }: RouterProps<TRouter, TDehydrated> & {
|
||||
children: React.ReactNode;
|
||||
}): import("react/jsx-runtime").JSX.Element;
|
||||
/**
|
||||
* Renders the current match presentation and provides the router to the React
|
||||
* tree via context.
|
||||
*
|
||||
* Accepts mutable router options via props. Configure initialization-only
|
||||
* options with `createRouter`.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction
|
||||
*/
|
||||
export declare function RouterProvider<TRouter extends AnyRouter = RegisteredRouter, TDehydrated extends Record<string, any> = Record<string, any>>({ router, ...rest }: RouterProps<TRouter, TDehydrated>): import("react/jsx-runtime").JSX.Element;
|
||||
export type RouterProps<TRouter extends AnyRouter = RegisteredRouter, TDehydrated extends Record<string, any> = Record<string, any>> = Omit<RouterOptions<TRouter['routeTree'], NonNullable<TRouter['options']['trailingSlash']>, NonNullable<TRouter['options']['defaultStructuralSharing']>, TRouter['history'], TDehydrated>, 'context' | 'pathParamsAllowedCharacters'> & {
|
||||
router: TRouter;
|
||||
context?: Partial<RouterOptions<TRouter['routeTree'], NonNullable<TRouter['options']['trailingSlash']>, NonNullable<TRouter['options']['defaultStructuralSharing']>, TRouter['history'], TDehydrated>['context']>;
|
||||
};
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
import { routerContext } from "./routerContext.js";
|
||||
import { Matches } from "./Matches.js";
|
||||
import { hasKeys } from "@tanstack/router-core";
|
||||
import "react";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/RouterProvider.tsx
|
||||
/**
|
||||
* Low-level provider that places the router into React context and optionally
|
||||
* updates router options from props. Most apps should use `RouterProvider`.
|
||||
*/
|
||||
function RouterContextProvider({ router, children, ...rest }) {
|
||||
if (hasKeys(rest)) router.update({
|
||||
...router.options,
|
||||
...rest,
|
||||
context: {
|
||||
...router.options.context,
|
||||
...rest.context
|
||||
}
|
||||
});
|
||||
const provider = /* @__PURE__ */ jsx(routerContext.Provider, {
|
||||
value: router,
|
||||
children
|
||||
});
|
||||
if (router.options.Wrap) return /* @__PURE__ */ jsx(router.options.Wrap, { children: provider });
|
||||
return provider;
|
||||
}
|
||||
/**
|
||||
* Renders the current match presentation and provides the router to the React
|
||||
* tree via context.
|
||||
*
|
||||
* Accepts mutable router options via props. Configure initialization-only
|
||||
* options with `createRouter`.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction
|
||||
*/
|
||||
function RouterProvider({ router, ...rest }) {
|
||||
return /* @__PURE__ */ jsx(RouterContextProvider, {
|
||||
router,
|
||||
...rest,
|
||||
children: /* @__PURE__ */ jsx(Matches, {})
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { RouterContextProvider, RouterProvider };
|
||||
|
||||
//# sourceMappingURL=RouterProvider.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"RouterProvider.js","names":[],"sources":["../../src/RouterProvider.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { hasKeys } from '@tanstack/router-core'\nimport { Matches } from './Matches'\nimport { routerContext } from './routerContext'\nimport type {\n AnyRouter,\n RegisteredRouter,\n RouterOptions,\n} from '@tanstack/router-core'\n\n/**\n * Low-level provider that places the router into React context and optionally\n * updates router options from props. Most apps should use `RouterProvider`.\n */\nexport function RouterContextProvider<\n TRouter extends AnyRouter = RegisteredRouter,\n TDehydrated extends Record<string, any> = Record<string, any>,\n>({\n router,\n children,\n ...rest\n}: RouterProps<TRouter, TDehydrated> & {\n children: React.ReactNode\n}) {\n if (hasKeys(rest)) {\n // Allow the router to update options on the router instance\n router.update({\n ...router.options,\n ...rest,\n context: {\n ...router.options.context,\n ...rest.context,\n },\n })\n }\n\n const provider = (\n <routerContext.Provider value={router as AnyRouter}>\n {children}\n </routerContext.Provider>\n )\n\n if (router.options.Wrap) {\n return <router.options.Wrap>{provider}</router.options.Wrap>\n }\n\n return provider\n}\n\n/**\n * Renders the current match presentation and provides the router to the React\n * tree via context.\n *\n * Accepts mutable router options via props. Configure initialization-only\n * options with `createRouter`.\n *\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction\n */\nexport function RouterProvider<\n TRouter extends AnyRouter = RegisteredRouter,\n TDehydrated extends Record<string, any> = Record<string, any>,\n>({ router, ...rest }: RouterProps<TRouter, TDehydrated>) {\n return (\n <RouterContextProvider router={router} {...rest}>\n <Matches />\n </RouterContextProvider>\n )\n}\n\nexport type RouterProps<\n TRouter extends AnyRouter = RegisteredRouter,\n TDehydrated extends Record<string, any> = Record<string, any>,\n> = Omit<\n RouterOptions<\n TRouter['routeTree'],\n NonNullable<TRouter['options']['trailingSlash']>,\n NonNullable<TRouter['options']['defaultStructuralSharing']>,\n TRouter['history'],\n TDehydrated\n >,\n 'context' | 'pathParamsAllowedCharacters'\n> & {\n router: TRouter\n context?: Partial<\n RouterOptions<\n TRouter['routeTree'],\n NonNullable<TRouter['options']['trailingSlash']>,\n NonNullable<TRouter['options']['defaultStructuralSharing']>,\n TRouter['history'],\n TDehydrated\n >['context']\n >\n}\n"],"mappings":";;;;;;;;;;;AAgBA,SAAgB,sBAGd,EACA,QACA,UACA,GAAG,QAGF;CACD,IAAI,QAAQ,IAAI,GAEd,OAAO,OAAO;EACZ,GAAG,OAAO;EACV,GAAG;EACH,SAAS;GACP,GAAG,OAAO,QAAQ;GAClB,GAAG,KAAK;EACV;CACF,CAAC;CAGH,MAAM,WACJ,oBAAC,cAAc,UAAf;EAAwB,OAAO;EAC5B;CACqB,CAAA;CAG1B,IAAI,OAAO,QAAQ,MACjB,OAAO,oBAAC,OAAO,QAAQ,MAAhB,EAAA,UAAsB,SAA8B,CAAA;CAG7D,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,eAGd,EAAE,QAAQ,GAAG,QAA2C;CACxD,OACE,oBAAC,uBAAD;EAA+B;EAAQ,GAAI;YACzC,oBAAC,SAAD,CAAU,CAAA;CACW,CAAA;AAE3B"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function SafeFragment(props: any): import("react/jsx-runtime").JSX.Element;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import "react";
|
||||
import { Fragment, jsx } from "react/jsx-runtime";
|
||||
//#region src/SafeFragment.tsx
|
||||
function SafeFragment(props) {
|
||||
return /* @__PURE__ */ jsx(Fragment, { children: props.children });
|
||||
}
|
||||
//#endregion
|
||||
export { SafeFragment };
|
||||
|
||||
//# sourceMappingURL=SafeFragment.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"SafeFragment.js","names":[],"sources":["../../src/SafeFragment.tsx"],"sourcesContent":["import * as React from 'react'\n\nexport function SafeFragment(props: any) {\n return <>{props.children}</>\n}\n"],"mappings":";;;AAEA,SAAgB,aAAa,OAAY;CACvC,OAAO,oBAAA,UAAA,EAAA,UAAG,MAAM,SAAW,CAAA;AAC7B"}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Server-only helper to emit a script tag exactly once during SSR.
|
||||
*/
|
||||
export declare function ScriptOnce({ children }: {
|
||||
children: string;
|
||||
}): import("react/jsx-runtime").JSX.Element | null;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/ScriptOnce.tsx
|
||||
/**
|
||||
* Server-only helper to emit a script tag exactly once during SSR.
|
||||
*/
|
||||
function ScriptOnce({ children }) {
|
||||
const router = useRouter();
|
||||
if (!(isServer ?? router.isServer)) return null;
|
||||
return /* @__PURE__ */ jsx("script", {
|
||||
nonce: router.options.ssr?.nonce,
|
||||
dangerouslySetInnerHTML: { __html: children + ";document.currentScript.remove()" }
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { ScriptOnce };
|
||||
|
||||
//# sourceMappingURL=ScriptOnce.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ScriptOnce.js","names":[],"sources":["../../src/ScriptOnce.tsx"],"sourcesContent":["import { isServer } from '@tanstack/router-core/isServer'\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"],"mappings":";;;;;;;AAMA,SAAgB,WAAW,EAAE,YAAkC;CAC7D,MAAM,SAAS,UAAU;CACzB,IAAI,EAAE,YAAY,OAAO,WACvB,OAAO;CAGT,OACE,oBAAC,UAAD;EACE,OAAO,OAAO,QAAQ,KAAK;EAC3B,yBAAyB,EACvB,QAAQ,WAAW,mCACrB;CACD,CAAA;AAEL"}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Render body script tags collected from route matches and SSR manifests.
|
||||
* During streaming SSR, `<Scripts>` marks where late hydration scripts may
|
||||
* begin to be inserted.
|
||||
*/
|
||||
export declare const Scripts: () => import("react/jsx-runtime").JSX.Element;
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { Asset } from "./Asset.js";
|
||||
import { composeSsrBodyScripts, deepEqual, getSsrBodyScriptParts } from "@tanstack/router-core";
|
||||
import { createElement } from "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { Fragment, jsx } from "react/jsx-runtime";
|
||||
import { useSelector } from "@tanstack/react-store";
|
||||
//#region src/Scripts.tsx
|
||||
var routeScriptAttrs = { suppressHydrationWarning: true };
|
||||
/**
|
||||
* Render body script tags collected from route matches and SSR manifests.
|
||||
* During streaming SSR, `<Scripts>` marks where late hydration scripts may
|
||||
* begin to be inserted.
|
||||
*/
|
||||
var Scripts = () => {
|
||||
const router = useRouter();
|
||||
const nonce = router.options.ssr?.nonce;
|
||||
const getParts = (matches) => {
|
||||
const parts = getSsrBodyScriptParts(matches, router.ssr?.manifest, nonce, routeScriptAttrs);
|
||||
for (const script of parts[1]) if (typeof script.attrs?.src === "string") {
|
||||
const scriptWithHoist = script;
|
||||
scriptWithHoist.preventScriptHoist = true;
|
||||
}
|
||||
return parts;
|
||||
};
|
||||
const getScripts = (matches) => {
|
||||
return composeSsrBodyScripts(getParts(matches));
|
||||
};
|
||||
if (isServer ?? router.isServer) return renderScripts(composeSsrBodyScripts(getParts(router.stores.matches.get()), router.serverSsr?.takeInitialHydrationScriptTags()));
|
||||
return renderScripts(useSelector(router.stores.matches, getScripts, { compare: deepEqual }));
|
||||
};
|
||||
function renderScripts(scripts) {
|
||||
return /* @__PURE__ */ jsx(Fragment, { children: scripts.map((asset, i) => /* @__PURE__ */ createElement(Asset, {
|
||||
...asset,
|
||||
key: `tsr-scripts-${asset.tag}-${i}`
|
||||
})) });
|
||||
}
|
||||
//#endregion
|
||||
export { Scripts };
|
||||
|
||||
//# sourceMappingURL=Scripts.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"Scripts.js","names":[],"sources":["../../src/Scripts.tsx"],"sourcesContent":["import { useSelector } from '@tanstack/react-store'\nimport {\n composeSsrBodyScripts,\n deepEqual,\n getSsrBodyScriptParts,\n} from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { Asset } from './Asset'\nimport { useRouter } from './useRouter'\nimport type { RouterManagedTag } from '@tanstack/router-core'\n\ntype ScriptRenderAsset = RouterManagedTag & {\n preventScriptHoist?: boolean\n}\n\nconst routeScriptAttrs = { suppressHydrationWarning: true }\n\n/**\n * Render body script tags collected from route matches and SSR manifests.\n * During streaming SSR, `<Scripts>` marks where late hydration scripts may\n * begin to be inserted.\n */\nexport const Scripts = () => {\n const router = useRouter()\n const nonce = router.options.ssr?.nonce\n\n const getParts = (matches: Array<any>) => {\n const parts = getSsrBodyScriptParts(\n matches,\n router.ssr?.manifest,\n nonce,\n routeScriptAttrs,\n )\n for (const script of parts[1]) {\n if (typeof script.attrs?.src === 'string') {\n const scriptWithHoist = script as ScriptRenderAsset\n scriptWithHoist.preventScriptHoist = true\n }\n }\n return parts\n }\n\n const getScripts = (matches: Array<any>) => {\n return composeSsrBodyScripts(getParts(matches))\n }\n\n if (isServer ?? router.isServer) {\n const activeMatches = router.stores.matches.get()\n return renderScripts(\n composeSsrBodyScripts(\n getParts(activeMatches),\n router.serverSsr?.takeInitialHydrationScriptTags(),\n ),\n )\n }\n\n // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static\n const scripts = useSelector(router.stores.matches, getScripts, {\n compare: deepEqual,\n })\n\n return renderScripts(scripts)\n}\n\nfunction renderScripts(scripts: Array<ScriptRenderAsset>) {\n return (\n <>\n {scripts.map((asset, i) => (\n <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />\n ))}\n </>\n )\n}\n"],"mappings":";;;;;;;;AAeA,IAAM,mBAAmB,EAAE,0BAA0B,KAAK;;;;;;AAO1D,IAAa,gBAAgB;CAC3B,MAAM,SAAS,UAAU;CACzB,MAAM,QAAQ,OAAO,QAAQ,KAAK;CAElC,MAAM,YAAY,YAAwB;EACxC,MAAM,QAAQ,sBACZ,SACA,OAAO,KAAK,UACZ,OACA,gBACF;EACA,KAAK,MAAM,UAAU,MAAM,IACzB,IAAI,OAAO,OAAO,OAAO,QAAQ,UAAU;GACzC,MAAM,kBAAkB;GACxB,gBAAgB,qBAAqB;EACvC;EAEF,OAAO;CACT;CAEA,MAAM,cAAc,YAAwB;EAC1C,OAAO,sBAAsB,SAAS,OAAO,CAAC;CAChD;CAEA,IAAI,YAAY,OAAO,UAErB,OAAO,cACL,sBACE,SAHkB,OAAO,OAAO,QAAQ,IAG/B,CAAa,GACtB,OAAO,WAAW,+BAA+B,CACnD,CACF;CAQF,OAAO,cAJS,YAAY,OAAO,OAAO,SAAS,YAAY,EAC7D,SAAS,UACX,CAEqB,CAAO;AAC9B;AAEA,SAAS,cAAc,SAAmC;CACxD,OACE,oBAAA,UAAA,EAAA,UACG,QAAQ,KAAK,OAAO,MACnB,8BAAC,OAAD;EAAO,GAAI;EAAO,KAAK,eAAe,MAAM,IAAI,GAAG;CAAM,CAAA,CAC1D,EACD,CAAA;AAEN"}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ParsedLocation, ScrollRestorationEntry, ScrollRestorationOptions } from '@tanstack/router-core';
|
||||
/**
|
||||
* @deprecated Use the `scrollRestoration` router option instead.
|
||||
*/
|
||||
export declare function ScrollRestoration(_props: ScrollRestorationOptions): null;
|
||||
export declare function useElementScrollRestoration(options: ({
|
||||
id: string;
|
||||
getElement?: () => Window | Element | undefined | null;
|
||||
} | {
|
||||
id?: string;
|
||||
getElement: () => Window | Element | undefined | null;
|
||||
}) & {
|
||||
getKey?: (location: ParsedLocation) => string;
|
||||
}): ScrollRestorationEntry | undefined;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { getElementScrollRestorationEntry, setupScrollRestoration } from "@tanstack/router-core";
|
||||
//#region src/ScrollRestoration.tsx
|
||||
function useScrollRestoration() {
|
||||
setupScrollRestoration(useRouter(), true);
|
||||
}
|
||||
/**
|
||||
* @deprecated Use the `scrollRestoration` router option instead.
|
||||
*/
|
||||
function ScrollRestoration(_props) {
|
||||
useScrollRestoration();
|
||||
if (process.env.NODE_ENV === "development") console.warn("The ScrollRestoration component is deprecated. Use createRouter's `scrollRestoration` option instead.");
|
||||
return null;
|
||||
}
|
||||
function useElementScrollRestoration(options) {
|
||||
useScrollRestoration();
|
||||
return getElementScrollRestorationEntry(useRouter(), options);
|
||||
}
|
||||
//#endregion
|
||||
export { ScrollRestoration, useElementScrollRestoration };
|
||||
|
||||
//# sourceMappingURL=ScrollRestoration.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ScrollRestoration.js","names":[],"sources":["../../src/ScrollRestoration.tsx"],"sourcesContent":["import {\n getElementScrollRestorationEntry,\n setupScrollRestoration,\n} from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport type {\n ParsedLocation,\n ScrollRestorationEntry,\n ScrollRestorationOptions,\n} from '@tanstack/router-core'\n\nfunction useScrollRestoration() {\n const router = useRouter()\n setupScrollRestoration(router, true)\n}\n\n/**\n * @deprecated Use the `scrollRestoration` router option instead.\n */\nexport function ScrollRestoration(_props: ScrollRestorationOptions) {\n useScrollRestoration()\n\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n \"The ScrollRestoration component is deprecated. Use createRouter's `scrollRestoration` option instead.\",\n )\n }\n\n return null\n}\n\nexport function useElementScrollRestoration(\n options: (\n | {\n id: string\n getElement?: () => Window | Element | undefined | null\n }\n | {\n id?: string\n getElement: () => Window | Element | undefined | null\n }\n ) & {\n getKey?: (location: ParsedLocation) => string\n },\n): ScrollRestorationEntry | undefined {\n useScrollRestoration()\n\n return getElementScrollRestorationEntry(useRouter(), options)\n}\n"],"mappings":";;;AAWA,SAAS,uBAAuB;CAE9B,uBADe,UACQ,GAAQ,IAAI;AACrC;;;;AAKA,SAAgB,kBAAkB,QAAkC;CAClE,qBAAqB;CAErB,IAAA,QAAA,IAAA,aAA6B,eAC3B,QAAQ,KACN,uGACF;CAGF,OAAO;AACT;AAEA,SAAgB,4BACd,SAYoC;CACpC,qBAAqB;CAErB,OAAO,iCAAiC,UAAU,GAAG,OAAO;AAC9D"}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { AnyRouter } from '@tanstack/router-core';
|
||||
import * as React from 'react';
|
||||
export declare function settleOwner(owner: NonNullable<AnyRouter['_rendered']>, rendered: boolean): void;
|
||||
export declare function Transitioner({ t, }: {
|
||||
t: React.Dispatch<React.SetStateAction<AnyRouter | undefined>>;
|
||||
}): null;
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
import { useLayoutEffect } from "./utils.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { getLocationChangeInfo, trimPathRight } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
//#region src/Transitioner.tsx
|
||||
function settleOwner(owner, rendered) {
|
||||
const settle = owner[1];
|
||||
owner.length = 0;
|
||||
settle?.(rendered);
|
||||
}
|
||||
function Transitioner({ t }) {
|
||||
const router = useRouter();
|
||||
const acknowledgement = router._rendered ??= [];
|
||||
const mounted = process.env.NODE_ENV !== "production" ? React$1.useRef(false) : void 0;
|
||||
router.startTransition = (fn, expected) => new Promise((resolve) => {
|
||||
settleOwner(acknowledgement, false);
|
||||
acknowledgement.push(expected, resolve);
|
||||
t(router);
|
||||
React$1.startTransition(fn);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
const unsub = router.history.subscribe(router.load);
|
||||
if (mounted?.current) return unsub;
|
||||
if (mounted) mounted.current = true;
|
||||
router.updateLatestLocation();
|
||||
const location = router.latestLocation;
|
||||
const nextLocation = router.buildLocation({
|
||||
to: location.pathname,
|
||||
search: true,
|
||||
params: true,
|
||||
hash: true,
|
||||
state: true,
|
||||
_includeValidateSearch: true
|
||||
});
|
||||
if (trimPathRight(location.publicHref) !== trimPathRight(nextLocation.publicHref)) {
|
||||
router.commitLocation({
|
||||
...nextLocation,
|
||||
replace: true,
|
||||
ignoreBlocker: true
|
||||
});
|
||||
return unsub;
|
||||
}
|
||||
const resolvedLocation = router.stores.resolvedLocation.get();
|
||||
if (resolvedLocation?.href === location.href && resolvedLocation.state.__TSR_key === location.state.__TSR_key) acknowledgement.push(router.stores.matches.get(), (rendered) => {
|
||||
if (rendered) router.emit({
|
||||
type: "onRendered",
|
||||
...getLocationChangeInfo(resolvedLocation, resolvedLocation)
|
||||
});
|
||||
});
|
||||
else if (!router._tx) router.load({ sync: true }).catch(console.error);
|
||||
return unsub;
|
||||
}, [router, router.history]);
|
||||
return null;
|
||||
}
|
||||
//#endregion
|
||||
export { Transitioner, settleOwner };
|
||||
|
||||
//# sourceMappingURL=Transitioner.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"Transitioner.js","names":[],"sources":["../../src/Transitioner.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core'\nimport { useLayoutEffect } from './utils'\nimport { useRouter } from './useRouter'\nimport type { AnyRouter } from '@tanstack/router-core'\n\nexport function settleOwner(\n owner: NonNullable<AnyRouter['_rendered']>,\n rendered: boolean,\n) {\n const settle = owner[1 /* settle */]\n owner.length = 0\n settle?.(rendered)\n}\n\nexport function Transitioner({\n t,\n}: {\n t: React.Dispatch<React.SetStateAction<AnyRouter | undefined>>\n}) {\n const router = useRouter()\n const acknowledgement = (router._rendered ??= [])\n const mounted =\n process.env.NODE_ENV !== 'production'\n ? // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useRef(false)\n : undefined\n\n router.startTransition = (fn, expected) =>\n new Promise((resolve) => {\n settleOwner(acknowledgement, false)\n acknowledgement.push(expected, resolve)\n t(router)\n React.startTransition(fn)\n })\n\n // Subscribe before canonicalizing so the initial URL has exactly one load.\n useLayoutEffect(() => {\n const unsub = router.history.subscribe(router.load)\n\n if (mounted?.current) {\n return unsub\n }\n if (mounted) {\n mounted.current = true\n }\n\n router.updateLatestLocation()\n const location = router.latestLocation\n const nextLocation = router.buildLocation({\n to: location.pathname,\n search: true,\n params: true,\n hash: true,\n state: true,\n _includeValidateSearch: true,\n })\n\n // Check if the current URL matches the canonical form.\n // Compare publicHref (browser-facing URL) consistently with server\n // canonicalization.\n if (\n trimPathRight(location.publicHref) !==\n trimPathRight(nextLocation.publicHref)\n ) {\n router.commitLocation({\n ...nextLocation,\n replace: true,\n ignoreBlocker: true,\n })\n return unsub\n }\n\n const resolvedLocation = router.stores.resolvedLocation.get()\n if (\n resolvedLocation?.href === location.href &&\n resolvedLocation.state.__TSR_key === location.state.__TSR_key\n ) {\n acknowledgement.push(router.stores.matches.get(), (rendered) => {\n if (rendered) {\n router.emit({\n type: 'onRendered',\n ...getLocationChangeInfo(resolvedLocation, resolvedLocation),\n })\n }\n })\n } else if (!router._tx) {\n router.load({ sync: true }).catch(console.error)\n }\n\n return unsub\n // `mounted` exists only in development and is a stable ref when present.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [router, router.history])\n\n return null\n}\n"],"mappings":";;;;;;AAQA,SAAgB,YACd,OACA,UACA;CACA,MAAM,SAAS,MAAM;CACrB,MAAM,SAAS;CACf,SAAS,QAAQ;AACnB;AAEA,SAAgB,aAAa,EAC3B,KAGC;CACD,MAAM,SAAS,UAAU;CACzB,MAAM,kBAAmB,OAAO,cAAc,CAAC;CAC/C,MAAM,UAAA,QAAA,IAAA,aACqB,eAErB,QAAM,OAAO,KAAK,IAClB,KAAA;CAEN,OAAO,mBAAmB,IAAI,aAC5B,IAAI,SAAS,YAAY;EACvB,YAAY,iBAAiB,KAAK;EAClC,gBAAgB,KAAK,UAAU,OAAO;EACtC,EAAE,MAAM;EACR,QAAM,gBAAgB,EAAE;CAC1B,CAAC;CAGH,sBAAsB;EACpB,MAAM,QAAQ,OAAO,QAAQ,UAAU,OAAO,IAAI;EAElD,IAAI,SAAS,SACX,OAAO;EAET,IAAI,SACF,QAAQ,UAAU;EAGpB,OAAO,qBAAqB;EAC5B,MAAM,WAAW,OAAO;EACxB,MAAM,eAAe,OAAO,cAAc;GACxC,IAAI,SAAS;GACb,QAAQ;GACR,QAAQ;GACR,MAAM;GACN,OAAO;GACP,wBAAwB;EAC1B,CAAC;EAKD,IACE,cAAc,SAAS,UAAU,MACjC,cAAc,aAAa,UAAU,GACrC;GACA,OAAO,eAAe;IACpB,GAAG;IACH,SAAS;IACT,eAAe;GACjB,CAAC;GACD,OAAO;EACT;EAEA,MAAM,mBAAmB,OAAO,OAAO,iBAAiB,IAAI;EAC5D,IACE,kBAAkB,SAAS,SAAS,QACpC,iBAAiB,MAAM,cAAc,SAAS,MAAM,WAEpD,gBAAgB,KAAK,OAAO,OAAO,QAAQ,IAAI,IAAI,aAAa;GAC9D,IAAI,UACF,OAAO,KAAK;IACV,MAAM;IACN,GAAG,sBAAsB,kBAAkB,gBAAgB;GAC7D,CAAC;EAEL,CAAC;OACI,IAAI,CAAC,OAAO,KACjB,OAAO,KAAK,EAAE,MAAM,KAAK,CAAC,EAAE,MAAM,QAAQ,KAAK;EAGjD,OAAO;CAGT,GAAG,CAAC,QAAQ,OAAO,OAAO,CAAC;CAE3B,OAAO;AACT"}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import * as React from 'react';
|
||||
export type AwaitOptions<T> = {
|
||||
promise: Promise<T>;
|
||||
};
|
||||
/** Suspend until a deferred promise resolves or rejects and return its data. */
|
||||
export declare function useAwaited<T>({ promise: _promise }: AwaitOptions<T>): T;
|
||||
/**
|
||||
* Component that suspends on a deferred promise and renders its child with
|
||||
* the resolved value. Optionally provides a Suspense fallback.
|
||||
*/
|
||||
export declare function Await<T>(props: AwaitOptions<T> & {
|
||||
fallback?: React.ReactNode;
|
||||
children: (result: T) => React.ReactNode;
|
||||
}): import("react/jsx-runtime").JSX.Element;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { reactUse } from "./utils.js";
|
||||
import { TSR_DEFERRED_PROMISE, defer } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/awaited.tsx
|
||||
/** Suspend until a deferred promise resolves or rejects and return its data. */
|
||||
function useAwaited({ promise: _promise }) {
|
||||
if (reactUse) return reactUse(_promise);
|
||||
const promise = defer(_promise);
|
||||
if (promise[TSR_DEFERRED_PROMISE].status === "pending") throw promise;
|
||||
if (promise[TSR_DEFERRED_PROMISE].status === "error") throw promise[TSR_DEFERRED_PROMISE].error;
|
||||
return promise[TSR_DEFERRED_PROMISE].data;
|
||||
}
|
||||
/**
|
||||
* Component that suspends on a deferred promise and renders its child with
|
||||
* the resolved value. Optionally provides a Suspense fallback.
|
||||
*/
|
||||
function Await(props) {
|
||||
const inner = /* @__PURE__ */ jsx(AwaitInner, { ...props });
|
||||
if (props.fallback) return /* @__PURE__ */ jsx(React$1.Suspense, {
|
||||
fallback: props.fallback,
|
||||
children: inner
|
||||
});
|
||||
return inner;
|
||||
}
|
||||
function AwaitInner(props) {
|
||||
const data = useAwaited(props);
|
||||
return props.children(data);
|
||||
}
|
||||
//#endregion
|
||||
export { Await, useAwaited };
|
||||
|
||||
//# sourceMappingURL=awaited.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"awaited.js","names":[],"sources":["../../src/awaited.tsx"],"sourcesContent":["import * as React from 'react'\n\nimport { TSR_DEFERRED_PROMISE, defer } from '@tanstack/router-core'\nimport { reactUse } from './utils'\n\nexport type AwaitOptions<T> = {\n promise: Promise<T>\n}\n\n/** Suspend until a deferred promise resolves or rejects and return its data. */\nexport function useAwaited<T>({ promise: _promise }: AwaitOptions<T>): T {\n if (reactUse) {\n const data = reactUse(_promise)\n return data\n }\n const promise = defer(_promise)\n\n if (promise[TSR_DEFERRED_PROMISE].status === 'pending') {\n throw promise\n }\n\n if (promise[TSR_DEFERRED_PROMISE].status === 'error') {\n throw promise[TSR_DEFERRED_PROMISE].error\n }\n\n return promise[TSR_DEFERRED_PROMISE].data\n}\n\n/**\n * Component that suspends on a deferred promise and renders its child with\n * the resolved value. Optionally provides a Suspense fallback.\n */\nexport function Await<T>(\n props: AwaitOptions<T> & {\n fallback?: React.ReactNode\n children: (result: T) => React.ReactNode\n },\n) {\n const inner = <AwaitInner {...props} />\n if (props.fallback) {\n return <React.Suspense fallback={props.fallback}>{inner}</React.Suspense>\n }\n return inner\n}\n\nfunction AwaitInner<T>(\n props: AwaitOptions<T> & {\n fallback?: React.ReactNode\n children: (result: T) => React.ReactNode\n },\n): React.JSX.Element {\n const data = useAwaited(props)\n\n return props.children(data) as React.JSX.Element\n}\n"],"mappings":";;;;;;AAUA,SAAgB,WAAc,EAAE,SAAS,YAAgC;CACvE,IAAI,UAEF,OADa,SAAS,QACf;CAET,MAAM,UAAU,MAAM,QAAQ;CAE9B,IAAI,QAAQ,sBAAsB,WAAW,WAC3C,MAAM;CAGR,IAAI,QAAQ,sBAAsB,WAAW,SAC3C,MAAM,QAAQ,sBAAsB;CAGtC,OAAO,QAAQ,sBAAsB;AACvC;;;;;AAMA,SAAgB,MACd,OAIA;CACA,MAAM,QAAQ,oBAAC,YAAD,EAAY,GAAI,MAAQ,CAAA;CACtC,IAAI,MAAM,UACR,OAAO,oBAAC,QAAM,UAAP;EAAgB,UAAU,MAAM;YAAW;CAAsB,CAAA;CAE1E,OAAO;AACT;AAEA,SAAS,WACP,OAImB;CACnB,MAAM,OAAO,WAAW,KAAK;CAE7B,OAAO,MAAM,SAAS,IAAI;AAC5B"}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import { UseParamsRoute } from './useParams.js';
|
||||
import { UseMatchRoute } from './useMatch.js';
|
||||
import { UseSearchRoute } from './useSearch.js';
|
||||
import { AnyContext, AnyRoute, AnyRouter, Constrain, ConstrainLiteral, FileBaseRouteOptions, FileRoutesByPath, LazyRouteOptions, Register, RegisteredRouter, ResolveParams, Route, RouteById, RouteConstraints, RouteIds, RouteLoaderEntry, UpdatableRouteOptions, UseNavigateResult } from '@tanstack/router-core';
|
||||
import { UseLoaderDepsRoute } from './useLoaderDeps.js';
|
||||
import { UseLoaderDataRoute } from './useLoaderData.js';
|
||||
import { UseRouteContextRoute } from './useRouteContext.js';
|
||||
/**
|
||||
* Creates a file-based Route factory for a given path.
|
||||
*
|
||||
* Used by TanStack Router's file-based routing to associate a file with a
|
||||
* route. The returned function accepts standard route options. In normal usage
|
||||
* the `path` string is inserted and maintained by the `tsr` generator.
|
||||
*
|
||||
* @param path File path literal for the route (usually auto-generated).
|
||||
* @returns A function that accepts Route options and returns a Route instance.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction
|
||||
*/
|
||||
export declare function createFileRoute<TFilePath extends keyof FileRoutesByPath, TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'], TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'], TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'], TFullPath extends RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath']>(path?: TFilePath): FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>['createRoute'];
|
||||
/**
|
||||
@deprecated It's no longer recommended to use the `FileRoute` class directly.
|
||||
Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
|
||||
*/
|
||||
export declare class FileRoute<TFilePath extends keyof FileRoutesByPath, TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'], TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'], TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'], TFullPath extends RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath']> {
|
||||
path?: TFilePath | undefined;
|
||||
silent?: boolean;
|
||||
constructor(path?: TFilePath | undefined, _opts?: {
|
||||
silent: boolean;
|
||||
});
|
||||
createRoute: <TRegister = Register, TSearchValidator = undefined, TParams = ResolveParams<TPath>, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TChildren = unknown, TSSR = unknown, const TMiddlewares = unknown, THandlers = undefined>(options?: FileBaseRouteOptions<TRegister, TParentRoute, TId, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, AnyContext, TRouteContextFn, TBeforeLoadFn, AnyContext, TSSR, TMiddlewares, THandlers> & UpdatableRouteOptions<TParentRoute, TId, TFullPath, TParams, TSearchValidator, TLoaderFn, TLoaderDeps, AnyContext, TRouteContextFn, TBeforeLoadFn>) => Route<TRegister, TParentRoute, TPath, TFullPath, TFilePath, TId, TSearchValidator, TParams, AnyContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, unknown, TSSR, TMiddlewares, THandlers>;
|
||||
}
|
||||
/**
|
||||
@deprecated It's recommended not to split loaders into separate files.
|
||||
Instead, place the loader function in the main route file via `createFileRoute`.
|
||||
*/
|
||||
export declare function FileRouteLoader<TFilePath extends keyof FileRoutesByPath, TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute']>(_path: TFilePath): <TLoaderFn>(loaderFn: Constrain<TLoaderFn, RouteLoaderEntry<Register, TRoute['parentRoute'], TRoute['types']['id'], TRoute['types']['params'], TRoute['types']['loaderDeps'], TRoute['types']['routerContext'], TRoute['types']['routeContextFn'], TRoute['types']['beforeLoadFn']>>) => TLoaderFn;
|
||||
declare module '@tanstack/router-core' {
|
||||
interface LazyRoute<in out TRoute extends AnyRoute> {
|
||||
useMatch: UseMatchRoute<TRoute['id']>;
|
||||
useRouteContext: UseRouteContextRoute<TRoute['id']>;
|
||||
useSearch: UseSearchRoute<TRoute['id']>;
|
||||
useParams: UseParamsRoute<TRoute['id']>;
|
||||
useLoaderDeps: UseLoaderDepsRoute<TRoute['id']>;
|
||||
useLoaderData: UseLoaderDataRoute<TRoute['id']>;
|
||||
useNavigate: () => UseNavigateResult<TRoute['fullPath']>;
|
||||
}
|
||||
}
|
||||
export declare class LazyRoute<TRoute extends AnyRoute> {
|
||||
options: {
|
||||
id: string;
|
||||
} & LazyRouteOptions;
|
||||
constructor(opts: {
|
||||
id: string;
|
||||
} & LazyRouteOptions);
|
||||
useMatch: UseMatchRoute<TRoute['id']>;
|
||||
useRouteContext: UseRouteContextRoute<TRoute['id']>;
|
||||
useSearch: UseSearchRoute<TRoute['id']>;
|
||||
useParams: UseParamsRoute<TRoute['id']>;
|
||||
useLoaderDeps: UseLoaderDepsRoute<TRoute['id']>;
|
||||
useLoaderData: UseLoaderDataRoute<TRoute['id']>;
|
||||
useNavigate: () => UseNavigateResult<TRoute["fullPath"]>;
|
||||
}
|
||||
/**
|
||||
* Creates a lazily-configurable code-based route stub by ID.
|
||||
*
|
||||
* Use this for code-splitting with code-based routes. The returned function
|
||||
* accepts only non-critical route options like `component`, `pendingComponent`,
|
||||
* `errorComponent`, and `notFoundComponent` which are applied when the route
|
||||
* is matched.
|
||||
*
|
||||
* @param id Route ID string literal to associate with the lazy route.
|
||||
* @returns A function that accepts lazy route options and returns a `LazyRoute`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyRouteFunction
|
||||
*/
|
||||
export declare function createLazyRoute<TRouter extends AnyRouter = RegisteredRouter, TId extends string = string, TRoute extends AnyRoute = RouteById<TRouter['routeTree'], TId>>(id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>): (opts: LazyRouteOptions) => LazyRoute<TRoute>;
|
||||
/**
|
||||
* Creates a lazily-configurable file-based route stub by file path.
|
||||
*
|
||||
* Use this for code-splitting with file-based routes (eg. `.lazy.tsx` files).
|
||||
* The returned function accepts only non-critical route options like
|
||||
* `component`, `pendingComponent`, `errorComponent`, and `notFoundComponent`.
|
||||
*
|
||||
* @param id File path literal for the route file.
|
||||
* @returns A function that accepts lazy route options and returns a `LazyRoute`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyFileRouteFunction
|
||||
*/
|
||||
export declare function createLazyFileRoute<TFilePath extends keyof FileRoutesByPath, TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute']>(id: TFilePath): (opts: LazyRouteOptions) => LazyRoute<TRoute>;
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { useMatch } from "./useMatch.js";
|
||||
import { useLoaderData } from "./useLoaderData.js";
|
||||
import { useLoaderDeps } from "./useLoaderDeps.js";
|
||||
import { useParams } from "./useParams.js";
|
||||
import { useSearch } from "./useSearch.js";
|
||||
import { useNavigate } from "./useNavigate.js";
|
||||
import { useRouteContext } from "./useRouteContext.js";
|
||||
import { createRoute } from "./route.js";
|
||||
//#region src/fileRoute.ts
|
||||
/**
|
||||
* Creates a file-based Route factory for a given path.
|
||||
*
|
||||
* Used by TanStack Router's file-based routing to associate a file with a
|
||||
* route. The returned function accepts standard route options. In normal usage
|
||||
* the `path` string is inserted and maintained by the `tsr` generator.
|
||||
*
|
||||
* @param path File path literal for the route (usually auto-generated).
|
||||
* @returns A function that accepts Route options and returns a Route instance.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction
|
||||
*/
|
||||
function createFileRoute(path) {
|
||||
return (options) => {
|
||||
const route = createRoute(options);
|
||||
route.isRoot = false;
|
||||
return route;
|
||||
};
|
||||
}
|
||||
/**
|
||||
@deprecated It's no longer recommended to use the `FileRoute` class directly.
|
||||
Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
|
||||
*/
|
||||
var FileRoute = class {
|
||||
constructor(path, _opts) {
|
||||
this.path = path;
|
||||
this.createRoute = (options) => {
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
if (!this.silent) console.warn("Warning: FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.");
|
||||
}
|
||||
const route = createRoute(options);
|
||||
route.isRoot = false;
|
||||
return route;
|
||||
};
|
||||
this.silent = _opts?.silent;
|
||||
}
|
||||
};
|
||||
/**
|
||||
@deprecated It's recommended not to split loaders into separate files.
|
||||
Instead, place the loader function in the main route file via `createFileRoute`.
|
||||
*/
|
||||
function FileRouteLoader(_path) {
|
||||
if (process.env.NODE_ENV !== "production") console.warn(`Warning: FileRouteLoader is deprecated and will be removed in the next major version. Please place the loader function in the main route file, inside the \`createFileRoute('/path/to/file')(options)\` options`);
|
||||
return (loaderFn) => loaderFn;
|
||||
}
|
||||
var LazyRoute = class {
|
||||
constructor(opts) {
|
||||
this.useMatch = (opts) => {
|
||||
return useMatch({
|
||||
...opts,
|
||||
from: this.options.id
|
||||
});
|
||||
};
|
||||
this.useRouteContext = (opts) => {
|
||||
return useRouteContext({
|
||||
...opts,
|
||||
from: this.options.id
|
||||
});
|
||||
};
|
||||
this.useSearch = (opts) => {
|
||||
return useSearch({
|
||||
...opts,
|
||||
from: this.options.id
|
||||
});
|
||||
};
|
||||
this.useParams = (opts) => {
|
||||
return useParams({
|
||||
...opts,
|
||||
from: this.options.id
|
||||
});
|
||||
};
|
||||
this.useLoaderDeps = (opts) => {
|
||||
return useLoaderDeps({
|
||||
...opts,
|
||||
from: this.options.id
|
||||
});
|
||||
};
|
||||
this.useLoaderData = (opts) => {
|
||||
return useLoaderData({
|
||||
...opts,
|
||||
from: this.options.id
|
||||
});
|
||||
};
|
||||
this.useNavigate = () => {
|
||||
return useNavigate({ from: useRouter().routesById[this.options.id].fullPath });
|
||||
};
|
||||
this.options = opts;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Creates a lazily-configurable code-based route stub by ID.
|
||||
*
|
||||
* Use this for code-splitting with code-based routes. The returned function
|
||||
* accepts only non-critical route options like `component`, `pendingComponent`,
|
||||
* `errorComponent`, and `notFoundComponent` which are applied when the route
|
||||
* is matched.
|
||||
*
|
||||
* @param id Route ID string literal to associate with the lazy route.
|
||||
* @returns A function that accepts lazy route options and returns a `LazyRoute`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyRouteFunction
|
||||
*/
|
||||
function createLazyRoute(id) {
|
||||
return (opts) => {
|
||||
return new LazyRoute({
|
||||
id,
|
||||
...opts
|
||||
});
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Creates a lazily-configurable file-based route stub by file path.
|
||||
*
|
||||
* Use this for code-splitting with file-based routes (eg. `.lazy.tsx` files).
|
||||
* The returned function accepts only non-critical route options like
|
||||
* `component`, `pendingComponent`, `errorComponent`, and `notFoundComponent`.
|
||||
*
|
||||
* @param id File path literal for the route file.
|
||||
* @returns A function that accepts lazy route options and returns a `LazyRoute`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyFileRouteFunction
|
||||
*/
|
||||
function createLazyFileRoute(id) {
|
||||
if (typeof id === "object") return new LazyRoute(id);
|
||||
return (opts) => new LazyRoute({
|
||||
id,
|
||||
...opts
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { FileRoute, FileRouteLoader, LazyRoute, createFileRoute, createLazyFileRoute, createLazyRoute };
|
||||
|
||||
//# sourceMappingURL=fileRoute.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"fileRoute.js","names":[],"sources":["../../src/fileRoute.ts"],"sourcesContent":["import { createRoute } from './route'\n\nimport { useMatch } from './useMatch'\nimport { useLoaderDeps } from './useLoaderDeps'\nimport { useLoaderData } from './useLoaderData'\nimport { useSearch } from './useSearch'\nimport { useParams } from './useParams'\nimport { useNavigate } from './useNavigate'\nimport { useRouter } from './useRouter'\nimport { useRouteContext } from './useRouteContext'\nimport type { UseParamsRoute } from './useParams'\nimport type { UseMatchRoute } from './useMatch'\nimport type { UseSearchRoute } from './useSearch'\nimport type {\n AnyContext,\n AnyRoute,\n AnyRouter,\n Constrain,\n ConstrainLiteral,\n FileBaseRouteOptions,\n FileRoutesByPath,\n LazyRouteOptions,\n Register,\n RegisteredRouter,\n ResolveParams,\n Route,\n RouteById,\n RouteConstraints,\n RouteIds,\n RouteLoaderEntry,\n UpdatableRouteOptions,\n UseNavigateResult,\n} from '@tanstack/router-core'\nimport type { UseLoaderDepsRoute } from './useLoaderDeps'\nimport type { UseLoaderDataRoute } from './useLoaderData'\nimport type { UseRouteContextRoute } from './useRouteContext'\n\n/**\n * Creates a file-based Route factory for a given path.\n *\n * Used by TanStack Router's file-based routing to associate a file with a\n * route. The returned function accepts standard route options. In normal usage\n * the `path` string is inserted and maintained by the `tsr` generator.\n *\n * @param path File path literal for the route (usually auto-generated).\n * @returns A function that accepts Route options and returns a Route instance.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction\n */\nexport function createFileRoute<\n TFilePath extends keyof FileRoutesByPath,\n TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],\n TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],\n TFullPath extends RouteConstraints['TFullPath'] =\n FileRoutesByPath[TFilePath]['fullPath'],\n>(\n // eslint-disable-next-line unused-imports/no-unused-vars\n path?: TFilePath,\n): FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>['createRoute'] {\n return (options) => {\n const route = createRoute(options as any)\n ;(route as any).isRoot = false\n return route as any\n }\n}\n\n/** \n @deprecated It's no longer recommended to use the `FileRoute` class directly.\n Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.\n*/\nexport class FileRoute<\n TFilePath extends keyof FileRoutesByPath,\n TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],\n TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],\n TFullPath extends RouteConstraints['TFullPath'] =\n FileRoutesByPath[TFilePath]['fullPath'],\n> {\n silent?: boolean\n\n constructor(\n public path?: TFilePath,\n _opts?: { silent: boolean },\n ) {\n this.silent = _opts?.silent\n }\n\n createRoute = <\n TRegister = Register,\n TSearchValidator = undefined,\n TParams = ResolveParams<TPath>,\n TRouteContextFn = AnyContext,\n TBeforeLoadFn = AnyContext,\n TLoaderDeps extends Record<string, any> = {},\n TLoaderFn = undefined,\n TChildren = unknown,\n TSSR = unknown,\n const TMiddlewares = unknown,\n THandlers = undefined,\n >(\n options?: FileBaseRouteOptions<\n TRegister,\n TParentRoute,\n TId,\n TPath,\n TSearchValidator,\n TParams,\n TLoaderDeps,\n TLoaderFn,\n AnyContext,\n TRouteContextFn,\n TBeforeLoadFn,\n AnyContext,\n TSSR,\n TMiddlewares,\n THandlers\n > &\n UpdatableRouteOptions<\n TParentRoute,\n TId,\n TFullPath,\n TParams,\n TSearchValidator,\n TLoaderFn,\n TLoaderDeps,\n AnyContext,\n TRouteContextFn,\n TBeforeLoadFn\n >,\n ): Route<\n TRegister,\n TParentRoute,\n TPath,\n TFullPath,\n TFilePath,\n TId,\n TSearchValidator,\n TParams,\n AnyContext,\n TRouteContextFn,\n TBeforeLoadFn,\n TLoaderDeps,\n TLoaderFn,\n TChildren,\n unknown,\n TSSR,\n TMiddlewares,\n THandlers\n > => {\n if (process.env.NODE_ENV !== 'production') {\n if (!this.silent) {\n console.warn(\n 'Warning: FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.',\n )\n }\n }\n const route = createRoute(options as any)\n ;(route as any).isRoot = false\n return route as any\n }\n}\n\n/**\n @deprecated It's recommended not to split loaders into separate files.\n Instead, place the loLine truncated
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { AssetCrossOriginConfig, RouterManagedTag } from '@tanstack/router-core';
|
||||
/**
|
||||
* Build the head/link/meta/script tags from the renderable presented prefix.
|
||||
* Used internally by `HeadContent`.
|
||||
*/
|
||||
export declare const useTags: (assetCrossOrigin?: AssetCrossOriginConfig) => RouterManagedTag[];
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { _getAssetMatches, appendUniqueUserTags, deepEqual, escapeHtml, getAssetCrossOrigin, getScriptPreloadAttrs, resolveManifestCssLink } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { useSelector } from "@tanstack/react-store";
|
||||
//#region src/headContentUtils.tsx
|
||||
function buildTagsFromMatches(router, nonce, matches, assetCrossOrigin) {
|
||||
matches = _getAssetMatches(matches);
|
||||
const routeMeta = matches.map((match) => match.meta).filter((meta) => meta !== void 0);
|
||||
const resultMeta = [];
|
||||
const metaByAttribute = {};
|
||||
let title;
|
||||
for (let i = routeMeta.length - 1; i >= 0; i--) {
|
||||
const metas = routeMeta[i];
|
||||
for (let j = metas.length - 1; j >= 0; j--) {
|
||||
const m = metas[j];
|
||||
if (!m) continue;
|
||||
if (m.title) {
|
||||
if (!title) title = {
|
||||
tag: "title",
|
||||
children: m.title
|
||||
};
|
||||
} else if ("script:ld+json" in m) try {
|
||||
const json = JSON.stringify(m["script:ld+json"]);
|
||||
resultMeta.push({
|
||||
tag: "script",
|
||||
attrs: { type: "application/ld+json" },
|
||||
children: escapeHtml(json)
|
||||
});
|
||||
} catch {}
|
||||
else {
|
||||
const attribute = m.name ?? m.property;
|
||||
if (attribute) if (metaByAttribute[attribute]) continue;
|
||||
else metaByAttribute[attribute] = true;
|
||||
resultMeta.push({
|
||||
tag: "meta",
|
||||
attrs: {
|
||||
...m,
|
||||
nonce
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (title) resultMeta.push(title);
|
||||
if (nonce) resultMeta.push({
|
||||
tag: "meta",
|
||||
attrs: {
|
||||
property: "csp-nonce",
|
||||
content: nonce
|
||||
}
|
||||
});
|
||||
resultMeta.reverse();
|
||||
const constructedLinks = matches.flatMap((match) => match.links ?? []).filter((link) => link !== void 0).map((link) => ({
|
||||
tag: "link",
|
||||
attrs: {
|
||||
...link,
|
||||
nonce
|
||||
}
|
||||
}));
|
||||
const manifest = router.ssr?.manifest;
|
||||
const manifestCssTags = [];
|
||||
if (manifest) {
|
||||
matches.forEach((match) => {
|
||||
(manifest.routes[match.routeId]?.css)?.forEach((link) => {
|
||||
const resolvedLink = resolveManifestCssLink(link);
|
||||
manifestCssTags.push({
|
||||
tag: "link",
|
||||
attrs: {
|
||||
rel: "stylesheet",
|
||||
...resolvedLink,
|
||||
crossOrigin: getAssetCrossOrigin(assetCrossOrigin, "stylesheet") ?? resolvedLink.crossOrigin,
|
||||
suppressHydrationWarning: true,
|
||||
nonce
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if (manifest.inlineStyle) manifestCssTags.push({
|
||||
tag: "style",
|
||||
attrs: {
|
||||
...manifest.inlineStyle.attrs,
|
||||
nonce
|
||||
},
|
||||
children: manifest.inlineStyle.children,
|
||||
inlineCss: true
|
||||
});
|
||||
}
|
||||
const preloadLinks = [];
|
||||
if (manifest) matches.forEach((match) => {
|
||||
manifest.routes[match.routeId]?.preloads?.forEach((preload) => {
|
||||
preloadLinks.push({
|
||||
tag: "link",
|
||||
attrs: {
|
||||
...getScriptPreloadAttrs(manifest, preload, assetCrossOrigin),
|
||||
nonce
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
const styles = matches.flatMap((match) => match.styles ?? []).filter((style) => style !== void 0).map(({ children, ...attrs }) => ({
|
||||
tag: "style",
|
||||
attrs: {
|
||||
...attrs,
|
||||
nonce
|
||||
},
|
||||
children
|
||||
}));
|
||||
const headScripts = matches.flatMap((match) => match.headScripts ?? []).filter((script) => script !== void 0).map(({ children, ...script }) => ({
|
||||
tag: "script",
|
||||
attrs: {
|
||||
...script,
|
||||
nonce
|
||||
},
|
||||
children
|
||||
}));
|
||||
const tags = [];
|
||||
appendUniqueUserTags(tags, resultMeta);
|
||||
tags.push(...preloadLinks);
|
||||
appendUniqueUserTags(tags, constructedLinks);
|
||||
tags.push(...manifestCssTags);
|
||||
appendUniqueUserTags(tags, styles);
|
||||
appendUniqueUserTags(tags, headScripts);
|
||||
return tags;
|
||||
}
|
||||
/**
|
||||
* Build the head/link/meta/script tags from the renderable presented prefix.
|
||||
* Used internally by `HeadContent`.
|
||||
*/
|
||||
var useTags = (assetCrossOrigin) => {
|
||||
const router = useRouter();
|
||||
const nonce = router.options.ssr?.nonce;
|
||||
if (isServer ?? router.isServer) return buildTagsFromMatches(router, nonce, router.stores.matches.get(), assetCrossOrigin);
|
||||
const selectTags = React$1.useCallback((matches) => buildTagsFromMatches(router, nonce, matches, assetCrossOrigin), [
|
||||
assetCrossOrigin,
|
||||
nonce,
|
||||
router
|
||||
]);
|
||||
return useSelector(router.stores.matches, selectTags, { compare: deepEqual });
|
||||
};
|
||||
//#endregion
|
||||
export { useTags };
|
||||
|
||||
//# sourceMappingURL=headContentUtils.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"headContentUtils.js","names":[],"sources":["../../src/headContentUtils.tsx"],"sourcesContent":["import * as React from 'react'\nimport { useSelector } from '@tanstack/react-store'\nimport {\n _getAssetMatches,\n appendUniqueUserTags,\n deepEqual,\n escapeHtml,\n getAssetCrossOrigin,\n getScriptPreloadAttrs,\n resolveManifestCssLink,\n} from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { useRouter } from './useRouter'\nimport type {\n AnyRouteMatch,\n AssetCrossOriginConfig,\n RouterManagedTag,\n} from '@tanstack/router-core'\n\nfunction buildTagsFromMatches(\n router: ReturnType<typeof useRouter>,\n nonce: string | undefined,\n matches: Array<AnyRouteMatch>,\n assetCrossOrigin?: AssetCrossOriginConfig,\n): Array<RouterManagedTag> {\n matches = _getAssetMatches(matches)\n const routeMeta = matches\n .map((match) => match.meta)\n .filter((meta) => meta !== undefined)\n\n const resultMeta: Array<RouterManagedTag> = []\n const metaByAttribute: Record<string, true> = {}\n let title: RouterManagedTag | undefined\n for (let i = routeMeta.length - 1; i >= 0; i--) {\n const metas = routeMeta[i]!\n for (let j = metas.length - 1; j >= 0; j--) {\n const m = metas[j]\n if (!m) continue\n\n if (m.title) {\n if (!title) {\n title = {\n tag: 'title',\n children: m.title,\n }\n }\n } else if ('script:ld+json' in m) {\n try {\n const json = JSON.stringify(m['script:ld+json'])\n resultMeta.push({\n tag: 'script',\n attrs: {\n type: 'application/ld+json',\n },\n children: escapeHtml(json),\n })\n } catch {\n // Skip invalid JSON-LD objects\n }\n } else {\n const attribute = m.name ?? m.property\n if (attribute) {\n if (metaByAttribute[attribute]) {\n continue\n } else {\n metaByAttribute[attribute] = true\n }\n }\n\n resultMeta.push({\n tag: 'meta',\n attrs: {\n ...m,\n nonce,\n },\n })\n }\n }\n }\n\n if (title) {\n resultMeta.push(title)\n }\n\n if (nonce) {\n resultMeta.push({\n tag: 'meta',\n attrs: {\n property: 'csp-nonce',\n content: nonce,\n },\n })\n }\n resultMeta.reverse()\n\n const constructedLinks = matches\n .flatMap((match) => match.links ?? [])\n .filter((link) => link !== undefined)\n .map((link) => ({\n tag: 'link',\n attrs: {\n ...link,\n nonce,\n },\n })) satisfies Array<RouterManagedTag>\n\n const manifest = router.ssr?.manifest\n const manifestCssTags: Array<RouterManagedTag> = []\n if (manifest) {\n matches.forEach((match) => {\n const css = manifest.routes[match.routeId]?.css\n css?.forEach((link) => {\n const resolvedLink = resolveManifestCssLink(link)\n manifestCssTags.push({\n tag: 'link',\n attrs: {\n rel: 'stylesheet',\n ...resolvedLink,\n crossOrigin:\n getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ??\n resolvedLink.crossOrigin,\n suppressHydrationWarning: true,\n nonce,\n },\n })\n })\n })\n\n if (manifest.inlineStyle) {\n manifestCssTags.push({\n tag: 'style',\n attrs: {\n ...manifest.inlineStyle.attrs,\n nonce,\n },\n children: manifest.inlineStyle.children,\n inlineCss: true,\n })\n }\n }\n\n const preloadLinks: Array<RouterManagedTag> = []\n if (manifest) {\n matches.forEach((match) => {\n manifest.routes[match.routeId]?.preloads?.forEach((preload) => {\n preloadLinks.push({\n tag: 'link',\n attrs: {\n ...getScriptPreloadAttrs(manifest, preload, assetCrossOrigin),\n nonce,\n },\n })\n })\n })\n }\n\n const styles = matches\n .flatMap((match) => match.styles ?? [])\n .filter((style) => style !== undefined)\n .map(({ children, ...attrs }) => ({\n tag: 'style',\n attrs: {\n ...attrs,\n nonce,\n },\n children: children as string | undefined,\n })) satisfies Array<RouterManagedTag>\n\n const headScripts = matches\n .flatMap((match) => match.headScripts ?? [])\n .filter((script) => script !== undefined)\n .map(({ children, ...script }) => ({\n tag: 'script',\n attrs: {\n ...script,\n nonce,\n },\n children: children as string | undefined,\n })) satisfies Array<RouterManagedTag>\n\n const tags: Array<RouterManagedTag> = []\n appendUniqueUserTags(tags, resultMeta)\n tags.push(...preloadLinks)\n appendUniqueUserTags(tags, constructedLinks)\n tags.push(...manifestCssTags)\n appendUniqueUseLine truncated
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
declare module '@tanstack/history' {
|
||||
interface HistoryState {
|
||||
__tempLocation?: HistoryLocation;
|
||||
__tempKey?: string;
|
||||
__hashScrollIntoViewOptions?: boolean | ScrollIntoViewOptions;
|
||||
}
|
||||
}
|
||||
export {};
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
export { defer, isMatch, joinPaths, cleanPath, trimPathLeft, trimPathRight, trimPath, resolvePath, interpolatePath, rootRouteId, defaultParseSearch, defaultStringifySearch, parseSearchWith, stringifySearchWith, functionalUpdate, replaceEqualDeep, deepEqual, createControlledPromise, retainSearchParams, stripSearchParams, createSerializationAdapter, } from '@tanstack/router-core';
|
||||
export type { AnyRoute, DeferredPromiseState, DeferredPromise, ParsedLocation, RemoveTrailingSlashes, RemoveLeadingSlashes, ActiveOptions, ResolveRelativePath, RootRouteId, AnyPathParams, ResolveParams, ResolveOptionalParams, ResolveRequiredParams, SearchSchemaInput, AnyContext, RouteContext, PreloadableObj, RoutePathOptions, StaticDataRouteOption, RoutePathOptionsIntersection, UpdatableStaticRouteOption, MetaDescriptor, RouteLinkEntry, ParseParamsFn, SearchFilter, ResolveId, InferFullSearchSchema, InferFullSearchSchemaInput, ErrorRouteProps, ErrorComponentProps, NotFoundRouteProps, TrimPath, TrimPathLeft, TrimPathRight, StringifyParamsFn, ParamsOptions, InferAllParams, InferAllContext, LooseReturnType, LooseAsyncReturnType, ContextReturnType, ContextAsyncReturnType, ResolveLoaderData, ResolveRouteContext, SearchSerializer, SearchParser, SearchMiddleware, TrailingSlashOption, Manifest, RouterManagedTag, ControlledPromise, Constrain, Expand, MergeAll, Assign, IntersectAssign, ResolveValidatorInput, ResolveValidatorOutput, Register, AnyValidator, DefaultValidator, ValidatorFn, AnySchema, AnyValidatorAdapter, AnyValidatorFn, AnyValidatorObj, ResolveValidatorInputFn, ResolveValidatorOutputFn, ResolveSearchValidatorInput, ResolveSearchValidatorInputFn, Validator, ValidatorAdapter, ValidatorObj, FileRoutesByPath, RouteById, RootRouteOptions, CreateFileRoute, SerializationAdapter, AnySerializationAdapter, SerializableExtensions, } from '@tanstack/router-core';
|
||||
export { createHistory, createBrowserHistory, createHashHistory, createMemoryHistory, } from '@tanstack/history';
|
||||
export type { BlockerFn, HistoryLocation, RouterHistory, ParsedPath, HistoryState, } from '@tanstack/history';
|
||||
export { useAwaited, Await } from './awaited.js';
|
||||
export type { AwaitOptions } from './awaited.js';
|
||||
export { CatchBoundary, ErrorComponent } from './CatchBoundary.js';
|
||||
export { ClientOnly, useHydrated } from './ClientOnly.js';
|
||||
export { reactUse, useLayoutEffect } from './utils.js';
|
||||
export { FileRoute, createFileRoute, FileRouteLoader, LazyRoute, createLazyRoute, createLazyFileRoute, } from './fileRoute.js';
|
||||
export * from './history.js';
|
||||
export { lazyRouteComponent } from './lazyRouteComponent.js';
|
||||
export { useLinkProps, createLink, Link, linkOptions } from './link.js';
|
||||
export type { InferDescendantToPaths, RelativeToPath, RelativeToParentPath, RelativeToCurrentPath, AbsoluteToPath, RelativeToPathAutoComplete, NavigateOptions, ToOptions, ToMaskOptions, ToSubOptions, ResolveRoute, SearchParamOptions, PathParamOptions, ToPathOption, LinkOptions, MakeOptionalPathParams, FileRouteTypes, RouteContextParameter, BeforeLoadContextParameter, ResolveAllContext, ResolveAllParamsFromParent, ResolveFullSearchSchema, ResolveFullSearchSchemaInput, RouteIds, NavigateFn, BuildLocationFn, FullSearchSchemaOption, MakeRemountDepsOptionsUnion, RemountDepsOptions, ResolveFullPath, AnyRouteWithContext, AnyRouterWithContext, CommitLocationOptions, MatchLocation, UseNavigateResult, AnyRedirect, Redirect, RedirectOptions, ResolvedRedirect, MakeRouteMatch, MakeRouteMatchUnion, RouteMatch, AnyRouteMatch, RouteContextFn, RouteContextOptions, BeforeLoadContextOptions, ContextOptions, RouteOptions, FileBaseRouteOptions, BaseRouteOptions, UpdatableRouteOptions, RouteLoaderFn, LoaderFnContext, LazyRouteOptions, AnyRouter, RegisteredRouter, RouterContextOptions, ControllablePromise, RouterOptions, RouterState, ListenerFn, BuildNextOptions, RouterConstructorOptions, RouterEvents, RouterEvent, RouterListener, RouteConstraints, RouteMask, MatchRouteOptions, CreateLazyFileRoute, } from '@tanstack/router-core';
|
||||
export type { UseLinkPropsOptions, ActiveLinkOptions, LinkProps, LinkComponent, LinkComponentProps, CreateLinkProps, } from './link.js';
|
||||
export { Matches, useMatchRoute, MatchRoute, useMatches, useParentMatches, useChildMatches, } from './Matches.js';
|
||||
export type { UseMatchRouteOptions, MakeMatchRouteOptions } from './Matches.js';
|
||||
export { Match, Outlet } from './Match.js';
|
||||
export { useMatch } from './useMatch.js';
|
||||
export { useLoaderDeps } from './useLoaderDeps.js';
|
||||
export { useLoaderData } from './useLoaderData.js';
|
||||
export { redirect, isRedirect, createRouterConfig, DEFAULT_PROTOCOL_ALLOWLIST, } from '@tanstack/router-core';
|
||||
export { RouteApi, getRouteApi, Route, createRoute, RootRoute, rootRouteWithContext, createRootRoute, createRootRouteWithContext, createRouteMask, NotFoundRoute, } from './route.js';
|
||||
export type { AnyRootRoute, AsyncRouteComponent, RouteComponent, ErrorRouteComponent, NotFoundRouteComponent, DefaultRouteTypes, RouteTypes, } from './route.js';
|
||||
export { createRouter, Router } from './router.js';
|
||||
export { lazyFn, SearchParamError } from '@tanstack/router-core';
|
||||
export { RouterProvider, RouterContextProvider } from './RouterProvider.js';
|
||||
export type { RouterProps } from './RouterProvider.js';
|
||||
export { useElementScrollRestoration, ScrollRestoration, } from './ScrollRestoration.js';
|
||||
export type { UseBlockerOpts, ShouldBlockFn } from './useBlocker.js';
|
||||
export { useBlocker, Block } from './useBlocker.js';
|
||||
export { useNavigate, Navigate } from './useNavigate.js';
|
||||
export { useParams } from './useParams.js';
|
||||
export { useSearch } from './useSearch.js';
|
||||
export { useRouteContext } from './useRouteContext.js';
|
||||
export { useRouter } from './useRouter.js';
|
||||
export { useRouterState } from './useRouterState.js';
|
||||
export { useLocation } from './useLocation.js';
|
||||
export { useCanGoBack } from './useCanGoBack.js';
|
||||
export { CatchNotFound, DefaultGlobalNotFound } from './not-found.js';
|
||||
export { notFound, isNotFound } from '@tanstack/router-core';
|
||||
export type { NotFoundError } from '@tanstack/router-core';
|
||||
export type { ValidateLinkOptions, InferStructuralSharing, ValidateUseSearchOptions, ValidateUseParamsOptions, ValidateLinkOptionsArray, } from './typePrimitives.js';
|
||||
export type { ValidateFromPath, ValidateToPath, ValidateSearch, ValidateParams, InferFrom, InferTo, InferMaskTo, InferMaskFrom, ValidateNavigateOptions, ValidateNavigateOptionsArray, ValidateRedirectOptions, ValidateRedirectOptionsArray, ValidateId, InferStrict, InferShouldThrow, InferSelected, ValidateUseSearchResult, ValidateUseParamsResult, SerializerExtensions, RegisteredSerializableInput, Serializable, } from '@tanstack/router-core';
|
||||
export { ScriptOnce } from './ScriptOnce.js';
|
||||
export { Asset } from './Asset.js';
|
||||
export { HeadContent } from './HeadContent.js';
|
||||
export { useTags } from './headContentUtils.js';
|
||||
export { Scripts } from './Scripts.js';
|
||||
export type * from './ssr/serializer.js';
|
||||
export { composeRewrites } from '@tanstack/router-core';
|
||||
export type { LocationRewrite, LocationRewriteFunction, } from '@tanstack/router-core';
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export * from './index.js';
|
||||
export { HeadContent } from './HeadContent.dev';
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
import { reactUse, useLayoutEffect } from "./utils.js";
|
||||
import { Await, useAwaited } from "./awaited.js";
|
||||
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
|
||||
import { ClientOnly, useHydrated } from "./ClientOnly.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { useMatch } from "./useMatch.js";
|
||||
import { useLoaderData } from "./useLoaderData.js";
|
||||
import { useLoaderDeps } from "./useLoaderDeps.js";
|
||||
import { useParams } from "./useParams.js";
|
||||
import { useSearch } from "./useSearch.js";
|
||||
import { Navigate, useNavigate } from "./useNavigate.js";
|
||||
import { useRouteContext } from "./useRouteContext.js";
|
||||
import { Link, createLink, linkOptions, useLinkProps } from "./link.js";
|
||||
import { NotFoundRoute, RootRoute, Route, RouteApi, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, getRouteApi, rootRouteWithContext } from "./route.js";
|
||||
import { FileRoute, FileRouteLoader, LazyRoute, createFileRoute, createLazyFileRoute, createLazyRoute } from "./fileRoute.js";
|
||||
import { lazyRouteComponent } from "./lazyRouteComponent.js";
|
||||
import { CatchNotFound, DefaultGlobalNotFound } from "./not-found.js";
|
||||
import { ScriptOnce } from "./ScriptOnce.js";
|
||||
import { Match, Outlet } from "./Match.js";
|
||||
import { MatchRoute, Matches, useChildMatches, useMatchRoute, useMatches, useParentMatches } from "./Matches.js";
|
||||
import { Router, createRouter } from "./router.js";
|
||||
import { RouterContextProvider, RouterProvider } from "./RouterProvider.js";
|
||||
import { ScrollRestoration, useElementScrollRestoration } from "./ScrollRestoration.js";
|
||||
import { Block, useBlocker } from "./useBlocker.js";
|
||||
import { useRouterState } from "./useRouterState.js";
|
||||
import { useLocation } from "./useLocation.js";
|
||||
import { useCanGoBack } from "./useCanGoBack.js";
|
||||
import { Asset } from "./Asset.js";
|
||||
import { useTags } from "./headContentUtils.js";
|
||||
import { Scripts } from "./Scripts.js";
|
||||
import { DEFAULT_PROTOCOL_ALLOWLIST, SearchParamError, cleanPath, composeRewrites, createBrowserHistory, createControlledPromise, createHashHistory, createHistory, createMemoryHistory, createRouterConfig, createSerializationAdapter, deepEqual, defaultParseSearch, defaultStringifySearch, defer, functionalUpdate, interpolatePath, isMatch, isNotFound, isRedirect, joinPaths, lazyFn, notFound, parseSearchWith, redirect, replaceEqualDeep, resolvePath, retainSearchParams, rootRouteId, stringifySearchWith, stripSearchParams, trimPath, trimPathLeft, trimPathRight } from "./index.js";
|
||||
import { HeadContent } from "./HeadContent.dev.js";
|
||||
export { Asset, Await, Block, CatchBoundary, CatchNotFound, ClientOnly, DEFAULT_PROTOCOL_ALLOWLIST, DefaultGlobalNotFound, ErrorComponent, FileRoute, FileRouteLoader, HeadContent, LazyRoute, Link, Match, MatchRoute, Matches, Navigate, NotFoundRoute, Outlet, RootRoute, Route, RouteApi, Router, RouterContextProvider, RouterProvider, ScriptOnce, Scripts, ScrollRestoration, SearchParamError, cleanPath, composeRewrites, createBrowserHistory, createControlledPromise, createFileRoute, createHashHistory, createHistory, createLazyFileRoute, createLazyRoute, createLink, createMemoryHistory, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, createRouter, createRouterConfig, createSerializationAdapter, deepEqual, defaultParseSearch, defaultStringifySearch, defer, functionalUpdate, getRouteApi, interpolatePath, isMatch, isNotFound, isRedirect, joinPaths, lazyFn, lazyRouteComponent, linkOptions, notFound, parseSearchWith, reactUse, redirect, replaceEqualDeep, resolvePath, retainSearchParams, rootRouteId, rootRouteWithContext, stringifySearchWith, stripSearchParams, trimPath, trimPathLeft, trimPathRight, useAwaited, useBlocker, useCanGoBack, useChildMatches, useElementScrollRestoration, useHydrated, useLayoutEffect, useLinkProps, useLoaderData, useLoaderDeps, useLocation, useMatch, useMatchRoute, useMatches, useNavigate, useParams, useParentMatches, useRouteContext, useRouter, useRouterState, useSearch, useTags };
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
import { reactUse, useLayoutEffect } from "./utils.js";
|
||||
import { Await, useAwaited } from "./awaited.js";
|
||||
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
|
||||
import { ClientOnly, useHydrated } from "./ClientOnly.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { useMatch } from "./useMatch.js";
|
||||
import { useLoaderData } from "./useLoaderData.js";
|
||||
import { useLoaderDeps } from "./useLoaderDeps.js";
|
||||
import { useParams } from "./useParams.js";
|
||||
import { useSearch } from "./useSearch.js";
|
||||
import { Navigate, useNavigate } from "./useNavigate.js";
|
||||
import { useRouteContext } from "./useRouteContext.js";
|
||||
import { Link, createLink, linkOptions, useLinkProps } from "./link.js";
|
||||
import { NotFoundRoute, RootRoute, Route, RouteApi, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, getRouteApi, rootRouteWithContext } from "./route.js";
|
||||
import { FileRoute, FileRouteLoader, LazyRoute, createFileRoute, createLazyFileRoute, createLazyRoute } from "./fileRoute.js";
|
||||
import { lazyRouteComponent } from "./lazyRouteComponent.js";
|
||||
import { CatchNotFound, DefaultGlobalNotFound } from "./not-found.js";
|
||||
import { ScriptOnce } from "./ScriptOnce.js";
|
||||
import { Match, Outlet } from "./Match.js";
|
||||
import { MatchRoute, Matches, useChildMatches, useMatchRoute, useMatches, useParentMatches } from "./Matches.js";
|
||||
import { Router, createRouter } from "./router.js";
|
||||
import { RouterContextProvider, RouterProvider } from "./RouterProvider.js";
|
||||
import { ScrollRestoration, useElementScrollRestoration } from "./ScrollRestoration.js";
|
||||
import { Block, useBlocker } from "./useBlocker.js";
|
||||
import { useRouterState } from "./useRouterState.js";
|
||||
import { useLocation } from "./useLocation.js";
|
||||
import { useCanGoBack } from "./useCanGoBack.js";
|
||||
import { Asset } from "./Asset.js";
|
||||
import { useTags } from "./headContentUtils.js";
|
||||
import { HeadContent } from "./HeadContent.js";
|
||||
import { Scripts } from "./Scripts.js";
|
||||
import { DEFAULT_PROTOCOL_ALLOWLIST, SearchParamError, cleanPath, composeRewrites, createControlledPromise, createRouterConfig, createSerializationAdapter, deepEqual, defaultParseSearch, defaultStringifySearch, defer, functionalUpdate, interpolatePath, isMatch, isNotFound, isRedirect, joinPaths, lazyFn, notFound, parseSearchWith, redirect, replaceEqualDeep, resolvePath, retainSearchParams, rootRouteId, stringifySearchWith, stripSearchParams, trimPath, trimPathLeft, trimPathRight } from "@tanstack/router-core";
|
||||
import { createBrowserHistory, createHashHistory, createHistory, createMemoryHistory } from "@tanstack/history";
|
||||
export { Asset, Await, Block, CatchBoundary, CatchNotFound, ClientOnly, DEFAULT_PROTOCOL_ALLOWLIST, DefaultGlobalNotFound, ErrorComponent, FileRoute, FileRouteLoader, HeadContent, LazyRoute, Link, Match, MatchRoute, Matches, Navigate, NotFoundRoute, Outlet, RootRoute, Route, RouteApi, Router, RouterContextProvider, RouterProvider, ScriptOnce, Scripts, ScrollRestoration, SearchParamError, cleanPath, composeRewrites, createBrowserHistory, createControlledPromise, createFileRoute, createHashHistory, createHistory, createLazyFileRoute, createLazyRoute, createLink, createMemoryHistory, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, createRouter, createRouterConfig, createSerializationAdapter, deepEqual, defaultParseSearch, defaultStringifySearch, defer, functionalUpdate, getRouteApi, interpolatePath, isMatch, isNotFound, isRedirect, joinPaths, lazyFn, lazyRouteComponent, linkOptions, notFound, parseSearchWith, reactUse, redirect, replaceEqualDeep, resolvePath, retainSearchParams, rootRouteId, rootRouteWithContext, stringifySearchWith, stripSearchParams, trimPath, trimPathLeft, trimPathRight, useAwaited, useBlocker, useCanGoBack, useChildMatches, useElementScrollRestoration, useHydrated, useLayoutEffect, useLinkProps, useLoaderData, useLoaderDeps, useLocation, useMatch, useMatchRoute, useMatches, useNavigate, useParams, useParentMatches, useRouteContext, useRouter, useRouterState, useSearch, useTags };
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export * from './index.js';
|
||||
export { notFound, isNotFound, redirect, isRedirect, rootRouteId, } from '@tanstack/router-core';
|
||||
export type { NotFoundError } from '@tanstack/router-core';
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { reactUse, useLayoutEffect } from "./utils.js";
|
||||
import { Await, useAwaited } from "./awaited.js";
|
||||
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
|
||||
import { ClientOnly, useHydrated } from "./ClientOnly.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { useMatch } from "./useMatch.js";
|
||||
import { useLoaderData } from "./useLoaderData.js";
|
||||
import { useLoaderDeps } from "./useLoaderDeps.js";
|
||||
import { useParams } from "./useParams.js";
|
||||
import { useSearch } from "./useSearch.js";
|
||||
import { Navigate, useNavigate } from "./useNavigate.js";
|
||||
import { useRouteContext } from "./useRouteContext.js";
|
||||
import { Link, createLink, linkOptions, useLinkProps } from "./link.js";
|
||||
import { NotFoundRoute, RootRoute, Route, RouteApi, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, getRouteApi, rootRouteWithContext } from "./route.js";
|
||||
import { FileRoute, FileRouteLoader, LazyRoute, createFileRoute, createLazyFileRoute, createLazyRoute } from "./fileRoute.js";
|
||||
import { lazyRouteComponent } from "./lazyRouteComponent.js";
|
||||
import { CatchNotFound, DefaultGlobalNotFound } from "./not-found.js";
|
||||
import { ScriptOnce } from "./ScriptOnce.js";
|
||||
import { Match, Outlet } from "./Match.js";
|
||||
import { MatchRoute, Matches, useChildMatches, useMatchRoute, useMatches, useParentMatches } from "./Matches.js";
|
||||
import { Router, createRouter } from "./router.js";
|
||||
import { RouterContextProvider, RouterProvider } from "./RouterProvider.js";
|
||||
import { ScrollRestoration, useElementScrollRestoration } from "./ScrollRestoration.js";
|
||||
import { Block, useBlocker } from "./useBlocker.js";
|
||||
import { useRouterState } from "./useRouterState.js";
|
||||
import { useLocation } from "./useLocation.js";
|
||||
import { useCanGoBack } from "./useCanGoBack.js";
|
||||
import { Asset } from "./Asset.js";
|
||||
import { useTags } from "./headContentUtils.js";
|
||||
import { HeadContent } from "./HeadContent.js";
|
||||
import { Scripts } from "./Scripts.js";
|
||||
import { DEFAULT_PROTOCOL_ALLOWLIST, SearchParamError, cleanPath, composeRewrites, createBrowserHistory, createControlledPromise, createHashHistory, createHistory, createMemoryHistory, createRouterConfig, createSerializationAdapter, deepEqual, defaultParseSearch, defaultStringifySearch, defer, functionalUpdate, interpolatePath, isMatch, joinPaths, lazyFn, parseSearchWith, replaceEqualDeep, resolvePath, retainSearchParams, stringifySearchWith, stripSearchParams, trimPath, trimPathLeft, trimPathRight } from "./index.js";
|
||||
import { isNotFound, isRedirect, notFound, redirect, rootRouteId } from "@tanstack/router-core";
|
||||
export { Asset, Await, Block, CatchBoundary, CatchNotFound, ClientOnly, DEFAULT_PROTOCOL_ALLOWLIST, DefaultGlobalNotFound, ErrorComponent, FileRoute, FileRouteLoader, HeadContent, LazyRoute, Link, Match, MatchRoute, Matches, Navigate, NotFoundRoute, Outlet, RootRoute, Route, RouteApi, Router, RouterContextProvider, RouterProvider, ScriptOnce, Scripts, ScrollRestoration, SearchParamError, cleanPath, composeRewrites, createBrowserHistory, createControlledPromise, createFileRoute, createHashHistory, createHistory, createLazyFileRoute, createLazyRoute, createLink, createMemoryHistory, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, createRouter, createRouterConfig, createSerializationAdapter, deepEqual, defaultParseSearch, defaultStringifySearch, defer, functionalUpdate, getRouteApi, interpolatePath, isMatch, isNotFound, isRedirect, joinPaths, lazyFn, lazyRouteComponent, linkOptions, notFound, parseSearchWith, reactUse, redirect, replaceEqualDeep, resolvePath, retainSearchParams, rootRouteId, rootRouteWithContext, stringifySearchWith, stripSearchParams, trimPath, trimPathLeft, trimPathRight, useAwaited, useBlocker, useCanGoBack, useChildMatches, useElementScrollRestoration, useHydrated, useLayoutEffect, useLinkProps, useLoaderData, useLoaderDeps, useLocation, useMatch, useMatchRoute, useMatches, useNavigate, useParams, useParentMatches, useRouteContext, useRouter, useRouterState, useSearch, useTags };
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { AsyncRouteComponent } from './route.js';
|
||||
/**
|
||||
* Wrap a dynamic import to create a route component that supports
|
||||
* `.preload()` and friendly reload-on-module-missing behavior.
|
||||
*
|
||||
* @param importer Function returning a module promise
|
||||
* @param exportName Named export to use (default: `default`)
|
||||
* @returns A lazy route component compatible with TanStack Router
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/lazyRouteComponentFunction
|
||||
*/
|
||||
export declare function lazyRouteComponent<T extends Record<string, any>, TKey extends keyof T = 'default'>(importer: () => Promise<T>, exportName?: TKey): T[TKey] extends (props: infer TProps) => any ? AsyncRouteComponent<TProps> : never;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { reactUse } from "./utils.js";
|
||||
import { isModuleNotFoundError } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
//#region src/lazyRouteComponent.tsx
|
||||
/**
|
||||
* Wrap a dynamic import to create a route component that supports
|
||||
* `.preload()` and friendly reload-on-module-missing behavior.
|
||||
*
|
||||
* @param importer Function returning a module promise
|
||||
* @param exportName Named export to use (default: `default`)
|
||||
* @returns A lazy route component compatible with TanStack Router
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/lazyRouteComponentFunction
|
||||
*/
|
||||
function lazyRouteComponent(importer, exportName) {
|
||||
let loadPromise;
|
||||
let comp;
|
||||
let error;
|
||||
const load = () => {
|
||||
if (!loadPromise) {
|
||||
error = void 0;
|
||||
loadPromise = importer().then((res) => {
|
||||
if (!(isServer ?? typeof window === "undefined")) {
|
||||
loadPromise = void 0;
|
||||
lazyComp.preload = void 0;
|
||||
}
|
||||
comp = res[exportName ?? "default"];
|
||||
}).catch((err) => {
|
||||
loadPromise = void 0;
|
||||
error = err;
|
||||
});
|
||||
}
|
||||
return loadPromise;
|
||||
};
|
||||
const lazyComp = function Lazy(props) {
|
||||
if (error) {
|
||||
if (isModuleNotFoundError(error) && !(isServer ?? typeof window === "undefined") && typeof sessionStorage !== "undefined") {
|
||||
const storageKey = `tanstack_router_reload:${error.message}`;
|
||||
if (!sessionStorage.getItem(storageKey)) {
|
||||
sessionStorage.setItem(storageKey, "1");
|
||||
window.location.reload();
|
||||
throw new Promise(() => {});
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!comp) if (reactUse) reactUse(load());
|
||||
else throw load();
|
||||
return React$1.createElement(comp, props);
|
||||
};
|
||||
lazyComp.preload = load;
|
||||
return lazyComp;
|
||||
}
|
||||
//#endregion
|
||||
export { lazyRouteComponent };
|
||||
|
||||
//# sourceMappingURL=lazyRouteComponent.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"lazyRouteComponent.js","names":[],"sources":["../../src/lazyRouteComponent.tsx"],"sourcesContent":["import * as React from 'react'\nimport { isModuleNotFoundError } from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { reactUse } from './utils'\nimport type { AsyncRouteComponent } from './route'\n\n/**\n * Wrap a dynamic import to create a route component that supports\n * `.preload()` and friendly reload-on-module-missing behavior.\n *\n * @param importer Function returning a module promise\n * @param exportName Named export to use (default: `default`)\n * @returns A lazy route component compatible with TanStack Router\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/lazyRouteComponentFunction\n */\nexport function lazyRouteComponent<\n T extends Record<string, any>,\n TKey extends keyof T = 'default',\n>(\n importer: () => Promise<T>,\n exportName?: TKey,\n): T[TKey] extends (props: infer TProps) => any\n ? AsyncRouteComponent<TProps>\n : never {\n let loadPromise: Promise<any> | undefined\n let comp: T[TKey] | T['default']\n let error: any\n\n const load = () => {\n if (!loadPromise) {\n error = undefined\n loadPromise = importer()\n .then((res) => {\n // Resolved clients have no preload work; SSR can reuse the import.\n if (!(isServer ?? typeof window === 'undefined')) {\n loadPromise = undefined\n ;(lazyComp as any).preload = undefined\n }\n comp = res[exportName ?? 'default']\n })\n .catch((err) => {\n loadPromise = undefined\n // We don't want an error thrown from preload in this case, because\n // there's nothing we want to do about module not found during preload.\n // Record the error, the rest is handled during the render path.\n error = err\n })\n }\n\n return loadPromise\n }\n const lazyComp = function Lazy(props: any) {\n if (error) {\n // A missing module can mean that a newer deployment replaced the URL.\n // Reload only for the error that is still current at render time, so a\n // successful retry cannot leave a stale reload request armed.\n if (\n isModuleNotFoundError(error) &&\n !(isServer ?? typeof window === 'undefined') &&\n typeof sessionStorage !== 'undefined'\n ) {\n const storageKey = `tanstack_router_reload:${error.message}`\n if (!sessionStorage.getItem(storageKey)) {\n sessionStorage.setItem(storageKey, '1')\n window.location.reload()\n // Suspend forever while the document reloads.\n throw new Promise(() => {})\n }\n }\n throw error\n }\n\n if (!comp) {\n if (reactUse) {\n reactUse(load())\n } else {\n throw load()\n }\n }\n\n return React.createElement(comp, props)\n }\n\n ;(lazyComp as any).preload = load\n\n return lazyComp as any\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,SAAgB,mBAId,UACA,YAGQ;CACR,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,aAAa;EACjB,IAAI,CAAC,aAAa;GAChB,QAAQ,KAAA;GACR,cAAc,SAAS,EACpB,MAAM,QAAQ;IAEb,IAAI,EAAE,YAAY,OAAO,WAAW,cAAc;KAChD,cAAc,KAAA;KACb,SAAkB,UAAU,KAAA;IAC/B;IACA,OAAO,IAAI,cAAc;GAC3B,CAAC,EACA,OAAO,QAAQ;IACd,cAAc,KAAA;IAId,QAAQ;GACV,CAAC;EACL;EAEA,OAAO;CACT;CACA,MAAM,WAAW,SAAS,KAAK,OAAY;EACzC,IAAI,OAAO;GAIT,IACE,sBAAsB,KAAK,KAC3B,EAAE,YAAY,OAAO,WAAW,gBAChC,OAAO,mBAAmB,aAC1B;IACA,MAAM,aAAa,0BAA0B,MAAM;IACnD,IAAI,CAAC,eAAe,QAAQ,UAAU,GAAG;KACvC,eAAe,QAAQ,YAAY,GAAG;KACtC,OAAO,SAAS,OAAO;KAEvB,MAAM,IAAI,cAAc,CAAC,CAAC;IAC5B;GACF;GACA,MAAM;EACR;EAEA,IAAI,CAAC,MACH,IAAI,UACF,SAAS,KAAK,CAAC;OAEf,MAAM,KAAK;EAIf,OAAO,QAAM,cAAc,MAAM,KAAK;CACxC;CAEC,SAAkB,UAAU;CAE7B,OAAO;AACT"}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { AnyRouter, Constrain, LinkOptions, RegisteredRouter, RoutePaths } from '@tanstack/router-core';
|
||||
import { ReactNode } from 'react';
|
||||
import { ValidateLinkOptions, ValidateLinkOptionsArray } from './typePrimitives.js';
|
||||
import * as React from 'react';
|
||||
/**
|
||||
* Build anchor-like props for declarative navigation and preloading.
|
||||
*
|
||||
* Returns stable `href`, event handlers and accessibility props derived from
|
||||
* router options and active state. Used internally by `Link` and custom links.
|
||||
*
|
||||
* Options cover `to`, `params`, `search`, `hash`, `state`, `preload`,
|
||||
* `activeProps`, `inactiveProps`, and more.
|
||||
*
|
||||
* @returns React anchor props suitable for `<a>` or custom components.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook
|
||||
*/
|
||||
export declare function useLinkProps<TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string = string, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, const TMaskTo extends string = ''>(options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>, forwardedRef?: React.ForwardedRef<Element>): React.ComponentPropsWithRef<'a'>;
|
||||
export declare const composeHandlers: (first: React.EventHandler<any> | undefined, second: React.EventHandler<any>) => (event: any) => void;
|
||||
type UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements ? React.JSX.IntrinsicElements[TComp] : TComp extends React.ComponentType<any> ? React.ComponentPropsWithoutRef<TComp> & React.RefAttributes<React.ComponentRef<TComp>> : never;
|
||||
export type UseLinkPropsOptions<TRouter extends AnyRouter = RegisteredRouter, TFrom extends RoutePaths<TRouter['routeTree']> | string = string, TTo extends string | undefined = '.', TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom, TMaskTo extends string = '.'> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & UseLinkReactProps<'a'>;
|
||||
export type ActiveLinkOptions<TComp = 'a', TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = '.', TMaskFrom extends string = TFrom, TMaskTo extends string = '.'> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & ActiveLinkOptionProps<TComp>;
|
||||
type ActiveLinkProps<TComp> = Partial<LinkComponentReactProps<TComp> & {
|
||||
[key: `data-${string}`]: unknown;
|
||||
}>;
|
||||
export interface ActiveLinkOptionProps<TComp = 'a'> {
|
||||
/**
|
||||
* A function that returns additional props for the `active` state of this link.
|
||||
* These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
|
||||
*/
|
||||
activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>);
|
||||
/**
|
||||
* A function that returns additional props for the `inactive` state of this link.
|
||||
* These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
|
||||
*/
|
||||
inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>);
|
||||
}
|
||||
export type LinkProps<TComp = 'a', TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = '.', TMaskFrom extends string = TFrom, TMaskTo extends string = '.'> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & LinkPropsChildren;
|
||||
export interface LinkPropsChildren {
|
||||
children?: React.ReactNode | ((state: {
|
||||
isActive: boolean;
|
||||
}) => React.ReactNode);
|
||||
}
|
||||
type LinkComponentReactProps<TComp> = Omit<UseLinkReactProps<TComp>, keyof CreateLinkProps>;
|
||||
export type LinkComponentProps<TComp = 'a', TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string, TTo extends string | undefined = '.', TMaskFrom extends string = TFrom, TMaskTo extends string = '.'> = LinkComponentReactProps<TComp> & LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>;
|
||||
export type CreateLinkProps = LinkProps<any, any, string, string, string, string>;
|
||||
export type LinkComponent<in out TComp, in out TDefaultFrom extends string = string> = <TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string = TDefaultFrom, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, const TMaskTo extends string = ''>(props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>) => React.ReactElement;
|
||||
export interface LinkComponentRoute<in out TDefaultFrom extends string = string> {
|
||||
defaultFrom: TDefaultFrom;
|
||||
<TRouter extends AnyRouter = RegisteredRouter, const TTo extends string | undefined = undefined, const TMaskTo extends string = ''>(props: LinkComponentProps<'a', TRouter, this['defaultFrom'], TTo, this['defaultFrom'], TMaskTo>): React.ReactElement;
|
||||
}
|
||||
/**
|
||||
* Creates a typed Link-like component that preserves TanStack Router's
|
||||
* navigation semantics and type-safety while delegating rendering to the
|
||||
* provided host component.
|
||||
*
|
||||
* Useful for integrating design system anchors/buttons while keeping
|
||||
* router-aware props (eg. `to`, `params`, `search`, `preload`).
|
||||
*
|
||||
* @param Comp The host component to render (eg. a design-system Link/Button)
|
||||
* @returns A router-aware component with the same API as `Link`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link
|
||||
*/
|
||||
export declare function createLink<const TComp>(Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>): LinkComponent<TComp>;
|
||||
/**
|
||||
* A strongly-typed anchor component for declarative navigation.
|
||||
* Handles path, search, hash and state updates with optional route preloading
|
||||
* and active-state styling.
|
||||
*
|
||||
* Props:
|
||||
* - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)
|
||||
* - `preloadDelay`: Delay in ms before preloading on focus, hover, or viewport entry
|
||||
* - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive
|
||||
* - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation
|
||||
* - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation
|
||||
* - `ignoreBlocker`: Bypass registered blockers
|
||||
*
|
||||
* @returns An anchor-like element that navigates without full page reloads.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent
|
||||
*/
|
||||
export declare const Link: LinkComponent<'a'>;
|
||||
export type LinkOptionsFnOptions<TOptions, TComp, TRouter extends AnyRouter = RegisteredRouter> = TOptions extends ReadonlyArray<any> ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp> : ValidateLinkOptions<TRouter, TOptions, string, TComp>;
|
||||
export type LinkOptionsFn<TComp> = <const TOptions, TRouter extends AnyRouter = RegisteredRouter>(options: LinkOptionsFnOptions<TOptions, TComp, TRouter>) => TOptions;
|
||||
/**
|
||||
* Validate and reuse navigation options for `Link`, `navigate` or `redirect`.
|
||||
* Accepts a literal options object and returns it typed for later spreading.
|
||||
* @example
|
||||
* const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
|
||||
*/
|
||||
export declare const linkOptions: LinkOptionsFn<'a'>;
|
||||
export {};
|
||||
/**
|
||||
* Type-check a literal object for use with `Link`, `navigate` or `redirect`.
|
||||
* Use to validate and reuse navigation options across your app.
|
||||
* @example
|
||||
* const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
|
||||
*/
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
"use client";
|
||||
import { useHydrated } from "./ClientOnly.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { deepEqual, functionalUpdate, getUrlScheme, isDangerousProtocol, preloadWarning, removeTrailingSlash } from "@tanstack/router-core";
|
||||
import * as React$1 from "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
import { useSelector } from "@tanstack/react-store";
|
||||
//#region src/link.tsx
|
||||
function useStableValues(...values) {
|
||||
const ref = React$1.useRef(values);
|
||||
const stable = ref.current;
|
||||
values.forEach((value, index) => {
|
||||
if (!deepEqual(stable[index], value, false, true)) stable[index] = value;
|
||||
});
|
||||
return ref.current;
|
||||
}
|
||||
function preloadLink(router, options) {
|
||||
router.preloadRoute(options).catch((err) => {
|
||||
console.warn(err);
|
||||
console.warn(preloadWarning);
|
||||
});
|
||||
}
|
||||
var LINK_SELECTOR_OPTIONS = { compare: (a, b) => a[0] === b[0] && a[1] === b[1] };
|
||||
function resolveExternalLink(to, protocolAllowlist) {
|
||||
const scheme = typeof to === "string" && getUrlScheme(to);
|
||||
if (!scheme) return;
|
||||
if (!protocolAllowlist.has(scheme)) {
|
||||
if (process.env.NODE_ENV !== "production") console.warn(`Blocked Link with dangerous protocol: ${to}`);
|
||||
return null;
|
||||
}
|
||||
return to;
|
||||
}
|
||||
function resolveIsActive(location, next, activeOptions, basepath, isHydrated) {
|
||||
const currentPath = removeTrailingSlash(location.pathname, basepath);
|
||||
const nextPath = removeTrailingSlash(next.pathname, basepath);
|
||||
if (activeOptions?.exact ? currentPath !== nextPath : !(currentPath.startsWith(nextPath) && (currentPath.length === nextPath.length || currentPath[nextPath.length] === "/"))) return false;
|
||||
if (activeOptions?.includeSearch ?? true) {
|
||||
if (!deepEqual(location.search, next.search, !activeOptions?.exact, activeOptions?.explicitUndefined)) return false;
|
||||
}
|
||||
if (activeOptions?.includeHash) return isHydrated && location.hash === next.hash;
|
||||
return true;
|
||||
}
|
||||
function useLinkProps(options, forwardedRef, host) {
|
||||
const router = useRouter();
|
||||
if (isServer ?? router.isServer) return getServerLinkProps(router, options, forwardedRef, host);
|
||||
const innerRef = React$1.useRef(null);
|
||||
const mergedRef = React$1.useCallback((element) => {
|
||||
innerRef.current = element;
|
||||
if (typeof forwardedRef === "function") return forwardedRef(element);
|
||||
if (forwardedRef) forwardedRef.current = element;
|
||||
}, [forwardedRef]);
|
||||
const { activeOptions, to, preload: userPreload, preloadDelay: userPreloadDelay, hashScrollIntoView, replace, startTransition, resetScroll, viewTransition, ignoreBlocker, disabled, target, onClick, onBlur, onFocus, onMouseEnter, onMouseLeave, onTouchStart } = options;
|
||||
const isHydrated = useHydrated();
|
||||
const [stableSearch, stableParams, stableActiveOptions] = useStableValues(options.search, options.params, activeOptions);
|
||||
const [_options, dest] = React$1.useMemo(() => [options, { ...options }], [
|
||||
router,
|
||||
options.from,
|
||||
options._fromLocation,
|
||||
options.hash,
|
||||
options.to,
|
||||
stableSearch,
|
||||
stableParams,
|
||||
options.state,
|
||||
options.mask,
|
||||
options.unsafeRelative
|
||||
]);
|
||||
const selectLinkState = React$1.useCallback((location) => {
|
||||
const directExternalLink = resolveExternalLink(to, router.protocolAllowlist);
|
||||
if (directExternalLink !== void 0) return [directExternalLink ?? void 0];
|
||||
if (!_options._fromLocation) dest._fromLocation = location;
|
||||
const next = router.buildLocation(dest);
|
||||
const hrefOption = getHrefOption(next, router, disabled);
|
||||
return [hrefOption, !disabled && (!hrefOption || getUrlScheme(hrefOption)) ? void 0 : resolveIsActive(location, next, stableActiveOptions, router.basepath, isHydrated)];
|
||||
}, [
|
||||
stableActiveOptions,
|
||||
disabled,
|
||||
isHydrated,
|
||||
_options,
|
||||
dest,
|
||||
router,
|
||||
to
|
||||
]);
|
||||
const [href, isActive] = useSelector(router.stores.location, selectLinkState, LINK_SELECTOR_OPTIONS);
|
||||
const externalLink = isActive === void 0 ? href : void 0;
|
||||
const linkDisabled = disabled || href === void 0;
|
||||
const hasRenderFetched = React$1.useRef(false);
|
||||
const preload = options.reloadDocument || externalLink || linkDisabled ? false : userPreload ?? router.options.defaultPreload;
|
||||
const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0;
|
||||
const enqueuePreload = React$1.useCallback((e) => {
|
||||
const isIntersecting = e?.isIntersecting;
|
||||
if (!(isIntersecting ?? preload === "intent")) {
|
||||
if (isIntersecting === false) cancelPreload(innerRef);
|
||||
return;
|
||||
}
|
||||
if (!preloadDelay) {
|
||||
preloadLink(router, _options);
|
||||
return;
|
||||
}
|
||||
if (timeoutMap.has(innerRef)) return;
|
||||
timeoutMap.set(innerRef, setTimeout(() => {
|
||||
timeoutMap.delete(innerRef);
|
||||
preloadLink(router, _options);
|
||||
}, preloadDelay));
|
||||
}, [
|
||||
router,
|
||||
_options,
|
||||
innerRef,
|
||||
preload,
|
||||
preloadDelay
|
||||
]);
|
||||
React$1.useEffect(() => {
|
||||
if (preload === "render" && !hasRenderFetched.current) {
|
||||
hasRenderFetched.current = true;
|
||||
preloadLink(router, _options);
|
||||
}
|
||||
let observer;
|
||||
if (preload === "viewport" && innerRef.current && typeof IntersectionObserver === "function") {
|
||||
observer = new IntersectionObserver((entries) => enqueuePreload(entries.pop()), { rootMargin: "100px" });
|
||||
observer.observe(innerRef.current);
|
||||
}
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
cancelPreload(innerRef);
|
||||
};
|
||||
}, [
|
||||
router,
|
||||
_options,
|
||||
preload,
|
||||
enqueuePreload,
|
||||
innerRef
|
||||
]);
|
||||
const props = collectElementProps(options, host);
|
||||
props.ref = forwardedRef ? mergedRef : innerRef;
|
||||
if (externalLink) {
|
||||
props.href = externalLink;
|
||||
return props;
|
||||
}
|
||||
const handleClick = (e) => {
|
||||
const effectiveTarget = target ?? e.currentTarget.getAttribute("target");
|
||||
if (!linkDisabled && !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) && !e.defaultPrevented && (!effectiveTarget || effectiveTarget === "_self") && e.button === 0) {
|
||||
e.preventDefault();
|
||||
router.navigate({
|
||||
..._options,
|
||||
replace,
|
||||
resetScroll,
|
||||
hashScrollIntoView,
|
||||
startTransition,
|
||||
viewTransition,
|
||||
ignoreBlocker
|
||||
});
|
||||
}
|
||||
};
|
||||
const handleTouchStart = () => {
|
||||
if (preload === "intent") preloadLink(router, _options);
|
||||
};
|
||||
const handleLeave = () => {
|
||||
if (preload === "intent") cancelPreload(innerRef);
|
||||
};
|
||||
props.onClick = composeHandlers(onClick, handleClick);
|
||||
props.onBlur = composeHandlers(onBlur, handleLeave);
|
||||
props.onFocus = composeHandlers(onFocus, enqueuePreload);
|
||||
props.onMouseEnter = composeHandlers(onMouseEnter, enqueuePreload);
|
||||
props.onMouseLeave = composeHandlers(onMouseLeave, handleLeave);
|
||||
props.onTouchStart = composeHandlers(onTouchStart, handleTouchStart);
|
||||
return applyLinkState(props, options, isActive, href, linkDisabled, host);
|
||||
}
|
||||
var STATIC_EMPTY_OBJECT = {};
|
||||
var STATIC_ACTIVE_OBJECT = { className: "active" };
|
||||
var ROUTER_OPTION_KEYS = /* @__PURE__ */ new Set([
|
||||
"to",
|
||||
"params",
|
||||
"search",
|
||||
"hash",
|
||||
"state",
|
||||
"mask",
|
||||
"from",
|
||||
"unsafeRelative",
|
||||
"_fromLocation",
|
||||
"reloadDocument",
|
||||
"preload",
|
||||
"preloadDelay",
|
||||
"preloadIntentProximity",
|
||||
"hashScrollIntoView",
|
||||
"replace",
|
||||
"startTransition",
|
||||
"resetScroll",
|
||||
"viewTransition",
|
||||
"ignoreBlocker",
|
||||
"activeProps",
|
||||
"inactiveProps",
|
||||
"activeOptions",
|
||||
"_asChild"
|
||||
]);
|
||||
function collectElementProps(options, host) {
|
||||
const props = {};
|
||||
for (const key in options) {
|
||||
if (ROUTER_OPTION_KEYS.has(key) || key === "type" && host !== void 0 || key === "disabled" && host === "a") continue;
|
||||
props[key] = options[key];
|
||||
}
|
||||
return props;
|
||||
}
|
||||
function applyLinkState(props, options, isActive, href, linkDisabled, host) {
|
||||
const { activeProps, inactiveProps, className, style, target } = options;
|
||||
const stateProps = functionalUpdate(isActive ? activeProps : inactiveProps, {}) ?? (isActive ? STATIC_ACTIVE_OBJECT : STATIC_EMPTY_OBJECT);
|
||||
Object.assign(props, stateProps);
|
||||
props.href = href;
|
||||
if (host !== "a") props.disabled = linkDisabled;
|
||||
props.target = target;
|
||||
const stateStyle = stateProps.style;
|
||||
if (style || stateStyle) props.style = style && stateStyle ? {
|
||||
...style,
|
||||
...stateStyle
|
||||
} : style || stateStyle;
|
||||
const stateClassName = stateProps.className;
|
||||
if (className || stateClassName) props.className = className ? stateClassName ? `${className} ${stateClassName}` : className : stateClassName;
|
||||
if (linkDisabled) {
|
||||
props.role = "link";
|
||||
props["aria-disabled"] = true;
|
||||
}
|
||||
if (isActive) {
|
||||
props["data-status"] = "active";
|
||||
props["aria-current"] = "page";
|
||||
}
|
||||
return props;
|
||||
}
|
||||
function getServerLinkProps(router, options, forwardedRef, host) {
|
||||
const { to, disabled, activeOptions } = options;
|
||||
const directExternalLink = resolveExternalLink(to, router.protocolAllowlist);
|
||||
const next = directExternalLink === void 0 ? router.buildLocation(options) : void 0;
|
||||
const hrefOption = next ? getHrefOption(next, router, disabled) : directExternalLink ?? void 0;
|
||||
const linkDisabled = disabled || !hrefOption;
|
||||
const externalLink = directExternalLink ?? (hrefOption && getUrlScheme(hrefOption) ? hrefOption : void 0);
|
||||
const props = collectElementProps(options, host);
|
||||
props.ref = forwardedRef;
|
||||
if (externalLink) {
|
||||
props.href = externalLink;
|
||||
return props;
|
||||
}
|
||||
return applyLinkState(props, options, !!next && !(!disabled && !hrefOption) && resolveIsActive(router.stores.location.get(), next, activeOptions, router.basepath, false), hrefOption, linkDisabled, host);
|
||||
}
|
||||
var timeoutMap = /* @__PURE__ */ new WeakMap();
|
||||
var cancelPreload = (eventTarget) => {
|
||||
clearTimeout(timeoutMap.get(eventTarget));
|
||||
timeoutMap.delete(eventTarget);
|
||||
};
|
||||
var composeHandlers = (first, second) => {
|
||||
if (!first) return second;
|
||||
return (event) => event.defaultPrevented || (first(event), event.defaultPrevented || second(event));
|
||||
};
|
||||
function getHrefOption(next, router, disabled) {
|
||||
if (disabled) return;
|
||||
const location = next.maskedLocation ?? next;
|
||||
const href = location.external ? location.publicHref : router.history.createHref(location.publicHref) || "/";
|
||||
if ((location.external || href !== location.publicHref) && isDangerousProtocol(href, router.protocolAllowlist)) {
|
||||
if (process.env.NODE_ENV !== "production") console.warn(`Blocked Link with dangerous protocol: ${href}`);
|
||||
return;
|
||||
}
|
||||
return href;
|
||||
}
|
||||
/**
|
||||
* Creates a typed Link-like component that preserves TanStack Router's
|
||||
* navigation semantics and type-safety while delegating rendering to the
|
||||
* provided host component.
|
||||
*
|
||||
* Useful for integrating design system anchors/buttons while keeping
|
||||
* router-aware props (eg. `to`, `params`, `search`, `preload`).
|
||||
*
|
||||
* @param Comp The host component to render (eg. a design-system Link/Button)
|
||||
* @returns A router-aware component with the same API as `Link`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link
|
||||
*/
|
||||
function createLink(Comp) {
|
||||
return React$1.forwardRef(function CreatedLink(props, ref) {
|
||||
return /* @__PURE__ */ jsx(Link, {
|
||||
...props,
|
||||
_asChild: Comp,
|
||||
ref
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* A strongly-typed anchor component for declarative navigation.
|
||||
* Handles path, search, hash and state updates with optional route preloading
|
||||
* and active-state styling.
|
||||
*
|
||||
* Props:
|
||||
* - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)
|
||||
* - `preloadDelay`: Delay in ms before preloading on focus, hover, or viewport entry
|
||||
* - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive
|
||||
* - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation
|
||||
* - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation
|
||||
* - `ignoreBlocker`: Bypass registered blockers
|
||||
*
|
||||
* @returns An anchor-like element that navigates without full page reloads.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent
|
||||
*/
|
||||
var Link = React$1.memo(React$1.forwardRef((props, ref) => {
|
||||
const host = props._asChild || "a";
|
||||
const linkProps = useLinkProps(props, ref, host);
|
||||
const children = typeof props.children === "function" ? props.children({ isActive: linkProps["data-status"] === "active" }) : props.children;
|
||||
return React$1.createElement(host, linkProps, children);
|
||||
}), areLinkPropsEqual);
|
||||
function areLinkPropsEqual(prev, next) {
|
||||
let extraKeys = 0;
|
||||
for (const key in next) {
|
||||
extraKeys++;
|
||||
if (prev[key] === next[key]) continue;
|
||||
if (!ROUTER_OPTION_KEYS.has(key) || !deepEqual(prev[key], next[key], false, true)) return false;
|
||||
}
|
||||
for (const _key in prev) extraKeys--;
|
||||
return extraKeys === 0;
|
||||
}
|
||||
/**
|
||||
* Validate and reuse navigation options for `Link`, `navigate` or `redirect`.
|
||||
* Accepts a literal options object and returns it typed for later spreading.
|
||||
* @example
|
||||
* const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
|
||||
*/
|
||||
var linkOptions = (options) => {
|
||||
return options;
|
||||
};
|
||||
/**
|
||||
* Type-check a literal object for use with `Link`, `navigate` or `redirect`.
|
||||
* Use to validate and reuse navigation options across your app.
|
||||
* @example
|
||||
* const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
|
||||
*/
|
||||
//#endregion
|
||||
export { Link, createLink, linkOptions, useLinkProps };
|
||||
|
||||
//# sourceMappingURL=link.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"link.js","names":[],"sources":["../../src/link.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport { useSelector } from '@tanstack/react-store'\nimport {\n deepEqual,\n functionalUpdate,\n getUrlScheme,\n isDangerousProtocol,\n preloadWarning,\n removeTrailingSlash,\n} from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { useRouter } from './useRouter'\n\nimport { useHydrated } from './ClientOnly'\nimport type {\n ActiveOptions,\n AnyRouter,\n Constrain,\n LinkOptions,\n ParsedLocation,\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// Undefined active state marks an external or blocked link.\n// Keep that classification with the href instead of parsing it again on render.\ntype LinkState = [href: string | undefined, isActive?: boolean]\n\n// Keep referentially stable values while their contents are equal. Links\n// routinely pass inline `params` / `search` object literals, which would\n// otherwise change `_options` identity on every parent render, rebuild the\n// store selector, and discard its memoized selection. One ref holds all of\n// them; each entry is replaced only when its own contents change.\n//\n// The router reuses a built location for as long as it sees the same options\n// object, so the references returned here are its invalidation signal: pass a\n// new object to change a destination. Like every other React prop, an object\n// mutated in place is not re-read. `deepEqual` short-circuits on reference\n// equality, so an unchanged reference costs nothing.\n//\n// `explicitUndefined` is required: an explicit `undefined` clears an\n// inherited param or search key, so `{}` and `{ category: undefined }` build\n// different locations and must not be treated as equal here.\nfunction useStableValues<T extends ReadonlyArray<unknown>>(...values: T): T {\n const ref = React.useRef<ReadonlyArray<unknown>>(values)\n const stable = ref.current as Array<unknown>\n values.forEach((value, index) => {\n if (!deepEqual(stable[index], value, false, true)) {\n stable[index] = value\n }\n })\n return ref.current as T\n}\n\nfunction preloadLink(router: AnyRouter, options: unknown) {\n router.preloadRoute(options as any).catch((err) => {\n console.warn(err)\n console.warn(preloadWarning)\n })\n}\n\nconst LINK_SELECTOR_OPTIONS = {\n compare: (a: LinkState, b: LinkState) => a[0] === b[0] && a[1] === b[1],\n}\n\nfunction resolveExternalLink(\n to: string | undefined,\n protocolAllowlist: AnyRouter['protocolAllowlist'],\n): string | null | undefined {\n const scheme = typeof to === 'string' && getUrlScheme(to)\n if (!scheme) {\n return undefined\n }\n if (!protocolAllowlist.has(scheme)) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`Blocked Link with dangerous protocol: ${to}`)\n }\n return null\n }\n return to\n}\n\nfunction resolveIsActive(\n location: ParsedLocation,\n next: ParsedLocation,\n activeOptions: ActiveOptions | undefined,\n basepath: string,\n isHydrated: boolean,\n): boolean {\n const currentPath = removeTrailingSlash(location.pathname, basepath)\n const nextPath = removeTrailingSlash(next.pathname, basepath)\n\n // Both modes compare normalized paths; fuzzy matches need a segment boundary.\n if (\n activeOptions?.exact\n ? currentPath !== nextPath\n : !(\n currentPath.startsWith(nextPath) &&\n (currentPath.length === nextPath.length ||\n currentPath[nextPath.length] === '/')\n )\n ) {\n return false\n }\n\n if (activeOptions?.includeSearch ?? true) {\n const searchTest = deepEqual(\n location.search,\n next.search,\n !activeOptions?.exact,\n activeOptions?.explicitUndefined,\n )\n if (!searchTest) {\n return false\n }\n }\n\n if (activeOptions?.includeHash) {\n return isHydrated && location.hash === next.hash\n }\n return true\n}\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, TMaskLine truncated
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import * as React from 'react';
|
||||
export declare const matchContext: React.Context<string | undefined>;
|
||||
export declare const dummyMatchContext: React.Context<string | undefined>;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
"use client";
|
||||
import * as React$1 from "react";
|
||||
//#region src/matchContext.tsx
|
||||
var matchContext = React$1.createContext(void 0);
|
||||
var dummyMatchContext = React$1.createContext(void 0);
|
||||
//#endregion
|
||||
export { dummyMatchContext, matchContext };
|
||||
|
||||
//# sourceMappingURL=matchContext.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"matchContext.js","names":[],"sources":["../../src/matchContext.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\n\nexport const matchContext = React.createContext<string | undefined>(undefined)\n\n// N.B. this only exists so we can conditionally call useContext on it when we are not interested in the nearest match\nexport const dummyMatchContext = React.createContext<string | undefined>(\n undefined,\n)\n"],"mappings":";;;AAIA,IAAa,eAAe,QAAM,cAAkC,KAAA,CAAS;AAG7E,IAAa,oBAAoB,QAAM,cACrC,KAAA,CACF"}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import * as React from 'react';
|
||||
export type NonRouteComponent = 'pendingComponent' | 'errorComponent' | 'notFoundComponent';
|
||||
export declare const nonRouteComponentContext: React.Context<NonRouteComponent | undefined> | undefined;
|
||||
export declare function wrapInNonRouteComponentContext(element: React.ReactElement, component: NonRouteComponent): React.ReactElement;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
import * as React$1 from "react";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/nonRouteComponentContext.tsx
|
||||
var nonRouteComponentContext = process.env.NODE_ENV !== "production" ? React$1.createContext(void 0) : void 0;
|
||||
function wrapInNonRouteComponentContext(element, component) {
|
||||
return /* @__PURE__ */ jsx(nonRouteComponentContext.Provider, {
|
||||
value: component,
|
||||
children: element
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { nonRouteComponentContext, wrapInNonRouteComponentContext };
|
||||
|
||||
//# sourceMappingURL=nonRouteComponentContext.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"nonRouteComponentContext.js","names":[],"sources":["../../src/nonRouteComponentContext.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\n\nexport type NonRouteComponent =\n | 'pendingComponent'\n | 'errorComponent'\n | 'notFoundComponent'\n\nexport const nonRouteComponentContext =\n process.env.NODE_ENV !== 'production'\n ? React.createContext<NonRouteComponent | undefined>(undefined)\n : undefined\n\nexport function wrapInNonRouteComponentContext(\n element: React.ReactElement,\n component: NonRouteComponent,\n): React.ReactElement {\n const Context = nonRouteComponentContext!\n return <Context.Provider value={component}>{element}</Context.Provider>\n}\n"],"mappings":";;;;AASA,IAAa,2BAAA,QAAA,IAAA,aACc,eACrB,QAAM,cAA6C,KAAA,CAAS,IAC5D,KAAA;AAEN,SAAgB,+BACd,SACA,WACoB;CAEpB,OAAO,oBAAC,yBAAQ,UAAT;EAAkB,OAAO;YAAY;CAA0B,CAAA;AACxE"}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { ErrorInfo } from 'react';
|
||||
import { NotFoundError } from '@tanstack/router-core';
|
||||
import * as React from 'react';
|
||||
export declare function CatchNotFound(props: {
|
||||
fallback?: (error: NotFoundError) => React.ReactElement;
|
||||
onCatch?: (error: NotFoundError, errorInfo: ErrorInfo) => void;
|
||||
children: React.ReactNode;
|
||||
}): import("react/jsx-runtime").JSX.Element;
|
||||
export declare function DefaultGlobalNotFound(): import("react/jsx-runtime").JSX.Element;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { CatchBoundary } from "./CatchBoundary.js";
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { isNotFound } from "@tanstack/router-core";
|
||||
import "react";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
import { useSelector } from "@tanstack/react-store";
|
||||
//#region src/not-found.tsx
|
||||
function CatchNotFound(props) {
|
||||
const router = useRouter();
|
||||
if (isServer ?? router.isServer) {
|
||||
const resetKey = `not-found-${router.stores.location.get().pathname}-${router.stores.status.get()}`;
|
||||
return /* @__PURE__ */ jsx(CatchBoundary, {
|
||||
getResetKey: () => resetKey,
|
||||
onCatch: (error, errorInfo) => {
|
||||
if (isNotFound(error)) props.onCatch?.(error, errorInfo);
|
||||
else throw error;
|
||||
},
|
||||
errorComponent: ({ error }) => {
|
||||
if (isNotFound(error)) return props.fallback?.(error);
|
||||
else throw error;
|
||||
},
|
||||
children: props.children
|
||||
});
|
||||
}
|
||||
const resetKey = `not-found-${useSelector(router.stores.location, (location) => location.pathname)}-${useSelector(router.stores.status)}`;
|
||||
return /* @__PURE__ */ jsx(CatchBoundary, {
|
||||
getResetKey: () => resetKey,
|
||||
onCatch: (error, errorInfo) => {
|
||||
if (isNotFound(error)) props.onCatch?.(error, errorInfo);
|
||||
else throw error;
|
||||
},
|
||||
errorComponent: ({ error }) => {
|
||||
if (isNotFound(error)) return props.fallback?.(error);
|
||||
else throw error;
|
||||
},
|
||||
children: props.children
|
||||
});
|
||||
}
|
||||
function DefaultGlobalNotFound() {
|
||||
return /* @__PURE__ */ jsx("p", { children: "Not Found" });
|
||||
}
|
||||
//#endregion
|
||||
export { CatchNotFound, DefaultGlobalNotFound };
|
||||
|
||||
//# sourceMappingURL=not-found.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"not-found.js","names":[],"sources":["../../src/not-found.tsx"],"sourcesContent":["import * as React from 'react'\nimport { isNotFound } from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { useSelector } from '@tanstack/react-store'\nimport { CatchBoundary } from './CatchBoundary'\nimport { useRouter } from './useRouter'\nimport type { ErrorInfo } from 'react'\nimport type { NotFoundError } from '@tanstack/router-core'\n\nexport function CatchNotFound(props: {\n fallback?: (error: NotFoundError) => React.ReactElement\n onCatch?: (error: NotFoundError, errorInfo: ErrorInfo) => void\n children: React.ReactNode\n}) {\n const router = useRouter()\n\n if (isServer ?? router.isServer) {\n const pathname = router.stores.location.get().pathname\n const status = router.stores.status.get()\n const resetKey = `not-found-${pathname}-${status}`\n\n return (\n <CatchBoundary\n getResetKey={() => resetKey}\n onCatch={(error, errorInfo) => {\n if (isNotFound(error)) {\n props.onCatch?.(error, errorInfo)\n } else {\n throw error\n }\n }}\n errorComponent={({ error }) => {\n if (isNotFound(error)) {\n return props.fallback?.(error)\n } else {\n throw error\n }\n }}\n >\n {props.children}\n </CatchBoundary>\n )\n }\n\n // TODO: Some way for the user to programmatically reset the not-found boundary?\n // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static\n const pathname = useSelector(\n router.stores.location,\n (location) => location.pathname,\n )\n // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static\n const status = useSelector(router.stores.status)\n const resetKey = `not-found-${pathname}-${status}`\n\n return (\n <CatchBoundary\n getResetKey={() => resetKey}\n onCatch={(error, errorInfo) => {\n if (isNotFound(error)) {\n props.onCatch?.(error, errorInfo)\n } else {\n throw error\n }\n }}\n errorComponent={({ error }) => {\n if (isNotFound(error)) {\n return props.fallback?.(error)\n } else {\n throw error\n }\n }}\n >\n {props.children}\n </CatchBoundary>\n )\n}\n\nexport function DefaultGlobalNotFound() {\n return <p>Not Found</p>\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,cAAc,OAI3B;CACD,MAAM,SAAS,UAAU;CAEzB,IAAI,YAAY,OAAO,UAAU;EAG/B,MAAM,WAAW,aAFA,OAAO,OAAO,SAAS,IAAI,EAAE,SAEP,GADxB,OAAO,OAAO,OAAO,IACM;EAE1C,OACE,oBAAC,eAAD;GACE,mBAAmB;GACnB,UAAU,OAAO,cAAc;IAC7B,IAAI,WAAW,KAAK,GAClB,MAAM,UAAU,OAAO,SAAS;SAEhC,MAAM;GAEV;GACA,iBAAiB,EAAE,YAAY;IAC7B,IAAI,WAAW,KAAK,GAClB,OAAO,MAAM,WAAW,KAAK;SAE7B,MAAM;GAEV;aAEC,MAAM;EACM,CAAA;CAEnB;CAUA,MAAM,WAAW,aANA,YACf,OAAO,OAAO,WACb,aAAa,SAAS,QAIK,EAAS,GADxB,YAAY,OAAO,OAAO,MACC;CAE1C,OACE,oBAAC,eAAD;EACE,mBAAmB;EACnB,UAAU,OAAO,cAAc;GAC7B,IAAI,WAAW,KAAK,GAClB,MAAM,UAAU,OAAO,SAAS;QAEhC,MAAM;EAEV;EACA,iBAAiB,EAAE,YAAY;GAC7B,IAAI,WAAW,KAAK,GAClB,OAAO,MAAM,WAAW,KAAK;QAE7B,MAAM;EAEV;YAEC,MAAM;CACM,CAAA;AAEnB;AAEA,SAAgB,wBAAwB;CACtC,OAAO,oBAAC,KAAD,EAAA,UAAG,YAAY,CAAA;AACxB"}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { AnyRoute, AnyRouter } from '@tanstack/router-core';
|
||||
/**
|
||||
* Renders a not found component for a route when no matching route is found.
|
||||
*
|
||||
* @param router - The router instance containing the route configuration
|
||||
* @param route - The route that triggered the not found state
|
||||
* @param data - Additional data to pass to the not found component
|
||||
* @returns The rendered not found component or a default fallback component
|
||||
*/
|
||||
export declare function renderRouteNotFound(router: AnyRouter, route: AnyRoute, data: any): import("react/jsx-runtime").JSX.Element;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { wrapInNonRouteComponentContext } from "./nonRouteComponentContext.js";
|
||||
import { DefaultGlobalNotFound } from "./not-found.js";
|
||||
import "react";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/renderRouteNotFound.tsx
|
||||
/**
|
||||
* Renders a not found component for a route when no matching route is found.
|
||||
*
|
||||
* @param router - The router instance containing the route configuration
|
||||
* @param route - The route that triggered the not found state
|
||||
* @param data - Additional data to pass to the not found component
|
||||
* @returns The rendered not found component or a default fallback component
|
||||
*/
|
||||
function renderRouteNotFound(router, route, data) {
|
||||
if (!route.options.notFoundComponent) {
|
||||
if (router.options.defaultNotFoundComponent) {
|
||||
const notFoundElement = /* @__PURE__ */ jsx(router.options.defaultNotFoundComponent, { ...data });
|
||||
return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(notFoundElement, "notFoundComponent") : notFoundElement;
|
||||
}
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
if (!route.options.notFoundComponent) console.warn(`Warning: A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<p>Not Found</p>)`);
|
||||
}
|
||||
return /* @__PURE__ */ jsx(DefaultGlobalNotFound, {});
|
||||
}
|
||||
const notFoundElement = /* @__PURE__ */ jsx(route.options.notFoundComponent, { ...data });
|
||||
return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(notFoundElement, "notFoundComponent") : notFoundElement;
|
||||
}
|
||||
//#endregion
|
||||
export { renderRouteNotFound };
|
||||
|
||||
//# sourceMappingURL=renderRouteNotFound.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"renderRouteNotFound.js","names":[],"sources":["../../src/renderRouteNotFound.tsx"],"sourcesContent":["import * as React from 'react'\nimport { DefaultGlobalNotFound } from './not-found'\nimport { wrapInNonRouteComponentContext } from './nonRouteComponentContext'\nimport type { AnyRoute, AnyRouter } from '@tanstack/router-core'\n\n/**\n * Renders a not found component for a route when no matching route is found.\n *\n * @param router - The router instance containing the route configuration\n * @param route - The route that triggered the not found state\n * @param data - Additional data to pass to the not found component\n * @returns The rendered not found component or a default fallback component\n */\nexport function renderRouteNotFound(\n router: AnyRouter,\n route: AnyRoute,\n data: any,\n) {\n if (!route.options.notFoundComponent) {\n if (router.options.defaultNotFoundComponent) {\n const notFoundElement = (\n <router.options.defaultNotFoundComponent {...data} />\n )\n return process.env.NODE_ENV !== 'production'\n ? wrapInNonRouteComponentContext(notFoundElement, 'notFoundComponent')\n : notFoundElement\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!route.options.notFoundComponent) {\n console.warn(\n `Warning: A notFoundError was encountered on the route with ID \"${route.id}\", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<p>Not Found</p>)`,\n )\n }\n }\n\n return <DefaultGlobalNotFound />\n }\n\n const notFoundElement = <route.options.notFoundComponent {...data} />\n return process.env.NODE_ENV !== 'production'\n ? wrapInNonRouteComponentContext(notFoundElement, 'notFoundComponent')\n : notFoundElement\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,oBACd,QACA,OACA,MACA;CACA,IAAI,CAAC,MAAM,QAAQ,mBAAmB;EACpC,IAAI,OAAO,QAAQ,0BAA0B;GAC3C,MAAM,kBACJ,oBAAC,OAAO,QAAQ,0BAAhB,EAAyC,GAAI,KAAO,CAAA;GAEtD,OAAA,QAAA,IAAA,aAAgC,eAC5B,+BAA+B,iBAAiB,mBAAmB,IACnE;EACN;EAEA,IAAA,QAAA,IAAA,aAA6B;OACvB,CAAC,MAAM,QAAQ,mBACjB,QAAQ,KACN,kEAAkE,MAAM,GAAG,mPAC7E;EAAA;EAIJ,OAAO,oBAAC,uBAAD,CAAwB,CAAA;CACjC;CAEA,MAAM,kBAAkB,oBAAC,MAAM,QAAQ,mBAAf,EAAiC,GAAI,KAAO,CAAA;CACpE,OAAA,QAAA,IAAA,aAAgC,eAC5B,+BAA+B,iBAAiB,mBAAmB,IACnE;AACN"}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import { BaseRootRoute, BaseRoute, BaseRouteApi, AnyContext, AnyRoute, AnyRouter, ConstrainLiteral, ErrorComponentProps, NotFoundError, NotFoundRouteProps, Register, RegisteredRouter, ResolveFullPath, ResolveId, ResolveParams, RootRoute as RootRouteCore, RootRouteId, RootRouteOptions, RouteConstraints, Route as RouteCore, RouteIds, RouteMask, RouteOptions, RouteTypesById, RouterCore, ToMaskOptions, UseNavigateResult } from '@tanstack/router-core';
|
||||
import { default as React } from 'react';
|
||||
import { UseLoaderDataRoute } from './useLoaderData.js';
|
||||
import { UseMatchRoute } from './useMatch.js';
|
||||
import { UseLoaderDepsRoute } from './useLoaderDeps.js';
|
||||
import { UseParamsRoute } from './useParams.js';
|
||||
import { UseSearchRoute } from './useSearch.js';
|
||||
import { UseRouteContextRoute } from './useRouteContext.js';
|
||||
import { LinkComponentRoute } from './link.js';
|
||||
declare module '@tanstack/router-core' {
|
||||
interface UpdatableRouteOptionsExtensions {
|
||||
component?: RouteComponent;
|
||||
errorComponent?: false | null | undefined | ErrorRouteComponent;
|
||||
notFoundComponent?: NotFoundRouteComponent;
|
||||
pendingComponent?: RouteComponent;
|
||||
}
|
||||
interface RootRouteOptionsExtensions {
|
||||
shellComponent?: ({ children, }: {
|
||||
children: React.ReactNode;
|
||||
}) => React.ReactNode;
|
||||
}
|
||||
interface RouteExtensions<in out TId extends string, in out TFullPath extends string> {
|
||||
useMatch: UseMatchRoute<TId>;
|
||||
useRouteContext: UseRouteContextRoute<TId>;
|
||||
useSearch: UseSearchRoute<TId>;
|
||||
useParams: UseParamsRoute<TId>;
|
||||
useLoaderDeps: UseLoaderDepsRoute<TId>;
|
||||
useLoaderData: UseLoaderDataRoute<TId>;
|
||||
useNavigate: () => UseNavigateResult<TFullPath>;
|
||||
Link: LinkComponentRoute<TFullPath>;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns a route-specific API that exposes type-safe hooks pre-bound
|
||||
* to a single route ID. Useful for consuming a route's APIs from files
|
||||
* where the route object isn't directly imported (e.g. code-split files).
|
||||
*
|
||||
* @param id Route ID string literal for the target route.
|
||||
* @returns A `RouteApi` instance bound to the given route ID.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/getRouteApiFunction
|
||||
*/
|
||||
export declare function getRouteApi<const TId, TRouter extends AnyRouter = RegisteredRouter>(id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>): RouteApi<TId, TRouter>;
|
||||
export declare class RouteApi<TId, TRouter extends AnyRouter = RegisteredRouter> extends BaseRouteApi<TId, TRouter> {
|
||||
/**
|
||||
* @deprecated Use the `getRouteApi` function instead.
|
||||
*/
|
||||
constructor({ id }: {
|
||||
id: TId;
|
||||
});
|
||||
useMatch: UseMatchRoute<TId>;
|
||||
useRouteContext: UseRouteContextRoute<TId>;
|
||||
useSearch: UseSearchRoute<TId>;
|
||||
useParams: UseParamsRoute<TId>;
|
||||
useLoaderDeps: UseLoaderDepsRoute<TId>;
|
||||
useLoaderData: UseLoaderDataRoute<TId>;
|
||||
useNavigate: () => UseNavigateResult<RouteTypesById<TRouter, TId>["fullPath"]>;
|
||||
notFound: (opts?: NotFoundError) => NotFoundError;
|
||||
Link: LinkComponentRoute<RouteTypesById<TRouter, TId>['fullPath']>;
|
||||
}
|
||||
export declare class Route<in out TRegister = unknown, in out TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute, in out TPath extends RouteConstraints['TPath'] = '/', in out TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<TParentRoute, TPath>, in out TCustomId extends RouteConstraints['TCustomId'] = string, in out TId extends RouteConstraints['TId'] = ResolveId<TParentRoute, TCustomId, TPath>, in out TSearchValidator = undefined, in out TParams = ResolveParams<TPath>, in out TRouterContext = AnyContext, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> extends BaseRoute<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> implements RouteCore<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> {
|
||||
/**
|
||||
* @deprecated Use the `createRoute` function instead.
|
||||
*/
|
||||
constructor(options?: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>);
|
||||
useMatch: UseMatchRoute<TId>;
|
||||
useRouteContext: UseRouteContextRoute<TId>;
|
||||
useSearch: UseSearchRoute<TId>;
|
||||
useParams: UseParamsRoute<TId>;
|
||||
useLoaderDeps: UseLoaderDepsRoute<TId>;
|
||||
useLoaderData: UseLoaderDataRoute<TId>;
|
||||
useNavigate: () => UseNavigateResult<TFullPath>;
|
||||
Link: LinkComponentRoute<TFullPath>;
|
||||
}
|
||||
/**
|
||||
* Creates a non-root Route instance for code-based routing.
|
||||
*
|
||||
* Use this to define a route that will be composed into a route tree
|
||||
* (typically via a parent route's `addChildren`). If you're using file-based
|
||||
* routing, prefer `createFileRoute`.
|
||||
*
|
||||
* @param options Route options (path, component, loader, context, etc.).
|
||||
* @returns A Route instance to be attached to the route tree.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouteFunction
|
||||
*/
|
||||
export declare function createRoute<TRegister = unknown, TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute, TPath extends RouteConstraints['TPath'] = '/', TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<TParentRoute, TPath>, TCustomId extends RouteConstraints['TCustomId'] = string, TId extends RouteConstraints['TId'] = ResolveId<TParentRoute, TCustomId, TPath>, TSearchValidator = undefined, TParams = ResolveParams<TPath>, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TChildren = unknown, TSSR = unknown, const TServerMiddlewares = unknown>(options: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, AnyContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares>): Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, AnyContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TSSR, TServerMiddlewares>;
|
||||
export type AnyRootRoute = RootRoute<any, any, any, any, any, any, any, any, any, any, any>;
|
||||
/**
|
||||
* Creates a root route factory that requires a router context type.
|
||||
*
|
||||
* Use when your root route expects `context` to be provided to `createRouter`.
|
||||
* The returned function behaves like `createRootRoute` but enforces a context type.
|
||||
*
|
||||
* @returns A factory function to configure and return a root route.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteWithContextFunction
|
||||
*/
|
||||
export declare function createRootRouteWithContext<TRouterContext extends {}>(): <TRegister = Register, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TSearchValidator = undefined, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TSSR = unknown, TServerMiddlewares = unknown>(options?: RootRouteOptions<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TSSR, TServerMiddlewares>) => RootRoute<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, unknown, unknown, TSSR, TServerMiddlewares, undefined>;
|
||||
/**
|
||||
* @deprecated Use the `createRootRouteWithContext` function instead.
|
||||
*/
|
||||
export declare const rootRouteWithContext: typeof createRootRouteWithContext;
|
||||
export declare class RootRoute<in out TRegister = unknown, in out TSearchValidator = undefined, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> extends BaseRootRoute<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> implements RootRouteCore<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> {
|
||||
/**
|
||||
* @deprecated `RootRoute` is now an internal implementation detail. Use `createRootRoute()` instead.
|
||||
*/
|
||||
constructor(options?: RootRouteOptions<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TSSR, TServerMiddlewares, THandlers>);
|
||||
useMatch: UseMatchRoute<RootRouteId>;
|
||||
useRouteContext: UseRouteContextRoute<RootRouteId>;
|
||||
useSearch: UseSearchRoute<RootRouteId>;
|
||||
useParams: UseParamsRoute<RootRouteId>;
|
||||
useLoaderDeps: UseLoaderDepsRoute<RootRouteId>;
|
||||
useLoaderData: UseLoaderDataRoute<RootRouteId>;
|
||||
useNavigate: () => UseNavigateResult<"/">;
|
||||
Link: LinkComponentRoute<'/'>;
|
||||
}
|
||||
/**
|
||||
* Creates a root Route instance used to build your route tree.
|
||||
*
|
||||
* Typically paired with `createRouter({ routeTree })`. If you need to require
|
||||
* a typed router context, use `createRootRouteWithContext` instead.
|
||||
*
|
||||
* @param options Root route options (component, error, pending, etc.).
|
||||
* @returns A root route instance.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteFunction
|
||||
*/
|
||||
export declare function createRootRoute<TRegister = Register, TSearchValidator = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TSSR = unknown, const TServerMiddlewares = unknown, THandlers = undefined>(options?: RootRouteOptions<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TSSR, TServerMiddlewares, THandlers>): RootRoute<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, unknown, unknown, TSSR, TServerMiddlewares, THandlers>;
|
||||
export declare function createRouteMask<TRouteTree extends AnyRoute, TFrom extends string, TTo extends string>(opts: {
|
||||
routeTree: TRouteTree;
|
||||
} & ToMaskOptions<RouterCore<TRouteTree, 'never', boolean>, TFrom, TTo>): RouteMask<TRouteTree>;
|
||||
export interface DefaultRouteTypes<TProps> {
|
||||
component: ((props: TProps) => any) | React.LazyExoticComponent<(props: TProps) => any>;
|
||||
}
|
||||
export interface RouteTypes<TProps> extends DefaultRouteTypes<TProps> {
|
||||
}
|
||||
export type AsyncRouteComponent<TProps> = RouteTypes<TProps>['component'] & {
|
||||
preload?: () => Promise<void> | undefined;
|
||||
};
|
||||
export type RouteComponent = AsyncRouteComponent<{}>;
|
||||
export type ErrorRouteComponent = AsyncRouteComponent<ErrorComponentProps>;
|
||||
export type NotFoundRouteComponent = RouteTypes<NotFoundRouteProps>['component'];
|
||||
export declare class NotFoundRoute<TRegister, TParentRoute extends AnyRootRoute, TRouterContext = AnyContext, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TSearchValidator = undefined, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TChildren = unknown, TSSR = unknown, TServerMiddlewares = unknown> extends Route<TRegister, TParentRoute, '/404', '/404', '404', '404', TSearchValidator, {}, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TSSR, TServerMiddlewares> {
|
||||
constructor(options: Omit<RouteOptions<TRegister, TParentRoute, string, string, string, string, TSearchValidator, {}, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares>, 'caseSensitive' | 'parseParams' | 'stringifyParams' | 'path' | 'id' | 'params'>);
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { useMatch } from "./useMatch.js";
|
||||
import { useLoaderData } from "./useLoaderData.js";
|
||||
import { useLoaderDeps } from "./useLoaderDeps.js";
|
||||
import { useParams } from "./useParams.js";
|
||||
import { useSearch } from "./useSearch.js";
|
||||
import { useNavigate } from "./useNavigate.js";
|
||||
import { useRouteContext } from "./useRouteContext.js";
|
||||
import { Link } from "./link.js";
|
||||
import { BaseRootRoute, BaseRoute, BaseRouteApi, notFound } from "@tanstack/router-core";
|
||||
import React from "react";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/route.tsx
|
||||
/**
|
||||
* Returns a route-specific API that exposes type-safe hooks pre-bound
|
||||
* to a single route ID. Useful for consuming a route's APIs from files
|
||||
* where the route object isn't directly imported (e.g. code-split files).
|
||||
*
|
||||
* @param id Route ID string literal for the target route.
|
||||
* @returns A `RouteApi` instance bound to the given route ID.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/getRouteApiFunction
|
||||
*/
|
||||
function getRouteApi(id) {
|
||||
return new RouteApi({ id });
|
||||
}
|
||||
var RouteApi = class extends BaseRouteApi {
|
||||
/**
|
||||
* @deprecated Use the `getRouteApi` function instead.
|
||||
*/
|
||||
constructor({ id }) {
|
||||
super({ id });
|
||||
this.useMatch = (opts) => {
|
||||
return useMatch({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useRouteContext = (opts) => {
|
||||
return useRouteContext({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useSearch = (opts) => {
|
||||
return useSearch({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useParams = (opts) => {
|
||||
return useParams({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useLoaderDeps = (opts) => {
|
||||
return useLoaderDeps({
|
||||
...opts,
|
||||
from: this.id,
|
||||
strict: false
|
||||
});
|
||||
};
|
||||
this.useLoaderData = (opts) => {
|
||||
return useLoaderData({
|
||||
...opts,
|
||||
from: this.id,
|
||||
strict: false
|
||||
});
|
||||
};
|
||||
this.useNavigate = () => {
|
||||
return useNavigate({ from: useRouter().routesById[this.id].fullPath });
|
||||
};
|
||||
this.notFound = (opts) => {
|
||||
return notFound({
|
||||
routeId: this.id,
|
||||
...opts
|
||||
});
|
||||
};
|
||||
this.Link = React.forwardRef((props, ref) => {
|
||||
const fullPath = useRouter().routesById[this.id].fullPath;
|
||||
return /* @__PURE__ */ jsx(Link, {
|
||||
ref,
|
||||
from: fullPath,
|
||||
...props
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
var Route = class extends BaseRoute {
|
||||
/**
|
||||
* @deprecated Use the `createRoute` function instead.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.useMatch = (opts) => {
|
||||
return useMatch({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useRouteContext = (opts) => {
|
||||
return useRouteContext({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useSearch = (opts) => {
|
||||
return useSearch({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useParams = (opts) => {
|
||||
return useParams({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useLoaderDeps = (opts) => {
|
||||
return useLoaderDeps({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useLoaderData = (opts) => {
|
||||
return useLoaderData({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useNavigate = () => {
|
||||
return useNavigate({ from: this.fullPath });
|
||||
};
|
||||
this.Link = React.forwardRef((props, ref) => {
|
||||
return /* @__PURE__ */ jsx(Link, {
|
||||
ref,
|
||||
from: this.fullPath,
|
||||
...props
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Creates a non-root Route instance for code-based routing.
|
||||
*
|
||||
* Use this to define a route that will be composed into a route tree
|
||||
* (typically via a parent route's `addChildren`). If you're using file-based
|
||||
* routing, prefer `createFileRoute`.
|
||||
*
|
||||
* @param options Route options (path, component, loader, context, etc.).
|
||||
* @returns A Route instance to be attached to the route tree.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouteFunction
|
||||
*/
|
||||
function createRoute(options) {
|
||||
return new Route(options);
|
||||
}
|
||||
/**
|
||||
* Creates a root route factory that requires a router context type.
|
||||
*
|
||||
* Use when your root route expects `context` to be provided to `createRouter`.
|
||||
* The returned function behaves like `createRootRoute` but enforces a context type.
|
||||
*
|
||||
* @returns A factory function to configure and return a root route.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteWithContextFunction
|
||||
*/
|
||||
function createRootRouteWithContext() {
|
||||
return (options) => {
|
||||
return createRootRoute(options);
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @deprecated Use the `createRootRouteWithContext` function instead.
|
||||
*/
|
||||
var rootRouteWithContext = createRootRouteWithContext;
|
||||
var RootRoute = class extends BaseRootRoute {
|
||||
/**
|
||||
* @deprecated `RootRoute` is now an internal implementation detail. Use `createRootRoute()` instead.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.useMatch = (opts) => {
|
||||
return useMatch({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useRouteContext = (opts) => {
|
||||
return useRouteContext({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useSearch = (opts) => {
|
||||
return useSearch({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useParams = (opts) => {
|
||||
return useParams({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useLoaderDeps = (opts) => {
|
||||
return useLoaderDeps({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useLoaderData = (opts) => {
|
||||
return useLoaderData({
|
||||
...opts,
|
||||
from: this.id
|
||||
});
|
||||
};
|
||||
this.useNavigate = () => {
|
||||
return useNavigate({ from: this.fullPath });
|
||||
};
|
||||
this.Link = React.forwardRef((props, ref) => {
|
||||
return /* @__PURE__ */ jsx(Link, {
|
||||
ref,
|
||||
from: this.fullPath,
|
||||
...props
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Creates a root Route instance used to build your route tree.
|
||||
*
|
||||
* Typically paired with `createRouter({ routeTree })`. If you need to require
|
||||
* a typed router context, use `createRootRouteWithContext` instead.
|
||||
*
|
||||
* @param options Root route options (component, error, pending, etc.).
|
||||
* @returns A root route instance.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteFunction
|
||||
*/
|
||||
function createRootRoute(options) {
|
||||
return new RootRoute(options);
|
||||
}
|
||||
function createRouteMask(opts) {
|
||||
return opts;
|
||||
}
|
||||
var NotFoundRoute = class extends Route {
|
||||
constructor(options) {
|
||||
super({
|
||||
...options,
|
||||
id: "404"
|
||||
});
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
export { NotFoundRoute, RootRoute, Route, RouteApi, createRootRoute, createRootRouteWithContext, createRoute, createRouteMask, getRouteApi, rootRouteWithContext };
|
||||
|
||||
//# sourceMappingURL=route.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"route.js","names":[],"sources":["../../src/route.tsx"],"sourcesContent":["import {\n BaseRootRoute,\n BaseRoute,\n BaseRouteApi,\n notFound,\n} from '@tanstack/router-core'\nimport React from 'react'\nimport { useLoaderData } from './useLoaderData'\nimport { useLoaderDeps } from './useLoaderDeps'\nimport { useParams } from './useParams'\nimport { useSearch } from './useSearch'\nimport { useNavigate } from './useNavigate'\nimport { useMatch } from './useMatch'\nimport { useRouteContext } from './useRouteContext'\nimport { useRouter } from './useRouter'\nimport { Link } from './link'\nimport type {\n AnyContext,\n AnyRoute,\n AnyRouter,\n ConstrainLiteral,\n ErrorComponentProps,\n NotFoundError,\n NotFoundRouteProps,\n Register,\n RegisteredRouter,\n ResolveFullPath,\n ResolveId,\n ResolveParams,\n RootRoute as RootRouteCore,\n RootRouteId,\n RootRouteOptions,\n RouteConstraints,\n Route as RouteCore,\n RouteIds,\n RouteMask,\n RouteOptions,\n RouteTypesById,\n RouterCore,\n ToMaskOptions,\n UseNavigateResult,\n} from '@tanstack/router-core'\nimport type { UseLoaderDataRoute } from './useLoaderData'\nimport type { UseMatchRoute } from './useMatch'\nimport type { UseLoaderDepsRoute } from './useLoaderDeps'\nimport type { UseParamsRoute } from './useParams'\nimport type { UseSearchRoute } from './useSearch'\nimport type { UseRouteContextRoute } from './useRouteContext'\nimport type { LinkComponentRoute } from './link'\n\ndeclare module '@tanstack/router-core' {\n export interface UpdatableRouteOptionsExtensions {\n component?: RouteComponent\n errorComponent?: false | null | undefined | ErrorRouteComponent\n notFoundComponent?: NotFoundRouteComponent\n pendingComponent?: RouteComponent\n }\n\n export interface RootRouteOptionsExtensions {\n shellComponent?: ({\n children,\n }: {\n children: React.ReactNode\n }) => React.ReactNode\n }\n\n export interface RouteExtensions<\n in out TId extends string,\n in out TFullPath extends string,\n > {\n useMatch: UseMatchRoute<TId>\n useRouteContext: UseRouteContextRoute<TId>\n useSearch: UseSearchRoute<TId>\n useParams: UseParamsRoute<TId>\n useLoaderDeps: UseLoaderDepsRoute<TId>\n useLoaderData: UseLoaderDataRoute<TId>\n useNavigate: () => UseNavigateResult<TFullPath>\n Link: LinkComponentRoute<TFullPath>\n }\n}\n\n/**\n * Returns a route-specific API that exposes type-safe hooks pre-bound\n * to a single route ID. Useful for consuming a route's APIs from files\n * where the route object isn't directly imported (e.g. code-split files).\n *\n * @param id Route ID string literal for the target route.\n * @returns A `RouteApi` instance bound to the given route ID.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/getRouteApiFunction\n */\nexport function getRouteApi<\n const TId,\n TRouter extends AnyRouter = RegisteredRouter,\n>(id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>) {\n return new RouteApi<TId, TRouter>({ id })\n}\n\nexport class RouteApi<\n TId,\n TRouter extends AnyRouter = RegisteredRouter,\n> extends BaseRouteApi<TId, TRouter> {\n /**\n * @deprecated Use the `getRouteApi` function instead.\n */\n constructor({ id }: { id: TId }) {\n super({ id })\n }\n\n useMatch: UseMatchRoute<TId> = (opts) => {\n return useMatch({ ...opts, from: this.id } as any) as any\n }\n\n useRouteContext: UseRouteContextRoute<TId> = (opts) => {\n return useRouteContext({ ...(opts as any), from: this.id })\n }\n\n useSearch: UseSearchRoute<TId> = (opts) => {\n return useSearch({ ...opts, from: this.id } as any)\n }\n\n useParams: UseParamsRoute<TId> = (opts) => {\n return useParams({ ...opts, from: this.id } as any)\n }\n\n useLoaderDeps: UseLoaderDepsRoute<TId> = (opts) => {\n return useLoaderDeps({ ...opts, from: this.id, strict: false } as any)\n }\n\n useLoaderData: UseLoaderDataRoute<TId> = (opts) => {\n return useLoaderData({ ...opts, from: this.id, strict: false } as any)\n }\n\n useNavigate = (): UseNavigateResult<\n RouteTypesById<TRouter, TId>['fullPath']\n > => {\n const router = useRouter()\n return useNavigate({ from: router.routesById[this.id as string].fullPath })\n }\n\n notFound = (opts?: NotFoundError) => {\n return notFound({ routeId: this.id as string, ...opts })\n }\n\n Link: LinkComponentRoute<RouteTypesById<TRouter, TId>['fullPath']> =\n React.forwardRef((props, ref: React.ForwardedRef<HTMLAnchorElement>) => {\n const router = useRouter()\n const fullPath = router.routesById[this.id as string].fullPath\n return <Link ref={ref} from={fullPath as never} {...props} />\n }) as unknown as LinkComponentRoute<\n RouteTypesById<TRouter, TId>['fullPath']\n >\n}\n\nexport class Route<\n in out TRegister = unknown,\n in out TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,\n in out TPath extends RouteConstraintsLine truncated
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import { RouterCore, AnyRoute, CreateRouterFn, RouterConstructorOptions, TrailingSlashOption } from '@tanstack/router-core';
|
||||
import { RouterHistory } from '@tanstack/history';
|
||||
import { ErrorRouteComponent, NotFoundRouteComponent, RouteComponent } from './route.js';
|
||||
declare module '@tanstack/router-core' {
|
||||
interface RouterOptionsExtensions {
|
||||
/**
|
||||
* The default `component` a route should use if no component is provided.
|
||||
*
|
||||
* @default Outlet
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultcomponent-property)
|
||||
*/
|
||||
defaultComponent?: RouteComponent;
|
||||
/**
|
||||
* The default `errorComponent` a route should use if no error component is provided.
|
||||
*
|
||||
* @default ErrorComponent
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaulterrorcomponent-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionserrorcomponent)
|
||||
*/
|
||||
defaultErrorComponent?: ErrorRouteComponent;
|
||||
/**
|
||||
* The default `pendingComponent` a route should use if no pending component is provided.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingcomponent-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#showing-a-pending-component)
|
||||
*/
|
||||
defaultPendingComponent?: RouteComponent;
|
||||
/**
|
||||
* The default `notFoundComponent` a route should use if no notFound component is provided.
|
||||
*
|
||||
* @default NotFound
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultnotfoundcomponent-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors#default-router-wide-not-found-handling)
|
||||
*/
|
||||
defaultNotFoundComponent?: NotFoundRouteComponent;
|
||||
/**
|
||||
* A component that will be used to wrap the entire router.
|
||||
*
|
||||
* This is useful for providing a context to the entire router.
|
||||
*
|
||||
* Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#wrap-property)
|
||||
*/
|
||||
Wrap?: (props: {
|
||||
children: any;
|
||||
}) => React.JSX.Element;
|
||||
/**
|
||||
* A component that will be used to wrap the inner contents of the router.
|
||||
*
|
||||
* This is useful for providing a context to the inner contents of the router where you also need access to the router context and hooks.
|
||||
*
|
||||
* Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#innerwrap-property)
|
||||
*/
|
||||
InnerWrap?: (props: {
|
||||
children: any;
|
||||
}) => React.JSX.Element;
|
||||
/**
|
||||
* The default `onCatch` handler for errors caught by the Router ErrorBoundary
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultoncatch-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionsoncatch)
|
||||
*/
|
||||
defaultOnCatch?: (error: unknown, errorInfo: React.ErrorInfo) => void;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a new Router instance for React.
|
||||
*
|
||||
* Pass the returned router to `RouterProvider` to enable routing.
|
||||
* Notable options: `routeTree` (your route definitions) and `context`
|
||||
* (required if the root route was created with `createRootRouteWithContext`).
|
||||
*
|
||||
* @param options Router options used to configure the router.
|
||||
* @returns A Router instance to be provided to `RouterProvider`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction
|
||||
*/
|
||||
export declare const createRouter: CreateRouterFn;
|
||||
export declare class Router<in out TRouteTree extends AnyRoute, in out TTrailingSlashOption extends TrailingSlashOption = 'never', in out TDefaultStructuralSharingOption extends boolean = false, in out TRouterHistory extends RouterHistory = RouterHistory, in out TDehydrated extends Record<string, any> = Record<string, any>> extends RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated> {
|
||||
constructor(options: RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import { getStoreFactory } from "./routerStores.js";
|
||||
import { RouterCore } from "@tanstack/router-core";
|
||||
//#region src/router.ts
|
||||
/**
|
||||
* Creates a new Router instance for React.
|
||||
*
|
||||
* Pass the returned router to `RouterProvider` to enable routing.
|
||||
* Notable options: `routeTree` (your route definitions) and `context`
|
||||
* (required if the root route was created with `createRootRouteWithContext`).
|
||||
*
|
||||
* @param options Router options used to configure the router.
|
||||
* @returns A Router instance to be provided to `RouterProvider`.
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction
|
||||
*/
|
||||
var createRouter = (options) => {
|
||||
return new Router(options);
|
||||
};
|
||||
var Router = class extends RouterCore {
|
||||
constructor(options) {
|
||||
super(options, getStoreFactory);
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
export { Router, createRouter };
|
||||
|
||||
//# sourceMappingURL=router.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"router.js","names":[],"sources":["../../src/router.ts"],"sourcesContent":["import { RouterCore } from '@tanstack/router-core'\nimport { getStoreFactory } from './routerStores'\nimport type { RouterHistory } from '@tanstack/history'\nimport type {\n AnyRoute,\n CreateRouterFn,\n RouterConstructorOptions,\n TrailingSlashOption,\n} from '@tanstack/router-core'\n\nimport type {\n ErrorRouteComponent,\n NotFoundRouteComponent,\n RouteComponent,\n} from './route'\n\ndeclare module '@tanstack/router-core' {\n export interface RouterOptionsExtensions {\n /**\n * The default `component` a route should use if no component is provided.\n *\n * @default Outlet\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultcomponent-property)\n */\n defaultComponent?: RouteComponent\n /**\n * The default `errorComponent` a route should use if no error component is provided.\n *\n * @default ErrorComponent\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaulterrorcomponent-property)\n * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionserrorcomponent)\n */\n defaultErrorComponent?: ErrorRouteComponent\n /**\n * The default `pendingComponent` a route should use if no pending component is provided.\n *\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingcomponent-property)\n * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#showing-a-pending-component)\n */\n defaultPendingComponent?: RouteComponent\n /**\n * The default `notFoundComponent` a route should use if no notFound component is provided.\n *\n * @default NotFound\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultnotfoundcomponent-property)\n * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors#default-router-wide-not-found-handling)\n */\n defaultNotFoundComponent?: NotFoundRouteComponent\n /**\n * A component that will be used to wrap the entire router.\n *\n * This is useful for providing a context to the entire router.\n *\n * Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.\n *\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#wrap-property)\n */\n Wrap?: (props: { children: any }) => React.JSX.Element\n /**\n * A component that will be used to wrap the inner contents of the router.\n *\n * This is useful for providing a context to the inner contents of the router where you also need access to the router context and hooks.\n *\n * Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.\n *\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#innerwrap-property)\n */\n InnerWrap?: (props: { children: any }) => React.JSX.Element\n\n /**\n * The default `onCatch` handler for errors caught by the Router ErrorBoundary\n *\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultoncatch-property)\n * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionsoncatch)\n */\n defaultOnCatch?: (error: unknown, errorInfo: React.ErrorInfo) => void\n }\n}\n\n/**\n * Creates a new Router instance for React.\n *\n * Pass the returned router to `RouterProvider` to enable routing.\n * Notable options: `routeTree` (your route definitions) and `context`\n * (required if the root route was created with `createRootRouteWithContext`).\n *\n * @param options Router options used to configure the router.\n * @returns A Router instance to be provided to `RouterProvider`.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction\n */\nexport const createRouter: CreateRouterFn = (options) => {\n return new Router(options)\n}\n\nexport class Router<\n in out TRouteTree extends AnyRoute,\n in out TTrailingSlashOption extends TrailingSlashOption = 'never',\n in out TDefaultStructuralSharingOption extends boolean = false,\n in out TRouterHistory extends RouterHistory = RouterHistory,\n in out TDehydrated extends Record<string, any> = Record<string, any>,\n> extends RouterCore<\n TRouteTree,\n TTrailingSlashOption,\n TDefaultStructuralSharingOption,\n TRouterHistory,\n TDehydrated\n> {\n constructor(\n options: RouterConstructorOptions<\n TRouteTree,\n TTrailingSlaLine truncated
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { AnyRouter } from '@tanstack/router-core';
|
||||
import * as React from 'react';
|
||||
export declare const routerContext: React.Context<AnyRouter>;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
"use client";
|
||||
import * as React$1 from "react";
|
||||
//#region src/routerContext.tsx
|
||||
var routerContext = React$1.createContext(null);
|
||||
//#endregion
|
||||
export { routerContext };
|
||||
|
||||
//# sourceMappingURL=routerContext.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"routerContext.js","names":[],"sources":["../../src/routerContext.tsx"],"sourcesContent":["'use client'\n\nimport * as React from 'react'\nimport type { AnyRouter } from '@tanstack/router-core'\n\nexport const routerContext = React.createContext<AnyRouter>(null!)\n"],"mappings":";;;AAKA,IAAa,gBAAgB,QAAM,cAAyB,IAAK"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { Readable } from '@tanstack/react-store';
|
||||
import { GetStoreConfig } from '@tanstack/router-core';
|
||||
declare module '@tanstack/router-core' {
|
||||
interface RouterReadableStore<TValue> extends Readable<TValue> {
|
||||
}
|
||||
}
|
||||
export declare const getStoreFactory: GetStoreConfig;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { createNonReactiveMutableStore, createNonReactiveReadonlyStore } from "@tanstack/router-core";
|
||||
import { isServer } from "@tanstack/router-core/isServer";
|
||||
import { batch, createAtom } from "@tanstack/react-store";
|
||||
//#region src/routerStores.ts
|
||||
var getStoreFactory = (opts) => {
|
||||
if (isServer ?? opts.isServer) return {
|
||||
createMutableStore: createNonReactiveMutableStore,
|
||||
createReadonlyStore: createNonReactiveReadonlyStore,
|
||||
batch: (fn) => fn()
|
||||
};
|
||||
return {
|
||||
createMutableStore: createAtom,
|
||||
createReadonlyStore: createAtom,
|
||||
batch
|
||||
};
|
||||
};
|
||||
//#endregion
|
||||
export { getStoreFactory };
|
||||
|
||||
//# sourceMappingURL=routerStores.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"routerStores.js","names":[],"sources":["../../src/routerStores.ts"],"sourcesContent":["import { batch, createAtom } from '@tanstack/react-store'\nimport {\n createNonReactiveMutableStore,\n createNonReactiveReadonlyStore,\n} from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport type { Readable } from '@tanstack/react-store'\nimport type { GetStoreConfig } from '@tanstack/router-core'\n\ndeclare module '@tanstack/router-core' {\n export interface RouterReadableStore<TValue> extends Readable<TValue> {}\n}\nexport const getStoreFactory: GetStoreConfig = (opts) => {\n if (isServer ?? opts.isServer) {\n return {\n createMutableStore: createNonReactiveMutableStore,\n createReadonlyStore: createNonReactiveReadonlyStore,\n batch: (fn) => fn(),\n }\n }\n return {\n createMutableStore: createAtom,\n createReadonlyStore: createAtom,\n batch: batch,\n }\n}\n"],"mappings":";;;;AAYA,IAAa,mBAAmC,SAAS;CACvD,IAAI,YAAY,KAAK,UACnB,OAAO;EACL,oBAAoB;EACpB,qBAAqB;EACrB,QAAQ,OAAO,GAAG;CACpB;CAEF,OAAO;EACL,oBAAoB;EACpB,qBAAqB;EACd;CACT;AACF"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function ScrollRestoration(): import("react/jsx-runtime").JSX.Element | null;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { useRouter } from "./useRouter.js";
|
||||
import { ScriptOnce } from "./ScriptOnce.js";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
import { getScrollRestorationScriptForRouter } from "@tanstack/router-core/scroll-restoration-script";
|
||||
//#region src/scroll-restoration.tsx
|
||||
function ScrollRestoration() {
|
||||
const script = getScrollRestorationScriptForRouter(useRouter());
|
||||
if (!script) return null;
|
||||
return /* @__PURE__ */ jsx(ScriptOnce, { children: script });
|
||||
}
|
||||
//#endregion
|
||||
export { ScrollRestoration };
|
||||
|
||||
//# sourceMappingURL=scroll-restoration.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"scroll-restoration.js","names":[],"sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import { getScrollRestorationScriptForRouter } from '@tanstack/router-core/scroll-restoration-script'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\n\nexport function ScrollRestoration() {\n const router = useRouter()\n const script = getScrollRestorationScriptForRouter(router)\n\n if (!script) {\n return null\n }\n\n return <ScriptOnce children={script} />\n}\n"],"mappings":";;;;;AAIA,SAAgB,oBAAoB;CAElC,MAAM,SAAS,oCADA,UACoC,CAAM;CAEzD,IAAI,CAAC,QACH,OAAO;CAGT,OAAO,oBAAC,YAAD,EAAY,UAAU,OAAS,CAAA;AACxC"}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { AnyRouter } from '@tanstack/router-core';
|
||||
export declare function RouterClient(props: {
|
||||
router: AnyRouter;
|
||||
}): import("react/jsx-runtime").JSX.Element;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { Await } from "../awaited.js";
|
||||
import { RouterProvider } from "../RouterProvider.js";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
import { hydrate } from "@tanstack/router-core/ssr/client";
|
||||
//#region src/ssr/RouterClient.tsx
|
||||
var hydrationPromise;
|
||||
function RouterClient(props) {
|
||||
hydrationPromise ??= hydrate(props.router).finally(() => window.$_TSR.h());
|
||||
return /* @__PURE__ */ jsx(Await, {
|
||||
promise: hydrationPromise,
|
||||
children: () => /* @__PURE__ */ jsx(RouterProvider, { router: props.router })
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
export { RouterClient };
|
||||
|
||||
//# sourceMappingURL=RouterClient.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"RouterClient.js","names":[],"sources":["../../../src/ssr/RouterClient.tsx"],"sourcesContent":["import { hydrate } from '@tanstack/router-core/ssr/client'\nimport { Await } from '../awaited'\nimport { RouterProvider } from '../RouterProvider'\nimport type { AnyRouter } from '@tanstack/router-core'\n\nlet hydrationPromise: Promise<void> | undefined\n\nexport function RouterClient(props: { router: AnyRouter }) {\n hydrationPromise ??= hydrate(props.router).finally(() => window.$_TSR!.h())\n\n return (\n <Await\n promise={hydrationPromise}\n children={() => <RouterProvider router={props.router} />}\n />\n )\n}\n"],"mappings":";;;;;AAKA,IAAI;AAEJ,SAAgB,aAAa,OAA8B;CACzD,qBAAqB,QAAQ,MAAM,MAAM,EAAE,cAAc,OAAO,MAAO,EAAE,CAAC;CAE1E,OACE,oBAAC,OAAD;EACE,SAAS;EACT,gBAAgB,oBAAC,gBAAD,EAAgB,QAAQ,MAAM,OAAS,CAAA;CACxD,CAAA;AAEL"}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { AnyRouter } from '@tanstack/router-core';
|
||||
export declare function RouterServer<TRouter extends AnyRouter>(props: {
|
||||
router: TRouter;
|
||||
}): import("react/jsx-runtime").JSX.Element;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { RouterProvider } from "../RouterProvider.js";
|
||||
import "react";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
//#region src/ssr/RouterServer.tsx
|
||||
function RouterServer(props) {
|
||||
return /* @__PURE__ */ jsx(RouterProvider, { router: props.router });
|
||||
}
|
||||
//#endregion
|
||||
export { RouterServer };
|
||||
|
||||
//# sourceMappingURL=RouterServer.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"RouterServer.js","names":[],"sources":["../../../src/ssr/RouterServer.tsx"],"sourcesContent":["import * as React from 'react'\nimport { RouterProvider } from '../RouterProvider'\nimport type { AnyRouter } from '@tanstack/router-core'\n\nexport function RouterServer<TRouter extends AnyRouter>(props: {\n router: TRouter\n}) {\n return <RouterProvider router={props.router} />\n}\n"],"mappings":";;;;AAIA,SAAgB,aAAwC,OAErD;CACD,OAAO,oBAAC,gBAAD,EAAgB,QAAQ,MAAM,OAAS,CAAA;AAChD"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export { RouterClient } from './RouterClient.js';
|
||||
export * from '@tanstack/router-core/ssr/client';
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { RouterClient } from "./RouterClient.js";
|
||||
export * from "@tanstack/router-core/ssr/client";
|
||||
export { RouterClient };
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare const defaultRenderHandler: import('@tanstack/router-core/ssr/server').HandlerCallback<import('@tanstack/router-core').AnyRouter>;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { RouterServer } from "./RouterServer.js";
|
||||
import { renderRouterToString } from "./renderRouterToString.js";
|
||||
import { jsx } from "react/jsx-runtime";
|
||||
import { defineHandlerCallback } from "@tanstack/router-core/ssr/server";
|
||||
//#region src/ssr/defaultRenderHandler.tsx
|
||||
var defaultRenderHandler = defineHandlerCallback(({ router, responseHeaders }) => renderRouterToString({
|
||||
router,
|
||||
responseHeaders,
|
||||
children: /* @__PURE__ */ jsx(RouterServer, { router })
|
||||
}));
|
||||
//#endregion
|
||||
export { defaultRenderHandler };
|
||||
|
||||
//# sourceMappingURL=defaultRenderHandler.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"defaultRenderHandler.js","names":[],"sources":["../../../src/ssr/defaultRenderHandler.tsx"],"sourcesContent":["import { defineHandlerCallback } from '@tanstack/router-core/ssr/server'\nimport { renderRouterToString } from './renderRouterToString'\nimport { RouterServer } from './RouterServer'\n\nexport const defaultRenderHandler = defineHandlerCallback(\n ({ router, responseHeaders }) =>\n renderRouterToString({\n router,\n responseHeaders,\n children: <RouterServer router={router} />,\n }),\n)\n"],"mappings":";;;;;AAIA,IAAa,uBAAuB,uBACjC,EAAE,QAAQ,sBACT,qBAAqB;CACnB;CACA;CACA,UAAU,oBAAC,cAAD,EAAsB,OAAS,CAAA;AAC3C,CAAC,CACL"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare const defaultStreamHandler: import('@tanstack/router-core/ssr/server').HandlerCallback<import('@tanstack/router-core').AnyRouter>;
|
||||
Loaded 100 of 4271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user