Skip to main content

waft_material/
button_bar.rs

1//! Flutter counterpart: material_ui's `button_bar.dart`.
2#![allow(
3    deprecated,
4    reason = "Dart deprecates `ButtonBar` and its theme, which this file still implements"
5)]
6
7use std::fmt;
8use std::rc::Rc;
9
10use waft_embedder::{Offset, Rect, Size, TextDirection};
11use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsNode};
12use waft_painting::{Axis, EdgeInsets, EdgeInsetsGeometry};
13use waft_rendering::{
14    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ContainerBoxParentData,
15    ContainerRenderObjectData, ContainerRenderObjectMixin, FlexParentData, MainAxisAlignment,
16    MainAxisSize, RenderBox, RenderBoxContainerDefaultsMixin, RenderBoxData, RenderFlexData,
17    RenderFlexMixin, RenderHandle, RenderObject, RenderObjectData,
18};
19use waft_widgets::{
20    BuildContext, Center, ConstrainedBox, Directionality, IntoWidget, KeyRef,
21    MultiChildRenderObjectWidget, Padding, RenderObjectWidget, StatelessWidget, VerticalDirection,
22    WidgetRef,
23};
24
25use crate::button_bar_theme::ButtonBarTheme;
26use crate::button_theme::ButtonTheme;
27use crate::button_theme::{ButtonBarLayoutBehavior, ButtonTextTheme};
28
29/// An end-aligned row of buttons, laying out into a column if there is not enough horizontal
30/// space.
31///
32/// [ButtonBar] has been replaced by a more efficient widget, `OverflowBar`.
33///
34/// Places the buttons horizontally according to `button_padding`. The children are laid out in
35/// a row with `MainAxisAlignment::End`. When the directionality is LTR, the button bar's
36/// children are right justified and the last child becomes the rightmost child. When it is RTL
37/// the children are left justified and the last child becomes the leftmost child.
38///
39/// If the button bar's width exceeds the maximum width constraint on the widget, it aligns its
40/// buttons in a column.
41#[deprecated(note = "Use OverflowBar instead. This feature was deprecated after v3.21.0-10.0.pre.")]
42pub struct ButtonBar {
43    pub key: Option<KeyRef>,
44    /// How the children should be placed along the horizontal axis.
45    pub alignment: Option<MainAxisAlignment>,
46    /// How much horizontal space is available.
47    pub main_axis_size: Option<MainAxisSize>,
48    /// Overrides the surrounding `ButtonBarThemeData::button_text_theme`.
49    pub button_text_theme: Option<ButtonTextTheme>,
50    /// Overrides the surrounding `ButtonThemeData`'s minimum width.
51    pub button_min_width: Option<f64>,
52    /// Overrides the surrounding `ButtonThemeData`'s height.
53    pub button_height: Option<f64>,
54    /// Overrides the surrounding `ButtonThemeData`'s padding.
55    pub button_padding: Option<EdgeInsetsGeometry>,
56    /// Overrides the surrounding `ButtonThemeData`'s aligned-dropdown setting.
57    pub button_aligned_dropdown: Option<bool>,
58    /// Defines whether the button bar sizes itself with a minimum size constraint or padding.
59    pub layout_behavior: Option<ButtonBarLayoutBehavior>,
60    /// Defines the vertical direction of the children if they overflow.
61    pub overflow_direction: Option<VerticalDirection>,
62    /// The spacing between buttons when they overflow.
63    pub overflow_button_spacing: Option<f64>,
64    /// The buttons to arrange horizontally.
65    pub children: Vec<WidgetRef>,
66}
67
68impl ButtonBar {
69    /// Creates a button bar; Dart's optional named arguments are the setters.
70    pub fn new() -> ButtonBar {
71        ButtonBar {
72            key: None,
73            alignment: None,
74            main_axis_size: None,
75            button_text_theme: None,
76            button_min_width: None,
77            button_height: None,
78            button_padding: None,
79            button_aligned_dropdown: None,
80            layout_behavior: None,
81            overflow_direction: None,
82            overflow_button_spacing: None,
83            children: Vec::new(),
84        }
85    }
86
87    /// Dart `ButtonBar(key:)`.
88    pub fn key(mut self, key: KeyRef) -> ButtonBar {
89        self.key = Some(key);
90        self
91    }
92
93    /// Dart `ButtonBar(alignment:)`.
94    pub fn alignment(mut self, alignment: MainAxisAlignment) -> ButtonBar {
95        self.alignment = Some(alignment);
96        self
97    }
98
99    /// Dart `ButtonBar(mainAxisSize:)`.
100    pub fn main_axis_size(mut self, main_axis_size: MainAxisSize) -> ButtonBar {
101        self.main_axis_size = Some(main_axis_size);
102        self
103    }
104
105    /// Dart `ButtonBar(buttonTextTheme:)`.
106    pub fn button_text_theme(mut self, button_text_theme: ButtonTextTheme) -> ButtonBar {
107        self.button_text_theme = Some(button_text_theme);
108        self
109    }
110
111    /// Dart `ButtonBar(buttonMinWidth:)`.
112    pub fn button_min_width(mut self, button_min_width: f64) -> ButtonBar {
113        debug_assert!(button_min_width >= 0.0);
114        self.button_min_width = Some(button_min_width);
115        self
116    }
117
118    /// Dart `ButtonBar(buttonHeight:)`.
119    pub fn button_height(mut self, button_height: f64) -> ButtonBar {
120        debug_assert!(button_height >= 0.0);
121        self.button_height = Some(button_height);
122        self
123    }
124
125    /// Dart `ButtonBar(buttonPadding:)`.
126    pub fn button_padding(mut self, button_padding: impl Into<EdgeInsetsGeometry>) -> ButtonBar {
127        self.button_padding = Some(button_padding.into());
128        self
129    }
130
131    /// Dart `ButtonBar(buttonAlignedDropdown:)`.
132    pub fn button_aligned_dropdown(mut self, button_aligned_dropdown: bool) -> ButtonBar {
133        self.button_aligned_dropdown = Some(button_aligned_dropdown);
134        self
135    }
136
137    /// Dart `ButtonBar(layoutBehavior:)`.
138    pub fn layout_behavior(mut self, layout_behavior: ButtonBarLayoutBehavior) -> ButtonBar {
139        self.layout_behavior = Some(layout_behavior);
140        self
141    }
142
143    /// Dart `ButtonBar(overflowDirection:)`.
144    pub fn overflow_direction(mut self, overflow_direction: VerticalDirection) -> ButtonBar {
145        self.overflow_direction = Some(overflow_direction);
146        self
147    }
148
149    /// Dart `ButtonBar(overflowButtonSpacing:)`.
150    pub fn overflow_button_spacing(mut self, overflow_button_spacing: f64) -> ButtonBar {
151        debug_assert!(overflow_button_spacing >= 0.0);
152        self.overflow_button_spacing = Some(overflow_button_spacing);
153        self
154    }
155
156    /// Dart `ButtonBar(children:)`.
157    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> ButtonBar {
158        self.children = children.into_iter().collect();
159        self
160    }
161}
162
163impl Default for ButtonBar {
164    fn default() -> ButtonBar {
165        ButtonBar::new()
166    }
167}
168
169impl fmt::Debug for ButtonBar {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.debug_struct("ButtonBar")
172            .field("alignment", &self.alignment)
173            .field("main_axis_size", &self.main_axis_size)
174            .finish_non_exhaustive()
175    }
176}
177
178impl StatelessWidget for ButtonBar {
179    fn key(&self) -> Option<&KeyRef> {
180        self.key.as_ref()
181    }
182
183    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
184        let parent_button_theme = ButtonTheme::of(app, context);
185        let bar_theme = ButtonBarTheme::of(app, context);
186
187        let button_theme = parent_button_theme
188            .copy_with()
189            .with_text_theme(
190                self.button_text_theme
191                    .or(bar_theme.button_text_theme)
192                    .unwrap_or(ButtonTextTheme::Primary),
193            )
194            .with_min_width(
195                self.button_min_width
196                    .or(bar_theme.button_min_width)
197                    .unwrap_or(64.0),
198            )
199            .with_height(
200                self.button_height
201                    .or(bar_theme.button_height)
202                    .unwrap_or(36.0),
203            )
204            .with_padding(
205                self.button_padding
206                    .or(bar_theme.button_padding)
207                    .unwrap_or_else(|| EdgeInsetsGeometry::symmetric(0.0, 8.0)),
208            )
209            .with_aligned_dropdown(
210                self.button_aligned_dropdown
211                    .or(bar_theme.button_aligned_dropdown)
212                    .unwrap_or(false),
213            )
214            .with_layout_behavior(
215                self.layout_behavior
216                    .or(bar_theme.layout_behavior)
217                    .unwrap_or(ButtonBarLayoutBehavior::Padded),
218            );
219
220        let padding_unit = button_theme.padding().horizontal() / 4.0;
221        let child = ButtonTheme::from_button_theme_data(
222            button_theme.clone(),
223            ButtonBarRow {
224                main_axis_alignment: self
225                    .alignment
226                    .or(bar_theme.alignment)
227                    .unwrap_or(MainAxisAlignment::End),
228                main_axis_size: self
229                    .main_axis_size
230                    .or(bar_theme.main_axis_size)
231                    .unwrap_or(MainAxisSize::Max),
232                overflow_direction: self
233                    .overflow_direction
234                    .or(bar_theme.overflow_direction)
235                    .unwrap_or(VerticalDirection::Down),
236                overflow_button_spacing: self.overflow_button_spacing,
237                children: self
238                    .children
239                    .iter()
240                    .map(|child| {
241                        Padding::new(EdgeInsets::symmetric(0.0, padding_unit))
242                            .child(child.clone())
243                            .into_widget()
244                    })
245                    .collect(),
246            },
247        );
248
249        match button_theme.layout_behavior {
250            ButtonBarLayoutBehavior::Padded => {
251                Padding::new(EdgeInsets::symmetric(2.0 * padding_unit, padding_unit))
252                    .child(child)
253                    .into_widget()
254            }
255            ButtonBarLayoutBehavior::Constrained => {
256                ConstrainedBox::new(BoxConstraints::new().min_height(52.0))
257                    .child(
258                        Padding::new(EdgeInsets::symmetric(0.0, padding_unit))
259                            .child(Center::new().child(child)),
260                    )
261                    .into_widget()
262            }
263        }
264    }
265}
266
267/// Dart's `_ButtonBarRow`.
268struct ButtonBarRow {
269    main_axis_alignment: MainAxisAlignment,
270    main_axis_size: MainAxisSize,
271    overflow_direction: VerticalDirection,
272    overflow_button_spacing: Option<f64>,
273    children: Vec<WidgetRef>,
274}
275
276impl RenderObjectWidget for ButtonBarRow {
277    type RenderObject = RenderButtonBarRow;
278
279    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
280        let text_direction =
281            Directionality::maybe_of(app, context).expect("a button bar needs a Directionality");
282        let render_object = RenderButtonBarRow::new(
283            app,
284            text_direction,
285            self.main_axis_alignment,
286            self.main_axis_size,
287            self.overflow_direction,
288            self.overflow_button_spacing,
289        );
290        render_object.as_object()
291    }
292
293    fn update_render_object(
294        &self,
295        app: &mut App,
296        context: BuildContext,
297        render_object: RenderHandle<RenderButtonBarRow>,
298    ) {
299        let text_direction = Directionality::maybe_of(app, context);
300        render_object.set_text_direction(app, text_direction);
301        render_object.set_main_axis_alignment(app, self.main_axis_alignment);
302        render_object.set_main_axis_size(app, self.main_axis_size);
303        render_object.set_vertical_direction(app, self.overflow_direction);
304        render_object.set_overflow_button_spacing(app, self.overflow_button_spacing);
305    }
306}
307
308impl MultiChildRenderObjectWidget for ButtonBarRow {
309    fn children(&self) -> &[WidgetRef] {
310        &self.children
311    }
312}
313
314impl fmt::Debug for ButtonBarRow {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        f.debug_struct("ButtonBarRow").finish_non_exhaustive()
317    }
318}
319
320/// Dart's `_RenderButtonBarRow`.
321struct RenderButtonBarRow {
322    render_object: RenderObjectData,
323    render_box: RenderBoxData,
324    container: ContainerRenderObjectData<AnyRenderBox>,
325    flex: RenderFlexData,
326    overflow_button_spacing: Option<f64>,
327    has_checked_layout_width: bool,
328}
329
330impl RenderButtonBarRow {
331    fn new(
332        app: &mut App,
333        text_direction: TextDirection,
334        main_axis_alignment: MainAxisAlignment,
335        main_axis_size: MainAxisSize,
336        overflow_direction: VerticalDirection,
337        overflow_button_spacing: Option<f64>,
338    ) -> RenderHandle<RenderButtonBarRow> {
339        debug_assert!(overflow_button_spacing.is_none_or(|spacing| spacing >= 0.0));
340        RenderHandle::new_box(
341            app,
342            RenderButtonBarRow {
343                render_object: RenderObjectData::new(),
344                render_box: RenderBoxData::new(),
345                container: ContainerRenderObjectData::new(),
346                flex: RenderFlexData::new()
347                    .direction(Axis::Horizontal)
348                    .main_axis_alignment(main_axis_alignment)
349                    .main_axis_size(main_axis_size)
350                    .vertical_direction(overflow_direction)
351                    .text_direction(Some(text_direction)),
352                overflow_button_spacing,
353                has_checked_layout_width: false,
354            },
355        )
356    }
357
358    fn overflow_button_spacing(self: RenderHandle<Self>, app: &App) -> Option<f64> {
359        self.get(app).overflow_button_spacing
360    }
361
362    fn set_overflow_button_spacing(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
363        if self.get(app).overflow_button_spacing == value {
364            return;
365        }
366        self.get_mut(app).overflow_button_spacing = value;
367        self.mark_needs_layout(app);
368    }
369
370    fn set_has_checked_layout_width(self: RenderHandle<Self>, app: &mut App, value: bool) {
371        self.get_mut(app).has_checked_layout_width = value;
372    }
373}
374
375impl ContainerRenderObjectMixin for RenderButtonBarRow {
376    type ChildType = AnyRenderBox;
377    type ParentDataType = FlexParentData;
378
379    fn container_data(
380        self: RenderHandle<Self>,
381        app: &App,
382    ) -> &ContainerRenderObjectData<AnyRenderBox> {
383        &self.get(app).container
384    }
385
386    fn container_data_mut(
387        self: RenderHandle<Self>,
388        app: &mut App,
389    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
390        &mut self.get_mut(app).container
391    }
392}
393
394impl RenderBoxContainerDefaultsMixin for RenderButtonBarRow {}
395
396impl RenderFlexMixin for RenderButtonBarRow {
397    fn flex_data(self: RenderHandle<Self>, app: &App) -> &RenderFlexData {
398        &self.get(app).flex
399    }
400
401    fn flex_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderFlexData {
402        &mut self.get_mut(app).flex
403    }
404}
405
406impl RenderObject for RenderButtonBarRow {
407    waft_rendering::render_object_accessors!();
408
409    fn debug_fill_properties(
410        self: RenderHandle<Self>,
411        app: &App,
412        properties: &mut DiagnosticPropertiesBuilder,
413    ) {
414        // Dart's `_RenderButtonBarRow` inherits `RenderFlex.debugFillProperties`.
415        RenderFlexMixin::debug_fill_properties(self, app, properties);
416    }
417
418    fn debug_describe_children(
419        self: RenderHandle<Self>,
420        app: &App,
421    ) -> Vec<Rc<dyn DiagnosticsNode>> {
422        ContainerRenderObjectMixin::debug_describe_children(self, app)
423    }
424
425    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
426        self.set_has_checked_layout_width(app, false);
427        RenderFlexMixin::perform_layout(self, app);
428        self.set_has_checked_layout_width(app, true);
429        let constraints = self.constraints(app);
430        if self.size(app).width() <= constraints.max_width {
431            RenderFlexMixin::perform_layout(self, app);
432            return;
433        }
434
435        let child_constraints = constraints.copy_with().min_width(0.0);
436        let mut current_height = 0.0;
437        let mut child = match self.vertical_direction(app) {
438            VerticalDirection::Down => self.first_child(app),
439            VerticalDirection::Up => self.last_child(app),
440        };
441        while let Some(current) = child {
442            current.layout(app, child_constraints, true);
443            let child_size = current.size(app);
444            let text_direction = self
445                .text_direction(app)
446                .expect("a button bar row is given a text direction");
447            let offset = match text_direction {
448                TextDirection::Ltr => match self.main_axis_alignment(app) {
449                    MainAxisAlignment::Center => Offset::new(
450                        (constraints.max_width - child_size.width()) / 2.0,
451                        current_height,
452                    ),
453                    MainAxisAlignment::End => {
454                        Offset::new(constraints.max_width - child_size.width(), current_height)
455                    }
456                    MainAxisAlignment::SpaceAround
457                    | MainAxisAlignment::SpaceBetween
458                    | MainAxisAlignment::SpaceEvenly
459                    | MainAxisAlignment::Start => Offset::new(0.0, current_height),
460                },
461                TextDirection::Rtl => match self.main_axis_alignment(app) {
462                    MainAxisAlignment::Center => Offset::new(
463                        constraints.max_width / 2.0 - child_size.width() / 2.0,
464                        current_height,
465                    ),
466                    MainAxisAlignment::End => Offset::new(0.0, current_height),
467                    MainAxisAlignment::SpaceAround
468                    | MainAxisAlignment::SpaceBetween
469                    | MainAxisAlignment::SpaceEvenly
470                    | MainAxisAlignment::Start => {
471                        Offset::new(constraints.max_width - child_size.width(), current_height)
472                    }
473                },
474            };
475            current
476                .as_object()
477                .parent_data_of_mut::<FlexParentData>(app)
478                .set_offset(offset);
479            current_height += child_size.height();
480            child = match self.vertical_direction(app) {
481                VerticalDirection::Down => self.child_after(app, current),
482                VerticalDirection::Up => self.child_before(app, current),
483            };
484            if let Some(spacing) = self.overflow_button_spacing(app)
485                && child.is_some()
486            {
487                current_height += spacing;
488            }
489        }
490        self.set_size(
491            app,
492            constraints.constrain(Size::new(constraints.max_width, current_height)),
493        );
494    }
495
496    fn visit_children(
497        self: RenderHandle<Self>,
498        app: &App,
499        visitor: &mut dyn FnMut(AnyRenderObject),
500    ) {
501        ContainerRenderObjectMixin::visit_children(self, app, visitor)
502    }
503
504    fn did_attach(
505        self: RenderHandle<Self>,
506        app: &mut App,
507        owner: waft_foundation::Handle<waft_rendering::PipelineOwner>,
508    ) {
509        ContainerRenderObjectMixin::did_attach(self, app, owner)
510    }
511
512    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
513        ContainerRenderObjectMixin::did_detach(self, app)
514    }
515
516    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
517        ContainerRenderObjectMixin::redepth_children(self, app)
518    }
519
520    fn paint(
521        self: RenderHandle<Self>,
522        app: &mut App,
523        context: &mut waft_rendering::PaintingContext,
524        offset: Offset,
525    ) {
526        RenderFlexMixin::paint(self, app, context, offset)
527    }
528
529    fn dispose(self: RenderHandle<Self>, app: &mut App) {
530        RenderFlexMixin::dispose(self, app)
531    }
532
533    fn describe_approximate_paint_clip(
534        self: RenderHandle<Self>,
535        app: &App,
536        child: AnyRenderObject,
537    ) -> Option<Rect> {
538        RenderFlexMixin::describe_approximate_paint_clip(self, app, child)
539    }
540}
541
542impl RenderBox for RenderButtonBarRow {
543    waft_rendering::render_box_accessors!();
544
545    fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
546        let constraints = self
547            .render_box_data(app)
548            .constraints()
549            .expect("the button bar has been given constraints");
550        if self.get(app).has_checked_layout_width {
551            constraints
552        } else {
553            constraints.copy_with().max_width(f64::INFINITY)
554        }
555    }
556
557    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
558        RenderFlexMixin::setup_parent_data(self, app, child)
559    }
560
561    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
562        RenderFlexMixin::compute_min_intrinsic_width(self, app, height)
563    }
564
565    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
566        RenderFlexMixin::compute_max_intrinsic_width(self, app, height)
567    }
568
569    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
570        RenderFlexMixin::compute_min_intrinsic_height(self, app, width)
571    }
572
573    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
574        RenderFlexMixin::compute_max_intrinsic_height(self, app, width)
575    }
576
577    fn compute_distance_to_actual_baseline(
578        self: RenderHandle<Self>,
579        app: &mut App,
580        baseline: waft_embedder::TextBaseline,
581    ) -> Option<f64> {
582        RenderFlexMixin::compute_distance_to_actual_baseline(self, app, baseline)
583    }
584
585    fn compute_dry_layout(
586        self: RenderHandle<Self>,
587        app: &mut App,
588        constraints: BoxConstraints,
589    ) -> Size {
590        let size = RenderFlexMixin::compute_dry_layout(
591            self,
592            app,
593            constraints.copy_with().max_width(f64::INFINITY),
594        );
595        if size.width() <= constraints.max_width {
596            return RenderFlexMixin::compute_dry_layout(self, app, constraints);
597        }
598        let mut current_height = 0.0;
599        let mut child = self.first_child(app);
600        while let Some(current) = child {
601            let child_constraints = constraints.copy_with().min_width(0.0);
602            let child_size = current.get_dry_layout(app, child_constraints);
603            current_height += child_size.height();
604            child = self.child_after(app, current);
605            if let Some(spacing) = self.overflow_button_spacing(app)
606                && child.is_some()
607            {
608                current_height += spacing;
609            }
610        }
611        constraints.constrain(Size::new(constraints.max_width, current_height))
612    }
613
614    fn compute_dry_baseline(
615        self: RenderHandle<Self>,
616        app: &mut App,
617        constraints: BoxConstraints,
618        baseline: waft_embedder::TextBaseline,
619    ) -> Option<f64> {
620        RenderFlexMixin::compute_dry_baseline(self, app, constraints, baseline)
621    }
622
623    fn hit_test_children(
624        self: RenderHandle<Self>,
625        app: &mut App,
626        result: &mut BoxHitTestResult<'_>,
627        position: Offset,
628    ) -> bool {
629        RenderFlexMixin::hit_test_children(self, app, result, position)
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use waft_embedder::Size;
636    use waft_foundation::{Listener, ValueKey};
637    use waft_widgets::testing::{WidgetTester, find, test_widgets};
638    use waft_widgets::{
639        Center, Directionality, IntoWidget, KeyRef, ListBody, MainAxisAlignment, MainAxisSize,
640        SingleChildScrollView, SizedBox, Text, TextDirection, VerticalDirection,
641    };
642
643    use super::*;
644    use crate::button_bar_theme::{ButtonBarTheme, ButtonBarThemeData};
645    use crate::button_theme::ButtonThemeData;
646    use crate::test_support::{material_app, probe};
647    use crate::text_button::TextButton;
648    use crate::theme_data::ThemeData;
649
650    /// Dart's `pumpWidget(MaterialApp(home: bar))`.
651    fn pump_home(tester: &mut WidgetTester, bar: ButtonBar) {
652        let theme = ThemeData::builder().build(&tester.cell.borrow());
653        tester.pump_widget(material_app(theme, bar.into_widget()));
654    }
655
656    /// Dart's `pumpWidget(MaterialApp(home: Center(child: bar)))`.
657    fn pump_centered(tester: &mut WidgetTester, bar: ButtonBar) {
658        let theme = ThemeData::builder().build(&tester.cell.borrow());
659        tester.pump_widget(material_app(theme, Center::new().child(bar).into_widget()));
660    }
661
662    /// Dart's `pumpWidget(MaterialApp(home: widget))`, for a theme-wrapped bar.
663    fn pump_wrapped(tester: &mut WidgetTester, widget: WidgetRef) {
664        let theme = ThemeData::builder().build(&tester.cell.borrow());
665        tester.pump_widget(material_app(theme, widget));
666    }
667
668    /// Dart's `SingleChildScrollView(child: ListBody(children: [Directionality(ltr, bar)]))`:
669    /// the bar is laid out with a loose height, as it is in a column.
670    fn pump_scrolling(tester: &mut WidgetTester, bar: ButtonBar) {
671        let theme = ThemeData::builder().build(&tester.cell.borrow());
672        tester.pump_widget(material_app(
673            theme,
674            SingleChildScrollView::new()
675                .child(ListBody::new().children(vec![
676                    Directionality::new(TextDirection::Ltr, bar).into_widget(),
677                ]))
678                .into_widget(),
679        ));
680    }
681
682    fn boxed(size: f64) -> WidgetRef {
683        SizedBox::new().width(size).height(size).into_widget()
684    }
685
686    fn keyed(width: f64, height: f64, name: &'static str) -> (KeyRef, WidgetRef) {
687        let key = KeyRef::from(ValueKey::new(name));
688        (
689            key.clone(),
690            SizedBox::new()
691                .key(key)
692                .width(width)
693                .height(height)
694                .into_widget(),
695        )
696    }
697
698    fn overflow_bar(
699        name: &'static str,
700        alignment: MainAxisAlignment,
701    ) -> (KeyRef, KeyRef, ButtonBar) {
702        let (first_key, first) = keyed(500.0, 50.0, name);
703        let (second_key, second) = keyed(500.0, 50.0, "second");
704        (
705            first_key,
706            second_key,
707            ButtonBar::new()
708                .alignment(alignment)
709                .button_padding(waft_painting::EdgeInsets::ZERO)
710                .children(vec![first, second]),
711        )
712    }
713
714    #[test]
715    fn button_bar_default_control_smoketest() {
716        test_widgets(|tester| {
717            tester.pump_widget(Directionality::new(TextDirection::Ltr, ButtonBar::new()));
718        });
719    }
720
721    #[test]
722    fn the_default_alignment_is_end() {
723        test_widgets(|tester| {
724            pump_home(tester, ButtonBar::new().children(vec![boxed(10.0)]));
725            let child = tester.get_rect(find::by_type::<SizedBox>().first());
726            assert_eq!(child.left, 782.0);
727            assert_eq!(child.right, 792.0);
728        });
729    }
730
731    #[test]
732    fn the_bar_theme_alignment_overrides_the_default() {
733        test_widgets(|tester| {
734            let data = ButtonBarThemeData::new().with_alignment(MainAxisAlignment::Center);
735            pump_wrapped(
736                tester,
737                ButtonBarTheme::new(data, ButtonBar::new().children(vec![boxed(10.0)]))
738                    .into_widget(),
739            );
740            let child = tester.get_rect(find::by_type::<SizedBox>().first());
741            assert_eq!(child.left, 395.0);
742            assert_eq!(child.right, 405.0);
743        });
744    }
745
746    #[test]
747    fn an_alignment_overrides_the_bar_theme_and_the_default() {
748        test_widgets(|tester| {
749            let data = ButtonBarThemeData::new().with_alignment(MainAxisAlignment::Center);
750            pump_wrapped(
751                tester,
752                ButtonBarTheme::new(
753                    data,
754                    ButtonBar::new()
755                        .alignment(MainAxisAlignment::Start)
756                        .children(vec![boxed(10.0)]),
757                )
758                .into_widget(),
759            );
760            let child = tester.get_rect(find::by_type::<SizedBox>().first());
761            assert_eq!(child.left, 8.0);
762            assert_eq!(child.right, 18.0);
763        });
764    }
765
766    fn three_children(name: &'static str) -> (KeyRef, KeyRef, KeyRef, Vec<WidgetRef>) {
767        let (child0, widget0) = keyed(100.0, 100.0, name);
768        let (child1, widget1) = keyed(100.0, 100.0, "child1");
769        let (child2, widget2) = keyed(100.0, 100.0, "child2");
770        (child0, child1, child2, vec![widget0, widget1, widget2])
771    }
772
773    #[test]
774    fn the_default_main_axis_size_is_max() {
775        test_widgets(|tester| {
776            let bar_key = KeyRef::from(ValueKey::new("row"));
777            let (child0, child1, child2, children) = three_children("child0");
778            pump_centered(
779                tester,
780                ButtonBar::new()
781                    .key(bar_key.clone())
782                    .button_padding(waft_painting::EdgeInsets::ZERO)
783                    .children(children),
784            );
785
786            let bar = tester.get_rect(find::by_key(bar_key));
787            assert_eq!(bar.width(), 800.0);
788            assert_eq!(bar.height(), 100.0);
789
790            let child0 = tester.get_rect(find::by_key(child0));
791            assert_eq!(child0.size(), Size::new(100.0, 100.0));
792            assert_eq!(child0.right, 800.0 - 200.0);
793            let child1 = tester.get_rect(find::by_key(child1));
794            assert_eq!(child1.size(), Size::new(100.0, 100.0));
795            assert_eq!(child1.right, 800.0 - 100.0);
796            let child2 = tester.get_rect(find::by_key(child2));
797            assert_eq!(child2.size(), Size::new(100.0, 100.0));
798            assert_eq!(child2.right, 800.0);
799        });
800    }
801
802    #[test]
803    fn the_bar_theme_main_axis_size_overrides_the_default() {
804        test_widgets(|tester| {
805            let bar_key = KeyRef::from(ValueKey::new("row"));
806            let (child0, child1, child2, children) = three_children("child0");
807            let data = ButtonBarThemeData::new().with_main_axis_size(MainAxisSize::Min);
808            pump_wrapped(
809                tester,
810                ButtonBarTheme::new(
811                    data,
812                    Center::new().child(
813                        ButtonBar::new()
814                            .key(bar_key.clone())
815                            .button_padding(waft_painting::EdgeInsets::ZERO)
816                            .children(children),
817                    ),
818                )
819                .into_widget(),
820            );
821
822            let bar = tester.get_rect(find::by_key(bar_key));
823            assert_eq!(bar.width(), 300.0);
824            assert_eq!(bar.height(), 100.0);
825
826            let left = (800.0 - bar.width()) / 2.0;
827            let child0 = tester.get_rect(find::by_key(child0));
828            assert_eq!(child0.size(), Size::new(100.0, 100.0));
829            assert_eq!(child0.left, left);
830            let child1 = tester.get_rect(find::by_key(child1));
831            assert_eq!(child1.size(), Size::new(100.0, 100.0));
832            assert_eq!(child1.left, left + 100.0);
833            let child2 = tester.get_rect(find::by_key(child2));
834            assert_eq!(child2.size(), Size::new(100.0, 100.0));
835            assert_eq!(child2.left, left + 200.0);
836        });
837    }
838
839    #[test]
840    fn a_main_axis_size_overrides_the_bar_theme_and_the_default() {
841        test_widgets(|tester| {
842            let bar_key = KeyRef::from(ValueKey::new("row"));
843            let (child0, child1, child2, children) = three_children("child0");
844            let data = ButtonBarThemeData::new().with_main_axis_size(MainAxisSize::Min);
845            pump_wrapped(
846                tester,
847                ButtonBarTheme::new(
848                    data,
849                    Center::new().child(
850                        ButtonBar::new()
851                            .key(bar_key.clone())
852                            .button_padding(waft_painting::EdgeInsets::ZERO)
853                            .main_axis_size(MainAxisSize::Max)
854                            .children(children),
855                    ),
856                )
857                .into_widget(),
858            );
859
860            let bar = tester.get_rect(find::by_key(bar_key));
861            assert_eq!(bar.width(), 800.0);
862            assert_eq!(bar.height(), 100.0);
863            let child0 = tester.get_rect(find::by_key(child0));
864            assert_eq!(child0.size(), Size::new(100.0, 100.0));
865            assert_eq!(child0.right, 800.0 - 200.0);
866            let child1 = tester.get_rect(find::by_key(child1));
867            assert_eq!(child1.size(), Size::new(100.0, 100.0));
868            assert_eq!(child1.right, 800.0 - 100.0);
869            let child2 = tester.get_rect(find::by_key(child2));
870            assert_eq!(child2.size(), Size::new(100.0, 100.0));
871            assert_eq!(child2.right, 800.0);
872        });
873    }
874
875    /// The `ButtonThemeData` a child of `bar` sees, under the theme `wrap` adds.
876    fn child_button_theme(
877        tester: &mut WidgetTester,
878        bar_theme: Option<ButtonBarThemeData>,
879        bar: impl FnOnce(WidgetRef) -> ButtonBar,
880    ) -> ButtonThemeData {
881        probe(
882            tester,
883            move |app, probe| {
884                let bar = bar(probe).into_widget();
885                let home = match bar_theme {
886                    Some(data) => ButtonBarTheme::new(data, bar).into_widget(),
887                    None => bar,
888                };
889                material_app(ThemeData::builder().build(app), home)
890            },
891            ButtonTheme::of,
892        )
893    }
894
895    #[test]
896    fn default_button_properties_override_button_theme_properties() {
897        test_widgets(|tester| {
898            let button_theme =
899                child_button_theme(tester, None, |child| ButtonBar::new().children(vec![child]));
900            assert_eq!(button_theme.text_theme, ButtonTextTheme::Primary);
901            assert_eq!(button_theme.min_width, 64.0);
902            assert_eq!(button_theme.height, 36.0);
903            assert_eq!(
904                button_theme.padding(),
905                EdgeInsets::symmetric(0.0, 8.0).into()
906            );
907            assert!(!button_theme.aligned_dropdown);
908            assert_eq!(
909                button_theme.layout_behavior,
910                ButtonBarLayoutBehavior::Padded
911            );
912        });
913    }
914
915    #[test]
916    fn button_bar_theme_button_properties_override_defaults_and_button_theme_properties() {
917        test_widgets(|tester| {
918            let bar_theme = ButtonBarThemeData::new()
919                .with_button_text_theme(ButtonTextTheme::Primary)
920                .with_button_min_width(42.0)
921                .with_button_height(84.0)
922                .with_button_padding(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0))
923                .with_button_aligned_dropdown(true)
924                .with_layout_behavior(ButtonBarLayoutBehavior::Constrained);
925            let button_theme = child_button_theme(tester, Some(bar_theme), |child| {
926                ButtonBar::new().children(vec![child])
927            });
928            assert_eq!(button_theme.text_theme, ButtonTextTheme::Primary);
929            assert_eq!(button_theme.min_width, 42.0);
930            assert_eq!(button_theme.height, 84.0);
931            assert_eq!(
932                button_theme.padding(),
933                EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0).into()
934            );
935            assert!(button_theme.aligned_dropdown);
936            assert_eq!(
937                button_theme.layout_behavior,
938                ButtonBarLayoutBehavior::Constrained
939            );
940        });
941    }
942
943    #[test]
944    fn button_bar_button_properties_override_button_bar_theme_defaults_and_button_theme_properties()
945    {
946        test_widgets(|tester| {
947            let bar_theme = ButtonBarThemeData::new()
948                .with_button_text_theme(ButtonTextTheme::Accent)
949                .with_button_min_width(4242.0)
950                .with_button_height(8484.0)
951                .with_button_padding(EdgeInsets::from_ltrb(50.0, 60.0, 70.0, 80.0))
952                .with_button_aligned_dropdown(false)
953                .with_layout_behavior(ButtonBarLayoutBehavior::Padded);
954            let button_theme = child_button_theme(tester, Some(bar_theme), |child| {
955                ButtonBar::new()
956                    .button_text_theme(ButtonTextTheme::Primary)
957                    .button_min_width(42.0)
958                    .button_height(84.0)
959                    .button_padding(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0))
960                    .button_aligned_dropdown(true)
961                    .layout_behavior(ButtonBarLayoutBehavior::Constrained)
962                    .children(vec![child])
963            });
964            assert_eq!(button_theme.text_theme, ButtonTextTheme::Primary);
965            assert_eq!(button_theme.min_width, 42.0);
966            assert_eq!(button_theme.height, 84.0);
967            assert_eq!(
968                button_theme.padding(),
969                EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0).into()
970            );
971            assert!(button_theme.aligned_dropdown);
972            assert_eq!(
973                button_theme.layout_behavior,
974                ButtonBarLayoutBehavior::Constrained
975            );
976        });
977    }
978
979    #[test]
980    fn a_constrained_layout_has_a_minimum_height_of_fifty_two() {
981        test_widgets(|tester| {
982            pump_scrolling(
983                tester,
984                ButtonBar::new()
985                    .layout_behavior(ButtonBarLayoutBehavior::Constrained)
986                    .children(vec![boxed(10.0)]),
987            );
988            let bar = tester.get_rect(find::by_type::<ButtonBar>());
989            assert_eq!(bar.bottom - bar.top, 52.0);
990        });
991    }
992
993    #[test]
994    fn a_padded_layout_adds_its_padding() {
995        test_widgets(|tester| {
996            pump_scrolling(
997                tester,
998                ButtonBar::new()
999                    .layout_behavior(ButtonBarLayoutBehavior::Padded)
1000                    .children(vec![boxed(10.0)]),
1001            );
1002            let bar = tester.get_rect(find::by_type::<ButtonBar>());
1003            assert_eq!(bar.bottom - bar.top, 26.0);
1004        });
1005    }
1006
1007    #[test]
1008    fn the_children_wrap_when_they_overflow() {
1009        test_widgets(|tester| {
1010            let (first_key, first) = keyed(800.0, 50.0, "one");
1011            let (second_key, second) = keyed(800.0, 50.0, "two");
1012            pump_home(tester, ButtonBar::new().children(vec![first, second]));
1013            let first = tester.get_rect(find::by_key(first_key));
1014            let second = tester.get_rect(find::by_key(second_key));
1015            assert_eq!(first.bottom, second.top);
1016            assert_eq!(first.left, second.left);
1017        });
1018    }
1019
1020    #[test]
1021    fn overflowing_children_default_to_the_end_alignment() {
1022        test_widgets(|tester| {
1023            let (first_key, second_key, bar) = overflow_bar("one", MainAxisAlignment::End);
1024            pump_home(tester, bar);
1025            let bar = tester.get_rect(find::by_type::<ButtonBar>());
1026            let first = tester.get_rect(find::by_key(first_key));
1027            let second = tester.get_rect(find::by_key(second_key));
1028            assert_eq!(first.bottom, second.top);
1029            assert_eq!(first.right, second.right);
1030            assert_eq!(first.right, bar.right);
1031        });
1032    }
1033
1034    #[test]
1035    fn overflowing_children_follow_a_start_alignment() {
1036        test_widgets(|tester| {
1037            let (first_key, second_key, bar) = overflow_bar("one", MainAxisAlignment::Start);
1038            pump_home(tester, bar);
1039            let bar = tester.get_rect(find::by_type::<ButtonBar>());
1040            let first = tester.get_rect(find::by_key(first_key));
1041            let second = tester.get_rect(find::by_key(second_key));
1042            assert_eq!(first.bottom, second.top);
1043            assert_eq!(first.left, second.left);
1044            assert_eq!(first.left, bar.left);
1045        });
1046    }
1047
1048    #[test]
1049    fn overflowing_children_follow_a_center_alignment() {
1050        test_widgets(|tester| {
1051            let (first_key, second_key, bar) = overflow_bar("one", MainAxisAlignment::Center);
1052            pump_home(tester, bar);
1053            let bar = tester.get_rect(find::by_type::<ButtonBar>());
1054            let first = tester.get_rect(find::by_key(first_key));
1055            let second = tester.get_rect(find::by_key(second_key));
1056            assert_eq!(first.bottom, second.top);
1057            assert_eq!(first.center().dx(), second.center().dx());
1058            assert_eq!(first.center().dx(), bar.center().dx());
1059        });
1060    }
1061
1062    #[test]
1063    fn overflowing_children_of_a_spread_alignment_start_at_the_start() {
1064        test_widgets(|tester| {
1065            for alignment in [
1066                MainAxisAlignment::SpaceEvenly,
1067                MainAxisAlignment::SpaceAround,
1068                MainAxisAlignment::SpaceBetween,
1069            ] {
1070                let (first_key, second_key, bar) = overflow_bar("one", alignment);
1071                pump_home(tester, bar);
1072                let bar_rect = tester.get_rect(find::by_type::<ButtonBar>());
1073                let first = tester.get_rect(find::by_key(first_key));
1074                let second = tester.get_rect(find::by_key(second_key));
1075                assert_eq!(first.bottom, second.top);
1076                assert_eq!(first.left, second.left);
1077                assert_eq!(first.left, bar_rect.left);
1078            }
1079        });
1080    }
1081
1082    #[test]
1083    fn overflowing_children_respect_the_overflow_direction() {
1084        test_widgets(|tester| {
1085            let (first_key, second_key, bar) = overflow_bar("one", MainAxisAlignment::Center);
1086            pump_home(tester, bar.overflow_direction(VerticalDirection::Up));
1087            let first = tester.get_rect(find::by_key(first_key));
1088            let second = tester.get_rect(find::by_key(second_key));
1089            assert!(second.bottom <= first.top);
1090        });
1091    }
1092
1093    #[test]
1094    fn overflowing_children_have_no_spacing_by_default() {
1095        test_widgets(|tester| {
1096            let (first_key, second_key, bar) = overflow_bar("one", MainAxisAlignment::Center);
1097            pump_home(tester, bar);
1098            let first = tester.get_rect(find::by_key(first_key));
1099            let second = tester.get_rect(find::by_key(second_key));
1100            assert_eq!(first.bottom, second.top);
1101        });
1102    }
1103
1104    #[test]
1105    fn overflowing_children_respect_the_overflow_button_spacing() {
1106        test_widgets(|tester| {
1107            let (first_key, second_key, bar) = overflow_bar("one", MainAxisAlignment::Center);
1108            pump_home(tester, bar.overflow_button_spacing(10.0));
1109            let first = tester.get_rect(find::by_key(first_key));
1110            let second = tester.get_rect(find::by_key(second_key));
1111            assert_eq!(first.bottom, second.top - 10.0);
1112        });
1113    }
1114
1115    #[test]
1116    fn the_bar_does_not_crash_at_zero_area() {
1117        test_widgets(|tester| {
1118            let theme = ThemeData::builder().build(&tester.cell.borrow());
1119            tester.pump_widget(material_app(
1120                theme,
1121                Center::new()
1122                    .child(SizedBox::shrink().child(ButtonBar::new().children(vec![
1123                        TextButton::new(Some(Listener::new(|_app| {})), Some(Text::new("X")))
1124                            .into_widget(),
1125                    ])))
1126                    .into_widget(),
1127            ));
1128            assert_eq!(tester.get_size(find::by_type::<ButtonBar>()), Size::ZERO);
1129        });
1130    }
1131
1132    /// Dart's `_RenderButtonBarRow` fills no properties of its own; it inherits
1133    /// `RenderFlex.debugFillProperties` and names its children `child 1`, `child 2`, ….
1134    #[test]
1135    fn a_button_bar_row_fills_the_properties_it_inherits() {
1136        use waft_foundation::{AppCell, DiagnosticPropertiesBuilder, DiagnosticsNode};
1137        use waft_rendering::RenderConstrainedBox;
1138
1139        let cell = AppCell::new();
1140        let mut app = cell.borrow_mut();
1141        let row = RenderButtonBarRow::new(
1142            &mut app,
1143            TextDirection::Ltr,
1144            MainAxisAlignment::End,
1145            MainAxisSize::Min,
1146            VerticalDirection::Down,
1147            None,
1148        );
1149        let first =
1150            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None)
1151                .as_box();
1152        let second =
1153            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None)
1154                .as_box();
1155        row.insert(&mut app, first, None);
1156        row.insert(&mut app, second, None);
1157
1158        let mut properties = DiagnosticPropertiesBuilder::new();
1159        RenderObject::debug_fill_properties(row, &app, &mut properties);
1160        let names: Vec<&str> = properties
1161            .properties
1162            .iter()
1163            .filter_map(|property| property.name())
1164            .collect();
1165        assert_eq!(
1166            names,
1167            [
1168                "direction",
1169                "mainAxisAlignment",
1170                "mainAxisSize",
1171                "crossAxisAlignment",
1172                "textDirection",
1173                "verticalDirection",
1174                "textBaseline",
1175                "spacing",
1176            ]
1177        );
1178
1179        let node = row.as_object().to_diagnostics_node(&app, None);
1180        let children: Vec<&str> = node
1181            .children()
1182            .iter()
1183            .filter_map(|child| child.name())
1184            .collect();
1185        assert_eq!(children, ["child 1", "child 2"]);
1186    }
1187}