-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
render.tsx
151 lines (122 loc) · 3.9 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
import global from 'global';
import React, {
Component as ReactComponent,
FunctionComponent,
ReactElement,
StrictMode,
Fragment,
} from 'react';
import ReactDOM, { version as reactDomVersion } from 'react-dom';
import type { Root as ReactRoot } from 'react-dom/client';
import type { RenderContext } from '@storybook/store';
import { ArgsStoryFn } from '@storybook/csf';
import { StoryContext } from './types';
import { ReactFramework } from './types-6-0';
const { FRAMEWORK_OPTIONS } = global;
// A map of all rendered React 18 nodes
const nodes = new Map<Element, ReactRoot>();
export const render: ArgsStoryFn<ReactFramework> = (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 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(node);
setTimeout(() => {
resolve(null);
}, 0);
} else {
ReactDOM.render(node, el, () => resolve(null));
}
});
};
const canUseNewReactRootApi =
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) {
// Skipping webpack's static analysis of import paths by defining the path value outside the import statement.
// eslint-disable-next-line import/no-unresolved
const reactDomClient = await import('react-dom/client');
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 renderToDOM(
{
storyContext,
unboundStoryFn,
showMain,
showException,
forceRemount,
}: RenderContext<ReactFramework>,
domElement: HTMLElement
) {
const Story = unboundStoryFn as FunctionComponent<StoryContext<ReactFramework>>;
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(domElement);
}
await renderElement(element, domElement);
}