Skip to content

Commit

Permalink
Merge pull request #22169 from gitstart/fix/wrong-multiple-mapped-args
Browse files Browse the repository at this point in the history
fix: multiple mapped args return array of labels
  • Loading branch information
JReinhold authored Apr 27, 2023
2 parents 8235a61 + fb7d968 commit 7b89042
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 2 deletions.
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' }],
});
},
};

0 comments on commit 7b89042

Please sign in to comment.