UNPKG

20.1 kBJavaScriptView Raw
1import "core-js/modules/es.array.slice.js";
2import "core-js/modules/es.object.freeze.js";
3import "core-js/modules/es.symbol.js";
4import "core-js/modules/es.symbol.description.js";
5import "core-js/modules/es.symbol.iterator.js";
6import "core-js/modules/es.array.from.js";
7import "core-js/modules/es.regexp.exec.js";
8var _excluded = ["globals", "globalTypes"],
9 _excluded2 = ["decorators", "loaders", "component", "args", "argTypes"],
10 _excluded3 = ["component", "args", "argTypes"];
11
12var _templateObject, _templateObject2, _templateObject3, _templateObject4;
13
14function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
15
16function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
17
18function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
19
20function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
21
22function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
23
24function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
25
26function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
27
28function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
29
30function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
31
32function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
33
34function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
35
36function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
37
38import "core-js/modules/es.array.iterator.js";
39import "core-js/modules/es.object.to-string.js";
40import "core-js/modules/es.set.js";
41import "core-js/modules/es.string.iterator.js";
42import "core-js/modules/web.dom-collections.iterator.js";
43import "core-js/modules/es.object.assign.js";
44import "core-js/modules/es.object.get-prototype-of.js";
45import "core-js/modules/es.regexp.to-string.js";
46import "core-js/modules/es.object.keys.js";
47import "core-js/modules/es.array.concat.js";
48import "core-js/modules/web.dom-collections.for-each.js";
49import "core-js/modules/es.object.entries.js";
50import "core-js/modules/es.function.name.js";
51import "core-js/modules/es.object.values.js";
52
53function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
54
55import deprecate from 'util-deprecate';
56import dedent from 'ts-dedent';
57import global from 'global';
58import { logger } from '@storybook/client-logger';
59import { toId, sanitize } from '@storybook/csf';
60import { combineParameters, normalizeInputTypes } from '@storybook/store';
61import { StoryStoreFacade } from './StoryStoreFacade';
62// ClientApi (and StoreStore) are really singletons. However they are not created until the
63// relevant framework instanciates them via `start.js`. The good news is this happens right away.
64var singleton;
65var warningAlternatives = {
66 addDecorator: "Instead, use `export const decorators = [];` in your `preview.js`.",
67 addParameters: "Instead, use `export const parameters = {};` in your `preview.js`.",
68 addLoaders: "Instead, use `export const loaders = [];` in your `preview.js`."
69};
70
71var warningMessage = function warningMessage(method) {
72 return deprecate(function () {}, dedent(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n `", "` is deprecated, and will be removed in Storybook 7.0.\n\n ", "\n\n Read more at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-addparameters-and-adddecorator)."], ["\n \\`", "\\` is deprecated, and will be removed in Storybook 7.0.\n\n ", "\n\n Read more at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-addparameters-and-adddecorator)."])), method, warningAlternatives[method]));
73};
74
75var warnings = {
76 addDecorator: warningMessage('addDecorator'),
77 addParameters: warningMessage('addParameters'),
78 addLoaders: warningMessage('addLoaders')
79};
80
81var checkMethod = function checkMethod(method, deprecationWarning) {
82 var _global$FEATURES;
83
84 if ((_global$FEATURES = global.FEATURES) !== null && _global$FEATURES !== void 0 && _global$FEATURES.storyStoreV7) {
85 throw new Error(dedent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["You cannot use `", "` with the new Story Store.\n \n ", ""], ["You cannot use \\`", "\\` with the new Story Store.\n \n ", ""])), method, warningAlternatives[method]));
86 }
87
88 if (!singleton) {
89 throw new Error("Singleton client API not yet initialized, cannot call `".concat(method, "`."));
90 }
91
92 if (deprecationWarning) {
93 warnings[method]();
94 }
95};
96
97export var addDecorator = function addDecorator(decorator) {
98 var deprecationWarning = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
99 checkMethod('addDecorator', deprecationWarning);
100 singleton.addDecorator(decorator);
101};
102export var addParameters = function addParameters(parameters) {
103 var deprecationWarning = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
104 checkMethod('addParameters', deprecationWarning);
105 singleton.addParameters(parameters);
106};
107export var addLoader = function addLoader(loader) {
108 var deprecationWarning = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
109 checkMethod('addLoader', deprecationWarning);
110 singleton.addLoader(loader);
111};
112export var addArgs = function addArgs(args) {
113 checkMethod('addArgs', false);
114 singleton.addArgs(args);
115};
116export var addArgTypes = function addArgTypes(argTypes) {
117 checkMethod('addArgTypes', false);
118 singleton.addArgTypes(argTypes);
119};
120export var addArgsEnhancer = function addArgsEnhancer(enhancer) {
121 checkMethod('addArgsEnhancer', false);
122 singleton.addArgsEnhancer(enhancer);
123};
124export var addArgTypesEnhancer = function addArgTypesEnhancer(enhancer) {
125 checkMethod('addArgTypesEnhancer', false);
126 singleton.addArgTypesEnhancer(enhancer);
127};
128export var getGlobalRender = function getGlobalRender() {
129 checkMethod('getGlobalRender', false);
130 return singleton.facade.projectAnnotations.render;
131};
132export var setGlobalRender = function setGlobalRender(render) {
133 checkMethod('setGlobalRender', false);
134 singleton.facade.projectAnnotations.render = render;
135};
136var invalidStoryTypes = new Set(['string', 'number', 'boolean', 'symbol']);
137export var ClientApi = /*#__PURE__*/function () {
138 // If we don't get passed modules so don't know filenames, we can
139 // just use numeric indexes
140 function ClientApi() {
141 var _this = this;
142
143 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
144 storyStore = _ref.storyStore;
145
146 _classCallCheck(this, ClientApi);
147
148 this.facade = void 0;
149 this.storyStore = void 0;
150 this.addons = void 0;
151 this.onImportFnChanged = void 0;
152 this.lastFileName = 0;
153 this.setAddon = deprecate(function (addon) {
154 _this.addons = Object.assign({}, _this.addons, addon);
155 }, dedent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n `setAddon` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-setaddon\n "], ["\n \\`setAddon\\` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-setaddon\n "]))));
156
157 this.addDecorator = function (decorator) {
158 _this.facade.projectAnnotations.decorators.push(decorator);
159 };
160
161 this.clearDecorators = deprecate(function () {
162 _this.facade.projectAnnotations.decorators = [];
163 }, dedent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n `clearDecorators` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-cleardecorators\n "], ["\n \\`clearDecorators\\` is deprecated and will be removed in Storybook 7.0.\n\n https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-cleardecorators\n "]))));
164
165 this.addParameters = function (_ref2) {
166 var globals = _ref2.globals,
167 globalTypes = _ref2.globalTypes,
168 parameters = _objectWithoutProperties(_ref2, _excluded);
169
170 _this.facade.projectAnnotations.parameters = combineParameters(_this.facade.projectAnnotations.parameters, parameters);
171
172 if (globals) {
173 _this.facade.projectAnnotations.globals = Object.assign({}, _this.facade.projectAnnotations.globals, globals);
174 }
175
176 if (globalTypes) {
177 _this.facade.projectAnnotations.globalTypes = Object.assign({}, _this.facade.projectAnnotations.globalTypes, normalizeInputTypes(globalTypes));
178 }
179 };
180
181 this.addLoader = function (loader) {
182 _this.facade.projectAnnotations.loaders.push(loader);
183 };
184
185 this.addArgs = function (args) {
186 _this.facade.projectAnnotations.args = Object.assign({}, _this.facade.projectAnnotations.args, args);
187 };
188
189 this.addArgTypes = function (argTypes) {
190 _this.facade.projectAnnotations.argTypes = Object.assign({}, _this.facade.projectAnnotations.argTypes, normalizeInputTypes(argTypes));
191 };
192
193 this.addArgsEnhancer = function (enhancer) {
194 _this.facade.projectAnnotations.argsEnhancers.push(enhancer);
195 };
196
197 this.addArgTypesEnhancer = function (enhancer) {
198 _this.facade.projectAnnotations.argTypesEnhancers.push(enhancer);
199 };
200
201 this.storiesOf = function (kind, m) {
202 if (!kind && typeof kind !== 'string') {
203 throw new Error('Invalid or missing kind provided for stories, should be a string');
204 }
205
206 if (!m) {
207 logger.warn("Missing 'module' parameter for story with a kind of '".concat(kind, "'. It will break your HMR"));
208 }
209
210 if (m) {
211 var proto = Object.getPrototypeOf(m);
212
213 if (proto.exports && proto.exports.default) {
214 // FIXME: throw an error in SB6.0
215 logger.error("Illegal mix of CSF default export and storiesOf calls in a single file: ".concat(proto.i));
216 }
217 } // eslint-disable-next-line no-plusplus
218
219
220 var baseFilename = m && m.id ? "".concat(m.id) : (_this.lastFileName++).toString();
221 var fileName = baseFilename;
222 var i = 1; // Deal with `storiesOf()` being called twice in the same file.
223 // On HMR, `this.csfExports[fileName]` will be reset to `{}`, so an empty object is due
224 // to this export, not a second call of `storiesOf()`.
225
226 while (_this.facade.csfExports[fileName] && Object.keys(_this.facade.csfExports[fileName]).length > 0) {
227 i += 1;
228 fileName = "".concat(baseFilename, "-").concat(i);
229 }
230
231 if (m && m.hot && m.hot.accept) {
232 // This module used storiesOf(), so when it re-runs on HMR, it will reload
233 // itself automatically without us needing to look at our imports
234 m.hot.accept();
235 m.hot.dispose(function () {
236 _this.facade.clearFilenameExports(fileName); // We need to update the importFn as soon as the module re-evaluates
237 // (and calls storiesOf() again, etc). We could call `onImportFnChanged()`
238 // at the end of every setStories call (somehow), but then we'd need to
239 // debounce it somehow for initial startup. Instead, we'll take advantage of
240 // the fact that the evaluation of the module happens immediately in the same tick
241
242
243 setTimeout(function () {
244 var _this$onImportFnChang;
245
246 (_this$onImportFnChang = _this.onImportFnChanged) === null || _this$onImportFnChang === void 0 ? void 0 : _this$onImportFnChang.call(_this, {
247 importFn: _this.importFn.bind(_this)
248 });
249 }, 0);
250 });
251 }
252
253 var hasAdded = false;
254 var api = {
255 kind: kind.toString(),
256 add: function add() {
257 return api;
258 },
259 addDecorator: function addDecorator() {
260 return api;
261 },
262 addLoader: function addLoader() {
263 return api;
264 },
265 addParameters: function addParameters() {
266 return api;
267 }
268 }; // apply addons
269
270 Object.keys(_this.addons).forEach(function (name) {
271 var addon = _this.addons[name];
272
273 api[name] = function () {
274 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
275 args[_key] = arguments[_key];
276 }
277
278 addon.apply(api, args);
279 return api;
280 };
281 });
282 var meta = {
283 id: sanitize(kind),
284 title: kind,
285 decorators: [],
286 loaders: [],
287 parameters: {}
288 }; // We map these back to a simple default export, even though we have type guarantees at this point
289
290 _this.facade.csfExports[fileName] = {
291 default: meta
292 };
293 var counter = 0;
294
295 api.add = function (storyName, storyFn) {
296 var parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
297 hasAdded = true;
298
299 if (typeof storyName !== 'string') {
300 throw new Error("Invalid or missing storyName provided for a \"".concat(kind, "\" story."));
301 }
302
303 if (!storyFn || Array.isArray(storyFn) || invalidStoryTypes.has(_typeof(storyFn))) {
304 throw new Error("Cannot load story \"".concat(storyName, "\" in \"").concat(kind, "\" due to invalid format. Storybook expected a function/object but received ").concat(_typeof(storyFn), " instead."));
305 }
306
307 var decorators = parameters.decorators,
308 loaders = parameters.loaders,
309 component = parameters.component,
310 args = parameters.args,
311 argTypes = parameters.argTypes,
312 storyParameters = _objectWithoutProperties(parameters, _excluded2); // eslint-disable-next-line no-underscore-dangle
313
314
315 var storyId = parameters.__id || toId(kind, storyName);
316 var csfExports = _this.facade.csfExports[fileName]; // Whack a _ on the front incase it is "default"
317
318 csfExports["story".concat(counter)] = {
319 name: storyName,
320 parameters: Object.assign({
321 fileName: fileName,
322 __id: storyId
323 }, storyParameters),
324 decorators: decorators,
325 loaders: loaders,
326 args: args,
327 argTypes: argTypes,
328 component: component,
329 render: storyFn
330 };
331 counter += 1;
332 _this.facade.stories[storyId] = {
333 id: storyId,
334 title: csfExports.default.title,
335 name: storyName,
336 importPath: fileName
337 };
338 return api;
339 };
340
341 api.addDecorator = function (decorator) {
342 if (hasAdded) throw new Error("You cannot add a decorator after the first story for a kind.\nRead more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories");
343 meta.decorators.push(decorator);
344 return api;
345 };
346
347 api.addLoader = function (loader) {
348 if (hasAdded) throw new Error("You cannot add a loader after the first story for a kind.");
349 meta.loaders.push(loader);
350 return api;
351 };
352
353 api.addParameters = function (_ref3) {
354 var component = _ref3.component,
355 args = _ref3.args,
356 argTypes = _ref3.argTypes,
357 parameters = _objectWithoutProperties(_ref3, _excluded3);
358
359 if (hasAdded) throw new Error("You cannot add parameters after the first story for a kind.\nRead more here: https://github.com/storybookjs/storybook/blob/master/MIGRATION.md#can-no-longer-add-decoratorsparameters-after-stories");
360 meta.parameters = combineParameters(meta.parameters, parameters);
361 if (component) meta.component = component;
362 if (args) meta.args = Object.assign({}, meta.args, args);
363 if (argTypes) meta.argTypes = Object.assign({}, meta.argTypes, argTypes);
364 return api;
365 };
366
367 return api;
368 };
369
370 this.getStorybook = function () {
371 var stories = _this.storyStore.storyIndex.stories;
372 var kinds = {};
373 Object.entries(stories).forEach(function (_ref4) {
374 var _ref5 = _slicedToArray(_ref4, 2),
375 storyId = _ref5[0],
376 _ref5$ = _ref5[1],
377 title = _ref5$.title,
378 name = _ref5$.name,
379 importPath = _ref5$.importPath;
380
381 if (!kinds[title]) {
382 kinds[title] = {
383 kind: title,
384 fileName: importPath,
385 stories: []
386 };
387 }
388
389 var _this$storyStore$from = _this.storyStore.fromId(storyId),
390 storyFn = _this$storyStore$from.storyFn;
391
392 kinds[title].stories.push({
393 name: name,
394 render: storyFn
395 });
396 });
397 return Object.values(kinds);
398 };
399
400 this.raw = function () {
401 return _this.storyStore.raw();
402 };
403
404 this.facade = new StoryStoreFacade();
405 this.addons = {};
406 this.storyStore = storyStore;
407 singleton = this;
408 }
409
410 _createClass(ClientApi, [{
411 key: "importFn",
412 value: function importFn(path) {
413 return this.facade.importFn(path);
414 }
415 }, {
416 key: "getStoryIndex",
417 value: function getStoryIndex() {
418 if (!this.storyStore) {
419 throw new Error('Cannot get story index before setting storyStore');
420 }
421
422 return this.facade.getStoryIndex(this.storyStore);
423 }
424 }, {
425 key: "_storyStore",
426 get: // @deprecated
427 function get() {
428 return this.storyStore;
429 }
430 }]);
431
432 return ClientApi;
433}();
\No newline at end of file