Open History to see the last commit
1import * as Vue from 'vue'
2import {
3 composeSsrBodyScripts,
4 getSsrBodyScriptParts,
5} from '@tanstack/router-core'
6import { isServer } from '@tanstack/router-core/isServer'
7import { useSelector } from '@tanstack/vue-store'
8import { Asset } from './Asset'
9import { useRouter } from './useRouter'
10import type { RouterManagedTag } from '@tanstack/router-core'
11β
12/**
13 * During streaming SSR, `<Scripts>` marks where late hydration scripts may
14 * begin to be inserted.
15 */
16export const Scripts = Vue.defineComponent({
17 name: 'Scripts',
18 setup() {
19 const router = useRouter()
20 const nonce = router.options.ssr?.nonce
21 const matches = useSelector(router.stores.matches, (value) => value)
22β
23 const scripts = Vue.computed(() =>
24 getSsrBodyScriptParts(matches.value, router.ssr?.manifest, nonce),
25 )
26β
27 const mounted = Vue.ref(false)
28 Vue.onMounted(() => {
29 mounted.value = true
30 })
31β
32 return () => {
33 return renderScripts(router, scripts.value, mounted.value, nonce)
34 }
35 },
36})
37β
38function renderScripts(
39 router: ReturnType<typeof useRouter>,
40 scriptParts: ReturnType<typeof getSsrBodyScriptParts>,
41 mounted: boolean,
42 nonce?: string,
43) {
44 const allScripts: Array<RouterManagedTag> = []
45 let streamBoundary: RouterManagedTag | undefined
46 const [scripts, assetScripts] = scriptParts
47β
48 if ((isServer ?? router.isServer) && router.serverSsr) {
49 const initialHydrationScripts =
50 router.serverSsr.takeInitialHydrationScriptTags()
51 allScripts.push(
52 ...composeSsrBodyScripts(scriptParts, initialHydrationScripts),
53 )
54 return renderScriptTags(allScripts)
55 } else if (router.ssr && !mounted) {
56 allScripts.push({
57 tag: 'script',
58 attrs: { nonce, 'data-allow-mismatch': true },
59 children: '',
60 } satisfies RouterManagedTag)
61β
62 streamBoundary = {
63 tag: 'script',
64 attrs: {
65 nonce,
66 'data-allow-mismatch': true,
67 },
68 children: '',
69 } satisfies RouterManagedTag
70β
71 for (const asset of assetScripts) {
72 allScripts.push({
73 tag: 'script',
74 attrs: {
75 ...asset.attrs,
76 'data-allow-mismatch': true,
77 },
78 children: '',
79 } satisfies RouterManagedTag)
80 }
81 }
82β
83 allScripts.push(...scripts)
84β
85 if (mounted) {
86 allScripts.push(...assetScripts)
87 }
88β
89 if (streamBoundary) {
90 allScripts.push(streamBoundary)
91 }
92β
93 return renderScriptTags(allScripts)
94}
95β
96function renderScriptTags(allScripts: Array<RouterManagedTag>) {
97 return (
98 <>
99 {allScripts.map((asset, i) => (
100 <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} />
101 ))}
102 </>
103 )
104}