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
//! [`Button`]: the reference's five buttons, in one widget with a variant.
//!
//! They are one box with one label and differ in **emphasis**: filled for the action a
//! screen is about, tonal for the one beside it, elevated where the surface underneath is
//! busy, outlined for a secondary action, and text for the least of all. Everything else —
//! the 40 px height, the 64 px minimum width, the stadium shape, the `label_large` label,
//! the 24 px of room either side — is shared, which is why they are a variant here and not
//! five types.
//!
//! ```ignore
//! Button::new("Save").on_press(Msg::Save) // filled
//! Button::new("Cancel").variant(Variant::Text).on_press(Msg::Cancel) // text
//! Button::new("Delete").variant(Variant::Danger).on_press(Msg::Delete) // the error role
//! ```
//!
//! Every measurement and colour is overridable, per call or through
//! [`ButtonTheme`](crate::ButtonTheme).
use frus_core::{BorderRadius, Color, Point, Rect, Scene, ShapeBorder, TextStyle};
use frus_layout::{Dimension, Style};
use crate::disabled::{disabled_container, disabled_content};
use crate::interaction::Status;
use crate::theme::Theme;
use crate::widget::Widget;
/// A button's height, and the smallest it will be.
pub const BUTTON_HEIGHT: f32 = 40.0;
/// The narrowest a button gets, however short its label.
pub const BUTTON_MIN_WIDTH: f32 = 64.0;
/// The room either side of the label.
pub const BUTTON_PADDING: f32 = 24.0;
/// The room either side of a **text** button's label, which has no box to fill.
pub const BUTTON_TEXT_PADDING: f32 = 12.0;
/// How far an elevated button sits off the surface **at rest** — see [`Button::elevation`]
/// for the other states.
pub const BUTTON_ELEVATION: f32 = 1.0;
/// How far an elevated button rises under a pointer (the reference's elevated button
/// defaults, line 579).
const ELEVATED_HOVER_ELEVATION: f32 = 3.0;
/// How far a filled or tonal button rises under a pointer, from flat (the reference's
/// filled button defaults, lines 597 and 738).
const FILLED_HOVER_ELEVATION: f32 = 1.0;
/// An outlined button's outline.
pub const BUTTON_BORDER_WIDTH: f32 = 1.0;
/// How much of a screen's attention a button is asking for.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum Variant {
/// The accent, filled: the one action a screen is about.
#[default]
Filled,
/// A tonal fill — beside a filled button, not competing with it.
Tonal,
/// A raised surface with a shadow, for a button over busy content.
Elevated,
/// An outline and no fill.
Outlined,
/// A label alone.
Text,
/// Filled in the **error** role — a destructive action.
///
/// Not one of the reference's five: there, a destructive button is a filled button
/// given the error colours by hand. It is here because saying *this action destroys
/// something* is worth a name, and because the alternative is every application
/// writing the same two colour overrides.
Danger,
}
impl Variant {
/// How far the variant sits off the surface in each state it can be in while enabled.
///
/// The reference's, variant by variant: an elevated button rests at 1, rises to 3 under
/// a pointer and is back at 1 focused or pressed (its elevated button defaults, lines
/// 570–585); a filled or a tonal one is flat except under a pointer, where it rises to 1
/// (its filled button defaults, lines 588–603 and 729–744) — and so is a danger one,
/// being a filled button in the error colours; an outlined or a text button never
/// leaves the surface.
const fn heights(self) -> Heights {
match self {
Variant::Elevated => Heights {
rest: BUTTON_ELEVATION,
hovered: ELEVATED_HOVER_ELEVATION,
focused: BUTTON_ELEVATION,
pressed: BUTTON_ELEVATION,
},
Variant::Filled | Variant::Tonal | Variant::Danger => Heights {
rest: 0.0,
hovered: FILLED_HOVER_ELEVATION,
focused: 0.0,
pressed: 0.0,
},
Variant::Outlined | Variant::Text => Heights::all(0.0),
}
}
/// The room either side of the label.
const fn padding(self) -> f32 {
match self {
Variant::Text => BUTTON_TEXT_PADDING,
_ => BUTTON_PADDING,
}
}
}
/// A button's height in each state it can be in while enabled. Disabled, every button is
/// flat, and that is decided before these are read.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Heights {
rest: f32,
hovered: f32,
focused: f32,
pressed: f32,
}
impl Heights {
const fn all(height: f32) -> Self {
Self {
rest: height,
hovered: height,
focused: height,
pressed: height,
}
}
/// The height this frame.
///
/// From rest towards the focused height, then the hovered one, then the pressed one,
/// each by its own progress. So a press outranks a hover and a hover outranks a focus,
/// which is the order the reference resolves the states in, and every change is exactly
/// as gradual as the state layer painted from the same status: the reference animates a
/// height it resolved outright, and this one is continuous by construction.
fn at(self, status: &Status) -> f32 {
let toward =
|from: f32, to: f32, progress: f32| from + (to - from) * progress.clamp(0.0, 1.0);
let height = toward(self.rest, self.focused, status.focus_progress);
let height = toward(height, self.hovered, status.hover_progress);
toward(height, self.pressed, status.press_progress)
}
}
/// A clickable button.
pub struct Button<Msg = crate::callback::Callback> {
label: String,
variant: Variant,
on_press: Option<Msg>,
/// Enabled? Disabled (`false`): greyed out, no shadow, no click, no focus.
enabled: bool,
label_style: Option<TextStyle>,
color: Option<Color>,
label_color: Option<Color>,
border_color: Option<Color>,
border_width: Option<f32>,
shape: Option<ShapeBorder>,
padding: Option<f32>,
height: Option<f32>,
min_width: Option<f32>,
elevation: Option<f32>,
}
impl<Msg> Button<Msg> {
/// Creates a button with a label.
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
variant: Variant::default(),
on_press: None,
enabled: true,
label_style: None,
color: None,
label_color: None,
border_color: None,
border_width: None,
shape: None,
padding: None,
height: None,
min_width: None,
elevation: None,
}
}
/// Enables or **disables** the button: disabled, it is greyed out, has no shadow
/// and emits nothing at all (neither click nor keyboard focus) — the rendering of
/// an unavailable control, e.g. "Next" while a step is invalid.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Overrides the corner radii (uniform via `f32`, per corner via [`BorderRadius`] —
/// connected segments, button groups…). Defaults to a **stadium**: the radius is half
/// the button's height, whatever that height turns out to be.
pub fn radius(mut self, radius: impl Into<BorderRadius>) -> Self {
self.shape = Some(ShapeBorder::rounded(radius));
self
}
/// **What shape it is** (`shape_border.dart`), over the corners named above. The last
/// of the two to be called is the one that counts — they are one property, and
/// [`radius`](Self::radius) is the shorthand for the common case.
#[must_use]
pub fn shape(mut self, shape: ShapeBorder) -> Self {
self.shape = Some(shape);
self
}
/// Chooses the visual variant.
pub fn variant(mut self, variant: Variant) -> Self {
self.variant = variant;
self
}
/// The label's type. Defaults to the theme's `label_large` step.
pub fn label_style(mut self, style: TextStyle) -> Self {
self.label_style = Some(style);
self
}
/// Font size — sugar for [`Button::label_style`] with the label step resized.
pub fn size(mut self, size: f32) -> Self {
let mut style = self.label_style.unwrap_or(TextStyle::new(size));
style.size = Some(size);
self.label_style = Some(style);
self
}
/// The surface under the label.
pub fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
/// The label's colour.
pub fn label_color(mut self, color: Color) -> Self {
self.label_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 room either side of the label.
pub fn padding(mut self, padding: f32) -> Self {
self.padding = Some(padding);
self
}
/// The button's height.
pub fn height(mut self, height: f32) -> Self {
self.height = Some(height);
self
}
/// The narrowest it will be, however short its label.
pub fn min_width(mut self, width: f32) -> Self {
self.min_width = Some(width);
self
}
/// How far it sits off the surface, **in every state**. `0.0` is flat whatever the
/// pointer does.
///
/// Unset, the variant's own heights, and they move with the state as the reference's
/// do: an elevated button rests at 1, rises to 3 under a pointer and is back at 1 while
/// pressed; a filled, tonal or danger button is flat and rises to 1 under a pointer; an
/// outlined or a text button stays flat. A disabled button is flat either way.
pub fn elevation(mut self, elevation: f32) -> Self {
self.elevation = Some(elevation);
self
}
/// Message emitted on click.
pub fn on_press(mut self, message: impl Into<Msg>) -> Self {
self.on_press = Some(message.into());
self
}
fn label_style_of(&self, theme: &Theme) -> TextStyle {
self.label_style
.or(theme.widgets.button.label_style)
.unwrap_or(theme.text.label_large)
}
fn padding_of(&self, theme: &Theme) -> f32 {
self.padding
.or(theme.widgets.button.padding)
.unwrap_or(self.variant.padding())
}
fn height_of(&self, theme: &Theme) -> f32 {
self.height
.or(theme.widgets.button.height)
.unwrap_or(BUTTON_HEIGHT)
}
fn min_width_of(&self, theme: &Theme) -> f32 {
self.min_width
.or(theme.widgets.button.min_width)
.unwrap_or(BUTTON_MIN_WIDTH)
}
/// The height this frame: nought while disabled, the caller's or the theme's in every
/// state, and otherwise the variant's own for the state the button is in.
///
/// It was one number whatever the state, so an elevated button did not rise under a
/// pointer and a filled one never left the surface.
fn elevation_of(&self, theme: &Theme, status: &Status) -> f32 {
if !self.enabled {
return 0.0;
}
match self.elevation.or(theme.widgets.button.elevation) {
Some(height) => height,
None => self.variant.heights().at(status),
}
}
/// **What shape this button is**: its own word, then the theme's shape, then the
/// theme's plain radius, then a **stadium** — which is what the reference's buttons
/// are (`button_style.dart`).
///
/// It used to work the stadium out here as `height / 2`, which is the right number
/// for a button wider than it is tall and the wrong one for a button that is not:
/// a stadium takes half its **short** side. Saying the word instead of the number
/// gets that right at every size, and lets a caller say `circle` or `beveled`.
fn shape_of(&self, theme: &Theme) -> ShapeBorder {
crate::resolve_shape(
self.shape,
theme.widgets.button.shape,
theme.widgets.button.radius,
ShapeBorder::stadium(),
)
}
/// `(background, label, outline)` for the variant and the theme, disabled included.
///
/// A disabled button loses its accent in every variant — the label goes to `on_surface`
/// at 38 % throughout, so unavailable reads as unavailable rather than as a quieter
/// version of the variant. What it does **not** do is give every variant a container.
///
/// Until milestone 324 it did, and the reference is explicit that it should not: a text
/// button's background is `transparent` in every state, and an outlined one's disabled
/// state keeps its outline at 12 % rather than trading it for a fill. Flattening all six
/// to the same grey pill destroyed any selection a group of buttons was carrying — a
/// disabled page strip showed six identical pills with no current page — which is the
/// same mistake as fading a selected chip's accent, arrived at from the other side.
fn palette(&self, theme: &Theme) -> (Color, Color, Option<Color>) {
if !self.enabled {
let label = disabled_content(theme);
return match self.variant {
// No container, disabled or not.
Variant::Text => (Color::TRANSPARENT, label, None),
// The outline *is* the container here, so it takes the container opacity.
Variant::Outlined => (Color::TRANSPARENT, label, Some(disabled_container(theme))),
// The variants that genuinely are a filled container flatten to one.
_ => (disabled_container(theme), label, None),
};
}
let (background, label, outline) = match self.variant {
Variant::Filled => (theme.scheme.primary, theme.scheme.on_primary, None),
Variant::Tonal => (
theme.scheme.secondary_container,
theme.scheme.on_secondary_container,
None,
),
// `elevated_button.dart:534` — off the page, on the low rung.
Variant::Elevated => (
theme.scheme.surface_container_low,
theme.scheme.primary,
None,
),
Variant::Outlined => (
Color::TRANSPARENT,
theme.scheme.primary,
Some(theme.scheme.outline),
),
Variant::Text => (Color::TRANSPARENT, theme.scheme.primary, None),
Variant::Danger => (theme.scheme.error, theme.scheme.on_error, None),
};
(
self.color
.or(theme.widgets.button.color)
.unwrap_or(background),
self.label_color
.or(theme.widgets.button.label_color)
.unwrap_or(label),
self.border_color
.or(theme.widgets.button.border_color)
.or(outline),
)
}
}
impl<Msg: Clone> Widget<Msg> for Button<Msg> {
fn style(&self) -> Style {
Widget::<Msg>::style_themed(self, &Theme::default())
}
fn style_themed(&self, theme: &Theme) -> Style {
let style = self.label_style_of(theme);
let measured = frus_text::measure_style(&self.label, style);
let width = (measured.width + self.padding_of(theme) * 2.0).max(self.min_width_of(theme));
Style {
width: Dimension::Length(width.ceil()),
height: Dimension::Length(self.height_of(theme).max(measured.height).ceil()),
..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 (base, on_color, border) = self.palette(theme);
let shape = self.shape_of(theme);
let radius = shape
.as_rounded(bounds)
.map(|(_, radius)| radius)
.unwrap_or(BorderRadius::ZERO);
let elevation = self.elevation_of(theme, &status);
// At rest the shadow belongs to **one** variant — every enabled button used to cast
// one, which is the reference's elevated button drawn five times over — and under a
// pointer to the filled three as well.
if elevation > 0.0 {
let blur = elevation * 4.0 + 8.0;
scene.shadow(
Rect::new(
bounds.x - blur,
bounds.y + elevation * 2.0 - blur,
bounds.width + 2.0 * blur,
bounds.height + 2.0 * blur,
),
theme.scheme.shadow.with_alpha(0.35).fade(o),
radius.inflate(blur),
blur,
);
}
// Hover/press/focus through the theme's baked state layer. A disabled control has
// no states to layer, and a transparent surface must stay transparent at rest:
// the layer is what tints it under the pointer.
let color = if self.enabled {
theme.state_layer(base, on_color, &status)
} else {
base
};
let (border_width, border_color) = match (
self.border_width.or(theme.widgets.button.border_width),
border,
) {
(Some(width), Some(color)) => (width, color),
(Some(width), None) => (width, theme.scheme.outline),
(None, Some(color)) => (BUTTON_BORDER_WIDTH, color),
(None, None) => (0.0, Color::TRANSPARENT),
};
scene.draw_shape(
bounds,
shape.with_side(frus_core::BorderSide::new(
border_color.fade(o),
border_width,
)),
color.fade(o),
);
// Centred, both ways: a label pinned to the padding drifts off centre the moment
// the button is given a width of its own.
let style = self.label_style_of(theme);
let resolved = style.resolved();
// **A box narrower than the label ellipsises it**, rather than painting the words
// straight out of the pill on both sides. A button asks for the width its label
// needs and almost always gets it, so this is the rare case — a layout that had to
// squeeze it, which is what a bar of actions folding into a column does to the
// longest answer at a reader's font size. What it must not do is come apart.
let room = bounds.width - self.padding_of(theme) * 2.0;
let mut label = self.label.clone();
let mut measured = frus_text::measure_style(&label, style);
if room > 0.0 && measured.width > room + 0.5 {
label = crate::text::ellipsise(&label, &resolved, room);
measured = frus_text::measure_resolved(&label, &resolved);
}
scene.text(
Point::new(
bounds.x + (bounds.width - measured.width) / 2.0,
bounds.y + (bounds.height - measured.height) / 2.0,
),
label,
&resolved,
on_color.fade(o),
);
}
fn on_click(&self) -> Option<Msg> {
if self.enabled {
self.on_press.clone()
} else {
None
}
}
fn ink(&self, theme: &Theme) -> Option<crate::InkStyle> {
// A disabled control does not answer a tap, so it does not splash either.
if !self.enabled {
return None;
}
// The splash takes the button's **own** label colour: white-ish ink on a filled
// button, the accent on a text one. The theme's default (`on_surface`) would
// vanish on the first and shout on the second.
let (_, on_color, _) = self.palette(theme);
// Unless the application has named one: a theme that says what ink looks like has
// said it for every surface, not for the plain ones only.
let splash = theme
.widgets
.ink
.color
.unwrap_or_else(|| on_color.fade(0.16));
Some(
crate::InkStyle::of(theme)
.color(splash)
// The ink is clipped to the button, so it takes the corners the shape
// resolves to at the button's own height. A width is not known here —
// the ripple is placed before layout — so the height stands in, which
// is what a stadium's short side is for a button wider than it is tall.
.radius(
self.shape_of(theme)
.as_rounded(Rect::new(
0.0,
0.0,
self.height_of(theme),
self.height_of(theme),
))
.map(|(_, radius)| radius)
.unwrap_or(BorderRadius::ZERO),
),
)
}
fn focusable(&self) -> bool {
self.enabled
}
fn semantics(&self) -> Option<frus_core::SemanticsProperties> {
let semantics =
frus_core::SemanticsProperties::new(frus_core::Role::Button).label(self.label.clone());
// A disabled button does not announce a clickable action.
Some(if self.enabled {
semantics.clickable()
} else {
semantics.disabled(true)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use frus_core::Primitive;
#[derive(Clone, Debug, PartialEq)]
enum Msg {
Pressed,
}
/// What a button paints, in order: the shadow if it has one, then its box, then its
/// label.
fn painted(button: &Button<Msg>) -> Vec<Primitive> {
let mut scene = Scene::new();
Widget::<Msg>::paint(
button,
Rect::new(0.0, 0.0, 120.0, BUTTON_HEIGHT),
Status::default(),
&Theme::default(),
&mut scene,
);
scene.primitives().to_vec()
}
/// **A box narrower than the label ellipsises it.** A button asks for the width its
/// words need and nearly always gets it; when a layout has to squeeze one — a bar of
/// actions folding into a column, at a reader's font size — the label used to be
/// painted at its full width straight out of both ends of the pill.
#[test]
fn a_squeezed_label_is_cut_rather_than_painted_out_of_the_pill() {
let button = crate::dsl::button("Delete permanently", Msg::Pressed);
let drawn = |width: f32| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
&button,
Rect::new(0.0, 0.0, width, BUTTON_HEIGHT),
Status::default(),
&Theme::default(),
&mut scene,
);
scene
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Text { text, position, .. } => Some((text.clone(), *position)),
_ => None,
})
.expect("a label")
};
let (whole, _) = drawn(400.0);
assert_eq!(whole, "Delete permanently", "room enough: nothing is cut");
let (cut, at) = drawn(120.0);
assert!(cut.ends_with('…'), "cut short: {cut:?}");
assert!(at.x >= 0.0, "and it starts inside the pill: {at:?}");
}
/// **A button is a pill at any size** (`button_style.dart`), which it was not.
///
/// The stadium used to be worked out here as `height / 2` — the right number for a
/// button wider than it is tall, and the wrong one for a button that is not: a
/// stadium takes half its **short** side. Saying the word instead of the number gets
/// it right at every size.
#[test]
fn a_button_is_a_pill_at_any_size() {
let corners = |w: f32, h: f32, button: &Button<Msg>| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
button,
Rect::new(0.0, 0.0, w, h),
Status::default(),
&Theme::default(),
&mut scene,
);
// The first crisp rectangle is the box: the shadow before it is blurred, and
// a circle's box is **not** the one the button was given, so the search
// cannot be narrowed by width.
scene.primitives().iter().find_map(|p| match p {
Primitive::Rect {
rect, radius, blur, ..
} if *blur == 0.0 => Some((*rect, *radius)),
_ => None,
})
};
let button = Button::new("OK").on_press(Msg::Pressed);
let (_, wide) = corners(120.0, 40.0, &button).expect("a box");
assert_eq!(
wide,
BorderRadius::uniform(20.0),
"half the height, being shorter"
);
let (_, narrow) = corners(24.0, 80.0, &button).expect("a box");
assert_eq!(
narrow,
BorderRadius::uniform(12.0),
"half the *width* here — the old `height / 2` said 40 and turned the box \
inside out"
);
// And a caller may say something else entirely.
let boxed = Button::new("OK")
.on_press(Msg::Pressed)
.shape(frus_core::ShapeBorder::rounded(4.0));
assert_eq!(
corners(120.0, 40.0, &boxed).unwrap().1,
BorderRadius::uniform(4.0)
);
// A circle takes a square out of the middle rather than filling the box.
let round = Button::new("OK")
.on_press(Msg::Pressed)
.shape(frus_core::ShapeBorder::circle());
let (box_, _) = corners(120.0, 40.0, &round).expect("a box");
assert_eq!(box_, Rect::new(40.0, 0.0, 40.0, 40.0));
}
fn surface(button: &Button<Msg>) -> (Color, BorderRadius, f32) {
painted(button)
.iter()
.find_map(|p| match p {
Primitive::Rect {
color,
radius,
border_width,
blur,
..
} if *blur == 0.0 => Some((*color, *radius, *border_width)),
_ => None,
})
.expect("a button paints its box")
}
#[test]
fn on_click_returns_message() {
let button = Button::new("OK").on_press(Msg::Pressed);
assert_eq!(Widget::on_click(&button), Some(Msg::Pressed));
}
#[test]
fn disabled_button_is_inert_and_unfocusable() {
let button = Button::new("Next").on_press(Msg::Pressed).enabled(false);
assert_eq!(Widget::on_click(&button), None, "disabled: no message");
assert!(
!Widget::<Msg>::focusable(&button),
"disabled: out of the tab order"
);
let semantics = Widget::<Msg>::semantics(&button).expect("semantics present");
assert!(!semantics.clickable, "disabled: not announced as clickable");
assert!(semantics.disabled, "and announced as unavailable");
let enabled = Button::new("Next").on_press(Msg::Pressed).enabled(true);
assert_eq!(Widget::on_click(&enabled), Some(Msg::Pressed));
}
#[test]
fn only_the_elevated_variant_casts_a_shadow() {
// Every enabled button used to cast one, which is the reference's *elevated*
// button drawn five times over — and an emphasis order in which nothing is quiet.
let shadows = |variant: Variant| {
painted(&Button::<Msg>::new("Go").variant(variant))
.iter()
.filter(|p| matches!(p, Primitive::Rect { blur, .. } if *blur > 0.0))
.count()
};
assert_eq!(shadows(Variant::Elevated), 1);
for flat in [
Variant::Filled,
Variant::Tonal,
Variant::Outlined,
Variant::Text,
Variant::Danger,
] {
assert_eq!(shadows(flat), 0, "{flat:?} is flat");
}
assert_eq!(
shadows(Variant::Elevated).min(
painted(
&Button::<Msg>::new("Go")
.variant(Variant::Elevated)
.enabled(false)
)
.iter()
.filter(|p| matches!(p, Primitive::Rect { blur, .. } if *blur > 0.0))
.count()
),
0,
"and a disabled one does not float"
);
}
#[test]
fn the_variants_are_told_apart_by_their_surface() {
let theme = Theme::default();
assert_eq!(surface(&Button::<Msg>::new("Go")).0, theme.scheme.primary);
assert_eq!(
surface(&Button::<Msg>::new("Go").variant(Variant::Tonal)).0,
theme.scheme.secondary_container
);
assert_eq!(
surface(&Button::<Msg>::new("Go").variant(Variant::Danger)).0,
theme.scheme.error
);
// The two quiet ones have no surface at all until something happens to them.
assert_eq!(
surface(&Button::<Msg>::new("Go").variant(Variant::Text)).0,
Color::TRANSPARENT
);
let outlined = surface(&Button::<Msg>::new("Go").variant(Variant::Outlined));
assert_eq!(outlined.0, Color::TRANSPARENT);
assert_eq!(
outlined.2, BUTTON_BORDER_WIDTH,
"an outline, and only there"
);
assert_eq!(
surface(&Button::<Msg>::new("Go").variant(Variant::Text)).2,
0.0
);
}
#[test]
fn a_button_is_a_stadium_whatever_its_height() {
// The radius follows the height rather than the theme's corner setting: half of it,
// so a button stays a lozenge instead of becoming a box with soft corners.
assert_eq!(
surface(&Button::<Msg>::new("Go")).1,
BorderRadius::uniform(BUTTON_HEIGHT / 2.0)
);
// And a caller who wants corners can still have them.
assert_eq!(
surface(&Button::<Msg>::new("Go").radius(4.0)).1,
BorderRadius::uniform(4.0)
);
}
#[test]
fn a_button_is_the_references_size() {
let theme = Theme::default();
let size = |button: Button<Msg>| {
let style = Widget::<Msg>::style_themed(&button, &theme);
match (style.width, style.height) {
(Dimension::Length(w), Dimension::Length(h)) => (w, h),
other => panic!("{other:?}"),
}
};
let (width, height) = size(Button::new("OK"));
assert_eq!(height, BUTTON_HEIGHT);
// The minimum binds only where the label plus its room falls short of it, which
// at 24 px either side means a label of about one character.
assert!(width >= BUTTON_MIN_WIDTH);
assert_eq!(
size(Button::new("I")).0,
BUTTON_MIN_WIDTH,
"a one-letter label does not give a narrower button"
);
// A long one grows past the minimum, by the padding on either side.
let (wide, _) = size(Button::new("A considerably longer label"));
assert!(wide > BUTTON_MIN_WIDTH);
// A text button keeps the height and gives back the room.
let (narrow, _) = size(Button::new("A considerably longer label").variant(Variant::Text));
assert_eq!(
wide - narrow,
(BUTTON_PADDING - BUTTON_TEXT_PADDING) * 2.0,
"a text button's label sits closer to its edges"
);
}
/// A disabled button loses its **accent** in every variant — that is what makes
/// unavailable read as unavailable rather than as a quieter version of the variant.
///
/// It does not lose its **shape**. This test asserted the opposite until milestone 324,
/// and the picture is what settled it: flattening all six to the same grey pill left a
/// disabled page strip showing six identical pills with no current page, and the
/// reference is explicit that a text button's background is transparent in every state.
#[test]
fn a_disabled_button_drops_its_accent_but_keeps_its_shape() {
let theme = Theme::default();
let grey = disabled_container(&theme);
// The variants that genuinely are a filled container flatten to one.
for variant in [
Variant::Filled,
Variant::Tonal,
Variant::Elevated,
Variant::Danger,
] {
let (fill, _, _) = surface(&Button::<Msg>::new("Go").variant(variant).enabled(false));
assert_eq!(fill, grey, "{variant:?} should flatten to a container");
}
// A text button has no container, disabled or not.
let (fill, _, width) = surface(
&Button::<Msg>::new("Go")
.variant(Variant::Text)
.enabled(false),
);
assert_eq!(fill.a, 0.0, "a disabled text button gains no fill");
assert_eq!(width, 0.0, "and no outline");
// An outlined one keeps its outline, at the container opacity, and gains no fill.
let (fill, _, width) = surface(
&Button::<Msg>::new("Go")
.variant(Variant::Outlined)
.enabled(false),
);
assert_eq!(fill.a, 0.0, "a disabled outlined button gains no fill");
assert!(width > 0.0, "and keeps its outline");
}
/// Whatever the shape, the **label** is the same grey in every variant: that is the
/// half of the rule that says "unavailable".
#[test]
fn a_disabled_label_is_the_same_in_every_variant() {
let theme = Theme::default();
for variant in [
Variant::Filled,
Variant::Tonal,
Variant::Elevated,
Variant::Outlined,
Variant::Text,
Variant::Danger,
] {
let label = painted(&Button::<Msg>::new("Go").variant(variant).enabled(false))
.iter()
.find_map(|p| match p {
Primitive::Text { color, .. } => Some(*color),
_ => None,
})
.expect("a button paints its label");
assert_eq!(label, disabled_content(&theme), "{variant:?}");
assert_ne!(label, theme.scheme.primary, "never the accent: {variant:?}");
}
}
#[test]
fn every_measurement_is_the_callers_and_then_the_themes() {
let mut theme = Theme::default();
theme.widgets.button.height = Some(56.0);
let height =
|button: Button<Msg>, theme: &Theme| match Widget::<Msg>::style_themed(&button, theme)
.height
{
Dimension::Length(h) => h,
other => panic!("{other:?}"),
};
assert_eq!(
height(Button::new("Go"), &Theme::default()),
BUTTON_HEIGHT,
"the framework's"
);
assert_eq!(height(Button::new("Go"), &theme), 56.0, "the theme's");
assert_eq!(
height(Button::new("Go").height(30.0), &theme),
30.0,
"the caller's, over the theme's"
);
}
/// **A button's height follows its state**, as the reference's does. An elevated one
/// rests at 1, rises to 3 under a pointer and is back at 1 once pressed; a filled, tonal
/// or danger one is flat and rises to 1 under a pointer. Every button here held one
/// height whatever the pointer did. The height moves by the progress the state layer is
/// painted with, so half-way into a hover is half-way up.
#[test]
fn the_height_follows_the_state() {
// The height a painted shadow stands for: its blur is four pixels a step, plus eight.
let height = |button: &Button<Msg>, status: Status, theme: &Theme| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
button,
Rect::new(0.0, 0.0, 120.0, BUTTON_HEIGHT),
status,
theme,
&mut scene,
);
scene
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { blur, .. } if *blur > 0.0 => Some((blur - 8.0) / 4.0),
_ => None,
})
.unwrap_or(0.0)
};
let theme = Theme::default();
let rest = Status::default();
let hovered = Status {
hover_progress: 1.0,
..Default::default()
};
let held = Status {
hover_progress: 1.0,
press_progress: 1.0,
..Default::default()
};
let focused = Status {
focus_progress: 1.0,
..Default::default()
};
let half = Status {
hover_progress: 0.5,
..Default::default()
};
let elevated = Button::new("Go")
.variant(Variant::Elevated)
.on_press(Msg::Pressed);
assert_eq!(height(&elevated, rest, &theme), 1.0);
assert_eq!(height(&elevated, hovered, &theme), 3.0);
assert_eq!(
height(&elevated, held, &theme),
1.0,
"a press outranks the hover"
);
assert_eq!(height(&elevated, focused, &theme), 1.0);
assert_eq!(
height(&elevated, half, &theme),
2.0,
"it moves, it does not jump"
);
for variant in [Variant::Filled, Variant::Tonal, Variant::Danger] {
let button = Button::new("Go").variant(variant).on_press(Msg::Pressed);
assert_eq!(height(&button, rest, &theme), 0.0, "{variant:?} rests flat");
assert_eq!(height(&button, hovered, &theme), 1.0, "{variant:?} rises");
assert_eq!(height(&button, held, &theme), 0.0, "{variant:?} pressed");
assert_eq!(height(&button, focused, &theme), 0.0, "{variant:?} focused");
}
for variant in [Variant::Outlined, Variant::Text] {
let button = Button::new("Go").variant(variant).on_press(Msg::Pressed);
assert_eq!(
height(&button, hovered, &theme),
0.0,
"{variant:?} stays flat"
);
}
let disabled = Button::new("Go")
.variant(Variant::Elevated)
.on_press(Msg::Pressed)
.enabled(false);
assert_eq!(
height(&disabled, hovered, &theme),
0.0,
"a disabled one does not rise"
);
// A height the caller or the theme names holds in every state.
let told = Button::new("Go").elevation(2.0).on_press(Msg::Pressed);
assert_eq!(height(&told, rest, &theme), 2.0);
assert_eq!(height(&told, held, &theme), 2.0);
let mut flat = Theme::default();
flat.widgets.button.elevation = Some(0.0);
assert_eq!(height(&elevated, hovered, &flat), 0.0, "the theme's word");
assert_eq!(
height(&told, hovered, &flat),
2.0,
"and the caller's over it"
);
}
}