-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathDropdownInputField.tsx
More file actions
237 lines (214 loc) · 7.85 KB
/
DropdownInputField.tsx
File metadata and controls
237 lines (214 loc) · 7.85 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import * as React from 'react';
import { memoizeOne } from '@renderer/util/memoize';
import { checkIfAncestor } from '../Util';
import { InputField, InputFieldProps } from './InputField';
/** A function that receives a HTML element (or null). */
type RefFunc<T extends HTMLElement> = (instance: T | null) => void;
/** Input element types used by this component. */
type InputElement = HTMLInputElement | HTMLTextAreaElement;
export type DropdownInputFieldProps = InputFieldProps & {
/** Items to display in the drop-down list. */
items: string[];
/** Called when a drop-down list item is clicked or otherwise "selected". */
onItemSelect?: (text: string, index: number) => void;
/** Function for getting a reference to the input element. Called whenever the reference could change. */
inputRef?: RefFunc<InputElement>;
};
type DropdownInputFieldState = {
/** If the drop-down content is "expanded" (visible). */
expanded: boolean;
};
/** An input element with a drop-down menu that can list any number of selectable and clickable text elements. */
export class DropdownInputField extends React.Component<DropdownInputFieldProps, DropdownInputFieldState> {
rootRef: React.RefObject<HTMLDivElement> = React.createRef();
contentRef: React.RefObject<HTMLDivElement> = React.createRef();
inputRef: React.RefObject<InputElement> = React.createRef();
constructor(props: DropdownInputFieldProps) {
super(props);
this.state = {
expanded: false,
};
}
componentDidMount() {
document.addEventListener('mousedown', this.onGlobalMouseDown);
this.updatePropRefs();
}
componentDidUpdate() {
this.updatePropRefs();
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.onGlobalMouseDown);
document.removeEventListener('keydown', this.onGlobalKeyDown);
this.updatePropRefs();
}
render() {
const { items, className, editable } = this.props;
const { expanded } = this.state;
// Render input field
const inputField = (
<InputField
{ ...this.props }
className={(className || '') + ' input-dropdown__input-field__input__inner'}
onChange={this.onInputChange}
onKeyDown={this.onInputKeyDown}
reference={this.inputRef} />
);
// Render
if (editable) {
return (
<div
className={'input-dropdown' + (this.props.disabled ? ' input-dropdown--disabled' : '')}
ref={this.rootRef}
onBlur={this.onBlur}>
<div className='input-dropdown__input-field'>
<input
className='input-dropdown__input-field__back'
tabIndex={-1}
readOnly={true} />
<div className='input-dropdown__input-field__input'>
{ inputField }
</div>
<div
className='input-dropdown__input-field__button'
onMouseDown={this.onExpandButtonMouseDown} />
</div>
<div
className={'input-dropdown__content simple-scroll' + (expanded ? '' : ' input-dropdown__content--hidden')}
onClick={this.onListItemClick}
onKeyDown={this.onListItemKeyDown}
ref={this.contentRef}>
{ this.renderItems(items) }
</div>
</div>
);
} else {
return inputField;
}
}
/** Renders the list of items in the drop-down menu. */
renderItems = memoizeOne<(items: string[]) => JSX.Element[]>((items: string[]) => {
return items.map((text, index) => (
<label
key={index}
data-dropdown-index={index}
tabIndex={0}>
{text}
</label>
));
}, ([ itemsA ], [ itemsB ]) => {
return checkIfArraysAreEqual(itemsA, itemsB);
});
onGlobalMouseDown = (event: MouseEvent) => {
if (this.state.expanded && !event.defaultPrevented) {
if (!checkIfAncestor(event.target as Element | null, this.rootRef.current)) {
this.setState({ expanded: false });
}
}
}
onGlobalKeyDown = (event: KeyboardEvent): void => {
if (this.state.expanded && event.key === 'Escape') {
this.setState({ expanded: false });
if (!this.inputRef.current) { throw new Error('input field is missing'); }
this.inputRef.current.focus();
}
}
onListItemClick = (event: React.MouseEvent): void => {
if (!this.props.disabled) {
this.setState({ expanded: false });
if (this.props.onItemSelect) {
const index = getListItemIndex(event.target);
if (index >= 0) {
this.props.onItemSelect(this.props.items[index], index);
}
}
}
}
onListItemKeyDown = (event: React.KeyboardEvent): void => {
if (!this.props.disabled) {
const { key, target } = event;
// Select the focused list item
if (this.props.onItemSelect && (key === 'Enter' || key === ' ')) {
const index = getListItemIndex(target);
if (index >= 0) {
this.props.onItemSelect(this.props.items[index], index);
this.setState({ expanded: false });
// Focus the input element
const input = this.inputRef.current;
if (input && input.focus) { input.focus(); }
}
}
// Move focus up or down
if (key === 'ArrowUp' || key === 'ArrowDown') {
const element = document.activeElement;
if (element && checkIfAncestor(element, this.contentRef.current)) {
const next: any = (key === 'ArrowUp')
? element.previousSibling
: element.nextElementSibling;
if (next && next.focus) {
next.focus();
event.preventDefault();
}
}
} else {
if (!this.state.expanded) { this.setState({ expanded: true }); }
}
}
}
onBlur = (event: React.FocusEvent): void => {
const { relatedTarget } = event;
if (relatedTarget && !checkIfAncestor(relatedTarget as any, this.rootRef.current)) {
this.setState({ expanded: false });
}
}
onInputChange = (event: React.ChangeEvent<InputElement>): void => {
if (!this.props.disabled) {
if (!this.state.expanded) { this.setState({ expanded: true }); }
if (this.props.onChange) { this.props.onChange(event); }
}
}
onInputKeyDown = (event: React.KeyboardEvent<InputElement>): void => {
if (!this.props.disabled) {
const { key } = event;
if (key === 'ArrowUp' || key === 'ArrowDown') {
// Focus the first or last item, also expand the content container
event.preventDefault();
if (!this.state.expanded) { this.setState({ expanded: true }); }
const content = this.contentRef.current;
if (!content) { throw new Error('dropdown input field content div is missing'); }
const element: any = (key === 'ArrowUp') ? content.lastChild : content.firstChild;
if (element && element.focus) { element.focus(); }
}
// Relay event
if (this.props.onKeyDown) { this.props.onKeyDown(event); }
}
}
onExpandButtonMouseDown = (): void => {
if (!this.props.disabled) {
this.setState({ expanded: !this.state.expanded });
}
}
/**
* Call the "ref" property functions.
* Do this whenever there's a possibility that the referenced elements has been replaced.
*/
updatePropRefs(): void {
if (this.props.inputRef) {
this.props.inputRef(this.inputRef.current || null);
}
}
}
/** Get the index of an item element (or -1 if index was not found). */
function getListItemIndex(target: any): number {
if (target instanceof Element || target instanceof HTMLElement) {
return parseInt(target.getAttribute('data-dropdown-index') || '-1', 10);
}
return -1;
}
/** Check if two arrays are of equal length and contains the exact same items in the same order. */
function checkIfArraysAreEqual(a: Array<any>, b: Array<any>): boolean {
if (a.length !== b.length) { return false; }
for (let i = a.length; i >= 0; i--) {
if (a[i] !== b[i]) { return false; }
}
return true;
}