xonecas.io
70160
Ce

cel-tui / files

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

24.9 KB
1import type {
2  Color,
3  ScrollbarPartStyle,
4  StateKey,
5  StyleProps,
6  TextInputProps,
7} from "@cel-tui/types";
8import type { Cell, CellBuffer } from "./cell-buffer.js";
9import type { LayoutNode, Rect } from "./layout.js";
10import { getMaxScrollOffset } from "./scroll.js";
11import { clampCursorToGraphemeBoundary } from "./text-edit.js";
12import { layoutText } from "./text-layout.js";
13import { visibleWidth, visibleWidthFromColumn } from "./width.js";
14
15const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
16
17/** Empty inherited style — no values set. */
18const EMPTY_STYLE: StyleProps = {};
19
20/**
21 * Paint a laid-out tree into a cell buffer.
22 *
23 * Walks the {@link LayoutNode} tree and writes styled cells into the
24 * buffer within each node's computed rect. Content is clipped at
25 * rect boundaries. Container styles are inherited by descendants.
26 *
27 * @param root - The root of the laid-out tree (from {@link layout}).
28 * @param buf - Target cell buffer.
29 */
30export function paint(root: LayoutNode, buf: CellBuffer): void {
31  paintLayoutNode(root, buf, root.rect, EMPTY_STYLE, 0, 0);
32}
33
34/**
35 * Intersect two rectangles. Returns a rect with zero area if they don't overlap.
36 */
37function intersectRect(a: Rect, b: Rect): Rect {
38  const x = Math.max(a.x, b.x);
39  const y = Math.max(a.y, b.y);
40  const right = Math.min(a.x + a.width, b.x + b.width);
41  const bottom = Math.min(a.y + a.height, b.y + b.height);
42  return {
43    x,
44    y,
45    width: Math.max(0, right - x),
46    height: Math.max(0, bottom - y),
47  };
48}
49
50/**
51 * Resolve the effective style for a container, accounting for focusStyle.
52 * When the container is focused and has focusStyle, those values override
53 * the normal style props.
54 */
55function resolveContainerStyle(
56  props: { focused?: boolean; focusStyle?: StyleProps } & StyleProps,
57): StyleProps {
58  const isFocused = props.focused === true;
59  if (!isFocused || !props.focusStyle) {
60    return props;
61  }
62  return {
63    bold: props.focusStyle.bold ?? props.bold,
64    italic: props.focusStyle.italic ?? props.italic,
65    underline: props.focusStyle.underline ?? props.underline,
66    fgColor: props.focusStyle.fgColor ?? props.fgColor,
67    bgColor: props.focusStyle.bgColor ?? props.bgColor,
68  };
69}
70
71/**
72 * Merge a container's resolved style into the inherited style.
73 * Only values explicitly set on the container override inherited ones.
74 */
75function mergeInherited(
76  inherited: StyleProps,
77  resolved: StyleProps,
78): StyleProps {
79  return {
80    bold: resolved.bold ?? inherited.bold,
81    italic: resolved.italic ?? inherited.italic,
82    underline: resolved.underline ?? inherited.underline,
83    fgColor: resolved.fgColor ?? inherited.fgColor,
84    bgColor: resolved.bgColor ?? inherited.bgColor,
85  };
86}
87
88/**
89 * Fill a rectangle with opaque background cells, respecting the clip rect.
90 * Writes space characters with the given bgColor, making the container
91 * fully opaque. This ensures upper layers properly occlude lower layers.
92 */
93function fillBackground(
94  rect: Rect,
95  clipRect: Rect,
96  bgColor: Color,
97  buf: CellBuffer,
98): void {
99  const fill = intersectRect(rect, clipRect);
100  if (fill.width <= 0 || fill.height <= 0) return;
101  buf.fill(fill.x, fill.y, fill.width, fill.height, {
102    char: " ",
103    fgColor: null,
104    bgColor,
105    bold: false,
106    italic: false,
107    underline: false,
108  });
109}
110
111function paintLayoutNode(
112  ln: LayoutNode,
113  buf: CellBuffer,
114  clipRect: Rect,
115  inherited: StyleProps,
116  offsetX: number,
117  offsetY: number,
118): void {
119  const { node } = ln;
120  const rect =
121    offsetX === 0 && offsetY === 0
122      ? ln.rect
123      : {
124          x: ln.rect.x + offsetX,
125          y: ln.rect.y + offsetY,
126          width: ln.rect.width,
127          height: ln.rect.height,
128        };
129
130  // Clip this node's rect against the parent clip rect
131  const clipped = intersectRect(rect, clipRect);
132  if (clipped.width <= 0 || clipped.height <= 0) return;
133
134  // Compute inherited style for this subtree
135  let childInherited = inherited;
136
137  switch (node.type) {
138    case "text": {
139      // Resolve text styles: own props override inherited
140      const effective = {
141        fgColor: node.props.fgColor ?? inherited.fgColor,
142        bgColor: node.props.bgColor ?? inherited.bgColor,
143        bold: node.props.bold ?? inherited.bold,
144        italic: node.props.italic ?? inherited.italic,
145        underline: node.props.underline ?? inherited.underline,
146      };
147      paintText(
148        node.content,
149        { ...node.props, ...effective },
150        rect,
151        clipped,
152        buf,
153      );
154      break;
155    }
156    case "textinput": {
157      // TextInput: resolve own styles with inheritance
158      const tiResolved = resolveContainerStyle(node.props);
159      const tiEffective = mergeInherited(inherited, tiResolved);
160      const tiProps = {
161        ...node.props,
162        ...tiEffective,
163      };
164      paintTextInput(tiProps, rect, clipped, buf, tiEffective);
165      break;
166    }
167    case "vstack":
168    case "hstack": {
169      // Resolve container style (applies focusStyle if focused)
170      const resolved = resolveContainerStyle(node.props);
171      childInherited = mergeInherited(inherited, resolved);
172
173      // Fill container background
174      const effectiveBg = childInherited.bgColor;
175      if (effectiveBg) {
176        fillBackground(rect, clipped, effectiveBg, buf);
177      }
178      break;
179    }
180  }
181
182  // Determine scroll offset for scrollable containers
183  const isContainer = node.type === "vstack" || node.type === "hstack";
184  const containerProps = isContainer ? node.props : null;
185  const isScrollable = containerProps?.overflow === "scroll";
186  const isVertical = node.type === "vstack";
187  let scrollOffset = 0;
188  if (isScrollable) {
189    const raw = containerProps.scrollOffset ?? 0;
190    // Clamp to valid range so apps can pass large values to mean "scroll to end"
191    const maxOffset = getMaxScrollOffset(ln);
192    scrollOffset = Math.max(0, Math.min(raw, maxOffset));
193  }
194
195  // Recurse into children, using this node's clipped rect as the clip for children
196  for (const child of ln.children) {
197    const childOffsetX =
198      offsetX + (isScrollable && !isVertical ? -scrollOffset : 0);
199    const childOffsetY =
200      offsetY + (isScrollable && isVertical ? -scrollOffset : 0);
201    paintLayoutNode(
202      child,
203      buf,
204      clipped,
205      childInherited,
206      childOffsetX,
207      childOffsetY,
208    );
209  }
210
211  // Paint scrollbar if enabled
212  if (isScrollable && containerProps.scrollbar) {
213    paintScrollbar(ln, rect, scrollOffset, buf, clipped);
214  }
215}
216
217/**
218 * Paint a scrollbar indicator for a scrollable container.
219 */
220function paintScrollbar(
221  ln: LayoutNode,
222  rect: Rect,
223  scrollOffset: number,
224  buf: CellBuffer,
225  clipRect: Rect,
226): void {
227  const { children } = ln;
228  const layoutRect = ln.rect;
229  const isVertical = ln.node.type === "vstack";
230  const props =
231    ln.node.type === "vstack" || ln.node.type === "hstack"
232      ? ln.node.props
233      : null;
234  if (!props) return;
235  const thumbStyle = props.scrollbarStyle?.thumb;
236  const trackStyle = props.scrollbarStyle?.track;
237
238  if (isVertical) {
239    // Compute total scrollable height from children plus bottom padding.
240    // Child positions already include top padding, so add only the trailing pad.
241    let contentHeight = 0;
242    for (const child of children) {
243      const childBottom = child.rect.y + child.rect.height - layoutRect.y;
244      if (childBottom > contentHeight) contentHeight = childBottom;
245    }
246    const scrollHeight = contentHeight + (props.padding?.y ?? 0);
247    const viewportH = rect.height;
248    if (scrollHeight <= viewportH) return; // no scrollbar needed
249
250    // Thumb size and position
251    const thumbSize = Math.max(
252      1,
253      Math.round((viewportH / scrollHeight) * viewportH),
254    );
255    const maxOffset = scrollHeight - viewportH;
256    const thumbPos =
257      maxOffset > 0
258        ? Math.round((scrollOffset / maxOffset) * (viewportH - thumbSize))
259        : 0;
260
261    const barX = rect.x + rect.width - 1;
262    for (let row = 0; row < viewportH; row++) {
263      const absY = rect.y + row;
264      if (absY < clipRect.y || absY >= clipRect.y + clipRect.height) continue;
265      if (barX < clipRect.x || barX >= clipRect.x + clipRect.width) continue;
266      const isThumb = row >= thumbPos && row < thumbPos + thumbSize;
267      buf.set(
268        barX,
269        absY,
270        scrollbarCell(
271          isThumb ? thumbStyle : trackStyle,
272          isThumb ? "┃" : "│",
273          isThumb ? null : "color08",
274        ),
275      );
276    }
277  } else {
278    // Horizontal scrollbar
279    let contentWidth = 0;
280    for (const child of children) {
281      const childRight = child.rect.x + child.rect.width - layoutRect.x;
282      if (childRight > contentWidth) contentWidth = childRight;
283    }
284    const scrollWidth = contentWidth + (props.padding?.x ?? 0);
285    const viewportW = rect.width;
286    if (scrollWidth <= viewportW) return;
287
288    const thumbSize = Math.max(
289      1,
290      Math.round((viewportW / scrollWidth) * viewportW),
291    );
292    const maxOffset = scrollWidth - viewportW;
293    const thumbPos =
294      maxOffset > 0
295        ? Math.round((scrollOffset / maxOffset) * (viewportW - thumbSize))
296        : 0;
297
298    const barY = rect.y + rect.height - 1;
299    for (let col = 0; col < viewportW; col++) {
300      const absX = rect.x + col;
301      if (absX < clipRect.x || absX >= clipRect.x + clipRect.width) continue;
302      if (barY < clipRect.y || barY >= clipRect.y + clipRect.height) continue;
303      const isThumb = col >= thumbPos && col < thumbPos + thumbSize;
304      buf.set(
305        absX,
306        barY,
307        scrollbarCell(
308          isThumb ? thumbStyle : trackStyle,
309          isThumb ? "━" : "─",
310          isThumb ? null : "color08",
311        ),
312      );
313    }
314  }
315}
316
317function scrollbarCell(
318  style: ScrollbarPartStyle | undefined,
319  defaultChar: string,
320  defaultFgColor: Color | null,
321): Cell {
322  const char = style?.char ?? defaultChar;
323  if (visibleWidth(char) !== 1) {
324    throw new Error(
325      "Scrollbar characters must occupy exactly one terminal column",
326    );
327  }
328  return {
329    char,
330    fgColor: style?.fgColor ?? defaultFgColor,
331    bgColor: style?.bgColor ?? null,
332    bold: style?.bold ?? false,
333    italic: style?.italic ?? false,
334    underline: style?.underline ?? false,
335  };
336}
337
338function makeCell(
339  char: string,
340  props: {
341    fgColor?: Color;
342    bgColor?: Color;
343    bold?: boolean;
344    italic?: boolean;
345    underline?: boolean;
346  },
347): Cell {
348  return {
349    char,
350    fgColor: props.fgColor ?? null,
351    bgColor: props.bgColor ?? null,
352    bold: props.bold ?? false,
353    italic: props.italic ?? false,
354    underline: props.underline ?? false,
355  };
356}
357
358/**
359 * Paint a single line of text into the buffer using grapheme segmentation.
360 * Correctly handles wide characters (CJK, emoji) and tab expansion by
361 * advancing the column by each segment's visible width. Respects the clip rect.
362 */
363function paintLineGraphemes(
364  line: string,
365  x: number,
366  y: number,
367  maxWidth: number,
368  clipRect: Rect,
369  props: {
370    fgColor?: Color;
371    bgColor?: Color;
372    bold?: boolean;
373    italic?: boolean;
374    underline?: boolean;
375  },
376  buf: CellBuffer,
377): void {
378  if (y < clipRect.y || y >= clipRect.y + clipRect.height) return;
379  const clipLeft = clipRect.x;
380  const clipRight = clipRect.x + clipRect.width;
381
382  // Printable ASCII is overwhelmingly the common terminal path. It maps
383  // one-to-one to cells, so avoid Intl.Segmenter and width lookups entirely.
384  let isPrintableAscii = true;
385  for (let i = 0; i < line.length; i++) {
386    const code = line.charCodeAt(i);
387    if (code < 0x20 || code > 0x7e) {
388      isPrintableAscii = false;
389      break;
390    }
391  }
392  if (isPrintableAscii) {
393    const start = Math.max(0, clipLeft - x);
394    const end = Math.min(line.length, maxWidth, clipRight - x);
395    for (let col = start; col < end; col++) {
396      const char = line[col];
397      if (char !== undefined) buf.set(x + col, y, makeCell(char, props));
398    }
399    return;
400  }
401
402  let col = 0;
403  for (const { segment } of segmenter.segment(line)) {
404    const gw = visibleWidthFromColumn(segment, col);
405    if (gw === 0) continue;
406
407    const absX = x + col;
408    if (absX >= clipRight) break;
409
410    if (segment === "\t") {
411      const visibleColumns = Math.min(gw, Math.max(0, maxWidth - col));
412      for (let w = 0; w < visibleColumns; w++) {
413        const cx = absX + w;
414        if (cx >= clipLeft && cx < clipRight) {
415          buf.set(cx, y, makeCell(" ", props));
416        }
417      }
418      col += gw;
419      if (col >= maxWidth) break;
420      continue;
421    }
422
423    if (col + gw > maxWidth) break;
424    // Wide graphemes are atomic. If either their lead or a continuation would
425    // fall outside the active clip, omit the whole glyph rather than creating
426    // an orphaned half that shifts subsequent terminal output.
427    if (absX < clipLeft) {
428      col += gw;
429      continue;
430    }
431    if (absX + gw > clipRight) break;
432
433    buf.set(absX, y, makeCell(segment, props));
434    for (let w = 1; w < gw; w++) {
435      buf.set(absX + w, y, makeCell("", props));
436    }
437    col += gw;
438  }
439}
440
441function paintText(
442  content: string,
443  props: {
444    repeat?: number | "fill";
445    wrap?: "none" | "word";
446    fgColor?: Color;
447    bgColor?: Color;
448    bold?: boolean;
449    italic?: boolean;
450    underline?: boolean;
451  },
452  rect: Rect,
453  clipRect: Rect,
454  buf: CellBuffer,
455): void {
456  const { x, y, width: w, height: h } = rect;
457  if (w <= 0 || h <= 0) return;
458
459  // Resolve repeat
460  let text = content;
461  if (props.repeat === "fill" && content.length > 0) {
462    const contentW = visibleWidth(content);
463    if (contentW > 0) {
464      if (content.includes("\t")) {
465        text = "";
466        while (visibleWidth(text) < w) {
467          text += content;
468        }
469      } else {
470        text = content.repeat(Math.ceil(w / contentW));
471      }
472    }
473  } else if (typeof props.repeat === "number" && props.repeat > 0) {
474    text = content.repeat(props.repeat);
475  }
476
477  // No-wrap text without ANSI only needs hard-line splitting. The full text
478  // layout is reserved for wrapping and ANSI stripping.
479  if ((props.wrap ?? "none") === "none" && !text.includes("\x1b")) {
480    const lines = text.split("\n");
481    for (let row = 0; row < lines.length && row < h; row++) {
482      const line = lines[row];
483      if (line === undefined) break;
484      paintLineGraphemes(line, x, y + row, w, clipRect, props, buf);
485    }
486    return;
487  }
488
489  const textLayout = layoutText(text, w, props.wrap ?? "none");
490
491  // Paint lines, clipped to rect (grapheme-aware)
492  for (let row = 0; row < textLayout.lineCount && row < h; row++) {
493    const line = textLayout.lines[row];
494    if (!line) {
495      break;
496    }
497    paintLineGraphemes(line.text, x, y + row, w, clipRect, props, buf);
498  }
499}
500
501function resolveTextInputScrollOffset(
502  props: TextInputProps,
503  lineCount: number,
504  viewportHeight: number,
505  cursorLine: number,
506): number {
507  const maxOffset = Math.max(0, lineCount - viewportHeight);
508  let scrollOffset = Math.max(
509    0,
510    Math.min(getTextInputScroll(props), maxOffset),
511  );
512
513  if (props.focused) {
514    if (cursorLine >= scrollOffset + viewportHeight) {
515      scrollOffset = cursorLine - viewportHeight + 1;
516    }
517    if (cursorLine < scrollOffset) {
518      scrollOffset = cursorLine;
519    }
520  }
521
522  setTextInputScroll(props, scrollOffset);
523  return scrollOffset;
524}
525
526function paintTextInput(
527  props: TextInputProps,
528  rect: Rect,
529  clipRect: Rect,
530  buf: CellBuffer,
531  inherited: StyleProps = EMPTY_STYLE,
532): void {
533  const { x, y, width: w, height: h } = rect;
534  if (w <= 0 || h <= 0) return;
535
536  // Apply padding — content is inset from the rect edges
537  const padX = props.padding?.x ?? 0;
538  const padY = props.padding?.y ?? 0;
539  const cx = x + padX;
540  const cy = y + padY;
541  const cw = Math.max(0, w - padX * 2);
542  const ch = Math.max(0, h - padY * 2);
543  if (cw <= 0 || ch <= 0) return;
544
545  // Fill the TextInput rect with background color (like containers do)
546  // so that cursor inversion and empty cells have correct colors.
547  const effectiveBg = props.bgColor ?? inherited.bgColor;
548  if (effectiveBg) {
549    fillBackground(rect, clipRect, effectiveBg, buf);
550  }
551
552  const value = props.value;
553  const showPlaceholder = value.length === 0 && props.placeholder;
554
555  if (showPlaceholder && props.placeholder) {
556    // Paint placeholder text in padded content area, inheriting
557    // styles from the TextInput's resolved style chain
558    const contentRect: Rect = { x: cx, y: cy, width: cw, height: ch };
559    const phProps = props.placeholder.props;
560    const effectivePh = {
561      ...phProps,
562      fgColor: phProps.fgColor ?? inherited.fgColor,
563      bgColor: phProps.bgColor ?? inherited.bgColor,
564      bold: phProps.bold ?? inherited.bold,
565      italic: phProps.italic ?? inherited.italic,
566      underline: phProps.underline ?? inherited.underline,
567    };
568    paintText(
569      props.placeholder.content,
570      effectivePh,
571      contentRect,
572      clipRect,
573      buf,
574    );
575    return;
576  }
577
578  const textLayout = layoutText(value, cw, "word");
579  const cursorOffset = getTextInputCursor(props);
580  const cursorPos = textLayout.offsetToPosition(cursorOffset);
581  const scrollOffset = resolveTextInputScrollOffset(
582    props,
583    textLayout.lineCount,
584    ch,
585    cursorPos.line,
586  );
587
588  // Paint visible lines (grapheme-aware) in content area
589  for (let row = 0; row < ch; row++) {
590    const lineIdx = scrollOffset + row;
591    if (lineIdx >= textLayout.lineCount) break;
592    const line = textLayout.lines[lineIdx];
593    if (!line) {
594      break;
595    }
596    paintLineGraphemes(line.text, cx, cy + row, cw, clipRect, props, buf);
597  }
598
599  // Paint cursor if focused — invert colors at cursor position so it's
600  // always visible regardless of terminal cursor configuration. The
601  // framework also positions the native terminal cursor here (in cel.ts)
602  // for blinking.
603  if (props.focused) {
604    const screenRow = cursorPos.line - scrollOffset;
605    if (screenRow >= 0 && screenRow < ch && cursorPos.col < cw) {
606      const absX = cx + cursorPos.col;
607      const absY = cy + screenRow;
608      if (
609        absX >= clipRect.x &&
610        absX < clipRect.x + clipRect.width &&
611        absY >= clipRect.y &&
612        absY < clipRect.y + clipRect.height
613      ) {
614        const existing = buf.get(absX, absY);
615        // Resolve null colors against inherited style so the inversion
616        // always produces visible contrast (e.g. on bg-filled empty cells
617        // where fgColor is null).
618        const resolvedFg = existing.fgColor ?? inherited.fgColor ?? "color07";
619        const resolvedBg = existing.bgColor ?? inherited.bgColor ?? "color00";
620        switch (props.cursorStyle ?? "block") {
621          case "block":
622            buf.set(absX, absY, {
623              char: existing.char,
624              fgColor: resolvedBg,
625              bgColor: resolvedFg,
626              bold: existing.bold,
627              italic: existing.italic,
628              underline: existing.underline,
629            });
630            break;
631          case "bar":
632            buf.set(absX, absY, {
633              char: "│",
634              fgColor: resolvedFg,
635              bgColor: existing.bgColor,
636              bold: existing.bold,
637              italic: existing.italic,
638              underline: existing.underline,
639            });
640            break;
641          case "underline":
642            buf.set(absX, absY, {
643              ...existing,
644              underline: true,
645            });
646            break;
647        }
648      }
649    }
650  }
651}
652
653// --- Framework-managed state ---
654
655/** Explicit stateKey storage plus the legacy onChange-reference fallback. */
656type OnChangeFn = (value: string) => void;
657type TextInputState = { value: string; cursor: number };
658let textInputStates = new WeakMap<OnChangeFn, TextInputState>();
659let textInputScrolls = new WeakMap<OnChangeFn, number>();
660const keyedTextInputStates = new Map<StateKey, TextInputState>();
661const keyedTextInputScrolls = new Map<StateKey, number>();
662
663function getStoredTextInputState(
664  props: TextInputProps,
665): TextInputState | undefined {
666  return props.stateKey === undefined
667    ? textInputStates.get(props.onChange)
668    : keyedTextInputStates.get(props.stateKey);
669}
670
671function storeTextInputState(
672  props: TextInputProps,
673  state: TextInputState,
674): void {
675  if (props.stateKey === undefined) {
676    textInputStates.set(props.onChange, state);
677  } else {
678    keyedTextInputStates.set(props.stateKey, state);
679  }
680}
681
682/** Retain keyed TextInput state only for keys mounted in the current frame. */
683export function retainTextInputStateKeys(keys: ReadonlySet<StateKey>): void {
684  for (const key of keyedTextInputStates.keys()) {
685    if (!keys.has(key)) keyedTextInputStates.delete(key);
686  }
687  for (const key of keyedTextInputScrolls.keys()) {
688    if (!keys.has(key)) keyedTextInputScrolls.delete(key);
689  }
690}
691
692/** Clear framework-managed TextInput state between runtime lifecycles. */
693export function resetTextInputState(): void {
694  textInputStates = new WeakMap();
695  textInputScrolls = new WeakMap();
696  keyedTextInputStates.clear();
697  keyedTextInputScrolls.clear();
698}
699
700function clampCursor(cursor: number, value: string): number {
701  return clampCursorToGraphemeBoundary(value, cursor);
702}
703
704/**
705 * Remap a stored cursor through an external value change by anchoring it to the
706 * unchanged prefix/suffix around the edit. Insertions at the cursor land after
707 * the inserted text; edits strictly after the cursor leave it untouched.
708 */
709function remapCursorOffset(
710  previousValue: string,
711  previousCursor: number,
712  nextValue: string,
713): number {
714  const cursor = clampCursor(previousCursor, previousValue);
715  if (previousValue === nextValue) return clampCursor(cursor, nextValue);
716
717  let prefix = 0;
718  const maxPrefix = Math.min(previousValue.length, nextValue.length);
719  while (
720    prefix < maxPrefix &&
721    previousValue.charCodeAt(prefix) === nextValue.charCodeAt(prefix)
722  ) {
723    prefix++;
724  }
725
726  let previousEnd = previousValue.length;
727  let nextEnd = nextValue.length;
728  while (
729    previousEnd > prefix &&
730    nextEnd > prefix &&
731    previousValue.charCodeAt(previousEnd - 1) ===
732      nextValue.charCodeAt(nextEnd - 1)
733  ) {
734    previousEnd--;
735    nextEnd--;
736  }
737
738  if (cursor < prefix) return cursor;
739  if (cursor > previousEnd) {
740    return clampCursor(cursor + (nextEnd - previousEnd), nextValue);
741  }
742  return nextEnd;
743}
744
745function getTextInputState(props: TextInputProps): TextInputState {
746  const stored = getStoredTextInputState(props);
747  if (stored === undefined) {
748    const initial = { value: props.value, cursor: props.value.length };
749    storeTextInputState(props, initial);
750    return initial;
751  }
752
753  if (stored.value === props.value) {
754    const clampedCursor = clampCursor(stored.cursor, props.value);
755    if (clampedCursor === stored.cursor) return stored;
756
757    const clampedState = { value: props.value, cursor: clampedCursor };
758    storeTextInputState(props, clampedState);
759    return clampedState;
760  }
761
762  const syncedState = {
763    value: props.value,
764    cursor: clampCursor(
765      remapCursorOffset(stored.value, stored.cursor, props.value),
766      props.value,
767    ),
768  };
769  storeTextInputState(props, syncedState);
770  return syncedState;
771}
772
773/**
774 * Compute the screen position of the cursor for a focused TextInput.
775 * Returns `{ x, y }` in 0-indexed screen coordinates, or `null` if
776 * the cursor is not visible (clipped or not focused).
777 */
778export function getTextInputCursorScreenPos(
779  props: TextInputProps,
780  rect: Rect,
781): { x: number; y: number } | null {
782  if (!props.focused) return null;
783
784  const { x, y, width: w, height: h } = rect;
785  if (w <= 0 || h <= 0) return null;
786
787  const padX = props.padding?.x ?? 0;
788  const padY = props.padding?.y ?? 0;
789  const cx = x + padX;
790  const cy = y + padY;
791  const cw = Math.max(0, w - padX * 2);
792  const ch = Math.max(0, h - padY * 2);
793  if (cw <= 0 || ch <= 0) return null;
794
795  const cursorOffset = getTextInputCursor(props);
796  const textLayout = layoutText(props.value, cw, "word");
797  const pos = textLayout.offsetToPosition(cursorOffset);
798  const scrollOffset = resolveTextInputScrollOffset(
799    props,
800    textLayout.lineCount,
801    ch,
802    pos.line,
803  );
804  const screenRow = pos.line - scrollOffset;
805
806  if (screenRow >= 0 && screenRow < ch && pos.col < cw) {
807    return { x: cx + pos.col, y: cy + screenRow };
808  }
809  return null;
810}
811
812/** Get the cursor offset for a TextInput (framework-managed). */
813export function getTextInputCursor(props: TextInputProps): number {
814  if (props.cursor !== undefined) {
815    const controlled = clampCursor(props.cursor, props.value);
816    storeTextInputState(props, { value: props.value, cursor: controlled });
817    return controlled;
818  }
819  return getTextInputState(props).cursor;
820}
821
822/** Set the cursor offset for a TextInput. */
823export function setTextInputCursor(
824  props: TextInputProps,
825  cursor: number,
826  value = props.value,
827): void {
828  storeTextInputState(props, {
829    value,
830    cursor: clampCursor(cursor, value),
831  });
832}
833
834/** Get the scroll offset for a TextInput (framework-managed). */
835export function getTextInputScroll(props: TextInputProps): number {
836  return props.stateKey === undefined
837    ? (textInputScrolls.get(props.onChange) ?? 0)
838    : (keyedTextInputScrolls.get(props.stateKey) ?? 0);
839}
840
841/** Set the scroll offset for a TextInput. */
842export function setTextInputScroll(
843  props: TextInputProps,
844  scroll: number,
845): void {
846  if (props.stateKey === undefined) {
847    textInputScrolls.set(props.onChange, scroll);
848  } else {
849    keyedTextInputScrolls.set(props.stateKey, scroll);
850  }
851}