-
Notifications
You must be signed in to change notification settings - Fork 328
/
entry-client.tsx
244 lines (214 loc) · 5.98 KB
/
entry-client.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import React, {
Suspense,
useState,
StrictMode,
Fragment,
type ElementType,
} from 'react';
import {hydrateRoot} from 'react-dom/client';
import type {ClientConfig, ClientHandler} from './types';
import {ErrorBoundary} from 'react-error-boundary';
import {
createFromFetch,
createFromReadableStream,
// @ts-ignore
} from '@shopify/hydrogen/vendor/react-server-dom-vite';
import {RSC_PATHNAME} from './constants';
import {ServerPropsProvider} from './foundation/ServerPropsProvider';
import type {DevServerMessage} from './utilities/devtools';
import type {LocationServerProps} from './foundation/ServerPropsProvider/ServerPropsProvider';
import {ClientAnalytics} from './foundation/Analytics/';
import {usePerformanceMark, Stage} from '@shopify/react-performance';
let rscReader: ReadableStream | null;
const cache = new Map();
// Hydrate an SSR response from <meta> tags placed in the DOM.
const flightChunks: string[] = [];
const FLIGHT_ATTRIBUTE = 'data-flight';
function addElementToFlightChunks(el: Element) {
// We don't need to decode, because `.getAttribute` already decodes
const chunk = el.getAttribute(FLIGHT_ATTRIBUTE);
if (chunk) {
flightChunks.push(chunk);
}
}
// Get initial payload
document
.querySelectorAll('[' + FLIGHT_ATTRIBUTE + ']')
.forEach(addElementToFlightChunks);
// Create a mutation observer on the document to detect when new
// <meta data-flight> tags are added, and add them to the array.
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (
node instanceof HTMLElement &&
node.tagName === 'META' &&
node.hasAttribute(FLIGHT_ATTRIBUTE)
) {
addElementToFlightChunks(node);
}
});
});
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
});
if (flightChunks.length > 0) {
const contentLoaded = new Promise((resolve) =>
document.addEventListener('DOMContentLoaded', resolve)
);
try {
rscReader = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const write = (chunk: string) => {
controller.enqueue(encoder.encode(chunk));
return 0;
};
flightChunks.forEach(write);
flightChunks.push = write;
contentLoaded.then(() => {
controller.close();
observer.disconnect();
});
},
});
} catch (_) {
// Old browser, will try a new hydration request later
}
}
const renderHydrogen: ClientHandler = async (ClientWrapper) => {
const root = document.getElementById('root');
if (!root) {
console.error(
`Could not find a root element <div id="root"></div> to render.`
);
return;
}
if (import.meta.hot) {
import.meta.hot.on(
'hydrogen-browser-console',
({type, data}: DevServerMessage) => {
if (type === 'warn') {
console.warn(data);
}
}
);
}
let config: ClientConfig;
try {
config = JSON.parse(root.dataset.clientConfig ?? '{}');
} catch (error: any) {
config = {};
if (__HYDROGEN_DEV__) {
console.warn(
'Could not parse client configuration in browser',
error.message
);
}
}
const RootComponent =
// Default to StrictMode on, unless explicitly turned off
config.strictMode !== false ? StrictMode : Fragment;
hydrateRoot(
root,
<>
<RootComponent>
<ErrorBoundary FallbackComponent={Error}>
<Suspense fallback={null}>
<Content clientWrapper={ClientWrapper} />
</Suspense>
</ErrorBoundary>
</RootComponent>
</>
);
};
export default renderHydrogen;
function Content({
clientWrapper: ClientWrapper = ({children}: {children: JSX.Element}) =>
children,
}: {
clientWrapper: ElementType;
}) {
const [serverProps, setServerProps] = useState<LocationServerProps>({
pathname: window.location.pathname,
search: window.location.search,
});
const response = useServerResponse(serverProps);
usePerformanceMark(Stage.Complete, window.location.pathname);
return (
<ServerPropsProvider
initialServerProps={serverProps}
setServerPropsForRsc={setServerProps}
>
<ClientWrapper>{response.readRoot()}</ClientWrapper>
</ServerPropsProvider>
);
}
function Error({error}: {error: Error}) {
if (import.meta.env.DEV) {
return (
<div style={{padding: '1em'}}>
<h1 style={{fontSize: '2em', marginBottom: '1em', fontWeight: 'bold'}}>
Error
</h1>
<pre style={{whiteSpace: 'pre-wrap'}}>{error.stack}</pre>
</div>
);
}
return (
<div
style={{
padding: '2em',
textAlign: 'center',
}}
>
<h1 style={{fontSize: '2em', marginBottom: '1em', fontWeight: 'bold'}}>
Something's wrong here...
</h1>
<div style={{fontSize: '1.1em'}}>
<p>We found an error while loading this page.</p>
<p>
Please, refresh or go back to the{' '}
<a href="/" style={{textDecoration: 'underline'}}>
home page
</a>
.
</p>
</div>
</div>
);
}
function useServerResponse(state: any) {
const key = JSON.stringify(state);
let response = cache.get(key);
if (response) {
return response;
}
if (rscReader) {
// The flight response was inlined during SSR, use it directly.
response = createFromReadableStream(rscReader);
rscReader = null;
} else {
if (
/* @ts-ignore */
window.BOOMR &&
/* @ts-ignore */
window.BOOMR.plugins &&
/* @ts-ignore */
window.BOOMR.plugins.Hydrogen
) {
/* @ts-ignore */
window.BOOMR.plugins.Hydrogen.trackSubPageLoadPerformance();
}
ClientAnalytics.resetPageAnalyticsData();
// Request a new flight response.
response = createFromFetch(
fetch(`${RSC_PATHNAME}?state=` + encodeURIComponent(key))
);
}
cache.clear();
cache.set(key, response);
return response;
}