Skip to content

Commit

Permalink
Merge pull request #15822 from yahma25/my-first-storybook-contribution
Browse files Browse the repository at this point in the history
Addon-docs: Account for non-string types when converting enums
  • Loading branch information
yannbf committed Feb 21, 2022
2 parents 390fc5d + 6d1dd06 commit 2e25ba7
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
oneOfNumber: PropTypes.oneOf([1, 2, 3]),
oneOfMiscellaneous: PropTypes.oneOf([false, true, undefined]),
oneOfStringNumber: PropTypes.oneOf(['1', '2', '3']),
oneOfString: PropTypes.oneOf(['static', 'timed']),
};
18 changes: 18 additions & 0 deletions addons/docs/src/lib/convert/convert.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,13 +594,31 @@ describe('storybook type system', () => {
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
oneOfNumber: PropTypes.oneOf([1, 2, 3]),
oneOfMiscellaneous: PropTypes.oneOf([false, true, undefined]),
oneOfStringNumber: PropTypes.oneOf(['1', '2', '3']),
oneOfString: PropTypes.oneOf(['static', 'timed']),
};
"
`);
expect(convertJs(input)).toMatchInlineSnapshot(`
{
"oneOfNumber": {
"name": "enum",
"value": [
1,
2,
3
]
},
"oneOfMiscellaneous": {
"name": "enum",
"value": [
"false",
"true",
"undefined"
]
},
"oneOfStringNumber": {
"name": "enum",
"value": [
"1",
Expand Down
12 changes: 10 additions & 2 deletions addons/docs/src/lib/convert/proptypes/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import mapValues from 'lodash/mapValues';
import { SBType } from '@storybook/csf';
import { PTType } from './types';
import { trimQuotes } from '../utils';
import { includesQuotes, trimQuotes } from '../utils';

const SIGNATURE_REGEXP = /^\(.*\) => /;

Expand All @@ -13,7 +13,15 @@ export const convert = (type: PTType): SBType | any => {

switch (name) {
case 'enum': {
const values = computed ? value : value.map((v: PTType) => trimQuotes(v.value));
const values = computed
? value
: value.map((v: PTType) => {
const trimmedValue = trimQuotes(v.value);

return includesQuotes(v.value) || Number.isNaN(Number(trimmedValue))
? trimmedValue
: Number(trimmedValue);
});
return { ...base, name, value: values };
}
case 'string':
Expand Down
1 change: 1 addition & 0 deletions addons/docs/src/lib/convert/utils.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
const QUOTE_REGEX = /^['"]|['"]$/g;
export const trimQuotes = (str: string) => str.replace(QUOTE_REGEX, '');
export const includesQuotes = (str: string) => QUOTE_REGEX.test(str);

0 comments on commit 2e25ba7

Please sign in to comment.