@tooee/commands 0.7.2 → 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
@@ -1,29 +1,16 @@
1
1
  import { createStore } from "@xstate/store";
2
- import type { KeyEvent } from "@opentui/core";
3
2
  import type {
4
3
  Command,
5
4
  CommandContext,
6
- CommandRegistry,
7
5
  CommandSequenceState,
8
6
  CommandSurfaceRole,
9
- ParsedHotkey,
10
7
  ParsedStep,
11
8
  RegisteredCommandGroup,
12
9
  } from "./types.js";
13
10
  import type { Mode } from "./mode.js";
14
- import { parseHotkey } from "./parse.js";
15
- import { matchStep } from "./match.js";
16
- import {
17
- DEFAULT_SEQUENCE_TIMEOUT_MS,
18
- findPendingMatch,
19
- matchesBuffer,
20
- pruneBuffer,
21
- } from "./sequence.js";
22
11
 
23
12
  export const ROOT_SURFACE_ID = "__root";
24
13
 
25
- const DEFAULT_MODES: Mode[] = ["cursor"];
26
-
27
14
  /**
28
15
  * A surface as tracked by the store. The root app is `surfaces[0]`, always
29
16
  * present, with role `"root"` — it never arbitrates as modal.
@@ -224,7 +211,7 @@ const sequenceAfterStackChange = function sequenceAfterStackChange(
224
211
  return before === after ? sequence : null;
225
212
  };
226
213
 
227
- const createBaseStore = function createBaseStore(initialContext: CommandStoreContext) {
214
+ export const createBaseStore = function createBaseStore(initialContext: CommandStoreContext) {
228
215
  return createStore({
229
216
  context: initialContext,
230
217
  on: {
@@ -382,480 +369,3 @@ const createBaseStore = function createBaseStore(initialContext: CommandStoreCon
382
369
  };
383
370
 
384
371
  export type CommandStoreInstance = ReturnType<typeof createBaseStore>;
385
-
386
- // --- Wrapper -----------------------------------------------------------------
387
-
388
- export interface KeyDispatchResult {
389
- handled: boolean;
390
- /**
391
- * Present on a full command match. The caller (the `useKeyboard` effect)
392
- * calls `preventDefault()` and then `invoke()` synchronously, preserving
393
- * today's dispatch order and `event.defaultPrevented` semantics.
394
- */
395
- invoke?: () => void;
396
- }
397
-
398
- export interface CommandStoreConfig {
399
- leader?: string;
400
- keymap?: Record<string, string>;
401
- sequenceTimeoutMs?: number;
402
- }
403
-
404
- export interface CreateCommandStoreOptions extends CommandStoreConfig {
405
- /** Root surface accessors, provided by the command provider/dispatcher. */
406
- root: { getMode: () => Mode; buildCtx: () => CommandContext };
407
- }
408
-
409
- /**
410
- * The single writer around the store. Owns the two pieces of IO-adjacent,
411
- * non-render state: the key buffer (not render state — putting it in store
412
- * context would notify subscribers on every keystroke) and the sequence
413
- * timeout timer. The renderable `sequence` display state lives in the store.
414
- */
415
- export interface CommandStore {
416
- /** The underlying @xstate/store instance (subscribe/getSnapshot/trigger). */
417
- store: CommandStoreInstance;
418
- /** The always-present root surface record (`surfaces[0]`). */
419
- rootRecord: SurfaceRecord;
420
-
421
- /**
422
- * Feed a key event: arbitrates the active surface, filters candidates by
423
- * mode/when, runs the pure sequence matchers against the internal buffer,
424
- * triggers sequencePending/sequenceReset as needed, schedules/clears the
425
- * timeout, and returns what happened so the caller can preventDefault and
426
- * invoke synchronously.
427
- */
428
- key: (event: KeyEvent) => KeyDispatchResult;
429
-
430
- /** Clears buffer + timer and triggers sequenceReset. Idempotent. */
431
- reset: () => void;
432
- /** Clears buffer + timer permanently, without touching store state. Called on dispatcher unmount. */
433
- dispose: () => void;
434
-
435
- /** Push a surface record; assigns registration order. Returns the pop cleanup. */
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;
444
- /** Notify a (root or surface-local) mode change: clears buffer + pending sequence. */
445
- modeChanged: (surfaceId: string) => void;
446
-
447
- /** Back-compat CommandRegistry facade for a surface record (stable per record). */
448
- registryFor: (record: SurfaceRecord) => CommandRegistry;
449
-
450
- /** Update live config (leader/keymap/timeout are read per dispatch, as before). */
451
- setConfig: (config: CommandStoreConfig) => void;
452
- }
453
-
454
- const reportCommandFailure = async function reportCommandFailure(result: Promise<void>) {
455
- try {
456
- await result;
457
- } catch (error: unknown) {
458
- console.error("Command handler failed", error);
459
- }
460
- };
461
-
462
- export const createCommandStore = function createCommandStore(
463
- options: CreateCommandStoreOptions,
464
- ): CommandStore {
465
- const rootRecord: SurfaceRecord = {
466
- buildCtx: options.root.buildCtx,
467
- depth: 0,
468
- getMode: options.root.getMode,
469
- id: ROOT_SURFACE_ID,
470
- order: 0,
471
- role: "root",
472
- };
473
-
474
- const store = createBaseStore({
475
- activePanels: new Map(),
476
- commandsBySurface: new Map(),
477
- contextSources: new Map(),
478
- groups: new Map(),
479
- sequence: null,
480
- surfaces: [rootRecord],
481
- });
482
-
483
- let config: CommandStoreConfig = {
484
- keymap: options.keymap,
485
- leader: options.leader,
486
- sequenceTimeoutMs: options.sequenceTimeoutMs,
487
- };
488
-
489
- // IO-adjacent wrapper state: key buffer, timer, parse cache, order counter.
490
- let buffer: readonly KeyEvent[] = [];
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;
497
- const parseCache = new Map<string, ParsedHotkey>();
498
- const registries = new Map<SurfaceRecord, CommandRegistry>();
499
- let orderCounter = 1;
500
-
501
- const clearTimer = function clearTimer(): void {
502
- if (timer !== null) {
503
- clearTimeout(timer);
504
- timer = null;
505
- }
506
- };
507
-
508
- // Clearing the buffer always relinquishes chord ownership: the two are one
509
- // unit of pending-sequence state.
510
- const clearBufferAndTimer = function clearBufferAndTimer(): void {
511
- buffer = [];
512
- sequenceOwnerId = null;
513
- clearTimer();
514
- };
515
-
516
- const reset = function reset(): void {
517
- clearBufferAndTimer();
518
- store.trigger.sequenceReset();
519
- };
520
-
521
- const armTimer = function armTimer(): void {
522
- clearTimer();
523
- timer = setTimeout(reset, config.sequenceTimeoutMs ?? DEFAULT_SEQUENCE_TIMEOUT_MS);
524
- };
525
-
526
- const dispose = function dispose(): void {
527
- clearBufferAndTimer();
528
- };
529
-
530
- const getParsedHotkey = function getParsedHotkey(hotkey: string): ParsedHotkey {
531
- const cacheKey = `${hotkey}:${config.leader ?? ""}`;
532
- let parsed = parseCache.get(cacheKey);
533
- if (!parsed) {
534
- parsed = parseHotkey(hotkey, config.leader);
535
- parseCache.set(cacheKey, parsed);
536
- }
537
- return parsed;
538
- };
539
-
540
- const collectCandidates = function collectCandidates(
541
- commands: ReadonlyMap<string, Command> | undefined,
542
- currentMode: Mode,
543
- cmdCtx: CommandContext,
544
- ): {
545
- singleStep: { command: Command; parsed: ParsedHotkey }[];
546
- multiStep: { command: Command; hotkey: string; parsed: ParsedHotkey }[];
547
- } {
548
- const singleStep: { command: Command; parsed: ParsedHotkey }[] = [];
549
- const multiStep: { command: Command; hotkey: string; parsed: ParsedHotkey }[] = [];
550
-
551
- for (const command of commands?.values() ?? []) {
552
- const commandModes = command.modes ?? DEFAULT_MODES;
553
- if (!commandModes.includes(currentMode) || (command.when && !command.when(cmdCtx))) {
554
- continue;
555
- }
556
-
557
- const hotkey = config.keymap?.[command.id] ?? command.defaultHotkey;
558
- if (hotkey === undefined || hotkey === "") {
559
- continue;
560
- }
561
-
562
- const parsed = getParsedHotkey(hotkey);
563
-
564
- // Unmatchable hotkeys (e.g. <leader> with no configured leader) register
565
- // nothing rather than matching everything.
566
- if (parsed.steps.length === 0) {
567
- continue;
568
- }
569
-
570
- if (parsed.steps.length === 1) {
571
- singleStep.push({ command, parsed });
572
- } else {
573
- multiStep.push({ command, hotkey, parsed });
574
- }
575
- }
576
-
577
- return { multiStep, singleStep };
578
- };
579
-
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" };
585
-
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();
600
- const { multiStep: multiStepCandidates, singleStep: singleStepCandidates } = collectCandidates(
601
- ctx.commandsBySurface.get(record.id),
602
- currentMode,
603
- cmdCtx,
604
- );
605
-
606
- // Check multi-step sequences first (they consume buffer state)
607
- if (multiStepCandidates.length > 0) {
608
- const hotkeys = multiStepCandidates.map((candidate) => candidate.parsed);
609
- buffer = [...buffer, event];
610
- armTimer();
611
-
612
- let matchedIndex = -1;
613
- for (let i = 0; i < hotkeys.length; i += 1) {
614
- if (matchesBuffer(buffer, hotkeys[i])) {
615
- matchedIndex = i;
616
- break;
617
- }
618
- }
619
-
620
- if (matchedIndex >= 0) {
621
- clearBufferAndTimer();
622
- store.trigger.sequenceReset();
623
- const matched = multiStepCandidates[matchedIndex].command;
624
- return {
625
- invoke: (): void => {
626
- void matched.handler(cmdCtx);
627
- },
628
- outcome: "invoke",
629
- };
630
- }
631
-
632
- buffer = pruneBuffer(buffer, hotkeys);
633
- const pending = findPendingMatch(buffer, hotkeys);
634
-
635
- if (pending) {
636
- const firstCandidate = multiStepCandidates[pending.indexes[0]];
637
- const state: CommandSequenceState = {
638
- candidates: pending.indexes
639
- .map((idx) => multiStepCandidates[idx])
640
- .filter(({ command }) => command.hidden !== true)
641
- .map(({ command, hotkey, parsed }) => ({
642
- command,
643
- group: ctx.groups.get(stepsKey(parsed.steps.slice(0, pending.prefixLength + 1))),
644
- hotkey,
645
- nextStep: parsed.steps[pending.prefixLength],
646
- remainingSteps: parsed.steps.slice(pending.prefixLength),
647
- steps: parsed.steps,
648
- })),
649
- prefix: firstCandidate.parsed.steps.slice(0, pending.prefixLength),
650
- };
651
- store.trigger.sequencePending({ state });
652
- return { outcome: "pending" };
653
- }
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();
660
- store.trigger.sequenceReset();
661
- }
662
-
663
- // Check single-step matches
664
- for (const { command, parsed } of singleStepCandidates) {
665
- if (matchStep(event, parsed.steps[0])) {
666
- store.trigger.sequenceReset();
667
- return {
668
- invoke: (): void => {
669
- void command.handler(cmdCtx);
670
- },
671
- outcome: "invoke",
672
- };
673
- }
674
- }
675
-
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
- }
702
- return { handled: false };
703
- };
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
-
759
- const pushSurface = function pushSurface(surface: SurfaceRecord): () => void {
760
- surface.order = orderCounter;
761
- orderCounter += 1;
762
- const before = selectKeyboardOwnerSurface(store.getSnapshot().context);
763
- store.trigger.surfacePushed({ surface });
764
- const after = selectKeyboardOwnerSurface(store.getSnapshot().context);
765
- // Keep the wrapper buffer consistent with the transition's sequence-clear
766
- // rule: clear exactly when keyboard ownership changed.
767
- if (before !== after) {
768
- clearBufferAndTimer();
769
- }
770
-
771
- return () => {
772
- const beforePop = selectKeyboardOwnerSurface(store.getSnapshot().context);
773
- store.trigger.surfacePopped({ surface });
774
- const afterPop = selectKeyboardOwnerSurface(store.getSnapshot().context);
775
- if (beforePop !== afterPop) {
776
- clearBufferAndTimer();
777
- }
778
- };
779
- };
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
-
801
- const modeChanged = function modeChanged(surfaceId: string): void {
802
- clearBufferAndTimer();
803
- store.trigger.modeChanged({ surfaceId });
804
- };
805
-
806
- const registryFor = function registryFor(record: SurfaceRecord): CommandRegistry {
807
- let registry = registries.get(record);
808
- if (!registry) {
809
- registry = {
810
- get commands() {
811
- const current = store.getSnapshot().context.commandsBySurface.get(record.id);
812
- // The registry contract exposes a Map; the store's per-surface maps
813
- // are Maps at runtime (readonly-typed). Consumers must not mutate.
814
- // Deferred(lint-sweep): expose readonly command snapshots through an immutable registry API.
815
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- compatibility facade preserves the existing mutable Map API
816
- return (current ?? new Map()) as Map<string, Command>;
817
- },
818
- invoke(id: string) {
819
- const ctx = store.getSnapshot().context;
820
- const cmd = ctx.commandsBySurface.get(record.id)?.get(id);
821
- if (!cmd) {
822
- return;
823
- }
824
- const cmdCtx = record.buildCtx();
825
- if (!cmd.when || cmd.when(cmdCtx)) {
826
- const result = cmd.handler(cmdCtx);
827
- if (result) {
828
- void reportCommandFailure(result);
829
- }
830
- }
831
- },
832
- register(command: Command) {
833
- store.trigger.commandRegistered({ command, surfaceId: record.id });
834
- return () => {
835
- store.trigger.commandUnregistered({ command, surfaceId: record.id });
836
- };
837
- },
838
- };
839
- registries.set(record, registry);
840
- }
841
- return registry;
842
- };
843
-
844
- const setConfig = function setConfig(next: CommandStoreConfig): void {
845
- config = next;
846
- };
847
-
848
- return {
849
- activatePanel,
850
- dispose,
851
- key,
852
- modeChanged,
853
- pushSurface,
854
- registryFor,
855
- removePanelGroup,
856
- reset,
857
- rootRecord,
858
- setConfig,
859
- store,
860
- };
861
- };