@asyra/input-system 0.2.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.
Files changed (49) hide show
  1. package/.turbo/turbo-test$colon$ci.log +132 -0
  2. package/.turbo/turbo-test$colon$local.log +48 -0
  3. package/.turbo/turbo-test.log +0 -0
  4. package/README.md +89 -0
  5. package/coverage/base.css +224 -0
  6. package/coverage/block-navigation.js +87 -0
  7. package/coverage/clover.xml +573 -0
  8. package/coverage/constants.ts.html +94 -0
  9. package/coverage/coverage-final.json +8963 -0
  10. package/coverage/event-mappings.ts.html +370 -0
  11. package/coverage/favicon.png +0 -0
  12. package/coverage/index.html +206 -0
  13. package/coverage/index.ts.html +106 -0
  14. package/coverage/input-system.ts.html +1216 -0
  15. package/coverage/keymap.ts.html +616 -0
  16. package/coverage/matcher.ts.html +187 -0
  17. package/coverage/prettify.css +1 -0
  18. package/coverage/prettify.js +2 -0
  19. package/coverage/sort-arrow-sprite.png +0 -0
  20. package/coverage/sorter.js +196 -0
  21. package/coverage/subscribe.ts.html +109 -0
  22. package/dist/__tests__/input-system.test.d.ts +1 -0
  23. package/dist/__tests__/input-system.test.js +279 -0
  24. package/dist/constants.d.ts +2 -0
  25. package/dist/constants.js +2 -0
  26. package/dist/event-mappings.d.ts +8 -0
  27. package/dist/event-mappings.js +78 -0
  28. package/dist/index.d.ts +3 -0
  29. package/dist/index.js +5 -0
  30. package/dist/input-system.d.ts +36 -0
  31. package/dist/input-system.js +276 -0
  32. package/dist/keymap.d.ts +13 -0
  33. package/dist/keymap.js +150 -0
  34. package/dist/matcher.d.ts +16 -0
  35. package/dist/matcher.js +32 -0
  36. package/dist/subscribe.d.ts +1 -0
  37. package/dist/subscribe.js +7 -0
  38. package/package.json +28 -0
  39. package/src/__tests__/input-system.test.ts +398 -0
  40. package/src/constants.ts +3 -0
  41. package/src/event-mappings.ts +95 -0
  42. package/src/index.ts +7 -0
  43. package/src/input-system.ts +377 -0
  44. package/src/keymap.ts +177 -0
  45. package/src/matcher.ts +34 -0
  46. package/src/subscribe.ts +8 -0
  47. package/test-setup.ts +6 -0
  48. package/tsconfig.json +22 -0
  49. package/vitest.config.ts +8 -0
@@ -0,0 +1,276 @@
1
+ import { MouseButton, SpecialEvent, InputType, arrEqual, DefaultPointerEventData } from '@asyra/utils';
2
+ import { InputFieldsList } from '@asyra/utils';
3
+ import { CLICK_THRESHOLD, CLEAR_KEY_TIME } from './constants';
4
+ import { InputEventMappings } from './event-mappings';
5
+ import keymap from './keymap';
6
+ const WHEEL_EVENT_OPTIONS = { passive: false };
7
+ const getMouseButton = (button) => {
8
+ switch (button) {
9
+ case 0:
10
+ return MouseButton.LEFT;
11
+ case 1:
12
+ return MouseButton.MIDDLE;
13
+ case 2:
14
+ return MouseButton.RIGHT;
15
+ default:
16
+ return MouseButton.NONE;
17
+ }
18
+ };
19
+ class InputSystem {
20
+ _previousWatchedElement;
21
+ combinations = {};
22
+ keyMap;
23
+ activeKeys;
24
+ listeners;
25
+ timers;
26
+ _startPos;
27
+ constructor() {
28
+ this._previousWatchedElement = window;
29
+ this.keyMap = keymap;
30
+ this.activeKeys = new Set();
31
+ this.listeners = new Map();
32
+ this.timers = new Map();
33
+ this._startPos = null;
34
+ this.setupListeners();
35
+ }
36
+ setupListeners() {
37
+ window.addEventListener('keydown', this.handleKeyDown);
38
+ window.addEventListener('keyup', this.handleKeyUp);
39
+ window.addEventListener('mousedown', this.handleMouseDown);
40
+ window.addEventListener('mouseup', this.handleMouseUp);
41
+ window.addEventListener('mousemove', this.handleMouseMove);
42
+ window.addEventListener('wheel', this.handleWheel, WHEEL_EVENT_OPTIONS);
43
+ window.addEventListener('contextmenu', (e) => e.preventDefault());
44
+ }
45
+ setCombinations(combinations) {
46
+ this.combinations = combinations;
47
+ }
48
+ on(action, callback) {
49
+ if (!this.listeners.has(action)) {
50
+ this.listeners.set(action, []);
51
+ }
52
+ this.listeners.get(action)?.push(callback);
53
+ return this;
54
+ }
55
+ switchWatchedElement(watchedElement) {
56
+ this._previousWatchedElement.removeEventListener('mousedown', this.handleMouseDown);
57
+ this._previousWatchedElement.removeEventListener('mouseup', this.handleMouseUp);
58
+ this._previousWatchedElement.removeEventListener('mousemove', this.handleMouseMove);
59
+ this._previousWatchedElement.removeEventListener('wheel', this.handleWheel, WHEEL_EVENT_OPTIONS);
60
+ watchedElement.addEventListener('mousedown', this.handleMouseDown);
61
+ watchedElement.addEventListener('mouseup', this.handleMouseUp);
62
+ watchedElement.addEventListener('mousemove', this.handleMouseMove);
63
+ watchedElement.addEventListener('wheel', this.handleWheel, {
64
+ passive: false
65
+ });
66
+ this._previousWatchedElement = watchedElement;
67
+ }
68
+ startTimer(key) {
69
+ if (this.timers.has(key)) {
70
+ const currentTimer = this.timers.get(key);
71
+ if (currentTimer) {
72
+ clearTimeout(currentTimer);
73
+ }
74
+ }
75
+ const timer = setTimeout(() => {
76
+ this.activeKeys.delete(key);
77
+ this.timers.delete(key);
78
+ }, CLEAR_KEY_TIME);
79
+ this.timers.set(key, timer);
80
+ }
81
+ clearTimer(key) {
82
+ if (this.timers.has(key)) {
83
+ const currentTimer = this.timers.get(key);
84
+ if (currentTimer) {
85
+ clearTimeout(currentTimer);
86
+ }
87
+ this.timers.delete(key);
88
+ }
89
+ }
90
+ _isInputActive(event) {
91
+ return (InputFieldsList.includes(event.target.tagName.toLowerCase()) || event.target.isContentEditable);
92
+ }
93
+ _hasTriggerBrowserShortcut(event) {
94
+ const hasMeta = this.activeKeys.has('Meta');
95
+ const key = this.keyMap.mapKey(event.code);
96
+ const hasNumber = !isNaN(Number(key));
97
+ return hasMeta && hasNumber;
98
+ }
99
+ handleKeyDown = (event) => {
100
+ if (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event)) {
101
+ event.preventDefault();
102
+ }
103
+ const key = this.keyMap.mapKey(event.code);
104
+ if (key) {
105
+ this.activeKeys.add(key);
106
+ if (!this.keyMap.isModifierKeys(key)) {
107
+ this.startTimer(key);
108
+ }
109
+ this.checkCombinations(InputType.KEYBOARD);
110
+ }
111
+ };
112
+ handleKeyUp = (event) => {
113
+ if (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event)) {
114
+ event.preventDefault();
115
+ }
116
+ const key = this.keyMap.mapKey(event.code);
117
+ if (key) {
118
+ this.activeKeys.delete(key);
119
+ this.clearTimer(key);
120
+ this.checkCombinations(InputType.KEYBOARD);
121
+ }
122
+ };
123
+ handleMouseDown = (event) => {
124
+ const button = getMouseButton(event.button);
125
+ const key = this.getMouseEventKey(button, 'Down');
126
+ if (key) {
127
+ this._startPos = {
128
+ clientX: event.clientX,
129
+ clientY: event.clientY
130
+ };
131
+ this.activeKeys.add(key);
132
+ this.checkCombinations(InputType.POINTER, {
133
+ ...DefaultPointerEventData,
134
+ ...this._startPos,
135
+ button
136
+ });
137
+ }
138
+ };
139
+ handleMouseUp = (event) => {
140
+ const button = getMouseButton(event.button);
141
+ const key = this.getMouseEventKey(button, 'Up');
142
+ if (key) {
143
+ this.activeKeys.add(key);
144
+ this.activeKeys.delete(key.replace('Up', 'Down'));
145
+ this.checkCombinations(InputType.POINTER, {
146
+ ...DefaultPointerEventData,
147
+ clientX: event.clientX,
148
+ clientY: event.clientY,
149
+ button
150
+ });
151
+ // No need to keep mouse up key after trigger action
152
+ this.activeKeys.delete(key);
153
+ }
154
+ };
155
+ handleMouseMove = (event) => {
156
+ const button = getMouseButton(event.button);
157
+ const key = this.getMouseEventKey(button, 'Move');
158
+ if (key) {
159
+ let canMove = true;
160
+ if (this._startPos) {
161
+ const dx = event.clientX - this._startPos.clientX;
162
+ const dy = event.clientY - this._startPos.clientY;
163
+ const distance = Math.sqrt(dx * dx + dy * dy);
164
+ if (distance < CLICK_THRESHOLD) {
165
+ canMove = false;
166
+ }
167
+ }
168
+ if (canMove) {
169
+ this.activeKeys.add(key);
170
+ this.checkCombinations(InputType.POINTER, {
171
+ ...DefaultPointerEventData,
172
+ clientX: event.clientX,
173
+ clientY: event.clientY,
174
+ button
175
+ });
176
+ // No need to keep mouse up key after trigger action
177
+ this.activeKeys.delete(key);
178
+ }
179
+ }
180
+ };
181
+ getMouseEventKey(button, state) {
182
+ if (button === MouseButton.NONE)
183
+ return;
184
+ return `${button}Mouse${state}`;
185
+ }
186
+ checkCombinations(type, pointerData = DefaultPointerEventData) {
187
+ const currentKeys = Array.from(this.activeKeys).filter((key) => !this.keyMap.isModifierKeys(key));
188
+ const activeModifiers = this.getActiveModifiers(this.activeKeys);
189
+ const allModifiers = this.getAllModifiers(activeModifiers);
190
+ for (const [eventName, combos] of Object.entries(InputEventMappings)) {
191
+ for (const combo of combos) {
192
+ if (this.isExactMatch(type, currentKeys, combo, activeModifiers)) {
193
+ const raw = {
194
+ type,
195
+ keys: currentKeys,
196
+ modifiers: allModifiers,
197
+ pointer: pointerData
198
+ };
199
+ if (combo.detail) {
200
+ raw.detail = combo.detail;
201
+ }
202
+ this.triggerAction(eventName, raw);
203
+ }
204
+ }
205
+ }
206
+ }
207
+ isExactMatch(type, keys, combo, modifiers) {
208
+ const isKeysMatch = arrEqual(keys, combo.keys);
209
+ if (type !== combo.type || !isKeysMatch)
210
+ return false;
211
+ if (isKeysMatch && (!combo.modifiers || !combo.modifiers.length)) {
212
+ return true;
213
+ }
214
+ return combo?.modifiers
215
+ ? combo.modifiers.every((m) => modifiers.includes(m))
216
+ : true;
217
+ }
218
+ triggerAction(event, raw) {
219
+ const callbacks = this.listeners.get(event);
220
+ if (callbacks) {
221
+ callbacks.forEach((cb) => {
222
+ const result = cb(raw);
223
+ // If callback returns a promise, catch any errors
224
+ if (result instanceof Promise) {
225
+ result.catch((error) => {
226
+ console.error('Error in async input system callback:', error);
227
+ });
228
+ }
229
+ });
230
+ }
231
+ }
232
+ handleWheel = (event) => {
233
+ const deltaX = event.deltaX;
234
+ const deltaY = event.deltaY;
235
+ if (this.keyMap.isSpecialEvent(SpecialEvent.WHEEL)) {
236
+ event.preventDefault();
237
+ const key = SpecialEvent.WHEEL;
238
+ this.activeKeys.add(key);
239
+ const wheelData = {
240
+ deltaX,
241
+ deltaY,
242
+ deltaZ: event.deltaZ,
243
+ clientX: event.clientX,
244
+ clientY: event.clientY,
245
+ button: MouseButton.MIDDLE
246
+ };
247
+ this.checkCombinations(InputType.WHEEL, wheelData);
248
+ // Remove wheel key immediately as scrolling is continuous
249
+ this.activeKeys.delete(key);
250
+ }
251
+ };
252
+ getActiveModifiers(keys) {
253
+ const modifiers = [];
254
+ keys.forEach((key) => {
255
+ if (this.keyMap.isModifierKeys(key)) {
256
+ modifiers.push(key.toLocaleLowerCase());
257
+ }
258
+ });
259
+ return modifiers;
260
+ }
261
+ getAllModifiers(modifiers) {
262
+ const allModifiers = {
263
+ meta: false,
264
+ ctrl: false,
265
+ alt: false,
266
+ shift: false
267
+ };
268
+ modifiers.forEach((m) => {
269
+ allModifiers[m] = true;
270
+ });
271
+ return allModifiers;
272
+ }
273
+ }
274
+ export { InputSystem };
275
+ const inputSystem = new InputSystem();
276
+ export default inputSystem;
@@ -0,0 +1,13 @@
1
+ export declare class KeyMap {
2
+ private os;
3
+ private keyMap;
4
+ constructor();
5
+ get keys(): Record<string, string>;
6
+ private detectOS;
7
+ private createKeyMap;
8
+ mapKey(code: string): string;
9
+ isModifierKeys(key: string): boolean;
10
+ isSpecialEvent(key: string): boolean;
11
+ }
12
+ declare const _default: KeyMap;
13
+ export default _default;
package/dist/keymap.js ADDED
@@ -0,0 +1,150 @@
1
+ import { ModifierKeyList, SpecialEventList, Platforms } from '@asyra/utils';
2
+ export class KeyMap {
3
+ os;
4
+ keyMap;
5
+ constructor() {
6
+ this.os = this.detectOS();
7
+ this.keyMap = this.createKeyMap();
8
+ }
9
+ get keys() {
10
+ return this.keyMap;
11
+ }
12
+ detectOS() {
13
+ // navigator.platform is often more reliable than userAgent for OS detection
14
+ const platform = (navigator
15
+ .userAgentData?.platform ||
16
+ navigator.platform ||
17
+ '').toLowerCase();
18
+ const userAgent = navigator.userAgent.toLowerCase();
19
+ if (platform.includes('mac') || userAgent.includes('mac'))
20
+ return Platforms.MAC;
21
+ if (platform.includes('win') || userAgent.includes('win'))
22
+ return Platforms.WINDOWS;
23
+ return Platforms.LINUX;
24
+ }
25
+ createKeyMap() {
26
+ const baseMap = {
27
+ Escape: 'Escape',
28
+ Tab: 'Tab',
29
+ CapsLock: 'CapsLock',
30
+ ShiftLeft: 'Shift',
31
+ ShiftRight: 'Shift',
32
+ ControlLeft: 'Ctrl',
33
+ ControlRight: 'Ctrl',
34
+ AltLeft: 'Alt',
35
+ AltRight: 'Alt',
36
+ MetaLeft: 'Meta',
37
+ MetaRight: 'Meta',
38
+ OSLeft: 'Meta',
39
+ OSRight: 'Meta',
40
+ Space: 'Space',
41
+ Enter: 'Enter',
42
+ // ... same as before
43
+ Backspace: 'Backspace',
44
+ // Arrow Key
45
+ ArrowUp: 'ArrowUp',
46
+ ArrowDown: 'ArrowDown',
47
+ ArrowLeft: 'ArrowLeft',
48
+ ArrowRight: 'ArrowRight',
49
+ // Number
50
+ Digit0: '0',
51
+ Digit1: '1',
52
+ Digit2: '2',
53
+ Digit3: '3',
54
+ Digit4: '4',
55
+ Digit5: '5',
56
+ Digit6: '6',
57
+ Digit7: '7',
58
+ Digit8: '8',
59
+ Digit9: '9',
60
+ // Letter
61
+ KeyA: 'A',
62
+ KeyB: 'B',
63
+ KeyC: 'C',
64
+ KeyD: 'D',
65
+ KeyE: 'E',
66
+ KeyF: 'F',
67
+ KeyG: 'G',
68
+ KeyH: 'H',
69
+ KeyI: 'I',
70
+ KeyJ: 'J',
71
+ KeyK: 'K',
72
+ KeyL: 'L',
73
+ KeyM: 'M',
74
+ KeyN: 'N',
75
+ KeyO: 'O',
76
+ KeyP: 'P',
77
+ KeyQ: 'Q',
78
+ KeyR: 'R',
79
+ KeyS: 'S',
80
+ KeyT: 'T',
81
+ KeyU: 'U',
82
+ KeyV: 'V',
83
+ KeyW: 'W',
84
+ KeyX: 'X',
85
+ KeyY: 'Y',
86
+ KeyZ: 'Z',
87
+ // Symbol
88
+ Minus: '-',
89
+ Equal: '=',
90
+ BracketLeft: '[',
91
+ BracketRight: ']',
92
+ Backslash: '\\',
93
+ Semicolon: ';',
94
+ Quote: "'",
95
+ Backquote: '`',
96
+ Comma: ',',
97
+ Period: '.',
98
+ Slash: '/',
99
+ // F1~F12
100
+ F1: 'F1',
101
+ F2: 'F2',
102
+ F3: 'F3',
103
+ F4: 'F4',
104
+ F5: 'F5',
105
+ F6: 'F6',
106
+ F7: 'F7',
107
+ F8: 'F8',
108
+ F9: 'F9',
109
+ F10: 'F10',
110
+ F11: 'F11',
111
+ F12: 'F12',
112
+ // Numpad
113
+ Numpad0: 'Numpad0',
114
+ Numpad1: 'Numpad1',
115
+ Numpad2: 'Numpad2',
116
+ Numpad3: 'Numpad3',
117
+ Numpad4: 'Numpad4',
118
+ Numpad5: 'Numpad5',
119
+ Numpad6: 'Numpad6',
120
+ Numpad7: 'Numpad7',
121
+ Numpad8: 'Numpad8',
122
+ Numpad9: 'Numpad9',
123
+ NumpadAdd: '+',
124
+ NumpadSubtract: '-',
125
+ NumpadMultiply: '*',
126
+ NumpadDivide: '/',
127
+ NumpadEnter: 'Enter',
128
+ NumpadDecimal: '.'
129
+ };
130
+ if (this.os === Platforms.MAC) {
131
+ baseMap['AltLeft'] = 'Alt';
132
+ baseMap['AltRight'] = 'Alt';
133
+ baseMap['Delete'] = 'Delete';
134
+ }
135
+ else if (this.os === Platforms.WINDOWS || this.os === Platforms.LINUX) {
136
+ baseMap['Delete'] = 'Del';
137
+ }
138
+ return baseMap;
139
+ }
140
+ mapKey(code) {
141
+ return this.keyMap[code] || code;
142
+ }
143
+ isModifierKeys(key) {
144
+ return ModifierKeyList.includes(key.toLowerCase());
145
+ }
146
+ isSpecialEvent(key) {
147
+ return SpecialEventList.includes(key);
148
+ }
149
+ }
150
+ export default new KeyMap();
@@ -0,0 +1,16 @@
1
+ import { InputKey } from '@asyra/utils';
2
+ /**
3
+ * Checks if the currently active keys match a given combination.
4
+ * The order of keys does not matter.
5
+ *
6
+ * @param keys - A Set of currently active keys (KeyboardKey | ModifierKey).
7
+ * @param combo - A list of keys that form a combination.
8
+ */
9
+ export declare function matchActive(keys: Set<InputKey>, combo: InputKey[]): boolean;
10
+ /**
11
+ * Checks if the recent key sequence ends with a specific ordered pattern.
12
+ *
13
+ * @param sequence - The full recent key sequence (e.g., for chord shortcuts).
14
+ * @param pattern - The ordered pattern to match.
15
+ */
16
+ export declare function matchSequence(sequence: InputKey[], pattern: InputKey[]): boolean;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Checks if the currently active keys match a given combination.
3
+ * The order of keys does not matter.
4
+ *
5
+ * @param keys - A Set of currently active keys (KeyboardKey | ModifierKey).
6
+ * @param combo - A list of keys that form a combination.
7
+ */
8
+ export function matchActive(keys, combo) {
9
+ if (combo.length === 0)
10
+ return false;
11
+ for (const key of combo) {
12
+ if (!keys.has(key))
13
+ return false;
14
+ }
15
+ return true;
16
+ }
17
+ /**
18
+ * Checks if the recent key sequence ends with a specific ordered pattern.
19
+ *
20
+ * @param sequence - The full recent key sequence (e.g., for chord shortcuts).
21
+ * @param pattern - The ordered pattern to match.
22
+ */
23
+ export function matchSequence(sequence, pattern) {
24
+ if (sequence.length < pattern.length)
25
+ return false;
26
+ const start = sequence.length - pattern.length;
27
+ for (let i = 0; i < pattern.length; i++) {
28
+ if (sequence[start + i] !== pattern[i])
29
+ return false;
30
+ }
31
+ return true;
32
+ }
@@ -0,0 +1 @@
1
+ export declare const initInputSystemSubscribe: () => void;
@@ -0,0 +1,7 @@
1
+ import { subscribeToSwitchInputSystemWatchedElement } from '@asyra/reactive-events';
2
+ import inputSystem from './input-system';
3
+ export const initInputSystemSubscribe = () => {
4
+ subscribeToSwitchInputSystemWatchedElement(({ payload }) => {
5
+ inputSystem.switchWatchedElement(payload.watchedElement);
6
+ });
7
+ };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@asyra/input-system",
3
+ "version": "0.2.0",
4
+ "description": "Keyboard and Mouse event listener plugin",
5
+ "author": "Asa Tsai",
6
+ "license": "MIT",
7
+ "packageManager": "yarn@4.3.1",
8
+ "main": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "scripts": {
11
+ "dev": "tsc --watch --preserveWatchOutput",
12
+ "build:input-system": "tsc",
13
+ "clean": "rm -rf dist",
14
+ "has:test": "find . -type f \\( -name \"*.test.ts\" -o -name \"*.test.tsx\" \\) | grep -q .",
15
+ "test": "yarn has:test && vitest || echo 'No test files found. Skipping test.'",
16
+ "test:local": "yarn has:test && vitest run || echo 'No test files found. Skipping test:local.'",
17
+ "test:ci": "yarn has:test && vitest run --coverage --reporter=default --reporter=junit || echo 'No test files found. Skipping test:ci.'"
18
+ },
19
+ "devDependencies": {
20
+ "@vitest/coverage-v8": "^2.1.8",
21
+ "typescript": "^5.7.2",
22
+ "vitest": "^2.1.8"
23
+ },
24
+ "dependencies": {
25
+ "@asyra/reactive-events": "workspace:*",
26
+ "@asyra/utils": "workspace:*"
27
+ }
28
+ }