This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
index.tsx
113 lines (94 loc) · 2.6 KB
/
index.tsx
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import React, { PureComponent } from 'react';
import { KEY_CODES } from 'dash-table/utils/unicode';
type Submit = (value: string | undefined) => void;
interface IProps {
onCopy?: (e: any) => void;
onPaste?: (e: any) => void;
placeholder?: string;
updateOnBlur?: boolean;
updateOnSubmit?: boolean;
updateOnEnter: boolean;
stopPropagation?: boolean;
submit: Submit;
value: string | undefined;
}
interface IDefaultProps {
stopPropagation: boolean;
updateOnEnter: boolean;
updateOnBlur: boolean;
updateOnSubmit: boolean;
}
interface IState {
value: string | undefined;
}
type PropsWithDefaults = IProps & IDefaultProps;
export default class IsolatedInput extends PureComponent<IProps, IState> {
public static readonly defaultProps = {
stopPropagation: false,
updateOnEnter: true,
updateOnBlur: true,
updateOnSubmit: true
};
private get propsWithDefaults() {
return this.props as PropsWithDefaults;
}
componentWillReceiveProps(nextProps: IProps) {
const { value } = this.props;
const { value: nextValue } = nextProps;
if (value !== nextValue) {
this.setState({
value: nextValue
});
}
}
constructor(props: PropsWithDefaults) {
super(props);
this.state = {
value: props.value
};
}
handleKeyDown = (e: React.KeyboardEvent) => {
const {
stopPropagation,
updateOnEnter
} = this.propsWithDefaults;
if (stopPropagation) {
e.stopPropagation();
}
if (updateOnEnter && e.keyCode === KEY_CODES.ENTER) {
this.submit();
}
}
handleChange = (ev: any) => {
this.setState({
value: ev.target.value
});
}
submit = () =>
this.state.value !== this.props.value &&
this.props.submit(this.state.value)
render() {
const {
onCopy,
onPaste,
placeholder,
updateOnBlur,
updateOnSubmit
} = this.propsWithDefaults;
let props = {
onBlur: updateOnBlur ? this.submit : undefined,
onKeyDown: this.handleKeyDown,
onSubmit: updateOnSubmit ? this.submit : undefined
};
return (<input
ref='input'
type='text'
value={this.state.value || ''}
onChange={this.handleChange}
onCopy={onCopy}
onPaste={onPaste}
placeholder={placeholder}
{...props}
/>);
}
}