-
-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
Story.tsx
223 lines (195 loc) · 6.8 KB
/
Story.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
import React, {
FunctionComponent,
ReactNode,
ElementType,
ComponentProps,
useContext,
useRef,
useEffect,
useState,
} from 'react';
import { MDXProvider } from '@mdx-js/react';
import global from 'global';
import { resetComponents, Story as PureStory, StorySkeleton } from '@storybook/components';
import { StoryId, toId, storyNameFromExport, StoryAnnotations, AnyFramework } from '@storybook/csf';
import { Story as StoryType } from '@storybook/store';
import { addons } from '@storybook/addons';
import Events from '@storybook/core-events';
import { CURRENT_SELECTION } from './types';
import { DocsContext, DocsContextProps } from './DocsContext';
import { useStory } from './useStory';
export const storyBlockIdFromId = (storyId: string) => `story--${storyId}`;
type PureStoryProps = ComponentProps<typeof PureStory>;
type CommonProps = StoryAnnotations & {
height?: string;
inline?: boolean;
};
type StoryDefProps = {
name: string;
children: ReactNode;
};
type StoryRefProps = {
id?: string;
};
type StoryImportProps = {
name: string;
story: ElementType;
};
export type StoryProps = (StoryDefProps | StoryRefProps | StoryImportProps) & CommonProps;
export const lookupStoryId = (
storyName: string,
{ mdxStoryNameToKey, mdxComponentAnnotations }: DocsContextProps
) =>
toId(
mdxComponentAnnotations.id || mdxComponentAnnotations.title,
storyNameFromExport(mdxStoryNameToKey[storyName])
);
export const getStoryId = (props: StoryProps, context: DocsContextProps): StoryId => {
const { id } = props as StoryRefProps;
const { name } = props as StoryDefProps;
const inputId = id === CURRENT_SELECTION ? context.id : id;
return inputId || lookupStoryId(name, context);
};
export const getStoryProps = <TFramework extends AnyFramework>(
{ height, inline }: StoryProps,
story: StoryType<TFramework>,
context: DocsContextProps<TFramework>,
onStoryFnCalled: () => void
): PureStoryProps => {
const { name: storyName, parameters } = story;
const { docs = {} } = parameters;
if (docs.disable) {
return null;
}
// prefer block props, then story parameters defined by the framework-specific settings and optionally overridden by users
const { inlineStories = false, iframeHeight = 100, prepareForInline } = docs;
const storyIsInline = typeof inline === 'boolean' ? inline : inlineStories;
if (storyIsInline && !prepareForInline) {
throw new Error(
`Story '${storyName}' is set to render inline, but no 'prepareForInline' function is implemented in your docs configuration!`
);
}
const boundStoryFn = () => {
const storyResult = story.unboundStoryFn({
...context.getStoryContext(story),
loaded: {},
abortSignal: undefined,
canvasElement: undefined,
});
// We need to wait until the bound story function has actually been called before we
// consider the story rendered. Certain frameworks (i.e. angular) don't actually render
// the component in the very first react render cycle, and so we can't just wait until the
// `PureStory` component has been rendered to consider the underlying story "rendered".
onStoryFnCalled();
return storyResult;
};
return {
inline: storyIsInline,
id: story.id,
height: height || (storyIsInline ? undefined : iframeHeight),
title: storyName,
...(storyIsInline && {
parameters,
storyFn: () => prepareForInline(boundStoryFn, context.getStoryContext(story)),
}),
};
};
function makeGate(): [Promise<void>, () => void] {
let open;
const gate = new Promise<void>((r) => {
open = r;
});
return [gate, open];
}
const Story: FunctionComponent<StoryProps> = (props) => {
const context = useContext(DocsContext);
const channel = addons.getChannel();
const storyRef = useRef();
const storyId = getStoryId(props, context);
const story = useStory(storyId, context);
const [showLoader, setShowLoader] = useState(true);
useEffect(() => {
let cleanup: () => void;
if (story && storyRef.current) {
const { componentId, id, title, name } = story;
const renderContext = {
componentId,
title,
kind: title,
id,
name,
story: name,
// TODO what to do when these fail?
showMain: () => {},
showError: () => {},
showException: () => {},
};
cleanup = context.renderStoryToElement({
story,
renderContext,
element: storyRef.current as HTMLElement,
});
setShowLoader(false);
}
return () => cleanup && cleanup();
}, [story]);
const [storyFnRan, onStoryFnRan] = makeGate();
const [rendered, onRendered] = makeGate();
useEffect(onRendered);
// If we are rendering a old-style inline Story via `PureStory` below, we want to emit
// the `STORY_RENDERED` event when it renders. The modern mode below calls out to
// `Preview.renderStoryToDom()` which itself emits the event.
if (story && !global?.FEATURES?.modernInlineRender) {
// We need to wait for two things before we can consider the story rendered:
// (a) React's `useEffect` hook needs to fire. This is needed for React stories, as
// decorators of the form `<A><B/></A>` will not actually execute `B` in the first
// call to the story function.
// (b) The story function needs to acutally have been called.
// Certain frameworks (i.e.angular) don't actually render the component in the very first
// React render cycle, so we need to wait for the framework to actually do that
Promise.all([storyFnRan, rendered]).then(() => {
console.log('called story fn', story.id);
channel.emit(Events.STORY_RENDERED, storyId);
});
}
if (!story) {
return <StorySkeleton />;
}
const storyProps = getStoryProps(props, story, context, onStoryFnRan);
if (!storyProps) {
return null;
}
if (global?.FEATURES?.modernInlineRender) {
// We do this so React doesn't complain when we replace the span in a secondary render
const htmlContents = `<span></span>`;
// FIXME: height/style/etc. lifted from PureStory
const { height } = storyProps;
return (
<div id={storyBlockIdFromId(story.id)}>
<MDXProvider components={resetComponents}>
{height ? (
<style>{`#story--${story.id} { min-height: ${height}; transform: translateZ(0); overflow: auto }`}</style>
) : null}
{showLoader && <StorySkeleton />}
<div
ref={storyRef}
data-name={story.name}
dangerouslySetInnerHTML={{ __html: htmlContents }}
/>
</MDXProvider>
</div>
);
}
return (
<div id={storyBlockIdFromId(story.id)}>
<MDXProvider components={resetComponents}>
<PureStory {...storyProps} />
</MDXProvider>
</div>
);
};
Story.defaultProps = {
children: null,
name: null,
};
export { Story };