Open History to see the last commit
1'use client'
2β
3import * as React from 'react'
4β
5import { isServer } from '@tanstack/router-core/isServer'
6import type {
7 HydrationStrategy as CoreHydrationStrategy,
8 HydrationPrefetchFunction,
9 HydrationPrefetchStrategy,
10 HydrationWhen,
11} from '@tanstack/start-client-core/hydration'
12β
13export type {
14 HydrationInteractionEvent,
15 HydrationInteractionEvents,
16 HydrationPrefetchContext,
17 HydrationPrefetchFunction,
18 HydrationPrefetchStrategy,
19 HydrationPrefetchWaitReason,
20 HydrationWhen,
21} from '@tanstack/start-client-core/hydration'
22β
23export type ReactHydrationStrategy<
24 TWhen extends HydrationWhen = HydrationWhen,
25 TCanPrefetch extends boolean = boolean,
26> = CoreHydrationStrategy<TWhen, TCanPrefetch> & {
27 _h: (this: ReactHydrationStrategy, props: HydrateProps) => React.JSX.Element
28}
29β
30export type HydrationStrategy<
31 TWhen extends HydrationWhen = HydrationWhen,
32 TCanPrefetch extends boolean = boolean,
33> = ReactHydrationStrategy<TWhen, TCanPrefetch>
34β
35export type HydrateWhen =
36 | ReactHydrationStrategy
37 | (() => ReactHydrationStrategy)
38β
39type HydrateCommonOptions = {
40 when: HydrateWhen
41 fallback?: React.ReactNode
42 onHydrated?: () => void
43}
44β
45export type HydrateOptions =
46 | (HydrateCommonOptions & {
47 prefetch?: never
48 split?: boolean
49 })
50 | (HydrateCommonOptions & {
51 prefetch: HydrationPrefetchStrategy
52 split?: true
53 })
54 | (HydrateCommonOptions & {
55 prefetch: HydrationPrefetchFunction
56 split?: boolean
57 })
58β
59export type HydrateProps = HydrateOptions & {
60 children: React.ReactNode
61}
62β
63export type InternalHydrateProps = HydrateProps & {
64 h?: string
65 p?: () => Promise<void>
66}
67β
68const dynamicType = 'dynamic'
69const hydrateIdAttribute = 'data-ts-hydrate-id'
70const hydrateWhenAttribute = 'data-ts-hydrate-when'
71β
72/* @__NO_SIDE_EFFECTS__ */
73function ServerDynamicHydrate(props: HydrateProps): React.JSX.Element {
74 const internalProps = props as InternalHydrateProps
75 const reactId = React.useId()
76 const id = internalProps.h ? `${internalProps.h}${reactId}` : reactId
77β
78 return (
79 <div
80 {...{
81 [hydrateIdAttribute]: id,
82 [hydrateWhenAttribute]: dynamicType,
83 }}
84 >
85 <React.Suspense fallback={props.fallback ?? null}>
86 {props.children}
87 </React.Suspense>
88 </div>
89 )
90}
91β
92/* @__NO_SIDE_EFFECTS__ */
93export function Hydrate(props: HydrateProps): React.JSX.Element {
94 if (typeof props.when === 'function') {
95 if (
96 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
97 isServer ??
98 typeof window === 'undefined'
99 ) {
100 return <ServerDynamicHydrate {...props} />
101 }
102β
103 return props.when()._h(props)
104 }
105β
106 return props.when._h(props)
107}