Wrap styled spans into visual lines while preserving color runs across splits.
(spans: RenderSpan[], width: number)
| 300 | |
| 301 | /** Wrap styled spans into visual lines while preserving color runs across splits. */ |
| 302 | function wrapSpans(spans: RenderSpan[], width: number) { |
| 303 | if (width <= 0) { |
| 304 | return [[]] as RenderSpan[][]; |
| 305 | } |
| 306 | |
| 307 | const lines: RenderSpan[][] = [[]]; |
| 308 | let current = lines[0]!; |
| 309 | let remaining = width; |
| 310 | |
| 311 | for (const span of sanitizeTerminalSpans(spans)) { |
| 312 | const spanWidth = measureTextWidth(span.text); |
| 313 | if (spanWidth === 0) { |
| 314 | appendRenderSpan(current, span); |
| 315 | continue; |
| 316 | } |
| 317 | |
| 318 | let offset = 0; |
| 319 | |
| 320 | while (offset < spanWidth) { |
| 321 | if (remaining <= 0) { |
| 322 | current = []; |
| 323 | lines.push(current); |
| 324 | remaining = width; |
| 325 | } |
| 326 | |
| 327 | const visible = sliceTextByWidth(span.text, offset, remaining); |
| 328 | if (visible.width === 0) { |
| 329 | // A single wide cluster cannot fit in the remaining cells; continue on the next row. |
| 330 | current = []; |
| 331 | lines.push(current); |
| 332 | remaining = width; |
| 333 | const forced = sliceTextByWidth(span.text, offset, width); |
| 334 | if (forced.width === 0) { |
| 335 | break; |
| 336 | } |
| 337 | const nextSpan = { |
| 338 | ...span, |
| 339 | text: forced.text, |
| 340 | }; |
| 341 | current.push(nextSpan); |
| 342 | offset += forced.width; |
| 343 | remaining = Math.max(0, width - forced.width); |
| 344 | continue; |
| 345 | } |
| 346 | |
| 347 | const nextSpan = { |
| 348 | ...span, |
| 349 | text: visible.text, |
| 350 | }; |
| 351 | appendRenderSpan(current, nextSpan); |
| 352 | |
| 353 | offset += visible.width; |
| 354 | remaining -= visible.width; |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | return lines; |
| 359 | } |
no test coverage detected