-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathTextInput.jsx
More file actions
108 lines (97 loc) · 2.64 KB
/
Copy pathTextInput.jsx
File metadata and controls
108 lines (97 loc) · 2.64 KB
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
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import colors from '../../theme/colors.scss';
import './TextInput.scss';
const prefixCls = 'kai-text-input';
const TextInput = ({
focusColor,
label,
index,
onFocusChange,
forwardedRef,
onChange,
enableTabSwitching,
...props,
}) => {
const [isFocused, setIsFocused] = useState(false);
const [caretPosition, setCaretPosition] = useState(0);
const [value, setValue] = useState('');
const handleKeyUp = (event) => {
if (enableTabSwitching) {
if (
(event.key === 'ArrowLeft' && caretPosition !== 0) ||
(event.key === 'ArrowRight' && caretPosition !== value.length)
) {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
}
} else {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
}
setCaretPosition(event.target.selectionStart);
};
const handleChange = (event) => {
setValue(event.target.value);
onChange(event);
};
const handleFocusChange = (isFocused) => {
const input = forwardedRef.current;
setIsFocused(isFocused);
if (isFocused) {
onFocusChange(index);
input.focus();
// Without this, it will just focus at position 0
requestAnimationFrame(() => {
input.selectionStart = caretPosition;
})
}
};
const itemCls = classnames([
prefixCls,
isFocused && `${prefixCls}--focused`
]);
const labelCls = `${prefixCls}-label p-thi`;
const inputCls = `${prefixCls}-input p-pri`;
return (
<div
tabIndex="0"
className={itemCls}
style={{ backgroundColor: isFocused ? focusColor : colors.white }}
onFocus={() => handleFocusChange(true)}
onBlur={() => handleFocusChange(false)}
>
<label className={labelCls}>{label}</label>
<input
ref={forwardedRef}
type="text"
className={inputCls}
onChange={handleChange}
onKeyUpCapture={handleKeyUp}
value={value}
{...props}
/>
</div>
);
}
TextInput.defaultProps = {
focusColor: colors.defaultFocusColor,
enableTabSwitching: false,
onChange: () => {}
};
TextInput.propTypes = {
label: PropTypes.string.isRequired,
focusColor: PropTypes.string,
forwardedRef: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({ current: PropTypes.instanceOf(Element) })
]),
index: PropTypes.number,
onFocusChange: PropTypes.func,
onChange: PropTypes.func,
enableTabSwitching: PropTypes.bool,
};
export default React.forwardRef((props, ref) => (
<TextInput forwardedRef={ref} {...props} />
));