frontend/js/panel-config/json_textarea.js
Nash Kaminski 012e0981f2 [Bug] Do not overwrite the content of JSONTextField while the user is editing such (#895)
* Do not overwrite the context of JSONTextField while the user is editing such

* Style changes

* Handle case where valid JSON could potentially be overwritten.
2018-02-16 10:40:46 -08:00

60 lines
1.1 KiB
JavaScript

import { h, Component } from 'preact';
export default class JSONTextArea extends Component {
constructor(props) {
super(props);
this.state.isValid = true;
this.state.value = JSON.stringify(props.value || {}, null, 2);
this.onChange = this.onChange.bind(this);
}
onChange(ev) {
const value = ev.target.value;
let parsed;
let isValid;
try {
parsed = JSON.parse(value);
isValid = true;
} catch (err) {
// Invalid JSON
isValid = false;
}
this.setState({
value,
isValid,
});
if (isValid) {
this.props.onChange(parsed);
}
}
componentWillReceiveProps({ value }) {
if (value === this.props.value) return;
this.setState({
value: JSON.stringify(value, null, 2),
isValid: true,
});
}
render({ label }, { value, isValid }) {
const style = {
minWidth: 300,
width: '100%',
};
if (!isValid) {
style.border = '1px solid red';
}
return (
<paper-textarea
label={label}
value={value}
style={style}
onvalue-changed={this.onChange}
/>
);
}
}