/
story_store.ts
407 lines (335 loc) · 9.48 KB
/
story_store.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
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
/* eslint no-underscore-dangle: 0 */
import EventEmitter from 'eventemitter3';
import memoize from 'memoizerific';
import debounce from 'lodash/debounce';
import { stripIndents } from 'common-tags';
import stable from 'stable';
import { Channel } from '@storybook/channels';
import Events from '@storybook/core-events';
import { logger } from '@storybook/client-logger';
import { StoryFn, Parameters } from '@storybook/addons';
import {
DecoratorFunction,
LegacyData,
LegacyItem,
StoreData,
AddStoryArgs,
StoreItem,
ErrorLike,
} from './types';
import { HooksContext } from './hooks';
// TODO: these are copies from components/nav/lib
// refactor to DRY
const toKey = (input: string) =>
input.replace(/[^a-z0-9]+([a-z0-9])/gi, (...params) => params[1].toUpperCase());
let count = 0;
const getId = (): number => {
count += 1;
return count;
};
const toExtracted = <T>(obj: T) =>
Object.entries(obj).reduce((acc, [key, value]) => {
if (typeof value === 'function') {
return acc;
}
if (Array.isArray(value)) {
return Object.assign(acc, { [key]: value.slice().sort() });
}
return Object.assign(acc, { [key]: value });
}, {});
interface Selection {
storyId: string;
viewMode: string;
}
interface StoryOptions {
includeDocsOnly?: boolean;
}
const isStoryDocsOnly = (parameters?: Parameters) => {
return parameters && parameters.docsOnly;
};
const includeStory = (story: StoreItem, options: StoryOptions = { includeDocsOnly: false }) => {
if (options.includeDocsOnly) {
return true;
}
return !isStoryDocsOnly(story.parameters);
};
export default class StoryStore extends EventEmitter {
_error?: ErrorLike;
_channel: Channel;
_data: StoreData;
_legacyData?: LegacyData;
_legacydata: LegacyData;
_revision: number;
_selection: Selection;
constructor(params: { channel: Channel }) {
super();
this._legacydata = {} as any;
this._data = {} as any;
this._revision = 0;
this._selection = {} as any;
this._channel = params.channel;
this._error = undefined;
}
setChannel = (channel: Channel) => {
this._channel = channel;
};
// NEW apis
fromId = (id: string): StoreItem | null => {
try {
const data = this._data[id as string];
if (!data || !data.getDecorated) {
return null;
}
return data;
} catch (e) {
logger.warn('failed to get story:', this._data);
logger.error(e);
return null;
}
};
raw(options?: StoryOptions) {
return Object.values(this._data)
.filter(i => !!i.getDecorated)
.filter(i => includeStory(i, options))
.map(({ id }) => this.fromId(id));
}
extract(options?: StoryOptions) {
const stories = Object.entries(this._data);
// determine if we should apply a sort to the stories or just use default import order
if (Object.values(this._data).length > 0) {
const index = Object.keys(this._data).find(
key =>
!!(this._data[key] && this._data[key].parameters && this._data[key].parameters.options)
);
if (index && this._data[index].parameters.options.storySort) {
const sortFn = this._data[index].parameters.options.storySort;
stable.inplace(stories, sortFn);
}
}
// removes function values from all stories so they are safe to transport over the channel
return stories.reduce(
(a, [k, v]) => (includeStory(v, options) ? Object.assign(a, { [k]: toExtracted(v) }) : a),
{}
);
}
setSelection(data: Selection | undefined, error: ErrorLike): void {
this._selection =
data === undefined ? this._selection : { storyId: data.storyId, viewMode: data.viewMode };
this._error = error === undefined ? this._error : error;
setTimeout(() => {
// preferred method to emit event.
if (this._channel) {
this._channel.emit(Events.STORY_RENDER);
}
// should be deprecated in future.
this.emit(Events.STORY_RENDER);
}, 1);
}
getSelection = (): Selection => this._selection;
getError = (): ErrorLike | undefined => this._error;
remove = (id: string): void => {
const { _data } = this;
const story = _data[id];
delete _data[id];
if (story) {
story.hooks.clean();
const { kind, name } = story;
const kindData = this._legacydata[toKey(kind)];
if (kindData) {
delete kindData.stories[toKey(name)];
}
}
};
addStory(
{ id, kind, name, storyFn: original, parameters = {} }: AddStoryArgs,
{
getDecorators,
applyDecorators,
}: {
getDecorators: () => DecoratorFunction[];
applyDecorators: (fn: StoryFn, decorators: DecoratorFunction[]) => any;
}
) {
const { _data } = this;
if (_data[id]) {
logger.warn(stripIndents`
Story with id ${id} already exists in the store!
Perhaps you added the same story twice, or you have a name collision?
Story ids need to be unique -- ensure you aren't using the same names modulo url-sanitization.
`);
}
const identification = {
id,
kind,
name,
story: name, // legacy
};
// immutable original storyFn
const getOriginal = () => original;
// lazily decorate the story when it's loaded
const getDecorated: () => StoryFn = memoize(1)(() =>
applyDecorators(getOriginal(), getDecorators())
);
const hooks = new HooksContext();
const storyFn: StoryFn = p =>
getDecorated()({
...identification,
...p,
hooks,
parameters: { ...parameters, ...(p && p.parameters) },
});
_data[id] = {
...identification,
hooks,
getDecorated,
getOriginal,
storyFn,
parameters,
};
// LEGACY DATA
if (!isStoryDocsOnly(parameters)) {
this.addLegacyStory({ kind, name, storyFn, parameters });
}
// LET'S SEND IT TO THE MANAGER
this.pushToManager();
}
pushToManager = debounce(() => {
if (this._channel) {
const stories = this.extract({ includeDocsOnly: true });
// send to the parent frame.
this._channel.emit(Events.SET_STORIES, { stories });
}
}, 0);
// OLD apis
getRevision() {
return this._revision;
}
incrementRevision() {
this._revision += 1;
}
addLegacyStory({
kind,
name,
storyFn,
parameters,
}: {
kind: string;
name: string;
storyFn: StoryFn;
parameters: Parameters;
}) {
const k = toKey(kind);
if (!this._legacydata[k as string]) {
this._legacydata[k as string] = {
kind,
fileName: parameters.fileName,
index: getId(),
stories: {},
};
}
this._legacydata[k as string].stories[toKey(name)] = {
name,
// kind,
index: getId(),
story: storyFn,
parameters,
};
}
getStoryKinds() {
return Object.values(this._legacydata)
.filter((kind: LegacyItem) => Object.keys(kind.stories).length > 0)
.sort((info1: LegacyItem, info2: LegacyItem) => info1.index - info2.index)
.map((info: LegacyItem) => info.kind);
}
getStories(kind: string) {
const key = toKey(kind);
if (!this._legacydata[key as string]) {
return [];
}
return Object.keys(this._legacydata[key as string].stories)
.map(name => this._legacydata[key as string].stories[name])
.sort((info1, info2) => info1.index - info2.index)
.map(info => info.name);
}
getStoriesForKind(kind: string) {
return this.raw().filter(story => story.kind === kind);
}
getStoryFileName(kind: string) {
const key = toKey(kind);
const storiesKind = this._legacydata[key as string];
if (!storiesKind) {
return null;
}
return storiesKind.fileName;
}
getStoryAndParameters(kind: string, name: string) {
if (!kind || !name) {
return null;
}
const storiesKind = this._legacydata[toKey(kind) as string];
if (!storiesKind) {
return null;
}
const storyInfo = storiesKind.stories[toKey(name)];
if (!storyInfo) {
return null;
}
const { story, parameters } = storyInfo;
return {
story,
parameters,
};
}
getStory(kind: string, name: string) {
const data = this.getStoryAndParameters(kind, name);
return data && data.story;
}
getStoryWithContext(kind: string, name: string) {
const data = this.getStoryAndParameters(kind, name);
if (!data) {
return null;
}
const { story } = data;
return story;
}
removeStoryKind(kind: string) {
if (this.hasStoryKind(kind)) {
this._legacydata[toKey(kind)].stories = {};
this.cleanHooksForKind(kind);
this._data = Object.entries(this._data).reduce((acc, [id, story]) => {
if (story.kind !== kind) {
Object.assign(acc, { [id]: story });
}
return acc;
}, {});
this.pushToManager();
}
}
hasStoryKind(kind: string) {
return Boolean(this._legacydata[toKey(kind) as string]);
}
hasStory(kind: string, name: string) {
return Boolean(this.getStory(kind, name));
}
dumpStoryBook() {
const data = this.getStoryKinds().map(kind => ({
kind,
stories: this.getStories(kind),
}));
return data;
}
size() {
return Object.keys(this._legacydata).length;
}
clean() {
this.getStoryKinds().forEach(kind => delete this._legacydata[toKey(kind) as string]);
}
cleanHooks(id: string) {
if (this._data[id]) {
this._data[id].hooks.clean();
}
}
cleanHooksForKind(kind: string) {
this.getStoriesForKind(kind).map(story => this.cleanHooks(story.id));
}
}