Last active
January 19, 2018 13:26
-
-
Save Niryo/ace32dd8c721c8800ec5fbe63ad809a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import './DevTools.css'; | |
import { observer, useExperimentalSerialization, Controller } from 'controllerim'; | |
import * as JSONPretty from 'react-json-pretty'; | |
useExperimentalSerialization(); // enables the auto indexing mechanism | |
export const DevTools = observer(class extends React.Component { | |
constructor(props) { | |
super(props); | |
// we save the snapshots in local state because if we save them on the controller it | |
// will trigger a change in the state tree and we will end up in an infinity loop: | |
this.state = { snapshots: [], sliderValue: 0 }; | |
this.handleOnSliderChange = this.handleOnSliderChange.bind(this); | |
} | |
componentWillMount() { | |
// we don't need to save things on the controller's state so | |
// we can use an anonymous controller, just to get access to the state tree: | |
this.controller = new Controller(this); | |
this.controller.addOnStateTreeChangeListener((data) => { | |
// save a snapshot object with time and data: | |
this.setState({ snapshots: this.state.snapshots.concat({ time: Date.now(), data }) }); | |
}); | |
} | |
setSnapshot(snapshot) { | |
this.controller.setStateTree(JSON.parse(snapshot.data)); | |
} | |
async handleOnSliderChange(e) { | |
const sliderValue = Number.parseInt(e.target.value, 10); | |
this.setState({ sliderValue }); | |
this.setSnapshot(this.state.snapshots[sliderValue]); | |
} | |
render() { | |
return ( | |
<div className="devToolsContainer"> | |
<div className="content"> | |
{this.props.children} | |
</div> | |
<div className="devToolsPanel"> | |
<div className="jsonViewer"> | |
<h2>State Tree</h2> | |
<JSONPretty json={JSON.stringify(this.controller.getStateTree())} /> | |
</div> | |
<div className="timeMachine"> | |
<h2>Time machine</h2> | |
<input | |
className="slider" | |
type="range" | |
min="0" | |
max={this.state.snapshots.length - 1} | |
value={this.state.sliderValue} | |
onChange={this.handleOnSliderChange} /> | |
<div>Number of saved snapshots: {this.state.snapshots.length}</div> | |
</div> | |
</div> | |
</div>); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment