Open History to see the last commit
1import * as Solid from 'solid-js'
2import { Dynamic } from 'solid-js/web'
3β
4import { useHydrated } from '@tanstack/solid-router'
5import { isServer } from '@tanstack/router-core/isServer'
6import {
7 hydrateIdAttribute,
8 hydrateWhenAttribute,
9} from '@tanstack/start-client-core/hydration/constants'
10import {
11 createResolvedGate,
12 getFallbackHtml,
13 getOrCreateGate,
14 onGateResolve,
15 releaseGate,
16 runHydrationStrategyCleanup,
17 saveFallbackHtml,
18 waitForHydrationPrefetchStrategy,
19} from '@tanstack/start-client-core/hydration/runtime'
20import { listenForDelegatedHydrationIntent } from '@tanstack/start-client-core/hydration'
21import type {
22 HydrationRuntimeContext,
23 HydrationStrategy,
24 HydrationWhen,
25} from '@tanstack/start-client-core/hydration'
26import type { HydrationGateRecord } from '@tanstack/start-client-core/hydration/runtime'
27import type { InternalHydrateProps } from './Hydrate'
28import type { DynamicProps } from 'solid-js/web'
29β
30type HydrationFallbackDynamicProps = DynamicProps<'div'>
31type HydrationMarkerDynamicProps = DynamicProps<'div'> & {
32 [hydrateIdAttribute]: string
33 [hydrateWhenAttribute]: HydrationWhen
34 [key: `data-${string}`]: string | undefined
35}
36type PrefetchController = {
37 abort: AbortController
38 requested: boolean
39 listeners: Set<() => void>
40 resolvePending: boolean
41 started: boolean
42 promise?: Promise<void>
43}
44β
45const dynamicType = 'dynamic'
46const dynamicHydrateStrategy = {
47 _t: dynamicType,
48 _d: () => true,
49} satisfies HydrationStrategy<typeof dynamicType, false>
50β
51function shouldDeferHydration(strategy: HydrationStrategy) {
52 return strategy._d ? strategy._d() : strategy._t !== 'load'
53}
54β
55/* @__NO_SIDE_EFFECTS__ */
56function HydratedBoundary(props: {
57 id: string
58 onHydrated?: () => void
59 onStrategyHydrated?: (id: string) => void
60 children: Solid.JSX.Element
61}) {
62 let didHydrate = false
63β
64 Solid.onMount(() => {
65 if (didHydrate) return
66 didHydrate = true
67 props.onHydrated?.()
68 props.onStrategyHydrated?.(props.id)
69 })
70β
71 return props.children
72}
73β
74/* @__NO_SIDE_EFFECTS__ */
75export function GenericHydrate(props: InternalHydrateProps) {
76 const when = props.when
77 const dynamicHydrate = typeof when === 'function'
78 const initialHydrateStrategy: HydrationStrategy = dynamicHydrate
79 ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
80 (isServer ?? typeof window === 'undefined')
81 ? dynamicHydrateStrategy
82 : when()
83 : when
84 const markerHydrateType: HydrationWhen = dynamicHydrate
85 ? dynamicType
86 : initialHydrateStrategy._t!
87 const prefetchStrategy = () => props.prefetch
88 const hydrated = useHydrated()
89 const uniqueId = Solid.createUniqueId()
90 const id = props.h ? `${props.h}${uniqueId}` : uniqueId
91 const initialHydrateType = initialHydrateStrategy._t!
92 const shouldPreserveServerHTML =
93 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
94 (isServer ?? typeof window === 'undefined') || !hydrated()
95 const shouldDeferInitialHydration =
96 !hydrated() && shouldDeferHydration(initialHydrateStrategy)
97 const gate: HydrationGateRecord =
98 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
99 (isServer ?? typeof window === 'undefined')
100 ? createResolvedGate(id, initialHydrateType)
101 : getOrCreateGate(id, initialHydrateType)
102 const [ready, setReady] = Solid.createSignal(
103 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
104 (isServer ?? typeof window === 'undefined') ||
105 (!shouldDeferInitialHydration && initialHydrateType !== 'never'),
106 )
107 const [prefetchError, setPrefetchError] = Solid.createSignal<unknown>()
108 const controller: PrefetchController = {
109 abort: new AbortController(),
110 requested: false,
111 listeners: new Set<() => void>(),
112 resolvePending: false,
113 started: false,
114 }
115 let didPrefetch = false
116 let markerElement: HTMLDivElement | undefined
117β
118 if (
119 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
120 !(isServer ?? typeof window === 'undefined') &&
121 initialHydrateType !== 'never' &&
122 (!shouldDeferInitialHydration ||
123 !shouldDeferHydration(initialHydrateStrategy))
124 ) {
125 gate.resolve()
126 }
127β
128 const onHydrate = (listener: () => void) => {
129 if (controller.requested) {
130 listener()
131 return () => {}
132 }
133β
134 controller.listeners.add(listener)
135 return () => {
136 controller.listeners.delete(listener)
137 }
138 }
139β
140 const requestHydration = () => {
141 if (!controller.requested) {
142 controller.requested = true
143 controller.listeners.forEach((listener) => listener())
144 controller.listeners.clear()
145 }
146β
147 if (!controller.promise) {
148 resolveGate()
149 return
150 }
151 if (controller.resolvePending) {
152 return
153 }
154 controller.resolvePending = true
155β
156 controller.promise.then(
157 () => resolveGate(),
158 (error) => {
159 if (!controller.abort.signal.aborted) {
160 setPrefetchError(() => error)
161 }
162 },
163 )
164 }
165 const resolveGate = gate.resolve
166β
167 Solid.onMount(() => {
168 const currentHydrateStrategy = initialHydrateStrategy
169 const currentPrefetchStrategy = prefetchStrategy()
170 const currentHydrateType = currentHydrateStrategy._t!
171 gate.when = currentHydrateType
172 if (markerElement) {
173 saveFallbackHtml(id, markerElement)
174 }
175β
176 if (
177 currentHydrateType === 'never' &&
178 !shouldPreserveServerHTML &&
179 markerElement
180 ) {
181 markerElement.replaceChildren()
182 }
183β
184 if (currentPrefetchStrategy && !controller.started) {
185 controller.started = true
186 const preload = () => props.p?.() ?? Promise.resolve()
187β
188 if (typeof currentPrefetchStrategy === 'function') {
189 const promise = Promise.resolve()
190 .then(() =>
191 currentPrefetchStrategy({
192 element: markerElement ?? null,
193 signal: controller.abort.signal,
194 preload,
195 waitFor: (strategy) =>
196 waitForHydrationPrefetchStrategy(strategy, {
197 element: markerElement ?? null,
198 signal: controller.abort.signal,
199 onHydrate,
200 }),
201 }),
202 )
203 .then(() => undefined)
204β
205 controller.promise = promise
206 promise.catch((error) => {
207 if (!controller.abort.signal.aborted) {
208 setPrefetchError(() => error)
209 }
210 })
211 } else if (props.p) {
212 const currentStrategy = currentPrefetchStrategy
213 const prefetch = () => {
214 if (didPrefetch) return
215 didPrefetch = true
216 void preload()
217 }
218 const cleanupPrefetch = runHydrationStrategyCleanup(
219 currentStrategy._s?.({
220 element: markerElement ?? null,
221 prefetch,
222 }),
223 )
224 if (cleanupPrefetch) Solid.onCleanup(cleanupPrefetch)
225 }
226 }
227β
228 if (
229 currentHydrateType !== 'never' &&
230 (!shouldDeferInitialHydration ||
231 !shouldDeferHydration(currentHydrateStrategy))
232 ) {
233 gate.resolve()
234 setReady(true)
235 }
236β
237 const cleanups: Array<() => void> = []
238 let removeResolveListener = () => {}
239 let disposed = false
240β
241 const resolveBoundary = () => {
242 setReady(true)
243 }
244β
245 const cleanup = () => {
246 if (disposed) return
247 disposed = true
248 if (gate.resolve === requestHydration) {
249 gate.resolve = resolveGate
250 }
251 removeResolveListener()
252 cleanups.forEach((fn) => fn())
253 }
254β
255 const addCleanup = (fn: void | (() => void)) => {
256 if (!fn) return
257 if (disposed || gate.resolved) {
258 fn()
259 return
260 }
261 cleanups.push(fn)
262 }
263β
264 Solid.onCleanup(() => {
265 controller.abort.abort()
266 controller.listeners.clear()
267 cleanup()
268 releaseGate(gate)
269 })
270β
271 removeResolveListener = onGateResolve(gate, () => {
272 cleanup()
273 resolveBoundary()
274 })
275β
276 if (
277 gate.resolved ||
278 !shouldDeferInitialHydration ||
279 currentHydrateType === 'never'
280 ) {
281 if (gate.resolved) resolveBoundary()
282 return
283 }
284β
285 gate.resolve = requestHydration
286 const context: HydrationRuntimeContext = {
287 element: markerElement ?? null,
288 gate,
289 }
290 addCleanup(
291 runHydrationStrategyCleanup(currentHydrateStrategy._s?.(context)),
292 )
293β
294 if (currentHydrateStrategy._t !== 'interaction') {
295 addCleanup(
296 runHydrationStrategyCleanup(
297 markerElement
298 ? listenForDelegatedHydrationIntent(markerElement, context)
299 : undefined,
300 ),
301 )
302 }
303 })
304β
305 Solid.createRenderEffect(() => {
306 if (
307 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
308 (isServer ?? typeof window === 'undefined') ||
309 gate.resolved ||
310 initialHydrateStrategy._t === 'never' ||
311 shouldDeferHydration(initialHydrateStrategy)
312 ) {
313 return
314 }
315β
316 gate.resolve()
317 })
318β
319 const markerAttributes =
320 markerHydrateType === dynamicType
321 ? undefined
322 : initialHydrateStrategy._a?.()
323 const markerProps: HydrationMarkerDynamicProps = {
324 component: 'div',
325 ref: (element) => {
326 markerElement = element
327 },
328 [hydrateIdAttribute]: id,
329 [hydrateWhenAttribute]: markerHydrateType,
330 ...markerAttributes,
331 }
332 const fallback = () => {
333 if (!shouldPreserveServerHTML) return props.fallback ?? null
334β
335 const html = getFallbackHtml(id)
336 if (!html) return null
337β
338 const fallbackProps: HydrationFallbackDynamicProps = {
339 component: 'div',
340 style: { display: 'contents' },
341 innerHTML: html,
342 }
343β
344 return <Dynamic {...fallbackProps} />
345 }
346β
347 return (
348 <Dynamic {...markerProps}>
349 {(() => {
350 const error = prefetchError()
351 if (error) throw error
352 return null
353 })()}
354 {initialHydrateType === 'never' && !shouldPreserveServerHTML ? (
355 (props.fallback ?? null)
356 ) : (
357 <Solid.Suspense fallback={fallback()}>
358 <Solid.Show when={ready()} fallback={fallback()}>
359 <HydratedBoundary
360 id={id}
361 onHydrated={props.onHydrated}
362 onStrategyHydrated={(id) => {
363 markerElement?.removeAttribute(hydrateWhenAttribute)
364 initialHydrateStrategy._o?.(id)
365 }}
366 >
367 {props.children}
368 </HydratedBoundary>
369 </Solid.Show>
370 </Solid.Suspense>
371 )}
372 </Dynamic>
373 )
374}