@tooee/commands 0.2.4 → 0.3.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 (54) hide show
  1. package/README.md +5 -5
  2. package/dist/build-context.d.ts +32 -0
  3. package/dist/build-context.d.ts.map +1 -0
  4. package/dist/build-context.js +44 -0
  5. package/dist/build-context.js.map +1 -0
  6. package/dist/command-store.d.ts +19 -19
  7. package/dist/command-store.d.ts.map +1 -1
  8. package/dist/command-store.js +191 -148
  9. package/dist/command-store.js.map +1 -1
  10. package/dist/context.d.ts +16 -16
  11. package/dist/context.d.ts.map +1 -1
  12. package/dist/context.js +112 -107
  13. package/dist/context.js.map +1 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/match.d.ts +1 -1
  18. package/dist/match.d.ts.map +1 -1
  19. package/dist/match.js +14 -8
  20. package/dist/match.js.map +1 -1
  21. package/dist/mode.d.ts +4 -4
  22. package/dist/mode.d.ts.map +1 -1
  23. package/dist/mode.js +14 -14
  24. package/dist/mode.js.map +1 -1
  25. package/dist/parse.d.ts +1 -1
  26. package/dist/parse.d.ts.map +1 -1
  27. package/dist/parse.js +19 -18
  28. package/dist/parse.js.map +1 -1
  29. package/dist/sequence.d.ts +6 -5
  30. package/dist/sequence.d.ts.map +1 -1
  31. package/dist/sequence.js +31 -20
  32. package/dist/sequence.js.map +1 -1
  33. package/dist/types.d.ts +18 -10
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/use-actions.d.ts +1 -1
  36. package/dist/use-actions.d.ts.map +1 -1
  37. package/dist/use-actions.js +22 -12
  38. package/dist/use-actions.js.map +1 -1
  39. package/dist/use-command.d.ts +1 -1
  40. package/dist/use-command.d.ts.map +1 -1
  41. package/dist/use-command.js +21 -12
  42. package/dist/use-command.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/build-context.ts +65 -0
  45. package/src/command-store.ts +366 -290
  46. package/src/context.tsx +298 -284
  47. package/src/index.ts +17 -16
  48. package/src/match.ts +23 -11
  49. package/src/mode.tsx +37 -41
  50. package/src/parse.ts +48 -46
  51. package/src/sequence.ts +88 -66
  52. package/src/types.ts +69 -57
  53. package/src/use-actions.ts +46 -35
  54. package/src/use-command.ts +44 -33
@@ -1,5 +1,5 @@
1
- import { createStore } from "@xstate/store"
2
- import type { KeyEvent } from "@opentui/core"
1
+ import { createStore } from "@xstate/store";
2
+ import type { KeyEvent } from "@opentui/core";
3
3
  import type {
4
4
  Command,
5
5
  CommandContext,
@@ -9,20 +9,20 @@ import type {
9
9
  ParsedHotkey,
10
10
  ParsedStep,
11
11
  RegisteredCommandGroup,
12
- } from "./types.js"
13
- import type { Mode } from "./mode.js"
14
- import { parseHotkey } from "./parse.js"
15
- import { matchStep } from "./match.js"
12
+ } from "./types.js";
13
+ import type { Mode } from "./mode.js";
14
+ import { parseHotkey } from "./parse.js";
15
+ import { matchStep } from "./match.js";
16
16
  import {
17
17
  DEFAULT_SEQUENCE_TIMEOUT_MS,
18
18
  findPendingMatch,
19
19
  matchesBuffer,
20
20
  pruneBuffer,
21
- } from "./sequence.js"
21
+ } from "./sequence.js";
22
22
 
23
- export const ROOT_SURFACE_ID = "__root"
23
+ export const ROOT_SURFACE_ID = "__root";
24
24
 
25
- const DEFAULT_MODES: Mode[] = ["cursor"]
25
+ const DEFAULT_MODES: Mode[] = ["cursor"];
26
26
 
27
27
  /**
28
28
  * A surface as tracked by the store. The root app is `surfaces[0]`, always
@@ -35,30 +35,30 @@ const DEFAULT_MODES: Mode[] = ["cursor"]
35
35
  * `commandsBySurface`, keyed by surface id, independent of the stack.
36
36
  */
37
37
  export interface SurfaceRecord {
38
- id: string
39
- role: CommandSurfaceRole | "root"
38
+ id: string;
39
+ role: CommandSurfaceRole | "root";
40
40
  /** Nesting depth (root = 0). */
41
- depth: number
41
+ depth: number;
42
42
  /** Monotonic registration order (tie-break), assigned by the wrapper on push. */
43
- order: number
43
+ order: number;
44
44
  /** Reads this surface's current local mode (mode stays in ModeProvider React state). */
45
- getMode: () => Mode
45
+ getMode: () => Mode;
46
46
  /** Builds the command context handed to this surface's handlers. */
47
- buildCtx: () => CommandContext
47
+ buildCtx: () => CommandContext;
48
48
  }
49
49
 
50
- export type ContextGetter = () => Partial<CommandContext>
50
+ export type ContextGetter = () => Partial<CommandContext>;
51
51
 
52
52
  export interface CommandStoreContext {
53
53
  /** Surface stack ordered by registration; `surfaces[0]` is the root record. */
54
- surfaces: readonly SurfaceRecord[]
54
+ surfaces: readonly SurfaceRecord[];
55
55
  /** Per-surface command maps, keyed by surface id (see SurfaceRecord docs). */
56
- commandsBySurface: ReadonlyMap<string, ReadonlyMap<string, Command>>
56
+ commandsBySurface: ReadonlyMap<string, ReadonlyMap<string, Command>>;
57
57
  /** Command groups keyed by prefixKey. */
58
- groups: ReadonlyMap<string, RegisteredCommandGroup>
59
- contextSources: ReadonlyMap<string, ContextGetter>
58
+ groups: ReadonlyMap<string, RegisteredCommandGroup>;
59
+ contextSources: ReadonlyMap<string, ContextGetter>;
60
60
  /** Renderable pending-sequence display state (which-key input). */
61
- sequence: CommandSequenceState | null
61
+ sequence: CommandSequenceState | null;
62
62
  }
63
63
 
64
64
  // --- Selectors ---------------------------------------------------------------
@@ -67,67 +67,83 @@ export interface CommandStoreContext {
67
67
  * The topmost modal surface: role === "modal", max depth, then max order.
68
68
  * Passive surfaces and the root never win.
69
69
  */
70
- export function selectActiveModalSurface(ctx: CommandStoreContext): SurfaceRecord | null {
71
- let best: SurfaceRecord | null = null
70
+ export const selectActiveModalSurface = function selectActiveModalSurface(
71
+ ctx: CommandStoreContext,
72
+ ): SurfaceRecord | null {
73
+ let best: SurfaceRecord | null = null;
72
74
  for (const record of ctx.surfaces) {
73
- if (record.role !== "modal") continue
75
+ if (record.role !== "modal") {
76
+ continue;
77
+ }
74
78
  if (
75
79
  best === null ||
76
80
  record.depth > best.depth ||
77
81
  (record.depth === best.depth && record.order > best.order)
78
82
  ) {
79
- best = record
83
+ best = record;
80
84
  }
81
85
  }
82
- return best
83
- }
86
+ return best;
87
+ };
84
88
 
85
89
  /**
86
90
  * Commands registered on a surface. Returns a fresh array; memoize against
87
91
  * `selectSurfaceCommandMap` identity in render paths.
88
92
  */
89
- export function selectSurfaceCommands(
93
+ export const selectSurfaceCommands = function selectSurfaceCommands(
90
94
  ctx: CommandStoreContext,
91
95
  surfaceId: string,
92
96
  ): readonly Command[] {
93
- const commands = ctx.commandsBySurface.get(surfaceId)
94
- return commands ? Array.from(commands.values()) : []
95
- }
97
+ const commands = ctx.commandsBySurface.get(surfaceId);
98
+ return commands ? [...commands.values()] : [];
99
+ };
96
100
 
97
101
  /** Identity-stable per-surface command map (undefined when none registered). */
98
- export function selectSurfaceCommandMap(
102
+ export const selectSurfaceCommandMap = function selectSurfaceCommandMap(
99
103
  ctx: CommandStoreContext,
100
104
  surfaceId: string,
101
105
  ): ReadonlyMap<string, Command> | undefined {
102
- return ctx.commandsBySurface.get(surfaceId)
103
- }
106
+ return ctx.commandsBySurface.get(surfaceId);
107
+ };
104
108
 
105
- export function selectSequence(ctx: CommandStoreContext): CommandSequenceState | null {
106
- return ctx.sequence
107
- }
109
+ export const selectSequence = function selectSequence(
110
+ ctx: CommandStoreContext,
111
+ ): CommandSequenceState | null {
112
+ return ctx.sequence;
113
+ };
108
114
 
109
- export function selectGroups(
115
+ export const selectGroups = function selectGroups(
110
116
  ctx: CommandStoreContext,
111
117
  ): ReadonlyMap<string, RegisteredCommandGroup> {
112
- return ctx.groups
113
- }
118
+ return ctx.groups;
119
+ };
114
120
 
115
121
  // --- Step-key helpers (shared by key dispatch and group registration) --------
116
122
 
117
- export function stepsKey(steps: readonly ParsedStep[]): string {
118
- return steps.map(formatStepKey).join(" ")
119
- }
123
+ export const formatStepKey = function formatStepKey(step: ParsedStep): string {
124
+ const modifiers = [];
125
+ if (step.ctrl) {
126
+ modifiers.push("ctrl");
127
+ }
128
+ if (step.meta) {
129
+ modifiers.push("meta");
130
+ }
131
+ if (step.option) {
132
+ modifiers.push("option");
133
+ }
134
+ if (step.shift) {
135
+ modifiers.push("shift");
136
+ }
137
+ if (step.super === true) {
138
+ modifiers.push("super");
139
+ }
140
+ modifiers.push(step.key);
141
+ return modifiers.join("+");
142
+ };
120
143
 
121
- export function formatStepKey(step: ParsedStep): string {
122
- const modifiers = []
123
- if (step.ctrl) modifiers.push("ctrl")
124
- if (step.meta) modifiers.push("meta")
125
- if (step.option) modifiers.push("option")
126
- if (step.shift) modifiers.push("shift")
127
- if (step.super) modifiers.push("super")
128
- modifiers.push(step.key)
129
- return modifiers.join("+")
130
- }
144
+ export const stepsKey = function stepsKey(steps: readonly ParsedStep[]): string {
145
+ return steps.map(formatStepKey).join(" ");
146
+ };
131
147
 
132
148
  // --- Store -------------------------------------------------------------------
133
149
 
@@ -138,15 +154,15 @@ export function formatStepKey(step: ParsedStep): string {
138
154
  * sequence it is displaying; replacing the active modal surface with a same-id
139
155
  * record clears it (F-09) because the record identity changes.
140
156
  */
141
- function sequenceAfterStackChange(
157
+ const sequenceAfterStackChange = function sequenceAfterStackChange(
142
158
  before: SurfaceRecord | null,
143
159
  after: SurfaceRecord | null,
144
160
  sequence: CommandSequenceState | null,
145
161
  ): CommandSequenceState | null {
146
- return before === after ? sequence : null
147
- }
162
+ return before === after ? sequence : null;
163
+ };
148
164
 
149
- function createBaseStore(initialContext: CommandStoreContext) {
165
+ const createBaseStore = function createBaseStore(initialContext: CommandStoreContext) {
150
166
  return createStore({
151
167
  context: initialContext,
152
168
  on: {
@@ -154,12 +170,16 @@ function createBaseStore(initialContext: CommandStoreContext) {
154
170
  ctx: CommandStoreContext,
155
171
  event: { surfaceId: string; command: Command },
156
172
  ): CommandStoreContext => {
157
- const existing = ctx.commandsBySurface.get(event.surfaceId)
158
- const commands = new Map(existing ?? [])
159
- commands.set(event.command.id, event.command)
160
- const commandsBySurface = new Map(ctx.commandsBySurface)
161
- commandsBySurface.set(event.surfaceId, commands)
162
- return { ...ctx, commandsBySurface }
173
+ const existing = ctx.commandsBySurface.get(event.surfaceId);
174
+ // Map construction replays entries in order, so a re-registered id keeps its
175
+ // original insertion position and takes the new value — identical to
176
+ // clone-then-set. Pinned by the duplicate-id ordering tests.
177
+ const commands = new Map([...(existing ?? []), [event.command.id, event.command] as const]);
178
+ const commandsBySurface = new Map([
179
+ ...ctx.commandsBySurface,
180
+ [event.surfaceId, commands] as const,
181
+ ]);
182
+ return { ...ctx, commandsBySurface };
163
183
  },
164
184
  commandUnregistered: (
165
185
  ctx: CommandStoreContext,
@@ -168,117 +188,124 @@ function createBaseStore(initialContext: CommandStoreContext) {
168
188
  // Identity-guarded (R-05): with duplicate ids the map holds the last
169
189
  // writer, and the first registrant's unmount must not delete the
170
190
  // second's live command.
171
- const existing = ctx.commandsBySurface.get(event.surfaceId)
172
- if (!existing || existing.get(event.command.id) !== event.command) return ctx
173
- const commands = new Map(existing)
174
- commands.delete(event.command.id)
175
- const commandsBySurface = new Map(ctx.commandsBySurface)
191
+ const existing = ctx.commandsBySurface.get(event.surfaceId);
192
+ if (!existing || existing.get(event.command.id) !== event.command) {
193
+ return ctx;
194
+ }
195
+ const commands = new Map(existing);
196
+ commands.delete(event.command.id);
197
+ const commandsBySurface = new Map(ctx.commandsBySurface);
176
198
  if (commands.size === 0) {
177
- commandsBySurface.delete(event.surfaceId)
199
+ commandsBySurface.delete(event.surfaceId);
178
200
  } else {
179
- commandsBySurface.set(event.surfaceId, commands)
201
+ commandsBySurface.set(event.surfaceId, commands);
180
202
  }
181
- return { ...ctx, commandsBySurface }
182
- },
183
- groupRegistered: (
184
- ctx: CommandStoreContext,
185
- event: { group: RegisteredCommandGroup },
186
- ): CommandStoreContext => {
187
- const groups = new Map(ctx.groups)
188
- groups.set(event.group.prefixKey, event.group)
189
- return { ...ctx, groups }
190
- },
191
- groupUnregistered: (
192
- ctx: CommandStoreContext,
193
- event: { group: RegisteredCommandGroup },
194
- ): CommandStoreContext => {
195
- // Identity-guarded, as for commands.
196
- if (ctx.groups.get(event.group.prefixKey) !== event.group) return ctx
197
- const groups = new Map(ctx.groups)
198
- groups.delete(event.group.prefixKey)
199
- return { ...ctx, groups }
203
+ return { ...ctx, commandsBySurface };
200
204
  },
201
205
  contextSourceRegistered: (
202
206
  ctx: CommandStoreContext,
203
207
  event: { id: string; getter: ContextGetter },
204
208
  ): CommandStoreContext => {
205
- const contextSources = new Map(ctx.contextSources)
206
- contextSources.set(event.id, event.getter)
207
- return { ...ctx, contextSources }
209
+ const contextSources = new Map([...ctx.contextSources, [event.id, event.getter] as const]);
210
+ return { ...ctx, contextSources };
208
211
  },
209
212
  contextSourceUnregistered: (
210
213
  ctx: CommandStoreContext,
211
214
  event: { id: string },
212
215
  ): CommandStoreContext => {
213
- if (!ctx.contextSources.has(event.id)) return ctx
214
- const contextSources = new Map(ctx.contextSources)
215
- contextSources.delete(event.id)
216
- return { ...ctx, contextSources }
216
+ if (!ctx.contextSources.has(event.id)) {
217
+ return ctx;
218
+ }
219
+ const contextSources = new Map(ctx.contextSources);
220
+ contextSources.delete(event.id);
221
+ return { ...ctx, contextSources };
217
222
  },
218
- surfacePushed: (
223
+ groupRegistered: (
219
224
  ctx: CommandStoreContext,
220
- event: { surface: SurfaceRecord },
225
+ event: { group: RegisteredCommandGroup },
221
226
  ): CommandStoreContext => {
222
- const before = selectActiveModalSurface(ctx)
223
- const surfaces = [...ctx.surfaces, event.surface]
224
- const after = selectActiveModalSurface({ ...ctx, surfaces })
225
- return { ...ctx, surfaces, sequence: sequenceAfterStackChange(before, after, ctx.sequence) }
227
+ const groups = new Map([...ctx.groups, [event.group.prefixKey, event.group] as const]);
228
+ return { ...ctx, groups };
226
229
  },
227
- surfacePopped: (
230
+ groupUnregistered: (
228
231
  ctx: CommandStoreContext,
229
- event: { surface: SurfaceRecord },
232
+ event: { group: RegisteredCommandGroup },
230
233
  ): CommandStoreContext => {
231
- // Identity-based removal: only the exact pushed record is removed.
232
- const surfaces = ctx.surfaces.filter((record) => record !== event.surface)
233
- if (surfaces.length === ctx.surfaces.length) return ctx
234
- const before = selectActiveModalSurface(ctx)
235
- const after = selectActiveModalSurface({ ...ctx, surfaces })
236
- return { ...ctx, surfaces, sequence: sequenceAfterStackChange(before, after, ctx.sequence) }
234
+ // Identity-guarded, as for commands.
235
+ if (ctx.groups.get(event.group.prefixKey) !== event.group) {
236
+ return ctx;
237
+ }
238
+ const groups = new Map(ctx.groups);
239
+ groups.delete(event.group.prefixKey);
240
+ return { ...ctx, groups };
237
241
  },
238
- modeChanged: (
239
- ctx: CommandStoreContext,
240
- _event: { surfaceId: string },
241
- ): CommandStoreContext => {
242
+ modeChanged: (ctx: CommandStoreContext, _event: { surfaceId: string }): CommandStoreContext =>
242
243
  // A mode change is a transition, not a post-render repair: any pending
243
244
  // chord is invalidated (F-08 — including surface-local mode changes).
244
- return ctx.sequence === null ? ctx : { ...ctx, sequence: null }
245
- },
245
+ ctx.sequence === null ? ctx : { ...ctx, sequence: null },
246
246
  sequencePending: (
247
247
  ctx: CommandStoreContext,
248
248
  event: { state: CommandSequenceState },
249
+ ): CommandStoreContext => ({ ...ctx, sequence: event.state }),
250
+ sequenceReset: (ctx: CommandStoreContext): CommandStoreContext =>
251
+ ctx.sequence === null ? ctx : { ...ctx, sequence: null },
252
+ surfacePopped: (
253
+ ctx: CommandStoreContext,
254
+ event: { surface: SurfaceRecord },
249
255
  ): CommandStoreContext => {
250
- return { ...ctx, sequence: event.state }
256
+ // Identity-based removal: only the exact pushed record is removed.
257
+ const surfaces = ctx.surfaces.filter((record) => record !== event.surface);
258
+ if (surfaces.length === ctx.surfaces.length) {
259
+ return ctx;
260
+ }
261
+ const before = selectActiveModalSurface(ctx);
262
+ const after = selectActiveModalSurface({ ...ctx, surfaces });
263
+ return {
264
+ ...ctx,
265
+ sequence: sequenceAfterStackChange(before, after, ctx.sequence),
266
+ surfaces,
267
+ };
251
268
  },
252
- sequenceReset: (ctx: CommandStoreContext): CommandStoreContext => {
253
- return ctx.sequence === null ? ctx : { ...ctx, sequence: null }
269
+ surfacePushed: (
270
+ ctx: CommandStoreContext,
271
+ event: { surface: SurfaceRecord },
272
+ ): CommandStoreContext => {
273
+ const before = selectActiveModalSurface(ctx);
274
+ const surfaces = [...ctx.surfaces, event.surface];
275
+ const after = selectActiveModalSurface({ ...ctx, surfaces });
276
+ return {
277
+ ...ctx,
278
+ sequence: sequenceAfterStackChange(before, after, ctx.sequence),
279
+ surfaces,
280
+ };
254
281
  },
255
282
  },
256
- })
257
- }
283
+ });
284
+ };
258
285
 
259
- export type CommandStoreInstance = ReturnType<typeof createBaseStore>
286
+ export type CommandStoreInstance = ReturnType<typeof createBaseStore>;
260
287
 
261
288
  // --- Wrapper -----------------------------------------------------------------
262
289
 
263
290
  export interface KeyDispatchResult {
264
- handled: boolean
291
+ handled: boolean;
265
292
  /**
266
293
  * Present on a full command match. The caller (the `useKeyboard` effect)
267
294
  * calls `preventDefault()` and then `invoke()` synchronously, preserving
268
295
  * today's dispatch order and `event.defaultPrevented` semantics.
269
296
  */
270
- invoke?: () => void
297
+ invoke?: () => void;
271
298
  }
272
299
 
273
300
  export interface CommandStoreConfig {
274
- leader?: string
275
- keymap?: Record<string, string>
276
- sequenceTimeoutMs?: number
301
+ leader?: string;
302
+ keymap?: Record<string, string>;
303
+ sequenceTimeoutMs?: number;
277
304
  }
278
305
 
279
306
  export interface CreateCommandStoreOptions extends CommandStoreConfig {
280
307
  /** Root surface accessors, provided by the command provider/dispatcher. */
281
- root: { getMode: () => Mode; buildCtx: () => CommandContext }
308
+ root: { getMode: () => Mode; buildCtx: () => CommandContext };
282
309
  }
283
310
 
284
311
  /**
@@ -289,9 +316,9 @@ export interface CreateCommandStoreOptions extends CommandStoreConfig {
289
316
  */
290
317
  export interface CommandStore {
291
318
  /** The underlying @xstate/store instance (subscribe/getSnapshot/trigger). */
292
- store: CommandStoreInstance
319
+ store: CommandStoreInstance;
293
320
  /** The always-present root surface record (`surfaces[0]`). */
294
- rootRecord: SurfaceRecord
321
+ rootRecord: SurfaceRecord;
295
322
 
296
323
  /**
297
324
  * Feed a key event: arbitrates the active surface, filters candidates by
@@ -300,255 +327,304 @@ export interface CommandStore {
300
327
  * timeout, and returns what happened so the caller can preventDefault and
301
328
  * invoke synchronously.
302
329
  */
303
- key: (event: KeyEvent) => KeyDispatchResult
330
+ key: (event: KeyEvent) => KeyDispatchResult;
304
331
 
305
332
  /** Clears buffer + timer and triggers sequenceReset. Idempotent. */
306
- reset: () => void
333
+ reset: () => void;
307
334
  /** Clears buffer + timer permanently, without touching store state. Called on dispatcher unmount. */
308
- dispose: () => void
335
+ dispose: () => void;
309
336
 
310
337
  /** Push a surface record; assigns registration order. Returns the pop cleanup. */
311
- pushSurface: (surface: SurfaceRecord) => () => void
338
+ pushSurface: (surface: SurfaceRecord) => () => void;
312
339
  /** Notify a (root or surface-local) mode change: clears buffer + pending sequence. */
313
- modeChanged: (surfaceId: string) => void
340
+ modeChanged: (surfaceId: string) => void;
314
341
 
315
342
  /** Back-compat CommandRegistry facade for a surface record (stable per record). */
316
- registryFor: (record: SurfaceRecord) => CommandRegistry
343
+ registryFor: (record: SurfaceRecord) => CommandRegistry;
317
344
 
318
345
  /** Update live config (leader/keymap/timeout are read per dispatch, as before). */
319
- setConfig: (config: CommandStoreConfig) => void
346
+ setConfig: (config: CommandStoreConfig) => void;
320
347
  }
321
348
 
322
- export function createCommandStore(options: CreateCommandStoreOptions): CommandStore {
349
+ const reportCommandFailure = async function reportCommandFailure(result: Promise<void>) {
350
+ try {
351
+ await result;
352
+ } catch (error: unknown) {
353
+ console.error("Command handler failed", error);
354
+ }
355
+ };
356
+
357
+ export const createCommandStore = function createCommandStore(
358
+ options: CreateCommandStoreOptions,
359
+ ): CommandStore {
323
360
  const rootRecord: SurfaceRecord = {
324
- id: ROOT_SURFACE_ID,
325
- role: "root",
361
+ buildCtx: options.root.buildCtx,
326
362
  depth: 0,
327
- order: 0,
328
363
  getMode: options.root.getMode,
329
- buildCtx: options.root.buildCtx,
330
- }
364
+ id: ROOT_SURFACE_ID,
365
+ order: 0,
366
+ role: "root",
367
+ };
331
368
 
332
369
  const store = createBaseStore({
333
- surfaces: [rootRecord],
334
370
  commandsBySurface: new Map(),
335
- groups: new Map(),
336
371
  contextSources: new Map(),
372
+ groups: new Map(),
337
373
  sequence: null,
338
- })
374
+ surfaces: [rootRecord],
375
+ });
339
376
 
340
377
  let config: CommandStoreConfig = {
341
- leader: options.leader,
342
378
  keymap: options.keymap,
379
+ leader: options.leader,
343
380
  sequenceTimeoutMs: options.sequenceTimeoutMs,
344
- }
381
+ };
345
382
 
346
383
  // IO-adjacent wrapper state: key buffer, timer, parse cache, order counter.
347
- let buffer: readonly KeyEvent[] = []
348
- let timer: ReturnType<typeof setTimeout> | null = null
349
- const parseCache = new Map<string, ParsedHotkey>()
350
- const registries = new Map<SurfaceRecord, CommandRegistry>()
351
- let orderCounter = 1
384
+ let buffer: readonly KeyEvent[] = [];
385
+ let timer: ReturnType<typeof setTimeout> | null = null;
386
+ const parseCache = new Map<string, ParsedHotkey>();
387
+ const registries = new Map<SurfaceRecord, CommandRegistry>();
388
+ let orderCounter = 1;
352
389
 
353
- function clearTimer(): void {
390
+ const clearTimer = function clearTimer(): void {
354
391
  if (timer !== null) {
355
- clearTimeout(timer)
356
- timer = null
392
+ clearTimeout(timer);
393
+ timer = null;
357
394
  }
358
- }
359
-
360
- function armTimer(): void {
361
- clearTimer()
362
- timer = setTimeout(reset, config.sequenceTimeoutMs ?? DEFAULT_SEQUENCE_TIMEOUT_MS)
363
- }
364
-
365
- function clearBufferAndTimer(): void {
366
- buffer = []
367
- clearTimer()
368
- }
369
-
370
- function reset(): void {
371
- clearBufferAndTimer()
372
- store.trigger.sequenceReset()
373
- }
374
-
375
- function dispose(): void {
376
- clearBufferAndTimer()
377
- }
378
-
379
- function getParsedHotkey(hotkey: string): ParsedHotkey {
380
- const cacheKey = `${hotkey}:${config.leader ?? ""}`
381
- let parsed = parseCache.get(cacheKey)
395
+ };
396
+
397
+ const clearBufferAndTimer = function clearBufferAndTimer(): void {
398
+ buffer = [];
399
+ clearTimer();
400
+ };
401
+
402
+ const reset = function reset(): void {
403
+ clearBufferAndTimer();
404
+ store.trigger.sequenceReset();
405
+ };
406
+
407
+ const armTimer = function armTimer(): void {
408
+ clearTimer();
409
+ timer = setTimeout(reset, config.sequenceTimeoutMs ?? DEFAULT_SEQUENCE_TIMEOUT_MS);
410
+ };
411
+
412
+ const dispose = function dispose(): void {
413
+ clearBufferAndTimer();
414
+ };
415
+
416
+ const getParsedHotkey = function getParsedHotkey(hotkey: string): ParsedHotkey {
417
+ const cacheKey = `${hotkey}:${config.leader ?? ""}`;
418
+ let parsed = parseCache.get(cacheKey);
382
419
  if (!parsed) {
383
- parsed = parseHotkey(hotkey, config.leader)
384
- parseCache.set(cacheKey, parsed)
420
+ parsed = parseHotkey(hotkey, config.leader);
421
+ parseCache.set(cacheKey, parsed);
385
422
  }
386
- return parsed
387
- }
388
-
389
- function key(event: KeyEvent): KeyDispatchResult {
390
- const ctx = store.getSnapshot().context
423
+ return parsed;
424
+ };
425
+
426
+ const collectCandidates = function collectCandidates(
427
+ commands: ReadonlyMap<string, Command> | undefined,
428
+ currentMode: Mode,
429
+ cmdCtx: CommandContext,
430
+ ): {
431
+ singleStep: { command: Command; parsed: ParsedHotkey }[];
432
+ multiStep: { command: Command; hotkey: string; parsed: ParsedHotkey }[];
433
+ } {
434
+ const singleStep: { command: Command; parsed: ParsedHotkey }[] = [];
435
+ const multiStep: { command: Command; hotkey: string; parsed: ParsedHotkey }[] = [];
436
+
437
+ for (const command of commands?.values() ?? []) {
438
+ const commandModes = command.modes ?? DEFAULT_MODES;
439
+ if (!commandModes.includes(currentMode) || (command.when && !command.when(cmdCtx))) {
440
+ continue;
441
+ }
391
442
 
392
- // Arbitration: a topmost modal surface owns input; otherwise the root app.
393
- const surface = selectActiveModalSurface(ctx) ?? rootRecord
394
- const currentMode = surface.getMode()
395
- const cmdCtx = surface.buildCtx()
396
- const commands = ctx.commandsBySurface.get(surface.id)
443
+ const hotkey = config.keymap?.[command.id] ?? command.defaultHotkey;
444
+ if (hotkey === undefined || hotkey === "") {
445
+ continue;
446
+ }
397
447
 
398
- // Collect eligible commands with their parsed hotkeys
399
- const singleStepCandidates: { command: Command; parsed: ParsedHotkey }[] = []
400
- const multiStepCandidates: { command: Command; hotkey: string; parsed: ParsedHotkey }[] = []
448
+ const parsed = getParsedHotkey(hotkey);
401
449
 
402
- if (commands) {
403
- for (const command of commands.values()) {
404
- const commandModes = command.modes ?? DEFAULT_MODES
405
- if (!commandModes.includes(currentMode)) continue
406
- if (command.when && !command.when(cmdCtx)) continue
450
+ // Unmatchable hotkeys (e.g. <leader> with no configured leader) register
451
+ // nothing rather than matching everything.
452
+ if (parsed.steps.length === 0) {
453
+ continue;
454
+ }
407
455
 
408
- const hotkey = config.keymap?.[command.id] ?? command.defaultHotkey
409
- if (!hotkey) continue
456
+ if (parsed.steps.length === 1) {
457
+ singleStep.push({ command, parsed });
458
+ } else {
459
+ multiStep.push({ command, hotkey, parsed });
460
+ }
461
+ }
410
462
 
411
- const parsed = getParsedHotkey(hotkey)
463
+ return { multiStep, singleStep };
464
+ };
412
465
 
413
- // Unmatchable hotkeys (e.g. <leader> with no configured leader) register
414
- // nothing rather than matching everything.
415
- if (parsed.steps.length === 0) continue
466
+ const key = function key(event: KeyEvent): KeyDispatchResult {
467
+ const ctx = store.getSnapshot().context;
416
468
 
417
- if (parsed.steps.length === 1) {
418
- singleStepCandidates.push({ command, parsed })
419
- } else {
420
- multiStepCandidates.push({ command, hotkey, parsed })
421
- }
422
- }
423
- }
469
+ // Arbitration: a topmost modal surface owns input; otherwise the root app.
470
+ const surface = selectActiveModalSurface(ctx) ?? rootRecord;
471
+ const currentMode = surface.getMode();
472
+ const cmdCtx = surface.buildCtx();
473
+ const { multiStep: multiStepCandidates, singleStep: singleStepCandidates } = collectCandidates(
474
+ ctx.commandsBySurface.get(surface.id),
475
+ currentMode,
476
+ cmdCtx,
477
+ );
424
478
 
425
479
  // Check multi-step sequences first (they consume buffer state)
426
480
  if (multiStepCandidates.length > 0) {
427
- const hotkeys = multiStepCandidates.map((candidate) => candidate.parsed)
428
- buffer = [...buffer, event]
429
- armTimer()
430
-
431
- let matchedIndex = -1
432
- for (let i = 0; i < hotkeys.length; i++) {
433
- if (matchesBuffer(buffer, hotkeys[i]!)) {
434
- matchedIndex = i
435
- break
481
+ const hotkeys = multiStepCandidates.map((candidate) => candidate.parsed);
482
+ buffer = [...buffer, event];
483
+ armTimer();
484
+
485
+ let matchedIndex = -1;
486
+ for (let i = 0; i < hotkeys.length; i += 1) {
487
+ if (matchesBuffer(buffer, hotkeys[i])) {
488
+ matchedIndex = i;
489
+ break;
436
490
  }
437
491
  }
438
492
 
439
493
  if (matchedIndex >= 0) {
440
- clearBufferAndTimer()
441
- store.trigger.sequenceReset()
442
- const matched = multiStepCandidates[matchedIndex]!.command
443
- return { handled: true, invoke: () => matched.handler(cmdCtx) }
494
+ clearBufferAndTimer();
495
+ store.trigger.sequenceReset();
496
+ const matched = multiStepCandidates[matchedIndex].command;
497
+ return {
498
+ handled: true,
499
+ invoke: (): void => {
500
+ void matched.handler(cmdCtx);
501
+ },
502
+ };
444
503
  }
445
504
 
446
- buffer = pruneBuffer(buffer, hotkeys)
447
- const pending = findPendingMatch(buffer, hotkeys)
505
+ buffer = pruneBuffer(buffer, hotkeys);
506
+ const pending = findPendingMatch(buffer, hotkeys);
448
507
 
449
508
  if (pending) {
450
- const firstCandidate = multiStepCandidates[pending.indexes[0]!]!
509
+ const firstCandidate = multiStepCandidates[pending.indexes[0]];
451
510
  const state: CommandSequenceState = {
452
- prefix: firstCandidate.parsed.steps.slice(0, pending.prefixLength),
453
511
  candidates: pending.indexes
454
- .map((idx) => multiStepCandidates[idx]!)
455
- .filter(({ command }) => !command.hidden)
512
+ .map((idx) => multiStepCandidates[idx])
513
+ .filter(({ command }) => command.hidden !== true)
456
514
  .map(({ command, hotkey, parsed }) => ({
457
515
  command,
516
+ group: ctx.groups.get(stepsKey(parsed.steps.slice(0, pending.prefixLength + 1))),
458
517
  hotkey,
459
- steps: parsed.steps,
518
+ nextStep: parsed.steps[pending.prefixLength],
460
519
  remainingSteps: parsed.steps.slice(pending.prefixLength),
461
- nextStep: parsed.steps[pending.prefixLength]!,
462
- group: ctx.groups.get(stepsKey(parsed.steps.slice(0, pending.prefixLength + 1))),
520
+ steps: parsed.steps,
463
521
  })),
464
- }
465
- store.trigger.sequencePending({ state })
466
- return { handled: true }
522
+ prefix: firstCandidate.parsed.steps.slice(0, pending.prefixLength),
523
+ };
524
+ store.trigger.sequencePending({ state });
525
+ return { handled: true };
467
526
  }
468
527
 
469
- store.trigger.sequenceReset()
528
+ store.trigger.sequenceReset();
470
529
  }
471
530
 
472
531
  // Check single-step matches
473
532
  for (const { command, parsed } of singleStepCandidates) {
474
- if (matchStep(event, parsed.steps[0]!)) {
475
- store.trigger.sequenceReset()
476
- return { handled: true, invoke: () => command.handler(cmdCtx) }
533
+ if (matchStep(event, parsed.steps[0])) {
534
+ store.trigger.sequenceReset();
535
+ return {
536
+ handled: true,
537
+ invoke: (): void => {
538
+ void command.handler(cmdCtx);
539
+ },
540
+ };
477
541
  }
478
542
  }
479
543
 
480
544
  // A modal surface swallows unhandled keys: dispatch never falls through to
481
545
  // the root app while a modal surface is topmost. (The caller does not
482
546
  // preventDefault unmatched keys — same as today.)
483
- return { handled: false }
484
- }
485
-
486
- function pushSurface(surface: SurfaceRecord): () => void {
487
- surface.order = orderCounter++
488
- const before = selectActiveModalSurface(store.getSnapshot().context)
489
- store.trigger.surfacePushed({ surface })
490
- const after = selectActiveModalSurface(store.getSnapshot().context)
547
+ return { handled: false };
548
+ };
549
+
550
+ const pushSurface = function pushSurface(surface: SurfaceRecord): () => void {
551
+ surface.order = orderCounter;
552
+ orderCounter += 1;
553
+ const before = selectActiveModalSurface(store.getSnapshot().context);
554
+ store.trigger.surfacePushed({ surface });
555
+ const after = selectActiveModalSurface(store.getSnapshot().context);
491
556
  // Keep the wrapper buffer consistent with the transition's sequence-clear
492
557
  // rule: clear exactly when keyboard ownership changed.
493
- if (before !== after) clearBufferAndTimer()
558
+ if (before !== after) {
559
+ clearBufferAndTimer();
560
+ }
494
561
 
495
562
  return () => {
496
- const beforePop = selectActiveModalSurface(store.getSnapshot().context)
497
- store.trigger.surfacePopped({ surface })
498
- const afterPop = selectActiveModalSurface(store.getSnapshot().context)
499
- if (beforePop !== afterPop) clearBufferAndTimer()
500
- }
501
- }
563
+ const beforePop = selectActiveModalSurface(store.getSnapshot().context);
564
+ store.trigger.surfacePopped({ surface });
565
+ const afterPop = selectActiveModalSurface(store.getSnapshot().context);
566
+ if (beforePop !== afterPop) {
567
+ clearBufferAndTimer();
568
+ }
569
+ };
570
+ };
502
571
 
503
- function modeChanged(surfaceId: string): void {
504
- clearBufferAndTimer()
505
- store.trigger.modeChanged({ surfaceId })
506
- }
572
+ const modeChanged = function modeChanged(surfaceId: string): void {
573
+ clearBufferAndTimer();
574
+ store.trigger.modeChanged({ surfaceId });
575
+ };
507
576
 
508
- function registryFor(record: SurfaceRecord): CommandRegistry {
509
- let registry = registries.get(record)
577
+ const registryFor = function registryFor(record: SurfaceRecord): CommandRegistry {
578
+ let registry = registries.get(record);
510
579
  if (!registry) {
511
580
  registry = {
512
581
  get commands() {
513
- const current = store.getSnapshot().context.commandsBySurface.get(record.id)
582
+ const current = store.getSnapshot().context.commandsBySurface.get(record.id);
514
583
  // The registry contract exposes a Map; the store's per-surface maps
515
584
  // are Maps at runtime (readonly-typed). Consumers must not mutate.
516
- return (current ?? new Map()) as Map<string, Command>
517
- },
518
- register(command: Command) {
519
- store.trigger.commandRegistered({ surfaceId: record.id, command })
520
- return () => {
521
- store.trigger.commandUnregistered({ surfaceId: record.id, command })
522
- }
585
+ // Deferred(lint-sweep): expose readonly command snapshots through an immutable registry API.
586
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- compatibility facade preserves the existing mutable Map API
587
+ return (current ?? new Map()) as Map<string, Command>;
523
588
  },
524
589
  invoke(id: string) {
525
- const ctx = store.getSnapshot().context
526
- const cmd = ctx.commandsBySurface.get(record.id)?.get(id)
527
- if (!cmd) return
528
- const cmdCtx = record.buildCtx()
590
+ const ctx = store.getSnapshot().context;
591
+ const cmd = ctx.commandsBySurface.get(record.id)?.get(id);
592
+ if (!cmd) {
593
+ return;
594
+ }
595
+ const cmdCtx = record.buildCtx();
529
596
  if (!cmd.when || cmd.when(cmdCtx)) {
530
- cmd.handler(cmdCtx)
597
+ const result = cmd.handler(cmdCtx);
598
+ if (result) {
599
+ void reportCommandFailure(result);
600
+ }
531
601
  }
532
602
  },
533
- }
534
- registries.set(record, registry)
603
+ register(command: Command) {
604
+ store.trigger.commandRegistered({ command, surfaceId: record.id });
605
+ return () => {
606
+ store.trigger.commandUnregistered({ command, surfaceId: record.id });
607
+ };
608
+ },
609
+ };
610
+ registries.set(record, registry);
535
611
  }
536
- return registry
537
- }
612
+ return registry;
613
+ };
538
614
 
539
- function setConfig(next: CommandStoreConfig): void {
540
- config = next
541
- }
615
+ const setConfig = function setConfig(next: CommandStoreConfig): void {
616
+ config = next;
617
+ };
542
618
 
543
619
  return {
544
- store,
545
- rootRecord,
546
- key,
547
- reset,
548
620
  dispose,
549
- pushSurface,
621
+ key,
550
622
  modeChanged,
623
+ pushSurface,
551
624
  registryFor,
625
+ reset,
626
+ rootRecord,
552
627
  setConfig,
553
- }
554
- }
628
+ store,
629
+ };
630
+ };