-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathInput.js
91 lines (77 loc) · 2.16 KB
/
Input.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
import React from 'react'
const SIZER_STYLES = {
position: 'absolute',
width: 0,
height: 0,
visibility: 'hidden',
overflow: 'scroll',
whiteSpace: 'pre'
}
const STYLE_PROPS = [
'fontSize',
'fontFamily',
'fontWeight',
'fontStyle',
'letterSpacing',
'textTransform'
]
class Input extends React.Component {
constructor (props) {
super(props)
this.state = { inputWidth: null }
this.input = React.createRef()
this.sizer = React.createRef()
}
componentDidMount () {
if (this.props.autoresize) {
this.copyInputStyles()
this.updateInputWidth()
}
}
componentDidUpdate ({ query, placeholderText }) {
if (query !== this.props.query || placeholderText !== this.props.placeholderText) {
this.updateInputWidth()
}
}
copyInputStyles () {
const inputStyle = window.getComputedStyle(this.input.current)
STYLE_PROPS.forEach((prop) => {
this.sizer.current.style[prop] = inputStyle[prop]
})
}
updateInputWidth () {
let inputWidth
if (this.props.autoresize) {
// scrollWidth is designed to be fast not accurate.
// +2 is completely arbitrary but does the job.
inputWidth = Math.ceil(this.sizer.current.scrollWidth) + 2
}
if (inputWidth !== this.state.inputWidth) {
this.setState({ inputWidth })
}
}
render () {
const { id, query, ariaLabelText, placeholderText, expanded, classNames, inputAttributes, inputEventHandlers, index } = this.props
return (
<div className={classNames.searchWrapper}>
<input
{...inputAttributes}
{...inputEventHandlers}
ref={this.input}
value={query}
placeholder={placeholderText}
className={classNames.searchInput}
role='combobox'
aria-autocomplete='list'
aria-label={ariaLabelText || placeholderText}
aria-owns={id}
aria-activedescendant={index > -1 ? `${id}-${index}` : null}
aria-expanded={expanded}
style={{ width: this.state.inputWidth }}
/>
<div ref={this.sizer} style={SIZER_STYLES}>{query || placeholderText}</div>
</div>
)
}
}
export default Input