/
start.js
474 lines (416 loc) · 14.6 KB
/
start.js
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import { navigator, window, document } from 'global';
import React from 'react';
import ReactDOM from 'react-dom';
import deprecate from 'util-deprecate';
import AnsiToHtml from 'ansi-to-html';
import addons from '@storybook/addons';
import createChannel from '@storybook/channel-postmessage';
import { ClientApi, StoryStore, ConfigApi } from '@storybook/client-api';
import { toId, storyNameFromExport } from '@storybook/router/utils';
import { logger } from '@storybook/client-logger';
import Events from '@storybook/core-events';
import { initializePath, setPath } from './url';
import { NoDocs } from './NoDocs';
const ansiConverter = new AnsiToHtml();
const classes = {
MAIN: 'sb-show-main',
NOPREVIEW: 'sb-show-nopreview',
ERROR: 'sb-show-errordisplay',
};
function matches(storyKey, arrayOrRegex) {
if (Array.isArray(arrayOrRegex)) {
return arrayOrRegex.includes(storyKey);
}
return storyKey.match(arrayOrRegex);
}
export function isExportStory(key, { includeStories, excludeStories }) {
return (
// https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
key !== '__esModule' &&
(!includeStories || matches(key, includeStories)) &&
(!excludeStories || !matches(key, excludeStories))
);
}
function showMain() {
document.body.classList.remove(classes.NOPREVIEW);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.MAIN);
}
function showNopreview() {
document.body.classList.remove(classes.MAIN);
document.body.classList.remove(classes.ERROR);
document.body.classList.add(classes.NOPREVIEW);
}
function 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);
}
// showError 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
function showError({ title, description }) {
addons.getChannel().emit(Events.STORY_ERRORED, { title, description });
showErrorDisplay({
message: title,
stack: description,
});
}
// showException is used if we fail to render the story and it is uncaught by the app layer
function showException(exception) {
addons.getChannel().emit(Events.STORY_THREW_EXCEPTION, exception);
showErrorDisplay(exception);
// Log the stack to the console. So, user could check the source code.
logger.error(exception);
}
const isBrowser =
navigator &&
navigator.userAgent &&
navigator.userAgent !== 'storyshots' &&
!(navigator.userAgent.indexOf('Node.js') > -1) &&
!(navigator.userAgent.indexOf('jsdom') > -1);
export const getContext = (() => {
let cache;
return decorateStory => {
if (cache) {
return cache;
}
let channel = null;
if (isBrowser) {
try {
channel = addons.getChannel();
} catch (e) {
channel = createChannel({ page: 'preview' });
addons.setChannel(channel);
}
}
let storyStore;
let clientApi;
if (typeof window !== 'undefined' && window.__STORYBOOK_CLIENT_API__) {
clientApi = window.__STORYBOOK_CLIENT_API__;
// eslint-disable-next-line no-underscore-dangle
storyStore = clientApi._storyStore;
} else {
storyStore = new StoryStore({ channel });
clientApi = new ClientApi({ storyStore, decorateStory });
}
const { clearDecorators } = clientApi;
const configApi = new ConfigApi({ clearDecorators, storyStore, channel, clientApi });
return {
configApi,
storyStore,
channel,
clientApi,
showMain,
showError,
showException,
};
};
})();
function focusInInput(event) {
return (
/input|textarea/i.test(event.target.tagName) ||
event.target.getAttribute('contenteditable') !== null
);
}
export default function start(render, { decorateStory } = {}) {
const context = getContext(decorateStory);
const { clientApi, channel, configApi, storyStore } = context;
// Provide access to external scripts if `window` is defined.
// NOTE this is different to isBrowser, primarily for the JSDOM use case
let previousKind = '';
let previousStory = '';
let previousRevision = -1;
let previousViewMode = '';
let previousId = null;
const renderMain = forceRender => {
const revision = storyStore.getRevision();
const loadError = storyStore.getError();
const { storyId, viewMode: urlViewMode } = storyStore.getSelection();
const data = storyStore.fromId(storyId);
const { kind, name, getDecorated, id, parameters, error } = data || {};
const viewMode = parameters && parameters.docsOnly ? 'docs' : urlViewMode;
const renderContext = {
...context,
...data,
selectedKind: kind,
selectedStory: name,
parameters,
forceRender,
};
if (loadError || error) {
showErrorDisplay(loadError || error);
return;
}
// Render story only if selectedKind or selectedStory have changed.
// However, we DO want the story to re-render if the store itself has changed
// (which happens at the moment when HMR occurs)
if (
!forceRender &&
revision === previousRevision &&
viewMode === previousViewMode &&
kind === previousKind &&
name === previousStory
) {
addons.getChannel().emit(Events.STORY_UNCHANGED, {
id,
revision,
kind,
name,
viewMode,
});
return;
}
if (!forceRender && previousKind && previousStory) {
addons.getChannel().emit(Events.STORY_CHANGED, id);
}
switch (previousViewMode) {
case 'docs':
if (previousKind != null && (kind !== previousKind || viewMode !== previousViewMode)) {
storyStore.cleanHooksForKind(previousKind);
ReactDOM.unmountComponentAtNode(document.getElementById('docs-root'));
}
break;
case 'story':
default:
if (previousId != null && (id !== previousId || viewMode !== previousViewMode)) {
storyStore.cleanHooks(previousId);
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 (viewMode !== previousViewMode) {
switch (viewMode) {
case 'docs': {
showMain();
document.getElementById('root').setAttribute('hidden', true);
document.getElementById('docs-root').removeAttribute('hidden');
break;
}
case 'story':
default: {
if (previousViewMode === 'docs') {
document.getElementById('docs-root').setAttribute('hidden', true);
document.getElementById('root').removeAttribute('hidden');
}
}
}
}
// Given a cleaned up state, render the appropriate view mode
switch (viewMode) {
case 'docs': {
const docs = (parameters && parameters.docs) || {};
// eslint-disable-next-line react/prop-types
const DocsContainer = docs.container || (({ children }) => <>{children}</>);
const Page = docs.page || NoDocs;
ReactDOM.render(
<DocsContainer context={renderContext}>
<Page />
</DocsContainer>,
document.getElementById('docs-root'),
() => addons.getChannel().emit(Events.DOCS_RENDERED, kind)
);
break;
}
case 'story':
default: {
if (getDecorated) {
(async () => {
try {
await render(renderContext);
addons.getChannel().emit(Events.STORY_RENDERED, id);
} catch (ex) {
showException(ex);
}
})();
} else {
showNopreview();
addons.getChannel().emit(Events.STORY_MISSING, id);
}
break;
}
}
previousRevision = revision;
previousKind = kind;
previousStory = name;
previousViewMode = viewMode;
previousId = id;
if (!forceRender && viewMode !== 'docs') {
document.documentElement.scrollTop = 0;
document.documentElement.scrollLeft = 0;
}
};
// initialize the UI
const renderUI = forceRender => {
if (isBrowser) {
try {
renderMain(forceRender);
} catch (ex) {
showException(ex);
}
}
};
const forceReRender = () => renderUI(true);
// channel can be null in NodeJS
if (isBrowser) {
const deprecatedToId = deprecate(
toId,
`Passing name+kind to the SET_CURRENT_STORY event is deprecated, use a storyId instead`
);
channel.on(Events.FORCE_RE_RENDER, forceReRender);
channel.on(Events.SET_CURRENT_STORY, ({ storyId: inputStoryId, name, kind, viewMode }) => {
let storyId = inputStoryId;
// For backwards compatibility
if (!storyId) {
if (!name || !kind) {
throw new Error('You should pass `storyId` into SET_CURRENT_STORY');
}
storyId = deprecatedToId(kind, name);
}
storyStore.setSelection({ storyId, viewMode });
setPath({ storyId, viewMode });
});
// Handle keyboard shortcuts
window.onkeydown = event => {
if (!focusInInput(event)) {
// We have to pick off the keys of the event that we need on the other side
const { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode } = event;
channel.emit(Events.PREVIEW_KEYDOWN, {
event: { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode },
});
}
};
}
storyStore.on(Events.STORY_INIT, () => {
const { storyId, viewMode } = initializePath();
storyStore.setSelection({ storyId, viewMode });
});
storyStore.on(Events.STORY_RENDER, renderUI);
if (typeof window !== 'undefined') {
window.__STORYBOOK_CLIENT_API__ = clientApi;
window.__STORYBOOK_STORY_STORE__ = storyStore;
window.__STORYBOOK_ADDONS_CHANNEL__ = channel; // may not be defined
}
let previousExports = new Map();
const loadStories = (loadable, framework) => () => {
// Make sure we don't try to define a kind more than once within the same load
const loadedKinds = new Set();
let reqs = null;
if (Array.isArray(loadable)) {
reqs = loadable;
} else if (loadable.keys) {
reqs = [loadable];
}
let currentExports = new Map();
if (reqs) {
reqs.forEach(req => {
req.keys().forEach(filename => {
const fileExports = req(filename);
currentExports.set(
fileExports,
typeof req.resolve === 'function' ? req.resolve(filename) : null
);
});
});
} else {
const exported = loadable();
if (Array.isArray(exported) && !exported.find(obj => !obj.default)) {
currentExports = new Map(exported.map(fileExports => [fileExports, null]));
} else if (exported) {
logger.warn(
`Loader function passed to 'configure' should return void or an array of module exports that all contain a 'default' export. Received: ${JSON.stringify(
exported
)}`
);
}
}
const removed = [...previousExports.keys()].filter(exp => !currentExports.has(exp));
removed.forEach(exp => {
if (exp.default) {
storyStore.removeStoryKind(exp.default.title);
}
});
if (removed.length > 0) {
storyStore.incrementRevision();
}
const added = [...currentExports.keys()].filter(exp => !previousExports.has(exp));
added.forEach(fileExports => {
// An old-style story file
if (!fileExports.default) {
return;
}
if (!fileExports.default.title) {
throw new Error(
`Unexpected default export without title: ${JSON.stringify(fileExports.default)}`
);
}
const { default: meta, ...exports } = fileExports;
const { title: kindName, parameters: params, decorators: decos, component } = meta;
if (loadedKinds.has(kindName)) {
throw new Error(
`Duplicate title '${kindName}' used in multiple files; use unique titles or combine '${kindName}' stories into a single file.`
);
}
loadedKinds.add(kindName);
// We pass true here to avoid the warning about HMR. It's cool clientApi, we got this
const kind = clientApi.storiesOf(kindName, true);
// we should always have a framework, rest optional
kind.addParameters({
framework,
component,
fileName: currentExports.get(fileExports),
...params,
});
(decos || []).forEach(decorator => {
kind.addDecorator(decorator);
});
Object.keys(exports).forEach(key => {
if (isExportStory(key, meta)) {
const storyFn = exports[key];
const { name, parameters, decorators } = storyFn.story || {};
if (parameters && parameters.decorators) {
deprecate(() => {},
`${kindName} => ${name || key}: story.parameters.decorators is deprecated; use story.decorators instead.`)();
}
const decoratorParams = decorators ? { decorators } : null;
const displayNameParams = name ? { displayName: name } : {};
kind.add(storyNameFromExport(key), storyFn, {
...parameters,
...decoratorParams,
...displayNameParams,
});
}
});
});
previousExports = currentExports;
};
let loaded = false;
/**
* Load a collection of stories. If it has a default export, assume that it is a module-style
* file and process its named exports as stories. If not, assume it's an old-style
* storiesof file and simply require it.
*
* @param {*} loadable a require.context `req`, an array of `req`s, or a loader function that returns void or an array of exports
* @param {*} m - ES module object for hot-module-reloading (HMR)
* @param {*} framework - name of framework in use, e.g. "react"
*/
const configure = (loadable, m, framework) => {
if (m && m.hot && m.hot.dispose) {
({ previousExports = new Map() } = m.hot.data || {});
m.hot.dispose(data => {
loaded = false;
// eslint-disable-next-line no-param-reassign
data.previousExports = previousExports;
});
}
if (loaded) {
logger.warn('Unexpected loaded state. Did you call `load` twice?');
}
loaded = true;
configApi.configure(loadStories(loadable, framework), m);
};
return { configure, context, clientApi, configApi, forceReRender };
}