-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
jsxDecorator.tsx
269 lines (233 loc) · 8.75 KB
/
jsxDecorator.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
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
/* eslint-disable no-underscore-dangle */
import type { ReactElement, ReactNode } from 'react';
import React, { isValidElement, createElement } from 'react';
import type { Options } from 'react-element-to-jsx-string';
import reactElementToJSXString from 'react-element-to-jsx-string';
import { addons, useEffect } from '@storybook/preview-api';
import type { StoryContext, ArgsStoryFn, PartialStoryFn } from '@storybook/types';
import { SourceType, SNIPPET_RENDERED, getDocgenSection } from '@storybook/docs-tools';
import { logger } from '@storybook/client-logger';
import { isMemo, isForwardRef } from './lib';
import type { ReactRenderer } from '../types';
const toPascalCase = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
/**
* Converts a React symbol to a React-like displayName
*
* Symbols come from here
* https://github.com/facebook/react/blob/338dddc089d5865761219f02b5175db85c54c489/packages/react-devtools-shared/src/backend/ReactSymbols.js
*
* E.g.
* Symbol(react.suspense) -> React.Suspense
* Symbol(react.strict_mode) -> React.StrictMode
* Symbol(react.server_context.defaultValue) -> React.ServerContext.DefaultValue
*
* @param {Symbol} elementType - The symbol to convert
* @returns {string | null} A displayName for the Symbol in case elementType is a Symbol; otherwise, null.
*/
export const getReactSymbolName = (elementType: any): string => {
const elementName = elementType.$$typeof || elementType;
const symbolDescription: string = elementName.toString().replace(/^Symbol\((.*)\)$/, '$1');
const reactComponentName = symbolDescription
.split('.')
.map((segment) => {
// Split segment by underscore to handle cases like 'strict_mode' separately, and PascalCase them
return segment.split('_').map(toPascalCase).join('');
})
.join('.');
return reactComponentName;
};
// Recursively remove "_owner" property from elements to avoid crash on docs page when passing components as an array prop (#17482)
// Note: It may be better to use this function only in development environment.
function simplifyNodeForStringify(node: ReactNode): ReactNode {
if (isValidElement(node)) {
const props = Object.keys(node.props).reduce<{ [key: string]: any }>((acc, cur) => {
acc[cur] = simplifyNodeForStringify(node.props[cur]);
return acc;
}, {});
return {
...node,
props,
// @ts-expect-error (this is an internal or removed api)
_owner: null,
};
}
if (Array.isArray(node)) {
return node.map(simplifyNodeForStringify);
}
return node;
}
type JSXOptions = Options & {
/** How many wrappers to skip when rendering the jsx */
skip?: number;
/** Whether to show the function in the jsx tab */
showFunctions?: boolean;
/** Whether to format HTML or Vue markup */
enableBeautify?: boolean;
/** Override the display name used for a component */
displayName?: string | Options['displayName'];
};
/** Apply the users parameters and render the jsx for a story */
export const renderJsx = (code: React.ReactElement, options?: JSXOptions) => {
if (typeof code === 'undefined') {
logger.warn('Too many skip or undefined component');
return null;
}
let renderedJSX = code;
const Type = renderedJSX.type;
// @ts-expect-error (Converted from ts-ignore)
for (let i = 0; i < options?.skip; i += 1) {
if (typeof renderedJSX === 'undefined') {
logger.warn('Cannot skip undefined element');
return null;
}
if (React.Children.count(renderedJSX) > 1) {
logger.warn('Trying to skip an array of elements');
return null;
}
if (typeof renderedJSX.props.children === 'undefined') {
logger.warn('Not enough children to skip elements.');
if (typeof renderedJSX.type === 'function' && renderedJSX.type.name === '') {
renderedJSX = <Type {...renderedJSX.props} />;
}
} else if (typeof renderedJSX.props.children === 'function') {
renderedJSX = renderedJSX.props.children();
} else {
renderedJSX = renderedJSX.props.children;
}
}
let displayNameDefaults;
if (typeof options?.displayName === 'string') {
displayNameDefaults = { showFunctions: true, displayName: () => options.displayName };
/**
* add `renderedJSX?.type`to handle this case:
*
* https://github.com/zhyd1997/storybook/blob/20863a75ba4026d7eba6b288991a2cf091d4dfff/code/renderers/react/template/stories/errors.stories.tsx#L14
*
* or it show the error message when run `yarn build-storybook --quiet`:
*
* Cannot read properties of undefined (reading '__docgenInfo').
*/
} else {
displayNameDefaults = {
// To get exotic component names resolving properly
displayName: (el: any): string => {
if (el.type.displayName) {
return el.type.displayName;
} else if (getDocgenSection(el.type, 'displayName')) {
return getDocgenSection(el.type, 'displayName');
} else if (el.type.render?.displayName) {
return el.type.render.displayName;
} else if (
typeof el.type === 'symbol' ||
(el.type.$$typeof && typeof el.type.$$typeof === 'symbol')
) {
return getReactSymbolName(el.type);
} else if (el.type.name && el.type.name !== '_default') {
return el.type.name;
} else if (typeof el.type === 'function') {
return 'No Display Name';
} else if (isForwardRef(el.type)) {
return el.type.render.name;
} else if (isMemo(el.type)) {
return el.type.type.name;
} else {
return el.type;
}
},
};
}
const filterDefaults = {
filterProps: (value: any, key: string): boolean => value !== undefined,
};
const opts = {
...displayNameDefaults,
...filterDefaults,
...options,
};
const result = React.Children.map(code, (c) => {
// @ts-expect-error FIXME: workaround react-element-to-jsx-string
const child = typeof c === 'number' ? c.toString() : c;
const toJSXString =
typeof reactElementToJSXString === 'function'
? reactElementToJSXString
: // @ts-expect-error (Converted from ts-ignore)
reactElementToJSXString.default;
let string: string = toJSXString(simplifyNodeForStringify(child), opts as Options);
if (string.indexOf('"') > -1) {
const matches = string.match(/\S+=\\"([^"]*)\\"/g);
if (matches) {
matches.forEach((match) => {
string = string.replace(match, match.replace(/"/g, "'"));
});
}
}
return string;
}).join('\n');
return result.replace(/function\s+noRefCheck\(\)\s*\{\}/g, '() => {}');
};
const defaultOpts = {
skip: 0,
showFunctions: false,
enableBeautify: true,
showDefaultProps: false,
};
export const skipJsxRender = (context: StoryContext<ReactRenderer>) => {
const sourceParams = context?.parameters.docs?.source;
const isArgsStory = context?.parameters.__isArgsStory;
// always render if the user forces it
if (sourceParams?.type === SourceType.DYNAMIC) {
return false;
}
// never render if the user is forcing the block to render code, or
// if the user provides code, or if it's not an args story.
return !isArgsStory || sourceParams?.code || sourceParams?.type === SourceType.CODE;
};
const isMdx = (node: any) => node.type?.displayName === 'MDXCreateElement' && !!node.props?.mdxType;
const mdxToJsx = (node: any) => {
if (!isMdx(node)) return node;
const { mdxType, originalType, children, ...rest } = node.props;
let jsxChildren = [] as ReactElement[];
if (children) {
const array = Array.isArray(children) ? children : [children];
jsxChildren = array.map(mdxToJsx);
}
return createElement(originalType, rest, ...jsxChildren);
};
export const jsxDecorator = (
storyFn: PartialStoryFn<ReactRenderer>,
context: StoryContext<ReactRenderer>
) => {
const channel = addons.getChannel();
const skip = skipJsxRender(context);
let jsx = '';
useEffect(() => {
if (!skip) {
const { id, unmappedArgs } = context;
channel.emit(SNIPPET_RENDERED, {
id,
source: jsx,
args: unmappedArgs,
});
}
});
const story = storyFn();
// We only need to render JSX if the source block is actually going to
// consume it. Otherwise it's just slowing us down.
if (skip) {
return story;
}
const options = {
...defaultOpts,
...(context?.parameters.jsx || {}),
} as Required<JSXOptions>;
// Exclude decorators from source code snippet by default
const storyJsx = context?.parameters.docs?.source?.excludeDecorators
? (context.originalStoryFn as ArgsStoryFn<ReactRenderer>)(context.args, context)
: story;
const sourceJsx = mdxToJsx(storyJsx);
const rendered = renderJsx(sourceJsx, options);
if (rendered) {
jsx = rendered;
}
return story;
};