a tool for shared writing and social publishing
1import { useUIState } from "./useUIState";
2import { Replicache } from "replicache";
3import { ReplicacheMutators } from "./replicache";
4import { isMac } from "./utils/isDevice";
5
6export type Shortcut = {
7 metaKey?: boolean;
8 metaAndCtrl?: boolean;
9 altKey?: boolean;
10 shift?: boolean;
11 key: string | string[];
12 handler: () => void;
13};
14export function addShortcut(shortcuts: Shortcut | Shortcut[]) {
15 let listener = (e: KeyboardEvent) => {
16 for (let shortcut of [shortcuts].flat()) {
17 if (e.shiftKey !== !!shortcut.shift) continue;
18 if (e.altKey !== !!shortcut.altKey) continue;
19 if (shortcut.metaAndCtrl) {
20 if (!(e.metaKey && e.ctrlKey)) continue;
21 } else if (!!shortcut.metaKey !== (isMac() ? e.metaKey : e.ctrlKey))
22 continue;
23 if (![shortcut.key].flat().includes(e.key)) continue;
24 e.preventDefault();
25 return shortcut.handler();
26 }
27 };
28 window.addEventListener("keydown", listener);
29 return () => window.removeEventListener("keydown", listener);
30}