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