Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

keys.ts

84 lines2.0 KB

1/**
2 * OpenAI key names and Anthropic xdotool key names, lower case, to
3 * `KeyboardEvent.key` names.
4 */
5const KEYS: Record<string, string> = {
6 ctrl: 'Control',
7 control: 'Control',
8 control_l: 'Control',
9 control_r: 'Control',
10 shift: 'Shift',
11 shift_l: 'Shift',
12 shift_r: 'Shift',
13 alt: 'Alt',
14 alt_l: 'Alt',
15 alt_r: 'Alt',
16 option: 'Alt',
17 meta: 'Meta',
18 meta_l: 'Meta',
19 meta_r: 'Meta',
20 cmd: 'Meta',
21 command: 'Meta',
22 super: 'Meta',
23 super_l: 'Meta',
24 super_r: 'Meta',
25 win: 'Meta',
26 enter: 'Enter',
27 return: 'Enter',
28 kp_enter: 'Enter',
29 esc: 'Escape',
30 escape: 'Escape',
31 tab: 'Tab',
32 space: ' ',
33 backspace: 'Backspace',
34 delete: 'Delete',
35 del: 'Delete',
36 insert: 'Insert',
37 home: 'Home',
38 end: 'End',
39 pageup: 'PageUp',
40 page_up: 'PageUp',
41 prior: 'PageUp',
42 pagedown: 'PageDown',
43 page_down: 'PageDown',
44 next: 'PageDown',
45 up: 'ArrowUp',
46 down: 'ArrowDown',
47 left: 'ArrowLeft',
48 right: 'ArrowRight',
49 arrowup: 'ArrowUp',
50 arrowdown: 'ArrowDown',
51 arrowleft: 'ArrowLeft',
52 arrowright: 'ArrowRight',
53 capslock: 'CapsLock',
54 caps_lock: 'CapsLock',
55 plus: '+',
56 minus: '-',
58​
59/**
60 * Maps one OpenAI or xdotool key name to a `KeyboardEvent.key` name.
61 * The match ignores case. An unknown name comes back unchanged.
62 */
63export function toKey(name: string) {
64 const known = KEYS[name.toLowerCase()]
65 if (known !== undefined) return known
66 const isFunctionKey = /^f\d{1,2}$/i.test(name)
67 return isFunctionKey ? name.toUpperCase() : name
69​
70/**
71 * Maps the keys of one combo, like `['CTRL', 'S']`, to `KeyboardEvent.key`
72 * names. In a combo with more than one key, a single letter becomes lower
73 * case. Then `Control` + `A` does not also send a capital `A`.
74 */
75export function toCombo(names: Array<string>) {
76 const keys = names.map(toKey)
77 if (keys.length < 2) return keys
78 return keys.map((key) => (/^[A-Z]$/.test(key) ? key.toLowerCase() : key))
80​
81/** Splits an xdotool combo, like `ctrl+s`, and maps each key. */
82export function parseKeyCombo(combo: string) {
83 return toCombo(combo.split('+').map((name) => name.trim()))