@tooee/commands 0.3.2 → 0.4.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.
@@ -41,6 +41,12 @@ export interface SurfaceRecord {
41
41
  depth: number;
42
42
  /** Monotonic registration order (tie-break), assigned by the wrapper on push. */
43
43
  order: number;
44
+ /**
45
+ * For `panel` surfaces: the id of the owning panel group. A panel surface
46
+ * arbitrates as active only when `activePanels.get(groupId) === id`. Ignored
47
+ * for other roles.
48
+ */
49
+ groupId?: string;
44
50
  /** Reads this surface's current local mode (mode stays in ModeProvider React state). */
45
51
  getMode: () => Mode;
46
52
  /** Builds the command context handed to this surface's handlers. */
@@ -57,6 +63,12 @@ export interface CommandStoreContext {
57
63
  /** Command groups keyed by prefixKey. */
58
64
  groups: ReadonlyMap<string, RegisteredCommandGroup>;
59
65
  contextSources: ReadonlyMap<string, ContextGetter>;
66
+ /**
67
+ * The active panel id per panel-group id. A panel group publishes its active
68
+ * panel here (see `panelActivated`); arbitration reads it to pick the active
69
+ * panel surface. Keyed by group id so nested groups are representable.
70
+ */
71
+ activePanels: ReadonlyMap<string, string>;
60
72
  /** Renderable pending-sequence display state (which-key input). */
61
73
  sequence: CommandSequenceState | null;
62
74
  }
@@ -86,6 +98,53 @@ export const selectActiveModalSurface = function selectActiveModalSurface(
86
98
  return best;
87
99
  };
88
100
 
101
+ /**
102
+ * The active panel surface, or null: a `role === "panel"` record whose id is its
103
+ * group's active id (`activePanels.get(groupId) === id`). Passive/modal/root
104
+ * surfaces never qualify.
105
+ *
106
+ * When several groups are active (nested panels), the deepest active panel wins
107
+ * (order breaks depth ties) — the innermost link of the active chain. v1 tests
108
+ * exercise a single group; the map-per-group shape keeps nesting representable
109
+ * at no cost, and this heuristic resolves the innermost active panel for any
110
+ * well-formed nesting (an inner group mounted inside its outer group's active
111
+ * panel). Panels never win via depth/order against a *modal* surface — modal
112
+ * arbitration is a separate, earlier step (I-5).
113
+ */
114
+ export const selectActivePanelSurface = function selectActivePanelSurface(
115
+ ctx: CommandStoreContext,
116
+ ): SurfaceRecord | null {
117
+ let best: SurfaceRecord | null = null;
118
+ for (const record of ctx.surfaces) {
119
+ if (record.role !== "panel" || record.groupId === undefined) {
120
+ continue;
121
+ }
122
+ if (ctx.activePanels.get(record.groupId) !== record.id) {
123
+ continue;
124
+ }
125
+ if (
126
+ best === null ||
127
+ record.depth > best.depth ||
128
+ (record.depth === best.depth && record.order > best.order)
129
+ ) {
130
+ best = record;
131
+ }
132
+ }
133
+ return best;
134
+ };
135
+
136
+ /**
137
+ * The surface that currently owns keyboard input, or null when the root app
138
+ * owns it: topmost modal → active panel → null. Mirrors the non-root part of
139
+ * key-dispatch arbitration and is used both to reconcile the sequence buffer
140
+ * across ownership changes and to back the surface-aware hooks.
141
+ */
142
+ export const selectKeyboardOwnerSurface = function selectKeyboardOwnerSurface(
143
+ ctx: CommandStoreContext,
144
+ ): SurfaceRecord | null {
145
+ return selectActiveModalSurface(ctx) ?? selectActivePanelSurface(ctx);
146
+ };
147
+
89
148
  /**
90
149
  * Commands registered on a surface. Returns a fresh array; memoize against
91
150
  * `selectSurfaceCommandMap` identity in render paths.
@@ -148,11 +207,14 @@ export const stepsKey = function stepsKey(steps: readonly ParsedStep[]): string
148
207
  // --- Store -------------------------------------------------------------------
149
208
 
150
209
  /**
151
- * Sequence-clear rule for surface transitions: a pending chord (display state)
152
- * is cleared exactly when the transition changes which surface record owns
153
- * keyboard input. Pushing/popping a passive surface (e.g. which-key) keeps the
154
- * sequence it is displaying; replacing the active modal surface with a same-id
155
- * record clears it (F-09) because the record identity changes.
210
+ * Sequence-clear rule for surface/activation transitions: a pending chord
211
+ * (display state) is cleared exactly when the transition changes which surface
212
+ * record owns keyboard input — where ownership is `selectKeyboardOwnerSurface`
213
+ * (topmost modal → active panel → root). Pushing/popping a passive surface
214
+ * (e.g. which-key) keeps the sequence it is displaying; replacing the active
215
+ * surface with a same-id record clears it (F-09) because the record identity
216
+ * changes; activating a different panel clears it because the owner record
217
+ * changes.
156
218
  */
157
219
  const sequenceAfterStackChange = function sequenceAfterStackChange(
158
220
  before: SurfaceRecord | null,
@@ -243,6 +305,42 @@ const createBaseStore = function createBaseStore(initialContext: CommandStoreCon
243
305
  // A mode change is a transition, not a post-render repair: any pending
244
306
  // chord is invalidated (F-08 — including surface-local mode changes).
245
307
  ctx.sequence === null ? ctx : { ...ctx, sequence: null },
308
+ panelActivated: (
309
+ ctx: CommandStoreContext,
310
+ event: { groupId: string; panelId: string },
311
+ ): CommandStoreContext => {
312
+ if (ctx.activePanels.get(event.groupId) === event.panelId) {
313
+ return ctx;
314
+ }
315
+ const before = selectKeyboardOwnerSurface(ctx);
316
+ const activePanels = new Map([
317
+ ...ctx.activePanels,
318
+ [event.groupId, event.panelId] as const,
319
+ ]);
320
+ const after = selectKeyboardOwnerSurface({ ...ctx, activePanels });
321
+ return {
322
+ ...ctx,
323
+ activePanels,
324
+ sequence: sequenceAfterStackChange(before, after, ctx.sequence),
325
+ };
326
+ },
327
+ panelGroupRemoved: (
328
+ ctx: CommandStoreContext,
329
+ event: { groupId: string },
330
+ ): CommandStoreContext => {
331
+ if (!ctx.activePanels.has(event.groupId)) {
332
+ return ctx;
333
+ }
334
+ const before = selectKeyboardOwnerSurface(ctx);
335
+ const activePanels = new Map(ctx.activePanels);
336
+ activePanels.delete(event.groupId);
337
+ const after = selectKeyboardOwnerSurface({ ...ctx, activePanels });
338
+ return {
339
+ ...ctx,
340
+ activePanels,
341
+ sequence: sequenceAfterStackChange(before, after, ctx.sequence),
342
+ };
343
+ },
246
344
  sequencePending: (
247
345
  ctx: CommandStoreContext,
248
346
  event: { state: CommandSequenceState },
@@ -258,8 +356,8 @@ const createBaseStore = function createBaseStore(initialContext: CommandStoreCon
258
356
  if (surfaces.length === ctx.surfaces.length) {
259
357
  return ctx;
260
358
  }
261
- const before = selectActiveModalSurface(ctx);
262
- const after = selectActiveModalSurface({ ...ctx, surfaces });
359
+ const before = selectKeyboardOwnerSurface(ctx);
360
+ const after = selectKeyboardOwnerSurface({ ...ctx, surfaces });
263
361
  return {
264
362
  ...ctx,
265
363
  sequence: sequenceAfterStackChange(before, after, ctx.sequence),
@@ -270,9 +368,9 @@ const createBaseStore = function createBaseStore(initialContext: CommandStoreCon
270
368
  ctx: CommandStoreContext,
271
369
  event: { surface: SurfaceRecord },
272
370
  ): CommandStoreContext => {
273
- const before = selectActiveModalSurface(ctx);
371
+ const before = selectKeyboardOwnerSurface(ctx);
274
372
  const surfaces = [...ctx.surfaces, event.surface];
275
- const after = selectActiveModalSurface({ ...ctx, surfaces });
373
+ const after = selectKeyboardOwnerSurface({ ...ctx, surfaces });
276
374
  return {
277
375
  ...ctx,
278
376
  sequence: sequenceAfterStackChange(before, after, ctx.sequence),
@@ -336,6 +434,13 @@ export interface CommandStore {
336
434
 
337
435
  /** Push a surface record; assigns registration order. Returns the pop cleanup. */
338
436
  pushSurface: (surface: SurfaceRecord) => () => void;
437
+ /**
438
+ * Publish a panel group's active panel. Clears the pending chord when it
439
+ * changes which surface owns keyboard input. Idempotent for an unchanged id.
440
+ */
441
+ activatePanel: (groupId: string, panelId: string) => void;
442
+ /** Forget a panel group's activation (e.g. the group unmounted). */
443
+ removePanelGroup: (groupId: string) => void;
339
444
  /** Notify a (root or surface-local) mode change: clears buffer + pending sequence. */
340
445
  modeChanged: (surfaceId: string) => void;
341
446
 
@@ -367,6 +472,7 @@ export const createCommandStore = function createCommandStore(
367
472
  };
368
473
 
369
474
  const store = createBaseStore({
475
+ activePanels: new Map(),
370
476
  commandsBySurface: new Map(),
371
477
  contextSources: new Map(),
372
478
  groups: new Map(),
@@ -383,6 +489,11 @@ export const createCommandStore = function createCommandStore(
383
489
  // IO-adjacent wrapper state: key buffer, timer, parse cache, order counter.
384
490
  let buffer: readonly KeyEvent[] = [];
385
491
  let timer: ReturnType<typeof setTimeout> | null = null;
492
+ // Id of the surface that owns the pending chord. Once a surface holds a
493
+ // multi-step chord, subsequent keys route only to it until the chord resolves
494
+ // or times out (§5.2) — mixing surfaces mid-chord is undefined. Null when no
495
+ // chord is pending.
496
+ let sequenceOwnerId: string | null = null;
386
497
  const parseCache = new Map<string, ParsedHotkey>();
387
498
  const registries = new Map<SurfaceRecord, CommandRegistry>();
388
499
  let orderCounter = 1;
@@ -394,8 +505,11 @@ export const createCommandStore = function createCommandStore(
394
505
  }
395
506
  };
396
507
 
508
+ // Clearing the buffer always relinquishes chord ownership: the two are one
509
+ // unit of pending-sequence state.
397
510
  const clearBufferAndTimer = function clearBufferAndTimer(): void {
398
511
  buffer = [];
512
+ sequenceOwnerId = null;
399
513
  clearTimer();
400
514
  };
401
515
 
@@ -463,15 +577,28 @@ export const createCommandStore = function createCommandStore(
463
577
  return { multiStep, singleStep };
464
578
  };
465
579
 
466
- const key = function key(event: KeyEvent): KeyDispatchResult {
467
- const ctx = store.getSnapshot().context;
580
+ /** Outcome of dispatching one key against a single surface's registry. */
581
+ type SurfaceDispatch =
582
+ | { outcome: "invoke"; invoke: () => void }
583
+ | { outcome: "pending" }
584
+ | { outcome: "miss" };
468
585
 
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();
586
+ /**
587
+ * Run one key against one surface's candidates. Owns the shared buffer while
588
+ * it does so: on a full match it clears the buffer and resets the sequence;
589
+ * on a partial multi-step it leaves the buffer populated and publishes the
590
+ * pending display; on a miss it leaves the buffer empty (pruned) so a caller
591
+ * may retry the key against another surface (fall-through).
592
+ */
593
+ const runSurface = function runSurface(
594
+ record: SurfaceRecord,
595
+ event: KeyEvent,
596
+ ctx: CommandStoreContext,
597
+ ): SurfaceDispatch {
598
+ const currentMode = record.getMode();
599
+ const cmdCtx = record.buildCtx();
473
600
  const { multiStep: multiStepCandidates, singleStep: singleStepCandidates } = collectCandidates(
474
- ctx.commandsBySurface.get(surface.id),
601
+ ctx.commandsBySurface.get(record.id),
475
602
  currentMode,
476
603
  cmdCtx,
477
604
  );
@@ -495,10 +622,10 @@ export const createCommandStore = function createCommandStore(
495
622
  store.trigger.sequenceReset();
496
623
  const matched = multiStepCandidates[matchedIndex].command;
497
624
  return {
498
- handled: true,
499
625
  invoke: (): void => {
500
626
  void matched.handler(cmdCtx);
501
627
  },
628
+ outcome: "invoke",
502
629
  };
503
630
  }
504
631
 
@@ -522,9 +649,14 @@ export const createCommandStore = function createCommandStore(
522
649
  prefix: firstCandidate.parsed.steps.slice(0, pending.prefixLength),
523
650
  };
524
651
  store.trigger.sequencePending({ state });
525
- return { handled: true };
652
+ return { outcome: "pending" };
526
653
  }
527
654
 
655
+ // No pending prefix survived. `pruneBuffer` only bounds history; it does
656
+ // not guarantee an empty buffer, so explicitly discard this surface's
657
+ // attempted sequence before single-step matching or fall-through. This
658
+ // also cancels the now-irrelevant timeout and relinquishes ownership.
659
+ clearBufferAndTimer();
528
660
  store.trigger.sequenceReset();
529
661
  }
530
662
 
@@ -533,26 +665,103 @@ export const createCommandStore = function createCommandStore(
533
665
  if (matchStep(event, parsed.steps[0])) {
534
666
  store.trigger.sequenceReset();
535
667
  return {
536
- handled: true,
537
668
  invoke: (): void => {
538
669
  void command.handler(cmdCtx);
539
670
  },
671
+ outcome: "invoke",
540
672
  };
541
673
  }
542
674
  }
543
675
 
544
- // A modal surface swallows unhandled keys: dispatch never falls through to
545
- // the root app while a modal surface is topmost. (The caller does not
546
- // preventDefault unmatched keys — same as today.)
676
+ // A miss is a dispatch boundary: no sequence contribution from this
677
+ // surface may leak into a fall-through attempt or a later physical key.
678
+ clearBufferAndTimer();
679
+ store.trigger.sequenceReset();
680
+ return { outcome: "miss" };
681
+ };
682
+
683
+ /**
684
+ * Translate a surface dispatch into the caller-facing result and record chord
685
+ * ownership: a pending chord makes `ownerId` the sequence owner; any resolved
686
+ * outcome (invoke/miss) relinquishes ownership. A `miss` is `handled: false`,
687
+ * so the caller does not preventDefault — matching today's modal-swallow and
688
+ * unhandled-key semantics.
689
+ */
690
+ const finishDispatch = function finishDispatch(
691
+ dispatch: SurfaceDispatch,
692
+ ownerId: string,
693
+ ): KeyDispatchResult {
694
+ if (dispatch.outcome === "pending") {
695
+ sequenceOwnerId = ownerId;
696
+ return { handled: true };
697
+ }
698
+ sequenceOwnerId = null;
699
+ if (dispatch.outcome === "invoke") {
700
+ return { handled: true, invoke: dispatch.invoke };
701
+ }
547
702
  return { handled: false };
548
703
  };
549
704
 
705
+ const resolveOwner = function resolveOwner(
706
+ ctx: CommandStoreContext,
707
+ ownerId: string,
708
+ ): SurfaceRecord | null {
709
+ if (ownerId === ROOT_SURFACE_ID) {
710
+ return rootRecord;
711
+ }
712
+ return ctx.surfaces.find((record) => record.id === ownerId) ?? null;
713
+ };
714
+
715
+ const key = function key(event: KeyEvent): KeyDispatchResult {
716
+ const ctx = store.getSnapshot().context;
717
+
718
+ // Pending-chord ownership: while a chord is buffered, its owner keeps every
719
+ // subsequent key until the chord resolves or times out. Arbitration is
720
+ // suspended so a mid-chord activation/fall-through cannot split the chord.
721
+ if (buffer.length > 0 && sequenceOwnerId !== null) {
722
+ const owner = resolveOwner(ctx, sequenceOwnerId);
723
+ if (owner) {
724
+ return finishDispatch(runSurface(owner, event, ctx), sequenceOwnerId);
725
+ }
726
+ // The owner disappeared without a transition clearing the chord: drop it
727
+ // and re-arbitrate this key from a clean buffer.
728
+ clearBufferAndTimer();
729
+ }
730
+
731
+ // Arbitration: topmost modal → active panel → root.
732
+ const modal = selectActiveModalSurface(ctx);
733
+ if (modal) {
734
+ // A modal surface swallows unhandled keys: dispatch never falls through
735
+ // to lower surfaces while a modal surface is topmost.
736
+ return finishDispatch(runSurface(modal, event, ctx), modal.id);
737
+ }
738
+
739
+ const panel = selectActivePanelSurface(ctx);
740
+ if (panel) {
741
+ const dispatch = runSurface(panel, event, ctx);
742
+ if (dispatch.outcome !== "miss") {
743
+ return finishDispatch(dispatch, panel.id);
744
+ }
745
+ // Insert mode belongs to the focused editor/input. Never retry its typed
746
+ // key against root commands (including panel-switch Tab bindings).
747
+ if (panel.getMode() === "insert") {
748
+ return finishDispatch(dispatch, panel.id);
749
+ }
750
+ // Fall-through (§5.2): the active panel neither matched nor holds a
751
+ // pending chord, so the enclosing surface (root) gets the key. A panel
752
+ // command that DID match shadows the root command (handled above). The
753
+ // buffer is empty after a panel miss, so root dispatch starts clean.
754
+ }
755
+
756
+ return finishDispatch(runSurface(rootRecord, event, ctx), ROOT_SURFACE_ID);
757
+ };
758
+
550
759
  const pushSurface = function pushSurface(surface: SurfaceRecord): () => void {
551
760
  surface.order = orderCounter;
552
761
  orderCounter += 1;
553
- const before = selectActiveModalSurface(store.getSnapshot().context);
762
+ const before = selectKeyboardOwnerSurface(store.getSnapshot().context);
554
763
  store.trigger.surfacePushed({ surface });
555
- const after = selectActiveModalSurface(store.getSnapshot().context);
764
+ const after = selectKeyboardOwnerSurface(store.getSnapshot().context);
556
765
  // Keep the wrapper buffer consistent with the transition's sequence-clear
557
766
  // rule: clear exactly when keyboard ownership changed.
558
767
  if (before !== after) {
@@ -560,15 +769,35 @@ export const createCommandStore = function createCommandStore(
560
769
  }
561
770
 
562
771
  return () => {
563
- const beforePop = selectActiveModalSurface(store.getSnapshot().context);
772
+ const beforePop = selectKeyboardOwnerSurface(store.getSnapshot().context);
564
773
  store.trigger.surfacePopped({ surface });
565
- const afterPop = selectActiveModalSurface(store.getSnapshot().context);
774
+ const afterPop = selectKeyboardOwnerSurface(store.getSnapshot().context);
566
775
  if (beforePop !== afterPop) {
567
776
  clearBufferAndTimer();
568
777
  }
569
778
  };
570
779
  };
571
780
 
781
+ const activatePanel = function activatePanel(groupId: string, panelId: string): void {
782
+ const before = selectKeyboardOwnerSurface(store.getSnapshot().context);
783
+ store.trigger.panelActivated({ groupId, panelId });
784
+ const after = selectKeyboardOwnerSurface(store.getSnapshot().context);
785
+ // Activation is an ownership change: clear the wrapper buffer whenever the
786
+ // owning surface record changes (mirrors pushSurface / the store rule).
787
+ if (before !== after) {
788
+ clearBufferAndTimer();
789
+ }
790
+ };
791
+
792
+ const removePanelGroup = function removePanelGroup(groupId: string): void {
793
+ const before = selectKeyboardOwnerSurface(store.getSnapshot().context);
794
+ store.trigger.panelGroupRemoved({ groupId });
795
+ const after = selectKeyboardOwnerSurface(store.getSnapshot().context);
796
+ if (before !== after) {
797
+ clearBufferAndTimer();
798
+ }
799
+ };
800
+
572
801
  const modeChanged = function modeChanged(surfaceId: string): void {
573
802
  clearBufferAndTimer();
574
803
  store.trigger.modeChanged({ surfaceId });
@@ -617,11 +846,13 @@ export const createCommandStore = function createCommandStore(
617
846
  };
618
847
 
619
848
  return {
849
+ activatePanel,
620
850
  dispose,
621
851
  key,
622
852
  modeChanged,
623
853
  pushSurface,
624
854
  registryFor,
855
+ removePanelGroup,
625
856
  reset,
626
857
  rootRecord,
627
858
  setConfig,
package/src/context.tsx CHANGED
@@ -18,7 +18,8 @@ import { parseHotkey } from "./parse.js";
18
18
  import {
19
19
  ROOT_SURFACE_ID,
20
20
  createCommandStore,
21
- selectActiveModalSurface,
21
+ selectActivePanelSurface,
22
+ selectKeyboardOwnerSurface,
22
23
  selectSequence,
23
24
  selectSurfaceCommandMap,
24
25
  stepsKey,
@@ -221,6 +222,12 @@ export interface CommandSurfaceProviderProps {
221
222
  id: string;
222
223
  /** Interaction role (default "modal"). */
223
224
  role?: CommandSurfaceRole;
225
+ /**
226
+ * For `role: "panel"` surfaces: the owning panel group's id. The surface only
227
+ * arbitrates as active while `activePanels.get(groupId) === id`. Ignored for
228
+ * other roles. Set by `@tooee/panels`'s `Panel`.
229
+ */
230
+ groupId?: string;
224
231
  /** Initial local mode for this surface (default "cursor"). */
225
232
  initialMode?: Mode;
226
233
  }
@@ -237,6 +244,7 @@ export const CommandSurfaceProvider = function CommandSurfaceProvider({
237
244
  children,
238
245
  id,
239
246
  role = "modal",
247
+ groupId,
240
248
  initialMode = "cursor",
241
249
  }: CommandSurfaceProviderProps): ReactNode {
242
250
  const parent = useContext(CommandContext);
@@ -255,7 +263,7 @@ export const CommandSurfaceProvider = function CommandSurfaceProvider({
255
263
  <ModeProvider initialMode={initialMode} onModeChange={handleModeChange}>
256
264
  {/* Deferred(lint-sweep): preserve top-down provider/wrapper organization. */}
257
265
  {/* oxlint-disable-next-line no-use-before-define -- inner surface is deliberately declared below */}
258
- <CommandSurfaceInner id={id} role={role}>
266
+ <CommandSurfaceInner id={id} role={role} groupId={groupId}>
259
267
  {children}
260
268
  {/* oxlint-disable-next-line no-use-before-define -- closing inner surface declaration is below provider */}
261
269
  </CommandSurfaceInner>
@@ -267,10 +275,12 @@ const CommandSurfaceInner = function CommandSurfaceInner({
267
275
  children,
268
276
  id,
269
277
  role,
278
+ groupId,
270
279
  }: {
271
280
  children: ReactNode;
272
281
  id: string;
273
282
  role: CommandSurfaceRole;
283
+ groupId?: string;
274
284
  }): ReactNode {
275
285
  const parent = useContext(CommandContext);
276
286
  if (!parent) {
@@ -306,12 +316,14 @@ const CommandSurfaceInner = function CommandSurfaceInner({
306
316
  recordRef.current === null ||
307
317
  recordRef.current.id !== id ||
308
318
  recordRef.current.role !== role ||
309
- recordRef.current.depth !== depth
319
+ recordRef.current.depth !== depth ||
320
+ recordRef.current.groupId !== groupId
310
321
  ) {
311
322
  recordRef.current = {
312
323
  buildCtx: () => buildCtxRef.current(),
313
324
  depth,
314
325
  getMode: () => modeRef.current,
326
+ groupId,
315
327
  id,
316
328
  order: 0,
317
329
  role,
@@ -443,18 +455,20 @@ export const useCommandSurfaceId = function useCommandSurfaceId(): string {
443
455
  };
444
456
 
445
457
  /**
446
- * Metadata for the topmost modal command surface, or null when the root app is
447
- * the active surface. Intended for which-key/help to read shortcuts from the
448
- * active interaction surface. `commands` is reactive (F-13).
458
+ * Metadata for the surface that currently owns keyboard input — the topmost
459
+ * modal surface, else the active panel, else null when the root app owns it.
460
+ * Intended for which-key/help to read shortcuts from the active interaction
461
+ * surface, and used as a suspension guard by contained editors (a surface whose
462
+ * id differs from the owner is suspended). `commands` is reactive (F-13).
449
463
  */
450
464
  export const useActiveCommandSurface =
451
465
  function useActiveCommandSurface(): ActiveCommandSurface | null {
452
466
  const ctx = useContext(CommandContext);
453
467
  const { store } = ctx?.commandStore ?? FALLBACK_COMMAND_STORE;
454
468
 
455
- const record = useSelector(store, (s) => selectActiveModalSurface(s.context));
469
+ const record = useSelector(store, (s) => selectKeyboardOwnerSurface(s.context));
456
470
  const commandMap = useSelector(store, (s) => {
457
- const active = selectActiveModalSurface(s.context);
471
+ const active = selectKeyboardOwnerSurface(s.context);
458
472
  return active ? selectSurfaceCommandMap(s.context, active.id) : undefined;
459
473
  });
460
474
 
@@ -473,8 +487,9 @@ export const useActiveCommandSurface =
473
487
  };
474
488
 
475
489
  /**
476
- * Commands registered on a surface (reactive). Defaults to the active modal
477
- * surface, falling back to the root surface when none is active.
490
+ * Commands registered on a surface (reactive). Defaults to the keyboard-owner
491
+ * surface (topmost modal, else active panel), falling back to the root surface
492
+ * when none is active.
478
493
  */
479
494
  export const useSurfaceCommands = function useSurfaceCommands(
480
495
  surfaceId?: string,
@@ -483,13 +498,85 @@ export const useSurfaceCommands = function useSurfaceCommands(
483
498
  const { store } = ctx?.commandStore ?? FALLBACK_COMMAND_STORE;
484
499
 
485
500
  const commandMap = useSelector(store, (s) => {
486
- const id = surfaceId ?? selectActiveModalSurface(s.context)?.id ?? ROOT_SURFACE_ID;
501
+ const id = surfaceId ?? selectKeyboardOwnerSurface(s.context)?.id ?? ROOT_SURFACE_ID;
487
502
  return selectSurfaceCommandMap(s.context, id);
488
503
  });
489
504
 
490
505
  return useMemo(() => (commandMap ? [...commandMap.values()] : []), [commandMap]);
491
506
  };
492
507
 
508
+ export interface EffectiveCommands {
509
+ /** Commands invocable from the current context, active-panel first. */
510
+ commands: Command[];
511
+ /** Invoke by id, routed to the surface that owns the command (panel, else root). */
512
+ invoke: (id: string) => void;
513
+ }
514
+
515
+ /**
516
+ * The command set a palette should present under panel fall-through: the active
517
+ * panel's commands plus the root's, mirroring dispatch. When a panel is active,
518
+ * a root command whose hotkey the panel shadows keeps its palette entry (still
519
+ * invocable there) but drops the now-misleading hotkey hint. With no active
520
+ * panel this is exactly the root command set, so non-panel apps are unchanged.
521
+ *
522
+ * Shadowing is computed on `defaultHotkey` — matching what the palette renders —
523
+ * so a `keymap`-remapped shadow is not reflected in the hint (a display-only
524
+ * edge; dispatch itself shadows correctly via the store).
525
+ */
526
+ export const useEffectiveCommands = function useEffectiveCommands(): EffectiveCommands {
527
+ const ctx = useContext(CommandContext);
528
+ if (!ctx) {
529
+ throw new Error("useEffectiveCommands must be used within a CommandProvider");
530
+ }
531
+ const { commandStore } = ctx;
532
+ const { store } = commandStore;
533
+
534
+ const panelMap = useSelector(store, (s) => {
535
+ const panel = selectActivePanelSurface(s.context);
536
+ return panel ? selectSurfaceCommandMap(s.context, panel.id) : undefined;
537
+ });
538
+ const rootMap = useSelector(store, (s) => selectSurfaceCommandMap(s.context, ROOT_SURFACE_ID));
539
+ const hasPanel = useSelector(store, (s) => selectActivePanelSurface(s.context) !== null);
540
+
541
+ return useMemo(() => {
542
+ const rootCommands = rootMap ? [...rootMap.values()] : [];
543
+ const rootInvoke = (id: string): void => {
544
+ commandStore.registryFor(commandStore.rootRecord).invoke(id);
545
+ };
546
+ if (!hasPanel) {
547
+ return { commands: rootCommands, invoke: rootInvoke };
548
+ }
549
+
550
+ const panelCommands = panelMap ? [...panelMap.values()] : [];
551
+ const panelIds = new Set(panelCommands.map((command) => command.id));
552
+ const shadowed = new Set(
553
+ panelCommands
554
+ .map((command) => command.defaultHotkey)
555
+ .filter((hotkey): hotkey is string => hotkey !== undefined && hotkey !== ""),
556
+ );
557
+ const effectiveRoot = rootCommands
558
+ .filter((command) => !panelIds.has(command.id))
559
+ .map((command) =>
560
+ command.defaultHotkey !== undefined && shadowed.has(command.defaultHotkey)
561
+ ? { ...command, defaultHotkey: undefined }
562
+ : command,
563
+ );
564
+
565
+ const invoke = (id: string): void => {
566
+ if (panelIds.has(id)) {
567
+ const panel = selectActivePanelSurface(store.getSnapshot().context);
568
+ if (panel) {
569
+ commandStore.registryFor(panel).invoke(id);
570
+ return;
571
+ }
572
+ }
573
+ rootInvoke(id);
574
+ };
575
+
576
+ return { commands: [...panelCommands, ...effectiveRoot], invoke };
577
+ }, [panelMap, rootMap, hasPanel, commandStore, store]);
578
+ };
579
+
493
580
  /**
494
581
  * Advanced/internal — subject to change. The command store instance backing
495
582
  * this provider tree, for bridges that must reach the dispatch machinery
package/src/index.ts CHANGED
@@ -20,6 +20,8 @@ export { ModeProvider, useMode, useSetMode } from "./mode.js";
20
20
  export type { ModeProviderProps } from "./mode.js";
21
21
  export { parseHotkey } from "./parse.js";
22
22
  export { matchStep } from "./match.js";
23
+ export { ScreenScopeProvider, useScreenScope } from "./screen-focus.js";
24
+ export type { ScreenScopeState } from "./screen-focus.js";
23
25
  export { DEFAULT_SEQUENCE_TIMEOUT_MS, SequenceTracker } from "./sequence.js";
24
26
  export type {
25
27
  SequenceFeedResult,
@@ -30,6 +32,7 @@ export {
30
32
  CommandProvider,
31
33
  CommandSurfaceProvider,
32
34
  useActiveCommandSurface,
35
+ useEffectiveCommands,
33
36
  useBuildCommandContext,
34
37
  useCommandContext,
35
38
  useCommandGroup,
@@ -45,7 +48,9 @@ export {
45
48
  ROOT_SURFACE_ID,
46
49
  createCommandStore,
47
50
  selectActiveModalSurface,
51
+ selectActivePanelSurface,
48
52
  selectGroups,
53
+ selectKeyboardOwnerSurface,
49
54
  selectSequence,
50
55
  selectSurfaceCommandMap,
51
56
  selectSurfaceCommands,
@@ -60,7 +65,11 @@ export type {
60
65
  KeyDispatchResult,
61
66
  SurfaceRecord,
62
67
  } from "./command-store.js";
63
- export type { CommandProviderProps, CommandSurfaceProviderProps } from "./context.js";
68
+ export type {
69
+ CommandProviderProps,
70
+ CommandSurfaceProviderProps,
71
+ EffectiveCommands,
72
+ } from "./context.js";
64
73
  export { useCommand } from "./use-command.js";
65
74
  export type { UseCommandOptions } from "./use-command.js";
66
75
  export { useActions } from "./use-actions.js";