Open History to see the last commit
1'use client'
2β
3import * as React from 'react'
4β
5import { reactUse, useHydrated, useLayoutEffect } from '@tanstack/react-router'
6import { isServer } from '@tanstack/router-core/isServer'
7import {
8 hydrateIdAttribute,
9 hydrateWhenAttribute,
10} from '@tanstack/start-client-core/hydration/constants'
11import {
12 createResolvedGate,
13 getFallbackHtml,
14 getOrCreateGate,
15 onGateResolve,
16 releaseGate,
17 runHydrationStrategyCleanup,
18 saveFallbackHtml,
19 waitForHydrationPrefetchStrategy,
20} from '@tanstack/start-client-core/hydration/runtime'
21import { listenForDelegatedHydrationIntent } from '@tanstack/start-client-core/hydration'
22import type {
23 HydrationRuntimeContext,
24 HydrationStrategy,
25 HydrationWhen,
26} from '@tanstack/start-client-core/hydration'
27import type { HydrationGateRecord } from '@tanstack/start-client-core/hydration/runtime'
28import type { HydrateProps, InternalHydrateProps } from './Hydrate'
29β
30type Gate = HydrationGateRecord & { promise: Promise<void> }
31type PrefetchController = {
32 abortController: AbortController
33 hydrationRequested: boolean
34 hydrationListeners: Set<() => void>
35 hydrationResolvePending: boolean
36 started: boolean
37 promise?: Promise<void>
38 cleanup?: () => void
39}
40β
41const dynamicType = 'dynamic'
42const dynamicHydrateStrategy = {
43 _t: dynamicType,
44 _d: () => true,
45} satisfies HydrationStrategy<typeof dynamicType, false>
46β
47function shouldDeferHydration(strategy: HydrationStrategy) {
48 return strategy._d ? strategy._d() : strategy._t !== 'load'
49}
50β
51function useLatest<T>(value: T) {
52 const ref = React.useRef(value)
53 ref.current = value
54 return ref
55}
56β
57function useHydrationGate(props: InternalHydrateProps) {
58 const hydrated = useHydrated()
59 const reactId = React.useId()
60 const id = props.h ? `${props.h}${reactId}` : reactId
61 const when = props.when
62 const isDynamicHydrate = typeof when === 'function'
63 const dynamicHydrateStrategyRef = React.useRef<HydrationStrategy | undefined>(
64 undefined,
65 )
66 if (isDynamicHydrate) {
67 dynamicHydrateStrategyRef.current ??=
68 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
69 (isServer ?? typeof window === 'undefined')
70 ? dynamicHydrateStrategy
71 : when()
72 }
73 const hydrateStrategy = isDynamicHydrate
74 ? dynamicHydrateStrategyRef.current!
75 : when
76 const markerHydrateType: HydrationWhen = isDynamicHydrate
77 ? dynamicType
78 : hydrateStrategy._t!
79 const [prefetchError, setPrefetchError] = React.useState<unknown>()
80 const latestRef = useLatest({
81 prefetch: props.prefetch,
82 preload: props.p,
83 })
84 const gateRef = React.useRef<HydrationGateRecord | undefined>(undefined)
85 const markerElementRef = React.useRef<HTMLDivElement | null>(null)
86 const shouldPreserveServerHTMLRef = React.useRef<boolean | undefined>(
87 undefined,
88 )
89 const shouldDeferInitialHydrationRef = React.useRef<boolean | undefined>(
90 undefined,
91 )
92 const didPrefetchRef = React.useRef(false)
93 const prefetchControllerRef = React.useRef<PrefetchController | undefined>(
94 undefined,
95 )
96β
97 prefetchControllerRef.current ??= {
98 abortController: new AbortController(),
99 hydrationRequested: false,
100 hydrationListeners: new Set<() => void>(),
101 hydrationResolvePending: false,
102 started: false,
103 }
104β
105 shouldPreserveServerHTMLRef.current ??=
106 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
107 (isServer ?? typeof window === 'undefined') || !hydrated
108 shouldDeferInitialHydrationRef.current ??=
109 !hydrated && shouldDeferHydration(hydrateStrategy)
110β
111 if (!gateRef.current) {
112 gateRef.current =
113 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
114 (isServer ?? typeof window === 'undefined')
115 ? createResolvedGate(id, hydrateStrategy._t!)
116 : getOrCreateGate(id, hydrateStrategy._t!)
117 }
118β
119 gateRef.current.when = hydrateStrategy._t!
120β
121 if (
122 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
123 !(isServer ?? typeof window === 'undefined') &&
124 hydrateStrategy._t !== 'never' &&
125 (!shouldDeferInitialHydrationRef.current ||
126 !shouldDeferHydration(hydrateStrategy))
127 ) {
128 gateRef.current.resolve()
129 }
130β
131 const markerRef = React.useCallback(
132 (element: HTMLDivElement | null) => {
133 markerElementRef.current = element
134 if (element) {
135 if (
136 hydrateStrategy._t === 'never' &&
137 !shouldPreserveServerHTMLRef.current
138 ) {
139 element.replaceChildren()
140 }
141 saveFallbackHtml(id, element)
142 }
143 },
144 [hydrateStrategy._t, id],
145 )
146β
147 React.useEffect(() => {
148 const gate = gateRef.current!
149 return () => {
150 const controller = prefetchControllerRef.current
151 controller?.abortController.abort()
152 controller?.cleanup?.()
153 controller?.hydrationListeners.clear()
154 releaseGate(gate)
155 }
156 }, [])
157β
158 React.useEffect(() => {
159 if (
160 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
161 (isServer ?? typeof window === 'undefined') ||
162 !latestRef.current.prefetch
163 ) {
164 return
165 }
166β
167 const controller = prefetchControllerRef.current!
168 if (controller.started) return
169 controller.started = true
170β
171 const onHydrate = (listener: () => void) => {
172 if (controller.hydrationRequested) {
173 listener()
174 return () => {}
175 }
176β
177 controller.hydrationListeners.add(listener)
178 return () => {
179 controller.hydrationListeners.delete(listener)
180 }
181 }
182β
183 const preload = () => latestRef.current.preload?.() ?? Promise.resolve()
184 const prefetchInput = latestRef.current.prefetch
185β
186 if (typeof prefetchInput === 'function') {
187 const promise = Promise.resolve()
188 .then(() =>
189 prefetchInput({
190 element: markerElementRef.current,
191 signal: controller.abortController.signal,
192 preload,
193 waitFor: (strategy) =>
194 waitForHydrationPrefetchStrategy(strategy, {
195 element: markerElementRef.current,
196 signal: controller.abortController.signal,
197 onHydrate,
198 }),
199 }),
200 )
201 .then(() => undefined)
202β
203 controller.promise = promise
204 promise.catch((error) => {
205 if (!controller.abortController.signal.aborted) {
206 setPrefetchError(error)
207 }
208 })
209 return
210 }
211β
212 if (!latestRef.current.preload) return
213β
214 const prefetch = () => {
215 if (didPrefetchRef.current) return
216 didPrefetchRef.current = true
217 void preload()
218 }
219β
220 controller.cleanup = runHydrationStrategyCleanup(
221 prefetchInput._s?.({
222 element: markerElementRef.current,
223 prefetch,
224 }),
225 )
226 }, [hydrateStrategy, latestRef])
227β
228 useLayoutEffect(() => {
229 const gate = gateRef.current!
230 if (
231 !shouldDeferInitialHydrationRef.current ||
232 hydrateStrategy._t === 'never'
233 ) {
234 return
235 }
236β
237 if (gate.resolved) {
238 return
239 }
240β
241 const cleanups: Array<() => void> = []
242 let removeResolveListener = () => {}
243 let disposed = false
244 const resolveGate = gate.resolve
245β
246 const cleanup = () => {
247 if (disposed) return
248 disposed = true
249 if (gate.resolve === requestHydration) {
250 gate.resolve = resolveGate
251 }
252 removeResolveListener()
253 cleanups.forEach((fn) => fn())
254 }
255β
256 const addCleanup = (fn: void | (() => void)) => {
257 if (!fn) return
258 if (disposed || gate.resolved) {
259 fn()
260 return
261 }
262 cleanups.push(fn)
263 }
264β
265 const requestHydration = () => {
266 const controller = prefetchControllerRef.current!
267 if (!controller.hydrationRequested) {
268 controller.hydrationRequested = true
269 controller.hydrationListeners.forEach((listener) => listener())
270 controller.hydrationListeners.clear()
271 }
272β
273 if (!controller.promise) {
274 resolveGate()
275 return
276 }
277 if (controller.hydrationResolvePending) return
278 controller.hydrationResolvePending = true
279β
280 controller.promise.then(
281 () => resolveGate(),
282 (error) => {
283 if (!controller.abortController.signal.aborted) {
284 setPrefetchError(error)
285 }
286 },
287 )
288 }
289β
290 gate.resolve = requestHydration
291 removeResolveListener = onGateResolve(gate, cleanup)
292β
293 const context: HydrationRuntimeContext = {
294 element: markerElementRef.current,
295 gate,
296 }
297 addCleanup(runHydrationStrategyCleanup(hydrateStrategy._s?.(context)))
298β
299 if (hydrateStrategy._t !== 'interaction') {
300 addCleanup(
301 runHydrationStrategyCleanup(
302 markerElementRef.current
303 ? listenForDelegatedHydrationIntent(
304 markerElementRef.current,
305 context,
306 )
307 : undefined,
308 ),
309 )
310 }
311β
312 return cleanup
313 }, [hydrateStrategy, latestRef])
314β
315 return {
316 gate: gateRef.current,
317 markerRef,
318 markerElementRef,
319 hydrateStrategy,
320 markerHydrateType,
321 prefetchError,
322 shouldPreserveServerHTML: shouldPreserveServerHTMLRef.current,
323 }
324}
325β
326function HydrationGate(props: { gate: Gate; children: React.ReactNode }) {
327 if (
328 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
329 isServer ??
330 typeof window === 'undefined'
331 ) {
332 return props.children as React.JSX.Element
333 }
334β
335 if (props.gate.resolved) {
336 return props.children as React.JSX.Element
337 }
338β
339 if (!reactUse) {
340 throw props.gate.promise
341 }
342β
343 reactUse(props.gate.promise)
344β
345 return props.children as React.JSX.Element
346}
347β
348function HydratedBoundary(props: {
349 id: string
350 onHydrated?: () => void
351 onStrategyHydrated?: (id: string) => void
352 children: React.ReactNode
353}) {
354 const { id, onHydrated, onStrategyHydrated } = props
355 const didHydrateRef = React.useRef(false)
356β
357 React.useEffect(() => {
358 if (didHydrateRef.current) return
359 didHydrateRef.current = true
360 onHydrated?.()
361 onStrategyHydrated?.(id)
362 }, [id, onHydrated, onStrategyHydrated])
363β
364 return props.children as React.JSX.Element
365}
366β
367export function GenericHydrate(props: HydrateProps): React.JSX.Element {
368 const internalProps = props as InternalHydrateProps
369 const {
370 gate,
371 hydrateStrategy,
372 markerHydrateType,
373 markerElementRef,
374 markerRef,
375 prefetchError,
376 shouldPreserveServerHTML,
377 } = useHydrationGate(internalProps)
378 if (prefetchError) throw prefetchError
379β
380 const fallback = shouldPreserveServerHTML
381 ? (() => {
382 const html = getFallbackHtml(gate.id)
383 return html ? (
384 <div
385 style={{ display: 'contents' }}
386 dangerouslySetInnerHTML={{ __html: html }}
387 />
388 ) : null
389 })()
390 : (props.fallback ?? null)
391 const markerAttributes =
392 markerHydrateType === dynamicType ? undefined : hydrateStrategy._a?.()
393β
394 const hydrateType = hydrateStrategy._t!
395β
396 if (hydrateType === 'never' && !shouldPreserveServerHTML) {
397 return (
398 <div
399 ref={markerRef}
400 {...{
401 [hydrateIdAttribute]: gate.id,
402 [hydrateWhenAttribute]: markerHydrateType,
403 ...markerAttributes,
404 }}
405 >
406 {props.fallback ?? null}
407 </div>
408 )
409 }
410β
411 return (
412 <div
413 ref={markerRef}
414 {...{
415 [hydrateIdAttribute]: gate.id,
416 [hydrateWhenAttribute]: markerHydrateType,
417 ...markerAttributes,
418 }}
419 >
420 <React.Suspense fallback={fallback}>
421 <HydrationGate gate={gate}>
422 <HydratedBoundary
423 id={gate.id}
424 onHydrated={props.onHydrated}
425 onStrategyHydrated={(id) => {
426 markerElementRef.current?.removeAttribute(hydrateWhenAttribute)
427 hydrateStrategy._o?.(id)
428 }}
429 >
430 {props.children}
431 </HydratedBoundary>
432 </HydrationGate>
433 </React.Suspense>
434 </div>
435 )
436}