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

useInlineActionConfirm.ts

71 lines2.3 KB

1import { useState, type MouseEvent } from "react";
2​
3interface ArmedAction {
4 readonly scopeKey: string;
5 readonly action: string;
6 readonly element: HTMLElement;
7 // Stable per arming, so React attaches it once. Detaching it (disarm, scope change, or the
8 // armed element unmounting) removes the listeners and disarms.
9 readonly ref: (node: HTMLElement | null) => (() => void) | undefined;
11​
12export function useInlineActionConfirm(scopeKey: string) {
13 const [armed, setArmed] = useState<ArmedAction | null>(null);
14 if (armed !== null && armed.scopeKey !== scopeKey) setArmed(null);
15 const active = armed?.scopeKey === scopeKey ? armed : null;
16​
17 const arm = (action: string, element: HTMLElement) => {
18 const entry: ArmedAction = {
19 scopeKey,
20 action,
21 element,
22 ref: (node) => {
23 if (node === null) return undefined;
24 const controller = new AbortController();
25 const { signal } = controller;
26 const release = () => setArmed((current) => (current === entry ? null : current));
27 document.addEventListener(
28 "pointerdown",
29 (event) => {
30 if (event.target instanceof Node && !node.contains(event.target)) release();
31 },
32 { capture: true, signal },
33 );
34 window.addEventListener(
35 "keydown",
36 (event) => {
37 if (event.key !== "Escape") return;
38 event.preventDefault();
39 event.stopPropagation();
40 release();
41 },
42 { capture: true, signal },
43 );
44 window.addEventListener("blur", release, { signal });
45 const timeout = window.setTimeout(release, 3000);
46 return () => {
47 controller.abort();
48 window.clearTimeout(timeout);
49 release();
50 };
51 },
52 };
53 setArmed(entry);
54 };
55​
56 return {
57 isArmed: (action: string) => active?.action === action,
58 props: (action: string, onConfirm: () => void) => ({
59 ref: active?.action === action ? active.ref : undefined,
60 onClick: (event: MouseEvent<HTMLElement>) => {
61 if (active?.action === action && active.element === event.currentTarget) {
62 setArmed(null);
63 onConfirm();
64 } else {
65 arm(action, event.currentTarget);
66 }
67 },
68 onBlur: () => setArmed(null),
69 }),
70 };