-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
Copy pathmake-decorator.ts
57 lines (48 loc) · 1.55 KB
/
make-decorator.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
import { StoryWrapper, StoryGetter, StoryContext } from './types';
type MakeDecoratorResult = (...args: any) => any;
interface MakeDecoratorOptions {
name: string;
parameterName: string;
skipIfNoParametersOrOptions?: boolean;
wrapper: StoryWrapper;
}
export const makeDecorator = ({
name,
parameterName,
wrapper,
skipIfNoParametersOrOptions = false,
}: MakeDecoratorOptions): MakeDecoratorResult => {
const decorator: any = (options: object) => (getStory: StoryGetter, context: StoryContext) => {
const parameters = context.parameters && context.parameters[parameterName];
if (parameters && parameters.disable) {
return getStory(context);
}
if (skipIfNoParametersOrOptions && !options && !parameters) {
return getStory(context);
}
return wrapper(getStory, context, {
options,
parameters,
});
};
return (...args: any) => {
// Used without options as .addDecorator(decorator)
if (typeof args[0] === 'function') {
return decorator()(...args);
}
return (...innerArgs: any): any => {
// Used as [.]addDecorator(decorator(options))
if (innerArgs.length > 1) {
// Used as [.]addDecorator(decorator(option1, option2))
if (args.length > 1) {
return decorator(args)(...innerArgs);
}
return decorator(...args)(...innerArgs);
}
throw new Error(
`Passing stories directly into ${name}() is not allowed,
instead use addDecorator(${name}) and pass options with the '${parameterName}' parameter`
);
};
};
};