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
use crossterm::style::Color;
use htui::html::css_parse;
use htui::html::html_parse;
use htui::layout::layout::TermMap;
use htui::tdom::node::{NodeArena, NodeId, NodeType};
use htui::tui::graph_api::TermLayout;

fn init() {
    let _ = env_logger::builder().is_test(true).try_init();
}

fn setup(html: &str, css: &str) -> (NodeId, NodeArena) {
    let mut html_parser = html_parse::Parser::new(html);
    let (root_id, mut arena, embedded) = html_parser.parse();
    let combined = if css.is_empty() {
        embedded
    } else if embedded.is_empty() {
        css.to_string()
    } else {
        format!("{embedded}\n{css}")
    };
    if !combined.trim().is_empty() {
        let mut css_parser = css_parse::Parser::new(&combined);
        let rules = css_parser.parse();
        css_parse::css_into_node(&mut arena, root_id, &rules);
    }
    (root_id, arena)
}

const COLS: u16 = 80;
const ROWS: u16 = 24;

fn mock_term_map() -> TermMap {
    TermMap {
        columns: COLS,
        rows: ROWS,
    }
}

fn cell_containing(tl: &TermLayout, needle: &str) -> Option<(usize, usize, usize)> {
    for (idx, block) in tl.layout.iter().enumerate() {
        if block.word == needle {
            let cols = tl.columns as usize;
            return Some((idx, idx / cols, idx % cols));
        }
    }
    None
}

#[test]
fn test_parse_tag_map_table() {
    assert_eq!(
        html_parse::tag_name_to_node_type("table"),
        Some(NodeType::Table)
    );
    assert_eq!(html_parse::tag_name_to_node_type("tr"), Some(NodeType::Tr));
    assert_eq!(html_parse::tag_name_to_node_type("td"), Some(NodeType::Td));
    assert_eq!(html_parse::tag_name_to_node_type("th"), Some(NodeType::Th));
    assert_eq!(
        html_parse::tag_name_to_node_type("thead"),
        Some(NodeType::Thead)
    );
    assert_eq!(
        html_parse::tag_name_to_node_type("tbody"),
        Some(NodeType::Tbody)
    );
    assert_eq!(
        html_parse::tag_name_to_node_type("tfoot"),
        Some(NodeType::Tfoot)
    );
}

#[test]
fn test_parse_tag_map_uppercase_table() {
    assert_eq!(
        html_parse::tag_name_to_node_type("TABLE"),
        Some(NodeType::Table)
    );
    assert_eq!(html_parse::tag_name_to_node_type("TR"), Some(NodeType::Tr));
    assert_eq!(html_parse::tag_name_to_node_type("TD"), Some(NodeType::Td));
    assert_eq!(html_parse::tag_name_to_node_type("TH"), Some(NodeType::Th));
}

#[test]
fn test_table_renders_all_cell_text() {
    init();
    let html = "<table><tr><td>Apple</td><td>Banana</td></tr><tr><td>Cherry</td><td>Date</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Apple"), "missing 'Apple' cell");
    assert!(canvas.contains("Banana"), "missing 'Banana' cell");
    assert!(canvas.contains("Cherry"), "missing 'Cherry' cell");
    assert!(canvas.contains("Date"), "missing 'Date' cell");
}

#[test]
fn test_table_renders_th_header_text() {
    init();
    let html = "<table><tr><th>Name</th><th>Role</th></tr><tr><td>Alice</td><td>Engineer</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Name"), "header 'Name' missing");
    assert!(canvas.contains("Role"), "header 'Role' missing");
    assert!(canvas.contains("Alice"), "data 'Alice' missing");
    assert!(canvas.contains("Engineer"), "data 'Engineer' missing");
}

#[test]
fn test_table_th_text_marks_bold() {
    // <th> should pick up the CSS default text-decoration? No, we don't
    // add <th> defaults — but with explicit CSS we should still see bold.
    init();
    let html = "<table><tr><th>H1</th><th>H2</th></tr><tr><td>D1</td><td>D2</td></tr></table>";
    let css = "th { font-weight: bold; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let bold_letters: String = tl
        .layout
        .iter()
        .filter(|b| b.style.contains(htui::tui::graph_api::FontStyle::BOLD))
        .map(|b| b.word.as_str())
        .collect();
    assert!(
        bold_letters.contains('H'),
        "<th> header letters should be bold via CSS rule; got {bold_letters:?}"
    );
}

#[test]
fn test_table_th_ua_defaults_bold_and_centered() {
    init();
    // Browser UA stylesheet: `th { font-weight: bold; text-align: center }`.
    // Both defaults resolve from the shared UA declaration table and yield to
    // author declarations.
    let html = "<table><tr><th>Hdr</th></tr><tr><td>D</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let bold_letters: String = tl
        .layout
        .iter()
        .filter(|b| b.style.contains(htui::tui::graph_api::FontStyle::BOLD))
        .map(|b| b.word.as_str())
        .collect();
    for ch in "Hdr".chars() {
        assert!(
            bold_letters.contains(ch),
            "the UA default must bold the header text; got {bold_letters:?}"
        );
    }
    // Data cells carry no UA bold default.
    assert!(
        !bold_letters.contains('D'),
        "data cells must not pick up the header default; got {bold_letters:?}"
    );
}

#[test]
fn test_table_th_ua_center_yields_to_author_left() {
    init();
    // The UA `text-align: center` is a cascade default: an author
    // `text-align: left` wins, like any other UA-vs-author rule.
    let (root_id, arena) = setup(
        "<table><tr><th>ab</th></tr></table>",
        "th { width: 20ch; text-align: left; }",
    );
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let cols = term_map.columns as usize;
    let a_col = tl
        .layout
        .iter()
        .position(|b| b.word == "a")
        .expect("'a' must render");
    assert_eq!(
        a_col % cols,
        0,
        "author left alignment must beat the UA center (cell content starts at column 0)"
    );

    // Control: without the author rule the same header centres.
    let (root2, arena2) = setup("<table><tr><th>ab</th></tr></table>", "th { width: 20ch; }");
    let mut tl2 = TermLayout::new(&term_map, 1.0);
    tl2.draw(&arena2, root2, &term_map);
    let a2 = tl2
        .layout
        .iter()
        .position(|b| b.word == "a")
        .expect("'a' must render");
    assert_ne!(a2 % cols, 0, "the UA default must centre the header");
}

#[test]
fn test_table_td_block_child_feeds_row_height() {
    init();
    // A block child inside a `<td>` claims its own rows: the row must grow
    // to the child's laid-out height, or the child paints over the next
    // table row. The child (a `width: 4ch` div of ten CJK glyphs, 2 cells
    // each) wraps to five rows at its own width, while the cell's direct
    // inline runs fit on one.
    let html = "<table><tr><td><div style=\"width: 4ch\">一二三四五六七八九十</div></td></tr>\
                <tr><td>NEXT</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let cols = term_map.columns as usize;
    // The invariant under test: the second table row starts BELOW the block
    // child's last wrapped line, wherever the `ch` unit resolution puts it.
    let last_child_row = tl
        .layout
        .iter()
        .position(|b| b.word == "十")
        .expect("the block child's last glyph must render")
        / cols;
    let next_row = tl
        .layout
        .iter()
        .position(|b| b.word == "N")
        .expect("'NEXT' must render")
        / cols;
    assert!(
        next_row > last_child_row,
        "the second row must start below the wrapped block child (last glyph on \
         row {last_child_row}), got NEXT on row {next_row} — the child's height \
         must feed the row height"
    );
}

#[test]
fn test_table_cells_align_in_columns() {
    // Two rows of two cells should align: each row's cell 1 sits on the same
    // starting column, and cell 2's column is shared too.
    init();
    let html = "<table><tr><td>AB</td><td>CD</td></tr><tr><td>EF</td><td>GH</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let cols = tl.columns as usize;
    let a_idx = cell_containing(&tl, "A").expect("missing 'A'").0;
    let c_idx = cell_containing(&tl, "C").expect("missing 'C'").0;
    let e_idx = cell_containing(&tl, "E").expect("missing 'E'").0;
    let g_idx = cell_containing(&tl, "G").expect("missing 'G'").0;

    let a_col = a_idx % cols;
    let c_col = c_idx % cols;
    let e_col = e_idx % cols;
    let g_col = g_idx % cols;

    assert_eq!(
        a_col, e_col,
        "row 1 cell 1 and row 2 cell 1 must share a column"
    );
    assert_eq!(
        c_col, g_col,
        "row 1 cell 2 and row 2 cell 2 must share a column"
    );
    assert_ne!(
        a_col, c_col,
        "cell 1 and cell 2 must be in different columns"
    );
}

#[test]
fn test_table_cells_on_consecutive_rows() {
    init();
    let html = "<table><tr><td>Row1</td></tr><tr><td>Row2</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let (_, row1_row, _) = cell_containing(&tl, "R").expect("missing 'R' of row1");
    let (_, row2_row, _) = tl
        .layout
        .iter()
        .enumerate()
        .filter_map(|(idx, b)| {
            if idx / (tl.columns as usize) > row1_row && b.word == "R" {
                let row = idx / tl.columns as usize;
                let col = idx % tl.columns as usize;
                Some((idx, row, col))
            } else {
                None
            }
        })
        .next()
        .expect("missing 'R' of row2");

    assert!(
        row2_row > row1_row,
        "row 2 (row={row2_row}) must be below row 1 (row={row1_row})"
    );
}

#[test]
fn test_table_with_thead_section() {
    init();
    let html = "<table><thead><tr><th>Header</th></tr></thead><tbody><tr><td>Body</td></tr></tbody></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Header"), "thead content missing");
    assert!(canvas.contains("Body"), "tbody content missing");
}

#[test]
fn test_table_with_tfoot_section() {
    init();
    let html = "<table><thead><tr><th>Item</th></tr></thead><tbody><tr><td>Data</td></tr></tbody><tfoot><tr><td>Foot</td></tr></tfoot></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Item"), "thead content missing");
    assert!(canvas.contains("Data"), "tbody content missing");
    assert!(canvas.contains("Foot"), "tfoot content missing");
}

#[test]
fn test_table_css_border_draws_box_glyphs() {
    init();
    let html = "<table><tr><td>A</td><td>B</td></tr></table>";
    let css = "table, td { border: 1ch solid white; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(
        canvas.contains('─') || canvas.contains('│'),
        "table border should draw at least one ─ or │ glyph"
    );
    assert!(
        canvas.contains('┌')
            || canvas.contains('┐')
            || canvas.contains('└')
            || canvas.contains('┘'),
        "table border should draw at least one corner glyph"
    );
}

#[test]
fn test_table_cell_color_applies() {
    init();
    let html = "<table><tr><td>Red</td></tr></table>";
    let css = "td { color: red; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let has_red = tl
        .layout
        .iter()
        .any(|b| b.fcolor == Some(Color::Rgb { r: 255, g: 0, b: 0 }));
    assert!(has_red, "td should pick up `color: red` via CSS selector");
}

#[test]
fn test_table_cell_bg_color_applies() {
    init();
    let html = "<table><tr><td>Yellow cell</td></tr></table>";
    let css = "td { background-color: yellow; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let yellow_count = tl
        .layout
        .iter()
        .filter(|b| {
            b.bcolor
                == Some(Color::Rgb {
                    r: 255,
                    g: 255,
                    b: 0,
                })
        })
        .count();
    assert!(
        yellow_count > 0,
        "td background-color: yellow should paint at least one cell"
    );
}

#[test]
fn test_table_nth_child_even_stripes_td_bg() {
    // `tr:nth-child(even) td` and
    // `tr:nth-child(odd) td` must colour the even / odd rows' cells
    // distinctly. Before the `:nth-child()` selector was implemented, both
    // rules silently no-op'd so all cells kept the same background.
    init();
    let html = "<table>\
        <tr><td>R1</td></tr>\
        <tr><td>R2</td></tr>\
        <tr><td>R3</td></tr>\
        <tr><td>R4</td></tr>\
        </table>";
    let css = "tr:nth-child(even) td { background-color: darkgrey; } \
               tr:nth-child(odd) td { background-color: black; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let even_cells = tl
        .layout
        .iter()
        .filter(|b| {
            b.bcolor
                == Some(Color::Rgb {
                    r: 169,
                    g: 169,
                    b: 169,
                })
        })
        .count();
    let odd_cells = tl
        .layout
        .iter()
        .filter(|b| b.bcolor == Some(Color::Rgb { r: 0, g: 0, b: 0 }))
        .count();
    assert!(
        even_cells > 0,
        "nth-child(even) must colour at least one cell darkgrey (got {even_cells})"
    );
    assert!(
        odd_cells > 0,
        "nth-child(odd) must colour at least one cell black (got {odd_cells})"
    );
}

#[test]
fn test_table_caption_renders_above_rows() {
    // `<caption>` renders as a (centered) text block above the table rows —
    // the CSS default `caption-side: top`.
    init();
    let html = "<table><caption>Hidden</caption><tr><td>Visible</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Visible"), "td text should render");
    assert!(
        canvas.contains("Hidden"),
        "caption text should render above the rows"
    );
    // The caption row sits above the first table row: its first glyph's
    // canvas row is smaller than any cell text's row (the layout is a flat
    // cell array, row = index / columns).
    let row_of = |needle: &str| -> usize {
        tl.layout
            .iter()
            .enumerate()
            .find(|(_, b)| b.word == needle)
            .map(|(idx, _)| idx / COLS as usize)
            .unwrap_or(usize::MAX)
    };
    let caption_row = row_of("H");
    let cell_row = row_of("V");
    assert!(caption_row < cell_row, "caption paints above the first row");
}

#[test]
fn test_table_caption_side_bottom_moves_below_rows() {
    init();
    let (root_id, arena) = setup(
        "<table><caption>Tail</caption><tr><td>Cell</td></tr></table>",
        "table { caption-side: bottom; }",
    );
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let row_of = |needle: &str| -> usize {
        tl.layout
            .iter()
            .enumerate()
            .find(|(_, b)| b.word == needle)
            .map(|(idx, _)| idx / COLS as usize)
            .unwrap_or(usize::MAX)
    };
    let caption_row = row_of("T");
    let cell_row = row_of("C");
    assert!(
        caption_row > cell_row,
        "caption-side: bottom paints the caption below the rows"
    );
}

#[test]
fn test_table_colgroup_silently_dropped() {
    // <colgroup> is parsed but not rendered — table should still render
    // its rows normally.
    init();
    let html = "<table><colgroup><col><col></colgroup><tr><td>A</td><td>B</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("A"), "cell A should render");
    assert!(canvas.contains("B"), "cell B should render");
}

#[test]
fn test_table_empty_renders_empty_box() {
    init();
    let (root_id, arena) = setup("<table></table>", "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    // No assertion needed; just verify draw doesn't fail.
}

#[test]
fn test_table_row_with_no_cells_keeps_row_geometry() {
    init();
    let html = "<table><tr></tr><tr><td>Below</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Below"), "second-row content must render");
}

#[test]
fn test_table_short_row_pads_with_empty_columns() {
    // A row with fewer cells than the column count should still align its
    // existing cells with the wider rows above.
    init();
    let html = "<table><tr><td>Long</td><td>Wide</td></tr><tr><td>Short</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Long"), "wide row cell 1 missing");
    assert!(canvas.contains("Wide"), "wide row cell 2 missing");
    assert!(canvas.contains("Short"), "short row cell 1 missing");
}

#[test]
fn test_table_does_not_crash_on_text_between_rows() {
    // Whitespace / text nodes between rows are flattened by the HTML parser,
    // so the table should still render its rows.
    init();
    let html = "<table><tr><td>A</td></tr>  <tr><td>B</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("A"), "first row missing");
    assert!(canvas.contains("B"), "second row missing");
}

#[test]
fn test_table_three_column_alignment() {
    init();
    let html = "<table><tr><td>A</td><td>B</td><td>C</td></tr><tr><td>D</td><td>E</td><td>F</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let cols = tl.columns as usize;
    let a_col = cell_containing(&tl, "A").unwrap().0 % cols;
    let b_col = cell_containing(&tl, "B").unwrap().0 % cols;
    let c_col = cell_containing(&tl, "C").unwrap().0 % cols;
    let d_col = cell_containing(&tl, "D").unwrap().0 % cols;
    let e_col = cell_containing(&tl, "E").unwrap().0 % cols;
    let f_col = cell_containing(&tl, "F").unwrap().0 % cols;

    assert_eq!(a_col, d_col, "col 1 aligned");
    assert_eq!(b_col, e_col, "col 2 aligned");
    assert_eq!(c_col, f_col, "col 3 aligned");
    assert!(
        a_col < b_col && b_col < c_col,
        "columns monotonically increase"
    );
}

#[test]
fn test_table_column_width_grows_to_widest_cell() {
    init();
    let html = "<table><tr><td>A</td><td>very wide cell content</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let a_idx = cell_containing(&tl, "A").unwrap().0;
    let v_idx = cell_containing(&tl, "v").unwrap().0;
    // Cell 2 must start at least 2 cells to the right of cell 1 (cell 1
    // needs at least one cell of content width + padding).
    let cell_1_width = v_idx - a_idx;
    assert!(
        cell_1_width >= 3,
        "cell 1 should be at least 3 cells wide (CELL_PADDING + content), got {cell_1_width}"
    );
}

#[test]
fn test_table_row_grows_when_cell_text_wraps_on_narrow_terminals() {
    init();
    // On a narrow terminal the column width can be clamped below the
    // cell's text width, so the cell text wraps to several lines. The row
    // height must grow to hold every wrapped line — otherwise the wrapped
    // lines paint over the row below (here the <div> after the table).
    let html = "<table><tr><td>longer cell text</td></tr></table><div>AFTER</div>";
    let (root_id, arena) = setup(html, "");
    let map = TermMap {
        columns: 10,
        rows: 10,
    };
    let mut tl = TermLayout::new(&map, 1.0);
    tl.draw(&arena, root_id, &map);
    let cols = map.columns as usize;
    let rows: Vec<String> = tl
        .layout
        .chunks(cols)
        .map(|chunk| chunk.iter().map(|b| b.word.as_str()).collect())
        .collect();
    assert!(
        rows[0].contains("longer"),
        "first wrapped line on row 0: {:?}",
        rows[0]
    );
    assert!(
        rows[1].contains("cell text"),
        "second wrapped line on row 1: {:?}",
        rows[1]
    );
    assert!(
        !rows[1].contains("AFTER"),
        "AFTER must not share the wrapped line: {:?}",
        rows[1]
    );
    assert!(
        rows[2].contains("AFTER"),
        "AFTER on row 2 (below the grown table row): {:?}",
        rows[2]
    );
}

#[test]
fn test_table_text_align_center_in_cell() {
    init();
    let html = "<table><tr><td>X</td></tr></table>";
    let css = "td { text-align: center; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // Find the column of the 'X' cell. With a wide column (3 minimum +
    // padding), X should be offset from the left edge of the column.
    let x_idx = cell_containing(&tl, "X").unwrap().0;
    let x_col = x_idx % (tl.columns as usize);
    assert!(
        x_col > 0,
        "X should be offset from the left edge (centered), got col {x_col}"
    );
}

#[test]
fn test_table_outside_table_falls_back_to_block() {
    // <tr>/<td> outside a table should still render via the fallback
    // block layout so their text is not silently dropped.
    init();
    let html = "<tr><td>stray</td></tr>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(
        canvas.contains("stray"),
        "stray <td> text should still render via fallback block"
    );
}

#[test]
fn scaled_columns_never_collapse_to_zero_width() {
    init();
    // When one dominant column drives the total far past the available
    // width. Every scaled column keeps a 1-cell floor, so each
    // narrow column still shows at least its first character.
    let long_word = "0123456789".repeat(33); // 330 chars
    let html = format!("<table><tr><td>a1</td><td>b2</td><td>{long_word}</td></tr></table>");
    let (root_id, arena) = setup(&html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(
        canvas.contains('a') && canvas.contains('b'),
        "the narrow columns must keep at least one visible cell after scaling: {canvas:?}"
    );
}

#[test]
fn cell_column_width_counts_inline_descendant_text() {
    init();
    // A `<td><b>…</b></td>` cell's column must size to the bold text: the
    // inline descendants' text folds into the cell's own runs at layout
    // time, so the column width must count descendant text rather than
    // stopping at direct text nodes.
    let html = "<table><tr><td><b>tenchars!!</b></td><td>x</td></tr></table>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let row0: String = tl.layout[..80].iter().map(|b| b.word.as_str()).collect();
    assert!(
        row0.contains("tenchars!!"),
        "the bold cell's text must fit on one row (column sized to the inline \
         descendant's text, not the 3-cell minimum): {row0:?}"
    );
}