@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,279 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { InputSystem } from '../input-system';
3
+ import { InputType, ModifierKey } from '@asyra/utils';
4
+ import keyMap from '../keymap';
5
+ import { CLEAR_KEY_TIME } from '../constants';
6
+ import { InputEventMappings } from '../event-mappings';
7
+ import * as EventMappingsModule from '../event-mappings';
8
+ vi.mock('../event-mappings', async (importOriginal) => {
9
+ const actual = await importOriginal();
10
+ return {
11
+ ...actual
12
+ };
13
+ });
14
+ describe('InputSystem', () => {
15
+ let inputSystem;
16
+ let addEventListenerSpy;
17
+ let preventDefaultSpy;
18
+ let clearTimeoutSpy;
19
+ let setTimeoutSpy;
20
+ let mockHTMLElement;
21
+ beforeEach(() => {
22
+ vi.clearAllMocks();
23
+ // Mock window event listeners
24
+ addEventListenerSpy = vi.spyOn(window, 'addEventListener');
25
+ preventDefaultSpy = vi.fn();
26
+ clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
27
+ setTimeoutSpy = vi.spyOn(global, 'setTimeout');
28
+ // Mock HTMLElement for event.target
29
+ mockHTMLElement = {
30
+ tagName: 'div',
31
+ isContentEditable: false
32
+ // Add other properties as needed by the code under test
33
+ };
34
+ inputSystem = new InputSystem();
35
+ });
36
+ // Test constructor and setupListeners
37
+ it('should set up event listeners on window during construction', () => {
38
+ expect(addEventListenerSpy).toHaveBeenCalledWith('keydown', expect.any(Function));
39
+ expect(addEventListenerSpy).toHaveBeenCalledWith('keyup', expect.any(Function));
40
+ expect(addEventListenerSpy).toHaveBeenCalledWith('mousedown', expect.any(Function));
41
+ expect(addEventListenerSpy).toHaveBeenCalledWith('mouseup', expect.any(Function));
42
+ expect(addEventListenerSpy).toHaveBeenCalledWith('mousemove', expect.any(Function));
43
+ expect(addEventListenerSpy).toHaveBeenCalledWith('wheel', expect.any(Function), { passive: false });
44
+ expect(addEventListenerSpy).toHaveBeenCalledWith('contextmenu', expect.any(Function));
45
+ });
46
+ // Test handleKeyDown
47
+ it('should add key to activeKeys and prevent default if not input active', () => {
48
+ const event = new KeyboardEvent('keydown', { code: 'KeyA' });
49
+ Object.defineProperty(event, 'target', { value: mockHTMLElement }); // Not an input field
50
+ event.preventDefault = preventDefaultSpy;
51
+ inputSystem['handleKeyDown'](event);
52
+ expect(inputSystem['activeKeys'].has(keyMap.keys.KeyA)).toBe(true);
53
+ expect(preventDefaultSpy).toHaveBeenCalled();
54
+ });
55
+ it('should not prevent default if input field is active', () => {
56
+ const event = new KeyboardEvent('keydown', { code: 'KeyA' });
57
+ const inputElement = document.createElement('input');
58
+ Object.defineProperty(event, 'target', { value: inputElement });
59
+ event.preventDefault = preventDefaultSpy;
60
+ inputSystem['handleKeyDown'](event);
61
+ expect(inputSystem['activeKeys'].has(keyMap.keys.KeyA)).toBe(true);
62
+ expect(preventDefaultSpy).not.toHaveBeenCalled();
63
+ });
64
+ it('should start timer for non-modifier keys', () => {
65
+ vi.spyOn(keyMap, 'isModifierKeys').mockReturnValue(false);
66
+ const event = new KeyboardEvent('keydown', { code: 'KeyA' });
67
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
68
+ event.preventDefault = preventDefaultSpy;
69
+ inputSystem['handleKeyDown'](event);
70
+ expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
71
+ expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), CLEAR_KEY_TIME);
72
+ });
73
+ it('should not start timer for modifier keys', () => {
74
+ vi.spyOn(keyMap, 'isModifierKeys').mockReturnValue(true);
75
+ const event = new KeyboardEvent('keydown', { code: 'ShiftLeft' });
76
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
77
+ event.preventDefault = preventDefaultSpy;
78
+ inputSystem['handleKeyDown'](event);
79
+ expect(setTimeoutSpy).not.toHaveBeenCalled();
80
+ });
81
+ // Test handleKeyUp
82
+ it('should remove key from activeKeys and clear timer', () => {
83
+ const key = keyMap.keys.KeyA;
84
+ inputSystem['activeKeys'].add(key);
85
+ const timerId = 123;
86
+ inputSystem['timers'].set(key, timerId);
87
+ const event = new KeyboardEvent('keyup', { code: 'KeyA' });
88
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
89
+ event.preventDefault = preventDefaultSpy;
90
+ inputSystem['handleKeyUp'](event);
91
+ expect(inputSystem['activeKeys'].has(key)).toBe(false);
92
+ expect(clearTimeoutSpy).toHaveBeenCalledWith(timerId);
93
+ expect(inputSystem['timers'].has(key)).toBe(false);
94
+ expect(preventDefaultSpy).toHaveBeenCalled();
95
+ });
96
+ // Test handleMouseDown
97
+ it('should add mouse button key to activeKeys and set startPos', () => {
98
+ const event = new MouseEvent('mousedown', {
99
+ button: 0,
100
+ clientX: 10,
101
+ clientY: 20
102
+ });
103
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
104
+ inputSystem['handleMouseDown'](event);
105
+ expect(inputSystem['activeKeys'].has('leftMouseDown')).toBe(true);
106
+ expect(inputSystem['_startPos']).toEqual({ clientX: 10, clientY: 20 });
107
+ });
108
+ // Test handleMouseUp
109
+ it('should add mouse up key, remove mouse down key, and trigger checkCombinations', () => {
110
+ inputSystem['activeKeys'].add('leftMouseDown');
111
+ const event = new MouseEvent('mouseup', {
112
+ button: 0,
113
+ clientX: 10,
114
+ clientY: 20
115
+ });
116
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
117
+ inputSystem['handleMouseUp'](event);
118
+ expect(inputSystem['activeKeys'].has('leftMouseUp')).toBe(false);
119
+ expect(inputSystem['activeKeys'].has('leftMouseDown')).toBe(false);
120
+ });
121
+ // Test handleMouseMove
122
+ it('should add mouse move key and trigger checkCombinations if dragging beyond threshold', () => {
123
+ inputSystem['_startPos'] = { clientX: 0, clientY: 0 };
124
+ const event = new MouseEvent('mousemove', {
125
+ button: 0,
126
+ clientX: 10,
127
+ clientY: 10
128
+ }); // Distance > CLICK_THRESHOLD (5)
129
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
130
+ inputSystem['handleMouseMove'](event);
131
+ expect(inputSystem['activeKeys'].has('leftMouseMove')).toBe(false);
132
+ });
133
+ it('should not add mouse move key if dragging within threshold', () => {
134
+ inputSystem['_startPos'] = { clientX: 0, clientY: 0 };
135
+ const event = new MouseEvent('mousemove', {
136
+ button: 0,
137
+ clientX: 1,
138
+ clientY: 1
139
+ }); // Distance < CLICK_THRESHOLD (5)
140
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
141
+ inputSystem['handleMouseMove'](event);
142
+ expect(inputSystem['activeKeys'].has('leftMouseMove')).toBe(false);
143
+ });
144
+ // Test handleWheel
145
+ it('should prevent default and trigger checkCombinations for wheel event', () => {
146
+ vi.spyOn(keyMap, 'isSpecialEvent').mockReturnValue(true); // Mock as special event
147
+ const event = new WheelEvent('wheel', {
148
+ deltaX: 10,
149
+ deltaY: 20,
150
+ clientX: 50,
151
+ clientY: 60
152
+ });
153
+ Object.defineProperty(event, 'target', { value: mockHTMLElement });
154
+ event.preventDefault = preventDefaultSpy;
155
+ inputSystem['handleWheel'](event);
156
+ expect(preventDefaultSpy).toHaveBeenCalled();
157
+ expect(inputSystem['activeKeys'].has('wheel')).toBe(false); // Should be removed immediately
158
+ });
159
+ // Test getActiveModifiers
160
+ it('should return active modifier keys', () => {
161
+ inputSystem['activeKeys'].add(keyMap.keys.ShiftLeft);
162
+ inputSystem['activeKeys'].add(keyMap.keys.KeyA);
163
+ inputSystem['activeKeys'].add(keyMap.keys.ControlLeft);
164
+ // Explicitly mock to ensure it works in this test context
165
+ vi.spyOn(keyMap, 'isModifierKeys').mockImplementation((key) => ['Shift', 'Ctrl'].includes(key));
166
+ const modifiers = inputSystem.getActiveModifiers(inputSystem['activeKeys']);
167
+ expect(modifiers).toEqual(['shift', 'ctrl']);
168
+ });
169
+ // Test getAllModifiers
170
+ it('should return all modifier keys status', () => {
171
+ const activeModifiers = [ModifierKey.SHIFT, ModifierKey.ALT];
172
+ const allModifiers = inputSystem.getAllModifiers(activeModifiers);
173
+ expect(allModifiers).toEqual({
174
+ meta: false,
175
+ ctrl: false,
176
+ alt: true,
177
+ shift: true
178
+ });
179
+ });
180
+ // Test checkCombinations and triggerAction
181
+ it('should trigger action for matching combination', () => {
182
+ const triggerActionSpy = vi.spyOn(inputSystem, 'triggerAction');
183
+ inputSystem['activeKeys'].add(keyMap.keys.KeyA);
184
+ const INPUT_KEYBOARD_A = 'INPUT_KEYBOARD_A';
185
+ vi.mocked(EventMappingsModule).InputEventMappings = {
186
+ ...InputEventMappings,
187
+ [INPUT_KEYBOARD_A]: [
188
+ { type: InputType.KEYBOARD, keys: [keyMap.keys.KeyA], modifiers: [] }
189
+ ]
190
+ };
191
+ inputSystem['checkCombinations'](InputType.KEYBOARD);
192
+ expect(triggerActionSpy).toHaveBeenCalledTimes(1);
193
+ expect(triggerActionSpy).toHaveBeenCalledWith('INPUT_KEYBOARD_A', expect.objectContaining({
194
+ type: InputType.KEYBOARD,
195
+ keys: [keyMap.keys.KeyA]
196
+ }));
197
+ });
198
+ it('should not trigger action for non-matching combination', () => {
199
+ const triggerActionSpy = vi.spyOn(inputSystem, 'triggerAction');
200
+ inputSystem['activeKeys'].add('KeyB'); // Active key is B
201
+ const INPUT_KEYBOARD_A = 'INPUT_KEYBOARD_A';
202
+ vi.mocked(EventMappingsModule).InputEventMappings = {
203
+ ...InputEventMappings,
204
+ [INPUT_KEYBOARD_A]: [
205
+ { type: InputType.KEYBOARD, keys: [keyMap.keys.KeyA], modifiers: [] } // Mapping is for A
206
+ ]
207
+ };
208
+ inputSystem['checkCombinations'](InputType.KEYBOARD);
209
+ expect(triggerActionSpy).not.toHaveBeenCalled();
210
+ });
211
+ it('should trigger action with detail if provided in combo', () => {
212
+ const triggerActionSpy = vi.spyOn(inputSystem, 'triggerAction');
213
+ inputSystem['activeKeys'].add(keyMap.keys.KeyA);
214
+ const mockDetail = { some: 'detail' };
215
+ const INPUT_KEYBOARD_A = 'INPUT_KEYBOARD_A';
216
+ vi.mocked(EventMappingsModule).InputEventMappings = {
217
+ ...InputEventMappings,
218
+ [INPUT_KEYBOARD_A]: [
219
+ {
220
+ type: InputType.KEYBOARD,
221
+ keys: [keyMap.keys.KeyA],
222
+ modifiers: [],
223
+ detail: mockDetail
224
+ }
225
+ ]
226
+ };
227
+ inputSystem['checkCombinations'](InputType.KEYBOARD);
228
+ expect(triggerActionSpy).toHaveBeenCalledWith('INPUT_KEYBOARD_A', expect.objectContaining({
229
+ detail: mockDetail
230
+ }));
231
+ });
232
+ it('should call registered listeners when triggerAction is called', () => {
233
+ const listener1 = vi.fn();
234
+ const listener2 = vi.fn();
235
+ const INPUT_KEYBOARD_A = 'INPUT_KEYBOARD_A';
236
+ inputSystem.on(INPUT_KEYBOARD_A, listener1);
237
+ inputSystem.on(INPUT_KEYBOARD_A, listener2);
238
+ const rawEvent = {
239
+ type: InputType.KEYBOARD,
240
+ keys: [keyMap.keys.KeyA],
241
+ modifiers: { meta: false, ctrl: false, alt: false, shift: false },
242
+ pointer: {}
243
+ };
244
+ inputSystem['triggerAction'](INPUT_KEYBOARD_A, rawEvent);
245
+ expect(listener1).toHaveBeenCalledTimes(1);
246
+ expect(listener1).toHaveBeenCalledWith(rawEvent);
247
+ expect(listener2).toHaveBeenCalledTimes(1);
248
+ expect(listener2).toHaveBeenCalledWith(rawEvent);
249
+ });
250
+ it('should handle async listeners correctly', async () => {
251
+ const asyncListener = vi.fn(() => Promise.resolve());
252
+ inputSystem.on('INPUT_KEYBOARD_A', asyncListener);
253
+ const rawEvent = {
254
+ type: InputType.KEYBOARD,
255
+ keys: [keyMap.keys.KeyA],
256
+ modifiers: { meta: false, ctrl: false, alt: false, shift: false },
257
+ pointer: {}
258
+ };
259
+ await inputSystem['triggerAction']('INPUT_KEYBOARD_A', rawEvent);
260
+ expect(asyncListener).toHaveBeenCalledTimes(1);
261
+ });
262
+ it('should catch errors in async listeners', async () => {
263
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {
264
+ /* no-op */
265
+ });
266
+ const asyncListener = vi.fn(() => Promise.reject('Test Error'));
267
+ inputSystem.on('INPUT_KEYBOARD_A', asyncListener);
268
+ const rawEvent = {
269
+ type: InputType.KEYBOARD,
270
+ keys: [keyMap.keys.KeyA],
271
+ modifiers: { meta: false, ctrl: false, alt: false, shift: false },
272
+ pointer: {}
273
+ };
274
+ await inputSystem['triggerAction']('INPUT_KEYBOARD_A', rawEvent);
275
+ expect(asyncListener).toHaveBeenCalledTimes(1);
276
+ expect(errorSpy).toHaveBeenCalledWith('Error in async input system callback:', 'Test Error');
277
+ errorSpy.mockRestore();
278
+ });
279
+ });
@@ -0,0 +1,2 @@
1
+ export declare const CLICK_THRESHOLD = 3;
2
+ export declare const CLEAR_KEY_TIME = 100;
@@ -0,0 +1,2 @@
1
+ export const CLICK_THRESHOLD = 3;
2
+ export const CLEAR_KEY_TIME = 100;
@@ -0,0 +1,8 @@
1
+ import { InputType, KeyboardKey, ModifierKey, InputSystemEvents, DetailType } from '@asyra/utils';
2
+ export interface InputEventCombo {
3
+ type: InputType;
4
+ keys: KeyboardKey[];
5
+ modifiers?: ModifierKey[];
6
+ detail?: DetailType;
7
+ }
8
+ export declare const InputEventMappings: Record<InputSystemEvents, InputEventCombo[]>;
@@ -0,0 +1,78 @@
1
+ import { InputType, PointerKey, ModifierKey, InputSystemEvents, PrimaryToolType } from '@asyra/utils';
2
+ import keyMap from './keymap';
3
+ export const InputEventMappings = {
4
+ [InputSystemEvents.INPUT_DRAG_START]: [
5
+ { type: InputType.POINTER, keys: [PointerKey.LEFT_MOUSE_DOWN] }
6
+ ],
7
+ [InputSystemEvents.INPUT_DRAG_UPDATE]: [
8
+ {
9
+ type: InputType.POINTER,
10
+ keys: [PointerKey.LEFT_MOUSE_DOWN, PointerKey.LEFT_MOUSE_MOVE]
11
+ }
12
+ ],
13
+ [InputSystemEvents.INPUT_DRAG_END]: [
14
+ { type: InputType.POINTER, keys: [PointerKey.LEFT_MOUSE_UP] }
15
+ ],
16
+ [InputSystemEvents.INPUT_MOUSE_MOVE]: [
17
+ {
18
+ type: InputType.POINTER,
19
+ keys: [PointerKey.LEFT_MOUSE_MOVE]
20
+ }
21
+ ],
22
+ [InputSystemEvents.INPUT_WHEEL_SCROLL]: [
23
+ { type: InputType.WHEEL, keys: [PointerKey.WHEEL] }
24
+ ],
25
+ [InputSystemEvents.INPUT_SHORTCUT_ARROW]: [
26
+ {
27
+ type: InputType.KEYBOARD,
28
+ keys: [keyMap.keys.ArrowUp]
29
+ },
30
+ {
31
+ type: InputType.KEYBOARD,
32
+ keys: [keyMap.keys.ArrowDown]
33
+ },
34
+ {
35
+ type: InputType.KEYBOARD,
36
+ keys: [keyMap.keys.ArrowLeft]
37
+ },
38
+ {
39
+ type: InputType.KEYBOARD,
40
+ keys: [keyMap.keys.ArrowRight]
41
+ }
42
+ ],
43
+ [InputSystemEvents.INPUT_SHORTCUT_UNDOREDO]: [
44
+ {
45
+ type: InputType.KEYBOARD,
46
+ keys: [keyMap.keys.KeyZ],
47
+ modifiers: [ModifierKey.META]
48
+ },
49
+ {
50
+ type: InputType.KEYBOARD,
51
+ keys: [keyMap.keys.KeyZ],
52
+ modifiers: [ModifierKey.CTRL]
53
+ }
54
+ ],
55
+ [InputSystemEvents.INPUT_SHORTCUT_ZOOM_PRESET]: [
56
+ {
57
+ type: InputType.KEYBOARD,
58
+ keys: [keyMap.keys.Digit1],
59
+ modifiers: [ModifierKey.META]
60
+ }
61
+ ],
62
+ [InputSystemEvents.INPUT_SHORTCUT_SWITCH_PRIMARY_TOOL]: [
63
+ {
64
+ type: InputType.KEYBOARD,
65
+ keys: [keyMap.keys.KeyR],
66
+ detail: {
67
+ primaryTool: PrimaryToolType.RECTANGLE
68
+ }
69
+ },
70
+ {
71
+ type: InputType.KEYBOARD,
72
+ keys: [keyMap.keys.KeyV],
73
+ detail: {
74
+ primaryTool: PrimaryToolType.SELECT
75
+ }
76
+ }
77
+ ]
78
+ };
@@ -0,0 +1,3 @@
1
+ import inputSystem, { InputSystem } from './input-system';
2
+ export { InputSystem };
3
+ export default inputSystem;
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import inputSystem, { InputSystem } from './input-system';
2
+ import { initInputSystemSubscribe } from './subscribe';
3
+ initInputSystemSubscribe();
4
+ export { InputSystem };
5
+ export default inputSystem;
@@ -0,0 +1,36 @@
1
+ import { ModifierKeys, RawInputEvent, ModifierKey } from '@asyra/utils';
2
+ type Callback = (raw: RawInputEvent) => void | Promise<void>;
3
+ type Combinations = Record<string, string[]>;
4
+ declare class InputSystem {
5
+ private _previousWatchedElement;
6
+ private combinations;
7
+ private keyMap;
8
+ private activeKeys;
9
+ private listeners;
10
+ private timers;
11
+ private _startPos;
12
+ constructor();
13
+ private setupListeners;
14
+ setCombinations(combinations: Combinations): void;
15
+ on(action: string, callback: Callback): this;
16
+ switchWatchedElement(watchedElement: HTMLElement): void;
17
+ private startTimer;
18
+ private clearTimer;
19
+ private _isInputActive;
20
+ private _hasTriggerBrowserShortcut;
21
+ private handleKeyDown;
22
+ private handleKeyUp;
23
+ private handleMouseDown;
24
+ private handleMouseUp;
25
+ private handleMouseMove;
26
+ private getMouseEventKey;
27
+ private checkCombinations;
28
+ private isExactMatch;
29
+ private triggerAction;
30
+ private handleWheel;
31
+ getActiveModifiers(keys: Set<string>): ModifierKey[];
32
+ getAllModifiers(modifiers: ModifierKey[]): ModifierKeys;
33
+ }
34
+ export { InputSystem };
35
+ declare const inputSystem: InputSystem;
36
+ export default inputSystem;