-
-
Notifications
You must be signed in to change notification settings - Fork 459
/
Copy pathOptionList.tsx
441 lines (385 loc) · 12.9 KB
/
OptionList.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
import classNames from 'classnames';
import KeyCode from '@rc-component/util/lib/KeyCode';
import useMemo from '@rc-component/util/lib/hooks/useMemo';
import omit from '@rc-component/util/lib/omit';
import pickAttrs from '@rc-component/util/lib/pickAttrs';
import type { ListRef } from 'rc-virtual-list';
import List from 'rc-virtual-list';
import type { ScrollConfig } from 'rc-virtual-list/lib/List';
import * as React from 'react';
import { useEffect } from 'react';
import type { BaseOptionType, RawValueType } from './Select';
import SelectContext from './SelectContext';
import TransBtn from './TransBtn';
import useBaseProps from './hooks/useBaseProps';
import type { FlattenOptionData } from './interface';
import { isPlatformMac } from './utils/platformUtil';
import { isValidCount } from './utils/valueUtil';
// export interface OptionListProps<OptionsType extends object[]> {
export type OptionListProps = Record<string, never>;
export interface RefOptionListProps {
onKeyDown: React.KeyboardEventHandler;
onKeyUp: React.KeyboardEventHandler;
scrollTo?: (args: number | ScrollConfig) => void;
}
function isTitleType(content: any) {
return typeof content === 'string' || typeof content === 'number';
}
/**
* Using virtual list of option display.
* Will fallback to dom if use customize render.
*/
const OptionList: React.ForwardRefRenderFunction<RefOptionListProps, {}> = (_, ref) => {
const {
prefixCls,
id,
open,
multiple,
mode,
searchValue,
toggleOpen,
notFoundContent,
onPopupScroll,
showScrollBar,
} = useBaseProps();
const {
maxCount,
flattenOptions,
onActiveValue,
defaultActiveFirstOption,
onSelect,
menuItemSelectedIcon,
rawValues,
fieldNames,
virtual,
direction,
listHeight,
listItemHeight,
optionRender,
classNames: contextClassNames,
styles: contextStyles,
} = React.useContext(SelectContext);
const itemPrefixCls = `${prefixCls}-item`;
const memoFlattenOptions = useMemo(
() => flattenOptions,
[open, flattenOptions],
(prev, next) => next[0] && prev[1] !== next[1],
);
// =========================== List ===========================
const listRef = React.useRef<ListRef>(null);
const overMaxCount = React.useMemo<boolean>(
() => multiple && isValidCount(maxCount) && rawValues?.size >= maxCount,
[multiple, maxCount, rawValues?.size],
);
const onListMouseDown: React.MouseEventHandler<HTMLDivElement> = (event) => {
event.preventDefault();
};
const scrollIntoView = (args: number | ScrollConfig) => {
listRef.current?.scrollTo(typeof args === 'number' ? { index: args } : args);
};
// https://github.com/ant-design/ant-design/issues/34975
const isSelected = React.useCallback(
(value: RawValueType) => {
if (mode === 'combobox') {
return false;
}
return rawValues.has(value);
},
[mode, [...rawValues].toString(), rawValues.size],
);
// ========================== Active ==========================
const getEnabledActiveIndex = (index: number, offset: number = 1): number => {
const len = memoFlattenOptions.length;
for (let i = 0; i < len; i += 1) {
const current = (index + i * offset + len) % len;
const { group, data } = memoFlattenOptions[current] || {};
if (!group && !data?.disabled && (isSelected(data.value) || !overMaxCount)) {
return current;
}
}
return -1;
};
const [activeIndex, setActiveIndex] = React.useState(() => getEnabledActiveIndex(0));
const setActive = (index: number, fromKeyboard = false) => {
setActiveIndex(index);
const info = { source: fromKeyboard ? ('keyboard' as const) : ('mouse' as const) };
// Trigger active event
const flattenItem = memoFlattenOptions[index];
if (!flattenItem) {
onActiveValue(null, -1, info);
return;
}
onActiveValue(flattenItem.value, index, info);
};
// Auto active first item when list length or searchValue changed
useEffect(() => {
setActive(defaultActiveFirstOption !== false ? getEnabledActiveIndex(0) : -1);
}, [memoFlattenOptions.length, searchValue]);
// https://github.com/ant-design/ant-design/issues/48036
const isAriaSelected = React.useCallback(
(value: RawValueType) => {
if (mode === 'combobox') {
return String(value).toLowerCase() === searchValue.toLowerCase();
}
return rawValues.has(value);
},
[mode, searchValue, [...rawValues].toString(), rawValues.size],
);
// Auto scroll to item position in single mode
useEffect(() => {
/**
* React will skip `onChange` when component update.
* `setActive` function will call root accessibility state update which makes re-render.
* So we need to delay to let Input component trigger onChange first.
*/
const timeoutId = setTimeout(() => {
if (!multiple && open && rawValues.size === 1) {
const value: RawValueType = Array.from(rawValues)[0];
const index = memoFlattenOptions.findIndex(({ data }) => data.value === value);
if (index !== -1) {
setActive(index);
scrollIntoView(index);
}
}
});
// Force trigger scrollbar visible when open
if (open) {
listRef.current?.scrollTo(undefined);
}
return () => clearTimeout(timeoutId);
}, [open, searchValue]);
// ========================== Values ==========================
const onSelectValue = (value: RawValueType) => {
if (value !== undefined) {
onSelect(value, { selected: !rawValues.has(value) });
}
// Single mode should always close by select
if (!multiple) {
toggleOpen(false);
}
};
// ========================= Keyboard =========================
React.useImperativeHandle(ref, () => ({
onKeyDown: (event) => {
const { which, ctrlKey } = event;
switch (which) {
// >>> Arrow keys & ctrl + n/p on Mac
case KeyCode.N:
case KeyCode.P:
case KeyCode.UP:
case KeyCode.DOWN: {
let offset = 0;
if (which === KeyCode.UP) {
offset = -1;
} else if (which === KeyCode.DOWN) {
offset = 1;
} else if (isPlatformMac() && ctrlKey) {
if (which === KeyCode.N) {
offset = 1;
} else if (which === KeyCode.P) {
offset = -1;
}
}
if (offset !== 0) {
const nextActiveIndex = getEnabledActiveIndex(activeIndex + offset, offset);
scrollIntoView(nextActiveIndex);
setActive(nextActiveIndex, true);
}
break;
}
// >>> Select (Tab / Enter)
case KeyCode.TAB:
case KeyCode.ENTER: {
// value
const item = memoFlattenOptions[activeIndex];
if (item && !item?.data?.disabled && !overMaxCount) {
onSelectValue(item.value);
} else {
onSelectValue(undefined);
}
if (open) {
event.preventDefault();
}
break;
}
// >>> Close
case KeyCode.ESC: {
toggleOpen(false);
if (open) {
event.stopPropagation();
}
}
}
},
onKeyUp: () => {},
scrollTo: (index) => {
scrollIntoView(index);
},
}));
// ========================== Render ==========================
if (memoFlattenOptions.length === 0) {
return (
<div
role="listbox"
id={`${id}_list`}
className={`${itemPrefixCls}-empty`}
onMouseDown={onListMouseDown}
>
{notFoundContent}
</div>
);
}
const omitFieldNameList = Object.keys(fieldNames).map((key) => fieldNames[key]);
const getLabel = (item: Record<string, any>) => item.label;
function getItemAriaProps(item: FlattenOptionData<BaseOptionType>, index: number) {
const { group } = item;
return {
role: group ? 'presentation' : 'option',
id: `${id}_list_${index}`,
};
}
const renderItem = (index: number) => {
const item = memoFlattenOptions[index];
if (!item) {
return null;
}
const itemData = item.data || {};
const { value } = itemData;
const { group } = item;
const attrs = pickAttrs(itemData, true);
const mergedLabel = getLabel(item);
return item ? (
<div
aria-label={typeof mergedLabel === 'string' && !group ? mergedLabel : null}
{...attrs}
key={index}
{...getItemAriaProps(item, index)}
aria-selected={isAriaSelected(value)}
>
{value}
</div>
) : null;
};
const a11yProps = {
role: 'listbox',
id: `${id}_list`,
};
return (
<>
{virtual && (
<div {...a11yProps} style={{ height: 0, width: 0, overflow: 'hidden' }}>
{renderItem(activeIndex - 1)}
{renderItem(activeIndex)}
{renderItem(activeIndex + 1)}
</div>
)}
<List<FlattenOptionData<BaseOptionType>>
itemKey="key"
ref={listRef}
data={memoFlattenOptions}
height={listHeight}
itemHeight={listItemHeight}
fullHeight={false}
onMouseDown={onListMouseDown}
onScroll={onPopupScroll}
virtual={virtual}
direction={direction}
innerProps={virtual ? null : a11yProps}
showScrollBar={showScrollBar}
className={contextClassNames?.list}
style={contextStyles?.list}
>
{(item, itemIndex) => {
const { group, groupOption, data, label, value } = item;
const { key } = data;
// Group
if (group) {
const groupTitle = data.title ?? (isTitleType(label) ? label.toString() : undefined);
return (
<div
className={classNames(itemPrefixCls, `${itemPrefixCls}-group`, data.className)}
title={groupTitle}
>
{label !== undefined ? label : key}
</div>
);
}
const { disabled, title, children, style, className, ...otherProps } = data;
const passedProps = omit(otherProps, omitFieldNameList);
// Option
const selected = isSelected(value);
const mergedDisabled = disabled || (!selected && overMaxCount);
const optionPrefixCls = `${itemPrefixCls}-option`;
const optionClassName = classNames(
itemPrefixCls,
optionPrefixCls,
className,
contextClassNames?.listItem,
{
[`${optionPrefixCls}-grouped`]: groupOption,
[`${optionPrefixCls}-active`]: activeIndex === itemIndex && !mergedDisabled,
[`${optionPrefixCls}-disabled`]: mergedDisabled,
[`${optionPrefixCls}-selected`]: selected,
},
);
const mergedLabel = getLabel(item);
const iconVisible =
!menuItemSelectedIcon || typeof menuItemSelectedIcon === 'function' || selected;
// https://github.com/ant-design/ant-design/issues/34145
const content = typeof mergedLabel === 'number' ? mergedLabel : mergedLabel || value;
// https://github.com/ant-design/ant-design/issues/26717
let optionTitle = isTitleType(content) ? content.toString() : undefined;
if (title !== undefined) {
optionTitle = title;
}
return (
<div
{...pickAttrs(passedProps)}
{...(!virtual ? getItemAriaProps(item, itemIndex) : {})}
aria-selected={isAriaSelected(value)}
className={optionClassName}
title={optionTitle}
onMouseMove={() => {
if (activeIndex === itemIndex || mergedDisabled) {
return;
}
setActive(itemIndex);
}}
onClick={() => {
if (!mergedDisabled) {
onSelectValue(value);
}
}}
style={{ ...contextStyles?.listItem, ...style }}
>
<div className={`${optionPrefixCls}-content`}>
{typeof optionRender === 'function'
? optionRender(item, { index: itemIndex })
: content}
</div>
{React.isValidElement(menuItemSelectedIcon) || selected}
{iconVisible && (
<TransBtn
className={`${itemPrefixCls}-option-state`}
customizeIcon={menuItemSelectedIcon}
customizeIconProps={{
value,
disabled: mergedDisabled,
isSelected: selected,
}}
>
{selected ? '✓' : null}
</TransBtn>
)}
</div>
);
}}
</List>
</>
);
};
const RefOptionList = React.forwardRef(OptionList);
if (process.env.NODE_ENV !== 'production') {
RefOptionList.displayName = 'OptionList';
}
export default RefOptionList;