-
-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathInput.tsx
More file actions
432 lines (366 loc) Β· 11.8 KB
/
Input.tsx
File metadata and controls
432 lines (366 loc) Β· 11.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
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
import { clsx } from 'clsx';
import { useEvent } from '@rc-component/util';
import useLayoutEffect from '@rc-component/util/lib/hooks/useLayoutEffect';
import raf from '@rc-component/util/lib/raf';
import * as React from 'react';
import { leftPad } from '../../utils/miscUtil';
import PickerContext from '../context';
import useLockEffect from '../hooks/useLockEffect';
import Icon from './Icon';
import MaskFormat from './MaskFormat';
import { getMaskRange } from './util';
import type { PickerRef } from '../../interface';
// Format logic
//
// First time on focus:
// 1. check if the text is valid, if not fill with format
// 2. set highlight cell to the first cell
// Cells
// 1. Selection the index cell, set inner `cacheValue` to ''
// 2. Key input filter non-number char, patch after the `cacheValue`
// 1. Replace the `cacheValue` with input align the cell length
// 2. Re-selection the mask cell
// 3. If `cacheValue` match the limit length or cell format (like 1 ~ 12 month), go to next cell
export interface InputRef extends PickerRef {
inputElement: HTMLInputElement;
}
export interface InputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
format?: string;
validateFormat: (value: string) => boolean;
active?: boolean;
/** Used for single picker only */
showActiveCls?: boolean;
suffixIcon?: React.ReactNode;
value?: string;
onChange: (value: string) => void;
onSubmit: VoidFunction;
/** Meaning current is from the hover cell getting the placeholder text */
helped?: boolean;
/**
* Trigger when input need additional help.
* Like open the popup for interactive.
*/
onHelp: () => void;
preserveInvalidOnBlur?: boolean;
invalid?: boolean;
clearIcon?: React.ReactNode;
}
const Input = React.forwardRef<InputRef, InputProps>((props, ref) => {
const {
className,
active,
showActiveCls = true,
suffixIcon,
format,
validateFormat,
onChange,
onInput,
helped,
onHelp,
onSubmit,
onKeyDown,
preserveInvalidOnBlur = false,
invalid,
clearIcon,
// Pass to input
...restProps
} = props;
const { value, onFocus, onBlur, onMouseUp } = props;
const {
prefixCls,
input: Component = 'input',
classNames,
styles,
} = React.useContext(PickerContext);
const inputPrefixCls = `${prefixCls}-input`;
// ======================== Value =========================
const [focused, setFocused] = React.useState(false);
const [internalInputValue, setInputValue] = React.useState<string>(value);
const [focusCellText, setFocusCellText] = React.useState<string>('');
const [focusCellIndex, setFocusCellIndex] = React.useState<number>(null);
const [forceSelectionSyncMark, forceSelectionSync] = React.useState<object>(null);
const inputValue = internalInputValue || '';
// Sync value if needed
React.useEffect(() => {
setInputValue(value);
}, [value]);
// ========================= Refs =========================
const holderRef = React.useRef<HTMLDivElement>(null);
const inputRef = React.useRef<HTMLInputElement>(null);
// When mousedown get focus, defer selection to mouseUp so click position is used
const mouseDownRef = React.useRef(false);
React.useImperativeHandle(ref, () => ({
nativeElement: holderRef.current,
inputElement: inputRef.current,
focus: (options) => {
inputRef.current.focus(options);
},
blur: () => {
inputRef.current.blur();
},
}));
// ======================== Format ========================
const maskFormat = React.useMemo(() => new MaskFormat(format || ''), [format]);
const [selectionStart, selectionEnd] = React.useMemo(() => {
if (helped) {
return [0, 0];
}
return maskFormat.getSelection(focusCellIndex);
}, [maskFormat, focusCellIndex, helped]);
// ======================== Modify ========================
// When input modify content, trigger `onHelp` if is not the format
const onModify = (text: string) => {
if (text && text !== format && text !== value) {
onHelp();
}
};
// ======================== Change ========================
/**
* Triggered by paste, keyDown and focus to show format
*/
const triggerInputChange = useEvent((text: string) => {
if (validateFormat(text)) {
onChange(text);
}
setInputValue(text);
onModify(text);
});
// Directly trigger `onChange` if `format` is empty
const onInternalChange: React.ChangeEventHandler<HTMLInputElement> = (event) => {
// Hack `onChange` with format to do nothing
if (!format) {
const text = event.target.value;
onModify(text);
setInputValue(text);
onChange(text);
}
};
const onFormatPaste: React.ClipboardEventHandler<HTMLInputElement> = (event) => {
// Block paste until selection is set (after mouseUp when focus was by mousedown)
if (mouseDownRef.current) {
event.preventDefault();
return;
}
// Get paste text
const pasteText = event.clipboardData.getData('text');
if (validateFormat(pasteText)) {
triggerInputChange(pasteText);
}
};
// ======================== Mouse =========================
// When `mouseDown` get focus, it's better to not to change the selection
// Since the up position maybe not is the first cell
const onFormatMouseDown: React.MouseEventHandler<HTMLInputElement> = () => {
mouseDownRef.current = true;
};
const onFormatMouseUp: React.MouseEventHandler<HTMLInputElement> = (event) => {
const { selectionStart: start } = event.target as HTMLInputElement;
const closeMaskIndex = maskFormat.getMaskCellIndex(start);
setFocusCellIndex(closeMaskIndex);
// Force update the selection
forceSelectionSync({});
onMouseUp?.(event);
mouseDownRef.current = false;
};
// ====================== Focus Blur ======================
const onFormatFocus: React.FocusEventHandler<HTMLInputElement> = (event) => {
setFocused(true);
setFocusCellIndex(0);
setFocusCellText('');
onFocus(event);
};
const onSharedBlur: React.FocusEventHandler<HTMLInputElement> = (event) => {
onBlur(event);
};
const onFormatBlur: React.FocusEventHandler<HTMLInputElement> = (event) => {
setFocused(false);
onSharedBlur(event);
};
// ======================== Active ========================
// Check if blur need reset input value
useLockEffect(active, () => {
if (!active && !preserveInvalidOnBlur) {
setInputValue(value);
}
});
// ======================= Keyboard =======================
const onSharedKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
if (event.key === 'Enter' && validateFormat(inputValue)) {
onSubmit();
}
onKeyDown?.(event);
};
const onFormatKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
// Block key input until selection is set (after mouseUp when focus was by mousedown)
if (mouseDownRef.current) {
event.preventDefault();
return;
}
onSharedKeyDown(event);
const { key } = event;
// Save the cache with cell text
let nextCellText: string = null;
// Fill in the input
let nextFillText: string = null;
const maskCellLen = selectionEnd - selectionStart;
const cellFormat = format.slice(selectionStart, selectionEnd);
// Cell Index
const offsetCellIndex = (offset: number) => {
setFocusCellIndex((idx) => {
let nextIndex = idx + offset;
nextIndex = Math.max(nextIndex, 0);
nextIndex = Math.min(nextIndex, maskFormat.size() - 1);
return nextIndex;
});
};
// Range
const offsetCellValue = (offset: number) => {
const [rangeStart, rangeEnd, rangeDefault] = getMaskRange(cellFormat);
const currentText = inputValue.slice(selectionStart, selectionEnd);
const currentTextNum = Number(currentText);
if (isNaN(currentTextNum)) {
return String(rangeDefault ? rangeDefault : offset > 0 ? rangeStart : rangeEnd);
}
const num = currentTextNum + offset;
const range = rangeEnd - rangeStart + 1;
return String(rangeStart + ((range + num - rangeStart) % range));
};
switch (key) {
// =============== Remove ===============
case 'Backspace':
case 'Delete':
nextCellText = '';
nextFillText = cellFormat;
break;
// =============== Arrows ===============
// Left key
case 'ArrowLeft':
nextCellText = '';
offsetCellIndex(-1);
break;
// Right key
case 'ArrowRight':
nextCellText = '';
offsetCellIndex(1);
break;
// Up key
case 'ArrowUp':
nextCellText = '';
nextFillText = offsetCellValue(1);
break;
// Down key
case 'ArrowDown':
nextCellText = '';
nextFillText = offsetCellValue(-1);
break;
// =============== Number ===============
default:
if (!isNaN(Number(key))) {
nextCellText = focusCellText + key;
nextFillText = nextCellText;
}
break;
}
// Update cell text
if (nextCellText !== null) {
setFocusCellText(nextCellText);
if (nextCellText.length >= maskCellLen) {
// Go to next cell
offsetCellIndex(1);
setFocusCellText('');
}
}
// Update the input text
if (nextFillText !== null) {
// Replace selection range with `nextCellText`
const nextFocusValue =
// before
inputValue.slice(0, selectionStart) +
// replace
leftPad(nextFillText, maskCellLen) +
// after
inputValue.slice(selectionEnd);
triggerInputChange(nextFocusValue.slice(0, format.length));
}
// Always trigger selection sync after key down
forceSelectionSync({});
};
// ======================== Format ========================
const rafRef = React.useRef<number>();
useLayoutEffect(() => {
if (!focused || !format || mouseDownRef.current) {
return;
}
// Reset with format if not match
if (!maskFormat.match(inputValue)) {
triggerInputChange(format);
return;
}
// Match the selection range
inputRef.current.setSelectionRange(selectionStart, selectionEnd);
// Chrome has the bug anchor position looks not correct but actually correct
rafRef.current = raf(() => {
inputRef.current.setSelectionRange(selectionStart, selectionEnd);
});
return () => {
raf.cancel(rafRef.current);
};
}, [
maskFormat,
format,
focused,
inputValue,
focusCellIndex,
selectionStart,
selectionEnd,
forceSelectionSyncMark,
triggerInputChange,
]);
// ======================== Render ========================
// Input props for format
const inputProps: React.InputHTMLAttributes<HTMLInputElement> = format
? {
onFocus: onFormatFocus,
onBlur: onFormatBlur,
onKeyDown: onFormatKeyDown,
onMouseDown: onFormatMouseDown,
onMouseUp: onFormatMouseUp,
onPaste: onFormatPaste,
}
: {};
return (
<div
ref={holderRef}
className={clsx(
inputPrefixCls,
{
[`${inputPrefixCls}-active`]: active && showActiveCls,
[`${inputPrefixCls}-placeholder`]: helped,
},
className,
)}
>
<Component
ref={inputRef}
aria-invalid={invalid}
autoComplete="off"
{...restProps}
onKeyDown={onSharedKeyDown}
onBlur={onSharedBlur}
// Replace with format
{...inputProps}
// Value
value={inputValue}
onChange={onInternalChange}
className={classNames.input}
style={styles.input}
/>
<Icon type="suffix" icon={suffixIcon} />
{clearIcon}
</div>
);
});
if (process.env.NODE_ENV !== 'production') {
Input.displayName = 'Input';
}
export default Input;