UNPKG

@tanstack/react-router

Version:

Modern and scalable routing for React applications

66 lines (65 loc) 2.31 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 []; for (const match of matches) { const scripts = manifest.routes[match.routeId]?.scripts; if (!scripts) continue; for (const asset of scripts) assetScripts.push({ tag: "script", attrs: { ...asset.attrs, nonce }, children: asset.children, ...typeof asset.attrs?.src === "string" ? { preventScriptHoist: true } : {} }); } 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 activeMatches = router.stores.matches.get(); const assetScripts = getAssetScripts(activeMatches); return renderScripts(router, getScripts(activeMatches), assetScripts); } const assetScripts = useStore(router.stores.matches, getAssetScripts, deepEqual); return renderScripts(router, useStore(router.stores.matches, getScripts, deepEqual), assetScripts); }; function renderScripts(router, scripts, assetScripts) { const allScripts = [...scripts, ...assetScripts]; if ((isServer ?? router.isServer) && router.serverSsr) { const serverBufferedScript = router.serverSsr.takeBufferedScripts(); 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