-
-
Notifications
You must be signed in to change notification settings - Fork 323
/
Copy pathreact.js
61 lines (56 loc) · 1.9 KB
/
react.js
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
export * from "$CDN/$PACKAGE";
import * as React from "$CDN/react$VERSION";
import * as ReactDOM from "$CDN/react-dom$VERSION";
export default ({ children, ...props }) => {
const [{ component }, setComponent] = React.useState({});
React.useEffect(() => {
import("$CDN/$PACKAGE").then((module) => {
// dynamically load the default export since we don't know if it's exported.
setComponent({ component: module.default });
});
});
return component
? React.createElement(component, props, ...(children || []))
: null;
};
export function bind(node, config) {
const root = ReactDOM.createRoot(node);
return {
create: (component, props, children) =>
React.createElement(component, wrapEventHandlers(props), ...children),
render: (element) => root.render(element),
unmount: () => root.unmount()
};
}
function wrapEventHandlers(props) {
const newProps = Object.assign({}, props);
for (const [key, value] of Object.entries(props)) {
if (typeof value === "function" && value.isHandler) {
newProps[key] = makeJsonSafeEventHandler(value);
}
}
return newProps;
}
function makeJsonSafeEventHandler(oldHandler) {
// Since we can't really know what the event handlers get passed we have to check if
// they are JSON serializable or not. We can allow normal synthetic events to pass
// through since the original handler already knows how to serialize those for us.
return function safeEventHandler() {
oldHandler(
...Array.from(arguments).filter((value) => {
if (typeof value === "object" && value.nativeEvent) {
// this is probably a standard React synthetic event
return true;
} else {
try {
JSON.stringify(value);
} catch (err) {
console.error("Failed to serialize some event data");
return false;
}
return true;
}
}),
);
};
}