egui_styled 0.5.5

Tailwind-style utility styling for egui: per-widget hover/focus/active variants, design tokens, and composable style functions.
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
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
use crate::state::PseudoState;

use egui::{
    Color32, CornerRadius, CursorIcon, FontId, Margin, Rect, Shape, Stroke, Vec2, Visuals, pos2,
    style::WidgetVisuals,
};

/// How a `background_image` fills its container rect when the image's intrinsic
/// aspect ratio differs from the styled box.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BackgroundImageFit {
    /// Map the full texture over the rect (uv 0→1 on both axes). Distorts if
    /// aspect ratios differ — equivalent to CSS `background-size: 100% 100%`.
    #[default]
    Stretch,
    /// Scale to cover the box, cropping overflow. Preserves aspect ratio —
    /// equivalent to CSS `background-size: cover`. Requires the texture to be
    /// loaded; on the loading frame the image is not painted.
    Cover,
}

/// A single paint decoration rendered behind the widget rect.
///
/// Use `.shadow()` (stroke-only) or `.shadow_filled()` (solid fill) on any
/// styled widget to paint offset copies of the widget's bounding rect on the
/// same layer, underneath the widget itself.
///
/// Multiple shadows are supported — append with repeated `.shadow(...)` calls.
/// Each shadow inherits the widget's `corner_radius` at paint time.
#[derive(Clone, Copy, Debug)]
pub struct Shadow {
    pub offset: Vec2,
    pub stroke: Stroke,
    pub fill: Option<Color32>,
}

/// Paint all `shadows` behind position `reserve_idx` (a `Shape::Noop`
/// placeholder inserted before the widget was rendered). Replaces the
/// placeholder with a `Shape::Vec` containing all shadow shapes.
///
/// Call pattern inside a widget's `show`:
/// ```text
/// let shadow_idx = ui.painter().add(Shape::Noop);
/// // ... add widget, get response ...
/// paint_shadows(ui, shadow_idx, response.rect, corner_radius, &style.shadows);
/// ```
pub fn paint_shadows(
    ui: &egui::Ui,
    reserve_idx: egui::layers::ShapeIdx,
    rect: egui::Rect,
    corner_radius: CornerRadius,
    shadows: &[Shadow],
) {
    if shadows.is_empty() {
        return;
    }
    let shapes: Vec<Shape> = shadows
        .iter()
        .flat_map(|s| {
            let r = rect.translate(s.offset);
            let mut parts: Vec<Shape> = Vec::with_capacity(2);
            if let Some(fill) = s.fill {
                parts.push(Shape::rect_filled(r, corner_radius, fill));
            }
            if s.stroke != Stroke::NONE {
                parts.push(Shape::rect_stroke(
                    r,
                    corner_radius,
                    s.stroke,
                    egui::StrokeKind::Outside,
                ));
            }
            parts
        })
        .collect();
    ui.painter().set(reserve_idx, Shape::Vec(shapes));
}

/// Per-side border overrides. Each side is `None` until the user sets it via a
/// `border_top` / `border_left` / … builder; an unset side falls back to the
/// uniform `border` (and then egui's default) at resolve time.
#[derive(Clone, Copy, Default, Debug)]
pub struct SideStrokes {
    pub top: Option<Stroke>,
    pub right: Option<Stroke>,
    pub bottom: Option<Stroke>,
    pub left: Option<Stroke>,
}

impl SideStrokes {
    /// True if any side has an explicit override.
    pub fn any(&self) -> bool {
        self.top.is_some() || self.right.is_some() || self.bottom.is_some() || self.left.is_some()
    }
}

/// A border resolved to a concrete `Stroke` per side. Produced by
/// [`SharedStyle::resolve`]; consumed by [`paint_side_borders`] when the user
/// set per-side overrides.
#[derive(Clone, Copy, Debug)]
pub struct ResolvedBorder {
    pub top: Stroke,
    pub right: Stroke,
    pub bottom: Stroke,
    pub left: Stroke,
}

/// Paint each border side as a straight line segment along the matching edge of
/// `rect`. Only sides with a positive stroke width are drawn.
///
/// Unlike egui's uniform `bg_stroke`, partial borders are **not** rounded around
/// the corner radius — each side is a straight edge. This is fine for the common
/// case (left/right or top/bottom borders) and keeps the painting trivial.
pub fn paint_side_borders(painter: &egui::Painter, rect: Rect, border: ResolvedBorder) {
    let line = |a, b, stroke: Stroke| {
        if stroke.width > 0.0 {
            painter.add(Shape::line_segment([a, b], stroke));
        }
    };
    line(rect.left_top(), rect.right_top(), border.top);
    line(rect.right_top(), rect.right_bottom(), border.right);
    line(rect.left_bottom(), rect.right_bottom(), border.bottom);
    line(rect.left_top(), rect.left_bottom(), border.left);
}

/// Compute the UV rect used to sample the texture for the given `fit` mode.
///
/// `intrinsic`: the loaded texture's original size in points (width, height).
/// `dest`: the target rect we are filling.
///
/// `Stretch` always returns `(0,0)→(1,1)`.
/// `Cover` adjusts the UV to crop the wider axis, preserving aspect ratio.
fn cover_uv(intrinsic: Vec2, dest: Rect) -> Rect {
    if intrinsic.x <= 0.0 || intrinsic.y <= 0.0 {
        return Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
    }
    let dest_aspect = dest.width() / dest.height();
    let img_aspect = intrinsic.x / intrinsic.y;
    if img_aspect > dest_aspect {
        // image wider than dest — crop sides
        let scale = dest_aspect / img_aspect;
        let pad = (1.0 - scale) / 2.0;
        Rect::from_min_max(pos2(pad, 0.0), pos2(1.0 - pad, 1.0))
    } else {
        // image taller than dest — crop top/bottom
        let scale = img_aspect / dest_aspect;
        let pad = (1.0 - scale) / 2.0;
        Rect::from_min_max(pos2(0.0, pad), pos2(1.0, 1.0 - pad))
    }
}

/// Fade alpha for a background-image reveal. Stamps the first-`ready` time in
/// `ctx` memory under `id`, so the image tint and (optionally) the body content
/// fade in lockstep off the same clock. Returns 1.0 when `duration <= 0`, and
/// 0.0 while `ready` is false — without stamping, so the clock only starts once
/// the texture has actually landed.
/// Vertically distribute body content within a container that has a known height.
///
/// Adds a top spacer of `(fill_height - cached_content_h) * justify_factor`,
/// renders the body (invisibly on the first frame when no height is cached yet),
/// then writes the measured content height back to memory and requests a repaint
/// on that measurement frame so the content appears correctly positioned
/// immediately on the next frame without a visible pop.
///
/// - `fill_height`: the container's total available height (e.g. `screen_size.y`
///   or `ui.available_height()` before sizing calls).
/// - `justify_factor`: 0.0 = top, 0.5 = center, 1.0 = bottom (from
///   [`egui::Align::to_factor`]).
/// - `content_h_id`: a stable [`egui::Id`] used to persist the measured height
///   between frames. Derive with `ui.make_persistent_id(...).with("some_tag")`.
pub fn justify_body_vertically<R>(
    ui: &mut egui::Ui,
    fill_height: f32,
    justify_factor: f32,
    content_h_id: egui::Id,
    body: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
    let cached_h = ui.ctx().memory(|m| m.data.get_temp::<f32>(content_h_id));
    let top_pad = ((fill_height - cached_h.unwrap_or(0.0)) * justify_factor).max(0.0);
    ui.add_space(top_pad);
    let scope = ui.scope(|ui| {
        if cached_h.is_none() {
            ui.set_invisible();
        }
        body(ui)
    });
    let measured_h = scope.response.rect.height();
    ui.ctx()
        .memory_mut(|m| m.data.insert_temp(content_h_id, measured_h));
    if cached_h.is_none() {
        ui.ctx().request_repaint();
    }
    scope.inner
}

/// Fade alpha for a background-image reveal. Stamps the first-`ready` time in
pub fn bgimg_fade_alpha(ctx: &egui::Context, id: egui::Id, duration: f32, ready: bool) -> f32 {
    if duration <= 0.0 {
        return 1.0;
    }
    if !ready {
        return 0.0;
    }
    let now = ctx.input(|i| i.time);
    let start = ctx.memory_mut(|m| *m.data.get_temp_mut_or_insert_with(id, || now));
    let alpha = (((now - start) / duration as f64).clamp(0.0, 1.0)) as f32;
    if alpha < 1.0 {
        ctx.request_repaint();
    }
    alpha
}

/// Build the `Shape` that paints a background image clipped to a rounded rect.
///
/// Returns `None` only when there is nothing to draw (no `bg`, no `border`, and
/// texture not yet ready). The `bg` fill and `border` paint every frame; the
/// textured layer is added on top once the texture is `Ready`.
///
/// Layers (front-to-back inside the returned `Shape::Vec`):
/// 1. `bg` fill (if any) — solid colour behind the texture
/// 2. Texture rectangle (rounded, tinted) — omitted while still loading
/// 3. Border stroke on top
#[allow(clippy::too_many_arguments)]
pub fn background_image_shape(
    ui: &egui::Ui,
    rect: Rect,
    corner_radius: CornerRadius,
    image: &egui::Image<'static>,
    fit: BackgroundImageFit,
    tint: Color32,
    bg: Option<Color32>,
    border: Option<Stroke>,
    border_sides: Option<ResolvedBorder>,
    fade: Option<(egui::Id, f32)>,
) -> Option<Shape> {
    use egui::epaint::RectShape;
    use egui::load::TexturePoll;

    let mut parts: Vec<Shape> = Vec::with_capacity(3);

    // Bg fill paints every frame from the first — does not wait for the texture.
    if let Some(fill) = bg {
        parts.push(Shape::rect_filled(rect, corner_radius, fill));
    }

    // Probe the texture; only add the textured layer when it is Ready.
    let poll = image.load_for_size(ui.ctx(), rect.size()).ok();
    if let Some(TexturePoll::Ready { texture }) = poll {
        let tint = match fade {
            // We only reach here once the texture is Ready.
            Some((id, duration)) if duration > 0.0 => {
                tint.gamma_multiply(bgimg_fade_alpha(ui.ctx(), id, duration, true))
            }
            _ => tint,
        };

        let uv = match fit {
            BackgroundImageFit::Stretch => Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
            BackgroundImageFit::Cover => cover_uv(texture.size, rect),
        };

        let tex_shape = RectShape::filled(rect, corner_radius, tint).with_texture(texture.id, uv);
        parts.push(Shape::Rect(tex_shape));
    }

    if let Some(sides) = border_sides {
        // Per-side overrides: paint each edge as a straight line segment, same
        // as `paint_side_borders`. Takes precedence over the uniform `border`.
        let mut push = |a, b, stroke: Stroke| {
            if stroke.width > 0.0 {
                parts.push(Shape::line_segment([a, b], stroke));
            }
        };
        push(rect.left_top(), rect.right_top(), sides.top);
        push(rect.right_top(), rect.right_bottom(), sides.right);
        push(rect.left_bottom(), rect.right_bottom(), sides.bottom);
        push(rect.left_top(), rect.left_bottom(), sides.left);
    } else if let Some(stroke) = border {
        parts.push(Shape::rect_stroke(
            rect,
            corner_radius,
            stroke,
            egui::StrokeKind::Outside,
        ));
    }

    if parts.is_empty() {
        None
    } else {
        Some(Shape::Vec(parts))
    }
}

/// Render `f` inside a child scope so a `visible == false` widget's
/// invisibility is contained to itself.
///
/// `Ui::set_invisible()` mutates the painter/enabled state of the `Ui` it's
/// called on and affects *all* subsequent widgets. Calling it on a cloned
/// child `Ui` (what `ui.scope` provides) keeps the effect local: the widget
/// hides but still allocates layout space, and following siblings are
/// unaffected. The scope must enclose the widget's entire visual output —
/// frame, shadows, and inner content — so call shadow allocation/painting
/// inside `f`.
pub fn render_scoped<R>(ui: &mut egui::Ui, visible: bool, f: impl FnOnce(&mut egui::Ui) -> R) -> R {
    ui.scope(|ui| {
        if !visible {
            ui.set_invisible();
        }
        f(ui)
    })
    .inner
}

/// The style bag carried by every styled widget.
///
/// Every field is `Option<T>` so `None` falls through to egui's active
/// `Visuals` at resolve time - we never overwrite a default the user didn't
/// explicitly set. Widget-specific properties (button image, slider step,
/// etc.) live on the widget struct itself, not here.
///
/// You rarely construct this directly; the `impl_style_builders!` macro
/// generates `.bg()`, `.hover_bg()`, etc. on each styled type.
#[derive(Clone, Default, Debug)]
pub struct SharedStyle {
    // Background
    pub bg: Option<Color32>,
    pub hover_bg: Option<Color32>,
    pub active_bg: Option<Color32>,
    pub focus_bg: Option<Color32>,

    // Accent — maps to egui's `selection.bg_fill` / `selection.stroke`
    // (slider trailing fill, text-edit focus ring, text selection highlight).
    pub accent: Option<Color32>,
    pub hover_accent: Option<Color32>,

    // Text
    pub text_color: Option<Color32>,
    pub hover_text_color: Option<Color32>,
    pub font_size: Option<f32>,
    pub font_id: Option<FontId>,

    // Border
    pub border: Option<Stroke>,
    pub hover_border: Option<Stroke>,
    pub focus_border: Option<Stroke>,

    // Per-side border overrides. Each side falls back to the matching uniform
    // border above when unset. `border_sides` is the base state; the hover/focus
    // variants override it under those interaction states.
    pub border_sides: SideStrokes,
    pub hover_border_sides: SideStrokes,
    pub focus_border_sides: SideStrokes,

    // Geometry
    pub corner_radius: Option<CornerRadius>,
    pub padding: Option<Margin>,
    pub margin: Option<Margin>,

    // Sizing
    pub min_width: Option<f32>,
    pub max_width: Option<f32>,
    pub min_height: Option<f32>,
    pub max_height: Option<f32>,
    pub full_width: bool,
    pub full_height: bool,

    // Cursor
    pub cursor_icon: Option<CursorIcon>,

    // Visibility — `Some(false)` calls `Ui::set_invisible()`: reserves layout
    // space, skips painting, implies disabled (no hover/click interaction).
    // `None` and `Some(true)` are both fully visible.
    pub visible: Option<bool>,

    // Decorations
    pub shadows: Vec<Shadow>,

    // Background image — drawn on top of `bg` fill, clipped to the same rounded rect.
    // Texture loading is the consuming app's responsibility (egui loader registry or
    // `ctx.load_texture`). egui_styled only paints a texture it has already received.
    pub background_image: Option<egui::Image<'static>>,
    pub background_image_fit: BackgroundImageFit,
    pub background_image_tint: Option<Color32>,
    /// Opt-in fade-in duration (seconds). When `Some`, the image fades up from
    /// the bg backdrop over the given duration once its texture is Ready.
    /// `None` = no fade (snap in, default behavior).
    pub background_image_fade_in: Option<f32>,
    /// When `true`, the body content fades in together with the background image
    /// (same timing) instead of rendering immediately over the backdrop. Set via
    /// `reveal_with_background_image`. The `bg` fill stays opaque.
    pub background_image_fade_content: bool,
}

/// Concrete style values for one interaction state after resolving pseudo-state
/// and falling back to egui defaults.
#[derive(Clone)]
pub struct ResolvedStyle {
    pub bg: Color32,
    pub text_color: Color32,
    /// Uniform border representative — preserves existing behavior (egui
    /// `bg_stroke`, focus ring). Equal to the resolved uniform base stroke.
    pub border: Stroke,
    /// Full per-side border. Each side = override.or(uniform base).or(default).
    /// Only painted (via [`paint_side_borders`]) when `has_border_overrides`.
    pub border_sides: ResolvedBorder,
    /// True when this state has any per-side override set. Drives the switch
    /// between egui's uniform painting and manual per-side painting.
    pub has_border_overrides: bool,
    pub corner_radius: CornerRadius,
    pub padding: Margin,
    pub margin: Margin,
    pub cursor_icon: Option<CursorIcon>,
}

/// Resolved style for all interaction states simultaneously. Allows writing
/// each per-state colour into the matching `WidgetVisuals` slot so egui's own
/// hover/active response picks the right variant without clobbering it.
#[derive(Clone)]
pub struct PerStateStyle {
    pub inactive: ResolvedStyle,
    pub hovered: ResolvedStyle,
    pub active: ResolvedStyle,
    /// Focused mirrors `focus_*` fields; falls back to `inactive` if unset.
    pub focused: ResolvedStyle,
    /// Maps to `selection.bg_fill` (slider trail, text selection).
    pub accent: Color32,
    /// Maps to `selection.bg_fill` on hover.
    pub hover_accent: Color32,
    /// Shared across states.
    pub corner_radius: CornerRadius,
    pub padding: Margin,
    pub margin: Margin,
    pub cursor_icon: Option<CursorIcon>,
}

impl SharedStyle {
    /// Resolve against current pseudo-state and egui's active visuals.
    /// Kept for back-compat; prefer `resolve_per_state` for new widget code.
    pub fn resolve(&self, state: PseudoState, default: &WidgetVisuals) -> ResolvedStyle {
        let bg = match state {
            _ if state.active && self.active_bg.is_some() => self.active_bg.unwrap(),
            _ if state.hovered && self.hover_bg.is_some() => self.hover_bg.unwrap(),
            _ if state.focused && self.focus_bg.is_some() => self.focus_bg.unwrap(),
            _ => self.bg.unwrap_or(default.bg_fill),
        };

        let border = match state {
            _ if state.focused && self.focus_border.is_some() => self.focus_border.unwrap(),
            _ if state.hovered && self.hover_border.is_some() => self.hover_border.unwrap(),
            _ => self.border.unwrap_or(default.bg_stroke),
        };

        // Per-side overrides follow the same focus > hover > base precedence as
        // the uniform border. Each side falls back to `border` (the resolved
        // uniform stroke) when not explicitly overridden for this state.
        let sides = match state {
            _ if state.focused && self.focus_border_sides.any() => self.focus_border_sides,
            _ if state.hovered && self.hover_border_sides.any() => self.hover_border_sides,
            _ => self.border_sides,
        };
        let has_border_overrides = sides.any();
        let border_sides = ResolvedBorder {
            top: sides.top.unwrap_or(border),
            right: sides.right.unwrap_or(border),
            bottom: sides.bottom.unwrap_or(border),
            left: sides.left.unwrap_or(border),
        };

        let text_color = match state {
            _ if state.hovered && self.hover_text_color.is_some() => self.hover_text_color.unwrap(),
            _ => self.text_color.unwrap_or(default.text_color()),
        };

        ResolvedStyle {
            bg,
            text_color,
            border,
            border_sides,
            has_border_overrides,
            corner_radius: self.corner_radius.unwrap_or(default.corner_radius),
            padding: self.padding.unwrap_or_default(),
            margin: self.margin.unwrap_or_default(),
            cursor_icon: self.cursor_icon,
        }
    }

    /// Resolve a `ResolvedStyle` for each interaction state independently.
    /// Use this in widget `show()` implementations so each state's colour is
    /// written into the matching `WidgetVisuals` slot.
    pub fn resolve_per_state(&self, visuals: &Visuals) -> PerStateStyle {
        let resolve_one = |state: PseudoState, wv: &WidgetVisuals| self.resolve(state, wv);

        let inactive = resolve_one(
            PseudoState {
                hovered: false,
                active: false,
                focused: false,
            },
            &visuals.widgets.inactive,
        );
        let hovered = resolve_one(
            PseudoState {
                hovered: true,
                active: false,
                focused: false,
            },
            &visuals.widgets.hovered,
        );
        let active = resolve_one(
            PseudoState {
                hovered: true,
                active: true,
                focused: false,
            },
            &visuals.widgets.active,
        );
        let focused = resolve_one(
            PseudoState {
                hovered: false,
                active: false,
                focused: true,
            },
            &visuals.widgets.inactive,
        );

        let corner_radius = self
            .corner_radius
            .unwrap_or(visuals.widgets.inactive.corner_radius);
        let accent = self.accent.unwrap_or(visuals.selection.bg_fill);
        let hover_accent = self.hover_accent.unwrap_or(accent);

        PerStateStyle {
            inactive,
            hovered,
            active,
            focused,
            accent,
            hover_accent,
            corner_radius,
            padding: self.padding.unwrap_or_default(),
            margin: self.margin.unwrap_or_default(),
            cursor_icon: self.cursor_icon,
        }
    }

    /// Write `per_state` into `vis` so every egui widget inside the current
    /// `ui.scope` inherits correct per-interaction-state colours.
    ///
    /// Handles all known egui visuals quirks:
    /// - `weak_bg_fill` (used by ComboBox button) is kept in sync with `bg_fill`
    /// - `expansion` is zeroed so border rects don't drift
    /// - `selection.bg_fill` receives `accent` (slider trail, text selection)
    /// - `selection.stroke` receives `focused.border` (text-edit focus ring)
    /// - `extreme_bg_color` receives `inactive.bg` (TextEdit background)
    pub fn apply_to_visuals(per: &PerStateStyle, vis: &mut Visuals) {
        let states: [(&ResolvedStyle, &mut WidgetVisuals); 3] = [
            (&per.inactive, &mut vis.widgets.inactive),
            (&per.hovered, &mut vis.widgets.hovered),
            (&per.active, &mut vis.widgets.active),
        ];
        for (resolved, wv) in states {
            wv.bg_fill = resolved.bg;
            wv.weak_bg_fill = resolved.bg;
            // When per-side overrides are present we paint the border ourselves
            // (egui's bg_stroke is uniform-only), so suppress egui's stroke.
            wv.bg_stroke = if resolved.has_border_overrides {
                Stroke::NONE
            } else {
                resolved.border
            };
            wv.corner_radius = per.corner_radius;
            wv.expansion = 0.0;
            wv.fg_stroke = Stroke::new(wv.fg_stroke.width, resolved.text_color);
        }
        // Also update the open state for combo-box menus.
        vis.widgets.open.bg_fill = per.inactive.bg;
        vis.widgets.open.weak_bg_fill = per.inactive.bg;
        vis.widgets.open.bg_stroke = if per.inactive.has_border_overrides {
            Stroke::NONE
        } else {
            per.inactive.border
        };
        vis.widgets.open.corner_radius = per.corner_radius;
        vis.widgets.open.expansion = 0.0;

        vis.extreme_bg_color = per.inactive.bg;
        vis.selection.bg_fill = per.accent;
        vis.selection.stroke = per.focused.border;
    }

    /// Pick the `ResolvedStyle` matching a widget response's interaction state,
    /// mirroring which `WidgetVisuals` slot egui itself would paint with.
    pub fn for_response<'a>(
        per: &'a PerStateStyle,
        response: &egui::Response,
    ) -> &'a ResolvedStyle {
        if response.has_focus() {
            &per.focused
        } else if response.is_pointer_button_down_on() {
            &per.active
        } else if response.hovered() {
            &per.hovered
        } else {
            &per.inactive
        }
    }

    /// Paint per-side borders for a widget when the response's interaction state
    /// has overrides set. No-op otherwise (egui already painted the uniform
    /// `bg_stroke`). Call after the widget renders, using its response rect.
    pub fn paint_widget_side_borders(
        ui: &egui::Ui,
        response: &egui::Response,
        per: &PerStateStyle,
    ) {
        let state = Self::for_response(per, response);
        if state.has_border_overrides {
            paint_side_borders(ui.painter(), response.rect, state.border_sides);
        }
    }

    /// True if any field that an [`egui::Frame`] could render is set.
    ///
    /// Containers (`StyledRow`, `StyledColumn`, `StyledStack`) use this to
    /// decide whether to wrap themselves in a `StyledFrame` or render directly.
    /// `margin` counts because it is applied via the wrapper frame's
    /// `outer_margin` - a margin-only container must still route through the
    /// frame or the spacing is silently dropped. Text color and sizing are
    /// intentionally excluded - they are not "frame" concerns.
    pub fn has_frame_styles(&self) -> bool {
        self.bg.is_some()
            || self.hover_bg.is_some()
            || self.active_bg.is_some()
            || self.focus_bg.is_some()
            || self.border.is_some()
            || self.hover_border.is_some()
            || self.focus_border.is_some()
            || self.border_sides.any()
            || self.hover_border_sides.any()
            || self.focus_border_sides.any()
            || self.padding.is_some()
            || self.corner_radius.is_some()
            || self.margin.is_some()
            || self.background_image.is_some()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use egui::Visuals;

    fn default_visuals() -> WidgetVisuals {
        Visuals::default().widgets.inactive
    }

    fn style_with_all_bgs() -> SharedStyle {
        SharedStyle {
            bg: Some(Color32::RED),
            hover_bg: Some(Color32::GREEN),
            active_bg: Some(Color32::BLUE),
            focus_bg: Some(Color32::YELLOW),
            ..Default::default()
        }
    }

    #[test]
    fn bg_active_beats_hovered_and_focused() {
        let style = style_with_all_bgs();
        let state = PseudoState {
            hovered: true,
            active: true,
            focused: true,
        };
        let resolved = style.resolve(state, &default_visuals());
        assert_eq!(resolved.bg, Color32::BLUE);
    }

    #[test]
    fn bg_hovered_beats_focused() {
        let style = style_with_all_bgs();
        let state = PseudoState {
            hovered: true,
            active: false,
            focused: true,
        };
        let resolved = style.resolve(state, &default_visuals());
        assert_eq!(resolved.bg, Color32::GREEN);
    }

    #[test]
    fn bg_focused_used_when_only_focused() {
        let style = style_with_all_bgs();
        let state = PseudoState {
            hovered: false,
            active: false,
            focused: true,
        };
        let resolved = style.resolve(state, &default_visuals());
        assert_eq!(resolved.bg, Color32::YELLOW);
    }

    #[test]
    fn bg_base_used_when_no_pseudo_state() {
        let style = style_with_all_bgs();
        let resolved = style.resolve(PseudoState::default(), &default_visuals());
        assert_eq!(resolved.bg, Color32::RED);
    }

    #[test]
    fn falls_back_to_default_visuals_when_unset() {
        let style = SharedStyle::default();
        let visuals = default_visuals();
        let resolved = style.resolve(PseudoState::default(), &visuals);
        assert_eq!(resolved.bg, visuals.bg_fill);
        assert_eq!(resolved.border, visuals.bg_stroke);
        assert_eq!(resolved.corner_radius, visuals.corner_radius);
        assert_eq!(resolved.text_color, visuals.text_color());
    }

    #[test]
    fn hover_text_color_only_applies_when_hovered() {
        let style = SharedStyle {
            text_color: Some(Color32::RED),
            hover_text_color: Some(Color32::GREEN),
            ..Default::default()
        };
        let visuals = default_visuals();

        let active = PseudoState {
            hovered: false,
            active: true,
            focused: false,
        };
        assert_eq!(style.resolve(active, &visuals).text_color, Color32::RED);

        let focused = PseudoState {
            hovered: false,
            active: false,
            focused: true,
        };
        assert_eq!(style.resolve(focused, &visuals).text_color, Color32::RED);

        let hovered = PseudoState {
            hovered: true,
            active: false,
            focused: false,
        };
        assert_eq!(style.resolve(hovered, &visuals).text_color, Color32::GREEN);
    }

    #[test]
    fn border_focused_beats_hovered() {
        let hover = Stroke::new(1.0, Color32::GREEN);
        let focus = Stroke::new(2.0, Color32::YELLOW);
        let style = SharedStyle {
            hover_border: Some(hover),
            focus_border: Some(focus),
            ..Default::default()
        };
        let state = PseudoState {
            hovered: true,
            active: false,
            focused: true,
        };
        let resolved = style.resolve(state, &default_visuals());
        assert_eq!(resolved.border, focus);
    }

    #[test]
    fn side_override_sets_only_that_side() {
        let left = Stroke::new(3.0, Color32::RED);
        let style = SharedStyle {
            border_sides: SideStrokes {
                left: Some(left),
                ..Default::default()
            },
            ..Default::default()
        };
        let visuals = default_visuals();
        let resolved = style.resolve(PseudoState::default(), &visuals);
        assert!(resolved.has_border_overrides);
        assert_eq!(resolved.border_sides.left, left);
        // Unset sides fall back to the uniform base (here egui's default stroke).
        assert_eq!(resolved.border_sides.top, visuals.bg_stroke);
        assert_eq!(resolved.border_sides.right, visuals.bg_stroke);
        assert_eq!(resolved.border_sides.bottom, visuals.bg_stroke);
    }

    #[test]
    fn side_override_falls_back_to_uniform_border() {
        let uniform = Stroke::new(1.0, Color32::GRAY);
        let left = Stroke::new(3.0, Color32::RED);
        let style = SharedStyle {
            border: Some(uniform),
            border_sides: SideStrokes {
                left: Some(left),
                ..Default::default()
            },
            ..Default::default()
        };
        let resolved = style.resolve(PseudoState::default(), &default_visuals());
        assert_eq!(resolved.border_sides.left, left);
        assert_eq!(resolved.border_sides.top, uniform);
        assert_eq!(resolved.border_sides.right, uniform);
        assert_eq!(resolved.border_sides.bottom, uniform);
        // The uniform representative is unchanged.
        assert_eq!(resolved.border, uniform);
    }

    #[test]
    fn no_side_override_means_no_overrides_flag() {
        let uniform = Stroke::new(1.0, Color32::GRAY);
        let style = SharedStyle {
            border: Some(uniform),
            ..Default::default()
        };
        let resolved = style.resolve(PseudoState::default(), &default_visuals());
        assert!(!resolved.has_border_overrides);
        assert_eq!(resolved.border, uniform);
    }

    #[test]
    fn focus_side_override_beats_base() {
        let base_left = Stroke::new(1.0, Color32::GRAY);
        let focus_left = Stroke::new(2.0, Color32::YELLOW);
        let style = SharedStyle {
            border_sides: SideStrokes {
                left: Some(base_left),
                ..Default::default()
            },
            focus_border_sides: SideStrokes {
                left: Some(focus_left),
                ..Default::default()
            },
            ..Default::default()
        };
        let focused = PseudoState {
            hovered: false,
            active: false,
            focused: true,
        };
        assert_eq!(
            style.resolve(focused, &default_visuals()).border_sides.left,
            focus_left
        );
        // Base state still uses the base side.
        assert_eq!(
            style
                .resolve(PseudoState::default(), &default_visuals())
                .border_sides
                .left,
            base_left
        );
    }

    #[test]
    fn paint_side_borders_only_emits_positive_width_sides() {
        let ctx = egui::Context::default();
        let output = ctx.run_ui(egui::RawInput::default(), |ui| {
            let rect = Rect::from_min_size(pos2(0.0, 0.0), Vec2::new(50.0, 30.0));
            // Only left + right have width; top + bottom are zero-width.
            let border = ResolvedBorder {
                top: Stroke::NONE,
                right: Stroke::new(2.0, Color32::RED),
                bottom: Stroke::new(0.0, Color32::RED),
                left: Stroke::new(2.0, Color32::RED),
            };
            paint_side_borders(ui.painter(), rect, border);
        });
        let segments = output
            .shapes
            .iter()
            .filter(|cs| matches!(cs.shape, Shape::LineSegment { .. }))
            .count();
        assert_eq!(segments, 2, "expected one segment per positive-width side");
    }

    #[test]
    fn has_frame_styles_empty() {
        assert!(!SharedStyle::default().has_frame_styles());
    }

    #[test]
    fn has_frame_styles_each_trigger() {
        let triggers: Vec<(&str, SharedStyle)> = vec![
            (
                "bg",
                SharedStyle {
                    bg: Some(Color32::RED),
                    ..Default::default()
                },
            ),
            (
                "hover_bg",
                SharedStyle {
                    hover_bg: Some(Color32::RED),
                    ..Default::default()
                },
            ),
            (
                "active_bg",
                SharedStyle {
                    active_bg: Some(Color32::RED),
                    ..Default::default()
                },
            ),
            (
                "focus_bg",
                SharedStyle {
                    focus_bg: Some(Color32::RED),
                    ..Default::default()
                },
            ),
            (
                "border",
                SharedStyle {
                    border: Some(Stroke::new(1.0, Color32::RED)),
                    ..Default::default()
                },
            ),
            (
                "hover_border",
                SharedStyle {
                    hover_border: Some(Stroke::new(1.0, Color32::RED)),
                    ..Default::default()
                },
            ),
            (
                "focus_border",
                SharedStyle {
                    focus_border: Some(Stroke::new(1.0, Color32::RED)),
                    ..Default::default()
                },
            ),
            (
                "padding",
                SharedStyle {
                    padding: Some(egui::Margin::same(4)),
                    ..Default::default()
                },
            ),
            (
                "corner_radius",
                SharedStyle {
                    corner_radius: Some(egui::CornerRadius::same(4)),
                    ..Default::default()
                },
            ),
            (
                "margin",
                SharedStyle {
                    margin: Some(egui::Margin::same(4)),
                    ..Default::default()
                },
            ),
            (
                "border_sides",
                SharedStyle {
                    border_sides: SideStrokes {
                        left: Some(Stroke::new(1.0, Color32::RED)),
                        ..Default::default()
                    },
                    ..Default::default()
                },
            ),
        ];
        for (name, style) in triggers {
            assert!(
                style.has_frame_styles(),
                "{name} did not trigger has_frame_styles"
            );
        }
    }

    #[test]
    fn has_frame_styles_ignores_non_frame_props() {
        // text_color and full_width are not frame concerns and must not flip
        // has_frame_styles. (margin does count - see has_frame_styles_each_trigger.)
        let style = SharedStyle {
            text_color: Some(Color32::RED),
            full_width: true,
            ..Default::default()
        };
        assert!(!style.has_frame_styles());
    }

    #[test]
    fn resolve_per_state_each_variant_independent() {
        let style = SharedStyle {
            bg: Some(Color32::RED),
            hover_bg: Some(Color32::GREEN),
            active_bg: Some(Color32::BLUE),
            focus_bg: Some(Color32::YELLOW),
            accent: Some(Color32::WHITE),
            ..Default::default()
        };
        let vis = Visuals::default();
        let per = style.resolve_per_state(&vis);
        assert_eq!(per.inactive.bg, Color32::RED);
        assert_eq!(per.hovered.bg, Color32::GREEN);
        assert_eq!(per.active.bg, Color32::BLUE);
        assert_eq!(per.focused.bg, Color32::YELLOW);
        assert_eq!(per.accent, Color32::WHITE);
    }

    #[test]
    fn resolve_per_state_accent_falls_back_to_selection_bg_fill() {
        let style = SharedStyle::default();
        let vis = Visuals::default();
        let per = style.resolve_per_state(&vis);
        assert_eq!(per.accent, vis.selection.bg_fill);
    }

    #[test]
    fn background_image_fit_default_is_stretch() {
        assert_eq!(BackgroundImageFit::default(), BackgroundImageFit::Stretch);
    }

    #[test]
    fn has_frame_styles_triggered_by_background_image() {
        let style = SharedStyle {
            background_image: Some(egui::Image::from_bytes("bytes://test", vec![])),
            ..Default::default()
        };
        assert!(style.has_frame_styles());
    }

    #[test]
    fn cover_uv_stretch_returns_full() {
        let dest = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::Vec2::new(100.0, 100.0));
        let uv = cover_uv(egui::Vec2::new(200.0, 100.0), dest);
        // Stretch isn't tested via cover_uv; Cover is. Wider image into square dest:
        // img_aspect=2, dest_aspect=1 → scale=0.5, pad=0.25 on x axis
        let uv_cover = cover_uv(egui::Vec2::new(200.0, 100.0), dest);
        assert!((uv_cover.min.x - 0.25).abs() < 1e-5);
        assert!((uv_cover.max.x - 0.75).abs() < 1e-5);
        assert!((uv_cover.min.y - 0.0).abs() < 1e-5);
        assert!((uv_cover.max.y - 1.0).abs() < 1e-5);
        let _ = uv;
    }

    #[test]
    fn cover_uv_tall_image_crops_vertically() {
        // 100×200 image into 100×100 dest → taller image, crop top/bottom
        let dest = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::Vec2::new(100.0, 100.0));
        let uv = cover_uv(egui::Vec2::new(100.0, 200.0), dest);
        assert!((uv.min.x - 0.0).abs() < 1e-5);
        assert!((uv.max.x - 1.0).abs() < 1e-5);
        // img_aspect=0.5, dest_aspect=1 → scale=0.5, pad=0.25 on y axis
        assert!((uv.min.y - 0.25).abs() < 1e-5);
        assert!((uv.max.y - 0.75).abs() < 1e-5);
    }

    #[test]
    fn cover_uv_square_image_returns_full() {
        let dest = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::Vec2::new(100.0, 100.0));
        let uv = cover_uv(egui::Vec2::new(100.0, 100.0), dest);
        assert!((uv.min.x - 0.0).abs() < 1e-5);
        assert!((uv.max.x - 1.0).abs() < 1e-5);
        assert!((uv.min.y - 0.0).abs() < 1e-5);
        assert!((uv.max.y - 1.0).abs() < 1e-5);
    }
}