Skip to content

Commit

Permalink
Call storyFn once and get the initial values.
Browse files Browse the repository at this point in the history
This avoids directly mutating the state while initialization of fields
in the PropEditor.
  • Loading branch information
roonyh committed Aug 30, 2016
1 parent bb13f3e commit 646922b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 28 deletions.
39 changes: 12 additions & 27 deletions src/components/PropEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ const stylesheet = {
};

export default class PropEditor extends React.Component {
constructor() {
super();
constructor(props) {
super(props);
this._handleChange = this.handleChange.bind(this);
this._createKnob = this.createKnob.bind(this);
this._shouldStoryUpdate = this.shouldStoryUpdate.bind(this);
this.state = { fields: {} };
this.state = { fields: this.props.initialValues };
}

handleChange(change) {
Expand All @@ -71,35 +71,19 @@ export default class PropEditor extends React.Component {
this.setState({ fields });
}

createKnob(name, initial, type) {
createKnob(name) {
const field = this.state.fields[name];
let { value } = field;

if (field) {
let { value } = field;
if (field.type === 'object') {
try {
value = eval(`(${value})`); // eslint-disable-line no-eval
} catch (e) {
return {};
}
if (field.type === 'object') {
try {
value = eval(`(${value})`); // eslint-disable-line no-eval
} catch (e) {
return {};
}

return value;
}

let value = initial;
if (type === 'object') {
value = JSON.stringify(value, null, 4);
}

this.state.fields[name] = {
name,
value,
type,
valid: true,
};

return initial;
return value;
}

shouldStoryUpdate() {
Expand Down Expand Up @@ -162,6 +146,7 @@ export default class PropEditor extends React.Component {
}

PropEditor.propTypes = {
initialValues: React.PropTypes.object.isRequired,
storyFn: React.PropTypes.func.isRequired,
context: React.PropTypes.object.isRequired,
};
Expand Down
25 changes: 24 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,30 @@ import React from 'react';
import PropEditor from './components/PropEditor';

export function addWithKnobs(storyName, storyFn) {
const initialValues = {};

const recordInitialValues = (name, initial, type) => {
let value = initial;
if (type === 'object') {
value = JSON.stringify(value, null, 4);
}

initialValues[name] = {
name,
value,
type,
valid: true,
};

return initial;
};

// Call storyFn once to get the initial values. Just ignore the result of
// this call.
const dummyContext = {}; // TODO: Find if this object needs some fields inside
storyFn(dummyContext, recordInitialValues);

this.add(storyName, (context) => (
<PropEditor storyFn={storyFn} context={context} />
<PropEditor storyFn={storyFn} context={context} initialValues={initialValues} />
));
}

0 comments on commit 646922b

Please sign in to comment.