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β
6export const Scripts = () => {
7 const router = useRouter()
8 const nonce = router.options.ssr?.nonce
9 const assetScripts = useRouterState({
10 select: (state) => {
11 const assetScripts: Array<RouterManagedTag> = []
12 const manifest = router.ssr?.manifest
13β
14 if (!manifest) {
15 return []
16 }
17β
18 state.matches
19 .map((match) => router.looseRoutesById[match.routeId]!)
20 .forEach((route) =>
21 manifest.routes[route.id]?.assets
22 ?.filter((d) => d.tag === 'script')
23 .forEach((asset) => {
24 assetScripts.push({
25 tag: 'script',
26 attrs: { ...asset.attrs, nonce },
27 children: asset.children,
28 } as any)
29 }),
30 )
31β
32 return assetScripts
33 },
34 })
35β
36 const scripts = useRouterState({
37 select: (state) => ({
38 scripts: (
39 state.matches
40 .map((match) => match.scripts!)
41 .flat(1)
42 .filter(Boolean) as Array<RouterManagedTag>
43 ).map(({ children, ...script }) => ({
44 tag: 'script',
45 attrs: {
46 ...script,
47 nonce,
48 },
49 children,
50 })),
51 }),
52 })
53β
54 let serverBufferedScript: RouterManagedTag | undefined = undefined
55β
56 if (router.serverSsr) {
57 serverBufferedScript = router.serverSsr.takeBufferedScripts()
58 }
59β
60 const allScripts = [
61 ...scripts().scripts,
62 ...assetScripts(),
63 ] as Array<RouterManagedTag>
64β
65 if (serverBufferedScript) {
66 allScripts.unshift(serverBufferedScript)
67 }
68β
69 return (
70 <>
71 {allScripts.map((asset, i) => (
72 <Asset {...asset} />
73 ))}
74 </>
75 )
76}