xonecas.io
70160
Ce

cel-tui / files

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

11.4 KB
1import { extractAnsiCode, visibleWidthFromColumn } from "./width.js";
2
3const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
4const whitespaceRegex = /^\s+$/u;
5const TEXT_LINE_COUNT_CACHE_SIZE = 2048;
6
7type WrapMode = "none" | "word";
8
9export interface VisualLine {
10  text: string;
11  startOffset: number;
12  endOffset: number;
13  width: number;
14}
15
16export interface VisualPosition {
17  line: number;
18  col: number;
19}
20
21export interface TextLayoutResult {
22  lines: VisualLine[];
23  lineCount: number;
24  offsetToPosition(offset: number): VisualPosition;
25  positionToOffset(line: number, col: number): number;
26}
27
28interface GraphemeInfo {
29  text: string;
30  startOffset: number;
31  endOffset: number;
32  width: number;
33  isWhitespace: boolean;
34}
35
36interface VisualLineData {
37  line: VisualLine;
38  graphemes: GraphemeInfo[];
39}
40
41interface Range {
42  start: number;
43  end: number;
44}
45
46interface LineCountCacheEntry {
47  none?: number;
48  wordByWidth?: Map<number, number>;
49}
50
51const lineCountCache = new Map<string, LineCountCacheEntry>();
52
53/** Clear text measurement caches. Useful for cold-cache benchmarks. */
54export function clearTextMeasurementCaches(): void {
55  lineCountCache.clear();
56}
57
58function requiredAt<T>(
59  items: readonly T[],
60  index: number,
61  description: string,
62): T {
63  const item = items[index];
64  if (item === undefined) {
65    throw new Error(`Missing ${description} at index ${index}`);
66  }
67  return item;
68}
69
70/**
71 * Measure the number of visual lines a string occupies for the given width and
72 * wrap mode. This avoids constructing the full `TextLayoutResult` when callers
73 * only need line count.
74 */
75export function measureTextLineCount(
76  value: string,
77  width: number,
78  wrap: WrapMode,
79): number {
80  const normalizedWidth = Math.max(1, width);
81  const cached = getCachedLineCount(value, normalizedWidth, wrap);
82  if (cached !== undefined) return cached;
83
84  const lineCount =
85    wrap === "word"
86      ? measureWrappedLineCount(value, normalizedWidth)
87      : countHardLines(value);
88
89  cacheLineCount(value, normalizedWidth, wrap, lineCount);
90  return lineCount;
91}
92
93export function layoutText(
94  value: string,
95  width: number,
96  wrap: WrapMode,
97): TextLayoutResult {
98  const hardLines = splitHardLines(value);
99  const lines: VisualLineData[] = [];
100
101  for (const hardLine of hardLines) {
102    const graphemes = segmentLine(value, hardLine.start, hardLine.end);
103    if (wrap === "word") {
104      lines.push(...wrapGraphemes(graphemes, Math.max(1, width), hardLine));
105    } else {
106      lines.push(
107        ...buildVisualLines(graphemes, [[0, graphemes.length]], hardLine),
108      );
109    }
110  }
111
112  if (lines.length === 0) {
113    const empty: VisualLineData = {
114      line: { text: "", startOffset: 0, endOffset: 0, width: 0 },
115      graphemes: [],
116    };
117    lines.push(empty);
118  }
119
120  return {
121    lines: lines.map((entry) => entry.line),
122    lineCount: lines.length,
123    offsetToPosition(offset: number): VisualPosition {
124      return offsetToPosition(lines, clamp(offset, 0, value.length));
125    },
126    positionToOffset(line: number, col: number): number {
127      return positionToOffset(lines, line, col);
128    },
129  };
130}
131
132function countHardLines(value: string): number {
133  let lineCount = 1;
134  for (let i = 0; i < value.length; i++) {
135    if (value[i] === "\n") {
136      lineCount++;
137    }
138  }
139  return lineCount;
140}
141
142function getCachedLineCount(
143  value: string,
144  width: number,
145  wrap: WrapMode,
146): number | undefined {
147  const entry = lineCountCache.get(value);
148  if (entry === undefined) return undefined;
149  if (wrap === "none") return entry.none;
150  return entry.wordByWidth?.get(width);
151}
152
153function cacheLineCount(
154  value: string,
155  width: number,
156  wrap: WrapMode,
157  lineCount: number,
158): void {
159  let entry = lineCountCache.get(value);
160  if (entry === undefined) {
161    if (lineCountCache.size >= TEXT_LINE_COUNT_CACHE_SIZE) {
162      const firstKey = lineCountCache.keys().next().value;
163      if (firstKey !== undefined) {
164        lineCountCache.delete(firstKey);
165      }
166    }
167    entry = {};
168    lineCountCache.set(value, entry);
169  }
170
171  if (wrap === "none") {
172    entry.none = lineCount;
173    return;
174  }
175
176  if (entry.wordByWidth === undefined) {
177    entry.wordByWidth = new Map();
178  }
179  entry.wordByWidth.set(width, lineCount);
180}
181
182function measureWrappedLineCount(value: string, width: number): number {
183  let lineCount = 0;
184  for (const hardLine of splitHardLines(value)) {
185    lineCount += measureWrappedHardLine(
186      value,
187      hardLine.start,
188      hardLine.end,
189      width,
190    );
191  }
192  return lineCount;
193}
194
195function measureWrappedHardLine(
196  value: string,
197  start: number,
198  end: number,
199  width: number,
200): number {
201  if (start === end) {
202    return 1;
203  }
204  const graphemes = segmentLine(value, start, end);
205  return Math.max(1, getWrappedRanges(graphemes, width).length);
206}
207
208function splitHardLines(value: string): Range[] {
209  const lines: Range[] = [];
210  let start = 0;
211  for (let i = 0; i < value.length; i++) {
212    if (value[i] === "\n") {
213      lines.push({ start, end: i });
214      start = i + 1;
215    }
216  }
217  lines.push({ start, end: value.length });
218  return lines;
219}
220
221function segmentLine(
222  value: string,
223  start: number,
224  end: number,
225): GraphemeInfo[] {
226  const graphemes: GraphemeInfo[] = [];
227  const text = value.slice(start, end);
228  let col = 0;
229  let ansiEnd = -1;
230
231  for (const { segment, index } of segmenter.segment(text)) {
232    const offset = start + index;
233    if (offset < ansiEnd) continue;
234
235    const ansi = extractAnsiCode(value, offset);
236    if (ansi !== null && offset + ansi.length <= end) {
237      ansiEnd = offset + ansi.length;
238      graphemes.push({
239        text: "",
240        startOffset: offset,
241        endOffset: ansiEnd,
242        width: 0,
243        isWhitespace: false,
244      });
245      continue;
246    }
247
248    const width = visibleWidthFromColumn(segment, col);
249    graphemes.push({
250      text: segment,
251      startOffset: offset,
252      endOffset: offset + segment.length,
253      width,
254      isWhitespace: whitespaceRegex.test(segment),
255    });
256    col += width;
257  }
258
259  return graphemes;
260}
261
262function wrapGraphemes(
263  graphemes: GraphemeInfo[],
264  width: number,
265  hardLine: Range,
266): VisualLineData[] {
267  if (graphemes.length === 0) {
268    return [makeVisualLine(graphemes, 0, 0, hardLine.start)];
269  }
270
271  return buildVisualLines(
272    graphemes,
273    getWrappedRanges(graphemes, width),
274    hardLine,
275  );
276}
277
278function getWrappedRanges(
279  graphemes: GraphemeInfo[],
280  width: number,
281): Array<[number, number]> {
282  const ranges: Array<[number, number]> = [];
283  let lineStart = 0;
284
285  while (lineStart < graphemes.length) {
286    let lineEnd = lineStart;
287    let lineWidth = 0;
288    let lastBreak = -1;
289
290    while (lineEnd < graphemes.length) {
291      const grapheme = requiredAt(graphemes, lineEnd, "grapheme");
292      const graphemeWidth = contextualGraphemeWidth(grapheme, lineWidth);
293      const nextWidth = lineWidth + graphemeWidth;
294      if (nextWidth > width) break;
295      lineWidth = nextWidth;
296      lineEnd++;
297      if (grapheme.isWhitespace) {
298        lastBreak = lineEnd;
299      }
300    }
301
302    if (lineEnd >= graphemes.length) {
303      if (lineWidth === 0 && ranges.length > 0) {
304        // Trailing control spans belong to the preceding visible line; they
305        // must not manufacture a blank line of their own.
306        const previous = requiredAt(ranges, ranges.length - 1, "wrap range");
307        previous[1] = graphemes.length;
308      } else {
309        ranges.push([lineStart, graphemes.length]);
310      }
311      break;
312    }
313
314    if (lineWidth === 0) {
315      // Zero-width control spans (for example a leading ANSI sequence) must
316      // travel with the first visible grapheme. Otherwise a wide grapheme
317      // that exceeds the viewport can strand those spans on a phantom blank
318      // visual line.
319      const forcedEnd = Math.min(graphemes.length, lineEnd + 1);
320      ranges.push([lineStart, forcedEnd]);
321      lineStart = forcedEnd;
322      continue;
323    }
324
325    if (lastBreak > lineStart) {
326      ranges.push([lineStart, lastBreak]);
327      lineStart = lastBreak;
328      continue;
329    }
330
331    ranges.push([lineStart, lineEnd]);
332    lineStart = lineEnd;
333  }
334
335  return ranges;
336}
337
338function buildVisualLines(
339  graphemes: GraphemeInfo[],
340  ranges: Array<[number, number]>,
341  hardLine: Range,
342): VisualLineData[] {
343  return ranges.map(([startIndex, endIndex]) =>
344    makeVisualLine(graphemes, startIndex, endIndex, hardLine.start),
345  );
346}
347
348function makeVisualLine(
349  graphemes: GraphemeInfo[],
350  startIndex: number,
351  endIndex: number,
352  hardLineStart: number,
353): VisualLineData {
354  if (startIndex === endIndex) {
355    return {
356      line: {
357        text: "",
358        startOffset: hardLineStart,
359        endOffset: hardLineStart,
360        width: 0,
361      },
362      graphemes: [],
363    };
364  }
365
366  let width = 0;
367  const lineGraphemes = graphemes
368    .slice(startIndex, endIndex)
369    .map((grapheme) => {
370      const contextualWidth = contextualGraphemeWidth(grapheme, width);
371      width += contextualWidth;
372      return contextualWidth === grapheme.width
373        ? grapheme
374        : { ...grapheme, width: contextualWidth };
375    });
376  const startOffset = requiredAt(lineGraphemes, 0, "line grapheme").startOffset;
377  const endOffset = requiredAt(
378    lineGraphemes,
379    lineGraphemes.length - 1,
380    "line grapheme",
381  ).endOffset;
382
383  return {
384    line: {
385      text: lineGraphemes.map((grapheme) => grapheme.text).join(""),
386      startOffset,
387      endOffset,
388      width,
389    },
390    graphemes: lineGraphemes,
391  };
392}
393
394function contextualGraphemeWidth(
395  grapheme: GraphemeInfo,
396  column: number,
397): number {
398  // Tabs advance to the next tab stop and therefore need their width
399  // recomputed after a soft wrap. All other graphemes have a stable width;
400  // re-segmenting each one here makes ordinary ASCII wrapping much slower.
401  return grapheme.text === "\t"
402    ? visibleWidthFromColumn(grapheme.text, column)
403    : grapheme.width;
404}
405
406function offsetToPosition(
407  lines: VisualLineData[],
408  offset: number,
409): VisualPosition {
410  for (let i = 1; i < lines.length; i++) {
411    if (offset === requiredAt(lines, i, "visual line").line.startOffset) {
412      return { line: i, col: 0 };
413    }
414  }
415
416  for (let i = 0; i < lines.length; i++) {
417    const entry = requiredAt(lines, i, "visual line");
418    const { line, graphemes } = entry;
419    if (offset < line.startOffset || offset > line.endOffset) continue;
420
421    let col = 0;
422    for (const grapheme of graphemes) {
423      if (offset <= grapheme.startOffset) break;
424      if (offset < grapheme.endOffset) break;
425      col += grapheme.width;
426    }
427    return { line: i, col };
428  }
429
430  const last = requiredAt(lines, lines.length - 1, "visual line");
431  return { line: lines.length - 1, col: last.line.width };
432}
433
434function positionToOffset(
435  lines: VisualLineData[],
436  line: number,
437  col: number,
438): number {
439  const lineIndex = clamp(line, 0, lines.length - 1);
440  const entry = requiredAt(lines, lineIndex, "visual line");
441  const targetCol = Math.max(0, col);
442
443  if (targetCol === 0 || entry.graphemes.length === 0) {
444    return entry.line.startOffset;
445  }
446  if (targetCol >= entry.line.width) {
447    return entry.line.endOffset;
448  }
449
450  let currentCol = 0;
451  for (const grapheme of entry.graphemes) {
452    const nextCol = currentCol + grapheme.width;
453    if (targetCol < nextCol) {
454      return targetCol - currentCol < nextCol - targetCol
455        ? grapheme.startOffset
456        : grapheme.endOffset;
457    }
458    if (targetCol === nextCol) {
459      return grapheme.endOffset;
460    }
461    currentCol = nextCol;
462  }
463
464  return entry.line.endOffset;
465}
466
467function clamp(value: number, min: number, max: number): number {
468  return Math.max(min, Math.min(max, value));
469}