/
ClientApi.ts
431 lines (356 loc) · 12.9 KB
/
ClientApi.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import deprecate from 'util-deprecate';
import dedent from 'ts-dedent';
import global from 'global';
import { logger } from '@storybook/client-logger';
import {
Args,
ArgTypes,
AnyFramework,
toId,
DecoratorFunction,
Parameters,
ArgTypesEnhancer,
ArgsEnhancer,
LoaderFunction,
StoryFn,
sanitize,
ComponentTitle,
Globals,
GlobalTypes,
LegacyStoryFn,
} from '@storybook/csf';
import {
NormalizedComponentAnnotations,
Path,
ModuleImportFn,
combineParameters,
StoryStore,
normalizeInputTypes,
} from '@storybook/store';
import { ClientApiAddons, StoryApi } from '@storybook/addons';
import { StoryStoreFacade } from './StoryStoreFacade';
export interface GetStorybookStory<TFramework extends AnyFramework> {
name: string;
render: LegacyStoryFn<TFramework>;
}
export interface GetStorybookKind<TFramework extends AnyFramework> {
kind: string;
fileName: string;
stories: GetStorybookStory<TFramework>[];
}
// ClientApi (and StoreStore) are really singletons. However they are not created until the
// relevant framework instanciates them via `start.js`. The good news is this happens right away.
let singleton: ClientApi<AnyFramework>;
const warningAlternatives = {
addDecorator: `Instead, use \`export const decorators = [];\` in your \`preview.js\`.`,
addParameters: `Instead, use \`export const parameters = {};\` in your \`preview.js\`.`,
addLoaders: `Instead, use \`export const loaders = [];\` in your \`preview.js\`.`,
};
const warningMessage = (method: keyof typeof warningAlternatives) =>
deprecate(
() => {},
dedent`
\`${method}\` is deprecated, and will be removed in Storybook 7.0.
${warningAlternatives[method]}
Read more at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-addparameters-and-adddecorator).`
);
const warnings = {
addDecorator: warningMessage('addDecorator'),
addParameters: warningMessage('addParameters'),
addLoaders: warningMessage('addLoaders'),
};
const checkMethod = (method: string, deprecationWarning: boolean) => {
if (global.FEATURES?.storyStoreV7) {
throw new Error(
dedent`You cannot use \`${method}\` with the new Story Store.
${warningAlternatives[method as keyof typeof warningAlternatives]}`
);
}
if (!singleton) {
throw new Error(`Singleton client API not yet initialized, cannot call \`${method}\`.`);
}
if (deprecationWarning) {
warnings[method as keyof typeof warningAlternatives]();
}
};
export const addDecorator = (
decorator: DecoratorFunction<AnyFramework>,
deprecationWarning = true
) => {
checkMethod('addDecorator', deprecationWarning);
singleton.addDecorator(decorator);
};
export const addParameters = (parameters: Parameters, deprecationWarning = true) => {
checkMethod('addParameters', deprecationWarning);
singleton.addParameters(parameters);
};
export const addLoader = (loader: LoaderFunction<AnyFramework>, deprecationWarning = true) => {
checkMethod('addLoader', deprecationWarning);
singleton.addLoader(loader);
};
export const addArgs = (args: Args) => {
checkMethod('addArgs', false);
singleton.addArgs(args);
};
export const addArgTypes = (argTypes: ArgTypes) => {
checkMethod('addArgTypes', false);
singleton.addArgTypes(argTypes);
};
export const addArgsEnhancer = (enhancer: ArgsEnhancer<AnyFramework>) => {
checkMethod('addArgsEnhancer', false);
singleton.addArgsEnhancer(enhancer);
};
export const addArgTypesEnhancer = (enhancer: ArgTypesEnhancer<AnyFramework>) => {
checkMethod('addArgTypesEnhancer', false);
singleton.addArgTypesEnhancer(enhancer);
};
export const getGlobalRender = () => {
checkMethod('getGlobalRender', false);
return singleton.facade.projectAnnotations.render;
};
export const setGlobalRender = (render: StoryFn<AnyFramework>) => {
checkMethod('setGlobalRender', false);
singleton.facade.projectAnnotations.render = render;
};
const invalidStoryTypes = new Set(['string', 'number', 'boolean', 'symbol']);
export class ClientApi<TFramework extends AnyFramework> {
facade: StoryStoreFacade<TFramework>;
storyStore?: StoryStore<TFramework>;
private addons: ClientApiAddons<TFramework['storyResult']>;
onImportFnChanged?: ({ importFn }: { importFn: ModuleImportFn }) => void;
// If we don't get passed modules so don't know filenames, we can
// just use numeric indexes
private lastFileName = 0;
constructor({ storyStore }: { storyStore?: StoryStore<TFramework> } = {}) {
this.facade = new StoryStoreFacade();
this.addons = {};
this.storyStore = storyStore;
singleton = this;
}
importFn(path: Path) {
return this.facade.importFn(path);
}
getStoryIndex() {
if (!this.storyStore) {
throw new Error('Cannot get story index before setting storyStore');
}
return this.facade.getStoryIndex(this.storyStore);
}
setAddon = deprecate(
(addon: any) => {
this.addons = { ...this.addons, ...addon };
},
dedent`
\`setAddon\` is deprecated and will be removed in Storybook 7.0.
https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-setaddon
`
);
addDecorator = (decorator: DecoratorFunction<TFramework>) => {
this.facade.projectAnnotations.decorators.push(decorator);
};
clearDecorators = deprecate(
() => {
this.facade.projectAnnotations.decorators = [];
},
dedent`
\`clearDecorators\` is deprecated and will be removed in Storybook 7.0.
https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-cleardecorators
`
);
addParameters = ({
globals,
globalTypes,
...parameters
}: Parameters & { globals?: Globals; globalTypes?: GlobalTypes }) => {
this.facade.projectAnnotations.parameters = combineParameters(
this.facade.projectAnnotations.parameters,
parameters
);
if (globals) {
this.facade.projectAnnotations.globals = {
...this.facade.projectAnnotations.globals,
...globals,
};
}
if (globalTypes) {
this.facade.projectAnnotations.globalTypes = {
...this.facade.projectAnnotations.globalTypes,
...normalizeInputTypes(globalTypes),
};
}
};
addLoader = (loader: LoaderFunction<TFramework>) => {
this.facade.projectAnnotations.loaders.push(loader);
};
addArgs = (args: Args) => {
this.facade.projectAnnotations.args = {
...this.facade.projectAnnotations.args,
...args,
};
};
addArgTypes = (argTypes: ArgTypes) => {
this.facade.projectAnnotations.argTypes = {
...this.facade.projectAnnotations.argTypes,
...normalizeInputTypes(argTypes),
};
};
addArgsEnhancer = (enhancer: ArgsEnhancer<TFramework>) => {
this.facade.projectAnnotations.argsEnhancers.push(enhancer);
};
addArgTypesEnhancer = (enhancer: ArgTypesEnhancer<TFramework>) => {
this.facade.projectAnnotations.argTypesEnhancers.push(enhancer);
};
// what are the occasions that "m" is a boolean vs an obj
storiesOf = (kind: string, m?: NodeModule): StoryApi<TFramework['storyResult']> => {
if (!kind && typeof kind !== 'string') {
throw new Error('Invalid or missing kind provided for stories, should be a string');
}
if (!m) {
logger.warn(
`Missing 'module' parameter for story with a kind of '${kind}'. It will break your HMR`
);
}
if (m) {
const proto = Object.getPrototypeOf(m);
if (proto.exports && proto.exports.default) {
// FIXME: throw an error in SB6.0
logger.error(
`Illegal mix of CSF default export and storiesOf calls in a single file: ${proto.i}`
);
}
}
// eslint-disable-next-line no-plusplus
const baseFilename = m && m.id ? `${m.id}` : (this.lastFileName++).toString();
let fileName = baseFilename;
let i = 1;
// Deal with `storiesOf()` being called twice in the same file.
// On HMR, `this.csfExports[fileName]` will be reset to `{}`, so an empty object is due
// to this export, not a second call of `storiesOf()`.
while (
this.facade.csfExports[fileName] &&
Object.keys(this.facade.csfExports[fileName]).length > 0
) {
i += 1;
fileName = `${baseFilename}-${i}`;
}
if (m && m.hot && m.hot.accept) {
// This module used storiesOf(), so when it re-runs on HMR, it will reload
// itself automatically without us needing to look at our imports
m.hot.accept();
m.hot.dispose(() => {
this.facade.clearFilenameExports(fileName);
// We need to update the importFn as soon as the module re-evaluates
// (and calls storiesOf() again, etc). We could call `onImportFnChanged()`
// at the end of every setStories call (somehow), but then we'd need to
// debounce it somehow for initial startup. Instead, we'll take advantage of
// the fact that the evaluation of the module happens immediately in the same tick
setTimeout(() => {
this.onImportFnChanged?.({ importFn: this.importFn.bind(this) });
}, 0);
});
}
let hasAdded = false;
const api: StoryApi<TFramework['storyResult']> = {
kind: kind.toString(),
add: () => api,
addDecorator: () => api,
addLoader: () => api,
addParameters: () => api,
};
// apply addons
Object.keys(this.addons).forEach((name) => {
const addon = this.addons[name];
api[name] = (...args: any[]) => {
addon.apply(api, args);
return api;
};
});
const meta: NormalizedComponentAnnotations<TFramework> = {
id: sanitize(kind),
title: kind,
decorators: [],
loaders: [],
parameters: {},
};
// We map these back to a simple default export, even though we have type guarantees at this point
this.facade.csfExports[fileName] = { default: meta };
let counter = 0;
api.add = (storyName: string, storyFn: StoryFn<TFramework>, parameters: Parameters = {}) => {
hasAdded = true;
if (typeof storyName !== 'string') {
throw new Error(`Invalid or missing storyName provided for a "${kind}" story.`);
}
if (!storyFn || Array.isArray(storyFn) || invalidStoryTypes.has(typeof storyFn)) {
throw new Error(
`Cannot load story "${storyName}" in "${kind}" due to invalid format. Storybook expected a function/object but received ${typeof storyFn} instead.`
);
}
const { decorators, loaders, component, args, argTypes, ...storyParameters } = parameters;
// eslint-disable-next-line no-underscore-dangle
const storyId = parameters.__id || toId(kind, storyName);
const csfExports = this.facade.csfExports[fileName];
// Whack a _ on the front incase it is "default"
csfExports[`story${counter}`] = {
name: storyName,
parameters: { fileName, __id: storyId, ...storyParameters },
decorators,
loaders,
args,
argTypes,
component,
render: storyFn,
};
counter += 1;
this.facade.stories[storyId] = {
id: storyId,
title: csfExports.default.title,
name: storyName,
importPath: fileName,
};
return api;
};
api.addDecorator = (decorator: DecoratorFunction<TFramework>) => {
if (hasAdded)
throw new Error(`You cannot add a decorator after the first story for a kind.
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);
meta.decorators.push(decorator);
return api;
};
api.addLoader = (loader: LoaderFunction<TFramework>) => {
if (hasAdded) throw new Error(`You cannot add a loader after the first story for a kind.`);
meta.loaders.push(loader);
return api;
};
api.addParameters = ({ component, args, argTypes, ...parameters }: Parameters) => {
if (hasAdded)
throw new Error(`You cannot add parameters after the first story for a kind.
Read more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories`);
meta.parameters = combineParameters(meta.parameters, parameters);
if (component) meta.component = component;
if (args) meta.args = { ...meta.args, ...args };
if (argTypes) meta.argTypes = { ...meta.argTypes, ...argTypes };
return api;
};
return api;
};
getStorybook = (): GetStorybookKind<TFramework>[] => {
const { stories } = this.storyStore.storyIndex;
const kinds: Record<ComponentTitle, GetStorybookKind<TFramework>> = {};
Object.entries(stories).forEach(([storyId, { title, name, importPath }]) => {
if (!kinds[title]) {
kinds[title] = { kind: title, fileName: importPath, stories: [] };
}
const { storyFn } = this.storyStore.fromId(storyId);
kinds[title].stories.push({ name, render: storyFn });
});
return Object.values(kinds);
};
// @deprecated
raw = () => {
return this.storyStore.raw();
};
// @deprecated
get _storyStore() {
return this.storyStore;
}
}