Skip to main content

waft_material/
toggle_buttons.rs

1//! Flutter counterpart: material_ui's `toggle_buttons.dart`.
2
3#![expect(deprecated, reason = "Dart calls the deprecated `withOpacity`")]
4
5use std::any::Any;
6use std::f64::consts::PI;
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9
10use waft_embedder::{
11    Color, FillRule, Offset, PathBuilder, RRect, Radius, Rect, Size, TextBaseline,
12};
13use waft_foundation::{
14    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, FlagProperty, Listener,
15    ValueChanged,
16};
17use waft_painting::{
18    Alignment, AnyColor, Axis, BorderRadius, BorderSide, ClipContext, ColorProperty,
19    EdgeInsetsDirectional, EdgeInsetsGeometry, OutlinedBorderRef, RoundedRectangleBorder,
20    TextStyle, VerticalDirection,
21};
22use waft_rendering::{
23    AnyRenderBox, AnyRenderObject, BaselineOffset, BoxConstraints, BoxHitTestResult, BoxParentData,
24    ChildLayoutHelper, ChildLayouter, CrossAxisAlignment, MainAxisSize, PaintingContext, RenderBox,
25    RenderBoxData, RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
26    RenderObjectWithChildMixin, RenderShiftedBox,
27};
28use waft_services::MouseCursorRef;
29use waft_widgets::{
30    BuildContext, Center, ClipRRect, Column, Directionality, FocusNodeRef, IntoWidget,
31    IntrinsicHeight, IntrinsicWidth, KeyRef, MergeSemantics, RenderObjectWidget, Row, Semantics,
32    SingleChildRenderObjectWidget, StatelessWidget, WidgetRef, WidgetState, WidgetStateColor,
33    WidgetStateProperty, WidgetStatePropertyAll, WidgetStatePropertyRef, WidgetStates,
34};
35
36use crate::button_style::ButtonStyle;
37use crate::color_scheme::ColorScheme;
38use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
39use crate::constants::K_THEME_CHANGE_DURATION;
40use crate::ink_ripple::InkRipple;
41use crate::text_button::TextButton;
42use crate::theme::Theme;
43use crate::theme_data::{MaterialTapTargetSize, VisualDensity};
44use crate::toggle_buttons_theme::ToggleButtonsTheme;
45use crate::toggle_buttons_theme::ToggleButtonsThemeData;
46
47/// A set of toggle buttons.
48///
49/// The list of [`children`](Self::children) are laid out along [`direction`](Self::direction).
50/// The state of each button is controlled by [`is_selected`](Self::is_selected), which is a
51/// list of bools that determine if a button is in an unselected or selected state. They are
52/// both correlated by their index in the list. The length of [`is_selected`](Self::is_selected)
53/// has to match the length of the [`children`](Self::children) list.
54///
55/// ## Updating the button states
56///
57/// When the button is tapped, a [`on_pressed`](Self::on_pressed) callback with the index of
58/// the pressed button is called. The app must update the selection state in response, as the
59/// buttons keep none.
60///
61/// ## Customizing toggle buttons
62///
63/// Each toggle's behavior can be configured by the [`on_pressed`](Self::on_pressed) callback
64/// and [`is_selected`](Self::is_selected) list, which determines if the button is enabled or
65/// selected, and the colors and border of the buttons are set by the other fields, falling
66/// back to `ToggleButtonsTheme`, then to values from the overall `Theme`.
67///
68/// See also:
69///
70///  * `SegmentedButton`, a Material 3 replacement for this widget.
71///  * `IconButton`, to create buttons that contain icons.
72///  * `TextButton`, a Material Design button without a shadow.
73///  * `ElevatedButton`, a filled button whose material elevates when pressed.
74///  * `OutlinedButton`, a button with an outlined border and no fill color.
75///  * <https://material.io/design/components/buttons.html>
76pub struct ToggleButtons {
77    /// See [`Widget::key`](waft_widgets::Widget::key).
78    pub key: Option<KeyRef>,
79
80    /// The toggle button widgets.
81    ///
82    /// These are typically `Icon` or `Text` widgets. The boolean selection
83    /// state of each widget is defined by the corresponding
84    /// [`is_selected`](Self::is_selected) list item.
85    ///
86    /// The length of this list has to match the length of the
87    /// [`is_selected`](Self::is_selected) list.
88    pub children: Vec<WidgetRef>,
89
90    /// The corresponding selection state of each toggle button.
91    ///
92    /// Each value in this list represents the selection state of the [`children`](Self::children)
93    /// widget at the same index.
94    ///
95    /// The length of this list has to match the length of the [`children`](Self::children) list.
96    pub is_selected: Vec<bool>,
97
98    /// The callback that is called when a button is tapped.
99    ///
100    /// The index parameter of the callback is the index of the button that is tapped or
101    /// otherwise activated.
102    ///
103    /// When the callback is null, all toggle buttons will be disabled.
104    pub on_pressed: Option<ValueChanged<usize>>,
105
106    /// {@macro flutter.material.RawMaterialButton.mouseCursor}
107    ///
108    /// If this property is null, `WidgetStateMouseCursor::adaptive_clickable` will be used.
109    pub mouse_cursor: Option<MouseCursorRef>,
110
111    /// Configures the minimum size of the area within which the buttons may be pressed.
112    ///
113    /// If the [`tap_target_size`](Self::tap_target_size) is larger than [`constraints`](Self::constraints),
114    /// the button will include a pad of the remaining size so that the tap target is
115    /// at least as big as the [`tap_target_size`](Self::tap_target_size).
116    ///
117    /// Defaults to `ThemeData::material_tap_target_size`.
118    pub tap_target_size: Option<MaterialTapTargetSize>,
119
120    /// The text style of [`children`](Self::children).
121    ///
122    /// `TextStyle::color` will be ignored and substituted by [`color`](Self::color),
123    /// [`selected_color`](Self::selected_color) or [`disabled_color`](Self::disabled_color)
124    /// depending on whether the buttons are active, selected, or disabled.
125    ///
126    /// If this property is null, then `ToggleButtonsThemeData::text_style` is used.
127    /// If that is also null, then `TextTheme::body_medium` is used.
128    pub text_style: Option<TextStyle>,
129
130    /// Defines the button's size.
131    ///
132    /// Typically used to constrain the button's minimum size.
133    ///
134    /// If this property is null, then `ToggleButtonsThemeData::constraints` is used. If that
135    /// is also null, then a minimum size of 48 by 48 is used.
136    pub constraints: Option<BoxConstraints>,
137
138    /// The color for descendant `Text` and `Icon` widgets if the button is enabled and not
139    /// selected.
140    ///
141    /// If [`on_pressed`](Self::on_pressed) is not null, this color will be used for
142    /// unselected children. If it is null, then `ToggleButtonsThemeData::color` is used.
143    /// If that is also null, then `ColorScheme::on_surface` with an opacity of 0.87 is used.
144    pub color: Option<Color>,
145
146    /// The color for descendant `Text` and `Icon` widgets if the button is selected.
147    ///
148    /// If null, then `ToggleButtonsThemeData::selected_color` is used. If that is also null,
149    /// then `ColorScheme::primary` is used.
150    pub selected_color: Option<Color>,
151
152    /// The color for descendant `Text` and `Icon` widgets if the button is disabled.
153    ///
154    /// If null, then `ToggleButtonsThemeData::disabled_color` is used. If that is also null,
155    /// then `ColorScheme::on_surface` with an opacity of 0.38 is used.
156    pub disabled_color: Option<Color>,
157
158    /// The fill color for selected toggle buttons.
159    ///
160    /// If this is null, then `ToggleButtonsThemeData::fill_color` is used. If that is also
161    /// null, then `ColorScheme::primary` with an opacity of 0.12 is used.
162    ///
163    /// It can be a `WidgetStateColor`, which then resolves in the `WidgetState::Selected` and
164    /// `WidgetState::Disabled` states.
165    pub fill_color: Option<AnyColor>,
166
167    /// The color to use for filling the button when the button has input focus.
168    ///
169    /// If null, `ToggleButtonsThemeData::focus_color` is used, else `ColorScheme::primary` or
170    /// `ColorScheme::on_surface` with an opacity of 0.12.
171    pub focus_color: Option<Color>,
172
173    /// The highlight color for the button's `InkWell`.
174    ///
175    /// If null, `ToggleButtonsThemeData::highlight_color` is used, else
176    /// `ColorScheme::on_surface` with an opacity of 0.16 for an unselected button.
177    pub highlight_color: Option<Color>,
178
179    /// The splash color for the button's `InkWell`.
180    ///
181    /// If null, `ToggleButtonsThemeData::splash_color` is used, else `ColorScheme::primary`
182    /// or `ColorScheme::on_surface` with an opacity of 0.16.
183    pub splash_color: Option<Color>,
184
185    /// The color to use for filling the button when the button has a pointer hovering over it.
186    ///
187    /// If null, `ToggleButtonsThemeData::hover_color` is used, else `ColorScheme::primary` or
188    /// `ColorScheme::on_surface` with an opacity of 0.04.
189    pub hover_color: Option<Color>,
190
191    /// The list of [`FocusNodeRef`]s, corresponding to each toggle button.
192    ///
193    /// Focus is used to determine which widget should be affected by keyboard events. The
194    /// focus tree keeps track of which widget is currently focused on by the user.
195    ///
196    /// If not null, the length of this list has to match the length of the
197    /// [`children`](Self::children) list.
198    pub focus_nodes: Option<Vec<FocusNodeRef>>,
199
200    /// Whether or not to render a border around each toggle button.
201    ///
202    /// When true, a border with [`border_width`](Self::border_width), [`border_color`](Self::border_color),
203    /// [`selected_border_color`](Self::selected_border_color) and
204    /// [`disabled_border_color`](Self::disabled_border_color) is drawn.
205    ///
206    /// Defaults to true.
207    pub render_border: bool,
208
209    /// The border color to display when the toggle button is enabled and not selected.
210    ///
211    /// If null, `ToggleButtonsThemeData::border_color` is used, else `ColorScheme::on_surface`
212    /// with an opacity of 0.12.
213    pub border_color: Option<Color>,
214
215    /// The border color to display when the toggle button is selected.
216    ///
217    /// If null, `ToggleButtonsThemeData::selected_border_color` is used, else
218    /// `ColorScheme::on_surface` with an opacity of 0.12.
219    pub selected_border_color: Option<Color>,
220
221    /// The border color to display when the toggle button is disabled.
222    ///
223    /// If null, `ToggleButtonsThemeData::disabled_border_color` is used, else
224    /// `ColorScheme::on_surface` with an opacity of 0.12.
225    pub disabled_border_color: Option<Color>,
226
227    /// The width of the border surrounding each toggle button.
228    ///
229    /// This applies to both the greater surrounding border, as well as the
230    /// borders dividing each toggle button.
231    ///
232    /// To render a hairline border (one physical pixel), set [`border_width`](Self::border_width)
233    /// to 0.0. If null, `ToggleButtonsThemeData::border_width` is used, else 1.0.
234    pub border_width: Option<f64>,
235
236    /// The radii of the border's corners.
237    ///
238    /// If this property is null, then `ToggleButtonsThemeData::border_radius` is used.
239    /// If that is also null, then [`BorderRadius::ZERO`] is used.
240    pub border_radius: Option<BorderRadius>,
241
242    /// The direction along which the buttons are rendered.
243    ///
244    /// Defaults to [`Axis::Horizontal`].
245    pub direction: Axis,
246
247    /// If [`direction`](Self::direction) is [`Axis::Vertical`], this property defines whether
248    /// the buttons are laid out starting from the top (down) or the bottom (up).
249    ///
250    /// Defaults to [`VerticalDirection::Down`].
251    pub vertical_direction: VerticalDirection,
252}
253
254impl ToggleButtons {
255    const DEFAULT_BORDER_WIDTH: f64 = 1.0;
256
257    /// Creates a set of toggle buttons.
258    ///
259    /// It displays its widgets provided in a list of [`children`](Self::children) along
260    /// [`direction`](Self::direction). The state of each button is controlled by
261    /// [`is_selected`](Self::is_selected), which is a list of bools that determine if a button
262    /// is in an unselected or selected state. They are both correlated by their index in the
263    /// list. The length of [`is_selected`](Self::is_selected) has to match the length of the
264    /// [`children`](Self::children) list.
265    pub fn new(children: Vec<WidgetRef>, is_selected: Vec<bool>) -> ToggleButtons {
266        ToggleButtons {
267            key: None,
268            children,
269            is_selected,
270            on_pressed: None,
271            mouse_cursor: None,
272            tap_target_size: None,
273            text_style: None,
274            constraints: None,
275            color: None,
276            selected_color: None,
277            disabled_color: None,
278            fill_color: None,
279            focus_color: None,
280            highlight_color: None,
281            splash_color: None,
282            hover_color: None,
283            focus_nodes: None,
284            render_border: true,
285            border_color: None,
286            selected_border_color: None,
287            disabled_border_color: None,
288            border_width: None,
289            border_radius: None,
290            direction: Axis::Horizontal,
291            vertical_direction: VerticalDirection::Down,
292        }
293    }
294
295    /// Dart `ToggleButtons(key:)`.
296    pub fn key(mut self, key: KeyRef) -> ToggleButtons {
297        self.key = Some(key);
298        self
299    }
300
301    /// Dart `ToggleButtons(onPressed:)`.
302    pub fn on_pressed(mut self, on_pressed: impl Fn(&mut App, usize) + 'static) -> ToggleButtons {
303        self.on_pressed = Some(Rc::new(on_pressed));
304        self
305    }
306
307    /// Dart `ToggleButtons(mouseCursor:)`.
308    pub fn mouse_cursor(mut self, mouse_cursor: impl Into<MouseCursorRef>) -> ToggleButtons {
309        self.mouse_cursor = Some(mouse_cursor.into());
310        self
311    }
312
313    /// Dart `ToggleButtons(tapTargetSize:)`.
314    pub fn tap_target_size(mut self, tap_target_size: MaterialTapTargetSize) -> ToggleButtons {
315        self.tap_target_size = Some(tap_target_size);
316        self
317    }
318
319    /// Dart `ToggleButtons(textStyle:)`.
320    pub fn text_style(mut self, text_style: TextStyle) -> ToggleButtons {
321        self.text_style = Some(text_style);
322        self
323    }
324
325    /// Dart `ToggleButtons(constraints:)`.
326    pub fn constraints(mut self, constraints: BoxConstraints) -> ToggleButtons {
327        self.constraints = Some(constraints);
328        self
329    }
330
331    /// Dart `ToggleButtons(color:)`.
332    pub fn color(mut self, color: Color) -> ToggleButtons {
333        self.color = Some(color);
334        self
335    }
336
337    /// Dart `ToggleButtons(selectedColor:)`.
338    pub fn selected_color(mut self, selected_color: Color) -> ToggleButtons {
339        self.selected_color = Some(selected_color);
340        self
341    }
342
343    /// Dart `ToggleButtons(disabledColor:)`.
344    pub fn disabled_color(mut self, disabled_color: Color) -> ToggleButtons {
345        self.disabled_color = Some(disabled_color);
346        self
347    }
348
349    /// Dart `ToggleButtons(fillColor:)`.
350    pub fn fill_color(mut self, fill_color: impl Into<AnyColor>) -> ToggleButtons {
351        self.fill_color = Some(fill_color.into());
352        self
353    }
354
355    /// Dart `ToggleButtons(focusColor:)`.
356    pub fn focus_color(mut self, focus_color: Color) -> ToggleButtons {
357        self.focus_color = Some(focus_color);
358        self
359    }
360
361    /// Dart `ToggleButtons(highlightColor:)`.
362    pub fn highlight_color(mut self, highlight_color: Color) -> ToggleButtons {
363        self.highlight_color = Some(highlight_color);
364        self
365    }
366
367    /// Dart `ToggleButtons(hoverColor:)`.
368    pub fn hover_color(mut self, hover_color: Color) -> ToggleButtons {
369        self.hover_color = Some(hover_color);
370        self
371    }
372
373    /// Dart `ToggleButtons(splashColor:)`.
374    pub fn splash_color(mut self, splash_color: Color) -> ToggleButtons {
375        self.splash_color = Some(splash_color);
376        self
377    }
378
379    /// Dart `ToggleButtons(focusNodes:)`.
380    pub fn focus_nodes(mut self, focus_nodes: Vec<FocusNodeRef>) -> ToggleButtons {
381        self.focus_nodes = Some(focus_nodes);
382        self
383    }
384
385    /// Dart `ToggleButtons(renderBorder:)`.
386    pub fn render_border(mut self, render_border: bool) -> ToggleButtons {
387        self.render_border = render_border;
388        self
389    }
390
391    /// Dart `ToggleButtons(borderColor:)`.
392    pub fn border_color(mut self, border_color: Color) -> ToggleButtons {
393        self.border_color = Some(border_color);
394        self
395    }
396
397    /// Dart `ToggleButtons(selectedBorderColor:)`.
398    pub fn selected_border_color(mut self, selected_border_color: Color) -> ToggleButtons {
399        self.selected_border_color = Some(selected_border_color);
400        self
401    }
402
403    /// Dart `ToggleButtons(disabledBorderColor:)`.
404    pub fn disabled_border_color(mut self, disabled_border_color: Color) -> ToggleButtons {
405        self.disabled_border_color = Some(disabled_border_color);
406        self
407    }
408
409    /// Dart `ToggleButtons(borderRadius:)`.
410    pub fn border_radius(mut self, border_radius: BorderRadius) -> ToggleButtons {
411        self.border_radius = Some(border_radius);
412        self
413    }
414
415    /// Dart `ToggleButtons(borderWidth:)`.
416    pub fn border_width(mut self, border_width: f64) -> ToggleButtons {
417        self.border_width = Some(border_width);
418        self
419    }
420
421    /// Dart `ToggleButtons(direction:)`.
422    pub fn direction(mut self, direction: Axis) -> ToggleButtons {
423        self.direction = direction;
424        self
425    }
426
427    /// Dart `ToggleButtons(verticalDirection:)`.
428    pub fn vertical_direction(mut self, vertical_direction: VerticalDirection) -> ToggleButtons {
429        self.vertical_direction = vertical_direction;
430        self
431    }
432
433    // Determines if this is the first child that is being laid out
434    // by the render object, _not_ the order of the children in its list.
435    fn is_first_button(
436        &self,
437        index: usize,
438        length: usize,
439        text_direction: waft_painting::TextDirection,
440    ) -> bool {
441        match self.direction {
442            Axis::Horizontal => match text_direction {
443                waft_painting::TextDirection::Rtl => index == length - 1,
444                waft_painting::TextDirection::Ltr => index == 0,
445            },
446            Axis::Vertical => match self.vertical_direction {
447                VerticalDirection::Up => index == length - 1,
448                VerticalDirection::Down => index == 0,
449            },
450        }
451    }
452
453    // Determines if this is the last child that is being laid out
454    // by the render object, _not_ the order of the children in its list.
455    fn is_last_button(
456        &self,
457        index: usize,
458        length: usize,
459        text_direction: waft_painting::TextDirection,
460    ) -> bool {
461        match self.direction {
462            Axis::Horizontal => match text_direction {
463                waft_painting::TextDirection::Rtl => index == 0,
464                waft_painting::TextDirection::Ltr => index == length - 1,
465            },
466            Axis::Vertical => match self.vertical_direction {
467                VerticalDirection::Up => index == 0,
468                VerticalDirection::Down => index == length - 1,
469            },
470        }
471    }
472
473    fn get_edge_border_radius(
474        &self,
475        index: usize,
476        length: usize,
477        text_direction: waft_painting::TextDirection,
478        toggle_buttons_theme: &ToggleButtonsThemeData,
479    ) -> BorderRadius {
480        let resulting_border_radius = self
481            .border_radius
482            .or(toggle_buttons_theme.border_radius)
483            .unwrap_or(BorderRadius::ZERO);
484
485        if length == 1 {
486            return resulting_border_radius;
487        } else if self.direction == Axis::Horizontal {
488            if self.is_first_button(index, length, text_direction) {
489                return BorderRadius::only(
490                    resulting_border_radius.top_left,
491                    Radius::ZERO,
492                    resulting_border_radius.bottom_left,
493                    Radius::ZERO,
494                );
495            } else if self.is_last_button(index, length, text_direction) {
496                return BorderRadius::only(
497                    Radius::ZERO,
498                    resulting_border_radius.top_right,
499                    Radius::ZERO,
500                    resulting_border_radius.bottom_right,
501                );
502            }
503        } else if self.is_first_button(index, length, text_direction) {
504            return BorderRadius::only(
505                resulting_border_radius.top_left,
506                resulting_border_radius.top_right,
507                Radius::ZERO,
508                Radius::ZERO,
509            );
510        } else if self.is_last_button(index, length, text_direction) {
511            return BorderRadius::only(
512                Radius::ZERO,
513                Radius::ZERO,
514                resulting_border_radius.bottom_left,
515                resulting_border_radius.bottom_right,
516            );
517        }
518
519        BorderRadius::ZERO
520    }
521
522    fn get_clip_border_radius(
523        &self,
524        index: usize,
525        length: usize,
526        text_direction: waft_painting::TextDirection,
527        toggle_buttons_theme: &ToggleButtonsThemeData,
528    ) -> BorderRadius {
529        let resulting_border_radius = self
530            .border_radius
531            .or(toggle_buttons_theme.border_radius)
532            .unwrap_or(BorderRadius::ZERO);
533        let resulting_border_width = self
534            .border_width
535            .or(toggle_buttons_theme.border_width)
536            .unwrap_or(Self::DEFAULT_BORDER_WIDTH);
537        let half = Radius::circular(resulting_border_width / 2.0);
538
539        if length == 1 {
540            return BorderRadius::only(
541                resulting_border_radius.top_left - half,
542                resulting_border_radius.top_right - half,
543                resulting_border_radius.bottom_left - half,
544                resulting_border_radius.bottom_right - half,
545            );
546        } else if self.direction == Axis::Horizontal {
547            if self.is_first_button(index, length, text_direction) {
548                return BorderRadius::only(
549                    resulting_border_radius.top_left - half,
550                    Radius::ZERO,
551                    resulting_border_radius.bottom_left - half,
552                    Radius::ZERO,
553                );
554            } else if self.is_last_button(index, length, text_direction) {
555                return BorderRadius::only(
556                    Radius::ZERO,
557                    resulting_border_radius.top_right - half,
558                    Radius::ZERO,
559                    resulting_border_radius.bottom_right - half,
560                );
561            }
562        } else if self.is_first_button(index, length, text_direction) {
563            return BorderRadius::only(
564                resulting_border_radius.top_left - half,
565                resulting_border_radius.top_right - half,
566                Radius::ZERO,
567                Radius::ZERO,
568            );
569        } else if self.is_last_button(index, length, text_direction) {
570            return BorderRadius::only(
571                Radius::ZERO,
572                Radius::ZERO,
573                resulting_border_radius.bottom_left - half,
574                resulting_border_radius.bottom_right - half,
575            );
576        }
577        BorderRadius::ZERO
578    }
579
580    /// The border side of a button in the state the button is in: Dart's three
581    /// `_get*BorderSide` methods differ only in whether `selected` is true.
582    fn border_side_in_state(
583        &self,
584        selected: bool,
585        theme: &crate::theme_data::ThemeData,
586        toggle_buttons_theme: &ToggleButtonsThemeData,
587    ) -> BorderSide {
588        let resulting_border_width = self
589            .border_width
590            .or(toggle_buttons_theme.border_width)
591            .unwrap_or(Self::DEFAULT_BORDER_WIDTH);
592        let default_color = theme.color_scheme.on_surface().with_opacity(0.12);
593        if self.on_pressed.is_some() && selected {
594            BorderSide {
595                color: self
596                    .selected_border_color
597                    .or(toggle_buttons_theme.selected_border_color)
598                    .unwrap_or(default_color),
599                width: resulting_border_width,
600                ..BorderSide::default()
601            }
602        } else if self.on_pressed.is_some() && !selected {
603            BorderSide {
604                color: self
605                    .border_color
606                    .or(toggle_buttons_theme.border_color)
607                    .unwrap_or(default_color),
608                width: resulting_border_width,
609                ..BorderSide::default()
610            }
611        } else {
612            BorderSide {
613                color: self
614                    .disabled_border_color
615                    .or(toggle_buttons_theme.disabled_border_color)
616                    .unwrap_or(default_color),
617                width: resulting_border_width,
618                ..BorderSide::default()
619            }
620        }
621    }
622
623    fn get_leading_border_side(
624        &self,
625        index: usize,
626        theme: &crate::theme_data::ThemeData,
627        toggle_buttons_theme: &ToggleButtonsThemeData,
628    ) -> BorderSide {
629        if !self.render_border {
630            return BorderSide::NONE;
631        }
632
633        self.border_side_in_state(
634            self.is_selected[index] || (index != 0 && self.is_selected[index - 1]),
635            theme,
636            toggle_buttons_theme,
637        )
638    }
639
640    fn get_border_side(
641        &self,
642        index: usize,
643        theme: &crate::theme_data::ThemeData,
644        toggle_buttons_theme: &ToggleButtonsThemeData,
645    ) -> BorderSide {
646        if !self.render_border {
647            return BorderSide::NONE;
648        }
649
650        self.border_side_in_state(self.is_selected[index], theme, toggle_buttons_theme)
651    }
652
653    fn get_trailing_border_side(
654        &self,
655        index: usize,
656        theme: &crate::theme_data::ThemeData,
657        toggle_buttons_theme: &ToggleButtonsThemeData,
658    ) -> BorderSide {
659        if !self.render_border {
660            return BorderSide::NONE;
661        }
662
663        if index != self.children.len() - 1 {
664            return BorderSide::NONE;
665        }
666
667        self.border_side_in_state(self.is_selected[index], theme, toggle_buttons_theme)
668    }
669}
670
671impl Debug for ToggleButtons {
672    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673        f.debug_struct("ToggleButtons")
674            .field("is_selected", &self.is_selected)
675            .field("disabled", &self.on_pressed.is_none())
676            .field("direction", &self.direction)
677            .field("vertical_direction", &self.vertical_direction)
678            .finish_non_exhaustive()
679    }
680}
681
682impl StatelessWidget for ToggleButtons {
683    fn key(&self) -> Option<&KeyRef> {
684        self.key.as_ref()
685    }
686
687    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
688        properties.add(
689            FlagProperty::new("disabled", Some(self.on_pressed.is_none()))
690                .if_true("Buttons are disabled")
691                .if_false("Buttons are enabled"),
692        );
693        if let Some(text_style) = &self.text_style {
694            text_style.debug_fill_properties_with_prefix(properties, "textStyle.");
695        }
696        properties.add(ColorProperty::new("color", self.color).default_value(None));
697        properties
698            .add(ColorProperty::new("selectedColor", self.selected_color).default_value(None));
699        properties
700            .add(ColorProperty::new("disabledColor", self.disabled_color).default_value(None));
701        properties.add(
702            DiagnosticsProperty::<AnyColor>::new("fillColor", self.fill_color.clone())
703                .default_value(None),
704        );
705        properties.add(ColorProperty::new("focusColor", self.focus_color).default_value(None));
706        properties
707            .add(ColorProperty::new("highlightColor", self.highlight_color).default_value(None));
708        properties.add(ColorProperty::new("hoverColor", self.hover_color).default_value(None));
709        properties.add(ColorProperty::new("splashColor", self.splash_color).default_value(None));
710        properties.add(ColorProperty::new("borderColor", self.border_color).default_value(None));
711        properties.add(
712            ColorProperty::new("selectedBorderColor", self.selected_border_color)
713                .default_value(None),
714        );
715        properties.add(
716            ColorProperty::new("disabledBorderColor", self.disabled_border_color)
717                .default_value(None),
718        );
719        properties.add(
720            DiagnosticsProperty::<BorderRadius>::new("borderRadius", self.border_radius)
721                .default_value(None),
722        );
723        properties.add(DoubleProperty::new("borderWidth", self.border_width).default_value(None));
724        properties.add(
725            DiagnosticsProperty::<waft_foundation::DartEnum<Axis>>::new(
726                "direction",
727                Some(waft_foundation::DartEnum(self.direction)),
728            )
729            .default_value(Some(waft_foundation::DartEnum(Axis::Horizontal))),
730        );
731        properties.add(
732            DiagnosticsProperty::<waft_foundation::DartEnum<VerticalDirection>>::new(
733                "verticalDirection",
734                Some(waft_foundation::DartEnum(self.vertical_direction)),
735            )
736            .default_value(Some(waft_foundation::DartEnum(VerticalDirection::Down))),
737        );
738    }
739
740    fn debug_check_constructor(&self) {
741        debug_assert!(
742            self.children.len() == self.is_selected.len(),
743            "children.length == isSelected.length: {} children, {} isSelected",
744            self.children.len(),
745            self.is_selected.len()
746        );
747    }
748
749    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
750        debug_assert!(
751            self.focus_nodes
752                .as_ref()
753                .is_none_or(|focus_nodes| focus_nodes.len() == self.children.len()),
754            "focusNodes.length must match children.length.\nThere are {} focus nodes, while \
755             there are {} children.",
756            self.focus_nodes.as_ref().map_or(0, Vec::len),
757            self.children.len()
758        );
759        let theme = Theme::of(app, context);
760        let toggle_buttons_theme = ToggleButtonsTheme::of(app, context);
761        let text_direction = Directionality::of(app, context);
762        let length = self.children.len();
763
764        let buttons: Vec<WidgetRef> = (0..length)
765            .map(|index| {
766                let edge_border_radius = self.get_edge_border_radius(
767                    index,
768                    length,
769                    text_direction,
770                    &toggle_buttons_theme,
771                );
772                let clip_border_radius = self.get_clip_border_radius(
773                    index,
774                    length,
775                    text_direction,
776                    &toggle_buttons_theme,
777                );
778
779                let leading_border_side =
780                    self.get_leading_border_side(index, &theme, &toggle_buttons_theme);
781                let border_side = self.get_border_side(index, &theme, &toggle_buttons_theme);
782                let trailing_border_side =
783                    self.get_trailing_border_side(index, &theme, &toggle_buttons_theme);
784
785                let mut states = WidgetStates::new();
786                if self.is_selected[index] && self.on_pressed.is_some() {
787                    states.insert(WidgetState::Selected);
788                }
789                if self.on_pressed.is_none() {
790                    states.insert(WidgetState::Disabled);
791                }
792                let effective_fill_color = ResolveFillColor::new(
793                    self.fill_color
794                        .clone()
795                        .or_else(|| toggle_buttons_theme.fill_color.clone()),
796                )
797                .resolve(&states)
798                .unwrap_or_else(|| DefaultFillColor::new(&theme.color_scheme).resolve(&states));
799                let current_color = if self.on_pressed.is_some() && self.is_selected[index] {
800                    self.selected_color
801                        .or(toggle_buttons_theme.selected_color)
802                        .unwrap_or(theme.color_scheme.primary())
803                } else if self.on_pressed.is_some() && !self.is_selected[index] {
804                    self.color
805                        .or(toggle_buttons_theme.color)
806                        .unwrap_or_else(|| theme.color_scheme.on_surface().with_opacity(0.87))
807                } else {
808                    self.disabled_color
809                        .or(toggle_buttons_theme.disabled_color)
810                        .unwrap_or_else(|| theme.color_scheme.on_surface().with_opacity(0.38))
811                };
812                let current_text_style = self
813                    .text_style
814                    .clone()
815                    .or_else(|| toggle_buttons_theme.text_style.clone())
816                    .or_else(|| theme.text_theme.body_medium.clone())
817                    .expect("the text theme has a bodyMedium");
818                let current_constraints = self.constraints.or(toggle_buttons_theme.constraints);
819                let minimum_size = current_constraints
820                    .map(|constraints| constraints.smallest())
821                    .unwrap_or(Size::new(
822                        K_MIN_INTERACTIVE_DIMENSION,
823                        K_MIN_INTERACTIVE_DIMENSION,
824                    ));
825                let maximum_size = current_constraints.map(|constraints| constraints.biggest());
826                let min_padding_size = match self
827                    .tap_target_size
828                    .unwrap_or(theme.material_tap_target_size)
829                {
830                    MaterialTapTargetSize::Padded => {
831                        let min_padding_size = match self.direction {
832                            Axis::Horizontal => Size::new(0.0, K_MIN_INTERACTIVE_DIMENSION),
833                            Axis::Vertical => Size::new(K_MIN_INTERACTIVE_DIMENSION, 0.0),
834                        };
835                        debug_assert!(min_padding_size.width() >= 0.0);
836                        debug_assert!(min_padding_size.height() >= 0.0);
837                        min_padding_size
838                    }
839                    MaterialTapTargetSize::ShrinkWrap => Size::ZERO,
840                };
841
842                let on_pressed = self.on_pressed.clone().map(|on_pressed| {
843                    Listener::new(move |app| {
844                        on_pressed(app, index);
845                    })
846                });
847                let mut text_button =
848                    TextButton::new(on_pressed, Some(self.children[index].clone())).style(
849                        ButtonStyle::new()
850                            .background_color(all(effective_fill_color))
851                            .foreground_color(all(current_color))
852                            .icon_size(all(24.0))
853                            .icon_color(all(current_color))
854                            .overlay_color(Rc::new(ToggleButtonDefaultOverlay {
855                                selected: self.on_pressed.is_some() && self.is_selected[index],
856                                unselected: self.on_pressed.is_some() && !self.is_selected[index],
857                                color_scheme: Some(theme.color_scheme.clone()),
858                                disabled_color: self
859                                    .disabled_color
860                                    .or(toggle_buttons_theme.disabled_color),
861                                focus_color: self.focus_color.or(toggle_buttons_theme.focus_color),
862                                highlight_color: self
863                                    .highlight_color
864                                    .or(toggle_buttons_theme.highlight_color),
865                                hover_color: self.hover_color.or(toggle_buttons_theme.hover_color),
866                                splash_color: self
867                                    .splash_color
868                                    .or(toggle_buttons_theme.splash_color),
869                            }))
870                            .elevation(all(0.0))
871                            .text_style(all(current_text_style.copy_with().color(current_color)))
872                            .padding(all(EdgeInsetsGeometry::ZERO))
873                            .minimum_size(all(minimum_size))
874                            .maximum_size(Rc::new(WidgetStatePropertyAll::new(maximum_size)))
875                            .shape(all(OutlinedBorderRef::new(
876                                RoundedRectangleBorder::default(),
877                            )))
878                            .mouse_cursor(Rc::new(WidgetStatePropertyAll::new(
879                                self.mouse_cursor.clone(),
880                            )))
881                            .visual_density(VisualDensity::STANDARD)
882                            .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
883                            .animation_duration(K_THEME_CHANGE_DURATION)
884                            .enable_feedback(true)
885                            .alignment(waft_painting::AlignmentGeometry::CENTER)
886                            .splash_factory(InkRipple::splash_factory()),
887                    );
888                if let Some(focus_nodes) = &self.focus_nodes {
889                    text_button = text_button.focus_node(focus_nodes[index].clone());
890                }
891
892                let mut button = SelectToggleButton {
893                    child: ClipRRect::new()
894                        .border_radius(clip_border_radius.into())
895                        .child(text_button)
896                        .into_widget(),
897                    leading_border_side,
898                    border_side,
899                    trailing_border_side,
900                    border_radius: edge_border_radius,
901                    is_first_button: index == 0,
902                    is_last_button: index == length - 1,
903                    direction: self.direction,
904                    vertical_direction: self.vertical_direction,
905                }
906                .into_widget();
907
908                if current_constraints.is_some() {
909                    button = Center::new().child(button).into_widget();
910                }
911
912                MergeSemantics::new()
913                    .child(
914                        Semantics::new()
915                            .container(true)
916                            .checked(self.is_selected[index])
917                            .enabled(self.on_pressed.is_some())
918                            .child(InputPadding {
919                                child: Some(button),
920                                min_size: min_padding_size,
921                                direction: self.direction,
922                            }),
923                    )
924                    .into_widget()
925            })
926            .collect();
927
928        if self.direction == Axis::Vertical {
929            return IntrinsicWidth::new()
930                .child(
931                    Column::new()
932                        .main_axis_size(MainAxisSize::Min)
933                        .cross_axis_alignment(CrossAxisAlignment::Stretch)
934                        .vertical_direction(self.vertical_direction)
935                        .children(buttons),
936                )
937                .into_widget();
938        }
939
940        IntrinsicHeight::new()
941            .child(
942                Row::new()
943                    .main_axis_size(MainAxisSize::Min)
944                    .cross_axis_alignment(CrossAxisAlignment::Stretch)
945                    .children(buttons),
946            )
947            .into_widget()
948    }
949}
950
951/// Dart's `MaterialStatePropertyAll<Color?>(value)` and its `<double>` and `<Size?>` kin.
952fn all<T: Clone + Debug + PartialEq + 'static>(value: T) -> WidgetStatePropertyRef<Option<T>> {
953    Rc::new(WidgetStatePropertyAll::new(Some(value)))
954}
955
956/// Dart's `_ResolveFillColor`.
957struct ResolveFillColor {
958    primary: Option<AnyColor>,
959}
960
961impl ResolveFillColor {
962    fn new(primary: Option<AnyColor>) -> ResolveFillColor {
963        ResolveFillColor { primary }
964    }
965
966    fn resolve(&self, states: &WidgetStates) -> Option<Color> {
967        let primary = self.primary.as_ref()?;
968        if primary.extension::<WidgetStateColor>().is_some() {
969            return Some(
970                <dyn WidgetStateProperty<Color>>::resolve_as(&Some(primary.clone()), states)?
971                    .color(),
972            );
973        }
974        if states.contains(&WidgetState::Selected) {
975            Some(primary.color())
976        } else {
977            None
978        }
979    }
980}
981
982/// Dart's `_DefaultFillColor`.
983struct DefaultFillColor<'a> {
984    color_scheme: &'a ColorScheme,
985}
986
987impl<'a> DefaultFillColor<'a> {
988    fn new(color_scheme: &'a ColorScheme) -> DefaultFillColor<'a> {
989        DefaultFillColor { color_scheme }
990    }
991
992    fn resolve(&self, states: &WidgetStates) -> Color {
993        if states.contains(&WidgetState::Selected) {
994            return self.color_scheme.primary().with_opacity(0.12);
995        }
996        self.color_scheme.surface().with_opacity(0.0)
997    }
998}
999
1000/// Dart's `_ToggleButtonDefaultOverlay`.
1001struct ToggleButtonDefaultOverlay {
1002    selected: bool,
1003    unselected: bool,
1004    color_scheme: Option<ColorScheme>,
1005    focus_color: Option<Color>,
1006    highlight_color: Option<Color>,
1007    hover_color: Option<Color>,
1008    splash_color: Option<Color>,
1009    #[expect(dead_code, reason = "Dart's class takes it and never reads it")]
1010    disabled_color: Option<Color>,
1011}
1012
1013impl ToggleButtonDefaultOverlay {
1014    fn primary(&self, opacity: f64) -> Option<Color> {
1015        self.color_scheme
1016            .as_ref()
1017            .map(|color_scheme| color_scheme.primary().with_opacity(opacity))
1018    }
1019
1020    fn on_surface(&self, opacity: f64) -> Option<Color> {
1021        self.color_scheme
1022            .as_ref()
1023            .map(|color_scheme| color_scheme.on_surface().with_opacity(opacity))
1024    }
1025}
1026
1027impl WidgetStateProperty<Option<Color>> for ToggleButtonDefaultOverlay {
1028    fn resolve(&self, states: &WidgetStates) -> Option<Color> {
1029        if self.selected {
1030            if states.contains(&WidgetState::Pressed) {
1031                return self.splash_color.or_else(|| self.primary(0.16));
1032            }
1033            if states.contains(&WidgetState::Hovered) {
1034                return self.hover_color.or_else(|| self.primary(0.04));
1035            }
1036            if states.contains(&WidgetState::Focused) {
1037                return self.focus_color.or_else(|| self.primary(0.12));
1038            }
1039        } else if self.unselected {
1040            if states.contains(&WidgetState::Pressed) {
1041                return self
1042                    .splash_color
1043                    .or(self.highlight_color)
1044                    .or_else(|| self.on_surface(0.16));
1045            }
1046            if states.contains(&WidgetState::Hovered) {
1047                return self.hover_color.or_else(|| self.on_surface(0.04));
1048            }
1049            if states.contains(&WidgetState::Focused) {
1050                return self.focus_color.or_else(|| self.on_surface(0.12));
1051            }
1052        }
1053        None
1054    }
1055
1056    fn as_any(&self) -> &dyn Any {
1057        self
1058    }
1059}
1060
1061impl Debug for ToggleButtonDefaultOverlay {
1062    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1063        write!(
1064            f,
1065            "{{\n  selected:\n    hovered: {:?}, otherwise: {:?},\n    focused: {:?}, otherwise: {:?},\n    pressed: {:?}, otherwise: {:?},\n  unselected:\n    hovered: {:?}, otherwise: {:?},\n    focused: {:?}, otherwise: {:?},\n    pressed: {:?}, otherwise: {:?},\n  otherwise: null,\n}}",
1066            self.hover_color,
1067            self.primary(0.04),
1068            self.focus_color,
1069            self.primary(0.12),
1070            self.splash_color,
1071            self.primary(0.16),
1072            self.hover_color,
1073            self.on_surface(0.04),
1074            self.focus_color,
1075            self.on_surface(0.12),
1076            self.splash_color,
1077            self.on_surface(0.16),
1078        )
1079    }
1080}
1081
1082/// Dart's `_SelectToggleButton`.
1083#[derive(Debug)]
1084struct SelectToggleButton {
1085    /// The width and color of the button's leading side border.
1086    leading_border_side: BorderSide,
1087
1088    /// The width and color of the side borders.
1089    ///
1090    /// If [`direction`](Self::direction) is [`Axis::Horizontal`], this corresponds to the width
1091    /// and color of the button's top and bottom side borders.
1092    ///
1093    /// If [`direction`](Self::direction) is [`Axis::Vertical`], this corresponds to the width
1094    /// and color of the button's left and right side borders.
1095    border_side: BorderSide,
1096
1097    /// The width and color of the button's trailing side border.
1098    trailing_border_side: BorderSide,
1099
1100    /// The border radii of each corner of the button.
1101    border_radius: BorderRadius,
1102
1103    /// Whether or not this toggle button is the first button in the list.
1104    is_first_button: bool,
1105
1106    /// Whether or not this toggle button is the last button in the list.
1107    is_last_button: bool,
1108
1109    /// The direction along which the buttons are rendered.
1110    direction: Axis,
1111
1112    /// If [`direction`](Self::direction) is [`Axis::Vertical`], this property defines whether
1113    /// or not this button in its list of buttons is laid out starting from top to bottom or
1114    /// from bottom to top.
1115    vertical_direction: VerticalDirection,
1116
1117    child: WidgetRef,
1118}
1119
1120impl RenderObjectWidget for SelectToggleButton {
1121    type RenderObject = SelectToggleButtonRenderObject;
1122
1123    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1124        let text_direction = Directionality::of(app, context);
1125        SelectToggleButtonRenderObject::new(
1126            app,
1127            self.leading_border_side,
1128            self.border_side,
1129            self.trailing_border_side,
1130            self.border_radius,
1131            self.is_first_button,
1132            self.is_last_button,
1133            self.direction,
1134            self.vertical_direction,
1135            text_direction,
1136        )
1137        .as_object()
1138    }
1139
1140    fn update_render_object(
1141        &self,
1142        app: &mut App,
1143        context: BuildContext,
1144        render_object: RenderHandle<SelectToggleButtonRenderObject>,
1145    ) {
1146        render_object.set_leading_border_side(app, self.leading_border_side);
1147        render_object.set_border_side(app, self.border_side);
1148        render_object.set_trailing_border_side(app, self.trailing_border_side);
1149        render_object.set_border_radius(app, self.border_radius);
1150        render_object.set_is_first_button(app, self.is_first_button);
1151        render_object.set_is_last_button(app, self.is_last_button);
1152        render_object.set_direction(app, self.direction);
1153        render_object.set_vertical_direction(app, self.vertical_direction);
1154        let text_direction = Directionality::of(app, context);
1155        render_object.set_text_direction(app, text_direction);
1156    }
1157}
1158
1159impl SingleChildRenderObjectWidget for SelectToggleButton {
1160    fn child(&self) -> Option<&WidgetRef> {
1161        Some(&self.child)
1162    }
1163}
1164
1165/// Dart's `_SelectToggleButtonRenderObject`.
1166pub(crate) struct SelectToggleButtonRenderObject {
1167    render_object: RenderObjectData,
1168    render_box: RenderBoxData,
1169    child: RenderObjectWithChildData<AnyRenderBox>,
1170    direction: Axis,
1171    vertical_direction: VerticalDirection,
1172    leading_border_side: BorderSide,
1173    border_side: BorderSide,
1174    trailing_border_side: BorderSide,
1175    border_radius: BorderRadius,
1176    is_first_button: bool,
1177    is_last_button: bool,
1178    text_direction: waft_painting::TextDirection,
1179}
1180
1181/// Dart's `Path.addArc(oval, startAngle, sweepAngle)` on the path being built.
1182///
1183/// A degenerate oval adds nothing.
1184fn add_arc(path: &mut PathBuilder, oval: Rect, start_angle: f64, sweep_angle: f64) {
1185    if oval.width() == 0.0 && oval.height() == 0.0 {
1186        return;
1187    }
1188    let center = oval.center();
1189    path.ellipse(
1190        center,
1191        [(oval.width() / 2.0) as f32, (oval.height() / 2.0) as f32],
1192        0.0,
1193        start_angle as f32,
1194        sweep_angle as f32,
1195    );
1196}
1197
1198impl SelectToggleButtonRenderObject {
1199    #[expect(
1200        clippy::too_many_arguments,
1201        reason = "Dart's constructor takes them positionally"
1202    )]
1203    fn new(
1204        app: &mut App,
1205        leading_border_side: BorderSide,
1206        border_side: BorderSide,
1207        trailing_border_side: BorderSide,
1208        border_radius: BorderRadius,
1209        is_first_button: bool,
1210        is_last_button: bool,
1211        direction: Axis,
1212        vertical_direction: VerticalDirection,
1213        text_direction: waft_painting::TextDirection,
1214    ) -> RenderHandle<SelectToggleButtonRenderObject> {
1215        RenderHandle::new_box(
1216            app,
1217            SelectToggleButtonRenderObject {
1218                render_object: RenderObjectData::new(),
1219                render_box: RenderBoxData::new(),
1220                child: RenderObjectWithChildData::new(),
1221                direction,
1222                vertical_direction,
1223                leading_border_side,
1224                border_side,
1225                trailing_border_side,
1226                border_radius,
1227                is_first_button,
1228                is_last_button,
1229                text_direction,
1230            },
1231        )
1232    }
1233
1234    fn direction(self: RenderHandle<Self>, app: &App) -> Axis {
1235        self.get(app).direction
1236    }
1237
1238    fn set_direction(self: RenderHandle<Self>, app: &mut App, value: Axis) {
1239        if self.direction(app) == value {
1240            return;
1241        }
1242        self.get_mut(app).direction = value;
1243        self.mark_needs_layout(app);
1244    }
1245
1246    fn vertical_direction(self: RenderHandle<Self>, app: &App) -> VerticalDirection {
1247        self.get(app).vertical_direction
1248    }
1249
1250    fn set_vertical_direction(self: RenderHandle<Self>, app: &mut App, value: VerticalDirection) {
1251        if self.vertical_direction(app) == value {
1252            return;
1253        }
1254        self.get_mut(app).vertical_direction = value;
1255        self.mark_needs_layout(app);
1256    }
1257
1258    // The width and color of the button's leading side border.
1259    fn leading_border_side(self: RenderHandle<Self>, app: &App) -> BorderSide {
1260        self.get(app).leading_border_side
1261    }
1262
1263    fn set_leading_border_side(self: RenderHandle<Self>, app: &mut App, value: BorderSide) {
1264        if self.leading_border_side(app) == value {
1265            return;
1266        }
1267        self.get_mut(app).leading_border_side = value;
1268        self.mark_needs_layout(app);
1269    }
1270
1271    // The width and color of the button's top and bottom side borders.
1272    fn border_side(self: RenderHandle<Self>, app: &App) -> BorderSide {
1273        self.get(app).border_side
1274    }
1275
1276    fn set_border_side(self: RenderHandle<Self>, app: &mut App, value: BorderSide) {
1277        if self.border_side(app) == value {
1278            return;
1279        }
1280        self.get_mut(app).border_side = value;
1281        self.mark_needs_layout(app);
1282    }
1283
1284    // The width and color of the button's trailing side border.
1285    fn trailing_border_side(self: RenderHandle<Self>, app: &App) -> BorderSide {
1286        self.get(app).trailing_border_side
1287    }
1288
1289    fn set_trailing_border_side(self: RenderHandle<Self>, app: &mut App, value: BorderSide) {
1290        if self.trailing_border_side(app) == value {
1291            return;
1292        }
1293        self.get_mut(app).trailing_border_side = value;
1294        self.mark_needs_layout(app);
1295    }
1296
1297    // The border radii of each corner of the button.
1298    fn border_radius(self: RenderHandle<Self>, app: &App) -> BorderRadius {
1299        self.get(app).border_radius
1300    }
1301
1302    fn set_border_radius(self: RenderHandle<Self>, app: &mut App, value: BorderRadius) {
1303        if self.border_radius(app) == value {
1304            return;
1305        }
1306        self.get_mut(app).border_radius = value;
1307        self.mark_needs_layout(app);
1308    }
1309
1310    // Whether or not this toggle button is the first button in the list.
1311    fn is_first_button(self: RenderHandle<Self>, app: &App) -> bool {
1312        self.get(app).is_first_button
1313    }
1314
1315    fn set_is_first_button(self: RenderHandle<Self>, app: &mut App, value: bool) {
1316        if self.is_first_button(app) == value {
1317            return;
1318        }
1319        self.get_mut(app).is_first_button = value;
1320        self.mark_needs_layout(app);
1321    }
1322
1323    // Whether or not this toggle button is the last button in the list.
1324    fn is_last_button(self: RenderHandle<Self>, app: &App) -> bool {
1325        self.get(app).is_last_button
1326    }
1327
1328    fn set_is_last_button(self: RenderHandle<Self>, app: &mut App, value: bool) {
1329        if self.is_last_button(app) == value {
1330            return;
1331        }
1332        self.get_mut(app).is_last_button = value;
1333        self.mark_needs_layout(app);
1334    }
1335
1336    // The direction in which text flows for this application.
1337    fn text_direction(self: RenderHandle<Self>, app: &App) -> waft_painting::TextDirection {
1338        self.get(app).text_direction
1339    }
1340
1341    fn set_text_direction(
1342        self: RenderHandle<Self>,
1343        app: &mut App,
1344        value: waft_painting::TextDirection,
1345    ) {
1346        if self.text_direction(app) == value {
1347            return;
1348        }
1349        self.get_mut(app).text_direction = value;
1350        self.mark_needs_layout(app);
1351    }
1352
1353    fn max_height(app: &mut App, child: Option<AnyRenderBox>, width: f64) -> f64 {
1354        child.map_or(0.0, |child| child.get_max_intrinsic_height(app, width))
1355    }
1356
1357    fn min_height(app: &mut App, child: Option<AnyRenderBox>, width: f64) -> f64 {
1358        child.map_or(0.0, |child| child.get_min_intrinsic_height(app, width))
1359    }
1360
1361    fn min_width(app: &mut App, child: Option<AnyRenderBox>, height: f64) -> f64 {
1362        child.map_or(0.0, |child| child.get_min_intrinsic_width(app, height))
1363    }
1364
1365    fn max_width(app: &mut App, child: Option<AnyRenderBox>, height: f64) -> f64 {
1366        child.map_or(0.0, |child| child.get_max_intrinsic_width(app, height))
1367    }
1368
1369    fn child_padding(self: RenderHandle<Self>, app: &App) -> EdgeInsetsDirectional {
1370        debug_assert!(self.child(app).is_some());
1371        let (leading, border, trailing) = (
1372            self.leading_border_side(app),
1373            self.border_side(app),
1374            self.trailing_border_side(app),
1375        );
1376        // It does not matter what [textDirection] or [verticalDirection] is,
1377        // since deflating the size constraints horizontally/vertically
1378        // and the returned size accounts for the width of both sides.
1379        match self.direction(app) {
1380            Axis::Horizontal => EdgeInsetsDirectional::only(
1381                leading.width,
1382                border.width,
1383                trailing.width,
1384                border.width,
1385            ),
1386            Axis::Vertical => EdgeInsetsDirectional::only(
1387                border.width,
1388                leading.width,
1389                border.width,
1390                trailing.width,
1391            ),
1392        }
1393    }
1394
1395    fn compute_size(
1396        self: RenderHandle<Self>,
1397        app: &mut App,
1398        constraints: BoxConstraints,
1399        layout_child: ChildLayouter,
1400    ) -> Size {
1401        let Some(child) = self.child(app) else {
1402            let horizontal_size = Size::new(
1403                self.leading_border_side(app).width + self.trailing_border_side(app).width,
1404                self.border_side(app).width * 2.0,
1405            );
1406            return match self.direction(app) {
1407                Axis::Horizontal => constraints.constrain(horizontal_size),
1408                Axis::Vertical => constraints.constrain(horizontal_size.flipped()),
1409            };
1410        };
1411
1412        let child_padding = EdgeInsetsGeometry::from(self.child_padding(app));
1413        let inner_constraints = constraints.deflate(child_padding);
1414        let child_size = layout_child(app, child, inner_constraints);
1415        constraints.constrain(child_padding.inflate_size(child_size))
1416    }
1417}
1418
1419impl RenderObjectWithChildMixin for SelectToggleButtonRenderObject {
1420    type ChildType = AnyRenderBox;
1421
1422    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1423        &self.get(app).child
1424    }
1425
1426    fn child_data_mut(
1427        self: RenderHandle<Self>,
1428        app: &mut App,
1429    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1430        &mut self.get_mut(app).child
1431    }
1432}
1433
1434impl RenderShiftedBox for SelectToggleButtonRenderObject {}
1435
1436impl RenderObject for SelectToggleButtonRenderObject {
1437    waft_rendering::render_object_accessors!();
1438
1439    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1440        let constraints = self.constraints(app);
1441        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
1442        self.set_size(app, size);
1443        let Some(child) = self.child(app) else {
1444            return;
1445        };
1446        let (leading, border, trailing) = (
1447            self.leading_border_side(app),
1448            self.border_side(app),
1449            self.trailing_border_side(app),
1450        );
1451        let offset = if self.direction(app) == Axis::Horizontal {
1452            match self.text_direction(app) {
1453                waft_painting::TextDirection::Ltr => Offset::new(leading.width, border.width),
1454                waft_painting::TextDirection::Rtl => Offset::new(trailing.width, border.width),
1455            }
1456        } else {
1457            match self.vertical_direction(app) {
1458                VerticalDirection::Down => Offset::new(border.width, leading.width),
1459                VerticalDirection::Up => Offset::new(border.width, trailing.width),
1460            }
1461        };
1462        child.parent_data_of_mut::<BoxParentData>(app).offset = offset;
1463    }
1464
1465    fn paint(
1466        self: RenderHandle<Self>,
1467        app: &mut App,
1468        context: &mut PaintingContext,
1469        offset: Offset,
1470    ) {
1471        RenderShiftedBox::paint(self, app, context, offset);
1472        let size = self.size(app);
1473        let (leading_border_side, border_side, trailing_border_side) = (
1474            self.leading_border_side(app),
1475            self.border_side(app),
1476            self.trailing_border_side(app),
1477        );
1478        let (border_radius, is_first_button, is_last_button) = (
1479            self.border_radius(app),
1480            self.is_first_button(app),
1481            self.is_last_button(app),
1482        );
1483        let (direction, vertical_direction, text_direction) = (
1484            self.direction(app),
1485            self.vertical_direction(app),
1486            self.text_direction(app),
1487        );
1488        let bottom_right = size.bottom_right(offset);
1489        let outer = Rect::from_ltrb(
1490            offset.dx(),
1491            offset.dy(),
1492            bottom_right.dx(),
1493            bottom_right.dy(),
1494        );
1495        let center = outer.deflate(border_side.width / 2.0);
1496        const SWEEP_ANGLE: f64 = PI / 2.0;
1497        let corner = |radius: Radius| {
1498            if radius.x * radius.y != 0.0 {
1499                radius
1500            } else {
1501                Radius::ZERO
1502            }
1503        };
1504        let rrect = RRect::from_rect_and_corners(
1505            center,
1506            corner(border_radius.top_left),
1507            corner(border_radius.top_right),
1508            corner(border_radius.bottom_right),
1509            corner(border_radius.bottom_left),
1510        )
1511        .scale_radii();
1512
1513        let tl_corner = Rect::from_ltwh(
1514            rrect.left,
1515            rrect.top,
1516            rrect.tl_radius_x * 2.0,
1517            rrect.tl_radius_y * 2.0,
1518        );
1519        let bl_corner = Rect::from_ltwh(
1520            rrect.left,
1521            rrect.bottom - (rrect.bl_radius_y * 2.0),
1522            rrect.bl_radius_x * 2.0,
1523            rrect.bl_radius_y * 2.0,
1524        );
1525        let tr_corner = Rect::from_ltwh(
1526            rrect.right - (rrect.tr_radius_x * 2.0),
1527            rrect.top,
1528            rrect.tr_radius_x * 2.0,
1529            rrect.tr_radius_y * 2.0,
1530        );
1531        let br_corner = Rect::from_ltwh(
1532            rrect.right - (rrect.br_radius_x * 2.0),
1533            rrect.bottom - (rrect.br_radius_y * 2.0),
1534            rrect.br_radius_x * 2.0,
1535            rrect.br_radius_y * 2.0,
1536        );
1537
1538        let leading_paint = leading_border_side.to_paint();
1539        let draw =
1540            |context: &mut PaintingContext, path: PathBuilder, paint: &waft_embedder::Paint| {
1541                context
1542                    .canvas()
1543                    .draw_path(&path.build(), FillRule::NonZero, paint);
1544            };
1545        // Only one button.
1546        if is_first_button && is_last_button {
1547            let mut leading_path = PathBuilder::new();
1548            let start_x = if rrect.br_radius_x == 0.0 {
1549                outer.right
1550            } else {
1551                rrect.right - rrect.br_radius_x
1552            };
1553            leading_path
1554                .move_to(Offset::new(start_x, rrect.bottom))
1555                .line_to(Offset::new(rrect.left + rrect.bl_radius_x, rrect.bottom));
1556            add_arc(&mut leading_path, bl_corner, PI / 2.0, SWEEP_ANGLE);
1557            leading_path.line_to(Offset::new(rrect.left, rrect.top + rrect.tl_radius_y));
1558            add_arc(&mut leading_path, tl_corner, PI, SWEEP_ANGLE);
1559            leading_path.line_to(Offset::new(rrect.right - rrect.tr_radius_x, rrect.top));
1560            add_arc(&mut leading_path, tr_corner, PI * 3.0 / 2.0, SWEEP_ANGLE);
1561            leading_path.line_to(Offset::new(rrect.right, rrect.bottom - rrect.br_radius_y));
1562            add_arc(&mut leading_path, br_corner, 0.0, SWEEP_ANGLE);
1563            draw(context, leading_path, &leading_paint);
1564            return;
1565        }
1566
1567        if direction == Axis::Horizontal {
1568            match text_direction {
1569                waft_painting::TextDirection::Ltr => {
1570                    if is_last_button {
1571                        let mut left_path = PathBuilder::new();
1572                        left_path
1573                            .move_to(Offset::new(
1574                                rrect.left,
1575                                rrect.bottom + leading_border_side.width / 2.0,
1576                            ))
1577                            .line_to(Offset::new(
1578                                rrect.left,
1579                                rrect.top - leading_border_side.width / 2.0,
1580                            ));
1581                        draw(context, left_path, &leading_paint);
1582
1583                        let ending_paint = trailing_border_side.to_paint();
1584                        let mut ending_path = PathBuilder::new();
1585                        ending_path
1586                            .move_to(Offset::new(rrect.left + border_side.width / 2.0, rrect.top))
1587                            .line_to(Offset::new(rrect.right - rrect.tr_radius_x, rrect.top));
1588                        add_arc(&mut ending_path, tr_corner, PI * 3.0 / 2.0, SWEEP_ANGLE);
1589                        ending_path
1590                            .line_to(Offset::new(rrect.right, rrect.bottom - rrect.br_radius_y));
1591                        add_arc(&mut ending_path, br_corner, 0.0, SWEEP_ANGLE);
1592                        ending_path.line_to(Offset::new(
1593                            rrect.left + border_side.width / 2.0,
1594                            rrect.bottom,
1595                        ));
1596                        draw(context, ending_path, &ending_paint);
1597                    } else if is_first_button {
1598                        let mut leading_path = PathBuilder::new();
1599                        leading_path
1600                            .move_to(Offset::new(outer.right, rrect.bottom))
1601                            .line_to(Offset::new(rrect.left + rrect.bl_radius_x, rrect.bottom));
1602                        add_arc(&mut leading_path, bl_corner, PI / 2.0, SWEEP_ANGLE);
1603                        leading_path
1604                            .line_to(Offset::new(rrect.left, rrect.top + rrect.tl_radius_y));
1605                        add_arc(&mut leading_path, tl_corner, PI, SWEEP_ANGLE);
1606                        leading_path.line_to(Offset::new(outer.right, rrect.top));
1607                        draw(context, leading_path, &leading_paint);
1608                    } else {
1609                        let mut leading_path = PathBuilder::new();
1610                        leading_path
1611                            .move_to(Offset::new(
1612                                rrect.left,
1613                                rrect.bottom + leading_border_side.width / 2.0,
1614                            ))
1615                            .line_to(Offset::new(
1616                                rrect.left,
1617                                rrect.top - leading_border_side.width / 2.0,
1618                            ));
1619                        draw(context, leading_path, &leading_paint);
1620
1621                        let horizontal_paint = border_side.to_paint();
1622                        let mut horizontal_paths = PathBuilder::new();
1623                        horizontal_paths
1624                            .move_to(Offset::new(rrect.left + border_side.width / 2.0, rrect.top))
1625                            .line_to(Offset::new(outer.right - rrect.tr_radius_x, rrect.top))
1626                            .move_to(Offset::new(
1627                                rrect.left + border_side.width / 2.0 + rrect.tl_radius_x,
1628                                rrect.bottom,
1629                            ))
1630                            .line_to(Offset::new(outer.right - rrect.tr_radius_x, rrect.bottom));
1631                        draw(context, horizontal_paths, &horizontal_paint);
1632                    }
1633                }
1634                waft_painting::TextDirection::Rtl => {
1635                    if is_last_button {
1636                        let mut leading_path = PathBuilder::new();
1637                        leading_path
1638                            .move_to(Offset::new(
1639                                rrect.right,
1640                                rrect.bottom + leading_border_side.width / 2.0,
1641                            ))
1642                            .line_to(Offset::new(
1643                                rrect.right,
1644                                rrect.top - leading_border_side.width / 2.0,
1645                            ));
1646                        draw(context, leading_path, &leading_paint);
1647
1648                        let ending_paint = trailing_border_side.to_paint();
1649                        let mut ending_path = PathBuilder::new();
1650                        ending_path
1651                            .move_to(Offset::new(
1652                                rrect.right - border_side.width / 2.0,
1653                                rrect.top,
1654                            ))
1655                            .line_to(Offset::new(rrect.left + rrect.tl_radius_x, rrect.top));
1656                        add_arc(&mut ending_path, tl_corner, PI * 3.0 / 2.0, -SWEEP_ANGLE);
1657                        ending_path
1658                            .line_to(Offset::new(rrect.left, rrect.bottom - rrect.bl_radius_y));
1659                        add_arc(&mut ending_path, bl_corner, PI, -SWEEP_ANGLE);
1660                        ending_path.line_to(Offset::new(
1661                            rrect.right - border_side.width / 2.0,
1662                            rrect.bottom,
1663                        ));
1664                        draw(context, ending_path, &ending_paint);
1665                    } else if is_first_button {
1666                        let mut leading_path = PathBuilder::new();
1667                        leading_path
1668                            .move_to(Offset::new(outer.left, rrect.bottom))
1669                            .line_to(Offset::new(rrect.right - rrect.br_radius_x, rrect.bottom));
1670                        add_arc(&mut leading_path, br_corner, PI / 2.0, -SWEEP_ANGLE);
1671                        leading_path
1672                            .line_to(Offset::new(rrect.right, rrect.top + rrect.tr_radius_y));
1673                        add_arc(&mut leading_path, tr_corner, 0.0, -SWEEP_ANGLE);
1674                        leading_path.line_to(Offset::new(outer.left, rrect.top));
1675                        draw(context, leading_path, &leading_paint);
1676                    } else {
1677                        let mut leading_path = PathBuilder::new();
1678                        leading_path
1679                            .move_to(Offset::new(
1680                                rrect.right,
1681                                rrect.bottom + leading_border_side.width / 2.0,
1682                            ))
1683                            .line_to(Offset::new(
1684                                rrect.right,
1685                                rrect.top - leading_border_side.width / 2.0,
1686                            ));
1687                        draw(context, leading_path, &leading_paint);
1688
1689                        let horizontal_paint = border_side.to_paint();
1690                        let mut horizontal_paths = PathBuilder::new();
1691                        horizontal_paths
1692                            .move_to(Offset::new(
1693                                rrect.right - border_side.width / 2.0,
1694                                rrect.top,
1695                            ))
1696                            .line_to(Offset::new(outer.left - rrect.tl_radius_x, rrect.top))
1697                            .move_to(Offset::new(
1698                                rrect.right - border_side.width / 2.0 + rrect.tr_radius_x,
1699                                rrect.bottom,
1700                            ))
1701                            .line_to(Offset::new(outer.left - rrect.tl_radius_x, rrect.bottom));
1702                        draw(context, horizontal_paths, &horizontal_paint);
1703                    }
1704                }
1705            }
1706        } else {
1707            match vertical_direction {
1708                VerticalDirection::Down => {
1709                    if is_last_button {
1710                        let mut top_path = PathBuilder::new();
1711                        top_path
1712                            .move_to(Offset::new(
1713                                outer.left,
1714                                outer.top + leading_border_side.width / 2.0,
1715                            ))
1716                            .line_to(Offset::new(
1717                                outer.right,
1718                                outer.top + leading_border_side.width / 2.0,
1719                            ));
1720                        draw(context, top_path, &leading_paint);
1721
1722                        let ending_paint = trailing_border_side.to_paint();
1723                        let mut ending_path = PathBuilder::new();
1724                        ending_path
1725                            .move_to(Offset::new(
1726                                rrect.left,
1727                                rrect.top + leading_border_side.width / 2.0,
1728                            ))
1729                            .line_to(Offset::new(rrect.left, rrect.bottom - rrect.bl_radius_y));
1730                        add_arc(&mut ending_path, bl_corner, PI * 3.0, -SWEEP_ANGLE);
1731                        ending_path
1732                            .line_to(Offset::new(rrect.right - rrect.bl_radius_x, rrect.bottom));
1733                        add_arc(&mut ending_path, br_corner, PI / 2.0, -SWEEP_ANGLE);
1734                        ending_path.line_to(Offset::new(
1735                            rrect.right,
1736                            rrect.top + leading_border_side.width / 2.0,
1737                        ));
1738                        draw(context, ending_path, &ending_paint);
1739                    } else if is_first_button {
1740                        let mut leading_path = PathBuilder::new();
1741                        leading_path
1742                            .move_to(Offset::new(rrect.left, outer.bottom))
1743                            .line_to(Offset::new(rrect.left, rrect.top + rrect.tl_radius_x));
1744                        add_arc(&mut leading_path, tl_corner, PI, SWEEP_ANGLE);
1745                        leading_path
1746                            .line_to(Offset::new(rrect.right - rrect.tr_radius_x, rrect.top));
1747                        add_arc(&mut leading_path, tr_corner, PI * 3.0 / 2.0, SWEEP_ANGLE);
1748                        leading_path.line_to(Offset::new(rrect.right, outer.bottom));
1749                        draw(context, leading_path, &leading_paint);
1750                    } else {
1751                        let mut top_path = PathBuilder::new();
1752                        top_path
1753                            .move_to(Offset::new(
1754                                outer.left,
1755                                outer.top + leading_border_side.width / 2.0,
1756                            ))
1757                            .line_to(Offset::new(
1758                                outer.right,
1759                                outer.top + leading_border_side.width / 2.0,
1760                            ));
1761                        draw(context, top_path, &leading_paint);
1762
1763                        let paint = border_side.to_paint();
1764                        let mut paths = PathBuilder::new(); // Left and right borders.
1765                        paths
1766                            .move_to(Offset::new(
1767                                rrect.left,
1768                                outer.top + leading_border_side.width,
1769                            ))
1770                            .line_to(Offset::new(rrect.left, outer.bottom))
1771                            .move_to(Offset::new(
1772                                rrect.right,
1773                                outer.top + leading_border_side.width,
1774                            ))
1775                            .line_to(Offset::new(rrect.right, outer.bottom));
1776                        draw(context, paths, &paint);
1777                    }
1778                }
1779                VerticalDirection::Up => {
1780                    if is_last_button {
1781                        let mut bottom_path = PathBuilder::new();
1782                        bottom_path
1783                            .move_to(Offset::new(
1784                                outer.left,
1785                                outer.bottom - leading_border_side.width / 2.0,
1786                            ))
1787                            .line_to(Offset::new(
1788                                outer.right,
1789                                outer.bottom - leading_border_side.width / 2.0,
1790                            ));
1791                        draw(context, bottom_path, &leading_paint);
1792
1793                        let ending_paint = trailing_border_side.to_paint();
1794                        let mut ending_path = PathBuilder::new();
1795                        ending_path
1796                            .move_to(Offset::new(
1797                                rrect.left,
1798                                rrect.bottom - leading_border_side.width / 2.0,
1799                            ))
1800                            .line_to(Offset::new(rrect.left, rrect.top + rrect.tl_radius_y));
1801                        add_arc(&mut ending_path, tl_corner, PI, SWEEP_ANGLE);
1802                        ending_path
1803                            .line_to(Offset::new(rrect.right - rrect.tr_radius_x, rrect.top));
1804                        add_arc(&mut ending_path, tr_corner, PI * 3.0 / 2.0, SWEEP_ANGLE);
1805                        ending_path.line_to(Offset::new(
1806                            rrect.right,
1807                            rrect.bottom - leading_border_side.width / 2.0,
1808                        ));
1809                        draw(context, ending_path, &ending_paint);
1810                    } else if is_first_button {
1811                        let mut leading_path = PathBuilder::new();
1812                        leading_path
1813                            .move_to(Offset::new(rrect.left, outer.top))
1814                            .line_to(Offset::new(rrect.left, rrect.bottom - rrect.bl_radius_y));
1815                        add_arc(&mut leading_path, bl_corner, PI, -SWEEP_ANGLE);
1816                        leading_path
1817                            .line_to(Offset::new(rrect.right - rrect.br_radius_x, rrect.bottom));
1818                        add_arc(&mut leading_path, br_corner, PI / 2.0, -SWEEP_ANGLE);
1819                        leading_path.line_to(Offset::new(rrect.right, outer.top));
1820                        draw(context, leading_path, &leading_paint);
1821                    } else {
1822                        let mut bottom_path = PathBuilder::new();
1823                        bottom_path
1824                            .move_to(Offset::new(
1825                                outer.left,
1826                                outer.bottom - leading_border_side.width / 2.0,
1827                            ))
1828                            .line_to(Offset::new(
1829                                outer.right,
1830                                outer.bottom - leading_border_side.width / 2.0,
1831                            ));
1832                        draw(context, bottom_path, &leading_paint);
1833
1834                        let paint = border_side.to_paint();
1835                        let mut paths = PathBuilder::new(); // Left and right borders.
1836                        paths
1837                            .move_to(Offset::new(rrect.left, outer.top))
1838                            .line_to(Offset::new(
1839                                rrect.left,
1840                                outer.bottom - leading_border_side.width,
1841                            ))
1842                            .move_to(Offset::new(rrect.right, outer.top))
1843                            .line_to(Offset::new(
1844                                rrect.right,
1845                                outer.bottom - leading_border_side.width,
1846                            ));
1847                        draw(context, paths, &paint);
1848                    }
1849                }
1850            }
1851        }
1852    }
1853
1854    fn visit_children(
1855        self: RenderHandle<Self>,
1856        app: &App,
1857        visitor: &mut dyn FnMut(AnyRenderObject),
1858    ) {
1859        if let Some(child) = self.child(app) {
1860            visitor(child.as_object());
1861        }
1862    }
1863}
1864
1865impl RenderBox for SelectToggleButtonRenderObject {
1866    waft_rendering::render_box_accessors!();
1867
1868    fn hit_test_children(
1869        self: RenderHandle<Self>,
1870        app: &mut App,
1871        result: &mut BoxHitTestResult<'_>,
1872        position: Offset,
1873    ) -> bool {
1874        RenderShiftedBox::hit_test_children(self, app, result, position)
1875    }
1876
1877    fn compute_distance_to_actual_baseline(
1878        self: RenderHandle<Self>,
1879        app: &mut App,
1880        baseline: TextBaseline,
1881    ) -> Option<f64> {
1882        // The baseline of this widget is the baseline of its child
1883        let child_offset = BaselineOffset(
1884            self.child(app)
1885                .and_then(|child| child.get_distance_to_actual_baseline(app, baseline)),
1886        );
1887        match self.direction(app) {
1888            Axis::Horizontal => child_offset + self.border_side(app).width,
1889            Axis::Vertical => {
1890                child_offset
1891                    + match self.vertical_direction(app) {
1892                        VerticalDirection::Down => self.leading_border_side(app).width,
1893                        VerticalDirection::Up => self.trailing_border_side(app).width,
1894                    }
1895            }
1896        }
1897        .offset()
1898    }
1899
1900    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1901        let child = self.child(app);
1902        let child_height = Self::max_height(app, child, width);
1903        let (leading, border, trailing) = (
1904            self.leading_border_side(app),
1905            self.border_side(app),
1906            self.trailing_border_side(app),
1907        );
1908        if self.direction(app) == Axis::Horizontal {
1909            border.width * 2.0 + child_height
1910        } else {
1911            leading.width + child_height + trailing.width
1912        }
1913    }
1914
1915    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1916        let child = self.child(app);
1917        let (leading, border, trailing) = (
1918            self.leading_border_side(app),
1919            self.border_side(app),
1920            self.trailing_border_side(app),
1921        );
1922        if self.direction(app) == Axis::Horizontal {
1923            border.width * 2.0 + Self::min_height(app, child, width)
1924        } else {
1925            leading.width + Self::max_height(app, child, width) + trailing.width
1926        }
1927    }
1928
1929    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1930        let child = self.child(app);
1931        let (leading, border, trailing) = (
1932            self.leading_border_side(app),
1933            self.border_side(app),
1934            self.trailing_border_side(app),
1935        );
1936        if self.direction(app) == Axis::Horizontal {
1937            leading.width + Self::max_width(app, child, height) + trailing.width
1938        } else {
1939            border.width * 2.0 + Self::max_width(app, child, height)
1940        }
1941    }
1942
1943    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1944        let child = self.child(app);
1945        let (leading, border, trailing) = (
1946            self.leading_border_side(app),
1947            self.border_side(app),
1948            self.trailing_border_side(app),
1949        );
1950        if self.direction(app) == Axis::Horizontal {
1951            leading.width + Self::min_width(app, child, height) + trailing.width
1952        } else {
1953            border.width * 2.0 + Self::min_width(app, child, height)
1954        }
1955    }
1956
1957    fn compute_dry_layout(
1958        self: RenderHandle<Self>,
1959        app: &mut App,
1960        constraints: BoxConstraints,
1961    ) -> Size {
1962        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
1963    }
1964
1965    fn compute_dry_baseline(
1966        self: RenderHandle<Self>,
1967        app: &mut App,
1968        constraints: BoxConstraints,
1969        baseline: TextBaseline,
1970    ) -> Option<f64> {
1971        let child = self.child(app)?;
1972        let child_padding = EdgeInsetsGeometry::from(self.child_padding(app));
1973        let child_baseline =
1974            child.get_dry_baseline(app, constraints.deflate(child_padding), baseline)?;
1975        Some(
1976            child_baseline
1977                + match self.direction(app) {
1978                    Axis::Horizontal => self.border_side(app).width,
1979                    Axis::Vertical => match self.vertical_direction(app) {
1980                        VerticalDirection::Down => self.leading_border_side(app).width,
1981                        VerticalDirection::Up => self.trailing_border_side(app).width,
1982                    },
1983                },
1984        )
1985    }
1986}
1987
1988/// A widget to pad the area around a [`ToggleButtons`]'s inner `TextButton`.
1989///
1990/// Redirect taps that occur in the padded area around the child to the center
1991/// of the child. This increases the size of the button and the button's
1992/// "tap target", but not its material or its ink splashes.
1993///
1994/// Dart's `_InputPadding`.
1995#[derive(Debug)]
1996struct InputPadding {
1997    child: Option<WidgetRef>,
1998    min_size: Size,
1999    direction: Axis,
2000}
2001
2002impl RenderObjectWidget for InputPadding {
2003    type RenderObject = RenderInputPadding;
2004
2005    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
2006        RenderInputPadding::new(app, self.min_size, self.direction).as_object()
2007    }
2008
2009    fn update_render_object(
2010        &self,
2011        app: &mut App,
2012        _context: BuildContext,
2013        render_object: RenderHandle<RenderInputPadding>,
2014    ) {
2015        render_object.set_min_size(app, self.min_size);
2016        render_object.set_direction(app, self.direction);
2017    }
2018}
2019
2020impl SingleChildRenderObjectWidget for InputPadding {
2021    fn child(&self) -> Option<&WidgetRef> {
2022        self.child.as_ref()
2023    }
2024}
2025
2026/// Dart's `_RenderInputPadding`.
2027struct RenderInputPadding {
2028    render_object: RenderObjectData,
2029    render_box: RenderBoxData,
2030    child: RenderObjectWithChildData<AnyRenderBox>,
2031    min_size: Size,
2032    direction: Axis,
2033}
2034
2035impl RenderInputPadding {
2036    fn new(app: &mut App, min_size: Size, direction: Axis) -> RenderHandle<RenderInputPadding> {
2037        RenderHandle::new_box(
2038            app,
2039            RenderInputPadding {
2040                render_object: RenderObjectData::new(),
2041                render_box: RenderBoxData::new(),
2042                child: RenderObjectWithChildData::new(),
2043                min_size,
2044                direction,
2045            },
2046        )
2047    }
2048
2049    fn min_size(self: RenderHandle<Self>, app: &App) -> Size {
2050        self.get(app).min_size
2051    }
2052
2053    fn set_min_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
2054        if self.min_size(app) == value {
2055            return;
2056        }
2057        self.get_mut(app).min_size = value;
2058        self.mark_needs_layout(app);
2059    }
2060
2061    fn direction(self: RenderHandle<Self>, app: &App) -> Axis {
2062        self.get(app).direction
2063    }
2064
2065    fn set_direction(self: RenderHandle<Self>, app: &mut App, value: Axis) {
2066        if self.direction(app) == value {
2067            return;
2068        }
2069        self.get_mut(app).direction = value;
2070        self.mark_needs_layout(app);
2071    }
2072
2073    fn compute_size(
2074        self: RenderHandle<Self>,
2075        app: &mut App,
2076        constraints: BoxConstraints,
2077        layout_child: ChildLayouter,
2078    ) -> Size {
2079        if let Some(child) = self.child(app) {
2080            let min_size = self.min_size(app);
2081            let child_size = layout_child(app, child, constraints);
2082            let width = child_size.width().max(min_size.width());
2083            let height = child_size.height().max(min_size.height());
2084            return constraints.constrain(Size::new(width, height));
2085        }
2086        Size::ZERO
2087    }
2088}
2089
2090impl RenderObjectWithChildMixin for RenderInputPadding {
2091    type ChildType = AnyRenderBox;
2092
2093    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2094        &self.get(app).child
2095    }
2096
2097    fn child_data_mut(
2098        self: RenderHandle<Self>,
2099        app: &mut App,
2100    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2101        &mut self.get_mut(app).child
2102    }
2103}
2104
2105impl RenderShiftedBox for RenderInputPadding {}
2106
2107impl RenderObject for RenderInputPadding {
2108    waft_rendering::render_object_accessors!();
2109
2110    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2111        let constraints = self.constraints(app);
2112        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
2113        self.set_size(app, size);
2114        if let Some(child) = self.child(app) {
2115            let child_size = child.size(app);
2116            child.parent_data_of_mut::<BoxParentData>(app).offset =
2117                Alignment::CENTER.along_offset(size - child_size);
2118        }
2119    }
2120
2121    fn paint(
2122        self: RenderHandle<Self>,
2123        app: &mut App,
2124        context: &mut PaintingContext,
2125        offset: Offset,
2126    ) {
2127        RenderShiftedBox::paint(self, app, context, offset);
2128    }
2129
2130    fn visit_children(
2131        self: RenderHandle<Self>,
2132        app: &App,
2133        visitor: &mut dyn FnMut(AnyRenderObject),
2134    ) {
2135        if let Some(child) = self.child(app) {
2136            visitor(child.as_object());
2137        }
2138    }
2139}
2140
2141impl RenderBox for RenderInputPadding {
2142    waft_rendering::render_box_accessors!();
2143
2144    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2145        if let Some(child) = self.child(app) {
2146            return child
2147                .get_min_intrinsic_width(app, height)
2148                .max(self.min_size(app).width());
2149        }
2150        0.0
2151    }
2152
2153    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2154        if let Some(child) = self.child(app) {
2155            return child
2156                .get_min_intrinsic_height(app, width)
2157                .max(self.min_size(app).height());
2158        }
2159        0.0
2160    }
2161
2162    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2163        if let Some(child) = self.child(app) {
2164            return child
2165                .get_max_intrinsic_width(app, height)
2166                .max(self.min_size(app).width());
2167        }
2168        0.0
2169    }
2170
2171    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2172        if let Some(child) = self.child(app) {
2173            return child
2174                .get_max_intrinsic_height(app, width)
2175                .max(self.min_size(app).height());
2176        }
2177        0.0
2178    }
2179
2180    fn compute_dry_layout(
2181        self: RenderHandle<Self>,
2182        app: &mut App,
2183        constraints: BoxConstraints,
2184    ) -> Size {
2185        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
2186    }
2187
2188    fn compute_dry_baseline(
2189        self: RenderHandle<Self>,
2190        app: &mut App,
2191        constraints: BoxConstraints,
2192        baseline: TextBaseline,
2193    ) -> Option<f64> {
2194        let child = self.child(app)?;
2195        let result = child.get_dry_baseline(app, constraints, baseline)?;
2196        // Calculate the size and child offset using the same logic as performLayout
2197        let dry_size = self.get_dry_layout(app, constraints);
2198        let child_size = child.get_dry_layout(app, constraints);
2199        let child_offset = Alignment::CENTER.along_offset(dry_size - child_size);
2200        Some(result + child_offset.dy())
2201    }
2202
2203    fn compute_distance_to_actual_baseline(
2204        self: RenderHandle<Self>,
2205        app: &mut App,
2206        baseline: TextBaseline,
2207    ) -> Option<f64> {
2208        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
2209    }
2210
2211    fn hit_test_children(
2212        self: RenderHandle<Self>,
2213        app: &mut App,
2214        result: &mut BoxHitTestResult<'_>,
2215        position: Offset,
2216    ) -> bool {
2217        RenderShiftedBox::hit_test_children(self, app, result, position)
2218    }
2219
2220    fn hit_test(
2221        self: RenderHandle<Self>,
2222        app: &mut App,
2223        result: &mut BoxHitTestResult<'_>,
2224        position: Offset,
2225    ) -> bool {
2226        // The super.hitTest() method also checks hitTestChildren(). We don't
2227        // want that in this case because we've padded around the children per
2228        // tapTargetSize.
2229        if !self.size(app).contains(position) {
2230            return false;
2231        }
2232
2233        let child = self.child(app).expect("a hit on the padding needs a child");
2234        let child_size = child.size(app);
2235        // Only adjust one axis to ensure the correct button is tapped.
2236        let center = match self.direction(app) {
2237            Axis::Horizontal => Offset::new(position.dx(), child_size.height() / 2.0),
2238            Axis::Vertical => Offset::new(child_size.width() / 2.0, position.dy()),
2239        };
2240        result.add_with_raw_transform(
2241            Some(waft_painting::force_to_point(center)),
2242            center,
2243            |result, position| {
2244                debug_assert!(
2245                    (position.dx() - center.dx()).abs() <= center.dx().abs() * f32::EPSILON as f64
2246                        && (position.dy() - center.dy()).abs()
2247                            <= center.dy().abs() * f32::EPSILON as f64,
2248                    "the forced transform maps every hit to the center"
2249                );
2250                child.hit_test(app, result, center)
2251            },
2252        )
2253    }
2254}
2255
2256#[cfg(test)]
2257pub(crate) mod tests {
2258    //! Ported from `test/toggle_buttons_test.dart`; the goldens and the semantics-tree cases are
2259    //! not ported.
2260
2261    use waft_painting::TextDirection;
2262    use waft_widgets::{Container, DefaultTextStyle, Icon, IconTheme, Text, WidgetStateColor};
2263
2264    use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
2265
2266    use super::*;
2267    use crate::colors::Colors;
2268    use crate::icons::Icons;
2269    use crate::material::{Material, MaterialType};
2270    use crate::test_support::{PaintInspection, path_like};
2271    use crate::theme_data::ThemeData;
2272    use waft_rendering::testing::RecordedCall;
2273    use waft_services::SystemMouseCursors;
2274    use waft_widgets::Directionality as DirectionalityWidget;
2275    use waft_widgets::FocusNodeLeaf;
2276    use waft_widgets::SizedBox;
2277
2278    const DEFAULT_BORDER_WIDTH: f64 = 1.0;
2279
2280    /// Dart's `boilerplate`.
2281    fn boilerplate<K>(theme: ThemeData, child: impl IntoWidget<K>) -> WidgetRef {
2282        let child = child.into_widget();
2283        Theme::new(
2284            theme,
2285            DirectionalityWidget::new(
2286                TextDirection::Ltr,
2287                Center::new().child(Material::new().child(child)),
2288            ),
2289        )
2290        .into_widget()
2291    }
2292
2293    pub(crate) fn default_theme(tester: &WidgetTester) -> ThemeData {
2294        ThemeData::new(&tester.cell.borrow())
2295    }
2296
2297    fn themed(tester: &WidgetTester, tap_target_size: MaterialTapTargetSize) -> ThemeData {
2298        ThemeData::builder()
2299            .material_tap_target_size(tap_target_size)
2300            .build(&tester.cell.borrow())
2301    }
2302
2303    pub(crate) fn texts(values: &[&str]) -> Vec<WidgetRef> {
2304        values
2305            .iter()
2306            .map(|value| Text::new(*value).into_widget())
2307            .collect()
2308    }
2309
2310    pub(crate) fn text_button_of(text: &str) -> waft_widgets::testing::Finder {
2311        find::widget_with_text::<TextButton>(text)
2312    }
2313
2314    /// `tester.widget<DefaultTextStyle>(find.descendant(of: find.widgetWithText(TextButton,
2315    /// text), matching: find.byType(DefaultTextStyle))).style`.
2316    pub(crate) fn button_text_style(tester: &WidgetTester, text: &str) -> TextStyle {
2317        tester.widget(
2318            find::descendant(text_button_of(text), find::by_type::<DefaultTextStyle>()),
2319            |style: &DefaultTextStyle| style.style.clone(),
2320        )
2321    }
2322
2323    pub(crate) fn style_color(style: &TextStyle) -> Option<Color> {
2324        style.color.as_deref().copied()
2325    }
2326
2327    /// The `IconTheme` of `icon` inside its `TextButton`: the last under it.
2328    pub(crate) fn icon_theme_color(
2329        tester: &WidgetTester,
2330        icon: &waft_widgets::IconData,
2331    ) -> Option<Color> {
2332        let theme = find::descendant(
2333            find::widget_with_icon::<TextButton>(icon),
2334            find::by_type::<IconTheme>(),
2335        )
2336        .last();
2337        tester.widget(theme, |theme: &IconTheme| {
2338            theme.data.color.as_deref().copied()
2339        })
2340    }
2341
2342    pub(crate) fn button_rect(tester: &WidgetTester, index: usize) -> Rect {
2343        let element = find::by_type::<TextButton>().evaluate(tester)[index];
2344        tester.get_rect(element)
2345    }
2346
2347    // 'Initial toggle state is reflected'
2348    #[test]
2349    fn the_initial_toggle_state_is_reflected() {
2350        test_widgets(|tester| {
2351            let theme = default_theme(tester);
2352            tester.pump_widget(boilerplate(
2353                theme.clone(),
2354                ToggleButtons::new(texts(&["First child", "Second child"]), vec![false, true])
2355                    .on_pressed(|_app, _index| {}),
2356            ));
2357
2358            assert_eq!(
2359                style_color(&button_text_style(tester, "First child")),
2360                Some(theme.color_scheme.on_surface().with_opacity(0.87))
2361            );
2362            assert_eq!(
2363                style_color(&button_text_style(tester, "Second child")),
2364                Some(theme.color_scheme.primary())
2365            );
2366        });
2367    }
2368
2369    // 'onPressed is triggered on button tap'
2370    #[test]
2371    fn on_pressed_is_triggered_on_button_tap() {
2372        test_widgets(|tester| {
2373            let theme = default_theme(tester);
2374            let is_selected = Rc::new(std::cell::RefCell::new(vec![false, true]));
2375            let root = {
2376                let theme = theme.clone();
2377                let is_selected = Rc::clone(&is_selected);
2378                waft_widgets::StatefulBuilder::new(move |_app, _context, set_state| {
2379                    let toggled = Rc::clone(&is_selected);
2380                    boilerplate(
2381                        theme.clone(),
2382                        ToggleButtons::new(
2383                            texts(&["First child", "Second child"]),
2384                            is_selected.borrow().clone(),
2385                        )
2386                        .on_pressed(move |app, index| {
2387                            let selected = toggled.borrow()[index];
2388                            toggled.borrow_mut()[index] = !selected;
2389                            set_state(app, &mut |_| {});
2390                        }),
2391                    )
2392                })
2393                .into_widget()
2394            };
2395            tester.pump_widget(root);
2396
2397            assert_eq!(*is_selected.borrow(), [false, true]);
2398            assert_eq!(
2399                style_color(&button_text_style(tester, "First child")),
2400                Some(theme.color_scheme.on_surface().with_opacity(0.87))
2401            );
2402            assert_eq!(
2403                style_color(&button_text_style(tester, "Second child")),
2404                Some(theme.color_scheme.primary())
2405            );
2406
2407            let center = text_center(tester, "Second child");
2408            tester.tap_at(center, 1);
2409            tester.pump_and_settle();
2410
2411            assert_eq!(*is_selected.borrow(), [false, false]);
2412            assert_eq!(
2413                style_color(&button_text_style(tester, "First child")),
2414                Some(theme.color_scheme.on_surface().with_opacity(0.87))
2415            );
2416            assert_eq!(
2417                style_color(&button_text_style(tester, "Second child")),
2418                Some(theme.color_scheme.on_surface().with_opacity(0.87))
2419            );
2420        });
2421    }
2422
2423    pub(crate) fn text_center(tester: &WidgetTester, text: &str) -> Offset {
2424        let element = find::text(text).evaluate(tester)[0];
2425        tester.get_rect(element).center()
2426    }
2427
2428    // 'onPressed that is null disables buttons'
2429    #[test]
2430    fn a_null_on_pressed_disables_the_buttons() {
2431        test_widgets(|tester| {
2432            let theme = default_theme(tester);
2433            tester.pump_widget(boilerplate(
2434                theme.clone(),
2435                ToggleButtons::new(texts(&["First child", "Second child"]), vec![false, true]),
2436            ));
2437
2438            let disabled = Some(theme.color_scheme.on_surface().with_opacity(0.38));
2439            assert_eq!(
2440                style_color(&button_text_style(tester, "First child")),
2441                disabled
2442            );
2443            assert_eq!(
2444                style_color(&button_text_style(tester, "Second child")),
2445                disabled
2446            );
2447
2448            let center = text_center(tester, "Second child");
2449            tester.tap_at(center, 1);
2450            tester.pump_and_settle();
2451
2452            // Nothing should change
2453            assert_eq!(
2454                style_color(&button_text_style(tester, "First child")),
2455                disabled
2456            );
2457            assert_eq!(
2458                style_color(&button_text_style(tester, "Second child")),
2459                disabled
2460            );
2461        });
2462    }
2463
2464    // 'children and isSelected properties have to be the same length'
2465    #[test]
2466    fn children_and_is_selected_have_to_be_the_same_length() {
2467        test_widgets(|tester| {
2468            let theme = default_theme(tester);
2469            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2470                tester.pump_widget(boilerplate(
2471                    theme,
2472                    ToggleButtons::new(texts(&["First child", "Second child"]), vec![false]),
2473                ));
2474            }));
2475            let panic = outcome.expect_err("a length mismatch asserts");
2476            let message = panic
2477                .downcast_ref::<String>()
2478                .cloned()
2479                .or_else(|| {
2480                    panic
2481                        .downcast_ref::<&str>()
2482                        .map(|message| (*message).to_string())
2483                })
2484                .unwrap_or_default();
2485            assert!(message.contains("children.length"), "{message}");
2486            assert!(message.contains("isSelected.length"), "{message}");
2487        });
2488    }
2489
2490    // 'Default text style is applied'
2491    #[test]
2492    fn the_default_text_style_is_applied() {
2493        test_widgets(|tester| {
2494            let theme = default_theme(tester);
2495            tester.pump_widget(boilerplate(
2496                theme.clone(),
2497                ToggleButtons::new(texts(&["First child", "Second child"]), vec![false, true])
2498                    .on_pressed(|_app, _index| {}),
2499            ));
2500
2501            let body_medium = theme.text_theme.body_medium.clone().expect("a bodyMedium");
2502            for text in ["First child", "Second child"] {
2503                let text_style = button_text_style(tester, text);
2504                assert_eq!(text_style.font_family, body_medium.font_family);
2505                assert_eq!(text_style.decoration, body_medium.decoration);
2506            }
2507        });
2508    }
2509
2510    // 'Custom text style except color is applied'
2511    #[test]
2512    fn a_custom_text_style_is_applied_except_its_color() {
2513        test_widgets(|tester| {
2514            let theme = default_theme(tester);
2515            tester.pump_widget(boilerplate(
2516                theme,
2517                ToggleButtons::new(texts(&["First child", "Second child"]), vec![false, true])
2518                    .on_pressed(|_app, _index| {})
2519                    .text_style(
2520                        TextStyle::new()
2521                            .text_baseline(waft_embedder::TextBaseline::Ideographic)
2522                            .font_size(20.0)
2523                            .color(Colors::ORANGE.primary()),
2524                    ),
2525            ));
2526
2527            for text in ["First child", "Second child"] {
2528                let text_style = button_text_style(tester, text);
2529                assert_eq!(
2530                    text_style.text_baseline,
2531                    Some(waft_embedder::TextBaseline::Ideographic)
2532                );
2533                assert_eq!(text_style.font_size, Some(20.0));
2534                assert_ne!(style_color(&text_style), Some(Colors::ORANGE.primary()));
2535            }
2536        });
2537    }
2538
2539    pub(crate) fn three_icons() -> Vec<WidgetRef> {
2540        [Icons::check(), Icons::access_alarm(), Icons::cake()]
2541            .into_iter()
2542            .map(|icon| Icon::new(Some(icon)).into_widget())
2543            .collect()
2544    }
2545
2546    // 'Default BoxConstraints'
2547    #[test]
2548    fn the_default_box_constraints_make_buttons_48_by_48() {
2549        test_widgets(|tester| {
2550            let theme = default_theme(tester);
2551            tester.pump_widget(boilerplate(
2552                theme,
2553                ToggleButtons::new(three_icons(), vec![false; 3]).on_pressed(|_app, _index| {}),
2554            ));
2555
2556            for index in 0..3 {
2557                let rect = button_rect(tester, index);
2558                assert_eq!(rect.width(), 48.0);
2559                assert_eq!(rect.height(), 48.0);
2560            }
2561        });
2562    }
2563
2564    // 'Custom BoxConstraints'
2565    #[test]
2566    fn custom_box_constraints_size_the_buttons() {
2567        test_widgets(|tester| {
2568            let theme = default_theme(tester);
2569            // Test for minimum constraints
2570            tester.pump_widget(boilerplate(
2571                theme.clone(),
2572                ToggleButtons::new(three_icons(), vec![false; 3])
2573                    .constraints(BoxConstraints::new().min_width(50.0).min_height(60.0))
2574                    .on_pressed(|_app, _index| {}),
2575            ));
2576            for index in 0..3 {
2577                let rect = button_rect(tester, index);
2578                assert_eq!(rect.width(), 50.0);
2579                assert_eq!(rect.height(), 60.0);
2580            }
2581
2582            // Test for maximum constraints
2583            tester.pump_widget(boilerplate(
2584                theme,
2585                ToggleButtons::new(three_icons(), vec![false; 3])
2586                    .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
2587                    .constraints(BoxConstraints::new().max_width(20.0).max_height(10.0))
2588                    .on_pressed(|_app, _index| {}),
2589            ));
2590            for index in 0..3 {
2591                let rect = button_rect(tester, index);
2592                assert_eq!(rect.width(), 20.0);
2593                assert_eq!(rect.height(), 10.0);
2594            }
2595        });
2596    }
2597
2598    pub(crate) fn row_with_check() -> Vec<WidgetRef> {
2599        vec![
2600            Row::new()
2601                .children([
2602                    Text::new("First child").into_widget(),
2603                    Icon::new(Some(Icons::check())).into_widget(),
2604                ])
2605                .into_widget(),
2606        ]
2607    }
2608
2609    // 'Default text/icon colors for enabled, selected and disabled states'
2610    #[test]
2611    fn the_default_text_and_icon_colors_follow_the_state() {
2612        test_widgets(|tester| {
2613            let theme = default_theme(tester);
2614            let check = Icons::check();
2615
2616            tester.pump_widget(boilerplate(
2617                theme.clone(),
2618                ToggleButtons::new(row_with_check(), vec![false]).on_pressed(|_app, _index| {}),
2619            ));
2620            // Default enabled color
2621            let enabled = Some(theme.color_scheme.on_surface().with_opacity(0.87));
2622            assert_eq!(
2623                style_color(&button_text_style(tester, "First child")),
2624                enabled
2625            );
2626            assert_eq!(icon_theme_color(tester, &check), enabled);
2627
2628            tester.pump_widget(boilerplate(
2629                theme.clone(),
2630                ToggleButtons::new(row_with_check(), vec![true]).on_pressed(|_app, _index| {}),
2631            ));
2632            tester.pump_and_settle();
2633            // Default selected color
2634            let selected = Some(theme.color_scheme.primary());
2635            assert_eq!(
2636                style_color(&button_text_style(tester, "First child")),
2637                selected
2638            );
2639            assert_eq!(icon_theme_color(tester, &check), selected);
2640
2641            tester.pump_widget(boilerplate(
2642                theme.clone(),
2643                ToggleButtons::new(row_with_check(), vec![true]),
2644            ));
2645            tester.pump_and_settle();
2646            // Default disabled color
2647            let disabled = Some(theme.color_scheme.on_surface().with_opacity(0.38));
2648            assert_eq!(
2649                style_color(&button_text_style(tester, "First child")),
2650                disabled
2651            );
2652            assert_eq!(icon_theme_color(tester, &check), disabled);
2653        });
2654    }
2655
2656    // 'Custom text/icon colors for enabled, selected and disabled states'
2657    #[test]
2658    fn custom_text_and_icon_colors_follow_the_state() {
2659        test_widgets(|tester| {
2660            let theme = default_theme(tester);
2661            let check = Icons::check();
2662            let enabled_color = Colors::LIME.primary();
2663            let selected_color = Colors::GREEN.primary();
2664            let disabled_color = Colors::YELLOW.primary();
2665
2666            // Tests are ineffective if the custom colors are the same as the theme's
2667            assert_ne!(theme.color_scheme.on_surface(), enabled_color);
2668            assert_ne!(theme.color_scheme.primary(), selected_color);
2669            assert_ne!(
2670                theme.color_scheme.on_surface().with_opacity(0.38),
2671                disabled_color
2672            );
2673
2674            tester.pump_widget(boilerplate(
2675                theme.clone(),
2676                ToggleButtons::new(row_with_check(), vec![false])
2677                    .color(enabled_color)
2678                    .on_pressed(|_app, _index| {}),
2679            ));
2680            // Custom enabled color
2681            assert_eq!(
2682                style_color(&button_text_style(tester, "First child")),
2683                Some(enabled_color)
2684            );
2685            assert_eq!(icon_theme_color(tester, &check), Some(enabled_color));
2686
2687            tester.pump_widget(boilerplate(
2688                theme.clone(),
2689                ToggleButtons::new(row_with_check(), vec![true])
2690                    .selected_color(selected_color)
2691                    .on_pressed(|_app, _index| {}),
2692            ));
2693            tester.pump_and_settle();
2694            // Custom selected color
2695            assert_eq!(
2696                style_color(&button_text_style(tester, "First child")),
2697                Some(selected_color)
2698            );
2699            assert_eq!(icon_theme_color(tester, &check), Some(selected_color));
2700
2701            tester.pump_widget(boilerplate(
2702                theme,
2703                ToggleButtons::new(row_with_check(), vec![true]).disabled_color(disabled_color),
2704            ));
2705            tester.pump_and_settle();
2706            // Custom disabled color
2707            assert_eq!(
2708                style_color(&button_text_style(tester, "First child")),
2709                Some(disabled_color)
2710            );
2711            assert_eq!(icon_theme_color(tester, &check), Some(disabled_color));
2712        });
2713    }
2714
2715    /// `tester.widget<Material>(find.descendant(of: find.byType(TextButton), matching:
2716    /// find.byType(Material)))`, or the one around `text`.
2717    pub(crate) fn button_material<R>(
2718        tester: &WidgetTester,
2719        text: Option<&str>,
2720        read: impl FnOnce(&Material) -> R,
2721    ) -> R {
2722        let button = match text {
2723            Some(text) => text_button_of(text),
2724            None => find::by_type::<TextButton>().first(),
2725        };
2726        let material = find::descendant(button, find::by_type::<Material>()).first();
2727        tester.widget(material, read)
2728    }
2729
2730    pub(crate) fn single_button(selected: bool, enabled: bool) -> ToggleButtons {
2731        let buttons = ToggleButtons::new(
2732            vec![
2733                Row::new()
2734                    .children([Text::new("First child").into_widget()])
2735                    .into_widget(),
2736            ],
2737            vec![selected],
2738        );
2739        if enabled {
2740            buttons.on_pressed(|_app, _index| {})
2741        } else {
2742            buttons
2743        }
2744    }
2745
2746    // 'Default button fillColor - unselected'
2747    #[test]
2748    fn the_default_fill_color_of_an_unselected_button() {
2749        test_widgets(|tester| {
2750            let theme = default_theme(tester);
2751            tester.pump_widget(boilerplate(theme.clone(), single_button(false, true)));
2752
2753            let (color, material_type) =
2754                button_material(tester, None, |material| (material.color, material.r#type));
2755            assert_eq!(color, Some(theme.color_scheme.surface().with_opacity(0.0)));
2756            assert_eq!(material_type, MaterialType::Button);
2757        });
2758    }
2759
2760    // 'Default button fillColor - selected'
2761    #[test]
2762    fn the_default_fill_color_of_a_selected_button() {
2763        test_widgets(|tester| {
2764            let theme = default_theme(tester);
2765            tester.pump_widget(boilerplate(theme.clone(), single_button(true, true)));
2766
2767            let (color, material_type) =
2768                button_material(tester, None, |material| (material.color, material.r#type));
2769            assert_eq!(color, Some(theme.color_scheme.primary().with_opacity(0.12)));
2770            assert_eq!(material_type, MaterialType::Button);
2771        });
2772    }
2773
2774    // 'Default button fillColor - disabled'
2775    #[test]
2776    fn the_default_fill_color_of_a_disabled_button() {
2777        test_widgets(|tester| {
2778            let theme = default_theme(tester);
2779            tester.pump_widget(boilerplate(theme.clone(), single_button(true, false)));
2780
2781            let (color, material_type) =
2782                button_material(tester, None, |material| (material.color, material.r#type));
2783            assert_eq!(color, Some(theme.color_scheme.surface().with_opacity(0.0)));
2784            assert_eq!(material_type, MaterialType::Button);
2785        });
2786    }
2787
2788    // 'Custom button fillColor'
2789    #[test]
2790    fn a_custom_fill_color_fills_a_selected_button() {
2791        test_widgets(|tester| {
2792            let theme = default_theme(tester);
2793            let custom_fill_color = Colors::GREEN.primary();
2794            tester.pump_widget(boilerplate(
2795                theme,
2796                single_button(true, true).fill_color(custom_fill_color),
2797            ));
2798
2799            let (color, material_type) =
2800                button_material(tester, None, |material| (material.color, material.r#type));
2801            assert_eq!(color, Some(custom_fill_color));
2802            assert_eq!(material_type, MaterialType::Button);
2803        });
2804    }
2805
2806    pub(crate) fn two_texts() -> Vec<WidgetRef> {
2807        texts(&["First child", "Second child"])
2808    }
2809
2810    pub(crate) fn material_color(tester: &WidgetTester, text: &str) -> Option<Color> {
2811        button_material(tester, Some(text), |material| material.color)
2812    }
2813
2814    // 'Custom button fillColor - Non WidgetState'
2815    #[test]
2816    fn a_plain_fill_color_fills_only_selected_enabled_buttons() {
2817        test_widgets(|tester| {
2818            let theme = default_theme(tester);
2819            let selected_fill_color = Colors::YELLOW.primary();
2820            let unselected = Some(theme.color_scheme.surface().with_opacity(0.0));
2821
2822            tester.pump_widget(boilerplate(
2823                theme.clone(),
2824                ToggleButtons::new(two_texts(), vec![false, true])
2825                    .fill_color(selected_fill_color)
2826                    .on_pressed(|_app, _index| {}),
2827            ));
2828            tester.pump_and_settle();
2829            assert_eq!(material_color(tester, "First child"), unselected);
2830            assert_eq!(
2831                material_color(tester, "Second child"),
2832                Some(selected_fill_color)
2833            );
2834
2835            tester.pump_widget(boilerplate(
2836                theme,
2837                ToggleButtons::new(two_texts(), vec![false, true]).fill_color(selected_fill_color),
2838            ));
2839            tester.pump_and_settle();
2840            assert_eq!(material_color(tester, "First child"), unselected);
2841            assert_eq!(material_color(tester, "Second child"), unselected);
2842        });
2843    }
2844
2845    // 'Custom button fillColor - WidgetState'
2846    #[test]
2847    fn a_widget_state_fill_color_resolves_in_the_button_states() {
2848        test_widgets(|tester| {
2849            let theme = default_theme(tester);
2850            let selected_fill_color = Colors::ORANGE.primary();
2851            let default_fill_color = Colors::BLUE.primary();
2852            let get_fill_color = move |states: &WidgetStates| {
2853                if states.contains(&WidgetState::Selected) {
2854                    return selected_fill_color;
2855                }
2856                default_fill_color
2857            };
2858
2859            tester.pump_widget(boilerplate(
2860                theme.clone(),
2861                ToggleButtons::new(two_texts(), vec![false, true])
2862                    .fill_color(WidgetStateColor::resolve_with(get_fill_color))
2863                    .on_pressed(|_app, _index| {}),
2864            ));
2865            tester.pump_and_settle();
2866            assert_eq!(
2867                material_color(tester, "First child"),
2868                Some(default_fill_color)
2869            );
2870            assert_eq!(
2871                material_color(tester, "Second child"),
2872                Some(selected_fill_color)
2873            );
2874
2875            // disabled
2876            tester.pump_widget(boilerplate(
2877                theme,
2878                ToggleButtons::new(two_texts(), vec![false, true])
2879                    .fill_color(WidgetStateColor::resolve_with(get_fill_color)),
2880            ));
2881            tester.pump_and_settle();
2882            assert_eq!(
2883                material_color(tester, "First child"),
2884                Some(default_fill_color)
2885            );
2886            assert_eq!(
2887                material_color(tester, "Second child"),
2888                Some(default_fill_color)
2889            );
2890        });
2891    }
2892
2893    /// What `paints` records for the first `_RenderInkFeatures`: its own paint and its
2894    /// descendants' (the button's `Material` is one of them).
2895    fn first_ink_features_painted(tester: &WidgetTester) -> Vec<RecordedCall> {
2896        let render = tester.first::<crate::material::RenderInkFeatures>();
2897        tester.painted_calls(render.as_object())
2898    }
2899
2900    pub(crate) fn ink_rect_colors(tester: &WidgetTester) -> Vec<u32> {
2901        first_ink_features_painted(tester)
2902            .into_iter()
2903            .filter_map(|drawn| match drawn {
2904                RecordedCall::Rect { color, .. } => Some(color.value()),
2905                _ => None,
2906            })
2907            .collect()
2908    }
2909
2910    pub(crate) fn ink_circle_colors(tester: &WidgetTester) -> Vec<u32> {
2911        first_ink_features_painted(tester)
2912            .into_iter()
2913            .filter_map(|drawn| path_like(&drawn).map(|(color, _)| color.value()))
2914            .collect()
2915    }
2916
2917    pub(crate) fn mouse() -> TestPointer {
2918        TestPointer::mouse(1, 0)
2919    }
2920
2921    /// Dart's InkWell colors cases: hover, then press, then focus a one-button toggle that
2922    /// `build` makes around the focus node it is given.
2923    pub(crate) fn check_ink_colors(
2924        tester: &mut WidgetTester,
2925        build: impl Fn(waft_foundation::Ref<waft_widgets::FocusNode>) -> WidgetRef,
2926        expected: [Color; 3],
2927        press_first: bool,
2928    ) {
2929        let focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut());
2930        tester.pump_widget(build(focus_node.clone()));
2931        let center = text_center(tester, "First child");
2932        let [hover, splash, focus] = expected;
2933        let argb = |color: Color| color.value();
2934
2935        let mut hover_gesture = mouse();
2936        let mut touch_gesture = TestPointer::touch(2);
2937        if press_first {
2938            // splashColor
2939            tester.down(&mut touch_gesture, center);
2940            tester.pump_and_settle();
2941            assert!(ink_circle_colors(tester).contains(&argb(splash)));
2942            tester.up(&touch_gesture);
2943            tester.pump_and_settle();
2944        }
2945
2946        // hoverColor
2947        tester.add_pointer(&mut hover_gesture, center);
2948        tester.move_to(&mut hover_gesture, center, false);
2949        tester.pump_and_settle();
2950        assert!(ink_rect_colors(tester).contains(&argb(hover)));
2951        tester.move_to(&mut hover_gesture, Offset::ZERO, false);
2952
2953        if !press_first {
2954            // splashColor
2955            tester.down(&mut touch_gesture, center); // The button is on hovered and pressed
2956            tester.pump_and_settle();
2957            assert!(ink_circle_colors(tester).contains(&argb(splash)));
2958            tester.up(&touch_gesture);
2959            tester.pump_and_settle();
2960            tester.move_to(&mut hover_gesture, Offset::new(0.0, 50.0), false);
2961            tester.pump_and_settle();
2962        }
2963
2964        // focusColor
2965        tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
2966        focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2967        tester.pump_and_settle();
2968        assert!(ink_rect_colors(tester).contains(&argb(focus)));
2969    }
2970
2971    // 'Default InkWell colors - unselected'
2972    #[test]
2973    fn the_default_ink_colors_of_an_unselected_button() {
2974        test_widgets(|tester| {
2975            let theme = default_theme(tester);
2976            let on_surface = theme.color_scheme.on_surface();
2977            check_ink_colors(
2978                tester,
2979                |focus_node| {
2980                    boilerplate(
2981                        theme.clone(),
2982                        ToggleButtons::new(texts(&["First child"]), vec![false])
2983                            .on_pressed(|_app, _index| {})
2984                            .focus_nodes(vec![focus_node.erase()]),
2985                    )
2986                },
2987                [
2988                    on_surface.with_opacity(0.04),
2989                    on_surface.with_opacity(0.16),
2990                    on_surface.with_opacity(0.12),
2991                ],
2992                false,
2993            );
2994        });
2995    }
2996
2997    // 'Default InkWell colors - selected'
2998    #[test]
2999    fn the_default_ink_colors_of_a_selected_button() {
3000        test_widgets(|tester| {
3001            let theme = default_theme(tester);
3002            let primary = theme.color_scheme.primary();
3003            check_ink_colors(
3004                tester,
3005                |focus_node| {
3006                    boilerplate(
3007                        theme.clone(),
3008                        ToggleButtons::new(texts(&["First child"]), vec![true])
3009                            .on_pressed(|_app, _index| {})
3010                            .focus_nodes(vec![focus_node.erase()]),
3011                    )
3012                },
3013                [
3014                    primary.with_opacity(0.04),
3015                    primary.with_opacity(0.16),
3016                    primary.with_opacity(0.12),
3017                ],
3018                false,
3019            );
3020        });
3021    }
3022
3023    // 'Custom InkWell colors'
3024    #[test]
3025    fn custom_ink_colors_are_used() {
3026        test_widgets(|tester| {
3027            let theme = default_theme(tester);
3028            let splash_color = Color::new(0xff4caf50);
3029            let highlight_color = Color::new(0xffcddc39);
3030            let hover_color = Color::new(0xffffeb3b);
3031            let focus_color = Color::new(0xffffff00);
3032            check_ink_colors(
3033                tester,
3034                |focus_node| {
3035                    boilerplate(
3036                        theme.clone(),
3037                        ToggleButtons::new(texts(&["First child"]), vec![true])
3038                            .splash_color(splash_color)
3039                            .highlight_color(highlight_color)
3040                            .hover_color(hover_color)
3041                            .focus_color(focus_color)
3042                            .on_pressed(|_app, _index| {})
3043                            .focus_nodes(vec![focus_node.erase()]),
3044                    )
3045                },
3046                [hover_color, splash_color, focus_color],
3047                true,
3048            );
3049        });
3050    }
3051
3052    /// Dart's `paints..path()..path(style: stroke, color:, strokeWidth:)...`: a path drawn
3053    /// first (the physical model, which Dart's recording canvas sees even at alpha 0, and
3054    /// which the display list drops when the button's fill has no effect, so `physical_model`
3055    /// is false for a button that fills at alpha 0), then each of `expected` in order, stroked.
3056    pub(crate) fn paints_physical_model_then_strokes(
3057        tester: &WidgetTester,
3058        render: AnyRenderObject,
3059        physical_model: bool,
3060        expected: &[(Color, f64)],
3061    ) -> bool {
3062        use waft_rendering::testing::{PaintCall, PaintedStyle, paints};
3063        // Dart's `path(style: stroke, color:, strokeWidth:)`.
3064        let stroked = |(color, width): &(Color, f64)| PaintCall::Path {
3065            color: Some(*color),
3066            style: Some(PaintedStyle::Stroke(Some(*width))),
3067            includes: Vec::new(),
3068            excludes: Vec::new(),
3069        };
3070        let mut pattern = Vec::new();
3071        if physical_model {
3072            pattern.push(PaintCall::path(None));
3073        }
3074        pattern.extend(expected.iter().map(stroked));
3075        paints(&tester.painted_ops(render), &pattern).is_ok()
3076    }
3077
3078    pub(crate) fn select_toggle_button_objects(
3079        tester: &WidgetTester,
3080    ) -> Vec<RenderHandle<SelectToggleButtonRenderObject>> {
3081        tester.all::<SelectToggleButtonRenderObject>()
3082    }
3083
3084    // 'Default border width and border colors for enabled, selected and disabled states'
3085    #[test]
3086    fn the_default_border_width_and_colors_follow_the_state() {
3087        test_widgets(|tester| {
3088            let theme = default_theme(tester);
3089            let border = (
3090                theme.color_scheme.on_surface().with_opacity(0.12),
3091                DEFAULT_BORDER_WIDTH,
3092            );
3093            for (selected, enabled) in [(false, true), (true, true), (false, false)] {
3094                tester.pump_widget(boilerplate(theme.clone(), single_button(selected, enabled)));
3095                let render = select_toggle_button_objects(tester)[0].as_object();
3096                assert!(paints_physical_model_then_strokes(
3097                    tester,
3098                    render,
3099                    selected && enabled,
3100                    &[border]
3101                ));
3102            }
3103        });
3104    }
3105
3106    // 'Custom border width and border colors for enabled, selected and disabled states'
3107    #[test]
3108    fn custom_border_width_and_colors_follow_the_state() {
3109        test_widgets(|tester| {
3110            let theme = default_theme(tester);
3111            let border_color = Color::new(0xff4caf50);
3112            let selected_border_color = Color::new(0xffcddc39);
3113            let disabled_border_color = Color::new(0xffffeb3b);
3114            const CUSTOM_WIDTH: f64 = 2.0;
3115
3116            tester.pump_widget(boilerplate(
3117                theme.clone(),
3118                single_button(false, true)
3119                    .border_color(border_color)
3120                    .border_width(CUSTOM_WIDTH),
3121            ));
3122            let render = select_toggle_button_objects(tester)[0].as_object();
3123            assert!(paints_physical_model_then_strokes(
3124                tester,
3125                render,
3126                false,
3127                &[(border_color, CUSTOM_WIDTH)]
3128            ));
3129
3130            tester.pump_widget(boilerplate(
3131                theme.clone(),
3132                single_button(true, true)
3133                    .selected_border_color(selected_border_color)
3134                    .border_width(CUSTOM_WIDTH),
3135            ));
3136            let render = select_toggle_button_objects(tester)[0].as_object();
3137            assert!(paints_physical_model_then_strokes(
3138                tester,
3139                render,
3140                true,
3141                &[(selected_border_color, CUSTOM_WIDTH)]
3142            ));
3143
3144            tester.pump_widget(boilerplate(
3145                theme,
3146                single_button(false, false)
3147                    .disabled_border_color(disabled_border_color)
3148                    .border_width(CUSTOM_WIDTH),
3149            ));
3150            let render = select_toggle_button_objects(tester)[0].as_object();
3151            assert!(paints_physical_model_then_strokes(
3152                tester,
3153                render,
3154                false,
3155                &[(disabled_border_color, CUSTOM_WIDTH)]
3156            ));
3157        });
3158    }
3159
3160    fn sized_boxes(sizes: &[(Option<f64>, Option<f64>)]) -> Vec<WidgetRef> {
3161        sizes
3162            .iter()
3163            .map(|(width, height)| {
3164                Container::new()
3165                    .constraints(BoxConstraints::tight_for(*width, *height))
3166                    .into_widget()
3167            })
3168            .collect()
3169    }
3170
3171    fn select_toggle_button_rects(tester: &WidgetTester) -> Vec<Rect> {
3172        find::by_type::<SelectToggleButton>()
3173            .evaluate(tester)
3174            .into_iter()
3175            .map(|element| tester.get_rect(element))
3176            .collect()
3177    }
3178
3179    // 'Height of segmented control is determined by tallest widget'
3180    #[test]
3181    fn the_height_of_the_buttons_is_that_of_the_tallest_child() {
3182        test_widgets(|tester| {
3183            let theme = default_theme(tester);
3184            let children = sized_boxes(&[
3185                (None, Some(100.0)),
3186                (None, Some(400.0)), // tallest widget
3187                (None, Some(200.0)),
3188            ]);
3189            tester.pump_widget(boilerplate(
3190                theme,
3191                ToggleButtons::new(children, vec![false, true, false]),
3192            ));
3193
3194            for rect in select_toggle_button_rects(tester) {
3195                assert_eq!(rect.height(), 400.0 + 2.0 * DEFAULT_BORDER_WIDTH);
3196            }
3197        });
3198    }
3199
3200    // 'Sizes of toggle buttons rebuilds with the correct dimensions'
3201    #[test]
3202    fn the_sizes_of_the_buttons_follow_a_rebuild() {
3203        test_widgets(|tester| {
3204            let theme = default_theme(tester);
3205            let children = sized_boxes(&[(Some(100.0), Some(100.0)); 3]);
3206            tester.pump_widget(boilerplate(
3207                theme.clone(),
3208                ToggleButtons::new(children, vec![false, true, false]),
3209            ));
3210
3211            let rects = select_toggle_button_rects(tester);
3212            for (i, rect) in rects.iter().enumerate() {
3213                assert_eq!(rect.height(), 100.0 + 2.0 * DEFAULT_BORDER_WIDTH);
3214
3215                // Only the last button paints both leading and trailing borders.
3216                // Other buttons only paint the leading border.
3217                if i == rects.len() - 1 {
3218                    assert_eq!(rect.width(), 100.0 + 2.0 * DEFAULT_BORDER_WIDTH);
3219                } else {
3220                    assert_eq!(rect.width(), 100.0 + DEFAULT_BORDER_WIDTH);
3221                }
3222            }
3223
3224            let children_rebuilt = sized_boxes(&[(Some(200.0), Some(200.0)); 3]);
3225
3226            // Update border width and widget sized to verify layout updates correctly
3227            const CUSTOM_BORDER_WIDTH: f64 = 5.0;
3228            tester.pump_widget(boilerplate(
3229                theme,
3230                ToggleButtons::new(children_rebuilt, vec![false, true, false])
3231                    .border_width(CUSTOM_BORDER_WIDTH),
3232            ));
3233
3234            // Only the last button paints both leading and trailing borders.
3235            // Other buttons only paint the leading border.
3236            let rects = select_toggle_button_rects(tester);
3237            for (i, rect) in rects.iter().enumerate() {
3238                assert_eq!(rect.height(), 200.0 + 2.0 * CUSTOM_BORDER_WIDTH);
3239                if i == rects.len() - 1 {
3240                    assert_eq!(rect.width(), 200.0 + 2.0 * CUSTOM_BORDER_WIDTH);
3241                } else {
3242                    assert_eq!(rect.width(), 200.0 + CUSTOM_BORDER_WIDTH);
3243                }
3244            }
3245        });
3246    }
3247
3248    fn bottom_left_dy(tester: &WidgetTester, text: &str) -> f64 {
3249        let element = find::text(text).evaluate(tester)[0];
3250        tester.get_rect(element).bottom
3251    }
3252
3253    fn baseline_row() -> Row {
3254        let style = |font_size: f64| {
3255            TextStyle::new()
3256                .font_family("FlutterTest")
3257                .font_size(font_size)
3258        };
3259        Row::new()
3260            .cross_axis_alignment(CrossAxisAlignment::Baseline)
3261            .text_baseline(TextBaseline::Alphabetic)
3262            .children([
3263                ToggleButtons::new(
3264                    vec![
3265                        Text::new("First child").style(style(8.0)).into_widget(),
3266                        Text::new("Second child").style(style(8.0)).into_widget(),
3267                    ],
3268                    vec![false, true],
3269                )
3270                .border_width(5.0)
3271                .into_widget(),
3272                crate::elevated_button::ElevatedButton::new(
3273                    None,
3274                    Some(Text::new("Elevated Button")),
3275                )
3276                .style(
3277                    crate::elevated_button::ElevatedButton::style_from()
3278                        .text_style(style(20.0))
3279                        .build(),
3280                )
3281                .into_widget(),
3282                Text::new("Text").style(style(28.0)).into_widget(),
3283            ])
3284    }
3285
3286    // 'Material2 - ToggleButtons text baseline alignment'
3287    #[test]
3288    fn material2_toggle_buttons_align_their_text_baseline() {
3289        test_widgets(|tester| {
3290            let theme = ThemeData::builder()
3291                .use_material3(false)
3292                .build(&tester.cell.borrow());
3293            // The font size must be a multiple of 4 until
3294            // https://github.com/flutter/flutter/issues/122066 is resolved.
3295            tester.pump_widget(boilerplate(theme, baseline_row()));
3296
3297            // The test font extends 0.25 * fontSize below the baseline.
3298            // So the three row elements line up like this:
3299            //
3300            //  ToggleButton  MaterialButton  Text
3301            //  ------------------------------------   baseline
3302            //  2.0           5.0             7.0      space below the baseline = 0.25 * fontSize
3303            //  ------------------------------------   widget text dy values
3304            let first_toggle_button_dy = bottom_left_dy(tester, "First child");
3305            let second_toggle_button_dy = bottom_left_dy(tester, "Second child");
3306            let elevated_button_dy = bottom_left_dy(tester, "Elevated Button");
3307            let text_dy = bottom_left_dy(tester, "Text");
3308
3309            assert_eq!(first_toggle_button_dy, second_toggle_button_dy);
3310            assert_eq!(first_toggle_button_dy, elevated_button_dy - 3.0);
3311            assert_eq!(first_toggle_button_dy, text_dy - 5.0);
3312        });
3313    }
3314
3315    // 'Material3 - ToggleButtons text baseline alignment'
3316    #[test]
3317    fn material3_toggle_buttons_align_their_text_baseline() {
3318        test_widgets(|tester| {
3319            let theme = default_theme(tester);
3320            // The point size of the fonts must be a multiple of 4 until
3321            // https://github.com/flutter/flutter/issues/122066 is resolved.
3322            tester.pump_widget(boilerplate(theme, baseline_row()));
3323
3324            let first_toggle_button_dy = bottom_left_dy(tester, "First child");
3325            let second_toggle_button_dy = bottom_left_dy(tester, "Second child");
3326            let elevated_button_dy = bottom_left_dy(tester, "Elevated Button");
3327            let text_dy = bottom_left_dy(tester, "Text");
3328
3329            assert_eq!(first_toggle_button_dy, second_toggle_button_dy);
3330            waft_widgets::testing::assert_more_or_less_equals_within(
3331                first_toggle_button_dy,
3332                elevated_button_dy - 1.7,
3333                0.1,
3334            );
3335            waft_widgets::testing::assert_more_or_less_equals_within(
3336                first_toggle_button_dy,
3337                text_dy - 9.7,
3338                0.1,
3339            );
3340        });
3341    }
3342
3343    fn top_right_dx(tester: &WidgetTester, text: &str) -> f64 {
3344        let element = find::text(text).evaluate(tester)[0];
3345        tester.get_rect(element).right
3346    }
3347
3348    // 'Directionality test'
3349    #[test]
3350    fn the_buttons_follow_the_text_direction() {
3351        test_widgets(|tester| {
3352            for (direction, first_is_left) in
3353                [(TextDirection::Ltr, true), (TextDirection::Rtl, false)]
3354            {
3355                tester.pump_widget(
3356                    Material::new()
3357                        .child(DirectionalityWidget::new(
3358                            direction,
3359                            Center::new().child(
3360                                ToggleButtons::new(
3361                                    texts(&["First child", "Second child"]),
3362                                    vec![false, true],
3363                                )
3364                                .on_pressed(|_app, _index| {}),
3365                            ),
3366                        ))
3367                        .into_widget(),
3368                );
3369
3370                let first_is_before_second =
3371                    top_right_dx(tester, "First child") < top_right_dx(tester, "Second child");
3372                assert_eq!(first_is_before_second, first_is_left);
3373            }
3374        });
3375    }
3376
3377    fn three_texts() -> Vec<WidgetRef> {
3378        texts(&["First child", "Second child", "Third child"])
3379    }
3380
3381    // 'Properly draws borders based on state'
3382    #[test]
3383    fn borders_are_drawn_based_on_the_state_of_each_button() {
3384        test_widgets(|tester| {
3385            let theme = default_theme(tester);
3386            tester.pump_widget(boilerplate(
3387                theme.clone(),
3388                ToggleButtons::new(three_texts(), vec![false, true, false])
3389                    .on_pressed(|_app, _index| {}),
3390            ));
3391            let border = (
3392                theme.color_scheme.on_surface().with_opacity(0.12),
3393                DEFAULT_BORDER_WIDTH,
3394            );
3395            let objects = select_toggle_button_objects(tester);
3396
3397            // The first button paints the leading, top and bottom sides with a path
3398            assert!(paints_physical_model_then_strokes(
3399                tester,
3400                objects[0].as_object(),
3401                false,
3402                &[border]
3403            ));
3404            // The middle buttons paint a leading side path first, followed by a
3405            // top and bottom side path
3406            assert!(paints_physical_model_then_strokes(
3407                tester,
3408                objects[1].as_object(),
3409                true,
3410                &[border, border]
3411            ));
3412            // The last button paints a leading side path first, followed by
3413            // a trailing, top and bottom side path
3414            assert!(paints_physical_model_then_strokes(
3415                tester,
3416                objects[2].as_object(),
3417                false,
3418                &[border, border]
3419            ));
3420        });
3421    }
3422
3423    // 'Properly draws borders based on state when direction is vertical and verticalDirection
3424    // is down.'
3425    #[test]
3426    fn vertical_borders_are_drawn_based_on_the_state_of_each_button() {
3427        test_widgets(|tester| {
3428            let theme = default_theme(tester);
3429            tester.pump_widget(boilerplate(
3430                theme.clone(),
3431                ToggleButtons::new(three_texts(), vec![false, true, false])
3432                    .direction(Axis::Vertical)
3433                    .on_pressed(|_app, _index| {}),
3434            ));
3435
3436            // The children should be laid out along vertical and the first child at top.
3437            // The item height is icon height + default border width (48.0 + 1.0) pixels.
3438            assert_eq!(
3439                text_center(tester, "First child"),
3440                Offset::new(400.0, 251.0)
3441            );
3442            assert_eq!(
3443                text_center(tester, "Second child"),
3444                Offset::new(400.0, 300.0)
3445            );
3446            assert_eq!(
3447                text_center(tester, "Third child"),
3448                Offset::new(400.0, 349.0)
3449            );
3450
3451            let border = (
3452                theme.color_scheme.on_surface().with_opacity(0.12),
3453                DEFAULT_BORDER_WIDTH,
3454            );
3455            let objects = select_toggle_button_objects(tester);
3456            // The first button paints the left, top and right sides with a path.
3457            assert!(paints_physical_model_then_strokes(
3458                tester,
3459                objects[0].as_object(),
3460                false,
3461                &[border]
3462            ));
3463            // The middle buttons paint a top side path first, followed by a
3464            // left and right side path.
3465            assert!(paints_physical_model_then_strokes(
3466                tester,
3467                objects[1].as_object(),
3468                true,
3469                &[border, border]
3470            ));
3471            // The last button paints a top side path first, followed by
3472            // a left, bottom and right side path
3473            assert!(paints_physical_model_then_strokes(
3474                tester,
3475                objects[2].as_object(),
3476                false,
3477                &[border, border]
3478            ));
3479        });
3480    }
3481
3482    // 'VerticalDirection test when direction is vertical.'
3483    #[test]
3484    fn the_vertical_direction_orders_the_buttons_of_a_vertical_toggle() {
3485        test_widgets(|tester| {
3486            let theme = default_theme(tester);
3487            tester.pump_widget(boilerplate(
3488                theme,
3489                ToggleButtons::new(three_texts(), vec![false, true, false])
3490                    .direction(Axis::Vertical)
3491                    .vertical_direction(VerticalDirection::Up)
3492                    .on_pressed(|_app, _index| {}),
3493            ));
3494
3495            // The children should be laid out along vertical and the last child at top.
3496            assert_eq!(
3497                text_center(tester, "Third child"),
3498                Offset::new(400.0, 251.0)
3499            );
3500            assert_eq!(
3501                text_center(tester, "Second child"),
3502                Offset::new(400.0, 300.0)
3503            );
3504            assert_eq!(
3505                text_center(tester, "First child"),
3506                Offset::new(400.0, 349.0)
3507            );
3508        });
3509    }
3510
3511    fn toggle_buttons_size(tester: &WidgetTester) -> Size {
3512        let element = find::by_type::<ToggleButtons>().evaluate(tester)[0];
3513        tester.get_size(element)
3514    }
3515
3516    fn tap_target_buttons(constraints: BoxConstraints, labels: [&str; 3]) -> ToggleButtons {
3517        ToggleButtons::new(texts(&labels), vec![false, true, false])
3518            .constraints(constraints)
3519            .on_pressed(|_app, _index| {})
3520    }
3521
3522    fn min_32() -> BoxConstraints {
3523        BoxConstraints::new().min_width(32.0).min_height(32.0)
3524    }
3525
3526    // 'Material2 - Tap target size is configurable by ThemeData.materialTapTargetSize'
3527    #[test]
3528    fn material2_tap_target_size_is_configurable_by_the_theme() {
3529        test_widgets(|tester| {
3530            // Dart's `boilerplate` takes `theme ?? ThemeData(materialTapTargetSize:)`, so the
3531            // Material 2 theme given here makes the argument moot: both sizes stay padded.
3532            for expected in [Size::new(228.0, 48.0), Size::new(228.0, 48.0)] {
3533                let theme = ThemeData::builder()
3534                    .use_material3(false)
3535                    .build(&tester.cell.borrow());
3536                tester.pump_widget(boilerplate(
3537                    theme,
3538                    tap_target_buttons(min_32(), ["First", "Second", "Third"]),
3539                ));
3540                assert_eq!(toggle_buttons_size(tester), expected);
3541            }
3542        });
3543    }
3544
3545    // 'Material3 - Tap target size is configurable by ThemeData.materialTapTargetSize'
3546    #[test]
3547    fn material3_tap_target_size_is_configurable_by_the_theme() {
3548        test_widgets(|tester| {
3549            for (tap_target_size, expected) in [
3550                (MaterialTapTargetSize::Padded, Size::new(232.0, 48.0)),
3551                (MaterialTapTargetSize::ShrinkWrap, Size::new(232.0, 34.0)),
3552            ] {
3553                let theme = themed(tester, tap_target_size);
3554                tester.pump_widget(boilerplate(
3555                    theme,
3556                    tap_target_buttons(min_32(), ["First", "Second", "Third"]),
3557                ));
3558                assert_eq!(toggle_buttons_size(tester), expected);
3559            }
3560        });
3561    }
3562
3563    // 'Material2 - Tap target size is configurable'
3564    #[test]
3565    fn material2_tap_target_size_is_configurable() {
3566        test_widgets(|tester| {
3567            for (tap_target_size, expected) in [
3568                (MaterialTapTargetSize::Padded, Size::new(228.0, 48.0)),
3569                (MaterialTapTargetSize::ShrinkWrap, Size::new(228.0, 34.0)),
3570            ] {
3571                let theme = ThemeData::builder()
3572                    .use_material3(false)
3573                    .build(&tester.cell.borrow());
3574                tester.pump_widget(boilerplate(
3575                    theme,
3576                    tap_target_buttons(min_32(), ["First", "Second", "Third"])
3577                        .tap_target_size(tap_target_size),
3578                ));
3579                assert_eq!(toggle_buttons_size(tester), expected);
3580            }
3581        });
3582    }
3583
3584    // 'Material3 - Tap target size is configurable'
3585    #[test]
3586    fn material3_tap_target_size_is_configurable() {
3587        test_widgets(|tester| {
3588            for (tap_target_size, expected) in [
3589                (MaterialTapTargetSize::Padded, Size::new(232.0, 48.0)),
3590                (MaterialTapTargetSize::ShrinkWrap, Size::new(232.0, 34.0)),
3591            ] {
3592                let theme = default_theme(tester);
3593                tester.pump_widget(boilerplate(
3594                    theme,
3595                    tap_target_buttons(min_32(), ["First", "Second", "Third"])
3596                        .tap_target_size(tap_target_size),
3597                ));
3598                assert_eq!(toggle_buttons_size(tester), expected);
3599            }
3600        });
3601    }
3602
3603    // 'Tap target size is configurable for vertical axis'
3604    #[test]
3605    fn tap_target_size_is_configurable_for_the_vertical_axis() {
3606        test_widgets(|tester| {
3607            for (tap_target_size, expected) in [
3608                (MaterialTapTargetSize::Padded, Size::new(48.0, 100.0)),
3609                (MaterialTapTargetSize::ShrinkWrap, Size::new(34.0, 100.0)),
3610            ] {
3611                let theme = default_theme(tester);
3612                tester.pump_widget(boilerplate(
3613                    theme,
3614                    tap_target_buttons(min_32(), ["1", "2", "3"])
3615                        .tap_target_size(tap_target_size)
3616                        .direction(Axis::Vertical),
3617                ));
3618                assert_eq!(toggle_buttons_size(tester), expected);
3619            }
3620        });
3621    }
3622
3623    // 'Material2 - Border radius paint test when there is only one button' and the Material 3
3624    // twin; their golden files are not compared.
3625    #[test]
3626    fn a_lone_button_with_a_border_radius_is_centered_and_strokes_its_border() {
3627        test_widgets(|tester| {
3628            for use_material3 in [false, true] {
3629                let theme = ThemeData::builder()
3630                    .use_material3(use_material3)
3631                    .build(&tester.cell.borrow());
3632                tester.pump_widget(boilerplate(
3633                    theme.clone(),
3634                    waft_widgets::RepaintBoundary::new().child(
3635                        single_button(true, true).border_radius(BorderRadius::circular(7.0)),
3636                    ),
3637                ));
3638
3639                // The only button should be laid out at the center of the screen.
3640                assert_eq!(
3641                    text_center(tester, "First child"),
3642                    Offset::new(400.0, 300.0)
3643                );
3644
3645                let border = (
3646                    theme.color_scheme.on_surface().with_opacity(0.12),
3647                    DEFAULT_BORDER_WIDTH,
3648                );
3649                let render = select_toggle_button_objects(tester)[0].as_object();
3650                assert!(paints_physical_model_then_strokes(
3651                    tester,
3652                    render,
3653                    true,
3654                    &[border]
3655                ));
3656            }
3657        });
3658    }
3659
3660    // 'ToggleButtons changes mouse cursor when the button is hovered'
3661    #[test]
3662    fn the_mouse_cursor_follows_the_toggle_buttons_configuration() {
3663        test_widgets(|tester| {
3664            let theme = default_theme(tester);
3665            let forbidden_region = |buttons: ToggleButtons| {
3666                waft_widgets::MouseRegion::new()
3667                    .cursor(SystemMouseCursors::FORBIDDEN.into())
3668                    .child(buttons)
3669            };
3670            tester.pump_widget(boilerplate(
3671                theme.clone(),
3672                forbidden_region(
3673                    ToggleButtons::new(two_texts(), vec![false, true])
3674                        .mouse_cursor(SystemMouseCursors::TEXT)
3675                        .on_pressed(|_app, _index| {}),
3676                ),
3677            ));
3678
3679            let mut gesture = TestPointer::mouse(1, 0);
3680            let center = text_center(tester, "First child");
3681            tester.add_pointer(&mut gesture, center);
3682            tester.pump();
3683            assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
3684
3685            // Test default cursor
3686            tester.pump_widget(boilerplate(
3687                theme.clone(),
3688                forbidden_region(
3689                    ToggleButtons::new(two_texts(), vec![false, true])
3690                        .on_pressed(|_app, _index| {}),
3691                ),
3692            ));
3693            assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
3694
3695            // Test default cursor when disabled
3696            tester.pump_widget(boilerplate(
3697                theme,
3698                forbidden_region(ToggleButtons::new(two_texts(), vec![false, true])),
3699            ));
3700            assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
3701        });
3702    }
3703
3704    // 'ToggleButtons focus, hover, and highlight elevations are 0'
3705    #[test]
3706    fn focus_hover_and_highlight_elevations_are_zero() {
3707        test_widgets(|tester| {
3708            let theme = default_theme(tester);
3709            let focus_nodes: Vec<_> = (0..2)
3710                .map(|_| waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut()))
3711                .collect();
3712            tester.pump_widget(boilerplate(
3713                theme,
3714                ToggleButtons::new(texts(&["one", "two"]), vec![true, false])
3715                    .on_pressed(|_app, _index| {})
3716                    .focus_nodes(focus_nodes.iter().map(|node| node.erase()).collect()),
3717            ));
3718
3719            // `find.widgetWithText(Material, text).first`: the outermost Material above the text.
3720            let toggle_button_elevation = |tester: &WidgetTester, text: &str| {
3721                let text_element = find::text(text).evaluate(tester)[0];
3722                let material = find::by_type::<Material>()
3723                    .evaluate(tester)
3724                    .into_iter()
3725                    .find(|material| tester.ancestors(text_element).contains(material))
3726                    .expect("a Material above the text");
3727                tester.widget(material, |material: &Material| material.elevation)
3728            };
3729
3730            // Default toggle button elevation
3731            assert_eq!(toggle_button_elevation(tester, "one"), 0.0); // highlighted
3732            assert_eq!(toggle_button_elevation(tester, "two"), 0.0); // not highlighted
3733
3734            // Hovered button elevation
3735            let mut hover_gesture = TestPointer::mouse(1, 0);
3736            let one = text_center(tester, "one");
3737            tester.add_pointer(&mut hover_gesture, one);
3738            tester.move_to(&mut hover_gesture, one, false);
3739            tester.pump_and_settle();
3740            assert_eq!(toggle_button_elevation(tester, "one"), 0.0);
3741            let two = text_center(tester, "two");
3742            tester.move_to(&mut hover_gesture, two, false);
3743            tester.pump_and_settle();
3744            assert_eq!(toggle_button_elevation(tester, "two"), 0.0);
3745
3746            // Focused button elevation
3747            let has_focus =
3748                |tester: &WidgetTester, node: &waft_foundation::Ref<waft_widgets::FocusNode>| {
3749                    node.has_focus(&mut tester.cell.borrow_mut())
3750                };
3751            focus_nodes[0].request_focus(&mut tester.cell.borrow_mut(), None);
3752            tester.pump_and_settle();
3753            assert!(has_focus(tester, &focus_nodes[0]));
3754            assert!(!has_focus(tester, &focus_nodes[1]));
3755            assert_eq!(toggle_button_elevation(tester, "one"), 0.0);
3756            focus_nodes[1].request_focus(&mut tester.cell.borrow_mut(), None);
3757            tester.pump_and_settle();
3758            assert!(!has_focus(tester, &focus_nodes[0]));
3759            assert!(has_focus(tester, &focus_nodes[1]));
3760            assert_eq!(toggle_button_elevation(tester, "two"), 0.0);
3761        });
3762    }
3763
3764    // 'Toggle buttons height matches MaterialTapTargetSize.padded height'
3765    #[test]
3766    fn the_buttons_height_matches_the_padded_tap_target_height() {
3767        test_widgets(|tester| {
3768            let theme = default_theme(tester);
3769            tester.pump_widget(boilerplate(
3770                theme,
3771                ToggleButtons::new(three_icons(), vec![false; 3]).on_pressed(|_app, _index| {}),
3772            ));
3773
3774            for index in 0..3 {
3775                assert_eq!(button_rect(tester, index).height(), 48.0);
3776            }
3777        });
3778    }
3779
3780    // 'Toggle buttons constraints size does not affect minimum input padding', without its
3781    // semantics-tree expectation (its flags, actions and rects are not ported).
3782    #[test]
3783    fn constraints_size_sets_the_height_of_the_buttons() {
3784        test_widgets(|tester| {
3785            let theme = default_theme(tester);
3786            tester.pump_widget(boilerplate(
3787                theme,
3788                ToggleButtons::new(three_icons(), vec![false; 3])
3789                    .on_pressed(|_app, _index| {})
3790                    .constraints(BoxConstraints::tight_for(Some(86.0), Some(32.0))),
3791            ));
3792
3793            // Button's height is constrained to `32.0`.
3794            for index in 0..3 {
3795                assert_eq!(button_rect(tester, index).height(), 32.0);
3796            }
3797        });
3798    }
3799
3800    // 'ToggleButtons does not crash at zero area'
3801    #[test]
3802    fn toggle_buttons_do_not_crash_at_zero_area() {
3803        test_widgets(|tester| {
3804            let theme = default_theme(tester);
3805            tester.pump_widget(boilerplate(
3806                theme,
3807                Center::new()
3808                    .child(SizedBox::shrink().child(ToggleButtons::new(texts(&["X"]), vec![true]))),
3809            ));
3810
3811            assert_eq!(toggle_buttons_size(tester), Size::ZERO);
3812        });
3813    }
3814    /// `toggle_buttons_test.dart`, "ToggleButtons implements debugFillProperties". The colors
3815    /// print as the `Color` the port stores, not as Dart's `MaterialColor` swatch wrapper.
3816    #[test]
3817    fn a_toggle_buttons_describes_its_properties() {
3818        use waft_embedder::Color;
3819        use waft_foundation::DiagnosticPropertiesBuilder;
3820        use waft_painting::{Axis, VerticalDirection};
3821
3822        let green = Color::new(0xff4caf50);
3823        let pink = Color::new(0xffe91e63);
3824        let blue = Color::new(0xff2196f3);
3825        let yellow = Color::new(0xffffeb3b);
3826        let toggle_buttons = ToggleButtons::new(
3827            [
3828                Text::new("First child").into_widget(),
3829                Text::new("Second child").into_widget(),
3830                Text::new("Third child").into_widget(),
3831            ]
3832            .to_vec(),
3833            vec![false, true, false],
3834        )
3835        .on_pressed(|_app, _index| {})
3836        .direction(Axis::Vertical)
3837        .vertical_direction(VerticalDirection::Up)
3838        .border_width(3.0)
3839        .color(green)
3840        .selected_border_color(pink)
3841        .disabled_color(blue)
3842        .disabled_border_color(yellow)
3843        .border_radius(BorderRadius::circular(7.0));
3844        let cell = waft_foundation::AppCell::new();
3845        let app = cell.borrow();
3846        let description: Vec<String> = waft_widgets::testing::describe_properties(
3847            |properties: &mut DiagnosticPropertiesBuilder| {
3848                toggle_buttons.debug_fill_properties(&app, properties)
3849            },
3850        );
3851        assert_eq!(
3852            description,
3853            [
3854                "Buttons are enabled".to_string(),
3855                format!("color: {green}"),
3856                format!("disabledColor: {blue}"),
3857                format!("selectedBorderColor: {pink}"),
3858                format!("disabledBorderColor: {yellow}"),
3859                "borderRadius: BorderRadius.circular(7.0)".to_string(),
3860                "borderWidth: 3.0".to_string(),
3861                "direction: Axis.vertical".to_string(),
3862                "verticalDirection: VerticalDirection.up".to_string(),
3863            ]
3864        );
3865    }
3866}