xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / core / src / emitter.ts

9.5 KB
1import type { Color, CursorStyle, Theme, ThemeValue } from "@cel-tui/types";
2import type { Cell, CellBuffer } from "./cell-buffer.js";
3
4// --- Default ANSI 16 theme ---
5
6/**
7 * The default theme — maps each color slot to its matching ANSI palette
8 * index. With this theme, colors inherit the terminal's configured
9 * color scheme automatically.
10 */
11export const defaultTheme: Theme = {
12  color00: 0,
13  color01: 1,
14  color02: 2,
15  color03: 3,
16  color04: 4,
17  color05: 5,
18  color06: 6,
19  color07: 7,
20  color08: 8,
21  color09: 9,
22  color10: 10,
23  color11: 11,
24  color12: 12,
25  color13: 13,
26  color14: 14,
27  color15: 15,
28};
29
30// --- Color resolution ---
31
32/** Parse a hex color string "#rrggbb" into [r, g, b]. */
33function parseHex(hex: string): [number, number, number] {
34  const r = parseInt(hex.slice(1, 3), 16);
35  const g = parseInt(hex.slice(3, 5), 16);
36  const b = parseInt(hex.slice(5, 7), 16);
37  return [r, g, b];
38}
39
40/** Resolve a color slot to an SGR code fragment for foreground. */
41function fgSgr(color: Color, theme: Theme): string {
42  const val: ThemeValue = theme[color];
43  if (typeof val === "number") {
44    // ANSI palette index 0-15
45    return String(val < 8 ? 30 + val : 82 + val);
46  }
47  // Hex true color
48  const [r, g, b] = parseHex(val);
49  return `38;2;${r};${g};${b}`;
50}
51
52/** Resolve a color slot to an SGR code fragment for background. */
53function bgSgr(color: Color, theme: Theme): string {
54  const val: ThemeValue = theme[color];
55  if (typeof val === "number") {
56    // ANSI palette index 0-15
57    return String(val < 8 ? 40 + val : 92 + val);
58  }
59  // Hex true color
60  const [r, g, b] = parseHex(val);
61  return `48;2;${r};${g};${b}`;
62}
63
64// --- SGR generation ---
65
66function sgrForCell(cell: Cell, theme: Theme): string {
67  const codes: string[] = [];
68  if (cell.bold) codes.push("1");
69  if (cell.italic) codes.push("3");
70  if (cell.underline) codes.push("4");
71  if (cell.fgColor) codes.push(fgSgr(cell.fgColor, theme));
72  if (cell.bgColor) codes.push(bgSgr(cell.bgColor, theme));
73  if (codes.length === 0) return "";
74  return `\x1b[${codes.join(";")}m`;
75}
76
77function styleEquals(a: Cell, b: Cell): boolean {
78  return (
79    a.fgColor === b.fgColor &&
80    a.bgColor === b.bgColor &&
81    a.bold === b.bold &&
82    a.italic === b.italic &&
83    a.underline === b.underline
84  );
85}
86
87function hasStyle(cell: Cell): boolean {
88  return (
89    cell.bold ||
90    cell.italic ||
91    cell.underline ||
92    cell.fgColor !== null ||
93    cell.bgColor !== null
94  );
95}
96
97// --- Synchronized output markers ---
98
99const SYNC_START = "\x1b[?2026h";
100const SYNC_END = "\x1b[?2026l";
101const CURSOR_HOME = "\x1b[H";
102const HIDE_CURSOR = "\x1b[?25l";
103const SHOW_CURSOR = "\x1b[?25h";
104const SAVE_CURSOR = "\x1b7";
105const RESTORE_CURSOR = "\x1b8";
106const RESET = "\x1b[0m";
107
108/** Native terminal cursor state emitted alongside a frame. */
109export type TerminalCursorState =
110  | { visible: false }
111  | {
112      visible: true;
113      x: number;
114      y: number;
115      /** Omitted by legacy callers means the default block cursor. */
116      style?: CursorStyle;
117    };
118
119/** Cursor state used when emitting a full or differential frame. */
120export interface EmitOptions {
121  /** Desired cursor state after the frame is applied. */
122  cursor?: TerminalCursorState;
123  /** Cursor state established by the previous frame, if known. */
124  previousCursor?: TerminalCursorState | null;
125}
126
127function cursorStyle(cursor: { style?: CursorStyle }): CursorStyle {
128  return cursor.style ?? "block";
129}
130
131function cursorShapeSequence(style: CursorStyle): string {
132  switch (style) {
133    case "block":
134      return "\x1b[1 q";
135    case "underline":
136      return "\x1b[3 q";
137    case "bar":
138      return "\x1b[5 q";
139  }
140}
141
142function sameVisibleCursor(
143  a: TerminalCursorState | null | undefined,
144  b: TerminalCursorState | null | undefined,
145): boolean {
146  return (
147    a?.visible === true &&
148    b?.visible === true &&
149    a.x === b.x &&
150    a.y === b.y &&
151    cursorStyle(a) === cursorStyle(b)
152  );
153}
154
155function sameVisibleCursorPosition(
156  a: TerminalCursorState,
157  b: TerminalCursorState | null,
158): boolean {
159  return (
160    a.visible === true && b?.visible === true && a.x === b.x && a.y === b.y
161  );
162}
163
164function getCursorControls(
165  options: EmitOptions | undefined,
166  hasPaintOutput: boolean,
167  forceCursorState = false,
168): { prefix: string; suffix: string } {
169  const cursor = options?.cursor ?? { visible: false };
170  const previous = options?.previousCursor ?? null;
171
172  if (forceCursorState) {
173    return cursor.visible
174      ? {
175          prefix: "",
176          suffix:
177            `\x1b[${cursor.y + 1};${cursor.x + 1}H` +
178            cursorShapeSequence(cursorStyle(cursor)) +
179            SHOW_CURSOR,
180        }
181      : { prefix: "", suffix: HIDE_CURSOR };
182  }
183
184  if (sameVisibleCursor(cursor, previous)) {
185    return hasPaintOutput
186      ? { prefix: SAVE_CURSOR, suffix: RESTORE_CURSOR }
187      : { prefix: "", suffix: "" };
188  }
189
190  if (cursor.visible) {
191    const positionUnchanged = sameVisibleCursorPosition(cursor, previous);
192    const shapeChanged =
193      previous?.visible !== true ||
194      cursorStyle(cursor) !== cursorStyle(previous);
195    return {
196      prefix: "",
197      suffix:
198        (!positionUnchanged || hasPaintOutput
199          ? `\x1b[${cursor.y + 1};${cursor.x + 1}H`
200          : "") +
201        (shapeChanged ? cursorShapeSequence(cursorStyle(cursor)) : "") +
202        (previous?.visible === true ? "" : SHOW_CURSOR),
203    };
204  }
205
206  return previous?.visible === true
207    ? { prefix: "", suffix: HIDE_CURSOR }
208    : { prefix: "", suffix: "" };
209}
210
211/**
212 * Emit a full cell buffer as an ANSI string for terminal output.
213 *
214 * Generates cursor positioning, SGR styling codes, and character content
215 * for every cell. Output is wrapped in synchronized output markers
216 * (CSI 2026) for flicker-free rendering.
217 *
218 * Optimizes by batching consecutive cells with the same style and
219 * only emitting SGR codes when the style changes.
220 *
221 * @param buf - The cell buffer to render.
222 * @param theme - Color theme mapping. Defaults to the ANSI 16 theme.
223 * @param options - Optional terminal cursor state to apply before the synchronized output ends.
224 * @returns A complete ANSI string ready to write to the terminal.
225 */
226export function emitBuffer(
227  buf: CellBuffer,
228  theme: Theme = defaultTheme,
229  options?: EmitOptions,
230): string {
231  // A full frame is also the recovery path after external screen corruption,
232  // so it must establish cursor position and visibility from scratch instead
233  // of trusting a saved terminal cursor.
234  const cursorControls = getCursorControls(options, true, true);
235  // Reset SGR unconditionally: redraw() is allowed to recover from arbitrary
236  // external terminal output, including colors or attributes left active.
237  let out = SYNC_START + cursorControls.prefix + CURSOR_HOME + RESET;
238
239  let lastStyle: Cell | null = null;
240
241  for (let y = 0; y < buf.height; y++) {
242    if (y > 0) out += "\r\n";
243
244    for (let x = 0; x < buf.width; x++) {
245      const cell = buf.get(x, y);
246
247      // Skip continuation cells (trailing half of wide characters)
248      if (cell.char === "") continue;
249
250      // Emit style change if needed
251      if (lastStyle === null || !styleEquals(cell, lastStyle)) {
252        // Reset before applying new style
253        if (lastStyle !== null && hasStyle(lastStyle)) {
254          out += RESET;
255        }
256        const sgr = sgrForCell(cell, theme);
257        if (sgr) out += sgr;
258        lastStyle = cell;
259      }
260
261      out += cell.char;
262    }
263  }
264
265  // Final reset if any style was active
266  if (lastStyle !== null && hasStyle(lastStyle)) {
267    out += RESET;
268  }
269
270  out += cursorControls.suffix + SYNC_END;
271  return out;
272}
273
274/**
275 * Emit only the cells that differ between two buffers.
276 *
277 * Uses cursor positioning (CSI row;col H) to jump to changed cells,
278 * batching consecutive changes on the same row into a single run.
279 * Output is wrapped in synchronized output markers for flicker-free updates.
280 *
281 * @param prev - The previous buffer.
282 * @param next - The new buffer.
283 * @param theme - Color theme mapping. Defaults to the ANSI 16 theme.
284 * @param options - Optional terminal cursor state to apply before the synchronized output ends.
285 * @returns An ANSI string with only the changed cells.
286 */
287export function emitDiff(
288  prev: CellBuffer,
289  next: CellBuffer,
290  theme: Theme = defaultTheme,
291  options?: EmitOptions,
292): string {
293  const changes = prev.diff(next);
294  const cursorControls = getCursorControls(options, changes.length > 0);
295
296  if (changes.length === 0) {
297    if (cursorControls.prefix === "" && cursorControls.suffix === "") return "";
298    return (
299      SYNC_START + cursorControls.prefix + cursorControls.suffix + SYNC_END
300    );
301  }
302
303  let out = SYNC_START + cursorControls.prefix;
304
305  let lastStyle: Cell | null = null;
306  let lastX = -1;
307  let lastY = -1;
308
309  for (const { x, y } of changes) {
310    const cell = next.get(x, y);
311
312    // Skip continuation cells (trailing half of wide characters)
313    if (cell.char === "") continue;
314
315    // Position cursor if not consecutive
316    if (y !== lastY || x !== lastX + 1) {
317      // Reset style before repositioning
318      if (lastStyle !== null && hasStyle(lastStyle)) {
319        out += RESET;
320        lastStyle = null;
321      }
322      // CSI row;col H (1-indexed)
323      out += `\x1b[${y + 1};${x + 1}H`;
324    }
325
326    // Emit style change if needed
327    if (lastStyle === null || !styleEquals(cell, lastStyle)) {
328      if (lastStyle !== null && hasStyle(lastStyle)) {
329        out += RESET;
330      }
331      const sgr = sgrForCell(cell, theme);
332      if (sgr) out += sgr;
333      lastStyle = cell;
334    }
335
336    out += cell.char;
337    lastX = x;
338    lastY = y;
339  }
340
341  // Final reset
342  if (lastStyle !== null && hasStyle(lastStyle)) {
343    out += RESET;
344  }
345
346  out += cursorControls.suffix + SYNC_END;
347  return out;
348}