@asyra/input-system 0.6.0 → 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/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,3 +1,4 @@
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>;
@@ -15,10 +16,14 @@ declare class InputSystem {
15
16
  private pointerInputBlocked;
16
17
  private pointerCaptureId;
17
18
  registry: InputSystemRegistry;
19
+ private releaseScope?;
18
20
  private runtimeGeneration;
19
21
  private browserListeners;
20
- constructor();
22
+ readonly shortcuts: ReturnType<typeof createShortcutRegistry>;
23
+ private readonly ownsShortcuts;
24
+ constructor(shortcuts?: ReturnType<typeof createShortcutRegistry>);
21
25
  attachBrowserHost(host: Window, pointerTarget?: Window | HTMLElement): void;
26
+ private clearScope;
22
27
  detachBrowserHost(): void;
23
28
  private addKeyboardListeners;
24
29
  private removeKeyboardListeners;
@@ -30,7 +35,7 @@ declare class InputSystem {
30
35
  setCombinations(combinations: Combinations): void;
31
36
  on(action: string, callback: Callback): this;
32
37
  off(action: string, callback: Callback): boolean;
33
- switchWatchedElement(watchedElement: HTMLElement): void;
38
+ switchWatchedElement(watchedElement: HTMLElement, interactionOwner?: symbol, keyboardTarget?: HTMLElement): void;
34
39
  private startTimer;
35
40
  private clearTimer;
36
41
  private _isInputActive;
@@ -40,7 +45,8 @@ declare class InputSystem {
40
45
  private handleKeyUp;
41
46
  private hasHeldInterest;
42
47
  private dispatchHeldKeyboard;
43
- private cancelHeldKeyboard;
48
+ private cancelKeyboard;
49
+ private synchronizeModifiers;
44
50
  private hiddenKeyboard;
45
51
  private handleMouseDown;
46
52
  private handleMouseUp;
@@ -1,8 +1,11 @@
1
+ import { bindToolInput } from './tool-input.js';
2
+ import { createShortcutRegistry } from './shortcuts.js';
1
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));
@@ -43,9 +46,14 @@ class InputSystem {
43
46
  pointerInputBlocked;
44
47
  pointerCaptureId;
45
48
  registry;
49
+ releaseScope;
46
50
  runtimeGeneration = 0;
47
51
  browserListeners = new Map();
48
- constructor() {
52
+ shortcuts;
53
+ ownsShortcuts;
54
+ constructor(shortcuts) {
55
+ this.ownsShortcuts = !shortcuts;
56
+ this.shortcuts = shortcuts ?? createShortcutRegistry();
49
57
  this.browserHost = null;
50
58
  this.pointerTarget = null;
51
59
  this.keyMap = keymap;
@@ -56,11 +64,14 @@ class InputSystem {
56
64
  this.pointerInputBlocked = false;
57
65
  this.pointerCaptureId = null;
58
66
  this.registry = new InputSystemRegistry();
67
+ this.shortcuts.attach(this.registry);
59
68
  }
60
69
  attachBrowserHost(host, pointerTarget = host) {
61
70
  if (this.browserHost === host && this.pointerTarget === pointerTarget) {
62
71
  return;
63
72
  }
73
+ this.shortcuts.attach(this.registry);
74
+ this.clearScope();
64
75
  if (this.pointerTarget && this.pointerTarget !== pointerTarget) {
65
76
  this.removePointerListeners(this.pointerTarget);
66
77
  this.pointerTarget = null;
@@ -78,7 +89,18 @@ class InputSystem {
78
89
  this.pointerTarget = pointerTarget;
79
90
  }
80
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
+ }
81
101
  detachBrowserHost() {
102
+ this.shortcuts.detach(this.registry);
103
+ this.clearScope();
82
104
  if (this.pointerTarget) {
83
105
  this.removePointerListeners(this.pointerTarget);
84
106
  this.pointerTarget = null;
@@ -95,7 +117,7 @@ class InputSystem {
95
117
  removeKeyboardListeners(host, attempt = (cleanup) => cleanup()) {
96
118
  this.keyboardBindings().forEach((binding) => attempt(() => host.removeEventListener(...binding)));
97
119
  attempt(() => host.document.removeEventListener('visibilitychange', this.browserListener(this.hiddenKeyboard)));
98
- attempt(this.cancelHeldKeyboard);
120
+ attempt(this.cancelKeyboard);
99
121
  }
100
122
  addPointerListeners(target) {
101
123
  this.pointerBindings().forEach((binding) => target.addEventListener(...binding));
@@ -108,9 +130,10 @@ class InputSystem {
108
130
  ['keydown', this.browserListener(this.handleKeyDown)],
109
131
  ['keyup', this.browserListener(this.releaseKey), true],
110
132
  ['keyup', this.browserListener(this.handleKeyUp)],
111
- ['blur', this.browserListener(this.cancelHeldKeyboard)],
112
- ['focusin', this.browserListener(this.cancelHeldKeyboard)],
113
- ['compositionstart', this.browserListener(this.cancelHeldKeyboard)]
133
+ ['blur', this.browserListener(this.cancelKeyboard)],
134
+ ['focus', this.browserListener(this.cancelKeyboard)],
135
+ ['focusin', this.browserListener(this.cancelKeyboard)],
136
+ ['compositionstart', this.browserListener(this.cancelKeyboard)]
114
137
  ];
115
138
  }
116
139
  pointerBindings() {
@@ -142,6 +165,20 @@ class InputSystem {
142
165
  }
143
166
  const generation = this.runtimeGeneration;
144
167
  const guarded = (event) => {
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
+ }
145
182
  if (generation === this.runtimeGeneration) {
146
183
  listener(event);
147
184
  }
@@ -174,12 +211,16 @@ class InputSystem {
174
211
  }
175
212
  return true;
176
213
  }
177
- switchWatchedElement(watchedElement) {
214
+ switchWatchedElement(watchedElement, interactionOwner, keyboardTarget) {
178
215
  const host = watchedElement.ownerDocument.defaultView;
179
216
  if (!host) {
180
217
  throw new Error('[InputSystem] Watched element must belong to a document with a Window');
181
218
  }
219
+ this.clearScope();
182
220
  this.attachBrowserHost(host, watchedElement);
221
+ if (interactionOwner || keyboardTarget) {
222
+ this.releaseScope = attachInputScope(this, keyboardTarget ?? watchedElement, interactionOwner);
223
+ }
183
224
  }
184
225
  startTimer(key) {
185
226
  if (this.timers.has(key)) {
@@ -208,7 +249,9 @@ class InputSystem {
208
249
  }
209
250
  }
210
251
  _isInputActive(event) {
211
- 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);
212
255
  }
213
256
  _hasTriggerBrowserShortcut(event) {
214
257
  const hasMeta = this.activeKeys.has('Meta');
@@ -217,10 +260,14 @@ class InputSystem {
217
260
  return hasMeta && hasNumber;
218
261
  }
219
262
  handleKeyDown = (event) => {
263
+ if (!this.shortcuts.accepts(event)) {
264
+ return;
265
+ }
266
+ this.synchronizeModifiers(event);
220
267
  const key = this.keyMap.mapKey(event.code);
221
268
  const interested = this.hasHeldInterest(key);
222
269
  if (event.isComposing) {
223
- this.cancelHeldKeyboard();
270
+ this.cancelKeyboard();
224
271
  }
225
272
  else {
226
273
  if (key && !this.keyMap.isModifierKeys(key)) {
@@ -245,17 +292,23 @@ class InputSystem {
245
292
  // Release bookkeeping must survive editors stopping event propagation.
246
293
  // Capture publishes opted-in held releases only; ordinary chord dispatch stays in bubble phase.
247
294
  releaseKey = (event, notifyHeld = true) => {
295
+ this.synchronizeModifiers(event);
248
296
  const key = this.keyMap.mapKey(event.code);
249
297
  if (key) {
250
- this.activeKeys.delete(key);
298
+ if (!this.keyMap.isModifierKeys(key)) {
299
+ this.activeKeys.delete(key);
300
+ }
251
301
  this.clearTimer(key);
252
- if (notifyHeld) {
302
+ if (notifyHeld && !this.shortcuts.released(event.code)) {
253
303
  this.heldKeyboardKeys.delete(key);
254
304
  this.dispatchHeldKeyboard(event, key, 'up');
255
305
  }
256
306
  }
257
307
  };
258
308
  handleKeyUp = (event) => {
309
+ if (!this.shortcuts.accepts(event)) {
310
+ return;
311
+ }
259
312
  if (!this.hasHeldInterest(this.keyMap.mapKey(event.code)) &&
260
313
  (!this._isInputActive(event) || this._hasTriggerBrowserShortcut(event))) {
261
314
  event.preventDefault();
@@ -290,7 +343,7 @@ class InputSystem {
290
343
  keyboard: {
291
344
  phase,
292
345
  changedKey: key ?? null,
293
- target: event?.target ?? null,
346
+ target: event?.composedPath?.()[0] ?? event?.target ?? null,
294
347
  repeat: event?.repeat ?? false,
295
348
  isComposing: event?.isComposing ?? false
296
349
  }
@@ -320,19 +373,45 @@ class InputSystem {
320
373
  }
321
374
  return accepted;
322
375
  }
323
- cancelHeldKeyboard = () => {
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
+ }
324
383
  if (!this.heldKeyboardKeys.size) {
325
384
  return;
326
385
  }
327
386
  this.heldKeyboardKeys.clear();
328
387
  this.dispatchHeldKeyboard(null, undefined, 'cancel');
329
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
+ }
330
408
  hiddenKeyboard = () => {
331
409
  if (this.browserHost?.document.hidden) {
332
- this.cancelHeldKeyboard();
410
+ this.cancelKeyboard();
333
411
  }
334
412
  };
335
413
  handleMouseDown = (event) => {
414
+ this.synchronizeModifiers(event);
336
415
  if (this.pointerInputBlocked) {
337
416
  return;
338
417
  }
@@ -347,11 +426,13 @@ class InputSystem {
347
426
  this.checkCombinations(InputType.POINTER, {
348
427
  ...DefaultPointerEventData,
349
428
  ...this._startPos,
429
+ clickCount: event.detail,
350
430
  button
351
431
  });
352
432
  }
353
433
  };
354
434
  handleMouseUp = (event) => {
435
+ this.synchronizeModifiers(event);
355
436
  if (this.pointerInputBlocked) {
356
437
  return;
357
438
  }
@@ -364,6 +445,7 @@ class InputSystem {
364
445
  ...DefaultPointerEventData,
365
446
  clientX: event.clientX,
366
447
  clientY: event.clientY,
448
+ clickCount: event.detail,
367
449
  button
368
450
  });
369
451
  // No need to keep mouse up key after trigger action
@@ -371,6 +453,7 @@ class InputSystem {
371
453
  }
372
454
  };
373
455
  handleMouseMove = (event) => {
456
+ this.synchronizeModifiers(event);
374
457
  if (this.pointerInputBlocked) {
375
458
  return;
376
459
  }
@@ -403,6 +486,7 @@ class InputSystem {
403
486
  }
404
487
  };
405
488
  handleDoubleClick = (event) => {
489
+ this.synchronizeModifiers(event);
406
490
  if (this.pointerInputBlocked) {
407
491
  return;
408
492
  }
@@ -412,6 +496,7 @@ class InputSystem {
412
496
  ...DefaultPointerEventData,
413
497
  clientX: event.clientX,
414
498
  clientY: event.clientY,
499
+ clickCount: event.detail,
415
500
  button
416
501
  });
417
502
  this.activeKeys.delete(PointerKey.MOUSE_DOUBLE_CLICK);
@@ -507,7 +592,7 @@ class InputSystem {
507
592
  };
508
593
  // Trackpad pinch supplies ctrlKey on the wheel event without a keydown.
509
594
  // Keep these modifiers local to this event; never latch them into keys.
510
- const modifiers = new Set(this.getActiveModifiers(this.activeKeys));
595
+ const modifiers = new Set();
511
596
  if (event.ctrlKey) {
512
597
  modifiers.add(ModifierKey.CTRL);
513
598
  }
@@ -579,6 +664,9 @@ class InputSystem {
579
664
  }
580
665
  clearTransientState() {
581
666
  this.listeners.clear();
667
+ if (this.ownsShortcuts) {
668
+ this.shortcuts.api.clearShortcuts();
669
+ }
582
670
  this.timers.forEach((timer) => clearTimeout(timer));
583
671
  this.timers.clear();
584
672
  this.activeKeys.clear();
@@ -606,6 +694,7 @@ class InputSystem {
606
694
  failures.push(error);
607
695
  }
608
696
  };
697
+ attempt(() => this.clearScope());
609
698
  if (this.pointerTarget) {
610
699
  this.removePointerListeners(this.pointerTarget, attempt);
611
700
  }
@@ -617,11 +706,13 @@ class InputSystem {
617
706
  this.browserListeners.clear();
618
707
  this.clearTransientState();
619
708
  this.registry.clear();
709
+ this.shortcuts.detach(this.registry);
620
710
  if (failures.length > 0) {
621
711
  throw failures[0];
622
712
  }
623
713
  }
624
714
  }
625
715
  export { InputSystem };
626
- const inputSystem = new InputSystem();
716
+ const connect = import.meta.connectShortcuts;
717
+ const inputSystem = new InputSystem(connect?.(createShortcutRegistry, bindToolInput));
627
718
  export default inputSystem;
@@ -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.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Keyboard and Mouse event listener plugin",
5
5
  "author": "Asa Tsai",
6
6
  "license": "MIT",
@@ -46,7 +46,7 @@
46
46
  "vitest": "^3.2.6"
47
47
  },
48
48
  "dependencies": {
49
- "@asyra/reactive-events": "0.6.0",
50
- "@asyra/utils": "0.6.0"
49
+ "@asyra/reactive-events": "0.6.1",
50
+ "@asyra/utils": "0.6.1"
51
51
  }
52
52
  }