UNPKG

@tanstack/react-router

Version:

Modern and scalable routing for React applications

61 lines (60 loc) 2.28 kB
import { useRouter } from "./useRouter.js"; import { Asset } from "./Asset.js"; import { deepEqual } from "@tanstack/router-core"; import { createElement } from "react"; import { Fragment, jsx } from "react/jsx-runtime"; import { useStore } from "@tanstack/react-store"; import { isServer } from "@tanstack/router-core/isServer"; //#region src/Scripts.tsx /** * Render body script tags collected from route matches and SSR manifests. * Should be placed near the end of the document body. */ var Scripts = () => { const router = useRouter(); const nonce = router.options.ssr?.nonce; const getAssetScripts = (matches) => { const assetScripts = []; const manifest = router.ssr?.manifest; if (!manifest) return []; matches.map((match) => router.looseRoutesById[match.routeId]).forEach((route) => manifest.routes[route.id]?.assets?.filter((d) => d.tag === "script").forEach((asset) => { assetScripts.push({ tag: "script", attrs: { ...asset.attrs, nonce }, children: asset.children }); })); return assetScripts; }; const getScripts = (matches) => matches.map((match) => match.scripts).flat(1).filter(Boolean).map(({ children, ...script }) => ({ tag: "script", attrs: { ...script, suppressHydrationWarning: true, nonce }, children })); if (isServer ?? router.isServer) { const assetScripts = getAssetScripts(router.stores.activeMatchesSnapshot.state); return renderScripts(router, getScripts(router.stores.activeMatchesSnapshot.state), assetScripts); } const assetScripts = useStore(router.stores.activeMatchesSnapshot, getAssetScripts, deepEqual); return renderScripts(router, useStore(router.stores.activeMatchesSnapshot, getScripts, deepEqual), assetScripts); }; function renderScripts(router, scripts, assetScripts) { let serverBufferedScript = void 0; if (router.serverSsr) serverBufferedScript = router.serverSsr.takeBufferedScripts(); const allScripts = [...scripts, ...assetScripts]; if (serverBufferedScript) allScripts.unshift(serverBufferedScript); return /* @__PURE__ */ jsx(Fragment, { children: allScripts.map((asset, i) => /* @__PURE__ */ createElement(Asset, { ...asset, key: `tsr-scripts-${asset.tag}-${i}` })) }); } //#endregion export { Scripts }; //# sourceMappingURL=Scripts.js.map