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

QuitHold.ts

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