@alwatr/keyboard-shortcut 9.26.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 ADDED
@@ -0,0 +1,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ Permanent-link, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # @alwatr/keyboard-shortcut
2
+
3
+ **Global keyboard-to-action bridge for Alwatr Flux.**
4
+
5
+ Listens for `keydown` events on `document`, normalizes the pressed key combination, and dispatches a corresponding Flux action. Designed to allow modules to react to keyboard shortcuts declaratively using `onAction()` without coupling to raw DOM events.
6
+
7
+ ---
8
+
9
+ ## Why `@alwatr/keyboard-shortcut`?
10
+
11
+ In structured, reactive web applications, UI elements and user interactions should flow unidirectionally. Hardcoding `addEventListener('keydown')` within multiple UI components leads to fragmented shortcut management, duplicate event listeners, and difficulty in testing or overriding shortcuts.
12
+
13
+ `@alwatr/keyboard-shortcut` unifies all keyboard interactions by:
14
+
15
+ - Listening once globally on the document.
16
+ - Normalizing the keyboard combo (e.g. modifier keys ordered deterministically as `ctrl → shift → alt`).
17
+ - Dispatching standard typed Flux actions, which components can cleanly subscribe to.
18
+
19
+ ---
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ bun add @alwatr/keyboard-shortcut
25
+ # or
26
+ npm i @alwatr/keyboard-shortcut
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Quick Start
32
+
33
+ ### 1. Initialize the shortcut listener
34
+
35
+ Call `keyboardShortcutService.setup()` at application bootstrap:
36
+
37
+ ```ts
38
+ import {keyboardShortcutService} from '@alwatr/keyboard-shortcut';
39
+
40
+ keyboardShortcutService.setup();
41
+ ```
42
+
43
+ ### 2. Subscribe to shortcuts
44
+
45
+ Subscribe to specific key action types using `onAction` from `@alwatr/action` or `@alwatr/flux`:
46
+
47
+ ```ts
48
+ import {onAction} from '@alwatr/flux';
49
+
50
+ // Close a drawer when Escape is pressed
51
+ onAction('key_escape', () => {
52
+ closeDrawer();
53
+ });
54
+
55
+ // Save changes when Ctrl+S is pressed
56
+ onAction('key_ctrl_s', () => {
57
+ saveChanges();
58
+ });
59
+ ```
60
+
61
+ ### 3. Registering new shortcuts (Type Safety)
62
+
63
+ Extend the global `ActionRecord` interface via declaration merging in your codebase to restrict and autocomplete shortcut actions:
64
+
65
+ ```ts
66
+ declare module '@alwatr/action' {
67
+ interface ActionRecord {
68
+ 'key_escape': void;
69
+ 'key_ctrl_s': void;
70
+ 'key_ctrl_space': void;
71
+ 'key_ctrl_shift_u': void;
72
+ }
73
+ }
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Action Naming Convention
79
+
80
+ Action types are prefixed with `key_` followed by the lowercase combo joined by `_`:
81
+
82
+ | Keys pressed | Action type |
83
+ | ---------------------- | ---------------------- |
84
+ | Escape | `key_escape` |
85
+ | Space | `key_space` |
86
+ | Ctrl + S | `key_ctrl_s` |
87
+ | Ctrl + Space | `key_ctrl_space` |
88
+ | Shift + Ctrl + U | `key_ctrl_shift_u` |
89
+ | Alt + Enter | `key_alt_enter` |
90
+ | Ctrl + Shift + Alt + U | `key_ctrl_shift_alt_u` |
91
+
92
+ Modifier order is always normalized to: **ctrl → shift → alt** (note: Meta/Command key is treated as Ctrl on Apple devices).
93
+
94
+ ### Text Fields Protection
95
+
96
+ To prevent intercepting normal user typing, bare shortcut actions (without modifiers, e.g. letters, numbers, Escape, Enter) are automatically ignored when the focus is inside editable elements:
97
+
98
+ - `<input>`
99
+ - `<textarea>`
100
+ - `<select>`
101
+ - Any element with `contenteditable` attribute
102
+
103
+ Shortcut combos that **include** a modifier (like `ctrlKey`, `metaKey`, or `altKey`) will still fire inside editable inputs normally (e.g. `Ctrl+S` will still trigger a save action).
104
+
105
+ ---
106
+
107
+ ## API Reference
108
+
109
+ ### `keyboardShortcutService`
110
+
111
+ The singleton instance of `KeyboardShortcutService` used to manage the lifecycle of keyboard shortcut dispatching.
112
+
113
+ #### `.setup()`
114
+
115
+ Registers the global `keydown` event listener on `document` with `capture: true`. Safe to call multiple times (idempotent).
116
+
117
+ ```ts
118
+ keyboardShortcutService.setup();
119
+ ```
120
+
121
+ #### `.teardown()`
122
+
123
+ Removes the global `keydown` event listener from the document. Useful for unit tests or micro-frontend unmounting.
124
+
125
+ ```ts
126
+ keyboardShortcutService.teardown();
127
+ ```
128
+
129
+ ---
130
+
131
+ ## 🌊 Part of Alwatr Flux
132
+
133
+ `@alwatr/keyboard-shortcut` is part of the [Alwatr Flux](https://github.com/Alwatr/alwatr/tree/next/pkg/flux) architecture — a complete Unidirectional Data Flow system for building scalable Progressive Web Applications.
134
+
135
+ In the Flux architecture, it bridges physical keyboard events to the global action dispatcher, enabling clean separation of concerns between DOM event handling and business logic.
136
+
137
+ ```typescript
138
+ // Use @alwatr/flux for the complete architecture
139
+ import {keyboardShortcutService, onAction} from '@alwatr/flux';
140
+
141
+ // Or use standalone
142
+ import {keyboardShortcutService} from '@alwatr/keyboard-shortcut';
143
+ import {onAction} from '@alwatr/action';
144
+ ```
145
+
146
+ → [View the complete Flux documentation](https://github.com/Alwatr/alwatr/tree/next/pkg/flux)
147
+
148
+ ---
149
+
150
+ ## Contributing
151
+
152
+ Contributions are welcome! Please read our [contribution guidelines](https://github.com/Alwatr/.github/blob/next/CONTRIBUTING.md) before submitting a pull request.
153
+
154
+ ## License
155
+
156
+ MPL-2.0 — see [LICENSE](./LICENSE).
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Global keyboard-to-action bridge for Alwatr Flux.
3
+ *
4
+ * Listens for `keydown` on `document` and dispatches a flux action whose
5
+ * name is derived from the pressed key combination. This lets any module
6
+ * react to keyboard shortcuts declaratively via `onAction()` without
7
+ * coupling to raw DOM events.
8
+ *
9
+ * ## Action naming convention
10
+ *
11
+ * The action type follows the pattern `key_<combo>` where `<combo>` is
12
+ * built from active modifiers + key name, all **lowercase**, joined by `_`:
13
+ *
14
+ * | Keys pressed | Action type |
15
+ * | --------------------- | ------------------------ |
16
+ * | Escape | `key_escape` |
17
+ * | Space | `key_space` |
18
+ * | Ctrl + S | `key_ctrl_s` |
19
+ * | Shift + Ctrl + U | `key_ctrl_shift_u` |
20
+ * | Alt + Enter | `key_alt_enter` |
21
+ *
22
+ * Modifier order is always **ctrl → shift → alt** for consistency.
23
+ *
24
+ * ## Usage
25
+ *
26
+ * ```ts
27
+ * import {keyboardShortcutService, onAction} from '@alwatr/flux';
28
+ *
29
+ * // Initialize keyboard shortcut listener
30
+ * keyboardShortcutService.setup();
31
+ *
32
+ * // Close drawer on Escape
33
+ * onAction('key_escape', () => closeDrawer());
34
+ *
35
+ * // Save on Ctrl+S
36
+ * onAction('key_ctrl_s', () => save());
37
+ *
38
+ * // Cleanup when no longer needed
39
+ * keyboardShortcutService.teardown();
40
+ * ```
41
+ */
42
+ /**
43
+ * Service to manage global keyboard shortcut mapping and dispatching.
44
+ *
45
+ * Implements global `keydown` event listener on `document` in the capture phase,
46
+ * normalizes modifier combinations, and dispatches equivalent flux actions.
47
+ */
48
+ export declare class KeyboardShortcutService {
49
+ protected readonly logger_: import("@alwatr/logger").AlwatrLogger;
50
+ private readonly modifierKeys__;
51
+ private readonly editableTags__;
52
+ private hasRegistered__;
53
+ constructor();
54
+ /**
55
+ * Registers global event listener for `keydown` on `document`.
56
+ * Safe to call multiple times (idempotent).
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * keyboardShortcutService.setup();
61
+ * ```
62
+ */
63
+ setup(): void;
64
+ /**
65
+ * Removes global event listener for `keydown` on `document`.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * keyboardShortcutService.teardown();
70
+ * ```
71
+ */
72
+ teardown(): void;
73
+ /**
74
+ * Global keydown event listener handler.
75
+ */
76
+ private handleKeyDown__;
77
+ /**
78
+ * Whether the event target is an editable element (input, textarea, select,
79
+ * or any element with `contenteditable`).
80
+ */
81
+ private isEditable__;
82
+ /**
83
+ * Whether the event carries at least one non-shift modifier (ctrl/meta/alt).
84
+ *
85
+ * Shift alone is not considered a modifier shortcut because Shift+Letter
86
+ * is normal typing (uppercase). Only ctrl/meta/alt signal an intentional
87
+ * keyboard shortcut.
88
+ */
89
+ private hasModifier__;
90
+ /**
91
+ * Builds a normalized, deterministic combo string from a KeyboardEvent.
92
+ *
93
+ * Modifier order is fixed (ctrl → shift → alt) so the same
94
+ * physical combination always produces the same string regardless of
95
+ * the order the user pressed the modifier keys.
96
+ */
97
+ private buildCombo__;
98
+ }
99
+ /**
100
+ * Singleton instance of KeyboardShortcutService.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * import {keyboardShortcutService} from '@alwatr/keyboard-shortcut';
105
+ *
106
+ * keyboardShortcutService.setup();
107
+ * ```
108
+ */
109
+ export declare const keyboardShortcutService: KeyboardShortcutService;
110
+ declare module '@alwatr/action' {
111
+ interface ActionRecord {
112
+ [key: `key_${string}`]: void;
113
+ }
114
+ }
115
+ //# sourceMappingURL=keyboard-shortcut.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyboard-shortcut.d.ts","sourceRoot":"","sources":["../src/keyboard-shortcut.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAKH;;;;;GAKG;AACH,qBAAa,uBAAuB;IAClC,SAAS,CAAC,QAAQ,CAAC,OAAO,wCAA6C;IAGvE,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAgD;IAG/E,OAAO,CAAC,QAAQ,CAAC,cAAc,CAA4C;IAE3E,OAAO,CAAC,eAAe,CAAS;;IAOhC;;;;;;;;OAQG;IACH,KAAK,IAAI,IAAI;IAOb;;;;;;;OAOG;IACH,QAAQ,IAAI,IAAI;IAOhB;;OAEG;IACH,OAAO,CAAC,eAAe;IAiBvB;;;OAGG;IACH,OAAO,CAAC,YAAY;IAMpB;;;;;;OAMG;IACH,OAAO,CAAC,aAAa;IAIrB;;;;;;OAMG;IACH,OAAO,CAAC,YAAY;CAYrB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,uBAAuB,yBAAgC,CAAC;AAIrE,OAAO,QAAQ,gBAAgB,CAAC;IAC9B,UAAU,YAAY;QACpB,CAAC,GAAG,EAAE,OAAO,MAAM,EAAE,GAAG,IAAI,CAAC;KAC9B;CACF"}
package/dist/main.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @alwatr/keyboard-shortcut — Global keyboard-to-action bridge.
3
+ *
4
+ * Listens for `keydown` on `document` and dispatches a flux action whose
5
+ * name is derived from the pressed key combination. This lets any module
6
+ * react to keyboard shortcuts declaratively via `onAction()` without
7
+ * coupling to raw DOM events.
8
+ *
9
+ * ## Usage
10
+ *
11
+ * ```ts
12
+ * import {keyboardShortcutService, onAction} from '@alwatr/keyboard-shortcut';
13
+ *
14
+ * // Initialize keyboard shortcut listener
15
+ * keyboardShortcutService.setup();
16
+ *
17
+ * // Close drawer on Escape
18
+ * onAction('key_escape', () => closeDrawer());
19
+ * ```
20
+ */
21
+ export * from './keyboard-shortcut.js';
22
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,cAAc,wBAAwB,CAAC"}
package/dist/main.js ADDED
@@ -0,0 +1,5 @@
1
+ /* 📦 @alwatr/keyboard-shortcut v9.26.0 */
2
+ import{dispatchAction as a}from"@alwatr/action";import{createLogger as r}from"@alwatr/logger";class i{logger_=r("keyboard-shortcut-service");modifierKeys__=new Set(["Control","Shift","Alt","Meta"]);editableTags__=new Set(["INPUT","TEXTAREA","SELECT"]);hasRegistered__=!1;constructor(){this.logger_.logMethod?.("constructor"),this.handleKeyDown__=this.handleKeyDown__.bind(this)}setup(){if(this.logger_.logMethod?.("setup"),this.hasRegistered__)return;this.hasRegistered__=!0,document.addEventListener("keydown",this.handleKeyDown__,{capture:!0})}teardown(){if(this.logger_.logMethod?.("teardown"),!this.hasRegistered__)return;this.hasRegistered__=!1,document.removeEventListener("keydown",this.handleKeyDown__,{capture:!0})}handleKeyDown__(o){if(this.modifierKeys__.has(o.key))return;if(this.isEditable__(o)&&!this.hasModifier__(o))return;let s=this.buildCombo__(o);this.logger_.logMethodArgs?.("keyboard_handler",{combo:s}),a({type:`key_${s}`})}isEditable__(o){let s=o.target;if(!(s instanceof HTMLElement))return!1;return this.editableTags__.has(s.tagName)||s.isContentEditable}hasModifier__(o){return o.ctrlKey||o.metaKey||o.altKey}buildCombo__(o){let s=[];if(o.ctrlKey||o.metaKey)s.push("ctrl");if(o.shiftKey)s.push("shift");if(o.altKey)s.push("alt");let d=o.key===" "?"space":o.key.toLowerCase();return s.push(d),s.join("_")}}var u=new i;export{u as keyboardShortcutService,i as KeyboardShortcutService};
3
+
4
+ //# debugId=1EF3F6B2FDE9074464756E2164756E21
5
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/keyboard-shortcut.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Global keyboard-to-action bridge for Alwatr Flux.\n *\n * Listens for `keydown` on `document` and dispatches a flux action whose\n * name is derived from the pressed key combination. This lets any module\n * react to keyboard shortcuts declaratively via `onAction()` without\n * coupling to raw DOM events.\n *\n * ## Action naming convention\n *\n * The action type follows the pattern `key_<combo>` where `<combo>` is\n * built from active modifiers + key name, all **lowercase**, joined by `_`:\n *\n * | Keys pressed | Action type |\n * | --------------------- | ------------------------ |\n * | Escape | `key_escape` |\n * | Space | `key_space` |\n * | Ctrl + S | `key_ctrl_s` |\n * | Shift + Ctrl + U | `key_ctrl_shift_u` |\n * | Alt + Enter | `key_alt_enter` |\n *\n * Modifier order is always **ctrl → shift → alt** for consistency.\n *\n * ## Usage\n *\n * ```ts\n * import {keyboardShortcutService, onAction} from '@alwatr/flux';\n *\n * // Initialize keyboard shortcut listener\n * keyboardShortcutService.setup();\n *\n * // Close drawer on Escape\n * onAction('key_escape', () => closeDrawer());\n *\n * // Save on Ctrl+S\n * onAction('key_ctrl_s', () => save());\n *\n * // Cleanup when no longer needed\n * keyboardShortcutService.teardown();\n * ```\n */\n\nimport {dispatchAction} from '@alwatr/action';\nimport {createLogger} from '@alwatr/logger';\n\n/**\n * Service to manage global keyboard shortcut mapping and dispatching.\n *\n * Implements global `keydown` event listener on `document` in the capture phase,\n * normalizes modifier combinations, and dispatches equivalent flux actions.\n */\nexport class KeyboardShortcutService {\n protected readonly logger_ = createLogger('keyboard-shortcut-service');\n\n // Modifier keys that should not produce standalone actions.\n private readonly modifierKeys__ = new Set(['Control', 'Shift', 'Alt', 'Meta']);\n\n // Editable element tags where bare key presses (no modifier) are user input, not shortcuts.\n private readonly editableTags__ = new Set(['INPUT', 'TEXTAREA', 'SELECT']);\n\n private hasRegistered__ = false;\n\n constructor() {\n this.logger_.logMethod?.('constructor');\n this.handleKeyDown__ = this.handleKeyDown__.bind(this);\n }\n\n /**\n * Registers global event listener for `keydown` on `document`.\n * Safe to call multiple times (idempotent).\n *\n * @example\n * ```ts\n * keyboardShortcutService.setup();\n * ```\n */\n setup(): void {\n this.logger_.logMethod?.('setup');\n if (this.hasRegistered__) return;\n this.hasRegistered__ = true;\n document.addEventListener('keydown', this.handleKeyDown__, {capture: true});\n }\n\n /**\n * Removes global event listener for `keydown` on `document`.\n *\n * @example\n * ```ts\n * keyboardShortcutService.teardown();\n * ```\n */\n teardown(): void {\n this.logger_.logMethod?.('teardown');\n if (!this.hasRegistered__) return;\n this.hasRegistered__ = false;\n document.removeEventListener('keydown', this.handleKeyDown__, {capture: true});\n }\n\n /**\n * Global keydown event listener handler.\n */\n private handleKeyDown__(event: KeyboardEvent): void {\n // Ignore standalone modifier presses — they are not actionable shortcuts.\n if (this.modifierKeys__.has(event.key)) return;\n\n // When focus is inside an editable element, only dispatch shortcut actions\n // that include a real modifier (ctrl/meta/alt). Bare key presses like\n // letters, digits, Escape, Enter, etc. are normal user input and must\n // not be intercepted.\n if (this.isEditable__(event) && !this.hasModifier__(event)) return;\n\n const combo = this.buildCombo__(event);\n\n this.logger_.logMethodArgs?.('keyboard_handler', {combo});\n\n dispatchAction({type: `key_${combo}`});\n }\n\n /**\n * Whether the event target is an editable element (input, textarea, select,\n * or any element with `contenteditable`).\n */\n private isEditable__(event: KeyboardEvent): boolean {\n const target = event.target;\n if (!(target instanceof HTMLElement)) return false;\n return this.editableTags__.has(target.tagName) || target.isContentEditable;\n }\n\n /**\n * Whether the event carries at least one non-shift modifier (ctrl/meta/alt).\n *\n * Shift alone is not considered a modifier shortcut because Shift+Letter\n * is normal typing (uppercase). Only ctrl/meta/alt signal an intentional\n * keyboard shortcut.\n */\n private hasModifier__(event: KeyboardEvent): boolean {\n return event.ctrlKey || event.metaKey || event.altKey;\n }\n\n /**\n * Builds a normalized, deterministic combo string from a KeyboardEvent.\n *\n * Modifier order is fixed (ctrl → shift → alt) so the same\n * physical combination always produces the same string regardless of\n * the order the user pressed the modifier keys.\n */\n private buildCombo__(event: KeyboardEvent): string {\n const parts: string[] = [];\n\n if (event.ctrlKey || event.metaKey) parts.push('ctrl');\n if (event.shiftKey) parts.push('shift');\n if (event.altKey) parts.push('alt');\n\n const key = event.key === ' ' ? 'space' : event.key.toLowerCase();\n parts.push(key);\n\n return parts.join('_');\n }\n}\n\n/**\n * Singleton instance of KeyboardShortcutService.\n *\n * @example\n * ```ts\n * import {keyboardShortcutService} from '@alwatr/keyboard-shortcut';\n *\n * keyboardShortcutService.setup();\n * ```\n */\nexport const keyboardShortcutService = new KeyboardShortcutService();\n\n// Type augmentation — register the `key_*` pattern so any module can\n// declare specific shortcuts via ActionRecord merging.\ndeclare module '@alwatr/action' {\n interface ActionRecord {\n [key: `key_${string}`]: void;\n }\n}\n"
6
+ ],
7
+ "mappings": ";AA0CA,yBAAQ,uBACR,uBAAQ,uBAQD,MAAM,CAAwB,CAChB,QAAU,EAAa,2BAA2B,EAGpD,eAAiB,IAAI,IAAI,CAAC,UAAW,QAAS,MAAO,MAAM,CAAC,EAG5D,eAAiB,IAAI,IAAI,CAAC,QAAS,WAAY,QAAQ,CAAC,EAEjE,gBAAkB,GAE1B,WAAW,EAAG,CACZ,KAAK,QAAQ,YAAY,aAAa,EACtC,KAAK,gBAAkB,KAAK,gBAAgB,KAAK,IAAI,EAYvD,KAAK,EAAS,CAEZ,GADA,KAAK,QAAQ,YAAY,OAAO,EAC5B,KAAK,gBAAiB,OAC1B,KAAK,gBAAkB,GACvB,SAAS,iBAAiB,UAAW,KAAK,gBAAiB,CAAC,QAAS,EAAI,CAAC,EAW5E,QAAQ,EAAS,CAEf,GADA,KAAK,QAAQ,YAAY,UAAU,EAC/B,CAAC,KAAK,gBAAiB,OAC3B,KAAK,gBAAkB,GACvB,SAAS,oBAAoB,UAAW,KAAK,gBAAiB,CAAC,QAAS,EAAI,CAAC,EAMvE,eAAe,CAAC,EAA4B,CAElD,GAAI,KAAK,eAAe,IAAI,EAAM,GAAG,EAAG,OAMxC,GAAI,KAAK,aAAa,CAAK,GAAK,CAAC,KAAK,cAAc,CAAK,EAAG,OAE5D,IAAM,EAAQ,KAAK,aAAa,CAAK,EAErC,KAAK,QAAQ,gBAAgB,mBAAoB,CAAC,OAAK,CAAC,EAExD,EAAe,CAAC,KAAM,OAAO,GAAO,CAAC,EAO/B,YAAY,CAAC,EAA+B,CAClD,IAAM,EAAS,EAAM,OACrB,GAAI,EAAE,aAAkB,aAAc,MAAO,GAC7C,OAAO,KAAK,eAAe,IAAI,EAAO,OAAO,GAAK,EAAO,kBAUnD,aAAa,CAAC,EAA+B,CACnD,OAAO,EAAM,SAAW,EAAM,SAAW,EAAM,OAUzC,YAAY,CAAC,EAA8B,CACjD,IAAM,EAAkB,CAAC,EAEzB,GAAI,EAAM,SAAW,EAAM,QAAS,EAAM,KAAK,MAAM,EACrD,GAAI,EAAM,SAAU,EAAM,KAAK,OAAO,EACtC,GAAI,EAAM,OAAQ,EAAM,KAAK,KAAK,EAElC,IAAM,EAAM,EAAM,MAAQ,IAAM,QAAU,EAAM,IAAI,YAAY,EAGhE,OAFA,EAAM,KAAK,CAAG,EAEP,EAAM,KAAK,GAAG,EAEzB,CAYO,IAAM,EAA0B,IAAI",
8
+ "debugId": "1EF3F6B2FDE9074464756E2164756E21",
9
+ "names": []
10
+ }
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@alwatr/keyboard-shortcut",
3
+ "version": "9.26.0",
4
+ "description": "Global keyboard-to-action bridge for Alwatr Flux. Listens for keydown and dispatches Flux actions based on normalized key combos.",
5
+ "license": "MPL-2.0",
6
+ "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
7
+ "type": "module",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Alwatr/alwatr",
11
+ "directory": "pkg/nanolib/keyboard-shortcut"
12
+ },
13
+ "homepage": "https://github.com/Alwatr/alwatr/tree/next/pkg/nanolib/keyboard-shortcut#readme",
14
+ "bugs": "https://github.com/Alwatr/alwatr/issues",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/main.d.ts",
18
+ "import": "./dist/main.js",
19
+ "default": "./dist/main.js"
20
+ }
21
+ },
22
+ "sideEffects": false,
23
+ "dependencies": {
24
+ "@alwatr/action": "9.26.0",
25
+ "@alwatr/logger": "9.25.0"
26
+ },
27
+ "devDependencies": {
28
+ "@alwatr/nano-build": "9.25.0",
29
+ "@alwatr/standard": "9.16.0",
30
+ "@alwatr/type-helper": "9.14.0",
31
+ "@happy-dom/global-registrator": "^20.9.0",
32
+ "typescript": "^6.0.3"
33
+ },
34
+ "scripts": {
35
+ "b": "bun run build",
36
+ "build": "bun run build:ts && bun run build:es",
37
+ "build:es": "nano-build --preset=module-web src/main.ts",
38
+ "build:ts": "tsc --build",
39
+ "cl": "bun run clean",
40
+ "clean": "rm -rfv dist *.tsbuildinfo",
41
+ "format": "prettier --write \"src/**/*.ts\"",
42
+ "lint": "eslint src/ --ext .ts",
43
+ "t": "bun run test",
44
+ "test": "ALWATR_DEBUG=0 bun test",
45
+ "w": "bun run watch",
46
+ "watch": "bun run watch:ts & bun run watch:es",
47
+ "watch:es": "bun run build:es --watch",
48
+ "watch:ts": "bun run build:ts --watch --preserveWatchOutput"
49
+ },
50
+ "files": [
51
+ "dist",
52
+ "src/**/*.ts",
53
+ "!src/**/*.test.ts",
54
+ "README.md",
55
+ "LICENSE"
56
+ ],
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "keywords": [
61
+ "alwatr",
62
+ "browser",
63
+ "esm",
64
+ "javascript",
65
+ "module",
66
+ "nanolib",
67
+ "keyboard",
68
+ "shortcut",
69
+ "action",
70
+ "flux",
71
+ "typescript"
72
+ ],
73
+ "gitHead": "ef62969b649929413c640e69d241f4e99d6062e8"
74
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Global keyboard-to-action bridge for Alwatr Flux.
3
+ *
4
+ * Listens for `keydown` on `document` and dispatches a flux action whose
5
+ * name is derived from the pressed key combination. This lets any module
6
+ * react to keyboard shortcuts declaratively via `onAction()` without
7
+ * coupling to raw DOM events.
8
+ *
9
+ * ## Action naming convention
10
+ *
11
+ * The action type follows the pattern `key_<combo>` where `<combo>` is
12
+ * built from active modifiers + key name, all **lowercase**, joined by `_`:
13
+ *
14
+ * | Keys pressed | Action type |
15
+ * | --------------------- | ------------------------ |
16
+ * | Escape | `key_escape` |
17
+ * | Space | `key_space` |
18
+ * | Ctrl + S | `key_ctrl_s` |
19
+ * | Shift + Ctrl + U | `key_ctrl_shift_u` |
20
+ * | Alt + Enter | `key_alt_enter` |
21
+ *
22
+ * Modifier order is always **ctrl → shift → alt** for consistency.
23
+ *
24
+ * ## Usage
25
+ *
26
+ * ```ts
27
+ * import {keyboardShortcutService, onAction} from '@alwatr/flux';
28
+ *
29
+ * // Initialize keyboard shortcut listener
30
+ * keyboardShortcutService.setup();
31
+ *
32
+ * // Close drawer on Escape
33
+ * onAction('key_escape', () => closeDrawer());
34
+ *
35
+ * // Save on Ctrl+S
36
+ * onAction('key_ctrl_s', () => save());
37
+ *
38
+ * // Cleanup when no longer needed
39
+ * keyboardShortcutService.teardown();
40
+ * ```
41
+ */
42
+
43
+ import {dispatchAction} from '@alwatr/action';
44
+ import {createLogger} from '@alwatr/logger';
45
+
46
+ /**
47
+ * Service to manage global keyboard shortcut mapping and dispatching.
48
+ *
49
+ * Implements global `keydown` event listener on `document` in the capture phase,
50
+ * normalizes modifier combinations, and dispatches equivalent flux actions.
51
+ */
52
+ export class KeyboardShortcutService {
53
+ protected readonly logger_ = createLogger('keyboard-shortcut-service');
54
+
55
+ // Modifier keys that should not produce standalone actions.
56
+ private readonly modifierKeys__ = new Set(['Control', 'Shift', 'Alt', 'Meta']);
57
+
58
+ // Editable element tags where bare key presses (no modifier) are user input, not shortcuts.
59
+ private readonly editableTags__ = new Set(['INPUT', 'TEXTAREA', 'SELECT']);
60
+
61
+ private hasRegistered__ = false;
62
+
63
+ constructor() {
64
+ this.logger_.logMethod?.('constructor');
65
+ this.handleKeyDown__ = this.handleKeyDown__.bind(this);
66
+ }
67
+
68
+ /**
69
+ * Registers global event listener for `keydown` on `document`.
70
+ * Safe to call multiple times (idempotent).
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * keyboardShortcutService.setup();
75
+ * ```
76
+ */
77
+ setup(): void {
78
+ this.logger_.logMethod?.('setup');
79
+ if (this.hasRegistered__) return;
80
+ this.hasRegistered__ = true;
81
+ document.addEventListener('keydown', this.handleKeyDown__, {capture: true});
82
+ }
83
+
84
+ /**
85
+ * Removes global event listener for `keydown` on `document`.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * keyboardShortcutService.teardown();
90
+ * ```
91
+ */
92
+ teardown(): void {
93
+ this.logger_.logMethod?.('teardown');
94
+ if (!this.hasRegistered__) return;
95
+ this.hasRegistered__ = false;
96
+ document.removeEventListener('keydown', this.handleKeyDown__, {capture: true});
97
+ }
98
+
99
+ /**
100
+ * Global keydown event listener handler.
101
+ */
102
+ private handleKeyDown__(event: KeyboardEvent): void {
103
+ // Ignore standalone modifier presses — they are not actionable shortcuts.
104
+ if (this.modifierKeys__.has(event.key)) return;
105
+
106
+ // When focus is inside an editable element, only dispatch shortcut actions
107
+ // that include a real modifier (ctrl/meta/alt). Bare key presses like
108
+ // letters, digits, Escape, Enter, etc. are normal user input and must
109
+ // not be intercepted.
110
+ if (this.isEditable__(event) && !this.hasModifier__(event)) return;
111
+
112
+ const combo = this.buildCombo__(event);
113
+
114
+ this.logger_.logMethodArgs?.('keyboard_handler', {combo});
115
+
116
+ dispatchAction({type: `key_${combo}`});
117
+ }
118
+
119
+ /**
120
+ * Whether the event target is an editable element (input, textarea, select,
121
+ * or any element with `contenteditable`).
122
+ */
123
+ private isEditable__(event: KeyboardEvent): boolean {
124
+ const target = event.target;
125
+ if (!(target instanceof HTMLElement)) return false;
126
+ return this.editableTags__.has(target.tagName) || target.isContentEditable;
127
+ }
128
+
129
+ /**
130
+ * Whether the event carries at least one non-shift modifier (ctrl/meta/alt).
131
+ *
132
+ * Shift alone is not considered a modifier shortcut because Shift+Letter
133
+ * is normal typing (uppercase). Only ctrl/meta/alt signal an intentional
134
+ * keyboard shortcut.
135
+ */
136
+ private hasModifier__(event: KeyboardEvent): boolean {
137
+ return event.ctrlKey || event.metaKey || event.altKey;
138
+ }
139
+
140
+ /**
141
+ * Builds a normalized, deterministic combo string from a KeyboardEvent.
142
+ *
143
+ * Modifier order is fixed (ctrl → shift → alt) so the same
144
+ * physical combination always produces the same string regardless of
145
+ * the order the user pressed the modifier keys.
146
+ */
147
+ private buildCombo__(event: KeyboardEvent): string {
148
+ const parts: string[] = [];
149
+
150
+ if (event.ctrlKey || event.metaKey) parts.push('ctrl');
151
+ if (event.shiftKey) parts.push('shift');
152
+ if (event.altKey) parts.push('alt');
153
+
154
+ const key = event.key === ' ' ? 'space' : event.key.toLowerCase();
155
+ parts.push(key);
156
+
157
+ return parts.join('_');
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Singleton instance of KeyboardShortcutService.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * import {keyboardShortcutService} from '@alwatr/keyboard-shortcut';
167
+ *
168
+ * keyboardShortcutService.setup();
169
+ * ```
170
+ */
171
+ export const keyboardShortcutService = new KeyboardShortcutService();
172
+
173
+ // Type augmentation — register the `key_*` pattern so any module can
174
+ // declare specific shortcuts via ActionRecord merging.
175
+ declare module '@alwatr/action' {
176
+ interface ActionRecord {
177
+ [key: `key_${string}`]: void;
178
+ }
179
+ }
package/src/main.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @alwatr/keyboard-shortcut — Global keyboard-to-action bridge.
3
+ *
4
+ * Listens for `keydown` on `document` and dispatches a flux action whose
5
+ * name is derived from the pressed key combination. This lets any module
6
+ * react to keyboard shortcuts declaratively via `onAction()` without
7
+ * coupling to raw DOM events.
8
+ *
9
+ * ## Usage
10
+ *
11
+ * ```ts
12
+ * import {keyboardShortcutService, onAction} from '@alwatr/keyboard-shortcut';
13
+ *
14
+ * // Initialize keyboard shortcut listener
15
+ * keyboardShortcutService.setup();
16
+ *
17
+ * // Close drawer on Escape
18
+ * onAction('key_escape', () => closeDrawer());
19
+ * ```
20
+ */
21
+
22
+ export * from './keyboard-shortcut.js';