Open History to see the last commit
1// @effect-diagnostics globalDate:off globalTimers:off -- Synchronous before-input-event handler; key events must be timed and the watchdog scheduled outside any Effect runtime.
2
3import type { QuitConfirmationMode, QuitShortcutHintEvent } from "@t3tools/contracts";
4
5export const QUIT_HOLD_DURATION_MS = 1200;
6export const QUIT_DOUBLE_PRESS_MS = 500;
7// "Still held" is proven by auto-repeat keydowns, not by the absence of a
8// release: macOS suppresses a letter keyUp while the command key is down, so a
9// tap release can go completely unseen and a release-based timer would quit
10// anyway. Once held, quitting waits for Q keyUp or a quiet grace period after
11// repeats stop so they cannot reach the next app.
12export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
13// A slow repeat rate can exceed the fixed grace. Waiting for two observed
14// cadences keeps the timer behind the next repeat without slowing normal rates.
15const QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER = 2;
16
17export interface QuitHoldKeyInput {
18 readonly type: string;
19 readonly key: string;
20 readonly meta: boolean;
21 readonly control: boolean;
22 readonly alt: boolean;
23 readonly shift: boolean;
24 readonly isAutoRepeat: boolean;
25}
26
27export interface QuitShortcutOptions {
28 readonly platform: NodeJS.Platform;
29 readonly getMode: () => Promise<QuitConfirmationMode>;
30 readonly notify: (event: QuitShortcutHintEvent) => void;
31 readonly concealWindow: () => void;
32 readonly quit: () => void;
33}
34
35export function makeQuitShortcutHandler(
36 options: QuitShortcutOptions,
37): (event: { preventDefault: () => void }, input: QuitHoldKeyInput) => void {
38 const modifierKey = options.platform === "darwin" ? "meta" : "control";
39 let watchdog: NodeJS.Timeout | undefined;
40 let holding = false;
41 let mode: QuitConfirmationMode | undefined;
42 let notified = false;
43 let armed = false;
44 let quitOnRelease = false;
45 let heldSince = 0;
46 let lastPressAt = 0;
47 let lastRepeatAt = 0;
48 let repeatCadenceMs = 0;
49 // Incremented when a press is superseded or explicitly cancelled. A plain
50 // key release does not invalidate its pending mode read: a direct-mode
51 // press must still quit after that read settles.
52 let generation = 0;
53
54 const clearWatchdog = () => {
55 if (watchdog !== undefined) {
56 clearTimeout(watchdog);
57 watchdog = undefined;
58 }
59 };
60
61 const release = (cancelPendingMode = true, keepDoublePressHint = false) => {
62 if (cancelPendingMode) generation += 1;
63 if (!holding && !notified) return;
64 const keepHint = keepDoublePressHint && mode === "double-click" && notified;
65 holding = false;
66 armed = false;
67 quitOnRelease = false;
68 lastRepeatAt = 0;
69 repeatCadenceMs = 0;
70 if (keepHint) return;
71
72 mode = undefined;
73 clearWatchdog();
74 if (notified) {
75 notified = false;
76 options.notify({ state: "up" });
77 }
78 };
79
80 const quitNow = () => {
81 release();
82 lastPressAt = 0;
83 options.quit();
84 };
85
86 const quitAfterQuietPeriod = () => {
87 clearWatchdog();
88 const quietPeriodMs = Math.max(
89 QUIT_HOLD_RELEASE_GRACE_MS,
90 repeatCadenceMs * QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER,
91 );
92 watchdog = setTimeout(quitNow, quietPeriodMs);
93 };
94
95 return (event, input) => {
96 const key = input.key.toLowerCase();
97 if (input.type === "keyUp") {
98 if (key === "q") {
99 const shouldQuit = quitOnRelease;
100 release(false, true);
101 if (shouldQuit) options.quit();
102 } else if (key === modifierKey) {
103 if (!quitOnRelease) {
104 release(false, true);
105 } else {
106 quitAfterQuietPeriod();
107 }
108 }
109 return;
110 }
111 if (input.type !== "keyDown") return;
112
113 const modifierDown = options.platform === "darwin" ? input.meta : input.control;
114 if (input.isAutoRepeat && modifierDown && key === "q") {
115 const now = Date.now();
116 repeatCadenceMs = now - (lastRepeatAt === 0 ? heldSince : lastRepeatAt);
117 lastRepeatAt = now;
118 }
119 if (quitOnRelease) {
120 event.preventDefault();
121 if (key === "q") quitAfterQuietPeriod();
122 return;
123 }
124
125 if (!modifierDown || input.alt || input.shift || key !== "q") {
126 if (key === modifierKey && !input.alt && !input.shift) return;
127
128 // Keep this separate from release(), which also runs when a fresh Q
129 // keydown follows a keyUp that macOS did not deliver.
130 if (!input.isAutoRepeat) {
131 lastPressAt = 0;
132 release();
133 }
134 return;
135 }
136
137 event.preventDefault();
138
139 if (input.isAutoRepeat) {
140 if (mode === "hold" && armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
141 armed = false;
142 quitOnRelease = true;
143 options.concealWindow();
144 quitAfterQuietPeriod();
145 }
146 return;
147 }
148
149 const now = Date.now();
150 const previousPressAt = lastPressAt;
151 lastPressAt = now;
152 if (holding || notified) release();
153
154 generation += 1;
155 if (previousPressAt !== 0 && now - previousPressAt <= QUIT_DOUBLE_PRESS_MS) {
156 quitNow();
157 return;
158 }
159
160 const pressGeneration = generation;
161 holding = true;
162 heldSince = now;
163 void options.getMode().then(
164 (resolvedMode) => {
165 if (generation !== pressGeneration) return;
166 if (resolvedMode === "direct") {
167 quitNow();
168 return;
169 }
170 if (resolvedMode === "double-click") {
171 const remainingMs = QUIT_DOUBLE_PRESS_MS - (Date.now() - now);
172 if (remainingMs <= 0) {
173 release();
174 return;
175 }
176 mode = resolvedMode;
177 notified = true;
178 options.notify({ state: "down", mode: resolvedMode });
179 watchdog = setTimeout(release, remainingMs);
180 return;
181 }
182
183 if (!holding) return;
184
185 mode = resolvedMode;
186 notified = true;
187 options.notify({ state: "down", mode: resolvedMode });
188
189 armed = true;
190 watchdog = setTimeout(() => {
191 watchdog = undefined;
192 release();
193 }, QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
194 },
195 () => {
196 if (generation !== pressGeneration) return;
197 quitNow();
198 },
199 );
200 };
201}