-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathTagInputField.tsx
More file actions
309 lines (285 loc) · 11 KB
/
TagInputField.tsx
File metadata and controls
309 lines (285 loc) · 11 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import { Tag } from '@database/entity/Tag';
import { TagCategory } from '@database/entity/TagCategory';
import { TagSuggestion } from '@shared/back/types';
import { memoizeOne } from '@renderer/util/memoize';
import * as React from 'react';
import { checkIfAncestor } from '../Util';
import { InputField, InputFieldProps } from './InputField';
import { OpenIcon } from './OpenIcon';
/** 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 TagInputFieldProps = InputFieldProps & {
/** Items to display in the drop-down list. */
tags: Tag[];
/** Called when a tag is selected */
onTagSelect?: (tag: Tag, index: number) => void;
/** Called when a tag is selected when editable */
onTagEditableSelect?: (tag: Tag, index: number) => void;
/** Called when a tag suggestion is selected */
onTagSuggestionSelect?: (suggestion: TagSuggestion) => void;
/** Called when the tag input box is submitted */
onTagSubmit?: (text: string) => void;
/** Function for getting a reference to the input element. Called whenever the reference could change. */
inputRef?: RefFunc<InputElement>;
/** Tag suggestions based on currently entered tag */
suggestions: TagSuggestion[];
/** Tag Category info */
categories: TagCategory[];
};
type TagInputFieldState = {
expanded: boolean;
};
/** An input element with a drop-down menu that can list any number of selectable and clickable text elements. */
export class TagInputField extends React.Component<TagInputFieldProps, TagInputFieldState> {
rootRef: React.RefObject<HTMLDivElement> = React.createRef();
contentRef: React.RefObject<HTMLDivElement> = React.createRef();
inputRef: React.RefObject<InputElement> = React.createRef();
constructor(props: TagInputFieldProps) {
super(props);
this.state = {
expanded: false
};
}
componentDidMount() {
document.addEventListener('mousedown', this.onGlobalMouseDown);
document.addEventListener('keydown', this.onGlobalKeyDown);
this.updatePropRefs();
}
componentDidUpdate() {
this.updatePropRefs();
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.onGlobalMouseDown);
document.removeEventListener('keydown', this.onGlobalKeyDown);
this.updatePropRefs();
}
render() {
const { suggestions, tags: items, className, editable, text } = this.props;
const { expanded } = this.state;
// Render input field
const inputField = (
<InputField
{ ...this.props }
text={text}
className={(className || '') + ' input-dropdown__input-field__input__inner'}
onChange={this.onInputChange}
onClick={this.onInputFieldClick}
onKeyDown={this.onInputKeyDown}
reference={this.inputRef} />
);
// Render
return (
<div
className={'input-dropdown' + (this.props.disabled ? ' input-dropdown--disabled' : '')}
ref={this.rootRef}>
{ editable ? inputField : undefined }
{ expanded && suggestions.length > 0 ?
<div
ref={this.contentRef}
onKeyDown={this.onSuggestionKeyDown}
className={'input-dropdown__content simple-scroll'} >
{ this.renderSuggestions(suggestions, expanded) }
</div>
: undefined }
<div
className={'tag-input-dropdown__content'}
onClick={this.onListItemClick} >
{ this.renderItems(items) }
</div>
</div>
);
}
/** Renders the list of items in the drop-down menu. */
renderSuggestions = memoizeOne<(items: TagSuggestion[], expanded: boolean) => JSX.Element[]>((items: TagSuggestion[], expanded: boolean) => {
return items.map((suggestion, index) => this.renderSuggestionItem(suggestion, index));
}, ([ itemsA, expandedA ], [ itemsB, expandedB ]) => {
return expandedA === expandedB ? checkIfArraysAreEqual(itemsA, itemsB) : false;
});
renderSuggestionItem = (suggestion: TagSuggestion, index: number) => {
const category = this.props.categories.find(c => c.id == suggestion.tag.categoryId);
const aliasRender = suggestion.alias ? (
<div className='tag-inner'>
<p>{suggestion.alias} <b className='tag_alias-joiner'>{'->'}</b> {suggestion.primaryAlias}</p>
{suggestion.tag.count ? (<p className='tag-count'>{suggestion.tag.count}</p>) : undefined}
</div>
) : (
<div className='tag-inner'>
<p>{suggestion.primaryAlias}</p>
{suggestion.tag.count ? (<p className='tag-count'>{suggestion.tag.count}</p>) : undefined}
</div>
);
return (
<div
onClick={() => this.onSuggestionItemClick(suggestion)}
data-dropdown-index={index}
className='tag-input-dropdown__suggestion' key={index} >
<OpenIcon
className='tag-icon'
color={category ? category.color : '#FFFFFF'}
key={index * 2}
icon='tag'/>
<label
className='tag-suggestion-label'
key={index * 2 + 1}
tabIndex={0}>
{aliasRender}
</label>
</div>
);
};
/** Renders the list of items in the drop-down menu. */
renderItems = memoizeOne<(items: Tag[]) => JSX.Element[]>((items: Tag[]) => {
const className = this.props.editable ? 'tag-editable' : 'tag-static';
return items.map((tag, index) => {
const category = this.props.categories.find(c => c.id == tag.categoryId);
const shownAlias = tag.primaryAlias ? tag.primaryAlias.name : 'No Primary Alias Set';
return (
<div
className={'tag ' + className}
key={index}>
<OpenIcon
className='tag-icon'
color={category ? category.color : '#FFFFFF'}
key={index * 2}
icon={category ? 'tag' : 'question-mark'}/>
<label
className='tag-label'
title={tag.description}
data-dropdown-index={index}
key={index * 2 + 1}
tabIndex={0}>
{ shownAlias }
</label>
{ this.props.editable && (
<div
className='browse-right-sidebar__title-row__buttons__discard-button'
onClick={() => this.props.onTagEditableSelect && this.props.onTagEditableSelect(this.props.tags[index], index)}>
<OpenIcon
icon='delete' />
</div>
)}
</div>
);
});
}, ([ itemsA ], [ itemsB ]) => {
return checkIfArraysAreEqual(itemsA, itemsB);
});
onListItemClick = (event: React.MouseEvent): void => {
if (!this.props.disabled) {
if (!this.props.editable) {
if (this.props.onTagSelect) {
const index = getListItemIndex(event.target);
if (index >= 0) {
this.props.onTagSelect(this.props.tags[index], index);
}
}
}
}
}
onSuggestionItemClick = (suggestion: TagSuggestion): void => {
if (!this.props.disabled) {
if (this.props.onTagSuggestionSelect) {
this.props.onTagSuggestionSelect(suggestion);
}
}
}
onInputChange = (event: React.ChangeEvent<InputElement>): void => {
if (!this.props.disabled) {
if (this.props.onChange) { this.props.onChange(event); }
}
}
onInputFieldClick = (event: React.MouseEvent): void => {
this.setState({ expanded: true });
}
onSuggestionKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
const { key } = event;
const element = document.activeElement ? document.activeElement.parentElement : document.activeElement;
if (key === 'Enter' && this.props.onTagSuggestionSelect) {
const idx = getListItemIndex(element);
if (idx > -1) {
const tagSuggestion = this.props.suggestions[idx];
this.props.onTagSuggestionSelect(tagSuggestion);
const inputElement = this.inputRef.current;
if (inputElement) { inputElement.focus(); }
}
}
if (key === 'ArrowUp' || key === 'ArrowDown') {
// Focus the first or last item
if (element && checkIfAncestor(element, this.contentRef.current)) {
const nextParent = (key === 'ArrowUp')
? element.previousSibling
: element.nextElementSibling;
if (nextParent) {
const nextChild: any = nextParent.lastChild;
if (nextChild && nextChild.focus) {
nextChild.focus();
}
}
}
event.preventDefault();
}
}
onInputKeyDown = (event: React.KeyboardEvent<InputElement>): void => {
this.setState({ expanded: true });
if (!this.props.disabled) {
const { key } = event;
if (key === 'Enter' && this.props.onTagSubmit) {
this.props.onTagSubmit(this.props.text);
}
if (key === 'ArrowUp' || key === 'ArrowDown') {
// Focus the first or last item
event.preventDefault();
const content = this.contentRef.current;
if (content) {
const parentElement = (key === 'ArrowUp') ? content.lastChild : content.firstChild;
if (parentElement) {
const childElement: any = parentElement.lastChild;
if (childElement && childElement.focus) { childElement.focus(); }
}
}
}
// Relay event
if (this.props.onKeyDown) { this.props.onKeyDown(event); }
}
}
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();
}
}
/**
* 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;
}