-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathAsset.tsx
More file actions
247 lines (221 loc) · 6.78 KB
/
Asset.tsx
File metadata and controls
247 lines (221 loc) · 6.78 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import * as React from 'react'
import { isServer } from '@tanstack/router-core/isServer'
import { useRouter } from './useRouter'
import { useHydrated } from './ClientOnly'
import type { RouterManagedTag } from '@tanstack/router-core'
interface ScriptAttrs {
[key: string]: string | boolean | undefined
src?: string
suppressHydrationWarning?: boolean
}
export function Asset({
tag,
attrs,
children,
nonce,
}: RouterManagedTag & { nonce?: string }): React.ReactElement | null {
switch (tag) {
case 'title':
return (
<title {...attrs} suppressHydrationWarning>
{children}
</title>
)
case 'meta':
return <meta {...attrs} suppressHydrationWarning />
case 'link':
return <link {...attrs} nonce={nonce} suppressHydrationWarning />
case 'style':
return (
<style
{...attrs}
dangerouslySetInnerHTML={{ __html: children as string }}
nonce={nonce}
/>
)
case 'script':
return <Script attrs={attrs}>{children}</Script>
default:
return null
}
}
function Script({
attrs,
children,
}: {
attrs?: ScriptAttrs
children?: string
}) {
const router = useRouter()
const hydrated = useHydrated()
// Track whether this component instance went through the !hydrated (pre-hydration) phase.
// true → component was SSR-rendered; the inline script was already executed by the browser.
// false → component was mounted fresh on the client (client-side navigation); useEffect must
// inject an executable script because dangerouslySetInnerHTML never executes scripts.
const wentThroughNonHydratedPhase = React.useRef(!hydrated)
const dataScript =
typeof attrs?.type === 'string' &&
attrs.type !== '' &&
attrs.type !== 'text/javascript' &&
attrs.type !== 'module'
if (
process.env.NODE_ENV !== 'production' &&
attrs?.src &&
typeof children === 'string' &&
children.trim().length
) {
console.warn(
'[TanStack Router] <Script> received both `src` and `children`. The `children` content will be ignored. Remove `children` or remove `src`.',
)
}
React.useEffect(() => {
if (dataScript) return
if (attrs?.src) {
const normSrc = (() => {
try {
const base = document.baseURI || window.location.href
return new URL(attrs.src, base).href
} catch {
return attrs.src
}
})()
const existingScript = Array.from(
document.querySelectorAll('script[src]'),
).find((el) => (el as HTMLScriptElement).src === normSrc)
if (existingScript) {
return
}
const script = document.createElement('script')
for (const [key, value] of Object.entries(attrs)) {
if (
key !== 'suppressHydrationWarning' &&
value !== undefined &&
value !== false
) {
script.setAttribute(
key,
typeof value === 'boolean' ? '' : String(value),
)
}
}
document.head.appendChild(script)
return () => {
if (script.parentNode) {
script.parentNode.removeChild(script)
}
}
}
if (typeof children === 'string') {
const typeAttr =
typeof attrs?.type === 'string' ? attrs.type : 'text/javascript'
const nonceAttr =
typeof attrs?.nonce === 'string' ? attrs.nonce : undefined
const existingScript = Array.from(
document.querySelectorAll('script:not([src])'),
).find((el) => {
if (!(el instanceof HTMLScriptElement)) return false
const sType = el.getAttribute('type') ?? 'text/javascript'
const sNonce = el.getAttribute('nonce') ?? undefined
return (
el.textContent === children &&
sType === typeAttr &&
sNonce === nonceAttr
)
})
if (existingScript) {
return
}
const script = document.createElement('script')
script.textContent = children
if (attrs) {
for (const [key, value] of Object.entries(attrs)) {
if (
key !== 'suppressHydrationWarning' &&
value !== undefined &&
value !== false
) {
script.setAttribute(
key,
typeof value === 'boolean' ? '' : String(value),
)
}
}
}
document.head.appendChild(script)
return () => {
if (script.parentNode) {
script.parentNode.removeChild(script)
}
}
}
return undefined
}, [attrs, children, dataScript])
// --- Server rendering ---
if (isServer ?? router.isServer) {
if (attrs?.src) {
return <script {...attrs} suppressHydrationWarning />
}
if (typeof children === 'string') {
return (
<script
{...attrs}
dangerouslySetInnerHTML={{ __html: children }}
suppressHydrationWarning
/>
)
}
return null
}
// --- Client rendering ---
// Data scripts (e.g. application/ld+json) are rendered in the tree;
// the useEffect intentionally skips them.
if (dataScript && typeof children === 'string') {
return (
<script
{...attrs}
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: children }}
/>
)
}
// During hydration (before useEffect has fired), render the script element
// to match the server-rendered HTML and avoid structural hydration mismatches.
// After hydration, return null — the useEffect handles imperative injection.
if (!hydrated) {
if (attrs?.src) {
return <script {...attrs} suppressHydrationWarning />
}
if (typeof children === 'string') {
return (
<script
{...attrs}
dangerouslySetInnerHTML={{ __html: children }}
suppressHydrationWarning
/>
)
}
}
// For inline scripts (children, no src) that went through SSR hydration, keep the element
// in the React tree so React doesn't unmount the SSR-rendered script from the DOM.
// The useEffect above detects the existing element via textContent match and skips
// re-injection, so the script won't execute a second time.
//
// For client-side navigation (wentThroughNonHydratedPhase === false), skip this path and
// fall through to return null — the useEffect handles imperative injection in that case.
// (dangerouslySetInnerHTML does not execute scripts, so we must not render an inert element
// that would fool the existingScript dedup check into returning early without executing.)
if (
!attrs?.src &&
typeof children === 'string' &&
wentThroughNonHydratedPhase.current
) {
return (
<script
{...attrs}
dangerouslySetInnerHTML={{ __html: children }}
suppressHydrationWarning
/>
)
}
return null
}