@bevelo/shortcuts 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +43 -2
- package/dist/index.cjs +397 -0
- package/dist/index.d.cts +114 -0
- package/dist/index.d.ts +114 -0
- package/dist/index.js +393 -0
- package/package.json +38 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bevelo contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bevelo/shortcuts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Keyboard shortcuts with one document listener. Chords are written once (`"mod+k"`) and
|
|
4
|
+
read three ways that agree: the key event that runs them, the hint a menu shows
|
|
5
|
+
(`⌘K` on a Mac, `Ctrl+K` elsewhere) and the `aria-keyshortcuts` value. Shortcuts can be
|
|
6
|
+
grouped into scopes, pause while a layer above their element is open, and stay out of
|
|
7
|
+
plain typing.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pnpm add @bevelo/shortcuts
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createShortcuts, formatShortcut } from "@bevelo/shortcuts";
|
|
19
|
+
|
|
20
|
+
const shortcuts = createShortcuts();
|
|
21
|
+
|
|
22
|
+
const unregister = shortcuts.register("mod+k", () => {
|
|
23
|
+
openPalette();
|
|
24
|
+
return true; // claimed: the event is prevented
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
hint.textContent = formatShortcut("mod+k");
|
|
28
|
+
|
|
29
|
+
// Later:
|
|
30
|
+
unregister();
|
|
31
|
+
shortcuts.dispose();
|
|
32
|
+
|
|
33
|
+
declare function openPalette(): void;
|
|
34
|
+
declare const hint: HTMLElement;
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Stability
|
|
38
|
+
|
|
39
|
+
The package is `@experimental` and may change in any minor release.
|
|
40
|
+
|
|
41
|
+
## Docs
|
|
42
|
+
|
|
43
|
+
See the shortcuts utility page in the
|
|
44
|
+
[Bevelo docs](https://github.com/bevelo/bevelo/tree/main/apps/docs/src/content/docs).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _bevelo_core_platform = require("@bevelo/core/platform");
|
|
3
|
+
// src/keys.ts
|
|
4
|
+
const MODIFIER_ALIASES = /* @__PURE__ */ new Map([
|
|
5
|
+
["mod", "mod"],
|
|
6
|
+
["cmd", "meta"],
|
|
7
|
+
["command", "meta"],
|
|
8
|
+
["meta", "meta"],
|
|
9
|
+
["ctrl", "ctrl"],
|
|
10
|
+
["control", "ctrl"],
|
|
11
|
+
["alt", "alt"],
|
|
12
|
+
["option", "alt"],
|
|
13
|
+
["opt", "alt"],
|
|
14
|
+
["shift", "shift"]
|
|
15
|
+
]);
|
|
16
|
+
/** Spellings a host may write for keys whose `event.key` differs. */
|
|
17
|
+
const KEY_ALIASES = /* @__PURE__ */ new Map([
|
|
18
|
+
["esc", "escape"],
|
|
19
|
+
["return", "enter"],
|
|
20
|
+
["space", " "],
|
|
21
|
+
["spacebar", " "],
|
|
22
|
+
["del", "delete"],
|
|
23
|
+
["up", "arrowup"],
|
|
24
|
+
["down", "arrowdown"],
|
|
25
|
+
["left", "arrowleft"],
|
|
26
|
+
["right", "arrowright"],
|
|
27
|
+
["pgup", "pageup"],
|
|
28
|
+
["pgdn", "pagedown"]
|
|
29
|
+
]);
|
|
30
|
+
/** Lower-cases `event.key` without trimming, because Space is " ". */
|
|
31
|
+
function canonicalKey(raw) {
|
|
32
|
+
const lower = raw.toLowerCase();
|
|
33
|
+
return KEY_ALIASES.get(lower) ?? lower;
|
|
34
|
+
}
|
|
35
|
+
function splitTokens(keys) {
|
|
36
|
+
return keys.trim().split("+").map((token) => token.trim().toLowerCase());
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Parses "mod+shift+k" into flags and a key.
|
|
40
|
+
*
|
|
41
|
+
* `undefined` means the string is not a chord at all (empty, a lone modifier, two
|
|
42
|
+
* plain keys, an empty token). Registering one is a programming error, so
|
|
43
|
+
* `createShortcuts` throws on it rather than installing a binding that can never
|
|
44
|
+
* fire — a dead shortcut is discovered by a user, not by the host that added it.
|
|
45
|
+
*
|
|
46
|
+
* Duplicated modifiers collapse ("shift+shift+k" is still one Shift) and the
|
|
47
|
+
* modifiers may appear in any order; the written order is preserved for display.
|
|
48
|
+
*/
|
|
49
|
+
function parseChord(keys) {
|
|
50
|
+
const trimmed = keys.trim();
|
|
51
|
+
if (trimmed === "") return;
|
|
52
|
+
if (trimmed === "+") return {
|
|
53
|
+
mod: false,
|
|
54
|
+
ctrl: false,
|
|
55
|
+
alt: false,
|
|
56
|
+
shift: false,
|
|
57
|
+
meta: false,
|
|
58
|
+
key: "+"
|
|
59
|
+
};
|
|
60
|
+
let mod = false;
|
|
61
|
+
let ctrl = false;
|
|
62
|
+
let alt = false;
|
|
63
|
+
let shift = false;
|
|
64
|
+
let meta = false;
|
|
65
|
+
let key;
|
|
66
|
+
for (const token of splitTokens(trimmed)) {
|
|
67
|
+
if (token === "") return;
|
|
68
|
+
const modifier = MODIFIER_ALIASES.get(token);
|
|
69
|
+
if (modifier !== void 0) {
|
|
70
|
+
if (key !== void 0) return;
|
|
71
|
+
mod = mod || modifier === "mod";
|
|
72
|
+
ctrl = ctrl || modifier === "ctrl";
|
|
73
|
+
alt = alt || modifier === "alt";
|
|
74
|
+
shift = shift || modifier === "shift";
|
|
75
|
+
meta = meta || modifier === "meta";
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (key !== void 0) return;
|
|
79
|
+
key = canonicalKey(token);
|
|
80
|
+
}
|
|
81
|
+
if (key === void 0 || key === "") return;
|
|
82
|
+
return {
|
|
83
|
+
mod,
|
|
84
|
+
ctrl,
|
|
85
|
+
alt,
|
|
86
|
+
shift,
|
|
87
|
+
meta,
|
|
88
|
+
key
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The platform a host most likely runs.
|
|
93
|
+
*
|
|
94
|
+
* Read at call time rather than frozen at import, so a test that stubs the
|
|
95
|
+
* navigator and the host that formats a hint for the platform being viewed both
|
|
96
|
+
* get the answer they expect. Every entry point accepts an explicit platform, so
|
|
97
|
+
* this is only the default a caller can override.
|
|
98
|
+
*/
|
|
99
|
+
function detectPlatform() {
|
|
100
|
+
if (typeof navigator === "undefined") return "other";
|
|
101
|
+
const nav = navigator;
|
|
102
|
+
const hint = nav.userAgentData?.platform ?? nav.platform ?? nav.userAgent ?? "";
|
|
103
|
+
return /mac|iphone|ipad|ipod/i.test(hint) ? "mac" : "other";
|
|
104
|
+
}
|
|
105
|
+
/** Matches a parsed chord with a pre-normalized event key. */
|
|
106
|
+
function matchesChordKey(event, eventKey, chord, platform) {
|
|
107
|
+
return chord.key === eventKey && event.ctrlKey === (chord.ctrl || chord.mod && platform === "other") && event.altKey === chord.alt && event.shiftKey === chord.shift && event.metaKey === (chord.meta || chord.mod && platform === "mac");
|
|
108
|
+
}
|
|
109
|
+
/** Matches a parsed chord, the form dispatch uses after the first parse. */
|
|
110
|
+
function matchesChord(event, chord, platform = detectPlatform()) {
|
|
111
|
+
return matchesChordKey(event, canonicalKey(event.key), chord, platform);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Whether the event is the chord.
|
|
115
|
+
*
|
|
116
|
+
* "mod" is Command on a Mac and Control elsewhere, so the same host code binds
|
|
117
|
+
* correctly on both. Every modifier must match exactly, and the key is compared
|
|
118
|
+
* through `event.key` case-insensitively: "mod+shift+k" fires for a K typed with
|
|
119
|
+
* Shift, while "shift+1" does not fire for "!", because the key became a symbol
|
|
120
|
+
* and "1" is no longer what `event.key` reports.
|
|
121
|
+
*/
|
|
122
|
+
function matchesShortcut(event, keys, platform = detectPlatform()) {
|
|
123
|
+
const chord = parseChord(keys);
|
|
124
|
+
if (chord === void 0) return false;
|
|
125
|
+
return matchesChord(event, chord, platform);
|
|
126
|
+
}
|
|
127
|
+
const MAC_MODIFIER_LABELS = {
|
|
128
|
+
ctrl: "⌃",
|
|
129
|
+
alt: "⌥",
|
|
130
|
+
shift: "⇧",
|
|
131
|
+
meta: "⌘"
|
|
132
|
+
};
|
|
133
|
+
const OTHER_MODIFIER_LABELS = {
|
|
134
|
+
ctrl: "Ctrl",
|
|
135
|
+
alt: "Alt",
|
|
136
|
+
shift: "Shift",
|
|
137
|
+
meta: "Meta"
|
|
138
|
+
};
|
|
139
|
+
const MAC_KEY_LABELS = {
|
|
140
|
+
escape: "Esc",
|
|
141
|
+
enter: "↩",
|
|
142
|
+
backspace: "⌫",
|
|
143
|
+
delete: "⌦",
|
|
144
|
+
tab: "⇥",
|
|
145
|
+
arrowup: "↑",
|
|
146
|
+
arrowdown: "↓",
|
|
147
|
+
arrowleft: "←",
|
|
148
|
+
arrowright: "→"
|
|
149
|
+
};
|
|
150
|
+
function titleKey(key) {
|
|
151
|
+
return key.charAt(0).toUpperCase() + key.slice(1);
|
|
152
|
+
}
|
|
153
|
+
function displayKey(key, platform) {
|
|
154
|
+
const named = platform === "mac" ? MAC_KEY_LABELS[key] ?? ARIA_KEY_NAMES[key] : key === "escape" ? "Esc" : ARIA_KEY_NAMES[key];
|
|
155
|
+
if (named !== void 0) return named;
|
|
156
|
+
return key.length === 1 ? key.toUpperCase() : titleKey(key);
|
|
157
|
+
}
|
|
158
|
+
/** The modifier labels for a platform, in the order the host wrote them. "mod"
|
|
159
|
+
* resolves to Command on a Mac and Control elsewhere, which is the only mapping
|
|
160
|
+
* a hint has to get right. */
|
|
161
|
+
function displayModifier(modifier, platform) {
|
|
162
|
+
if (modifier === "mod") return platform === "mac" ? MAC_MODIFIER_LABELS.meta : OTHER_MODIFIER_LABELS.ctrl;
|
|
163
|
+
return (platform === "mac" ? MAC_MODIFIER_LABELS : OTHER_MODIFIER_LABELS)[modifier];
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Renders a chord the way a hint row shows it: "mod+k" is "⌘K" on a Mac and
|
|
167
|
+
* "Ctrl+K" elsewhere, "shift+alt+p" is "⇧⌥P" or "Shift+Alt+P".
|
|
168
|
+
*
|
|
169
|
+
* Modifier order follows the written order, not a canonical one: the host writes
|
|
170
|
+
* the chord once and it is displayed the same way everywhere, so a menu and the
|
|
171
|
+
* documented binding cannot drift. An invalid chord is returned unchanged — a
|
|
172
|
+
* display helper must not throw in a render.
|
|
173
|
+
*/
|
|
174
|
+
function formatShortcut(keys, options = {}) {
|
|
175
|
+
const platform = options.platform ?? detectPlatform();
|
|
176
|
+
const chord = parseChord(keys);
|
|
177
|
+
if (chord === void 0) return keys;
|
|
178
|
+
const labels = [];
|
|
179
|
+
const seen = /* @__PURE__ */ new Set();
|
|
180
|
+
for (const token of splitTokens(keys)) {
|
|
181
|
+
const modifier = MODIFIER_ALIASES.get(token);
|
|
182
|
+
if (modifier === void 0 || seen.has(modifier)) continue;
|
|
183
|
+
seen.add(modifier);
|
|
184
|
+
labels.push(displayModifier(modifier, platform));
|
|
185
|
+
}
|
|
186
|
+
labels.push(displayKey(chord.key, platform));
|
|
187
|
+
return labels.join(platform === "mac" ? "" : "+");
|
|
188
|
+
}
|
|
189
|
+
const ARIA_MODIFIER_NAMES = {
|
|
190
|
+
ctrl: "Control",
|
|
191
|
+
alt: "Alt",
|
|
192
|
+
shift: "Shift",
|
|
193
|
+
meta: "Meta"
|
|
194
|
+
};
|
|
195
|
+
const ARIA_KEY_NAMES = {
|
|
196
|
+
escape: "Escape",
|
|
197
|
+
enter: "Enter",
|
|
198
|
+
backspace: "Backspace",
|
|
199
|
+
delete: "Delete",
|
|
200
|
+
tab: "Tab",
|
|
201
|
+
" ": "Space",
|
|
202
|
+
arrowup: "ArrowUp",
|
|
203
|
+
arrowdown: "ArrowDown",
|
|
204
|
+
arrowleft: "ArrowLeft",
|
|
205
|
+
arrowright: "ArrowRight",
|
|
206
|
+
pageup: "PageUp",
|
|
207
|
+
pagedown: "PageDown",
|
|
208
|
+
home: "Home",
|
|
209
|
+
end: "End",
|
|
210
|
+
insert: "Insert"
|
|
211
|
+
};
|
|
212
|
+
function ariaKeyName(key) {
|
|
213
|
+
const named = ARIA_KEY_NAMES[key];
|
|
214
|
+
if (named !== void 0) return named;
|
|
215
|
+
return key.length === 1 ? key.toUpperCase() : titleKey(key);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* The `aria-keyshortcuts` value for a chord, in the DOM key vocabulary that
|
|
219
|
+
* assistive technology understands ("Meta+K", "Control+Shift+P", "Escape").
|
|
220
|
+
*
|
|
221
|
+
* This is deliberately not `formatShortcut`: screen readers compare the value
|
|
222
|
+
* with KeyboardEvent.key names, so the pretty glyphs would be unusable there.
|
|
223
|
+
* `undefined` for a chord that cannot be parsed, so a caller can omit the
|
|
224
|
+
* attribute instead of announcing a broken binding.
|
|
225
|
+
*/
|
|
226
|
+
function ariaShortcut(keys, platform = detectPlatform()) {
|
|
227
|
+
const chord = parseChord(keys);
|
|
228
|
+
if (chord === void 0) return;
|
|
229
|
+
const names = [];
|
|
230
|
+
const seen = /* @__PURE__ */ new Set();
|
|
231
|
+
const push = (name) => {
|
|
232
|
+
if (!seen.has(name)) {
|
|
233
|
+
seen.add(name);
|
|
234
|
+
names.push(name);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
for (const token of splitTokens(keys)) {
|
|
238
|
+
const modifier = MODIFIER_ALIASES.get(token);
|
|
239
|
+
if (modifier === void 0) continue;
|
|
240
|
+
if (modifier === "mod") push(platform === "mac" ? "Meta" : "Control");
|
|
241
|
+
else push(ARIA_MODIFIER_NAMES[modifier]);
|
|
242
|
+
}
|
|
243
|
+
names.push(ariaKeyName(chord.key));
|
|
244
|
+
return names.join("+");
|
|
245
|
+
}
|
|
246
|
+
// src/registry.ts
|
|
247
|
+
/** Walks from the event's real target up through ancestors. */
|
|
248
|
+
function targetElement(event) {
|
|
249
|
+
if (typeof Element === "undefined") return;
|
|
250
|
+
if (typeof event.composedPath === "function") {
|
|
251
|
+
for (const node of event.composedPath()) if (node instanceof Element) return node;
|
|
252
|
+
}
|
|
253
|
+
return event.target instanceof Element ? event.target : void 0;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Whether the keystroke is going into a text field.
|
|
257
|
+
*
|
|
258
|
+
* A plain letter shortcut must not steal typing; a chord with Control, Alt or
|
|
259
|
+
* Meta still must, because those combinations are not how text is entered. The
|
|
260
|
+
* edited element is found through the composed path so a control inside a shadow
|
|
261
|
+
* root counts, and the walk covers a contenteditable's child nodes.
|
|
262
|
+
*/
|
|
263
|
+
function isTypingTarget(event) {
|
|
264
|
+
let current = targetElement(event) ?? null;
|
|
265
|
+
while (current !== null) {
|
|
266
|
+
const tag = current.tagName;
|
|
267
|
+
if (tag === "INPUT" || tag === "TEXTAREA") return true;
|
|
268
|
+
const editable = current.getAttribute("contenteditable");
|
|
269
|
+
if (editable !== null && editable !== "false") return true;
|
|
270
|
+
current = current.parentElement;
|
|
271
|
+
}
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
/** Whether the chord carries a modifier that still means something while typing. */
|
|
275
|
+
function hasCommandModifier(chord) {
|
|
276
|
+
return chord.mod || chord.ctrl || chord.alt || chord.meta;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Creates one listener over a registry of shortcuts.
|
|
280
|
+
*
|
|
281
|
+
* The listener is installed at creation, not at the first registration: a host
|
|
282
|
+
* that registers on mount and renders before the first paint would otherwise
|
|
283
|
+
* miss the keystroke that arrives between the two. `dispose` removes it.
|
|
284
|
+
*/
|
|
285
|
+
function createShortcuts(options = {}) {
|
|
286
|
+
const platform = options.platform ?? detectPlatform();
|
|
287
|
+
const target = options.target ?? (typeof document === "undefined" ? void 0 : document);
|
|
288
|
+
const registrations = [];
|
|
289
|
+
const activeScopes = /* @__PURE__ */ new Set();
|
|
290
|
+
let disposed = false;
|
|
291
|
+
const isElementActive = (given, getLayers) => {
|
|
292
|
+
if (given === void 0) return !getLayers().some((layer) => layer.getAttribute("aria-modal") === "true");
|
|
293
|
+
const element = typeof given === "function" ? given() : given;
|
|
294
|
+
if (element == null || element.closest("[hidden], [inert]") !== null) return false;
|
|
295
|
+
const stacked = getLayers();
|
|
296
|
+
const top = stacked[stacked.length - 1];
|
|
297
|
+
return top === void 0 || top === element || top.contains(element);
|
|
298
|
+
};
|
|
299
|
+
const isEnabled = (registration, getLayers) => {
|
|
300
|
+
const settings = registration.options;
|
|
301
|
+
if (settings.scope !== void 0 && !activeScopes.has(settings.scope)) return false;
|
|
302
|
+
if (settings.when !== void 0 && settings.when() !== true) return false;
|
|
303
|
+
return isElementActive(settings.element, getLayers);
|
|
304
|
+
};
|
|
305
|
+
const layerReader = () => {
|
|
306
|
+
let cached;
|
|
307
|
+
return () => cached ??= (0, _bevelo_core_platform.layers)();
|
|
308
|
+
};
|
|
309
|
+
const handle = (event) => {
|
|
310
|
+
if (disposed || event.defaultPrevented || event.isComposing || event.repeat) return false;
|
|
311
|
+
const getLayers = layerReader();
|
|
312
|
+
let typing;
|
|
313
|
+
const eventKey = canonicalKey(event.key);
|
|
314
|
+
for (let i = 0; i < registrations.length; i += 1) {
|
|
315
|
+
const registration = registrations[i];
|
|
316
|
+
if (registration.removed || !matchesChordKey(event, eventKey, registration.chord, platform)) continue;
|
|
317
|
+
if (!hasCommandModifier(registration.chord)) {
|
|
318
|
+
typing ??= isTypingTarget(event);
|
|
319
|
+
if (typing) continue;
|
|
320
|
+
}
|
|
321
|
+
if (!isEnabled(registration, getLayers)) continue;
|
|
322
|
+
if (registration.handler(event) === false) continue;
|
|
323
|
+
event.preventDefault();
|
|
324
|
+
return true;
|
|
325
|
+
}
|
|
326
|
+
return false;
|
|
327
|
+
};
|
|
328
|
+
const onKeyDown = (event) => {
|
|
329
|
+
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) handle(event);
|
|
330
|
+
};
|
|
331
|
+
target?.addEventListener("keydown", onKeyDown);
|
|
332
|
+
const register = (keys, handler, registrationOptions = {}) => {
|
|
333
|
+
if (disposed) throw new Error("createShortcuts: register() was called after dispose()");
|
|
334
|
+
const chord = parseChord(keys);
|
|
335
|
+
if (chord === void 0) throw new TypeError("createShortcuts: \"" + keys + "\" is not a shortcut chord");
|
|
336
|
+
const registration = {
|
|
337
|
+
keys,
|
|
338
|
+
chord,
|
|
339
|
+
handler,
|
|
340
|
+
options: { ...registrationOptions },
|
|
341
|
+
removed: false
|
|
342
|
+
};
|
|
343
|
+
registrations.push(registration);
|
|
344
|
+
return () => {
|
|
345
|
+
if (registration.removed) return;
|
|
346
|
+
registration.removed = true;
|
|
347
|
+
const index = registrations.indexOf(registration);
|
|
348
|
+
if (index !== -1) registrations.splice(index, 1);
|
|
349
|
+
};
|
|
350
|
+
};
|
|
351
|
+
const setScope = (scope, active) => {
|
|
352
|
+
if (disposed) return;
|
|
353
|
+
if (active) activeScopes.add(scope);
|
|
354
|
+
else activeScopes.delete(scope);
|
|
355
|
+
};
|
|
356
|
+
const list = () => {
|
|
357
|
+
const getLayers = layerReader();
|
|
358
|
+
const infos = [];
|
|
359
|
+
for (const registration of registrations) {
|
|
360
|
+
if (registration.removed) continue;
|
|
361
|
+
const settings = registration.options;
|
|
362
|
+
infos.push({
|
|
363
|
+
keys: registration.keys,
|
|
364
|
+
enabled: isEnabled(registration, getLayers),
|
|
365
|
+
...settings.id !== void 0 ? { id: settings.id } : {},
|
|
366
|
+
...settings.description !== void 0 ? { description: settings.description } : {},
|
|
367
|
+
...settings.scope !== void 0 ? { scope: settings.scope } : {}
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
return infos;
|
|
371
|
+
};
|
|
372
|
+
const keyshortcutsFor = (id) => {
|
|
373
|
+
for (const registration of registrations) {
|
|
374
|
+
if (registration.removed || registration.options.id !== id) continue;
|
|
375
|
+
return ariaShortcut(registration.keys, platform);
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
const dispose = () => {
|
|
379
|
+
if (disposed) return;
|
|
380
|
+
disposed = true;
|
|
381
|
+
target?.removeEventListener("keydown", onKeyDown);
|
|
382
|
+
registrations.length = 0;
|
|
383
|
+
activeScopes.clear();
|
|
384
|
+
};
|
|
385
|
+
return {
|
|
386
|
+
register,
|
|
387
|
+
setScope,
|
|
388
|
+
list,
|
|
389
|
+
handle,
|
|
390
|
+
dispose,
|
|
391
|
+
keyshortcutsFor
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
exports.ariaShortcut = ariaShortcut;
|
|
395
|
+
exports.createShortcuts = createShortcuts;
|
|
396
|
+
exports.formatShortcut = formatShortcut;
|
|
397
|
+
exports.matchesShortcut = matchesShortcut;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/** Which modifier "mod" resolves to. Passed explicitly in tests and on a host
|
|
2
|
+
* that renders hints for a platform other than the one it runs on. */
|
|
3
|
+
type ShortcutPlatform = "mac" | "other";
|
|
4
|
+
/**
|
|
5
|
+
* Whether the event is the chord.
|
|
6
|
+
*
|
|
7
|
+
* "mod" is Command on a Mac and Control elsewhere, so the same host code binds
|
|
8
|
+
* correctly on both. Every modifier must match exactly, and the key is compared
|
|
9
|
+
* through `event.key` case-insensitively: "mod+shift+k" fires for a K typed with
|
|
10
|
+
* Shift, while "shift+1" does not fire for "!", because the key became a symbol
|
|
11
|
+
* and "1" is no longer what `event.key` reports.
|
|
12
|
+
*/
|
|
13
|
+
export declare function matchesShortcut(event: KeyboardEvent, keys: string, platform?: ShortcutPlatform): boolean;
|
|
14
|
+
interface FormatShortcutOptions {
|
|
15
|
+
/** Defaults to the running platform. */
|
|
16
|
+
platform?: ShortcutPlatform;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Renders a chord the way a hint row shows it: "mod+k" is "⌘K" on a Mac and
|
|
20
|
+
* "Ctrl+K" elsewhere, "shift+alt+p" is "⇧⌥P" or "Shift+Alt+P".
|
|
21
|
+
*
|
|
22
|
+
* Modifier order follows the written order, not a canonical one: the host writes
|
|
23
|
+
* the chord once and it is displayed the same way everywhere, so a menu and the
|
|
24
|
+
* documented binding cannot drift. An invalid chord is returned unchanged — a
|
|
25
|
+
* display helper must not throw in a render.
|
|
26
|
+
*/
|
|
27
|
+
export declare function formatShortcut(keys: string, options?: FormatShortcutOptions): string;
|
|
28
|
+
/**
|
|
29
|
+
* The `aria-keyshortcuts` value for a chord, in the DOM key vocabulary that
|
|
30
|
+
* assistive technology understands ("Meta+K", "Control+Shift+P", "Escape").
|
|
31
|
+
*
|
|
32
|
+
* This is deliberately not `formatShortcut`: screen readers compare the value
|
|
33
|
+
* with KeyboardEvent.key names, so the pretty glyphs would be unusable there.
|
|
34
|
+
* `undefined` for a chord that cannot be parsed, so a caller can omit the
|
|
35
|
+
* attribute instead of announcing a broken binding.
|
|
36
|
+
*/
|
|
37
|
+
export declare function ariaShortcut(keys: string, platform?: ShortcutPlatform): string | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* What a handler may answer. Returning `false` declines the shortcut: dispatch
|
|
40
|
+
* continues with the next match (if any) and the browser keeps the keystroke.
|
|
41
|
+
* Anything else claims it and the event is prevented.
|
|
42
|
+
*/
|
|
43
|
+
type ShortcutHandler = (event: KeyboardEvent) => boolean | void;
|
|
44
|
+
interface ShortcutOptions {
|
|
45
|
+
/**
|
|
46
|
+
* The scope must be active for the shortcut to run; absent means always.
|
|
47
|
+
* Scopes start inactive, so a host registers a scoped shortcut and activates
|
|
48
|
+
* the scope when the surface it belongs to is on screen.
|
|
49
|
+
*/
|
|
50
|
+
scope?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Ties the shortcut to an element: it runs only while the platform's top layer
|
|
53
|
+
* contains that element. A page-level shortcut is therefore paused while a
|
|
54
|
+
* modal is open, and a shortcut inside the modal keeps working. A function is
|
|
55
|
+
* read at dispatch, for an element that mounts and unmounts; while it
|
|
56
|
+
* answers no element the shortcut is inactive.
|
|
57
|
+
*/
|
|
58
|
+
element?: Element | (() => Element | null | undefined);
|
|
59
|
+
/** Last veto before the handler: queried at dispatch time, not registration. */
|
|
60
|
+
when?: () => boolean;
|
|
61
|
+
/** Stable name used by `keyshortcutsFor` and by list consumers. */
|
|
62
|
+
id?: string;
|
|
63
|
+
/** Human description for a shortcut list ("Save document"). */
|
|
64
|
+
description?: string;
|
|
65
|
+
}
|
|
66
|
+
/** One registration as `list()` reports it. */
|
|
67
|
+
interface ShortcutInfo {
|
|
68
|
+
/** The chord as registered ("mod+k"). */
|
|
69
|
+
readonly keys: string;
|
|
70
|
+
readonly id?: string;
|
|
71
|
+
readonly description?: string;
|
|
72
|
+
readonly scope?: string;
|
|
73
|
+
/** Whether the shortcut would run right now: scope active, `when` allows,
|
|
74
|
+
* and its element's layer is topmost. */
|
|
75
|
+
readonly enabled: boolean;
|
|
76
|
+
}
|
|
77
|
+
interface ShortcutsOptions {
|
|
78
|
+
/** The document the listener attaches to; defaults to the global document so a
|
|
79
|
+
* test can supply a fresh one, and an SSR host can omit it entirely. */
|
|
80
|
+
target?: Document;
|
|
81
|
+
/** Defaults to the navigator's platform. */
|
|
82
|
+
platform?: ShortcutPlatform;
|
|
83
|
+
}
|
|
84
|
+
interface Shortcuts {
|
|
85
|
+
/** Adds a binding and returns its unregister. Idempotent to unregister. */
|
|
86
|
+
register(keys: string, handler: ShortcutHandler, options?: ShortcutOptions): () => void;
|
|
87
|
+
/** Turns every shortcut in a scope on or off. Scopes start inactive; a
|
|
88
|
+
* scoped shortcut never runs until its scope has been activated. */
|
|
89
|
+
setScope(scope: string, active: boolean): void;
|
|
90
|
+
/** Every live registration, in registration order. */
|
|
91
|
+
list(): readonly ShortcutInfo[];
|
|
92
|
+
/**
|
|
93
|
+
* Dispatches one key event; returns whether a shortcut claimed it.
|
|
94
|
+
*
|
|
95
|
+
* Ignored without running anything when the event was already prevented, is
|
|
96
|
+
* composing (IME), or repeats because the key is held: a shortcut fires once
|
|
97
|
+
* per physical press. A host with its own listener can call this instead of
|
|
98
|
+
* relying on the one `createShortcuts` installed.
|
|
99
|
+
*/
|
|
100
|
+
handle(event: KeyboardEvent): boolean;
|
|
101
|
+
/** Removes the listener and forgets every registration. */
|
|
102
|
+
dispose(): void;
|
|
103
|
+
/** The `aria-keyshortcuts` value for a registration id, for a control's attribute. */
|
|
104
|
+
keyshortcutsFor(id: string): string | undefined;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Creates one listener over a registry of shortcuts.
|
|
108
|
+
*
|
|
109
|
+
* The listener is installed at creation, not at the first registration: a host
|
|
110
|
+
* that registers on mount and renders before the first paint would otherwise
|
|
111
|
+
* miss the keystroke that arrives between the two. `dispose` removes it.
|
|
112
|
+
*/
|
|
113
|
+
export declare function createShortcuts(options?: ShortcutsOptions): Shortcuts;
|
|
114
|
+
export type { FormatShortcutOptions, ShortcutHandler, ShortcutInfo, ShortcutOptions, ShortcutPlatform, Shortcuts, ShortcutsOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/** Which modifier "mod" resolves to. Passed explicitly in tests and on a host
|
|
2
|
+
* that renders hints for a platform other than the one it runs on. */
|
|
3
|
+
type ShortcutPlatform = "mac" | "other";
|
|
4
|
+
/**
|
|
5
|
+
* Whether the event is the chord.
|
|
6
|
+
*
|
|
7
|
+
* "mod" is Command on a Mac and Control elsewhere, so the same host code binds
|
|
8
|
+
* correctly on both. Every modifier must match exactly, and the key is compared
|
|
9
|
+
* through `event.key` case-insensitively: "mod+shift+k" fires for a K typed with
|
|
10
|
+
* Shift, while "shift+1" does not fire for "!", because the key became a symbol
|
|
11
|
+
* and "1" is no longer what `event.key` reports.
|
|
12
|
+
*/
|
|
13
|
+
export declare function matchesShortcut(event: KeyboardEvent, keys: string, platform?: ShortcutPlatform): boolean;
|
|
14
|
+
interface FormatShortcutOptions {
|
|
15
|
+
/** Defaults to the running platform. */
|
|
16
|
+
platform?: ShortcutPlatform;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Renders a chord the way a hint row shows it: "mod+k" is "⌘K" on a Mac and
|
|
20
|
+
* "Ctrl+K" elsewhere, "shift+alt+p" is "⇧⌥P" or "Shift+Alt+P".
|
|
21
|
+
*
|
|
22
|
+
* Modifier order follows the written order, not a canonical one: the host writes
|
|
23
|
+
* the chord once and it is displayed the same way everywhere, so a menu and the
|
|
24
|
+
* documented binding cannot drift. An invalid chord is returned unchanged — a
|
|
25
|
+
* display helper must not throw in a render.
|
|
26
|
+
*/
|
|
27
|
+
export declare function formatShortcut(keys: string, options?: FormatShortcutOptions): string;
|
|
28
|
+
/**
|
|
29
|
+
* The `aria-keyshortcuts` value for a chord, in the DOM key vocabulary that
|
|
30
|
+
* assistive technology understands ("Meta+K", "Control+Shift+P", "Escape").
|
|
31
|
+
*
|
|
32
|
+
* This is deliberately not `formatShortcut`: screen readers compare the value
|
|
33
|
+
* with KeyboardEvent.key names, so the pretty glyphs would be unusable there.
|
|
34
|
+
* `undefined` for a chord that cannot be parsed, so a caller can omit the
|
|
35
|
+
* attribute instead of announcing a broken binding.
|
|
36
|
+
*/
|
|
37
|
+
export declare function ariaShortcut(keys: string, platform?: ShortcutPlatform): string | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* What a handler may answer. Returning `false` declines the shortcut: dispatch
|
|
40
|
+
* continues with the next match (if any) and the browser keeps the keystroke.
|
|
41
|
+
* Anything else claims it and the event is prevented.
|
|
42
|
+
*/
|
|
43
|
+
type ShortcutHandler = (event: KeyboardEvent) => boolean | void;
|
|
44
|
+
interface ShortcutOptions {
|
|
45
|
+
/**
|
|
46
|
+
* The scope must be active for the shortcut to run; absent means always.
|
|
47
|
+
* Scopes start inactive, so a host registers a scoped shortcut and activates
|
|
48
|
+
* the scope when the surface it belongs to is on screen.
|
|
49
|
+
*/
|
|
50
|
+
scope?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Ties the shortcut to an element: it runs only while the platform's top layer
|
|
53
|
+
* contains that element. A page-level shortcut is therefore paused while a
|
|
54
|
+
* modal is open, and a shortcut inside the modal keeps working. A function is
|
|
55
|
+
* read at dispatch, for an element that mounts and unmounts; while it
|
|
56
|
+
* answers no element the shortcut is inactive.
|
|
57
|
+
*/
|
|
58
|
+
element?: Element | (() => Element | null | undefined);
|
|
59
|
+
/** Last veto before the handler: queried at dispatch time, not registration. */
|
|
60
|
+
when?: () => boolean;
|
|
61
|
+
/** Stable name used by `keyshortcutsFor` and by list consumers. */
|
|
62
|
+
id?: string;
|
|
63
|
+
/** Human description for a shortcut list ("Save document"). */
|
|
64
|
+
description?: string;
|
|
65
|
+
}
|
|
66
|
+
/** One registration as `list()` reports it. */
|
|
67
|
+
interface ShortcutInfo {
|
|
68
|
+
/** The chord as registered ("mod+k"). */
|
|
69
|
+
readonly keys: string;
|
|
70
|
+
readonly id?: string;
|
|
71
|
+
readonly description?: string;
|
|
72
|
+
readonly scope?: string;
|
|
73
|
+
/** Whether the shortcut would run right now: scope active, `when` allows,
|
|
74
|
+
* and its element's layer is topmost. */
|
|
75
|
+
readonly enabled: boolean;
|
|
76
|
+
}
|
|
77
|
+
interface ShortcutsOptions {
|
|
78
|
+
/** The document the listener attaches to; defaults to the global document so a
|
|
79
|
+
* test can supply a fresh one, and an SSR host can omit it entirely. */
|
|
80
|
+
target?: Document;
|
|
81
|
+
/** Defaults to the navigator's platform. */
|
|
82
|
+
platform?: ShortcutPlatform;
|
|
83
|
+
}
|
|
84
|
+
interface Shortcuts {
|
|
85
|
+
/** Adds a binding and returns its unregister. Idempotent to unregister. */
|
|
86
|
+
register(keys: string, handler: ShortcutHandler, options?: ShortcutOptions): () => void;
|
|
87
|
+
/** Turns every shortcut in a scope on or off. Scopes start inactive; a
|
|
88
|
+
* scoped shortcut never runs until its scope has been activated. */
|
|
89
|
+
setScope(scope: string, active: boolean): void;
|
|
90
|
+
/** Every live registration, in registration order. */
|
|
91
|
+
list(): readonly ShortcutInfo[];
|
|
92
|
+
/**
|
|
93
|
+
* Dispatches one key event; returns whether a shortcut claimed it.
|
|
94
|
+
*
|
|
95
|
+
* Ignored without running anything when the event was already prevented, is
|
|
96
|
+
* composing (IME), or repeats because the key is held: a shortcut fires once
|
|
97
|
+
* per physical press. A host with its own listener can call this instead of
|
|
98
|
+
* relying on the one `createShortcuts` installed.
|
|
99
|
+
*/
|
|
100
|
+
handle(event: KeyboardEvent): boolean;
|
|
101
|
+
/** Removes the listener and forgets every registration. */
|
|
102
|
+
dispose(): void;
|
|
103
|
+
/** The `aria-keyshortcuts` value for a registration id, for a control's attribute. */
|
|
104
|
+
keyshortcutsFor(id: string): string | undefined;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Creates one listener over a registry of shortcuts.
|
|
108
|
+
*
|
|
109
|
+
* The listener is installed at creation, not at the first registration: a host
|
|
110
|
+
* that registers on mount and renders before the first paint would otherwise
|
|
111
|
+
* miss the keystroke that arrives between the two. `dispose` removes it.
|
|
112
|
+
*/
|
|
113
|
+
export declare function createShortcuts(options?: ShortcutsOptions): Shortcuts;
|
|
114
|
+
export type { FormatShortcutOptions, ShortcutHandler, ShortcutInfo, ShortcutOptions, ShortcutPlatform, Shortcuts, ShortcutsOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import { layers } from "@bevelo/core/platform";
|
|
2
|
+
// src/keys.ts
|
|
3
|
+
const MODIFIER_ALIASES = /* @__PURE__ */ new Map([
|
|
4
|
+
["mod", "mod"],
|
|
5
|
+
["cmd", "meta"],
|
|
6
|
+
["command", "meta"],
|
|
7
|
+
["meta", "meta"],
|
|
8
|
+
["ctrl", "ctrl"],
|
|
9
|
+
["control", "ctrl"],
|
|
10
|
+
["alt", "alt"],
|
|
11
|
+
["option", "alt"],
|
|
12
|
+
["opt", "alt"],
|
|
13
|
+
["shift", "shift"]
|
|
14
|
+
]);
|
|
15
|
+
/** Spellings a host may write for keys whose `event.key` differs. */
|
|
16
|
+
const KEY_ALIASES = /* @__PURE__ */ new Map([
|
|
17
|
+
["esc", "escape"],
|
|
18
|
+
["return", "enter"],
|
|
19
|
+
["space", " "],
|
|
20
|
+
["spacebar", " "],
|
|
21
|
+
["del", "delete"],
|
|
22
|
+
["up", "arrowup"],
|
|
23
|
+
["down", "arrowdown"],
|
|
24
|
+
["left", "arrowleft"],
|
|
25
|
+
["right", "arrowright"],
|
|
26
|
+
["pgup", "pageup"],
|
|
27
|
+
["pgdn", "pagedown"]
|
|
28
|
+
]);
|
|
29
|
+
/** Lower-cases `event.key` without trimming, because Space is " ". */
|
|
30
|
+
function canonicalKey(raw) {
|
|
31
|
+
const lower = raw.toLowerCase();
|
|
32
|
+
return KEY_ALIASES.get(lower) ?? lower;
|
|
33
|
+
}
|
|
34
|
+
function splitTokens(keys) {
|
|
35
|
+
return keys.trim().split("+").map((token) => token.trim().toLowerCase());
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Parses "mod+shift+k" into flags and a key.
|
|
39
|
+
*
|
|
40
|
+
* `undefined` means the string is not a chord at all (empty, a lone modifier, two
|
|
41
|
+
* plain keys, an empty token). Registering one is a programming error, so
|
|
42
|
+
* `createShortcuts` throws on it rather than installing a binding that can never
|
|
43
|
+
* fire — a dead shortcut is discovered by a user, not by the host that added it.
|
|
44
|
+
*
|
|
45
|
+
* Duplicated modifiers collapse ("shift+shift+k" is still one Shift) and the
|
|
46
|
+
* modifiers may appear in any order; the written order is preserved for display.
|
|
47
|
+
*/
|
|
48
|
+
function parseChord(keys) {
|
|
49
|
+
const trimmed = keys.trim();
|
|
50
|
+
if (trimmed === "") return;
|
|
51
|
+
if (trimmed === "+") return {
|
|
52
|
+
mod: false,
|
|
53
|
+
ctrl: false,
|
|
54
|
+
alt: false,
|
|
55
|
+
shift: false,
|
|
56
|
+
meta: false,
|
|
57
|
+
key: "+"
|
|
58
|
+
};
|
|
59
|
+
let mod = false;
|
|
60
|
+
let ctrl = false;
|
|
61
|
+
let alt = false;
|
|
62
|
+
let shift = false;
|
|
63
|
+
let meta = false;
|
|
64
|
+
let key;
|
|
65
|
+
for (const token of splitTokens(trimmed)) {
|
|
66
|
+
if (token === "") return;
|
|
67
|
+
const modifier = MODIFIER_ALIASES.get(token);
|
|
68
|
+
if (modifier !== void 0) {
|
|
69
|
+
if (key !== void 0) return;
|
|
70
|
+
mod = mod || modifier === "mod";
|
|
71
|
+
ctrl = ctrl || modifier === "ctrl";
|
|
72
|
+
alt = alt || modifier === "alt";
|
|
73
|
+
shift = shift || modifier === "shift";
|
|
74
|
+
meta = meta || modifier === "meta";
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (key !== void 0) return;
|
|
78
|
+
key = canonicalKey(token);
|
|
79
|
+
}
|
|
80
|
+
if (key === void 0 || key === "") return;
|
|
81
|
+
return {
|
|
82
|
+
mod,
|
|
83
|
+
ctrl,
|
|
84
|
+
alt,
|
|
85
|
+
shift,
|
|
86
|
+
meta,
|
|
87
|
+
key
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The platform a host most likely runs.
|
|
92
|
+
*
|
|
93
|
+
* Read at call time rather than frozen at import, so a test that stubs the
|
|
94
|
+
* navigator and the host that formats a hint for the platform being viewed both
|
|
95
|
+
* get the answer they expect. Every entry point accepts an explicit platform, so
|
|
96
|
+
* this is only the default a caller can override.
|
|
97
|
+
*/
|
|
98
|
+
function detectPlatform() {
|
|
99
|
+
if (typeof navigator === "undefined") return "other";
|
|
100
|
+
const nav = navigator;
|
|
101
|
+
const hint = nav.userAgentData?.platform ?? nav.platform ?? nav.userAgent ?? "";
|
|
102
|
+
return /mac|iphone|ipad|ipod/i.test(hint) ? "mac" : "other";
|
|
103
|
+
}
|
|
104
|
+
/** Matches a parsed chord with a pre-normalized event key. */
|
|
105
|
+
function matchesChordKey(event, eventKey, chord, platform) {
|
|
106
|
+
return chord.key === eventKey && event.ctrlKey === (chord.ctrl || chord.mod && platform === "other") && event.altKey === chord.alt && event.shiftKey === chord.shift && event.metaKey === (chord.meta || chord.mod && platform === "mac");
|
|
107
|
+
}
|
|
108
|
+
/** Matches a parsed chord, the form dispatch uses after the first parse. */
|
|
109
|
+
function matchesChord(event, chord, platform = detectPlatform()) {
|
|
110
|
+
return matchesChordKey(event, canonicalKey(event.key), chord, platform);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Whether the event is the chord.
|
|
114
|
+
*
|
|
115
|
+
* "mod" is Command on a Mac and Control elsewhere, so the same host code binds
|
|
116
|
+
* correctly on both. Every modifier must match exactly, and the key is compared
|
|
117
|
+
* through `event.key` case-insensitively: "mod+shift+k" fires for a K typed with
|
|
118
|
+
* Shift, while "shift+1" does not fire for "!", because the key became a symbol
|
|
119
|
+
* and "1" is no longer what `event.key` reports.
|
|
120
|
+
*/
|
|
121
|
+
function matchesShortcut(event, keys, platform = detectPlatform()) {
|
|
122
|
+
const chord = parseChord(keys);
|
|
123
|
+
if (chord === void 0) return false;
|
|
124
|
+
return matchesChord(event, chord, platform);
|
|
125
|
+
}
|
|
126
|
+
const MAC_MODIFIER_LABELS = {
|
|
127
|
+
ctrl: "⌃",
|
|
128
|
+
alt: "⌥",
|
|
129
|
+
shift: "⇧",
|
|
130
|
+
meta: "⌘"
|
|
131
|
+
};
|
|
132
|
+
const OTHER_MODIFIER_LABELS = {
|
|
133
|
+
ctrl: "Ctrl",
|
|
134
|
+
alt: "Alt",
|
|
135
|
+
shift: "Shift",
|
|
136
|
+
meta: "Meta"
|
|
137
|
+
};
|
|
138
|
+
const MAC_KEY_LABELS = {
|
|
139
|
+
escape: "Esc",
|
|
140
|
+
enter: "↩",
|
|
141
|
+
backspace: "⌫",
|
|
142
|
+
delete: "⌦",
|
|
143
|
+
tab: "⇥",
|
|
144
|
+
arrowup: "↑",
|
|
145
|
+
arrowdown: "↓",
|
|
146
|
+
arrowleft: "←",
|
|
147
|
+
arrowright: "→"
|
|
148
|
+
};
|
|
149
|
+
function titleKey(key) {
|
|
150
|
+
return key.charAt(0).toUpperCase() + key.slice(1);
|
|
151
|
+
}
|
|
152
|
+
function displayKey(key, platform) {
|
|
153
|
+
const named = platform === "mac" ? MAC_KEY_LABELS[key] ?? ARIA_KEY_NAMES[key] : key === "escape" ? "Esc" : ARIA_KEY_NAMES[key];
|
|
154
|
+
if (named !== void 0) return named;
|
|
155
|
+
return key.length === 1 ? key.toUpperCase() : titleKey(key);
|
|
156
|
+
}
|
|
157
|
+
/** The modifier labels for a platform, in the order the host wrote them. "mod"
|
|
158
|
+
* resolves to Command on a Mac and Control elsewhere, which is the only mapping
|
|
159
|
+
* a hint has to get right. */
|
|
160
|
+
function displayModifier(modifier, platform) {
|
|
161
|
+
if (modifier === "mod") return platform === "mac" ? MAC_MODIFIER_LABELS.meta : OTHER_MODIFIER_LABELS.ctrl;
|
|
162
|
+
return (platform === "mac" ? MAC_MODIFIER_LABELS : OTHER_MODIFIER_LABELS)[modifier];
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Renders a chord the way a hint row shows it: "mod+k" is "⌘K" on a Mac and
|
|
166
|
+
* "Ctrl+K" elsewhere, "shift+alt+p" is "⇧⌥P" or "Shift+Alt+P".
|
|
167
|
+
*
|
|
168
|
+
* Modifier order follows the written order, not a canonical one: the host writes
|
|
169
|
+
* the chord once and it is displayed the same way everywhere, so a menu and the
|
|
170
|
+
* documented binding cannot drift. An invalid chord is returned unchanged — a
|
|
171
|
+
* display helper must not throw in a render.
|
|
172
|
+
*/
|
|
173
|
+
function formatShortcut(keys, options = {}) {
|
|
174
|
+
const platform = options.platform ?? detectPlatform();
|
|
175
|
+
const chord = parseChord(keys);
|
|
176
|
+
if (chord === void 0) return keys;
|
|
177
|
+
const labels = [];
|
|
178
|
+
const seen = /* @__PURE__ */ new Set();
|
|
179
|
+
for (const token of splitTokens(keys)) {
|
|
180
|
+
const modifier = MODIFIER_ALIASES.get(token);
|
|
181
|
+
if (modifier === void 0 || seen.has(modifier)) continue;
|
|
182
|
+
seen.add(modifier);
|
|
183
|
+
labels.push(displayModifier(modifier, platform));
|
|
184
|
+
}
|
|
185
|
+
labels.push(displayKey(chord.key, platform));
|
|
186
|
+
return labels.join(platform === "mac" ? "" : "+");
|
|
187
|
+
}
|
|
188
|
+
const ARIA_MODIFIER_NAMES = {
|
|
189
|
+
ctrl: "Control",
|
|
190
|
+
alt: "Alt",
|
|
191
|
+
shift: "Shift",
|
|
192
|
+
meta: "Meta"
|
|
193
|
+
};
|
|
194
|
+
const ARIA_KEY_NAMES = {
|
|
195
|
+
escape: "Escape",
|
|
196
|
+
enter: "Enter",
|
|
197
|
+
backspace: "Backspace",
|
|
198
|
+
delete: "Delete",
|
|
199
|
+
tab: "Tab",
|
|
200
|
+
" ": "Space",
|
|
201
|
+
arrowup: "ArrowUp",
|
|
202
|
+
arrowdown: "ArrowDown",
|
|
203
|
+
arrowleft: "ArrowLeft",
|
|
204
|
+
arrowright: "ArrowRight",
|
|
205
|
+
pageup: "PageUp",
|
|
206
|
+
pagedown: "PageDown",
|
|
207
|
+
home: "Home",
|
|
208
|
+
end: "End",
|
|
209
|
+
insert: "Insert"
|
|
210
|
+
};
|
|
211
|
+
function ariaKeyName(key) {
|
|
212
|
+
const named = ARIA_KEY_NAMES[key];
|
|
213
|
+
if (named !== void 0) return named;
|
|
214
|
+
return key.length === 1 ? key.toUpperCase() : titleKey(key);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* The `aria-keyshortcuts` value for a chord, in the DOM key vocabulary that
|
|
218
|
+
* assistive technology understands ("Meta+K", "Control+Shift+P", "Escape").
|
|
219
|
+
*
|
|
220
|
+
* This is deliberately not `formatShortcut`: screen readers compare the value
|
|
221
|
+
* with KeyboardEvent.key names, so the pretty glyphs would be unusable there.
|
|
222
|
+
* `undefined` for a chord that cannot be parsed, so a caller can omit the
|
|
223
|
+
* attribute instead of announcing a broken binding.
|
|
224
|
+
*/
|
|
225
|
+
function ariaShortcut(keys, platform = detectPlatform()) {
|
|
226
|
+
const chord = parseChord(keys);
|
|
227
|
+
if (chord === void 0) return;
|
|
228
|
+
const names = [];
|
|
229
|
+
const seen = /* @__PURE__ */ new Set();
|
|
230
|
+
const push = (name) => {
|
|
231
|
+
if (!seen.has(name)) {
|
|
232
|
+
seen.add(name);
|
|
233
|
+
names.push(name);
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
for (const token of splitTokens(keys)) {
|
|
237
|
+
const modifier = MODIFIER_ALIASES.get(token);
|
|
238
|
+
if (modifier === void 0) continue;
|
|
239
|
+
if (modifier === "mod") push(platform === "mac" ? "Meta" : "Control");
|
|
240
|
+
else push(ARIA_MODIFIER_NAMES[modifier]);
|
|
241
|
+
}
|
|
242
|
+
names.push(ariaKeyName(chord.key));
|
|
243
|
+
return names.join("+");
|
|
244
|
+
}
|
|
245
|
+
// src/registry.ts
|
|
246
|
+
/** Walks from the event's real target up through ancestors. */
|
|
247
|
+
function targetElement(event) {
|
|
248
|
+
if (typeof Element === "undefined") return;
|
|
249
|
+
if (typeof event.composedPath === "function") {
|
|
250
|
+
for (const node of event.composedPath()) if (node instanceof Element) return node;
|
|
251
|
+
}
|
|
252
|
+
return event.target instanceof Element ? event.target : void 0;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Whether the keystroke is going into a text field.
|
|
256
|
+
*
|
|
257
|
+
* A plain letter shortcut must not steal typing; a chord with Control, Alt or
|
|
258
|
+
* Meta still must, because those combinations are not how text is entered. The
|
|
259
|
+
* edited element is found through the composed path so a control inside a shadow
|
|
260
|
+
* root counts, and the walk covers a contenteditable's child nodes.
|
|
261
|
+
*/
|
|
262
|
+
function isTypingTarget(event) {
|
|
263
|
+
let current = targetElement(event) ?? null;
|
|
264
|
+
while (current !== null) {
|
|
265
|
+
const tag = current.tagName;
|
|
266
|
+
if (tag === "INPUT" || tag === "TEXTAREA") return true;
|
|
267
|
+
const editable = current.getAttribute("contenteditable");
|
|
268
|
+
if (editable !== null && editable !== "false") return true;
|
|
269
|
+
current = current.parentElement;
|
|
270
|
+
}
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
/** Whether the chord carries a modifier that still means something while typing. */
|
|
274
|
+
function hasCommandModifier(chord) {
|
|
275
|
+
return chord.mod || chord.ctrl || chord.alt || chord.meta;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Creates one listener over a registry of shortcuts.
|
|
279
|
+
*
|
|
280
|
+
* The listener is installed at creation, not at the first registration: a host
|
|
281
|
+
* that registers on mount and renders before the first paint would otherwise
|
|
282
|
+
* miss the keystroke that arrives between the two. `dispose` removes it.
|
|
283
|
+
*/
|
|
284
|
+
function createShortcuts(options = {}) {
|
|
285
|
+
const platform = options.platform ?? detectPlatform();
|
|
286
|
+
const target = options.target ?? (typeof document === "undefined" ? void 0 : document);
|
|
287
|
+
const registrations = [];
|
|
288
|
+
const activeScopes = /* @__PURE__ */ new Set();
|
|
289
|
+
let disposed = false;
|
|
290
|
+
const isElementActive = (given, getLayers) => {
|
|
291
|
+
if (given === void 0) return !getLayers().some((layer) => layer.getAttribute("aria-modal") === "true");
|
|
292
|
+
const element = typeof given === "function" ? given() : given;
|
|
293
|
+
if (element == null || element.closest("[hidden], [inert]") !== null) return false;
|
|
294
|
+
const stacked = getLayers();
|
|
295
|
+
const top = stacked[stacked.length - 1];
|
|
296
|
+
return top === void 0 || top === element || top.contains(element);
|
|
297
|
+
};
|
|
298
|
+
const isEnabled = (registration, getLayers) => {
|
|
299
|
+
const settings = registration.options;
|
|
300
|
+
if (settings.scope !== void 0 && !activeScopes.has(settings.scope)) return false;
|
|
301
|
+
if (settings.when !== void 0 && settings.when() !== true) return false;
|
|
302
|
+
return isElementActive(settings.element, getLayers);
|
|
303
|
+
};
|
|
304
|
+
const layerReader = () => {
|
|
305
|
+
let cached;
|
|
306
|
+
return () => cached ??= layers();
|
|
307
|
+
};
|
|
308
|
+
const handle = (event) => {
|
|
309
|
+
if (disposed || event.defaultPrevented || event.isComposing || event.repeat) return false;
|
|
310
|
+
const getLayers = layerReader();
|
|
311
|
+
let typing;
|
|
312
|
+
const eventKey = canonicalKey(event.key);
|
|
313
|
+
for (let i = 0; i < registrations.length; i += 1) {
|
|
314
|
+
const registration = registrations[i];
|
|
315
|
+
if (registration.removed || !matchesChordKey(event, eventKey, registration.chord, platform)) continue;
|
|
316
|
+
if (!hasCommandModifier(registration.chord)) {
|
|
317
|
+
typing ??= isTypingTarget(event);
|
|
318
|
+
if (typing) continue;
|
|
319
|
+
}
|
|
320
|
+
if (!isEnabled(registration, getLayers)) continue;
|
|
321
|
+
if (registration.handler(event) === false) continue;
|
|
322
|
+
event.preventDefault();
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
return false;
|
|
326
|
+
};
|
|
327
|
+
const onKeyDown = (event) => {
|
|
328
|
+
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) handle(event);
|
|
329
|
+
};
|
|
330
|
+
target?.addEventListener("keydown", onKeyDown);
|
|
331
|
+
const register = (keys, handler, registrationOptions = {}) => {
|
|
332
|
+
if (disposed) throw new Error("createShortcuts: register() was called after dispose()");
|
|
333
|
+
const chord = parseChord(keys);
|
|
334
|
+
if (chord === void 0) throw new TypeError("createShortcuts: \"" + keys + "\" is not a shortcut chord");
|
|
335
|
+
const registration = {
|
|
336
|
+
keys,
|
|
337
|
+
chord,
|
|
338
|
+
handler,
|
|
339
|
+
options: { ...registrationOptions },
|
|
340
|
+
removed: false
|
|
341
|
+
};
|
|
342
|
+
registrations.push(registration);
|
|
343
|
+
return () => {
|
|
344
|
+
if (registration.removed) return;
|
|
345
|
+
registration.removed = true;
|
|
346
|
+
const index = registrations.indexOf(registration);
|
|
347
|
+
if (index !== -1) registrations.splice(index, 1);
|
|
348
|
+
};
|
|
349
|
+
};
|
|
350
|
+
const setScope = (scope, active) => {
|
|
351
|
+
if (disposed) return;
|
|
352
|
+
if (active) activeScopes.add(scope);
|
|
353
|
+
else activeScopes.delete(scope);
|
|
354
|
+
};
|
|
355
|
+
const list = () => {
|
|
356
|
+
const getLayers = layerReader();
|
|
357
|
+
const infos = [];
|
|
358
|
+
for (const registration of registrations) {
|
|
359
|
+
if (registration.removed) continue;
|
|
360
|
+
const settings = registration.options;
|
|
361
|
+
infos.push({
|
|
362
|
+
keys: registration.keys,
|
|
363
|
+
enabled: isEnabled(registration, getLayers),
|
|
364
|
+
...settings.id !== void 0 ? { id: settings.id } : {},
|
|
365
|
+
...settings.description !== void 0 ? { description: settings.description } : {},
|
|
366
|
+
...settings.scope !== void 0 ? { scope: settings.scope } : {}
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
return infos;
|
|
370
|
+
};
|
|
371
|
+
const keyshortcutsFor = (id) => {
|
|
372
|
+
for (const registration of registrations) {
|
|
373
|
+
if (registration.removed || registration.options.id !== id) continue;
|
|
374
|
+
return ariaShortcut(registration.keys, platform);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
const dispose = () => {
|
|
378
|
+
if (disposed) return;
|
|
379
|
+
disposed = true;
|
|
380
|
+
target?.removeEventListener("keydown", onKeyDown);
|
|
381
|
+
registrations.length = 0;
|
|
382
|
+
activeScopes.clear();
|
|
383
|
+
};
|
|
384
|
+
return {
|
|
385
|
+
register,
|
|
386
|
+
setScope,
|
|
387
|
+
list,
|
|
388
|
+
handle,
|
|
389
|
+
dispose,
|
|
390
|
+
keyshortcutsFor
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
export { ariaShortcut, createShortcuts, formatShortcut, matchesShortcut };
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bevelo/shortcuts",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Keyboard shortcuts: one listener, named scopes, layer awareness, aria-keyshortcuts.",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@bevelo/core": "0.1.0"
|
|
18
|
+
},
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"files": [
|
|
21
|
+
"dist"
|
|
22
|
+
],
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"homepage": "https://github.com/bevelo/bevelo#readme",
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/bevelo/bevelo/issues"
|
|
27
|
+
},
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "https://github.com/bevelo/bevelo.git",
|
|
31
|
+
"directory": "packages/shortcuts"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "vp pack",
|
|
38
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
39
|
+
"test": "vp test run"
|
|
40
|
+
}
|
|
6
41
|
}
|