use reviver to inject constructor.name

This commit is contained in:
Rob Halff 2017-09-24 21:33:01 +02:00
parent dcfc078864
commit 28bcceac8c
2 changed files with 18 additions and 6 deletions

View File

@ -24,7 +24,7 @@ export default class ActionLogger extends React.Component {
}
addAction(action) {
action.data.args = action.data.args.map(arg => retrocycle(JSON.parse(arg))); // eslint-disable-line
action.data.args = action.data.args.map(arg => retrocycle(arg)); // eslint-disable-line
const isCyclic = !!action.data.args.find(arg => isObject(arg) && arg[CYCLIC_KEY]);
const actions = [...this.state.actions];
const previous = actions.length && actions[0];

View File

@ -1,8 +1,8 @@
export const CLASS_NAME_KEY = '$___storybook.className';
export const CYCLIC_KEY = '$___storybook.isCyclic';
export function muteProperties(keys, value) {
keys.forEach(key => Object.defineProperty(value, key, { enumerable: false }));
export function muteProperty(key, value) {
return Object.defineProperty(value, key, { enumerable: false });
}
export function isObject(value) {
@ -18,9 +18,19 @@ export function createFakeConstructor(obj) {
value: obj[CLASS_NAME_KEY],
});
delete obj[CLASS_NAME_KEY]; // eslint-disable-line no-param-reassign
return new FakeConstructor(obj);
}
export function reviver(key, value) {
if (isObject(value) && value[CLASS_NAME_KEY]) {
return createFakeConstructor(value);
}
return value;
}
// Based on: https://github.com/douglascrockford/JSON-js/blob/master/cycle.js
export function decycle(object, depth = 15) {
const objects = new WeakMap();
@ -76,9 +86,11 @@ export function decycle(object, depth = 15) {
})(object, '$', 0);
}
export function retrocycle($) {
export function retrocycle(json) {
const pathReg = /^\$(?:\[(?:\d+|"(?:[^\\"\u0000-\u001f]|\\([\\"/bfnrt]|u[0-9a-zA-Z]{4}))*")])*$/;
const $ = JSON.parse(json, reviver);
(function rez(value) {
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
@ -94,8 +106,6 @@ export function retrocycle($) {
}
}
} else {
muteProperties([CLASS_NAME_KEY, CYCLIC_KEY], value);
Object.keys(value).forEach(name => {
const item = value[name];
@ -113,5 +123,7 @@ export function retrocycle($) {
}
})($);
muteProperty(CYCLIC_KEY, $);
return $;
}