-
Notifications
You must be signed in to change notification settings - Fork 467
/
index.tsx
536 lines (467 loc) · 12.5 KB
/
index.tsx
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
/**
* SPDX-FileCopyrightText: © 2019 Liferay, Inc. <https://liferay.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
import ACT, {
Autocomplete,
Item as AutocompleteItem,
} from '@clayui/autocomplete';
import {ClayButtonWithIcon} from '@clayui/button';
import {ClayInput} from '@clayui/form';
import {
FocusScope,
InternalDispatch,
sub,
useControlledState,
useId,
} from '@clayui/shared';
import classNames from 'classnames';
import React, {useEffect, useRef, useState} from 'react';
import {Labels} from './Labels';
import type {ICollectionProps} from '@clayui/core';
import type {Item, LastChangeLiveRegion, Locator} from './types';
type Size = null | 'sm';
interface IMenuRendererProps {
/**
* Value of input
* * @deprecated since v3.49.0 - use `value` instead.
*/
inputValue: string;
locator: Locator;
onItemClick?: (item: Item) => void;
sourceItems: Array<Item>;
/**
* The value property sets the current value (controlled).
*/
value: string;
}
type MenuRenderer = (props: IMenuRendererProps) => JSX.Element;
export interface IProps<T>
extends Omit<
React.HTMLAttributes<HTMLInputElement>,
'onChange' | 'children'
>,
Omit<Partial<ICollectionProps<T, unknown>>, 'virtualize' | 'items'> {
/**
* Flag to indicate if menu is showing or not.
*/
active?: boolean;
/**
* Whether MultiSelect allows an input value not corresponding to an item
* to be added.
*/
allowsCustomLabel?: boolean;
/**
* Flag to align the Autocomplete within the viewport.
* @deprecated since v3.95.2 - it is no longer necessary...
*/
alignmentByViewport?: boolean;
/**
* Title for the `Clear All` button.
*/
clearAllTitle?: string;
/**
* Aria label for the Close button of the labels.
*/
closeButtonAriaLabel?: string;
/**
* The initial value of the active state (uncontrolled).
*/
defaultActive?: boolean;
/**
* Property to set the default value (uncontrolled).
*/
defaultValue?: string;
/**
* Set the default value of label items (uncontrolled).
*/
defaultItems?: Array<Item>;
/**
* Direction the menu will render relative to the Autocomplete.
*/
direction?: 'bottom' | 'top';
/**
* Adds a component to replace the default component that renders
* the content of the `<ClayDropDown />` component.
* @deprecated since v3.95.2
*/
menuRenderer?: MenuRenderer;
/**
* Flag that indicates to disable all features of the component.
*/
disabled?: boolean;
/**
* Flag to disabled Clear All functionality.
*/
disabledClearAll?: boolean;
/**
* Defines the description of hotkeys for the component, use this
* to handle internationalization.
* @deprecated since v3.96.1 - use `messages` instead.
*/
hotkeysDescription?: string;
/**
* Value used for each selected item's hidden input name attribute
*/
inputName?: string;
/**
* Value of input
* * @deprecated since v3.49.0 - use `value` instead.
*/
inputValue?: string;
/**
* Flag to indicate if loading icon should be rendered
* @deprecated since v3.95.2 - use `loadingState` instead.
*/
isLoading?: boolean;
/**
* Flag to indicate if input is valid or not
*/
isValid?: boolean;
/**
* Values that display as label items (controlled).
*/
items?: Array<Item>;
/**
* The off-screen live region informs screen reader users the result of
* removing or adding a label.
* @deprecated since v3.96.1 - use `messages` instead.
*/
liveRegion?: {
added: string;
removed: string;
};
/**
* Sets the name of the field to map the value/label of the item
*/
locator?: Locator;
/**
* Messages for autocomplete.
*/
messages?: {
loading: string;
notFound: string;
// Defines the description of hotkeys for the component, use this
// to handle internationalization.
hotkeys: string;
// The off-screen live region informs screen reader users the result of
// removing or adding a label.
labelAdded: string;
labelRemoved: string;
};
/**
* Callback for when the active state changes (controlled).
*/
onActiveChange?: InternalDispatch<boolean>;
/**
* Callback for when the clear all button is clicked
*/
onClearAllButtonClick?: () => void;
/**
* Callback for when the input value changes (controlled).
*/
onChange?: InternalDispatch<string>;
/**
* Callback for when items are added or removed (controlled).
*/
onItemsChange?: InternalDispatch<Array<Item>>;
/**
* Callback is called when more items need to be loaded when the scroll
* reaches the bottom.
*/
onLoadMore?: () => Promise<any> | null;
/**
* Determines the size of the Multi Select component.
*/
size?: Size;
/**
* List of pre-populated items that will show up in a dropdown menu
*/
sourceItems?: Array<Item> | null;
/**
* Path to spritemap for clay icons
*/
spritemap?: string;
/**
* The value property sets the current value (controlled).
*/
value?: string;
/**
* The current state of Autocomplete current loading. Determines whether the
* loading indicator should be shown or not.
*/
loadingState?: number;
}
const ClayMultiSelect = React.forwardRef<HTMLDivElement, IProps<unknown>>(
(
{
active: externalActive,
allowsCustomLabel = true,
alignmentByViewport,
children,
clearAllTitle = 'Clear All',
closeButtonAriaLabel = 'Remove {0}',
defaultActive = false,
defaultItems = [],
defaultValue = '',
disabled,
disabledClearAll,
hotkeysDescription,
inputName,
inputValue,
isLoading: _i,
isValid = true,
items: externalItems,
liveRegion,
locator = {
id: 'key',
label: 'label',
value: 'value',
},
loadingState,
menuRenderer: MenuRenderer,
messages = {
hotkeys: 'Press backspace to delete the current row.',
labelAdded: 'Label {0} added to the list',
labelRemoved: 'Label {0} removed to the list',
loading: 'Loading...',
notFound: 'No results found',
},
onActiveChange,
onChange,
onClearAllButtonClick,
onItemsChange,
onLoadMore,
placeholder,
size,
sourceItems = null,
spritemap,
value: externalValue,
...otherProps
}: IProps<unknown>,
ref
) => {
const containerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const lastChangesRef = useRef<LastChangeLiveRegion | null>(null);
const [isFocused, setIsFocused] = useState(false);
const [items, setItems] = useControlledState({
defaultName: 'defaultItems',
defaultValue: defaultItems,
handleName: 'onItemsChange',
name: 'items',
onChange: onItemsChange,
value: externalItems,
});
const [value, setValue] = useControlledState({
defaultName: 'defaultValue',
defaultValue,
handleName: 'onChange',
name: 'value',
onChange,
value: externalValue ?? inputValue,
});
const [active, setActive] = useControlledState({
defaultName: 'defaultActive',
defaultValue: defaultActive,
handleName: 'onActiveChange',
name: 'active',
onChange: onActiveChange,
value: externalActive,
});
const inputElementRef =
(ref as React.RefObject<HTMLInputElement>) || inputRef;
const ariaDescriptionId = useId();
const hasAsyncItems = !!onLoadMore || typeof loadingState === 'number';
const Container = MenuRenderer ? FocusScope : React.Fragment;
const containerProps = MenuRenderer ? {arrowKeysUpDown: false} : {};
// Throws the warning only when the component is mounted and avoids
// throwing it every time a rerender happens.
useEffect(() => {
if (MenuRenderer) {
console.warn(
`<ClayMultiSelect />: You are using 'menuRenderer' which is deprecated and missing the new features and improvements that have been implemented in the component try to migrate to the new composition based API to custom list items.`
);
}
}, []);
useEffect(() => {
// Backward compatibility with the `menuRenderer` API.
if (MenuRenderer && sourceItems) {
setActive(!!value && sourceItems.length !== 0);
}
}, [value]);
return (
<Container {...containerProps}>
<div
className={classNames(
'form-control form-control-tag-group input-group',
{
focus: isFocused && isValid,
[`form-control-tag-group-${size}`]: size,
}
)}
ref={containerRef}
>
<Autocomplete
{...otherProps}
active={MenuRenderer ? false : active}
allowsCustomLabel={allowsCustomLabel}
ariaDescriptionId={ariaDescriptionId}
as={Labels}
closeButtonAriaLabel={closeButtonAriaLabel}
containerElementRef={containerRef}
defaultItems={!hasAsyncItems ? sourceItems : undefined}
filterKey={locator.label}
inputName={inputName}
items={hasAsyncItems ? sourceItems : undefined}
labels={items}
lastChangesRef={lastChangesRef}
locator={locator}
menuTrigger="focus"
messages={messages}
onActiveChange={MenuRenderer ? () => {} : setActive}
onChange={setValue}
onFocus={
MenuRenderer && sourceItems
? (
event: React.FocusEvent<HTMLInputElement>
) => {
if (otherProps.onFocus) {
otherProps.onFocus(event);
}
setActive(
!!value && sourceItems.length !== 0
);
}
: otherProps.onFocus
}
onFocusChange={setIsFocused}
onItemsChange={hasAsyncItems ? () => {} : undefined}
onLabelsChange={setItems}
placeholder={placeholder}
ref={inputElementRef}
spritemap={spritemap}
value={value}
>
{(item: Item) => {
if (children && typeof children === 'function') {
const child = children(item);
return React.cloneElement(child, {
onClick: (event) => {
if (child.props.onClick) {
child.props.onClick(event);
}
if (event.defaultPrevented) {
return;
}
event.preventDefault();
setActive(false);
setItems([...items, item]);
setValue('');
},
});
}
return (
<AutocompleteItem
key={item[locator.value]}
onClick={(event) => {
event.preventDefault();
setActive(false);
setItems([...items, item]);
setValue('');
}}
>
{item[locator.label]}
</AutocompleteItem>
);
}}
</Autocomplete>
{sourceItems && MenuRenderer && sourceItems.length > 0 && (
<ACT.DropDown
active={active}
alignElementRef={containerRef}
alignmentByViewport={alignmentByViewport}
onActiveChange={setActive}
>
<MenuRenderer
inputValue={value}
locator={locator}
onItemClick={(item) => {
setItems([...items, item]);
setValue('');
if (inputElementRef.current) {
inputElementRef.current.focus();
}
}}
sourceItems={sourceItems}
value={value}
/>
</ACT.DropDown>
)}
{!disabled &&
!disabledClearAll &&
(value || items.length > 0) && (
<ClayInput.GroupItem shrink>
<ClayButtonWithIcon
aria-label={clearAllTitle}
borderless
className="component-action"
displayType="secondary"
onClick={() => {
if (onClearAllButtonClick) {
onClearAllButtonClick();
} else {
setItems([]);
setValue('');
}
if (inputElementRef.current) {
inputElementRef.current.focus();
}
}}
outline
spritemap={spritemap}
symbol="times-circle"
title={clearAllTitle}
/>
</ClayInput.GroupItem>
)}
<div className="sr-only">
<span id={ariaDescriptionId}>
{hotkeysDescription ?? messages.hotkeys}
</span>
<span aria-live="polite" aria-relevant="text">
{lastChangesRef.current
? sub(
liveRegion
? liveRegion[
lastChangesRef.current
.action
]
: lastChangesRef.current.action ===
'added'
? messages.labelAdded
: messages.labelRemoved,
[lastChangesRef.current.label]
)
: null}
</span>
</div>
</div>
</Container>
);
}
);
ClayMultiSelect.displayName = 'ClayMultiSelect';
/**
* Utility used for filtering an array of items based off the locator which
* is set to `label` by default.
* @deprecated since v3.95.2 - it is no longer necessary...
*/
export const itemLabelFilter = (
items: Array<Item>,
_value: string,
_locator = 'label'
) => items;
export default Object.assign(ClayMultiSelect, {
Item: AutocompleteItem,
});