Skip to content

Commit

Permalink
feat: custom serialization of mdx attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
atanasster committed Jul 3, 2020
1 parent 563add3 commit 028e366
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
6 changes: 4 additions & 2 deletions core/instrument/src/babel/extract-attributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ interface StoryAttribute {
name: string;
value: any;
}

const nodeToValue = (node: any): any => {
if (node) {
switch (node.type) {
Expand All @@ -10,7 +11,8 @@ const nodeToValue = (node: any): any => {
case 'StringLiteral':
return node.value;
case 'Identifier':
return node.name;
//String class is used when the prop value should not be stringified when serializing
return new String(node.name);
case 'Property':
return node.name;
case 'ObjectProperty':
Expand All @@ -25,7 +27,7 @@ const nodeToValue = (node: any): any => {
? value.replace(/^\/|\/$/g, '')
: value;
case 'MemberExpression':
return `${node.object.name}.${node.property.name}`;
return new String(`${node.object.name}.${node.property.name}`);
case 'ObjectExpression':
return extractAttributes(node);
case 'ArrayExpression':
Expand Down
47 changes: 46 additions & 1 deletion core/instrument/src/misc/mdx-exports.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,52 @@
import jsStringEscape from 'js-string-escape';
import { MDXExportType, MDXExportTypes } from '../types';

const stringifyObject = (
val: any,
sep: string = ' ',
depth: number = 1,
): string => {
const t = typeof val;
switch (t) {
case 'string':
return `"${jsStringEscape(val)}"`;
case 'function':
return val.name || val.toString();
case 'object':
if (val instanceof Date) {
return '"' + val.toISOString() + '"';
}
if (val instanceof String) {
return val.toString();
}
if (Array.isArray(val)) {
return (
'[' +
val.map(v => stringifyObject(v, sep, depth + 1)).join(', ') +
']'
);
}
if (val === null) {
return 'null';
}
return `
{
${Object.keys(val)
.map(key => {
return typeof val[key] === 'function'
? null
: `${key}: ${stringifyObject(val[key], sep, depth + 1)}`;
})
.filter(v => v)}
}
`;
default:
return val.toString();
}
};

const mdxPropertiesExport = (exportType: MDXExportType): string | undefined => {
return exportType ? JSON.stringify(exportType.story, null, 2) : undefined;
return exportType ? stringifyObject(exportType.story) : undefined;
};

const mdxFunctionExport = (
Expand Down

0 comments on commit 028e366

Please sign in to comment.