This repository was archived by the owner on May 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathDatString.js
99 lines (83 loc) · 2.38 KB
/
DatString.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import isString from 'lodash.isstring';
import result from 'lodash.result';
import cx from 'classnames';
export default class DatString extends Component {
static propTypes = {
className: PropTypes.string,
style: PropTypes.object,
data: PropTypes.object.isRequired,
path: PropTypes.string,
label: PropTypes.string,
labelWidth: PropTypes.string.isRequired,
liveUpdate: PropTypes.bool.isRequired,
onUpdate: PropTypes.func,
_onUpdateValue: PropTypes.func.isRequired
};
static defaultProps = {
className: null,
style: null,
path: null,
label: null,
onUpdate: () => null
};
constructor() {
super();
this.state = {
value: null
};
}
static getDerivedStateFromProps(nextProps, prevState) {
const nextValue = result(nextProps.data, nextProps.path);
if (prevState.value === nextValue) return null;
return {
value: nextValue
};
}
handleChange = event => {
const { value } = event.target;
const { liveUpdate } = this.props;
if (liveUpdate) this.update(value);
};
handleFocus = () => {
document.addEventListener('keydown', this.handleKeyDown);
};
handleBlur = () => {
document.removeEventListener('keydown', this.handleKeyDown);
window.getSelection().removeAllRanges();
const { liveUpdate } = this.props;
if (!liveUpdate) this.update();
};
handleKeyDown = event => {
const key = event.keyCode || event.which;
const { liveUpdate } = this.props;
if (key === 13 && !liveUpdate) this.update();
};
update(value) {
const { _onUpdateValue, onUpdate, path } = this.props;
_onUpdateValue(path, value);
onUpdate(value);
}
render() {
const { path, label, labelWidth, className, style } = this.props;
const labelText = isString(label) ? label : path;
return (
<li className={cx('cr', 'string', className)} style={style}>
<label>
<span className="label-text" style={{ width: labelWidth }}>
{labelText}
</span>
<input
style={{ width: `calc(100% - ${labelWidth})` }}
type="text"
value={this.state.value}
onChange={this.handleChange}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
/>
</label>
</li>
);
}
}