-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmake_key.ts
More file actions
59 lines (50 loc) · 1.63 KB
/
make_key.ts
File metadata and controls
59 lines (50 loc) · 1.63 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
import type { KeyboardEvent } from 'react';
import type { KbsInternalShortcut, KbsKeyDefinition } from '../types.ts';
import { isMultiplatformCtrlKey } from './apple_interop.ts';
export interface Modifiers {
ctrl?: boolean;
shift?: boolean;
alt?: boolean;
}
export function shortcutToKeys(
shortcut: KbsInternalShortcut,
): readonly string[] {
return [
...shortcutObjectToKey(shortcut.shortcut),
...shortcut.aliases.flatMap(shortcutObjectToKey),
];
}
export function shortcutObjectToKey(shortcut: KbsKeyDefinition) {
const modifiers = `ctrl[${boolToString(shortcut.ctrl)}]_alt[${boolToString(
shortcut.alt,
)}]`;
let prefix: string;
if ('key' in shortcut) {
prefix = `key[${shortcut.key}]_${modifiers}`;
} else {
prefix = `code[${shortcut.code}]_${modifiers}`;
}
if (typeof shortcut.shift === 'boolean') {
return [`${prefix}_shift[${boolToString(shortcut.shift)}]`];
} else {
// If `shift` is not specified, allow it regardless of its state during the
// event. This is to support any keyboard layout.
return [`${prefix}_shift[true]`, `${prefix}_shift[false]`];
}
}
export function eventToKeyOrCode(
event: KeyboardEvent<HTMLDivElement> | globalThis.KeyboardEvent,
): { key: string; code: string } {
const modifiers = `ctrl[${boolToString(
isMultiplatformCtrlKey(event),
)}]_alt[${boolToString(event.altKey)}]_shift[${boolToString(
event.shiftKey,
)}]`;
return {
key: `key[${event.key.toLowerCase()}]_${modifiers}`,
code: `code[${event.code.toLowerCase()}]_${modifiers}`,
};
}
function boolToString(bool?: boolean): string {
return bool ? 'true' : 'false';
}