Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

Scripts.tsx

73 lines1.9 KB

1import { useSelector } from '@tanstack/react-store'
2import {
3 composeSsrBodyScripts,
4 deepEqual,
5 getSsrBodyScriptParts,
6} from '@tanstack/router-core'
7import { isServer } from '@tanstack/router-core/isServer'
8import { Asset } from './Asset'
9import { useRouter } from './useRouter'
10import type { RouterManagedTag } from '@tanstack/router-core'
11​
12type ScriptRenderAsset = RouterManagedTag & {
13 preventScriptHoist?: boolean
15​
16const routeScriptAttrs = { suppressHydrationWarning: true }
17​
18/**
19 * Render body script tags collected from route matches and SSR manifests.
20 * During streaming SSR, `<Scripts>` marks where late hydration scripts may
21 * begin to be inserted.
22 */
23export const Scripts = () => {
24 const router = useRouter()
25 const nonce = router.options.ssr?.nonce
26​
27 const getParts = (matches: Array<any>) => {
28 const parts = getSsrBodyScriptParts(
29 matches,
30 router.ssr?.manifest,
31 nonce,
32 routeScriptAttrs,
33 )
34 for (const script of parts[1]) {
35 if (typeof script.attrs?.src === 'string') {
36 const scriptWithHoist = script as ScriptRenderAsset
37 scriptWithHoist.preventScriptHoist = true
38 }
39 }
40 return parts
41 }
42​
43 const getScripts = (matches: Array<any>) => {
44 return composeSsrBodyScripts(getParts(matches))
45 }
46​
47 if (isServer ?? router.isServer) {
48 const activeMatches = router.stores.matches.get()
49 return renderScripts(
50 composeSsrBodyScripts(
51 getParts(activeMatches),
52 router.serverSsr?.takeInitialHydrationScriptTags(),
53 ),
54 )
55 }
56​
57 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
58 const scripts = useSelector(router.stores.matches, getScripts, {
59 compare: deepEqual,
60 })
61​
62 return renderScripts(scripts)
64​
65function renderScripts(scripts: Array<ScriptRenderAsset>) {
66 return (
67 <>
68 {scripts.map((asset, i) => (
69 <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />
70 ))}
71 </>
72 )