File size: 26,183 Bytes
064bfd6 46f810c 064bfd6 46f810c 064bfd6 46f810c 064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 | import {
type AnsiCode,
type StyledChar,
styledCharsFromTokens,
tokenize,
} from '@alcalzone/ansi-tokenize'
import { logForDebugging } from '../utils/debug.js'
import { getGraphemeSegmenter } from '../utils/intl.js'
import sliceAnsi from '../utils/sliceAnsi.js'
import { reorderBidi } from './bidi.js'
import { type Rectangle, unionRect } from './layout/geometry.js'
import {
blitRegion,
CellWidth,
extractHyperlinkFromStyles,
filterOutHyperlinkStyles,
markNoSelectRegion,
OSC8_PREFIX,
resetScreen,
type Screen,
type StylePool,
setCellAt,
shiftRows,
} from './screen.js'
import { stringWidth } from './stringWidth.js'
import { widestLine } from './widest-line.js'
/**
* A grapheme cluster with precomputed terminal width, styleId, and hyperlink.
* Built once per unique line (cached via charCache), so the per-char hot loop
* is just property reads + setCellAt β no stringWidth, no style interning,
* no hyperlink extraction per frame.
*
* styleId is safe to cache: StylePool is session-lived (never reset).
* hyperlink is stored as a string (not interned ID) since hyperlinkPool
* resets every 5 min; setCellAt interns it per-frame (cheap Map.get).
*/
type ClusteredChar = {
value: string
width: number
styleId: number
hyperlink: string | undefined
}
/**
* Collects write/blit/clear/clip operations from the render tree, then
* applies them to a Screen buffer in `get()`. The Screen is what gets
* diffed against the previous frame to produce terminal updates.
*/
type Options = {
width: number
height: number
stylePool: StylePool
/**
* Screen to render into. Will be reset before use.
* For double-buffering, pass a reusable screen. Otherwise create a new one.
*/
screen: Screen
}
export type Operation =
| WriteOperation
| ClipOperation
| UnclipOperation
| BlitOperation
| ClearOperation
| NoSelectOperation
| ShiftOperation
type WriteOperation = {
type: 'write'
x: number
y: number
text: string
/**
* Per-line soft-wrap flags, parallel to text.split('\n'). softWrap[i]=true
* means line i is a continuation of line i-1 (the `\n` before it was
* inserted by word-wrap, not in the source). Index 0 is always false.
* Undefined means the producer didn't track wrapping (e.g. fills,
* raw-ansi) β the screen's per-row bitmap is left untouched.
*/
softWrap?: boolean[]
}
type ClipOperation = {
type: 'clip'
clip: Clip
}
export type Clip = {
x1: number | undefined
x2: number | undefined
y1: number | undefined
y2: number | undefined
}
/**
* Intersect two clips. `undefined` on an axis means unbounded; the other
* clip's bound wins. If both are bounded, take the tighter constraint
* (max of mins, min of maxes). If the resulting region is empty
* (x1 >= x2 or y1 >= y2), writes clipped by it will be dropped.
*/
function intersectClip(parent: Clip | undefined, child: Clip): Clip {
if (!parent) return child
return {
x1: maxDefined(parent.x1, child.x1),
x2: minDefined(parent.x2, child.x2),
y1: maxDefined(parent.y1, child.y1),
y2: minDefined(parent.y2, child.y2),
}
}
function maxDefined(
a: number | undefined,
b: number | undefined,
): number | undefined {
if (a === undefined) return b
if (b === undefined) return a
return Math.max(a, b)
}
function minDefined(
a: number | undefined,
b: number | undefined,
): number | undefined {
if (a === undefined) return b
if (b === undefined) return a
return Math.min(a, b)
}
type UnclipOperation = {
type: 'unclip'
}
type BlitOperation = {
type: 'blit'
src: Screen
x: number
y: number
width: number
height: number
}
type ShiftOperation = {
type: 'shift'
top: number
bottom: number
n: number
}
type ClearOperation = {
type: 'clear'
region: Rectangle
/**
* Set when the clear is for an absolute-positioned node's old bounds.
* Absolute nodes overlay normal-flow siblings, so their stale paint is
* what an earlier sibling's clean-subtree blit wrongly restores from
* prevScreen. Normal-flow siblings' clears don't have this problem β
* their old position can't have been painted on top of a sibling.
*/
fromAbsolute?: boolean
}
type NoSelectOperation = {
type: 'noSelect'
region: Rectangle
}
export default class Output {
width: number
height: number
private readonly stylePool: StylePool
private screen: Screen
private readonly operations: Operation[] = []
private charCache: Map<string, ClusteredChar[]> = new Map()
constructor(options: Options) {
const { width, height, stylePool, screen } = options
this.width = width
this.height = height
this.stylePool = stylePool
this.screen = screen
resetScreen(screen, width, height)
}
/**
* Reuse this Output for a new frame. Zeroes the screen buffer, clears
* the operation list (backing storage is retained), and caps charCache
* growth. Preserving charCache across frames is the main win β most
* lines don't change between renders, so tokenize + grapheme clustering
* becomes a cache hit.
*/
reset(width: number, height: number, screen: Screen): void {
this.width = width
this.height = height
this.screen = screen
this.operations.length = 0
resetScreen(screen, width, height)
if (this.charCache.size > 16384) this.charCache.clear()
}
/**
* Copy cells from a source screen region (blit = block image transfer).
*/
blit(src: Screen, x: number, y: number, width: number, height: number): void {
this.operations.push({ type: 'blit', src, x, y, width, height })
}
/**
* Shift full-width rows within [top, bottom] by n. n > 0 = up. Mirrors
* what DECSTBM + SU/SD does to the terminal. Paired with blit() to reuse
* prevScreen content during pure scroll, avoiding full child re-render.
*/
shift(top: number, bottom: number, n: number): void {
this.operations.push({ type: 'shift', top, bottom, n })
}
/**
* Clear a region by writing empty cells. Used when a node shrinks to
* ensure stale content from the previous frame is removed.
*/
clear(region: Rectangle, fromAbsolute?: boolean): void {
this.operations.push({ type: 'clear', region, fromAbsolute })
}
/**
* Mark a region as non-selectable (excluded from fullscreen text
* selection copy + highlight). Used by <NoSelect> to fence off
* gutters (line numbers, diff sigils). Applied AFTER blit/write so
* the mark wins regardless of what's blitted into the region.
*/
noSelect(region: Rectangle): void {
this.operations.push({ type: 'noSelect', region })
}
write(x: number, y: number, text: string, softWrap?: boolean[]): void {
if (!text) {
return
}
this.operations.push({
type: 'write',
x,
y,
text,
softWrap,
})
}
clip(clip: Clip) {
this.operations.push({
type: 'clip',
clip,
})
}
unclip() {
this.operations.push({
type: 'unclip',
})
}
get(): Screen {
const screen = this.screen
const screenWidth = this.width
const screenHeight = this.height
// Track blit vs write cell counts for debugging
let blitCells = 0
let writeCells = 0
// Pass 1: expand damage to cover clear regions. The buffer is freshly
// zeroed by resetScreen, so this pass only marks damage so diff()
// checks these regions against the previous frame.
//
// Also collect clears from absolute-positioned nodes. An absolute
// node overlays normal-flow siblings; when it shrinks, its clear is
// pushed AFTER those siblings' clean-subtree blits (DOM order). The
// blit copies the absolute node's own stale paint from prevScreen,
// and since clear is damage-only, the ghost survives diff. Normal-
// flow clears don't need this β a normal-flow node's old position
// can't have been painted on top of a sibling's current position.
const absoluteClears: Rectangle[] = []
for (const operation of this.operations) {
if (operation.type !== 'clear') continue
const { x, y, width, height } = operation.region
const startX = Math.max(0, x)
const startY = Math.max(0, y)
const maxX = Math.min(x + width, screenWidth)
const maxY = Math.min(y + height, screenHeight)
if (startX >= maxX || startY >= maxY) continue
const rect = {
x: startX,
y: startY,
width: maxX - startX,
height: maxY - startY,
}
screen.damage = screen.damage ? unionRect(screen.damage, rect) : rect
if (operation.fromAbsolute) absoluteClears.push(rect)
}
const clips: Clip[] = []
for (const operation of this.operations) {
switch (operation.type) {
case 'clear':
// handled in pass 1
continue
case 'clip':
// Intersect with the parent clip (if any) so nested
// overflow:hidden boxes can't write outside their ancestor's
// clip region. Without this, a message with overflow:hidden at
// the bottom of a scrollbox pushes its OWN clip (based on its
// layout bounds, already translated by -scrollTop) which can
// extend below the scrollbox viewport β writes escape into
// the sibling bottom section's rows.
clips.push(intersectClip(clips.at(-1), operation.clip))
continue
case 'unclip':
clips.pop()
continue
case 'blit': {
// Bulk-copy cells from source screen region using TypedArray.set().
// Tracking damage ensures diff() checks blitted cells for stale content
// when a parent blits an area that previously contained child content.
const {
src,
x: regionX,
y: regionY,
width: regionWidth,
height: regionHeight,
} = operation
// Intersect with active clip β a child's clean-blit passes its full
// cached rect, but the parent ScrollBox may have shrunk (pill mount).
// Without this, the blit writes past the ScrollBox's new bottom edge
// into the pill's row.
const clip = clips.at(-1)
const startX = Math.max(regionX, clip?.x1 ?? 0)
const startY = Math.max(regionY, clip?.y1 ?? 0)
const maxY = Math.min(
regionY + regionHeight,
screenHeight,
src.height,
clip?.y2 ?? Infinity,
)
const maxX = Math.min(
regionX + regionWidth,
screenWidth,
src.width,
clip?.x2 ?? Infinity,
)
if (startX >= maxX || startY >= maxY) continue
// Skip rows covered by an absolute-positioned node's clear.
// Absolute nodes overlay normal-flow siblings, so prevScreen in
// that region holds the absolute node's stale paint β blitting
// it back would ghost. See absoluteClears collection above.
if (absoluteClears.length === 0) {
blitRegion(screen, src, startX, startY, maxX, maxY)
blitCells += (maxY - startY) * (maxX - startX)
continue
}
let rowStart = startY
for (let row = startY; row <= maxY; row++) {
const excluded =
row < maxY &&
absoluteClears.some(
r =>
row >= r.y &&
row < r.y + r.height &&
startX >= r.x &&
maxX <= r.x + r.width,
)
if (excluded || row === maxY) {
if (row > rowStart) {
blitRegion(screen, src, startX, rowStart, maxX, row)
blitCells += (row - rowStart) * (maxX - startX)
}
rowStart = row + 1
}
}
continue
}
case 'shift': {
shiftRows(screen, operation.top, operation.bottom, operation.n)
continue
}
case 'write': {
const { text, softWrap } = operation
let { x, y } = operation
let lines = text.split('\n')
let swFrom = 0
let prevContentEnd = 0
const clip = clips.at(-1)
if (clip) {
const clipHorizontally =
typeof clip?.x1 === 'number' && typeof clip?.x2 === 'number'
const clipVertically =
typeof clip?.y1 === 'number' && typeof clip?.y2 === 'number'
// If text is positioned outside of clipping area altogether,
// skip to the next operation to avoid unnecessary calculations
if (clipHorizontally) {
const width = widestLine(text)
if (x + width <= clip.x1! || x >= clip.x2!) {
continue
}
}
if (clipVertically) {
const height = lines.length
if (y + height <= clip.y1! || y >= clip.y2!) {
continue
}
}
if (clipHorizontally) {
lines = lines.map(line => {
const from = x < clip.x1! ? clip.x1! - x : 0
const width = stringWidth(line)
const to = x + width > clip.x2! ? clip.x2! - x : width
let sliced = sliceAnsi(line, from, to)
// Wide chars (CJK, emoji) occupy 2 cells. When `to` lands
// on the first cell of a wide char, sliceAnsi includes the
// entire glyph and the result overflows clip.x2 by one cell,
// writing a SpacerTail into the adjacent sibling. Re-slice
// one cell earlier; wide chars are exactly 2 cells, so a
// single retry always fits.
if (stringWidth(sliced) > to - from) {
sliced = sliceAnsi(line, from, to - 1)
}
return sliced
})
if (x < clip.x1!) {
x = clip.x1!
}
}
if (clipVertically) {
const from = y < clip.y1! ? clip.y1! - y : 0
const height = lines.length
const to = y + height > clip.y2! ? clip.y2! - y : height
// If the first visible line is a soft-wrap continuation, we
// need the clipped previous line's content end so
// screen.softWrap[lineY] correctly records the join point
// even though that line's cells were never written.
if (softWrap && from > 0 && softWrap[from] === true) {
prevContentEnd = x + stringWidth(lines[from - 1]!)
}
lines = lines.slice(from, to)
swFrom = from
if (y < clip.y1!) {
y = clip.y1!
}
}
}
const swBits = screen.softWrap
let offsetY = 0
for (const line of lines) {
const lineY = y + offsetY
// Line can be outside screen if `text` is taller than screen height
if (lineY >= screenHeight) {
break
}
const contentEnd = writeLineToScreen(
screen,
line,
x,
lineY,
screenWidth,
this.stylePool,
this.charCache,
)
writeCells += contentEnd - x
// See Screen.softWrap docstring for the encoding. contentEnd
// from writeLineToScreen is tab-expansion-aware, unlike
// x+stringWidth(line) which treats tabs as width 0.
if (softWrap) {
const isSW = softWrap[swFrom + offsetY] === true
swBits[lineY] = isSW ? prevContentEnd : 0
prevContentEnd = contentEnd
}
offsetY++
}
continue
}
}
}
// noSelect ops go LAST so they win over blits (which copy noSelect
// from prevScreen) and writes (which don't touch noSelect). This way
// a <NoSelect> box correctly fences its region even when the parent
// blits, and moving a <NoSelect> between frames correctly clears the
// old region (resetScreen already zeroed the bitmap).
for (const operation of this.operations) {
if (operation.type === 'noSelect') {
const { x, y, width, height } = operation.region
markNoSelectRegion(screen, x, y, width, height)
}
}
// Log blit/write ratio for debugging - high write count suggests blitting isn't working
const totalCells = blitCells + writeCells
if (totalCells > 1000 && writeCells > blitCells) {
logForDebugging(
`High write ratio: blit=${blitCells}, write=${writeCells} (${((writeCells / totalCells) * 100).toFixed(1)}% writes), screen=${screenHeight}x${screenWidth}`,
)
}
return screen
}
}
function stylesEqual(a: AnsiCode[], b: AnsiCode[]): boolean {
if (a === b) return true // Reference equality fast path
const len = a.length
if (len !== b.length) return false
if (len === 0) return true // Both empty
for (let i = 0; i < len; i++) {
if (a[i]!.code !== b[i]!.code) return false
}
return true
}
/**
* Convert a string with ANSI codes into styled characters with proper grapheme
* clustering. Fixes ansi-tokenize splitting grapheme clusters (like family
* emojis) into individual code points.
*
* Also precomputes styleId + hyperlink per style run (not per char) β an
* 80-char line with 3 style runs does 3 intern calls instead of 80.
*/
function styledCharsWithGraphemeClustering(
chars: StyledChar[],
stylePool: StylePool,
): ClusteredChar[] {
const charCount = chars.length
if (charCount === 0) return []
const result: ClusteredChar[] = []
const bufferChars: string[] = []
let bufferStyles: AnsiCode[] = chars[0]!.styles
for (let i = 0; i < charCount; i++) {
const char = chars[i]!
const styles = char.styles
// Different styles means we need to flush and start new buffer
if (bufferChars.length > 0 && !stylesEqual(styles, bufferStyles)) {
flushBuffer(bufferChars.join(''), bufferStyles, stylePool, result)
bufferChars.length = 0
}
bufferChars.push(char.value)
bufferStyles = styles
}
// Final flush
if (bufferChars.length > 0) {
flushBuffer(bufferChars.join(''), bufferStyles, stylePool, result)
}
return result
}
function flushBuffer(
buffer: string,
styles: AnsiCode[],
stylePool: StylePool,
out: ClusteredChar[],
): void {
// Compute styleId + hyperlink ONCE for the whole style run.
// Every grapheme in this buffer shares the same styles.
//
// Extract and track hyperlinks separately, filter from styles.
// Always check for OSC 8 codes to filter, not just when a URL is
// extracted. The tokenizer treats OSC 8 close codes (empty URL) as
// active styles, so they must be filtered even when no hyperlink
// URL is present.
const hyperlink = extractHyperlinkFromStyles(styles) ?? undefined
const hasOsc8Styles =
hyperlink !== undefined ||
styles.some(
s =>
s.code.length >= OSC8_PREFIX.length && s.code.startsWith(OSC8_PREFIX),
)
const filteredStyles = hasOsc8Styles
? filterOutHyperlinkStyles(styles)
: styles
const styleId = stylePool.intern(filteredStyles)
for (const { segment: grapheme } of getGraphemeSegmenter().segment(buffer)) {
out.push({
value: grapheme,
width: stringWidth(grapheme),
styleId,
hyperlink,
})
}
}
/**
* Write a single line's characters into the screen buffer.
* Extracted from Output.get() so JSC can optimize this tight,
* monomorphic loop independently β better register allocation,
* setCellAt inlining, and type feedback than when buried inside
* a 300-line dispatch function.
*
* Returns the end column (x + visual width, including tab expansion) so
* the caller can record it in screen.softWrap without re-walking the
* line via stringWidth(). Caller computes the debug cell-count as end-x.
*/
function writeLineToScreen(
screen: Screen,
line: string,
x: number,
y: number,
screenWidth: number,
stylePool: StylePool,
charCache: Map<string, ClusteredChar[]>,
): number {
let characters = charCache.get(line)
if (!characters) {
characters = reorderBidi(
styledCharsWithGraphemeClustering(
styledCharsFromTokens(tokenize(line)),
stylePool,
),
)
charCache.set(line, characters)
}
let offsetX = x
for (let charIdx = 0; charIdx < characters.length; charIdx++) {
const character = characters[charIdx]!
const codePoint = character.value.codePointAt(0)
// Handle C0 control characters (0x00-0x1F) that cause cursor movement
// mismatches. stringWidth treats these as width 0, but terminals may
// move the cursor differently.
if (codePoint !== undefined && codePoint <= 0x1f) {
// Tab (0x09): expand to spaces to reach next tab stop
if (codePoint === 0x09) {
const tabWidth = 8
const spacesToNextStop = tabWidth - (offsetX % tabWidth)
for (let i = 0; i < spacesToNextStop && offsetX < screenWidth; i++) {
setCellAt(screen, offsetX, y, {
char: ' ',
styleId: stylePool.none,
width: CellWidth.Narrow,
hyperlink: undefined,
})
offsetX++
}
}
// ESC (0x1B): skip incomplete escape sequences that ansi-tokenize
// didn't recognize. ansi-tokenize only parses SGR sequences (ESC[...m)
// and OSC 8 hyperlinks (ESC]8;;url BEL). Other sequences like cursor
// movement, screen clearing, or terminal title become individual char
// tokens that we need to skip here.
else if (codePoint === 0x1b) {
const nextChar = characters[charIdx + 1]?.value
const nextCode = nextChar?.codePointAt(0)
if (
nextChar === '(' ||
nextChar === ')' ||
nextChar === '*' ||
nextChar === '+'
) {
// Charset selection: ESC ( X, ESC ) X, etc.
// Skip the intermediate char and the charset designator
charIdx += 2
} else if (nextChar === '[') {
// CSI sequence: ESC [ ... final-byte
// Final byte is in range 0x40-0x7E (@, A-Z, [\]^_`, a-z, {|}~)
// Examples: ESC[2J (clear), ESC[?25l (cursor hide), ESC[H (home)
charIdx++ // skip the [
while (charIdx < characters.length - 1) {
charIdx++
const c = characters[charIdx]?.value.codePointAt(0)
// Final byte terminates the sequence
if (c !== undefined && c >= 0x40 && c <= 0x7e) {
break
}
}
} else if (
nextChar === ']' ||
nextChar === 'P' ||
nextChar === '_' ||
nextChar === '^' ||
nextChar === 'X'
) {
// String-based sequences terminated by BEL (0x07) or ST (ESC \):
// - OSC: ESC ] ... (Operating System Command)
// - DCS: ESC P ... (Device Control String)
// - APC: ESC _ ... (Application Program Command)
// - PM: ESC ^ ... (Privacy Message)
// - SOS: ESC X ... (Start of String)
charIdx++ // skip the introducer char
while (charIdx < characters.length - 1) {
charIdx++
const c = characters[charIdx]?.value
// BEL (0x07) terminates the sequence
if (c === '\x07') {
break
}
// ST (String Terminator) is ESC \
// When we see ESC, check if next char is backslash
if (c === '\x1b') {
const nextC = characters[charIdx + 1]?.value
if (nextC === '\\') {
charIdx++ // skip the backslash too
break
}
}
}
} else if (
nextCode !== undefined &&
nextCode >= 0x30 &&
nextCode <= 0x7e
) {
// Single-character escape sequences: ESC followed by 0x30-0x7E
// (excluding the multi-char introducers already handled above)
// - Fp range (0x30-0x3F): ESC 7 (save cursor), ESC 8 (restore)
// - Fe range (0x40-0x5F): ESC D (index), ESC M (reverse index)
// - Fs range (0x60-0x7E): ESC c (reset)
charIdx++ // skip the command char
}
}
// Carriage return (0x0D): would move cursor to column 0, skip it
// Backspace (0x08): would move cursor left, skip it
// Bell (0x07), vertical tab (0x0B), form feed (0x0C): skip
// All other control chars (0x00-0x06, 0x0E-0x1F): skip
// Note: newline (0x0A) is already handled by line splitting
continue
}
// Zero-width characters (combining marks, ZWNJ, ZWS, etc.)
// don't occupy terminal cells β storing them as Narrow cells
// desyncs the virtual cursor from the real terminal cursor.
// Width was computed once during clustering (cached via charCache).
const charWidth = character.width
if (charWidth === 0) {
continue
}
const isWideCharacter = charWidth >= 2
// Wide char at last column can't fit β terminal would wrap it to
// the next line, desyncing our cursor model. Place a SpacerHead
// to mark the blank column, matching terminal behavior.
if (isWideCharacter && offsetX + 2 > screenWidth) {
setCellAt(screen, offsetX, y, {
char: ' ',
styleId: stylePool.none,
width: CellWidth.SpacerHead,
hyperlink: undefined,
})
offsetX++
continue
}
// styleId + hyperlink were precomputed during clustering (once per
// style run, cached via charCache). Hot loop is now just property
// reads β no intern, no extract, no filter per frame.
setCellAt(screen, offsetX, y, {
char: character.value,
styleId: character.styleId,
width: isWideCharacter ? CellWidth.Wide : CellWidth.Narrow,
hyperlink: character.hyperlink,
})
offsetX += isWideCharacter ? 2 : 1
}
return offsetX
}
|