xonecas.io
70160
Ce

cel-tui / commit 1896195

feat(core): implement differential rendering

Add emitDiff() to the emitter that uses CellBuffer.diff() to emit
only changed cells with cursor positioning (CSI row;col H).
Consecutive changed cells on the same row are batched into a
single write for efficiency.

doRender() in cel.ts now keeps the previous buffer and uses
emitDiff() for subsequent renders. Full emitBuffer() is only used
for the first render and after terminal resizes.

The hello example's spinner and clock now only update the few
cells that actually change each frame instead of redrawing the
entire screen.

xonecas2026-04-03 18961950cc6e167590fbebb0ab3e3b1e371c3fcd parent c477b71

6 files changed

TODO.md+1−1
@@ -28,7 +28,7 @@ What's implemented, what's missing, and what needs hardening. Reference `spec.md
2828 - ✅ ANSI emitter (SGR colors, bold/italic/underline, synchronized output CSI 2026)
2929 - ✅ Reactive rendering (`cel.render()` batched via `process.nextTick`)
3030 - ✅ Full render on first paint, cursor home positioning
31-- 🔧 Differential rendering — `CellBuffer.diff()` exists but `cel.ts` always does full redraws (doesn't use diff to skip unchanged cells)
31+- ✅ Differential rendering — `emitDiff()` uses `CellBuffer.diff()` to emit only changed cells
3232 - ❌ Full clear + re-render on terminal resize (currently re-renders but doesn't clear scrollback)
3333
3434 ## Painting
packages/core/src/cel.test.ts+4−1
@@ -114,7 +114,10 @@ describe("cel end-to-end", () => {
114114 await waitForRender();
115115
116116 expect(renderCount).toBe(2);
117- expect(term.output).toContain("Count: 3");
117+ // Differential rendering: initial full render has "Count: 0",
118+ // subsequent render emits only the changed character "3"
119+ expect(term.output).toContain("Count: 0");
120+ expect(term.output).toContain("3");
118121 });
119122
120123 test("wraps output in synchronized output markers", async () => {
packages/core/src/cel.ts+20−10
@@ -1,6 +1,6 @@
11 import type { Node } from "@cel-tui/types";
22 import { CellBuffer } from "./cell-buffer.js";
3-import { emitBuffer } from "./emitter.js";
3+import { emitBuffer, emitDiff } from "./emitter.js";
44 import {
55 hitTest,
66 findClickHandler,
@@ -32,6 +32,7 @@ type RenderFn = () => Node | Node[];
3232 let terminal: Terminal | null = null;
3333 let renderFn: RenderFn | null = null;
3434 let renderScheduled = false;
35+let prevBuffer: CellBuffer | null = null;
3536 let currentBuffer: CellBuffer | null = null;
3637 let currentLayouts: LayoutNode[] = [];
3738
@@ -43,14 +44,17 @@ function doRender(): void {
4344 const height = terminal.rows;
4445
4546 // Create or resize buffer
46- if (
47- !currentBuffer ||
48- currentBuffer.width !== width ||
49- currentBuffer.height !== height
50- ) {
47+ const isResize =
48+ currentBuffer !== null &&
49+ (currentBuffer.width !== width || currentBuffer.height !== height);
50+ const isFirstRender = currentBuffer === null;
51+
52+ if (isFirstRender || isResize) {
53+ prevBuffer = null;
5154 currentBuffer = new CellBuffer(width, height);
5255 } else {
53- currentBuffer.clear();
56+ prevBuffer = currentBuffer;
57+ currentBuffer = new CellBuffer(width, height);
5458 }
5559
5660 // Get the tree from the render function
@@ -65,9 +69,14 @@ function doRender(): void {
6569 paint(layoutTree, currentBuffer);
6670 }
6771
68- // Emit to terminal
69- const output = emitBuffer(currentBuffer);
70- terminal.write(output);
72+ // Emit to terminal — differential when possible
73+ if (prevBuffer) {
74+ const output = emitDiff(prevBuffer, currentBuffer);
75+ if (output.length > 0) terminal.write(output);
76+ } else {
77+ const output = emitBuffer(currentBuffer);
78+ terminal.write(output);
79+ }
7180 }
7281
7382 // --- Input handling ---
@@ -314,6 +323,7 @@ export const cel = {
314323 terminal?.stop();
315324 terminal = null;
316325 renderFn = null;
326+ prevBuffer = null;
317327 currentBuffer = null;
318328 currentLayouts = [];
319329 renderScheduled = false;
packages/core/src/composite.test.ts+7−2
@@ -116,11 +116,16 @@ describe("layer compositing", () => {
116116 expect(term.output).toContain("main");
117117 expect(term.output).not.toContain("modal");
118118
119- term.clearOutput();
120119 showModal = true;
121120 cel.render();
122121 await waitForRender();
123122
124- expect(term.output).toContain("modal");
123+ // Check buffer contents — diff rendering may not emit "modal" as a
124+ // contiguous string since unchanged chars (like 'm') are skipped
125+ const buf = cel._getBuffer()!;
126+ const row = Array.from({ length: 5 }, (_, i) => buf.get(i, 0).char).join(
127+ "",
128+ );
129+ expect(row).toBe("modal");
125130 });
126131 });
packages/core/src/emitter.test.ts+59−1
@@ -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+});
packages/core/src/emitter.ts+61−0
@@ -129,3 +129,64 @@ export function emitBuffer(buf: CellBuffer): string {
129129 out += SYNC_END;
130130 return out;
131131 }
132+
133+/**
134+ * Emit only the cells that differ between two buffers.
135+ *
136+ * Uses cursor positioning (CSI row;col H) to jump to changed cells,
137+ * batching consecutive changes on the same row into a single run.
138+ * Output is wrapped in synchronized output markers for flicker-free updates.
139+ *
140+ * @param prev - The previous buffer.
141+ * @param next - The new buffer.
142+ * @returns An ANSI string with only the changed cells.
143+ */
144+export function emitDiff(prev: CellBuffer, next: CellBuffer): string {
145+ let out = SYNC_START;
146+
147+ const changes = prev.diff(next);
148+ if (changes.length === 0) {
149+ return out + SYNC_END;
150+ }
151+
152+ let lastStyle: Cell | null = null;
153+ let lastX = -1;
154+ let lastY = -1;
155+
156+ for (const { x, y } of changes) {
157+ const cell = next.get(x, y);
158+
159+ // Position cursor if not consecutive
160+ if (y !== lastY || x !== lastX + 1) {
161+ // Reset style before repositioning
162+ if (lastStyle !== null && hasStyle(lastStyle)) {
163+ out += RESET;
164+ lastStyle = null;
165+ }
166+ // CSI row;col H (1-indexed)
167+ out += `\x1b[${y + 1};${x + 1}H`;
168+ }
169+
170+ // Emit style change if needed
171+ if (lastStyle === null || !styleEquals(cell, lastStyle)) {
172+ if (lastStyle !== null && hasStyle(lastStyle)) {
173+ out += RESET;
174+ }
175+ const sgr = sgrForCell(cell);
176+ if (sgr) out += sgr;
177+ lastStyle = cell;
178+ }
179+
180+ out += cell.char;
181+ lastX = x;
182+ lastY = y;
183+ }
184+
185+ // Final reset
186+ if (lastStyle !== null && hasStyle(lastStyle)) {
187+ out += RESET;
188+ }
189+
190+ out += SYNC_END;
191+ return out;
192+}