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

fix: multiple mapped args return array of labels #22169

Merged
merged 10 commits into from
Apr 27, 2023
15 changes: 13 additions & 2 deletions code/lib/preview-api/src/modules/store/csf/prepareStory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,19 @@ export function prepareStory<TRenderer extends Renderer>(
}

const mappedArgs = Object.entries(finalContext.args).reduce((acc, [key, val]) => {
const mapping = finalContext.argTypes[key]?.mapping;
acc[key] = mapping && val in mapping ? mapping[val] : val;
if (!finalContext.argTypes[key]?.mapping) {
acc[key] = val;

return acc;
}

const mappingFn = (originalValue: any) =>
originalValue in finalContext.argTypes[key].mapping
? finalContext.argTypes[key].mapping[originalValue]
: originalValue;

acc[key] = Array.isArray(val) ? val.map(mappingFn) : mappingFn(val);

return acc;
}, {} as Args);

Expand Down
71 changes: 71 additions & 0 deletions code/lib/store/template/stories/argMapping.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { global as globalThis } from '@storybook/global';
import type { PartialStoryFn, PlayFunctionContext, StoryContext } from '@storybook/types';
import { within } from '@storybook/testing-library';
import { expect } from '@storybook/jest';

const arrows = {
ArrowUp: { name: 'ArrowUp' },
ArrowDown: { name: 'ArrowDown' },
ArrowLeft: { name: 'ArrowLeft' },
ArrowRight: { name: 'ArrowRight' },
};

const labels = {
ArrowUp: 'Up',
ArrowDown: 'Down',
ArrowLeft: 'Left',
ArrowRight: 'Right',
};

export default {
component: globalThis.Components.Pre,
decorators: [
(storyFn: PartialStoryFn, context: StoryContext) => {
return storyFn({
args: { object: context.args },
});
},
],
};

export const Single = {
args: {
mappingArg: 'ArrowRight',
},
argTypes: {
mappingArg: {
options: Object.keys(arrows),
mapping: arrows,
control: {
type: 'select',
labels,
},
},
},
play: async ({ canvasElement }: PlayFunctionContext<any>) => {
await expect(JSON.parse(within(canvasElement).getByTestId('pre').innerText)).toMatchObject({
mappingArg: { name: 'ArrowRight' },
});
},
};

export const Multiple = {
args: {
mappingArg: ['ArrowRight', 'ArrowLeft'],
},
argTypes: {
mappingArg: {
options: Object.keys(arrows),
mapping: arrows,
control: {
type: 'multi-select',
labels,
},
},
},
play: async ({ canvasElement }: PlayFunctionContext<any>) => {
await expect(JSON.parse(within(canvasElement).getByTestId('pre').innerText)).toMatchObject({
mappingArg: [{ name: 'ArrowRight' }, { name: 'ArrowLeft' }],
});
},
};