sinomo-ui-widgets 0.4.1

Built-in widget library for SUI.
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
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
use crate::ControlMetrics;
use crate::DefaultTheme;
use crate::GlowTone;
use crate::IconGlyph;
use crate::Interpolate;
use crate::Progress;
use crate::ResolvedEffectStyle;
use crate::SemanticTone;
use crate::ThemeTextToken;
use crate::binding::Binding;
use crate::composites::popups::TooltipPlacement;
use crate::composites::status::{StatusBadge, paint_status_badge};
use crate::controls::apply_hdr_policy_cap;
use crate::draw::{inset_rect, measure_text, mix_color, rect_center};
use crate::frame::{draw_control_shape, physical_pixels, stroke_border};
use crate::paint_theme_glow;
use crate::text_align::paint_text;
use crate::text_align::paint_text_line;
use sui_core::Color;
use sui_core::Path;
use sui_core::PathBuilder;
use sui_core::Point;
use sui_core::Rect;
use sui_core::SemanticsNode;
use sui_core::SemanticsRole;
use sui_core::SemanticsValue;
use sui_core::Size;
use sui_core::Vector;
use sui_layout::Constraints;
use sui_layout::Padding as Insets;
use sui_reactive::Observable;
use sui_runtime::MeasureCtx;
use sui_runtime::PaintCtx;
use sui_runtime::SemanticsCtx;
use sui_runtime::Widget;
use sui_text::FontWeight;
use sui_text::TextStyle;
use sui_text::{FontFeature, TextAlign};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CoverageDotsConfig {
    pub current: usize,
    pub target: usize,
    pub tone: SemanticTone,
    pub max_dots: usize,
    pub show_label: bool,
}

impl Default for CoverageDotsConfig {
    fn default() -> Self {
        Self::new(0, 0)
    }
}

impl CoverageDotsConfig {
    pub fn new(current: usize, target: usize) -> Self {
        Self {
            current,
            target,
            tone: SemanticTone::Neutral,
            max_dots: 4,
            show_label: true,
        }
    }

    pub(super) fn normalized_target(self) -> usize {
        self.target.max(self.current)
    }

    pub(super) fn normalized_max_dots(self) -> usize {
        self.max_dots.max(1)
    }

    pub(super) fn label(self) -> String {
        format!("{}/{}", self.current, self.normalized_target())
    }
}

pub fn paint_coverage_dots(
    ctx: &mut PaintCtx,
    theme: &DefaultTheme,
    rect: Rect,
    current: usize,
    target: usize,
    tone: SemanticTone,
) {
    let mut config = CoverageDotsConfig::new(current, target);
    config.tone = tone;
    paint_coverage_dots_with_config(ctx, theme, rect, config);
}

pub fn paint_coverage_dots_with_config(
    ctx: &mut PaintCtx,
    theme: &DefaultTheme,
    rect: Rect,
    config: CoverageDotsConfig,
) {
    let target = config.normalized_target();
    if target == 0 || rect.width() <= 0.0 || rect.height() <= 0.0 {
        return;
    }

    let (dot, gap, label_gap) = coverage_dot_metrics(theme);
    let label = config.label();
    let text_style = numeric_text_style(text_token_style(
        theme,
        theme.text.xs,
        theme.palette.text_muted,
    ));
    let label_width = if config.show_label {
        ctx.measure_text(label.clone(), text_style.clone())
            .map(|measurement| measurement.width)
            .unwrap_or(0.0)
    } else {
        0.0
    };
    // Keep the exact count readable first. Dots are redundant decoration and
    // disappear as a group when their complete representation does not fit.
    let shown = target.min(config.normalized_max_dots());
    let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
    let separation = if config.show_label { label_gap } else { 0.0 };
    let show_dots = dots_width + separation + label_width <= rect.width();
    let mut x = rect.x();
    ctx.push_clip_rect(rect);
    if show_dots {
        let y = rect.y() + (rect.height() - dot) * 0.5;
        let (tone_color, _) = theme.semantic_tone_colors(config.tone);
        for index in 0..shown {
            let dot_rect = Rect::new(x, y, dot, dot);
            if index < config.current.min(shown) {
                ctx.fill(Path::rounded_rect(dot_rect, dot * 0.5), tone_color);
            } else {
                stroke_border(
                    ctx,
                    dot_rect,
                    dot * 0.5,
                    physical_pixels(ctx, theme.metrics.border_width.max(1.0)),
                    theme.palette.border,
                );
            }
            x += dot + gap;
        }
        x += separation - gap;
    }
    if config.show_label {
        let label_rect = Rect::new(x, rect.y(), (rect.max_x() - x).max(0.0), rect.height());
        paint_text_line(ctx, label_rect, &label, &text_style, TextAlign::Start);
    }
    ctx.pop_clip();
}

pub(super) fn coverage_dot_metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
    let dot = (theme.text.xs.size * 0.42).clamp(4.0, 6.0);
    let gap = (dot * 0.65).clamp(2.0, 4.0);
    let label_gap = (theme.metrics.icon_label_gap * 0.7).max(4.0);
    (dot, gap, label_gap)
}

pub struct CoverageDots {
    pub(super) theme: Box<DefaultTheme>,
    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
    pub(super) name: String,
    pub(super) config: CoverageDotsConfig,
    pub(super) min_width: Option<f32>,
}

impl CoverageDots {
    pub fn new(name: impl Into<String>, current: usize, target: usize) -> Self {
        Self {
            theme: Box::new(DefaultTheme::default()),
            theme_reader: None,
            name: name.into(),
            config: CoverageDotsConfig::new(current, target),
            min_width: None,
        }
    }

    pub fn theme(mut self, theme: DefaultTheme) -> Self {
        self.theme = Box::new(theme);
        self.theme_reader = None;
        self
    }

    pub fn theme_when<F>(mut self, theme: F) -> Self
    where
        F: Fn() -> DefaultTheme + 'static,
    {
        self.theme_reader = Some(Box::new(theme));
        self
    }

    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.config.tone = tone;
        self
    }

    pub fn max_dots(mut self, max_dots: usize) -> Self {
        self.config.max_dots = max_dots;
        self
    }

    pub fn show_label(mut self, show_label: bool) -> Self {
        self.config.show_label = show_label;
        self
    }

    pub fn min_width(mut self, min_width: f32) -> Self {
        self.min_width = Some(min_width.max(0.0));
        self
    }

    pub(super) fn resolved_theme(&self) -> DefaultTheme {
        self.theme_reader
            .as_ref()
            .map(|theme| theme())
            .unwrap_or(*self.theme)
    }
}

impl Widget for CoverageDots {
    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        let theme = self.resolved_theme();
        let target = self.config.normalized_target();
        if target == 0 {
            return constraints.clamp(Size::ZERO);
        }
        let (dot, gap, label_gap) = coverage_dot_metrics(&theme);
        let shown = target.min(self.config.normalized_max_dots());
        let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
        let label_width = if self.config.show_label {
            measure_text(
                ctx,
                &self.config.label(),
                &numeric_text_style(text_token_style(
                    &theme,
                    theme.text.xs,
                    theme.palette.text_muted,
                )),
            )
            .width
                + label_gap
        } else {
            0.0
        };
        constraints.clamp(Size::new(
            self.min_width.unwrap_or(0.0).max(dots_width + label_width),
            theme
                .text
                .xs
                .line_height
                .max(dot + 2.0)
                .max(theme.metrics.min_height * 0.55),
        ))
    }

    fn paint(&self, ctx: &mut PaintCtx) {
        paint_coverage_dots_with_config(ctx, &self.resolved_theme(), ctx.bounds(), self.config);
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let target = self.config.normalized_target();
        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
        node.name = Some(self.name.clone());
        node.value = Some(SemanticsValue::Text(self.config.label()));
        node.description = Some(format!(
            "{} of {} covered",
            self.config.current.min(target),
            target
        ));
        ctx.push(node);
    }
}

pub struct PlacementBadge {
    pub(super) theme: Box<DefaultTheme>,
    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
    pub(super) label: Binding<String>,
    pub(super) icon: Option<IconGlyph>,
    pub(super) tone: SemanticTone,
    pub(super) tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
    pub(super) coverage: Option<(usize, usize)>,
    pub(super) coverage_reader: Option<Box<dyn Fn() -> Option<(usize, usize)>>>,
    pub(super) min_width: Option<f32>,
}

impl PlacementBadge {
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            theme: Box::new(DefaultTheme::default()),
            theme_reader: None,
            label: Binding::new(label.into()),
            icon: None,
            tone: SemanticTone::Neutral,
            tone_reader: None,
            coverage: None,
            coverage_reader: None,
            min_width: None,
        }
    }

    #[deprecated(note = "use `PlacementBadge::new(fallback).label_when(reader)`")]
    pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
    where
        F: Fn() -> String + 'static,
    {
        Self::new(fallback).label_when(reader)
    }

    /// The label, read each time the badge lays out.
    pub fn label_when<F>(mut self, label: F) -> Self
    where
        F: Fn() -> String + 'static,
    {
        self.label.set_when(label);
        self
    }

    /// The label, following an observable and laying out again when it
    /// changes.
    pub fn label_from<O>(mut self, label: O) -> Self
    where
        O: Observable<String> + 'static,
    {
        self.label.set_from(label);
        self
    }

    pub fn theme(mut self, theme: DefaultTheme) -> Self {
        self.theme = Box::new(theme);
        self.theme_reader = None;
        self
    }

    pub fn theme_when<F>(mut self, theme: F) -> Self
    where
        F: Fn() -> DefaultTheme + 'static,
    {
        self.theme_reader = Some(Box::new(theme));
        self
    }

    pub fn icon(mut self, icon: IconGlyph) -> Self {
        self.icon = Some(icon);
        self
    }

    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.tone = tone;
        self.tone_reader = None;
        self
    }

    pub fn tone_when<F>(mut self, tone: F) -> Self
    where
        F: Fn() -> SemanticTone + 'static,
    {
        self.tone_reader = Some(Box::new(tone));
        self
    }

    pub fn coverage(mut self, current: usize, target: usize) -> Self {
        self.coverage = Some((current, target));
        self.coverage_reader = None;
        self
    }

    pub fn coverage_when<F>(mut self, coverage: F) -> Self
    where
        F: Fn() -> Option<(usize, usize)> + 'static,
    {
        self.coverage_reader = Some(Box::new(coverage));
        self
    }

    pub fn min_width(mut self, min_width: f32) -> Self {
        self.min_width = Some(min_width.max(0.0));
        self
    }

    pub(super) fn resolved_theme(&self) -> DefaultTheme {
        self.theme_reader
            .as_ref()
            .map(|theme| theme())
            .unwrap_or(*self.theme)
    }

    pub(super) fn label(&self) -> String {
        self.label.get()
    }

    pub(super) fn resolved_tone(&self) -> SemanticTone {
        self.tone_reader
            .as_ref()
            .map(|reader| reader())
            .unwrap_or(self.tone)
    }

    pub(super) fn resolved_coverage(&self) -> Option<(usize, usize)> {
        self.coverage_reader
            .as_ref()
            .map(|reader| reader())
            .unwrap_or(self.coverage)
            .filter(|(_, target)| *target > 0)
    }

    pub(super) fn metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
        let height = (theme.metrics.min_height - 2.0).max(22.0);
        let coverage_width = 50.0;
        let gap = theme.metrics.icon_label_gap.max(6.0);
        (height, coverage_width, gap)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlacementBadgePaint {
    pub padding: Insets,
}

impl PlacementBadgePaint {
    pub const fn new() -> Self {
        Self {
            padding: Insets::ZERO,
        }
    }

    pub const fn padding(mut self, left: f32, top: f32, right: f32, bottom: f32) -> Self {
        self.padding = Insets {
            left,
            top,
            right,
            bottom,
        };
        self
    }

    pub(super) fn content_rect(self, rect: Rect) -> Rect {
        Rect::new(
            rect.x() + self.padding.left,
            rect.y() + self.padding.top,
            (rect.width() - self.padding.left - self.padding.right).max(0.0),
            (rect.height() - self.padding.top - self.padding.bottom).max(0.0),
        )
    }
}

impl Default for PlacementBadgePaint {
    fn default() -> Self {
        Self::new()
    }
}

pub fn paint_placement_badge(
    ctx: &mut PaintCtx,
    theme: &DefaultTheme,
    rect: Rect,
    label: &str,
    icon: Option<IconGlyph>,
    tone: SemanticTone,
    coverage: Option<(usize, usize)>,
) {
    paint_placement_badge_with(
        ctx,
        theme,
        rect,
        label,
        icon,
        tone,
        coverage,
        PlacementBadgePaint::new(),
    );
}

pub fn paint_placement_badge_with(
    ctx: &mut PaintCtx,
    theme: &DefaultTheme,
    rect: Rect,
    label: &str,
    icon: Option<IconGlyph>,
    tone: SemanticTone,
    coverage: Option<(usize, usize)>,
    paint: PlacementBadgePaint,
) {
    let rect = paint.content_rect(rect);
    if rect.width() <= 0.0 || rect.height() <= 0.0 {
        return;
    }

    let (_, coverage_width, gap) = PlacementBadge::metrics(theme);
    let show_coverage = coverage.is_some() && rect.width() >= 118.0;
    let coverage_slot = if show_coverage { coverage_width } else { 0.0 };
    let slot_gap = if show_coverage { gap } else { 0.0 };
    let badge_rect = Rect::new(
        rect.x(),
        rect.y(),
        (rect.width() - coverage_slot - slot_gap).clamp(48.0, 86.0),
        rect.height(),
    );
    let label_width = ctx
        .measure_text(
            label.to_string(),
            semibold_control_text_style(theme, theme.palette.text),
        )
        .map(|measurement| measurement.width)
        .unwrap_or(0.0);
    let icon_width =
        (rect.height() - 13.0).clamp(11.0, 15.0) + theme.metrics.icon_label_gap.max(4.0);
    let padding = theme.metrics.button_padding.left.max(6.0) * 1.5;
    let icon = icon.filter(|_| label_width + icon_width + padding <= badge_rect.width());
    paint_status_badge(ctx, badge_rect, theme, label, icon, tone);

    if show_coverage && let Some((current, target)) = coverage {
        let dots_rect = Rect::new(
            badge_rect.max_x() + slot_gap,
            rect.y(),
            (rect.max_x() - badge_rect.max_x() - slot_gap).max(0.0),
            rect.height(),
        );
        paint_coverage_dots(ctx, theme, dots_rect, current, target, tone);
    }
}

impl Widget for PlacementBadge {
    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        self.label.observe(|label| {
            ctx.observe::<String, _>(label);
        });
        let theme = self.resolved_theme();
        let (height, coverage_width, gap) = Self::metrics(&theme);
        let label = self.label();
        let tone = self.resolved_tone();
        let icon_w = self
            .icon
            .map(|_| (height - 13.0).clamp(11.0, 15.0) + theme.metrics.icon_label_gap.max(4.0))
            .unwrap_or(0.0);
        let text = measure_text(
            ctx,
            &label,
            &StatusBadge::new(&label).text_style(&theme, &label, tone),
        );
        let badge_width =
            (text.width.ceil() + icon_w + theme.metrics.button_padding.left.max(8.0) * 2.0)
                .clamp(48.0, 86.0);
        let coverage_width = if self.resolved_coverage().is_some() {
            coverage_width + gap
        } else {
            0.0
        };
        constraints.clamp(Size::new(
            self.min_width
                .unwrap_or(0.0)
                .max(badge_width + coverage_width),
            height,
        ))
    }

    fn paint(&self, ctx: &mut PaintCtx) {
        let theme = self.resolved_theme();
        paint_placement_badge(
            ctx,
            &theme,
            ctx.bounds(),
            &self.label(),
            self.icon,
            self.resolved_tone(),
            self.resolved_coverage(),
        );
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let label = self.label();
        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
        node.name = Some(label.clone());
        node.value = Some(SemanticsValue::Text(label.clone()));
        if let Some((current, target)) = self.resolved_coverage() {
            let target = target.max(current);
            node.description = Some(format!("{current} of {target} replicas available"));
        }
        ctx.push(node);
    }
}

pub struct ProgressBar {
    pub(super) theme: Box<DefaultTheme>,
    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
    pub(super) name: String,
    pub(super) min: f64,
    pub(super) max: f64,
    pub(super) value: f64,
    pub(super) tone: SemanticTone,
    pub(super) min_width: Option<f32>,
    pub(super) height: Option<f32>,
    pub(super) show_value: bool,
}

impl ProgressBar {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            theme: Box::new(DefaultTheme::default()),
            theme_reader: None,
            name: name.into(),
            min: 0.0,
            max: 1.0,
            value: 0.0,
            tone: SemanticTone::Accent,
            min_width: None,
            height: None,
            show_value: false,
        }
    }

    pub fn theme(mut self, theme: DefaultTheme) -> Self {
        self.theme = Box::new(theme);
        self.theme_reader = None;
        self
    }

    pub fn theme_when<F>(mut self, theme: F) -> Self
    where
        F: Fn() -> DefaultTheme + 'static,
    {
        self.theme_reader = Some(Box::new(theme));
        self
    }

    pub fn range(mut self, min: f64, max: f64) -> Self {
        self.min = min.min(max);
        self.max = max.max(min);
        self.value = self.value.clamp(self.min, self.max);
        self
    }

    pub fn value(mut self, value: f64) -> Self {
        self.value = value.clamp(self.min, self.max);
        self
    }

    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.tone = tone;
        self
    }

    pub fn min_width(mut self, min_width: f32) -> Self {
        self.min_width = Some(min_width.max(0.0));
        self
    }

    pub fn height(mut self, height: f32) -> Self {
        self.height = Some(height.max(1.0));
        self
    }

    pub fn show_value(mut self, show_value: bool) -> Self {
        self.show_value = show_value;
        self
    }

    pub(super) fn fraction(&self) -> f32 {
        if (self.max - self.min).abs() <= f64::EPSILON {
            0.0
        } else {
            ((self.value - self.min) / (self.max - self.min)).clamp(0.0, 1.0) as f32
        }
    }

    pub(super) fn resolved_theme(&self) -> DefaultTheme {
        self.theme_reader
            .as_ref()
            .map(|theme| theme())
            .unwrap_or(*self.theme)
    }
}

pub fn paint_progress_bar(
    ctx: &mut PaintCtx,
    rect: Rect,
    theme: &DefaultTheme,
    fraction: f32,
    tone: SemanticTone,
) {
    if rect.width() <= 0.0 || rect.height() <= 0.0 {
        return;
    }

    let metrics = theme.metrics;
    let palette = theme.palette;
    let (tone, _) = theme.semantic_tone_colors(tone);
    // An unbordered recessed track under the tone-colored fill.
    ctx.fill(
        Path::rounded_rect(rect, metrics.corner_radius),
        palette.control_hover,
    );

    let fill = Rect::new(
        rect.x(),
        rect.y(),
        rect.width() * fraction.clamp(0.0, 1.0),
        rect.height(),
    );
    if fill.width() > 0.0 {
        ctx.fill(Path::rounded_rect(fill, metrics.corner_radius), tone);
    }
}

impl Widget for ProgressBar {
    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        let theme = self.resolved_theme();
        let metrics = theme.metrics;
        let min_height = if let Some(height) = self.height {
            height
        } else if self.show_value {
            metrics
                .progress_bar_value_height
                .max(text_token_style(&theme, theme.text.sm, theme.palette.text).line_height)
        } else {
            metrics.progress_bar_height
        };
        constraints.clamp(Size::new(
            self.min_width.unwrap_or(metrics.progress_bar_min_width),
            min_height,
        ))
    }

    fn paint(&self, ctx: &mut PaintCtx) {
        let theme = self.resolved_theme();
        let metrics = theme.metrics;
        let (_, tone_text) = theme.semantic_tone_colors(self.tone);
        let bounds = ctx.bounds();
        paint_progress_bar(ctx, bounds, &theme, self.fraction(), self.tone);
        if self.show_value {
            let label = format!("{:.0}%", self.fraction() * 100.0);
            let label_padding = Insets {
                top: 0.0,
                bottom: 0.0,
                ..metrics.progress_bar_label_padding
            };
            let label_slot = inset_rect(bounds, label_padding);
            // The centered label straddles the fill edge: glyphs over the fill
            // take the tone's content color, glyphs over the track take body
            // text, so the value stays readable at every fraction.
            let fill_edge = bounds.x() + bounds.width() * self.fraction();
            let fill_part = Rect::new(
                bounds.x(),
                bounds.y(),
                (fill_edge - bounds.x()).max(0.0),
                bounds.height(),
            );
            let track_part = Rect::new(
                fill_edge,
                bounds.y(),
                (bounds.max_x() - fill_edge).max(0.0),
                bounds.height(),
            );
            for (part, color) in [(fill_part, tone_text), (track_part, theme.palette.text)] {
                let Some(clip) = part.intersection(label_slot) else {
                    continue;
                };
                let text_style = numeric_text_style(text_token_style(&theme, theme.text.sm, color));
                ctx.push_clip_rect(clip);
                paint_text(ctx, label_slot, &label, &text_style, TextAlign::Center);
                ctx.pop_clip();
            }
        }
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let mut node =
            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ProgressBar, ctx.bounds());
        node.name = Some(self.name.clone());
        node.value = Some(SemanticsValue::Range {
            value: self.value,
            min: self.min,
            max: self.max,
        });
        ctx.push(node);
    }
}

#[doc(alias = "BusyIndicator")]
pub struct Spinner {
    pub(super) theme: Box<DefaultTheme>,
    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
    pub(super) name: String,
    pub(super) size: f32,
    pub(super) label: Option<String>,
}

impl Spinner {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            theme: Box::new(DefaultTheme::default()),
            theme_reader: None,
            name: name.into(),
            size: 20.0,
            label: None,
        }
    }

    pub fn theme(mut self, theme: DefaultTheme) -> Self {
        self.theme = Box::new(theme);
        self.theme_reader = None;
        self
    }

    pub fn theme_when<F>(mut self, theme: F) -> Self
    where
        F: Fn() -> DefaultTheme + 'static,
    {
        self.theme_reader = Some(Box::new(theme));
        self
    }

    pub fn size(mut self, size: f32) -> Self {
        self.size = size.max(8.0);
        self
    }

    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    pub(super) fn indicator_rect(&self, bounds: Rect) -> Rect {
        Rect::new(
            bounds.x(),
            bounds.y() + ((bounds.height() - self.size) * 0.5),
            self.size,
            self.size,
        )
    }

    pub(super) fn resolved_theme(&self) -> DefaultTheme {
        self.theme_reader
            .as_ref()
            .map(|theme| theme())
            .unwrap_or(*self.theme)
    }
}

impl Widget for Spinner {
    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
        let theme = self.resolved_theme();
        let text_style = text_token_style(&theme, theme.text.sm, theme.palette.text);
        let label_measurement = self
            .label
            .as_ref()
            .map(|label| measure_text(ctx, label, &text_style));
        let label_width = label_measurement
            .map(|measurement| measurement.width + 12.0)
            .unwrap_or(0.0);
        let label_height = label_measurement
            .map(|measurement| measurement.height.max(text_style.line_height))
            .unwrap_or(0.0);
        constraints.clamp(Size::new(
            self.size + label_width,
            self.size.max(20.0).max(label_height),
        ))
    }

    fn paint(&self, ctx: &mut PaintCtx) {
        let theme = self.resolved_theme();
        let palette = theme.palette;
        let indicator = self.indicator_rect(ctx.bounds());
        // Busy is a live signal: the indicator glows where the theme glows.
        let glow = theme.glow_for_output(GlowTone::Accent, ctx.output_color_range());
        paint_theme_glow(ctx, indicator, [indicator.width() * 0.5; 4], &glow);
        let center = rect_center(indicator);
        let radius = indicator.width().min(indicator.height()) * 0.4;
        let dot_radius = (indicator.width() * 0.09).max(1.5);
        for index in 0..10 {
            let angle = (index as f32 / 10.0) * std::f32::consts::TAU;
            let alpha = 0.22 + ((index as f32) / 10.0) * 0.72;
            let color = Color::rgba(
                palette.accent.red,
                palette.accent.green,
                palette.accent.blue,
                alpha,
            );
            let dot = Point::new(
                center.x + angle.cos() * radius,
                center.y + angle.sin() * radius,
            );
            ctx.fill(Path::circle(dot, dot_radius), color);
        }

        if let Some(label) = &self.label {
            let text_style = text_token_style(&theme, theme.text.sm, palette.text);
            let text_slot = Rect::new(
                indicator.max_x() + 12.0,
                ctx.bounds().y(),
                ctx.bounds().width() - indicator.width() - 12.0,
                ctx.bounds().height(),
            );
            ctx.push_clip_rect(text_slot);
            paint_text(ctx, text_slot, label, &text_style, TextAlign::Start);
            ctx.pop_clip();
        }
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        let mut node =
            SemanticsNode::new(ctx.widget_id(), SemanticsRole::BusyIndicator, ctx.bounds());
        node.name = Some(self.name.clone());
        node.description = self.label.clone();
        node.state.busy = true;
        ctx.push(node);
    }
}

/// Former name of [`Spinner`].
#[deprecated(note = "use `Spinner`")]
pub type BusyIndicator = Spinner;

pub(super) fn text_token_style(
    theme: &DefaultTheme,
    token: ThemeTextToken,
    color: Color,
) -> TextStyle {
    TextStyle {
        font_size: token.size.max(1.0),
        line_height: token.line_height.max(1.0),
        color,
        ..theme.body_text_style()
    }
}

pub(super) fn semibold_control_text_style(theme: &DefaultTheme, color: Color) -> TextStyle {
    let mut style = theme.text_style(color);
    style.weight = FontWeight::SEMIBOLD;
    style
}

pub(super) fn numeric_text_style(mut style: TextStyle) -> TextStyle {
    style.features.enable(FontFeature::TABULAR_FIGURES);
    style
}

pub(super) fn numeric_text_style_if_numeric(text: &str, style: TextStyle) -> TextStyle {
    if text_contains_ascii_digit(text) {
        numeric_text_style(style)
    } else {
        style
    }
}

pub(super) fn text_contains_ascii_digit(text: &str) -> bool {
    text.chars().any(|c| c.is_ascii_digit())
}

pub(super) fn tab_indicator_rect<F>(
    mut tab_rect: F,
    from_index: usize,
    selected_index: usize,
    progress: f32,
    padding: Insets,
    thickness: f32,
) -> Option<Rect>
where
    F: FnMut(usize) -> Option<Rect>,
{
    let to = tab_indicator_from_tab_rect(tab_rect(selected_index)?, padding, thickness);
    let from = tab_rect(from_index)
        .map(|rect| tab_indicator_from_tab_rect(rect, padding, thickness))
        .unwrap_or(to);
    Some(lerp_rect(from, to, progress))
}

pub(super) fn tab_indicator_from_tab_rect(rect: Rect, padding: Insets, thickness: f32) -> Rect {
    Rect::new(
        rect.x() + padding.left,
        rect.max_y() - thickness,
        (rect.width() - padding.left - padding.right).max(0.0),
        thickness,
    )
}

pub(super) fn sliding_inset_rect<F>(
    mut item_rect: F,
    from_index: usize,
    selected_index: usize,
    progress: f32,
    insets: Insets,
) -> Option<Rect>
where
    F: FnMut(usize) -> Option<Rect>,
{
    let to = inset_rect(item_rect(selected_index)?, insets);
    let from = item_rect(from_index)
        .map(|rect| inset_rect(rect, insets))
        .unwrap_or(to);
    Some(lerp_rect(from, to, progress))
}

pub(super) fn tab_panel_transition_translation(
    from_index: usize,
    selected_index: usize,
    progress: f32,
    metrics: ControlMetrics,
) -> Vector {
    if from_index == selected_index {
        return Vector::ZERO;
    }

    let remaining = 1.0 - progress.clamp(0.0, 1.0);
    if remaining <= Progress::EPSILON {
        return Vector::ZERO;
    }

    let direction = if selected_index > from_index {
        1.0
    } else {
        -1.0
    };
    Vector::new(direction * metrics.tab_panel_gap * remaining, 0.0)
}

pub(super) fn lerp_rect(from: Rect, to: Rect, progress: f32) -> Rect {
    let progress = progress.clamp(0.0, 1.0);
    Rect::new(
        f32::interpolate(from.x(), to.x(), progress),
        f32::interpolate(from.y(), to.y(), progress),
        f32::interpolate(from.width(), to.width(), progress),
        f32::interpolate(from.height(), to.height(), progress),
    )
}

/// State fills for tab-like items. Unselected items are ghosts that reveal a
/// borderless neutral wash on hover and press; a selected browser-style tab
/// is raised to the panel surface. Underline tabs pass `selected = false`
/// and let their accent indicator carry selection.
pub(super) fn tab_state_visuals(
    theme: &DefaultTheme,
    selected: bool,
    hovered: bool,
    pressed: bool,
    hover_amount: f32,
    press_amount: f32,
) -> Option<(Color, Color)> {
    let palette = theme.palette;
    let interaction = theme.interaction;
    if selected {
        return Some((palette.surface_raised, palette.border));
    }
    if !(hovered || pressed || hover_amount > 0.0 || press_amount > 0.0) {
        return None;
    }
    let hovered_fill = mix_color(
        palette.control.with_alpha(0.0),
        palette.control,
        interaction.hover_blend * hover_amount,
    );
    let fill = mix_color(
        hovered_fill,
        palette.control_hover,
        interaction.pressed_blend * press_amount,
    );
    Some((fill, Color::TRANSPARENT))
}

pub(super) fn draw_popover_arrival_overlay(
    ctx: &mut PaintCtx,
    rect: Rect,
    metrics: ControlMetrics,
    background: Color,
    border: Color,
    arrival_effect: ResolvedEffectStyle,
) {
    let overlay_inset = physical_pixels(ctx, 1.0);
    let overlay_rect = rect.inflate(-overlay_inset, -overlay_inset);
    let overlay_radius = (metrics.corner_radius + 2.0 - overlay_inset).max(0.0);
    let overlay_fill = mix_color(background, arrival_effect.color, 0.35)
        .with_alpha((0.10 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.22));
    let stroke_color = apply_hdr_policy_cap(
        mix_color(border, arrival_effect.color, 0.55),
        arrival_effect
            .color
            .red
            .max(arrival_effect.color.green.max(arrival_effect.color.blue)),
    )
    .with_alpha((0.16 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.30));

    draw_control_shape(
        ctx,
        overlay_rect,
        overlay_radius,
        physical_pixels(ctx, 1.0),
        overlay_fill,
        stroke_color,
    );
}

/// The triangle pointing from `bubble` toward `trigger`. Its base reaches
/// `base_inset` into the bubble, and its slanted sides are pushed outward by
/// `side_outset`, so the same tail can be filled once wider in the border
/// color and once over the border in the fill color, outlining it.
pub(super) fn tooltip_tail(
    trigger: Rect,
    bubble: Rect,
    placement: TooltipPlacement,
    base_inset: f32,
    side_outset: f32,
) -> Path {
    const HALF_WIDTH: f32 = 6.0;
    const HEIGHT: f32 = 8.0;
    let side_length = HALF_WIDTH.hypot(HEIGHT);
    let center_x = rect_center(trigger)
        .x
        .clamp(bubble.x() + 12.0, bubble.max_x() - 12.0);
    let (edge, direction) = match placement {
        TooltipPlacement::Above => (bubble.max_y(), 1.0),
        TooltipPlacement::Below => (bubble.y(), -1.0),
    };
    let base_y = edge - direction * base_inset;
    let half_width =
        HALF_WIDTH + side_outset * side_length / HEIGHT + base_inset * HALF_WIDTH / HEIGHT;
    let apex_y = edge + direction * (HEIGHT + side_outset * side_length / HALF_WIDTH);
    let mut builder = PathBuilder::new();
    builder
        .move_to(Point::new(center_x - half_width, base_y))
        .line_to(Point::new(center_x + half_width, base_y))
        .line_to(Point::new(center_x, apex_y));
    builder.build()
}