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

Asset.tsx

181 lines4.6 KB

1import { Link, Meta, Style, Title } from '@solidjs/meta'
2import { onCleanup, onMount } from 'solid-js'
3import { isServer } from '@tanstack/router-core/isServer'
4import { useRouter } from './useRouter'
5import type { RouterManagedTag } from '@tanstack/router-core'
6import type { JSX } from 'solid-js'
7​
8const INLINE_CSS_HYDRATION_ATTR = 'data-tsr-inline-css'
9​
10export function Asset(asset: RouterManagedTag): JSX.Element | null {
11 const { tag, attrs, children } = asset
12​
13 switch (tag) {
14 case 'title':
15 return <Title {...attrs}>{children}</Title>
16 case 'meta':
17 return <Meta {...attrs} />
18 case 'link':
19 return <Link {...attrs} />
20 case 'style':
21 if (
22 asset.inlineCss &&
23 (process.env.TSS_INLINE_CSS_ENABLED === 'true' ||
24 (process.env.TSS_INLINE_CSS_ENABLED === undefined && isServer))
25 ) {
26 return <InlineCssStyle attrs={attrs}>{children}</InlineCssStyle>
27 }
28​
29 return <Style {...attrs}>{children}</Style>
30 case 'script':
31 return <Script attrs={attrs}>{children}</Script>
32 default:
33 return null
34 }
36​
37function InlineCssStyle({
38 attrs,
39 children,
40}: {
41 attrs?: Record<string, any>
42 children?: RouterManagedTag['children']
43}) {
44 const isInlineCssPlaceholder = children === undefined
45 const html = isInlineCssPlaceholder
46 ? typeof document === 'undefined'
47 ? ''
48 : (document.querySelector<HTMLStyleElement>(
49 `style[${INLINE_CSS_HYDRATION_ATTR}]`,
50 )?.textContent ?? '')
51 : (children ?? '')
52​
53 return (
54 <Style {...attrs} {...{ [INLINE_CSS_HYDRATION_ATTR]: '' }}>
55 {html}
56 </Style>
57 )
59​
60interface ScriptAttrs {
61 [key: string]: string | boolean | undefined
62 src?: string
64​
65function Script({
66 attrs,
67 children,
68}: {
69 attrs?: ScriptAttrs
70 children?: string
71}): JSX.Element | null {
72 const router = useRouter()
73 const dataScript =
74 typeof attrs?.type === 'string' &&
75 attrs.type !== '' &&
76 attrs.type !== 'text/javascript' &&
77 attrs.type !== 'module'
78​
79 onMount(() => {
80 if (dataScript) return
81​
82 if (attrs?.src) {
83 const normSrc = (() => {
84 try {
85 const base = document.baseURI || window.location.href
86 return new URL(attrs.src, base).href
87 } catch {
88 return attrs.src
89 }
90 })()
91 const existingScript = Array.from(
92 document.querySelectorAll('script[src]'),
93 ).find((el) => (el as HTMLScriptElement).src === normSrc)
94​
95 if (existingScript) {
96 return
97 }
98​
99 const script = document.createElement('script')
100​
101 for (const [key, value] of Object.entries(attrs)) {
102 if (value !== undefined && value !== false) {
103 script.setAttribute(
104 key,
105 typeof value === 'boolean' ? '' : String(value),
106 )
107 }
108 }
109​
110 document.head.appendChild(script)
111​
112 onCleanup(() => {
113 if (script.parentNode) {
114 script.parentNode.removeChild(script)
115 }
116 })
117 } else if (typeof children === 'string') {
118 const typeAttr =
119 typeof attrs?.type === 'string' ? attrs.type : 'text/javascript'
120 const nonceAttr =
121 typeof attrs?.nonce === 'string' ? attrs.nonce : undefined
122 const existingScript = Array.from(
123 document.querySelectorAll('script:not([src])'),
124 ).find((el) => {
125 if (!(el instanceof HTMLScriptElement)) return false
126 const sType = el.getAttribute('type') ?? 'text/javascript'
127 const sNonce = el.getAttribute('nonce') ?? undefined
128 return (
129 el.textContent === children &&
130 sType === typeAttr &&
131 sNonce === nonceAttr
132 )
133 })
134​
135 if (existingScript) {
136 return
137 }
138​
139 const script = document.createElement('script')
140 script.textContent = children
141​
142 if (attrs) {
143 for (const [key, value] of Object.entries(attrs)) {
144 if (value !== undefined && value !== false) {
145 script.setAttribute(
146 key,
147 typeof value === 'boolean' ? '' : String(value),
148 )
149 }
150 }
151 }
152​
153 document.head.appendChild(script)
154​
155 onCleanup(() => {
156 if (script.parentNode) {
157 script.parentNode.removeChild(script)
158 }
159 })
160 }
161 })
162​
163 if (!(isServer ?? router.isServer)) {
164 if (dataScript && typeof children === 'string') {
165 return <script {...attrs} innerHTML={children} />
166 }
167​
168 // render an empty script on the client just to avoid hydration errors
169 return null
170 }
171​
172 if (attrs?.src && typeof attrs.src === 'string') {
173 return <script {...attrs} />
174 }
175​
176 if (typeof children === 'string') {
177 return <script {...attrs} innerHTML={children} />
178 }
179​
180 return null