Debian Codegraph @

frontend/src/keyboard-shortcuts.ts

raw
1 import { tick } from "svelte";
2 import type { Action } from "svelte/action";
3
4 import { log_error } from "./log";
5
6 /**
7 * Add a tooltip showing the keyboard shortcut over the target element.
8 * @param target - The target element to show the tooltip on.
9 * @returns A function to remove event handler.
10 */
11 function showTooltip(target: HTMLElement, description: string): () => void {
12 const { hidden } = target;
13 if (hidden) {
14 target.hidden = false;
15 }
16 const tooltip = document.createElement("div");
17 tooltip.className = "keyboard-tooltip";
18 tooltip.textContent = description;
19 document.body.appendChild(tooltip);
20 const targetRect = target.getBoundingClientRect();
21 // Padded 10px to the left if there is space or centered otherwise
22 const left =
23 targetRect.left +
24 Math.min((target.offsetWidth - tooltip.offsetWidth) / 2, 10);
25 const top = targetRect.top + (target.offsetHeight - tooltip.offsetHeight) / 2;
26 tooltip.style.left = `${left.toString()}px`;
27 tooltip.style.top = `${(top + window.scrollY).toString()}px`;
28 return () => {
29 tooltip.remove();
30 if (hidden) {
31 target.hidden = true;
32 }
33 };
34 }
35
36 /**
37 * Show all keyboard shortcut tooltips.
38 */
39 function showTooltips(): () => void {
40 const removes: (() => void)[] = [];
41 document.querySelectorAll("[data-key]").forEach((el) => {
42 const key = el.getAttribute("data-key");
43 if (el instanceof HTMLElement && key !== null) {
44 removes.push(showTooltip(el, key));
45 }
46 });
47 return () => {
48 removes.forEach((r) => {
49 r();
50 });
51 };
52 }
53
54 /**
55 * Ignore events originating from editable elements.
56 * @param element - The element to check.
57 * @returns true if the element is one of input/select/textarea or a
58 * contentEditable element.
59 */
60 function isEditableElement(element: EventTarget | null): boolean {
61 return (
62 element instanceof HTMLElement &&
63 (element instanceof HTMLInputElement ||
64 element instanceof HTMLSelectElement ||
65 element instanceof HTMLTextAreaElement ||
66 element.isContentEditable)
67 );
68 }
69
70 type UppercaseLetter =
71 | "A"
72 | "B"
73 | "C"
74 | "D"
75 | "E"
76 | "F"
77 | "G"
78 | "H"
79 | "I"
80 | "J"
81 | "L"
82 | "M"
83 | "N"
84 | "O"
85 | "P"
86 | "Q"
87 | "R"
88 | "S"
89 | "T"
90 | "U"
91 | "V"
92 | "W"
93 | "X"
94 | "Y"
95 | "Z";
96 type LowercaseLetter = Lowercase<UppercaseLetter>;
97 type Letter = UppercaseLetter | LowercaseLetter;
98 // This type can be extended as needed to support all the desired
99 // key combinations
100 type KeyCombo =
101 | "?"
102 | Letter
103 | `${"Control" | "Meta"}+${"d" | "s" | "Enter"}`
104 // d,s,t - journal filters; f - filters; g - reports
105 | `${"d" | "f" | "g" | "s" | "t"} ${Letter}`;
106 /** A handler function or an element to click. */
107 type KeyboardShortcutAction = ((event: KeyboardEvent) => void) | HTMLElement;
108 const keyboardShortcuts = new Map<string, KeyboardShortcutAction>();
109 // The last typed character to check for sequences of two keys.
110 let lastChar = "";
111
112 /**
113 * Handle a `keydown` event on the document.
114 *
115 * Dispatch to the relevant handler.
116 */
117 function keydown(event: KeyboardEvent): void {
118 if (isEditableElement(event.target)) {
119 // ignore events in editable elements.
120 return;
121 }
122 let eventKey = event.key;
123 if (event.metaKey) {
124 eventKey = `Meta+${eventKey}`;
125 }
126 if (event.altKey) {
127 eventKey = `Alt+${eventKey}`;
128 }
129 if (event.ctrlKey) {
130 eventKey = `Control+${eventKey}`;
131 }
132 const lastTwoKeys = `${lastChar} ${eventKey}`;
133 const handler =
134 keyboardShortcuts.get(lastTwoKeys) ?? keyboardShortcuts.get(eventKey);
135 if (handler) {
136 if (handler instanceof HTMLInputElement) {
137 event.preventDefault();
138 handler.focus();
139 } else if (handler instanceof HTMLElement) {
140 event.preventDefault();
141 handler.click();
142 } else {
143 handler(event);
144 }
145 }
146 if (event.key !== "Alt" && event.key !== "Control" && event.key !== "Shift") {
147 lastChar = eventKey;
148 }
149 }
150
151 document.addEventListener("keydown", keydown);
152
153 /** A type to specify a platform-dependent keyboard shortcut. */
154 export type KeySpec =
155 | KeyCombo
156 | { key: KeyCombo; mac?: KeyCombo; note?: string };
157
158 const isMac =
159 // This still seems to be the least bad way to check whether we are running on macOS or iOS
160 // eslint-disable-next-line @typescript-eslint/no-deprecated
161 navigator.platform.startsWith("Mac") || navigator.platform === "iPhone";
162
163 export const modKey = isMac ? "Cmd" : "Ctrl";
164
165 /**
166 * Get the keyboard key specifier string for the current platform.
167 * @param spec - The key spec.
168 */
169 function getKeySpecKey(spec: KeySpec): KeyCombo {
170 if (typeof spec === "string") {
171 return spec;
172 }
173 return isMac ? (spec.mac ?? spec.key) : spec.key;
174 }
175
176 /**
177 * Get the keyboard key description.
178 * @param spec - The key spec.
179 */
180 function getKeySpecDescription(spec: KeySpec): string {
181 if (typeof spec === "string") {
182 return spec;
183 }
184 const key = isMac ? (spec.mac ?? spec.key) : spec.key;
185 return spec.note != null ? `${key} - ${spec.note}` : key;
186 }
187
188 /**
189 * Bind an event handler to a key.
190 * @param spec - The key to bind.
191 * @param handler - The callback to run on key press.
192 * @returns A function to unbind the keyboard handler.
193 */
194 function bindKey(spec: KeySpec, handler: KeyboardShortcutAction): () => void {
195 const key = getKeySpecKey(spec);
196 const sequence = key.split(" ");
197 if (sequence.length > 2) {
198 console.error("Only key sequences of length <=2 are supported: ", key);
199 }
200 if (keyboardShortcuts.has(key)) {
201 console.warn("Duplicate keyboard shortcut: ", key, handler);
202 }
203 keyboardShortcuts.set(key, handler);
204 return () => {
205 keyboardShortcuts.delete(key);
206 };
207 }
208
209 /**
210 * A svelte action to attach a global keyboard shortcut.
211 *
212 * This will attach a listener for the given key (or key sequence of length 2).
213 * This listener will focus the given node if it is an <input> element and
214 * trigger a click on it otherwise.
215 */
216 export const keyboardShortcut: Action<HTMLElement, KeySpec | undefined> = (
217 node,
218 spec,
219 ) => {
220 const setup = (s?: KeySpec) => {
221 if (s != null) {
222 node.setAttribute("data-key", getKeySpecDescription(s));
223 const unbind = bindKey(s, node);
224 return () => {
225 unbind();
226 node.removeAttribute("data-key");
227 };
228 }
229 return () => {
230 // pass
231 };
232 };
233 let destroy = setup(spec);
234
235 return {
236 destroy,
237 update(new_spec) {
238 destroy();
239 // Await tick so that key bindings that might have been removed from other
240 // elements in the same render are gone.
241 tick()
242 .then(() => {
243 destroy = setup(new_spec);
244 })
245 .catch(log_error);
246 },
247 };
248 };
249
250 /**
251 * Register the keys to show/hide the tooltips
252 */
253 export function initGlobalKeyboardShortcuts(): void {
254 bindKey("?", () => {
255 const hide = showTooltips();
256 const once = () => {
257 hide();
258 document.removeEventListener("mousedown", once);
259 document.removeEventListener("keydown", once);
260 document.removeEventListener("scroll", once);
261 };
262 document.addEventListener("mousedown", once);
263 document.addEventListener("keydown", once);
264 document.addEventListener("scroll", once);
265 });
266 }