forked from equinor/webviz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathholdPressedIntervalCallbackButton.tsx
54 lines (45 loc) · 1.63 KB
/
holdPressedIntervalCallbackButton.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
import React from "react";
import { Button, ButtonProps } from "../Button/button";
export type HoldPressedIntervalCallbackButtonProps = Omit<ButtonProps, "ref"> & {
onHoldPressedIntervalCallback: () => void;
};
function HoldPressedIntervalCallbackButtonComponent(
props: HoldPressedIntervalCallbackButtonProps,
ref: React.ForwardedRef<HTMLDivElement>
): React.ReactNode {
const { onHoldPressedIntervalCallback, ...other } = props;
const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const intervalRef = React.useRef<ReturnType<typeof setInterval> | null>(null);
function handleClick() {
onHoldPressedIntervalCallback();
}
function handlePointerDown(e: React.PointerEvent<HTMLButtonElement>) {
timeoutRef.current = setTimeout(() => {
e.preventDefault();
intervalRef.current = setInterval(() => {
onHoldPressedIntervalCallback();
}, 100);
}, 300);
}
function handlePointerUp() {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}
return (
<Button
{...other}
ref={ref}
onClick={handleClick}
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
onPointerLeave={handlePointerUp}
/>
);
}
export const HoldPressedIntervalCallbackButton = React.forwardRef(HoldPressedIntervalCallbackButtonComponent);