-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathSpinButton.tsx
89 lines (84 loc) · 2.86 KB
/
SpinButton.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
import React, { useRef } from 'react';
import classNames from 'classnames';
interface SpinButtonProps extends React.ComponentPropsWithoutRef<'span'> {
className?: string;
onSpinButtonChange: (value: number[], allowFocusNext?: boolean) => void;
children: React.ReactNode;
maxLength: number;
min: number;
max: number;
value?: number;
nextSpinButton?: React.RefObject<HTMLSpanElement>;
prevSpinButton?: React.RefObject<HTMLSpanElement>;
}
export const SpinButton = React.forwardRef<HTMLSpanElement, SpinButtonProps>(
(
{
className,
onSpinButtonChange,
maxLength,
min,
max,
value,
nextSpinButton,
prevSpinButton,
children,
...rest
},
ref,
) => {
const history = useRef<number[]>([]);
const handleKeyDown = (evt: React.KeyboardEvent) => {
evt.stopPropagation();
if (/\d/.test(evt.key)) {
history.current =
history.current.length === maxLength
? (history.current = [parseInt(evt.key)])
: history.current.concat(parseInt(evt.key));
onSpinButtonChange(history.current);
} else if (evt.key === 'Backspace') {
history.current = [];
onSpinButtonChange(history.current);
} else if (evt.key === 'ArrowUp') {
evt.preventDefault();
let newValue = (value ?? 0) + 1;
if (newValue && newValue !== null && newValue > max) {
newValue = min;
}
onSpinButtonChange([newValue], false);
} else if (evt.key === 'ArrowDown') {
evt.preventDefault();
let newValue = (value ?? 0) - 1;
if (newValue < min) {
newValue = max;
}
onSpinButtonChange([newValue], false);
} else if (evt.key === 'ArrowLeft') {
evt.preventDefault();
prevSpinButton?.current?.focus();
} else if (evt.key === 'ArrowRight') {
evt.preventDefault();
nextSpinButton?.current?.focus();
}
};
return (
<span
role={'spinbutton'}
inputMode={'numeric'}
className={classNames(className, 'ffe-dateinput__field')}
tabIndex={0}
onFocus={() => {
history.current = [];
}}
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={value}
ref={ref}
onKeyDown={handleKeyDown}
{...rest}
>
{children}
</span>
);
},
);