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

QuitHold.ts

228 lines7.5 KB

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​
5// The quit accelerator is intercepted in before-input-event, which runs
6// before the native menu accelerator. Quitting from the application menu is
7// untouched and always quits immediately.
8export const QUIT_HOLD_DURATION_MS = 1200;
9export const QUIT_DOUBLE_PRESS_MS = 500;
10// "Still held" is proven by auto-repeat keydowns, not by the absence of a
11// release: macOS suppresses a letter keyUp while the command key is down, so a
12// tap release can go completely unseen and a release-based timer would quit
13// anyway. Once held, quitting waits for Q keyUp or a quiet grace period after
14// repeats stop so they cannot reach the next app. Keyboards with
15// auto-repeat disabled fall back to the application menu Quit action.
16export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
17// A slow repeat rate can exceed the fixed grace. Waiting for two observed
18// cadences keeps the timer behind the next repeat without slowing normal rates.
19const QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER = 2;
20​
21export interface QuitHoldKeyInput {
22 readonly type: string;
23 readonly key: string;
24 readonly meta: boolean;
25 readonly control: boolean;
26 readonly alt: boolean;
27 readonly shift: boolean;
28 readonly isAutoRepeat: boolean;
30​
31export interface QuitShortcutOptions {
32 readonly platform: NodeJS.Platform;
33 readonly getMode: () => Promise<QuitConfirmationMode>;
34 readonly notify: (event: QuitShortcutHintEvent) => void;
35 readonly concealWindow: () => void;
36 readonly quit: () => void;
38​
39export function makeQuitShortcutHandler(
40 options: QuitShortcutOptions,
41): (event: { preventDefault: () => void }, input: QuitHoldKeyInput) => void {
42 const modifierKey = options.platform === "darwin" ? "meta" : "control";
43 let watchdog: NodeJS.Timeout | undefined;
44 let holding = false;
45 let mode: QuitConfirmationMode | undefined;
46 let notified = false;
47 // Set once getMode resolves to hold; auto-repeats may only complete the hold when armed.
48 let armed = false;
49 let quitOnRelease = false;
50 let heldSince = 0;
51 let lastPressAt = 0;
52 let lastRepeatAt = 0;
53 let repeatCadenceMs = 0;
54 // Incremented when a press is superseded or explicitly cancelled. A plain
55 // key release does not invalidate its pending mode read: direct mode and a
56 // completed second press must still be honored after that read settles.
57 let generation = 0;
58​
59 const clearWatchdog = () => {
60 if (watchdog !== undefined) {
61 clearTimeout(watchdog);
62 watchdog = undefined;
63 }
64 };
65​
66 const release = (cancelPendingMode = true, keepDoublePressHint = false) => {
67 if (!holding && !notified) return;
68 const keepHint = keepDoublePressHint && mode === "double-click" && notified;
69 if (cancelPendingMode) generation += 1;
70 holding = false;
71 armed = false;
72 quitOnRelease = false;
73 lastRepeatAt = 0;
74 repeatCadenceMs = 0;
75 if (keepHint) return;
76​
77 mode = undefined;
78 clearWatchdog();
79 if (notified) {
80 notified = false;
81 options.notify({ state: "up" });
82 }
83 };
84​
85 // Dismisses any overlay first so a cancelled quit cannot leave a stale hint.
86 const quitNow = () => {
87 release();
88 options.quit();
89 };
90​
91 const quitAfterQuietPeriod = () => {
92 clearWatchdog();
93 const quietPeriodMs = Math.max(
94 QUIT_HOLD_RELEASE_GRACE_MS,
95 repeatCadenceMs * QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER,
96 );
97 watchdog = setTimeout(quitNow, quietPeriodMs);
98 };
99​
100 return (event, input) => {
101 const key = input.key.toLowerCase();
102 if (input.type === "keyUp") {
103 if (key === "q") {
104 const shouldQuit = quitOnRelease;
105 release(false, true);
106 if (shouldQuit) options.quit();
107 } else if (key === modifierKey) {
108 if (!quitOnRelease) {
109 release(false, true);
110 } else {
111 quitAfterQuietPeriod();
112 }
113 }
114 return;
115 }
116 if (input.type !== "keyDown") return;
117​
118 const modifierDown = options.platform === "darwin" ? input.meta : input.control;
119 if (input.isAutoRepeat && modifierDown && key === "q") {
120 const now = Date.now();
121 repeatCadenceMs = now - (lastRepeatAt === 0 ? heldSince : lastRepeatAt);
122 lastRepeatAt = now;
123 }
124 if (quitOnRelease) {
125 event.preventDefault();
126 if (key === "q") {
127 if (modifierDown) {
128 quitAfterQuietPeriod();
129 } else {
130 clearWatchdog();
131 }
132 }
133 return;
134 }
135​
136 if (!modifierDown || input.alt || input.shift || key !== "q") {
137 // Re-pressing the platform modifier is the first half of a second full
138 // quit shortcut, so it must not cancel an active double-press window.
139 if (key === modifierKey && !input.alt && !input.shift) return;
140​
141 // Any other key (or an extra modifier) pressed mid-hold breaks the
142 // gesture; without this the hold timer keeps running through the
143 // interruption and the next qualifying repeat would quit early. The
144 // interrupted press also stops counting toward a double press, but only
145 // here, not in release(), which runs mid-restart on an unseen-release
146 // re-press and must not wipe that press's own tap timestamp.
147 if ((holding || notified) && !input.isAutoRepeat) {
148 lastPressAt = 0;
149 release();
150 }
151 return;
152 }
153​
154 event.preventDefault();
155​
156 if (input.isAutoRepeat) {
157 if (mode === "hold" && armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
158 armed = false;
159 quitOnRelease = true;
160 options.concealWindow();
161 quitAfterQuietPeriod();
162 }
163 return;
164 }
165​
166 const now = Date.now();
167 const previousPressAt = lastPressAt;
168 lastPressAt = now;
169 // A fresh keydown supersedes the current physical hold or the hint kept
170 // alive after a detected release.
171 if (holding || notified) release();
172​
173 generation += 1;
174 const pressGeneration = generation;
175 holding = true;
176 heldSince = now;
177 void options.getMode().then(
178 (resolvedMode) => {
179 if (generation !== pressGeneration) return;
180 if (resolvedMode === "direct") {
181 quitNow();
182 return;
183 }
184 if (
185 resolvedMode === "double-click" &&
186 previousPressAt !== 0 &&
187 now - previousPressAt <= QUIT_DOUBLE_PRESS_MS
188 ) {
189 quitNow();
190 return;
191 }
192​
193 if (resolvedMode === "double-click") {
194 const remainingMs = QUIT_DOUBLE_PRESS_MS - (Date.now() - now);
195 if (remainingMs <= 0) {
196 release();
197 return;
198 }
199 mode = resolvedMode;
200 notified = true;
201 options.notify({ state: "down", mode: resolvedMode });
202 watchdog = setTimeout(release, remainingMs);
203 return;
204 }
205​
206 // A hold cannot be armed after its physical press has ended.
207 if (!holding) return;
208​
209 mode = resolvedMode;
210 notified = true;
211 options.notify({ state: "down", mode: resolvedMode });
212​
213 armed = true;
214 // No auto-repeat by then means the key was released (possibly with a
215 // suppressed keyUp) or repeat is disabled; either way, don't quit.
216 watchdog = setTimeout(() => {
217 watchdog = undefined;
218 release();
219 }, QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
220 },
221 // A failed settings read must never strand the quit request.
222 () => {
223 if (generation !== pressGeneration) return;
224 quitNow();
225 },
226 );
227 };