Open History to see the last commit
1import { Asset } from './Asset'
2import { useRouterState } from './useRouterState'
3import { useRouter } from './useRouter'
4import type { RouterManagedTag } from '@tanstack/router-core'
5β
6/**
7 * Render body script tags collected from route matches and SSR manifests.
8 * Should be placed near the end of the document body.
9 */
10/**
11 * Render body script tags collected from route matches and SSR manifests.
12 * Should be placed near the end of the document body.
13 */
14export const Scripts = () => {
15 const router = useRouter()
16 const nonce = router.options.ssr?.nonce
17 const assetScripts = useRouterState({
18 select: (state) => {
19 const assetScripts: Array<RouterManagedTag> = []
20 const manifest = router.ssr?.manifest
21β
22 if (!manifest) {
23 return []
24 }
25β
26 state.matches
27 .map((match) => router.looseRoutesById[match.routeId]!)
28 .forEach((route) =>
29 manifest.routes[route.id]?.assets
30 ?.filter((d) => d.tag === 'script')
31 .forEach((asset) => {
32 assetScripts.push({
33 tag: 'script',
34 attrs: { ...asset.attrs, nonce },
35 children: asset.children,
36 } as any)
37 }),
38 )
39β
40 return assetScripts
41 },
42 structuralSharing: true as any,
43 })
44β
45 const { scripts } = useRouterState({
46 select: (state) => ({
47 scripts: (
48 state.matches
49 .map((match) => match.scripts!)
50 .flat(1)
51 .filter(Boolean) as Array<RouterManagedTag>
52 ).map(({ children, ...script }) => ({
53 tag: 'script',
54 attrs: {
55 ...script,
56 suppressHydrationWarning: true,
57 nonce,
58 },
59 children,
60 })),
61 }),
62 structuralSharing: true as any,
63 })
64β
65 const allScripts = [...scripts, ...assetScripts] as Array<RouterManagedTag>
66β
67 return (
68 <>
69 {allScripts.map((asset, i) => (
70 <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />
71 ))}
72 </>
73 )
74}