import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CombinedAutocompleteProvider, type EditorTheme, KeybindingsManager, type TUI, TUI_KEYBINDINGS, } from "@earendil-works/pi-tui"; import { describe, expect, it, vi } from "vitest"; import { KeysmashEditor } from "../src/editor.ts"; const NEWLINE = "\n"; const ENTER = "\r"; const TAB = "\t"; const SHIFT_TAB = "\x1b[Z"; const BACKSPACE = "\x7f"; const LEFT = "\x1b[D"; const UNDO = "\x1f"; const PASTE_START = "\x1b[200~"; const PASTE_END = "\x1b[201~"; const theme = { borderColor: (text: string) => text, selectList: { selectedPrefix: (text: string) => text, selectedText: (text: string) => text, description: (text: string) => text, scrollInfo: (text: string) => text, noMatch: (text: string) => text, }, } as EditorTheme; type Keys = ConstructorParameters[2]; // The app's own bindings are not exported, so declare the one the tests need. const APP_KEYBINDINGS = { "app.message.followUp": { defaultKeys: "alt+enter", description: "Queue follow-up", }, }; const defaultKeys = ( overrides: ConstructorParameters[1] = {}, ): Keys => new KeybindingsManager( { ...TUI_KEYBINDINGS, ...APP_KEYBINDINGS }, overrides, ) as unknown as Keys; function editor(text = "", keybindings: Keys = defaultKeys()) { const tui = { terminal: { rows: 40, columns: 80 }, requestRender() {}, } as unknown as TUI; const instance = new KeysmashEditor(tui, theme, keybindings); instance.setText(text); return instance; } function press(instance: KeysmashEditor, ...keys: string[]): KeysmashEditor { for (const key of keys) instance.handleInput(key); return instance; } function typeText(instance: KeysmashEditor, text: string): KeysmashEditor { for (const char of text) instance.handleInput(char); return instance; } describe("list continuation", () => { it("continues bullets, tasks, numbers, and quotes", () => { expect(press(editor("- a"), NEWLINE).getText()).toBe("- a\n- "); expect(press(editor("* a"), NEWLINE).getText()).toBe("* a\n* "); expect(press(editor("- [x] a"), NEWLINE).getText()).toBe("- [x] a\n- [ ] "); expect(press(editor("9. a"), NEWLINE).getText()).toBe("9. a\n10. "); expect(press(editor("2) a"), NEWLINE).getText()).toBe("2) a\n3) "); expect(press(editor("> a"), NEWLINE).getText()).toBe("> a\n> "); expect(press(editor(" - a"), NEWLINE).getText()).toBe(" - a\n - "); }); it("restores pre-continuation text through native undo", () => { const instance = press(editor("- alpha"), NEWLINE); expect(instance.getText()).toBe("- alpha\n- "); press(instance, UNDO, UNDO); expect(instance.getText()).toBe("- alpha"); expect(instance.getCursor()).toEqual({ line: 0, col: 7 }); }); it("splits a bullet at the cursor", () => { const instance = press(editor("- ab"), LEFT, NEWLINE); expect(instance.getText()).toBe("- a\n- b"); expect(instance.getCursor()).toEqual({ line: 1, col: 2 }); }); it("steps out of empty items one level at a time", () => { const instance = editor("- a"); press(instance, NEWLINE, TAB); expect(instance.getText()).toBe("- a\n - "); press(instance, NEWLINE); expect(instance.getText()).toBe("- a\n- "); press(instance, NEWLINE); expect(instance.getText()).toBe("- a\n"); press(instance, NEWLINE); expect(instance.getText()).toBe("- a\n\n"); }); it("uses a trailing backslash with Enter like a newline key", () => { const instance = typeText(editor(), "- a\\"); press(instance, ENTER); expect(instance.getText()).toBe("- a\n- "); press(instance, "\\", ENTER); expect(instance.getText()).toBe("- a\n"); }); it("leaves Enter alone so it still submits", () => { const submitted: string[] = []; const instance = editor("- a"); instance.onSubmit = (text) => submitted.push(text); press(instance, ENTER); expect(submitted).toEqual(["- a"]); }); it("ignores markers it does not recognize", () => { for (const text of [ "-a", "**bold**", "---", ">quote", "1.5 apples", "2024. was rough", ]) expect(press(editor(text), NEWLINE).getText()).toBe(`${text}\n`); }); it("does not touch lines inside code fences", () => { expect(press(editor("```yaml\n- a"), NEWLINE).getText()).toBe( "```yaml\n- a\n", ); expect(press(editor("```\ncode\n```\n- a"), NEWLINE).getText()).toBe( "```\ncode\n```\n- a\n- ", ); }); it("keeps indentation on plain indented lines", () => { expect(press(editor(" code"), NEWLINE).getText()).toBe(" code\n "); expect(press(editor("plain"), NEWLINE).getText()).toBe("plain\n"); expect(press(editor(" "), NEWLINE).getText()).toBe(" \n"); }); }); describe("nesting", () => { it("indents and outdents while keeping the cursor on its text", () => { const instance = press(editor("- a\n- bc"), LEFT); press(instance, TAB); expect(instance.getText()).toBe("- a\n - bc"); expect(instance.getCursor()).toEqual({ line: 1, col: 5 }); press(instance, SHIFT_TAB); expect(instance.getText()).toBe("- a\n- bc"); expect(instance.getCursor()).toEqual({ line: 1, col: 3 }); }); it("aligns children with the parent's content", () => { const instance = press(editor("1. a\n- b"), TAB); expect(instance.getText()).toBe("1. a\n - b"); }); it("outdents to the parent level", () => { const instance = press(editor("- a\n - b\n - c"), SHIFT_TAB); expect(instance.getText()).toBe("- a\n - b\n - c"); }); it("undoes an outdent in one step", () => { const instance = press(editor("- a\n - b"), SHIFT_TAB); expect(instance.getText()).toBe("- a\n- b"); press(instance, UNDO); expect(instance.getText()).toBe("- a\n - b"); }); it("leaves Tab and Shift+Tab to Pi outside lists and at the margins", () => { expect(press(editor("plain"), TAB).getText()).toBe("plain"); expect(press(editor("- a"), SHIFT_TAB).getText()).toBe("- a"); expect(press(editor("- see @src/fo"), TAB).getText()).toBe("- see @src/fo"); expect(press(editor("```\n- a"), TAB).getText()).toBe("```\n- a"); }); }); describe("native completion precedence", () => { it("completes plain filenames, accepts an open menu, and nests only without matches", async () => { const root = mkdtempSync(join(tmpdir(), "keysmash-completion-")); try { writeFileSync(join(root, "manual-one.txt"), ""); writeFileSync(join(root, "manual-two.txt"), ""); const instance = editor("- manual-o"); instance.setAutocompleteProvider( new CombinedAutocompleteProvider([], root), ); press(instance, TAB); await vi.waitFor(() => expect(instance.getText()).toBe("- manual-one.txt"), ); instance.setText("- manual-"); press(instance, TAB); await vi.waitFor(() => expect(instance.isShowingAutocomplete()).toBe(true), ); press(instance, ENTER); expect(instance.getText()).toMatch(/^- manual-(one|two)\.txt$/); expect(instance.getLines()).toHaveLength(1); instance.setText("- no-file-matches"); press(instance, TAB); await vi.waitFor(() => expect(instance.getText()).toBe(" - no-file-matches"), ); } finally { rmSync(root, { recursive: true, force: true }); } }); it("does not apply a stale completion fallback after further typing", async () => { const instance = editor("- alpha"); let finish!: () => void; const pending = new Promise((resolve) => { finish = () => resolve(null); }); instance.setAutocompleteProvider({ getSuggestions: () => pending, applyCompletion: () => { throw new Error("No completion available"); }, }); press(instance, TAB, "z"); finish(); await pending; await Promise.resolve(); expect(instance.getText()).toBe("- alphaz"); }); }); describe("bare markers", () => { it("removes an empty marker in one Backspace", () => { expect(press(editor("- a\n- "), BACKSPACE).getText()).toBe("- a\n"); expect(press(editor(" - [ ] "), BACKSPACE).getText()).toBe("- [ ] "); expect(press(editor("- a\n - "), BACKSPACE).getText()).toBe("- a\n- "); expect(press(editor("- [ ] "), BACKSPACE).getText()).toBe(""); expect(press(editor("- a"), BACKSPACE).getText()).toBe("- "); }); }); describe("pairing", () => { it("pairs, overtypes, and unpairs", () => { const instance = typeText(editor(), "("); expect(instance.getText()).toBe("()"); expect(instance.getCursor().col).toBe(1); typeText(instance, "x)"); expect(instance.getText()).toBe("(x)"); expect(instance.getCursor().col).toBe(3); expect(press(typeText(editor(), "["), BACKSPACE).getText()).toBe(""); }); it("writes markdown links without stray brackets", () => { expect(typeText(editor(), "[a](b)").getText()).toBe("[a](b)"); }); it("pairs quotes and backticks only at word edges", () => { expect(typeText(editor(), '"hi"').getText()).toBe('"hi"'); expect(typeText(editor(), "say `x`").getText()).toBe("say `x`"); expect(typeText(editor(), "don't").getText()).toBe("don't"); expect(typeText(editor(), 'a"').getText()).toBe('a"'); expect(typeText(editor(), "```").getText()).toBe("```"); }); it("skips emoticons, escapes, and text that follows", () => { expect(typeText(editor(), ":(").getText()).toBe(":("); expect(typeText(editor(), "\\(").getText()).toBe("\\("); expect(typeText(press(editor("word"), "\x01"), "(").getText()).toBe( "(word", ); }); it("handles pasted text as typed by the terminal", () => { const instance = press(editor(), PASTE_START, "(", PASTE_END); expect(instance.getText()).toBe("("); }); it("does not intercept the target of a character jump", () => { const instance = press(editor("a(b"), "\x01", "\x1d", "("); expect(instance.getText()).toBe("a(b"); expect(instance.getCursor().col).toBe(1); }); }); describe("Pi shortcuts", () => { it("keeps keys bound to app actions", () => { const followUp: string[] = []; for (const text of ["- a", "- "]) { const instance = editor(text); instance.actionHandlers.set("app.message.followUp", () => followUp.push(text), ); press(instance, "\x1b\r"); expect(instance.getText()).toBe(text); } expect(followUp).toEqual(["- a", "- "]); }); it("preserves a non-thinking app action remapped onto Shift+Tab", () => { const keys = defaultKeys({ "app.message.followUp": "shift+tab" }); const instance = editor("- a\n - b", keys); const submitted: string[] = []; instance.actionHandlers.set("app.message.followUp", () => submitted.push(instance.getText()), ); press(instance, SHIFT_TAB); expect(submitted).toEqual(["- a\n - b"]); expect(instance.getText()).toBe("- a\n - b"); }); it("lets extension shortcuts consume keys first", () => { const instance = editor("- a\n- b"); instance.onExtensionShortcut = (data) => data === TAB; press(instance, TAB); expect(instance.getText()).toBe("- a\n- b"); }); }); describe("remapped keys", () => { it("stays out of the way when its primitive moves are unavailable", () => { const keys = defaultKeys({ "tui.editor.cursorLeft": "ctrl+x", "tui.editor.cursorRight": "ctrl+x", }); expect(typeText(editor("", keys), "(").getText()).toBe("("); const instance = press(editor("- a\n- b", keys), TAB); expect(instance.getText()).toBe("- a\n- b"); }); });