@asyra/input-system 0.2.5 → 0.5.1

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -48
  3. package/dist/event-mappings.d.ts +37 -2
  4. package/dist/event-mappings.js +1 -78
  5. package/dist/index.d.ts +5 -2
  6. package/dist/index.js +5 -3
  7. package/dist/input-system.d.ts +11 -0
  8. package/dist/input-system.js +133 -11
  9. package/dist/registry.d.ts +39 -0
  10. package/dist/registry.js +57 -0
  11. package/dist/subscribe.js +14 -2
  12. package/package.json +22 -4
  13. package/.turbo/turbo-test$colon$ci.log +0 -132
  14. package/.turbo/turbo-test$colon$local.log +0 -52
  15. package/.turbo/turbo-test.log +0 -0
  16. package/CHANGELOG.md +0 -46
  17. package/coverage/base.css +0 -224
  18. package/coverage/block-navigation.js +0 -87
  19. package/coverage/clover.xml +0 -573
  20. package/coverage/constants.ts.html +0 -94
  21. package/coverage/coverage-final.json +0 -8963
  22. package/coverage/event-mappings.ts.html +0 -370
  23. package/coverage/favicon.png +0 -0
  24. package/coverage/index.html +0 -206
  25. package/coverage/index.ts.html +0 -106
  26. package/coverage/input-system.ts.html +0 -1216
  27. package/coverage/keymap.ts.html +0 -616
  28. package/coverage/matcher.ts.html +0 -187
  29. package/coverage/prettify.css +0 -1
  30. package/coverage/prettify.js +0 -2
  31. package/coverage/sort-arrow-sprite.png +0 -0
  32. package/coverage/sorter.js +0 -196
  33. package/coverage/subscribe.ts.html +0 -109
  34. package/dist/__tests__/input-system.test.d.ts +0 -1
  35. package/dist/__tests__/input-system.test.js +0 -279
  36. package/dist/matcher.d.ts +0 -16
  37. package/dist/matcher.js +0 -32
  38. package/src/__tests__/input-system.test.ts +0 -398
  39. package/src/constants.ts +0 -3
  40. package/src/event-mappings.ts +0 -95
  41. package/src/index.ts +0 -7
  42. package/src/input-system.ts +0 -377
  43. package/src/keymap.ts +0 -177
  44. package/src/matcher.ts +0 -34
  45. package/src/subscribe.ts +0 -8
  46. package/test-setup.ts +0 -6
  47. package/tsconfig.json +0 -22
  48. package/vitest.config.ts +0 -8
@@ -1,377 +0,0 @@
1
- import {
2
- MouseData,
3
- MouseButton,
4
- SpecialEvent,
5
- InputField,
6
- ModifierKeys,
7
- RawInputEvent,
8
- InputType,
9
- ModifierKey,
10
- KeyboardKey,
11
- arrEqual,
12
- PointerEventData,
13
- DefaultPointerEventData,
14
- InputSystemEvents
15
- } from '@asyra/utils'
16
- import { InputFieldsList } from '@asyra/utils'
17
- import { CLICK_THRESHOLD, CLEAR_KEY_TIME } from './constants'
18
- import { InputEventCombo, InputEventMappings } from './event-mappings'
19
- import keymap, { KeyMap } from './keymap'
20
-
21
- type Callback = (raw: RawInputEvent) => void | Promise<void>
22
- type Combinations = Record<string, string[]>
23
-
24
- const WHEEL_EVENT_OPTIONS: AddEventListenerOptions = { passive: false }
25
-
26
- const getMouseButton = (button: number): MouseButton => {
27
- switch (button) {
28
- case 0:
29
- return MouseButton.LEFT
30
- case 1:
31
- return MouseButton.MIDDLE
32
- case 2:
33
- return MouseButton.RIGHT
34
- default:
35
- return MouseButton.NONE
36
- }
37
- }
38
-
39
- class InputSystem {
40
- private _previousWatchedElement: Window | HTMLElement
41
- private combinations: Combinations = {}
42
- private keyMap: KeyMap
43
- private activeKeys: Set<string>
44
- private listeners: Map<string, Callback[]>
45
- private timers: Map<string, NodeJS.Timeout>
46
- private _startPos: MouseData | null
47
-
48
- constructor() {
49
- this._previousWatchedElement = window
50
- this.keyMap = keymap
51
- this.activeKeys = new Set()
52
- this.listeners = new Map()
53
- this.timers = new Map()
54
- this._startPos = null
55
-
56
- this.setupListeners()
57
- }
58
-
59
- private setupListeners() {
60
- window.addEventListener('keydown', this.handleKeyDown)
61
- window.addEventListener('keyup', this.handleKeyUp)
62
- window.addEventListener('mousedown', this.handleMouseDown)
63
- window.addEventListener('mouseup', this.handleMouseUp)
64
- window.addEventListener('mousemove', this.handleMouseMove)
65
- window.addEventListener('wheel', this.handleWheel, WHEEL_EVENT_OPTIONS)
66
- window.addEventListener('contextmenu', (e: MouseEvent) =>
67
- e.preventDefault()
68
- )
69
- }
70
-
71
- setCombinations(combinations: Combinations) {
72
- this.combinations = combinations
73
- }
74
-
75
- on(action: string, callback: Callback): this {
76
- if (!this.listeners.has(action)) {
77
- this.listeners.set(action, [])
78
- }
79
- this.listeners.get(action)?.push(callback)
80
- return this
81
- }
82
-
83
- switchWatchedElement(watchedElement: HTMLElement) {
84
- this._previousWatchedElement.removeEventListener(
85
- 'mousedown',
86
- this.handleMouseDown as EventListener
87
- )
88
- this._previousWatchedElement.removeEventListener(
89
- 'mouseup',
90
- this.handleMouseUp as EventListener
91
- )
92
- this._previousWatchedElement.removeEventListener(
93
- 'mousemove',
94
- this.handleMouseMove as EventListener
95
- )
96
- this._previousWatchedElement.removeEventListener(
97
- 'wheel',
98
- this.handleWheel as EventListener,
99
- WHEEL_EVENT_OPTIONS
100
- )
101
-
102
- watchedElement.addEventListener('mousedown', this.handleMouseDown)
103
- watchedElement.addEventListener('mouseup', this.handleMouseUp)
104
- watchedElement.addEventListener('mousemove', this.handleMouseMove)
105
- watchedElement.addEventListener('wheel', this.handleWheel, {
106
- passive: false
107
- })
108
-
109
- this._previousWatchedElement = watchedElement
110
- }
111
-
112
- private startTimer(key: string) {
113
- if (this.timers.has(key)) {
114
- const currentTimer = this.timers.get(key)
115
- if (currentTimer) {
116
- clearTimeout(currentTimer)
117
- }
118
- }
119
-
120
- const timer = setTimeout(() => {
121
- this.activeKeys.delete(key)
122
- this.timers.delete(key)
123
- }, CLEAR_KEY_TIME)
124
- this.timers.set(key, timer)
125
- }
126
-
127
- private clearTimer(key: string) {
128
- if (this.timers.has(key)) {
129
- const currentTimer = this.timers.get(key)
130
- if (currentTimer) {
131
- clearTimeout(currentTimer)
132
- }
133
- this.timers.delete(key)
134
- }
135
- }
136
-
137
- private _isInputActive(event: KeyboardEvent) {
138
- return (
139
- InputFieldsList.includes(
140
- (event.target as HTMLElement).tagName.toLowerCase() as InputField
141
- ) || (event.target as HTMLElement).isContentEditable
142
- )
143
- }
144
-
145
- private _hasTriggerBrowserShortcut(event: KeyboardEvent) {
146
- const hasMeta = this.activeKeys.has('Meta')
147
- const key = this.keyMap.mapKey(event.code)
148
- const hasNumber = !isNaN(Number(key))
149
- return hasMeta && hasNumber
150
- }
151
-
152
- private handleKeyDown = (event: KeyboardEvent) => {
153
- if (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event)) {
154
- event.preventDefault()
155
- }
156
-
157
- const key = this.keyMap.mapKey(event.code)
158
- if (key) {
159
- this.activeKeys.add(key)
160
- if (!this.keyMap.isModifierKeys(key)) {
161
- this.startTimer(key)
162
- }
163
-
164
- this.checkCombinations(InputType.KEYBOARD)
165
- }
166
- }
167
-
168
- private handleKeyUp = (event: KeyboardEvent) => {
169
- if (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event)) {
170
- event.preventDefault()
171
- }
172
-
173
- const key = this.keyMap.mapKey(event.code)
174
- if (key) {
175
- this.activeKeys.delete(key)
176
- this.clearTimer(key)
177
-
178
- this.checkCombinations(InputType.KEYBOARD)
179
- }
180
- }
181
-
182
- private handleMouseDown = (event: MouseEvent) => {
183
- const button = getMouseButton(event.button)
184
- const key = this.getMouseEventKey(button, 'Down')
185
-
186
- if (key) {
187
- this._startPos = {
188
- clientX: event.clientX,
189
- clientY: event.clientY
190
- }
191
- this.activeKeys.add(key)
192
-
193
- this.checkCombinations(InputType.POINTER, {
194
- ...DefaultPointerEventData,
195
- ...this._startPos,
196
- button
197
- })
198
- }
199
- }
200
-
201
- private handleMouseUp = (event: MouseEvent) => {
202
- const button = getMouseButton(event.button)
203
- const key = this.getMouseEventKey(button, 'Up')
204
-
205
- if (key) {
206
- this.activeKeys.add(key)
207
- this.activeKeys.delete(key.replace('Up', 'Down'))
208
-
209
- this.checkCombinations(InputType.POINTER, {
210
- ...DefaultPointerEventData,
211
- clientX: event.clientX,
212
- clientY: event.clientY,
213
- button
214
- })
215
-
216
- // No need to keep mouse up key after trigger action
217
- this.activeKeys.delete(key)
218
- }
219
- }
220
-
221
- private handleMouseMove = (event: MouseEvent) => {
222
- const button = getMouseButton(event.button)
223
- const key = this.getMouseEventKey(button, 'Move')
224
-
225
- if (key) {
226
- let canMove = true
227
- if (this._startPos) {
228
- const dx = event.clientX - this._startPos.clientX
229
- const dy = event.clientY - this._startPos.clientY
230
- const distance = Math.sqrt(dx * dx + dy * dy)
231
-
232
- if (distance < CLICK_THRESHOLD) {
233
- canMove = false
234
- }
235
- }
236
-
237
- if (canMove) {
238
- this.activeKeys.add(key)
239
-
240
- this.checkCombinations(InputType.POINTER, {
241
- ...DefaultPointerEventData,
242
- clientX: event.clientX,
243
- clientY: event.clientY,
244
- button
245
- })
246
-
247
- // No need to keep mouse up key after trigger action
248
- this.activeKeys.delete(key)
249
- }
250
- }
251
- }
252
-
253
- private getMouseEventKey(
254
- button: MouseButton,
255
- state: string
256
- ): string | undefined {
257
- if (button === MouseButton.NONE) return
258
-
259
- return `${button}Mouse${state}`
260
- }
261
-
262
- private checkCombinations(
263
- type: InputType,
264
- pointerData: PointerEventData = DefaultPointerEventData
265
- ) {
266
- const currentKeys = Array.from(this.activeKeys).filter(
267
- (key) => !this.keyMap.isModifierKeys(key)
268
- )
269
- const activeModifiers = this.getActiveModifiers(this.activeKeys)
270
- const allModifiers = this.getAllModifiers(activeModifiers)
271
- for (const [eventName, combos] of Object.entries(InputEventMappings)) {
272
- for (const combo of combos) {
273
- if (this.isExactMatch(type, currentKeys, combo, activeModifiers)) {
274
- const raw: RawInputEvent = {
275
- type,
276
- keys: currentKeys,
277
- modifiers: allModifiers,
278
- pointer: pointerData
279
- }
280
- if (combo.detail) {
281
- raw.detail = combo.detail
282
- }
283
- this.triggerAction(eventName as InputSystemEvents, raw)
284
- }
285
- }
286
- }
287
- }
288
-
289
- private isExactMatch(
290
- type: InputType,
291
- keys: KeyboardKey[],
292
- combo: InputEventCombo,
293
- modifiers: ModifierKey[]
294
- ): boolean {
295
- const isKeysMatch = arrEqual(keys, combo.keys)
296
- if (type !== combo.type || !isKeysMatch) return false
297
- if (isKeysMatch && (!combo.modifiers || !combo.modifiers.length)) {
298
- return true
299
- }
300
-
301
- return combo?.modifiers
302
- ? combo.modifiers.every((m) => modifiers.includes(m))
303
- : true
304
- }
305
-
306
- private triggerAction(event: InputSystemEvents, raw: RawInputEvent) {
307
- const callbacks = this.listeners.get(event)
308
- if (callbacks) {
309
- callbacks.forEach((cb) => {
310
- const result = cb(raw)
311
- // If callback returns a promise, catch any errors
312
- if (result instanceof Promise) {
313
- result.catch((error) => {
314
- console.error('Error in async input system callback:', error)
315
- })
316
- }
317
- })
318
- }
319
- }
320
-
321
- private handleWheel = (event: WheelEvent) => {
322
- const deltaX = event.deltaX
323
- const deltaY = event.deltaY
324
-
325
- if (this.keyMap.isSpecialEvent(SpecialEvent.WHEEL)) {
326
- event.preventDefault()
327
- const key = SpecialEvent.WHEEL
328
- this.activeKeys.add(key)
329
-
330
- const wheelData: PointerEventData = {
331
- deltaX,
332
- deltaY,
333
- deltaZ: event.deltaZ,
334
- clientX: event.clientX,
335
- clientY: event.clientY,
336
- button: MouseButton.MIDDLE
337
- }
338
-
339
- this.checkCombinations(InputType.WHEEL, wheelData)
340
-
341
- // Remove wheel key immediately as scrolling is continuous
342
- this.activeKeys.delete(key)
343
- }
344
- }
345
-
346
- getActiveModifiers(keys: Set<string>): ModifierKey[] {
347
- const modifiers: ModifierKey[] = []
348
-
349
- keys.forEach((key) => {
350
- if (this.keyMap.isModifierKeys(key)) {
351
- modifiers.push(key.toLocaleLowerCase() as ModifierKey)
352
- }
353
- })
354
-
355
- return modifiers
356
- }
357
-
358
- getAllModifiers(modifiers: ModifierKey[]): ModifierKeys {
359
- const allModifiers: ModifierKeys = {
360
- meta: false,
361
- ctrl: false,
362
- alt: false,
363
- shift: false
364
- }
365
-
366
- modifiers.forEach((m) => {
367
- allModifiers[m] = true
368
- })
369
-
370
- return allModifiers
371
- }
372
- }
373
-
374
- export { InputSystem }
375
-
376
- const inputSystem = new InputSystem()
377
- export default inputSystem
package/src/keymap.ts DELETED
@@ -1,177 +0,0 @@
1
- import {
2
- ModifierKeyList,
3
- SpecialEventList,
4
- Platforms,
5
- ModifierKey,
6
- SpecialEvent,
7
- KeyboardKey
8
- } from '@asyra/utils'
9
-
10
- export class KeyMap {
11
- private os: Platforms
12
- private keyMap: Record<string, KeyboardKey>
13
-
14
- constructor() {
15
- this.os = this.detectOS()
16
- this.keyMap = this.createKeyMap()
17
- }
18
-
19
- get keys() {
20
- return this.keyMap
21
- }
22
-
23
- private detectOS(): Platforms {
24
- // navigator.platform is often more reliable than userAgent for OS detection
25
- const platform = (
26
- (navigator as unknown as { userAgentData?: { platform?: string } })
27
- .userAgentData?.platform ||
28
- navigator.platform ||
29
- ''
30
- ).toLowerCase()
31
- const userAgent = navigator.userAgent.toLowerCase()
32
-
33
- if (platform.includes('mac') || userAgent.includes('mac'))
34
- return Platforms.MAC
35
- if (platform.includes('win') || userAgent.includes('win'))
36
- return Platforms.WINDOWS
37
- return Platforms.LINUX
38
- }
39
-
40
- private createKeyMap(): Record<string, KeyboardKey> {
41
- const baseMap: Record<string, KeyboardKey> = {
42
- Escape: 'Escape',
43
- Tab: 'Tab',
44
- CapsLock: 'CapsLock',
45
- ShiftLeft: 'Shift',
46
- ShiftRight: 'Shift',
47
- ControlLeft: 'Ctrl',
48
- ControlRight: 'Ctrl',
49
- AltLeft: 'Alt',
50
- AltRight: 'Alt',
51
- MetaLeft: 'Meta',
52
- MetaRight: 'Meta',
53
- OSLeft: 'Meta',
54
- OSRight: 'Meta',
55
- Space: 'Space',
56
- Enter: 'Enter',
57
- // ... same as before
58
- Backspace: 'Backspace',
59
-
60
- // Arrow Key
61
- ArrowUp: 'ArrowUp',
62
- ArrowDown: 'ArrowDown',
63
- ArrowLeft: 'ArrowLeft',
64
- ArrowRight: 'ArrowRight',
65
-
66
- // Number
67
- Digit0: '0',
68
- Digit1: '1',
69
- Digit2: '2',
70
- Digit3: '3',
71
- Digit4: '4',
72
- Digit5: '5',
73
- Digit6: '6',
74
- Digit7: '7',
75
- Digit8: '8',
76
- Digit9: '9',
77
-
78
- // Letter
79
- KeyA: 'A',
80
- KeyB: 'B',
81
- KeyC: 'C',
82
- KeyD: 'D',
83
- KeyE: 'E',
84
- KeyF: 'F',
85
- KeyG: 'G',
86
- KeyH: 'H',
87
- KeyI: 'I',
88
- KeyJ: 'J',
89
- KeyK: 'K',
90
- KeyL: 'L',
91
- KeyM: 'M',
92
- KeyN: 'N',
93
- KeyO: 'O',
94
- KeyP: 'P',
95
- KeyQ: 'Q',
96
- KeyR: 'R',
97
- KeyS: 'S',
98
- KeyT: 'T',
99
- KeyU: 'U',
100
- KeyV: 'V',
101
- KeyW: 'W',
102
- KeyX: 'X',
103
- KeyY: 'Y',
104
- KeyZ: 'Z',
105
-
106
- // Symbol
107
- Minus: '-',
108
- Equal: '=',
109
- BracketLeft: '[',
110
- BracketRight: ']',
111
- Backslash: '\\',
112
- Semicolon: ';',
113
-
114
- Quote: "'",
115
- Backquote: '`',
116
- Comma: ',',
117
- Period: '.',
118
- Slash: '/',
119
-
120
- // F1~F12
121
- F1: 'F1',
122
- F2: 'F2',
123
- F3: 'F3',
124
- F4: 'F4',
125
- F5: 'F5',
126
- F6: 'F6',
127
- F7: 'F7',
128
- F8: 'F8',
129
- F9: 'F9',
130
- F10: 'F10',
131
- F11: 'F11',
132
- F12: 'F12',
133
-
134
- // Numpad
135
- Numpad0: 'Numpad0',
136
- Numpad1: 'Numpad1',
137
- Numpad2: 'Numpad2',
138
- Numpad3: 'Numpad3',
139
- Numpad4: 'Numpad4',
140
- Numpad5: 'Numpad5',
141
- Numpad6: 'Numpad6',
142
- Numpad7: 'Numpad7',
143
- Numpad8: 'Numpad8',
144
- Numpad9: 'Numpad9',
145
- NumpadAdd: '+',
146
- NumpadSubtract: '-',
147
- NumpadMultiply: '*',
148
- NumpadDivide: '/',
149
- NumpadEnter: 'Enter',
150
- NumpadDecimal: '.'
151
- }
152
-
153
- if (this.os === Platforms.MAC) {
154
- baseMap['AltLeft'] = 'Alt'
155
- baseMap['AltRight'] = 'Alt'
156
- baseMap['Delete'] = 'Delete'
157
- } else if (this.os === Platforms.WINDOWS || this.os === Platforms.LINUX) {
158
- baseMap['Delete'] = 'Del'
159
- }
160
-
161
- return baseMap
162
- }
163
-
164
- public mapKey(code: string): string {
165
- return this.keyMap[code] || code
166
- }
167
-
168
- public isModifierKeys(key: string): boolean {
169
- return ModifierKeyList.includes(key.toLowerCase() as ModifierKey)
170
- }
171
-
172
- public isSpecialEvent(key: string): boolean {
173
- return SpecialEventList.includes(key as SpecialEvent)
174
- }
175
- }
176
-
177
- export default new KeyMap()
package/src/matcher.ts DELETED
@@ -1,34 +0,0 @@
1
- import { InputKey } from '@asyra/utils'
2
-
3
- /**
4
- * Checks if the currently active keys match a given combination.
5
- * The order of keys does not matter.
6
- *
7
- * @param keys - A Set of currently active keys (KeyboardKey | ModifierKey).
8
- * @param combo - A list of keys that form a combination.
9
- */
10
- export function matchActive(keys: Set<InputKey>, combo: InputKey[]): boolean {
11
- if (combo.length === 0) return false
12
- for (const key of combo) {
13
- if (!keys.has(key)) return false
14
- }
15
- return true
16
- }
17
-
18
- /**
19
- * Checks if the recent key sequence ends with a specific ordered pattern.
20
- *
21
- * @param sequence - The full recent key sequence (e.g., for chord shortcuts).
22
- * @param pattern - The ordered pattern to match.
23
- */
24
- export function matchSequence(
25
- sequence: InputKey[],
26
- pattern: InputKey[]
27
- ): boolean {
28
- if (sequence.length < pattern.length) return false
29
- const start = sequence.length - pattern.length
30
- for (let i = 0; i < pattern.length; i++) {
31
- if (sequence[start + i] !== pattern[i]) return false
32
- }
33
- return true
34
- }
package/src/subscribe.ts DELETED
@@ -1,8 +0,0 @@
1
- import { subscribeToSwitchInputSystemWatchedElement } from '@asyra/reactive-events'
2
- import inputSystem from './input-system'
3
-
4
- export const initInputSystemSubscribe = () => {
5
- subscribeToSwitchInputSystemWatchedElement(({ payload }) => {
6
- inputSystem.switchWatchedElement(payload.watchedElement)
7
- })
8
- }
package/test-setup.ts DELETED
@@ -1,6 +0,0 @@
1
- Object.defineProperty(globalThis, 'navigator', {
2
- value: {
3
- userAgent: 'node.js'
4
- },
5
- writable: true
6
- })
package/tsconfig.json DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "esnext",
4
- "module": "esnext",
5
- "moduleResolution": "node",
6
- "rootDir": "./src",
7
- "outDir": "./dist",
8
- "resolveJsonModule": true,
9
- "esModuleInterop": true,
10
- "noEmit": false,
11
- "strict": true,
12
- "skipLibCheck": true,
13
- "declaration": true
14
- },
15
- "include": [
16
- "src"
17
- ],
18
- "exclude": [
19
- "node_modules",
20
- "dist"
21
- ]
22
- }
package/vitest.config.ts DELETED
@@ -1,8 +0,0 @@
1
- import { defineConfig } from 'vitest/config'
2
-
3
- export default defineConfig({
4
- test: {
5
- environment: 'jsdom',
6
- setupFiles: ['./test-setup.ts']
7
- }
8
- })