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 * A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
55 */
56 nonce?: string
57}
58β
59export function createHydrationStreamProvider<TShape>() {
60 const context = React.createContext<HydrationStreamContext<TShape>>(
61 null as any,
62 )
63 /**
64β
65 * 1. (Happens on server): `useServerInsertedHTML()` is called **on the server** whenever a `Suspense`-boundary completes
66 * - This means that we might have some new entries in the cache that needs to be flushed
67 * - We pass these to the client by inserting a `<script>`-tag where we do `window[id].push(serializedVersionOfCache)`
68 * 2. (Happens in browser) In `useEffect()`:
69 * - 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
70 * - We replace `window[id]` with a `push()`-method that will be called whenever new entries are received
71 **/
72 function UseClientHydrationStreamProvider(props: {
73 children: React.ReactNode
74 /**
75 * Optional transformer to serialize/deserialize the data
76 * Example devalue, superjson et al
77 */
78 transformer?: DataTransformer
79 /**
80 * **Client method**
81 * Called in the browser when new entries are received
82 */
83 onEntries: (entries: Array<TShape>) => void
84 /**
85 * **Server method**
86 * onFlush is called on the server when the cache is flushed
87 */
88 onFlush?: () => Array<TShape>
89 /**
90 * A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
91 */
92 nonce?: string
93 }) {
94 // unique id for the cache provider
95 const id = `__RQ${React.useId()}`
96 const idJSON = htmlEscapeJsonString(JSON.stringify(id))
97β
98 const [transformer] = React.useState(
99 () =>
100 (props.transformer ?? {
101 // noop
102 serialize: (obj: any) => obj,
103 deserialize: (obj: any) => obj,
104 }) as unknown as TypedDataTransformer<TShape>,
105 )
106β
107 // <server stuff>
108 const [stream] = React.useState<Array<TShape>>(() => {
109 if (!isServer) {
110 return {
111 push() {
112 // no-op on the client
113 },
114 } as unknown as Array<TShape>
115 }
116 return []
117 })
118 const count = React.useRef(0)
119 useServerInsertedHTML(() => {
120 // This only happens on the server
121 stream.push(...(props.onFlush?.() ?? []))
122β
123 if (!stream.length) {
124 return null
125 }
126 // console.log(`pushing ${stream.length} entries`)
127 const serializedCacheArgs = stream
128 .map((entry) => transformer.serialize(entry))
129 .map((entry) => JSON.stringify(entry))
130 .join(',')
131β
132 // Flush stream
133 // eslint-disable-next-line react-hooks/immutability
134 stream.length = 0
135β
136 const html: Array<string> = [
137 `window[${idJSON}] = window[${idJSON}] || [];`,
138 `window[${idJSON}].push(${htmlEscapeJsonString(serializedCacheArgs)});`,
139 ]
140 return (
141 <script
142 key={count.current++}
143 nonce={props.nonce}
144 dangerouslySetInnerHTML={{
145 __html: html.join(''),
146 }}
147 />
148 )
149 })
150 // </server stuff>
151β
152 // <client stuff>
153 // Setup and run the onEntries handler on the client only, but do it during
154 // the initial render so children have access to the data immediately
155 // This is important to avoid the client suspending during the initial render
156 // if the data has not yet been hydrated.
157 if (!isServer) {
158 const win = window as any
159 if (!win[id]?.initialized) {
160 // Client: consume cache:
161 const onEntries = (...serializedEntries: Array<Serialized<TShape>>) => {
162 const entries = serializedEntries.map((serialized) =>
163 transformer.deserialize(serialized),
164 )
165 props.onEntries(entries)
166 }
167β
168 const winStream: Array<Serialized<TShape>> = win[id] ?? []
169β
170 onEntries(...winStream)
171β
172 // eslint-disable-next-line react-hooks/immutability
173 win[id] = {
174 initialized: true,
175 push: onEntries,
176 }
177 }
178 }
179 // </client stuff>
180β
181 return (
182 <context.Provider value={{ stream, id }}>
183 {props.children}
184 </context.Provider>
185 )
186 }
187β
188 return {
189 Provider: UseClientHydrationStreamProvider,
190 context,
191 }
192}