@ftrdotdev/pi-tui 0.2.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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -0
  3. package/package.json +80 -0
  4. package/src/autocomplete-contract.test.ts +126 -0
  5. package/src/autocomplete-contract.ts +91 -0
  6. package/src/commands/git-execution.test.ts +69 -0
  7. package/src/commands/git-execution.ts +198 -0
  8. package/src/commands/git-status.test.ts +379 -0
  9. package/src/commands/git-status.ts +320 -0
  10. package/src/components/bordered-box.test.ts +136 -0
  11. package/src/components/bordered-box.ts +106 -0
  12. package/src/components/define-component.ts +33 -0
  13. package/src/components/index.ts +35 -0
  14. package/src/config.test.ts +469 -0
  15. package/src/config.ts +307 -0
  16. package/src/frame/box-frame.test.ts +44 -0
  17. package/src/frame/box-frame.ts +160 -0
  18. package/src/icons.ts +203 -0
  19. package/src/index.ts +359 -0
  20. package/src/runtime.ts +256 -0
  21. package/src/session-lifecycle.ts +41 -0
  22. package/src/state.test.ts +7 -0
  23. package/src/state.ts +90 -0
  24. package/src/telemetry.ts +301 -0
  25. package/src/ui/editor-tint.test.ts +70 -0
  26. package/src/ui/editor-tint.ts +78 -0
  27. package/src/ui/editor.ts +403 -0
  28. package/src/ui/footer.test.ts +350 -0
  29. package/src/ui/footer.ts +225 -0
  30. package/src/ui/header.test.ts +260 -0
  31. package/src/ui/header.ts +165 -0
  32. package/src/ui/preview.test.ts +639 -0
  33. package/src/ui/preview.ts +374 -0
  34. package/src/ui/render-helpers.ts +275 -0
  35. package/src/ui/settings-command.test.ts +218 -0
  36. package/src/ui/settings-command.ts +390 -0
  37. package/src/utils.ts +448 -0
  38. package/src/vim/editor-close-autocomplete.ts +26 -0
  39. package/src/vim/editor-host.test.ts +340 -0
  40. package/src/vim/editor-state.test.ts +385 -0
  41. package/src/vim/editor-state.ts +314 -0
  42. package/src/vim/mode-indicator.test.ts +27 -0
  43. package/src/vim/mode-indicator.ts +44 -0
  44. package/src/vim/selection-render.test.ts +77 -0
  45. package/src/vim/selection-render.ts +85 -0
  46. package/src/vim/text-model.test.ts +85 -0
  47. package/src/vim/text-model.ts +75 -0
  48. package/src/vim/vim-router.test.ts +50 -0
  49. package/src/vim/vim-router.ts +55 -0
  50. package/src/vim/word-motion.ts +96 -0
@@ -0,0 +1,27 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { vimModeGlyph, vimModeTint } from "./mode-indicator.ts";
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // vimModeTint (pure mode → border color mapping)
6
+ // ---------------------------------------------------------------------------
7
+
8
+ it("insert (or vim off) yields no tint", () => {
9
+ assert.strictEqual(vimModeTint({ enabled: true, mode: "insert" }), undefined);
10
+ assert.strictEqual(vimModeTint({ enabled: false, mode: "normal" }), undefined);
11
+ });
12
+
13
+ it("normal tints syntaxOperator; visual tints syntaxNumber", () => {
14
+ assert.strictEqual(vimModeTint({ enabled: true, mode: "normal" }), "syntaxOperator");
15
+ assert.strictEqual(vimModeTint({ enabled: true, mode: "visual" }), "syntaxNumber");
16
+ });
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // vimModeGlyph (pure mode → top-border glyph mapping)
20
+ // ---------------------------------------------------------------------------
21
+
22
+ it("maps modes to single letters; vim off yields nothing", () => {
23
+ assert.strictEqual(vimModeGlyph({ enabled: true, mode: "insert" }), "I");
24
+ assert.strictEqual(vimModeGlyph({ enabled: true, mode: "normal" }), "N");
25
+ assert.strictEqual(vimModeGlyph({ enabled: true, mode: "visual" }), "V");
26
+ assert.strictEqual(vimModeGlyph({ enabled: false, mode: "normal" }), undefined);
27
+ });
@@ -0,0 +1,44 @@
1
+ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import type { EditorMode } from "./editor-state.ts";
3
+
4
+ /**
5
+ * vim-mode → editor presentation mappings (border tint, top-border glyph).
6
+ *
7
+ * The generic editor host never knows vim exists: `installEditor` injects
8
+ * these through the editor's options (`getBorderTint`, `getModeIndicator`)
9
+ * and evaluates them live on every render. Keeping the mappings here, pure
10
+ * and unit-tested, mirrors `selection-render.ts` — vim presentation logic
11
+ * lives in `vim/`, chrome stays in `ui/`.
12
+ */
13
+
14
+ /** The modal state both mappings read. */
15
+ export interface VimModeState {
16
+ readonly enabled: boolean;
17
+ readonly mode: EditorMode;
18
+ }
19
+
20
+ /**
21
+ * vim's border tint for the current modal state: block-style modes tint the
22
+ * border (visual uses a distinct color from normal); insert and vim-off fall
23
+ * through to pi's border.
24
+ */
25
+ export function vimModeTint(state: VimModeState): ThemeColor | undefined {
26
+ if (!state.enabled) return undefined;
27
+ if (state.mode === "visual") return "syntaxNumber";
28
+ if (state.mode === "normal") return "syntaxOperator";
29
+ return undefined;
30
+ }
31
+
32
+ /**
33
+ * vim's mode indicator for the current modal state: a single letter on the
34
+ * editor's top border (N normal, V visual, I insert); vim-off yields
35
+ * nothing. Injectable via `TuiEditorOptions.getModeIndicator` — the editor
36
+ * never knows vim exists, installEditor supplies the live glyph reading the
37
+ * modal state.
38
+ */
39
+ export function vimModeGlyph(state: VimModeState): string | undefined {
40
+ if (!state.enabled) return undefined;
41
+ if (state.mode === "normal") return "N";
42
+ if (state.mode === "visual") return "V";
43
+ return "I";
44
+ }
@@ -0,0 +1,77 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { makeRange } from "./text-model.ts";
3
+ import { paintVisibleSpan, renderSelection } from "./selection-render.ts";
4
+
5
+ const paint = (s: string) => `[sel]${s}[/sel]`;
6
+
7
+ // ---------------------------------------------------------------------------
8
+ // renderSelection
9
+ // ---------------------------------------------------------------------------
10
+
11
+ it("is inert with no selection", () => {
12
+ const lines = ["foo", "bar"];
13
+ assert.deepStrictEqual(renderSelection({ lines, selection: undefined, paint }), lines);
14
+ });
15
+
16
+ it("paints the span on the first/last lines of the range", () => {
17
+ const lines = ["foo bar", "second line", "third"];
18
+ const selection = makeRange({ line: 0, col: 1 }, { line: 2, col: 2 });
19
+ const out = renderSelection({ lines, selection, paint });
20
+ assert.strictEqual(out[0], "f[sel]oo bar[/sel]");
21
+ assert.strictEqual(out[1], "[sel]second line[/sel]"); // interior line: full
22
+ assert.strictEqual(out[2], "[sel]th[/sel]ird");
23
+ });
24
+
25
+ it("paints nothing for a single-cursor range", () => {
26
+ const lines = ["foo bar"];
27
+ const selection = makeRange({ line: 0, col: 2 }, { line: 0, col: 2 });
28
+ assert.deepStrictEqual(renderSelection({ lines, selection, paint }), lines);
29
+ });
30
+
31
+ it("makeRange normalizes a reverse range into a forward span", () => {
32
+ const r = makeRange({ line: 0, col: 4 }, { line: 0, col: 2 });
33
+ assert.deepStrictEqual(r.start, { line: 0, col: 2 });
34
+ assert.deepStrictEqual(r.end, { line: 0, col: 4 });
35
+ const out = renderSelection({ lines: ["foo bar"], selection: r, paint });
36
+ assert.strictEqual(out[0], "fo[sel]o [/sel]bar");
37
+ });
38
+
39
+ it("leaves lines outside the range untouched", () => {
40
+ const lines = ["alpha", "beta", "gamma"];
41
+ const selection = makeRange({ line: 1, col: 0 }, { line: 1, col: 2 });
42
+ const out = renderSelection({ lines, selection, paint });
43
+ assert.strictEqual(out[0], "alpha");
44
+ assert.strictEqual(out[1], "[sel]be[/sel]ta");
45
+ assert.strictEqual(out[2], "gamma");
46
+ });
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // paintVisibleSpan: ANSI awareness
50
+ // ---------------------------------------------------------------------------
51
+
52
+ it("copies escape sequences verbatim without counting their width", () => {
53
+ const line = "he\x1b[7ml\x1b[0mlo"; // cursor marker over the 'l' at col 2
54
+ const out = paintVisibleSpan(line, 0, 5, paint);
55
+ assert.strictEqual(out, "[sel]he\x1b[7ml\x1b[0mlo[/sel]");
56
+ });
57
+
58
+ it("paints a span that excludes a leading escape sequence", () => {
59
+ const line = "he\x1b[7ml\x1b[0mlo";
60
+ const out = paintVisibleSpan(line, 3, 4, paint);
61
+ assert.strictEqual(out, "he\x1b[7ml\x1b[0m[sel]l[/sel]o");
62
+ });
63
+
64
+ it("does not paint when the span starts beyond the visible text", () => {
65
+ const line = "abc";
66
+ assert.strictEqual(paintVisibleSpan(line, 9, 10, paint), line);
67
+ });
68
+
69
+ it("paints to the last visible char when the span runs past the line end", () => {
70
+ assert.strictEqual(paintVisibleSpan("abc", 1, 99, paint), "a[sel]bc[/sel]");
71
+ });
72
+
73
+ it("is a no-op for a zero-width span", () => {
74
+ const line = "abc";
75
+ assert.strictEqual(paintVisibleSpan(line, 1, 1, paint), line);
76
+ assert.strictEqual(paintVisibleSpan(line, 3, 1, paint), line);
77
+ });
@@ -0,0 +1,85 @@
1
+ import { visibleWidth } from "@earendil-works/pi-tui";
2
+ import type { Range } from "./text-model.ts";
3
+
4
+ /**
5
+ * Selection highlight renderer: paints the logical {@link Range} onto the
6
+ * editor's rendered content lines. It owns no state of its own — the range
7
+ * is derived from the state machine's `selection` (design boundary).
8
+ *
9
+ * First cut (assumption 6): logical-line mapping. Interior lines are
10
+ * highlighted in full, the first/last lines only over their column span.
11
+ * The cursor marker (an OSC escape) and any SGR codes inside the span are
12
+ * copied verbatim, so the paint wraps visible text without disturbing them.
13
+ */
14
+
15
+ /** Length of the escape sequence starting at `i`, or 0 when not an escape. */
16
+ function escapeLength(line: string, i: number): number {
17
+ const rest = line.slice(i);
18
+ const csi = rest.match(/^\x1b\[[0-9;?]*[A-Za-z]/);
19
+ if (csi) return csi[0].length;
20
+ const osc = rest.match(/^\x1b\][^\x07]*(?:\x07|\x1b\\)/);
21
+ if (osc) return osc[0].length;
22
+ const oscu = rest.match(/^\x1b_[^\x07]*(?:\x07|\x1b\\)/);
23
+ if (oscu) return oscu[0].length;
24
+ return 0;
25
+ }
26
+
27
+ /**
28
+ * Wrap the visible columns `[from, to)` of a rendered line in `paint`,
29
+ * returning the line unchanged when the span is empty or out of bounds.
30
+ * Escape sequences contribute zero visible width and are copied verbatim.
31
+ */
32
+ export function paintVisibleSpan(
33
+ line: string,
34
+ from: number,
35
+ to: number,
36
+ paint: (s: string) => string,
37
+ ): string {
38
+ if (from >= to) return line;
39
+ const n = line.length;
40
+ let visible = 0;
41
+ let startRaw = -1;
42
+ let endRaw = -1;
43
+ let lastVisibleEnd = 0;
44
+ let i = 0;
45
+ while (i < n) {
46
+ const escLen = escapeLength(line, i);
47
+ if (escLen > 0) {
48
+ i += escLen;
49
+ continue;
50
+ }
51
+ const width = visibleWidth(line[i]!);
52
+ if (startRaw < 0 && visible + width > from) startRaw = i;
53
+ visible += width;
54
+ lastVisibleEnd = i + 1;
55
+ if (endRaw < 0 && visible >= to) {
56
+ endRaw = i + 1;
57
+ break;
58
+ }
59
+ i++;
60
+ }
61
+ if (startRaw < 0) return line; // the selection starts beyond this line
62
+ if (endRaw < 0) endRaw = lastVisibleEnd; // the selection runs past the line end
63
+ const head = line.slice(0, startRaw);
64
+ const span = line.slice(startRaw, endRaw);
65
+ const tail = line.slice(endRaw);
66
+ return `${head}${paint(span)}${tail}`;
67
+ }
68
+
69
+ export interface SelectionRenderInput {
70
+ readonly lines: string[];
71
+ readonly selection: Range | undefined;
72
+ /** Theme paint applied to the selected span (e.g. `theme.inverse`). */
73
+ readonly paint: (s: string) => string;
74
+ }
75
+
76
+ export function renderSelection({ lines, selection, paint }: SelectionRenderInput): string[] {
77
+ if (!selection) return lines; // inert with no selection
78
+ const { start, end } = selection;
79
+ return lines.map((line, i) => {
80
+ if (i < start.line || i > end.line) return line; // outside the range
81
+ const from = i === start.line ? start.col : 0;
82
+ const to = i === end.line ? end.col : line.length;
83
+ return paintVisibleSpan(line, from, to, paint);
84
+ });
85
+ }
@@ -0,0 +1,85 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect, Layer } from "effect";
3
+ import { makeRange, type VimTextModelShape, VimTextModel } from "./text-model.ts";
4
+ import { findWordBackStart, findWordEnd, findWordStart, wordForward } from "./word-motion.ts";
5
+
6
+ // ---------------------------------------------------------------------------
7
+ // Range normalization (binding decision 3)
8
+ // ---------------------------------------------------------------------------
9
+
10
+ it("makeRange keeps anchor and active and normalizes start/end", () => {
11
+ const r = makeRange({ line: 0, col: 1 }, { line: 0, col: 3 });
12
+ assert.deepStrictEqual(r.anchor, { line: 0, col: 1 });
13
+ assert.deepStrictEqual(r.active, { line: 0, col: 3 });
14
+ assert.deepStrictEqual(r.start, { line: 0, col: 1 });
15
+ assert.deepStrictEqual(r.end, { line: 0, col: 3 });
16
+ });
17
+
18
+ it("makeRange orders multi-line ranges by line then column", () => {
19
+ const r = makeRange({ line: 2, col: 0 }, { line: 1, col: 5 });
20
+ assert.deepStrictEqual(r.start, { line: 1, col: 5 });
21
+ assert.deepStrictEqual(r.end, { line: 2, col: 0 });
22
+ });
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // Word-motion geometry
26
+ // ---------------------------------------------------------------------------
27
+
28
+ it("findWordStart skips the current word and whitespace", () => {
29
+ assert.strictEqual(findWordStart("foo bar", 0), 4);
30
+ assert.strictEqual(findWordStart("foo bar", 4), 7);
31
+ assert.strictEqual(findWordStart("foo", 0), 3);
32
+ assert.strictEqual(findWordStart("", 0), 0);
33
+ });
34
+
35
+ it("findWordBackStart returns the start of the previous word", () => {
36
+ assert.strictEqual(findWordBackStart("foo bar", 4), 0);
37
+ assert.strictEqual(findWordBackStart("foo bar", 7), 4);
38
+ assert.strictEqual(findWordBackStart("foo", 0), 0);
39
+ });
40
+
41
+ it("findWordEnd returns the last character of the word at or after col", () => {
42
+ assert.strictEqual(findWordEnd("foo bar", 0), 2);
43
+ assert.strictEqual(findWordEnd("foo bar", 3), 6);
44
+ assert.strictEqual(findWordEnd("foo bar", 2), 2);
45
+ });
46
+
47
+ it("wordForward composes across lines", () => {
48
+ assert.deepStrictEqual(wordForward(["foo bar", "baz"], { line: 0, col: 0 }), {
49
+ line: 0,
50
+ col: 4,
51
+ });
52
+ // at the end of "bar" there is no further word on line 0 → next line start
53
+ assert.deepStrictEqual(wordForward(["foo bar", "baz"], { line: 0, col: 7 }), {
54
+ line: 1,
55
+ col: 0,
56
+ });
57
+ });
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // VimTextModel service tag (house service pattern)
61
+ // ---------------------------------------------------------------------------
62
+
63
+ const noopShape: VimTextModelShape = {
64
+ getText: () => "hello",
65
+ getCursor: () => ({ line: 0, col: 0 }),
66
+ moveCursorTo: () => {},
67
+ getLineCount: () => 1,
68
+ lineLength: () => 5,
69
+ moveWordForward: (from) => from,
70
+ moveWordBackward: (from) => from,
71
+ moveWordEnd: (from) => from,
72
+ moveToLineStart: (c) => c,
73
+ moveToLineEnd: (c) => c,
74
+ deleteRange: () => {},
75
+ yankRange: () => "",
76
+ replaceRange: () => {},
77
+ insertTextAtCursor: () => {},
78
+ };
79
+
80
+ it.effect("VimTextModel.layerFrom provides the shape through the service tag", () =>
81
+ Effect.gen(function* () {
82
+ const model = yield* VimTextModel;
83
+ assert.strictEqual(model.getText(), "hello");
84
+ }).pipe(Effect.provide(VimTextModel.layerFrom(noopShape) as Layer.Layer<VimTextModel>)),
85
+ );
@@ -0,0 +1,75 @@
1
+ import { Context, Layer } from "effect";
2
+
3
+ /**
4
+ * Cursor position in the text model: logical line index and column within
5
+ * that line (UTF-16 code units, matching pi-tui's editor columns).
6
+ */
7
+ export interface Cursor {
8
+ readonly line: number;
9
+ readonly col: number;
10
+ }
11
+
12
+ /**
13
+ * One range concept (binding decision 3): Visual selections AND Normal-mode
14
+ * operator motions share this single primitive.
15
+ *
16
+ * `anchor` is the selection start point (fixed while the selection is
17
+ * extended); `active` is the moving end. `start`/`end` are the normalized
18
+ * span (min/max of anchor/active, ordered by line then column). Text
19
+ * operations consume `[start, end)` — start inclusive, end exclusive.
20
+ */
21
+ export interface Range {
22
+ readonly anchor: Cursor;
23
+ readonly active: Cursor;
24
+ readonly start: Cursor;
25
+ readonly end: Cursor;
26
+ }
27
+
28
+ function order(a: Cursor, b: Cursor): [Cursor, Cursor] {
29
+ return a.line < b.line || (a.line === b.line && a.col <= b.col) ? [a, b] : [b, a];
30
+ }
31
+
32
+ /** Build a {@link Range} from anchor and active, normalizing start/end. */
33
+ export function makeRange(anchor: Cursor, active: Cursor): Range {
34
+ const [start, end] = order(anchor, active);
35
+ return { anchor, active, start, end };
36
+ }
37
+
38
+ /**
39
+ * The state machine's dependency: a plain interface over the text the vim
40
+ * mode edits. Motions, selection, and operators all operate on this shape, so
41
+ * the `VimEditorState` core is pure and unit-testable without pi-tui
42
+ * internals. `TuiEditor` implements it over the real editor; tests provide a
43
+ * fake with real line/word geometry through the `VimTextModel` service tag.
44
+ */
45
+ export interface VimTextModelShape {
46
+ readonly getText: () => string;
47
+ readonly getCursor: () => Cursor;
48
+ readonly moveCursorTo: (c: Cursor) => void;
49
+ readonly getLineCount: () => number;
50
+ readonly lineLength: (line: number) => number;
51
+ // motion geometry
52
+ readonly moveWordForward: (from: Cursor) => Cursor;
53
+ readonly moveWordBackward: (from: Cursor) => Cursor;
54
+ readonly moveWordEnd: (from: Cursor) => Cursor;
55
+ readonly moveToLineStart: (c: Cursor) => Cursor;
56
+ readonly moveToLineEnd: (c: Cursor) => Cursor;
57
+ // operations (Slice 5): consume `[range.start, range.end)`
58
+ readonly deleteRange: (range: Range) => void;
59
+ readonly yankRange: (range: Range) => string;
60
+ readonly replaceRange: (range: Range, text: string) => void;
61
+ readonly insertTextAtCursor: (text: string) => void;
62
+ }
63
+
64
+ /**
65
+ * Effect service tag over the same shape (house service pattern). Layers and
66
+ * tests provide doubles via `layerFrom`; the host wires the real editor
67
+ * through the session's effect context.
68
+ */
69
+ export class VimTextModel extends Context.Service<VimTextModel, VimTextModelShape>()(
70
+ "tui/vim/VimTextModel",
71
+ ) {
72
+ static layerFrom(model: VimTextModelShape): Layer.Layer<VimTextModel> {
73
+ return Layer.succeed(VimTextModel, VimTextModel.of(model));
74
+ }
75
+ }
@@ -0,0 +1,50 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect } from "effect";
3
+ import { VimRouter } from "./vim-router.ts";
4
+
5
+ it.effect("emits a down intent for j when vim is on", () =>
6
+ Effect.gen(function* () {
7
+ const router = yield* VimRouter;
8
+ assert.deepStrictEqual(router.decodeNavigation("j"), { kind: "move", dir: "down" });
9
+ }).pipe(Effect.provide(VimRouter.layerTest(() => true))),
10
+ );
11
+
12
+ it.effect("emits an up intent for k when vim is on", () =>
13
+ Effect.gen(function* () {
14
+ const router = yield* VimRouter;
15
+ assert.deepStrictEqual(router.decodeNavigation("k"), { kind: "move", dir: "up" });
16
+ }).pipe(Effect.provide(VimRouter.layerTest(() => true))),
17
+ );
18
+
19
+ it.effect("emits a left intent for h when vim is on", () =>
20
+ Effect.gen(function* () {
21
+ const router = yield* VimRouter;
22
+ assert.deepStrictEqual(router.decodeNavigation("h"), { kind: "move", dir: "left" });
23
+ }).pipe(Effect.provide(VimRouter.layerTest(() => true))),
24
+ );
25
+
26
+ it.effect("emits a right intent for l when vim is on", () =>
27
+ Effect.gen(function* () {
28
+ const router = yield* VimRouter;
29
+ assert.deepStrictEqual(router.decodeNavigation("l"), { kind: "move", dir: "right" });
30
+ }).pipe(Effect.provide(VimRouter.layerTest(() => true))),
31
+ );
32
+
33
+ it.effect("is inert and returns no intent for vim keys when vim is off", () =>
34
+ Effect.gen(function* () {
35
+ const router = yield* VimRouter;
36
+ for (const key of ["j", "k", "h", "l"]) {
37
+ assert.strictEqual(router.decodeNavigation(key), undefined);
38
+ }
39
+ }).pipe(Effect.provide(VimRouter.layerTest(() => false))),
40
+ );
41
+
42
+ it.effect("passes through non-vim input unchanged", () =>
43
+ Effect.gen(function* () {
44
+ const router = yield* VimRouter;
45
+ const inputs = ["\x1b[B", "\x1b[A", "\t", "\x1b", "\x1b[Z", " ", "\r"];
46
+ for (const data of inputs) {
47
+ assert.strictEqual(router.decodeNavigation(data), undefined);
48
+ }
49
+ }).pipe(Effect.provide(VimRouter.layerTest(() => true))),
50
+ );
@@ -0,0 +1,55 @@
1
+ import { matchesKey } from "@earendil-works/pi-tui";
2
+ import { Context, Layer } from "effect";
3
+
4
+ /**
5
+ * Uniform movement intent decoded from raw terminal bytes for list-like
6
+ * widgets (settings list, tracker overlay, etc.). The router emits movement
7
+ * intent only — no cursor or editor state — so any selectable surface can
8
+ * consume it without dragging in editor machinery.
9
+ */
10
+ export type NavigationIntent = {
11
+ readonly kind: "move";
12
+ readonly dir: "up" | "down" | "left" | "right";
13
+ };
14
+
15
+ /**
16
+ * Single interception point for vim navigation semantics on list surfaces.
17
+ *
18
+ * Self-gating (binding decision 1): the router holds a live `getVimEnabled`
19
+ * getter and applies the gate inside `decodeNavigation`; consumers never
20
+ * check `config.vim` themselves. When the gate is off the router is inert and
21
+ * returns no intent, so the consumer falls back to its own handling (arrows,
22
+ * Tab, etc. keep working on every surface).
23
+ *
24
+ * Consumers may deliberately opt out of the gate by injecting an always-true
25
+ * getter — the settings UI does this so its h/j/k/l stay unconditional.
26
+ *
27
+ * House service pattern (config.ts, header.ts): `Context.Service` class with
28
+ * `static make(...)` → `Layer`. Importable by tracker/inquiry — they already
29
+ * depend on `effect` via the catalog.
30
+ */
31
+ export class VimRouter extends Context.Service<
32
+ VimRouter,
33
+ { readonly decodeNavigation: (data: string) => NavigationIntent | undefined }
34
+ >()("tui/vim/VimRouter") {
35
+ static make(getVimEnabled: () => boolean): Layer.Layer<VimRouter> {
36
+ return Layer.succeed(
37
+ VimRouter,
38
+ VimRouter.of({
39
+ decodeNavigation: (data) => {
40
+ if (!getVimEnabled()) return undefined; // inert when off
41
+ if (matchesKey(data, "j")) return { kind: "move", dir: "down" };
42
+ if (matchesKey(data, "k")) return { kind: "move", dir: "up" };
43
+ if (matchesKey(data, "h")) return { kind: "move", dir: "left" };
44
+ if (matchesKey(data, "l")) return { kind: "move", dir: "right" };
45
+ return undefined; // pass through: consumer delegates
46
+ },
47
+ }),
48
+ );
49
+ }
50
+
51
+ /** Test layer with a stub getter for the toggle (London school). */
52
+ static layerTest(getVimEnabled: () => boolean): Layer.Layer<VimRouter> {
53
+ return VimRouter.make(getVimEnabled);
54
+ }
55
+ }
@@ -0,0 +1,96 @@
1
+ import type { Cursor } from "./text-model.ts";
2
+
3
+ /**
4
+ * Pure word-motion geometry over plain lines, shared by the real editor's
5
+ * `VimTextModelShape` implementation and the test fakes (a fake with real
6
+ * geometry per the London-school test-double guidance).
7
+ *
8
+ * A "word" is a run of non-whitespace characters. Motions operate on logical
9
+ * lines and compose across newlines; they never mutate anything.
10
+ */
11
+
12
+ const isWs = (ch: string | undefined): boolean => ch === undefined || /\s/.test(ch);
13
+
14
+ /**
15
+ * Vim `w`: the start of the next word at or after `col`, or `line.length`
16
+ * when the line has no further word. Skips the current word run, then any
17
+ * whitespace, and returns the first non-whitespace index.
18
+ */
19
+ export function findWordStart(line: string, col: number): number {
20
+ const n = line.length;
21
+ if (n === 0) return 0;
22
+ let i = Math.min(col, n);
23
+ while (i < n && !isWs(line[i])) i++;
24
+ while (i < n && isWs(line[i])) i++;
25
+ return i;
26
+ }
27
+
28
+ /**
29
+ * Vim `b`: the start of the word at or before `col`. Skips whitespace
30
+ * backwards, then the preceding word run; returns the word's first index.
31
+ * Returns 0 when no word precedes on this line.
32
+ */
33
+ export function findWordBackStart(line: string, col: number): number {
34
+ const n = line.length;
35
+ let i = Math.min(col, n);
36
+ while (i > 0 && isWs(line[i - 1])) i--;
37
+ while (i > 0 && !isWs(line[i - 1])) i--;
38
+ return i;
39
+ }
40
+
41
+ /**
42
+ * Vim `e`: the index of the last character of the word at or after `col`
43
+ * (inclusive). Whitespace is skipped forward first. Returns `line.length`
44
+ * when no word is ahead on this line.
45
+ */
46
+ export function findWordEnd(line: string, col: number): number {
47
+ const n = line.length;
48
+ if (n === 0) return 0;
49
+ let i = Math.min(col, n - 1);
50
+ while (i < n && isWs(line[i])) i++;
51
+ if (i >= n) return n;
52
+ while (i + 1 < n && !isWs(line[i + 1])) i++;
53
+ return i;
54
+ }
55
+
56
+ /** `w` across lines: next word start; at the end of a line, next line's start. */
57
+ export function wordForward(lines: readonly string[], from: Cursor): Cursor {
58
+ const line = lines[from.line] ?? "";
59
+ const target = findWordStart(line, from.col);
60
+ if (target < line.length || (target === 0 && line.length === 0)) {
61
+ return { line: from.line, col: target };
62
+ }
63
+ if (from.line < lines.length - 1) return { line: from.line + 1, col: 0 };
64
+ return { line: from.line, col: line.length };
65
+ }
66
+
67
+ /** `b` across lines: previous word start; at a line start, the previous line's last word. */
68
+ export function wordBackward(lines: readonly string[], from: Cursor): Cursor {
69
+ if (from.line === 0 && from.col === 0) return from;
70
+ const line = lines[from.line] ?? "";
71
+ const target = findWordBackStart(line, from.col);
72
+ if (target > 0 || (from.col > 0 && target === 0)) {
73
+ return { line: from.line, col: target };
74
+ }
75
+ const prev = lines[from.line - 1] ?? "";
76
+ return { line: from.line - 1, col: findWordBackStart(prev, prev.length) };
77
+ }
78
+
79
+ /** `e` across lines: end of the current/next word; at a line end, the next line's first word. */
80
+ export function wordEnd(lines: readonly string[], from: Cursor): Cursor {
81
+ const line = lines[from.line] ?? "";
82
+ const at = Math.min(from.col, line.length);
83
+ if (at >= line.length) {
84
+ if (from.line < lines.length - 1) {
85
+ const next = lines[from.line + 1] ?? "";
86
+ const end = findWordEnd(next, 0);
87
+ return { line: from.line + 1, col: end === 0 && next.length > 0 ? 0 : end };
88
+ }
89
+ return from;
90
+ }
91
+ const target = findWordEnd(line, from.col);
92
+ if (target !== from.col) return { line: from.line, col: target };
93
+ // Already at the end of the current word: move to the end of the next word.
94
+ const nextTarget = findWordEnd(line, from.col + 1);
95
+ return { line: from.line, col: nextTarget };
96
+ }