/
addArgsHelpers.ts
59 lines (51 loc) · 1.52 KB
/
addArgsHelpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Args } from '@storybook/addons';
import { ArgsEnhancer } from '@storybook/client-api';
import { action } from '../index';
// interface ActionsParameter {
// disable?: boolean;
// argTypesRegex?: RegExp;
// }
/**
* Automatically add action args for argTypes whose name
* matches a regex, such as `^on.*` for react-style `onClick` etc.
*/
export const inferActionsFromArgTypesRegex: ArgsEnhancer = (context) => {
const {
args,
argTypes,
parameters: { actions },
} = context;
if (!actions || actions.disable || !actions.argTypesRegex || !argTypes) {
return {};
}
const argTypesRegex = new RegExp(actions.argTypesRegex);
const argTypesMatchingRegex = Object.entries(argTypes).filter(
([name]) => !!argTypesRegex.test(name)
);
return argTypesMatchingRegex.reduce((acc, [name, argType]) => {
if (typeof args[name] === 'undefined') {
acc[name] = action(name);
}
return acc;
}, {} as Args);
};
/**
* Add action args for list of strings.
*/
export const addActionsFromArgTypes: ArgsEnhancer = (context) => {
const {
args,
argTypes,
parameters: { actions },
} = context;
if (actions?.disable || !argTypes) {
return {};
}
const argTypesWithAction = Object.entries(argTypes).filter(([name, argType]) => !!argType.action);
return argTypesWithAction.reduce((acc, [name, argType]) => {
if (typeof args[name] === 'undefined') {
acc[name] = action(typeof argType.action === 'string' ? argType.action : name);
}
return acc;
}, {} as Args);
};