Skip to main content

waft_material/compose/
button_group.rs

1//! Compose's material3 `ButtonGroup.kt`: the parts the port can carry.
2//!
3//! Compose's button group gathers a row of related buttons. A standard group spaces them 12
4//! apart; a connected group spaces them 2 apart and rounds the corners that meet the gap
5//! tighter than the outer ones. Compose also expands the pressed button and hides the ones that
6//! do not fit into an overflow menu; see PORTING.md for why those are not here.
7//!
8//! The group lays out buttons the app builds, so an app styles a connected group's buttons with
9//! the shapes in [`ButtonGroupDefaults`].
10
11use std::fmt;
12
13use waft_embedder::Radius;
14use waft_foundation::App;
15use waft_painting::{
16    BorderRadiusDirectional, BorderRadiusGeometry, BorderSide, OutlinedBorderRef,
17    RoundedRectangleBorder,
18};
19use waft_widgets::{
20    BuildContext, CrossAxisAlignment, IntoWidget, KeyRef, MainAxisAlignment, MainAxisSize, Row,
21    StatelessWidget, WidgetRef,
22};
23
24use crate::compose::split_button::SplitButtonDefaults;
25
26/// Compose's `ButtonGroupDefaults`: the spacing and shapes a group uses.
27pub struct ButtonGroupDefaults;
28
29impl ButtonGroupDefaults {
30    /// The fraction of the pressed button's width a press is allowed to add.
31    ///
32    /// The group does not expand a pressed button (PORTING.md); this is the value Compose would
33    /// use.
34    pub const EXPANDED_RATIO: f64 = 0.15;
35
36    /// The default spacing between the buttons of a standard group.
37    pub const BETWEEN_SPACE: f64 = 12.0;
38
39    /// The default spacing between the buttons of a connected group.
40    pub const CONNECTED_SPACE_BETWEEN: f64 = 2.0;
41
42    /// The resting inner corner of a connected button, `ShapeTokens.CornerValueSmall`.
43    const INNER: f64 = 8.0;
44
45    /// The pressed inner corner of a connected button, `ShapeTokens.CornerValueExtraSmall`.
46    const PRESSED_INNER: f64 = 4.0;
47
48    /// The shapes of the first button of a connected group at `button_height`.
49    pub fn connected_leading_button_shapes_for(
50        button_height: f64,
51    ) -> (OutlinedBorderRef, OutlinedBorderRef, OutlinedBorderRef) {
52        let full = Radius::circular(button_height / 2.0);
53        (
54            rounded(full, Radius::circular(Self::INNER)),
55            rounded(full, Radius::circular(Self::PRESSED_INNER)),
56            rounded(full, full),
57        )
58    }
59
60    /// The shapes of a middle button of a connected group at `button_height`.
61    pub fn connected_middle_button_shapes_for(
62        button_height: f64,
63    ) -> (OutlinedBorderRef, OutlinedBorderRef, OutlinedBorderRef) {
64        let full = Radius::circular(button_height / 2.0);
65        (
66            rounded(Radius::circular(Self::INNER), Radius::circular(Self::INNER)),
67            rounded(
68                Radius::circular(Self::PRESSED_INNER),
69                Radius::circular(Self::PRESSED_INNER),
70            ),
71            rounded(full, full),
72        )
73    }
74
75    /// The shapes of the last button of a connected group at `button_height`.
76    pub fn connected_trailing_button_shapes_for(
77        button_height: f64,
78    ) -> (OutlinedBorderRef, OutlinedBorderRef, OutlinedBorderRef) {
79        let full = Radius::circular(button_height / 2.0);
80        (
81            rounded(Radius::circular(Self::INNER), full),
82            rounded(Radius::circular(Self::PRESSED_INNER), full),
83            rounded(full, full),
84        )
85    }
86
87    /// The three shapes of the first button of a connected group of small buttons.
88    pub fn connected_leading_button_shapes()
89    -> (OutlinedBorderRef, OutlinedBorderRef, OutlinedBorderRef) {
90        Self::connected_leading_button_shapes_for(SplitButtonDefaults::SMALL_CONTAINER_HEIGHT)
91    }
92
93    /// The three shapes of a middle button of a connected group of small buttons.
94    pub fn connected_middle_button_shapes()
95    -> (OutlinedBorderRef, OutlinedBorderRef, OutlinedBorderRef) {
96        Self::connected_middle_button_shapes_for(SplitButtonDefaults::SMALL_CONTAINER_HEIGHT)
97    }
98
99    /// The three shapes of the last button of a connected group of small buttons.
100    pub fn connected_trailing_button_shapes()
101    -> (OutlinedBorderRef, OutlinedBorderRef, OutlinedBorderRef) {
102        Self::connected_trailing_button_shapes_for(SplitButtonDefaults::SMALL_CONTAINER_HEIGHT)
103    }
104}
105
106/// A shape whose start corners are `start` and end corners `end`, flipped for right-to-left text
107/// as Compose's `RoundedCornerShape(topStart, topEnd, bottomEnd, bottomStart)` is.
108fn rounded(start: Radius, end: Radius) -> OutlinedBorderRef {
109    OutlinedBorderRef::new(RoundedRectangleBorder::new(
110        BorderSide::NONE,
111        BorderRadiusGeometry::Directional(BorderRadiusDirectional::only(start, end, start, end)),
112    ))
113}
114
115/// A row of related buttons.
116///
117/// Compose's `ButtonGroup`, without its press expansion or its overflow menu (PORTING.md).
118pub struct ButtonGroup {
119    pub key: Option<KeyRef>,
120    /// The group's buttons, which the app builds and styles.
121    pub children: Vec<WidgetRef>,
122    /// The space between neighbouring buttons.
123    pub spacing: f64,
124    /// How the buttons are placed along the row.
125    pub horizontal_alignment: MainAxisAlignment,
126    /// How a button shorter than the group is aligned vertically; Compose's default is the top.
127    pub vertical_alignment: CrossAxisAlignment,
128}
129
130impl ButtonGroup {
131    /// Creates a standard button group; Compose's `ButtonGroup(overflowIndicator, content)` with
132    /// its default arrangement, and no overflow indicator.
133    pub fn new(children: impl IntoIterator<Item = WidgetRef>) -> ButtonGroup {
134        ButtonGroup {
135            key: None,
136            children: children.into_iter().collect(),
137            spacing: ButtonGroupDefaults::BETWEEN_SPACE,
138            horizontal_alignment: MainAxisAlignment::Start,
139            vertical_alignment: CrossAxisAlignment::Start,
140        }
141    }
142
143    /// Creates a connected button group, whose buttons sit 2 apart and are styled with
144    /// [`ButtonGroupDefaults`]'s connected shapes.
145    pub fn connected(children: impl IntoIterator<Item = WidgetRef>) -> ButtonGroup {
146        ButtonGroup {
147            spacing: ButtonGroupDefaults::CONNECTED_SPACE_BETWEEN,
148            ..ButtonGroup::new(children)
149        }
150    }
151
152    /// Dart `key:`.
153    pub fn key(mut self, key: KeyRef) -> ButtonGroup {
154        self.key = Some(key);
155        self
156    }
157
158    /// Compose's `horizontalArrangement:` argument, as the space between buttons and the row's
159    /// alignment.
160    pub fn spacing(mut self, spacing: f64) -> ButtonGroup {
161        self.spacing = spacing;
162        self
163    }
164
165    /// Compose's `horizontalArrangement: Arrangement.Start/Center/End`.
166    pub fn horizontal_alignment(mut self, horizontal_alignment: MainAxisAlignment) -> ButtonGroup {
167        self.horizontal_alignment = horizontal_alignment;
168        self
169    }
170
171    /// Compose's `verticalAlignment:` argument.
172    pub fn vertical_alignment(mut self, vertical_alignment: CrossAxisAlignment) -> ButtonGroup {
173        self.vertical_alignment = vertical_alignment;
174        self
175    }
176}
177
178impl fmt::Debug for ButtonGroup {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.debug_struct("ButtonGroup")
181            .field("buttons", &self.children.len())
182            .field("spacing", &self.spacing)
183            .finish_non_exhaustive()
184    }
185}
186
187impl StatelessWidget for ButtonGroup {
188    fn key(&self) -> Option<&KeyRef> {
189        self.key.as_ref()
190    }
191
192    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
193        Row::new()
194            .main_axis_size(MainAxisSize::Min)
195            .main_axis_alignment(self.horizontal_alignment)
196            .cross_axis_alignment(self.vertical_alignment)
197            .spacing(self.spacing)
198            .children(self.children.clone())
199            .into_widget()
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use waft_embedder::{Radius, Rect};
206    use waft_widgets::testing::{WidgetTester, find, test_widgets};
207    use waft_widgets::{Center, IntoWidget, SizedBox, Text};
208
209    use super::*;
210    use crate::filled_button::FilledButton;
211    use crate::test_support::material_app;
212    use crate::theme_data::ThemeData;
213
214    fn button(label: &'static str) -> WidgetRef {
215        FilledButton::new(
216            Some(waft_foundation::Listener::new(|_app| {})),
217            Some(Text::new(label)),
218        )
219        .into_widget()
220    }
221
222    fn sized_button(label: &'static str, height: f64) -> WidgetRef {
223        SizedBox::new()
224            .height(height)
225            .child(button(label))
226            .into_widget()
227    }
228
229    fn pump<K>(tester: &mut WidgetTester, group: impl IntoWidget<K>) {
230        let theme = ThemeData::builder().build(&tester.cell.borrow());
231        tester.pump_widget(material_app(
232            theme,
233            Center::new().child(group).into_widget(),
234        ));
235    }
236
237    fn button_rects(tester: &WidgetTester) -> Vec<Rect> {
238        find::by_type::<FilledButton>()
239            .evaluate(tester)
240            .into_iter()
241            .map(|element| tester.get_rect(element))
242            .collect()
243    }
244
245    /// Compose's `default_positioning`, whose twin `differentHorizontalSpacing_positioning` asserts
246    /// the same: the buttons sit 12 apart and the group wraps them.
247    #[test]
248    fn default_positioning() {
249        test_widgets(|tester| {
250            pump(
251                tester,
252                ButtonGroup::new(vec![button("A"), button("B"), button("C"), button("D")]),
253            );
254            let wrapper = tester.get_rect(find::by_type::<ButtonGroup>());
255            let buttons = button_rects(tester);
256            assert_eq!(buttons[0].left - wrapper.left, 0.0);
257            assert_eq!(buttons[1].left - buttons[0].right, 12.0);
258            assert_eq!(buttons[2].left - buttons[1].right, 12.0);
259            assert_eq!(buttons[3].left - buttons[2].right, 12.0);
260            assert_eq!(wrapper.right - buttons[3].right, 0.0);
261        });
262    }
263
264    /// Not a Compose test: a spacing of zero puts the buttons edge to edge.
265    #[test]
266    fn a_custom_spacing_puts_the_buttons_edge_to_edge() {
267        test_widgets(|tester| {
268            pump(
269                tester,
270                ButtonGroup::new(vec![button("One"), button("Two")]).spacing(0.0),
271            );
272            let buttons = button_rects(tester);
273            assert!((buttons[1].left - buttons[0].right).abs() < 1e-3);
274        });
275    }
276
277    /// Compose's `horizontalArrangement_*Arrangement_buttonGroupPositioning`: a group as wide as
278    /// a phone's screen, 360 here, places three buttons so that they cover the point `fraction` of
279    /// its width.
280    fn check_arrangement(alignment: MainAxisAlignment, fraction: f64) {
281        test_widgets(|tester| {
282            pump(
283                tester,
284                SizedBox::new().width(360.0).child(
285                    ButtonGroup::new(vec![button("0"), button("1"), button("2")])
286                        .horizontal_alignment(alignment),
287                ),
288            );
289            let screen = tester.get_rect(find::by_type::<ButtonGroup>());
290            let buttons = button_rects(tester);
291            let expected_positioning = screen.left + screen.width() * fraction;
292            assert!((buttons[0].left..=buttons[2].right).contains(&expected_positioning));
293        });
294    }
295
296    #[test]
297    fn horizontal_arrangement_start_arrangement_button_group_positioning() {
298        check_arrangement(MainAxisAlignment::Start, 1.0 / 3.0);
299    }
300
301    #[test]
302    fn horizontal_arrangement_center_arrangement_button_group_positioning() {
303        check_arrangement(MainAxisAlignment::Center, 1.0 / 2.0);
304    }
305
306    #[test]
307    fn horizontal_arrangement_end_arrangement_button_group_positioning() {
308        check_arrangement(MainAxisAlignment::End, 2.0 / 3.0);
309    }
310
311    /// Compose's `buttonGroup_verticalAlignment_is*`: buttons 48 and 64 high, aligned by the
312    /// group's vertical alignment.
313    fn aligned_button_rects(tester: &mut WidgetTester, alignment: CrossAxisAlignment) -> Vec<Rect> {
314        pump(
315            tester,
316            ButtonGroup::new(vec![sized_button("A", 48.0), sized_button("B", 64.0)])
317                .vertical_alignment(alignment),
318        );
319        button_rects(tester)
320    }
321
322    #[test]
323    fn button_group_vertical_alignment_is_top() {
324        test_widgets(|tester| {
325            let buttons = aligned_button_rects(tester, CrossAxisAlignment::Start);
326            assert_eq!(buttons[0].top, buttons[1].top);
327        });
328    }
329
330    #[test]
331    fn button_group_vertical_alignment_is_center() {
332        test_widgets(|tester| {
333            let buttons = aligned_button_rects(tester, CrossAxisAlignment::Center);
334            assert_eq!(
335                buttons[0].center().dy().round(),
336                buttons[1].center().dy().round()
337            );
338        });
339    }
340
341    #[test]
342    fn button_group_vertical_alignment_is_bottom() {
343        test_widgets(|tester| {
344            let buttons = aligned_button_rects(tester, CrossAxisAlignment::End);
345            assert_eq!(buttons[0].bottom, buttons[1].bottom);
346        });
347    }
348
349    /// The default vertical alignment is Compose's `Alignment.Top`.
350    #[test]
351    fn button_group_vertical_alignment_defaults_to_top() {
352        test_widgets(|tester| {
353            pump(
354                tester,
355                ButtonGroup::new(vec![sized_button("A", 48.0), sized_button("B", 64.0)]),
356            );
357            let buttons = button_rects(tester);
358            assert_eq!(buttons[0].top, buttons[1].top);
359        });
360    }
361
362    fn corners(shape: &OutlinedBorderRef) -> [Radius; 4] {
363        let shape = shape
364            .as_any()
365            .downcast_ref::<RoundedRectangleBorder>()
366            .expect("a rounded rectangle");
367        let BorderRadiusGeometry::Directional(radius) = shape.border_radius else {
368            panic!("a directional border radius");
369        };
370        [
371            radius.top_start,
372            radius.top_end,
373            radius.bottom_start,
374            radius.bottom_end,
375        ]
376    }
377
378    /// Not a Compose test: `connectedLeadingButtonShapes`' outer corners take the full height's
379    /// radius, the inner ones the connected group's resting and pressed inner corner.
380    #[test]
381    fn the_connected_leading_shapes_follow_their_corners() {
382        let (shape, pressed, checked) =
383            ButtonGroupDefaults::connected_leading_button_shapes_for(40.0);
384        assert_eq!(
385            corners(&shape),
386            [
387                Radius::circular(20.0),
388                Radius::circular(8.0),
389                Radius::circular(20.0),
390                Radius::circular(8.0)
391            ]
392        );
393        assert_eq!(
394            corners(&pressed),
395            [
396                Radius::circular(20.0),
397                Radius::circular(4.0),
398                Radius::circular(20.0),
399                Radius::circular(4.0)
400            ]
401        );
402        assert_eq!([20.0; 4].map(Radius::circular), corners(&checked));
403    }
404
405    /// Not a Compose test: `connectedMiddleButtonShapes` and `connectedTrailingButtonShapes`' corners.
406    #[test]
407    fn the_connected_middle_and_trailing_shapes_follow_their_corners() {
408        let (middle, pressed, _) = ButtonGroupDefaults::connected_middle_button_shapes_for(40.0);
409        assert_eq!(
410            corners(&middle),
411            [
412                Radius::circular(8.0),
413                Radius::circular(8.0),
414                Radius::circular(8.0),
415                Radius::circular(8.0)
416            ]
417        );
418        assert_eq!([4.0; 4].map(Radius::circular), corners(&pressed));
419
420        let (trailing, pressed, checked) =
421            ButtonGroupDefaults::connected_trailing_button_shapes_for(40.0);
422        assert_eq!(
423            corners(&trailing),
424            [
425                Radius::circular(8.0),
426                Radius::circular(20.0),
427                Radius::circular(8.0),
428                Radius::circular(20.0)
429            ]
430        );
431        assert_eq!(
432            corners(&pressed),
433            [
434                Radius::circular(4.0),
435                Radius::circular(20.0),
436                Radius::circular(4.0),
437                Radius::circular(20.0)
438            ]
439        );
440        assert_eq!([20.0; 4].map(Radius::circular), corners(&checked));
441    }
442}