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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
|
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { getHTMLElementOrNull } from "@/scripts/get-dom-node-or-null.js";
//#region types
export type Keymap = Record<string, CallbackFunction | CallbackObject>;
type CallbackFunction = (ev: KeyboardEvent) => unknown;
type CallbackObject = {
callback: CallbackFunction;
allowRepeat?: boolean;
};
type Pattern = {
which: string[];
ctrl: boolean;
alt: boolean;
shift: boolean;
};
type Action = {
patterns: Pattern[];
callback: CallbackFunction;
options: Required<Omit<CallbackObject, 'callback'>>;
};
//#endregion
//#region consts
const KEY_ALIASES = {
'esc': 'Escape',
'enter': 'Enter',
'space': ' ',
'up': 'ArrowUp',
'down': 'ArrowDown',
'left': 'ArrowLeft',
'right': 'ArrowRight',
'plus': ['+', ';'],
};
const MODIFIER_KEYS = ['ctrl', 'alt', 'shift'];
const IGNORE_ELEMENTS = ['input', 'textarea', 'ruffle-player'];
//#endregion
//#region store
let latestHotkey: Pattern & { callback: CallbackFunction } | null = null;
//#endregion
//#region impl
export const makeHotkey = (keymap: Keymap) => {
const actions = parseKeymap(keymap);
return (ev: KeyboardEvent) => {
if ('pswp' in window && window.pswp != null) return;
if (document.activeElement != null) {
if (IGNORE_ELEMENTS.includes(document.activeElement.tagName.toLowerCase())) return;
if (getHTMLElementOrNull(document.activeElement)?.isContentEditable) return;
}
for (const action of actions) {
if (matchPatterns(ev, action)) {
ev.preventDefault();
ev.stopPropagation();
action.callback(ev);
storePattern(ev, action.callback);
}
}
};
};
const parseKeymap = (keymap: Keymap) => {
return Object.entries(keymap).map(([rawPatterns, rawCallback]) => {
const patterns = parsePatterns(rawPatterns);
const callback = parseCallback(rawCallback);
const options = parseOptions(rawCallback);
return { patterns, callback, options } as const satisfies Action;
});
};
const parsePatterns = (rawPatterns: keyof Keymap) => {
return rawPatterns.split('|').map(part => {
const keys = part.split('+').map(trimLower);
const which = parseKeyCode(keys.findLast(x => !MODIFIER_KEYS.includes(x)));
const ctrl = keys.includes('ctrl');
const alt = keys.includes('alt');
const shift = keys.includes('shift');
return { which, ctrl, alt, shift } as const satisfies Pattern;
});
};
const parseCallback = (rawCallback: Keymap[keyof Keymap]) => {
if (typeof rawCallback === 'object') {
return rawCallback.callback;
}
return rawCallback;
};
const parseOptions = (rawCallback: Keymap[keyof Keymap]) => {
const defaultOptions = {
allowRepeat: false,
} as const satisfies Action['options'];
if (typeof rawCallback === 'object') {
const { callback, ...rawOptions } = rawCallback;
const options = { ...defaultOptions, ...rawOptions };
return { ...options } as const satisfies Action['options'];
}
return { ...defaultOptions } as const satisfies Action['options'];
};
const matchPatterns = (ev: KeyboardEvent, action: Action) => {
const { patterns, options, callback } = action;
if (ev.repeat && !options.allowRepeat) return false;
const key = ev.key.toLowerCase();
return patterns.some(({ which, ctrl, shift, alt }) => {
if (
options.allowRepeat === false &&
latestHotkey != null &&
latestHotkey.which.includes(key) &&
latestHotkey.ctrl === ctrl &&
latestHotkey.alt === alt &&
latestHotkey.shift === shift &&
latestHotkey.callback === callback
) {
return false;
}
if (!which.includes(key)) return false;
if (ctrl !== (ev.ctrlKey || ev.metaKey)) return false;
if (alt !== ev.altKey) return false;
if (shift !== ev.shiftKey) return false;
return true;
});
};
let lastHotKeyStoreTimer: number | null = null;
const storePattern = (ev: KeyboardEvent, callback: CallbackFunction) => {
if (lastHotKeyStoreTimer != null) {
clearTimeout(lastHotKeyStoreTimer);
}
latestHotkey = {
which: [ev.key.toLowerCase()],
ctrl: ev.ctrlKey || ev.metaKey,
alt: ev.altKey,
shift: ev.shiftKey,
callback,
};
lastHotKeyStoreTimer = window.setTimeout(() => {
latestHotkey = null;
}, 500);
};
const parseKeyCode = (input?: string | null) => {
if (input == null) return [];
const raw = getValueByKey(KEY_ALIASES, input);
if (raw == null) return [input];
if (typeof raw === 'string') return [trimLower(raw)];
return raw.map(trimLower);
};
const getValueByKey = <
T extends Record<keyof any, unknown>,
K extends keyof T | keyof any,
R extends K extends keyof T ? T[K] : T[keyof T] | undefined,
>(obj: T, key: K) => {
return obj[key] as R;
};
const trimLower = (str: string) => str.trim().toLowerCase();
//#endregion
|