-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMultiSelect.tsx
More file actions
591 lines (542 loc) · 21.4 KB
/
MultiSelect.tsx
File metadata and controls
591 lines (542 loc) · 21.4 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import React, { useRef } from "react";
import { HTMLInputProps as BlueprintHTMLInputProps, Intent as BlueprintIntent } from "@blueprintjs/core";
import {
ItemRendererProps as BlueprintItemRendererProps,
MultiSelect as BlueprintMultiSelect,
MultiSelectProps as BlueprintMultiSelectProps,
} from "@blueprintjs/select";
import { removeExtraSpaces } from "../../common/utils/stringUtils";
import { CLASSPREFIX as eccgui } from "../../configuration/constants";
import { TestableComponent } from "../interfaces";
import {
ContextOverlayProps,
Highlighter,
highlighterUtils,
IconButton,
MenuItem,
OverflowText,
Spinner,
} from "./../../index";
export interface MultiSuggestFieldSelectionProps<T> {
newlySelected?: T;
newlyRemoved?: T;
selectedItems: T[];
createdItems: Partial<T>[];
}
interface MultiSuggestFieldCommonProps<T>
extends TestableComponent,
Pick<BlueprintMultiSelectProps<T>, "items" | "placeholder" | "openOnKeyDown"> {
/**
* Additional class name, space separated.
*/
className?: string;
/**
* Returns the unique ID of an item. This will be used for equality of items.
*/
itemId: (item: T) => string;
/**
* Returns the label of an item.
* this would be used in the item selection list as well as the multi-select input
*/
itemLabel: (item: T) => string;
/**
* function handler that would be called anytime an item is selected/deselected or an item is created/removed
*/
onSelection?: (params: MultiSuggestFieldSelectionProps<T>) => void;
/**
* Props to spread to `ContextOverlay`. Note that `content` cannot be changed.
*/
contextOverlayProps?: Partial<Omit<ContextOverlayProps, "content" | "children">>;
/**
* Props to spread to `TagInput`. Use `query` and `onQueryChange` to control the input.
*/
tagInputProps?: BlueprintMultiSelectProps<T>["tagInputProps"];
/** Additional properties for the (query) input field of the multi-selection. */
inputProps?: BlueprintHTMLInputProps;
/**
* prop to listen for query changes, when text is entered in the multi-select input
*/
runOnQueryChange?: (query: string) => Promise<T[] | undefined> | (T[] | undefined);
/**
* Whether the component should take up the full width of its container.
* This overrides `tagInputProps.fill`.
*/
fullWidth?: boolean;
/**
* text content to render when filtering items returns zero results.
* If omitted, "No results." will be rendered in this case.
*/
noResultText?: string;
/**
* text content to render when a new item non-existing in filtered items is about to be created .
* If omitted, "No results." will be rendered in this case.
*/
newItemCreationText?: string;
/**
* Allows to creates new item from a given query. If this is not provided then no new items can be created.
*/
createNewItemFromQuery?: (query: string) => T;
/**
* Items that were newly created and not taken from the list will be post-fixed with this string.
*/
newItemPostfix?: string;
/**
* Intent state of the multi select.
*/
intent?: BlueprintIntent;
/**
* Disables the input element
*/
disabled?: boolean;
/**
* Delay in ms how long the request for the given query should be delayed.
*/
requestDelay?: number;
/**
* Clear query when an option is selected or unselected.
* The query is empty then and the user need to enter a new query.
*/
clearQueryOnSelection?: boolean;
/**
* If set then a `div` element is used as wrapper.
* It uses the attributes given via this property.
*/
wrapperProps?: React.HTMLAttributes<HTMLDivElement>;
/**
* Function that allows us to filter values from the option list.
* If not provided, values are filtered by their labels
*/
searchPredicate?: (item: T, query: string) => boolean;
/**
* Limits the height of the input target plus its dropdown menu when it is opened.
* Need to be a `number not greater than 100` (as `vh`, a unit describing a length relative to the viewport height) or `true` (equals 100).
* If not set than the dropdown menu cannot be larger that appr. the half of the available viewport hight.
*/
limitHeightOpened?: boolean | number;
}
export type MultiSuggestFieldProps<T> = MultiSuggestFieldCommonProps<T> &
(
| {
/**
* Predefined selected values.
* `prePopulateWithItems` cannot be used then.
*/
selectedItems?: T[];
prePopulateWithItems?: never;
}
| {
selectedItems?: never;
/**
* When set to `true` will set the multi-select value with all the items provided.
* `selectedItems` cannot be used then.
*/
prePopulateWithItems?: boolean;
}
);
/**
* Element behaves very similar to `SuggestField` but allows multiple selections.
* Its value does not represent a string but a stack of objects.
*
* Example usage: input field for user created tags.
*
* Attention: there may be another `MultiSelect` component in future but this will be a re-implemented `Select` like element allowing multiple selections.
*/
export function MultiSuggestField<T>({
items,
selectedItems: externalSelectedItems,
prePopulateWithItems,
itemId,
itemLabel,
onSelection,
contextOverlayProps,
tagInputProps,
inputProps,
runOnQueryChange,
fullWidth = true,
noResultText = "No results.",
newItemCreationText = "Add new item",
newItemPostfix = " (new item)",
disabled,
createNewItemFromQuery,
requestDelay = 0,
clearQueryOnSelection = false,
className,
"data-test-id": dataTestId,
"data-testid": dataTestid,
wrapperProps,
searchPredicate,
limitHeightOpened,
intent,
...otherMultiSelectProps
}: MultiSuggestFieldProps<T>) {
type SelectionChange = { type: "selected"; item: T } | { type: "removed"; item: T } | { type: "none" };
// Options created by a user
const createdItems = useRef<T[]>([]);
// Options passed ouside (f.e. from the backend)
const [externalItems, setExternalItems] = React.useState<T[]>([...items]);
// All options (created and passed) that match the query
const [filteredItems, setFilteredItems] = React.useState<T[]>([]);
// All options (created and passed) selected by a user
const [selectedItems, setSelectedItems] = React.useState<T[]>(() =>
prePopulateWithItems ? [...items] : externalSelectedItems ? [...externalSelectedItems] : []
);
// Max height of the menu
const [calculatedMaxHeight, setCalculatedMaxHeight] = React.useState<string | null>(null);
//currently focused element in popover list
const [focusedItem, setFocusedItem] = React.useState<T | null>(null);
const [showSpinner, setShowSpinner] = React.useState(false);
const inputRef = React.useRef<HTMLInputElement>(null);
const requestState = useRef<{
query?: string;
timeoutId?: number;
}>({});
const selectionChange = useRef<SelectionChange>({ type: "none" });
/** Update external items when they change
* e.g for auto-complete when query change
*/
React.useEffect(() => {
setExternalItems(items);
setFilteredItems([...items, ...createdItems.current]);
}, [items.map((item) => itemId(item)).join("|")]);
React.useEffect(() => {
const selectionParams: MultiSuggestFieldSelectionProps<T> = {
createdItems: createdItems.current,
selectedItems,
};
if (selectionChange.current.type === "selected") {
selectionParams.newlySelected = selectionChange.current.item;
}
if (selectionChange.current.type === "removed") {
selectionParams.newlyRemoved = selectionChange.current.item;
}
onSelection?.(selectionParams);
selectionChange.current = { type: "none" };
}, [
onSelection,
selectedItems.map((item) => itemId(item)).join("|"),
createdItems.current.map((item) => itemId(item)).join("|"),
]);
/**
* Update selected items if we get new selected items from outside
*/
React.useEffect(() => {
if (!externalSelectedItems) {
return;
}
selectionChange.current = { type: "none" };
setSelectedItems(externalSelectedItems);
}, [externalSelectedItems?.map((item) => itemId(item)).join("|")]);
React.useEffect(() => {
const calculateMaxHeight = () => {
if (inputRef.current) {
// Get the height of the input target
const inputTargetHeight = inputRef.current.getBoundingClientRect().height;
// Calculate the menu dropdown by using the limited height reduced by the target height
setCalculatedMaxHeight(`calc(${maxHeightToProcess}vh - ${inputTargetHeight}px)`);
}
};
const removeListener = () => {
window.removeEventListener("resize", calculateMaxHeight);
};
if (!limitHeightOpened || (typeof limitHeightOpened === "number" && limitHeightOpened > 100))
return removeListener;
const maxHeightToProcess = typeof limitHeightOpened === "number" ? limitHeightOpened : 100;
calculateMaxHeight();
window.addEventListener("resize", calculateMaxHeight);
return removeListener;
}, [limitHeightOpened, selectedItems]);
/**
* using the equality prop specified checks if an item has already been selected
* @param matcher
* @returns
*/
const itemHasBeenSelectedAlready = (matcher: string) => {
return !!selectedItems.find((item) => itemId(item) === matcher);
};
/**
* removes already selected item from the selectedItems
* @param matcher
*/
const removeItemSelection = (matcher: string) => {
setSelectedItems((items) => {
const removedItem = items.find((item) => itemId(item) === matcher);
selectionChange.current = removedItem ? { type: "removed", item: removedItem } : { type: "none" };
return items.filter((item) => itemId(item) !== matcher);
});
};
const defaultFilterPredicate = (item: T, query: string) => {
const searchWords = highlighterUtils.extractSearchWords(query, true);
return highlighterUtils.matchesAllWords(itemLabel(item).toLowerCase(), searchWords);
};
/**
* selects and deselects an item from selection list
* if the item exists it removes it instead
* @param item
*/
const onItemSelect = (item: T) => {
if (itemHasBeenSelectedAlready(itemId(item))) {
removeItemSelection(itemId(item));
} else {
selectionChange.current = { type: "selected", item };
setSelectedItems((items) => [...items, item]);
}
if (clearQueryOnSelection) {
requestState.current.query = "";
inputRef.current?.focus();
} else {
inputRef.current?.select();
}
};
/**
* search through item list using "label prop" and update the items popover
* @param query
*/
const onQueryChange = (query: string) => {
setFilteredItems([]);
if (query.length && query !== requestState.current.query) {
requestState.current.query = query;
if (requestState.current.timeoutId) {
clearTimeout(requestState.current.timeoutId);
}
const fn = async () => {
setShowSpinner(true);
setFilteredItems([]);
const resultFromQuery = runOnQueryChange && (await runOnQueryChange(removeExtraSpaces(query)));
if (requestState.current.query === query) {
// Only use most recent request
const outsideOptions = [...(resultFromQuery ?? externalItems)];
const filter = searchPredicate ?? defaultFilterPredicate;
setFilteredItems(
[...outsideOptions, ...createdItems.current].filter((item) => filter(item, query.toLowerCase()))
);
setShowSpinner(false);
}
};
requestState.current.timeoutId = window.setTimeout(fn, requestDelay && requestDelay > 0 ? requestDelay : 0);
} else if (!query.length) {
// if the query is empty we need to show all options and reset current query
requestState.current.query = "";
setFilteredItems(() => [...externalItems, ...createdItems.current]);
}
};
// Renders the entries of the (search) options list
const optionRenderer = (label: string) => {
return <Highlighter label={label} searchValue={requestState.current.query} />;
};
/**
* defines how an item in the item list is displayed
*/
const onItemRenderer = (item: T, { handleClick, modifiers }: BlueprintItemRendererProps) => {
if (!modifiers.matchesPredicate) {
return null;
}
let label = itemLabel(item);
if (createdItems.current.find((created) => itemId(created) === itemId(item))) {
label += newItemPostfix;
}
return (
<MenuItem
active={modifiers.active}
key={itemId(item)}
icon={itemHasBeenSelectedAlready(itemId(item)) ? "state-checked" : "state-unchecked"}
onClick={handleClick}
text={optionRenderer(label)}
shouldDismissPopover={false}
/>
);
};
/**
* clear all selected items in the multi-select input
*/
const handleClear = () => {
requestState.current.query = "";
selectionChange.current = { type: "none" };
setSelectedItems([]);
setFilteredItems([...externalItems, ...createdItems.current]);
};
/**
* remove a specific item from the multi-select input
* @param label
* @param index
*/
const removeTagFromSelectionViaIndex = (_label: React.ReactNode, index: number) => {
setSelectedItems((items) => {
const removedItem = items[index];
selectionChange.current = removedItem ? { type: "removed", item: removedItem } : { type: "none" };
return [...items.slice(0, index), ...items.slice(index + 1)];
});
};
/**
* Utility function to create a new Item. createNewItemFromQuery is assumed to be defined!
*/
const createNewItem = (query: string): T => {
const newItem = createNewItemFromQuery!(query);
//set new items
createdItems.current = [...createdItems.current, newItem];
setFilteredItems((items) => [...items, newItem]);
requestState.current.query = "";
return newItem;
};
/**
* added functionality to create new item when there are no matching items on enter keypress
* @param event
*/
const handleOnKeyUp = (event: React.KeyboardEvent<HTMLElement>) => {
if (event.key === "Enter" && !filteredItems.length && !!requestState.current.query && createNewItemFromQuery) {
createNewItem(requestState.current.query);
}
inputRef.current?.focus();
};
/**
* added functionality to either create new item
* when there are no matching items or select an item on tab keypress
* @param event
*/
const handleOnKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {
if (event.key === "Tab" && !!requestState.current.query) {
event.preventDefault();
if (focusedItem) {
onItemSelect(focusedItem);
} else {
onItemSelect(createNewItem(requestState.current.query));
}
requestState.current.query = "";
setTimeout(() => inputRef.current?.focus());
}
};
/**
* create new item handler, displays the new item selector and creates a new item when selected
* @param label '
* @param active
* @param handleClick
* @returns
*/
const newItemRenderer = (label: string, active: boolean, handleClick: React.MouseEventHandler<HTMLElement>) => {
if (!createNewItemFromQuery) return undefined;
const clickHandler = (e: React.MouseEvent<HTMLElement>) => {
createNewItem(label);
handleClick(e);
};
return (
<MenuItem
id={"new-item"}
icon="item-add-artefact"
active={active}
key={label}
onClick={clickHandler}
text={<OverflowText>{`${newItemCreationText} '${label}'`}</OverflowText>}
/>
);
};
// Clear button and spinner are both shown as "right element"
const clearButton =
selectedItems.length > 0 ? (
<IconButton
disabled={disabled}
name="operation-clear"
data-test-id={dataTestId ? dataTestId + "_clearance" : undefined}
data-testid={dataTestid ? dataTestid + "_clearance" : undefined}
onClick={handleClear}
/>
) : undefined;
const spinnerProps = showSpinner
? {
rightElement: <Spinner position={"inline"} size={"tiny"} />,
}
: {};
const contentMultiSelect = (
<BlueprintMultiSelect<T>
placeholder={
!otherMultiSelectProps.placeholder && createNewItemFromQuery
? "Search for item, or enter term to create new one..."
: undefined
}
{...otherMultiSelectProps}
query={requestState.current.query}
onQueryChange={onQueryChange}
items={filteredItems}
onItemSelect={onItemSelect}
itemRenderer={onItemRenderer}
itemsEqual={(a: T, b: T) => itemId(a) === itemId(b)}
selectedItems={selectedItems}
noResults={<MenuItem disabled={true} text={noResultText} />}
tagRenderer={(item) => itemLabel(item)}
createNewItemRenderer={newItemRenderer}
onActiveItemChange={(activeItem) => setFocusedItem(activeItem)}
fill={fullWidth}
createNewItemFromQuery={createNewItemFromQuery}
disabled={disabled}
tagInputProps={{
inputProps: {
id: "item",
autoComplete: "off",
"data-test-id": dataTestId ? dataTestId + "_searchinput" : undefined,
"data-testid": dataTestid ? dataTestid + "_searchinput" : undefined,
...inputProps,
} as React.InputHTMLAttributes<HTMLInputElement>,
className: `${eccgui}-multisuggestfield ${eccgui}-multiselect` + (className ? ` ${className}` : ""),
fill: fullWidth,
inputRef: inputRef,
intent: intent,
addOnBlur: true,
onKeyDown: handleOnKeyDown,
onKeyUp: handleOnKeyUp,
onRemove: removeTagFromSelectionViaIndex,
rightElement: (
<>
{clearButton ?? null}
{otherMultiSelectProps.openOnKeyDown !== true && (
<IconButton
disabled={disabled}
name={"toggler-caretdown"}
data-test-id={dataTestId ? dataTestId + "_toggler" : undefined}
data-testid={dataTestid ? dataTestid + "_toggler" : undefined}
/>
)}
</>
),
tagProps: { minimal: true },
disabled,
...tagInputProps,
...spinnerProps,
}}
popoverTargetProps={{
className: `${eccgui}-multiselect__target`,
}}
popoverProps={{
minimal: true,
placement: "bottom-start",
matchTargetWidth: fullWidth,
...contextOverlayProps,
}}
popoverContentProps={
{
"data-test-id": dataTestId ? dataTestId + "_drowpdown" : undefined,
"data-testid": dataTestid ? dataTestid + "_dropdown" : undefined,
style: calculatedMaxHeight
? ({
"--eccgui-multisuggestfield-max-height": `${calculatedMaxHeight}`,
} as React.CSSProperties)
: undefined,
} as BlueprintMultiSelectProps<T>["popoverContentProps"]
}
/>
);
return wrapperProps || dataTestId || dataTestid ? (
<div
className={`${eccgui}-multiselect__wrapper`}
{...(wrapperProps ?? {})}
{...{ "data-test-id": dataTestId, "data-testid": dataTestid }}
>
{contentMultiSelect}
</div>
) : (
<>{contentMultiSelect}</>
);
}
// we still return the Blueprint element here because it was already used like that
/**
* @deprecated (v26) use directly <MultiSuggestField<TYPE>> (`ofType` also returns the original BlueprintJS element, not ours!)
*/
MultiSuggestField.ofType = BlueprintMultiSelect.ofType;
export default MultiSuggestField;