-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathScripts.tsx
More file actions
80 lines (70 loc) 路 2.06 KB
/
Copy pathScripts.tsx
File metadata and controls
80 lines (70 loc) 路 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { Asset } from './Asset'
import { useRouterState } from './useRouterState'
import { useRouter } from './useRouter'
import type { RouterManagedTag } from '@tanstack/router-core'
/**
* Render body script tags collected from route matches and SSR manifests.
* Should be placed near the end of the document body.
*/
export const Scripts = () => {
const router = useRouter()
const nonce = router.options.ssr?.nonce
const assetScripts = useRouterState({
select: (state) => {
const assetScripts: Array<RouterManagedTag> = []
const manifest = router.ssr?.manifest
if (!manifest) {
return []
}
state.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,
} as any)
}),
)
return assetScripts
},
structuralSharing: true as any,
})
const { scripts } = useRouterState({
select: (state) => ({
scripts: (
state.matches
.map((match) => match.scripts!)
.flat(1)
.filter(Boolean) as Array<RouterManagedTag>
).map(({ children, ...script }) => ({
tag: 'script',
attrs: {
...script,
suppressHydrationWarning: true,
nonce,
},
children,
})),
}),
structuralSharing: true as any,
})
let serverBufferedScript: RouterManagedTag | undefined = undefined
if (router.serverSsr) {
serverBufferedScript = router.serverSsr.takeBufferedScripts()
}
const allScripts = [...scripts, ...assetScripts] as Array<RouterManagedTag>
if (serverBufferedScript) {
allScripts.unshift(serverBufferedScript)
}
return (
<>
{allScripts.map((asset, i) => (
<Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />
))}
</>
)
}