xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / core / src / cell-buffer.ts

8.0 KB
1import type { Color } from "@cel-tui/types";
2
3/**
4 * A single terminal cell with character content and styling.
5 *
6 * Each cell represents one column in the terminal grid.
7 * Wide characters (CJK, emoji) occupy two cells — the first cell
8 * holds the character, the second is a continuation marker.
9 */
10export interface Cell {
11  /** The grapheme cluster displayed in this cell. */
12  readonly char: string;
13  /** Foreground color, or null for terminal default. */
14  readonly fgColor: Color | null;
15  /** Background color, or null for terminal default. */
16  readonly bgColor: Color | null;
17  /** Bold weight. */
18  readonly bold: boolean;
19  /** Italic style. */
20  readonly italic: boolean;
21  /** Underline decoration. */
22  readonly underline: boolean;
23}
24
25/**
26 * The default empty cell — a space with no styling.
27 * Used for cleared/uninitialized cells and transparency detection.
28 */
29export const EMPTY_CELL: Cell = Object.freeze({
30  char: " ",
31  fgColor: null,
32  bgColor: null,
33  bold: false,
34  italic: false,
35  underline: false,
36});
37
38function cellsEqual(a: Cell, b: Cell): boolean {
39  if (a === b) return true;
40  return (
41    a.char === b.char &&
42    a.fgColor === b.fgColor &&
43    a.bgColor === b.bgColor &&
44    a.bold === b.bold &&
45    a.italic === b.italic &&
46    a.underline === b.underline
47  );
48}
49
50/**
51 * A 2D grid of styled terminal cells.
52 *
53 * The cell buffer is the core rendering target. The layout engine
54 * computes rects, painting writes styled cells into those rects,
55 * and the diff algorithm compares the current buffer against the
56 * previous one to produce minimal terminal updates.
57 *
58 * Empty cells (matching {@link EMPTY_CELL}) are considered transparent
59 * for layer compositing — higher layers overwrite lower layers only
60 * where they have non-empty content.
61 */
62export class CellBuffer {
63  private cells: Cell[];
64  private _width: number;
65  private _height: number;
66
67  /**
68   * Create a new cell buffer filled with empty cells.
69   *
70   * @param width - Buffer width in columns.
71   * @param height - Buffer height in rows.
72   */
73  constructor(width: number, height: number) {
74    this._width = width;
75    this._height = height;
76    this.cells = new Array(width * height);
77    this.clearCells(0, this.cells.length);
78  }
79
80  /** Buffer width in columns. */
81  get width(): number {
82    return this._width;
83  }
84
85  /** Buffer height in rows. */
86  get height(): number {
87    return this._height;
88  }
89
90  /**
91   * Get the cell at `(x, y)`.
92   * Returns {@link EMPTY_CELL} for out-of-bounds coordinates.
93   */
94  get(x: number, y: number): Cell {
95    if (x < 0 || x >= this._width || y < 0 || y >= this._height) {
96      return EMPTY_CELL;
97    }
98
99    const cell = this.cells[y * this._width + x];
100    if (cell === undefined) {
101      throw new Error(`Missing cell at (${x}, ${y})`);
102    }
103    return cell;
104  }
105
106  /**
107   * Set the cell at `(x, y)`.
108   * Out-of-bounds writes are silently ignored.
109   */
110  set(x: number, y: number, cell: Cell): void {
111    if (x < 0 || x >= this._width || y < 0 || y >= this._height) return;
112
113    const index = y * this._width + x;
114    const current = this.cells[index];
115    if (current?.char === "" && cell.char === "") {
116      // Painting a wide glyph writes its lead first and its continuation
117      // cells afterward. Rewriting an existing continuation is therefore a
118      // style/content refresh, not an overlap that should erase the lead.
119      this.cells[index] = cell;
120      return;
121    }
122    if (
123      current !== undefined &&
124      current.char === cell.char &&
125      cell.char !== ""
126    ) {
127      // A style-only rewrite of a wide glyph must preserve its continuation
128      // markers. Keep their styles in sync as well so the glyph remains one
129      // coherent unit for later compositing and comparisons.
130      this.cells[index] = cell;
131      for (let col = x + 1; col < this._width; col++) {
132        const continuationIndex = y * this._width + col;
133        const continuation = this.cells[continuationIndex];
134        if (continuation === undefined || continuation.char !== "") break;
135        this.cells[continuationIndex] = { ...cell, char: "" };
136      }
137      return;
138    }
139
140    // A terminal renders a wide grapheme atomically even though the buffer
141    // represents its trailing columns with empty-string continuation cells.
142    // Clear any existing glyph that overlaps this write so composited layers
143    // can never leave an orphaned lead or continuation behind.
144    this.clearGlyphAt(x, y);
145    this.cells[index] = cell;
146  }
147
148  /**
149   * Check if the cell at `(x, y)` is empty (transparent).
150   * A cell is empty if it matches {@link EMPTY_CELL} exactly.
151   */
152  isEmpty(x: number, y: number): boolean {
153    return cellsEqual(this.get(x, y), EMPTY_CELL);
154  }
155
156  /** Reset all cells to {@link EMPTY_CELL}. */
157  clear(): void {
158    this.clearCells(0, this.cells.length);
159  }
160
161  /**
162   * Fill a rectangular region with a cell value.
163   * Coordinates are clipped to buffer bounds.
164   *
165   * @param x - Left column (inclusive).
166   * @param y - Top row (inclusive).
167   * @param w - Width in columns.
168   * @param h - Height in rows.
169   * @param cell - Cell value to fill with.
170   */
171  fill(x: number, y: number, w: number, h: number, cell: Cell): void {
172    const x0 = Math.max(0, x);
173    const y0 = Math.max(0, y);
174    const x1 = Math.min(this._width, x + w);
175    const y1 = Math.min(this._height, y + h);
176    for (let row = y0; row < y1; row++) {
177      for (let col = x0; col < x1; col++) {
178        this.set(col, row, cell);
179      }
180    }
181  }
182
183  /**
184   * Resize the buffer. Existing content within the new bounds is preserved.
185   * New cells are initialized to {@link EMPTY_CELL}.
186   *
187   * @param width - New width in columns.
188   * @param height - New height in rows.
189   */
190  resize(width: number, height: number): void {
191    const newCells = new Array<Cell>(width * height);
192    newCells.fill(EMPTY_CELL);
193    // Copy existing content
194    const copyW = Math.min(this._width, width);
195    const copyH = Math.min(this._height, height);
196    for (let y = 0; y < copyH; y++) {
197      for (let x = 0; x < copyW; x++) {
198        newCells[y * width + x] = this.get(x, y);
199      }
200
201      // Do not retain a wide-glyph lead when its continuation was clipped by
202      // the new right edge.
203      if (width > 0 && width < this._width && this.get(width, y).char === "") {
204        newCells[y * width + width - 1] = EMPTY_CELL;
205      }
206    }
207    this.cells = newCells;
208    this._width = width;
209    this._height = height;
210  }
211
212  /**
213   * Compare this buffer against another and return positions that differ.
214   * Used for differential rendering — only changed cells need terminal updates.
215   *
216   * @param other - The buffer to compare against.
217   * @returns Array of `{ x, y }` positions where cells differ.
218   */
219  diff(other: CellBuffer): { x: number; y: number }[] {
220    const changes: { x: number; y: number }[] = [];
221    const w = Math.min(this._width, other._width);
222    const h = Math.min(this._height, other._height);
223    for (let y = 0; y < h; y++) {
224      for (let x = 0; x < w; x++) {
225        if (!cellsEqual(this.get(x, y), other.get(x, y))) {
226          changes.push({ x, y });
227        }
228      }
229    }
230    return changes;
231  }
232
233  private clearCells(start: number, end: number): void {
234    this.cells.fill(EMPTY_CELL, start, end);
235  }
236
237  /** Clear the complete stored glyph that occupies `(x, y)`, if any. */
238  private clearGlyphAt(x: number, y: number): void {
239    const rowStart = y * this._width;
240    const index = rowStart + x;
241    const current = this.cells[index];
242    if (
243      current === undefined ||
244      current === EMPTY_CELL ||
245      cellsEqual(current, EMPTY_CELL)
246    ) {
247      return;
248    }
249
250    let leadX = x;
251    if (current.char === "") {
252      while (leadX > 0) {
253        leadX--;
254        const candidate = this.cells[rowStart + leadX];
255        if (candidate === undefined || candidate.char !== "") break;
256      }
257    }
258
259    this.cells[rowStart + leadX] = EMPTY_CELL;
260    for (let col = leadX + 1; col < this._width; col++) {
261      const continuation = this.cells[rowStart + col];
262      if (continuation === undefined || continuation.char !== "") break;
263      this.cells[rowStart + col] = EMPTY_CELL;
264    }
265  }
266}