From 4b04c87b3d0152e11a8ba383d252069c7e33dc03 Mon Sep 17 00:00:00 2001 From: Markus Ylisiurunen <8409947+markusylisiurunen@users.noreply.github.com> Date: Tue, 16 Dec 2025 21:13:43 +0200 Subject: [PATCH] add new getCursor and getLines methods to editor (#201) --- packages/tui/src/components/editor.ts | 8 ++++++++ packages/tui/test/editor.test.ts | 28 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/packages/tui/src/components/editor.ts b/packages/tui/src/components/editor.ts index 9f5ee2aa..522f2025 100644 --- a/packages/tui/src/components/editor.ts +++ b/packages/tui/src/components/editor.ts @@ -595,6 +595,14 @@ export class Editor implements Component { return this.state.lines.join("\n"); } + getLines(): string[] { + return [...this.state.lines]; + } + + getCursor(): { line: number; col: number } { + return { line: this.state.cursorLine, col: this.state.cursorCol }; + } + setText(text: string): void { this.historyIndex = -1; // Exit history browsing mode this.setTextInternal(text); diff --git a/packages/tui/test/editor.test.ts b/packages/tui/test/editor.test.ts index d0b3d2f7..1f02e3e4 100644 --- a/packages/tui/test/editor.test.ts +++ b/packages/tui/test/editor.test.ts @@ -247,6 +247,34 @@ describe("Editor component", () => { }); }); + describe("public state accessors", () => { + it("returns cursor position", () => { + const editor = new Editor(defaultEditorTheme); + + assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 }); + + editor.handleInput("a"); + editor.handleInput("b"); + editor.handleInput("c"); + + assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 }); + + editor.handleInput("\x1b[D"); // Left + assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 2 }); + }); + + it("returns lines as a defensive copy", () => { + const editor = new Editor(defaultEditorTheme); + editor.setText("a\nb"); + + const lines = editor.getLines(); + assert.deepStrictEqual(lines, ["a", "b"]); + + lines[0] = "mutated"; + assert.deepStrictEqual(editor.getLines(), ["a", "b"]); + }); + }); + describe("Unicode text editing behavior", () => { it("inserts mixed ASCII, umlauts, and emojis as literal text", () => { const editor = new Editor(defaultEditorTheme);