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

Scripts.tsx

65 lines1.6 KB

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​
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,
27 children: asset.children,
28 } as any)
29 }),
30 )
31​
32 return assetScripts
33 },
34 structuralSharing: true as any,
35 })
36​
37 const { scripts } = useRouterState({
38 select: (state) => ({
39 scripts: (
40 state.matches
41 .map((match) => match.scripts!)
42 .flat(1)
43 .filter(Boolean) as Array<RouterManagedTag>
44 ).map(({ children, ...script }) => ({
45 tag: 'script',
46 attrs: {
47 ...script,
48 suppressHydrationWarning: true,
49 },
50 children,
51 })),
52 }),
53 structuralSharing: true as any,
54 })
55​
56 const allScripts = [...scripts, ...assetScripts] as Array<RouterManagedTag>
57​
58 return (
59 <>
60 {allScripts.map((asset, i) => (
61 <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />
62 ))}
63 </>
64 )