@@ -1,6 +1,6 @@
11 import { describe, expect, test } from "bun:test";
22 import { CellBuffer, type Cell } from "./cell-buffer.js";
3-import { emitBuffer } from "./emitter.js";
3+import { emitBuffer, emitDiff } from "./emitter.js";
44
55 function cell(char: string, overrides: Partial<Cell> = {}): Cell {
66 return {
@@ -126,3 +126,61 @@ describe("emitBuffer", () => {
126126 expect(output).toContain(" ");
127127 });
128128 });
129+
130+describe("emitDiff", () => {
131+ test("returns empty string when buffers are identical", () => {
132+ const prev = new CellBuffer(5, 2);
133+ const next = new CellBuffer(5, 2);
134+ prev.set(0, 0, cell("A"));
135+ next.set(0, 0, cell("A"));
136+ const output = emitDiff(prev, next);
137+ // Only sync markers, no content
138+ expect(output).toBe("\x1b[?2026h\x1b[?2026l");
139+ });
140+
141+ test("emits only changed cells with cursor positioning", () => {
142+ const prev = new CellBuffer(5, 2);
143+ const next = new CellBuffer(5, 2);
144+ prev.set(0, 0, cell("A"));
145+ next.set(0, 0, cell("A"));
146+ // Change cell at (2, 1)
147+ next.set(2, 1, cell("X"));
148+ const output = emitDiff(prev, next);
149+ // Should position cursor at (2, 1) = CSI row;col H (1-indexed)
150+ expect(output).toContain("\x1b[2;3H");
151+ expect(output).toContain("X");
152+ });
153+
154+ test("emits styled changed cells", () => {
155+ const prev = new CellBuffer(3, 1);
156+ const next = new CellBuffer(3, 1);
157+ next.set(1, 0, cell("Z", { fgColor: "red", bold: true }));
158+ const output = emitDiff(prev, next);
159+ expect(output).toContain("\x1b[1;2H"); // cursor to (1, 0)
160+ expect(output).toContain("Z");
161+ expect(output).toContain("\x1b[1;31m"); // bold + red
162+ });
163+
164+ test("wraps in synchronized output markers", () => {
165+ const prev = new CellBuffer(1, 1);
166+ const next = new CellBuffer(1, 1);
167+ next.set(0, 0, cell("Q"));
168+ const output = emitDiff(prev, next);
169+ expect(output.startsWith("\x1b[?2026h")).toBe(true);
170+ expect(output.endsWith("\x1b[?2026l")).toBe(true);
171+ });
172+
173+ test("batches consecutive changed cells on same row", () => {
174+ const prev = new CellBuffer(5, 1);
175+ const next = new CellBuffer(5, 1);
176+ next.set(1, 0, cell("A"));
177+ next.set(2, 0, cell("B"));
178+ next.set(3, 0, cell("C"));
179+ const output = emitDiff(prev, next);
180+ // Should position once and emit ABC together
181+ expect(output).toContain("ABC");
182+ // Only one cursor positioning for this run
183+ const cursorMoves = output.match(/\x1b\[\d+;\d+H/g) || [];
184+ expect(cursorMoves.length).toBe(1);
185+ });
186+});