Open History to see the last commit
1'use client'
2β
3import { isServer } from '@tanstack/react-query'
4import { useServerInsertedHTML } from 'next/navigation'
5import * as React from 'react'
6import { htmlEscapeJsonString } from './htmlescape'
7β
8const serializedSymbol = Symbol('serialized')
9β
10interface DataTransformer {
11 serialize: (object: any) => any
12 deserialize: (object: any) => any
13}
14β
15type Serialized<TData> = unknown & {
16 [serializedSymbol]: TData
17}
18β
19interface TypedDataTransformer<TData> {
20 serialize: (obj: TData) => Serialized<TData>
21 deserialize: (obj: Serialized<TData>) => TData
22}
23β
24interface HydrationStreamContext<TShape> {
25 id: string
26 stream: {
27 /**
28 * **Server method**
29 * Push a new entry to the stream
30 * Will be ignored on the client
31 */
32 push: (...shape: Array<TShape>) => void
33 }
34}
35β
36export interface HydrationStreamProviderProps<TShape> {
37 children: React.ReactNode
38 /**
39 * Optional transformer to serialize/deserialize the data
40 * Example devalue, superjson et al
41 */
42 transformer?: DataTransformer
43 /**
44 * **Client method**
45 * Called in the browser when new entries are received
46 */
47 onEntries: (entries: Array<TShape>) => void
48 /**
49 * **Server method**
50 * onFlush is called on the server when the cache is flushed
51 */
52 onFlush?: () => Array<TShape>
53}
54β
55export function createHydrationStreamProvider<TShape>() {
56 const context = React.createContext<HydrationStreamContext<TShape>>(
57 null as any,
58 )
59 /**
60β
61 * 1. (Happens on server): `useServerInsertedHTML()` is called **on the server** whenever a `Suspense`-boundary completes
62 * - This means that we might have some new entries in the cache that needs to be flushed
63 * - We pass these to the client by inserting a `<script>`-tag where we do `window[id].push(serializedVersionOfCache)`
64 * 2. (Happens in browser) In `useEffect()`:
65 * - We check if `window[id]` is set to an array and call `push()` on all the entries which will call `onEntries()` with the new entries
66 * - We replace `window[id]` with a `push()`-method that will be called whenever new entries are received
67 **/
68 function UseClientHydrationStreamProvider(props: {
69 children: React.ReactNode
70 /**
71 * Optional transformer to serialize/deserialize the data
72 * Example devalue, superjson et al
73 */
74 transformer?: DataTransformer
75 /**
76 * **Client method**
77 * Called in the browser when new entries are received
78 */
79 onEntries: (entries: Array<TShape>) => void
80 /**
81 * **Server method**
82 * onFlush is called on the server when the cache is flushed
83 */
84 onFlush?: () => Array<TShape>
85 }) {
86 // unique id for the cache provider
87 const id = `__RQ${React.useId()}`
88 const idJSON = htmlEscapeJsonString(JSON.stringify(id))
89β
90 const [transformer] = React.useState(
91 () =>
92 (props.transformer ?? {
93 // noop
94 serialize: (obj: any) => obj,
95 deserialize: (obj: any) => obj,
96 }) as unknown as TypedDataTransformer<TShape>,
97 )
98β
99 // <server stuff>
100 const [stream] = React.useState<Array<TShape>>(() => {
101 if (typeof window !== 'undefined') {
102 return {
103 push() {
104 // no-op on the client
105 },
106 } as unknown as Array<TShape>
107 }
108 return []
109 })
110 const count = React.useRef(0)
111 useServerInsertedHTML(() => {
112 // This only happens on the server
113 stream.push(...(props.onFlush?.() ?? []))
114β
115 if (!stream.length) {
116 return null
117 }
118 // console.log(`pushing ${stream.length} entries`)
119 const serializedCacheArgs = stream
120 .map((entry) => transformer.serialize(entry))
121 .map((entry) => JSON.stringify(entry))
122 .join(',')
123β
124 // Flush stream
125 stream.length = 0
126β
127 const html: Array<string> = [
128 `window[${idJSON}] = window[${idJSON}] || [];`,
129 `window[${idJSON}].push(${htmlEscapeJsonString(serializedCacheArgs)});`,
130 ]
131 return (
132 <script
133 key={count.current++}
134 dangerouslySetInnerHTML={{
135 __html: html.join(''),
136 }}
137 />
138 )
139 })
140 // </server stuff>
141β
142 // <client stuff>
143 // Setup and run the onEntries handler on the client only, but do it during
144 // the initial render so children have access to the data immediately
145 // This is important to avoid the client suspending during the initial render
146 // if the data has not yet been hydrated.
147 if (!isServer) {
148 const win = window as any
149 if (!win[id]?.initialized) {
150 // Client: consume cache:
151 const onEntries = (...serializedEntries: Array<Serialized<TShape>>) => {
152 const entries = serializedEntries.map((serialized) =>
153 transformer.deserialize(serialized),
154 )
155 props.onEntries(entries)
156 }
157β
158 const winStream: Array<Serialized<TShape>> = win[id] ?? []
159β
160 onEntries(...winStream)
161β
162 win[id] = {
163 initialized: true,
164 push: onEntries,
165 }
166 }
167 }
168 // </client stuff>
169β
170 return (
171 <context.Provider value={{ stream, id }}>
172 {props.children}
173 </context.Provider>
174 )
175 }
176β
177 return {
178 Provider: UseClientHydrationStreamProvider,
179 context,
180 }
181}