-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
StoryRender.ts
353 lines (304 loc) · 11.5 KB
/
StoryRender.ts
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
346
347
348
349
350
351
352
353
import type {
Renderer,
RenderContext,
RenderContextCallbacks,
RenderToCanvas,
PreparedStory,
TeardownRenderToCanvas,
StoryContext,
StoryContextForLoaders,
StoryId,
StoryRenderOptions,
ViewMode,
} from '@storybook/types';
import type { Channel } from '@storybook/channels';
import {
STORY_RENDER_PHASE_CHANGED,
STORY_RENDERED,
PLAY_FUNCTION_THREW_EXCEPTION,
UNHANDLED_ERRORS_WHILE_PLAYING,
} from '@storybook/core-events';
import type { StoryStore } from '../../store';
import type { Render, RenderType } from './Render';
import { PREPARE_ABORTED } from './Render';
const { AbortController } = globalThis;
export type RenderPhase =
| 'preparing'
| 'loading'
| 'beforeEach'
| 'rendering'
| 'playing'
| 'played'
| 'completed'
| 'aborted'
| 'errored';
function serializeError(error: any) {
try {
const { name = 'Error', message = String(error), stack } = error;
return { name, message, stack };
} catch (e) {
return { name: 'Error', message: String(error) };
}
}
export class StoryRender<TRenderer extends Renderer> implements Render<TRenderer> {
public type: RenderType = 'story';
public story?: PreparedStory<TRenderer>;
public phase?: RenderPhase;
private abortController?: AbortController;
private canvasElement?: TRenderer['canvasElement'];
private notYetRendered = true;
private rerenderEnqueued = false;
public disableKeyListeners = false;
private teardownRender: TeardownRenderToCanvas = () => {};
public torndown = false;
constructor(
public channel: Channel,
public store: StoryStore<TRenderer>,
private renderToScreen: RenderToCanvas<TRenderer>,
private callbacks: RenderContextCallbacks<TRenderer>,
public id: StoryId,
public viewMode: ViewMode,
public renderOptions: StoryRenderOptions = { autoplay: true, forceInitialArgs: false },
story?: PreparedStory<TRenderer>
) {
this.abortController = new AbortController();
// Allow short-circuiting preparing if we happen to already
// have the story (this is used by docs mode)
if (story) {
this.story = story;
// TODO -- what should the phase be now?
// TODO -- should we emit the render phase changed event?
this.phase = 'preparing';
}
}
private async runPhase(signal: AbortSignal, phase: RenderPhase, phaseFn?: () => Promise<void>) {
this.phase = phase;
this.channel.emit(STORY_RENDER_PHASE_CHANGED, { newPhase: this.phase, storyId: this.id });
if (phaseFn) await phaseFn();
if (signal.aborted) {
this.phase = 'aborted';
this.channel.emit(STORY_RENDER_PHASE_CHANGED, { newPhase: this.phase, storyId: this.id });
}
}
async prepare() {
await this.runPhase((this.abortController as AbortController).signal, 'preparing', async () => {
this.story = await this.store.loadStory({ storyId: this.id });
});
if ((this.abortController as AbortController).signal.aborted) {
await this.store.cleanupStory(this.story as PreparedStory<TRenderer>);
throw PREPARE_ABORTED;
}
}
// The two story "renders" are equal and have both loaded the same story
isEqual(other: Render<TRenderer>): boolean {
return !!(
this.id === other.id &&
this.story &&
this.story === (other as StoryRender<TRenderer>).story
);
}
isPreparing() {
return ['preparing'].includes(this.phase as RenderPhase);
}
isPending() {
return ['loading', 'beforeEach', 'rendering', 'playing'].includes(this.phase as RenderPhase);
}
async renderToElement(canvasElement: TRenderer['canvasElement']) {
this.canvasElement = canvasElement;
// FIXME: this comment
// Start the first (initial) render. We don't await here because we need to return the "cleanup"
// function below right away, so if the user changes story during the first render we can cancel
// it without having to first wait for it to finish.
// Whenever the selection changes we want to force the component to be remounted.
return this.render({ initial: true, forceRemount: true });
}
private storyContext() {
if (!this.story) throw new Error(`Cannot call storyContext before preparing`);
const { forceInitialArgs } = this.renderOptions;
return this.store.getStoryContext(this.story, { forceInitialArgs });
}
async render({
initial = false,
forceRemount = false,
}: {
initial?: boolean;
forceRemount?: boolean;
} = {}) {
const { canvasElement } = this;
if (!this.story) throw new Error('cannot render when not prepared');
const story = this.story;
if (!canvasElement) throw new Error('cannot render when canvasElement is unset');
const {
id,
componentId,
title,
name,
tags,
applyLoaders,
applyBeforeEach,
unboundStoryFn,
playFunction,
} = story;
if (forceRemount && !initial) {
// NOTE: we don't check the cancel actually worked here, so the previous
// render could conceivably still be running after this call.
// We might want to change that in the future.
this.cancelRender();
this.abortController = new AbortController();
}
// We need a stable reference to the signal -- if a re-mount happens the
// abort controller may be torn down (above) before we actually check the signal.
const abortSignal = (this.abortController as AbortController).signal;
try {
let loadedContext: Awaited<ReturnType<typeof applyLoaders>>;
await this.runPhase(abortSignal, 'loading', async () => {
loadedContext = await applyLoaders({
...this.storyContext(),
viewMode: this.viewMode,
// TODO add this to CSF
canvasElement,
} as unknown as StoryContextForLoaders<TRenderer>);
});
if (abortSignal.aborted) return;
const renderStoryContext: StoryContext<TRenderer> = {
...loadedContext!,
// By this stage, it is possible that new args/globals have been received for this story
// and we need to ensure we render it with the new values
...this.storyContext(),
abortSignal,
// We should consider parameterizing the story types with TRenderer['canvasElement'] in the future
canvasElement: canvasElement as any,
};
await this.runPhase(abortSignal, 'beforeEach', async () => {
const cleanupCallbacks = await applyBeforeEach(renderStoryContext);
this.store.addCleanupCallbacks(story, cleanupCallbacks);
});
if (abortSignal.aborted) return;
const renderContext: RenderContext<TRenderer> = {
componentId,
title,
kind: title,
id,
name,
story: name,
tags,
...this.callbacks,
showError: (error) => {
this.phase = 'errored';
return this.callbacks.showError(error);
},
showException: (error) => {
this.phase = 'errored';
return this.callbacks.showException(error);
},
forceRemount: forceRemount || this.notYetRendered,
storyContext: renderStoryContext,
storyFn: () => unboundStoryFn(renderStoryContext),
unboundStoryFn,
};
await this.runPhase(abortSignal, 'rendering', async () => {
const teardown = await this.renderToScreen(renderContext, canvasElement);
this.teardownRender = teardown || (() => {});
});
this.notYetRendered = false;
if (abortSignal.aborted) return;
const ignoreUnhandledErrors =
this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors === true;
const unhandledErrors: Set<unknown> = new Set();
const onError = (event: ErrorEvent | PromiseRejectionEvent) =>
unhandledErrors.add('error' in event ? event.error : event.reason);
// The phase should be 'rendering' but it might be set to 'aborted' by another render cycle
if (this.renderOptions.autoplay && forceRemount && playFunction && this.phase !== 'errored') {
window.addEventListener('error', onError);
window.addEventListener('unhandledrejection', onError);
this.disableKeyListeners = true;
try {
await this.runPhase(abortSignal, 'playing', async () => {
await playFunction(renderContext.storyContext);
});
if (!ignoreUnhandledErrors && unhandledErrors.size > 0) {
await this.runPhase(abortSignal, 'errored');
} else {
await this.runPhase(abortSignal, 'played');
}
} catch (error) {
await this.runPhase(abortSignal, 'errored', async () => {
this.channel.emit(PLAY_FUNCTION_THREW_EXCEPTION, serializeError(error));
});
if (this.story.parameters.throwPlayFunctionExceptions !== false) throw error;
console.error(error);
}
if (!ignoreUnhandledErrors && unhandledErrors.size > 0) {
this.channel.emit(
UNHANDLED_ERRORS_WHILE_PLAYING,
Array.from(unhandledErrors).map(serializeError)
);
}
this.disableKeyListeners = false;
window.removeEventListener('unhandledrejection', onError);
window.removeEventListener('error', onError);
if (abortSignal.aborted) return;
}
await this.runPhase(abortSignal, 'completed', async () =>
this.channel.emit(STORY_RENDERED, id)
);
} catch (err) {
this.phase = 'errored';
this.callbacks.showException(err as Error);
}
// If a rerender was enqueued during the render, clear the queue and render again
if (this.rerenderEnqueued) {
this.rerenderEnqueued = false;
this.render();
}
}
/**
* Rerender the story.
* If the story is currently pending (loading/rendering), the rerender will be enqueued,
* and will be executed after the current render is completed.
* Rerendering while playing will not be enqueued, and will be executed immediately, to support
* rendering args changes while playing.
*/
async rerender() {
if (this.isPending() && this.phase !== 'playing') {
this.rerenderEnqueued = true;
} else {
return this.render();
}
}
async remount() {
await this.teardown();
return this.render({ forceRemount: true });
}
// If the story is torn down (either a new story is rendered or the docs page removes it)
// we need to consider the fact that the initial render may not be finished
// (possibly the loaders or the play function are still running). We use the controller
// as a method to abort them, ASAP, but this is not foolproof as we cannot control what
// happens inside the user's code.
cancelRender() {
this.abortController?.abort();
}
async teardown() {
this.torndown = true;
this.cancelRender();
// If the story has loaded, we need to clean up
if (this.story) {
await this.store.cleanupStory(this.story);
}
// Check if we're done loading/rendering/playing. If not, we may have to reload the page.
// Wait several ticks that may be needed to handle the abort, then try again.
// Note that there's a max of 5 nested timeouts before they're no longer "instant".
for (let i = 0; i < 3; i += 1) {
if (!this.isPending()) {
await this.teardownRender();
return;
}
await new Promise((resolve) => setTimeout(resolve, 0));
}
// If we still haven't completed, reload the page (iframe) to ensure we have a clean slate
// for the next render. Since the reload can take a brief moment to happen, we want to stop
// further rendering by awaiting a never-resolving promise (which is destroyed on reload).
window.location.reload();
await new Promise(() => {});
}
}