Repository navigation
Expand file tree
/
Copy pathkeybinding.ts
More file actions
71 lines (60 loc) · 2.11 KB
/
Copy pathkeybinding.ts
File metadata and controls
71 lines (60 loc) · 2.11 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
import type { TActionWithOptionalArgs } from "./types";
/**
* Alt is also regarded as macOS OPTION (⌥) key
* Ctrl is also regarded as macOS COMMAND (⌘) key (NOTE: this differs from HTML Keyboard spec where COMMAND is Meta key!)
*/
export type ModifierKeys =
| "ctrl"
| "alt"
| "shift"
| "ctrl+shift"
| "alt+shift"
| "ctrl+alt"
| "ctrl+alt+shift";
const KEYS = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"up", "down", "left", "right",
"/", "?", ".",
"enter", "tab", "space", "escape", "esc",
"backspace", "delete", "home", "end",
] as const;
export type Key = (typeof KEYS)[number];
const KEY_SET: ReadonlySet<string> = new Set(KEYS);
export function isKey(value: string): value is Key {
return KEY_SET.has(value);
}
export type ModifierBasedShortcutKey = `${ModifierKeys}+${Key}`;
// Singular keybindings (these will be disabled when an input-ish area has been focused)
export type SingleCharacterShortcutKey = `${Key}`;
export type ShortcutKey = ModifierBasedShortcutKey | SingleCharacterShortcutKey;
const MODIFIER_KEYS: readonly ModifierKeys[] = [
"ctrl",
"alt",
"shift",
"ctrl+shift",
"alt+shift",
"ctrl+alt",
"ctrl+alt+shift",
];
const MODIFIER_SET: ReadonlySet<string> = new Set(MODIFIER_KEYS);
/**
* Validate that an arbitrary string is a well-formed `ShortcutKey`: either a
* bare `Key` (e.g. "s", "space") or a `<modifier>+<key>` combo (e.g. "ctrl+v",
* "ctrl+alt+shift+a"). The final `+`-separated segment is the key; everything
* before it must be a recognized modifier combination. No `Key` contains `+`,
* so splitting on the last `+` is unambiguous.
*/
export function isShortcutKey(value: string): value is ShortcutKey {
if (isKey(value)) return true;
const idx = value.lastIndexOf("+");
if (idx <= 0 || idx >= value.length - 1) return false;
const modifier = value.slice(0, idx);
const key = value.slice(idx + 1);
return MODIFIER_SET.has(modifier) && isKey(key);
}
export type KeybindingConfig = {
[key in ShortcutKey]?: TActionWithOptionalArgs;
};