/
StoryRenderer.tsx
345 lines (291 loc) · 10.3 KB
/
StoryRenderer.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import React from 'react';
import ReactDOM from 'react-dom';
import global from 'global';
import AnsiToHtml from 'ansi-to-html';
import dedent from 'ts-dedent';
import { StoryId, StoryKind, StoryFn, ViewMode, Channel } from '@storybook/addons';
import Events from '@storybook/core-events';
import { logger } from '@storybook/client-logger';
import { StoryStore } from '@storybook/client-api';
import { NoDocs } from './NoDocs';
import { RenderStoryFunction, RenderContextWithoutStoryContext } from './types';
const { document, FEATURES = {} } = global;
// We have "changed" story if this changes
interface RenderMetadata {
id: StoryId;
kind: StoryKind;
viewMode: ViewMode;
getDecorated: () => StoryFn<any>;
}
const layoutClassMap = {
centered: 'sb-main-centered',
fullscreen: 'sb-main-fullscreen',
padded: 'sb-main-padded',
} as const;
type Layout = keyof typeof layoutClassMap | 'none';
const classes = {
MAIN: 'sb-show-main',
NOPREVIEW: 'sb-show-nopreview',
ERROR: 'sb-show-errordisplay',
};
const ansiConverter = new AnsiToHtml({
escapeXML: true,
});
/**
* StoryRenderer is responsible for rendering the correct story to the screen
*
* It is very much concerned with drawing to the screen and will do things like change classes
* on the body etc.
*/
export class StoryRenderer {
render: RenderStoryFunction;
channel?: Channel;
storyStore: StoryStore;
previousMetadata?: RenderMetadata;
previousLayoutClass?: typeof layoutClassMap[keyof typeof layoutClassMap] | null;
constructor({
render,
channel,
storyStore,
}: {
render: RenderStoryFunction;
channel?: Channel;
storyStore: StoryStore;
}) {
this.render = render;
this.channel = channel;
this.storyStore = storyStore;
this.setupListeners();
}
setupListeners() {
// Channel can be null in StoryShots
if (this.channel) {
this.channel.on(Events.CURRENT_STORY_WAS_SET, () => this.renderCurrentStory(false));
this.channel.on(Events.STORY_ARGS_UPDATED, () => this.forceReRender());
this.channel.on(Events.GLOBALS_UPDATED, () => this.forceReRender());
this.channel.on(Events.FORCE_RE_RENDER, () => this.forceReRender());
}
}
forceReRender() {
this.renderCurrentStory(true);
}
async renderCurrentStory(forceRender: boolean) {
const { storyStore } = this;
const loadError = storyStore.getError();
if (loadError) {
this.showErrorDisplay(loadError);
return;
}
const { storyId, viewMode: urlViewMode } = storyStore.getSelection() || {};
const data = storyStore.fromId(storyId);
const { kind, id, parameters = {}, getDecorated } = data || {};
const { docsOnly, layout } = parameters;
const metadata: RenderMetadata = {
id,
kind,
viewMode: docsOnly ? 'docs' : urlViewMode,
getDecorated,
};
this.applyLayout(metadata.viewMode === 'docs' ? 'fullscreen' : layout);
const context: RenderContextWithoutStoryContext = {
id: storyId, // <- in case data is null, at least we'll know what we tried to render
...data,
forceRender,
showMain: () => this.showMain(),
showError: ({ title, description }: { title: string; description: string }) =>
this.renderError({ title, description }),
showException: (err: Error) => this.renderException(err),
};
await this.renderStoryIfChanged({ metadata, context });
}
async renderStoryIfChanged({
metadata,
context,
}: {
metadata: RenderMetadata;
context: RenderContextWithoutStoryContext;
}) {
const { forceRender, name } = context;
const { previousMetadata, storyStore } = this;
const storyChanged = !previousMetadata || previousMetadata.id !== metadata.id;
// getDecorated is a function that returns a decorated story function. It'll change whenever the story
// is reloaded into the store, which means the module the story was defined in was HMR-ed.
const implementationChanged =
!previousMetadata || previousMetadata.getDecorated !== metadata.getDecorated;
const viewModeChanged = !previousMetadata || previousMetadata.viewMode !== metadata.viewMode;
const kindChanged = !previousMetadata || previousMetadata.kind !== metadata.kind;
// Don't re-render the story if nothing has changed to justify it
if (!forceRender && !storyChanged && !implementationChanged && !viewModeChanged) {
this.channel.emit(Events.STORY_UNCHANGED, {
...metadata,
name,
});
return;
}
// If we are rendering something new (as opposed to re-rendering the same or first story), emit
if (previousMetadata && (storyChanged || kindChanged || viewModeChanged)) {
this.channel.emit(Events.STORY_CHANGED, metadata.id);
}
switch (previousMetadata ? previousMetadata.viewMode : 'story') {
case 'docs':
if (kindChanged || viewModeChanged) {
this.storyStore.cleanHooksForKind(previousMetadata.kind);
ReactDOM.unmountComponentAtNode(document.getElementById('docs-root'));
}
break;
case 'story':
default:
if (previousMetadata && (storyChanged || viewModeChanged)) {
this.storyStore.cleanHooks(previousMetadata.id);
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
}
}
// Docs view renders into a different root ID to avoid conflicts
// with the user's view layer. Therefore we need to clean up whenever
// we transition between view modes
if (viewModeChanged) {
switch (metadata.viewMode) {
case 'docs': {
this.showMain();
this.showDocs();
break;
}
case 'story':
default: {
if (previousMetadata) {
this.showStory();
}
}
}
}
// Given a cleaned up state, render the appropriate view mode
switch (metadata.viewMode) {
case 'docs': {
this.renderDocs({ context, storyStore });
break;
}
case 'story':
default: {
await this.renderStory({ context });
break;
}
}
this.previousMetadata = metadata;
if (!forceRender && metadata.viewMode !== 'docs') {
document.documentElement.scrollTop = 0;
document.documentElement.scrollLeft = 0;
}
}
applyLayout(layout: Layout = 'padded') {
if (layout === 'none') {
document.body.classList.remove(this.previousLayoutClass);
this.previousLayoutClass = null;
return;
}
this.checkIfLayoutExists(layout);
const layoutClass = layoutClassMap[layout];
document.body.classList.remove(this.previousLayoutClass);
document.body.classList.add(layoutClass);
this.previousLayoutClass = layoutClass;
}
checkIfLayoutExists(layout: keyof typeof layoutClassMap) {
if (!layoutClassMap[layout]) {
logger.warn(
dedent`The desired layout: ${layout} is not a valid option.
The possible options are: ${Object.keys(layoutClassMap).join(', ')}, none.`
);
}
}
showErrorDisplay({ message = '', stack = '' }) {
document.getElementById('error-message').innerHTML = ansiConverter.toHtml(message);
document.getElementById('error-stack').innerHTML = ansiConverter.toHtml(stack);
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.add(classes.ERROR);
}
showNoPreview() {
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.NOPREVIEW);
}
showMain() {
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.MAIN);
}
showDocs() {
document.getElementById('root').setAttribute('hidden', 'true');
document.getElementById('docs-root').removeAttribute('hidden');
}
showStory() {
document.getElementById('docs-root').setAttribute('hidden', 'true');
document.getElementById('root').removeAttribute('hidden');
}
async renderStory({
context,
context: { id, getDecorated },
}: {
context: RenderContextWithoutStoryContext;
}) {
if (getDecorated) {
try {
const { applyLoaders, runPlayFunction, unboundStoryFn, forceRender } = context;
const storyContext = await applyLoaders();
const storyFn = () => unboundStoryFn(storyContext);
await this.render({ ...context, storyContext, storyFn });
if (FEATURES.previewCsfV3 && !forceRender) {
await runPlayFunction();
}
this.channel.emit(Events.STORY_RENDERED, id);
} catch (err) {
this.renderException(err);
}
} else {
this.showNoPreview();
this.channel.emit(Events.STORY_MISSING, id);
}
}
renderDocs({
context,
storyStore,
}: {
context: RenderContextWithoutStoryContext;
storyStore: StoryStore;
}) {
const { kind, parameters, id } = context;
if (id === '*' || !parameters) {
return;
}
const docs = parameters.docs || {};
if (docs.page && !docs.container) {
throw new Error('No `docs.container` set, did you run `addon-docs/preset`?');
}
const DocsContainer =
docs.container || (({ children }: { children: Element }) => <>{children}</>);
const Page = docs.page || NoDocs;
// Docs context includes the storyStore. Probably it would be better if it didn't but that can be fixed in a later refactor
ReactDOM.render(
<DocsContainer context={{ storyStore, ...context }}>
<Page />
</DocsContainer>,
document.getElementById('docs-root'),
() => this.channel.emit(Events.DOCS_RENDERED, kind)
);
}
// renderException is used if we fail to render the story and it is uncaught by the app layer
renderException(err: Error) {
this.channel.emit(Events.STORY_THREW_EXCEPTION, err);
this.showErrorDisplay(err);
// Log the stack to the console. So, user could check the source code.
logger.error(err);
}
// renderError is used by the various app layers to inform the user they have done something
// wrong -- for instance returned the wrong thing from a story
renderError({ title, description }: { title: string; description: string }) {
this.channel.emit(Events.STORY_ERRORED, { title, description });
this.showErrorDisplay({
message: title,
stack: description,
});
}
}