-
Notifications
You must be signed in to change notification settings - Fork 307
/
useClient.ts
589 lines (512 loc) · 17.4 KB
/
useClient.ts
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import type {
BundlerState,
ListenerFunction,
ReactDevToolsMode,
SandpackError,
SandpackMessage,
UnsubscribeFunction,
SandpackClient,
} from "@codesandbox/sandpack-client";
import {
loadSandpackClient,
extractErrorDetails,
} from "@codesandbox/sandpack-client";
import { useCallback, useEffect, useRef, useState } from "react";
import type {
SandpackInitMode,
SandpackProviderProps,
SandpackStatus,
} from "../..";
import { generateRandomId } from "../../utils/stringUtils";
import type { FilesState } from "./useFiles";
type SandpackClientType = InstanceType<typeof SandpackClient>;
const BUNDLER_TIMEOUT = 40_000;
interface SandpackConfigState {
reactDevTools?: ReactDevToolsMode;
startRoute?: string;
initMode: SandpackInitMode;
bundlerState: BundlerState | undefined;
error: SandpackError | null;
status: SandpackStatus;
}
export interface ClientPropsOverride {
startRoute?: string;
}
export interface UseClientOperations {
clients: Record<string, SandpackClientType>;
initializeSandpackIframe: () => void;
runSandpack: () => Promise<void>;
unregisterBundler: (clientId: string) => void;
registerBundler: (
iframe: HTMLIFrameElement,
clientId: string,
clientPropsOverride?: ClientPropsOverride
) => Promise<void>;
registerReactDevTools: (value: ReactDevToolsMode) => void;
addListener: (
listener: ListenerFunction,
clientId?: string
) => UnsubscribeFunction;
dispatchMessage: (message: SandpackMessage, clientId?: string) => void;
lazyAnchorRef: React.RefObject<HTMLDivElement>;
unsubscribeClientListenersRef: React.MutableRefObject<
Record<string, Record<string, UnsubscribeFunction>>
>;
queuedListenersRef: React.MutableRefObject<
Record<string, Record<string, ListenerFunction>>
>;
}
type UseClient = (
props: SandpackProviderProps,
filesState: FilesState
) => [SandpackConfigState, UseClientOperations];
export const useClient: UseClient = (
{ options, customSetup, teamId, sandboxId },
filesState
) => {
options ??= {};
customSetup ??= {};
const initModeFromProps = options?.initMode || "lazy";
const [state, setState] = useState<SandpackConfigState>({
startRoute: options?.startRoute,
bundlerState: undefined,
error: null,
initMode: initModeFromProps,
reactDevTools: undefined,
status: options?.autorun ?? true ? "initial" : "idle",
});
/**
* Refs
*/
type InterserctionObserverCallback = (
entries: IntersectionObserverEntry[]
) => void;
const intersectionObserverCallback = useRef<
InterserctionObserverCallback | undefined
>();
const intersectionObserver = useRef<IntersectionObserver | null>(null);
const lazyAnchorRef = useRef<HTMLDivElement>(null);
const registeredIframes = useRef<
Record<
string,
{ iframe: HTMLIFrameElement; clientPropsOverride?: ClientPropsOverride }
>
>({});
const clients = useRef<Record<string, SandpackClientType>>({});
const timeoutHook = useRef<NodeJS.Timer | null>(null);
const unsubscribeClientListeners = useRef<
Record<string, Record<string, UnsubscribeFunction>>
>({});
const unsubscribe = useRef<() => void | undefined>();
const queuedListeners = useRef<
Record<string, Record<string, ListenerFunction>>
>({ global: {} });
const debounceHook = useRef<number | undefined>();
const prevEnvironment = useRef(filesState.environment);
/**
* Callbacks
*/
const createClient = useCallback(
async (
iframe: HTMLIFrameElement,
clientId: string,
clientPropsOverride?: ClientPropsOverride
): Promise<void> => {
// Clean up any existing clients that
// have been created with the given id
if (clients.current[clientId]) {
clients.current[clientId].destroy();
}
options ??= {};
customSetup ??= {};
const timeOut = options?.bundlerTimeOut ?? BUNDLER_TIMEOUT;
if (timeoutHook.current) {
clearTimeout(timeoutHook.current);
}
/**
* Subscribe inside the context with the first client that gets instantiated.
* This subscription is for global states like error and timeout, so no need for a per client listen
* Also, set the timeout timer only when the first client is instantiated
*/
const shouldSetTimeout = typeof unsubscribe.current !== "function";
if (shouldSetTimeout) {
timeoutHook.current = setTimeout(() => {
unregisterAllClients();
setState((prev) => ({ ...prev, status: "timeout" }));
}, timeOut);
}
const client = await loadSandpackClient(
iframe,
{
files: filesState.files,
template: filesState.environment,
},
{
externalResources: options.externalResources,
bundlerURL: options.bundlerURL,
startRoute: clientPropsOverride?.startRoute ?? options.startRoute,
fileResolver: options.fileResolver,
skipEval: options.skipEval ?? false,
logLevel: options.logLevel,
showOpenInCodeSandbox: false,
showErrorScreen: true,
showLoadingScreen: false,
reactDevTools: state.reactDevTools,
customNpmRegistries: customSetup?.npmRegistries,
teamId,
sandboxId,
}
);
if (typeof unsubscribe.current !== "function") {
unsubscribe.current = client.listen(handleMessage);
}
unsubscribeClientListeners.current[clientId] =
unsubscribeClientListeners.current[clientId] || {};
/**
* Register any potential listeners that subscribed before sandpack ran
*/
if (queuedListeners.current[clientId]) {
Object.keys(queuedListeners.current[clientId]).forEach((listenerId) => {
const listener = queuedListeners.current[clientId][listenerId];
const unsubscribe = client.listen(listener) as () => void;
unsubscribeClientListeners.current[clientId][listenerId] =
unsubscribe;
});
// Clear the queued listeners after they were registered
queuedListeners.current[clientId] = {};
}
/**
* Register global listeners
*/
const globalListeners = Object.entries(queuedListeners.current.global);
globalListeners.forEach(([listenerId, listener]) => {
const unsubscribe = client.listen(listener) as () => void;
unsubscribeClientListeners.current[clientId][listenerId] = unsubscribe;
/**
* Important: Do not clean the global queue
* Instead of cleaning the queue, keep it there for the
* following clients that might be created
*/
});
clients.current[clientId] = client;
},
[filesState.environment, filesState.files, state.reactDevTools]
);
const unregisterAllClients = useCallback((): void => {
Object.keys(clients.current).map(unregisterBundler);
if (typeof unsubscribe.current === "function") {
unsubscribe.current();
unsubscribe.current = undefined;
}
}, []);
const runSandpack = useCallback(async (): Promise<void> => {
await Promise.all(
Object.entries(registeredIframes.current).map(
async ([clientId, { iframe, clientPropsOverride = {} }]) => {
await createClient(iframe, clientId, clientPropsOverride);
}
)
);
setState((prev) => ({ ...prev, error: null, status: "running" }));
}, [createClient]);
intersectionObserverCallback.current = (
entries: IntersectionObserverEntry[]
): void => {
if (entries.some((entry) => entry.isIntersecting)) {
runSandpack();
}
};
const initializeSandpackIframe = useCallback((): void => {
const autorun = options?.autorun ?? true;
if (!autorun) {
return;
}
const observerOptions = options?.initModeObserverOptions ?? {
rootMargin: `1000px 0px`,
};
if (intersectionObserver.current && lazyAnchorRef.current) {
intersectionObserver.current?.unobserve(lazyAnchorRef.current);
}
if (lazyAnchorRef.current && state.initMode === "lazy") {
// If any component registered a lazy anchor ref component, use that for the intersection observer
intersectionObserver.current = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
intersectionObserverCallback.current?.(entries);
}
}, observerOptions);
intersectionObserver.current.observe(lazyAnchorRef.current);
} else if (lazyAnchorRef.current && state.initMode === "user-visible") {
intersectionObserver.current = new IntersectionObserver((entries) => {
intersectionObserverCallback.current?.(entries);
}, observerOptions);
intersectionObserver.current.observe(lazyAnchorRef.current);
} else {
runSandpack();
}
}, [
options?.autorun,
options?.initModeObserverOptions,
runSandpack,
state.initMode,
unregisterAllClients,
]);
const registerBundler = useCallback(
async (
iframe: HTMLIFrameElement,
clientId: string,
clientPropsOverride?: ClientPropsOverride
): Promise<void> => {
// Store the iframe info so it can be
// used later to manually run sandpack
registeredIframes.current[clientId] = {
iframe,
clientPropsOverride,
};
if (state.status === "running") {
await createClient(iframe, clientId, clientPropsOverride);
}
},
[createClient, state.status]
);
const unregisterBundler = (clientId: string): void => {
const client = clients.current[clientId];
if (client) {
client.destroy();
client.iframe.contentWindow?.location.replace("about:blank");
client.iframe.removeAttribute("src");
delete clients.current[clientId];
} else {
delete registeredIframes.current[clientId];
}
if (timeoutHook.current) {
clearTimeout(timeoutHook.current);
}
const unsubscribeQueuedClients = Object.values(
unsubscribeClientListeners.current[clientId] ?? {}
);
// Unsubscribing all listener registered
unsubscribeQueuedClients.forEach((listenerOfClient) => {
const listenerFunctions = Object.values(listenerOfClient);
listenerFunctions.forEach((unsubscribe) => unsubscribe());
});
// Keep running if it still have clients
const status = Object.keys(clients.current).length > 0 ? "running" : "idle";
setState((prev) => ({ ...prev, status }));
};
const handleMessage = (msg: SandpackMessage): void => {
if (msg.type === "start") {
setState((prev) => ({ ...prev, error: null }));
} else if (msg.type === "state") {
setState((prev) => ({ ...prev, bundlerState: msg.state }));
} else if (
(msg.type === "done" && !msg.compilatonError) ||
msg.type === "connected"
) {
if (timeoutHook.current) {
clearTimeout(timeoutHook.current);
}
setState((prev) => ({ ...prev, error: null }));
} else if (msg.type === "action" && msg.action === "show-error") {
if (timeoutHook.current) {
clearTimeout(timeoutHook.current);
}
setState((prev) => ({ ...prev, error: extractErrorDetails(msg) }));
} else if (
msg.type === "action" &&
msg.action === "notification" &&
msg.notificationType === "error"
) {
setState((prev) => ({
...prev,
error: { message: msg.title },
}));
}
};
const registerReactDevTools = (value: ReactDevToolsMode): void => {
setState((prev) => ({ ...prev, reactDevTools: value }));
};
const recompileMode = options?.recompileMode ?? "delayed";
const recompileDelay = options?.recompileDelay ?? 200;
const dispatchMessage = (
message: SandpackMessage,
clientId?: string
): void => {
if (state.status !== "running") {
console.warn(
`[sandpack-react]: dispatch cannot be called while in idle mode`
);
return;
}
if (clientId) {
clients.current[clientId].dispatch(message);
} else {
Object.values(clients.current).forEach((client) => {
client.dispatch(message);
});
}
};
const addListener = (
listener: ListenerFunction,
clientId?: string
): UnsubscribeFunction => {
if (clientId) {
if (clients.current[clientId]) {
const unsubscribeListener = clients.current[clientId].listen(listener);
return unsubscribeListener;
} else {
/**
* When listeners are added before the client is instantiated, they are stored with an unique id
* When the client is eventually instantiated, the listeners are registered on the spot
* Their unsubscribe functions are stored in unsubscribeClientListeners for future cleanup
*/
const listenerId = generateRandomId();
queuedListeners.current[clientId] =
queuedListeners.current[clientId] || {};
unsubscribeClientListeners.current[clientId] =
unsubscribeClientListeners.current[clientId] || {};
queuedListeners.current[clientId][listenerId] = listener;
const unsubscribeListener = (): void => {
if (queuedListeners.current[clientId][listenerId]) {
/**
* Unsubscribe was called before the client was instantiated
* common example - a component with autorun=false that unmounted
*/
delete queuedListeners.current[clientId][listenerId];
} else if (unsubscribeClientListeners.current[clientId][listenerId]) {
/**
* unsubscribe was called for a listener that got added before the client was instantiated
* call the unsubscribe function and remove it from memory
*/
unsubscribeClientListeners.current[clientId][listenerId]();
delete unsubscribeClientListeners.current[clientId][listenerId];
}
};
return unsubscribeListener;
}
} else {
// Push to the **global** queue
const listenerId = generateRandomId();
queuedListeners.current.global[listenerId] = listener;
// Add to the current clients
const clientsList = Object.values(clients.current);
const currentClientUnsubscribeListeners = clientsList.map((client) =>
client.listen(listener)
);
const unsubscribeListener = (): void => {
// Unsubscribing from the clients already created
currentClientUnsubscribeListeners.forEach((unsubscribe) =>
unsubscribe()
);
delete queuedListeners.current.global[listenerId];
// Unsubscribe in case it was added later from `global`
Object.values(unsubscribeClientListeners.current).forEach((client) => {
client?.[listenerId]?.();
});
};
return unsubscribeListener;
}
};
/**
* Effects
*/
useEffect(
function watchFileChanges() {
if (state.status !== "running" || !filesState.shouldUpdatePreview) {
return;
}
/**
* When the environment changes, Sandpack needs to make sure
* to create a new client and the proper bundler
*/
if (prevEnvironment.current !== filesState.environment) {
prevEnvironment.current = filesState.environment;
Object.entries(clients.current).forEach(([key, client]) => {
registerBundler(client.iframe, key);
});
}
if (recompileMode === "immediate") {
Object.values(clients.current).forEach((client) => {
/**
* Avoid concurrency
*/
if (client.status === "done") {
client.updateSandbox({
files: filesState.files,
template: filesState.environment,
});
}
});
}
if (recompileMode === "delayed") {
if (typeof window === "undefined") return;
window.clearTimeout(debounceHook.current);
debounceHook.current = window.setTimeout(() => {
Object.values(clients.current).forEach((client) => {
/**
* Avoid concurrency
*/
if (client.status === "done") {
client.updateSandbox({
files: filesState.files,
template: filesState.environment,
});
}
});
}, recompileDelay);
}
return () => {
window.clearTimeout(debounceHook.current);
};
},
[
filesState.files,
filesState.environment,
filesState.shouldUpdatePreview,
recompileDelay,
recompileMode,
registerBundler,
state.status,
]
);
useEffect(
function watchInitMode() {
if (initModeFromProps !== state.initMode) {
setState((prev) => ({ ...prev, initMode: initModeFromProps }));
initializeSandpackIframe();
}
},
[initModeFromProps, initializeSandpackIframe, state.initMode]
);
useEffect(() => {
return function unmountClient(): void {
if (typeof unsubscribe.current === "function") {
unsubscribe.current();
}
if (timeoutHook.current) {
clearTimeout(timeoutHook.current);
}
if (debounceHook.current) {
clearTimeout(debounceHook.current);
}
if (intersectionObserver.current) {
intersectionObserver.current.disconnect();
}
};
}, []);
return [
state,
{
clients: clients.current,
initializeSandpackIframe,
runSandpack,
registerBundler,
unregisterBundler,
registerReactDevTools,
addListener,
dispatchMessage,
lazyAnchorRef,
unsubscribeClientListenersRef: unsubscribeClientListeners,
queuedListenersRef: queuedListeners,
},
];
};