Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useInlineActionConfirm.ts

54 lines1.7 KB

1import { useEffect, useState, type MouseEvent } from "react";
2​
3export function useInlineActionConfirm(scopeKey: string) {
4 const [armed, setArmed] = useState<{
5 scopeKey: string;
6 action: string;
7 element: HTMLElement;
8 } | null>(null);
9 const active = armed?.scopeKey === scopeKey ? armed : null;
10​
11 useEffect(() => {
12 if (!armed) return;
13 const disarm = () => setArmed(null);
14 if (armed.scopeKey !== scopeKey) {
15 disarm();
16 return;
17 }
18 const onPointerDown = (event: PointerEvent) => {
19 if (event.target instanceof Node && !armed.element.contains(event.target)) disarm();
20 };
21 const onKeyDown = (event: KeyboardEvent) => {
22 if (event.key === "Escape") {
23 event.preventDefault();
24 event.stopPropagation();
25 disarm();
26 }
27 };
28 const timeout = window.setTimeout(disarm, 3000);
29 document.addEventListener("pointerdown", onPointerDown, true);
30 window.addEventListener("keydown", onKeyDown, true);
31 window.addEventListener("blur", disarm);
32 return () => {
33 window.clearTimeout(timeout);
34 document.removeEventListener("pointerdown", onPointerDown, true);
35 window.removeEventListener("keydown", onKeyDown, true);
36 window.removeEventListener("blur", disarm);
37 };
38 }, [armed, scopeKey]);
39​
40 return {
41 isArmed: (action: string) => active?.action === action,
42 props: (action: string, onConfirm: () => void) => ({
43 onClick: (event: MouseEvent<HTMLElement>) => {
44 if (active?.action === action && active.element === event.currentTarget) {
45 setArmed(null);
46 onConfirm();
47 } else {
48 setArmed({ scopeKey, action, element: event.currentTarget });
49 }
50 },
51 onBlur: () => setArmed(null),
52 }),
53 };