| 1 |
/** |
| 2 |
* A single press of a keybinding sequence. |
| 3 |
*/ |
| 4 |
export type KeybindingPress = readonly [ |
| 5 |
requiredModifiers: ReadonlyArray<string>, |
| 6 |
optionalModifiers: ReadonlyArray<string>, |
| 7 |
key: string | RegExp, |
| 8 |
] |
| 9 |
|
| 10 |
/** |
| 11 |
* Keyboard event callback fired when keybinding is triggered. |
| 12 |
*/ |
| 13 |
export type KeybindingHandler = (event: KeyboardEvent) => void |
| 14 |
|
| 15 |
/** |
| 16 |
* A map of keybinding strings to event handlers. |
| 17 |
*/ |
| 18 |
export type KeybindingsMap = Record<string, KeybindingHandler> |
| 19 |
|
| 20 |
/** |
| 21 |
* Predicate that returns true if a keyboard event should be ignored. |
| 22 |
*/ |
| 23 |
export type KeybindingFilter = (event: KeyboardEvent) => boolean |
| 24 |
|
| 25 |
export interface KeybindingHandlerOptions { |
| 26 |
/** |
| 27 |
* Keybinding sequences will wait this long between key presses before |
| 28 |
* cancelling (default: 1000). |
| 29 |
* |
| 30 |
* **Note:** Setting this value too low (i.e. `300`) will be too fast for many |
| 31 |
* of your users. |
| 32 |
*/ |
| 33 |
timeout?: number |
| 34 |
|
| 35 |
/** |
| 36 |
* Customize the behavior of which keyboard events will be ignored/skipped. |
| 37 |
* |
| 38 |
* By default this uses the behavior of {@link defaultKeybindingsHandlerIgnore}. |
| 39 |
* |
| 40 |
* @example Allow all events |
| 41 |
* ```tsx |
| 42 |
* tinykeys(window, {...}, { |
| 43 |
* ignore: () => false |
| 44 |
* }) |
| 45 |
* ``` |
| 46 |
* |
| 47 |
* @example Extend the default ignore |
| 48 |
* ```tsx |
| 49 |
* tinykeys(window, {...}, { |
| 50 |
* ignore: event => { |
| 51 |
* return ( |
| 52 |
* // Also ignore events inside a dialog |
| 53 |
* event.target.closest("dialog") != null && |
| 54 |
* defaultKeybindingsHandlerIgnore(event) |
| 55 |
* ); |
| 56 |
* } |
| 57 |
* }) |
| 58 |
* ``` |
| 59 |
*/ |
| 60 |
ignore?: KeybindingFilter |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Options to configure the behavior of keybindings. |
| 65 |
*/ |
| 66 |
export interface KeybindingOptions extends KeybindingHandlerOptions { |
| 67 |
/** |
| 68 |
* Key presses will listen to this event (default: "keydown"). |
| 69 |
*/ |
| 70 |
event?: "keydown" | "keyup" |
| 71 |
|
| 72 |
/** |
| 73 |
* Key presses will use a capture listener (default: false) |
| 74 |
*/ |
| 75 |
capture?: boolean |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* These are the modifier keys that change the meaning of keybindings. |
| 80 |
* |
| 81 |
* Note: Ignoring "AltGraph" because it is covered by the others. |
| 82 |
*/ |
| 83 |
let KEYBINDING_MODIFIER_KEYS = ["Shift", "Meta", "Alt", "Control"] |
| 84 |
|
| 85 |
/** |
| 86 |
* Keybinding sequences should timeout if individual key presses are more than |
| 87 |
* 1s apart by default. |
| 88 |
*/ |
| 89 |
let DEFAULT_TIMEOUT = 1000 |
| 90 |
|
| 91 |
/** |
| 92 |
* Keybinding sequences should bind to this event by default. |
| 93 |
*/ |
| 94 |
let DEFAULT_EVENT = "keydown" as const |
| 95 |
|
| 96 |
/** |
| 97 |
* Platform detection code. |
| 98 |
* @see https://github.com/jamiebuilds/tinykeys/issues/184 |
| 99 |
*/ |
| 100 |
let PLATFORM = typeof navigator === "object" ? navigator.platform : "" |
| 101 |
let APPLE_DEVICE = /Mac|iPod|iPhone|iPad/.test(PLATFORM) |
| 102 |
|
| 103 |
/** |
| 104 |
* An alias for creating platform-specific keybinding aliases. |
| 105 |
*/ |
| 106 |
let MOD = APPLE_DEVICE ? "Meta" : "Control" |
| 107 |
|
| 108 |
/** |
| 109 |
* Meaning of `AltGraph`, from MDN: |
| 110 |
* - Windows: Both Alt and Ctrl keys are pressed, or AltGr key is pressed |
| 111 |
* - Mac: ⌥ Option key pressed |
| 112 |
* - Linux: Level 3 Shift key (or Level 5 Shift key) pressed |
| 113 |
* - Android: Not supported |
| 114 |
* @see https://github.com/jamiebuilds/tinykeys/issues/185 |
| 115 |
*/ |
| 116 |
let ALT_GRAPH_ALIASES = PLATFORM === "Win32" ? ["Control", "Alt"] : ["Alt"] |
| 117 |
|
| 118 |
/** |
| 119 |
* Ensure and stop any event that isn't a full keyboard event. |
| 120 |
* Autocomplete option navigation and selection would fire an Event, |
| 121 |
* instead of the expected KeyboardEvent |
| 122 |
*/ |
| 123 |
function isKeyboardEvent( |
| 124 |
event: Partial<KeyboardEvent>, |
| 125 |
): event is KeyboardEvent { |
| 126 |
return !!(event.key && event.code && event.getModifierState) |
| 127 |
} |
| 128 |
|
| 129 |
/** |
| 130 |
* Ignores keyboard events from contenteditable and form elements unless they |
| 131 |
* are the current target. |
| 132 |
*/ |
| 133 |
export function defaultKeybindingsHandlerIgnore(event: KeyboardEvent) { |
| 134 |
let target = event.target as HTMLElement |
| 135 |
return ( |
| 136 |
// Always ignore repeated keyboard events |
| 137 |
event.repeat || |
| 138 |
// Always ignore keyboard events during composition input |
| 139 |
event.isComposing || |
| 140 |
// Always allow the current target |
| 141 |
(target !== event.currentTarget && |
| 142 |
// Ignore contenteditable and form elements |
| 143 |
target.matches("[contenteditable],input,select,textarea")) |
| 144 |
) |
| 145 |
} |
| 146 |
|
| 147 |
/** |
| 148 |
* There's a bug in Chrome that causes event.getModifierState not to exist on |
| 149 |
* KeyboardEvent's for F1/F2/etc keys. |
| 150 |
*/ |
| 151 |
function getModifierState(event: KeyboardEvent, mod: string) { |
| 152 |
return typeof event.getModifierState === "function" |
| 153 |
? event.getModifierState(mod) || |
| 154 |
(ALT_GRAPH_ALIASES.includes(mod) && event.getModifierState("AltGraph")) |
| 155 |
: false |
| 156 |
} |
| 157 |
|
| 158 |
/** |
| 159 |
* Parses a keybinding string into its parts. |
| 160 |
* |
| 161 |
* ``` |
| 162 |
* grammar = `<sequence>` |
| 163 |
* <sequence> = `<press> <press> <press> ...` |
| 164 |
* <press> = `<key>` or `<mods>+<key>` |
| 165 |
* <mods> = `<mod>+<mod>+...` |
| 166 |
* <mod> = `<modifier>` (required) or `[<modifier>]` (optional) |
| 167 |
* <key> = `<KeyboardEvent.key>` or `<KeyboardEvent.code>` (case-insensitive) |
| 168 |
* <key> = `(<regex>)` -> `/^(?:<regex>)$/iy` (case-insensitive) |
| 169 |
* ``` |
| 170 |
*/ |
| 171 |
export function parseKeybinding(str: string): KeybindingPress[] { |
| 172 |
return str |
| 173 |
.trim() |
| 174 |
.split(" ") |
| 175 |
.map(press => { |
| 176 |
let parts = press.split(/(?<=\w|\])\+/) |
| 177 |
|
| 178 |
let last: string | RegExp = parts.pop() as string |
| 179 |
let regex = last.match(/^\((.+)\)$/) |
| 180 |
let key = regex ? new RegExp(`^(?:${regex[1]})$`, "iv") : last |
| 181 |
|
| 182 |
let requiredModifiers: string[] = [] |
| 183 |
let optionalModifiers: string[] = [] |
| 184 |
|
| 185 |
for (const part of parts) { |
| 186 |
let optional = part.match(/^\[(.*)\]$/) |
| 187 |
let mod = optional?.[1] ?? part |
| 188 |
mod = mod === "$mod" ? MOD : mod |
| 189 |
if (optional) { |
| 190 |
optionalModifiers.push(mod) |
| 191 |
} else { |
| 192 |
requiredModifiers.push(mod) |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
return [requiredModifiers, optionalModifiers, key] |
| 197 |
}) |
| 198 |
} |
| 199 |
|
| 200 |
/** |
| 201 |
* This tells us if a single keyboard event matches a single keybinding press. |
| 202 |
*/ |
| 203 |
export function matchKeybindingPress( |
| 204 |
event: KeyboardEvent, |
| 205 |
[requiredModifiers, optionalModifiers, key]: KeybindingPress, |
| 206 |
): boolean { |
| 207 |
const hasAltGraph = requiredModifiers.includes("AltGraph") |
| 208 |
// prettier-ignore |
| 209 |
return !( |
| 210 |
// Allow either the `event.key` or the `event.code` |
| 211 |
// MDN event.key: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key |
| 212 |
// MDN event.code: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code |
| 213 |
( |
| 214 |
key instanceof RegExp ? !(key.test(event.key) || key.test(event.code)) : |
| 215 |
(key.toUpperCase() !== event.key.toUpperCase() && |
| 216 |
key !== event.code) |
| 217 |
) || |
| 218 |
|
| 219 |
// Ensure all required modifiers in the keybinding are pressed. |
| 220 |
requiredModifiers.find(mod => { |
| 221 |
return !getModifierState(event, mod) |
| 222 |
}) || |
| 223 |
|
| 224 |
// KEYBINDING_MODIFIER_KEYS (Shift/Control/etc) change the meaning of a |
| 225 |
// keybinding. So if they are pressed but aren't part of the current |
| 226 |
// keybinding press, then we don't have a match. |
| 227 |
KEYBINDING_MODIFIER_KEYS.find(mod => { |
| 228 |
return ( |
| 229 |
!requiredModifiers.includes(mod) && |
| 230 |
!optionalModifiers.includes(mod) && |
| 231 |
key !== mod && |
| 232 |
getModifierState(event, mod) && |
| 233 |
// When AltGraph is required, its alias modifiers (e.g. Alt, Control) |
| 234 |
// being active is expected — don't treat them as unexpected modifiers. |
| 235 |
!(hasAltGraph && ALT_GRAPH_ALIASES.includes(mod)) |
| 236 |
); |
| 237 |
}) |
| 238 |
) |
| 239 |
} |
| 240 |
|
| 241 |
/** |
| 242 |
* Creates an event listener for handling keybindings. |
| 243 |
* |
| 244 |
* @example |
| 245 |
* ```js |
| 246 |
* import { createKeybindingsHandler } from "../src/keybindings" |
| 247 |
* |
| 248 |
* let handler = createKeybindingsHandler({ |
| 249 |
* "Shift+d": () => { |
| 250 |
* alert("The 'Shift' and 'd' keys were pressed at the same time") |
| 251 |
* }, |
| 252 |
* "y e e t": () => { |
| 253 |
* alert("The keys 'y', 'e', 'e', and 't' were pressed in order") |
| 254 |
* }, |
| 255 |
* "$mod+d": () => { |
| 256 |
* alert("Either 'Control+d' or 'Meta+d' were pressed") |
| 257 |
* }, |
| 258 |
* }) |
| 259 |
* |
| 260 |
* window.addEventListener("keydown", handler) |
| 261 |
* ``` |
| 262 |
*/ |
| 263 |
export function createKeybindingsHandler( |
| 264 |
keybindingsMap: KeybindingsMap, |
| 265 |
options: KeybindingHandlerOptions = {}, |
| 266 |
): EventListener { |
| 267 |
let timeout = options.timeout ?? DEFAULT_TIMEOUT |
| 268 |
let ignore = options.ignore ?? defaultKeybindingsHandlerIgnore |
| 269 |
|
| 270 |
let keybindings = Object.keys(keybindingsMap).map(input => { |
| 271 |
return [input, parseKeybinding(input), keybindingsMap[input]] as const |
| 272 |
}) |
| 273 |
|
| 274 |
let pending = new Map<string, KeybindingPress[]>() |
| 275 |
let timer: number | null = null |
| 276 |
|
| 277 |
return event => { |
| 278 |
if (!isKeyboardEvent(event) || ignore(event)) { |
| 279 |
return |
| 280 |
} |
| 281 |
|
| 282 |
let conflicts: Array<string> = [] |
| 283 |
for (let [input, sequence, handler] of keybindings) { |
| 284 |
let prev = pending.get(input) |
| 285 |
let expected = prev ? prev : sequence |
| 286 |
let [current, ...rest] = expected |
| 287 |
|
| 288 |
let matches = matchKeybindingPress(event, current) |
| 289 |
|
| 290 |
if (!matches) { |
| 291 |
// Modifier keydown events shouldn't break sequences |
| 292 |
// Note: This works because: |
| 293 |
// - non-modifiers will always return false |
| 294 |
// - if the current keypress is a modifier then it will return true when we check its state |
| 295 |
// MDN: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState |
| 296 |
if (!getModifierState(event, event.key)) { |
| 297 |
pending.delete(input) |
| 298 |
} |
| 299 |
} else if (rest.length > 0) { |
| 300 |
pending.set(input, rest) |
| 301 |
conflicts.push(input) |
| 302 |
} else { |
| 303 |
pending.delete(input) |
| 304 |
if (conflicts.length) { |
| 305 |
console.warn( |
| 306 |
`tinykeys: Conflict found, "${input}" did not fire, waiting for:`, |
| 307 |
conflicts, |
| 308 |
) |
| 309 |
} else { |
| 310 |
handler(event) |
| 311 |
break |
| 312 |
} |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
if (timer) { |
| 317 |
clearTimeout(timer) |
| 318 |
} |
| 319 |
|
| 320 |
timer = setTimeout(() => pending.clear(), timeout) |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
/** |
| 325 |
* Subscribes to keybindings. |
| 326 |
* |
| 327 |
* Returns an unsubscribe method. |
| 328 |
* |
| 329 |
* @example |
| 330 |
* ```js |
| 331 |
* import { tinykeys } from "../src/tinykeys" |
| 332 |
* |
| 333 |
* tinykeys(window, { |
| 334 |
* "Shift+d": () => { |
| 335 |
* alert("The 'Shift' and 'd' keys were pressed at the same time") |
| 336 |
* }, |
| 337 |
* "y e e t": () => { |
| 338 |
* alert("The keys 'y', 'e', 'e', and 't' were pressed in order") |
| 339 |
* }, |
| 340 |
* "$mod+d": () => { |
| 341 |
* alert("Either 'Control+d' or 'Meta+d' were pressed") |
| 342 |
* }, |
| 343 |
* }) |
| 344 |
* ``` |
| 345 |
*/ |
| 346 |
export function tinykeys( |
| 347 |
target: Window | HTMLElement, |
| 348 |
keybindingMap: KeybindingsMap, |
| 349 |
options: KeybindingOptions = {}, |
| 350 |
): () => void { |
| 351 |
let event = options.event ?? DEFAULT_EVENT |
| 352 |
let onKeyEvent = createKeybindingsHandler(keybindingMap, options) |
| 353 |
target.addEventListener(event, onKeyEvent, options.capture) |
| 354 |
return () => { |
| 355 |
target.removeEventListener(event, onKeyEvent, options.capture) |
| 356 |
} |
| 357 |
} |