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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
use crossterm::style::Color;
use htui::html::html_parse::Parser;
use htui::html::{css_parse, html_parse};
use htui::layout::layout::TermMap;
use htui::tdom::node::{NodeArena, NodeId};
use htui::tui::graph_api::{FontStyle, 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,
    }
}

#[test]
fn test_layout_p() {
    let mut p = Parser::new("<p>Hello</p><p>World</p>");
    let (root, arena, _) = p.parse();
    let term_map = TermMap {
        columns: 80,
        rows: 24,
    };
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root, &term_map);
    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("Hello"));
    assert!(canvas.contains("World"));
}

// ============================================================
// text-align — exercised through `<p>` and `<h1>`-`<h5>` so the
// inheritance chain `div { text-align: ... } → <p>` is covered.
// ============================================================

#[test]
fn test_layout_p_text_align_center() {
    init();
    let html = "<p>Centered</p>";
    let css = "p { text-align: center; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word != " ")
        .expect("should find text");
    let row = text_idx / cols;
    let rstart = row * cols;
    let leading_spaces = tl.layout[rstart..rstart + cols]
        .iter()
        .take_while(|b| b.word == " ")
        .count();
    let text_str_width = "Centered".len();
    let expected_padding = (cols - text_str_width) / 2;
    assert_eq!(
        leading_spaces, expected_padding,
        "<p> text should be centered within row"
    );
}

#[test]
fn test_layout_p_text_align_right() {
    init();
    let html = "<p>Right</p>";
    let css = "p { text-align: right; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word != " ")
        .expect("should find text");
    let row = text_idx / cols;
    let rstart = row * cols;
    let leading_spaces = tl.layout[rstart..rstart + cols]
        .iter()
        .take_while(|b| b.word == " ")
        .count();
    let text_str_width = "Right".len();
    let expected_padding = cols - text_str_width;
    assert_eq!(
        leading_spaces, expected_padding,
        "<p> text should be right-aligned within row"
    );
}

#[test]
fn test_layout_p_text_align_inherited_from_div() {
    init();
    let html = "<div><p>centered</p></div>";
    let css = "div { text-align: center; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // "centered" must not start at column 0 — it should be indented by the
    // center-padding because <p> inherited text-align from <div>.
    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "c")
        .expect("should find 'centered'");
    let row = text_idx / cols;
    let col_in_row = text_idx % cols;
    let text_str_width = "centered".len();
    let expected_padding = (cols - text_str_width) / 2;
    assert_eq!(
        col_in_row, expected_padding,
        "<p> should inherit text-align from <div>, row={row}"
    );
}

#[test]
fn test_layout_h1_text_align_center() {
    init();
    let html = "<h1>Title</h1>";
    let css = "h1 { text-align: center; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // Rendered text is "# Title" (prefix included in alignment width).
    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "#")
        .expect("should find heading '#' prefix");
    let col_in_row = text_idx % cols;
    let rendered_width = "# Title".chars().count() * 2;
    let expected_padding = (cols - rendered_width) / 2;
    assert_eq!(
        col_in_row, expected_padding,
        "<h1> should be centered including '# ' prefix"
    );
}

#[test]
fn test_layout_h2_text_align_right() {
    init();
    let html = "<h2>Sub</h2>";
    let css = "h2 { text-align: right; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "#")
        .expect("should find heading '#' prefix");
    let col_in_row = text_idx % cols;
    let rendered_width = "## Sub".chars().count() * 2;
    let expected_padding = cols - rendered_width;
    assert_eq!(
        col_in_row, expected_padding,
        "<h2> should be right-aligned including '## ' prefix"
    );
}

#[test]
fn test_layout_heading_text_align_inherited_from_div() {
    init();
    let html = "<div><h1>Heading</h1></div>";
    let css = "div { text-align: center; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "#")
        .expect("should find heading prefix");
    let col_in_row = text_idx % cols;
    let rendered_width = "# Heading".chars().count() * 2;
    let expected_padding = (cols - rendered_width) / 2;
    assert_eq!(
        col_in_row, expected_padding,
        "<h1> should inherit text-align from <div>"
    );
}

#[test]
fn test_layout_p_text_align_default_left() {
    init();
    let html = "<p>Left</p>";
    let css = "";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word != " ")
        .expect("should find text");
    let row = text_idx / cols;
    let col_in_row = text_idx % cols;
    assert_eq!(
        col_in_row, 0,
        "default text-align should leave text at column 0, row={row}"
    );
}

// ============================================================
// Terminal-size sanity bounds
// ============================================================

/// Render the document and collect each canvas row's text (trailing spaces
/// trimmed), for layout-space assertions.
fn canvas_rows(tl: &TermLayout, cols: usize) -> Vec<String> {
    tl.layout
        .chunks(cols)
        .map(|row| {
            let s: String = row.iter().map(|b| b.word.as_str()).collect();
            s.trim_end().to_string()
        })
        .collect()
}

#[test]
fn visibility_hidden_keeps_layout_space_but_paints_nothing() {
    init();
    // `visibility: hidden` removes the content visually but keeps the box's
    // layout space (unlike `display: none`): the paragraph after the hidden
    // one must still start on the next row.
    let html = "<div><p>a</p><p class=\"hid\">b</p><p>c</p></div>";
    let css = ".hid { visibility: hidden; }";
    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 rows = canvas_rows(&tl, term_map.columns as usize);
    assert!(
        !rows.iter().any(|r| r.contains('b')),
        "hidden content must not paint"
    );
    let row_a = rows.iter().position(|r| r.contains('a')).expect("a row");
    let row_c = rows.iter().position(|r| r.contains('c')).expect("c row");
    assert_eq!(
        row_c,
        row_a + 4,
        "the hidden <p> keeps its layout space; a and c are 4 rows apart (text + margin + hidden text + margin)"
    );
}

#[test]
fn visibility_hidden_child_block_with_visible_restores() {
    init();
    // `visibility` is inherited: a hidden parent hides its own content, but a
    // block child with an explicit `visible` still paints (browser behaviour).
    let html = "<div class=\"hid\">x<div class=\"vis\">y</div></div>";
    let css = ".hid { visibility: hidden; } .vis { visibility: visible; }";
    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('x'),
        "the hidden parent's own content must not paint"
    );
    assert!(
        canvas.contains('y'),
        "a block child overriding visibility: visible must paint"
    );
}

#[test]
fn term_layout_caps_a_pathological_viewport_size() {
    // A transiently-inverted Windows `SMALL_RECT` during a resize can make
    // crossterm report ~65535 columns / rows (i16 → u16 wrap). Taking that
    // literally would allocate `65535 × 65535` cells (~hundreds of GB) and
    // freeze the render thread — `TermLayout::new` must cap the canvas.
    let term_map = TermMap {
        columns: u16::MAX,
        rows: u16::MAX,
    };
    let tl = TermLayout::new(&term_map, 1.0);
    let max_cells =
        htui::layout::layout::MAX_TERM_COLS as usize * htui::layout::layout::MAX_TERM_ROWS as usize;
    assert!(
        tl.layout.len() <= max_cells,
        "canvas must be bounded by the size clamps, got {}",
        tl.layout.len()
    );
}

#[test]
fn term_layout_caps_an_extreme_but_plausible_viewport() {
    // 3000 × 1000 would still be a ~96 MB allocation with 64-byte cells; the
    // clamp must keep even an out-of-spec size within the sane bound.
    let term_map = TermMap {
        columns: 3000,
        rows: 1000,
    };
    let tl = TermLayout::new(&term_map, 1.0);
    assert!(tl.layout.len() <= 1000 * 500);
}

// ============================================================
// <h6> / <hgroup> / <address>
// ============================================================

#[test]
fn test_layout_h6_prefix_renders() {
    init();
    let html = "<h6>Small</h6>";
    let css = "";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // h6's default `0.67em` rounds to 1 cell per char (like h4/h5), so the
    // `###### ` prefix paints six plain '#' glyphs followed by a space.
    let hash_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "#")
        .expect("h6 '######' prefix should render");
    let row = hash_idx / cols;
    let rstart = row * cols;
    let row_cells = &tl.layout[rstart..rstart + cols];
    let prefix: String = row_cells[0..7].iter().map(|b| b.word.as_str()).collect();
    assert_eq!(
        prefix, "###### ",
        "h6 must render the 6-level markdown prefix"
    );
    let text: String = row_cells[7..12].iter().map(|b| b.word.as_str()).collect();
    assert_eq!(
        text, "Small",
        "heading text must follow the prefix on the same row"
    );
}

#[test]
fn test_layout_hgroup_renders_heading_children() {
    init();
    // `<hgroup>` is a plain block container: its members (headings, and a
    // trailing <p>) keep their own block rendering. h4 defaults to 1 cell
    // per char so the canvas string is unambiguous.
    let html = "<hgroup><h4>Grouped</h4><p>tagline</p></hgroup>";
    let css = "";
    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("#### Grouped"),
        "hgroup member heading must render with its own prefix"
    );
    assert!(
        canvas.contains("tagline"),
        "hgroup's trailing <p> child must render"
    );
}

#[test]
fn test_layout_address_italic_default() {
    init();
    // Browser UA default: unstyled `<address>` renders italic.
    let html = "<address>Contact</address>";
    let css = "";
    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 idx = tl
        .layout
        .iter()
        .position(|b| b.word == "C")
        .expect("address text must render");
    let cell = &tl.layout[idx];
    assert!(
        cell.style.contains(FontStyle::ITALIC),
        "default <address> rendering must be italic (got style {:?})",
        cell.style
    );
}

#[test]
fn test_layout_address_font_style_normal_disables_italic() {
    init();
    // Author CSS resetting the UA default must take effect.
    let html = "<address>Contact</address>";
    let css = "address { font-style: normal; }";
    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 idx = tl
        .layout
        .iter()
        .position(|b| b.word == "C")
        .expect("address text must render");
    let cell = &tl.layout[idx];
    assert!(
        !cell.style.contains(FontStyle::ITALIC),
        "`address {{ font-style: normal }}` must suppress the UA italic default (got {:?})",
        cell.style
    );
}

#[test]
fn test_layout_address_inherits_italic_from_ancestor() {
    init();
    // font-style is inherited: an ancestor rule must win over (and satisfy)
    // the UA default without an explicit rule on the address itself.
    let html = "<div><address>Contact</address></div>";
    let css = "div { font-style: italic; }";
    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 idx = tl
        .layout
        .iter()
        .position(|b| b.word == "C")
        .expect("address text must render");
    let cell = &tl.layout[idx];
    assert!(
        cell.style.contains(FontStyle::ITALIC),
        "<address> must inherit font-style from its ancestor (got {:?})",
        cell.style
    );
}

// ============================================================
// display: inline-block
// ============================================================

#[test]
fn inline_block_boxes_flow_side_by_side() {
    init();
    // Consecutive `display: inline-block` boxes flow left-to-right on one
    // line (browser inline-level layout), keeping their own margins. Each
    // card is 20 cells wide with a 2-cell right margin; the source-code
    // whitespace between the cards collapses to a single separating space
    // (browser inter-element whitespace), so consecutive starts are
    // 20 + 2 margin + 1 space = 23 cells apart.
    let html = r#"
        <div class="card">AA</div>
        <div class="card">BB</div>
        <div class="card">CC</div>
    "#;
    let css = ".card { display: inline-block; width: 20ch; margin-right: 2ch; }";
    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 idx_a = tl.layout.iter().position(|b| b.word == "A").unwrap();
    let idx_b = tl.layout.iter().position(|b| b.word == "B").unwrap();
    let idx_c = tl.layout.iter().position(|b| b.word == "C").unwrap();
    assert_eq!(idx_a / 80, 0, "all cards share the first row");
    assert_eq!(idx_b / 80, 0);
    assert_eq!(idx_c / 80, 0);
    assert_eq!(
        idx_b,
        idx_a + 23,
        "second card starts after 20 + 2 margin + 1 collapsed space"
    );
    assert_eq!(idx_c, idx_b + 23, "third card follows the same spacing");
}

#[test]
fn inline_row_skips_unlayouttable_item_without_shifting_siblings() {
    init();
    // An inline row containing a `display: inline-grid` item (grid geometry
    // is unimplemented — its layout dispatch returns `None`) must skip that
    // item. Measurement indices and placement positions stay aligned so a
    // later sibling consumes its own measurement and its box, including any
    // background fill, is painted.
    let html = r#"<div><span class="a">AA</span><span class="g" style="display: inline-grid">G</span><span class="b">BBB</span></div>"#;
    let css = ".a, .b { display: inline-block; } .b { background-color: navy; }";
    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 row0: String = tl.layout[..80].iter().map(|b| b.word.as_str()).collect();
    assert_eq!(
        row0.find("AA"),
        Some(0),
        "the first inline item keeps its own measurements: {row0:?}"
    );
    let navy = Color::Rgb {
        r: 0,
        g: 0,
        b: 0x80,
    };
    let painted = tl.layout[..80]
        .iter()
        .any(|b| b.word == "B" && b.bcolor == Some(navy));
    assert!(
        painted,
        "the sibling after the unlayouttable item must keep its own measurements \
         and place its box (background fill) on the row: {row0:?}"
    );
}

#[test]
fn inline_block_whitespace_separates_and_collapses() {
    init();
    // Inter-element whitespace between two inline-blocks collapses to one
    // space cell (any run length), while adjacent cards in the source with
    // no whitespace between them keep only their margins — both match the
    // browser.
    let html = "<div class=\"a\">A</div>  <div class=\"b\">B</div><div class=\"c\">C</div>";
    let css = ".a, .b, .c { display: inline-block; width: 10ch; margin-right: 2ch; }";
    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 idx_a = tl.layout.iter().position(|b| b.word == "A").unwrap();
    let idx_b = tl.layout.iter().position(|b| b.word == "B").unwrap();
    let idx_c = tl.layout.iter().position(|b| b.word == "C").unwrap();
    assert_eq!(
        idx_b,
        idx_a + 13,
        "whitespace run collapses to one cell: 10 + 2 + 1"
    );
    assert_eq!(idx_c, idx_b + 12, "no whitespace: margin only (10 + 2)");
}

#[test]
fn inline_block_line_start_space_is_removed() {
    init();
    // A wrapped line drops its leading collapsed space (browser rule), so
    // the second card starts at column 0 of the wrapped row, not column 1.
    let html = "<div class=\"a\">A</div> <div class=\"b\">B</div>";
    let css = ".a, .b { display: inline-block; width: 10ch; margin-right: 2ch; }";
    let (root_id, arena) = setup(html, css);
    // 11 columns: 10 + 2 + 1 + 10 = 23 does not fit; the second card wraps.
    let term_map = TermMap {
        columns: 11,
        rows: 8,
    };
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let idx_a = tl.layout.iter().position(|b| b.word == "A").unwrap();
    let idx_b = tl.layout.iter().position(|b| b.word == "B").unwrap();
    assert_eq!(idx_a % 11, 0, "first card at column 0");
    assert_eq!(
        idx_b / 11,
        idx_a / 11 + 1,
        "second card wrapped to the next row"
    );
    assert_eq!(
        idx_b % 11,
        0,
        "wrapped card starts at column 0 (leading space removed)"
    );
}

#[test]
fn inline_block_keeps_its_own_box_and_width() {
    init();
    // An `inline-block` produces its own box (border / background / width)
    // instead of flattening its children into the parent flow.
    let html = r#"<div class="card">hi</div>"#;
    let css = ".card { display: inline-block; width: 10ch; border: 1ch solid 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);
    // Border frame spans exactly 10 cells (the declared width) on row 0;
    // the content sits on row 1 inside the frame.
    assert_eq!(tl.layout[0].word, "┌");
    assert_eq!(tl.layout[9].word, "┐");
    assert_eq!(tl.layout[80 + 1].word, "h");
    assert_eq!(tl.layout[80 + 2].word, "i");
}

#[test]
fn inline_block_wraps_at_line_width() {
    init();
    // Three 39-cell inline-blocks in an 80-cell line: two fit on a row
    // (39 + 1 space + 39 = 79), the third wraps (the separating space plus
    // a third card would need 39+1+39+1+39 = 119 cells).
    let html = r#"
        <div class="card">AA</div>
        <div class="card">BB</div>
        <div class="card">CC</div>
    "#;
    let css = ".card { display: inline-block; width: 39ch; }";
    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 idx_a = tl.layout.iter().position(|b| b.word == "A").unwrap();
    let idx_b = tl.layout.iter().position(|b| b.word == "B").unwrap();
    let idx_c = tl.layout.iter().position(|b| b.word == "C").unwrap();
    assert_eq!(idx_a / 80, 0);
    assert_eq!(idx_b / 80, 0, "second card stays on row 1");
    assert_eq!(idx_c / 80, 1, "third card wraps to row 2");
    assert_eq!(
        idx_b,
        idx_a + 40,
        "second card follows by 39 + 1 collapsed space"
    );
}

// ============================================================
// <hr> + text-level semantics (strong/b/i/u/s/mark/…, code/kbd/samp, br)
// ============================================================

#[test]
fn test_layout_hr_renders_rule_across_width() {
    init();
    let html = "<hr>";
    let css = "";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let idx = tl
        .layout
        .iter()
        .position(|b| b.word == "─")
        .expect("hr rule must render");
    let row = idx / cols;
    let rstart = row * cols;
    let rule_len = tl.layout[rstart..rstart + cols]
        .iter()
        .take_while(|b| b.word == "─")
        .count();
    assert_eq!(
        rule_len, cols,
        "hr must span the full content width (got {rule_len} cells)"
    );
}

#[test]
fn test_layout_strong_b_bold() {
    init();
    let html = "<p>alpha <strong>sbold</strong> <b>bravo</b></p>";
    let css = "";
    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 strong_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "s")
        .expect("strong text must render");
    let b_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "b")
        .expect("b text must render");
    let plain_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "a")
        .expect("plain text must render");
    assert!(
        tl.layout[strong_idx].style.contains(FontStyle::BOLD),
        "<strong> must be bold (got {:?})",
        tl.layout[strong_idx].style
    );
    assert!(
        tl.layout[b_idx].style.contains(FontStyle::BOLD),
        "<b> must be bold (got {:?})",
        tl.layout[b_idx].style
    );
    assert!(
        !tl.layout[plain_idx].style.contains(FontStyle::BOLD),
        "plain text must not be bold"
    );
}

#[test]
fn test_layout_text_semantics_styles() {
    init();
    // i → italic, u → underline, s → line-through, mark → yellow/black.
    // Each tag uses a distinct leading letter so the cell lookup is
    // unambiguous.
    let html = "<p><i>italic</i> <u>under</u> <s>strike</s> <mark>mark</mark></p>";
    let css = "";
    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 find = |word: &str| {
        tl.layout
            .iter()
            .position(|b| b.word == word)
            .unwrap_or_else(|| panic!("cell {word:?} must render"))
    };
    assert!(
        tl.layout[find("i")].style.contains(FontStyle::ITALIC),
        "<i> must be italic"
    );
    assert!(
        tl.layout[find("u")].style.contains(FontStyle::UNDERLINED),
        "<u> must be underlined"
    );
    assert!(
        tl.layout[find("s")].style.contains(FontStyle::CROSSED_OUT),
        "<s> must be line-through"
    );
    let mark_idx = find("m");
    // The UA default for `<mark>` resolves through the shared
    // `inline_ua_declarations` table (`background-color: yellow` → the named
    // colour's RGB value), the same source the block-level path injects into
    // `css_attr` — inline and block `<mark>` paint the identical truecolour
    // yellow.
    assert_eq!(
        tl.layout[mark_idx].bcolor,
        Some(Color::Rgb {
            r: 255,
            g: 255,
            b: 0
        }),
        "<mark> must paint the UA yellow background"
    );
    assert_eq!(
        tl.layout[mark_idx].fcolor,
        Some(Color::Rgb { r: 0, g: 0, b: 0 }),
        "<mark> must paint black foreground"
    );
}

#[test]
fn test_layout_edits_and_citation_styles() {
    init();
    // ins → underline, del → line-through, cite/dfn/var → italic.
    let html = "<p><ins>1</ins><del>2</del><cite>3</cite><dfn>4</dfn><var>5</var></p>";
    let css = "";
    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 find = |word: &str| {
        tl.layout
            .iter()
            .position(|b| b.word == word)
            .unwrap_or_else(|| panic!("cell {word:?} must render"))
    };
    assert!(
        tl.layout[find("1")].style.contains(FontStyle::UNDERLINED),
        "<ins> must be underlined"
    );
    assert!(
        tl.layout[find("2")].style.contains(FontStyle::CROSSED_OUT),
        "<del> must be line-through"
    );
    for word in ["3", "4", "5"] {
        assert!(
            tl.layout[find(word)].style.contains(FontStyle::ITALIC),
            "<cite>/<dfn>/<var> must be italic ({word})"
        );
    }
}

#[test]
fn test_layout_strong_font_weight_normal_disables_bold() {
    init();
    // Author CSS resetting the UA default must take effect.
    let html = "<p><strong>word</strong></p>";
    let css = "strong { font-weight: normal; }";
    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 idx = tl
        .layout
        .iter()
        .position(|b| b.word == "w")
        .expect("strong text must render");
    assert!(
        !tl.layout[idx].style.contains(FontStyle::BOLD),
        "`strong {{ font-weight: normal }}` must suppress the UA bold (got {:?})",
        tl.layout[idx].style
    );
}

#[test]
fn test_layout_code_kbd_samp_render_plain() {
    init();
    // code / kbd / samp keep their text (UA monospace = the terminal's
    // native font, so no style flag applies).
    let html = "<p><code>fn main()</code> <kbd>ctrl</kbd> <samp>out</samp></p>";
    let css = "";
    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("fn main()"), "code text must render");
    assert!(canvas.contains("ctrl"), "kbd text must render");
    assert!(canvas.contains("out"), "samp text must render");
}

#[test]
fn test_layout_code_css_color_applies() {
    init();
    // The tag is addressable by CSS even though its UA style is a no-op in
    // the terminal.
    let html = "<p><code>x</code></p>";
    let css = "code { color: magenta; }";
    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 idx = tl
        .layout
        .iter()
        .position(|b| b.word == "x")
        .expect("code text must render");
    assert_eq!(
        tl.layout[idx].fcolor,
        Some(Color::Rgb {
            r: 255,
            g: 0,
            b: 255
        }),
        "code {{ color: magenta }} must paint the cell magenta"
    );
}

#[test]
fn test_layout_br_forces_line_break() {
    init();
    // `<br>` must force a line break even under the default `white-space:
    // normal` (where a plain newline would collapse).
    let html = "<p>aaa<br>bbb</p>";
    let css = "";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let a_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "a")
        .expect("pre-br text must render");
    let b_idx = tl
        .layout
        .iter()
        .position(|b| b.word == "b")
        .expect("post-br text must render");
    assert!(b_idx / cols > a_idx / cols, "<br> must break the line");
    assert_eq!(
        b_idx % cols,
        a_idx % cols,
        "post-br text must start at the same column"
    );
}

// ============================================================
// Canvas background (<html>/<body> propagate to the full viewport)
// ============================================================

#[test]
fn test_body_background_fills_canvas() {
    init();
    // Browser semantics: a short page still paints the whole terminal with
    // the <body> background (transparent <html> falls back to <body>).
    let html = "<body><h1>Hi</h1></body>";
    let css = "body { background-color: blue; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let rows = tl.layout.len() / cols;
    let last_row = &tl.layout[(rows - 1) * cols];
    assert_eq!(
        last_row.bcolor,
        Some(Color::Rgb { r: 0, g: 0, b: 255 }),
        "body background must fill rows below the content"
    );
    assert_eq!(last_row.word, " ", "the fill must not add glyphs");
}

#[test]
fn test_html_background_wins_over_body_for_canvas() {
    init();
    // When both are set, the <html> background paints the canvas.
    let html = "<body><p>x</p></body>";
    let css = "html { background-color: green; } body { background-color: red; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let rows = tl.layout.len() / cols;
    let cell = &tl.layout[(rows - 1) * cols];
    assert_eq!(
        cell.bcolor,
        Some(Color::Rgb { r: 0, g: 128, b: 0 }),
        "<html> background must win over <body> for the canvas"
    );
}

#[test]
fn test_hsl_background_through_cascade_and_paint() {
    init();
    // A modern hsl() value must survive the cascade and paint the canvas via
    // the `background` shorthand alias.
    let html = "<body><p>x</p></body>";
    let css = "body { background: hsl(240, 100%, 50%); }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let rows = tl.layout.len() / cols;
    let cell = &tl.layout[(rows - 1) * cols];
    assert_eq!(
        cell.bcolor,
        Some(Color::Rgb { r: 0, g: 0, b: 255 }),
        "hsl() through the `background` shorthand must paint the canvas"
    );
}

#[test]
fn test_linear_gradient_background_paints_each_cell() {
    init();
    let html = "<div id='gradient'>ok</div>";
    let css = "#gradient { width: 20ch; height: 2; \
               background: linear-gradient(to right, red, blue); }";
    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 first = tl.layout[0].bcolor.expect("gradient start color");
    let last = tl.layout[19].bcolor.expect("gradient end color");
    assert_ne!(first, last);
    assert!(
        matches!(first, Color::Rgb { r, b, .. } if r > b),
        "the left edge should lean red, got {first:?}"
    );
    assert!(
        matches!(last, Color::Rgb { r, b, .. } if b > r),
        "the right edge should lean blue, got {last:?}"
    );
    assert!(tl.layout[..20].iter().all(|cell| cell.bcolor.is_some()));
}

#[test]
fn test_child_preserves_gradient_origin_from_parent() {
    init();
    let html = "<div id='gradient'><div>one</div><div>two</div></div>";
    let css = "#gradient { width: 20ch; height: 4ch; \
               background: linear-gradient(to bottom, red, blue); } \
               #gradient > div { height: 1ch; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let first = tl.layout[0].bcolor.expect("first child background");
    let second = tl.layout[cols].bcolor.expect("second child background");
    assert!(
        matches!((first, second), (
            Color::Rgb { b: first_b, .. },
            Color::Rgb { b: second_b, .. }
        ) if second_b > first_b),
        "child fills must continue the parent gradient: {first:?} -> {second:?}"
    );
}

#[test]
fn test_background_clip_text_paints_gradient_glyphs() {
    init();
    let html = "<div id='text'>AB</div>";
    let css = "#text { width: 2ch; color: transparent; \
               background: linear-gradient(to right, red, blue); \
               background-clip: text; }";
    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 first = tl.layout[0].fcolor.expect("first glyph color");
    let second = tl.layout[1].fcolor.expect("second glyph color");
    assert!(
        matches!(first, Color::Rgb { r, b, .. } if r > b)
            && matches!(second, Color::Rgb { r, b, .. } if b > r),
        "text gradient should progress from red to blue: {first:?} -> {second:?}"
    );
    assert!(
        tl.layout[..2].iter().all(|cell| cell.bcolor.is_none()),
        "background-clip: text must not paint the box background"
    );
}

#[test]
fn example_spectrum_stays_inside_sidebar_scroll_area() {
    init();
    let html = include_str!("../../../example/src/player.html")
        // The sidebar is edge-triggered in the live demo; make it visible for
        // this pure-layout regression test.
        .replace(
            "<div id=\"music-side\" class=\"side\" style=\"display:none\"",
            "<div id=\"music-side\" class=\"side\"",
        )
        .replace(
            "<div id=\"viz-l\" class=\"viz-pre\"> </div>",
            "<div id=\"viz-l\" class=\"viz-pre\">1&#9601;2&#9602;3&#9603;4&#9604;</div>",
        )
        .replace(
            "<div id=\"viz-r\" class=\"viz-pre\"> </div>",
            "<div id=\"viz-r\" class=\"viz-pre\">8&#9608;7&#9607;6&#9606;5&#9605;</div>",
        );
    let mut html_parser = html_parse::Parser::new(&html);
    let (root_id, base_arena, embedded_css) = html_parser.parse();

    for (cols, rows) in [(100, 30), (80, 24), (60, 20), (50, 20), (40, 20)] {
        let mut arena = base_arena.clone();
        let mut css_parser = css_parse::Parser::new(&embedded_css);
        let rules = css_parser.parse();
        css_parse::css_into_node_with_state(
            &mut arena,
            root_id,
            &rules,
            &css_parse::DynamicState {
                viewport: css_parse::Viewport { cols, rows },
                ..Default::default()
            },
        );
        let term_map = TermMap {
            columns: cols as u16,
            rows: rows as u16,
        };
        let mut tl = TermLayout::new(&term_map, 1.0);
        let boxes = tl.draw(&arena, root_id, &term_map);

        fn find<'a>(
            arena: &NodeArena,
            boxes: &'a [htui::layout::LayoutBox],
            class_name: &str,
        ) -> Option<&'a htui::layout::LayoutBox> {
            for lb in boxes {
                let class = arena[lb.node_id]
                    .attributes
                    .get("class")
                    .map(String::as_str)
                    .unwrap_or("");
                if class.split_whitespace().any(|part| part == class_name) {
                    return Some(lb);
                }
                if let Some(found) = find(arena, &lb.children, class_name) {
                    return Some(found);
                }
            }
            None
        }

        let side = find(&arena, &boxes, "side").expect("sidebar exists");
        let scroll = find(&arena, &boxes, "side-scroll").expect("sidebar scroll exists");
        let spectrum = find(&arena, &boxes, "spectrum-card").expect("spectrum card exists");
        let viz = find(&arena, &boxes, "viz-pre").expect("spectrum bars exist");

        assert!(
            scroll.rect.y.saturating_add(scroll.rect.height)
                <= side.rect.y.saturating_add(side.rect.height),
            "{cols}x{rows}: sidebar scroll must stay inside the sidebar"
        );
        assert!(
            spectrum.rect.y >= scroll.rect.y
                && spectrum.rect.y < scroll.rect.y.saturating_add(scroll.rect.height),
            "{cols}x{rows}: spectrum card must start inside the scroll viewport"
        );
        assert!(
            viz.rect.x.saturating_add(viz.rect.width)
                <= scroll.rect.x.saturating_add(scroll.rect.width),
            "{cols}x{rows}: spectrum must not paint outside the scroll area"
        );
    }
}