@tooee/commands 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +26 -1
  2. package/dist/build-context.d.ts +3 -12
  3. package/dist/build-context.d.ts.map +1 -1
  4. package/dist/build-context.js +6 -17
  5. package/dist/build-context.js.map +1 -1
  6. package/dist/command-store-wrapper.d.ts +28 -0
  7. package/dist/command-store-wrapper.d.ts.map +1 -0
  8. package/dist/command-store-wrapper.js +115 -0
  9. package/dist/command-store-wrapper.js.map +1 -0
  10. package/dist/command-store.d.ts +2 -65
  11. package/dist/command-store.d.ts.map +1 -1
  12. package/dist/command-store.js +1 -345
  13. package/dist/command-store.js.map +1 -1
  14. package/dist/context.d.ts +9 -4
  15. package/dist/context.d.ts.map +1 -1
  16. package/dist/context.js +59 -50
  17. package/dist/context.js.map +1 -1
  18. package/dist/hooks/use-latest.d.ts +4 -0
  19. package/dist/hooks/use-latest.d.ts.map +1 -0
  20. package/dist/hooks/use-latest.js +8 -0
  21. package/dist/hooks/use-latest.js.map +1 -0
  22. package/dist/hooks/use-lazy-ref.d.ts +4 -0
  23. package/dist/hooks/use-lazy-ref.d.ts.map +1 -0
  24. package/dist/hooks/use-lazy-ref.js +8 -0
  25. package/dist/hooks/use-lazy-ref.js.map +1 -0
  26. package/dist/index.d.ts +7 -7
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +7 -4
  29. package/dist/index.js.map +1 -1
  30. package/dist/key-dispatch.d.ts +24 -0
  31. package/dist/key-dispatch.d.ts.map +1 -0
  32. package/dist/key-dispatch.js +159 -0
  33. package/dist/key-dispatch.js.map +1 -0
  34. package/dist/parse.js +10 -10
  35. package/dist/parse.js.map +1 -1
  36. package/dist/store.d.ts +9 -0
  37. package/dist/store.d.ts.map +1 -0
  38. package/dist/store.js +5 -0
  39. package/dist/store.js.map +1 -0
  40. package/dist/types.d.ts +6 -5
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/use-actions.d.ts.map +1 -1
  43. package/dist/use-actions.js +3 -1
  44. package/dist/use-actions.js.map +1 -1
  45. package/dist/use-command.d.ts.map +1 -1
  46. package/dist/use-command.js +3 -1
  47. package/dist/use-command.js.map +1 -1
  48. package/package.json +8 -1
  49. package/src/build-context.ts +7 -18
  50. package/src/command-store-wrapper.ts +149 -0
  51. package/src/command-store.ts +1 -491
  52. package/src/context.tsx +78 -65
  53. package/src/hooks/use-latest.ts +9 -0
  54. package/src/hooks/use-lazy-ref.ts +9 -0
  55. package/src/index.ts +8 -21
  56. package/src/key-dispatch.ts +272 -0
  57. package/src/parse.ts +10 -10
  58. package/src/store.ts +12 -0
  59. package/src/types.ts +6 -5
  60. package/src/use-actions.ts +3 -1
  61. package/src/use-command.ts +3 -1
package/src/context.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, useContext, useRef, useCallback, useEffect, useMemo } from "react";
1
+ import { createContext, useContext, useCallback, useEffect, useMemo } from "react";
2
2
  import type { ReactNode } from "react";
3
3
  import { useKeyboard } from "@opentui/react";
4
4
  import { useSelector } from "@xstate/store-react";
@@ -17,21 +17,24 @@ import { ModeProvider, useMode, useSetMode } from "./mode.js";
17
17
  import { parseHotkey } from "./parse.js";
18
18
  import {
19
19
  ROOT_SURFACE_ID,
20
- createCommandStore,
21
20
  selectActivePanelSurface,
22
21
  selectKeyboardOwnerSurface,
23
22
  selectSequence,
24
23
  selectSurfaceCommandMap,
25
24
  stepsKey,
26
25
  } from "./command-store.js";
27
- import type { CommandStore, ContextGetter, SurfaceRecord } from "./command-store.js";
26
+ import type { ContextGetter, SurfaceRecord } from "./command-store.js";
27
+ import { createCommandStore } from "./command-store-wrapper.js";
28
+ import type { CommandStore } from "./command-store-wrapper.js";
28
29
  import { buildCommandContext, commandsFromRegistry } from "./build-context.js";
30
+ import { useLatest } from "./hooks/use-latest.js";
31
+ import { useLazyRef } from "./hooks/use-lazy-ref.js";
29
32
 
30
33
  interface CommandContextValue {
31
34
  registry: CommandRegistry;
32
35
  leaderKey?: string;
33
- contextSources: Map<string, ContextGetter>;
34
- groups: Map<string, RegisteredCommandGroup>;
36
+ contextSources: ReadonlyMap<string, ContextGetter>;
37
+ groups: ReadonlyMap<string, RegisteredCommandGroup>;
35
38
  }
36
39
 
37
40
  /** Internal provider value: the store plus the surface this subtree registers to. */
@@ -54,9 +57,16 @@ const CommandSurfaceDepthContext = createContext(0);
54
57
  */
55
58
  const placeholderCommandContext = function placeholderCommandContext(mode: Mode): CommandContext {
56
59
  return buildCommandContext({
57
- commands: { invoke: () => void 0, list: () => [] },
60
+ commands: {
61
+ invoke: () => {
62
+ // Placeholder: no dispatcher is mounted yet.
63
+ },
64
+ list: () => [],
65
+ },
58
66
  mode,
59
- setMode: () => void 0,
67
+ setMode: () => {
68
+ // Placeholder: no dispatcher is mounted yet.
69
+ },
60
70
  });
61
71
  };
62
72
 
@@ -94,23 +104,24 @@ export const CommandProvider = function CommandProvider({
94
104
  // The store is created here (above the root ModeProvider) so mode changes
95
105
  // can be routed into it as transitions; the dispatcher below installs the
96
106
  // real root accessors before any key can dispatch.
97
- const rootAccessRef = useRef<RootAccess>({
107
+ const rootAccessRef = useLazyRef<RootAccess>(() => ({
98
108
  // Placeholder until CommandDispatcher installs the real accessors on its
99
109
  // first render (before any key can dispatch).
100
110
  buildCtx: () => placeholderCommandContext(initialMode ?? "cursor"),
101
111
  getMode: () => initialMode ?? "cursor",
102
- });
103
-
104
- const storeRef = useRef<CommandStore | null>(null);
105
- storeRef.current ??= createCommandStore({
106
- keymap,
107
- leader,
108
- root: {
109
- buildCtx: () => rootAccessRef.current.buildCtx(),
110
- getMode: () => rootAccessRef.current.getMode(),
111
- },
112
- sequenceTimeoutMs,
113
- });
112
+ }));
113
+
114
+ const storeRef = useLazyRef(() =>
115
+ createCommandStore({
116
+ keymap,
117
+ leader,
118
+ root: {
119
+ buildCtx: () => rootAccessRef.current.buildCtx(),
120
+ getMode: () => rootAccessRef.current.getMode(),
121
+ },
122
+ sequenceTimeoutMs,
123
+ }),
124
+ );
114
125
  const commandStore = storeRef.current;
115
126
 
116
127
  // Root mode changes are transitions: reset any pending chord synchronously
@@ -136,7 +147,7 @@ export const CommandProvider = function CommandProvider({
136
147
  );
137
148
  };
138
149
 
139
- // Deferred(lint-sweep): preserve the top-down provider/dispatcher organization.
150
+ // preserve the top-down provider/dispatcher organization.
140
151
  // oxlint-disable-next-line no-use-before-define -- provider deliberately renders its dispatcher below
141
152
  const CommandDispatcher = function CommandDispatcher({
142
153
  children,
@@ -154,8 +165,7 @@ const CommandDispatcher = function CommandDispatcher({
154
165
  sequenceTimeoutMs?: number;
155
166
  }): ReactNode {
156
167
  const mode = useMode();
157
- const modeRef = useRef(mode);
158
- modeRef.current = mode;
168
+ const modeRef = useLatest(mode);
159
169
  const setMode = useSetMode();
160
170
 
161
171
  const buildCtx = useCallback(
@@ -166,11 +176,10 @@ const CommandDispatcher = function CommandDispatcher({
166
176
  mode: modeRef.current,
167
177
  setMode,
168
178
  }),
169
- [commandStore, setMode],
179
+ [commandStore, modeRef, setMode],
170
180
  );
171
181
 
172
- const buildCtxRef = useRef(buildCtx);
173
- buildCtxRef.current = buildCtx;
182
+ const buildCtxRef = useLatest(buildCtx);
174
183
 
175
184
  // Install the live root accessors and config (ref writes, same pattern as
176
185
  // the previous modeRef mirrors; leader/keymap are read per dispatch).
@@ -261,7 +270,7 @@ export const CommandSurfaceProvider = function CommandSurfaceProvider({
261
270
 
262
271
  return (
263
272
  <ModeProvider initialMode={initialMode} onModeChange={handleModeChange}>
264
- {/* Deferred(lint-sweep): preserve top-down provider/wrapper organization. */}
273
+ {/* preserve top-down provider/wrapper organization. */}
265
274
  {/* oxlint-disable-next-line no-use-before-define -- inner surface is deliberately declared below */}
266
275
  <CommandSurfaceInner id={id} role={role} groupId={groupId}>
267
276
  {children}
@@ -293,27 +302,32 @@ const CommandSurfaceInner = function CommandSurfaceInner({
293
302
 
294
303
  const mode = useMode();
295
304
  const setMode = useSetMode();
296
- const modeRef = useRef(mode);
297
- modeRef.current = mode;
298
-
299
- const buildCtx = useCallback((): CommandContext => {
300
- // Deferred(lint-sweep): replace this lifecycle ref with an API that models render-time initialization.
301
- // oxlint-disable-next-line typescript/no-non-null-assertion, no-use-before-define -- initialized lifecycle ref intentionally captured by closure
302
- const registry = commandStore.registryFor(recordRef.current!);
305
+ const modeRef = useLatest(mode);
306
+
307
+ const recordRef = useLazyRef<SurfaceRecord>(() => ({
308
+ // oxlint-disable-next-line no-use-before-define -- buildCtxRef is initialized before this callback can run
309
+ buildCtx: () => buildCtxRef.current(),
310
+ depth,
311
+ getMode: () => modeRef.current,
312
+ groupId,
313
+ id,
314
+ order: 0,
315
+ role,
316
+ }));
317
+
318
+ const buildCtx = (): CommandContext => {
319
+ const registry = commandStore.registryFor(recordRef.current);
303
320
  return buildCommandContext({
304
321
  commands: commandsFromRegistry(registry),
305
322
  contributions: commandStore.store.getSnapshot().context.contextSources.values(),
306
323
  mode: modeRef.current,
307
324
  setMode,
308
325
  });
309
- }, [commandStore, setMode]);
326
+ };
310
327
 
311
- const buildCtxRef = useRef(buildCtx);
312
- buildCtxRef.current = buildCtx;
328
+ const buildCtxRef = useLatest(buildCtx);
313
329
 
314
- const recordRef = useRef<SurfaceRecord | null>(null);
315
330
  if (
316
- recordRef.current === null ||
317
331
  recordRef.current.id !== id ||
318
332
  recordRef.current.role !== role ||
319
333
  recordRef.current.depth !== depth ||
@@ -353,13 +367,13 @@ const CommandSurfaceInner = function CommandSurfaceInner({
353
367
  );
354
368
  };
355
369
 
356
- export const useCommandContext = function useCommandContext(): {
370
+ export const useSurfaceInvoke = function useSurfaceInvoke(): {
357
371
  commands: Command[];
358
372
  invoke: (id: string) => void;
359
373
  } {
360
374
  const ctx = useContext(CommandContext);
361
375
  if (!ctx) {
362
- throw new Error("useCommandContext must be used within a CommandProvider");
376
+ throw new Error("useSurfaceInvoke must be used within a CommandProvider");
363
377
  }
364
378
  const { commandStore, surface } = ctx;
365
379
 
@@ -379,6 +393,11 @@ export const useCommandContext = function useCommandContext(): {
379
393
  );
380
394
  };
381
395
 
396
+ /**
397
+ * @deprecated Use `useSurfaceInvoke` instead.
398
+ */
399
+ export const useCommandContext = useSurfaceInvoke;
400
+
382
401
  /**
383
402
  * Builds the live command context of the nearest surface — the same value
384
403
  * command handlers receive. For callers that must hand a context to something
@@ -402,7 +421,7 @@ export const useBuildCommandContext = function useBuildCommandContext(): () => C
402
421
  export const useSurfaceRegistry = function useSurfaceRegistry(): CommandRegistry {
403
422
  const ctx = useContext(CommandContext);
404
423
  if (!ctx) {
405
- throw new Error("useCommandRegistry must be used within a CommandProvider");
424
+ throw new Error("useSurfaceRegistry must be used within a CommandProvider");
406
425
  }
407
426
  return ctx.commandStore.registryFor(ctx.surface);
408
427
  };
@@ -422,12 +441,8 @@ export const useCommandRegistry = function useCommandRegistry(): CommandContextV
422
441
 
423
442
  return useMemo(
424
443
  () => ({
425
- // Deferred(lint-sweep): expose readonly store maps through an immutable registry API.
426
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- compatibility facade preserves the existing mutable Map API
427
- contextSources: contextSources as Map<string, ContextGetter>,
428
- // Deferred(lint-sweep): expose readonly store maps through an immutable registry API.
429
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- compatibility facade preserves the existing mutable Map API
430
- groups: groups as Map<string, RegisteredCommandGroup>,
444
+ contextSources,
445
+ groups,
431
446
  leaderKey,
432
447
  registry,
433
448
  }),
@@ -473,15 +488,16 @@ export const useActiveCommandSurface =
473
488
  });
474
489
 
475
490
  return useMemo(() => {
476
- if (!record) {
491
+ // The keyboard owner is always a modal or panel surface: the root record
492
+ // never comes out of `selectKeyboardOwnerSurface`. The guard lets the type
493
+ // say so instead of asserting it.
494
+ if (!record || record.role === "root") {
477
495
  return null;
478
496
  }
479
497
  return {
480
498
  commands: commandMap ? [...commandMap.values()] : [],
481
499
  id: record.id,
482
- // Deferred(lint-sweep): model selector records with the public surface-role type.
483
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- selector record is trusted store data
484
- role: record.role as CommandSurfaceRole,
500
+ role: record.role,
485
501
  };
486
502
  }, [record, commandMap]);
487
503
  };
@@ -596,8 +612,7 @@ export const useCommandGroup = function useCommandGroup(group: CommandGroup): vo
596
612
  throw new Error("useCommandGroup must be used within a CommandProvider");
597
613
  }
598
614
 
599
- const groupRef = useRef(group);
600
- groupRef.current = group;
615
+ const groupRef = useLatest(group);
601
616
  const { commandStore, leaderKey } = ctx;
602
617
 
603
618
  useEffect(() => {
@@ -618,6 +633,7 @@ export const useCommandGroup = function useCommandGroup(group: CommandGroup): vo
618
633
  group.description,
619
634
  group.icon,
620
635
  group.order,
636
+ groupRef,
621
637
  commandStore,
622
638
  leaderKey,
623
639
  ]);
@@ -633,21 +649,18 @@ export const useProvideCommandContext = function useProvideCommandContext(
633
649
  throw new Error("useProvideCommandContext must be used within a CommandProvider");
634
650
  }
635
651
 
636
- const idRef = useRef<string | null>(null);
637
- if (idRef.current === null) {
638
- idRef.current = `ctx-${nextContextSourceId}`;
652
+ const idRef = useLazyRef(() => {
653
+ const id = `ctx-${nextContextSourceId}`;
639
654
  nextContextSourceId += 1;
640
- }
655
+ return id;
656
+ });
641
657
 
642
- const getterRef = useRef(getter);
643
- getterRef.current = getter;
658
+ const getterRef = useLatest(getter);
644
659
 
645
660
  const { commandStore } = ctx;
646
661
 
647
662
  useEffect(() => {
648
- // Deferred(lint-sweep): replace nullable ref bookkeeping with an API that returns the initialized id.
649
- // oxlint-disable-next-line typescript/no-non-null-assertion -- idRef is initialized in the render immediately above
650
- const id = idRef.current!;
663
+ const id = idRef.current;
651
664
  commandStore.store.trigger.contextSourceRegistered({
652
665
  getter: () => getterRef.current(),
653
666
  id,
@@ -655,13 +668,13 @@ export const useProvideCommandContext = function useProvideCommandContext(
655
668
  return () => {
656
669
  commandStore.store.trigger.contextSourceUnregistered({ id });
657
670
  };
658
- }, [commandStore]);
671
+ }, [commandStore, getterRef, idRef]);
659
672
  };
660
673
 
661
674
  export const useProvideCommandContextKey = function useProvideCommandContextKey<
662
675
  K extends keyof CommandContext,
663
676
  >(key: K, getter: () => CommandContext[K]): void {
664
- // Deferred(lint-sweep): provide a typed augmentation builder instead of asserting computed keys.
677
+ // provide a typed augmentation builder instead of asserting computed keys.
665
678
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- computed key is constrained by K
666
679
  useProvideCommandContext(() => ({ [key]: getter() }));
667
680
  };
@@ -0,0 +1,9 @@
1
+ import { useRef } from "react";
2
+ import type { RefObject } from "react";
3
+
4
+ /** Returns a stable ref whose current value is refreshed during every render. */
5
+ export const useLatest = function useLatest<T>(value: T): RefObject<T> {
6
+ const ref = useRef(value);
7
+ ref.current = value;
8
+ return ref;
9
+ };
@@ -0,0 +1,9 @@
1
+ import { useRef } from "react";
2
+ import type { RefObject } from "react";
3
+
4
+ /** Returns a stable ref initialized by calling `init` only on the first render. */
5
+ export const useLazyRef = function useLazyRef<T>(init: () => T): RefObject<T> {
6
+ const container = useRef<RefObject<T> | null>(null);
7
+ container.current ??= { current: init() };
8
+ return container.current;
9
+ };
package/src/index.ts CHANGED
@@ -16,24 +16,18 @@ export type {
16
16
  RegisteredCommandGroup,
17
17
  } from "./types.js";
18
18
  export type { Mode } from "./mode.js";
19
- export { ModeProvider, useMode, useSetMode } from "./mode.js";
20
- export type { ModeProviderProps } from "./mode.js";
19
+ export { useMode, useSetMode } from "./mode.js";
21
20
  export { parseHotkey } from "./parse.js";
22
21
  export { matchStep } from "./match.js";
23
22
  export { ScreenScopeProvider, useScreenScope } from "./screen-focus.js";
24
23
  export type { ScreenScopeState } from "./screen-focus.js";
25
- export { DEFAULT_SEQUENCE_TIMEOUT_MS, SequenceTracker } from "./sequence.js";
26
- export type {
27
- SequenceFeedResult,
28
- SequencePendingMatch,
29
- SequenceTrackerOptions,
30
- } from "./sequence.js";
31
24
  export {
32
25
  CommandProvider,
33
26
  CommandSurfaceProvider,
34
27
  useActiveCommandSurface,
35
28
  useEffectiveCommands,
36
29
  useBuildCommandContext,
30
+ // oxlint-disable-next-line typescript/no-deprecated -- retained as the documented compatibility alias for useSurfaceInvoke
37
31
  useCommandContext,
38
32
  useCommandGroup,
39
33
  useCommandRegistry,
@@ -43,28 +37,19 @@ export {
43
37
  useProvideCommandContext,
44
38
  useProvideCommandContextKey,
45
39
  useSurfaceCommands,
40
+ useSurfaceInvoke,
46
41
  } from "./context.js";
47
42
  export {
48
43
  ROOT_SURFACE_ID,
49
- createCommandStore,
44
+ formatStepKey,
50
45
  selectActiveModalSurface,
51
46
  selectActivePanelSurface,
52
- selectGroups,
53
47
  selectKeyboardOwnerSurface,
54
48
  selectSequence,
55
- selectSurfaceCommandMap,
56
49
  selectSurfaceCommands,
57
50
  } from "./command-store.js";
58
- export type {
59
- CommandStore,
60
- CommandStoreConfig,
61
- CommandStoreContext,
62
- CommandStoreInstance,
63
- ContextGetter,
64
- CreateCommandStoreOptions,
65
- KeyDispatchResult,
66
- SurfaceRecord,
67
- } from "./command-store.js";
51
+ export type { CommandStoreContext, SurfaceRecord } from "./command-store.js";
52
+ export type { CommandStore, CommandStoreConfig } from "./command-store-wrapper.js";
68
53
  export type {
69
54
  CommandProviderProps,
70
55
  CommandSurfaceProviderProps,
@@ -74,3 +59,5 @@ export { useCommand } from "./use-command.js";
74
59
  export type { UseCommandOptions } from "./use-command.js";
75
60
  export { useActions } from "./use-actions.js";
76
61
  export type { ActionDefinition } from "./use-actions.js";
62
+ export { useLatest } from "./hooks/use-latest.js";
63
+ export { useLazyRef } from "./hooks/use-lazy-ref.js";
@@ -0,0 +1,272 @@
1
+ import type { KeyEvent } from "@opentui/core";
2
+ import type { Mode } from "./mode.js";
3
+ import { matchStep } from "./match.js";
4
+ import { parseHotkey } from "./parse.js";
5
+ import {
6
+ ROOT_SURFACE_ID,
7
+ selectActiveModalSurface,
8
+ selectActivePanelSurface,
9
+ stepsKey,
10
+ } from "./command-store.js";
11
+ import type { CommandStoreContext, CommandStoreInstance, SurfaceRecord } from "./command-store.js";
12
+ import {
13
+ DEFAULT_SEQUENCE_TIMEOUT_MS,
14
+ findPendingMatch,
15
+ matchesBuffer,
16
+ pruneBuffer,
17
+ } from "./sequence.js";
18
+ import type { Command, CommandContext, CommandSequenceState, ParsedHotkey } from "./types.js";
19
+
20
+ const DEFAULT_MODES: Mode[] = ["cursor"];
21
+
22
+ export interface KeyDispatchResult {
23
+ handled: boolean;
24
+ invoke?: () => void;
25
+ }
26
+
27
+ export interface KeyDispatchConfig {
28
+ leader?: string;
29
+ keymap?: Record<string, string>;
30
+ sequenceTimeoutMs?: number;
31
+ }
32
+
33
+ interface HotkeyCandidates {
34
+ singleStep: { command: Command; parsed: ParsedHotkey }[];
35
+ multiStep: { command: Command; hotkey: string; parsed: ParsedHotkey }[];
36
+ }
37
+
38
+ type SurfaceDispatch =
39
+ | { outcome: "invoke"; invoke: () => void }
40
+ | { outcome: "pending" }
41
+ | { outcome: "miss" };
42
+
43
+ interface DispatchState {
44
+ buffer: readonly KeyEvent[];
45
+ sequenceOwnerId: string | null;
46
+ timer: ReturnType<typeof setTimeout> | null;
47
+ }
48
+
49
+ interface DispatchEnvironment {
50
+ getConfig: () => KeyDispatchConfig;
51
+ rootRecord: SurfaceRecord;
52
+ store: CommandStoreInstance;
53
+ }
54
+
55
+ const collectCandidates = function collectCandidates(
56
+ commands: ReadonlyMap<string, Command> | undefined,
57
+ currentMode: Mode,
58
+ cmdCtx: CommandContext,
59
+ config: KeyDispatchConfig,
60
+ getParsedHotkey: (hotkey: string) => ParsedHotkey,
61
+ ): HotkeyCandidates {
62
+ const singleStep: HotkeyCandidates["singleStep"] = [];
63
+ const multiStep: HotkeyCandidates["multiStep"] = [];
64
+
65
+ for (const command of commands?.values() ?? []) {
66
+ const commandModes = command.modes ?? DEFAULT_MODES;
67
+ if (!commandModes.includes(currentMode) || (command.when && !command.when(cmdCtx))) {
68
+ continue;
69
+ }
70
+ const hotkey = config.keymap?.[command.id] ?? command.defaultHotkey;
71
+ if (hotkey === undefined || hotkey === "") {
72
+ continue;
73
+ }
74
+ const parsed = getParsedHotkey(hotkey);
75
+ if (parsed.steps.length === 0) {
76
+ continue;
77
+ }
78
+ if (parsed.steps.length === 1) {
79
+ singleStep.push({ command, parsed });
80
+ } else {
81
+ multiStep.push({ command, hotkey, parsed });
82
+ }
83
+ }
84
+ return { multiStep, singleStep };
85
+ };
86
+
87
+ const runSurface = function runSurface(
88
+ record: SurfaceRecord,
89
+ event: KeyEvent,
90
+ ctx: CommandStoreContext,
91
+ state: DispatchState,
92
+ environment: DispatchEnvironment,
93
+ getParsedHotkey: (hotkey: string) => ParsedHotkey,
94
+ armTimer: () => void,
95
+ clearBufferAndTimer: () => void,
96
+ ): SurfaceDispatch {
97
+ const cmdCtx = record.buildCtx();
98
+ const candidates = collectCandidates(
99
+ ctx.commandsBySurface.get(record.id),
100
+ record.getMode(),
101
+ cmdCtx,
102
+ environment.getConfig(),
103
+ getParsedHotkey,
104
+ );
105
+
106
+ if (candidates.multiStep.length > 0) {
107
+ const hotkeys = candidates.multiStep.map((candidate) => candidate.parsed);
108
+ state.buffer = [...state.buffer, event];
109
+ armTimer();
110
+
111
+ const matchedIndex = hotkeys.findIndex((hotkey) => matchesBuffer(state.buffer, hotkey));
112
+ if (matchedIndex !== -1) {
113
+ clearBufferAndTimer();
114
+ environment.store.trigger.sequenceReset();
115
+ const matched = candidates.multiStep[matchedIndex].command;
116
+ return {
117
+ invoke: (): void => {
118
+ void matched.handler(cmdCtx);
119
+ },
120
+ outcome: "invoke",
121
+ };
122
+ }
123
+
124
+ state.buffer = pruneBuffer(state.buffer, hotkeys);
125
+ const pending = findPendingMatch(state.buffer, hotkeys);
126
+ if (pending) {
127
+ const firstCandidate = candidates.multiStep[pending.indexes[0]];
128
+ const sequence: CommandSequenceState = {
129
+ candidates: pending.indexes
130
+ .map((index) => candidates.multiStep[index])
131
+ .filter(({ command }) => command.hidden !== true)
132
+ .map(({ command, hotkey, parsed }) => ({
133
+ command,
134
+ group: ctx.groups.get(stepsKey(parsed.steps.slice(0, pending.prefixLength + 1))),
135
+ hotkey,
136
+ nextStep: parsed.steps[pending.prefixLength],
137
+ remainingSteps: parsed.steps.slice(pending.prefixLength),
138
+ steps: parsed.steps,
139
+ })),
140
+ prefix: firstCandidate.parsed.steps.slice(0, pending.prefixLength),
141
+ };
142
+ environment.store.trigger.sequencePending({ state: sequence });
143
+ return { outcome: "pending" };
144
+ }
145
+
146
+ clearBufferAndTimer();
147
+ environment.store.trigger.sequenceReset();
148
+ }
149
+
150
+ for (const { command, parsed } of candidates.singleStep) {
151
+ if (matchStep(event, parsed.steps[0])) {
152
+ environment.store.trigger.sequenceReset();
153
+ return {
154
+ invoke: (): void => {
155
+ void command.handler(cmdCtx);
156
+ },
157
+ outcome: "invoke",
158
+ };
159
+ }
160
+ }
161
+
162
+ clearBufferAndTimer();
163
+ environment.store.trigger.sequenceReset();
164
+ return { outcome: "miss" };
165
+ };
166
+
167
+ const finishDispatch = function finishDispatch(
168
+ dispatch: SurfaceDispatch,
169
+ ownerId: string,
170
+ state: DispatchState,
171
+ ): KeyDispatchResult {
172
+ if (dispatch.outcome === "pending") {
173
+ state.sequenceOwnerId = ownerId;
174
+ return { handled: true };
175
+ }
176
+ state.sequenceOwnerId = null;
177
+ return dispatch.outcome === "invoke"
178
+ ? { handled: true, invoke: dispatch.invoke }
179
+ : { handled: false };
180
+ };
181
+
182
+ export interface KeyDispatcher {
183
+ dispose: () => void;
184
+ key: (event: KeyEvent) => KeyDispatchResult;
185
+ reset: () => void;
186
+ }
187
+
188
+ export const createKeyDispatcher = function createKeyDispatcher(
189
+ environment: DispatchEnvironment,
190
+ ): KeyDispatcher {
191
+ const state: DispatchState = { buffer: [], sequenceOwnerId: null, timer: null };
192
+ const parseCache = new Map<string, ParsedHotkey>();
193
+
194
+ const clearTimer = (): void => {
195
+ if (state.timer !== null) {
196
+ clearTimeout(state.timer);
197
+ state.timer = null;
198
+ }
199
+ };
200
+ const clearBufferAndTimer = (): void => {
201
+ state.buffer = [];
202
+ state.sequenceOwnerId = null;
203
+ clearTimer();
204
+ };
205
+ const reset = (): void => {
206
+ clearBufferAndTimer();
207
+ environment.store.trigger.sequenceReset();
208
+ };
209
+ const armTimer = (): void => {
210
+ clearTimer();
211
+ state.timer = setTimeout(
212
+ reset,
213
+ environment.getConfig().sequenceTimeoutMs ?? DEFAULT_SEQUENCE_TIMEOUT_MS,
214
+ );
215
+ };
216
+ const getParsedHotkey = (hotkey: string): ParsedHotkey => {
217
+ const { leader } = environment.getConfig();
218
+ const cacheKey = `${hotkey}:${leader ?? ""}`;
219
+ let parsed = parseCache.get(cacheKey);
220
+ if (!parsed) {
221
+ parsed = parseHotkey(hotkey, leader);
222
+ parseCache.set(cacheKey, parsed);
223
+ }
224
+ return parsed;
225
+ };
226
+ const dispatchTo = (
227
+ record: SurfaceRecord,
228
+ event: KeyEvent,
229
+ ctx: CommandStoreContext,
230
+ ): SurfaceDispatch =>
231
+ runSurface(
232
+ record,
233
+ event,
234
+ ctx,
235
+ state,
236
+ environment,
237
+ getParsedHotkey,
238
+ armTimer,
239
+ clearBufferAndTimer,
240
+ );
241
+ const finish = (dispatch: SurfaceDispatch, ownerId: string): KeyDispatchResult =>
242
+ finishDispatch(dispatch, ownerId, state);
243
+
244
+ const key = (event: KeyEvent): KeyDispatchResult => {
245
+ const ctx = environment.store.getSnapshot().context;
246
+ if (state.buffer.length > 0 && state.sequenceOwnerId !== null) {
247
+ const owner =
248
+ state.sequenceOwnerId === ROOT_SURFACE_ID
249
+ ? environment.rootRecord
250
+ : (ctx.surfaces.find((record) => record.id === state.sequenceOwnerId) ?? null);
251
+ if (owner) {
252
+ return finish(dispatchTo(owner, event, ctx), state.sequenceOwnerId);
253
+ }
254
+ clearBufferAndTimer();
255
+ }
256
+
257
+ const modal = selectActiveModalSurface(ctx);
258
+ if (modal) {
259
+ return finish(dispatchTo(modal, event, ctx), modal.id);
260
+ }
261
+ const panel = selectActivePanelSurface(ctx);
262
+ if (panel) {
263
+ const dispatch = dispatchTo(panel, event, ctx);
264
+ if (dispatch.outcome !== "miss" || panel.getMode() === "insert") {
265
+ return finish(dispatch, panel.id);
266
+ }
267
+ }
268
+ return finish(dispatchTo(environment.rootRecord, event, ctx), ROOT_SURFACE_ID);
269
+ };
270
+
271
+ return { dispose: clearBufferAndTimer, key, reset };
272
+ };