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
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
//! `<input>` field tests — replaced-element rendering, the pure text-editing
//! logic (`apply_input_key`), and the engine edit-state rendering path.
//!
//! The editing tests drive `apply_input_key` directly (no terminal, no event
//! loop); the render tests draw a small document and assert on the canvas.

use compact_str::CompactString;
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
use htui::events::EventBindings;
use htui::html::{css_parse, html_parse};
use htui::layout::layout::TermMap;
use htui::script::ScriptEngine;
use htui::tdom::node::{NodeArena, NodeId, NodeType};
use htui::tui::graph_api::Block;
use htui::tui::graph_api::{
    InputRenderState, InputState, TermLayout, apply_input_key, apply_input_word_key,
    collect_input_ids, is_input_field_key, key_event_info, next_word_boundary,
    number_input_allows_char, prev_word_boundary, selection_range,
};

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

fn setup(html: &str) -> (NodeId, NodeArena) {
    let mut html_parser = html_parse::Parser::new(html);
    let (root_id, mut arena, embedded) = html_parser.parse();
    if !embedded.trim().is_empty() {
        let mut css_parser = css_parse::Parser::new(&embedded);
        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,
    }
}

/// Render and return the per-row text strings for inspection.
fn render_rows(html: &str) -> (Vec<String>, TermLayout) {
    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;
    let mut rows: Vec<String> = Vec::new();
    for chunk in tl.layout.chunks(cols) {
        let s: String = chunk.iter().map(|b| b.word.as_str()).collect();
        rows.push(s);
    }
    (rows, tl)
}

/// Layout the document into a box tree (for geometry assertions).
fn layout_boxes(arena: &NodeArena, root: NodeId) -> Vec<htui::layout::LayoutBox> {
    use htui::layout::{BoxConstraint, Cursor, layout_tree};
    let containing = BoxConstraint::root(&mock_term_map());
    let mut cursor = Cursor::new();
    layout_tree(
        arena,
        root,
        containing,
        &mut cursor,
        COLS as usize,
        ROWS as usize,
    )
}

/// Depth-first search for the first box belonging to `node_id`.
fn find_box(
    boxes: &[htui::layout::LayoutBox],
    node_id: NodeId,
) -> Option<&htui::layout::LayoutBox> {
    for b in boxes {
        if b.node_id == node_id {
            return Some(b);
        }
        if let Some(found) = find_box(&b.children, node_id) {
            return Some(found);
        }
    }
    None
}

#[test]
fn select_renders_as_field_with_current_label() {
    init();
    // A `<select>` draws a background-filled field showing the option that
    // matches the `value` attribute (falling back to the first option).
    let (rows, _) = render_rows(
        r#"<div><select value="b"><option>A</option><option value="b">BB</option></select></div>"#,
    );
    let r = &rows[0];
    assert!(
        r.contains("BB"),
        "select must show the selected option; row={r:?}"
    );
}

#[test]
fn select_renders_first_option_without_value() {
    init();
    // No `value` attribute → the first option is shown.
    let (rows, _) =
        render_rows(r#"<div><select><option>Alpha</option><option>Beta</option></select></div>"#);
    let r = &rows[0];
    assert!(
        r.contains("Alpha"),
        "select must fall back to the first option; row={r:?}"
    );
}

/// Find the first node with `node_type == NodeType::Input`.
fn find_input(arena: &NodeArena, root: NodeId) -> NodeId {
    let mut stack = vec![root];
    while let Some(id) = stack.pop() {
        let node = &arena[id];
        if node.node_type == NodeType::Input {
            return id;
        }
        stack.extend(node.children.iter().copied());
    }
    panic!("no <input> in document");
}

fn find_textarea(arena: &NodeArena, root: NodeId) -> NodeId {
    let mut stack = vec![root];
    while let Some(id) = stack.pop() {
        let node = &arena[id];
        if node.node_type == NodeType::Textarea {
            return id;
        }
        stack.extend(node.children.iter().copied());
    }
    panic!("no <textarea> in document");
}

#[test]
fn selection_range_orders_anchor_and_caret() {
    // Anchor may sit on either side of the caret; the range is always ordered.
    assert_eq!(selection_range(1, 4), (1, 4));
    assert_eq!(selection_range(4, 1), (1, 4));
    assert_eq!(selection_range(2, 2), (2, 2));
}

#[test]
fn input_renders_selection_highlight() {
    init();
    let (root_id, arena) = setup(r#"<div><input></div>"#);
    let input_id = find_input(&arena, root_id);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.input_states.insert(
        input_id,
        InputRenderState {
            value: "hello".into(),
            cursor: 4,
            focused: true,
            selection: Some((1, 4)),
        },
    );
    tl.draw(&arena, root_id, &term_map);
    // Cells: `h e l l o` (cols 0-4) on the default grey field background.
    // Selection (1..4) = `ell` (cols 1-3) get the Tokyo Night selection
    // blue; the caret sits on `o` (inverted) and the unselected `h` keeps
    // the field's default background.
    let cell = |x: usize| -> &Block { &tl.layout[x] };
    assert_eq!(cell(0).word, "h");
    assert_eq!(
        cell(0).bcolor,
        Some(crossterm::style::Color::DarkGrey),
        "unselected char sits on the default control background"
    );
    assert_eq!(
        cell(1).bcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0x3b,
            g: 0x42,
            b: 0x61,
        }),
        "selected char gets the highlight bg"
    );
    assert_eq!(cell(3).bcolor, cell(1).bcolor, "selection is contiguous");
    assert_eq!(
        cell(4).bcolor,
        Some(crossterm::style::Color::White),
        "caret cell stays inverted"
    );
}

#[test]
fn input_renders_empty_field_without_panicking() {
    init();
    // An `<input>` with no `value` renders an empty background-filled field —
    // the caret window must not index past the empty character vector.
    let (rows, _) = render_rows(r#"<div><input></div>"#);
    assert!(
        rows[0].chars().take(8).all(|c| c == ' '),
        "empty field paints 8 blank cells; row={:?}",
        rows[0]
    );
}

#[test]
fn input_long_value_windows_around_the_caret() {
    init();
    // Width 8 (6 content cells), value much longer: the visible window must
    // follow the caret so a long value remains visible.
    let (root_id, arena) = setup(r#"<div><input width="8"></div>"#);
    let input_id = find_input(&arena, root_id);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.input_states.insert(
        input_id,
        InputRenderState {
            value: "abcdefghijkl".into(),
            cursor: 12,
            focused: true,
            selection: None,
        },
    );
    tl.draw(&arena, root_id, &term_map);
    // Caret at the end (a blank inverted cell): the window follows the caret
    // and shows `fghijkl` (indices 5..12 of "abcdefghijkl") + the caret cell
    // across the field's full 8-cell width.
    let row: String = tl.layout.iter().take(8).map(|b| b.word.as_str()).collect();
    assert_eq!(row, "fghijkl ");
}

#[test]
fn input_renders_multibyte_values_at_display_width() {
    init();
    let (rows, _) = render_rows(r#"<div><input value="你好"></div>"#);
    // CJK glyphs occupy two columns each: the renderer skips their second
    // (empty-word) cells, so the field reads `你好    ` (wide glyphs then
    // blank filler to the default 8-cell width).
    let r = &rows[0];
    assert_eq!(r.chars().next(), Some('你'));
    assert_eq!(r.chars().nth(1), Some('好'));
    assert_eq!(r.chars().nth(2), Some(' '), "filler after the wide glyphs");
    assert_eq!(r.chars().nth(7), Some(' '), "field stays 8 cells wide");
}

#[test]
fn set_value_commits_edited_value_to_the_dom_and_marks_dirty() {
    // The blur path writes the edited value back into the DOM `value`
    // attribute (single source of truth) and marks the node dirty, so the
    // commit always reaches the render thread as a `RenderArena` — a JS blur
    // handler that rewrites the value (e.g. clearing a submitted box) is what
    // ends up on screen. Committing an unchanged value is a no-op.
    init();
    let mut engine = ScriptEngine::new(
        r#"<div><input value="initial"></div>"#,
        "",
        EventBindings::default(),
    )
    .expect("engine");
    let input_id = find_input(&engine.arena(), engine.root_id());

    engine.set_value(input_id, "edited");

    assert!(
        engine.take_dirty().nodes.contains(&input_id),
        "set_value must mark the node dirty"
    );
    let stored = engine
        .arena()
        .get(input_id)
        .and_then(|n| n.attributes.get("value"))
        .cloned();
    assert_eq!(stored.as_deref(), Some("edited"));

    engine.set_value(input_id, "edited");
    assert!(
        engine.take_dirty().is_empty(),
        "committing the same value again must not mark dirty"
    );
}

#[test]
fn layout_drops_unfocused_input_state_but_keeps_focused() {
    init();
    let (root_id, arena) = setup(r#"<div><input value="hi"></div>"#);
    let input_id = find_input(&arena, root_id);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);

    // A stale unfocused cache entry (the transient blur repaint) must not
    // survive a fresh layout: the arena's `value` attribute is the display
    // truth for unfocused fields.
    tl.input_states.insert(
        input_id,
        InputRenderState {
            value: "stale".into(),
            cursor: 0,
            focused: false,
            selection: None,
        },
    );
    tl.draw(&arena, root_id, &term_map);
    assert!(
        !tl.input_states.contains_key(&input_id),
        "layout must drop stale unfocused entries"
    );
    let row: String = tl.layout.iter().take(8).map(|b| b.word.as_str()).collect();
    assert_eq!(row, "hi      ", "unfocused field paints the DOM value");

    // A focused entry holds the live edit buffer and must survive layout.
    tl.input_states.insert(
        input_id,
        InputRenderState {
            value: "typing".into(),
            cursor: 5,
            focused: true,
            selection: None,
        },
    );
    tl.draw(&arena, root_id, &term_map);
    assert!(
        tl.input_states.contains_key(&input_id),
        "focused edit state must survive layout"
    );
    let row: String = tl.layout.iter().take(8).map(|b| b.word.as_str()).collect();
    assert_eq!(row, "typing  ", "focused field paints the live edit buffer");
}

#[test]
fn input_renders_as_field_with_value() {
    init();
    let (rows, _) = render_rows(r#"<div><input value="hi"></div>"#);
    // Default field width = 8 cells (tappable minimum); the value fills the
    // content area from the left edge (no bracket frame).
    assert_eq!(rows[0].chars().next(), Some('h'));
    assert_eq!(rows[0].chars().nth(1), Some('i'));
    assert_eq!(rows[0].chars().nth(7), Some(' '), "field is 8 cells wide");
    assert_eq!(rows[0].chars().nth(8), Some(' '), "field must not overflow");
}

#[test]
fn input_respects_width_attribute() {
    init();
    let (rows, _) = render_rows(r#"<div><input width="4" value="abc"></div>"#);
    // width=4 cells of content, no bracket columns. The caret starts at
    // position 0, so the window shows `abc` + one blank cell.
    assert_eq!(rows[0].chars().next(), Some('a'));
    assert_eq!(rows[0].chars().nth(1), Some('b'));
    assert_eq!(rows[0].chars().nth(2), Some('c'));
    assert_eq!(rows[0].chars().nth(3), Some(' '), "field is 4 cells wide");
}

#[test]
fn input_field_key_classifies_editing_keys() {
    // A focused `<input>` owns the editing / caret keys — even when they are
    // boundary no-ops (Home at the start) — but not page navigation (↓ / ↑ /
    // PageDown / PageUp), which must fall through to scrolling while the
    // field stays focused.
    assert!(is_input_field_key(KeyCode::Char('a')));
    assert!(is_input_field_key(KeyCode::Backspace));
    assert!(is_input_field_key(KeyCode::Delete));
    assert!(is_input_field_key(KeyCode::Left));
    assert!(is_input_field_key(KeyCode::Right));
    assert!(is_input_field_key(KeyCode::Home));
    assert!(is_input_field_key(KeyCode::End));
    assert!(!is_input_field_key(KeyCode::Down));
    assert!(!is_input_field_key(KeyCode::Up));
    assert!(!is_input_field_key(KeyCode::PageDown));
    assert!(!is_input_field_key(KeyCode::PageUp));
    assert!(!is_input_field_key(KeyCode::Enter));
    assert!(!is_input_field_key(KeyCode::F(1)));
}

#[test]
fn apply_input_key_inserts_removes_and_moves() {
    let mut value = CompactString::from("hello");
    let mut cursor = 5;

    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Char('!')));
    assert_eq!(value, "hello!");
    assert_eq!(cursor, 6);

    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Backspace));
    assert_eq!(value, "hello");
    assert_eq!(cursor, 5);

    // Left + insert in the middle.
    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Left));
    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Char('X')));
    assert_eq!(value, "hellXo");
    assert_eq!(cursor, 5);

    // Delete removes the char right of the caret.
    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Delete));
    assert_eq!(value, "hellX");
}

#[test]
fn apply_input_key_home_end_and_limits() {
    let mut value = CompactString::from("ab");
    let mut cursor = 2;

    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Home));
    assert_eq!(cursor, 0);
    // At the start, Left / Backspace are no-ops.
    assert!(!apply_input_key(&mut value, &mut cursor, KeyCode::Left));
    assert!(!apply_input_key(
        &mut value,
        &mut cursor,
        KeyCode::Backspace
    ));

    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::End));
    assert_eq!(cursor, 2);
    assert!(!apply_input_key(&mut value, &mut cursor, KeyCode::Right));
    assert!(!apply_input_key(&mut value, &mut cursor, KeyCode::Delete));

    // Enter / Esc are not consumed by the editor.
    assert!(!apply_input_key(&mut value, &mut cursor, KeyCode::Enter));
    assert!(!apply_input_key(&mut value, &mut cursor, KeyCode::Esc));
}

#[test]
fn apply_input_key_handles_multibyte_chars() {
    // Caret is a character index; multi-byte characters must stay intact.
    let mut value = CompactString::from("你好");
    let mut cursor = 0;

    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Char('!')));
    assert_eq!(value, "!你好");
    assert_eq!(cursor, 1);

    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Backspace));
    assert_eq!(value, "你好");
    assert_eq!(cursor, 0);

    // Move to the end and delete the last (multi-byte) char.
    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::End));
    assert!(apply_input_key(&mut value, &mut cursor, KeyCode::Backspace));
    assert_eq!(value, "你");
    assert_eq!(cursor, 1);
}

#[test]
fn engine_input_state_renders_value_and_caret() {
    init();
    let (root_id, arena) = setup(r#"<div><input value="initial"></div>"#);
    let input_id = find_input(&arena, root_id);

    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.input_states.insert(
        input_id,
        InputRenderState {
            value: "abc".into(),
            cursor: 1,
            focused: true,
            selection: None,
        },
    );
    tl.draw(&arena, root_id, &term_map);

    // Field shows the engine value `abc`, caret inverts the char at index 1.
    let cell = |x: usize| -> &Block { &tl.layout[x] };
    assert_eq!(cell(0).word, "a");
    assert_eq!(cell(1).word, "b");
    assert_eq!(cell(2).word, "c");
    // Default field width is fixed at 8 cells, independent of the value.
    assert_eq!(cell(7).word, " ");
    // The unselected `a` sits on the default control grey; the caret cell
    // (char index 1 → column 1) is inverted to black-on-white.
    assert_eq!(cell(0).fcolor, None);
    assert_eq!(cell(0).bcolor, Some(crossterm::style::Color::DarkGrey));
    assert_eq!(cell(1).bcolor, Some(crossterm::style::Color::White));
}

#[test]
fn input_caret_color_paints_the_caret_cell() {
    init();
    // `caret-color: red` paints the focused field's caret block red instead
    // of the default inverted cell.
    let (root_id, arena) =
        setup(r#"<div><input value="initial"></div><style>input { caret-color: red; }</style>"#);
    let input_id = find_input(&arena, root_id);

    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.input_states.insert(
        input_id,
        InputRenderState {
            value: "abc".into(),
            cursor: 1,
            focused: true,
            selection: None,
        },
    );
    tl.draw(&arena, root_id, &term_map);

    let cell = |x: usize| -> &Block { &tl.layout[x] };
    // Caret on char index 1 → column 1: its background is the declared colour.
    assert_eq!(
        cell(1).bcolor,
        Some(crossterm::style::Color::Rgb { r: 255, g: 0, b: 0 }),
        "caret cell must take the caret-color"
    );
    // Non-caret cells keep the field's default background.
    assert_eq!(cell(0).bcolor, Some(crossterm::style::Color::DarkGrey));
}

#[test]
fn textarea_caret_color_paints_the_caret_cell() {
    init();
    // `caret-color: blue` colours the `<textarea>` caret block.
    let (root_id, arena) = setup(
        r#"<div><textarea rows="3">initial</textarea></div>
            <style>textarea { caret-color: blue; }</style>"#,
    );
    let textarea_id = find_textarea(&arena, root_id);

    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.input_states.insert(
        textarea_id,
        InputRenderState {
            value: "hi".into(),
            cursor: 1,
            focused: true,
            selection: None,
        },
    );
    tl.draw(&arena, root_id, &term_map);

    let cols = term_map.columns as usize;
    // No border: content starts at row 0, column 0 of the field.
    let cell = |x: usize, y: usize| -> &Block { &tl.layout[y * cols + x] };
    assert_eq!(
        cell(1, 0).bcolor,
        Some(crossterm::style::Color::Rgb { r: 0, g: 0, b: 255 }),
        "caret cell must take the caret-color"
    );
}

#[test]
fn word_boundaries_match_browser_semantics() {
    // `Ctrl`/`Alt`+←/→ word navigation: boundaries fall between word runs and
    // non-word / whitespace runs (browser / vim `b` / `w` semantics).
    let s = "hello brave new world";
    assert_eq!(
        prev_word_boundary(s, 11),
        6,
        "back to the previous word start"
    );
    assert_eq!(next_word_boundary(s, 0), 5, "forward to the next word end");
    assert_eq!(
        next_word_boundary(s, 5),
        11,
        "whitespace + the next word are covered in one step (browser semantics)"
    );
    assert_eq!(prev_word_boundary(s, 6), 0, "back over a leading word");

    // Punctuation counts as a non-word run (a single boundary hop).
    assert_eq!(prev_word_boundary("a,b", 2), 1, "stop before the comma");
    assert_eq!(next_word_boundary("a,b", 0), 1, "stop after `a`");

    // Clamping at the string ends.
    assert_eq!(prev_word_boundary("ab", 0), 0);
    assert_eq!(next_word_boundary("ab", 2), 2);
    assert_eq!(prev_word_boundary("", 0), 0);
    assert_eq!(next_word_boundary("", 0), 0);
}

#[test]
fn apply_word_key_moves_caret_by_word() {
    let mut value = CompactString::from("hello brave new world");
    let mut cursor = 0;
    let mut anchor = None;

    // Ctrl+Right jumps to the end of the next word.
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Right,
        KeyModifiers::CONTROL,
    ));
    assert_eq!(cursor, 5);
    // Ctrl+Left returns to the previous word start.
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Left,
        KeyModifiers::CONTROL,
    ));
    assert_eq!(cursor, 0);
    // Alt+Left is accepted as a word move too (mac muscle memory).
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Right,
        KeyModifiers::ALT,
    ));
    assert_eq!(cursor, 5);
    // Boundary no-ops report `false` (caret already at the start).
    cursor = 0;
    assert!(!apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Left,
        KeyModifiers::ALT,
    ));
    assert_eq!(cursor, 0);
}

#[test]
fn apply_word_key_deletes_by_word() {
    // Ctrl+Backspace removes the word before the caret.
    let mut value = CompactString::from("hello world");
    let mut cursor = 11;
    let mut anchor = None;
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Backspace,
        KeyModifiers::CONTROL,
    ));
    assert_eq!(value, "hello ");
    assert_eq!(cursor, 6, "caret lands on the deleted word's start");

    // Ctrl+Delete removes the word after the caret.
    let mut value = CompactString::from("hello world");
    let mut cursor = 6;
    let mut anchor = None;
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Delete,
        KeyModifiers::CONTROL,
    ));
    assert_eq!(value, "hello ");
    assert_eq!(cursor, 6);

    // Ctrl+Home / Ctrl+End jump to the line edges (browser caret movement).
    let mut value = CompactString::from("abc def");
    let mut cursor = 3;
    let mut anchor = None;
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Home,
        KeyModifiers::CONTROL,
    ));
    assert_eq!(cursor, 0);
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::End,
        KeyModifiers::CONTROL,
    ));
    assert_eq!(cursor, 7);
}

#[test]
fn apply_word_key_shift_extends_the_selection() {
    // Shift+Ctrl+Right selects from the original caret to the next word end.
    let mut value = CompactString::from("hello brave");
    let mut cursor = 0;
    let mut anchor = None;
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Right,
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ));
    assert_eq!(cursor, 5);
    assert_eq!(anchor, Some(0), "selection anchor stays at the start");

    // A second word move extends the selection further: the whitespace run
    // and the next word are covered in one step (browser semantics).
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Right,
        KeyModifiers::CONTROL | KeyModifiers::SHIFT,
    ));
    assert_eq!(cursor, 11);
    assert_eq!(anchor, Some(0));

    // A plain word move (no Shift) drops the selection.
    assert!(apply_input_word_key(
        &mut value,
        &mut cursor,
        &mut anchor,
        KeyCode::Left,
        KeyModifiers::CONTROL,
    ));
    assert_eq!(anchor, None, "plain navigation clears the selection");
}

#[test]
fn collect_input_ids_returns_document_order() {
    init();
    let (root_id, arena) =
        setup(r#"<div><input id="first"><p><input id="second"><input id="third"></p></div>"#);
    let ids = collect_input_ids(&arena);
    let labels: Vec<&str> = ids
        .iter()
        .map(|&id| {
            arena[id]
                .attributes
                .get("id")
                .map(String::as_str)
                .unwrap_or("?")
        })
        .collect();
    assert_eq!(
        labels,
        vec!["first", "second", "third"],
        "Tab order follows DOM order"
    );
    assert!(ids.iter().all(|&id| id != root_id), "root is not an input");
}

#[test]
fn key_event_info_maps_every_key_to_browser_fields() {
    // The crossterm → `KeyEventInfo` conversion keeps the browser vocabulary:
    // pages branch on the same `key` / `code` / `keyCode` strings as in a real
    // browser.
    let mut info = key_event_info(&KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
    assert_eq!(info.key, "a");
    assert_eq!(info.code, "KeyA");
    assert_eq!(info.key_code, 'a' as u32);
    assert!(!info.ctrl && !info.shift && !info.alt && !info.meta && !info.repeat);

    info = key_event_info(&KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE));
    assert_eq!(info.key, " ");
    assert_eq!(info.code, "Space");
    assert_eq!(info.key_code, 32);

    info = key_event_info(&KeyEvent::new(KeyCode::Char('5'), KeyModifiers::NONE));
    assert_eq!(info.code, "Digit5");

    info = key_event_info(&KeyEvent::new(KeyCode::Up, KeyModifiers::SHIFT));
    assert_eq!(info.key, "ArrowUp");
    assert_eq!(info.key_code, 38);
    assert!(info.shift);

    info = key_event_info(&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
    assert_eq!((info.key.as_str(), info.key_code), ("Enter", 13));

    info = key_event_info(&KeyEvent::new(KeyCode::F(5), KeyModifiers::NONE));
    assert_eq!(
        (info.key.as_str(), info.code.as_str(), info.key_code),
        ("F5", "F5", 116)
    );

    info = key_event_info(&KeyEvent::new(KeyCode::Esc, KeyModifiers::CONTROL));
    assert_eq!(info.key, "Escape");
    assert!(info.ctrl);

    // A repeated press is flagged for JS (`event.repeat`).
    let ev = KeyEvent {
        code: KeyCode::Char('x'),
        modifiers: KeyModifiers::NONE,
        kind: KeyEventKind::Repeat,
        state: KeyEventState::empty(),
    };
    info = key_event_info(&ev);
    assert!(
        info.repeat,
        "repeat presses must be visible to JS listeners"
    );
}

#[test]
fn input_state_clamps_scroll_to_the_content_ceiling() {
    // Growing the terminal or reloading a shorter document can lower
    // `max_scroll` below the current scroll position. The input loop must
    // follow the render thread's clamp or every wheel / arrow `Rerender` is
    // clamped to the same value in the render thread and dropped as a no-op —
    // the scroll wheel appears dead after a resize.
    let mut state = InputState::new();
    state.scroll_y = 60; // scrolled to the bottom of a 100-row doc @ 24 rows
    state.clamp_scroll_to(76); // ceiling above the position: no clamp
    assert_eq!(state.scroll_y, 60);
    state.clamp_scroll_to(60); // terminal grew to 40 rows: ceiling at 60
    assert_eq!(state.scroll_y, 60);
    state.clamp_scroll_to(59); // grew further / shorter reload: ceiling drops
    assert_eq!(state.scroll_y, 59);

    // The u32::MAX startup placeholder must never clamp a fresh session.
    let mut fresh = InputState::new();
    fresh.scroll_y = 5;
    fresh.clamp_scroll_to(u32::MAX);
    assert_eq!(fresh.scroll_y, 5);
}

// ============================================================
// `<input type=button|submit|reset>` — push-button inputs
// ============================================================

#[test]
fn input_button_types_render_as_buttons() {
    init();
    // `button` / `submit` / `reset` paint a background-filled button with the
    // label centred (browser style); the label comes from the `value`
    // attribute. Each inline replaced element claims its own row (the
    // engine's flow semantics).
    let (rows, _) = render_rows(
        r#"<div><input type="button" value="X"><input type="submit" value="Save"><input type="reset" value="Clear"></div>"#,
    );
    assert_eq!(
        rows[0].trim(),
        "X",
        "button input paints its label centred; row={:?}",
        rows[0]
    );
    assert_eq!(
        rows[1].trim(),
        "Save",
        "submit input paints its value label; row={:?}",
        rows[1]
    );
    assert_eq!(
        rows[2].trim(),
        "Clear",
        "reset input paints its value label; row={:?}",
        rows[2]
    );
}

#[test]
fn input_button_default_labels_submit_reset() {
    init();
    // No `value` attribute → the browser default labels `Submit` / `Reset`.
    let (rows, _) = render_rows(r#"<div><input type="submit"><input type="reset"></div>"#);
    assert_eq!(
        rows[0].trim(),
        "Submit",
        "default submit label; row={:?}",
        rows[0]
    );
    assert_eq!(
        rows[1].trim(),
        "Reset",
        "default reset label; row={:?}",
        rows[1]
    );
}

#[test]
fn input_button_geometry_sizes_from_label() {
    init();
    // The button input width adapts to its label, like `<button>`
    // — not the fixed `width` attribute used for text fields.
    let (root_id, arena) = setup(
        r#"<div><input id="sub" type="submit" value="Go"><input id="txt" type="text" width="20"></div>"#,
    );
    let boxes = layout_boxes(&arena, root_id);
    let id_of = |id: &str| {
        arena
            .iter()
            .find(|(_, n)| n.attributes.get("id").map(String::as_str) == Some(id))
            .map(|(nid, _)| nid)
            .expect(id)
    };
    let submit = find_box(&boxes, id_of("sub")).expect("submit box");
    assert_eq!(
        submit.rect.width, 6,
        "`Go` button is 6 columns (label + padding)"
    );
    let text = find_box(&boxes, id_of("txt")).expect("text box");
    assert_eq!(text.rect.width, 20, "text field keeps the width attribute");
}

#[test]
fn input_button_skipped_by_tab_focus_cycle() {
    init();
    // Button inputs activate on click only — they are not text fields, so
    // `Tab` focus cycling must skip them.
    let (_, arena) = setup(
        r#"<div><input id="a" type="text"><input type="submit"><input type="button" value="X"><input id="b" type="text"></div>"#,
    );
    let ids = collect_input_ids(&arena);
    let labels: Vec<&str> = ids
        .iter()
        .map(|&id| {
            arena[id]
                .attributes
                .get("id")
                .map(String::as_str)
                .unwrap_or("?")
        })
        .collect();
    assert_eq!(
        labels,
        vec!["a", "b"],
        "button inputs must not enter the text-field tab order"
    );
}

// ============================================================
// placeholder / disabled / number
// ============================================================

#[test]
fn input_placeholder_shows_dimmed_hint_when_empty() {
    init();
    // An empty field with a `placeholder` attribute shows the hint text in
    // grey (the field is unfocused, so no value/caret either).
    let (_, tl) = render_rows(r#"<div><input placeholder="Type here" width="20"></div>"#);
    let hint_cells: Vec<&Block> = tl.layout.iter().filter(|b| !b.word.is_empty()).collect();
    let text: String = hint_cells.iter().map(|b| b.word.as_str()).collect();
    let text = text.trim();
    assert_eq!(
        text, "Type here",
        "placeholder must render in the empty field"
    );
    // Every non-space placeholder glyph (the frame and blank padding cells
    // keep their own colours) must be dimmed grey.
    assert!(
        hint_cells
            .iter()
            .filter(|b| b.word != " ")
            .all(|b| b.fcolor == Some(crossterm::style::Color::DarkGrey)),
        "placeholder hint must be dimmed grey"
    );
}

#[test]
fn input_placeholder_hidden_when_value_present() {
    init();
    // A non-empty `value` wins over the placeholder hint.
    let (_, tl) = render_rows(r#"<div><input placeholder="hint" value="val"></div>"#);
    let text: String = tl
        .layout
        .iter()
        .filter(|b| !b.word.is_empty() && b.word != " ")
        .map(|b| b.word.as_str())
        .collect();
    assert_eq!(text, "val", "the value renders, not the placeholder");
}

#[test]
fn input_disabled_field_is_dimmed() {
    init();
    // A `disabled` text field dims its frame and value (grey) like a disabled
    // `<button>`.
    let (_, tl) = render_rows(r#"<div><input disabled value="off"></div>"#);
    let cells: Vec<&Block> = tl
        .layout
        .iter()
        .filter(|b| !b.word.is_empty() && b.word != " ")
        .collect();
    let text: String = cells.iter().map(|b| b.word.as_str()).collect();
    assert_eq!(text, "off", "disabled field keeps its value");
    assert!(
        cells
            .iter()
            .all(|b| b.fcolor == Some(crossterm::style::Color::DarkGrey)),
        "disabled field must be dimmed grey"
    );
}

#[test]
fn number_input_character_filter_matches_browser() {
    init();
    // The number-editor character set: digits plus sign / decimal / exponent
    // markers. Letters and other symbols are rejected.
    for ok in ['0', '9', '-', '+', '.', 'e', 'E'] {
        assert!(number_input_allows_char(ok), "{ok:?} must be accepted");
    }
    for bad in ['a', 'x', '_', ' ', ',', '#', '你'] {
        assert!(!number_input_allows_char(bad), "{bad:?} must be rejected");
    }
}

#[test]
fn input_checkbox_radio_disabled_is_dimmed() {
    init();
    // A disabled toggle paints its glyph in grey (clicks are already
    // swallowed); the enabled one keeps its normal colour. Both controls are
    // block-level: the checkbox fills row 0, the radio row 1.
    let (rows, tl) = render_rows(
        r#"<div><input id="c" type="checkbox" disabled><input id="r" type="radio" disabled checked></div>"#,
    );
    let dark = crossterm::style::Color::DarkGrey;
    let cols = COLS as usize;
    let head = |row: &str| row.chars().take(2).collect::<String>();
    assert_eq!(head(&rows[0]), "□ ");
    assert_eq!(head(&rows[1]), "● ");
    let glyph_idx: [usize; 4] = [0, 1, cols, cols + 1];
    assert!(
        glyph_idx.iter().all(|&i| tl.layout[i].fcolor == Some(dark)),
        "disabled toggles must be dimmed grey"
    );
}

#[test]
fn input_image_renders_as_button() {
    init();
    // `image` is a button-shaped control: it paints its label on the filled
    // background (the browser's own look) even though the terminal has no
    // image — the label comes from its `value` / `alt` with a default
    // fallback.
    let (rows, _) = render_rows(
        r#"<div><input type="image" value="Go"><input type="image" alt="Logo"><input type="image"></div>"#,
    );
    assert_eq!(
        rows[0].trim(),
        "Go",
        "image input uses its value label; row={:?}",
        rows[0]
    );
    assert_eq!(
        rows[1].trim(),
        "Logo",
        "image input falls back to alt; row={:?}",
        rows[1]
    );
    assert_eq!(
        rows[2].trim(),
        "Submit Query",
        "image input defaults to `Submit Query`; row={:?}",
        rows[2]
    );
}

#[test]
fn input_honours_css_size_and_margin_auto() {
    init();
    // CSS `width` / `height` size the control (border-box, px → cells at
    // 8 px per cell), and `margin: 0 auto` centres it in the containing
    // block — the browser-replaced-element sizing chain a plain HTML
    // `width` attribute could not express.
    let (root_id, arena) =
        setup(r#"<style>input { width: 16px; height: 24px; margin: 0 auto; }</style><input>"#);
    let boxes = layout_boxes(&arena, root_id);
    let input = find_input(&arena, root_id);
    let r = find_box(&boxes, input).expect("input box");
    assert_eq!(r.rect.width, 2, "16px resolves to 2 cells");
    assert_eq!(r.rect.height, 3, "24px resolves to 3 rows");
    assert_eq!(
        r.rect.x,
        (COLS as usize - 2) / 2,
        "auto horizontal margins must centre the field"
    );
}

#[test]
fn textarea_css_size_overrides_cols_rows() {
    init();
    // A declared CSS `width` / `height` beats the `cols` / `rows`
    // attributes (browser cascade: CSS beats presentational attributes).
    let (root_id, arena) = setup(
        r#"<style>textarea { width: 40px; height: 16px; }</style><textarea cols="60" rows="8"></textarea>"#,
    );
    let boxes = layout_boxes(&arena, root_id);
    let textarea = find_textarea(&arena, root_id);
    let r = find_box(&boxes, textarea).expect("textarea box");
    assert_eq!(r.rect.width, 5, "40px resolves to 5 cells");
    assert_eq!(r.rect.height, 2, "16px resolves to 2 rows");
}

#[test]
fn input_min_width_beats_max_width_when_they_conflict() {
    init();
    // CSS: when min-width exceeds max-width, the minimum wins (the clamps
    // apply max first, min last).
    let (root_id, arena) =
        setup(r#"<style>input { width: 8px; max-width: 8px; min-width: 24px; }</style><input>"#);
    let boxes = layout_boxes(&arena, root_id);
    let input = find_input(&arena, root_id);
    let r = find_box(&boxes, input).expect("input box");
    assert_eq!(
        r.rect.width, 3,
        "24px min-width must win over 8px max-width"
    );
}

#[test]
fn input_without_css_keeps_attribute_or_default_size() {
    init();
    // No CSS declared: the HTML `width` attribute (cells) still wins, and
    // without either the historical 8-cell default applies — the control
    // sits at the container's left edge (no auto margins to centre it).
    let (root_id, arena) = setup(r#"<input width="12">"#);
    let boxes = layout_boxes(&arena, root_id);
    let input = find_input(&arena, root_id);
    let r = find_box(&boxes, input).expect("input box");
    assert_eq!(r.rect.width, 12);
    assert_eq!(r.rect.height, 1);
    assert_eq!(r.rect.x, 0);

    let (root_id, arena) = setup(r#"<input>"#);
    let boxes = layout_boxes(&arena, root_id);
    let input = find_input(&arena, root_id);
    let r = find_box(&boxes, input).expect("default input box");
    assert_eq!(r.rect.width, 8);
    assert_eq!(r.rect.x, 0);
}

#[test]
fn collect_input_ids_includes_range_sliders() {
    init();
    let (root, arena) = setup(
        r#"<input value="text"><input type="range" min="0" max="4" value="2"><input type="checkbox">"#,
    );
    let ids = collect_input_ids(&arena);
    assert_eq!(
        ids.len(),
        2,
        "text and range are focusable; checkbox is not"
    );
    assert_ne!(ids[0], ids[1]);
    let _ = root;
}

#[test]
fn range_input_renders_track_and_thumb() {
    init();
    let (rows, _) =
        render_rows(r#"<input type="range" min="0" max="4" step="1" value="2" width="9">"#);
    let slider: String = rows[0].chars().take(9).collect();
    assert_eq!(
        slider, "\u{2501}\u{2501}\u{2501}\u{2501}\u{25CF}\u{2500}\u{2500}\u{2500}\u{2500}",
        "value 2 of 4 places the thumb halfway across a 9-cell track"
    );
}

#[test]
fn range_pseudo_element_webkit_thumb_color() {
    init();
    let html = r#"<style>
        input::-webkit-slider-thumb { background-color: #ff0000; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x]; // row 0 where the slider paints
    // Thumb is at column 4 (value 2 of 4 across 9 cells); it should be red.
    assert_eq!(
        cell(4).fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0xff,
            g: 0x00,
            b: 0x00
        }),
        "::-webkit-slider-thumb background-color colours the thumb"
    );
}

#[test]
fn range_pseudo_element_moz_thumb_color() {
    init();
    let html = r#"<style>
        input::-moz-range-thumb { background-color: #00ff00; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x];
    assert_eq!(
        cell(4).fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0x00,
            g: 0xff,
            b: 0x00
        }),
        "::-moz-range-thumb background-color colours the thumb"
    );
}

#[test]
fn range_unfilled_track_stays_neutral_with_accent_color() {
    init();
    let html = r#"<style>
        input { accent-color: #43e5a0; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let accent = crossterm::style::Color::Rgb {
        r: 0x43,
        g: 0xe5,
        b: 0xa0,
    };
    assert_eq!(
        tl.layout[0].fcolor,
        Some(accent),
        "the filled track takes accent-color"
    );
    assert_ne!(
        tl.layout[8].fcolor,
        Some(accent),
        "the unfilled track stays neutral so filled and unfilled remain distinguishable"
    );
}

#[test]
fn range_pseudo_element_moz_progress_color() {
    init();
    let html = r#"<style>
        input::-moz-range-progress { background-color: #0000ff; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x];
    // Filled cells (columns 0-3, left of thumb) should be blue.
    assert_eq!(
        cell(0).fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0x00,
            g: 0x00,
            b: 0xff
        }),
        "::-moz-range-progress background-color colours the filled track"
    );
    // Empty cells (columns 5-8, right of thumb) remain DarkGrey.
    assert_eq!(
        cell(6).fcolor,
        Some(crossterm::style::Color::DarkGrey),
        "unfilled track without ::-moz-range-track stays DarkGrey"
    );
}

#[test]
fn range_pseudo_element_track_color() {
    init();
    let html = r#"<style>
        input::-webkit-slider-runnable-track { background-color: #ffff00; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x];
    // Empty cells (right of thumb) should be yellow instead of DarkGrey.
    assert_eq!(
        cell(6).fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0xff,
            g: 0xff,
            b: 0x00
        }),
        "::-webkit-slider-runnable-track background-color colours the unfilled track"
    );
}

#[test]
fn range_pseudo_element_moz_track_color() {
    init();
    let html = r#"<style>
        input::-moz-range-track { color: #00ffff; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x];
    assert_eq!(
        cell(6).fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0x00,
            g: 0xff,
            b: 0xff
        }),
        "::-moz-range-track color colours the unfilled track"
    );
}

#[test]
fn range_accent_color_fallback_for_thumb_and_fill() {
    init();
    let html = r#"<style>
        input { accent-color: #ff8800; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x];
    let orange = Some(crossterm::style::Color::Rgb {
        r: 0xff,
        g: 0x88,
        b: 0x00,
    });
    assert_eq!(cell(4).fcolor, orange, "accent-color colours the thumb");
    assert_eq!(
        cell(0).fcolor,
        orange,
        "accent-color colours the filled track"
    );
}

#[test]
fn range_pseudo_element_overrides_accent_color() {
    init();
    let html = r#"<style>
        input { accent-color: #ff8800; }
        input::-webkit-slider-thumb { background-color: #00ff00; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9">"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x];
    // Thumb uses the pseudo-element green; fill falls back to accent orange.
    assert_eq!(
        cell(4).fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0x00,
            g: 0xff,
            b: 0x00
        }),
        "pseudo-element thumb overrides accent-color"
    );
    assert_eq!(
        cell(0).fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0xff,
            g: 0x88,
            b: 0x00
        }),
        "filled track without a pseudo-element uses accent-color"
    );
}

#[test]
fn checkbox_accent_color() {
    init();
    let html = r#"<style>input { accent-color: red; }</style>
    <input type="checkbox" checked>"#;
    let (_, tl) = render_rows(html);
    let cell = &tl.layout[0];
    assert_eq!(
        cell.fcolor,
        Some(crossterm::style::Color::Rgb {
            r: 0xff,
            g: 0x00,
            b: 0x00
        }),
        "accent-color themes the checked checkbox glyph"
    );
}

#[test]
fn range_pseudo_element_disabled_overrides_colors() {
    init();
    let html = r#"<style>
        input::-webkit-slider-thumb { background-color: #ff0000; }
        input::-moz-range-progress { background-color: #0000ff; }
    </style>
    <input type="range" min="0" max="4" step="1" value="2" width="9" disabled>"#;
    let (_, tl) = render_rows(html);
    let cell = |x: usize| &tl.layout[x];
    // Disabled controls keep the grey override regardless of pseudo-element colours.
    assert_eq!(
        cell(4).fcolor,
        Some(crossterm::style::Color::DarkGrey),
        "disabled slider ignores pseudo-element thumb colour"
    );
    assert_eq!(
        cell(0).fcolor,
        Some(crossterm::style::Color::DarkGrey),
        "disabled slider ignores pseudo-element progress colour"
    );
}

#[test]
fn clipped_range_control_does_not_paint_over_parent_border() {
    init();
    let html = r#"<style>
        #shell { width: 10ch; height: 3ch; overflow: hidden; border: 1ch solid #888; }
        input { width: 20ch; margin-left: 1ch; }
    </style>
    <div id="shell"><input type="range" min="0" max="9" step="1" value="4"></div>"#;
    let (_, tl) = render_rows(html);
    let cols = 80;
    let word = |x: usize, y: usize| tl.layout[y * cols + x].word.as_str().to_string();

    assert_eq!(word(0, 1), "\u{2502}", "left border stays intact");
    assert_eq!(word(9, 1), "\u{2502}", "right border stays intact");
    assert_eq!(word(10, 1), " ", "control must stop at its inherited clip");
    assert_ne!(
        word(2, 1),
        " ",
        "the visible track starts inside the parent"
    );
    assert_ne!(word(8, 1), " ", "the visible track ends inside the parent");
}