frus-widgets 0.5.0

frus — declarative widget tree
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
//! [`IconButton`]: a button holding **one glyph**, in a box as wide as it is tall.
//!
//! It exists because milestone 313 kept finding the same thing. A `Button` is sized for a
//! word — 64 px wide before its label is measured, 24 px of room either side — and a back
//! arrow, a month arrow, a delete cross or a stepper's plus is not a word. Seven call sites
//! in this repository were asking a button to be something it is not, and the reference has
//! had the answer all along: 40 × 40, circular, no fill, the icon in `on_surface_variant`.
//!
//! ```ignore
//! IconButton::new(Icons::CLOSE).label("Remove").on_press(Msg::Delete)
//! IconButton::glyph("\u{2190}").label("Back").on_press(Msg::Pop)
//! IconButton::new(Icons::STAR).selected(starred).on_press(Msg::Star)
//! ```
//!
//! It takes either an icon from the bundled set or a **glyph**, because the set does not
//! cover everything an application draws and a button that only accepts what happens to be
//! bundled is a button that sends people back to `Button`.
//!
//! **A label is not optional in practice.** An icon says nothing to a screen reader, so
//! [`IconButton::label`] is what makes it announceable — the reference's `tooltip`, doing
//! the same job.

use frus_core::{BorderRadius, Color, Point, Rect, Scene, TextStyle};
use frus_layout::{Dimension, Style};

use crate::disabled::{disabled_container, disabled_content};
use crate::icons::IconData;
use crate::interaction::Status;
use crate::theme::{TapTarget, Theme};
use crate::widget::Widget;

/// The box: as wide as it is tall.
pub const ICON_BUTTON_SIZE: f32 = 40.0;
/// The glyph inside it.
pub const ICON_BUTTON_ICON_SIZE: f32 = 24.0;
/// An outlined icon button's outline.
pub const ICON_BUTTON_BORDER_WIDTH: f32 = 1.0;

/// How much of a surface an icon button brings with it.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum IconButtonVariant {
    /// No surface at all: the glyph, and the ink a tap leaves.
    #[default]
    Standard,
    /// The accent, filled.
    Filled,
    /// A tonal fill.
    Tonal,
    /// An outline and no fill.
    Outlined,
}

/// What the button draws: one of the bundled icons, or a glyph of your own.
enum Content {
    Icon(IconData),
    Glyph(String),
    /// A pair being crossed, and the end it is heading for — see
    /// [`IconButton::animated`].
    Morph(crate::icons::AnimatedIconData, f32),
    /// A picture rather than a path — see [`IconButton::image`]. Boxed: a picture is
    /// several times the size of the other three, and every button would carry it.
    Image(Box<crate::ImageIcon>),
}

/// A button holding one glyph.
pub struct IconButton<Msg = crate::callback::Callback> {
    content: Content,
    variant: IconButtonVariant,
    /// Whether it is a toggle, and if so whether it is on: `None` for a plain button.
    selected: Option<bool>,
    enabled: bool,
    label: Option<String>,
    on_press: Option<Msg>,
    size: Option<f32>,
    icon_size: Option<f32>,
    color: Option<Color>,
    icon_color: Option<Color>,
    border_color: Option<Color>,
    border_width: Option<f32>,
    radius: Option<BorderRadius>,
    tap_target: Option<TapTarget>,
}

impl<Msg> IconButton<Msg> {
    /// A button showing one of the bundled icons.
    pub fn new(icon: IconData) -> Self {
        Self::of(Content::Icon(icon))
    }

    /// A button showing a **glyph** — an arrow, a cross, an ellipsis — for the many shapes
    /// the bundled set does not carry.
    pub fn glyph(glyph: impl Into<String>) -> Self {
        Self::of(Content::Glyph(glyph.into()))
    }

    /// A button showing a **picture**: a brand mark, a flag, a glyph that is artwork
    /// rather than a path.
    ///
    /// It is drawn at the button's own glyph size, like every other kind of mark here, so
    /// a picture and an icon in one bar are the same size without either being told.
    ///
    /// ```ignore
    /// IconButton::image(ImageIcon::new(Image::memory(MARK))).label("Home").on_press(msg)
    /// ```
    pub fn image(icon: crate::ImageIcon) -> Self {
        Self::of(Content::Image(Box::new(icon)))
    }

    /// **A button whose mark crosses between two**, at the end `on` names — a drawer's
    /// hamburger becoming a cross as the drawer opens, a play becoming a pause.
    ///
    /// The button does not time the crossing: it declares the end and the runtime drives
    /// the value there, the way a drawer's own slide is driven. Two controls reading the
    /// same flag are therefore at the same place on the same frame, because it is the
    /// same rule moving both and not two timers that happen to agree.
    ///
    /// ```
    /// use frus_widgets::{AnimatedIcons, IconButton};
    ///
    /// let drawer_open = false;
    /// let _button = IconButton::<()>::animated(AnimatedIcons::MENU_CLOSE, drawer_open)
    ///     .label("Menu")
    ///     .on_press(());
    /// ```
    pub fn animated(icon: crate::icons::AnimatedIconData, on: bool) -> Self {
        Self::of(Content::Morph(icon, if on { 1.0 } else { 0.0 }))
    }

    fn of(content: Content) -> Self {
        Self {
            content,
            variant: IconButtonVariant::default(),
            selected: None,
            enabled: true,
            label: None,
            on_press: None,
            size: None,
            icon_size: None,
            color: None,
            icon_color: None,
            border_color: None,
            border_width: None,
            radius: None,
            tap_target: None,
        }
    }

    /// What a screen reader announces. An icon has no text of its own, so without this the
    /// button is a shape with no name.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Chooses how much surface the button brings.
    pub fn variant(mut self, variant: IconButtonVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Makes it a **toggle**, on or off; on, the glyph takes the accent. A button never told
    /// is a plain button, and assistive technology offers it as one to press, not to switch.
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = Some(selected);
        self
    }

    /// Enables or disables it. Disabled, it is greyed out and emits nothing.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// The message emitted on click.
    pub fn on_press(mut self, message: impl Into<Msg>) -> Self {
        self.on_press = Some(message.into());
        self
    }

    /// The box's side.
    pub fn size(mut self, size: f32) -> Self {
        self.size = Some(size);
        self
    }

    /// The glyph's size inside it.
    pub fn icon_size(mut self, size: f32) -> Self {
        self.icon_size = Some(size);
        self
    }

    /// The surface under the glyph.
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// The glyph's colour.
    pub fn icon_color(mut self, color: Color) -> Self {
        self.icon_color = Some(color);
        self
    }

    /// The outline's colour.
    pub fn border_color(mut self, color: Color) -> Self {
        self.border_color = Some(color);
        self
    }

    /// The outline's thickness; `0.0` removes it.
    pub fn border_width(mut self, width: f32) -> Self {
        self.border_width = Some(width);
        self
    }

    /// The corner radii. Unset, the button is a **circle**.
    pub fn radius(mut self, radius: impl Into<BorderRadius>) -> Self {
        self.radius = Some(radius.into());
        self
    }

    /// **How much room it reserves for a finger** ([`TapTarget`]). Unset, the theme's
    /// answer, which is [`Padded`](TapTarget::Padded) — at least 48 pixels either way,
    /// whatever this control paints in the middle of it.
    pub fn tap_target(mut self, target: TapTarget) -> Self {
        self.tap_target = Some(target);
        self
    }

    fn side(&self, theme: &Theme) -> f32 {
        self.size
            .or(theme.widgets.icon_button.size)
            .unwrap_or(ICON_BUTTON_SIZE)
    }

    /// The room this button reserves, resolved as `caller ?? theme ?? framework`
    /// (`icon_button.dart:708`).
    fn reserved(&self, theme: &Theme) -> f32 {
        self.tap_target
            .or(theme.widgets.icon_button.tap_target)
            .unwrap_or(theme.tap_target)
            .min_side()
    }

    /// The **face** — what the button paints — centred in the box it was given, which is
    /// its tap target and is larger.
    fn face(&self, bounds: Rect, theme: &Theme) -> Rect {
        let side = self.side(theme);
        Rect::new(
            bounds.x + (bounds.width - side) * 0.5,
            bounds.y + (bounds.height - side) * 0.5,
            side,
            side,
        )
    }

    fn glyph_size(&self, theme: &Theme) -> f32 {
        self.icon_size
            .or(theme.widgets.icon_button.icon_size)
            .unwrap_or(ICON_BUTTON_ICON_SIZE)
    }

    fn radius_of(&self, theme: &Theme, side: f32) -> BorderRadius {
        self.radius
            .or(theme.widgets.icon_button.radius)
            // A circle, which is what an icon button is: the radius follows the box, so a
            // smaller one stays round instead of becoming a square with soft corners.
            .unwrap_or(BorderRadius::uniform(side / 2.0))
    }

    /// `(surface, glyph, outline)`.
    fn palette(&self, theme: &Theme) -> (Color, Color, Option<Color>) {
        if !self.enabled {
            return (
                match self.variant {
                    IconButtonVariant::Standard | IconButtonVariant::Outlined => Color::TRANSPARENT,
                    _ => disabled_container(theme),
                },
                disabled_content(theme),
                // An outlined icon button **keeps its outline**, at the container opacity.
                // Dropping it took the shape away entirely: milestone 324's golden showed a
                // disabled stepper as two bare glyphs with no buttons around them, which
                // reads as broken rather than as unavailable.
                match self.variant {
                    IconButtonVariant::Outlined => Some(disabled_container(theme)),
                    _ => None,
                },
            );
        }
        let (surface, glyph, outline) = match self.variant {
            IconButtonVariant::Standard => (
                Color::TRANSPARENT,
                if self.selected == Some(true) {
                    theme.scheme.primary
                } else {
                    theme.scheme.on_surface_variant
                },
                None,
            ),
            IconButtonVariant::Filled => (theme.scheme.primary, theme.scheme.on_primary, None),
            IconButtonVariant::Tonal => (
                theme.scheme.secondary_container,
                theme.scheme.on_secondary_container,
                None,
            ),
            IconButtonVariant::Outlined => (
                Color::TRANSPARENT,
                if self.selected == Some(true) {
                    theme.scheme.primary
                } else {
                    theme.scheme.on_surface_variant
                },
                Some(theme.scheme.outline),
            ),
        };
        (
            self.color
                .or(theme.widgets.icon_button.color)
                .unwrap_or(surface),
            self.icon_color
                .or(theme.widgets.icon_button.icon_color)
                .unwrap_or(glyph),
            self.border_color
                .or(theme.widgets.icon_button.border_color)
                .or(outline),
        )
    }
}

impl<Msg: Clone> Widget<Msg> for IconButton<Msg> {
    fn style(&self) -> Style {
        Widget::<Msg>::style_themed(self, &Theme::default())
    }

    /// **The box is the tap target, not the face** (`icon_button.dart:708`). An icon
    /// button paints 40 pixels and the reference reserves 48 for the finger, painting the
    /// face in the middle of it. This is the control most often placed at the very edge
    /// of a bar, where the eight missing pixels are the ones a thumb reaches for.
    fn style_themed(&self, theme: &Theme) -> Style {
        let side = self.side(theme).max(self.reserved(theme));
        Style {
            width: Dimension::Length(side),
            height: Dimension::Length(side),
            ..Default::default()
        }
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &[]
    }

    fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
        let o = status.opacity;
        let (surface, glyph, outline) = self.palette(theme);
        let bounds = self.face(bounds, theme);
        let radius = self.radius_of(theme, bounds.height.min(bounds.width));
        let (border_width, border_color) = match (
            self.border_width.or(theme.widgets.icon_button.border_width),
            outline,
        ) {
            (Some(width), Some(color)) => (width, color),
            (Some(width), None) => (width, theme.scheme.outline),
            (None, Some(color)) => (ICON_BUTTON_BORDER_WIDTH, color),
            (None, None) => (0.0, Color::TRANSPARENT),
        };
        let surface = if self.enabled {
            theme.state_layer(surface, glyph, &status)
        } else {
            surface
        };
        scene.draw_rect(
            bounds,
            surface.fade(o),
            radius,
            border_width,
            border_color.fade(o),
        );

        let size = self.glyph_size(theme);
        match &self.content {
            // The end of the animation is what an isolated frame draws — a test, a
            // golden, the frame before the loop has advanced anything — which is the
            // same rule `Status::value` already applies on mount.
            Content::Morph(pair, _) => {
                let path = pair.at(status.value).placed(
                    size,
                    bounds.x + (bounds.width - size) / 2.0,
                    bounds.y + (bounds.height - size) / 2.0,
                    theme.direction,
                );
                scene.fill_path(&path, glyph.fade(o));
            }
            Content::Icon(name) => {
                let path = name.placed(
                    size,
                    bounds.x + (bounds.width - size) / 2.0,
                    bounds.y + (bounds.height - size) / 2.0,
                    theme.direction,
                );
                scene.fill_path(&path, glyph.fade(o));
            }
            // The picture takes the button's glyph size, which is what makes a mark drawn
            // from a bitmap and one drawn from a path interchangeable in a row of actions.
            Content::Image(icon) => {
                let square = Rect::new(
                    bounds.x + (bounds.width - size) / 2.0,
                    bounds.y + (bounds.height - size) / 2.0,
                    size,
                    size,
                );
                icon.paint_at(square, status, theme, scene);
            }
            Content::Glyph(text) => {
                let style = TextStyle::new(size);
                let measured = frus_text::measure_styled(
                    text,
                    size,
                    style.resolved().weight,
                    style.resolved().italic,
                );
                scene.text(
                    Point::new(
                        bounds.x + (bounds.width - measured.width) / 2.0,
                        bounds.y + (bounds.height - measured.height) / 2.0,
                    ),
                    text.clone(),
                    &style.resolved(),
                    glyph.fade(o),
                );
            }
        }
    }

    /// Only a morphing button has an animated value; every other one answers `None` and
    /// keeps the behaviour it had before this existed.
    fn anim_target(&self) -> Option<f32> {
        match self.content {
            Content::Morph(_, target) => Some(target),
            _ => None,
        }
    }

    fn on_click(&self) -> Option<Msg> {
        if self.enabled {
            self.on_press.clone()
        } else {
            None
        }
    }

    fn ink(&self, theme: &Theme) -> Option<crate::InkStyle> {
        if !self.enabled {
            return None;
        }
        let (_, glyph, _) = self.palette(theme);
        let splash = theme.widgets.ink.color.unwrap_or_else(|| glyph.fade(0.16));
        Some(
            crate::InkStyle::of(theme)
                .color(splash)
                .radius(self.radius_of(theme, self.side(theme))),
        )
    }

    fn focusable(&self) -> bool {
        self.enabled
    }

    fn semantics(&self) -> Option<frus_core::SemanticsProperties> {
        let semantics = frus_core::SemanticsProperties::new(frus_core::Role::Button);
        let semantics = match &self.label {
            Some(label) => semantics.label(label.clone()),
            // Better than nothing, and visibly worse than a label: a glyph read out is at
            // least something, an unnamed icon is silence.
            None => match &self.content {
                Content::Glyph(text) => semantics.label(text.clone()),
                Content::Icon(_) | Content::Morph(..) | Content::Image(_) => semantics,
            },
        };
        Some(if self.enabled {
            match self.selected {
                Some(on) => semantics.toggled(on),
                None => semantics,
            }
            .clickable()
        } else {
            semantics.disabled(true)
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::icons::Icons;
    use crate::theme::{MIN_TAP_TARGET, SHRUNK_TAP_TARGET};
    use frus_core::Primitive;

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Pressed,
    }

    fn painted(button: &IconButton<Msg>) -> Vec<Primitive> {
        let mut scene = Scene::new();
        Widget::<Msg>::paint(
            button,
            Rect::new(0.0, 0.0, ICON_BUTTON_SIZE, ICON_BUTTON_SIZE),
            Status::default(),
            &Theme::default(),
            &mut scene,
        );
        scene.primitives().to_vec()
    }

    /// **A morphing button is a path, and it follows the animated value.** The mark it
    /// draws at half the crossing is neither end, and the button still says what it is
    /// for through its label rather than through the mark — a shape that is halfway
    /// between two things names neither of them.
    #[test]
    fn a_morphing_button_draws_the_crossing_and_still_says_what_it_does() {
        let paint_at = |value: f32| {
            let mut scene = Scene::new();
            Widget::<Msg>::paint(
                &IconButton::animated(crate::AnimatedIcons::MENU_CLOSE, true)
                    .label("Menu")
                    .on_press(Msg::Pressed),
                Rect::new(0.0, 0.0, ICON_BUTTON_SIZE, ICON_BUTTON_SIZE),
                Status {
                    value,
                    ..Status::default()
                },
                &Theme::default(),
                &mut scene,
            );
            scene
                .primitives()
                .iter()
                .find_map(|p| match p {
                    Primitive::Path { path, .. } => Some(path.clone()),
                    _ => None,
                })
                .expect("a morphing button paints a path")
        };
        assert_ne!(paint_at(0.0).verbs(), paint_at(0.5).verbs());
        assert_ne!(paint_at(0.5).verbs(), paint_at(1.0).verbs());

        let button = IconButton::animated(crate::AnimatedIcons::MENU_CLOSE, false)
            .label("Menu")
            .on_press(Msg::Pressed);
        assert_eq!(Widget::<Msg>::anim_target(&button), Some(0.0));
        assert_eq!(
            Widget::<Msg>::anim_target(&IconButton::<Msg>::new(Icons::CLOSE)),
            None,
            "a button that is one mark has no animated value"
        );
    }

    /// **An icon button paints 40 pixels and the reference reserves 48** (milestone 442,
    /// `icon_button.dart:708`). It is the control most often put at the very edge of a
    /// bar, where the eight missing pixels are the ones a thumb reaches for.
    #[test]
    fn an_icon_button_reserves_room_for_a_finger() {
        let theme = Theme::dark();
        let side = |button: &IconButton<()>, theme: &Theme| match Widget::<()>::style_themed(
            button, theme,
        )

        .width
        {
            Dimension::Length(w) => w,
            other => panic!("{other:?}"),
        };
        assert_eq!(side(&IconButton::new(Icons::CLOSE), &theme), MIN_TAP_TARGET);
        assert_eq!(
            side(
                &IconButton::new(Icons::CLOSE).tap_target(TapTarget::ShrinkWrap),
                &theme
            ),
            SHRUNK_TAP_TARGET
        );
        // A button asked for a face **larger** than the target keeps its own size: the
        // target is a floor, not a size.
        assert_eq!(
            side(&IconButton::new(Icons::CLOSE).size(64.0), &theme),
            64.0
        );
    }

    /// And **the face it paints does not grow with the room**: it keeps its own side and
    /// sits in the middle of it.
    #[test]
    fn the_face_is_centred_in_the_room() {
        let theme = Theme::dark();
        let mut scene = Scene::new();
        Widget::<()>::paint(
            &IconButton::new(Icons::CLOSE),
            Rect::new(0.0, 0.0, MIN_TAP_TARGET, MIN_TAP_TARGET),
            Status::default(),
            &theme,
            &mut scene,
        );
        let face = scene
            .primitives()
            .iter()
            .find_map(|p| match p {
                frus_core::Primitive::Rect { rect, .. } => Some(*rect),
                _ => None,
            })
            .expect("an icon button paints its surface");
        assert_eq!(face.width, ICON_BUTTON_SIZE);
        assert_eq!(face.height, ICON_BUTTON_SIZE);
        let inset = (MIN_TAP_TARGET - ICON_BUTTON_SIZE) * 0.5;
        assert!(
            (face.x - inset).abs() < 0.01 && (face.y - inset).abs() < 0.01,
            "centred in the room: {face:?}"
        );
    }

    #[test]
    fn it_is_a_circle_as_wide_as_it_is_tall() {
        let theme = Theme::default();
        // The **box** is square at the tap target since milestone 442; the face it paints
        // inside that box is square at its own side.
        let style = Widget::<Msg>::style_themed(&IconButton::new(Icons::CLOSE), &theme);
        assert_eq!(style.width, Dimension::Length(MIN_TAP_TARGET));
        assert_eq!(style.height, Dimension::Length(MIN_TAP_TARGET));
        let radius = painted(&IconButton::new(Icons::CLOSE))
            .iter()
            .find_map(|p| match p {
                Primitive::Rect { radius, .. } => Some(*radius),
                _ => None,
            })
            .expect("a box");
        assert_eq!(radius, BorderRadius::uniform(ICON_BUTTON_SIZE / 2.0));
    }

    #[test]
    fn a_standard_one_is_a_glyph_and_nothing_else() {
        let theme = Theme::default();
        let painted = painted(&IconButton::new(Icons::CLOSE));
        let (color, border) = painted
            .iter()
            .find_map(|p| match p {
                Primitive::Rect {
                    color,
                    border_width,
                    ..
                } => Some((*color, *border_width)),
                _ => None,
            })
            .expect("a box");
        assert_eq!(color, Color::TRANSPARENT, "no surface at rest");
        assert_eq!(border, 0.0);
        let glyph = painted
            .iter()
            .find_map(|p| match p {
                Primitive::Path { fill, .. } => *fill,
                _ => None,
            })
            .expect("an icon");
        assert_eq!(glyph, theme.scheme.on_surface_variant);
    }

    #[test]
    fn a_glyph_is_drawn_where_the_set_has_no_icon() {
        // The bundled set has no back arrow, no minus, no ellipsis. A button that only took
        // what happens to be bundled would send those call sites back to `Button`.
        let painted = painted(&IconButton::<Msg>::glyph("\u{2190}"));
        assert!(
            painted
                .iter()
                .any(|p| matches!(p, Primitive::Text { text, .. } if text == "\u{2190}")),
            "the glyph is drawn"
        );
    }

    /// **Only a button told it is selected is a toggle.** A plain one — a back arrow, a
    /// menu — was described as a toggle switched off, so assistive technology offered to
    /// switch it rather than press it (found on the desktop, milestone 701).
    #[test]
    fn only_a_selected_button_is_a_toggle() {
        use frus_core::Toggled;
        let toggled = |button: IconButton<Msg>| {
            Widget::semantics(&button.on_press(Msg::Pressed))
                .expect("an enabled button describes itself")
                .toggled
        };
        assert_eq!(toggled(IconButton::new(Icons::STAR)), Toggled::None);
        assert_eq!(
            toggled(IconButton::new(Icons::STAR).selected(false)),
            Toggled::False
        );
        assert_eq!(
            toggled(IconButton::new(Icons::STAR).selected(true)),
            Toggled::True
        );
    }

    #[test]
    fn selected_takes_the_accent() {
        let theme = Theme::default();
        let glyph = |selected: bool| {
            painted(&IconButton::<Msg>::new(Icons::STAR).selected(selected))
                .iter()
                .find_map(|p| match p {
                    Primitive::Path { fill, .. } => *fill,
                    _ => None,
                })
                .expect("an icon")
        };
        assert_eq!(glyph(false), theme.scheme.on_surface_variant);
        assert_eq!(glyph(true), theme.scheme.primary);
    }

    #[test]
    fn the_variants_are_told_apart_by_their_surface() {
        let theme = Theme::default();
        let surface = |variant: IconButtonVariant| {
            painted(&IconButton::<Msg>::new(Icons::CLOSE).variant(variant))
                .iter()
                .find_map(|p| match p {
                    Primitive::Rect {
                        color,
                        border_width,
                        ..
                    } => Some((*color, *border_width)),
                    _ => None,
                })
                .expect("a box")
        };
        assert_eq!(surface(IconButtonVariant::Filled).0, theme.scheme.primary);
        assert_eq!(
            surface(IconButtonVariant::Tonal).0,
            theme.scheme.secondary_container
        );
        let outlined = surface(IconButtonVariant::Outlined);
        assert_eq!(outlined.0, Color::TRANSPARENT);
        assert_eq!(outlined.1, ICON_BUTTON_BORDER_WIDTH);
    }

    #[test]
    fn disabled_is_inert_and_says_so() {
        let button = IconButton::new(Icons::CLOSE)
            .on_press(Msg::Pressed)
            .enabled(false);
        assert_eq!(Widget::on_click(&button), None);
        assert!(!Widget::<Msg>::focusable(&button));
        assert!(Widget::<Msg>::ink(&button, &Theme::default()).is_none());
        let semantics = Widget::<Msg>::semantics(&button).expect("semantics");
        assert!(semantics.disabled);
        assert!(!semantics.clickable);
    }

    #[test]
    fn an_icon_button_can_be_named() {
        // An icon says nothing to a screen reader; the label is what it is announced by.
        let named = IconButton::<Msg>::new(Icons::CLOSE).label("Remove");
        assert_eq!(
            Widget::<Msg>::semantics(&named).unwrap().label.as_deref(),
            Some("Remove")
        );
        // A glyph at least reads as itself.
        assert_eq!(
            Widget::<Msg>::semantics(&IconButton::<Msg>::glyph("+"))
                .unwrap()
                .label
                .as_deref(),
            Some("+")
        );
    }

    #[test]
    fn every_measurement_is_the_callers_and_then_the_themes() {
        let mut theme = Theme::default();
        theme.widgets.icon_button.size = Some(56.0);
        // The **face** — what the button paints — since milestone 442, because the box
        // around it is the tap target and is a floor rather than a size.
        let side = |button: IconButton<Msg>, theme: &Theme| {
            let mut scene = Scene::new();
            Widget::<Msg>::paint(
                &button,
                Rect::new(0.0, 0.0, 96.0, 96.0),
                Status::default(),
                theme,
                &mut scene,
            );
            scene
                .primitives()
                .iter()
                .find_map(|p| match p {
                    Primitive::Rect { rect, .. } => Some(rect.width),
                    _ => None,
                })
                .expect("a box")
        };
        assert_eq!(
            side(IconButton::new(Icons::CLOSE), &Theme::default()),
            ICON_BUTTON_SIZE,
            "the framework's"
        );
        assert_eq!(
            side(IconButton::new(Icons::CLOSE), &theme),
            56.0,
            "the theme's"
        );
        assert_eq!(
            side(IconButton::new(Icons::CLOSE).size(32.0), &theme),
            32.0,
            "the caller's, over the theme's"
        );
        // And a face smaller than the target still gets the target's room around it: the
        // control shrinks, the area a finger may land in does not.
        assert_eq!(
            match Widget::<Msg>::style_themed(&IconButton::new(Icons::CLOSE).size(32.0), &theme)
                .width
            {
                Dimension::Length(w) => w,
                other => panic!("{other:?}"),
            },
            MIN_TAP_TARGET
        );
    }
}