Open History to see the last commit
1'use client'
2β
3import * as React from 'react'
4β
5import { reactUse, useHydrated } from '@tanstack/react-router'
6import { isServer } from '@tanstack/router-core/isServer'
7import {
8 never as coreNever,
9 withHydrationRenderer,
10} from '@tanstack/start-client-core/hydration'
11import {
12 hydrateIdAttribute,
13 hydrateWhenAttribute,
14} from '@tanstack/start-client-core/hydration/constants'
15import {
16 getFallbackHtml,
17 saveFallbackHtml,
18} from '@tanstack/start-client-core/hydration/runtime'
19import type {
20 HydrateProps,
21 InternalHydrateProps,
22 ReactHydrationStrategy,
23} from '../Hydrate'
24β
25const neverType = 'never'
26const neverPromise = new Promise<void>(() => {})
27β
28function NeverGate(props: { children: React.ReactNode }) {
29 if (
30 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
31 isServer ??
32 typeof window === 'undefined'
33 ) {
34 return props.children as React.JSX.Element
35 }
36β
37 if (!reactUse) {
38 throw neverPromise
39 }
40β
41 reactUse(neverPromise)
42β
43 return props.children as React.JSX.Element
44}
45β
46export function NeverHydrate(props: HydrateProps): React.JSX.Element {
47 const internalProps = props as InternalHydrateProps
48 const hydrated = useHydrated()
49 const reactId = React.useId()
50 const id = internalProps.h ? `${internalProps.h}${reactId}` : reactId
51 const shouldPreserveServerHTMLRef = React.useRef<boolean | undefined>(
52 undefined,
53 )
54 shouldPreserveServerHTMLRef.current ??=
55 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
56 (isServer ?? typeof window === 'undefined') || !hydrated
57 const markerRef = React.useCallback(
58 (element: HTMLDivElement | null) => {
59 if (!element) return
60 if (!shouldPreserveServerHTMLRef.current) {
61 element.replaceChildren()
62 } else {
63 saveFallbackHtml(id, element)
64 }
65 },
66 [id],
67 )
68 const markerProps = {
69 ref: markerRef,
70 [hydrateIdAttribute]: id,
71 [hydrateWhenAttribute]: neverType,
72 }
73 const fallback = (() => {
74 const html = getFallbackHtml(id)
75 return html ? (
76 <div
77 style={{ display: 'contents' }}
78 dangerouslySetInnerHTML={{ __html: html }}
79 />
80 ) : (
81 (props.fallback ?? null)
82 )
83 })()
84β
85 return (
86 <div {...markerProps}>
87 <React.Suspense fallback={fallback}>
88 <NeverGate>{props.children}</NeverGate>
89 </React.Suspense>
90 </div>
91 )
92}
93β
94/* @__NO_SIDE_EFFECTS__ */
95export function never(): ReactHydrationStrategy<'never', false> {
96 return /* @__PURE__ */ withHydrationRenderer(coreNever(), NeverHydrate)
97}