/
stories.ts
359 lines (319 loc) · 9.19 KB
/
stories.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
import memoize from 'memoizerific';
import React from 'react';
import deprecate from 'util-deprecate';
import dedent from 'ts-dedent';
import mapValues from 'lodash/mapValues';
import countBy from 'lodash/countBy';
import global from 'global';
import type {
StoryId,
ComponentTitle,
StoryKind,
StoryName,
Args,
ArgTypes,
Parameters,
} from '@storybook/csf';
import { sanitize } from '@storybook/csf';
import { combineParameters } from '../index';
import merge from './merge';
import type { Provider } from '../modules/provider';
import type { ViewMode } from '../modules/addons';
const { FEATURES } = global;
export type { StoryId };
export interface Root {
type: 'root';
id: StoryId;
depth: 0;
name: string;
refId?: string;
children: StoryId[];
isComponent: false;
isRoot: true;
isLeaf: false;
renderLabel?: (item: Root) => React.ReactNode;
startCollapsed?: boolean;
}
export interface Group {
type: 'group' | 'component';
id: StoryId;
depth: number;
name: string;
children: StoryId[];
refId?: string;
parent?: StoryId;
isComponent: boolean;
isRoot: false;
isLeaf: false;
renderLabel?: (item: Group) => React.ReactNode;
// MDX docs-only stories are "Group" type
parameters?: {
docsOnly?: boolean;
viewMode?: ViewMode;
};
}
export interface Story {
type: 'story' | 'docs';
id: StoryId;
depth: number;
parent: StoryId;
name: string;
kind: StoryKind;
refId?: string;
children?: StoryId[];
isComponent: boolean;
isRoot: false;
isLeaf: true;
renderLabel?: (item: Story) => React.ReactNode;
prepared: boolean;
parameters?: {
fileName: string;
options: {
[optionName: string]: any;
};
docsOnly?: boolean;
viewMode?: ViewMode;
[parameterName: string]: any;
};
args?: Args;
argTypes?: ArgTypes;
initialArgs?: Args;
}
export interface StoryInput {
id: StoryId;
name: string;
refId?: string;
kind: StoryKind;
parameters: {
fileName: string;
options: {
[optionName: string]: any;
};
docsOnly?: boolean;
viewMode?: ViewMode;
[parameterName: string]: any;
};
args?: Args;
initialArgs?: Args;
}
export interface StoriesHash {
[id: string]: Root | Group | Story;
}
export type StoriesList = (Group | Story)[];
export type GroupsList = (Root | Group)[];
export interface StoriesRaw {
[id: string]: StoryInput;
}
type Path = string;
export interface StoryIndexStory {
id: StoryId;
name: StoryName;
title: ComponentTitle;
importPath: Path;
// v2 or v2-compatible story index includes this
parameters?: Parameters;
}
export interface StoryIndex {
v: number;
stories: Record<StoryId, StoryIndexStory>;
}
export type SetStoriesPayload =
| {
v: 2;
error?: Error;
globals: Args;
globalParameters: Parameters;
stories: StoriesRaw;
kindParameters: {
[kind: string]: Parameters;
};
}
| ({
v?: number;
stories: StoriesRaw;
} & Record<string, never>);
const warnLegacyShowRoots = deprecate(
() => {},
dedent`
The 'showRoots' config option is deprecated and will be removed in Storybook 7.0. Use 'sidebar.showRoots' instead.
Read more about it in the migration guide: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md
`
);
const warnChangedDefaultHierarchySeparators = deprecate(
() => {},
dedent`
The default hierarchy separators changed in Storybook 6.0.
'|' and '.' will no longer create a hierarchy, but codemods are available.
Read more about it in the migration guide: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md
`
);
export const denormalizeStoryParameters = ({
globalParameters,
kindParameters,
stories,
}: SetStoriesPayload): StoriesRaw => {
return mapValues(stories, (storyData) => ({
...storyData,
parameters: combineParameters(
globalParameters,
kindParameters[storyData.kind],
storyData.parameters as unknown as Parameters
),
}));
};
const STORY_KIND_PATH_SEPARATOR = /\s*\/\s*/;
export const transformStoryIndexToStoriesHash = (
index: StoryIndex,
{ provider }: { provider: Provider }
): StoriesHash => {
const countByTitle = countBy(Object.values(index.stories), 'title');
const input = Object.entries(index.stories).reduce(
(acc, [id, { title, name, importPath, parameters }]) => {
const docsOnly = name === 'Page' && countByTitle[title] === 1;
acc[id] = {
id,
kind: title,
name,
parameters: { fileName: importPath, options: {}, docsOnly, ...parameters },
};
return acc;
},
{} as StoriesRaw
);
return transformStoriesRawToStoriesHash(input, { provider, prepared: false });
};
export const transformStoriesRawToStoriesHash = (
input: StoriesRaw,
{ provider, prepared = true }: { provider: Provider; prepared?: Story['prepared'] }
): StoriesHash => {
const values = Object.values(input).filter(Boolean);
const usesOldHierarchySeparator = values.some(({ kind }) => kind.match(/\.|\|/)); // dot or pipe
const storiesHashOutOfOrder = values.reduce((acc, item) => {
const { kind, parameters } = item;
const { sidebar = {}, showRoots: deprecatedShowRoots } = provider.getConfig();
const { showRoots = deprecatedShowRoots, collapsedRoots = [], renderLabel } = sidebar;
if (typeof deprecatedShowRoots !== 'undefined') {
warnLegacyShowRoots();
}
const setShowRoots = typeof showRoots !== 'undefined';
if (usesOldHierarchySeparator && !setShowRoots && FEATURES?.warnOnLegacyHierarchySeparator) {
warnChangedDefaultHierarchySeparators();
}
const groups = kind.trim().split(STORY_KIND_PATH_SEPARATOR);
const root = (!setShowRoots || showRoots) && groups.length > 1 ? [groups.shift()] : [];
const rootAndGroups = [...root, ...groups].reduce((list, name, index) => {
const parent = index > 0 && list[index - 1].id;
const id = sanitize(parent ? `${parent}-${name}` : name);
if (parent === id) {
throw new Error(
dedent`
Invalid part '${name}', leading to id === parentId ('${id}'), inside kind '${kind}'
Did you create a path that uses the separator char accidentally, such as 'Vue <docs/>' where '/' is a separator char? See https://github.com/storybookjs/storybook/issues/6128
`
);
}
if (root.length && index === 0) {
list.push({
type: 'root',
id,
name,
depth: index,
children: [],
isComponent: false,
isLeaf: false,
isRoot: true,
renderLabel,
startCollapsed: collapsedRoots.includes(id),
});
} else {
list.push({
type: 'group',
id,
name,
parent,
depth: index,
children: [],
isComponent: false,
isLeaf: false,
isRoot: false,
renderLabel,
parameters: {
docsOnly: parameters?.docsOnly,
viewMode: parameters?.viewMode,
},
});
}
return list;
}, [] as GroupsList);
const paths = [...rootAndGroups.map(({ id }) => id), item.id];
// Ok, now let's add everything to the store
rootAndGroups.forEach((group, index) => {
const child = paths[index + 1];
const { id } = group;
acc[id] = merge(acc[id] || {}, {
...group,
...(child && { children: [child] }),
});
});
acc[item.id] = {
type: item.parameters?.docsOnly ? 'docs' : 'story',
...item,
depth: rootAndGroups.length,
parent: rootAndGroups[rootAndGroups.length - 1].id,
isLeaf: true,
isComponent: false,
isRoot: false,
renderLabel,
prepared,
};
return acc;
}, {} as StoriesHash);
function addItem(acc: StoriesHash, item: Story | Group) {
if (!acc[item.id]) {
// If we were already inserted as part of a group, that's great.
acc[item.id] = item;
const { children } = item;
if (children) {
const childNodes = children.map((id) => storiesHashOutOfOrder[id]) as (Story | Group)[];
if (childNodes.every((childNode) => childNode.isLeaf)) {
acc[item.id].isComponent = true;
acc[item.id].type = 'component';
}
childNodes.forEach((childNode) => addItem(acc, childNode));
}
}
return acc;
}
return Object.values(storiesHashOutOfOrder).reduce(addItem, {});
};
export type Item = StoriesHash[keyof StoriesHash];
export function isRoot(item: Item): item is Root {
if (item as Root) {
return item.isRoot;
}
return false;
}
export function isGroup(item: Item): item is Group {
if (item as Group) {
return !item.isRoot && !item.isLeaf;
}
return false;
}
export function isStory(item: Item): item is Story {
if (item as Story) {
return item.isLeaf;
}
return false;
}
export const getComponentLookupList = memoize(1)((hash: StoriesHash) => {
return Object.entries(hash).reduce((acc, i) => {
const value = i[1];
if (value.isComponent) {
acc.push([...i[1].children]);
}
return acc;
}, [] as StoryId[][]);
});
export const getStoriesLookupList = memoize(1)((hash: StoriesHash) => {
return Object.keys(hash).filter((k) => !(hash[k].children || Array.isArray(hash[k])));
});