@storybook/csf 0.0.2-alpha.0 → 0.0.2-next.0

Sign up to get free protection for your applications and to get access to all the features.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 CSF contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,14 +1,52 @@
1
- # Storybook Component Story Format (CSF)
1
+ <img src="https://user-images.githubusercontent.com/42671/89649515-eceafc00-d88e-11ea-9728-5ef80cdf8462.png" width="321px" height="236px" />
2
2
 
3
- A minimal set of utility functions for dealing with Storybook [Component Story Format (CSF)](https://storybook.js.org/docs/formats/component-story-format/).
3
+ # Component Story Format (CSF)
4
4
 
5
- ## Install
5
+ ### Why a standard format?
6
+ Components have risen to dominate the UI landscape. There are new component-oriented tools for development, testing, design, and prototyping. These tools engage in the creation and consumption of components and component examples (a.k.a. stories). But each tool has its own proprietary format because a simple, platform-agnostic way to express component examples doesn't yet exist.
7
+
8
+ ### The "Story" is the source of truth for a component.
9
+ A story is a code snippet that renders an example of a component in a specific state. Think about it like a "[user story](https://en.wikipedia.org/wiki/User_story)".
10
+
11
+ It uses the production code shipped to users, making it the most accurate representation of a component example. What's more, stories are expressed in the view layer you use to build your app.
12
+
13
+
14
+ ### Component Story Format
15
+ The Component Story Format is an open standard for component examples based on JavaScript ES6 modules. This enables interoperation between development, testing, and design tools.
16
+
17
+ ```js
18
+ export default { title: 'atoms/Button' };
19
+ export const text = () => <Button>Hello</Button>;
20
+ export const emoji = () => <Button>😀😎👍💯</Button>;
21
+ ```
22
+
23
+ 💎 **Simple.** Writing component "stories" is as easy as exporting ES6 functions using a clean, widely-used format.
24
+
25
+ 🚚 **Non-proprietary.** CSF doesn't require any vendor-specific libraries. Component stories are easily consumed anywhere ES6 modules live, including your favourite testing tools like Jest and Cypress.
26
+
27
+ ☝️ **Declarative.** The declarative syntax is isomorphic to higher-level formats like MDX, enabling clean, verifiable transformations.
28
+
29
+ 🔥 **Optimized.** Component stories don't need any libraries other than your components. And because they're ES6 modules, they're even tree-shakeable!
30
+
31
+ ### Who uses CSF?
32
+
33
+ **Tools:** [Storybook](https://storybook.js.org), [WebComponents.dev](https://webcomponents.dev), [Components.studio](https://components.studio), [RedwoodJS](https://redwoodjs.com/), [UXPin](https://www.uxpin.com/)
34
+
35
+ **Compatible with:** [Jest](https://jestjs.io/), [Enzyme](https://enzymejs.github.io/enzyme), [Testing Library](https://testing-library.com), [Cypress](https://www.cypress.io/), [Playwright](https://playwright.dev/), [Mocha](https://mochajs.org), etc.
36
+
37
+
38
+ ## CSF utilities
39
+
40
+ A minimal set of utility functions for dealing with [Component Story Format (CSF)](https://storybook.js.org/docs/formats/component-story-format/).
41
+
42
+
43
+ ### Install
6
44
 
7
45
  ```sh
8
- yarn add @storybook/csf
46
+ yarn add @componentdriven/csf
9
47
  ```
10
48
 
11
- ## API
49
+ ### API
12
50
 
13
51
  See package source for function definitions and types:
14
52
 
package/dist/index.d.ts CHANGED
@@ -1,28 +1,339 @@
1
- import { StoryProperties } from './properties';
2
- export * from './properties';
3
- export declare const sanitize: (string: string) => string;
4
- export declare const toId: (kind: string, name: string) => string;
5
- export declare const storyNameFromExport: (key: string) => string;
1
+ import { Simplify, UnionToIntersection } from 'type-fest';
2
+
3
+ interface SBBaseType {
4
+ required?: boolean;
5
+ raw?: string;
6
+ }
7
+ declare type SBScalarType = SBBaseType & {
8
+ name: 'boolean' | 'string' | 'number' | 'function' | 'symbol';
9
+ };
10
+ declare type SBArrayType = SBBaseType & {
11
+ name: 'array';
12
+ value: SBType;
13
+ };
14
+ declare type SBObjectType = SBBaseType & {
15
+ name: 'object';
16
+ value: Record<string, SBType>;
17
+ };
18
+ declare type SBEnumType = SBBaseType & {
19
+ name: 'enum';
20
+ value: (string | number)[];
21
+ };
22
+ declare type SBIntersectionType = SBBaseType & {
23
+ name: 'intersection';
24
+ value: SBType[];
25
+ };
26
+ declare type SBUnionType = SBBaseType & {
27
+ name: 'union';
28
+ value: SBType[];
29
+ };
30
+ declare type SBOtherType = SBBaseType & {
31
+ name: 'other';
32
+ value: string;
33
+ };
34
+ declare type SBType = SBScalarType | SBEnumType | SBArrayType | SBObjectType | SBIntersectionType | SBUnionType | SBOtherType;
35
+
36
+ declare type StoryId = string;
37
+ declare type ComponentId = string;
38
+ declare type ComponentTitle = string;
39
+ declare type StoryName = string;
40
+ /** @deprecated */
41
+ declare type StoryKind = ComponentTitle;
42
+ interface StoryIdentifier {
43
+ componentId: ComponentId;
44
+ title: ComponentTitle;
45
+ /** @deprecated */
46
+ kind: ComponentTitle;
47
+ id: StoryId;
48
+ name: StoryName;
49
+ /** @deprecated */
50
+ story: StoryName;
51
+ }
52
+ declare type Parameters = {
53
+ [name: string]: any;
54
+ };
55
+ declare type ConditionalTest = {
56
+ truthy?: boolean;
57
+ } | {
58
+ exists: boolean;
59
+ } | {
60
+ eq: any;
61
+ } | {
62
+ neq: any;
63
+ };
64
+ declare type ConditionalValue = {
65
+ arg: string;
66
+ } | {
67
+ global: string;
68
+ };
69
+ declare type Conditional = ConditionalValue & ConditionalTest;
70
+ interface InputType {
71
+ name?: string;
72
+ description?: string;
73
+ defaultValue?: any;
74
+ type?: SBType | SBScalarType['name'];
75
+ if?: Conditional;
76
+ [key: string]: any;
77
+ }
78
+ interface StrictInputType extends InputType {
79
+ name: string;
80
+ type?: SBType;
81
+ }
82
+ declare type Args = {
83
+ [name: string]: any;
84
+ };
85
+ declare type ArgTypes<TArgs = Args> = {
86
+ [name in keyof TArgs]: InputType;
87
+ };
88
+ declare type StrictArgTypes<TArgs = Args> = {
89
+ [name in keyof TArgs]: StrictInputType;
90
+ };
91
+ declare type Globals = {
92
+ [name: string]: any;
93
+ };
94
+ declare type GlobalTypes = {
95
+ [name: string]: InputType;
96
+ };
97
+ declare type StrictGlobalTypes = {
98
+ [name: string]: StrictInputType;
99
+ };
100
+ declare type AnyFramework = {
101
+ component: unknown;
102
+ storyResult: unknown;
103
+ T?: unknown;
104
+ };
105
+ declare type StoryContextForEnhancers<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryIdentifier & {
106
+ component?: (TFramework & {
107
+ T: any;
108
+ })['component'];
109
+ subcomponents?: Record<string, (TFramework & {
110
+ T: any;
111
+ })['component']>;
112
+ parameters: Parameters;
113
+ initialArgs: TArgs;
114
+ argTypes: StrictArgTypes<TArgs>;
115
+ };
116
+ declare type ArgsEnhancer<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: StoryContextForEnhancers<TFramework, TArgs>) => TArgs;
117
+ declare type ArgTypesEnhancer<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = ((context: StoryContextForEnhancers<TFramework, TArgs>) => StrictArgTypes<TArgs>) & {
118
+ secondPass?: boolean;
119
+ };
120
+ declare type StoryContextUpdate<TArgs = Args> = {
121
+ args?: TArgs;
122
+ globals?: Globals;
123
+ [key: string]: any;
124
+ };
125
+ declare type ViewMode = 'story' | 'docs';
126
+ declare type StoryContextForLoaders<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryContextForEnhancers<TFramework, TArgs> & Required<StoryContextUpdate<TArgs>> & {
127
+ hooks: unknown;
128
+ viewMode: ViewMode;
129
+ originalStoryFn: StoryFn<TFramework>;
130
+ };
131
+ declare type LoaderFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: StoryContextForLoaders<TFramework, TArgs>) => Promise<Record<string, any>>;
132
+ declare type StoryContext<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryContextForLoaders<TFramework, TArgs> & {
133
+ loaded: Record<string, any>;
134
+ abortSignal: AbortSignal;
135
+ canvasElement: HTMLElement;
136
+ };
137
+ declare type StepLabel = string;
138
+ declare type StepFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (label: StepLabel, play: PlayFunction<TFramework, TArgs>) => Promise<void> | void;
139
+ declare type PlayFunctionContext<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryContext<TFramework, TArgs> & {
140
+ step: StepFunction<TFramework, TArgs>;
141
+ };
142
+ declare type PlayFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: PlayFunctionContext<TFramework, TArgs>) => Promise<void> | void;
143
+ declare type PartialStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (update?: StoryContextUpdate<Partial<TArgs>>) => TFramework['storyResult'];
144
+ declare type LegacyStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: StoryContext<TFramework, TArgs>) => TFramework['storyResult'];
145
+ declare type ArgsStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (args: TArgs, context: StoryContext<TFramework, TArgs>) => (TFramework & {
146
+ T: TArgs;
147
+ })['storyResult'];
148
+ declare type StoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = LegacyStoryFn<TFramework, TArgs> | ArgsStoryFn<TFramework, TArgs>;
149
+ declare type DecoratorFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (fn: PartialStoryFn<TFramework, TArgs>, c: StoryContext<TFramework, TArgs>) => TFramework['storyResult'];
150
+ declare type DecoratorApplicator<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (storyFn: LegacyStoryFn<TFramework, TArgs>, decorators: DecoratorFunction<TFramework, TArgs>[]) => LegacyStoryFn<TFramework, TArgs>;
151
+ declare type StepRunner<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (label: StepLabel, play: PlayFunction<TFramework, TArgs>, context: PlayFunctionContext<TFramework, TArgs>) => Promise<void>;
152
+ declare type BaseAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = {
153
+ /**
154
+ * Wrapper components or Storybook decorators that wrap a story.
155
+ *
156
+ * Decorators defined in Meta will be applied to every story variation.
157
+ * @see [Decorators](https://storybook.js.org/docs/addons/introduction/#1-decorators)
158
+ */
159
+ decorators?: DecoratorFunction<TFramework, TArgs>[];
160
+ /**
161
+ * Custom metadata for a story.
162
+ * @see [Parameters](https://storybook.js.org/docs/basics/writing-stories/#parameters)
163
+ */
164
+ parameters?: Parameters;
165
+ /**
166
+ * Dynamic data that are provided (and possibly updated by) Storybook and its addons.
167
+ * @see [Arg story inputs](https://storybook.js.org/docs/react/api/csf#args-story-inputs)
168
+ */
169
+ args?: Partial<TArgs>;
170
+ /**
171
+ * ArgTypes encode basic metadata for args, such as `name`, `description`, `defaultValue` for an arg. These get automatically filled in by Storybook Docs.
172
+ * @see [Control annotations](https://github.com/storybookjs/storybook/blob/91e9dee33faa8eff0b342a366845de7100415367/addons/controls/README.md#control-annotations)
173
+ */
174
+ argTypes?: Partial<ArgTypes<TArgs>>;
175
+ /**
176
+ * Asynchronous functions which provide data for a story.
177
+ * @see [Loaders](https://storybook.js.org/docs/react/writing-stories/loaders)
178
+ */
179
+ loaders?: LoaderFunction<TFramework, TArgs>[];
180
+ /**
181
+ * Define a custom render function for the story(ies). If not passed, a default render function by the framework will be used.
182
+ */
183
+ render?: ArgsStoryFn<TFramework, TArgs>;
184
+ };
185
+ declare type ProjectAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = BaseAnnotations<TFramework, TArgs> & {
186
+ argsEnhancers?: ArgsEnhancer<TFramework, Args>[];
187
+ argTypesEnhancers?: ArgTypesEnhancer<TFramework, Args>[];
188
+ globals?: Globals;
189
+ globalTypes?: GlobalTypes;
190
+ applyDecorators?: DecoratorApplicator<TFramework, Args>;
191
+ runStep?: StepRunner<TFramework, TArgs>;
192
+ };
193
+ declare type StoryDescriptor$1 = string[] | RegExp;
194
+ interface ComponentAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args> extends BaseAnnotations<TFramework, TArgs> {
195
+ /**
196
+ * Title of the component which will be presented in the navigation. **Should be unique.**
197
+ *
198
+ * Components can be organized in a nested structure using "/" as a separator.
199
+ *
200
+ * Since CSF 3.0 this property is optional -- it can be inferred from the filesystem path
201
+ *
202
+ * @example
203
+ * export default {
204
+ * ...
205
+ * title: 'Design System/Atoms/Button'
206
+ * }
207
+ *
208
+ * @see [Story Hierarchy](https://storybook.js.org/docs/basics/writing-stories/#story-hierarchy)
209
+ */
210
+ title?: ComponentTitle;
211
+ /**
212
+ * Id of the component (prefix of the story id) which is used for URLs.
213
+ *
214
+ * By default is inferred from sanitizing the title
215
+ *
216
+ * @see [Story Hierarchy](https://storybook.js.org/docs/basics/writing-stories/#story-hierarchy)
217
+ */
218
+ id?: ComponentId;
219
+ /**
220
+ * Used to only include certain named exports as stories. Useful when you want to have non-story exports such as mock data or ignore a few stories.
221
+ * @example
222
+ * includeStories: ['SimpleStory', 'ComplexStory']
223
+ * includeStories: /.*Story$/
224
+ *
225
+ * @see [Non-story exports](https://storybook.js.org/docs/formats/component-story-format/#non-story-exports)
226
+ */
227
+ includeStories?: StoryDescriptor$1;
228
+ /**
229
+ * Used to exclude certain named exports. Useful when you want to have non-story exports such as mock data or ignore a few stories.
230
+ * @example
231
+ * excludeStories: ['simpleData', 'complexData']
232
+ * excludeStories: /.*Data$/
233
+ *
234
+ * @see [Non-story exports](https://storybook.js.org/docs/formats/component-story-format/#non-story-exports)
235
+ */
236
+ excludeStories?: StoryDescriptor$1;
237
+ /**
238
+ * The primary component for your story.
239
+ *
240
+ * Used by addons for automatic prop table generation and display of other component metadata.
241
+ */
242
+ component?: (TFramework & {
243
+ T: Args extends TArgs ? any : TArgs;
244
+ })['component'];
245
+ /**
246
+ * Auxiliary subcomponents that are part of the stories.
247
+ *
248
+ * Used by addons for automatic prop table generation and display of other component metadata.
249
+ *
250
+ * @example
251
+ * import { Button, ButtonGroup } from './components';
252
+ *
253
+ * export default {
254
+ * ...
255
+ * subcomponents: { Button, ButtonGroup }
256
+ * }
257
+ *
258
+ * By defining them each component will have its tab in the args table.
259
+ */
260
+ subcomponents?: Record<string, TFramework['component']>;
261
+ /**
262
+ * Function that is executed after the story is rendered.
263
+ */
264
+ play?: PlayFunction<TFramework, TArgs>;
265
+ }
266
+ declare type StoryAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args, TRequiredArgs = Partial<TArgs>> = BaseAnnotations<TFramework, TArgs> & {
267
+ /**
268
+ * Override the display name in the UI (CSF v3)
269
+ */
270
+ name?: StoryName;
271
+ /**
272
+ * Override the display name in the UI (CSF v2)
273
+ */
274
+ storyName?: StoryName;
275
+ /**
276
+ * Function that is executed after the story is rendered.
277
+ */
278
+ play?: PlayFunction<TFramework, TArgs>;
279
+ /** @deprecated */
280
+ story?: Omit<StoryAnnotations<TFramework, TArgs>, 'story'>;
281
+ } & ({} extends TRequiredArgs ? {
282
+ args?: TRequiredArgs;
283
+ } : {
284
+ args: TRequiredArgs;
285
+ });
286
+ declare type LegacyAnnotatedStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryFn<TFramework, TArgs> & StoryAnnotations<TFramework, TArgs>;
287
+ declare type LegacyStoryAnnotationsOrFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = LegacyAnnotatedStoryFn<TFramework, TArgs> | StoryAnnotations<TFramework, TArgs>;
288
+ declare type AnnotatedStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = ArgsStoryFn<TFramework, TArgs> & StoryAnnotations<TFramework, TArgs>;
289
+ declare type StoryAnnotationsOrFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = AnnotatedStoryFn<TFramework, TArgs> | StoryAnnotations<TFramework, TArgs>;
290
+ declare type ArgsFromMeta<TFramework extends AnyFramework, Meta> = Meta extends {
291
+ render?: ArgsStoryFn<TFramework, infer RArgs>;
292
+ loaders?: (infer Loaders)[];
293
+ decorators?: (infer Decorators)[];
294
+ } ? Simplify<RArgs & DecoratorsArgs<TFramework, Decorators> & LoaderArgs<TFramework, Loaders>> : unknown;
295
+ declare type DecoratorsArgs<TFramework extends AnyFramework, Decorators> = UnionToIntersection<Decorators extends DecoratorFunction<TFramework, infer TArgs> ? TArgs : unknown>;
296
+ declare type LoaderArgs<TFramework extends AnyFramework, Loaders> = UnionToIntersection<Loaders extends LoaderFunction<TFramework, infer TArgs> ? TArgs : unknown>;
297
+
298
+ /**
299
+ * Helper function to include/exclude an arg based on the value of other other args
300
+ * aka "conditional args"
301
+ */
302
+ declare const includeConditionalArg: (argType: InputType, args: Args, globals: Globals) => boolean;
303
+
304
+ /**
305
+ * Remove punctuation and illegal characters from a story ID.
306
+ *
307
+ * See https://gist.github.com/davidjrice/9d2af51100e41c6c4b4a
308
+ */
309
+ declare const sanitize: (string: string) => string;
310
+ /**
311
+ * Generate a storybook ID from a component/kind and story name.
312
+ */
313
+ declare const toId: (kind: string, name?: string) => string;
314
+ /**
315
+ * Transform a CSF named export into a readable story name
316
+ */
317
+ declare const storyNameFromExport: (key: string) => string;
6
318
  declare type StoryDescriptor = string[] | RegExp;
7
- export interface IncludeExcludeOptions {
319
+ interface IncludeExcludeOptions {
8
320
  includeStories?: StoryDescriptor;
9
321
  excludeStories?: StoryDescriptor;
10
322
  }
11
- export declare function isExportStory(key: string, { includeStories, excludeStories }: IncludeExcludeOptions): boolean | null;
12
- export interface SeparatorOptions {
323
+ /**
324
+ * Does a named export match CSF inclusion/exclusion options?
325
+ */
326
+ declare function isExportStory(key: string, { includeStories, excludeStories }: IncludeExcludeOptions): boolean | null;
327
+ interface SeparatorOptions {
13
328
  rootSeparator: string | RegExp;
14
329
  groupSeparator: string | RegExp;
15
330
  }
16
- export declare const parseKind: (kind: string, { rootSeparator, groupSeparator }: SeparatorOptions) => {
331
+ /**
332
+ * Parse out the component/kind name from a path, using the given separator config.
333
+ */
334
+ declare const parseKind: (kind: string, { rootSeparator, groupSeparator }: SeparatorOptions) => {
17
335
  root: string | null;
18
336
  groups: string[];
19
337
  };
20
- export interface StoryMetadata {
21
- story?: {
22
- name?: string;
23
- properties?: StoryProperties;
24
- parameters?: {
25
- [key: string]: any;
26
- };
27
- };
28
- }
338
+
339
+ export { AnnotatedStoryFn, AnyFramework, ArgTypes, ArgTypesEnhancer, Args, ArgsEnhancer, ArgsFromMeta, ArgsStoryFn, BaseAnnotations, ComponentAnnotations, ComponentId, ComponentTitle, Conditional, DecoratorApplicator, DecoratorFunction, GlobalTypes, Globals, IncludeExcludeOptions, InputType, LegacyAnnotatedStoryFn, LegacyStoryAnnotationsOrFn, LegacyStoryFn, LoaderFunction, Parameters, PartialStoryFn, PlayFunction, PlayFunctionContext, ProjectAnnotations, SBArrayType, SBEnumType, SBIntersectionType, SBObjectType, SBOtherType, SBScalarType, SBType, SBUnionType, SeparatorOptions, StepFunction, StepLabel, StepRunner, StoryAnnotations, StoryAnnotationsOrFn, StoryContext, StoryContextForEnhancers, StoryContextForLoaders, StoryContextUpdate, StoryFn, StoryId, StoryIdentifier, StoryKind, StoryName, StrictArgTypes, StrictGlobalTypes, StrictInputType, ViewMode, includeConditionalArg, isExportStory, parseKind, sanitize, storyNameFromExport, toId };
package/dist/index.js CHANGED
@@ -1,129 +1,109 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- var _exportNames = {
7
- sanitize: true,
8
- toId: true,
9
- storyNameFromExport: true,
10
- isExportStory: true,
11
- parseKind: true
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
12
11
  };
13
- exports.isExportStory = isExportStory;
14
- exports.parseKind = exports.storyNameFromExport = exports.toId = exports.sanitize = void 0;
15
-
16
- var _startCase = _interopRequireDefault(require("lodash/startCase"));
17
-
18
- var _properties = require("./properties");
19
-
20
- Object.keys(_properties).forEach(function (key) {
21
- if (key === "default" || key === "__esModule") return;
22
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
23
- Object.defineProperty(exports, key, {
24
- enumerable: true,
25
- get: function get() {
26
- return _properties[key];
27
- }
28
- });
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/index.ts
27
+ var src_exports = {};
28
+ __export(src_exports, {
29
+ includeConditionalArg: () => includeConditionalArg,
30
+ isExportStory: () => isExportStory,
31
+ parseKind: () => parseKind,
32
+ sanitize: () => sanitize,
33
+ storyNameFromExport: () => storyNameFromExport,
34
+ toId: () => toId
29
35
  });
30
-
31
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
32
-
33
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
34
-
35
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
36
-
37
- function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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; }
38
-
39
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
40
-
41
- /**
42
- * Remove punctuation and illegal characters from a story ID.
43
- *
44
- * See https://gist.github.com/davidjrice/9d2af51100e41c6c4b4a
45
- */
46
- var sanitize = function sanitize(string) {
47
- return string.toLowerCase() // eslint-disable-next-line no-useless-escape
48
- .replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '-').replace(/-+/g, '-').replace(/^-+/, '').replace(/-+$/, '');
36
+ module.exports = __toCommonJS(src_exports);
37
+ var import_startCase = __toESM(require("lodash/startCase"));
38
+
39
+ // src/includeConditionalArg.ts
40
+ var import_isEqual = __toESM(require("lodash/isEqual"));
41
+ var count = (vals) => vals.map((v) => typeof v !== "undefined").filter(Boolean).length;
42
+ var testValue = (cond, value) => {
43
+ const { exists, eq, neq, truthy } = cond;
44
+ if (count([exists, eq, neq, truthy]) > 1) {
45
+ throw new Error(`Invalid conditional test ${JSON.stringify({ exists, eq, neq })}`);
46
+ }
47
+ if (typeof eq !== "undefined") {
48
+ return (0, import_isEqual.default)(value, eq);
49
+ }
50
+ if (typeof neq !== "undefined") {
51
+ return !(0, import_isEqual.default)(value, neq);
52
+ }
53
+ if (typeof exists !== "undefined") {
54
+ const valueExists = typeof value !== "undefined";
55
+ return exists ? valueExists : !valueExists;
56
+ }
57
+ const shouldBeTruthy = typeof truthy === "undefined" ? true : truthy;
58
+ return shouldBeTruthy ? !!value : !value;
49
59
  };
50
-
51
- exports.sanitize = sanitize;
52
-
53
- var sanitizeSafe = function sanitizeSafe(string, part) {
54
- var sanitized = sanitize(string);
55
-
56
- if (sanitized === '') {
57
- throw new Error("Invalid ".concat(part, " '").concat(string, "', must include alphanumeric characters"));
60
+ var includeConditionalArg = (argType, args, globals) => {
61
+ if (!argType.if)
62
+ return true;
63
+ const { arg, global } = argType.if;
64
+ if (count([arg, global]) !== 1) {
65
+ throw new Error(`Invalid conditional value ${JSON.stringify({ arg, global })}`);
58
66
  }
59
-
60
- return sanitized;
67
+ const value = arg ? args[arg] : globals[global];
68
+ return testValue(argType.if, value);
61
69
  };
62
- /**
63
- * Generate a storybook ID from a component/kind and story name.
64
- */
65
-
66
70
 
67
- var toId = function toId(kind, name) {
68
- return "".concat(sanitizeSafe(kind, 'kind'), "--").concat(sanitizeSafe(name, 'name'));
71
+ // src/index.ts
72
+ var sanitize = (string) => {
73
+ return string.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
69
74
  };
70
- /**
71
- * Transform a CSF named export into a readable story name
72
- */
73
-
74
-
75
- exports.toId = toId;
76
-
77
- var storyNameFromExport = function storyNameFromExport(key) {
78
- return (0, _startCase["default"])(key);
75
+ var sanitizeSafe = (string, part) => {
76
+ const sanitized = sanitize(string);
77
+ if (sanitized === "") {
78
+ throw new Error(`Invalid ${part} '${string}', must include alphanumeric characters`);
79
+ }
80
+ return sanitized;
79
81
  };
80
-
81
- exports.storyNameFromExport = storyNameFromExport;
82
-
82
+ var toId = (kind, name) => `${sanitizeSafe(kind, "kind")}${name ? `--${sanitizeSafe(name, "name")}` : ""}`;
83
+ var storyNameFromExport = (key) => (0, import_startCase.default)(key);
83
84
  function matches(storyKey, arrayOrRegex) {
84
85
  if (Array.isArray(arrayOrRegex)) {
85
86
  return arrayOrRegex.includes(storyKey);
86
87
  }
87
-
88
88
  return storyKey.match(arrayOrRegex);
89
89
  }
90
- /**
91
- * Does a named export match CSF inclusion/exclusion options?
92
- */
93
-
94
-
95
- function isExportStory(key, _ref) {
96
- var includeStories = _ref.includeStories,
97
- excludeStories = _ref.excludeStories;
98
- return (// https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
99
- key !== '__esModule' && (!includeStories || matches(key, includeStories)) && (!excludeStories || !matches(key, excludeStories))
100
- );
90
+ function isExportStory(key, { includeStories, excludeStories }) {
91
+ return key !== "__esModule" && (!includeStories || matches(key, includeStories)) && (!excludeStories || !matches(key, excludeStories));
101
92
  }
102
-
103
- /**
104
- * Parse out the component/kind name from a path, using the given separator config.
105
- */
106
- var parseKind = function parseKind(kind, _ref2) {
107
- var rootSeparator = _ref2.rootSeparator,
108
- groupSeparator = _ref2.groupSeparator;
109
-
110
- var _kind$split = kind.split(rootSeparator, 2),
111
- _kind$split2 = _slicedToArray(_kind$split, 2),
112
- root = _kind$split2[0],
113
- remainder = _kind$split2[1];
114
-
115
- var groups = (remainder || kind).split(groupSeparator).filter(function (i) {
116
- return !!i;
117
- }); // when there's no remainder, it means the root wasn't found/split
118
-
93
+ var parseKind = (kind, { rootSeparator, groupSeparator }) => {
94
+ const [root, remainder] = kind.split(rootSeparator, 2);
95
+ const groups = (remainder || kind).split(groupSeparator).filter((i) => !!i);
119
96
  return {
120
97
  root: remainder ? root : null,
121
- groups: groups
98
+ groups
122
99
  };
123
100
  };
124
- /**
125
- * csf story metadata attached to the story export function
126
- */
127
-
128
-
129
- exports.parseKind = parseKind;
101
+ // Annotate the CommonJS export names for ESM import in node:
102
+ 0 && (module.exports = {
103
+ includeConditionalArg,
104
+ isExportStory,
105
+ parseKind,
106
+ sanitize,
107
+ storyNameFromExport,
108
+ toId
109
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,73 @@
1
+ // src/index.ts
2
+ import startCase from "lodash/startCase";
3
+
4
+ // src/includeConditionalArg.ts
5
+ import isEqual from "lodash/isEqual";
6
+ var count = (vals) => vals.map((v) => typeof v !== "undefined").filter(Boolean).length;
7
+ var testValue = (cond, value) => {
8
+ const { exists, eq, neq, truthy } = cond;
9
+ if (count([exists, eq, neq, truthy]) > 1) {
10
+ throw new Error(`Invalid conditional test ${JSON.stringify({ exists, eq, neq })}`);
11
+ }
12
+ if (typeof eq !== "undefined") {
13
+ return isEqual(value, eq);
14
+ }
15
+ if (typeof neq !== "undefined") {
16
+ return !isEqual(value, neq);
17
+ }
18
+ if (typeof exists !== "undefined") {
19
+ const valueExists = typeof value !== "undefined";
20
+ return exists ? valueExists : !valueExists;
21
+ }
22
+ const shouldBeTruthy = typeof truthy === "undefined" ? true : truthy;
23
+ return shouldBeTruthy ? !!value : !value;
24
+ };
25
+ var includeConditionalArg = (argType, args, globals) => {
26
+ if (!argType.if)
27
+ return true;
28
+ const { arg, global } = argType.if;
29
+ if (count([arg, global]) !== 1) {
30
+ throw new Error(`Invalid conditional value ${JSON.stringify({ arg, global })}`);
31
+ }
32
+ const value = arg ? args[arg] : globals[global];
33
+ return testValue(argType.if, value);
34
+ };
35
+
36
+ // src/index.ts
37
+ var sanitize = (string) => {
38
+ return string.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
39
+ };
40
+ var sanitizeSafe = (string, part) => {
41
+ const sanitized = sanitize(string);
42
+ if (sanitized === "") {
43
+ throw new Error(`Invalid ${part} '${string}', must include alphanumeric characters`);
44
+ }
45
+ return sanitized;
46
+ };
47
+ var toId = (kind, name) => `${sanitizeSafe(kind, "kind")}${name ? `--${sanitizeSafe(name, "name")}` : ""}`;
48
+ var storyNameFromExport = (key) => startCase(key);
49
+ function matches(storyKey, arrayOrRegex) {
50
+ if (Array.isArray(arrayOrRegex)) {
51
+ return arrayOrRegex.includes(storyKey);
52
+ }
53
+ return storyKey.match(arrayOrRegex);
54
+ }
55
+ function isExportStory(key, { includeStories, excludeStories }) {
56
+ return key !== "__esModule" && (!includeStories || matches(key, includeStories)) && (!excludeStories || !matches(key, excludeStories));
57
+ }
58
+ var parseKind = (kind, { rootSeparator, groupSeparator }) => {
59
+ const [root, remainder] = kind.split(rootSeparator, 2);
60
+ const groups = (remainder || kind).split(groupSeparator).filter((i) => !!i);
61
+ return {
62
+ root: remainder ? root : null,
63
+ groups
64
+ };
65
+ };
66
+ export {
67
+ includeConditionalArg,
68
+ isExportStory,
69
+ parseKind,
70
+ sanitize,
71
+ storyNameFromExport,
72
+ toId
73
+ };
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "@storybook/csf",
3
- "version": "0.0.2-alpha.0",
4
- "description": "Storybook Component Story Format (CSF) utilities",
3
+ "version": "0.0.2-next.0",
4
+ "description": "Component Story Format (CSF) utilities",
5
5
  "keywords": [
6
6
  "storybook",
7
7
  "component story format",
8
8
  "csf",
9
9
  "stories"
10
10
  ],
11
- "homepage": "https://github.com/storybookjs/csf",
11
+ "homepage": "https://github.com/ComponentDriven/csf",
12
12
  "bugs": {
13
- "url": "https://github.com/storybookjs/csf/issues"
13
+ "url": "https://github.com/ComponentDriven/csf/issues"
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
17
- "url": "https://github.com/storybookjs/csf.git"
17
+ "url": "https://github.com/ComponentDriven/csf.git"
18
18
  },
19
19
  "license": "MIT",
20
20
  "files": [
@@ -24,40 +24,65 @@
24
24
  "*.d.ts"
25
25
  ],
26
26
  "main": "dist/index.js",
27
+ "module": "dist/index.mjs",
27
28
  "types": "dist/index.d.ts",
28
29
  "scripts": {
29
- "build": "babel src --out-dir dist --extensions \".ts\" && tsc --emitDeclarationOnly",
30
- "lint": "eslint src --ext .js,.ts",
31
- "prepublish": "yarn build",
32
- "test": "jest"
30
+ "build": "tsup ./src/index.ts --format esm,cjs --dts",
31
+ "check": "tsc",
32
+ "lint": "eslint src --ext .ts",
33
+ "test": "jest",
34
+ "release": "yarn build && auto shipit"
33
35
  },
34
36
  "eslintConfig": {
35
37
  "extends": [
36
38
  "@storybook/eslint-config-storybook"
37
- ]
39
+ ],
40
+ "rules": {
41
+ "jest/expect-expect": [
42
+ "warn",
43
+ {
44
+ "assertFunctionNames": [
45
+ "expect",
46
+ "expectTypeOf"
47
+ ]
48
+ }
49
+ ]
50
+ }
38
51
  },
39
52
  "prettier": "@storybook/linter-config/prettier.config",
40
53
  "jest": {
41
- "testEnvironment": "node"
54
+ "preset": "ts-jest",
55
+ "testEnvironment": "node",
56
+ "roots": [
57
+ "<rootDir>/src"
58
+ ]
42
59
  },
43
60
  "dependencies": {
44
- "lodash": "^4.17.15"
61
+ "expect-type": "^0.14.2",
62
+ "lodash": "^4.17.15",
63
+ "type-fest": "^2.19.0"
45
64
  },
46
65
  "devDependencies": {
47
- "@babel/cli": "^7.7.4",
48
- "@babel/core": "^7.7.4",
49
- "@babel/preset-env": "^7.7.4",
50
- "@babel/preset-typescript": "^7.7.4",
66
+ "@auto-it/released": "^10.37.1",
51
67
  "@storybook/eslint-config-storybook": "^2.1.0",
52
- "@types/jest": "^24.0.23",
68
+ "@types/jest": "^29.2.0",
53
69
  "@types/lodash": "^4.14.149",
54
- "babel-core": "7.0.0-bridge.0",
55
- "babel-jest": "^24.9.0",
70
+ "@types/node": "^18.11.0",
71
+ "@typescript-eslint/parser": "^4.33.0",
72
+ "auto": "^10.31.0",
56
73
  "common-tags": "^1.8.0",
57
74
  "eslint": "^6.7.1",
58
- "jest": "^24.9.0",
59
- "prettier": "^1.19.1",
60
- "typescript": "^3.7.2"
75
+ "jest": "^29.2.0",
76
+ "prettier": "^2.7.1",
77
+ "ts-jest": "^29.0.3",
78
+ "tsup": "^6.3.0",
79
+ "typescript": "^4.8.4"
80
+ },
81
+ "auto": {
82
+ "plugins": [
83
+ "npm",
84
+ "released"
85
+ ]
61
86
  },
62
87
  "publishConfig": {
63
88
  "access": "public"
package/.babelrc.js DELETED
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- presets: [
3
- '@babel/preset-env',
4
- '@babel/preset-typescript',
5
- ],
6
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,137 +0,0 @@
1
- "use strict";
2
-
3
- var _ = require(".");
4
-
5
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
6
-
7
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
8
-
9
- function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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; }
10
-
11
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
12
-
13
- describe('toId', function () {
14
- [// name, kind, story, output
15
- ['handles simple cases', 'kind', 'story', 'kind--story'], ['handles basic substitution', 'a b$c?d😀e', '1-2:3', 'a-b-c-d😀e--1-2-3'], ['handles runs of non-url chars', 'a?&*b', 'story', 'a-b--story'], ['removes non-url chars from start and end', '?ab-', 'story', 'ab--story'], ['downcases', 'KIND', 'STORY', 'kind--story'], ['non-latin', 'Кнопки', 'нормальный', 'кнопки--нормальный'], ['korean', 'kind', '바보 (babo)', 'kind--바보-babo'], ['all punctuation', 'kind', 'unicorns,’–—―′¿`"<>()!.!!!{}[]%^&$*#&', 'kind--unicorns']].forEach(function (_ref) {
16
- var _ref2 = _slicedToArray(_ref, 4),
17
- name = _ref2[0],
18
- kind = _ref2[1],
19
- story = _ref2[2],
20
- output = _ref2[3];
21
-
22
- it(name, function () {
23
- expect((0, _.toId)(kind, story)).toBe(output);
24
- });
25
- });
26
- it('does not allow kind with *no* url chars', function () {
27
- expect(function () {
28
- return (0, _.toId)('?', 'asdf');
29
- }).toThrow("Invalid kind '?', must include alphanumeric characters");
30
- });
31
- it('does not allow empty kind', function () {
32
- expect(function () {
33
- return (0, _.toId)('', 'asdf');
34
- }).toThrow("Invalid kind '', must include alphanumeric characters");
35
- });
36
- it('does not allow story with *no* url chars', function () {
37
- expect(function () {
38
- return (0, _.toId)('kind', '?');
39
- }).toThrow("Invalid name '?', must include alphanumeric characters");
40
- });
41
- it('does not allow empty story', function () {
42
- expect(function () {
43
- return (0, _.toId)('kind', '');
44
- }).toThrow("Invalid name '', must include alphanumeric characters");
45
- });
46
- });
47
- describe('storyNameFromExport', function () {
48
- it('should format CSF exports with sensible defaults', function () {
49
- var testCases = {
50
- name: 'Name',
51
- someName: 'Some Name',
52
- someNAME: 'Some NAME',
53
- some_custom_NAME: 'Some Custom NAME',
54
- someName1234: 'Some Name 1234',
55
- someName1_2_3_4: 'Some Name 1 2 3 4'
56
- };
57
- Object.entries(testCases).forEach(function (_ref3) {
58
- var _ref4 = _slicedToArray(_ref3, 2),
59
- key = _ref4[0],
60
- val = _ref4[1];
61
-
62
- return expect((0, _.storyNameFromExport)(key)).toBe(val);
63
- });
64
- });
65
- });
66
- describe('isExportStory', function () {
67
- it('should exclude __esModule', function () {
68
- expect((0, _.isExportStory)('__esModule', {})).toBeFalsy();
69
- });
70
- it('should include all stories when there are no filters', function () {
71
- expect((0, _.isExportStory)('a', {})).toBeTruthy();
72
- });
73
- it('should filter stories by arrays', function () {
74
- expect((0, _.isExportStory)('a', {
75
- includeStories: ['a']
76
- })).toBeTruthy();
77
- expect((0, _.isExportStory)('a', {
78
- includeStories: []
79
- })).toBeFalsy();
80
- expect((0, _.isExportStory)('a', {
81
- includeStories: ['b']
82
- })).toBeFalsy();
83
- expect((0, _.isExportStory)('a', {
84
- excludeStories: ['a']
85
- })).toBeFalsy();
86
- expect((0, _.isExportStory)('a', {
87
- excludeStories: []
88
- })).toBeTruthy();
89
- expect((0, _.isExportStory)('a', {
90
- excludeStories: ['b']
91
- })).toBeTruthy();
92
- expect((0, _.isExportStory)('a', {
93
- includeStories: ['a'],
94
- excludeStories: ['a']
95
- })).toBeFalsy();
96
- expect((0, _.isExportStory)('a', {
97
- includeStories: [],
98
- excludeStories: []
99
- })).toBeFalsy();
100
- expect((0, _.isExportStory)('a', {
101
- includeStories: ['a'],
102
- excludeStories: ['b']
103
- })).toBeTruthy();
104
- });
105
- it('should filter stories by regex', function () {
106
- expect((0, _.isExportStory)('a', {
107
- includeStories: /a/
108
- })).toBeTruthy();
109
- expect((0, _.isExportStory)('a', {
110
- includeStories: /.*/
111
- })).toBeTruthy();
112
- expect((0, _.isExportStory)('a', {
113
- includeStories: /b/
114
- })).toBeFalsy();
115
- expect((0, _.isExportStory)('a', {
116
- excludeStories: /a/
117
- })).toBeFalsy();
118
- expect((0, _.isExportStory)('a', {
119
- excludeStories: /.*/
120
- })).toBeFalsy();
121
- expect((0, _.isExportStory)('a', {
122
- excludeStories: /b/
123
- })).toBeTruthy();
124
- expect((0, _.isExportStory)('a', {
125
- includeStories: /a/,
126
- excludeStories: ['a']
127
- })).toBeFalsy();
128
- expect((0, _.isExportStory)('a', {
129
- includeStories: /.*/,
130
- excludeStories: /.*/
131
- })).toBeFalsy();
132
- expect((0, _.isExportStory)('a', {
133
- includeStories: /a/,
134
- excludeStories: /b/
135
- })).toBeTruthy();
136
- });
137
- });
@@ -1,75 +0,0 @@
1
- export declare enum PropertyTypes {
2
- TEXT = "text",
3
- NUMBER = "number",
4
- BOOLEAN = "boolean",
5
- OPTIONS = "options",
6
- DATE = "date",
7
- COLOR = "color",
8
- BUTTON = "button",
9
- OBJECT = "object",
10
- ARRAY = "array",
11
- FILES = "files"
12
- }
13
- export interface StoryPropertyBase<T> {
14
- type: PropertyTypes;
15
- label?: string;
16
- value?: T;
17
- hideLabel?: boolean;
18
- hidden?: boolean;
19
- groupId?: string;
20
- order?: number;
21
- }
22
- export interface StoryPropertyText extends StoryPropertyBase<string> {
23
- type: PropertyTypes.TEXT;
24
- placeholder?: string;
25
- maxRows?: number;
26
- }
27
- export interface StoryPropertyBoolean extends StoryPropertyBase<boolean> {
28
- type: PropertyTypes.BOOLEAN;
29
- }
30
- export interface StoryPropertyColor extends StoryPropertyBase<string> {
31
- type: PropertyTypes.COLOR;
32
- }
33
- export interface StoryPropertyDate extends StoryPropertyBase<Date> {
34
- type: PropertyTypes.DATE;
35
- datePicker?: boolean;
36
- timePicker?: boolean;
37
- }
38
- export interface StoryPropertyFiles extends StoryPropertyBase<string[]> {
39
- type: PropertyTypes.FILES;
40
- accept?: string;
41
- }
42
- export interface StoryPropertyArray extends StoryPropertyBase<string[]> {
43
- type: PropertyTypes.ARRAY;
44
- separator?: string;
45
- }
46
- export interface StoryPropertyObject extends StoryPropertyBase<object> {
47
- type: PropertyTypes.OBJECT;
48
- }
49
- export interface StoryPropertyButton extends StoryPropertyBase<void> {
50
- type: PropertyTypes.BUTTON;
51
- onClick?: (prop: StoryPropertyButton) => void;
52
- }
53
- export declare type OptionsValueType<T = unknown> = T | string | number | string[] | number[] | {
54
- label: string;
55
- value: any;
56
- };
57
- export declare type OptionsListType<T = unknown> = {
58
- [key: string]: T;
59
- } | OptionsValueType<T>[];
60
- export interface StoryPropertyOptions<T = unknown> extends StoryPropertyBase<OptionsValueType<T>> {
61
- type: PropertyTypes.OPTIONS;
62
- options: OptionsListType<T>;
63
- display?: 'select' | 'multi-select' | 'radio' | 'inline-radio' | 'check' | 'inline-check';
64
- }
65
- export interface StoryPropertyNumber extends StoryPropertyBase<number> {
66
- type: PropertyTypes.NUMBER;
67
- range?: boolean;
68
- min?: number;
69
- max?: number;
70
- step?: number;
71
- }
72
- export declare type StoryProperty = StoryPropertyText | StoryPropertyBoolean | StoryPropertyColor | StoryPropertyDate | StoryPropertyObject | StoryPropertyButton | StoryPropertyOptions | StoryPropertyNumber | StoryPropertyArray | StoryPropertyFiles;
73
- export interface StoryProperties {
74
- [name: string]: StoryProperty;
75
- }
@@ -1,27 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.PropertyTypes = void 0;
7
-
8
- /**
9
- * Property field types
10
- * examples are provided for the different types:
11
- *
12
- */
13
- var PropertyTypes;
14
- exports.PropertyTypes = PropertyTypes;
15
-
16
- (function (PropertyTypes) {
17
- PropertyTypes["TEXT"] = "text";
18
- PropertyTypes["NUMBER"] = "number";
19
- PropertyTypes["BOOLEAN"] = "boolean";
20
- PropertyTypes["OPTIONS"] = "options";
21
- PropertyTypes["DATE"] = "date";
22
- PropertyTypes["COLOR"] = "color";
23
- PropertyTypes["BUTTON"] = "button";
24
- PropertyTypes["OBJECT"] = "object";
25
- PropertyTypes["ARRAY"] = "array";
26
- PropertyTypes["FILES"] = "files";
27
- })(PropertyTypes || (exports.PropertyTypes = PropertyTypes = {}));
@@ -1 +0,0 @@
1
- export {};
@@ -1,14 +0,0 @@
1
- "use strict";
2
-
3
- var _ = require(".");
4
-
5
- describe('properties', function () {
6
- it('type PropertyTypes.TEXT', function () {
7
- expect(function () {
8
- var prop = {
9
- type: _.PropertyTypes.TEXT
10
- };
11
- return prop.type === 'text';
12
- }).toBeTruthy();
13
- });
14
- });