htui 0.2.0

A terminal HTML/CSS renderer with an embedded JavaScript engine — build interactive TUIs from HTML, CSS and JS
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! CSS Text Level 3 line-breaker for terminal inline runs.
//!
//! Walks a flat list of [`InlineRun`]s and emits a vector of visual
//! lines, each no wider than `max_width` terminal cells. The break
//! rules are driven by `white_space`, `word_break`, and
//! `overflow_wrap` per the CSS Text Module Level 3 specification
//! (terminal simplification: greedy best-fit, not minimum-raggedness).
//!
//! Visible from the layout phase (block + flex) via
//! [`crate::layout::layoutbox::wrap_runs`] /
//! [`crate::layout::layoutbox::wrapped_size`].

use unicode_segmentation::UnicodeSegmentation;

use crossterm::style::Color;

use crate::{
    graphics::{FontStyle, grapheme_width},
    html::css_parse::{OverflowWrap, WhiteSpace, WordBreak},
    layout::InlineRun,
    tdom::node::NodeId,
};

/// One token extracted from the input run list.
///
/// `Word` owns its text so the line-breaker can copy it into the
/// per-line `InlineRun` outputs without lifetime gymnastics.
#[derive(Debug, Clone)]
enum Token {
    /// A run of horizontal whitespace graphemes (`' '`, `'\t'`, NBSP).
    /// `_count` is the number of graphemes; `width` is the total cell
    /// width after font-size expansion. `_count` is currently unused
    /// after the `apply_white_space` collapsing phase but is kept on
    /// the variant for symmetry with `width` and future use.
    Space { width: usize, _count: usize },
    /// A forced break (`'\n'`) in the source text.
    Newline,
    /// An unconditional forced break (`<br>`). Unlike [`Token::Newline`],
    /// it splits the line even under `white-space: normal` (where a text
    /// newline collapses as a space boundary).
    Break,
    /// A maximal non-whitespace grapheme run lifted from one source
    /// `InlineRun`. The styling is carried alongside so the output
    /// lines preserve span boundaries; `node_id` names the DOM element
    /// the source run belonged to (e.g. a `<label>`) so inline hit
    /// regions survive the wrap.
    Word {
        text: String,
        width: usize,
        style: FontStyle,
        fg: Option<Color>,
        bg: Option<Color>,
        node_id: Option<NodeId>,
        /// Source-run letter spacing, replayed onto the reconstructed runs.
        letter_spacing: usize,
        /// Source-run word spacing (words never contain spaces, so this is
        /// carried for completeness / symmetry with the source run).
        word_spacing: isize,
    },
}

/// Returns `true` when `g` is one of the horizontal whitespace
/// graphemes the HTML spec treats as collapsible when `white-space`
/// is `normal` / `nowrap` / `pre-line`.
fn is_horizontal_ws(g: &str) -> bool {
    matches!(g, " " | "\t")
}

/// Returns `true` when `c` is in any of the major CJK ranges for
/// which browsers introduce break opportunities under
/// `word-break: normal`.
///
/// Covers CJK Unified Ideographs (basic + extensions), compatibility
/// forms, Hiragana / Katakana, Hangul Syllables, full-width ASCII
/// forms, CJK punctuation, Kangxi Radicals, and Tangut. The
/// table-based detection mirrors the character classes browsers
/// use for the CJK line-break opportunity rule.
pub fn is_cjk_break_opportunity(c: char) -> bool {
    let cp = c as u32;
    matches!(cp,
        0x4E00..=0x9FFF       // CJK Unified Ideographs
        | 0x3400..=0x4DBF     // CJK Unified Ideographs Extension A
        | 0x20000..=0x2A6DF   // Extension B
        | 0x2A700..=0x2B73F   // Extension C
        | 0x2B740..=0x2B81F   // Extension D
        | 0x2B820..=0x2CEAF   // Extension E
        | 0x2EBF0..=0x2EE5D   // Extension I
        | 0xF900..=0xFAFF     // CJK Compatibility Ideographs
        | 0x2F800..=0x2FA1F   // CJK Compatibility Supplement
        | 0x3040..=0x309F     // Hiragana
        | 0x30A0..=0x30FF     // Katakana
        | 0xAC00..=0xD7AF     // Hangul Syllables
        | 0x3000..=0x303F     // CJK Symbols & Punctuation
        | 0xFF00..=0xFFEF     // Half-width / Full-width Forms
        | 0x2E80..=0x2EFF     // CJK Radicals Supplement
        | 0x31C0..=0x31EF     // CJK Strokes
        | 0x2F00..=0x2FDF     // Kangxi Radicals
        | 0x17000..=0x187FF   // Tangut
        | 0x1B170..=0x1B2FF   // Tangut Components
        | 0x18B00..=0x18CFF   // Khitan Small Script
    )
}

/// `true` when `c` is forbidden from starting a visual line (simple CJK
/// kinsoku shori). Closing punctuation, prolonged-sound marks and the
/// small kana cannot detach from the word before them: the tokenizer
/// attaches such graphemes to the pending word instead of emitting a
/// break opportunity, so a line never opens with `。` / `、` / `」` / `っ`.
///
/// This is the terminal-sized subset of the browser's line-break rules
/// (`line-break: strict` is a documented reject): it covers the closing
/// side only — an opening bracket that cannot END a line would need a
/// look-ahead in the wrap phase and is not modelled.
fn is_forbidden_line_start(c: char) -> bool {
    matches!(
        c,
        '、' | '。'
            | ','
            | '.'
            | ':'
            | ';'
            | '?'
            | '!'
            | '・'
            | 'ー'
            | '」'
            | '』'
            | ')'
            | ']'
            | '}'
            | '〉'
            | '》'
            | '】'
            | '〗'
            | '〙'
            | '〛'
            | '’'
            | '”'
            | '…'
            | '~'
            | '%'
            | '‰'
            | '°'
            | '゛'
            | '゜'
            | 'ぁ'
            | 'ぃ'
            | 'ぅ'
            | 'ぇ'
            | 'ぉ'
            | 'っ'
            | 'ゃ'
            | 'ゅ'
            | 'ょ'
            | 'ゎ'
            | 'ァ'
            | 'ィ'
            | 'ゥ'
            | 'ェ'
            | 'ォ'
            | 'ッ'
            | 'ャ'
            | 'ュ'
            | 'ョ'
            | 'ヮ'
    )
}

/// Tokenize one `InlineRun`'s text into a flat sequence of `Token`s
/// appended to `out`. Words preserve the source run's styling; the
/// `Space` token only stores total cell width and grapheme count.
///
/// CJK Unified Ideographs (and other East-Asian wide characters) get
/// their own one-grapheme `Word` token each: under the browser-default
/// `word-break: normal` the line-breaker must allow a break between any
/// two adjacent CJK characters, so we cannot merge them into a single
/// word the way we merge runs of ASCII letters. CJK runs of consecutive
/// characters therefore become a sequence of single-grapheme `Word`
/// tokens; the wrap phase then fits them greedily into the available
/// width and naturally breaks at character boundaries.
///
/// `word-break: keep-all` flips this for CJK text: the entire CJK run
/// is accumulated into a single `Word` so the wrap phase treats the
/// sequence as unbreakable. The text is then emitted as one wide word
/// (overflowing the line if it cannot fit) — the same behaviour
/// browsers ship for `keep-all`.
fn tokenize_run(
    run: &InlineRun,
    font_size_cells: usize,
    word_break: WordBreak,
    out: &mut Vec<Token>,
) {
    let font = font_size_cells.max(1);

    // 0 = "currently accumulating spaces", 1 = "currently accumulating a word"
    let mut pending_kind: Option<u8> = None;
    let mut pending_text = String::new();
    let mut pending_count: usize = 0;
    let mut pending_width: usize = 0;

    let flush = |kind: Option<u8>,

                 text: &mut String,
                 count: &mut usize,
                 width: &mut usize,
                 run: &InlineRun,
                 out: &mut Vec<Token>| {
        if let Some(k) = kind {
            if *count == 0 || text.is_empty() {
                return;
            }
            if k == 0 {
                out.push(Token::Space {
                    width: *width,
                    _count: *count,
                });
                // Drop the space graphemes from the accumulator so the
                // next pending kind starts with a clean string. (Without
                // this, the next `Word` token inherits the spaces as
                // leading characters — the "row" example becomes "
                // row", which paints an extra leading space.)
                text.clear();
            } else {
                out.push(Token::Word {
                    text: std::mem::take(text),
                    width: *width,
                    style: run.style,
                    fg: run.fg,
                    bg: run.bg,
                    node_id: run.node_id,
                    letter_spacing: run.letter_spacing,
                    word_spacing: run.word_spacing,
                });
            }
        }
        *count = 0;
        *width = 0;
    };

    for g in run.text.graphemes(true) {
        if g == "\n" {
            // Close whatever is pending, then push the forced break.
            // A `<br>` marker run (force_break) is unconditional — it
            // splits the line even under `white-space: normal`.
            flush(
                pending_kind,
                &mut pending_text,
                &mut pending_count,
                &mut pending_width,
                run,
                out,
            );
            pending_kind = None;
            out.push(if run.force_break {
                Token::Break
            } else {
                Token::Newline
            });
            continue;
        }
        let w = run.grapheme_advance(g, font);
        if is_horizontal_ws(g) {
            if pending_kind != Some(0) {
                flush(
                    pending_kind,
                    &mut pending_text,
                    &mut pending_count,
                    &mut pending_width,
                    run,
                    out,
                );
                pending_kind = Some(0);
            }
            pending_text.push_str(g);
            pending_count += 1;
            pending_width += w;
        } else if word_break != WordBreak::KeepAll
            && g.chars()
                .next()
                .is_some_and(|c| is_cjk_break_opportunity(c) && !is_forbidden_line_start(c))
        {
            // CJK (or full-width) grapheme under `normal` / `break-all`:
            // flush whatever is pending so the boundary before this
            // character is recognised as a wrap opportunity, then emit
            // it as its own one-grapheme word.
            flush(
                pending_kind,
                &mut pending_text,
                &mut pending_count,
                &mut pending_width,
                run,
                out,
            );
            pending_kind = None;
            out.push(Token::Word {
                text: g.to_string(),
                width: w,
                style: run.style,
                fg: run.fg,
                bg: run.bg,
                node_id: run.node_id,
                letter_spacing: run.letter_spacing,
                word_spacing: run.word_spacing,
            });
        } else if word_break != WordBreak::KeepAll
            && g.chars()
                .next()
                .is_some_and(|c| is_cjk_break_opportunity(c) && is_forbidden_line_start(c))
        {
            // Kinsoku: a closing mark must never open a visual line, so it
            // attaches to the word before it. The previous standalone CJK
            // glyph is already on `out` (the branch above bypasses the
            // pending buffer), so an unbroken same-style Word there absorbs
            // the mark; otherwise the mark starts a pending accumulation the
            // following glyphs can extend.
            let merged = if let Some(Token::Word {
                text,
                width: tok_width,
                style: tok_style,
                fg: tok_fg,
                bg: tok_bg,
                node_id: tok_node,
                letter_spacing: tok_ls,
                word_spacing: tok_ws,
            }) = out.last_mut()
            {
                if *tok_style == run.style
                    && *tok_fg == run.fg
                    && *tok_bg == run.bg
                    && *tok_node == run.node_id
                    && *tok_ls == run.letter_spacing
                    && *tok_ws == run.word_spacing
                {
                    text.push_str(g);
                    *tok_width += w;
                    true
                } else {
                    false
                }
            } else {
                false
            };
            if !merged {
                if pending_kind != Some(1) {
                    flush(
                        pending_kind,
                        &mut pending_text,
                        &mut pending_count,
                        &mut pending_width,
                        run,
                        out,
                    );
                    pending_kind = Some(1);
                }
                pending_text.push_str(g);
                pending_count += 1;
                pending_width += w;
            }
        } else {
            // Non-CJK, or CJK under `keep-all`: accumulate as one word
            // so the wrap phase treats the run as unbreakable.
            if pending_kind != Some(1) {
                flush(
                    pending_kind,
                    &mut pending_text,
                    &mut pending_count,
                    &mut pending_width,
                    run,
                    out,
                );
                pending_kind = Some(1);
            }
            pending_text.push_str(g);
            pending_count += 1;
            pending_width += w;
        }
    }
    flush(
        pending_kind,
        &mut pending_text,
        &mut pending_count,
        &mut pending_width,
        run,
        out,
    );
}

/// Apply the `white-space` collapsing rules to a token stream and
/// emit "logical lines": sequences of tokens that must appear on the
/// same line (unless wrapping kicks in). Forced breaks (`Newline`)
/// separate logical lines.
///
/// `font_size_cells` is the run's effective font expansion: a collapsed
/// space occupies one *expanded* slot (`max(grapheme_width, font)`), the
/// same width the paint phase's `width_at` accounts for the `" "` run —
/// the wrap accounting and the paint accounting must agree or
/// `text-align` offsets and the trailing-slot clip diverge once the font
/// size exceeds 1.
fn apply_white_space(
    tokens: Vec<Token>,
    ws: WhiteSpace,
    _font_size_cells: usize,
) -> Vec<Vec<Token>> {
    if ws.preserves_whitespace() {
        // `pre` / `pre-wrap`: every Newline is a forced break; spaces
        // are preserved as-is. `<br>` breaks are unconditional.
        let mut lines: Vec<Vec<Token>> = vec![Vec::new()];
        for t in tokens {
            if matches!(t, Token::Newline | Token::Break) {
                lines.push(Vec::new());
            } else if let Some(line) = lines.last_mut() {
                line.push(t);
            }
        }
        return lines;
    }
    // `normal` / `nowrap` / `pre-line`: collapse runs of Space (and
    // any Newlines they contain, except `pre-line` where standalone
    // newlines are forced breaks). A `<br>` Break is forced in every mode.
    let mut lines: Vec<Vec<Token>> = vec![Vec::new()];
    for t in tokens {
        match t {
            Token::Newline => {
                if matches!(ws, WhiteSpace::PreLine) {
                    lines.push(Vec::new());
                }
                // `normal` / `nowrap` swallow the newline as a
                // collapsible-space boundary.
            }
            Token::Break => {
                // `<br>` forces a line break regardless of `white-space`.
                lines.push(Vec::new());
            }
            Token::Space { width, _count } => {
                if let Some(line) = lines.last_mut() {
                    let last_is_space = matches!(line.last(), Some(Token::Space { .. }));
                    if !last_is_space {
                        // The collapsed representative carries ONE space's
                        // real advance (the run's width split over its
                        // graphemes): the tokenizer already counted word /
                        // letter spacing per space, and the wrap budget
                        // must match what the reconstructed space run will
                        // actually paint — a cheap `font_size` width here
                        // lets a line book-keep far below its painted width
                        // and the paint pass then truncates the line's tail
                        // (whole words silently disappear).
                        let per_space = width.div_ceil(_count.max(1));
                        line.push(Token::Space {
                            width: per_space,
                            _count: 1,
                        });
                    }
                }
            }
            Token::Word { .. } => {
                if let Some(line) = lines.last_mut() {
                    line.push(t);
                }
            }
        }
    }
    lines
}

/// Wrap a single logical line onto one or more visual lines. The
/// caller has already applied the `white_space` collapsing rules so
/// each `Space` token here represents a single-cell break opportunity
/// (or a run of spaces that the previous phase kept together).
fn wrap_logical_line(
    logical: Vec<Token>,
    max_width: usize,
    font_size_cells: usize,
    word_break: WordBreak,
    overflow_wrap: OverflowWrap,
    first_indent: usize,
    out: &mut Vec<Vec<InlineRun>>,
) {
    let mut current_line: Vec<InlineRun> = Vec::new();
    // The indent occupies the head of the line: the first token must fit
    // in `max_width - indent`, exactly like a leading run of blank cells.
    let mut current_width: usize = first_indent.min(max_width);
    // Carry the previous non-space run's fg / bg / style so a space
    // run inserted between two word runs paints with the same look —
    // the original text node carried the same fg / bg across the
    // space, and the renderer's SGR batcher relies on every cell in
    // a row having consistent attributes. The owner (`node_id`) rides
    // along so a space inside an inline element's text still belongs
    // to that element's hit region.
    let mut last_run_style: (Option<Color>, Option<Color>, FontStyle) =
        (None, None, FontStyle::empty());
    let mut last_run_node_id: Option<NodeId> = None;
    let mut last_run_spacing: (usize, isize) = (0, 0);

    // Try to place `word` on the current line. If it does not fit and
    // the line is non-empty, flush and retry on a fresh line. If the
    // word is wider than the line, split it according to the
    // `word_break` / `overflow_wrap` policy.
    for token in logical {
        match token {
            Token::Newline => unreachable!("Newline should have split logical lines"),
            Token::Break => unreachable!("Break should have split logical lines"),
            Token::Space { width, .. } => {
                if current_line.is_empty() {
                    continue; // skip leading spaces
                }
                if current_width + width <= max_width {
                    // Keep the space. Width bookkeeping is on the
                    // output InlineRun (single cell), so the input
                    // width already counts it.
                    let (fg, bg, style) = last_run_style;
                    let (ls, ws) = last_run_spacing;
                    let mut space_run = InlineRun::owned(" ", style, fg, bg, last_run_node_id);
                    space_run.letter_spacing = ls;
                    space_run.word_spacing = ws;
                    current_line.push(space_run);
                    current_width += width;
                } else {
                    // The space run does not fit on the current line. Flush
                    // the line we have so far and discard the space (the
                    // browser "hanging whitespace" rule: trailing whitespace
                    // at a line break is dropped even under `pre-wrap`).
                    out.push(std::mem::take(&mut current_line));
                    current_width = 0;
                }
            }
            Token::Word {
                text,
                width,
                style,
                fg,
                bg,
                node_id,
                letter_spacing,
                word_spacing,
            } => {
                last_run_style = (fg, bg, style);
                last_run_node_id = node_id;
                last_run_spacing = (letter_spacing, word_spacing);
                let make_run = |text: String| {
                    let mut r = InlineRun::owned(text, style, fg, bg, node_id);
                    r.letter_spacing = letter_spacing;
                    r.word_spacing = word_spacing;
                    r
                };
                if width + current_width <= max_width {
                    // Whole word fits on the current line.
                    current_line.push(make_run(text));
                    current_width += width;
                } else if width <= max_width && !current_line.is_empty() {
                    // Word fits on a fresh line; flush current first.
                    out.push(std::mem::take(&mut current_line));
                    current_line.push(make_run(text));
                    current_width = width;
                } else if width <= max_width {
                    // Word fits on a fresh line; current is empty.
                    current_line.push(make_run(text));
                    current_width = width;
                } else {
                    // Word is wider than a full line. Split it.
                    let is_purely_cjk = text.chars().all(is_cjk_break_opportunity);
                    let should_split = match (word_break, overflow_wrap) {
                        (WordBreak::BreakAll, _) => true,
                        (WordBreak::KeepAll, _) if is_purely_cjk => false,
                        (WordBreak::KeepAll, _) => true,
                        (WordBreak::Normal, OverflowWrap::Anywhere) => true,
                        (WordBreak::Normal, OverflowWrap::BreakWord) => true,
                        (WordBreak::Normal, OverflowWrap::Normal) => false,
                    };
                    if !should_split {
                        // Word overflows; emit the whole thing.
                        current_line.push(make_run(text));
                        current_width += width;
                        continue;
                    }
                    // Flush anything already on the current line — the long
                    // word starts a fresh visual line.
                    if !current_line.is_empty() {
                        out.push(std::mem::take(&mut current_line));
                        current_width = 0;
                    }
                    // Greedy split by grapheme. `buf_width` tracks the
                    // accumulated width of the current buffer; when adding
                    // the next grapheme would overflow the line, flush the
                    // buffer as its own visual line and start a new one.
                    let font = font_size_cells.max(1);
                    let graphemes: Vec<&str> = text.graphemes(true).collect();
                    let mut buf = String::new();
                    let mut buf_width: usize = 0;
                    let split_run =
                        |text: String, style, fg, bg, node_id, letter_spacing, word_spacing| {
                            let mut r = InlineRun::owned(text, style, fg, bg, node_id);
                            r.letter_spacing = letter_spacing;
                            r.word_spacing = word_spacing;
                            r
                        };
                    for g in graphemes {
                        // Words contain no spaces, so word spacing never
                        // applies inside the split; letter spacing does.
                        let w = grapheme_width(g).max(font) + letter_spacing;
                        if !buf.is_empty() && buf_width + w > max_width {
                            current_line.push(split_run(
                                std::mem::take(&mut buf),
                                style,
                                fg,
                                bg,
                                node_id,
                                letter_spacing,
                                word_spacing,
                            ));
                            out.push(std::mem::take(&mut current_line));
                            buf_width = 0;
                        }
                        buf.push_str(g);
                        buf_width += w;
                    }
                    if !buf.is_empty() {
                        current_line.push(split_run(
                            buf,
                            style,
                            fg,
                            bg,
                            node_id,
                            letter_spacing,
                            word_spacing,
                        ));
                        current_width = buf_width;
                    }
                }
            }
        }
    }
    out.push(current_line);
}

/// Emit one visual line per logical line under [`WhiteSpace::Pre`].
///
/// `pre` preserves every whitespace grapheme verbatim AND forces a
/// break at each `\n`. Soft wrapping is off (no `max_width`
/// splitting), so this routine is much simpler than the greedy
/// wrap: walk graphemes, accumulate into a per-style buffer, and
/// flush the buffer at each newline. Style changes flush the
/// current buffer to a new [`InlineRun`] within the same visual
/// line so span boundaries stay intact.
///
/// Always returns at least one entry (an empty visual line for an
/// empty input). The returned visual lines preserve leading and
/// trailing spaces, tabs, and any number of consecutive spaces
/// within a line — the collapsing that the standard
/// `apply_white_space` path applies for `normal` / `nowrap` is
/// explicitly *not* in effect here.
fn emit_preserving_newlines(runs: &[InlineRun]) -> Vec<Vec<InlineRun>> {
    let mut lines: Vec<Vec<InlineRun>> = Vec::new();
    let mut line: Vec<InlineRun> = Vec::new();
    let mut buf = String::new();
    let mut cur_fg: Option<Color> = None;
    let mut cur_bg: Option<Color> = None;
    let mut cur_style = FontStyle::empty();
    let mut cur_node_id: Option<NodeId> = None;
    let mut cur_spacing: (usize, isize) = (0, 0);
    let mut buffering = false;

    for run in runs {
        if run.is_empty() {
            continue;
        }
        for g in run.text.graphemes(true) {
            if g == "\n" {
                if buffering {
                    let mut flushed = InlineRun::owned(
                        std::mem::take(&mut buf),
                        cur_style,
                        cur_fg,
                        cur_bg,
                        cur_node_id,
                    );
                    flushed.letter_spacing = cur_spacing.0;
                    flushed.word_spacing = cur_spacing.1;
                    line.push(flushed);
                    buffering = false;
                }
                lines.push(std::mem::take(&mut line));
                continue;
            }
            // Style change inside a single visual line flushes the
            // accumulated buffer so fg / bg / style never silently
            // bleed across span boundaries.
            if buffering
                && (cur_fg != run.fg
                    || cur_bg != run.bg
                    || cur_style != run.style
                    || cur_node_id != run.node_id
                    || cur_spacing != (run.letter_spacing, run.word_spacing))
            {
                line.push(InlineRun::owned(
                    std::mem::take(&mut buf),
                    cur_style,
                    cur_fg,
                    cur_bg,
                    cur_node_id,
                ));
                if let Some(last) = line.last_mut() {
                    last.letter_spacing = cur_spacing.0;
                    last.word_spacing = cur_spacing.1;
                }
                buffering = false;
            }
            if !buffering {
                cur_fg = run.fg;
                cur_bg = run.bg;
                cur_style = run.style;
                cur_node_id = run.node_id;
                cur_spacing = (run.letter_spacing, run.word_spacing);
                buffering = true;
            }
            buf.push_str(g);
        }
    }
    if buffering {
        let mut tail = InlineRun::owned(buf, cur_style, cur_fg, cur_bg, cur_node_id);
        tail.letter_spacing = cur_spacing.0;
        tail.word_spacing = cur_spacing.1;
        line.push(tail);
    }
    // Always emit a trailing visual line — even an empty one when
    // the input ended on a newline. This keeps callers (which split
    // the canvas one line at a time) aligned with the source.
    lines.push(line);
    if lines.is_empty() {
        lines.push(Vec::new());
    }
    lines
}

/// Wrap inline runs into visual lines according to the white-space, word-break, and overflow-wrap policies.
///
/// `first_line_indent` reserves leading columns of the block's first visual
/// line (CSS `text-indent`): the wrap budget shrinks by that amount — the
/// paint phase shifts the line's origin to match.
pub fn wrap_runs(
    runs: &[InlineRun],
    max_width: usize,
    font_size_cells: usize,
    white_space: WhiteSpace,
    word_break: WordBreak,
    overflow_wrap: OverflowWrap,
    first_line_indent: usize,
) -> Vec<Vec<InlineRun>> {
    if runs.is_empty() {
        return vec![Vec::new()];
    }
    if !white_space.allows_wrap() {
        if matches!(white_space, WhiteSpace::Pre) {
            // `pre` keeps every whitespace grapheme (spaces, tabs) AND
            // every newline. Soft wrapping is forbidden, but `\n` is
            // a forced break: each newline starts a fresh visual line.
            // Falls through to a dedicated splitter that walks the
            // grapheme stream so it can keep multi-space runs intact
            // (which the `tokenize_run` collapse phase would otherwise
            // strip away).
            return emit_preserving_newlines(runs);
        }
        // `nowrap`: collapse whitespace (still happens in apply_white_space)
        // and never wrap. A single visual line; text newlines collapse —
        // except `<br>` breaks, which split the line unconditionally.
        let mut out: Vec<Vec<InlineRun>> = vec![Vec::new()];
        for r in runs {
            if r.force_break {
                out.push(Vec::new());
            } else if !r.is_empty()
                && let Some(line) = out.last_mut()
            {
                line.push(r.clone());
            }
        }
        return out;
    }
    if max_width == 0 {
        // Defensive: avoid infinite loops in the splitter. Render
        // each non-empty run on its own line.
        let mut out: Vec<Vec<InlineRun>> = Vec::new();
        for r in runs {
            if !r.is_empty() {
                out.push(vec![r.clone()]);
            }
        }
        if out.is_empty() {
            out.push(Vec::new());
        }
        return out;
    }

    // Phase 1: tokenize.
    let mut tokens: Vec<Token> = Vec::new();
    for r in runs {
        tokenize_run(r, font_size_cells, word_break, &mut tokens);
    }
    // Phase 2: apply white-space collapsing / forced breaks.
    let logical_lines = apply_white_space(tokens, white_space, font_size_cells);
    // Phase 3: greedy wrap each logical line. The block's first visual
    // line carries the `text-indent` budget (CSS: the first line of the
    // block's inline content); later logical lines start flush.
    let mut visual_lines: Vec<Vec<InlineRun>> = Vec::new();
    for (idx, logical) in logical_lines.into_iter().enumerate() {
        let indent = if idx == 0 { first_line_indent } else { 0 };
        wrap_logical_line(
            logical,
            max_width,
            font_size_cells,
            word_break,
            overflow_wrap,
            indent,
            &mut visual_lines,
        );
    }
    if visual_lines.is_empty() || visual_lines.iter().all(|l| l.is_empty()) {
        // Whitespace-only input collapses away to no visible content: report
        // zero lines so callers don't reserve a phantom inline row for it.
        return Vec::new();
    }
    visual_lines
}

/// `text-overflow: ellipsis` post-pass: any visual line wider than
/// `max_width` (in practice the single unwrapped `nowrap` line of a clipped
/// box) is cut to `max_width - 1` columns and terminated with an `…` run in
/// the cut point's style. Lines that already fit pass through untouched.
pub fn apply_ellipsis(
    lines: Vec<Vec<InlineRun>>,
    max_width: usize,
    font_size_cells: usize,
) -> Vec<Vec<InlineRun>> {
    lines
        .into_iter()
        .map(|line| {
            let total: usize = line.iter().map(|r| r.width_at(font_size_cells)).sum();
            if total <= max_width || line.is_empty() {
                return line;
            }
            let budget = max_width.saturating_sub(1);
            let mut out: Vec<InlineRun> = Vec::new();
            let mut used = 0usize;
            for run in line {
                let w = run.width_at(font_size_cells);
                if used + w <= budget {
                    out.push(run);
                    used += w;
                    continue;
                }
                // Cut this run at the remaining budget, grapheme-aligned.
                let remaining = budget.saturating_sub(used);
                let mut text = String::new();
                let mut acc = 0usize;
                for g in run.text.graphemes(true) {
                    let gw = run.grapheme_advance(g, font_size_cells);
                    if acc + gw > remaining {
                        break;
                    }
                    text.push_str(g);
                    acc += gw;
                }
                if !text.is_empty() {
                    out.push(InlineRun::owned_spaced(
                        text,
                        run.style,
                        run.fg,
                        run.bg,
                        run.node_id,
                        run.letter_spacing,
                        run.word_spacing,
                    ));
                }
                break;
            }
            // The ellipsis inherits the last kept (or cut) run's look.
            let tail = out.last().map(|r| {
                (
                    r.style,
                    r.fg,
                    r.bg,
                    r.node_id,
                    r.letter_spacing,
                    r.word_spacing,
                )
            });
            match tail {
                Some((style, fg, bg, node_id, ls, ws)) => {
                    out.push(InlineRun::owned_spaced("…", style, fg, bg, node_id, ls, ws));
                }
                None => out.push(InlineRun::new("…", FontStyle::empty(), None, None)),
            }
            out
        })
        .collect()
}

/// Return `(max_line_width, line_count * font_size_cells)` of
/// wrapping `runs` to `max_width` under the same rules as
/// [`wrap_runs`] (including the first-line indent's effect on line
/// count). Useful for intrinsic measurements where the caller only
/// needs the dimensions, not the per-line run lists.
pub fn wrapped_size(
    runs: &[InlineRun],
    max_width: usize,
    font_size_cells: usize,
    white_space: WhiteSpace,
    word_break: WordBreak,
    overflow_wrap: OverflowWrap,
    first_line_indent: usize,
) -> (usize, usize) {
    let lines = wrap_runs(
        runs,
        max_width,
        font_size_cells,
        white_space,
        word_break,
        overflow_wrap,
        first_line_indent,
    );
    let font = font_size_cells.max(1);
    let max_line_w = lines
        .iter()
        .enumerate()
        .map(|(idx, l)| {
            let base = l.iter().map(|r| r.width_at(font)).sum::<usize>();
            let indent = if idx == 0 { first_line_indent } else { 0 };
            base + indent
        })
        .max()
        .unwrap_or(0);
    let total_rows = lines.len().saturating_mul(font);
    (max_line_w, total_rows)
}