File size: 1,316 Bytes
794cf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
export interface Shortcut {
  key: string;
  ctrl?: boolean;
  meta?: boolean;
  shift?: boolean;
  alt?: boolean;
  action: () => void;
  description: string;
}

export const shortcuts: Shortcut[] = [
  {
    key: "e",
    ctrl: true,
    meta: true,
    action: () => {
      import("../stores/ui").then(({ uiStore }) => {
        uiStore.toggleViewMode();
      });
    },
    description: "Toggle between code and preview mode",
  },
];

export function registerShortcuts(shortcuts: Shortcut[]): () => void {
  const handler = (e: KeyboardEvent) => {
    for (const shortcut of shortcuts) {
      const ctrlMatch = shortcut.ctrl
        ? e.ctrlKey
        : !shortcut.ctrl || !e.ctrlKey;
      const metaMatch = shortcut.meta
        ? e.metaKey
        : !shortcut.meta || !e.metaKey;
      const shiftMatch = shortcut.shift
        ? e.shiftKey
        : !shortcut.shift || !e.shiftKey;
      const altMatch = shortcut.alt ? e.altKey : !shortcut.alt || !e.altKey;

      if (
        e.key === shortcut.key &&
        (ctrlMatch || metaMatch) &&
        shiftMatch &&
        altMatch
      ) {
        e.preventDefault();
        shortcut.action();
        break;
      }
    }
  };

  window.addEventListener("keydown", handler);

  return () => {
    window.removeEventListener("keydown", handler);
  };
}