-
-
Notifications
You must be signed in to change notification settings - Fork 489
Expand file tree
/
Copy pathindex.tsx
More file actions
306 lines (264 loc) · 8.8 KB
/
index.tsx
File metadata and controls
306 lines (264 loc) · 8.8 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
import * as React from 'react';
import Affix from './Affix';
import SelectContent from './Content';
import SelectInputContext from './context';
import type { DisplayValueType, Mode, RenderNode } from '../interface';
import useBaseProps from '../hooks/useBaseProps';
import { omit, useEvent } from '@rc-component/util';
import KeyCode from '@rc-component/util/lib/KeyCode';
import { isValidateOpenKey } from '../utils/keyUtil';
import { clsx } from 'clsx';
import type { ComponentsConfig } from '../hooks/useComponents';
import { getDOM } from '@rc-component/util/lib/Dom/findDOMNode';
import { composeRef } from '@rc-component/util/lib/ref';
import pickAttrs from '@rc-component/util/lib/pickAttrs';
export interface SelectInputRef {
focus: (options?: FocusOptions) => void;
blur: () => void;
nativeElement: HTMLDivElement;
}
export interface SelectInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'prefix'> {
prefixCls: string;
prefix?: React.ReactNode;
suffix?: React.ReactNode;
clearIcon?: React.ReactNode;
removeIcon?: RenderNode;
multiple?: boolean;
displayValues: DisplayValueType[];
placeholder?: React.ReactNode;
searchValue?: string;
activeValue?: string;
mode?: Mode;
autoClearSearchValue?: boolean;
onSearch?: (searchText: string, fromTyping: boolean, isCompositing: boolean) => void;
onSearchSubmit?: (searchText: string) => void;
onInputBlur?: () => void;
onClearMouseDown?: React.MouseEventHandler<HTMLElement>;
onInputKeyDown?: React.KeyboardEventHandler<HTMLInputElement | HTMLTextAreaElement>;
onSelectorRemove?: (value: DisplayValueType) => void;
maxLength?: number;
autoFocus?: boolean;
/** Check if `tokenSeparators` contains `\n` or `\r\n` */
tokenWithEnter?: boolean;
// Add other props that need to be passed through
className?: string;
style?: React.CSSProperties;
focused?: boolean;
components: ComponentsConfig;
children?: React.ReactElement;
}
const DEFAULT_OMIT_PROPS = [
'value',
'onChange',
'removeIcon',
'placeholder',
'maxTagCount',
'maxTagTextLength',
'maxTagPlaceholder',
'choiceTransitionName',
'onInputKeyDown',
'onPopupScroll',
'tabIndex',
'activeValue',
'onSelectorRemove',
'focused',
] as const;
export default React.forwardRef<SelectInputRef, SelectInputProps>(function SelectInput(
props: SelectInputProps,
ref: React.ForwardedRef<SelectInputRef>,
) {
const {
// Style
prefixCls,
className,
style,
// UI
prefix,
suffix,
clearIcon,
children,
// Data
multiple,
displayValues,
placeholder,
mode,
// Search
searchValue,
onSearch,
onSearchSubmit,
onInputBlur,
// Input
maxLength,
autoFocus,
// Events
onMouseDown,
onClearMouseDown,
onInputKeyDown,
onSelectorRemove,
// Token handling
tokenWithEnter,
// Components
components,
...restProps
} = props;
const { triggerOpen, toggleOpen, showSearch, disabled, loading, classNames, styles } =
useBaseProps();
const rootRef = React.useRef<HTMLDivElement>(null);
const inputRef = React.useRef<HTMLInputElement>(null);
// Handle keyboard events similar to original Selector
const onInternalInputKeyDown = useEvent(
(event: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { which } = event;
// Compatible with multiple lines in TextArea
const isTextAreaElement = inputRef.current instanceof HTMLTextAreaElement;
// Prevent default behavior for up/down arrows when dropdown is open
if (!isTextAreaElement && triggerOpen && (which === KeyCode.UP || which === KeyCode.DOWN)) {
event.preventDefault();
}
// Call the original onInputKeyDown callback
if (onInputKeyDown) {
onInputKeyDown(event);
}
// Move within the text box for TextArea
if (
isTextAreaElement &&
!triggerOpen &&
~[KeyCode.UP, KeyCode.DOWN, KeyCode.LEFT, KeyCode.RIGHT].indexOf(which)
) {
return;
}
// Open dropdown when a valid open key is pressed
const isModifier = event.ctrlKey || event.altKey || event.metaKey;
if (!isModifier && isValidateOpenKey(which)) {
toggleOpen(true);
}
},
);
// ====================== Refs ======================
React.useImperativeHandle(ref, () => {
return {
focus: (options?: FocusOptions) => {
// Focus the inner input if available, otherwise fall back to root div.
(inputRef.current || rootRef.current).focus?.(options);
},
blur: () => {
(inputRef.current || rootRef.current).blur?.();
},
// Use getDOM to handle nested nativeElement structure (e.g., when RootComponent is antd Input)
nativeElement: getDOM(rootRef.current) as HTMLDivElement,
};
});
// ====================== Open ======================
const onInternalMouseDown: SelectInputProps['onMouseDown'] = useEvent((event) => {
if (!disabled) {
const inputDOM = getDOM(inputRef.current);
// https://github.com/ant-design/ant-design/issues/56002
// Tell `useSelectTriggerControl` to ignore this event
// When icon is dynamic render, the parentNode will miss
// so we need to mark the event directly
(event.nativeEvent as any)._ori_target = inputDOM;
const isClickOnInput = inputDOM === event.target || inputDOM?.contains(event.target as Node);
if (inputDOM && !isClickOnInput) {
event.preventDefault();
}
// Check if we should prevent closing when clicking on selector
// Don't close if: open && not multiple && (combobox mode || showSearch)
const shouldPreventCloseOnSingle =
triggerOpen && !multiple && (mode === 'combobox' || showSearch);
// Don't close if: open && multiple && click on input
const shouldPreventCloseOnMultipleInput = triggerOpen && multiple && isClickOnInput;
const shouldPreventClose = shouldPreventCloseOnSingle || shouldPreventCloseOnMultipleInput;
if (!(event.nativeEvent as any)._select_lazy) {
inputRef.current?.focus();
// Only toggle open if we should not prevent close
if (!shouldPreventClose) {
toggleOpen();
}
} else if (triggerOpen) {
// Lazy should also close when click clear icon
toggleOpen(false);
}
}
onMouseDown?.(event);
});
// =================== Components ===================
const { root: RootComponent } = components;
// ===================== Render =====================
const domProps = omit(restProps, DEFAULT_OMIT_PROPS as any);
const ariaProps = pickAttrs(domProps, { aria: true });
const ariaKeys = Object.keys(ariaProps) as (keyof typeof domProps)[];
// Create context value with wrapped callbacks
const contextValue = {
...props,
onInputKeyDown: onInternalInputKeyDown,
};
if (RootComponent) {
const originProps = (RootComponent as any).props || {};
const mergedProps = { ...originProps, ...domProps };
Object.keys(originProps).forEach((key) => {
const originVal = originProps[key];
const domVal = domProps[key];
if (typeof originVal === 'function' && typeof domVal === 'function') {
mergedProps[key] = (...args: any[]) => {
domVal(...args);
originVal(...args);
};
}
});
if (React.isValidElement<any>(RootComponent)) {
return React.cloneElement(RootComponent, {
...mergedProps,
ref: composeRef((RootComponent as any).ref, rootRef),
});
}
return <RootComponent {...mergedProps} ref={rootRef} />;
}
return (
<SelectInputContext.Provider value={contextValue}>
<div
{...omit(domProps, ariaKeys)}
// Style
ref={rootRef}
className={className}
style={style}
// Mouse Events
onMouseDown={onInternalMouseDown}
>
{/* Prefix */}
<Affix className={clsx(`${prefixCls}-prefix`, classNames?.prefix)} style={styles?.prefix}>
{prefix}
</Affix>
{/* Content */}
<SelectContent ref={inputRef} />
{/* Suffix */}
<Affix
className={clsx(
`${prefixCls}-suffix`,
{
[`${prefixCls}-suffix-loading`]: loading,
},
classNames?.suffix,
)}
style={styles?.suffix}
>
{suffix}
</Affix>
{/* Clear Icon */}
{clearIcon && (
<Affix
className={clsx(`${prefixCls}-clear`, classNames?.clear)}
style={styles?.clear}
onMouseDown={(e) => {
// Mark to tell not trigger open or focus
(e.nativeEvent as any)._select_lazy = true;
onClearMouseDown?.(e);
}}
>
{clearIcon}
</Affix>
)}
{children}
</div>
</SelectInputContext.Provider>
);
});