Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow multiple conditionalArgs #106

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/includeConditionalArg.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ describe('includeConditionalArg', () => {
});
});
});

describe('array of conditions', () => {
it.each([
['all conditions pass', { if: [{ arg: 'a', truthy: true }, { arg: 'b', eq: 2 }] }, { a: 1, b: 2 }, {}, true],
['one condition fails', { if: [{ arg: 'a', truthy: true }, { arg: 'b', eq: 3 }] }, { a: 1, b: 2 }, {}, false],
['no conditions provided', { if: [] }, { a: 1, b: 2 }, {}, true],
])('%s', (_name, argType, args, globals, expected) => {
expect(includeConditionalArg(argType, args, globals)).toBe(expected);
});
});
describe('globals', () => {
describe('truthy', () => {
it.each([
Expand Down
24 changes: 16 additions & 8 deletions src/includeConditionalArg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,22 @@ export const testValue = (cond: Omit<Conditional, 'arg' | 'global'>, value: any)
* aka "conditional args"
*/
export const includeConditionalArg = (argType: InputType, args: Args, globals: Globals) => {
if (!argType.if) return true;
const conditions = Array.isArray(argType.if) ? argType.if : [argType.if];

for (const condition of conditions) {
if (!condition) continue;

const { arg, global } = argType.if as any;
if (count([arg, global]) !== 1) {
throw new Error(`Invalid conditional value ${JSON.stringify({ arg, global })}`);
}
const { arg, global } = condition as any;
if (count([arg, global]) !== 1) {
throw new Error(`Invalid conditional value ${JSON.stringify({ arg, global })}`);
}

const value = arg ? args[arg] : globals[global];
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return testValue(argType.if!, value);
const value = arg ? args[arg] : globals[global];
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (!testValue(condition!, value)) {
return false;
}
}

return true;
};
2 changes: 1 addition & 1 deletion src/story.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export interface InputType {
/**
* @see https://storybook.js.org/docs/api/arg-types#if
*/
if?: Conditional;
if?: Conditional | Conditional[];
/**
* @see https://storybook.js.org/docs/api/arg-types#mapping
*/
Expand Down