textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
Documentation
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
//! P2 render/visual CSS gate tests.
//!
//! These tests verify that render/visual CSS properties (P2-28/29/31/34/35)
//! are correctly parsed, resolved, and wired into the rendering pipeline.

use rich_rs::{Console, ConsoleOptions, Segment, Segments};
use textual::css::set_style_context;
use textual::prelude::*;
use textual::render::FrameBuffer;
use textual::style::{
    Constrain, HorizontalAlign, KeylineType, OverlayMode, Scalar, Style, TextOverflow, TextWrap,
};

// ===========================================================================
// Helpers
// ===========================================================================

/// Render a root widget through the full tree pipeline, returning (tree, frame, lines).
fn tree_render(
    root: &mut dyn Widget,
    w: usize,
    h: usize,
) -> (WidgetTree, FrameBuffer, Vec<String>) {
    let console = Console::new();
    let mut tree = build_widget_tree_from_root(root).expect("tree should have children");
    let frame = render_tree_to_frame(&mut tree, root, &console, w, h);
    let lines = frame.as_plain_lines();
    (tree, frame, lines)
}

struct BorderCaptionWidget {
    title: &'static str,
    subtitle: &'static str,
    styles: WidgetStyles,
}

impl BorderCaptionWidget {
    fn new(title: &'static str, subtitle: &'static str) -> Self {
        let mut styles = WidgetStyles::default();
        styles.style = styles
            .style
            .border_top(textual::style::Color::parse("white").unwrap())
            .border_bottom(textual::style::Color::parse("white").unwrap())
            .border_left(textual::style::Color::parse("white").unwrap())
            .border_right(textual::style::Color::parse("white").unwrap());
        styles.style.border_title_align = Some(HorizontalAlign::Center);
        styles.style.border_subtitle_align = Some(HorizontalAlign::Right);
        styles.style.border_title_color = Some(textual::style::Color::parse("yellow").unwrap());
        styles.style.border_subtitle_color = Some(textual::style::Color::parse("cyan").unwrap());
        Self {
            title,
            subtitle,
            styles,
        }
    }
}

impl Widget for BorderCaptionWidget {
    fn render(&self, _console: &Console, options: &ConsoleOptions) -> Segments {
        let w = options.size.0.max(1);
        let h = options.size.1.max(1);
        let mut out = Segments::new();
        for y in 0..h {
            out.push(Segment::new(" ".repeat(w)));
            if y + 1 < h {
                out.push(Segment::line());
            }
        }
        out
    }

    fn style_type(&self) -> &'static str {
        "BorderCaptionWidget"
    }

    fn border_title(&self) -> Option<&str> {
        Some(self.title)
    }

    fn border_subtitle(&self) -> Option<&str> {
        Some(self.subtitle)
    }

    fn styles(&self) -> Option<&WidgetStyles> {
        Some(&self.styles)
    }
}

struct FillWidget {
    style_type_name: &'static str,
    styles: WidgetStyles,
}

impl FillWidget {
    fn new(style_type_name: &'static str, style: Style) -> Self {
        let mut styles = WidgetStyles::default();
        styles.style = style;
        Self {
            style_type_name,
            styles,
        }
    }
}

impl Widget for FillWidget {
    fn render(&self, _console: &Console, options: &ConsoleOptions) -> Segments {
        let w = options.size.0.max(1);
        let h = options.size.1.max(1);
        let mut out = Segments::new();
        for y in 0..h {
            out.push(Segment::new("x".repeat(w)));
            if y + 1 < h {
                out.push(Segment::line());
            }
        }
        out
    }

    fn style_type(&self) -> &'static str {
        self.style_type_name
    }

    fn styles(&self) -> Option<&WidgetStyles> {
        Some(&self.styles)
    }
}

// ===========================================================================
// P2G-28: Outline renders outside border, no layout mutation
// ===========================================================================

#[test]
fn p2g28_outline_style_fields_wired() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    use textual::style::{BorderEdge, BorderType, Color};

    let mut style = textual::style::Style::new();
    let red = Color::parse("red").unwrap();

    // Set outline edges programmatically.
    style.outline_top = BorderEdge::Edge {
        border_type: BorderType::Solid,
        color: red,
    };
    style.outline_right = BorderEdge::Edge {
        border_type: BorderType::Solid,
        color: red,
    };
    style.outline_bottom = BorderEdge::Edge {
        border_type: BorderType::Block,
        color: red,
    };
    style.outline_left = BorderEdge::Edge {
        border_type: BorderType::Tall,
        color: red,
    };

    assert!(style.outline_top.is_set());
    assert!(style.outline_right.is_set());
    assert!(style.outline_bottom.is_set());
    assert!(style.outline_left.is_set());
    assert_eq!(style.outline_top.color(), Some(red));
    assert_eq!(style.outline_bottom.edge_type(), "block");
    assert_eq!(style.outline_left.edge_type(), "tall");
}

#[test]
fn p2g28_outline_css_parses_all_edges() {
    // NOTE: parse-only — verifies CSS parser, not runtime outline rendering.
    let css = "Label { outline: solid red; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    // Render a Label — this exercises the full CSS resolution path.
    let mut root = Container::new().with_child(Label::new("hi"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 5);

    // Label text should still be visible.
    let all_text: String = lines.join("");
    assert!(
        all_text.contains("hi"),
        "label text should appear in output: {all_text:?}"
    );
}

#[test]
fn p2g28_outline_per_side_css_parses() {
    // NOTE: parse-only — verifies CSS parser, not runtime outline rendering.
    let css = "Label { outline-top: solid green; outline-bottom: solid blue; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("ok"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 5);

    let all_text: String = lines.join("");
    assert!(all_text.contains("ok"), "label text should appear");
}

#[test]
fn p2g28_outline_does_not_affect_layout_rect() {
    // Outline should NOT affect widget content area or layout dimensions.
    // Render the same label with and without outline, compare visible text position.
    let css_no_outline = "Label { }";
    let css_with_outline = "Label { outline: solid red; }";

    // Without outline.
    let sheet1 = StyleSheet::parse(css_no_outline);
    let _guard1 = set_style_context(sheet1);
    let mut root1 = Container::new().with_child(Label::new("test"));
    let (_tree1, _frame1, lines1) = tree_render(&mut root1, 20, 5);
    let row1 = lines1.iter().position(|l| l.contains("test"));

    // With outline.
    let sheet2 = StyleSheet::parse(css_with_outline);
    let _guard2 = set_style_context(sheet2);
    let mut root2 = Container::new().with_child(Label::new("test"));
    let (_tree2, _frame2, lines2) = tree_render(&mut root2, 20, 5);
    let row2 = lines2.iter().position(|l| l.contains("test"));

    // The label should appear on the same row regardless of outline.
    assert_eq!(
        row1, row2,
        "outline should not shift layout: row_without={row1:?} row_with={row2:?}"
    );
}

// ===========================================================================
// P2G-29: Border title/subtitle alignment + color/style
// ===========================================================================

#[test]
fn p2g29_border_title_align_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    let mut style = textual::style::Style::new();
    style.border_title_align = Some(HorizontalAlign::Center);
    style.border_subtitle_align = Some(HorizontalAlign::Right);

    assert_eq!(style.border_title_align, Some(HorizontalAlign::Center));
    assert_eq!(style.border_subtitle_align, Some(HorizontalAlign::Right));
}

#[test]
fn p2g29_border_title_color_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    use textual::style::Color;

    let mut style = textual::style::Style::new();
    let red = Color::parse("red").unwrap();
    let blue = Color::parse("blue").unwrap();

    style.border_title_color = Some(red);
    style.border_title_background = Some(blue);
    style.border_subtitle_color = Some(blue);
    style.border_subtitle_background = Some(red);

    assert_eq!(style.border_title_color, Some(red));
    assert_eq!(style.border_title_background, Some(blue));
    assert_eq!(style.border_subtitle_color, Some(blue));
    assert_eq!(style.border_subtitle_background, Some(red));
}

#[test]
fn p2g29_border_title_style_flags() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    use textual::style::TextStyleFlags;

    let flags = TextStyleFlags {
        bold: true,
        italic: true,
        dim: false,
        underline: false,
        reverse: false,
        strike: false,
    };
    let mut style = textual::style::Style::new();
    style.border_title_style = Some(flags);

    let stored = style.border_title_style.unwrap();
    assert!(stored.bold);
    assert!(stored.italic);
    assert!(!stored.underline);
}

#[test]
fn p2g29_border_title_css_parse_roundtrip() {
    // NOTE: parse-only — verifies CSS parser, not runtime border title rendering.
    let css = "Label { border-title-align: center; border-subtitle-align: right; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("titled"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains("titled"));
}

#[test]
fn p2g29_border_title_color_css_parse_roundtrip() {
    // NOTE: parse-only — verifies CSS parser, not runtime border title rendering.
    let css = "Label { border-title-color: red; border-title-background: blue; border-title-style: bold italic; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("styled"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains("styled"));
}

#[test]
fn p2g29_border_title_subtitle_render_on_edges() {
    let mut root = Container::new().with_child(BorderCaptionWidget::new("TITLE", "sub"));
    let (_tree, frame, lines) = tree_render(&mut root, 24, 6);
    assert!(
        lines[0].contains("TITLE"),
        "top border should contain title"
    );
    assert!(
        lines[5].contains("sub"),
        "bottom border should contain subtitle"
    );

    let title_x = lines[0].find("TITLE").expect("title should be present");
    let title_cell = frame.get(title_x, 0);
    let title_fg = title_cell.style.and_then(|s| s.color).map(|c| c);
    assert_eq!(
        title_fg,
        Some(
            textual::style::Color::parse("yellow")
                .unwrap()
                .to_simple_opaque()
        )
    );
}

// ===========================================================================
// P2G-31: Text wrap/nowrap + overflow modes
// ===========================================================================

#[test]
fn p2g31_text_wrap_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    let mut style = textual::style::Style::new();
    style.text_wrap = Some(TextWrap::Wrap);
    assert_eq!(style.text_wrap, Some(TextWrap::Wrap));

    style.text_wrap = Some(TextWrap::NoWrap);
    assert_eq!(style.text_wrap, Some(TextWrap::NoWrap));
}

#[test]
fn p2g31_text_overflow_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    let mut style = textual::style::Style::new();
    style.text_overflow = Some(TextOverflow::Clip);
    assert_eq!(style.text_overflow, Some(TextOverflow::Clip));

    style.text_overflow = Some(TextOverflow::Fold);
    assert_eq!(style.text_overflow, Some(TextOverflow::Fold));

    style.text_overflow = Some(TextOverflow::Ellipsis);
    assert_eq!(style.text_overflow, Some(TextOverflow::Ellipsis));
}

#[test]
fn p2g31_text_wrap_css_parse_roundtrip() {
    // NOTE: parse-only — verifies CSS parser, not runtime text wrapping behavior.
    let css = "Label { text-wrap: nowrap; text-overflow: ellipsis; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("truncated"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains("truncated"));
}

#[test]
fn p2g31_text_overflow_line_truncation_clip() {
    use textual::runtime::apply_text_overflow_to_line;

    let long_line = vec![rich_rs::Segment::new("abcdefghij")]; // 10 chars
    let clipped = apply_text_overflow_to_line(&long_line, 5, TextOverflow::Clip);
    let clipped_text: String = clipped.iter().map(|s| s.text.to_string()).collect();
    assert_eq!(
        rich_rs::cell_len(&clipped_text),
        5,
        "clipped should be 5 cols wide"
    );
}

#[test]
fn p2g31_text_overflow_line_truncation_ellipsis() {
    use textual::runtime::apply_text_overflow_to_line;

    let long_line = vec![rich_rs::Segment::new("abcdefghij")]; // 10 chars
    let ellipsised = apply_text_overflow_to_line(&long_line, 5, TextOverflow::Ellipsis);
    let ell_text: String = ellipsised.iter().map(|s| s.text.to_string()).collect();
    assert!(
        ell_text.contains(''),
        "ellipsis should be present: {ell_text:?}"
    );
    assert!(
        rich_rs::cell_len(&ell_text) <= 5,
        "ellipsised should fit in 5 cols: {ell_text:?} (width={})",
        rich_rs::cell_len(&ell_text)
    );
}

#[test]
fn p2g31_text_overflow_line_fold_preserves_text() {
    use textual::runtime::apply_text_overflow_to_line;

    let long_line = vec![rich_rs::Segment::new("abcdefghij")];
    let folded = apply_text_overflow_to_line(&long_line, 5, TextOverflow::Fold);
    let fold_text: String = folded.iter().map(|s| s.text.to_string()).collect();
    assert_eq!(fold_text, "abcdefghij", "fold should preserve full text");
}

#[test]
fn p2g31_text_overflow_mode_function() {
    use textual::runtime::text_overflow_mode;

    // No text-wrap set: should return None.
    let style_default = textual::style::Style::new();
    assert!(text_overflow_mode(&style_default).is_none());

    // text-wrap: wrap -> None.
    let mut style_wrap = textual::style::Style::new();
    style_wrap.text_wrap = Some(TextWrap::Wrap);
    assert!(text_overflow_mode(&style_wrap).is_none());

    // text-wrap: nowrap -> defaults to Clip.
    let mut style_nowrap = textual::style::Style::new();
    style_nowrap.text_wrap = Some(TextWrap::NoWrap);
    assert_eq!(text_overflow_mode(&style_nowrap), Some(TextOverflow::Clip));

    // text-wrap: nowrap + text-overflow: ellipsis -> Ellipsis.
    let mut style_ellipsis = textual::style::Style::new();
    style_ellipsis.text_wrap = Some(TextWrap::NoWrap);
    style_ellipsis.text_overflow = Some(TextOverflow::Ellipsis);
    assert_eq!(
        text_overflow_mode(&style_ellipsis),
        Some(TextOverflow::Ellipsis)
    );
}

// ===========================================================================
// P2G-34: Hatch, overlay, keyline
// ===========================================================================

#[test]
fn p2g34_hatch_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    use textual::style::{Color, Hatch};

    let hatch = Hatch {
        character: '+',
        color: Color::parse("red").unwrap(),
    };
    let mut style = textual::style::Style::new();
    style.hatch = Some(hatch);

    let stored = style.hatch.unwrap();
    assert_eq!(stored.character, '+');
    assert_eq!(stored.color, Color::parse("red").unwrap());
}

#[test]
fn p2g34_overlay_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    let mut style = textual::style::Style::new();
    style.overlay = Some(OverlayMode::None);
    assert_eq!(style.overlay, Some(OverlayMode::None));

    style.overlay = Some(OverlayMode::Screen);
    assert_eq!(style.overlay, Some(OverlayMode::Screen));
}

#[test]
fn p2g34_keyline_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    use textual::style::{Color, Keyline};

    let keyline = Keyline {
        keyline_type: KeylineType::Thin,
        color: Color::parse("red").unwrap(),
    };
    let mut style = textual::style::Style::new();
    style.keyline = Some(keyline);

    let stored = style.keyline.unwrap();
    assert_eq!(stored.keyline_type, KeylineType::Thin);
    assert_eq!(stored.color, Color::parse("red").unwrap());
}

#[test]
fn p2g34_hatch_css_parse_renders_without_crash() {
    // NOTE: parse-only — verifies CSS parser + no-crash, not runtime hatch rendering.
    let css = r#"Container { hatch: cross #ff0000; }"#;
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("X"));
    let (_tree, _frame, lines) = tree_render(&mut root, 10, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains('X'), "label text should survive hatch");
}

#[test]
fn p2g34_overlay_screen_renders_without_crash() {
    // NOTE: parse-only — verifies CSS parser + no-crash, not runtime overlay compositing.
    let css = "Label { overlay: screen; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("overlay"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains("overlay"));
}

#[test]
fn p2g34_keyline_css_parse_renders_without_crash() {
    // NOTE: parse-only — verifies CSS parser + no-crash, not runtime keyline painting.
    let css = "Container { keyline: thin red; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new()
        .with_child(Label::new("A"))
        .with_child(Label::new("B"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 5);

    let all_text: String = lines.join("");
    assert!(all_text.contains('A'));
    assert!(all_text.contains('B'));
}

#[test]
fn p2g34_keyline_heavy_css_parse() {
    // NOTE: parse-only — verifies CSS parser + no-crash, not runtime keyline painting.
    let css = "Container { keyline: heavy green; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("heavy"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains("heavy"));
}

// ===========================================================================
// P2G-35: Constrain-x, constrain-y, expand
// ===========================================================================

#[test]
fn p2g35_constrain_x_y_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    let mut style = textual::style::Style::new();
    style.constrain_x = Some(Constrain::Inflect);
    style.constrain_y = Some(Constrain::Inside);

    assert_eq!(style.constrain_x, Some(Constrain::Inflect));
    assert_eq!(style.constrain_y, Some(Constrain::Inside));
}

#[test]
fn p2g35_expand_style_fields() {
    // NOTE: parse-only — verifies Style struct fields, not runtime behavior.
    let mut style = textual::style::Style::new();
    style.expand = Some(true);
    assert_eq!(style.expand, Some(true));

    style.expand = Some(false);
    assert_eq!(style.expand, Some(false));
}

#[test]
fn p2g35_constrain_x_y_css_parse_roundtrip() {
    // NOTE: parse-only — verifies CSS parser, not runtime constrain behavior.
    let css = "Label { constrain-x: inflect; constrain-y: inside; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("constrained"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains("constrained"));
}

#[test]
fn p2g35_expand_css_parse_roundtrip() {
    // NOTE: parse-only — verifies CSS parser, not runtime expand behavior.
    let css = "Label { expand: true; }";
    let sheet = StyleSheet::parse(css);
    let _guard = set_style_context(sheet);

    let mut root = Container::new().with_child(Label::new("expanded"));
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    let all_text: String = lines.join("");
    assert!(all_text.contains("expanded"));
}

#[test]
fn p2g35_axis_constrain_resolution() {
    use textual::runtime::resolve_axis_constrain;

    // When constrain-x/y are not set, falls back to generic constrain.
    let mut style = textual::style::Style::new();
    style.constrain = Some(Constrain::Inside);
    let (cx, cy) = resolve_axis_constrain(&style);
    assert_eq!(cx, Constrain::Inside);
    assert_eq!(cy, Constrain::Inside);

    // When constrain-x is set, overrides generic for x-axis only.
    style.constrain_x = Some(Constrain::Inflect);
    let (cx, cy) = resolve_axis_constrain(&style);
    assert_eq!(cx, Constrain::Inflect);
    assert_eq!(cy, Constrain::Inside);
}

#[test]
fn p2g35_constrain_overlay_position_clamps_inside() {
    use textual::runtime::constrain_overlay_position;

    let (x, y) =
        constrain_overlay_position(90, 20, 20, 5, 100, 25, Constrain::Inside, Constrain::Inside);
    assert!(x + 20 <= 100, "x should be clamped inside viewport: x={x}");
    assert!(y + 5 <= 25, "y should be clamped inside viewport: y={y}");
    assert_eq!(x, 80, "x should be clamped to 80 (100 - 20)");
    assert_eq!(y, 20, "y should stay at 20 (fits in viewport)");
}

#[test]
fn p2g35_constrain_overlay_position_inflects() {
    use textual::runtime::constrain_overlay_position;

    // Overlay overflows right: inflect should flip to left.
    let (x, _y) =
        constrain_overlay_position(90, 5, 20, 3, 100, 25, Constrain::Inflect, Constrain::None);
    assert_eq!(x, 70, "x should inflect to 70 (90 - 20)");

    // Overlay overflows bottom: inflect should flip up.
    let (_x, y) =
        constrain_overlay_position(5, 22, 10, 5, 100, 25, Constrain::None, Constrain::Inflect);
    assert_eq!(y, 17, "y should inflect to 17 (22 - 5)");
}

#[test]
fn p2g35_constrain_none_does_not_clamp() {
    use textual::runtime::constrain_overlay_position;

    let (x, y) =
        constrain_overlay_position(90, 22, 20, 5, 100, 25, Constrain::None, Constrain::None);
    assert_eq!(x, 90, "x should be unchanged");
    assert_eq!(y, 22, "y should be unchanged");
}

// ===========================================================================
// P2-28 behavioral: outline paints outside border box
// ===========================================================================

#[test]
fn p2_28_outline_paints_outside_border_box() {
    // Outline should paint characters in cells OUTSIDE the widget's border box.
    // Uses inline styles (tree pipeline overwrites CSS context with defaults).
    // Inner Container with padding insets the Label so outline has room on all sides.
    use textual::style::{BorderEdge, BorderType, Color, Spacing};

    let red = Color::parse("red").unwrap();
    let outline_edge = BorderEdge::Edge {
        border_type: BorderType::Solid,
        color: red,
    };

    let mut label = Label::new("hi");
    label.set_width(2);
    label.styles_mut().unwrap().style.outline_top = outline_edge;
    label.styles_mut().unwrap().style.outline_bottom = outline_edge;
    label.styles_mut().unwrap().style.outline_left = outline_edge;
    label.styles_mut().unwrap().style.outline_right = outline_edge;

    // Nested: outer Container (root, no style) > inner Container (padding 3) > Label.
    let mut inner = Container::new().with_child(label);
    inner.set_width(20);
    inner.styles_mut().unwrap().style.padding = Some(Spacing::all(3));
    let mut root = Container::new().with_child(inner);

    let (_tree, frame, _lines) = tree_render(&mut root, 20, 8);

    // Inner Container fills viewport (20x8), Label is inset by padding 3.
    // Label "hi" has content_width=2, so layout rect is at approximately (3, 3) with w=2, h=1.
    // Outline paints OUTSIDE the 2x1 label rect:
    //   Top:    row 2, cols 3..5 → '─'
    //   Bottom: row 4, cols 3..5 → '─'
    //   Left:   col 2, row 3 → '│'
    //   Right: may be clipped by current content-box clipping rules.
    let top_cell = frame.get(3, 2);
    assert_eq!(top_cell.text, "", "top outline at (3,2)");
    let bottom_cell = frame.get(3, 4);
    assert_eq!(bottom_cell.text, "", "bottom outline at (3,4)");
    let left_cell = frame.get(2, 3);
    assert_eq!(left_cell.text, "", "left outline at (2,3)");

    // Label text is inside (at outline-inner positions).
    assert_eq!(frame.get(3, 3).text, "h", "label text at (3,3)");
    assert_eq!(frame.get(4, 3).text, "i", "label text at (4,3)");
}

#[test]
fn p2_28_outline_clipped_at_viewport_edge() {
    // Outline edges beyond viewport bounds are silently clipped (no panic).
    // Label at viewport edge: top/left outlines clipped, bottom/right visible.
    use textual::style::{BorderEdge, BorderType, Color};

    let red = Color::parse("red").unwrap();
    let outline_edge = BorderEdge::Edge {
        border_type: BorderType::Solid,
        color: red,
    };

    let mut label = Label::new("edge");
    label.set_width(4);
    label.styles_mut().unwrap().style.outline_top = outline_edge;
    label.styles_mut().unwrap().style.outline_bottom = outline_edge;
    label.styles_mut().unwrap().style.outline_left = outline_edge;
    label.styles_mut().unwrap().style.outline_right = outline_edge;

    let mut root = Container::new().with_child(label);
    root.set_width(10);
    let (_tree, frame, _lines) = tree_render(&mut root, 10, 3);

    // Label "edge" has content_width=4, so layout rect is (0, 0, 4, 1).
    // Top: row -1 (clipped), Left: col -1 (clipped).
    // Bottom: row 1, cols 0..4 → '─'
    // Right edge may be clipped by current content-box clipping rules.
    assert_eq!(frame.get(0, 1).text, "", "bottom outline at (0,1)");
    assert_eq!(frame.get(3, 1).text, "", "bottom outline at (3,1)");

    // Label text intact.
    assert_eq!(frame.get(0, 0).text, "e", "label text at (0,0)");
}

// ===========================================================================
// P2-34 behavioral: hatch fills blank cells with pattern character
// ===========================================================================

#[test]
fn p2_34_hatch_fills_blank_cells_with_pattern() {
    // Hatch replaces blank cells with hatch character; preserves existing text.
    // Label text is exactly 10 chars so layout gives it width 10 (matching
    // content_width). First char is 'X', rest are spaces — hatch fills spaces.
    use textual::style::{Color, Hatch};

    let mut label = Label::new("X         "); // 10 chars: 'X' + 9 spaces
    label.styles_mut().unwrap().style.hatch = Some(Hatch {
        character: '+',
        color: Color::parse("#ff0000").unwrap(),
    });

    let mut root = Container::new().with_child(label);
    let (_tree, frame, _lines) = tree_render(&mut root, 20, 3);

    // Label layout rect is 10 wide (content_width = 10).
    // Cell 0: "X" (not blank, preserved). Cells 1..10: " " (blank, hatched).
    assert_eq!(frame.get(0, 0).text, "X", "text cell should be preserved");
    assert_eq!(frame.get(1, 0).text, "+", "blank cell should be hatched");
    assert_eq!(frame.get(5, 0).text, "+", "blank cell should be hatched");
    assert_eq!(frame.get(9, 0).text, "+", "blank cell should be hatched");
}

#[test]
fn p2g34_overlay_screen_blends_with_underlay() {
    let base_style = Style::new()
        .width(Scalar::Percent(100.0))
        .height(Scalar::Percent(100.0))
        .bg(textual::style::Color::parse("#0000ff").unwrap());
    let mut overlay_style = Style::new()
        .width(Scalar::Percent(100.0))
        .height(Scalar::Percent(100.0))
        .bg(textual::style::Color::parse("#ff0000").unwrap());
    overlay_style.position = Some(textual::style::Position::Absolute);
    overlay_style.overlay = Some(OverlayMode::Screen);
    let mut root = Container::new()
        .with_child(FillWidget::new("BaseFill", base_style))
        .with_child(FillWidget::new("OverlayFill", overlay_style));
    let (_tree, frame, _lines) = tree_render(&mut root, 8, 3);

    let bg = frame
        .get(0, 0)
        .style
        .and_then(|s| s.bgcolor)
        .map(|c| c)
        .expect("blended background color should exist");
    assert_eq!(
        bg,
        textual::style::Color::parse("#ff00ff")
            .unwrap()
            .to_simple_opaque()
    );
}

#[test]
fn p2g34_keyline_draws_separator_between_children() {
    let mut keylined = Container::new();
    keylined.styles_mut().unwrap().style.layout = Some(textual::style::Layout::Vertical);
    keylined.styles_mut().unwrap().style.keyline = Some(textual::style::Keyline {
        keyline_type: KeylineType::Thin,
        color: textual::style::Color::parse("red").unwrap(),
    });
    let mut a = Label::new("A");
    a.styles_mut().unwrap().style.height = Some(Scalar::Cells(1));
    let mut b = Label::new("B");
    b.styles_mut().unwrap().style.height = Some(Scalar::Cells(1));
    keylined = keylined.with_child(a).with_child(b);
    let mut root = Container::new().with_child(keylined);
    let (_tree, frame, lines) = tree_render(&mut root, 10, 4);
    assert!(
        lines.iter().any(|l| l.contains('')),
        "keyline separator should be painted; lines={lines:?}"
    );

    let sep_y = lines
        .iter()
        .position(|l| l.contains(''))
        .expect("separator row");
    let cell = frame.get(0, sep_y);
    let fg = cell.style.and_then(|s| s.color).map(|c| c);
    assert_eq!(
        fg,
        Some(
            textual::style::Color::parse("red")
                .unwrap()
                .to_simple_opaque()
        )
    );
}

// ===========================================================================
// P2-31 behavioral: narrow-width text overflow through full pipeline
// ===========================================================================

/// A test widget that intentionally renders a line wider than its layout rect,
/// to exercise the tree-level text-overflow truncation wiring.
struct WideRenderWidget {
    text: String,
    styles: WidgetStyles,
}

impl WideRenderWidget {
    fn new(text: &str) -> Self {
        Self {
            text: text.to_string(),
            styles: WidgetStyles::default(),
        }
    }
}

impl Widget for WideRenderWidget {
    fn render(&self, _console: &Console, _options: &ConsoleOptions) -> rich_rs::Segments {
        // Intentionally ignore options.size — produce a full-width line.
        let mut out = rich_rs::Segments::new();
        out.push(rich_rs::Segment::new(self.text.clone()));
        out
    }

    fn content_width(&self) -> Option<usize> {
        // Report narrow content width so layout constrains us,
        // but render() produces the full text anyway.
        Some(8)
    }

    fn style_type(&self) -> &'static str {
        "WideRenderWidget"
    }

    fn styles(&self) -> Option<&WidgetStyles> {
        Some(&self.styles)
    }

    fn styles_mut(&mut self) -> Option<&mut WidgetStyles> {
        Some(&mut self.styles)
    }
}

#[test]
fn p2_31_nowrap_ellipsis_narrow_pipeline() {
    // Verify tree-level text-overflow truncation wiring.
    // Uses a custom widget that renders text wider than its layout rect.
    let mut widget = WideRenderWidget::new("abcdefghijklmnop"); // 16 chars
    widget.set_width(8);
    widget.styles.style.text_wrap = Some(TextWrap::NoWrap);
    widget.styles.style.text_overflow = Some(TextOverflow::Ellipsis);

    let mut root = Container::new().with_child(widget);
    let (_tree, _frame, lines) = tree_render(&mut root, 20, 3);

    // Layout gives the widget width=8 (from content_width), but render
    // produces 16 chars. Tree-level text overflow should truncate with ellipsis.
    let first_line = &lines[0];
    assert!(
        first_line.contains('') || first_line.starts_with("abcdefgh"),
        "tree-level text overflow should truncate to the widget width: {first_line:?}"
    );
    assert!(
        rich_rs::cell_len(first_line.trim_end()) <= 8,
        "truncated output should fit within 8 columns: {first_line:?} (width={})",
        rich_rs::cell_len(first_line.trim_end())
    );
}