@asyra/input-system 0.5.5 → 0.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @asyra/input-system
2
2
 
3
+ ## Pending - Office input and spatial materials
4
+
5
+ ```update-note
6
+ {
7
+ "change": "office-input-and-spatial-materials",
8
+ "owner": "Framework - @asyra/input-system",
9
+ "summary": "Support held keyboard control or optional spatial material effects used by the Office preview, preserving existing defaults.",
10
+ "sources": [
11
+ "packages/input-system/src/__tests__/held-keyboard.test.ts",
12
+ "packages/input-system/src/__tests__/input-system.test.ts",
13
+ "packages/input-system/src/__tests__/runtime-reset.test.ts",
14
+ "packages/input-system/src/event-mappings.ts",
15
+ "packages/input-system/src/input-system.ts"
16
+ ],
17
+ "impact": "integration",
18
+ "guides": [
19
+ "docs/public/updates/held-input-and-spatial-materials-r1.md"
20
+ ],
21
+ "reason": "Optional APIs require explicit consumer registration and preservation of app-owned policies; see the adoption guide."
22
+ }
23
+ ```
24
+
3
25
  ## 0.5.5
4
26
 
5
27
  ### Patch Changes
@@ -38,6 +38,13 @@ export interface InputEventCombo {
38
38
  type: InputType;
39
39
  keys: KeyboardKey[];
40
40
  modifiers?: ModifierKey[];
41
+ /**
42
+ * Keyboard-only held observation: keys are alternatives, not an exact chord.
43
+ * Reports down/up/cancel with live modifiers; callback owns modifier admission.
44
+ * `modifiers` is a chord-mode filter and is not applied in held mode.
45
+ */
46
+ keyboardMode?: 'held';
41
47
  detail?: DetailType;
42
- callback?: (raw: RawInputEvent) => void;
48
+ /** Return false to ignore this input before dispatch; policy belongs to the caller. */
49
+ callback?: ((raw: RawInputEvent) => void) | ((raw: RawInputEvent) => boolean);
43
50
  }
package/dist/index.d.ts CHANGED
@@ -3,4 +3,5 @@ import { InputSystemRegistry } from './registry.js';
3
3
  import { InputEventCombo } from './event-mappings.js';
4
4
  import keyMap from './keymap.js';
5
5
  export { InputSystem, InputSystemRegistry, InputEventCombo, keyMap };
6
+ export { requestInputAttachment } from './subscribe.js';
6
7
  export default inputSystem;
package/dist/index.js CHANGED
@@ -4,4 +4,5 @@ import keyMap from './keymap.js';
4
4
  import { initInputSystemSubscribe } from './subscribe.js';
5
5
  initInputSystemSubscribe();
6
6
  export { InputSystem, InputSystemRegistry, keyMap };
7
+ export { requestInputAttachment } from './subscribe.js';
7
8
  export default inputSystem;
@@ -0,0 +1,4 @@
1
+ import type { InputSystem } from './input-system.js';
2
+ export declare function inputOwner(event: Event): InputSystem | undefined;
3
+ export declare function captureOwner(owner: symbol): InputSystem | undefined;
4
+ export declare function attachInputScope(input: InputSystem, target: HTMLElement, owner?: symbol): () => void;
@@ -0,0 +1,35 @@
1
+ const surfaces = new WeakMap();
2
+ const captures = new Map();
3
+ export function inputOwner(event) {
4
+ for (const node of event.composedPath()) {
5
+ const owner = surfaces.get(node);
6
+ if (owner) {
7
+ return owner;
8
+ }
9
+ }
10
+ }
11
+ export function captureOwner(owner) {
12
+ return captures.get(owner);
13
+ }
14
+ export function attachInputScope(input, target, owner) {
15
+ const makeFocusable = !target.hasAttribute('tabindex') && target.tabIndex < 0;
16
+ if (makeFocusable) {
17
+ target.tabIndex = -1;
18
+ }
19
+ surfaces.set(target, input);
20
+ if (owner) {
21
+ captures.set(owner, input);
22
+ }
23
+ return () => {
24
+ if (owner && captures.get(owner) === input) {
25
+ captures.delete(owner);
26
+ }
27
+ if (surfaces.get(target) !== input) {
28
+ return;
29
+ }
30
+ surfaces.delete(target);
31
+ if (makeFocusable && target.getAttribute('tabindex') === '-1') {
32
+ target.removeAttribute('tabindex');
33
+ }
34
+ };
35
+ }
@@ -1,8 +1,10 @@
1
+ import { createShortcutRegistry } from './shortcuts.js';
1
2
  import { ModifierKeys, RawInputEvent, ModifierKey } from '@asyra/utils';
2
3
  import { InputSystemRegistry } from './registry.js';
3
4
  type Callback = (raw: RawInputEvent) => void | Promise<void>;
4
5
  type Combinations = Record<string, string[]>;
5
6
  declare class InputSystem {
7
+ private heldKeyboardKeys;
6
8
  private browserHost;
7
9
  private pointerTarget;
8
10
  private combinations;
@@ -14,10 +16,14 @@ declare class InputSystem {
14
16
  private pointerInputBlocked;
15
17
  private pointerCaptureId;
16
18
  registry: InputSystemRegistry;
19
+ private releaseScope?;
17
20
  private runtimeGeneration;
18
21
  private browserListeners;
19
- constructor();
22
+ readonly shortcuts: ReturnType<typeof createShortcutRegistry>;
23
+ private readonly ownsShortcuts;
24
+ constructor(shortcuts?: ReturnType<typeof createShortcutRegistry>);
20
25
  attachBrowserHost(host: Window, pointerTarget?: Window | HTMLElement): void;
26
+ private clearScope;
21
27
  detachBrowserHost(): void;
22
28
  private addKeyboardListeners;
23
29
  private removeKeyboardListeners;
@@ -29,13 +35,19 @@ declare class InputSystem {
29
35
  setCombinations(combinations: Combinations): void;
30
36
  on(action: string, callback: Callback): this;
31
37
  off(action: string, callback: Callback): boolean;
32
- switchWatchedElement(watchedElement: HTMLElement): void;
38
+ switchWatchedElement(watchedElement: HTMLElement, interactionOwner?: symbol, keyboardTarget?: HTMLElement): void;
33
39
  private startTimer;
34
40
  private clearTimer;
35
41
  private _isInputActive;
36
42
  private _hasTriggerBrowserShortcut;
37
43
  private handleKeyDown;
44
+ private releaseKey;
38
45
  private handleKeyUp;
46
+ private hasHeldInterest;
47
+ private dispatchHeldKeyboard;
48
+ private cancelKeyboard;
49
+ private synchronizeModifiers;
50
+ private hiddenKeyboard;
39
51
  private handleMouseDown;
40
52
  private handleMouseUp;
41
53
  private handleMouseMove;
@@ -1,8 +1,11 @@
1
- import { MouseButton, SpecialEvent, InputType, arrEqual, DefaultPointerEventData, measureBrowserDragPhase } from '@asyra/utils';
1
+ import { bindToolInput } from './tool-input.js';
2
+ import { createShortcutRegistry } from './shortcuts.js';
3
+ import { MouseButton, SpecialEvent, InputType, ModifierKey, arrEqual, DefaultPointerEventData, measureBrowserDragPhase } from '@asyra/utils';
2
4
  import { InputFieldsList } from '@asyra/utils';
3
5
  import { PointerKey } from '@asyra/utils';
4
6
  import { CLICK_THRESHOLD, CLEAR_KEY_TIME } from './constants.js';
5
7
  import { InputSystemRegistry } from './registry.js';
8
+ import { attachInputScope, inputOwner } from './input-scope.js';
6
9
  import keymap from './keymap.js';
7
10
  const WHEEL_EVENT_OPTIONS = { passive: false };
8
11
  const POINTER_KEYS = new Set(Object.values(PointerKey));
@@ -31,6 +34,7 @@ const getMouseButtonFromButtonsMask = (buttons) => {
31
34
  return MouseButton.NONE;
32
35
  };
33
36
  class InputSystem {
37
+ heldKeyboardKeys = new Set();
34
38
  browserHost;
35
39
  pointerTarget;
36
40
  combinations = {};
@@ -42,9 +46,14 @@ class InputSystem {
42
46
  pointerInputBlocked;
43
47
  pointerCaptureId;
44
48
  registry;
49
+ releaseScope;
45
50
  runtimeGeneration = 0;
46
51
  browserListeners = new Map();
47
- constructor() {
52
+ shortcuts;
53
+ ownsShortcuts;
54
+ constructor(shortcuts) {
55
+ this.ownsShortcuts = !shortcuts;
56
+ this.shortcuts = shortcuts ?? createShortcutRegistry();
48
57
  this.browserHost = null;
49
58
  this.pointerTarget = null;
50
59
  this.keyMap = keymap;
@@ -55,11 +64,14 @@ class InputSystem {
55
64
  this.pointerInputBlocked = false;
56
65
  this.pointerCaptureId = null;
57
66
  this.registry = new InputSystemRegistry();
67
+ this.shortcuts.attach(this.registry);
58
68
  }
59
69
  attachBrowserHost(host, pointerTarget = host) {
60
70
  if (this.browserHost === host && this.pointerTarget === pointerTarget) {
61
71
  return;
62
72
  }
73
+ this.shortcuts.attach(this.registry);
74
+ this.clearScope();
63
75
  if (this.pointerTarget && this.pointerTarget !== pointerTarget) {
64
76
  this.removePointerListeners(this.pointerTarget);
65
77
  this.pointerTarget = null;
@@ -77,7 +89,18 @@ class InputSystem {
77
89
  this.pointerTarget = pointerTarget;
78
90
  }
79
91
  }
92
+ clearScope() {
93
+ if (!this.releaseScope) {
94
+ return;
95
+ }
96
+ this.releaseScope();
97
+ this.releaseScope = undefined;
98
+ this.cancelKeyboard();
99
+ this.setPointerCaptureBlock(false);
100
+ }
80
101
  detachBrowserHost() {
102
+ this.shortcuts.detach(this.registry);
103
+ this.clearScope();
81
104
  if (this.pointerTarget) {
82
105
  this.removePointerListeners(this.pointerTarget);
83
106
  this.pointerTarget = null;
@@ -88,10 +111,13 @@ class InputSystem {
88
111
  }
89
112
  }
90
113
  addKeyboardListeners(host) {
91
- this.keyboardBindings().forEach(([name, listener]) => host.addEventListener(name, listener));
114
+ this.keyboardBindings().forEach((binding) => host.addEventListener(...binding));
115
+ host.document.addEventListener('visibilitychange', this.browserListener(this.hiddenKeyboard));
92
116
  }
93
117
  removeKeyboardListeners(host, attempt = (cleanup) => cleanup()) {
94
- this.keyboardBindings().forEach(([name, listener]) => attempt(() => host.removeEventListener(name, listener)));
118
+ this.keyboardBindings().forEach((binding) => attempt(() => host.removeEventListener(...binding)));
119
+ attempt(() => host.document.removeEventListener('visibilitychange', this.browserListener(this.hiddenKeyboard)));
120
+ attempt(this.cancelKeyboard);
95
121
  }
96
122
  addPointerListeners(target) {
97
123
  this.pointerBindings().forEach((binding) => target.addEventListener(...binding));
@@ -102,7 +128,12 @@ class InputSystem {
102
128
  keyboardBindings() {
103
129
  return [
104
130
  ['keydown', this.browserListener(this.handleKeyDown)],
105
- ['keyup', this.browserListener(this.handleKeyUp)]
131
+ ['keyup', this.browserListener(this.releaseKey), true],
132
+ ['keyup', this.browserListener(this.handleKeyUp)],
133
+ ['blur', this.browserListener(this.cancelKeyboard)],
134
+ ['focus', this.browserListener(this.cancelKeyboard)],
135
+ ['focusin', this.browserListener(this.cancelKeyboard)],
136
+ ['compositionstart', this.browserListener(this.cancelKeyboard)]
106
137
  ];
107
138
  }
108
139
  pointerBindings() {
@@ -129,12 +160,28 @@ class InputSystem {
129
160
  }
130
161
  browserListener(listener) {
131
162
  const existing = this.browserListeners.get(listener);
132
- if (existing)
163
+ if (existing) {
133
164
  return existing;
165
+ }
134
166
  const generation = this.runtimeGeneration;
135
167
  const guarded = (event) => {
136
- if (generation === this.runtimeGeneration)
168
+ if (event.type === 'keydown' || event.type === 'keyup') {
169
+ const owner = inputOwner(event);
170
+ if (owner ? owner !== this : this.releaseScope) {
171
+ return;
172
+ }
173
+ const target = this.pointerTarget;
174
+ // Composed keyboard events reach every window listener, including sibling editors.
175
+ if (!owner && target && 'getRootNode' in target) {
176
+ const root = target.getRootNode();
177
+ if ('host' in root && !event.composedPath().includes(root)) {
178
+ return;
179
+ }
180
+ }
181
+ }
182
+ if (generation === this.runtimeGeneration) {
137
183
  listener(event);
184
+ }
138
185
  };
139
186
  this.browserListeners.set(listener, guarded);
140
187
  return guarded;
@@ -164,12 +211,16 @@ class InputSystem {
164
211
  }
165
212
  return true;
166
213
  }
167
- switchWatchedElement(watchedElement) {
214
+ switchWatchedElement(watchedElement, interactionOwner, keyboardTarget) {
168
215
  const host = watchedElement.ownerDocument.defaultView;
169
216
  if (!host) {
170
217
  throw new Error('[InputSystem] Watched element must belong to a document with a Window');
171
218
  }
219
+ this.clearScope();
172
220
  this.attachBrowserHost(host, watchedElement);
221
+ if (interactionOwner || keyboardTarget) {
222
+ this.releaseScope = attachInputScope(this, keyboardTarget ?? watchedElement, interactionOwner);
223
+ }
173
224
  }
174
225
  startTimer(key) {
175
226
  if (this.timers.has(key)) {
@@ -180,8 +231,9 @@ class InputSystem {
180
231
  }
181
232
  const generation = this.runtimeGeneration;
182
233
  const timer = setTimeout(() => {
183
- if (generation !== this.runtimeGeneration)
234
+ if (generation !== this.runtimeGeneration) {
184
235
  return;
236
+ }
185
237
  this.activeKeys.delete(key);
186
238
  this.timers.delete(key);
187
239
  }, CLEAR_KEY_TIME);
@@ -197,7 +249,9 @@ class InputSystem {
197
249
  }
198
250
  }
199
251
  _isInputActive(event) {
200
- return (InputFieldsList.includes(event.target.tagName.toLowerCase()) || event.target.isContentEditable);
252
+ const origin = (event.composedPath?.()[0] ?? event.target);
253
+ return (InputFieldsList.includes(origin?.tagName?.toLowerCase()) ||
254
+ origin?.isContentEditable);
201
255
  }
202
256
  _hasTriggerBrowserShortcut(event) {
203
257
  const hasMeta = this.activeKeys.has('Meta');
@@ -206,10 +260,27 @@ class InputSystem {
206
260
  return hasMeta && hasNumber;
207
261
  }
208
262
  handleKeyDown = (event) => {
209
- if (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event)) {
210
- event.preventDefault();
263
+ if (!this.shortcuts.accepts(event)) {
264
+ return;
211
265
  }
266
+ this.synchronizeModifiers(event);
212
267
  const key = this.keyMap.mapKey(event.code);
268
+ const interested = this.hasHeldInterest(key);
269
+ if (event.isComposing) {
270
+ this.cancelKeyboard();
271
+ }
272
+ else {
273
+ if (key && !this.keyMap.isModifierKeys(key)) {
274
+ this.heldKeyboardKeys.add(key);
275
+ }
276
+ if (this.dispatchHeldKeyboard(event, key, 'down')) {
277
+ event.preventDefault();
278
+ }
279
+ }
280
+ if (!interested &&
281
+ (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event))) {
282
+ event.preventDefault();
283
+ }
213
284
  if (key) {
214
285
  this.activeKeys.add(key);
215
286
  if (!this.keyMap.isModifierKeys(key)) {
@@ -218,18 +289,129 @@ class InputSystem {
218
289
  this.checkCombinations(InputType.KEYBOARD);
219
290
  }
220
291
  };
292
+ // Release bookkeeping must survive editors stopping event propagation.
293
+ // Capture publishes opted-in held releases only; ordinary chord dispatch stays in bubble phase.
294
+ releaseKey = (event, notifyHeld = true) => {
295
+ this.synchronizeModifiers(event);
296
+ const key = this.keyMap.mapKey(event.code);
297
+ if (key) {
298
+ if (!this.keyMap.isModifierKeys(key)) {
299
+ this.activeKeys.delete(key);
300
+ }
301
+ this.clearTimer(key);
302
+ if (notifyHeld && !this.shortcuts.released(event.code)) {
303
+ this.heldKeyboardKeys.delete(key);
304
+ this.dispatchHeldKeyboard(event, key, 'up');
305
+ }
306
+ }
307
+ };
221
308
  handleKeyUp = (event) => {
222
- if (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event)) {
309
+ if (!this.shortcuts.accepts(event)) {
310
+ return;
311
+ }
312
+ if (!this.hasHeldInterest(this.keyMap.mapKey(event.code)) &&
313
+ (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event))) {
223
314
  event.preventDefault();
224
315
  }
225
316
  const key = this.keyMap.mapKey(event.code);
226
317
  if (key) {
227
- this.activeKeys.delete(key);
228
- this.clearTimer(key);
318
+ this.releaseKey(event, false);
229
319
  this.checkCombinations(InputType.KEYBOARD);
230
320
  }
231
321
  };
322
+ hasHeldInterest(key) {
323
+ return this.registry
324
+ .getEventNames()
325
+ .some((name) => this.registry
326
+ .getCombinations(name)
327
+ ?.some((combo) => combo.type === InputType.KEYBOARD &&
328
+ combo.keyboardMode === 'held' &&
329
+ combo.keys.some((candidate) => candidate === key || this.heldKeyboardKeys.has(candidate))));
330
+ }
331
+ dispatchHeldKeyboard(event, key, phase) {
332
+ let accepted = false;
333
+ const raw = {
334
+ type: InputType.KEYBOARD,
335
+ keys: [...this.heldKeyboardKeys],
336
+ modifiers: {
337
+ shift: event?.shiftKey ?? false,
338
+ ctrl: event?.ctrlKey ?? false,
339
+ alt: event?.altKey ?? false,
340
+ meta: event?.metaKey ?? false
341
+ },
342
+ pointer: DefaultPointerEventData,
343
+ keyboard: {
344
+ phase,
345
+ changedKey: key ?? null,
346
+ target: event?.composedPath?.()[0] ?? event?.target ?? null,
347
+ repeat: event?.repeat ?? false,
348
+ isComposing: event?.isComposing ?? false
349
+ }
350
+ };
351
+ for (const name of this.registry.getEventNames()) {
352
+ for (const combo of this.registry.getCombinations(name) ?? []) {
353
+ if (combo.type !== InputType.KEYBOARD ||
354
+ combo.keyboardMode !== 'held') {
355
+ continue;
356
+ }
357
+ if (phase !== 'cancel' &&
358
+ !combo.keys.some((candidate) => candidate === key || this.heldKeyboardKeys.has(candidate))) {
359
+ continue;
360
+ }
361
+ const snapshot = {
362
+ ...raw,
363
+ keys: [...raw.keys],
364
+ modifiers: { ...raw.modifiers },
365
+ detail: combo.detail
366
+ };
367
+ if (combo.callback?.(snapshot) === false) {
368
+ continue;
369
+ }
370
+ accepted = true;
371
+ this.triggerAction(name, snapshot);
372
+ }
373
+ }
374
+ return accepted;
375
+ }
376
+ cancelKeyboard = () => {
377
+ for (const key of this.activeKeys) {
378
+ if (!POINTER_KEYS.has(key)) {
379
+ this.activeKeys.delete(key);
380
+ this.clearTimer(key);
381
+ }
382
+ }
383
+ if (!this.heldKeyboardKeys.size) {
384
+ return;
385
+ }
386
+ this.heldKeyboardKeys.clear();
387
+ this.dispatchHeldKeyboard(null, undefined, 'cancel');
388
+ };
389
+ synchronizeModifiers(event) {
390
+ // Browsers can swallow the remaining keyups of an OS Command shortcut.
391
+ if (this.activeKeys.has('Meta') && !event.metaKey) {
392
+ this.cancelKeyboard();
393
+ }
394
+ for (const [key, down] of [
395
+ ['Shift', event.shiftKey],
396
+ ['Ctrl', event.ctrlKey],
397
+ ['Alt', event.altKey],
398
+ ['Meta', event.metaKey]
399
+ ]) {
400
+ if (down) {
401
+ this.activeKeys.add(key);
402
+ }
403
+ else {
404
+ this.activeKeys.delete(key);
405
+ }
406
+ }
407
+ }
408
+ hiddenKeyboard = () => {
409
+ if (this.browserHost?.document.hidden) {
410
+ this.cancelKeyboard();
411
+ }
412
+ };
232
413
  handleMouseDown = (event) => {
414
+ this.synchronizeModifiers(event);
233
415
  if (this.pointerInputBlocked) {
234
416
  return;
235
417
  }
@@ -244,11 +426,13 @@ class InputSystem {
244
426
  this.checkCombinations(InputType.POINTER, {
245
427
  ...DefaultPointerEventData,
246
428
  ...this._startPos,
429
+ clickCount: event.detail,
247
430
  button
248
431
  });
249
432
  }
250
433
  };
251
434
  handleMouseUp = (event) => {
435
+ this.synchronizeModifiers(event);
252
436
  if (this.pointerInputBlocked) {
253
437
  return;
254
438
  }
@@ -261,6 +445,7 @@ class InputSystem {
261
445
  ...DefaultPointerEventData,
262
446
  clientX: event.clientX,
263
447
  clientY: event.clientY,
448
+ clickCount: event.detail,
264
449
  button
265
450
  });
266
451
  // No need to keep mouse up key after trigger action
@@ -268,6 +453,7 @@ class InputSystem {
268
453
  }
269
454
  };
270
455
  handleMouseMove = (event) => {
456
+ this.synchronizeModifiers(event);
271
457
  if (this.pointerInputBlocked) {
272
458
  return;
273
459
  }
@@ -300,6 +486,7 @@ class InputSystem {
300
486
  }
301
487
  };
302
488
  handleDoubleClick = (event) => {
489
+ this.synchronizeModifiers(event);
303
490
  if (this.pointerInputBlocked) {
304
491
  return;
305
492
  }
@@ -309,16 +496,18 @@ class InputSystem {
309
496
  ...DefaultPointerEventData,
310
497
  clientX: event.clientX,
311
498
  clientY: event.clientY,
499
+ clickCount: event.detail,
312
500
  button
313
501
  });
314
502
  this.activeKeys.delete(PointerKey.MOUSE_DOUBLE_CLICK);
315
503
  };
316
504
  getMouseEventKey(button, state) {
317
- if (button === MouseButton.NONE)
505
+ if (button === MouseButton.NONE) {
318
506
  return;
507
+ }
319
508
  return `${button}Mouse${state}`;
320
509
  }
321
- checkCombinations(type, pointerData = DefaultPointerEventData) {
510
+ checkCombinations(type, pointerData = DefaultPointerEventData, activeModifiers = this.getActiveModifiers(this.activeKeys)) {
322
511
  const currentKeys = Array.from(this.activeKeys).filter((key) => {
323
512
  if (this.keyMap.isModifierKeys(key)) {
324
513
  return false;
@@ -331,13 +520,16 @@ class InputSystem {
331
520
  }
332
521
  return POINTER_KEYS.has(key) && key !== SpecialEvent.WHEEL;
333
522
  });
334
- const activeModifiers = this.getActiveModifiers(this.activeKeys);
335
523
  const allModifiers = this.getAllModifiers(activeModifiers);
336
524
  for (const eventName of this.registry.getEventNames()) {
337
525
  const combos = this.registry.getCombinations(eventName);
338
- if (!combos)
526
+ if (!combos) {
339
527
  continue;
528
+ }
340
529
  for (const combo of combos) {
530
+ if (combo.keyboardMode === 'held') {
531
+ continue;
532
+ }
341
533
  if (this.isExactMatch(type, currentKeys, combo, activeModifiers)) {
342
534
  const raw = {
343
535
  type,
@@ -348,9 +540,9 @@ class InputSystem {
348
540
  if (combo.detail) {
349
541
  raw.detail = combo.detail;
350
542
  }
351
- // Call callback before triggering action (if defined)
352
- if (combo.callback) {
353
- combo.callback(raw);
543
+ // Admission happens before any downstream queue or session receives input.
544
+ if (combo.callback?.(raw) === false) {
545
+ continue;
354
546
  }
355
547
  this.triggerAction(eventName, raw);
356
548
  }
@@ -359,8 +551,9 @@ class InputSystem {
359
551
  }
360
552
  isExactMatch(type, keys, combo, modifiers) {
361
553
  const isKeysMatch = arrEqual(keys, combo.keys);
362
- if (type !== combo.type || !isKeysMatch)
554
+ if (type !== combo.type || !isKeysMatch) {
363
555
  return false;
556
+ }
364
557
  if (isKeysMatch && (!combo.modifiers || !combo.modifiers.length)) {
365
558
  return true;
366
559
  }
@@ -397,7 +590,22 @@ class InputSystem {
397
590
  clientY: event.clientY,
398
591
  button: MouseButton.MIDDLE
399
592
  };
400
- this.checkCombinations(InputType.WHEEL, wheelData);
593
+ // Trackpad pinch supplies ctrlKey on the wheel event without a keydown.
594
+ // Keep these modifiers local to this event; never latch them into keys.
595
+ const modifiers = new Set();
596
+ if (event.ctrlKey) {
597
+ modifiers.add(ModifierKey.CTRL);
598
+ }
599
+ if (event.metaKey) {
600
+ modifiers.add(ModifierKey.META);
601
+ }
602
+ if (event.shiftKey) {
603
+ modifiers.add(ModifierKey.SHIFT);
604
+ }
605
+ if (event.altKey) {
606
+ modifiers.add(ModifierKey.ALT);
607
+ }
608
+ this.checkCombinations(InputType.WHEEL, wheelData, [...modifiers]);
401
609
  // Remove wheel key immediately as scrolling is continuous
402
610
  this.activeKeys.delete(key);
403
611
  }
@@ -456,9 +664,13 @@ class InputSystem {
456
664
  }
457
665
  clearTransientState() {
458
666
  this.listeners.clear();
667
+ if (this.ownsShortcuts) {
668
+ this.shortcuts.api.clearShortcuts();
669
+ }
459
670
  this.timers.forEach((timer) => clearTimeout(timer));
460
671
  this.timers.clear();
461
672
  this.activeKeys.clear();
673
+ this.heldKeyboardKeys.clear();
462
674
  this.combinations = {};
463
675
  this._startPos = null;
464
676
  this.pointerInputBlocked = false;
@@ -482,19 +694,25 @@ class InputSystem {
482
694
  failures.push(error);
483
695
  }
484
696
  };
485
- if (this.pointerTarget)
697
+ attempt(() => this.clearScope());
698
+ if (this.pointerTarget) {
486
699
  this.removePointerListeners(this.pointerTarget, attempt);
487
- if (this.browserHost)
700
+ }
701
+ if (this.browserHost) {
488
702
  this.removeKeyboardListeners(this.browserHost, attempt);
703
+ }
489
704
  this.pointerTarget = null;
490
705
  this.browserHost = null;
491
706
  this.browserListeners.clear();
492
707
  this.clearTransientState();
493
708
  this.registry.clear();
494
- if (failures.length > 0)
709
+ this.shortcuts.detach(this.registry);
710
+ if (failures.length > 0) {
495
711
  throw failures[0];
712
+ }
496
713
  }
497
714
  }
498
715
  export { InputSystem };
499
- const inputSystem = new InputSystem();
716
+ const connect = import.meta.connectShortcuts;
717
+ const inputSystem = new InputSystem(connect?.(createShortcutRegistry, bindToolInput));
500
718
  export default inputSystem;
package/dist/keymap.js CHANGED
@@ -16,10 +16,12 @@ export class KeyMap {
16
16
  navigator.platform ||
17
17
  '').toLowerCase();
18
18
  const userAgent = navigator.userAgent.toLowerCase();
19
- if (platform.includes('mac') || userAgent.includes('mac'))
19
+ if (platform.includes('mac') || userAgent.includes('mac')) {
20
20
  return Platforms.MAC;
21
- if (platform.includes('win') || userAgent.includes('win'))
21
+ }
22
+ if (platform.includes('win') || userAgent.includes('win')) {
22
23
  return Platforms.WINDOWS;
24
+ }
23
25
  return Platforms.LINUX;
24
26
  }
25
27
  createKeyMap() {
@@ -16,6 +16,12 @@ export declare class InputSystemRegistry {
16
16
  * Get all registered event names
17
17
  */
18
18
  getEventNames(): string[];
19
+ getKeyboardBindings(): {
20
+ eventName: string;
21
+ keys: string[];
22
+ modifiers: import("@asyra/utils").ModifierKey[];
23
+ mode: string;
24
+ }[];
19
25
  /**
20
26
  * Get combinations for a specific event
21
27
  * @param eventName - The event name
package/dist/registry.js CHANGED
@@ -1,4 +1,4 @@
1
- import { MapRegistry } from '@asyra/utils';
1
+ import { InputType, MapRegistry } from '@asyra/utils';
2
2
  export class InputSystemRegistry {
3
3
  mappings = new MapRegistry();
4
4
  /**
@@ -26,6 +26,16 @@ export class InputSystemRegistry {
26
26
  getEventNames() {
27
27
  return this.mappings.keys();
28
28
  }
29
+ getKeyboardBindings() {
30
+ return this.mappings.entries().flatMap(([eventName, combos]) => combos
31
+ .filter((combo) => combo.type === InputType.KEYBOARD)
32
+ .map((combo) => ({
33
+ eventName,
34
+ keys: [...combo.keys],
35
+ modifiers: [...(combo.modifiers ?? [])],
36
+ mode: combo.keyboardMode ?? 'chord'
37
+ })));
38
+ }
29
39
  /**
30
40
  * Get combinations for a specific event
31
41
  * @param eventName - The event name
@@ -0,0 +1,37 @@
1
+ import type { InputSystemRegistry } from './registry.js';
2
+ type Handler = (event: KeyboardEvent) => void | Promise<void>;
3
+ type Commands = Readonly<Record<string, Handler>>;
4
+ declare function chordKeys(chord: string): string[];
5
+ export declare function createShortcutRegistry(): {
6
+ api: {
7
+ registerShortcut: (chord: string, handler: Handler) => () => void;
8
+ registerShortcuts: (commands: Commands) => () => void;
9
+ overrideShortcut: (chord: string, handler: Handler) => () => void;
10
+ overrideShortcuts: (commands: Commands) => () => void;
11
+ unregisterShortcut: (chord: string) => () => void;
12
+ unregisterShortcuts: (chords: readonly string[]) => () => void;
13
+ clearShortcuts: () => void;
14
+ resetShortcut(chord: string): void;
15
+ getShortcut(chord: string): Handler | undefined;
16
+ hasShortcut(chord: string): boolean;
17
+ getShortcuts: () => {
18
+ shortcut: string;
19
+ handler: Handler | undefined;
20
+ }[];
21
+ getShortcutBindings: () => {
22
+ eventName: string;
23
+ keys: string[];
24
+ modifiers: import("@asyra/utils").ModifierKey[];
25
+ mode: string;
26
+ }[];
27
+ onShortcut(chord: string, handler: Handler): () => void;
28
+ offShortcut: (chord: string, handler: Handler) => boolean;
29
+ };
30
+ chordKeys: typeof chordKeys;
31
+ accepts: (event: KeyboardEvent) => boolean;
32
+ attach(registry: InputSystemRegistry): void;
33
+ detach(registry: InputSystemRegistry): void;
34
+ released: (code: string) => boolean;
35
+ dispose(): void;
36
+ };
37
+ export {};
@@ -0,0 +1,249 @@
1
+ import { MapRegistry, ModifierKeyList } from '@asyra/utils';
2
+ const modifierOrder = [...ModifierKeyList];
3
+ function chordKeys(chord) {
4
+ const parts = chord.split('+').map((part) => part.trim().toLowerCase());
5
+ let code = parts.pop() ?? '';
6
+ const mods = new Set(parts);
7
+ if (!/^[a-z][a-z0-9]*$|^[0-9]$/.test(code) ||
8
+ mods.size !== parts.length ||
9
+ parts.some((part) => part !== 'mod' && !modifierOrder.some((m) => m === part)) ||
10
+ (mods.has('mod') && (mods.has('meta') || mods.has('ctrl')))) {
11
+ throw new TypeError('Expected a physical code with optional modifiers, e.g. Mod+Shift+KeyZ');
12
+ }
13
+ if (/^[a-z]$/.test(code)) {
14
+ code = 'key' + code;
15
+ }
16
+ if (/^[0-9]$/.test(code)) {
17
+ code = 'digit' + code;
18
+ }
19
+ return (mods.has('mod') ? ['meta', 'ctrl'] : ['']).map((primary) => [...modifierOrder.filter((m) => mods.has(m) || m === primary), code].join('+'));
20
+ }
21
+ function report(error) {
22
+ globalThis.reportError(error);
23
+ }
24
+ function notify(handler, event) {
25
+ try {
26
+ const result = handler(event);
27
+ if (result) {
28
+ void Promise.resolve(result).catch(report);
29
+ }
30
+ }
31
+ catch (error) {
32
+ report(error);
33
+ }
34
+ }
35
+ // Host policy sits above the App's exact and held keyboard mappings.
36
+ // Removing an arbitrary layer must never resurrect a disposed handler.
37
+ export function createShortcutRegistry() {
38
+ const layers = new MapRegistry();
39
+ const listeners = new MapRegistry();
40
+ const released = new Set();
41
+ const handled = new WeakMap();
42
+ const sources = new Set();
43
+ let disposed = false;
44
+ function active() {
45
+ if (disposed) {
46
+ throw new Error('Shortcut registry is disposed');
47
+ }
48
+ }
49
+ function install(entries, override = false) {
50
+ active();
51
+ const pending = new MapRegistry();
52
+ for (const [chord, handler] of entries) {
53
+ for (const key of chordKeys(chord)) {
54
+ if (!override && layers.get(key)?.at(-1)?.handler) {
55
+ throw new Error('Shortcut already registered: ' + chord);
56
+ }
57
+ pending.register(key, { handler });
58
+ }
59
+ }
60
+ for (const [key, layer] of pending.entries()) {
61
+ const stack = layers.get(key) ?? [];
62
+ stack.push(layer);
63
+ layers.set(key, stack);
64
+ }
65
+ return () => {
66
+ for (const [key, layer] of pending.entries()) {
67
+ const stack = layers.get(key);
68
+ if (!stack) {
69
+ continue;
70
+ }
71
+ const index = stack.indexOf(layer);
72
+ if (index >= 0) {
73
+ stack.splice(index, 1);
74
+ }
75
+ if (!stack.length) {
76
+ layers.delete(key);
77
+ }
78
+ }
79
+ pending.clear();
80
+ };
81
+ }
82
+ function register(commands, override = false) {
83
+ const entries = Object.entries(commands);
84
+ if (entries.some(([, handler]) => typeof handler !== 'function')) {
85
+ throw new TypeError('Expected a shortcut handler');
86
+ }
87
+ return install(entries, override);
88
+ }
89
+ function offShortcut(chord, handler) {
90
+ let removed = false;
91
+ for (const key of chordKeys(chord)) {
92
+ const set = listeners.get(key);
93
+ if (set) {
94
+ for (const entry of set) {
95
+ if (entry.handler === handler) {
96
+ set.delete(entry);
97
+ removed = true;
98
+ break;
99
+ }
100
+ }
101
+ }
102
+ if (!set?.size) {
103
+ listeners.delete(key);
104
+ }
105
+ }
106
+ return removed;
107
+ }
108
+ function clearShortcuts() {
109
+ layers.clear();
110
+ listeners.clear();
111
+ }
112
+ const api = {
113
+ registerShortcut: (chord, handler) => register({ [chord]: handler }),
114
+ registerShortcuts: (commands) => register(commands),
115
+ overrideShortcut: (chord, handler) => register({ [chord]: handler }, true),
116
+ overrideShortcuts: (commands) => register(commands, true),
117
+ unregisterShortcut: (chord) => install([[chord, undefined]], true),
118
+ unregisterShortcuts: (chords) => install(chords.map((chord) => [chord, undefined]), true),
119
+ clearShortcuts,
120
+ resetShortcut(chord) {
121
+ active();
122
+ for (const key of chordKeys(chord)) {
123
+ layers.delete(key);
124
+ }
125
+ },
126
+ getShortcut(chord) {
127
+ const handlers = chordKeys(chord).map((key) => layers.get(key)?.at(-1)?.handler);
128
+ return handlers.every((handler) => handler === handlers[0])
129
+ ? handlers[0]
130
+ : undefined;
131
+ },
132
+ hasShortcut(chord) {
133
+ return chordKeys(chord).every((key) => !!layers.get(key)?.at(-1)?.handler);
134
+ },
135
+ getShortcuts: () => layers.entries().map(([shortcut, stack]) => ({
136
+ shortcut,
137
+ handler: stack.at(-1)?.handler
138
+ })),
139
+ getShortcutBindings: () => Array.from(sources)[0]?.getKeyboardBindings() ?? [],
140
+ onShortcut(chord, handler) {
141
+ active();
142
+ if (typeof handler !== 'function') {
143
+ throw new TypeError('Expected a shortcut listener');
144
+ }
145
+ const entry = { handler };
146
+ const sets = chordKeys(chord).map((key) => {
147
+ const set = listeners.get(key) ?? new Set();
148
+ listeners.set(key, set);
149
+ set.add(entry);
150
+ return { key, set };
151
+ });
152
+ return () => {
153
+ for (const { key, set } of sets) {
154
+ set.delete(entry);
155
+ if (!set.size && listeners.get(key) === set) {
156
+ listeners.delete(key);
157
+ }
158
+ }
159
+ };
160
+ },
161
+ offShortcut
162
+ };
163
+ function accepts(event) {
164
+ if (disposed) {
165
+ return false;
166
+ }
167
+ const admission = handled.get(event);
168
+ if (admission !== undefined) {
169
+ return admission;
170
+ }
171
+ if (event.type === 'keyup') {
172
+ return !released.delete(event.code);
173
+ }
174
+ if (!event.repeat) {
175
+ released.delete(event.code);
176
+ }
177
+ if (released.has(event.code)) {
178
+ return false;
179
+ }
180
+ if (!layers.size() && !listeners.size()) {
181
+ return true;
182
+ }
183
+ const pressed = {
184
+ ctrl: event.ctrlKey,
185
+ meta: event.metaKey,
186
+ alt: event.altKey,
187
+ shift: event.shiftKey
188
+ };
189
+ const key = [
190
+ ...modifierOrder.filter((m) => pressed[m]),
191
+ event.code.toLowerCase()
192
+ ].join('+');
193
+ const layer = layers.get(key)?.at(-1);
194
+ const observers = listeners.get(key);
195
+ if (!layer && !observers) {
196
+ return true;
197
+ }
198
+ handled.set(event, false);
199
+ const origin = event.composedPath()[0] ?? event.target;
200
+ const skip = event.defaultPrevented ||
201
+ event.isComposing ||
202
+ event.keyCode === 229 ||
203
+ (origin instanceof HTMLElement &&
204
+ (origin.isContentEditable ||
205
+ origin.closest('input,textarea,select,[role="textbox"],[role="dialog"],dialog[open]')));
206
+ if (skip) {
207
+ return false;
208
+ }
209
+ if (layer) {
210
+ released.add(event.code);
211
+ if (layer.handler) {
212
+ event.preventDefault();
213
+ }
214
+ }
215
+ if (!event.repeat) {
216
+ if (observers) {
217
+ for (const listener of [...observers]) {
218
+ notify(listener.handler, event);
219
+ }
220
+ }
221
+ if (layer?.handler) {
222
+ notify(layer.handler, event);
223
+ }
224
+ }
225
+ handled.set(event, !layer);
226
+ return !layer;
227
+ }
228
+ return {
229
+ api,
230
+ chordKeys,
231
+ accepts,
232
+ attach(registry) {
233
+ sources.add(registry);
234
+ },
235
+ detach(registry) {
236
+ sources.delete(registry);
237
+ if (!sources.size) {
238
+ released.clear();
239
+ }
240
+ },
241
+ released: (code) => released.has(code),
242
+ dispose() {
243
+ disposed = true;
244
+ sources.clear();
245
+ clearShortcuts();
246
+ released.clear();
247
+ }
248
+ };
249
+ }
@@ -1 +1,3 @@
1
+ import { type InputSystem } from './input-system.js';
2
+ export declare function requestInputAttachment(input: InputSystem, element: HTMLElement, interactionOwner?: symbol, keyboardTarget?: HTMLElement): void;
1
3
  export declare const initInputSystemSubscribe: () => void;
package/dist/subscribe.js CHANGED
@@ -1,19 +1,45 @@
1
- import { subscribeToSwitchInputSystemWatchedElement, subscribeToRenderPointerCaptureStart, subscribeToRenderPointerCaptureEnd } from '@asyra/reactive-events';
1
+ import { EventTypes, subscribeToSynchronousEvent, switchInputSystemWatchedElement, subscribeToRenderPointerCaptureStart, subscribeToRenderPointerCaptureEnd } from '@asyra/reactive-events';
2
+ import { captureOwner } from './input-scope.js';
2
3
  import inputSystem from './input-system.js';
4
+ // The event may be replayed to observers. Only the synchronous owner can
5
+ // resolve the request, and the bus never retains a reference to the editor.
6
+ const pending = new Map();
7
+ export function requestInputAttachment(input, element, interactionOwner, keyboardTarget) {
8
+ const request = Symbol('input-attachment');
9
+ pending.set(request, (target) => input.switchWatchedElement(target, interactionOwner, keyboardTarget));
10
+ try {
11
+ switchInputSystemWatchedElement(element, request);
12
+ }
13
+ finally {
14
+ pending.delete(request);
15
+ }
16
+ }
3
17
  export const initInputSystemSubscribe = () => {
4
- subscribeToSwitchInputSystemWatchedElement(({ payload }) => {
5
- inputSystem.switchWatchedElement(payload.watchedElement);
18
+ subscribeToSynchronousEvent(EventTypes.SWITCH_INPUT_SYSTEM_WATCHED_ELEMENT, ({ payload }) => {
19
+ if (payload.request) {
20
+ pending.get(payload.request)?.(payload.watchedElement);
21
+ }
22
+ else {
23
+ inputSystem.switchWatchedElement(payload.watchedElement);
24
+ }
25
+ return false;
6
26
  });
7
- subscribeToRenderPointerCaptureStart(({ payload }) => {
27
+ subscribeToRenderPointerCaptureStart(({ payload, interactionOwner }) => {
8
28
  if (!payload.blockInput) {
9
29
  return;
10
30
  }
11
- inputSystem.setPointerCaptureBlock(true, payload.targetId);
31
+ const target = interactionOwner
32
+ ? captureOwner(interactionOwner)
33
+ : inputSystem;
34
+ target?.setPointerCaptureBlock(true, payload.targetId);
12
35
  });
13
- subscribeToRenderPointerCaptureEnd(({ payload }) => {
36
+ subscribeToRenderPointerCaptureEnd(({ payload, interactionOwner }) => {
14
37
  if (!payload.blockInput) {
15
38
  return;
16
39
  }
17
- inputSystem.setPointerCaptureBlock(false, payload.targetId);
40
+ const target = interactionOwner
41
+ ? captureOwner(interactionOwner)
42
+ : inputSystem;
43
+ target?.setPointerCaptureBlock(false, payload.targetId);
18
44
  });
19
45
  };
@@ -0,0 +1,8 @@
1
+ interface ToolInput {
2
+ active(): boolean;
3
+ dispatch(event: PointerEvent, x: number, y: number): void;
4
+ cancel(): void;
5
+ }
6
+ /** Claim only primary gestures beginning on the supplied editor surface. */
7
+ export declare function bindToolInput(host: HTMLElement, surface: HTMLElement, signal: AbortSignal, owner: ToolInput): () => void;
8
+ export {};
@@ -0,0 +1,62 @@
1
+ /** Claim only primary gestures beginning on the supplied editor surface. */
2
+ export function bindToolInput(host, surface, signal, owner) {
3
+ let pointer;
4
+ function cancel() {
5
+ if (pointer === undefined) {
6
+ return;
7
+ }
8
+ const id = pointer;
9
+ pointer = undefined;
10
+ if (surface.hasPointerCapture(id)) {
11
+ surface.releasePointerCapture(id);
12
+ }
13
+ owner.cancel();
14
+ }
15
+ function route(event) {
16
+ if (!event.isPrimary) {
17
+ return;
18
+ }
19
+ if (event.type === 'pointerdown') {
20
+ if (!owner.active() ||
21
+ event.button !== 0 ||
22
+ !event.composedPath().includes(surface)) {
23
+ return;
24
+ }
25
+ pointer = event.pointerId;
26
+ surface.focus({ preventScroll: true });
27
+ surface.setPointerCapture(pointer);
28
+ }
29
+ else if (event.pointerId !== pointer) {
30
+ return;
31
+ }
32
+ event.preventDefault();
33
+ event.stopImmediatePropagation();
34
+ if (event.type === 'pointercancel' || event.type === 'lostpointercapture') {
35
+ cancel();
36
+ return;
37
+ }
38
+ const rect = surface.getBoundingClientRect();
39
+ if (event.type === 'pointerup') {
40
+ pointer = undefined;
41
+ }
42
+ try {
43
+ owner.dispatch(event, event.clientX - rect.left, event.clientY - rect.top);
44
+ }
45
+ catch (error) {
46
+ cancel();
47
+ throw error;
48
+ }
49
+ }
50
+ for (const type of [
51
+ 'pointerdown',
52
+ 'pointermove',
53
+ 'pointerup',
54
+ 'pointercancel',
55
+ 'lostpointercapture'
56
+ ]) {
57
+ host.addEventListener(type, route, { capture: true, signal });
58
+ }
59
+ host.ownerDocument.defaultView?.addEventListener('blur', cancel, { signal });
60
+ signal.addEventListener('abort', cancel, { once: true });
61
+ return cancel;
62
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asyra/input-system",
3
- "version": "0.5.5",
3
+ "version": "0.6.1",
4
4
  "description": "Keyboard and Mouse event listener plugin",
5
5
  "author": "Asa Tsai",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/karote00/asyra.git",
10
10
  "directory": "packages/input-system"
11
11
  },
12
- "homepage": "https://asyra-framework.vercel.app",
12
+ "homepage": "https://asyra-framework.pages.dev",
13
13
  "type": "module",
14
14
  "engines": {
15
15
  "node": "24.x"
@@ -38,7 +38,7 @@
38
38
  "has:test": "find . -type f \\( -name \"*.test.ts\" -o -name \"*.test.tsx\" \\) | grep -q .",
39
39
  "test": "yarn has:test && vitest || echo 'No test files found. Skipping test.'",
40
40
  "test:local": "vitest run",
41
- "test:ci": "yarn has:test && vitest run --coverage --reporter=default --reporter=junit || echo 'No test files found. Skipping test:ci.'"
41
+ "test:ci": "yarn has:test && vitest run --coverage --reporter=default --reporter=junit"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@vitest/coverage-v8": "^3.2.6",
@@ -46,7 +46,7 @@
46
46
  "vitest": "^3.2.6"
47
47
  },
48
48
  "dependencies": {
49
- "@asyra/reactive-events": "0.5.4",
50
- "@asyra/utils": "0.5.2"
49
+ "@asyra/reactive-events": "0.6.1",
50
+ "@asyra/utils": "0.6.1"
51
51
  }
52
52
  }