-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
useLiveDemo.ts
203 lines (182 loc) 路 6.45 KB
/
useLiveDemo.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
import { SHOULD_SKIP_LIVEDEMO_ERROR } from '@/constants';
import { useDemo } from 'dumi';
import throttle from 'lodash.throttle';
import {
createElement,
useCallback,
useRef,
useState,
type ComponentType,
type ReactNode,
type RefObject,
} from 'react';
import DemoErrorBoundary from './DumiDemo/DemoErrorBoundary';
import type { AgnosticComponentType } from './types';
import { useRenderer } from './useRenderer';
import { getAgnosticComponentModule } from './utils';
const THROTTLE_WAIT = 500;
type CommonJSContext = {
module: any;
exports: {
default?: any;
};
require: any;
};
function evalCommonJS(
js: string,
{ module, exports, require }: CommonJSContext,
) {
new Function('module', 'exports', 'require', js)(module, exports, require);
}
export const useLiveDemo = (
id: string,
opts?: { containerRef?: RefObject<HTMLElement>; iframe?: boolean },
) => {
const demo = useDemo(id)!;
const [loading, setLoading] = useState(false);
const loadingTimer = useRef<number>();
const taskToken = useRef<number>();
function resetLoadingStatus() {
clearTimeout(loadingTimer.current);
setLoading(false);
}
const { context = {}, asset, renderOpts } = demo;
const [error, setError] = useState<Error | null>(null);
const { canvasRef: ref, setComponent } = useRenderer({
id,
renderOpts: demo.renderOpts,
onResolved: () => {
resetLoadingStatus();
},
});
const [demoNode, setDemoNode] = useState<ReactNode>();
const setSource = useCallback(
throttle(
async (source: Record<string, string>) => {
// set loading status if still compiling after 499ms
loadingTimer.current = window.setTimeout(
() => {
setLoading(true);
},
// make sure timer be fired before next throttle
THROTTLE_WAIT - 1,
);
if (opts?.iframe && opts?.containerRef?.current) {
const iframeWindow =
opts.containerRef.current.querySelector('iframe')!.contentWindow!;
await new Promise<void>((resolve) => {
const handler = (
ev: MessageEvent<{
type: string;
value: { err: null | Error };
}>,
) => {
if (ev.data.type.startsWith('dumi.liveDemo.compileDone')) {
iframeWindow.removeEventListener('message', handler);
setError(ev.data.value.err);
resolve();
}
};
iframeWindow.addEventListener('message', handler);
iframeWindow.postMessage({
type: 'dumi.liveDemo.setSource',
value: source,
});
});
} else {
const entryFileName = Object.keys(asset.dependencies).find(
(k) => asset.dependencies[k].type === 'FILE',
)!;
// why not require?
// https://github.com/airbnb/babel-plugin-dynamic-import-node/blob/a68388870de822183218515a1adbb3e8d7fa9486/src/utils.js#L24
// if just use require, local variable will overwrite __webpack__require__ in the template method
const liveRequire = (v: string) => {
if (v in context!) return context![v];
throw new Error(`Cannot find module: ${v}`);
};
const token = (taskToken.current = Math.random());
let entryFileCode = source[entryFileName];
if (renderOpts?.compile) {
try {
entryFileCode = await renderOpts.compile(entryFileCode, {
filename: entryFileName,
});
} catch (error: any) {
setError(error);
resetLoadingStatus();
return;
}
}
if (renderOpts?.renderer && renderOpts?.compile) {
try {
const liveExports: AgnosticComponentType = {};
const liveModule = { exports: liveExports };
evalCommonJS(entryFileCode, {
exports: liveExports,
module: liveModule,
require: liveRequire,
});
const component = await getAgnosticComponentModule(liveExports);
if (renderOpts.preflight) {
await renderOpts.preflight(component);
}
setComponent(component);
setDemoNode(createElement('div', { ref }));
setError(null);
} catch (err: any) {
setError(err);
resetLoadingStatus();
}
return;
}
try {
// load renderToStaticMarkup in async way
const renderToStaticMarkupDeferred = import(
'react-dom/server'
).then(({ renderToStaticMarkup }) => renderToStaticMarkup);
// skip current task if another task is running
if (token !== taskToken.current) return;
const liveExports: { default?: ComponentType } = {};
const liveModule = { exports: liveExports };
// initial component with fake runtime
evalCommonJS(entryFileCode, {
exports: liveExports,
module: liveModule,
require: liveRequire,
});
const newDemoNode = createElement(
DemoErrorBoundary,
null,
createElement(liveExports.default!),
);
const oError = console.error;
// hijack console.error to avoid useLayoutEffect error
console.error = (...args) =>
!args[0].includes('useLayoutEffect does nothing on the server') &&
oError.apply(console, args);
// check component is able to render, to avoid show react overlay error
try {
(await renderToStaticMarkupDeferred)(newDemoNode);
} catch (err: any) {
const shouldSkipError = SHOULD_SKIP_LIVEDEMO_ERROR.some((e) =>
err.message.includes(e),
);
if (!shouldSkipError) throw err;
}
console.error = oError;
// set new demo node with passing source
setDemoNode(newDemoNode);
setError(null);
} catch (err: any) {
setError(err);
}
}
resetLoadingStatus();
},
THROTTLE_WAIT,
{ leading: true },
) as (source: Record<string, string>) => Promise<void>,
[context, asset, renderOpts],
);
return { node: demoNode, loading, error, setSource };
};