modal-editor.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * Modal Editor - vim-like modal editing example
  3. *
  4. * Usage: pi --extension ./examples/extensions/modal-editor.ts
  5. *
  6. * - Escape: insert → normal mode (in normal mode, aborts agent)
  7. * - i: normal → insert mode
  8. * - hjkl: navigation in normal mode
  9. * - ctrl+c, ctrl+d, etc. work in both modes
  10. */
  11. import { CustomEditor, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
  12. import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
  13. // Normal mode key mappings: key -> escape sequence (or null for mode switch)
  14. const NORMAL_KEYS: Record<string, string | null> = {
  15. h: "\x1b[D", // left
  16. j: "\x1b[B", // down
  17. k: "\x1b[A", // up
  18. l: "\x1b[C", // right
  19. "0": "\x01", // line start
  20. $: "\x05", // line end
  21. x: "\x1b[3~", // delete char
  22. i: null, // insert mode
  23. a: null, // append (insert + right)
  24. };
  25. class ModalEditor extends CustomEditor {
  26. private mode: "normal" | "insert" = "insert";
  27. handleInput(data: string): void {
  28. // Escape toggles to normal mode, or passes through for app handling
  29. if (matchesKey(data, "escape")) {
  30. if (this.mode === "insert") {
  31. this.mode = "normal";
  32. } else {
  33. super.handleInput(data); // abort agent, etc.
  34. }
  35. return;
  36. }
  37. // Insert mode: pass everything through
  38. if (this.mode === "insert") {
  39. super.handleInput(data);
  40. return;
  41. }
  42. // Normal mode: check mapped keys
  43. if (data in NORMAL_KEYS) {
  44. const seq = NORMAL_KEYS[data];
  45. if (data === "i") {
  46. this.mode = "insert";
  47. } else if (data === "a") {
  48. this.mode = "insert";
  49. super.handleInput("\x1b[C"); // move right first
  50. } else if (seq) {
  51. super.handleInput(seq);
  52. }
  53. return;
  54. }
  55. // Pass control sequences (ctrl+c, etc.) to super, ignore printable chars
  56. if (data.length === 1 && data.charCodeAt(0) >= 32) return;
  57. super.handleInput(data);
  58. }
  59. render(width: number): string[] {
  60. const lines = super.render(width);
  61. if (lines.length === 0) return lines;
  62. // Add mode indicator to bottom border
  63. const label = this.mode === "normal" ? " NORMAL " : " INSERT ";
  64. const last = lines.length - 1;
  65. if (visibleWidth(lines[last]!) >= label.length) {
  66. lines[last] = truncateToWidth(lines[last]!, width - label.length, "") + label;
  67. }
  68. return lines;
  69. }
  70. }
  71. export default function (pi: ExtensionAPI) {
  72. pi.on("session_start", (_event, ctx) => {
  73. ctx.ui.setEditorComponent((tui, theme, kb) => new ModalEditor(tui, theme, kb));
  74. });
  75. }