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

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,349 @@
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
+ declare type Tag = string;
43
+ interface StoryIdentifier {
44
+ componentId: ComponentId;
45
+ title: ComponentTitle;
46
+ /** @deprecated */
47
+ kind: ComponentTitle;
48
+ id: StoryId;
49
+ name: StoryName;
50
+ /** @deprecated */
51
+ story: StoryName;
52
+ tags: Tag[];
53
+ }
54
+ declare type Parameters = {
55
+ [name: string]: any;
56
+ };
57
+ declare type ConditionalTest = {
58
+ truthy?: boolean;
59
+ } | {
60
+ exists: boolean;
61
+ } | {
62
+ eq: any;
63
+ } | {
64
+ neq: any;
65
+ };
66
+ declare type ConditionalValue = {
67
+ arg: string;
68
+ } | {
69
+ global: string;
70
+ };
71
+ declare type Conditional = ConditionalValue & ConditionalTest;
72
+ interface InputType {
73
+ name?: string;
74
+ description?: string;
75
+ defaultValue?: any;
76
+ type?: SBType | SBScalarType['name'];
77
+ if?: Conditional;
78
+ [key: string]: any;
79
+ }
80
+ interface StrictInputType extends InputType {
81
+ name: string;
82
+ type?: SBType;
83
+ }
84
+ declare type Args = {
85
+ [name: string]: any;
86
+ };
87
+ declare type ArgTypes<TArgs = Args> = {
88
+ [name in keyof TArgs]: InputType;
89
+ };
90
+ declare type StrictArgTypes<TArgs = Args> = {
91
+ [name in keyof TArgs]: StrictInputType;
92
+ };
93
+ declare type Globals = {
94
+ [name: string]: any;
95
+ };
96
+ declare type GlobalTypes = {
97
+ [name: string]: InputType;
98
+ };
99
+ declare type StrictGlobalTypes = {
100
+ [name: string]: StrictInputType;
101
+ };
102
+ declare type AnyFramework = {
103
+ component: unknown;
104
+ storyResult: unknown;
105
+ T?: unknown;
106
+ };
107
+ declare type StoryContextForEnhancers<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryIdentifier & {
108
+ component?: (TFramework & {
109
+ T: any;
110
+ })['component'];
111
+ subcomponents?: Record<string, (TFramework & {
112
+ T: any;
113
+ })['component']>;
114
+ parameters: Parameters;
115
+ initialArgs: TArgs;
116
+ argTypes: StrictArgTypes<TArgs>;
117
+ };
118
+ declare type ArgsEnhancer<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: StoryContextForEnhancers<TFramework, TArgs>) => TArgs;
119
+ declare type ArgTypesEnhancer<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = ((context: StoryContextForEnhancers<TFramework, TArgs>) => StrictArgTypes<TArgs>) & {
120
+ secondPass?: boolean;
121
+ };
122
+ declare type StoryContextUpdate<TArgs = Args> = {
123
+ args?: TArgs;
124
+ globals?: Globals;
125
+ [key: string]: any;
126
+ };
127
+ declare type ViewMode = 'story' | 'docs';
128
+ declare type StoryContextForLoaders<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryContextForEnhancers<TFramework, TArgs> & Required<StoryContextUpdate<TArgs>> & {
129
+ hooks: unknown;
130
+ viewMode: ViewMode;
131
+ originalStoryFn: StoryFn<TFramework>;
132
+ };
133
+ declare type LoaderFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: StoryContextForLoaders<TFramework, TArgs>) => Promise<Record<string, any>>;
134
+ declare type StoryContext<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryContextForLoaders<TFramework, TArgs> & {
135
+ loaded: Record<string, any>;
136
+ abortSignal: AbortSignal;
137
+ canvasElement: HTMLElement;
138
+ };
139
+ declare type StepLabel = string;
140
+ declare type StepFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (label: StepLabel, play: PlayFunction<TFramework, TArgs>) => Promise<void> | void;
141
+ declare type PlayFunctionContext<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryContext<TFramework, TArgs> & {
142
+ step: StepFunction<TFramework, TArgs>;
143
+ };
144
+ declare type PlayFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: PlayFunctionContext<TFramework, TArgs>) => Promise<void> | void;
145
+ declare type PartialStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (update?: StoryContextUpdate<Partial<TArgs>>) => TFramework['storyResult'];
146
+ declare type LegacyStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (context: StoryContext<TFramework, TArgs>) => TFramework['storyResult'];
147
+ declare type ArgsStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (args: TArgs, context: StoryContext<TFramework, TArgs>) => (TFramework & {
148
+ T: TArgs;
149
+ })['storyResult'];
150
+ declare type StoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = LegacyStoryFn<TFramework, TArgs> | ArgsStoryFn<TFramework, TArgs>;
151
+ declare type DecoratorFunction<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (fn: PartialStoryFn<TFramework, TArgs>, c: StoryContext<TFramework, TArgs>) => TFramework['storyResult'];
152
+ declare type DecoratorApplicator<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (storyFn: LegacyStoryFn<TFramework, TArgs>, decorators: DecoratorFunction<TFramework, TArgs>[]) => LegacyStoryFn<TFramework, TArgs>;
153
+ declare type StepRunner<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = (label: StepLabel, play: PlayFunction<TFramework, TArgs>, context: PlayFunctionContext<TFramework, TArgs>) => Promise<void>;
154
+ declare type BaseAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = {
155
+ /**
156
+ * Wrapper components or Storybook decorators that wrap a story.
157
+ *
158
+ * Decorators defined in Meta will be applied to every story variation.
159
+ * @see [Decorators](https://storybook.js.org/docs/addons/introduction/#1-decorators)
160
+ */
161
+ decorators?: DecoratorFunction<TFramework, TArgs>[];
162
+ /**
163
+ * Custom metadata for a story.
164
+ * @see [Parameters](https://storybook.js.org/docs/basics/writing-stories/#parameters)
165
+ */
166
+ parameters?: Parameters;
167
+ /**
168
+ * Dynamic data that are provided (and possibly updated by) Storybook and its addons.
169
+ * @see [Arg story inputs](https://storybook.js.org/docs/react/api/csf#args-story-inputs)
170
+ */
171
+ args?: Partial<TArgs>;
172
+ /**
173
+ * ArgTypes encode basic metadata for args, such as `name`, `description`, `defaultValue` for an arg. These get automatically filled in by Storybook Docs.
174
+ * @see [Control annotations](https://github.com/storybookjs/storybook/blob/91e9dee33faa8eff0b342a366845de7100415367/addons/controls/README.md#control-annotations)
175
+ */
176
+ argTypes?: Partial<ArgTypes<TArgs>>;
177
+ /**
178
+ * Asynchronous functions which provide data for a story.
179
+ * @see [Loaders](https://storybook.js.org/docs/react/writing-stories/loaders)
180
+ */
181
+ loaders?: LoaderFunction<TFramework, TArgs>[];
182
+ /**
183
+ * Define a custom render function for the story(ies). If not passed, a default render function by the framework will be used.
184
+ */
185
+ render?: ArgsStoryFn<TFramework, TArgs>;
186
+ };
187
+ declare type ProjectAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = BaseAnnotations<TFramework, TArgs> & {
188
+ argsEnhancers?: ArgsEnhancer<TFramework, Args>[];
189
+ argTypesEnhancers?: ArgTypesEnhancer<TFramework, Args>[];
190
+ globals?: Globals;
191
+ globalTypes?: GlobalTypes;
192
+ applyDecorators?: DecoratorApplicator<TFramework, Args>;
193
+ runStep?: StepRunner<TFramework, TArgs>;
194
+ };
195
+ declare type StoryDescriptor$1 = string[] | RegExp;
196
+ interface ComponentAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args> extends BaseAnnotations<TFramework, TArgs> {
197
+ /**
198
+ * Title of the component which will be presented in the navigation. **Should be unique.**
199
+ *
200
+ * Components can be organized in a nested structure using "/" as a separator.
201
+ *
202
+ * Since CSF 3.0 this property is optional -- it can be inferred from the filesystem path
203
+ *
204
+ * @example
205
+ * export default {
206
+ * ...
207
+ * title: 'Design System/Atoms/Button'
208
+ * }
209
+ *
210
+ * @see [Story Hierarchy](https://storybook.js.org/docs/basics/writing-stories/#story-hierarchy)
211
+ */
212
+ title?: ComponentTitle;
213
+ /**
214
+ * Id of the component (prefix of the story id) which is used for URLs.
215
+ *
216
+ * By default is inferred from sanitizing the title
217
+ *
218
+ * @see [Story Hierarchy](https://storybook.js.org/docs/basics/writing-stories/#story-hierarchy)
219
+ */
220
+ id?: ComponentId;
221
+ /**
222
+ * 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.
223
+ * @example
224
+ * includeStories: ['SimpleStory', 'ComplexStory']
225
+ * includeStories: /.*Story$/
226
+ *
227
+ * @see [Non-story exports](https://storybook.js.org/docs/formats/component-story-format/#non-story-exports)
228
+ */
229
+ includeStories?: StoryDescriptor$1;
230
+ /**
231
+ * Used to exclude certain named exports. Useful when you want to have non-story exports such as mock data or ignore a few stories.
232
+ * @example
233
+ * excludeStories: ['simpleData', 'complexData']
234
+ * excludeStories: /.*Data$/
235
+ *
236
+ * @see [Non-story exports](https://storybook.js.org/docs/formats/component-story-format/#non-story-exports)
237
+ */
238
+ excludeStories?: StoryDescriptor$1;
239
+ /**
240
+ * The primary component for your story.
241
+ *
242
+ * Used by addons for automatic prop table generation and display of other component metadata.
243
+ */
244
+ component?: (TFramework & {
245
+ T: Args extends TArgs ? any : TArgs;
246
+ })['component'];
247
+ /**
248
+ * Auxiliary subcomponents that are part of the stories.
249
+ *
250
+ * Used by addons for automatic prop table generation and display of other component metadata.
251
+ *
252
+ * @example
253
+ * import { Button, ButtonGroup } from './components';
254
+ *
255
+ * export default {
256
+ * ...
257
+ * subcomponents: { Button, ButtonGroup }
258
+ * }
259
+ *
260
+ * By defining them each component will have its tab in the args table.
261
+ */
262
+ subcomponents?: Record<string, TFramework['component']>;
263
+ /**
264
+ * Function that is executed after the story is rendered.
265
+ */
266
+ play?: PlayFunction<TFramework, TArgs>;
267
+ /**
268
+ * Named tags for a story, used to filter stories in different contexts.
269
+ */
270
+ tags?: Tag[];
271
+ }
272
+ declare type StoryAnnotations<TFramework extends AnyFramework = AnyFramework, TArgs = Args, TRequiredArgs = Partial<TArgs>> = BaseAnnotations<TFramework, TArgs> & {
273
+ /**
274
+ * Override the display name in the UI (CSF v3)
275
+ */
276
+ name?: StoryName;
277
+ /**
278
+ * Override the display name in the UI (CSF v2)
279
+ */
280
+ storyName?: StoryName;
281
+ /**
282
+ * Function that is executed after the story is rendered.
283
+ */
284
+ play?: PlayFunction<TFramework, TArgs>;
285
+ /**
286
+ * Named tags for a story, used to filter stories in different contexts.
287
+ */
288
+ tags?: Tag[];
289
+ /** @deprecated */
290
+ story?: Omit<StoryAnnotations<TFramework, TArgs>, 'story'>;
291
+ } & ({} extends TRequiredArgs ? {
292
+ args?: TRequiredArgs;
293
+ } : {
294
+ args: TRequiredArgs;
295
+ });
296
+ declare type LegacyAnnotatedStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = StoryFn<TFramework, TArgs> & StoryAnnotations<TFramework, TArgs>;
297
+ declare type LegacyStoryAnnotationsOrFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = LegacyAnnotatedStoryFn<TFramework, TArgs> | StoryAnnotations<TFramework, TArgs>;
298
+ declare type AnnotatedStoryFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = ArgsStoryFn<TFramework, TArgs> & StoryAnnotations<TFramework, TArgs>;
299
+ declare type StoryAnnotationsOrFn<TFramework extends AnyFramework = AnyFramework, TArgs = Args> = AnnotatedStoryFn<TFramework, TArgs> | StoryAnnotations<TFramework, TArgs>;
300
+ declare type ArgsFromMeta<TFramework extends AnyFramework, Meta> = Meta extends {
301
+ render?: ArgsStoryFn<TFramework, infer RArgs>;
302
+ loaders?: (infer Loaders)[];
303
+ decorators?: (infer Decorators)[];
304
+ } ? Simplify<RArgs & DecoratorsArgs<TFramework, Decorators> & LoaderArgs<TFramework, Loaders>> : unknown;
305
+ declare type DecoratorsArgs<TFramework extends AnyFramework, Decorators> = UnionToIntersection<Decorators extends DecoratorFunction<TFramework, infer TArgs> ? TArgs : unknown>;
306
+ declare type LoaderArgs<TFramework extends AnyFramework, Loaders> = UnionToIntersection<Loaders extends LoaderFunction<TFramework, infer TArgs> ? TArgs : unknown>;
307
+
308
+ /**
309
+ * Helper function to include/exclude an arg based on the value of other other args
310
+ * aka "conditional args"
311
+ */
312
+ declare const includeConditionalArg: (argType: InputType, args: Args, globals: Globals) => boolean;
313
+
314
+ /**
315
+ * Remove punctuation and illegal characters from a story ID.
316
+ *
317
+ * See https://gist.github.com/davidjrice/9d2af51100e41c6c4b4a
318
+ */
319
+ declare const sanitize: (string: string) => string;
320
+ /**
321
+ * Generate a storybook ID from a component/kind and story name.
322
+ */
323
+ declare const toId: (kind: string, name?: string) => string;
324
+ /**
325
+ * Transform a CSF named export into a readable story name
326
+ */
327
+ declare const storyNameFromExport: (key: string) => string;
6
328
  declare type StoryDescriptor = string[] | RegExp;
7
- export interface IncludeExcludeOptions {
329
+ interface IncludeExcludeOptions {
8
330
  includeStories?: StoryDescriptor;
9
331
  excludeStories?: StoryDescriptor;
10
332
  }
11
- export declare function isExportStory(key: string, { includeStories, excludeStories }: IncludeExcludeOptions): boolean | null;
12
- export interface SeparatorOptions {
333
+ /**
334
+ * Does a named export match CSF inclusion/exclusion options?
335
+ */
336
+ declare function isExportStory(key: string, { includeStories, excludeStories }: IncludeExcludeOptions): boolean | null;
337
+ interface SeparatorOptions {
13
338
  rootSeparator: string | RegExp;
14
339
  groupSeparator: string | RegExp;
15
340
  }
16
- export declare const parseKind: (kind: string, { rootSeparator, groupSeparator }: SeparatorOptions) => {
341
+ /**
342
+ * Parse out the component/kind name from a path, using the given separator config.
343
+ */
344
+ declare const parseKind: (kind: string, { rootSeparator, groupSeparator }: SeparatorOptions) => {
17
345
  root: string | null;
18
346
  groups: string[];
19
347
  };
20
- export interface StoryMetadata {
21
- story?: {
22
- name?: string;
23
- properties?: StoryProperties;
24
- parameters?: {
25
- [key: string]: any;
26
- };
27
- };
28
- }
348
+
349
+ 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, Tag, 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.1",
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
- });