Open History to see the last commit
1import { useSyncExternalStore } from "react";
2import { isEditableFocused } from "./lib/editableFocus";
3
4export interface ShortcutModifierState {
5 metaKey: boolean;
6 ctrlKey: boolean;
7 altKey: boolean;
8 shiftKey: boolean;
9}
10
11const EMPTY_SHORTCUT_MODIFIER_STATE: ShortcutModifierState = {
12 metaKey: false,
13 ctrlKey: false,
14 altKey: false,
15 shiftKey: false,
16};
17
18function areShortcutModifierStatesEqual(
19 left: ShortcutModifierState,
20 right: ShortcutModifierState,
21): boolean {
22 return (
23 left.metaKey === right.metaKey &&
24 left.ctrlKey === right.ctrlKey &&
25 left.altKey === right.altKey &&
26 left.shiftKey === right.shiftKey
27 );
28}
29
30function createShortcutModifierStore(ignoreEditable: boolean) {
31 let state = EMPTY_SHORTCUT_MODIFIER_STATE;
32 const listeners = new Set<() => void>();
33 let stopTracking: (() => void) | null = null;
34 const heldModifierCodes = new Map<string, keyof ShortcutModifierState>();
35
36 const updateState = (next: ShortcutModifierState) => {
37 if (areShortcutModifierStatesEqual(state, next)) return;
38 state = next;
39 for (const listener of listeners) listener();
40 };
41 // Dictation tools can omit Meta keyup after synthetic paste, leaving jump hints stuck.
42 const onResetEvent = () => {
43 heldModifierCodes.clear();
44 updateState(EMPTY_SHORTCUT_MODIFIER_STATE);
45 };
46 const onKeyboardEvent = (event: KeyboardEvent) => {
47 if (ignoreEditable && isEditableFocused(event.target)) return onResetEvent();
48 const modifier = normalizeModifierKey(event.key);
49 if (modifier && event.type === "keydown") heldModifierCodes.set(event.code, modifier);
50 if (modifier && event.type === "keyup") heldModifierCodes.delete(event.code);
51 const next = shortcutModifierStateAfterKeyboardEvent(state, event);
52 // Chromium reports the flag as released while the other side is still down, so trust tracked keys.
53 // A lost keyup is pruned below by the next event whose flags drop the modifier.
54 const otherSideHeld = modifier !== null && [...heldModifierCodes.values()].includes(modifier);
55 const nextState = otherSideHeld ? { ...next, [modifier]: true } : next;
56 for (const [code, held] of heldModifierCodes) {
57 if (!nextState[held]) heldModifierCodes.delete(code);
58 }
59 updateState(nextState);
60 };
61 const onFocus = (event: FocusEvent) => {
62 if (ignoreEditable && isEditableFocused(event.target)) onResetEvent();
63 };
64 const startTracking = () => {
65 window.addEventListener("focusin", onFocus);
66 window.addEventListener("keydown", onKeyboardEvent, true);
67 window.addEventListener("keyup", onKeyboardEvent, true);
68 window.addEventListener("paste", onResetEvent, true);
69 window.addEventListener("blur", onResetEvent);
70 return () => {
71 window.removeEventListener("focusin", onFocus);
72 window.removeEventListener("keydown", onKeyboardEvent, true);
73 window.removeEventListener("keyup", onKeyboardEvent, true);
74 window.removeEventListener("paste", onResetEvent, true);
75 window.removeEventListener("blur", onResetEvent);
76 heldModifierCodes.clear();
77 state = EMPTY_SHORTCUT_MODIFIER_STATE;
78 };
79 };
80
81 return {
82 subscribe: (listener: () => void) => {
83 listeners.add(listener);
84 stopTracking ??= startTracking();
85 return () => {
86 listeners.delete(listener);
87 if (listeners.size > 0) return;
88 stopTracking?.();
89 stopTracking = null;
90 };
91 },
92 getSnapshot: () => state,
93 };
94}
95
96/** Shared by every subscriber; read it from a snapshot to re-render only when a derived value changes. */
97export const shortcutModifierStore = createShortcutModifierStore(false);
98const editableIgnoringShortcutModifierStore = createShortcutModifierStore(true);
99
100export function useShortcutModifierState(ignoreEditable = false): ShortcutModifierState {
101 const store = ignoreEditable ? editableIgnoringShortcutModifierStore : shortcutModifierStore;
102 return useSyncExternalStore(store.subscribe, store.getSnapshot);
103}
104
105function normalizeModifierKey(key: string): keyof ShortcutModifierState | null {
106 switch (key) {
107 case "Meta":
108 case "OS":
109 case "Command":
110 return "metaKey";
111 case "Control":
112 return "ctrlKey";
113 case "Alt":
114 case "Option":
115 return "altKey";
116 case "Shift":
117 return "shiftKey";
118 default:
119 return null;
120 }
121}
122
123export function shortcutModifierStateAfterKeyboardEvent(
124 currentState: ShortcutModifierState,
125 event: KeyboardEvent,
126): ShortcutModifierState {
127 const normalizedModifierKey = normalizeModifierKey(event.key);
128 let nextState: ShortcutModifierState;
129 if (normalizedModifierKey) {
130 nextState = {
131 ...currentState,
132 [normalizedModifierKey]: event.type === "keydown",
133 };
134 } else {
135 // Dictation paste can poison real events with metaKey=true until a physical Meta press.
136 nextState = {
137 metaKey: currentState.metaKey && event.metaKey,
138 ctrlKey: currentState.ctrlKey && event.ctrlKey,
139 altKey: currentState.altKey && event.altKey,
140 shiftKey: currentState.shiftKey && event.shiftKey,
141 };
142 }
143
144 return areShortcutModifierStatesEqual(currentState, nextState) ? currentState : nextState;
145}