xonecas.io
70160
Ce

cel-tui / files

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

46.1 KB
1import type {
2  CursorStyle,
3  FocusChangeReason,
4  KittyKeyboardOptions,
5  Node,
6  TextInputNode,
7  TextInputProps,
8  Theme,
9} from "@cel-tui/types";
10import { CellBuffer } from "./cell-buffer.js";
11import { defaultTheme, emitBuffer, emitDiff } from "./emitter.js";
12import {
13  collectFocusable,
14  collectKeyPressHandlers,
15  collectScrollTargets,
16  findClickHandler,
17  hitTest,
18} from "./hit-test.js";
19import { decodeKeyEvents, isEditingKey, type KeyInput } from "./keys.js";
20import { type LayoutNode, layout, type Rect } from "./layout.js";
21import {
22  getTextInputCursor,
23  getTextInputCursorScreenPos,
24  getTextInputScroll,
25  paint,
26  resetTextInputState,
27  retainTextInputStateKeys,
28  setTextInputCursor,
29  setTextInputScroll,
30} from "./paint.js";
31import {
32  clampScrollOffset,
33  getMaxScrollOffset,
34  getScrollStep,
35} from "./scroll.js";
36import {
37  explicitStateIdentity,
38  inspectMountedStateKeys,
39  layerIdentity,
40  type MountedStateSnapshot,
41} from "./state-identity.js";
42import type { Terminal } from "./terminal.js";
43import {
44  deleteBackward,
45  deleteForward,
46  deleteWordBackward,
47  deleteWordForward,
48  type EditState,
49  insertChar,
50  moveCursor,
51  moveCursorByWord,
52} from "./text-edit.js";
53
54/** Reactive viewport function evaluated for each requested frame. */
55export type RenderFn = () => Node | Node[];
56
57/** Framework initialization options. */
58export interface CelInitOptions {
59  /** Color theme mapping. Defaults to the ANSI 16 theme. */
60  theme?: Theme;
61  /** Kitty progressive-enhancement flags. Baseline disambiguation stays on. */
62  kittyKeyboard?: KittyKeyboardOptions;
63}
64
65/** Public cel-tui runtime controller. */
66export interface Cel {
67  /** Initialize terminal I/O and runtime state. */
68  init(term: Terminal, options?: CelInitOptions): void;
69  /** Install the reactive viewport function and request its first frame. */
70  viewport(fn: RenderFn): void;
71  /** Request a batched differential render. */
72  render(): void;
73  /** Request a batched full-frame redraw. */
74  redraw(): void;
75  /** Replace the active palette and request a full redraw. */
76  setTheme(theme: Theme): void;
77  /** Set the sanitized terminal window or tab title. */
78  setTitle(title: string): void;
79  /** Stop the runtime and restore terminal state. */
80  stop(): void;
81}
82
83/** Runtime-only hooks hidden behind the test-helper module. */
84interface CelTestRuntime extends Cel {
85  _getBuffer(): CellBuffer | null;
86  _flush(): Promise<void>;
87}
88
89type TerminalCursorState =
90  | { visible: false }
91  | {
92      visible: true;
93      x: number;
94      y: number;
95      style: CursorStyle;
96    };
97
98let terminal: Terminal | null = null;
99let activeTheme: Theme = defaultTheme;
100let renderFn: RenderFn | null = null;
101let renderScheduled = false;
102let renderWaiters: Array<() => void> = [];
103let fullRedrawScheduled = false;
104let prevBuffer: CellBuffer | null = null;
105let currentBuffer: CellBuffer | null = null;
106let currentLayouts: LayoutNode[] = [];
107
108type FocusRef =
109  { kind: "keyed"; identity: string } | { kind: "legacy"; index: number };
110
111interface LayerFocusState {
112  current: FocusRef | null;
113  last: FocusRef | null;
114  autoFocusConsumed: Set<string>;
115}
116
117/** Focus is remembered independently for each mounted viewport layer. */
118const layerFocusStates = new Map<string, LayerFocusState>();
119
120/** The node whose props were stamped with `focused: true` during the last paint. */
121let stampedNode: LayoutNode | null = null;
122
123/**
124 * Uncontrolled scroll offsets, keyed by explicit state identity when present
125 * and by structural tree path as the compatible fallback.
126 */
127const uncontrolledScrollOffsets = new Map<string, number>();
128
129/** Nodes whose props were stamped with scrollOffset during the last paint. */
130let stampedScrollNodes: { node: Node; key: string }[] = [];
131
132/** The cursor state currently expected on the terminal. */
133let lastTerminalCursor: TerminalCursorState | null = { visible: false };
134let lastTerminalTitle: string | null = null;
135
136function requiredAt<T>(
137  items: readonly T[],
138  index: number,
139  description: string,
140): T {
141  const item = items[index];
142  if (item === undefined) {
143    throw new Error(`Missing ${description} at index ${index}`);
144  }
145  return item;
146}
147
148function topLayerContext(): {
149  root: LayoutNode;
150  identity: string;
151  focus: LayerFocusState;
152} | null {
153  const index = currentLayouts.length - 1;
154  const root = currentLayouts[index];
155  if (!root) return null;
156  const identity = layerIdentity(root, index);
157  let focus = layerFocusStates.get(identity);
158  if (!focus) {
159    focus = { current: null, last: null, autoFocusConsumed: new Set() };
160    layerFocusStates.set(identity, focus);
161  }
162  return { root, identity, focus };
163}
164
165function focusRefFor(
166  target: LayoutNode,
167  focusables: readonly LayoutNode[],
168): FocusRef {
169  const identity = explicitStateIdentity(target.node);
170  return identity === null
171    ? { kind: "legacy", index: focusables.indexOf(target) }
172    : { kind: "keyed", identity };
173}
174
175function resolveFocusRef(
176  ref: FocusRef | null,
177  focusables: readonly LayoutNode[],
178): LayoutNode | null {
179  if (ref === null) return null;
180  if (ref.kind === "legacy") return focusables[ref.index] ?? null;
181  return (
182    focusables.find(
183      (focusable) => explicitStateIdentity(focusable.node) === ref.identity,
184    ) ?? null
185  );
186}
187
188function autoFocusIdentity(
189  target: LayoutNode,
190  focusables: readonly LayoutNode[],
191): string {
192  return (
193    explicitStateIdentity(target.node) ?? `legacy:${focusables.indexOf(target)}`
194  );
195}
196
197function hasAutoFocus(target: LayoutNode): boolean {
198  return target.node.type !== "text" && target.node.props.autoFocus === true;
199}
200
201function seedAutoFocus(
202  focus: LayerFocusState,
203  focusables: readonly LayoutNode[],
204  focusAlreadyOwned: boolean,
205): void {
206  const pending = focusables.filter(
207    (target) =>
208      hasAutoFocus(target) &&
209      !focus.autoFocusConsumed.has(autoFocusIdentity(target, focusables)),
210  );
211  for (const target of pending) {
212    focus.autoFocusConsumed.add(autoFocusIdentity(target, focusables));
213  }
214  if (focusAlreadyOwned || pending.length === 0) return;
215
216  const target = requiredAt(pending, 0, "autoFocus target");
217  if (!isControlledFocus(target)) {
218    focus.current = focusRefFor(target, focusables);
219  }
220  if (target.node.type !== "text") {
221    target.node.props.onFocus?.({ reason: "auto" });
222  }
223}
224
225/** Discard state only after the frame using this mount set rendered fully. */
226function finalizeMountedStateKeys(keys: MountedStateSnapshot): void {
227  retainTextInputStateKeys(keys.textInputKeys);
228  const mountedLayers = new Map<string, LayoutNode>();
229  for (let i = 0; i < currentLayouts.length; i++) {
230    const root = requiredAt(currentLayouts, i, "layout root");
231    mountedLayers.set(layerIdentity(root, i), root);
232  }
233
234  for (const identity of uncontrolledScrollOffsets.keys()) {
235    if (identity.startsWith("K:") && !keys.containerIdentities.has(identity)) {
236      uncontrolledScrollOffsets.delete(identity);
237    }
238  }
239
240  for (const [identity, focus] of layerFocusStates) {
241    if (!keys.layerIdentities.has(identity)) {
242      layerFocusStates.delete(identity);
243      continue;
244    }
245    if (
246      focus.current?.kind === "keyed" &&
247      !keys.stateIdentities.has(focus.current.identity)
248    ) {
249      focus.current = null;
250    }
251    if (
252      focus.last?.kind === "keyed" &&
253      !keys.stateIdentities.has(focus.last.identity)
254    ) {
255      focus.last = null;
256    }
257
258    const root = mountedLayers.get(identity);
259    if (root) {
260      const focusables = collectFocusable(root);
261      const mountedAutoFocus = new Set(
262        focusables
263          .filter(hasAutoFocus)
264          .map((target) => autoFocusIdentity(target, focusables)),
265      );
266      for (const consumed of focus.autoFocusConsumed) {
267        if (!mountedAutoFocus.has(consumed)) {
268          focus.autoFocusConsumed.delete(consumed);
269        }
270      }
271    }
272  }
273}
274
275function resolveRenderWaiters(): void {
276  const waiters = renderWaiters;
277  renderWaiters = [];
278  for (const resolve of waiters) resolve();
279}
280
281function doRender(): void {
282  renderScheduled = false;
283  if (!renderFn || !terminal) return;
284
285  const forceFullRedraw = fullRedrawScheduled;
286  fullRedrawScheduled = false;
287
288  const width = terminal.columns;
289  const height = terminal.rows;
290
291  // Create or resize buffer
292  const isResize =
293    currentBuffer !== null &&
294    (currentBuffer.width !== width || currentBuffer.height !== height);
295  const isFirstRender = currentBuffer === null;
296
297  if (isFirstRender || isResize || forceFullRedraw) {
298    prevBuffer = null;
299    currentBuffer = new CellBuffer(width, height);
300  } else {
301    prevBuffer = currentBuffer;
302    currentBuffer = new CellBuffer(width, height);
303  }
304
305  // Get the tree from the render function
306  const tree = renderFn();
307  const layers = Array.isArray(tree) ? tree : [tree];
308
309  // Layout each layer
310  currentLayouts = [];
311  for (const layer of layers) {
312    const layoutTree = layout(layer, width, height);
313    currentLayouts.push(layoutTree);
314  }
315
316  const mountedStateKeys = inspectMountedStateKeys(currentLayouts);
317
318  syncLayerFocusState();
319
320  let nextCursor: TerminalCursorState;
321  try {
322    // Stamp uncontrolled focus and scroll before painting
323    stampUncontrolledFocus();
324    stampUncontrolledScroll();
325
326    // Paint each layer into the buffer
327    for (const layoutTree of currentLayouts) {
328      paint(layoutTree, currentBuffer);
329    }
330
331    nextCursor = getDesiredTerminalCursor();
332  } finally {
333    // Never leave framework-only state on application-owned node props.
334    unstampUncontrolledFocus();
335    unstampUncontrolledScroll();
336  }
337
338  // Emit to terminal — differential when possible
339  if (prevBuffer) {
340    const output = emitDiff(prevBuffer, currentBuffer, activeTheme, {
341      cursor: nextCursor,
342      previousCursor: lastTerminalCursor,
343    });
344    if (output.length > 0) terminal.write(output);
345  } else {
346    const output = emitBuffer(currentBuffer, activeTheme, {
347      cursor: nextCursor,
348      previousCursor: lastTerminalCursor,
349    });
350    terminal.write(output);
351  }
352
353  lastTerminalCursor = nextCursor;
354  finalizeMountedStateKeys(mountedStateKeys);
355}
356
357/**
358 * Resolve the final terminal cursor state for the current frame.
359 * The cursor is shown only for a focused TextInput whose cursor is visible
360 * within the clipped viewport.
361 */
362function getDesiredTerminalCursor(): TerminalCursorState {
363  const focusedTI = findFocusedTextInputLayout();
364  if (!focusedTI) return { visible: false };
365
366  const path = findPathInCurrentLayouts(focusedTI);
367  if (!path) return { visible: false };
368
369  const projection = projectLayoutThroughAncestors(path);
370  if (!projection) return { visible: false };
371
372  const props = focusedTI.node.props as import("@cel-tui/types").TextInputProps;
373  const pos = getTextInputCursorScreenPos(props, projection.rect);
374  if (!pos || !pointInRect(pos.x, pos.y, projection.clip)) {
375    return { visible: false };
376  }
377
378  return {
379    visible: true,
380    x: pos.x,
381    y: pos.y,
382    style: props.cursorStyle ?? "block",
383  };
384}
385
386function findPathInCurrentLayouts(target: LayoutNode): LayoutNode[] | null {
387  for (let i = currentLayouts.length - 1; i >= 0; i--) {
388    const path = findPathTo(
389      requiredAt(currentLayouts, i, "layout root"),
390      target,
391    );
392    if (path) return path;
393  }
394  return null;
395}
396
397function projectLayoutThroughAncestors(
398  path: LayoutNode[],
399): { rect: Rect; clip: Rect } | null {
400  if (!terminal || path.length === 0) return null;
401
402  let offsetX = 0;
403  let offsetY = 0;
404  let clip: Rect = {
405    x: 0,
406    y: 0,
407    width: terminal.columns,
408    height: terminal.rows,
409  };
410
411  for (let i = 0; i < path.length; i++) {
412    const current = requiredAt(path, i, "focused path node");
413    const projectedRect = translateRect(current.rect, offsetX, offsetY);
414    clip = intersectRects(clip, projectedRect);
415    if (clip.width <= 0 || clip.height <= 0) return null;
416
417    if (i === path.length - 1) {
418      return { rect: projectedRect, clip };
419    }
420
421    if (
422      (current.node.type === "vstack" || current.node.type === "hstack") &&
423      current.node.props.overflow === "scroll"
424    ) {
425      const scrollOffset = resolveScrollOffset(current);
426      if (current.node.type === "vstack") {
427        offsetY -= scrollOffset;
428      } else {
429        offsetX -= scrollOffset;
430      }
431    }
432  }
433
434  return null;
435}
436
437function translateRect(rect: Rect, offsetX: number, offsetY: number): Rect {
438  return {
439    x: rect.x + offsetX,
440    y: rect.y + offsetY,
441    width: rect.width,
442    height: rect.height,
443  };
444}
445
446function intersectRects(a: Rect, b: Rect): Rect {
447  const x = Math.max(a.x, b.x);
448  const y = Math.max(a.y, b.y);
449  const right = Math.min(a.x + a.width, b.x + b.width);
450  const bottom = Math.min(a.y + a.height, b.y + b.height);
451  return {
452    x,
453    y,
454    width: Math.max(0, right - x),
455    height: Math.max(0, bottom - y),
456  };
457}
458
459function pointInRect(x: number, y: number, rect: Rect): boolean {
460  return (
461    x >= rect.x &&
462    x < rect.x + rect.width &&
463    y >= rect.y &&
464    y < rect.y + rect.height
465  );
466}
467
468/**
469 * Find the focused TextInput in the current layout tree.
470 * Checks controlled focus (props.focused) and uncontrolled
471 * (framework-tracked index). Returns the LayoutNode or null.
472 */
473function findFocusedTextInputLayout(): LayoutNode | null {
474  const context = topLayerContext();
475  if (!context) return null;
476
477  const controlled = findFocusedTIInTree(context.root);
478  if (controlled) return controlled;
479
480  const target = resolveFocusRef(
481    context.focus.current,
482    collectFocusable(context.root),
483  );
484  if (target?.node.type === "textinput") return target;
485  return null;
486}
487
488function findFocusedTIInTree(ln: LayoutNode): LayoutNode | null {
489  if (ln.node.type === "textinput" && ln.node.props.focused) return ln;
490  for (const child of ln.children) {
491    const found = findFocusedTIInTree(child);
492    if (found) return found;
493  }
494  return null;
495}
496
497function syncLayerFocusState(): void {
498  const context = topLayerContext();
499  if (!context) return;
500
501  const focusables = collectFocusable(context.root);
502  if (focusables.length === 0) {
503    context.focus.current = null;
504    context.focus.last = null;
505    return;
506  }
507
508  const controlled = findFocusedInTree(context.root);
509  const uncontrolled = resolveFocusRef(context.focus.current, focusables);
510  if (uncontrolled === null && context.focus.current?.kind === "keyed") {
511    context.focus.current = null;
512  }
513  seedAutoFocus(
514    context.focus,
515    focusables,
516    controlled !== null || uncontrolled !== null,
517  );
518
519  if (controlled) {
520    context.focus.last = focusRefFor(controlled, focusables);
521    return;
522  }
523}
524
525// --- Input handling ---
526
527const BRACKETED_PASTE_START = "\x1b[200~";
528const BRACKETED_PASTE_END = "\x1b[201~";
529const LEGACY_ESCAPE_TIMEOUT_MS = 25;
530
531// Regex for a single SGR mouse event, anchored to the current parse position.
532// biome-ignore lint/complexity/useRegexLiterals: using RegExp here avoids control-character regex diagnostics.
533const SGR_MOUSE_RE = new RegExp(String.raw`^\x1b\[<(\d+);(\d+);(\d+)([Mm])`);
534// biome-ignore lint/complexity/useRegexLiterals: using RegExp here avoids control-character regex diagnostics.
535const TERMINAL_TITLE_CONTROL_CHARS_RE = new RegExp(
536  String.raw`[\x00-\x1f\x7f-\x9f]`,
537  "g",
538);
539
540// Trailing input that ended with an incomplete CSI or paste-start sequence.
541let pendingKeyData = "";
542let pendingEscapeTimer: ReturnType<typeof setTimeout> | null = null;
543
544// Bracketed paste state across stdin chunks.
545let inBracketedPaste = false;
546let bracketedPasteData = "";
547let bracketedPasteSuffix = "";
548
549// Tracks accumulated scroll offsets during a batch of mouse events.
550// Controlled scroll reads scrollOffset from props, which doesn't update until
551// re-render. Within a single data chunk containing multiple scroll events, we
552// need to remember the offset we already dispatched via onScroll.
553let batchScrollOffsets: Map<object, number> | null = null;
554
555// Tracks the focused TextInput's latest edit state during a batched keyboard
556// chunk. The layout tree does not re-render until the next tick, so subsequent
557// keys in the same chunk must see the updated value/cursor immediately.
558let batchTextInputEdits: Map<TextInputProps, EditState> | null = null;
559
560function sanitizeTerminalTitle(title: string): string {
561  return title.replace(TERMINAL_TITLE_CONTROL_CHARS_RE, "");
562}
563
564function handleInput(data: string): void {
565  clearPendingEscapeTimer();
566  batchTextInputEdits = new Map();
567
568  try {
569    let remaining = data;
570
571    if (inBracketedPaste) {
572      remaining = consumeBracketedPasteData(remaining);
573      if (remaining.length === 0) return;
574    }
575
576    let chunk = pendingKeyData + remaining;
577    pendingKeyData = "";
578
579    let keyChunkStart = 0;
580    let index = 0;
581
582    while (index < chunk.length) {
583      if (chunk.startsWith(BRACKETED_PASTE_START, index)) {
584        handleKeyChunk(chunk.slice(keyChunkStart, index));
585
586        index += BRACKETED_PASTE_START.length;
587        keyChunkStart = index;
588        inBracketedPaste = true;
589
590        const afterPaste = consumeBracketedPasteData(chunk.slice(index));
591        if (afterPaste.length === 0) return;
592
593        chunk = afterPaste;
594        index = 0;
595        keyChunkStart = 0;
596        continue;
597      }
598
599      const mouse = readSgrMouseEvent(chunk, index);
600      if (mouse) {
601        handleKeyChunk(chunk.slice(keyChunkStart, index));
602
603        if (batchScrollOffsets === null) {
604          batchScrollOffsets = new Map();
605        }
606        if (mouse.event) handleMouseEvent(mouse.event);
607
608        index = mouse.nextIndex;
609        keyChunkStart = index;
610        continue;
611      }
612
613      index++;
614    }
615
616    const { complete, pending } = splitIncompleteInputSuffix(
617      chunk.slice(keyChunkStart),
618    );
619    handleKeyChunk(complete);
620    pendingKeyData = pending;
621    schedulePendingEscape();
622  } finally {
623    batchScrollOffsets = null;
624    batchTextInputEdits = null;
625  }
626}
627
628function handleKeyChunk(data: string): void {
629  if (data.length === 0) return;
630  for (const key of decodeKeyEvents(data)) {
631    handleKeyEvent(key);
632  }
633}
634
635function clearPendingEscapeTimer(): void {
636  if (pendingEscapeTimer === null) return;
637  clearTimeout(pendingEscapeTimer);
638  pendingEscapeTimer = null;
639}
640
641function schedulePendingEscape(): void {
642  if (pendingKeyData !== "\x1b") return;
643
644  pendingEscapeTimer = setTimeout(() => {
645    pendingEscapeTimer = null;
646    if (pendingKeyData !== "\x1b") return;
647
648    const escapeData = pendingKeyData;
649    pendingKeyData = "";
650    handleKeyChunk(escapeData);
651  }, LEGACY_ESCAPE_TIMEOUT_MS);
652}
653
654function consumeBracketedPasteData(data: string): string {
655  const chunk = bracketedPasteSuffix + data;
656  bracketedPasteSuffix = "";
657
658  const endIndex = chunk.indexOf(BRACKETED_PASTE_END);
659  if (endIndex === -1) {
660    const { complete, pending } = splitTrailingMarkerPrefix(
661      chunk,
662      BRACKETED_PASTE_END,
663    );
664    bracketedPasteData += complete;
665    bracketedPasteSuffix = pending;
666    return "";
667  }
668
669  bracketedPasteData += chunk.slice(0, endIndex);
670  const pastedText = bracketedPasteData;
671
672  inBracketedPaste = false;
673  bracketedPasteData = "";
674  bracketedPasteSuffix = "";
675  handleBracketedPaste(pastedText);
676
677  return chunk.slice(endIndex + BRACKETED_PASTE_END.length);
678}
679
680function splitTrailingMarkerPrefix(
681  data: string,
682  marker: string,
683): { complete: string; pending: string } {
684  const maxPrefixLength = Math.min(data.length, marker.length - 1);
685  for (let length = maxPrefixLength; length > 0; length--) {
686    if (data.endsWith(marker.slice(0, length))) {
687      return {
688        complete: data.slice(0, data.length - length),
689        pending: data.slice(data.length - length),
690      };
691    }
692  }
693  return { complete: data, pending: "" };
694}
695
696function splitIncompleteInputSuffix(data: string): {
697  complete: string;
698  pending: string;
699} {
700  const pasteStart = splitTrailingMarkerPrefix(data, BRACKETED_PASTE_START);
701  if (pasteStart.pending.length > 0) {
702    return pasteStart;
703  }
704
705  const csiStart = data.lastIndexOf("\x1b[");
706  if (csiStart === -1) return { complete: data, pending: "" };
707
708  const suffix = data.slice(csiStart);
709  for (let i = 2; i < suffix.length; i++) {
710    const code = suffix.charCodeAt(i);
711    if (code >= 0x40 && code <= 0x7e) {
712      return { complete: data, pending: "" };
713    }
714  }
715
716  return { complete: data.slice(0, csiStart), pending: suffix };
717}
718
719interface MouseEvent {
720  type: "click" | "scroll-up" | "scroll-down";
721  x: number;
722  y: number;
723}
724
725function readSgrMouseEvent(
726  data: string,
727  index: number,
728): { event: MouseEvent | null; nextIndex: number } | null {
729  const match = SGR_MOUSE_RE.exec(data.slice(index));
730  if (!match) return null;
731  return {
732    event: parseSgrMatch(match),
733    nextIndex: index + match[0].length,
734  };
735}
736
737/**
738 * Parse a single SGR mouse event from a RegExp match.
739 * Returns a MouseEvent for scroll and click events, null for unhandled buttons.
740 */
741function parseSgrMatch(match: RegExpExecArray): MouseEvent | null {
742  const cbMatch = match[1];
743  const xMatch = match[2];
744  const yMatch = match[3];
745  if (cbMatch === undefined || xMatch === undefined || yMatch === undefined) {
746    throw new Error("Incomplete SGR mouse match");
747  }
748
749  const cb = parseInt(cbMatch, 10);
750  const x = parseInt(xMatch, 10) - 1; // 1-indexed → 0-indexed
751  const y = parseInt(yMatch, 10) - 1;
752  const isRelease = match[4] === "m";
753
754  // Scroll up (cb=64) / scroll down (cb=65)
755  if (cb === 64) return { type: "scroll-up", x, y };
756  if (cb === 65) return { type: "scroll-down", x, y };
757
758  // Button click (cb=0 for left button, release event)
759  if (cb === 0 && isRelease) return { type: "click", x, y };
760
761  return null;
762}
763
764/**
765 * Check if a focusable element uses controlled focus (explicit `focused` prop).
766 */
767function isControlledFocus(ln: LayoutNode): boolean {
768  const node = ln.node;
769  if (node.type === "textinput") return node.props.focused !== undefined;
770  if (node.type === "vstack" || node.type === "hstack")
771    return node.props.focused !== undefined;
772  return false;
773}
774
775/**
776 * Find the currently focused element in the active (topmost) layer.
777 * Checks controlled focus (`focused: true` in props) first,
778 * then falls back to framework-tracked uncontrolled focus.
779 */
780function findFocusedElement(): LayoutNode | null {
781  const context = topLayerContext();
782  if (!context) return null;
783  const controlled = findFocusedInTree(context.root);
784  if (controlled) return controlled;
785  return resolveFocusRef(context.focus.current, collectFocusable(context.root));
786}
787
788/**
789 * Stamp `focused: true` on the framework-tracked focused node's props
790 * before painting, so that paint/focusStyle/cursor rendering picks it up.
791 * Only stamps if no controlled element is already focused.
792 * Must be followed by {@link unstampUncontrolledFocus} after paint.
793 */
794function stampUncontrolledFocus(): void {
795  stampedNode = null;
796  const context = topLayerContext();
797  if (!context || context.focus.current === null) return;
798
799  // Controlled focus replaces uncontrolled focus within the same layer.
800  if (findFocusedInTree(context.root)) {
801    context.focus.current = null;
802    return;
803  }
804
805  const target = resolveFocusRef(
806    context.focus.current,
807    collectFocusable(context.root),
808  );
809  if (!target) return;
810  const node = target.node;
811  if (
812    node.type === "textinput" ||
813    node.type === "vstack" ||
814    node.type === "hstack"
815  ) {
816    node.props.focused = true;
817    stampedNode = target;
818  }
819}
820
821/**
822 * Remove the `focused: true` stamp set by {@link stampUncontrolledFocus}.
823 * Called after paint so input handlers see the original props and can
824 * correctly distinguish controlled from uncontrolled elements.
825 */
826function unstampUncontrolledFocus(): void {
827  if (!stampedNode) return;
828  const node = stampedNode.node;
829  if (
830    node.type === "textinput" ||
831    node.type === "vstack" ||
832    node.type === "hstack"
833  ) {
834    delete node.props.focused;
835  }
836  stampedNode = null;
837}
838
839/**
840 * Compute the structural tree path from a layer root to a target LayoutNode.
841 * Returns a string like "0/2/1" or null if target is not in the tree.
842 */
843function computeTreePath(root: LayoutNode, target: LayoutNode): string | null {
844  if (root === target) return "";
845  for (let i = 0; i < root.children.length; i++) {
846    const sub = computeTreePath(
847      requiredAt(root.children, i, "layout child"),
848      target,
849    );
850    if (sub !== null) return sub === "" ? String(i) : `${i}/${sub}`;
851  }
852  return null;
853}
854
855/**
856 * Get the full path key for a scrollable node, prefixed by layer index.
857 */
858function getScrollPathKey(target: LayoutNode): string | null {
859  const explicit = explicitStateIdentity(target.node);
860  if (explicit !== null) return explicit;
861
862  for (let i = 0; i < currentLayouts.length; i++) {
863    const path = computeTreePath(
864      requiredAt(currentLayouts, i, "layout root"),
865      target,
866    );
867    if (path !== null) return `L${i}:${path}`;
868  }
869  return null;
870}
871
872/**
873 * Stamp `scrollOffset` on uncontrolled scrollable containers' props
874 * before painting, so paint reads the correct offset.
875 */
876function stampUncontrolledScroll(): void {
877  stampedScrollNodes = [];
878  if (uncontrolledScrollOffsets.size === 0) return;
879  for (let i = 0; i < currentLayouts.length; i++) {
880    walkAndStampScroll(requiredAt(currentLayouts, i, "layout root"), `L${i}:`);
881  }
882}
883
884function walkAndStampScroll(ln: LayoutNode, pathKey: string): void {
885  const node = ln.node;
886  if (node.type === "vstack" || node.type === "hstack") {
887    if (
888      node.props.overflow === "scroll" &&
889      node.props.scrollOffset === undefined
890    ) {
891      const stateIdentity = explicitStateIdentity(node) ?? pathKey;
892      const offset = uncontrolledScrollOffsets.get(stateIdentity);
893      if (offset !== undefined && offset !== 0) {
894        node.props.scrollOffset = offset;
895        stampedScrollNodes.push({ node, key: stateIdentity });
896      }
897    }
898  }
899  for (let i = 0; i < ln.children.length; i++) {
900    // Keys match getScrollPathKey format: "L0:" for root, "L0:2" for child 2, "L0:2/1" for grandchild
901    const childKey = pathKey.endsWith(":")
902      ? `${pathKey}${i}`
903      : `${pathKey}/${i}`;
904    walkAndStampScroll(requiredAt(ln.children, i, "layout child"), childKey);
905  }
906}
907
908function unstampUncontrolledScroll(): void {
909  for (const { node } of stampedScrollNodes) {
910    if (node.type === "vstack" || node.type === "hstack") {
911      delete node.props.scrollOffset;
912    }
913  }
914  stampedScrollNodes = [];
915}
916
917/**
918 * Blur the currently focused element and focus a new one.
919 * Manages both controlled (via onFocus/onBlur callbacks) and
920 * uncontrolled per-layer focus.
921 */
922function changeFocus(
923  target: LayoutNode | null,
924  reason: FocusChangeReason,
925): void {
926  const context = topLayerContext();
927  if (!context) return;
928  const focusables = collectFocusable(context.root);
929  const current = findFocusedElement();
930  const event = { reason };
931
932  // Blur current — save position for Tab/Shift+Tab continuity
933  if (current && current !== target) {
934    context.focus.last = focusRefFor(current, focusables);
935    context.focus.current = null;
936    const props =
937      current.node.type === "textinput"
938        ? current.node.props
939        : current.node.type !== "text"
940          ? current.node.props
941          : null;
942    if (props && "onBlur" in props && props.onBlur) {
943      props.onBlur(event);
944    }
945  }
946
947  // Focus new target — clear saved position
948  if (target && target !== current) {
949    context.focus.last = null;
950    // Set or clear framework tracking based on controlled/uncontrolled
951    if (!isControlledFocus(target)) {
952      context.focus.current = focusRefFor(target, focusables);
953    } else {
954      context.focus.current = null;
955    }
956    const props =
957      target.node.type === "textinput"
958        ? target.node.props
959        : target.node.type !== "text"
960          ? target.node.props
961          : null;
962    if (props && "onFocus" in props && props.onFocus) {
963      props.onFocus(event);
964    }
965  }
966}
967
968/**
969 * Resolve the current scroll offset for a layout node.
970 * Checks controlled (props.scrollOffset), then uncontrolled (path-based map).
971 */
972function resolveScrollOffset(ln: import("./layout.js").LayoutNode): number {
973  const node = ln.node;
974  if (node.type === "text") return 0;
975  if (node.type === "textinput") {
976    return getTextInputScroll(node.props);
977  }
978  const props = node.props;
979  if (props.scrollOffset !== undefined) {
980    return clampScrollOffset(ln, props.scrollOffset);
981  }
982  // Check uncontrolled map
983  const pathKey = getScrollPathKey(ln);
984  if (pathKey !== null) {
985    return clampScrollOffset(ln, uncontrolledScrollOffsets.get(pathKey) ?? 0);
986  }
987  return 0;
988}
989
990function handleMouseEvent(event: MouseEvent): void {
991  // Hit test on topmost layer first
992  for (let i = currentLayouts.length - 1; i >= 0; i--) {
993    const layoutRoot = requiredAt(currentLayouts, i, "layout root");
994    const path = hitTest(layoutRoot, event.x, event.y, resolveScrollOffset);
995    if (path.length === 0) continue;
996
997    if (event.type === "click") {
998      // Find and focus the focusable element at click position
999      const focusable = findClickFocusTarget(path);
1000      if (focusable) {
1001        changeFocus(focusable, "click");
1002      }
1003
1004      const click = findClickHandler(path);
1005      if (click) {
1006        click.handler();
1007      }
1008      cel.render();
1009      return;
1010    }
1011
1012    if (event.type === "scroll-up" || event.type === "scroll-down") {
1013      const targets = collectScrollTargets(path);
1014      for (const target of targets) {
1015        const step = getScrollStep(target);
1016        const delta = event.type === "scroll-up" ? -step : step;
1017        const maxOffset = getMaxScrollOffset(target);
1018
1019        if (target.node.type === "textinput") {
1020          // TextInput scroll is always framework-managed and consumes wheel input.
1021          const tiProps = target.node.props;
1022          const current = getTextInputScroll(tiProps);
1023          const clamped = Math.max(0, Math.min(maxOffset, current + delta));
1024          setTextInputScroll(tiProps, clamped);
1025          cel.render();
1026          return;
1027        }
1028
1029        if (target.node.type === "vstack" || target.node.type === "hstack") {
1030          const props = target.node.props;
1031          if (props.overflow !== "scroll") continue;
1032
1033          if (props.scrollOffset !== undefined) {
1034            // Controlled scroll: the app owns the offset. Notify it when a
1035            // handler is present, but never write framework scroll state.
1036            // Use batch accumulator if available (multiple events in one chunk),
1037            // otherwise read from props. Clamp to maxOffset first so that
1038            // Infinity (sticky-bottom) resolves to a finite value before
1039            // applying the delta — otherwise Infinity + (-1) = Infinity
1040            // and scrolling up never unsticks.
1041            if (props.onScroll) {
1042              const rawBase =
1043                batchScrollOffsets?.get(props) ?? props.scrollOffset;
1044              const baseOffset = Math.min(rawBase, maxOffset);
1045              const newOffset = Math.max(
1046                0,
1047                Math.min(maxOffset, baseOffset + delta),
1048              );
1049              const result = props.onScroll(newOffset, maxOffset);
1050              if (result === false) continue;
1051              batchScrollOffsets?.set(props, newOffset);
1052            }
1053          } else {
1054            // Uncontrolled scroll: callbacks participate in consume/bubble
1055            // routing, while the framework remains the source of truth.
1056            const pathKey = getScrollPathKey(target);
1057            const current =
1058              pathKey === null
1059                ? 0
1060                : (uncontrolledScrollOffsets.get(pathKey) ?? 0);
1061            const newOffset = Math.max(0, Math.min(maxOffset, current + delta));
1062
1063            if (props.onScroll) {
1064              const result = props.onScroll(newOffset, maxOffset);
1065              if (result === false) continue;
1066            }
1067
1068            if (pathKey !== null) {
1069              uncontrolledScrollOffsets.set(pathKey, newOffset);
1070            }
1071          }
1072
1073          cel.render();
1074          return;
1075        }
1076      }
1077      return;
1078    }
1079  }
1080}
1081
1082/**
1083 * Find the nearest focusable element in a hit path (for mouse click focusing).
1084 */
1085function findClickFocusTarget(path: LayoutNode[]): LayoutNode | null {
1086  for (let i = path.length - 1; i >= 0; i--) {
1087    const layoutNode = requiredAt(path, i, "hit path node");
1088    const node = layoutNode.node;
1089    if (node.type === "textinput" && node.props.focusable !== false) {
1090      return layoutNode;
1091    }
1092    if (node.type === "vstack" || node.type === "hstack") {
1093      const isFocusable =
1094        node.props.focusable === true ||
1095        (node.props.onClick != null && node.props.focusable !== false);
1096      if (isFocusable) return layoutNode;
1097    }
1098  }
1099  return null;
1100}
1101
1102function getTextInputEditState(props: TextInputProps): EditState {
1103  const batched = batchTextInputEdits?.get(props);
1104  if (batched) return batched;
1105  return {
1106    value: props.value,
1107    cursor: getTextInputCursor(props),
1108  };
1109}
1110
1111function commitTextInputEdit(
1112  props: TextInputProps,
1113  previousState: EditState,
1114  nextState: EditState,
1115): void {
1116  batchTextInputEdits?.set(props, nextState);
1117  setTextInputCursor(props, nextState.cursor, nextState.value);
1118  if (nextState.value !== previousState.value) {
1119    props.onChange(nextState.value);
1120  }
1121  if (nextState.cursor !== previousState.cursor) {
1122    props.onCursorChange?.(nextState.cursor);
1123  }
1124  cel.render();
1125}
1126
1127function handleBracketedPaste(text: string): void {
1128  if (text.length === 0) return;
1129
1130  const focusedInput = findFocusedTextInput();
1131  if (!focusedInput) return;
1132
1133  const props = focusedInput.node.props as TextInputProps;
1134  const editState = getTextInputEditState(props);
1135  const nextState = insertChar(editState, text);
1136  commitTextInputEdit(props, editState, nextState);
1137}
1138
1139function blurFocusedElement(reason: FocusChangeReason = "escape"): boolean {
1140  const current = findFocusedElement();
1141  if (!current) return false;
1142
1143  changeFocus(null, reason);
1144  cel.render();
1145  return true;
1146}
1147
1148function handleKeyEvent(event: KeyInput): void {
1149  const { key, text } = event;
1150  const isRelease = event.eventType === "release";
1151
1152  // --- Focus traversal keys ---
1153
1154  // Tab / Shift+Tab: cycle through focusable elements
1155  // Skip focus traversal when a TextInput is focused — Tab is an editing key
1156  // that inserts \t. The user must Escape first, then Tab to traverse.
1157  if (!isRelease && (key === "tab" || key === "shift+tab")) {
1158    const focusedTI = findFocusedTextInput();
1159    if (focusedTI) {
1160      // Fall through to TextInput key routing below
1161    } else {
1162      const context = topLayerContext();
1163      if (!context) return;
1164      const focusables = collectFocusable(context.root);
1165      if (focusables.length === 0) return;
1166
1167      const current = findFocusedElement();
1168      let currentIdx = current ? focusables.indexOf(current) : -1;
1169
1170      // If current not found in focusables list, search by identity
1171      if (currentIdx === -1 && current) {
1172        currentIdx = focusables.findIndex((f) => f.node === current.node);
1173      }
1174
1175      // Continue from the last focused identity after Escape. Keyed refs
1176      // survive sibling reordering; the legacy fallback remains positional.
1177      if (currentIdx === -1) {
1178        const previous = resolveFocusRef(context.focus.last, focusables);
1179        if (previous) currentIdx = focusables.indexOf(previous);
1180      }
1181
1182      let nextIdx: number;
1183      if (key === "tab") {
1184        nextIdx = currentIdx === -1 ? 0 : (currentIdx + 1) % focusables.length;
1185      } else {
1186        nextIdx =
1187          currentIdx === -1
1188            ? focusables.length - 1
1189            : (currentIdx - 1 + focusables.length) % focusables.length;
1190      }
1191
1192      changeFocus(
1193        requiredAt(focusables, nextIdx, "focusable node"),
1194        key === "tab" ? "tab" : "shift+tab",
1195      );
1196      cel.render();
1197      return;
1198    } // end: not a focused TextInput
1199  }
1200
1201  // Enter: activate focused clickable container
1202  if (!isRelease && key === "enter") {
1203    const current = findFocusedElement();
1204    if (current && current.node.type !== "textinput") {
1205      const props = current.node.type !== "text" ? current.node.props : null;
1206      if (props?.onClick) {
1207        props.onClick();
1208        cel.render();
1209        return;
1210      }
1211    }
1212  }
1213
1214  // --- TextInput key routing ---
1215  const focusedInput = findFocusedTextInput();
1216
1217  if (focusedInput) {
1218    const props = focusedInput.node.props as TextInputProps;
1219
1220    // onKeyPress fires before editing — return false prevents the default action
1221    if (props.onKeyPress) {
1222      const result = props.onKeyPress(key, event);
1223      if (result === false) {
1224        cel.render();
1225        return;
1226      }
1227    }
1228
1229    let newState: EditState | null = null;
1230    const editState = getTextInputEditState(props);
1231    const isTextInputEditingKey =
1232      !isRelease && text === undefined && isEditingKey(key);
1233
1234    if (!isRelease && text !== undefined) {
1235      newState = insertChar(editState, text);
1236    } else if (isTextInputEditingKey) {
1237      switch (key) {
1238        case "backspace":
1239          newState = deleteBackward(editState);
1240          break;
1241        case "delete":
1242          newState = deleteForward(editState);
1243          break;
1244        case "ctrl+w":
1245          newState = deleteWordBackward(editState);
1246          break;
1247        case "alt+d":
1248          newState = deleteWordForward(editState);
1249          break;
1250        case "left":
1251        case "right":
1252        case "up":
1253        case "down":
1254        case "home":
1255        case "end":
1256        case "ctrl+a":
1257        case "ctrl+e":
1258          {
1259            const tiPadX =
1260              (focusedInput.node as TextInputNode).props.padding?.x ?? 0;
1261            const contentWidth = Math.max(
1262              0,
1263              focusedInput.rect.width - tiPadX * 2,
1264            );
1265            const direction =
1266              key === "ctrl+a" ? "home" : key === "ctrl+e" ? "end" : key;
1267            newState = moveCursor(
1268              editState,
1269              direction as "left" | "right" | "up" | "down" | "home" | "end",
1270              contentWidth,
1271            );
1272          }
1273          break;
1274        case "alt+b":
1275        case "ctrl+left":
1276          newState = moveCursorByWord(editState, "backward");
1277          break;
1278        case "alt+f":
1279        case "ctrl+right":
1280          newState = moveCursorByWord(editState, "forward");
1281          break;
1282        case "enter":
1283        case "shift+enter":
1284          newState = insertChar(editState, "\n");
1285          break;
1286        case "tab":
1287          newState = insertChar(editState, "\t");
1288          break;
1289        case "space":
1290          newState = insertChar(editState, " ");
1291          break;
1292        case "plus":
1293          newState = insertChar(editState, "+");
1294          break;
1295      }
1296    }
1297
1298    if (newState && newState !== editState) {
1299      commitTextInputEdit(props, editState, newState);
1300      return;
1301    }
1302
1303    // Editing keys belong to the focused TextInput even when the requested
1304    // operation is a boundary no-op (for example, Backspace at offset 0).
1305    if (isTextInputEditingKey) return;
1306  }
1307
1308  // Key not consumed by TextInput — bubble up from focused element
1309  const focused = findFocusedElement();
1310  if (focused) {
1311    for (let i = currentLayouts.length - 1; i >= 0; i--) {
1312      const path = findPathTo(
1313        requiredAt(currentLayouts, i, "layout root"),
1314        focused,
1315      );
1316      if (path) {
1317        let handlers = collectKeyPressHandlers(path);
1318        // If a TextInput's onKeyPress was already called in the pre-editing
1319        // hook above, exclude it from bubbling to avoid calling it twice.
1320        if (
1321          focusedInput &&
1322          handlers.length > 0 &&
1323          requiredAt(handlers, 0, "key handler").layoutNode === focusedInput
1324        ) {
1325          handlers = handlers.slice(1);
1326        }
1327        if (handlers.length > 0) {
1328          let consumed = false;
1329          for (const h of handlers) {
1330            const result = h.handler(key, event);
1331            if (result !== false) {
1332              consumed = true;
1333              break;
1334            }
1335            // result === false → key not consumed, keep bubbling
1336          }
1337          // Always return — the key was offered to every handler in the
1338          // focused element's path (including root). Even if all returned
1339          // false, we don't retry via the top-layer fallback path.
1340          if (consumed) {
1341            cel.render();
1342            return;
1343          }
1344          if (!isRelease && key === "escape" && blurFocusedElement()) return;
1345          return;
1346        }
1347
1348        // The focused path already includes the top-layer root. Do not retry
1349        // the fallback path after excluding a TextInput's pre-edit handler.
1350        if (!isRelease && key === "escape" && blurFocusedElement()) return;
1351        return;
1352      }
1353    }
1354  }
1355
1356  // Fallback: offer the key to the topmost layer's root when it was not
1357  // already handled on the focused path.
1358  const topLayer = currentLayouts[currentLayouts.length - 1];
1359  if (!topLayer) {
1360    if (key === "escape") blurFocusedElement();
1361    return;
1362  }
1363
1364  const handlers = collectKeyPressHandlers([topLayer]);
1365  if (handlers.length > 0) {
1366    let consumed = false;
1367    for (const h of handlers) {
1368      const result = h.handler(key, event);
1369      if (result !== false) {
1370        consumed = true;
1371        break;
1372      }
1373    }
1374    if (consumed) {
1375      cel.render();
1376      return;
1377    }
1378  }
1379
1380  if (!isRelease && key === "escape" && blurFocusedElement()) return;
1381  if (handlers.length === 0) return;
1382  cel.render();
1383}
1384
1385/**
1386 * Build the path from root to a target node (depth-first search).
1387 * Returns the path array [root, ..., target] or null if not found.
1388 */
1389function findPathTo(root: LayoutNode, target: LayoutNode): LayoutNode[] | null {
1390  if (root === target || root.node === target.node) return [root];
1391  for (const child of root.children) {
1392    const childPath = findPathTo(child, target);
1393    if (childPath) return [root, ...childPath];
1394  }
1395  return null;
1396}
1397
1398function findFocusedTextInput(): LayoutNode | null {
1399  const focused = findFocusedElement();
1400  return focused && focused.node.type === "textinput" ? focused : null;
1401}
1402
1403function findFocusedInTree(ln: LayoutNode): LayoutNode | null {
1404  if (ln.node.type === "textinput" && ln.node.props.focused) {
1405    return ln;
1406  }
1407  if (
1408    (ln.node.type === "vstack" || ln.node.type === "hstack") &&
1409    ln.node.props.focused
1410  ) {
1411    return ln;
1412  }
1413  for (const child of ln.children) {
1414    const found = findFocusedInTree(child);
1415    if (found) return found;
1416  }
1417  return null;
1418}
1419
1420// --- Public API ---
1421
1422/**
1423 * cel-tui framework entrypoint.
1424 *
1425 * The framework is stateless — it renders whatever tree the render function
1426 * returns. State management is fully external. Use any approach you like
1427 * (plain variables, classes, libraries) and call {@link cel.render} when
1428 * state changes.
1429 *
1430 * @example
1431 * ```ts
1432 * import { cel, VStack, Text, ProcessTerminal } from "@cel-tui/core";
1433 *
1434 * cel.init(new ProcessTerminal());
1435 * cel.viewport(() =>
1436 *   VStack({ height: "100%" }, [
1437 *     Text("Hello, world!", { bold: true }),
1438 *   ])
1439 * );
1440 * ```
1441 */
1442export const cel = {
1443  /**
1444   * Initialize the framework with a terminal implementation.
1445   * Must be called before {@link cel.viewport}.
1446   *
1447   * Enables Kitty baseline disambiguation and any requested progressive
1448   * enhancements, plus bracketed paste and mouse tracking via the terminal.
1449   *
1450   * @param term - Terminal to render to (ProcessTerminal or MockTerminal).
1451   * @param options - Optional configuration.
1452   * @param options.theme - Color theme mapping. Defaults to the ANSI 16 theme.
1453   * @param options.kittyKeyboard - Advanced Kitty keyboard reporting flags.
1454   */
1455  init(term: Terminal, options?: CelInitOptions): void {
1456    terminal = term;
1457    activeTheme = options?.theme ?? defaultTheme;
1458    layerFocusStates.clear();
1459    resetTextInputState();
1460    lastTerminalCursor = { visible: false };
1461    lastTerminalTitle = null;
1462    fullRedrawScheduled = false;
1463    terminal.start(
1464      handleInput,
1465      () => cel.render(),
1466      options?.kittyKeyboard
1467        ? { kittyKeyboard: options.kittyKeyboard }
1468        : undefined,
1469    );
1470  },
1471
1472  /**
1473   * Set the render function that returns the UI tree.
1474   * Triggers the first render automatically.
1475   *
1476   * @param fn - A function that returns the current UI tree.
1477   */
1478  viewport(fn: RenderFn): void {
1479    renderFn = fn;
1480    cel.render();
1481  },
1482
1483  /**
1484   * Request a re-render. Call this after state changes.
1485   *
1486   * Batched via `process.nextTick()` — multiple calls within the same
1487   * tick produce a single render.
1488   */
1489  render(): void {
1490    if (renderScheduled) return;
1491    renderScheduled = true;
1492    process.nextTick(() => {
1493      try {
1494        doRender();
1495      } finally {
1496        resolveRenderWaiters();
1497      }
1498    });
1499  },
1500
1501  /**
1502   * Request a full redraw of the current viewport.
1503   *
1504   * Unlike {@link cel.render}, this discards the differential baseline and
1505   * re-emits every cell. Use it after external screen corruption or terminal
1506   * resume. Calls remain batched within the current tick.
1507   */
1508  redraw(): void {
1509    fullRedrawScheduled = true;
1510    cel.render();
1511  },
1512
1513  /**
1514   * Replace the active color theme at runtime and redraw every cell.
1515   *
1516   * A full redraw is required because cell buffers store palette slots, so a
1517   * normal logical diff cannot observe that a slot's rendered color changed.
1518   */
1519  setTheme(theme: Theme): void {
1520    activeTheme = theme;
1521    cel.redraw();
1522  },
1523
1524  /**
1525   * Set the terminal window or tab title.
1526   *
1527   * This is an imperative side effect, not part of the render tree.
1528   * Control characters are stripped from the title before writing the
1529   * terminal sequence. Best effort only — some hosts may ignore it.
1530   */
1531  setTitle(title: string): void {
1532    if (!terminal) return;
1533    const sanitized = sanitizeTerminalTitle(title);
1534    if (sanitized === lastTerminalTitle) return;
1535    terminal.write(`\x1b]2;${sanitized}\x1b\\`);
1536    lastTerminalTitle = sanitized;
1537  },
1538
1539  /**
1540   * Stop the framework and restore terminal state.
1541   *
1542   * Pops the Kitty keyboard protocol mode, disables bracketed paste and mouse
1543   * tracking, and restores the terminal to its previous state.
1544   */
1545  stop(): void {
1546    terminal?.stop();
1547    terminal = null;
1548    renderFn = null;
1549    prevBuffer = null;
1550    currentBuffer = null;
1551    currentLayouts = [];
1552    renderScheduled = false;
1553    resolveRenderWaiters();
1554    fullRedrawScheduled = false;
1555    layerFocusStates.clear();
1556    stampedNode = null;
1557    uncontrolledScrollOffsets.clear();
1558    resetTextInputState();
1559    stampedScrollNodes = [];
1560    clearPendingEscapeTimer();
1561    pendingKeyData = "";
1562    inBracketedPaste = false;
1563    bracketedPasteData = "";
1564    bracketedPasteSuffix = "";
1565    lastTerminalCursor = { visible: false };
1566    lastTerminalTitle = null;
1567    activeTheme = defaultTheme;
1568  },
1569
1570  /** @internal */
1571  _getBuffer(): CellBuffer | null {
1572    return currentBuffer;
1573  },
1574
1575  /** Resolve after the currently scheduled render finishes. @internal */
1576  _flush(): Promise<void> {
1577    if (!renderScheduled) return Promise.resolve();
1578    return new Promise((resolve) => renderWaiters.push(resolve));
1579  },
1580} satisfies CelTestRuntime as Cel;