-
-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
render.tsx
163 lines (131 loc) · 4.25 KB
/
render.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
import { global } from '@storybook/global';
import type { FC, ReactElement } from 'react';
import React, {
Component as ReactComponent,
StrictMode,
Fragment,
useLayoutEffect,
useRef,
} from 'react';
import ReactDOM, { version as reactDomVersion } from 'react-dom';
import type { Root as ReactRoot } from 'react-dom/client';
import type { RenderContext, ArgsStoryFn } from '@storybook/types';
import type { ReactRenderer, StoryContext } from './types';
const { FRAMEWORK_OPTIONS } = global;
// A map of all rendered React 18 nodes
const nodes = new Map<Element, ReactRoot>();
export const render: ArgsStoryFn<ReactRenderer> = (args, context) => {
const { id, component: Component } = context;
if (!Component) {
throw new Error(
`Unable to render story ${id} as the component annotation is missing from the default export`
);
}
return <Component {...args} />;
};
const WithCallback: FC<{ callback: () => void; children: ReactElement }> = ({
callback,
children,
}) => {
// See https://github.com/reactwg/react-18/discussions/5#discussioncomment-2276079
const once = useRef<() => void>();
useLayoutEffect(() => {
if (once.current === callback) return;
once.current = callback;
callback();
}, [callback]);
return children;
};
const renderElement = async (node: ReactElement, el: Element) => {
// Create Root Element conditionally for new React 18 Root Api
const root = await getReactRoot(el);
return new Promise((resolve) => {
if (root) {
root.render(<WithCallback callback={() => resolve(null)}>{node}</WithCallback>);
} else {
ReactDOM.render(node, el, () => resolve(null));
}
});
};
const canUseNewReactRootApi =
reactDomVersion && (reactDomVersion.startsWith('18') || reactDomVersion.startsWith('0.0.0'));
const shouldUseNewRootApi = FRAMEWORK_OPTIONS?.legacyRootApi !== true;
const isUsingNewReactRootApi = shouldUseNewRootApi && canUseNewReactRootApi;
const unmountElement = (el: Element) => {
const root = nodes.get(el);
if (root && isUsingNewReactRootApi) {
root.unmount();
nodes.delete(el);
} else {
ReactDOM.unmountComponentAtNode(el);
}
};
const getReactRoot = async (el: Element): Promise<ReactRoot | null> => {
if (!isUsingNewReactRootApi) {
return null;
}
let root = nodes.get(el);
if (!root) {
// eslint-disable-next-line import/no-unresolved
const reactDomClient = (await import('react-dom/client')).default;
root = reactDomClient.createRoot(el);
nodes.set(el, root);
}
return root;
};
class ErrorBoundary extends ReactComponent<{
showException: (err: Error) => void;
showMain: () => void;
}> {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidMount() {
const { hasError } = this.state;
const { showMain } = this.props;
if (!hasError) {
showMain();
}
}
componentDidCatch(err: Error) {
const { showException } = this.props;
// message partially duplicates stack, strip it
showException(err);
}
render() {
const { hasError } = this.state;
const { children } = this.props;
return hasError ? null : children;
}
}
const Wrapper = FRAMEWORK_OPTIONS?.strictMode ? StrictMode : Fragment;
export async function renderToCanvas(
{
storyContext,
unboundStoryFn,
showMain,
showException,
forceRemount,
}: RenderContext<ReactRenderer>,
canvasElement: ReactRenderer['canvasElement']
) {
const Story = unboundStoryFn as FC<StoryContext<ReactRenderer>>;
const content = (
<ErrorBoundary showMain={showMain} showException={showException}>
<Story {...storyContext} />
</ErrorBoundary>
);
// For React 15, StrictMode & Fragment doesn't exists.
const element = Wrapper ? <Wrapper>{content}</Wrapper> : content;
// In most cases, we need to unmount the existing set of components in the DOM node.
// Otherwise, React may not recreate instances for every story run.
// This could leads to issues like below:
// https://github.com/storybookjs/react-storybook/issues/81
// (This is not the case when we change args or globals to the story however)
if (forceRemount) {
unmountElement(canvasElement);
}
await renderElement(element, canvasElement);
return () => unmountElement(canvasElement);
}