Skip to main content

waft_material/
stepper.rs

1//! Flutter counterpart: material_ui's `stepper.dart`.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::rc::Rc;
6
7use waft_embedder::{
8    Brightness, Canvas, Clip, Color, FillRule, Offset, Paint, PathBuilder, Size, TextDirection,
9    valo,
10};
11use waft_foundation::{
12    App, DiagnosticPropertiesBuilder, Diagnosticable, DiagnosticsProperty, DoubleProperty, Handle,
13    Listener, ValueChanged,
14};
15use waft_painting::{
16    Alignment, BorderRadiusGeometry, BorderSide, BoxBorderRef, BoxDecoration, BoxShadow, BoxShape,
17    ColorProperty, EdgeInsets, EdgeInsetsDirectional, EdgeInsetsGeometry, GradientRef,
18    OutlinedBorderRef, RoundedRectangleBorder, TextStyle,
19};
20use waft_rendering::CustomPainter;
21use waft_widgets::{
22    Align, AnimatedContainer, AnimatedCrossFade, AnimatedDefaultTextStyle, AnimatedSize,
23    BuildContext, Center, ClipRect, ColoredBox, Column, CrossAxisAlignment, CustomPaint, Expanded,
24    GlobalKey, Icon, Interval, IntoWidget, KeyRef, ListView, MainAxisAlignment, MainAxisSize,
25    Padding, PositionedDirectional, Row, ScrollControllerRef, ScrollPositionAlignmentPolicy,
26    Scrollable, SizedBox, Stack, State, StateData, StatefulWidget, Text, Visibility, WidgetRef,
27    WidgetState, WidgetStateProperty, WidgetStatePropertyAll, WidgetStatePropertyRef,
28};
29
30use crate::button_style::ButtonStyle;
31use crate::colors::Colors;
32use crate::debug::{debug_check_has_material, debug_check_has_material_localizations};
33use crate::icons::Icons;
34use crate::ink_well::{InkResponse, InkWell};
35use crate::material::Material;
36use crate::material_localizations::MaterialLocalizations;
37use crate::text_button::TextButton;
38use crate::theme::{K_THEME_ANIMATION_DURATION, Theme};
39
40fn k_step_style() -> TextStyle {
41    TextStyle::new().font_size(12.0).color(Colors::WHITE)
42}
43fn k_error_light() -> Color {
44    Colors::RED.primary()
45}
46fn k_error_dark() -> Color {
47    Colors::RED.shade400()
48}
49const K_CIRCLE_ACTIVE_LIGHT: Color = Colors::WHITE;
50const K_CIRCLE_ACTIVE_DARK: Color = Colors::BLACK87;
51const K_DISABLED_LIGHT: Color = Colors::BLACK38;
52const K_DISABLED_DARK: Color = Colors::WHITE38;
53const K_STEP_SIZE: f64 = 24.0;
54/// `sqrt(3.0) / 2.0`.
55const K_TRIANGLE_SQRT: f64 = 0.866_025;
56const K_TRIANGLE_HEIGHT: f64 = K_STEP_SIZE * K_TRIANGLE_SQRT;
57const K_MAX_STEP_SIZE: f64 = 80.0;
58const K_DEFAULT_VERTICAL_CONTENT_PADDING: EdgeInsetsDirectional =
59    EdgeInsetsDirectional::only(60.0, 0.0, 24.0, 24.0);
60const K_DEFAULT_HORIZONTAL_CONTENT_PADDING: EdgeInsets = EdgeInsets::all(24.0);
61const K_DEFAULT_HEADER_PADDING: EdgeInsetsGeometry = EdgeInsetsGeometry::symmetric(0.0, 24.0);
62
63/// Dart's `<WidgetState>{if (isActive) WidgetState.selected else WidgetState.disabled}`.
64fn selected_or_disabled(is_active: bool) -> waft_widgets::WidgetStates {
65    let state = if is_active {
66        WidgetState::Selected
67    } else {
68        WidgetState::Disabled
69    };
70    [state].into_iter().collect()
71}
72
73/// The state of a [`Step`], which is used to control the style of the circle and text.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub enum StepState {
76    /// A step that displays its index in its circle.
77    Indexed,
78    /// A step that displays a pencil icon in its circle.
79    Editing,
80    /// A step that displays a tick icon in its circle.
81    Complete,
82    /// A step that is disabled and does not react to taps.
83    Disabled,
84    /// A step that is currently having an error.
85    Error,
86}
87
88/// Defines the [`Stepper`]'s main axis.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum StepperType {
91    /// A vertical layout of the steps with their content in between the titles.
92    Vertical,
93    /// A horizontal layout of the steps with their content below the titles.
94    Horizontal,
95}
96
97/// All the information necessary to build a [`Stepper`]'s forward and backward controls for a
98/// given step.
99///
100/// Used by [`Stepper::controls_builder`].
101#[derive(Clone, Debug)]
102pub struct ControlsDetails {
103    /// Index that is active for the surrounding [`Stepper`].
104    pub current_step: usize,
105    /// Index of the step for which these controls are being built.
106    pub step_index: usize,
107    /// The callback called when the 'continue' button is tapped.
108    pub on_step_continue: Option<Listener>,
109    /// The callback called when the 'cancel' button is tapped.
110    pub on_step_cancel: Option<Listener>,
111}
112
113impl ControlsDetails {
114    /// Whether the indicated step is also the current active step.
115    pub fn is_active(&self) -> bool {
116        self.current_step == self.step_index
117    }
118}
119
120/// A builder that creates the controls from their [`ControlsDetails`].
121pub type ControlsWidgetBuilder = Rc<dyn Fn(&mut App, BuildContext, ControlsDetails) -> WidgetRef>;
122
123/// A builder that creates the icon for the step at the index, given its state.
124pub type StepIconBuilder = Rc<dyn Fn(usize, StepState) -> Option<WidgetRef>>;
125
126/// A material step used in [`Stepper`]. The step can have a title and subtitle, an icon within
127/// its circle, some content and a state that governs its styling.
128#[derive(Clone)]
129pub struct Step {
130    /// The title of the step that typically describes it.
131    pub title: WidgetRef,
132    /// The subtitle of the step that appears below the title.
133    pub subtitle: Option<WidgetRef>,
134    /// The content of the step that appears below the title and subtitle.
135    pub content: WidgetRef,
136    /// The state of the step which determines the styling of its components and whether steps
137    /// are interactive.
138    pub state: StepState,
139    /// Whether or not the step is active. The flag only influences styling.
140    pub is_active: bool,
141    /// Only for [`StepperType::Horizontal`], an optional widget that appears under the title.
142    pub label: Option<WidgetRef>,
143    /// Optional overrides for the step's default visual configuration.
144    pub step_style: Option<StepStyle>,
145}
146
147impl Step {
148    /// Creates a step for a [`Stepper`]; Dart's optional named arguments are the setters.
149    #[cfg_attr(debug_assertions, track_caller)]
150    pub fn new<T, C>(title: impl IntoWidget<T>, content: impl IntoWidget<C>) -> Step {
151        Step {
152            title: title.into_widget(),
153            subtitle: None,
154            content: content.into_widget(),
155            state: StepState::Indexed,
156            is_active: false,
157            label: None,
158            step_style: None,
159        }
160    }
161
162    /// Dart `Step(subtitle:)`.
163    #[cfg_attr(debug_assertions, track_caller)]
164    pub fn subtitle<K>(mut self, subtitle: impl IntoWidget<K>) -> Step {
165        self.subtitle = Some(subtitle.into_widget());
166        self
167    }
168
169    /// Dart `Step(state:)`.
170    pub fn state(mut self, state: StepState) -> Step {
171        self.state = state;
172        self
173    }
174
175    /// Dart `Step(isActive:)`.
176    pub fn is_active(mut self, is_active: bool) -> Step {
177        self.is_active = is_active;
178        self
179    }
180
181    /// Dart `Step(label:)`.
182    #[cfg_attr(debug_assertions, track_caller)]
183    pub fn label<K>(mut self, label: impl IntoWidget<K>) -> Step {
184        self.label = Some(label.into_widget());
185        self
186    }
187
188    /// Dart `Step(stepStyle:)`.
189    pub fn step_style(mut self, step_style: StepStyle) -> Step {
190        self.step_style = Some(step_style);
191        self
192    }
193}
194
195impl fmt::Debug for Step {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        f.debug_struct("Step")
198            .field("state", &self.state)
199            .field("is_active", &self.is_active)
200            .finish_non_exhaustive()
201    }
202}
203
204/// A material stepper widget that displays progress through a sequence of steps.
205///
206/// Steppers are particularly useful in the case of forms where one step requires the
207/// completion of another one, or where multiple steps need to be completed in order to submit
208/// the whole form.
209///
210/// The widget is a flexible wrapper. A parent class should pass [`current_step`](Self::current_step)
211/// to this widget based on some logic triggered by the three callbacks that it provides.
212#[derive(Clone)]
213pub struct Stepper {
214    pub key: Option<KeyRef>,
215    /// The steps of the stepper whose titles, subtitles and icons always get shown.
216    ///
217    /// The length of [`steps`](Self::steps) must not change.
218    pub steps: Vec<Step>,
219    /// How the stepper's scroll view should respond to user input.
220    pub physics: Option<waft_widgets::ScrollPhysicsRef>,
221    /// An object that can be used to control the position to which the scroll view is scrolled.
222    pub controller: Option<ScrollControllerRef>,
223    /// The type of stepper that determines the layout.
224    pub r#type: StepperType,
225    /// The index into [`steps`](Self::steps) of the current step whose content is displayed.
226    pub current_step: usize,
227    /// The callback called when a step is tapped, with its index passed as an argument.
228    pub on_step_tapped: Option<ValueChanged<usize>>,
229    /// The callback called when the 'continue' button is tapped.
230    pub on_step_continue: Option<Listener>,
231    /// The callback called when the 'cancel' button is tapped.
232    pub on_step_cancel: Option<Listener>,
233    /// The callback for creating custom controls.
234    pub controls_builder: Option<ControlsWidgetBuilder>,
235    /// The elevation of this stepper's material when [`r#type`](Self::r#type) is
236    /// [`StepperType::Horizontal`].
237    pub elevation: Option<f64>,
238    /// Custom margin on a vertical stepper.
239    pub margin: Option<EdgeInsetsGeometry>,
240    /// Customize the connected lines' colors.
241    ///
242    /// Resolves in the following states: [`WidgetState::Selected`] and
243    /// [`WidgetState::Disabled`].
244    pub connector_color: Option<WidgetStatePropertyRef<Color>>,
245    /// The thickness of the connecting lines.
246    pub connector_thickness: Option<f64>,
247    /// Callback for creating custom icons for the steps.
248    pub step_icon_builder: Option<StepIconBuilder>,
249    /// Overrides the default step icon size height.
250    pub step_icon_height: Option<f64>,
251    /// Overrides the default step icon size width.
252    pub step_icon_width: Option<f64>,
253    /// Overrides the default step icon margin.
254    pub step_icon_margin: Option<EdgeInsets>,
255    /// The [`Step::content`] will be clipped to this [`Clip`] type.
256    pub clip_behavior: Clip,
257    /// The padding around the header row in both [`StepperType::Vertical`] and
258    /// [`StepperType::Horizontal`] steppers.
259    pub header_padding: Option<EdgeInsetsGeometry>,
260    /// The padding around the content area in both stepper types.
261    pub content_padding: Option<EdgeInsetsGeometry>,
262}
263
264impl Stepper {
265    /// Creates a stepper from a list of steps; Dart's optional named arguments are the setters.
266    pub fn new(steps: Vec<Step>) -> Stepper {
267        debug_assert!(!steps.is_empty(), "current_step must name one of the steps");
268        Stepper {
269            key: None,
270            steps,
271            physics: None,
272            controller: None,
273            r#type: StepperType::Vertical,
274            current_step: 0,
275            on_step_tapped: None,
276            on_step_continue: None,
277            on_step_cancel: None,
278            controls_builder: None,
279            elevation: None,
280            margin: None,
281            connector_color: None,
282            connector_thickness: None,
283            step_icon_builder: None,
284            step_icon_height: None,
285            step_icon_width: None,
286            step_icon_margin: None,
287            clip_behavior: Clip::None,
288            header_padding: None,
289            content_padding: None,
290        }
291    }
292
293    /// Dart `Stepper(key:)`.
294    pub fn key(mut self, key: KeyRef) -> Stepper {
295        self.key = Some(key);
296        self
297    }
298
299    /// Dart `Stepper(physics:)`.
300    pub fn physics(mut self, physics: waft_widgets::ScrollPhysicsRef) -> Stepper {
301        self.physics = Some(physics);
302        self
303    }
304
305    /// Dart `Stepper(controller:)`.
306    pub fn controller(mut self, controller: ScrollControllerRef) -> Stepper {
307        self.controller = Some(controller);
308        self
309    }
310
311    /// Dart `Stepper(type:)`.
312    pub fn r#type(mut self, r#type: StepperType) -> Stepper {
313        self.r#type = r#type;
314        self
315    }
316
317    /// Dart `Stepper(currentStep:)`.
318    pub fn current_step(mut self, current_step: usize) -> Stepper {
319        debug_assert!(
320            current_step < self.steps.len(),
321            "current_step must name one of the steps"
322        );
323        self.current_step = current_step;
324        self
325    }
326
327    /// Dart `Stepper(onStepTapped:)`.
328    pub fn on_step_tapped(mut self, on_step_tapped: ValueChanged<usize>) -> Stepper {
329        self.on_step_tapped = Some(on_step_tapped);
330        self
331    }
332
333    /// Dart `Stepper(onStepContinue:)`.
334    pub fn on_step_continue(mut self, on_step_continue: Listener) -> Stepper {
335        self.on_step_continue = Some(on_step_continue);
336        self
337    }
338
339    /// Dart `Stepper(onStepCancel:)`.
340    pub fn on_step_cancel(mut self, on_step_cancel: Listener) -> Stepper {
341        self.on_step_cancel = Some(on_step_cancel);
342        self
343    }
344
345    /// Dart `Stepper(controlsBuilder:)`.
346    pub fn controls_builder(mut self, controls_builder: ControlsWidgetBuilder) -> Stepper {
347        self.controls_builder = Some(controls_builder);
348        self
349    }
350
351    /// Dart `Stepper(elevation:)`.
352    pub fn elevation(mut self, elevation: f64) -> Stepper {
353        self.elevation = Some(elevation);
354        self
355    }
356
357    /// Dart `Stepper(margin:)`.
358    pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> Stepper {
359        self.margin = Some(margin.into());
360        self
361    }
362
363    /// Dart `Stepper(connectorColor:)`.
364    pub fn connector_color(mut self, connector_color: WidgetStatePropertyRef<Color>) -> Stepper {
365        self.connector_color = Some(connector_color);
366        self
367    }
368
369    /// Dart `Stepper(connectorThickness:)`.
370    pub fn connector_thickness(mut self, connector_thickness: f64) -> Stepper {
371        self.connector_thickness = Some(connector_thickness);
372        self
373    }
374
375    /// Dart `Stepper(stepIconBuilder:)`.
376    pub fn step_icon_builder(mut self, step_icon_builder: StepIconBuilder) -> Stepper {
377        self.step_icon_builder = Some(step_icon_builder);
378        self
379    }
380
381    /// Dart `Stepper(stepIconHeight:)`.
382    pub fn step_icon_height(mut self, step_icon_height: f64) -> Stepper {
383        debug_assert!(
384            (K_STEP_SIZE..=K_MAX_STEP_SIZE).contains(&step_icon_height),
385            "step_icon_height must be greater than {K_STEP_SIZE} and less or equal to \
386             {K_MAX_STEP_SIZE}"
387        );
388        self.step_icon_height = Some(step_icon_height);
389        self
390    }
391
392    /// Dart `Stepper(stepIconWidth:)`.
393    pub fn step_icon_width(mut self, step_icon_width: f64) -> Stepper {
394        debug_assert!(
395            (K_STEP_SIZE..=K_MAX_STEP_SIZE).contains(&step_icon_width),
396            "step_icon_width must be greater than {K_STEP_SIZE} and less or equal to \
397             {K_MAX_STEP_SIZE}"
398        );
399        self.step_icon_width = Some(step_icon_width);
400        self
401    }
402
403    /// Dart `Stepper(stepIconMargin:)`.
404    pub fn step_icon_margin(mut self, step_icon_margin: EdgeInsets) -> Stepper {
405        self.step_icon_margin = Some(step_icon_margin);
406        self
407    }
408
409    /// Dart `Stepper(clipBehavior:)`.
410    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Stepper {
411        self.clip_behavior = clip_behavior;
412        self
413    }
414
415    /// Dart `Stepper(headerPadding:)`.
416    pub fn header_padding(mut self, header_padding: impl Into<EdgeInsetsGeometry>) -> Stepper {
417        self.header_padding = Some(header_padding.into());
418        self
419    }
420
421    /// Dart `Stepper(contentPadding:)`.
422    pub fn content_padding(mut self, content_padding: impl Into<EdgeInsetsGeometry>) -> Stepper {
423        self.content_padding = Some(content_padding.into());
424        self
425    }
426}
427
428impl fmt::Debug for Stepper {
429    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430        f.debug_struct("Stepper")
431            .field("current_step", &self.current_step)
432            .field("type", &self.r#type)
433            .finish_non_exhaustive()
434    }
435}
436
437impl StatefulWidget for Stepper {
438    type State = StepperState;
439
440    fn key(&self) -> Option<&KeyRef> {
441        self.key.as_ref()
442    }
443
444    fn create_state(&self) -> StepperState {
445        StepperState {
446            state: StateData::new(),
447            keys: Vec::new(),
448            old_states: HashMap::new(),
449        }
450    }
451}
452
453/// Dart's `_StepperState`.
454pub struct StepperState {
455    state: StateData<Stepper>,
456    keys: Vec<GlobalKey>,
457    old_states: HashMap<usize, StepState>,
458}
459
460impl StepperState {
461    /// The padding around the header row.
462    fn effective_header_padding(self: Handle<Self>, stepper: &Stepper) -> EdgeInsetsGeometry {
463        stepper.header_padding.unwrap_or(K_DEFAULT_HEADER_PADDING)
464    }
465
466    /// How tall the horizontal header is, as a multiple of [`Stepper::step_icon_height`].
467    fn height_factor(self: Handle<Self>, stepper: &Stepper) -> f64 {
468        if self.is_label(stepper) && stepper.step_icon_height.is_some() {
469            2.5
470        } else {
471            2.0
472        }
473    }
474
475    fn is_first(self: Handle<Self>, index: usize) -> bool {
476        index == 0
477    }
478
479    fn is_last(self: Handle<Self>, stepper: &Stepper, index: usize) -> bool {
480        stepper.steps.len() - 1 == index
481    }
482
483    fn is_current(self: Handle<Self>, stepper: &Stepper, index: usize) -> bool {
484        stepper.current_step == index
485    }
486
487    fn is_dark(self: Handle<Self>, app: &mut App, context: BuildContext) -> bool {
488        Theme::brightness_of(app, context) == Brightness::Dark
489    }
490
491    fn is_label(self: Handle<Self>, stepper: &Stepper) -> bool {
492        stepper.steps.iter().any(|step| step.label.is_some())
493    }
494
495    fn step_style(self: Handle<Self>, stepper: &Stepper, index: usize) -> Option<StepStyle> {
496        stepper.steps[index].step_style.clone()
497    }
498
499    fn connector_color(
500        self: Handle<Self>,
501        app: &mut App,
502        context: BuildContext,
503        is_active: bool,
504    ) -> Color {
505        let color_scheme = Theme::of(app, context).color_scheme.clone();
506        let states = selected_or_disabled(is_active);
507        let resolved_connector_color = self
508            .widget(app)
509            .connector_color
510            .as_ref()
511            .map(|connector_color| connector_color.resolve(&states));
512        resolved_connector_color.unwrap_or_else(|| {
513            if is_active {
514                color_scheme.primary()
515            } else {
516                Colors::GREY.shade400()
517            }
518        })
519    }
520
521    fn build_line(
522        self: Handle<Self>,
523        app: &mut App,
524        context: BuildContext,
525        stepper: &Stepper,
526        visible: bool,
527        is_active: bool,
528    ) -> WidgetRef {
529        let color = self.connector_color(app, context, is_active);
530        let width = if visible {
531            stepper.connector_thickness.unwrap_or(1.0)
532        } else {
533            0.0
534        };
535        ColoredBox::new(color)
536            .child(SizedBox::new().width(width).height(16.0))
537            .into_widget()
538    }
539
540    fn build_circle_child(
541        self: Handle<Self>,
542        app: &mut App,
543        context: BuildContext,
544        index: usize,
545        old_state: bool,
546    ) -> WidgetRef {
547        let stepper = self.widget(app).clone();
548        let state = if old_state {
549            app.get(self).old_states[&index]
550        } else {
551            stepper.steps[index].state
552        };
553        if let Some(icon) = stepper
554            .step_icon_builder
555            .as_ref()
556            .and_then(|builder| builder(index, state))
557        {
558            return icon;
559        }
560        let is_dark_active = self.is_dark(app, context) && stepper.steps[index].is_active;
561        let icon_color = if is_dark_active {
562            K_CIRCLE_ACTIVE_DARK
563        } else {
564            K_CIRCLE_ACTIVE_LIGHT
565        };
566        let text_style = self
567            .step_style(&stepper, index)
568            .and_then(|step_style| step_style.index_style.clone())
569            .unwrap_or_else(|| {
570                if is_dark_active {
571                    k_step_style().copy_with().color(Colors::BLACK87)
572                } else {
573                    k_step_style()
574                }
575            });
576
577        match state {
578            StepState::Indexed | StepState::Disabled => Text::new(format!("{}", index + 1))
579                .style(text_style)
580                .into_widget(),
581            StepState::Editing => Icon::new(Some(Icons::edit()))
582                .color(icon_color)
583                .size(18.0)
584                .into_widget(),
585            StepState::Complete => Icon::new(Some(Icons::check()))
586                .color(icon_color)
587                .size(18.0)
588                .into_widget(),
589            StepState::Error => Center::new()
590                .child(Text::new("!").style(k_step_style()))
591                .into_widget(),
592        }
593    }
594
595    #[expect(
596        deprecated,
597        reason = "Dart's `_circleColor` reads the deprecated `ColorScheme.background` and \
598                  `Color.withOpacity`"
599    )]
600    fn circle_color(
601        self: Handle<Self>,
602        app: &mut App,
603        context: BuildContext,
604        stepper: &Stepper,
605        index: usize,
606    ) -> Color {
607        let is_active = stepper.steps[index].is_active;
608        let color_scheme = Theme::of(app, context).color_scheme.clone();
609        let states = selected_or_disabled(is_active);
610        if let Some(resolved_connector_color) = stepper
611            .connector_color
612            .as_ref()
613            .map(|connector_color| connector_color.resolve(&states))
614        {
615            return resolved_connector_color;
616        }
617        if !self.is_dark(app, context) {
618            if is_active {
619                color_scheme.primary()
620            } else {
621                color_scheme.on_surface().with_opacity(0.38)
622            }
623        } else if is_active {
624            color_scheme.secondary()
625        } else {
626            color_scheme.background()
627        }
628    }
629
630    fn build_circle(
631        self: Handle<Self>,
632        app: &mut App,
633        context: BuildContext,
634        index: usize,
635        old_state: bool,
636    ) -> WidgetRef {
637        let stepper = self.widget(app).clone();
638        let step_style = self.step_style(&stepper, index);
639        let color = step_style
640            .as_ref()
641            .and_then(|step_style| step_style.color)
642            .unwrap_or_else(|| self.circle_color(app, context, &stepper, index));
643        let mut decoration = BoxDecoration::new().color(color).shape(BoxShape::Circle);
644        if let Some(border) = step_style
645            .as_ref()
646            .and_then(|step_style| step_style.border.clone())
647        {
648            decoration = decoration.border(border);
649        }
650        if let Some(box_shadow) = step_style
651            .as_ref()
652            .and_then(|step_style| step_style.box_shadow)
653        {
654            decoration = decoration.box_shadow(vec![box_shadow]);
655        }
656        if let Some(gradient) = step_style
657            .as_ref()
658            .and_then(|step_style| step_style.gradient.clone())
659        {
660            decoration = decoration.gradient(gradient);
661        }
662        let circle_child = self.build_circle_child(
663            app,
664            context,
665            index,
666            old_state && stepper.steps[index].state == StepState::Error,
667        );
668        Padding::new(
669            stepper
670                .step_icon_margin
671                .unwrap_or(EdgeInsets::symmetric(8.0, 0.0)),
672        )
673        .child(
674            SizedBox::new()
675                .width(stepper.step_icon_width.unwrap_or(K_STEP_SIZE))
676                .height(stepper.step_icon_height.unwrap_or(K_STEP_SIZE))
677                .child(
678                    AnimatedContainer::new(K_THEME_ANIMATION_DURATION)
679                        .curve(waft_animation::Curves::fast_out_slow_in())
680                        .decoration(decoration)
681                        .child(Center::new().child(circle_child)),
682                ),
683        )
684        .into_widget()
685    }
686
687    fn build_triangle(
688        self: Handle<Self>,
689        app: &mut App,
690        context: BuildContext,
691        index: usize,
692        old_state: bool,
693    ) -> WidgetRef {
694        let stepper = self.widget(app).clone();
695        let color = self
696            .step_style(&stepper, index)
697            .and_then(|step_style| step_style.error_color)
698            .unwrap_or_else(|| {
699                if self.is_dark(app, context) {
700                    k_error_dark()
701                } else {
702                    k_error_light()
703                }
704            });
705        let triangle_height = stepper
706            .step_icon_height
707            .map(|height| height * K_TRIANGLE_SQRT)
708            .unwrap_or(K_TRIANGLE_HEIGHT);
709        let circle_child = self.build_circle_child(
710            app,
711            context,
712            index,
713            old_state && stepper.steps[index].state != StepState::Error,
714        );
715        Padding::new(
716            stepper
717                .step_icon_margin
718                .unwrap_or(EdgeInsets::symmetric(8.0, 0.0)),
719        )
720        .child(
721            SizedBox::new()
722                .width(stepper.step_icon_width.unwrap_or(K_STEP_SIZE))
723                .height(stepper.step_icon_height.unwrap_or(K_STEP_SIZE))
724                .child(
725                    Center::new().child(
726                        SizedBox::new()
727                            .width(stepper.step_icon_width.unwrap_or(K_STEP_SIZE))
728                            .height(triangle_height)
729                            .child(
730                                CustomPaint::new().painter(TrianglePainter { color }).child(
731                                    Align::new()
732                                        // 0.8 looks better than the geometrical 0.33.
733                                        .alignment(Alignment::new(0.0, 0.8).into())
734                                        .child(circle_child),
735                                ),
736                            ),
737                    ),
738                ),
739        )
740        .into_widget()
741    }
742
743    fn build_icon(
744        self: Handle<Self>,
745        app: &mut App,
746        context: BuildContext,
747        index: usize,
748    ) -> WidgetRef {
749        let stepper = self.widget(app).clone();
750        let state = stepper.steps[index].state;
751        let old_state = app.get(self).old_states[&index];
752        if state != old_state {
753            AnimatedCrossFade::new(
754                self.build_circle(app, context, index, true),
755                self.build_triangle(app, context, index, true),
756                if state == StepState::Error {
757                    waft_widgets::CrossFadeState::ShowSecond
758                } else {
759                    waft_widgets::CrossFadeState::ShowFirst
760                },
761                K_THEME_ANIMATION_DURATION,
762            )
763            .first_curve(Rc::new(Interval::new(
764                0.0,
765                0.6,
766                waft_animation::Curves::fast_out_slow_in(),
767            )))
768            .second_curve(Rc::new(Interval::new(
769                0.4,
770                1.0,
771                waft_animation::Curves::fast_out_slow_in(),
772            )))
773            .size_curve(waft_animation::Curves::fast_out_slow_in())
774            .into_widget()
775        } else if state != StepState::Error {
776            self.build_circle(app, context, index, false)
777        } else {
778            self.build_triangle(app, context, index, false)
779        }
780    }
781
782    fn title_style(
783        self: Handle<Self>,
784        app: &mut App,
785        context: BuildContext,
786        index: usize,
787    ) -> TextStyle {
788        let stepper = self.widget(app).clone();
789        let text_theme = Theme::of(app, context).text_theme.clone();
790        let body_large = text_theme
791            .body_large
792            .clone()
793            .expect("the text theme has a body large");
794        match stepper.steps[index].state {
795            StepState::Indexed | StepState::Editing | StepState::Complete => body_large,
796            StepState::Disabled => body_large.copy_with().color(if self.is_dark(app, context) {
797                K_DISABLED_DARK
798            } else {
799                K_DISABLED_LIGHT
800            }),
801            StepState::Error => body_large.copy_with().color(if self.is_dark(app, context) {
802                k_error_dark()
803            } else {
804                k_error_light()
805            }),
806        }
807    }
808
809    fn subtitle_style(
810        self: Handle<Self>,
811        app: &mut App,
812        context: BuildContext,
813        index: usize,
814    ) -> TextStyle {
815        let stepper = self.widget(app).clone();
816        let text_theme = Theme::of(app, context).text_theme.clone();
817        let body_small = text_theme
818            .body_small
819            .clone()
820            .expect("the text theme has a body small");
821        match stepper.steps[index].state {
822            StepState::Indexed | StepState::Editing | StepState::Complete => body_small,
823            StepState::Disabled => body_small.copy_with().color(if self.is_dark(app, context) {
824                K_DISABLED_DARK
825            } else {
826                K_DISABLED_LIGHT
827            }),
828            StepState::Error => body_small.copy_with().color(if self.is_dark(app, context) {
829                k_error_dark()
830            } else {
831                k_error_light()
832            }),
833        }
834    }
835
836    fn label_style(
837        self: Handle<Self>,
838        app: &mut App,
839        context: BuildContext,
840        index: usize,
841    ) -> TextStyle {
842        self.title_style(app, context, index)
843    }
844
845    fn build_header_text(
846        self: Handle<Self>,
847        app: &mut App,
848        context: BuildContext,
849        index: usize,
850    ) -> WidgetRef {
851        let stepper = self.widget(app).clone();
852        let title_style = self.title_style(app, context, index);
853        let mut children = vec![
854            AnimatedDefaultTextStyle::new(
855                stepper.steps[index].title.clone(),
856                title_style,
857                K_THEME_ANIMATION_DURATION,
858            )
859            .curve(waft_animation::Curves::fast_out_slow_in())
860            .into_widget(),
861        ];
862        if let Some(subtitle) = stepper.steps[index].subtitle.clone() {
863            let style = self.subtitle_style(app, context, index);
864            children.push(
865                Padding::new(EdgeInsets::only(0.0, 2.0, 0.0, 0.0))
866                    .child(
867                        AnimatedDefaultTextStyle::new(subtitle, style, K_THEME_ANIMATION_DURATION)
868                            .curve(waft_animation::Curves::fast_out_slow_in()),
869                    )
870                    .into_widget(),
871            );
872        }
873        Column::new()
874            .cross_axis_alignment(CrossAxisAlignment::Start)
875            .main_axis_size(MainAxisSize::Min)
876            .children(children)
877            .into_widget()
878    }
879
880    fn build_label_text(
881        self: Handle<Self>,
882        app: &mut App,
883        context: BuildContext,
884        index: usize,
885    ) -> WidgetRef {
886        let stepper = self.widget(app).clone();
887        match stepper.steps[index].label.clone() {
888            Some(label) => {
889                let style = self.label_style(app, context, index);
890                AnimatedDefaultTextStyle::new(label, style, K_THEME_ANIMATION_DURATION)
891                    .into_widget()
892            }
893            None => SizedBox::shrink().into_widget(),
894        }
895    }
896
897    fn build_vertical_header(
898        self: Handle<Self>,
899        app: &mut App,
900        context: BuildContext,
901        index: usize,
902    ) -> WidgetRef {
903        let stepper = self.widget(app).clone();
904        let is_active = stepper.steps[index].is_active;
905        let is_previous_active = index > 0 && stepper.steps[index - 1].is_active;
906        let padding = self.effective_header_padding(&stepper);
907        let first_line = self.build_line(
908            app,
909            context,
910            &stepper,
911            !self.is_first(index),
912            is_previous_active,
913        );
914        let icon = self.build_icon(app, context, index);
915        let last_line = self.build_line(
916            app,
917            context,
918            &stepper,
919            !self.is_last(&stepper, index),
920            is_active,
921        );
922        let header_text = self.build_header_text(app, context, index);
923        Padding::new(padding)
924            .child(Row::new().children(vec![
925                    Column::new()
926                        .children(vec![first_line, icon, last_line])
927                        .into_widget(),
928                    Expanded::new(
929                        Padding::new(EdgeInsetsDirectional::only(12.0, 0.0, 0.0, 0.0))
930                            .child(header_text),
931                    )
932                    .into_widget(),
933                ]))
934            .into_widget()
935    }
936
937    fn build_vertical_controls(
938        self: Handle<Self>,
939        app: &mut App,
940        context: BuildContext,
941        step_index: usize,
942    ) -> WidgetRef {
943        let stepper = self.widget(app).clone();
944        if let Some(controls_builder) = stepper.controls_builder.clone() {
945            return controls_builder(
946                app,
947                context,
948                ControlsDetails {
949                    current_step: stepper.current_step,
950                    on_step_continue: stepper.on_step_continue.clone(),
951                    on_step_cancel: stepper.on_step_cancel.clone(),
952                    step_index,
953                },
954            );
955        }
956
957        let is_dark = self.is_dark(app, context);
958        let cancel_color = match Theme::brightness_of(app, context) {
959            Brightness::Light => Colors::BLACK54,
960            Brightness::Dark => Colors::WHITE70,
961        };
962
963        let theme_data = Theme::of(app, context);
964        let color_scheme = theme_data.color_scheme.clone();
965        let localizations = <dyn MaterialLocalizations>::of(app, context);
966
967        let button_shape = OutlinedBorderRef::new(RoundedRectangleBorder::new(
968            BorderSide::NONE,
969            BorderRadiusGeometry::all(waft_embedder::Radius::circular(2.0)),
970        ));
971        let button_padding = EdgeInsetsGeometry::symmetric(0.0, 16.0);
972
973        let foreground_color_scheme = color_scheme.clone();
974        let continue_foreground_color: WidgetStatePropertyRef<Option<Color>> =
975            <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
976                if states.contains(&WidgetState::Disabled) {
977                    None
978                } else if is_dark {
979                    Some(foreground_color_scheme.on_surface())
980                } else {
981                    Some(foreground_color_scheme.on_primary())
982                }
983            });
984        let continue_background_color: WidgetStatePropertyRef<Option<Color>> =
985            <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
986                if is_dark || states.contains(&WidgetState::Disabled) {
987                    None
988                } else {
989                    Some(color_scheme.primary())
990                }
991            });
992        let continue_style = ButtonStyle::new()
993            .foreground_color(continue_foreground_color)
994            .background_color(continue_background_color)
995            .padding(Rc::new(WidgetStatePropertyAll::new(Some(button_padding))))
996            .shape(Rc::new(WidgetStatePropertyAll::new(Some(
997                button_shape.clone(),
998            ))));
999
1000        let continue_label = if theme_data.use_material3 {
1001            localizations.continue_button_label()
1002        } else {
1003            localizations.continue_button_label().to_uppercase()
1004        };
1005        let cancel_label = if theme_data.use_material3 {
1006            localizations.cancel_button_label()
1007        } else {
1008            localizations.cancel_button_label().to_uppercase()
1009        };
1010        let cancel_style = TextButton::style_from()
1011            .foreground_color(cancel_color)
1012            .padding(button_padding)
1013            .shape(button_shape)
1014            .build();
1015
1016        let continue_button = TextButton::new(
1017            stepper.on_step_continue.clone(),
1018            Some(Text::new(continue_label)),
1019        )
1020        .style(continue_style);
1021        let cancel_button = TextButton::new(
1022            stepper.on_step_cancel.clone(),
1023            Some(Text::new(cancel_label)),
1024        )
1025        .style(cancel_style);
1026
1027        Padding::new(EdgeInsets::only(0.0, 16.0, 0.0, 0.0))
1028            .child(SizedBox::new().height(48.0).child(Row::new().children(vec![
1029                        continue_button.into_widget(),
1030                        Padding::new(EdgeInsetsDirectional::only(8.0, 0.0, 0.0, 0.0))
1031                            .child(cancel_button)
1032                            .into_widget(),
1033                    ])))
1034            .into_widget()
1035    }
1036
1037    fn build_vertical_body(
1038        self: Handle<Self>,
1039        app: &mut App,
1040        context: BuildContext,
1041        index: usize,
1042    ) -> WidgetRef {
1043        let stepper = self.widget(app).clone();
1044        let step_icon_margin = stepper.step_icon_margin;
1045        let margin_left =
1046            step_icon_margin.map(|margin| margin.resolve(Some(TextDirection::Ltr)).left);
1047        let margin_right =
1048            step_icon_margin.map(|margin| margin.resolve(Some(TextDirection::Ltr)).right);
1049        let additional_margin_left = margin_left.map(|margin_left| margin_left / 2.0);
1050        let additional_margin_right = margin_right.map(|margin_right| margin_right / 2.0);
1051        // Adjust vertical content padding to align with step icon when stepIconMargin is set.
1052        let effective_vertical_content_padding = stepper
1053            .content_padding
1054            .unwrap_or(K_DEFAULT_VERTICAL_CONTENT_PADDING.into())
1055            .add(EdgeInsetsDirectional::only(margin_left.unwrap_or(0.0), 0.0, 0.0, 0.0).into());
1056
1057        let connector_width = if !self.is_last(&stepper, index) {
1058            stepper.connector_thickness.unwrap_or(1.0)
1059        } else {
1060            0.0
1061        };
1062        let connector_color = self.connector_color(app, context, stepper.steps[index].is_active);
1063        let line = PositionedDirectional::new(
1064            Center::new().child(
1065                SizedBox::new()
1066                    .width(connector_width)
1067                    .height(f64::INFINITY)
1068                    .child(ColoredBox::new(connector_color)),
1069            ),
1070        )
1071        // When use margin affects the left or right side of the child, we need to add half of the
1072        // margin to the start or end of the child respectively to get the correct positioning.
1073        .start(
1074            24.0 + additional_margin_left.unwrap_or(0.0) + additional_margin_right.unwrap_or(0.0),
1075        )
1076        .top(0.0)
1077        .bottom(0.0)
1078        .width(stepper.step_icon_width.unwrap_or(K_STEP_SIZE));
1079
1080        let content = stepper.steps[index].content.clone();
1081        let controls = self.build_vertical_controls(app, context, index);
1082        let clip_behavior = stepper.clip_behavior;
1083        let is_current = self.is_current(&stepper, index);
1084        let body = AnimatedCrossFade::new(
1085            SizedBox::new().width(f64::INFINITY).height(0.0),
1086            Padding::new(effective_vertical_content_padding).child(Column::new().children(vec![
1087                    ClipRect::new()
1088                        .clip_behavior(clip_behavior)
1089                        .child(content)
1090                        .into_widget(),
1091                    controls,
1092                ])),
1093            if is_current {
1094                waft_widgets::CrossFadeState::ShowSecond
1095            } else {
1096                waft_widgets::CrossFadeState::ShowFirst
1097            },
1098            K_THEME_ANIMATION_DURATION,
1099        )
1100        .first_curve(Rc::new(Interval::new(
1101            0.0,
1102            0.6,
1103            waft_animation::Curves::fast_out_slow_in(),
1104        )))
1105        .second_curve(Rc::new(Interval::new(
1106            0.4,
1107            1.0,
1108            waft_animation::Curves::fast_out_slow_in(),
1109        )))
1110        .size_curve(waft_animation::Curves::fast_out_slow_in())
1111        .into_widget();
1112
1113        Stack::new()
1114            .children(vec![line.into_widget(), body])
1115            .into_widget()
1116    }
1117
1118    fn build_vertical(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1119        let stepper = self.widget(app).clone();
1120        let keys = app.get(self).keys.clone();
1121        let children: Vec<WidgetRef> = (0..stepper.steps.len())
1122            .map(|index| {
1123                let key = keys[index].clone();
1124                let is_disabled = stepper.steps[index].state == StepState::Disabled;
1125                let on_step_tapped = stepper.on_step_tapped.clone();
1126                let tap_key = key.clone();
1127                let mut ink_well = InkWell::new().can_request_focus(!is_disabled);
1128                if !is_disabled {
1129                    ink_well = ink_well.on_tap(Listener::new(move |app: &mut App| {
1130                        // In the vertical case we need to scroll to the newly tapped step.
1131                        let current_context = tap_key
1132                            .current_context(app)
1133                            .expect("the tapped step is mounted");
1134                        drop(Scrollable::ensure_visible(
1135                            app,
1136                            current_context,
1137                            0.0,
1138                            K_THEME_ANIMATION_DURATION,
1139                            waft_animation::Curves::fast_out_slow_in(),
1140                            ScrollPositionAlignmentPolicy::Explicit,
1141                        ));
1142                        if let Some(on_step_tapped) = on_step_tapped.as_ref() {
1143                            on_step_tapped(app, index);
1144                        }
1145                    }));
1146                }
1147                let header = self.build_vertical_header(app, context, index);
1148                let body = self.build_vertical_body(app, context, index);
1149                Column::new()
1150                    .key(KeyRef::Global(key))
1151                    .children(vec![ink_well.child(header).into_widget(), body])
1152                    .into_widget()
1153            })
1154            .collect();
1155
1156        let mut list_view = ListView::new().shrink_wrap(true).children(children);
1157        if let Some(controller) = stepper.controller.clone() {
1158            list_view = list_view.controller(controller);
1159        }
1160        if let Some(physics) = stepper.physics.clone() {
1161            list_view = list_view.physics(physics);
1162        }
1163        list_view.into_widget()
1164    }
1165
1166    fn build_horizontal(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1167        let stepper = self.widget(app).clone();
1168        let is_label = self.is_label(&stepper);
1169
1170        let mut children: Vec<WidgetRef> = Vec::new();
1171        for index in 0..stepper.steps.len() {
1172            let is_disabled = stepper.steps[index].state == StepState::Disabled;
1173            let on_step_tapped = stepper.on_step_tapped.clone();
1174            let mut ink_response = InkResponse::new().can_request_focus(!is_disabled);
1175            if !is_disabled {
1176                ink_response = ink_response.on_tap(Listener::new(move |app: &mut App| {
1177                    if let Some(on_step_tapped) = on_step_tapped.as_ref() {
1178                        on_step_tapped(app, index);
1179                    }
1180                }));
1181            }
1182
1183            let has_label = stepper.steps[index].label.is_some();
1184            let icon = self.build_icon(app, context, index);
1185            let label = self.build_label_text(app, context, index);
1186            let header_text = self.build_header_text(app, context, index);
1187            let margin: EdgeInsetsGeometry = stepper.step_icon_margin.map_or_else(
1188                || EdgeInsetsDirectional::only(12.0, 0.0, 0.0, 0.0).into(),
1189                |margin| margin.into(),
1190            );
1191
1192            let mut column_children = Vec::new();
1193            if has_label {
1194                column_children.push(SizedBox::new().height(24.0).into_widget());
1195            }
1196            column_children.push(Center::new().child(icon).into_widget());
1197            if has_label {
1198                column_children.push(SizedBox::new().height(24.0).child(label).into_widget());
1199            }
1200
1201            children.push(
1202                ink_response
1203                    .child(Row::new().children(vec![
1204                            SizedBox::new()
1205                                .height(if is_label { 104.0 } else { 72.0 })
1206                                .child(
1207                                    Column::new()
1208                                        .main_axis_alignment(MainAxisAlignment::Center)
1209                                        .children(column_children),
1210                                )
1211                                .into_widget(),
1212                            Padding::new(margin).child(header_text).into_widget(),
1213                        ]))
1214                    .into_widget(),
1215            );
1216
1217            if !self.is_last(&stepper, index) {
1218                let connector_height = stepper.steps[index]
1219                    .step_style
1220                    .as_ref()
1221                    .and_then(|step_style| step_style.connector_thickness)
1222                    .or(stepper.connector_thickness)
1223                    .unwrap_or(1.0);
1224                let connector_color = stepper.steps[index]
1225                    .step_style
1226                    .as_ref()
1227                    .and_then(|step_style| step_style.connector_color)
1228                    .unwrap_or_else(|| {
1229                        self.connector_color(app, context, stepper.steps[index].is_active)
1230                    });
1231                let connector_margin = stepper.step_icon_margin.map_or_else(
1232                    || EdgeInsetsGeometry::symmetric(0.0, 8.0),
1233                    |margin| margin.into(),
1234                );
1235                children.push(
1236                    Expanded::new(
1237                        Padding::new(connector_margin).child(
1238                            SizedBox::new()
1239                                .height(connector_height)
1240                                .child(ColoredBox::new(connector_color)),
1241                        ),
1242                    )
1243                    .into_widget(),
1244                );
1245            }
1246        }
1247
1248        let mut step_panels: Vec<WidgetRef> = Vec::new();
1249        for index in 0..stepper.steps.len() {
1250            step_panels.push(
1251                Visibility::new(
1252                    ClipRect::new()
1253                        .clip_behavior(stepper.clip_behavior)
1254                        .child(stepper.steps[index].content.clone()),
1255                )
1256                .maintain_state(true)
1257                .visible(index == stepper.current_step)
1258                .into_widget(),
1259            );
1260        }
1261
1262        let header_height = stepper
1263            .step_icon_height
1264            .map(|height| height * self.height_factor(&stepper));
1265        let mut header_row = SizedBox::new().child(Row::new().children(children));
1266        if let Some(header_height) = header_height {
1267            header_row = header_row.height(header_height);
1268        }
1269        let header = Material::new()
1270            .elevation(stepper.elevation.unwrap_or(2.0))
1271            .child(Padding::new(self.effective_header_padding(&stepper)).child(header_row));
1272
1273        let content = AnimatedSize::new(K_THEME_ANIMATION_DURATION)
1274            .curve(waft_animation::Curves::fast_out_slow_in())
1275            .child(
1276                Column::new()
1277                    .cross_axis_alignment(CrossAxisAlignment::Stretch)
1278                    .children(step_panels),
1279            );
1280        let controls = self.build_vertical_controls(app, context, stepper.current_step);
1281        // Effective horizontal content padding (custom or default).
1282        let horizontal_content_padding = stepper
1283            .content_padding
1284            .unwrap_or(K_DEFAULT_HORIZONTAL_CONTENT_PADDING.into());
1285        let mut list_view = ListView::new()
1286            .padding(horizontal_content_padding)
1287            .children(vec![content.into_widget(), controls]);
1288        if let Some(controller) = stepper.controller.clone() {
1289            list_view = list_view.controller(controller);
1290        }
1291        if let Some(physics) = stepper.physics.clone() {
1292            list_view = list_view.physics(physics);
1293        }
1294
1295        Column::new()
1296            .children(vec![
1297                header.into_widget(),
1298                Expanded::new(list_view).into_widget(),
1299            ])
1300            .into_widget()
1301    }
1302}
1303
1304impl fmt::Debug for StepperState {
1305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1306        f.debug_struct("StepperState").finish_non_exhaustive()
1307    }
1308}
1309
1310impl State for StepperState {
1311    type Widget = Stepper;
1312    waft_widgets::state_accessors!();
1313
1314    fn init_state(self: Handle<Self>, app: &mut App) {
1315        let stepper = self.widget(app).clone();
1316        let keys = (0..stepper.steps.len()).map(|_| GlobalKey::new()).collect();
1317        let mut old_states = HashMap::new();
1318        for (index, step) in stepper.steps.iter().enumerate() {
1319            old_states.insert(index, step.state);
1320        }
1321        let state = app.get_mut(self);
1322        state.keys = keys;
1323        state.old_states = old_states;
1324    }
1325
1326    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Stepper) {
1327        assert_eq!(
1328            self.widget(app).steps.len(),
1329            old_widget.steps.len(),
1330            "the length of steps must not change"
1331        );
1332        let mut old_states = HashMap::new();
1333        for (index, step) in old_widget.steps.iter().enumerate() {
1334            old_states.insert(index, step.state);
1335        }
1336        app.get_mut(self).old_states = old_states;
1337    }
1338
1339    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1340        let stepper = self.widget(app).clone();
1341        debug_assert!(
1342            stepper.step_icon_height.is_none()
1343                || stepper.step_icon_width.is_none()
1344                || stepper.step_icon_height == stepper.step_icon_width,
1345            "if either step_icon_height or step_icon_width is specified, both must be specified \
1346             and the values must be equal"
1347        );
1348        debug_assert!(debug_check_has_material(app, context));
1349        debug_assert!(debug_check_has_material_localizations(app, context));
1350        debug_assert!(
1351            context
1352                .find_ancestor_widget_of_exact_type::<Stepper>(app)
1353                .is_none(),
1354            "Steppers must not be nested.\n\
1355             The material specification advises that one should avoid embedding steppers within \
1356             steppers. \
1357             https://material.io/archive/guidelines/components/steppers.html#steppers-usage"
1358        );
1359        match stepper.r#type {
1360            StepperType::Vertical => self.build_vertical(app, context),
1361            StepperType::Horizontal => self.build_horizontal(app, context),
1362        }
1363    }
1364}
1365
1366/// Paints a triangle whose base is the bottom of the bounding rectangle and its top vertex the
1367/// middle of its top.
1368struct TrianglePainter {
1369    color: Color,
1370}
1371
1372impl CustomPainter for TrianglePainter {
1373    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
1374        let base = size.width();
1375        let half_base = size.width() / 2.0;
1376        let height = size.height();
1377        let mut path = PathBuilder::new();
1378        path.move_to(valo::Point::new(0.0, height as f32));
1379        path.line_to(valo::Point::new(base as f32, height as f32));
1380        path.line_to(valo::Point::new(half_base as f32, 0.0));
1381        path.close();
1382        canvas.draw_path(
1383            &path.build(),
1384            FillRule::NonZero,
1385            &Paint::from_color(self.color.into()),
1386        );
1387    }
1388
1389    // Hitting the rectangle is fine enough.
1390    fn hit_test(&self, _app: &App, _position: Offset) -> Option<bool> {
1391        Some(true)
1392    }
1393
1394    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1395        old_delegate
1396            .as_any()
1397            .downcast_ref::<TrianglePainter>()
1398            .is_none_or(|old_delegate| old_delegate.color != self.color)
1399    }
1400
1401    fn as_any(&self) -> &dyn std::any::Any {
1402        self
1403    }
1404}
1405
1406/// Used to override the default visual properties of [`Step`] widgets within a [`Stepper`].
1407#[derive(Clone, Debug, Default, PartialEq)]
1408pub struct StepStyle {
1409    /// Overrides the default color of the circle in the step.
1410    pub color: Option<Color>,
1411    /// Overrides the default color of the error indicator in the step.
1412    pub error_color: Option<Color>,
1413    /// Overrides the default color of the connector line between two steps.
1414    ///
1415    /// This property only applies when [`Stepper::r#type`] is [`StepperType::Horizontal`].
1416    pub connector_color: Option<Color>,
1417    /// Overrides the default thickness of the connector line between two steps.
1418    ///
1419    /// This property only applies when [`Stepper::r#type`] is [`StepperType::Horizontal`].
1420    pub connector_thickness: Option<f64>,
1421    /// Adds a border around the step.
1422    ///
1423    /// Will be applied to the circle in the step.
1424    pub border: Option<BoxBorderRef>,
1425    /// Adds a shadow around the step.
1426    pub box_shadow: Option<BoxShadow>,
1427    /// Adds a gradient around the step.
1428    ///
1429    /// If [`gradient`](Self::gradient) is specified, [`color`](Self::color) will be ignored.
1430    pub gradient: Option<GradientRef>,
1431    /// Overrides the default style of the index in the step.
1432    pub index_style: Option<TextStyle>,
1433}
1434
1435impl StepStyle {
1436    /// Constructs a set of step properties; Dart's optional named arguments are the setters,
1437    /// which carry `with_` so that they do not collide with the fields.
1438    pub fn new() -> StepStyle {
1439        StepStyle::default()
1440    }
1441
1442    /// Dart `StepStyle(color:)`.
1443    pub fn with_color(mut self, color: Color) -> StepStyle {
1444        self.color = Some(color);
1445        self
1446    }
1447
1448    /// Dart `StepStyle(errorColor:)`.
1449    pub fn with_error_color(mut self, error_color: Color) -> StepStyle {
1450        self.error_color = Some(error_color);
1451        self
1452    }
1453
1454    /// Dart `StepStyle(connectorColor:)`.
1455    pub fn with_connector_color(mut self, connector_color: Color) -> StepStyle {
1456        self.connector_color = Some(connector_color);
1457        self
1458    }
1459
1460    /// Dart `StepStyle(connectorThickness:)`.
1461    pub fn with_connector_thickness(mut self, connector_thickness: f64) -> StepStyle {
1462        self.connector_thickness = Some(connector_thickness);
1463        self
1464    }
1465
1466    /// Dart `StepStyle(border:)`.
1467    pub fn with_border(mut self, border: impl Into<BoxBorderRef>) -> StepStyle {
1468        self.border = Some(border.into());
1469        self
1470    }
1471
1472    /// Dart `StepStyle(boxShadow:)`.
1473    pub fn with_box_shadow(mut self, box_shadow: BoxShadow) -> StepStyle {
1474        self.box_shadow = Some(box_shadow);
1475        self
1476    }
1477
1478    /// Dart `StepStyle(gradient:)`.
1479    pub fn with_gradient(mut self, gradient: impl Into<GradientRef>) -> StepStyle {
1480        self.gradient = Some(gradient.into());
1481        self
1482    }
1483
1484    /// Dart `StepStyle(indexStyle:)`.
1485    pub fn with_index_style(mut self, index_style: TextStyle) -> StepStyle {
1486        self.index_style = Some(index_style);
1487        self
1488    }
1489
1490    /// Returns a copy of this style with the given fields replaced with the new values.
1491    pub fn copy_with(&self) -> StepStyle {
1492        self.clone()
1493    }
1494
1495    /// Returns a copy of this style where the fields `step_style` sets replace the
1496    /// corresponding fields of this style.
1497    pub fn merge(&self, step_style: Option<&StepStyle>) -> StepStyle {
1498        let Some(step_style) = step_style else {
1499            return self.clone();
1500        };
1501        StepStyle {
1502            color: step_style.color.or(self.color),
1503            error_color: step_style.error_color.or(self.error_color),
1504            connector_color: step_style.connector_color.or(self.connector_color),
1505            connector_thickness: step_style.connector_thickness.or(self.connector_thickness),
1506            border: step_style.border.clone().or_else(|| self.border.clone()),
1507            box_shadow: step_style.box_shadow.or(self.box_shadow),
1508            gradient: step_style
1509                .gradient
1510                .clone()
1511                .or_else(|| self.gradient.clone()),
1512            index_style: step_style
1513                .index_style
1514                .clone()
1515                .or_else(|| self.index_style.clone()),
1516        }
1517    }
1518}
1519
1520impl Diagnosticable for StepStyle {
1521    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
1522        // Dart's `indexStyle` default is `ThemeData.fallback().textTheme.bodyLarge`; without a
1523        // fallback theme the line has no default and is shown whenever it is set.
1524        properties.add(ColorProperty::new("color", self.color).default_value(None));
1525        properties.add(ColorProperty::new("errorColor", self.error_color).default_value(None));
1526        properties
1527            .add(ColorProperty::new("connectorColor", self.connector_color).default_value(None));
1528        properties.add(
1529            DoubleProperty::new("connectorThickness", self.connector_thickness).default_value(None),
1530        );
1531        properties.add(
1532            DiagnosticsProperty::<BoxBorderRef>::new("border", self.border.clone())
1533                .default_value(None),
1534        );
1535        properties.add(
1536            DiagnosticsProperty::<BoxShadow>::new("boxShadow", self.box_shadow).default_value(None),
1537        );
1538        properties.add(
1539            DiagnosticsProperty::<GradientRef>::new("gradient", self.gradient.clone())
1540                .default_value(None),
1541        );
1542        properties.add(DiagnosticsProperty::<TextStyle>::new(
1543            "indexStyle",
1544            self.index_style.clone(),
1545        ));
1546    }
1547}
1548
1549/// Dart's `StepStyle.toString`, through its diagnostics.
1550impl fmt::Display for StepStyle {
1551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1552        f.write_str(&Diagnosticable::to_string(self))
1553    }
1554}
1555
1556#[cfg(test)]
1557mod tests {
1558    use std::cell::{Cell, RefCell};
1559    use std::rc::Rc;
1560    use std::time::Duration;
1561
1562    use waft_embedder::{Rect, Size};
1563    use waft_foundation::ValueKey;
1564    use waft_painting::{Border, BorderStyle, LinearGradient, ShapeBorderRef};
1565    use waft_rendering::testing::{PaintCall, paints};
1566    use waft_rendering::{RenderFlex, RenderFlexMixin};
1567    use waft_widgets::testing::{
1568        WidgetTester, assert_more_or_less_equals, assert_more_or_less_equals_within, find,
1569        test_widgets,
1570    };
1571    use waft_widgets::{
1572        AnyElement, BoxScrollView, Center, Container, Focus, GestureDetector, IntoWidget, ListView,
1573        NeverScrollableScrollPhysics, ScrollController, ScrollControllerLeaf, ScrollView,
1574        ScrollableState, SizedBox, StatefulBuilder, Text, downcast_widget,
1575    };
1576
1577    use super::*;
1578    use crate::material::Material;
1579    use crate::scaffold::Scaffold;
1580    use crate::test_support::{PaintInspection, material_app};
1581    use crate::theme_data::ThemeData;
1582
1583    /// Dart's `Step(title: Text(title), content: SizedBox(width: width, height: height))`.
1584    fn sized_step(title: &'static str, width: f64, height: f64) -> Step {
1585        Step::new(
1586            Text::new(title),
1587            SizedBox::new().width(width).height(height),
1588        )
1589    }
1590
1591    /// Dart's `Step(title: Text(title), content: Text(content))`.
1592    fn text_step(title: &'static str, content: &'static str) -> Step {
1593        Step::new(Text::new(title), Text::new(content))
1594    }
1595
1596    fn light_theme(tester: &WidgetTester) -> ThemeData {
1597        ThemeData::builder().build(&tester.cell.borrow())
1598    }
1599
1600    fn material2_theme(tester: &WidgetTester) -> ThemeData {
1601        ThemeData::builder()
1602            .use_material3(false)
1603            .build(&tester.cell.borrow())
1604    }
1605
1606    /// Dart's `pumpWidget(MaterialApp(home: Material(child: stepper)))`.
1607    fn pump(tester: &mut WidgetTester, stepper: Stepper) {
1608        let theme = light_theme(tester);
1609        tester.pump_widget(material_app(
1610            theme,
1611            Material::new().child(stepper).into_widget(),
1612        ));
1613    }
1614
1615    /// Dart's `pumpWidget(MaterialApp(home: Center(child: Material(child: stepper))))`.
1616    fn pump_centered(tester: &mut WidgetTester, stepper: Stepper) {
1617        let theme = light_theme(tester);
1618        tester.pump_widget(material_app(
1619            theme,
1620            Center::new()
1621                .child(Material::new().child(stepper))
1622                .into_widget(),
1623        ));
1624    }
1625
1626    /// Dart's `pumpWidget(MaterialApp(home: Scaffold(body: Center(child: child))))`.
1627    fn pump_in_scaffold(tester: &mut WidgetTester, theme: ThemeData, child: WidgetRef) {
1628        tester.pump_widget(material_app(
1629            theme,
1630            Scaffold::new()
1631                .body(Center::new().child(child))
1632                .into_widget(),
1633        ));
1634    }
1635
1636    fn count(tester: &WidgetTester, finder: waft_widgets::testing::Finder) -> usize {
1637        finder.evaluate(tester).len()
1638    }
1639
1640    fn stepper_height(tester: &WidgetTester) -> f64 {
1641        tester.get_size(find::by_type::<Stepper>()).height()
1642    }
1643
1644    /// Dart's `(tester.widget<AnimatedContainer>(find.widgetWithText(AnimatedContainer, text))
1645    /// .decoration as BoxDecoration?)?.color`.
1646    fn circle_color(tester: &WidgetTester, text: &str) -> Option<Color> {
1647        tester.widget(
1648            find::widget_with_text::<AnimatedContainer>(text),
1649            |container: &AnimatedContainer| {
1650                container.decoration.as_ref().and_then(|decoration| {
1651                    decoration
1652                        .as_any()
1653                        .downcast_ref::<BoxDecoration>()
1654                        .and_then(|decoration| decoration.color.as_ref())
1655                        .map(|color| color.color())
1656                })
1657            },
1658        )
1659    }
1660
1661    /// Dart's `tester.widget<ColoredBox>(finder).color`.
1662    fn colored_box_color(tester: &WidgetTester, element: AnyElement) -> Color {
1663        tester.widget(element, |colored_box: &ColoredBox| {
1664            colored_box.color.color()
1665        })
1666    }
1667
1668    /// The `ListView` a stepper builds: Dart's `tester.widget<ListView>(find.descendant(of:
1669    /// find.byType(Stepper), matching: find.byType(ListView)))`.
1670    fn stepper_list_view<R>(tester: &WidgetTester, read: impl FnOnce(&ListView) -> R) -> R {
1671        tester.widget(
1672            find::descendant(find::by_type::<Stepper>(), find::by_type::<ListView>()),
1673            read,
1674        )
1675    }
1676
1677    /// The paddings above `text`, nearest first: Dart's `tester.widgetList<Padding>(
1678    /// find.ancestor(of: find.text(text), matching: find.byType(Padding)))`.
1679    fn paddings_above(tester: &WidgetTester, text: &str) -> Vec<EdgeInsets> {
1680        find::ancestor(find::text(text), find::by_type::<Padding>())
1681            .evaluate(tester)
1682            .into_iter()
1683            .map(|element| {
1684                tester.widget(element, |padding: &Padding| {
1685                    padding.padding.resolve(Some(TextDirection::Ltr))
1686                })
1687            })
1688            .collect()
1689    }
1690
1691    #[test]
1692    fn material3_has_sentence_case_labels() {
1693        test_widgets(|tester| {
1694            pump(
1695                tester,
1696                Stepper::new(vec![
1697                    sized_step("Step 1", 100.0, 100.0),
1698                    sized_step("Step 2", 100.0, 100.0),
1699                ])
1700                .on_step_tapped(Rc::new(|_app, _index| {})),
1701            );
1702            assert!(count(tester, find::text("Continue")) > 0);
1703            assert!(count(tester, find::text("Cancel")) > 0);
1704        });
1705    }
1706
1707    #[test]
1708    fn stepper_tap_callback_test() {
1709        test_widgets(|tester| {
1710            let index = Rc::new(Cell::new(0));
1711            let tapped = Rc::clone(&index);
1712            pump(
1713                tester,
1714                Stepper::new(vec![
1715                    sized_step("Step 1", 100.0, 100.0),
1716                    sized_step("Step 2", 100.0, 100.0),
1717                ])
1718                .on_step_tapped(Rc::new(move |_app, i| tapped.set(i))),
1719            );
1720            tester.tap(find::text("Step 2"));
1721            assert_eq!(index.get(), 1);
1722        });
1723    }
1724
1725    #[test]
1726    fn stepper_expansion_test() {
1727        test_widgets(|tester| {
1728            let steps = || {
1729                vec![
1730                    sized_step("Step 1", 100.0, 100.0),
1731                    sized_step("Step 2", 200.0, 200.0),
1732                ]
1733            };
1734            pump_centered(tester, Stepper::new(steps()));
1735            assert_eq!(stepper_height(tester), 332.0);
1736
1737            pump_centered(tester, Stepper::new(steps()).current_step(1));
1738            tester.pump_by(Duration::from_millis(100));
1739            assert!(stepper_height(tester) > 332.0);
1740            tester.pump_by(Duration::from_millis(100));
1741            assert_eq!(stepper_height(tester), 432.0);
1742        });
1743    }
1744
1745    #[test]
1746    fn stepper_horizontal_size_test() {
1747        test_widgets(|tester| {
1748            pump_centered(
1749                tester,
1750                Stepper::new(vec![sized_step("Step 1", 100.0, 100.0)])
1751                    .r#type(StepperType::Horizontal),
1752            );
1753            assert_eq!(stepper_height(tester), 600.0);
1754        });
1755    }
1756
1757    #[test]
1758    fn stepper_visibility_test() {
1759        test_widgets(|tester| {
1760            let steps = || vec![text_step("Step 1", "A"), text_step("Step 2", "B")];
1761            pump(
1762                tester,
1763                Stepper::new(steps()).r#type(StepperType::Horizontal),
1764            );
1765            assert_eq!(count(tester, find::text("A")), 1);
1766            assert_eq!(count(tester, find::text("B")), 0);
1767
1768            pump(
1769                tester,
1770                Stepper::new(steps())
1771                    .current_step(1)
1772                    .r#type(StepperType::Horizontal),
1773            );
1774            assert_eq!(count(tester, find::text("A")), 0);
1775            assert_eq!(count(tester, find::text("B")), 1);
1776        });
1777    }
1778
1779    /// Dart's `Stepper button test`: taps the continue and cancel buttons labelled `continue_label`
1780    /// and `cancel_label` under `theme`.
1781    fn stepper_button_test(
1782        tester: &mut WidgetTester,
1783        theme: ThemeData,
1784        continue_label: &str,
1785        cancel_label: &str,
1786    ) {
1787        let continue_pressed = Rc::new(Cell::new(false));
1788        let cancel_pressed = Rc::new(Cell::new(false));
1789        let (continued, cancelled) = (Rc::clone(&continue_pressed), Rc::clone(&cancel_pressed));
1790        tester.pump_widget(material_app(
1791            theme,
1792            Material::new()
1793                .child(
1794                    Stepper::new(vec![
1795                        sized_step("Step 1", 100.0, 100.0),
1796                        sized_step("Step 2", 200.0, 200.0),
1797                    ])
1798                    .r#type(StepperType::Horizontal)
1799                    .on_step_continue(Listener::new(move |_app| continued.set(true)))
1800                    .on_step_cancel(Listener::new(move |_app| cancelled.set(true))),
1801                )
1802                .into_widget(),
1803        ));
1804
1805        tester.tap(find::text(continue_label));
1806        tester.tap(find::text(cancel_label));
1807
1808        assert!(continue_pressed.get());
1809        assert!(cancel_pressed.get());
1810    }
1811
1812    #[test]
1813    fn material2_stepper_button_test() {
1814        test_widgets(|tester| {
1815            let theme = material2_theme(tester);
1816            stepper_button_test(tester, theme, "CONTINUE", "CANCEL");
1817        });
1818    }
1819
1820    #[test]
1821    fn material3_stepper_button_test() {
1822        test_widgets(|tester| {
1823            let theme = light_theme(tester);
1824            stepper_button_test(tester, theme, "Continue", "Cancel");
1825        });
1826    }
1827
1828    #[test]
1829    fn stepper_disabled_step_test() {
1830        test_widgets(|tester| {
1831            let index = Rc::new(Cell::new(0));
1832            let tapped = Rc::clone(&index);
1833            pump(
1834                tester,
1835                Stepper::new(vec![
1836                    sized_step("Step 1", 100.0, 100.0),
1837                    sized_step("Step 2", 100.0, 100.0).state(StepState::Disabled),
1838                ])
1839                .on_step_tapped(Rc::new(move |_app, i| tapped.set(i))),
1840            );
1841            tester.tap(find::text("Step 2"));
1842            assert_eq!(index.get(), 0);
1843        });
1844    }
1845
1846    #[test]
1847    fn stepper_scroll_test() {
1848        test_widgets(|tester| {
1849            let steps = || {
1850                vec![
1851                    sized_step("Step 1", 100.0, 300.0),
1852                    sized_step("Step 2", 100.0, 300.0),
1853                    sized_step("Step 3", 100.0, 100.0),
1854                ]
1855            };
1856            pump(tester, Stepper::new(steps()));
1857
1858            let scrollable_state = tester
1859                .element(find::by_type::<Scrollable>().first())
1860                .state_handle::<ScrollableState>(&tester.cell.borrow())
1861                .expect("a scrollable state");
1862            let pixels = |tester: &WidgetTester| {
1863                let app = tester.cell.borrow();
1864                scrollable_state.position(&app).pixels(&app)
1865            };
1866            assert_eq!(pixels(tester), 0.0);
1867
1868            tester.tap(find::text("Step 3"));
1869            pump(tester, Stepper::new(steps()).current_step(2));
1870
1871            tester.pump_by(Duration::from_millis(100));
1872            assert!(pixels(tester) > 0.0);
1873        });
1874    }
1875
1876    #[test]
1877    fn stepper_index_test() {
1878        test_widgets(|tester| {
1879            pump_centered(
1880                tester,
1881                Stepper::new(vec![
1882                    sized_step("A", 100.0, 100.0).state(StepState::Complete),
1883                    sized_step("B", 100.0, 100.0),
1884                ]),
1885            );
1886            assert_eq!(count(tester, find::text("1")), 0);
1887            assert_eq!(count(tester, find::text("2")), 1);
1888        });
1889    }
1890
1891    /// Dart's custom `controlsBuilder`: a continue and a cancel button labelled by `labels`,
1892    /// pressing the callbacks `details` carries, or nothing when `labels` gives no labels.
1893    fn custom_controls(
1894        labels: impl Fn(&ControlsDetails) -> Option<(String, String)> + 'static,
1895    ) -> ControlsWidgetBuilder {
1896        Rc::new(move |_app, _context, details| {
1897            let Some((continue_label, cancel_label)) = labels(&details) else {
1898                return Container::new().into_widget();
1899            };
1900            Container::new()
1901                .margin(EdgeInsets::only(0.0, 16.0, 0.0, 0.0))
1902                .child(SizedBox::new().height(48.0).child(Row::new().children(vec![
1903                            TextButton::new(
1904                                details.on_step_continue.clone(),
1905                                Some(Text::new(continue_label)),
1906                            )
1907                            .into_widget(),
1908                            Container::new()
1909                                .margin(EdgeInsetsDirectional::only(8.0, 0.0, 0.0, 0.0))
1910                                .child(TextButton::new(
1911                                    details.on_step_cancel.clone(),
1912                                    Some(Text::new(cancel_label)),
1913                                ))
1914                                .into_widget(),
1915                        ])))
1916                .into_widget()
1917        })
1918    }
1919
1920    #[test]
1921    fn stepper_custom_controls_test() {
1922        test_widgets(|tester| {
1923            let continue_pressed = Rc::new(Cell::new(false));
1924            let canceled_pressed = Rc::new(Cell::new(false));
1925            let (set_continue, set_canceled) =
1926                (Rc::clone(&continue_pressed), Rc::clone(&canceled_pressed));
1927            pump_centered(
1928                tester,
1929                Stepper::new(vec![
1930                    sized_step("A", 100.0, 100.0).state(StepState::Complete),
1931                    sized_step("B", 100.0, 100.0),
1932                ])
1933                .controls_builder(custom_controls(|_details| {
1934                    Some(("Let us continue!".to_owned(), "Cancel This!".to_owned()))
1935                }))
1936                .on_step_cancel(Listener::new(move |_app| set_canceled.set(true)))
1937                .on_step_continue(Listener::new(move |_app| set_continue.set(true))),
1938            );
1939
1940            // 2 because stepper creates a set of controls for each step
1941            assert_eq!(count(tester, find::text("Let us continue!")), 2);
1942            assert_eq!(count(tester, find::text("Cancel This!")), 2);
1943
1944            tester.tap(find::text("Cancel This!").first());
1945            tester.pump_and_settle();
1946            tester.tap(find::text("Let us continue!").first());
1947            tester.pump_and_settle();
1948
1949            assert!(canceled_pressed.get());
1950            assert!(continue_pressed.get());
1951        });
1952    }
1953
1954    #[test]
1955    fn stepper_custom_indexed_controls_test() {
1956        test_widgets(|tester| {
1957            let current_step = Rc::new(Cell::new(0_i32));
1958            let builder = {
1959                let current_step = Rc::clone(&current_step);
1960                StatefulBuilder::new(move |_app, _context, set_state| {
1961                    let (cancel_step, continue_step) =
1962                        (Rc::clone(&current_step), Rc::clone(&current_step));
1963                    let (cancel_set_state, continue_set_state) = (set_state.clone(), set_state);
1964                    Stepper::new(vec![
1965                        sized_step("A", 100.0, 100.0).state(StepState::Complete),
1966                        sized_step("C", 100.0, 100.0),
1967                    ])
1968                    .current_step(current_step.get() as usize)
1969                    // For the purposes of testing, only render something for the active step.
1970                    .controls_builder(custom_controls(|details| {
1971                        details.is_active().then(|| {
1972                            let step_index = details.step_index as i32;
1973                            (
1974                                format!("Continue to {}", step_index + 1),
1975                                format!("Return to {}", step_index - 1),
1976                            )
1977                        })
1978                    }))
1979                    .on_step_cancel(Listener::new(move |app| {
1980                        cancel_set_state(app, &mut |_app| cancel_step.set(cancel_step.get() - 1));
1981                    }))
1982                    .on_step_continue(Listener::new(move |app| {
1983                        continue_set_state(app, &mut |_app| {
1984                            continue_step.set(continue_step.get() + 1);
1985                        });
1986                    }))
1987                    .into_widget()
1988                })
1989            };
1990            let theme = light_theme(tester);
1991            tester.pump_widget(material_app(
1992                theme,
1993                Center::new()
1994                    .child(Material::new().child(builder))
1995                    .into_widget(),
1996            ));
1997
1998            // Never mind that there is no Step -1 or Step 2 -- actual build method
1999            // implementations would make those checks.
2000            assert_eq!(count(tester, find::text("Return to -1")), 1);
2001            assert_eq!(count(tester, find::text("Continue to 1")), 1);
2002            assert_eq!(count(tester, find::text("Return to 0")), 0);
2003            assert_eq!(count(tester, find::text("Continue to 2")), 0);
2004
2005            tester.tap(find::text("Continue to 1").first());
2006            tester.pump_and_settle();
2007
2008            assert_eq!(count(tester, find::text("Return to -1")), 0);
2009            assert_eq!(count(tester, find::text("Continue to 1")), 0);
2010            assert_eq!(count(tester, find::text("Return to 0")), 1);
2011            assert_eq!(count(tester, find::text("Continue to 2")), 1);
2012        });
2013    }
2014
2015    #[test]
2016    fn stepper_error_test() {
2017        test_widgets(|tester| {
2018            pump_centered(
2019                tester,
2020                Stepper::new(vec![sized_step("A", 100.0, 100.0).state(StepState::Error)]),
2021            );
2022            assert_eq!(count(tester, find::text("!")), 1);
2023        });
2024    }
2025
2026    #[test]
2027    #[should_panic(
2028        expected = "Steppers must not be nested.\nThe material specification advises \
2029                               that one should avoid embedding steppers within steppers. \
2030                               https://material.io/archive/guidelines/components/steppers.html#steppers-usage"
2031    )]
2032    fn nested_stepper_error_test() {
2033        test_widgets(|tester| {
2034            pump(
2035                tester,
2036                Stepper::new(vec![
2037                    Step::new(
2038                        Text::new("Step 2"),
2039                        Stepper::new(vec![
2040                            text_step("Nested step 1", "A"),
2041                            text_step("Nested step 2", "A"),
2042                        ]),
2043                    ),
2044                    text_step("Step 1", "A"),
2045                ])
2046                .r#type(StepperType::Horizontal),
2047            );
2048        });
2049    }
2050
2051    // https://github.com/flutter/flutter/issues/16920
2052    #[test]
2053    fn stepper_icons_size_test() {
2054        test_widgets(|tester| {
2055            pump(
2056                tester,
2057                Stepper::new(vec![
2058                    sized_step("A", 100.0, 100.0).state(StepState::Editing),
2059                    sized_step("B", 100.0, 100.0).state(StepState::Complete),
2060                ]),
2061            );
2062            assert_eq!(
2063                tester.get_size(find::by_icon(&Icons::edit())),
2064                Size::square(18.0)
2065            );
2066            assert_eq!(
2067                tester.get_size(find::by_icon(&Icons::check())),
2068                Size::square(18.0)
2069            );
2070        });
2071    }
2072
2073    #[test]
2074    fn stepper_physics_scroll_error_test() {
2075        test_widgets(|tester| {
2076            let steps = (1..=10)
2077                .map(|i| {
2078                    Step::new(
2079                        Text::new(format!("Step {i}")),
2080                        Text::new(format!("Text {i}")),
2081                    )
2082                })
2083                .collect();
2084            let theme = light_theme(tester);
2085            tester.pump_widget(material_app(
2086                theme,
2087                Material::new()
2088                    .child(ListView::new().children(vec![
2089                        Stepper::new(steps).into_widget(),
2090                        Text::new("Text After Stepper").into_widget(),
2091                    ]))
2092                    .into_widget(),
2093            ));
2094
2095            tester.fling(find::by_type::<Stepper>(), Offset::new(0.0, -100.0), 1000.0);
2096            tester.pump_and_settle();
2097
2098            assert_eq!(count(tester, find::text("Text After Stepper")), 0);
2099        });
2100    }
2101
2102    /// Dart's `Stepper can't be focused when disabled.`: asks the disabled step's focus node for
2103    /// focus and checks it did not take it.
2104    fn disabled_step_takes_focus(tester: &mut WidgetTester, r#type: StepperType) -> bool {
2105        pump(
2106            tester,
2107            Stepper::new(vec![
2108                text_step("Step 0", "Text 0").state(StepState::Disabled),
2109            ])
2110            .r#type(r#type),
2111        );
2112        tester.pump();
2113
2114        let element = tester.element(find::text("Step 0"));
2115        let disabled_node = Focus::of(&mut tester.cell.borrow_mut(), element, true, false);
2116        disabled_node.request_focus(&mut tester.cell.borrow_mut(), None);
2117        tester.pump();
2118        disabled_node.has_primary_focus(&tester.cell.borrow())
2119    }
2120
2121    #[test]
2122    fn vertical_stepper_cant_be_focused_when_disabled() {
2123        test_widgets(|tester| {
2124            assert!(!disabled_step_takes_focus(tester, StepperType::Vertical));
2125        });
2126    }
2127
2128    #[test]
2129    fn horizontal_stepper_cant_be_focused_when_disabled() {
2130        test_widgets(|tester| {
2131            assert!(!disabled_step_takes_focus(tester, StepperType::Horizontal));
2132        });
2133    }
2134
2135    /// Dart's `expect(tester.takeException(), isNull)` after a layout that may overflow: Waft
2136    /// reports no overflow exception, so the case reads each `RenderFlex`'s overflow.
2137    fn assert_no_flex_overflows(tester: &WidgetTester) {
2138        let flexes = tester.all::<RenderFlex>();
2139        let app = tester.cell.borrow();
2140        for flex in flexes {
2141            assert!(!flex.has_overflow(&app));
2142        }
2143    }
2144
2145    const LONG_TEXT: &str = "A long long long long long long long long long long long long text";
2146
2147    #[test]
2148    fn stepper_header_title_should_not_overflow() {
2149        test_widgets(|tester| {
2150            let theme = light_theme(tester);
2151            tester.pump_widget(material_app(
2152                theme,
2153                Material::new()
2154                    .child(ListView::new().children(vec![
2155                            Stepper::new(vec![Step::new(
2156                                Text::new(LONG_TEXT),
2157                                Text::new("Text content"),
2158                            )])
2159                            .into_widget(),
2160                        ]))
2161                    .into_widget(),
2162            ));
2163            assert_no_flex_overflows(tester);
2164        });
2165    }
2166
2167    #[test]
2168    fn stepper_header_subtitle_should_not_overflow() {
2169        test_widgets(|tester| {
2170            let theme = light_theme(tester);
2171            tester.pump_widget(material_app(
2172                theme,
2173                Material::new()
2174                    .child(ListView::new().children(vec![
2175                            Stepper::new(vec![
2176                                text_step("Regular title", "Text content")
2177                                    .subtitle(Text::new(LONG_TEXT)),
2178                            ])
2179                            .into_widget(),
2180                        ]))
2181                    .into_widget(),
2182            ));
2183            assert_no_flex_overflows(tester);
2184        });
2185    }
2186
2187    /// What a test reads of the `Material` under the `TextButton` labelled `label`: its color,
2188    /// its text style's color and its shape.
2189    struct ButtonMaterial {
2190        color: Option<Color>,
2191        text_color: Option<Color>,
2192        shape: Option<RoundedRectangleBorder>,
2193    }
2194
2195    /// Dart's `buttonMaterial(label)`.
2196    fn button_material(tester: &WidgetTester, label: &str) -> ButtonMaterial {
2197        tester.widget(
2198            find::descendant(
2199                find::widget_with_text::<TextButton>(label),
2200                find::by_type::<Material>(),
2201            ),
2202            |material: &Material| ButtonMaterial {
2203                color: material.color,
2204                text_color: material
2205                    .text_style
2206                    .as_ref()
2207                    .and_then(|style| style.color.as_ref())
2208                    .map(|color| color.color()),
2209                shape: material.shape.as_ref().and_then(|shape: &ShapeBorderRef| {
2210                    shape
2211                        .as_any()
2212                        .downcast_ref::<RoundedRectangleBorder>()
2213                        .copied()
2214                }),
2215            },
2216        )
2217    }
2218
2219    fn button_shape() -> RoundedRectangleBorder {
2220        RoundedRectangleBorder::new(
2221            BorderSide::NONE,
2222            BorderRadiusGeometry::all(waft_embedder::Radius::circular(2.0)),
2223        )
2224    }
2225
2226    /// Dart's `buildFrame(theme)` of the button style cases: a horizontal stepper of one step,
2227    /// with both buttons enabled when `enabled`.
2228    fn pump_button_frame(tester: &mut WidgetTester, theme: ThemeData, enabled: bool) {
2229        let mut stepper =
2230            Stepper::new(vec![sized_step("step1", 100.0, 100.0)]).r#type(StepperType::Horizontal);
2231        if enabled {
2232            stepper = stepper
2233                .on_step_cancel(Listener::new(|_app| {}))
2234                .on_step_continue(Listener::new(|_app| {}));
2235        }
2236        tester.pump_widget(material_app(
2237            theme,
2238            Material::new().child(stepper).into_widget(),
2239        ));
2240    }
2241
2242    fn assert_rect_more_or_less_equals(actual: Rect, expected: Rect) {
2243        assert_more_or_less_equals_within(actual.left, expected.left, 0.001);
2244        assert_more_or_less_equals_within(actual.top, expected.top, 0.001);
2245        assert_more_or_less_equals_within(actual.right, expected.right, 0.001);
2246        assert_more_or_less_equals_within(actual.bottom, expected.bottom, 0.001);
2247    }
2248
2249    #[test]
2250    fn material2_stepper_enabled_button_styles() {
2251        test_widgets(|tester| {
2252            let theme_light = material2_theme(tester);
2253            pump_button_frame(tester, theme_light, true);
2254
2255            const CONTINUE_STR: &str = "CONTINUE";
2256            const CANCEL_STR: &str = "CANCEL";
2257            let continue_button_rect = Rect::from_ltrb(24.0, 212.0, 168.0, 260.0);
2258            let cancel_button_rect = Rect::from_ltrb(176.0, 212.0, 292.0, 260.0);
2259            let continue_material = button_material(tester, CONTINUE_STR);
2260            assert_eq!(continue_material.color, Some(Color::new(0xff2196f3)));
2261            assert_eq!(continue_material.text_color, Some(Color::new(0xffffffff)));
2262            assert_eq!(continue_material.shape, Some(button_shape()));
2263            assert_eq!(
2264                tester.get_rect(find::widget_with_text::<TextButton>(CONTINUE_STR)),
2265                continue_button_rect
2266            );
2267
2268            let cancel_material = button_material(tester, CANCEL_STR);
2269            assert_eq!(cancel_material.color, Some(Color::new(0)));
2270            assert_eq!(cancel_material.text_color, Some(Color::new(0x8a000000)));
2271            assert_eq!(cancel_material.shape, Some(button_shape()));
2272            assert_eq!(
2273                tester.get_rect(find::widget_with_text::<TextButton>(CANCEL_STR)),
2274                cancel_button_rect
2275            );
2276
2277            let theme_dark = ThemeData::dark(&tester.cell.borrow(), Some(false));
2278            pump_button_frame(tester, theme_dark, true);
2279            // Complete the theme animation.
2280            tester.pump_and_settle();
2281
2282            let continue_material = button_material(tester, CONTINUE_STR);
2283            assert_eq!(continue_material.color, Some(Color::new(0)));
2284            assert_eq!(continue_material.text_color, Some(Color::new(0xffffffff)));
2285            assert_eq!(continue_material.shape, Some(button_shape()));
2286            assert_eq!(
2287                tester.get_rect(find::widget_with_text::<TextButton>(CONTINUE_STR)),
2288                continue_button_rect
2289            );
2290
2291            let cancel_material = button_material(tester, CANCEL_STR);
2292            assert_eq!(cancel_material.color, Some(Color::new(0)));
2293            assert_eq!(cancel_material.text_color, Some(Color::new(0xb3ffffff)));
2294            assert_eq!(cancel_material.shape, Some(button_shape()));
2295            assert_eq!(
2296                tester.get_rect(find::widget_with_text::<TextButton>(CANCEL_STR)),
2297                cancel_button_rect
2298            );
2299        });
2300    }
2301
2302    #[test]
2303    fn material3_stepper_enabled_button_styles() {
2304        test_widgets(|tester| {
2305            let theme_light = light_theme(tester);
2306            let light_primary = theme_light.color_scheme.primary();
2307            pump_button_frame(tester, theme_light, true);
2308
2309            const CONTINUE_STR: &str = "Continue";
2310            const CANCEL_STR: &str = "Cancel";
2311            let continue_button_rect = Rect::from_ltrb(24.0, 212.0, 168.8, 260.0);
2312            let cancel_button_rect = Rect::from_ltrb(176.8, 212.0, 293.4, 260.0);
2313            let continue_material = button_material(tester, CONTINUE_STR);
2314            assert_eq!(continue_material.color, Some(light_primary));
2315            assert_eq!(continue_material.text_color, Some(Color::new(0xffffffff)));
2316            assert_eq!(continue_material.shape, Some(button_shape()));
2317            assert_rect_more_or_less_equals(
2318                tester.get_rect(find::widget_with_text::<TextButton>(CONTINUE_STR)),
2319                continue_button_rect,
2320            );
2321
2322            let cancel_material = button_material(tester, CANCEL_STR);
2323            assert_eq!(cancel_material.color, Some(Color::new(0)));
2324            assert_eq!(cancel_material.text_color, Some(Color::new(0x8a000000)));
2325            assert_eq!(cancel_material.shape, Some(button_shape()));
2326            assert_rect_more_or_less_equals(
2327                tester.get_rect(find::widget_with_text::<TextButton>(CANCEL_STR)),
2328                cancel_button_rect,
2329            );
2330
2331            let theme_dark = ThemeData::dark(&tester.cell.borrow(), None);
2332            let dark_on_surface = theme_dark.color_scheme.on_surface();
2333            pump_button_frame(tester, theme_dark, true);
2334            // Complete the theme animation.
2335            tester.pump_and_settle();
2336
2337            let continue_material = button_material(tester, CONTINUE_STR);
2338            assert_eq!(continue_material.color, Some(Color::new(0)));
2339            assert_eq!(continue_material.text_color, Some(dark_on_surface));
2340            assert_eq!(continue_material.shape, Some(button_shape()));
2341            assert_rect_more_or_less_equals(
2342                tester.get_rect(find::widget_with_text::<TextButton>(CONTINUE_STR)),
2343                continue_button_rect,
2344            );
2345
2346            let cancel_material = button_material(tester, CANCEL_STR);
2347            assert_eq!(cancel_material.color, Some(Color::new(0)));
2348            assert_eq!(cancel_material.text_color, Some(Color::new(0xb3ffffff)));
2349            assert_eq!(cancel_material.shape, Some(button_shape()));
2350            assert_rect_more_or_less_equals(
2351                tester.get_rect(find::widget_with_text::<TextButton>(CANCEL_STR)),
2352                cancel_button_rect,
2353            );
2354        });
2355    }
2356
2357    /// Dart's `Stepper disabled button styles`: both buttons are transparent with
2358    /// `disabled_text` text, under `theme`.
2359    fn assert_disabled_button_styles(
2360        tester: &mut WidgetTester,
2361        theme: ThemeData,
2362        continue_label: &str,
2363        cancel_label: &str,
2364        disabled_text: Color,
2365    ) {
2366        pump_button_frame(tester, theme, false);
2367        // Complete the theme animation.
2368        tester.pump_and_settle();
2369        for label in [continue_label, cancel_label] {
2370            let material = button_material(tester, label);
2371            assert_eq!(material.color, Some(Color::new(0)), "{label}");
2372            assert_eq!(material.text_color, Some(disabled_text), "{label}");
2373        }
2374    }
2375
2376    #[test]
2377    fn material2_stepper_disabled_button_styles() {
2378        test_widgets(|tester| {
2379            let theme_light = material2_theme(tester);
2380            assert_disabled_button_styles(
2381                tester,
2382                theme_light,
2383                "CONTINUE",
2384                "CANCEL",
2385                Color::new(0x61000000),
2386            );
2387
2388            let theme_dark = ThemeData::dark(&tester.cell.borrow(), Some(false));
2389            assert_disabled_button_styles(
2390                tester,
2391                theme_dark,
2392                "CONTINUE",
2393                "CANCEL",
2394                Color::new(0x61ffffff),
2395            );
2396        });
2397    }
2398
2399    #[test]
2400    #[expect(
2401        deprecated,
2402        reason = "Dart's case compares against `Color.withOpacity`"
2403    )]
2404    fn material3_stepper_disabled_button_styles() {
2405        test_widgets(|tester| {
2406            let theme_light = light_theme(tester);
2407            let colors_light = theme_light.color_scheme.clone();
2408            assert_disabled_button_styles(
2409                tester,
2410                theme_light,
2411                "Continue",
2412                "Cancel",
2413                colors_light.on_surface().with_opacity(0.38),
2414            );
2415
2416            let theme_dark = ThemeData::dark(&tester.cell.borrow(), None);
2417            let colors_dark = theme_dark.color_scheme.clone();
2418            assert_disabled_button_styles(
2419                tester,
2420                theme_dark,
2421                "Continue",
2422                "Cancel",
2423                colors_dark.on_surface().with_opacity(0.38),
2424            );
2425        });
2426    }
2427
2428    #[test]
2429    fn vertical_and_horizontal_stepper_physics_test() {
2430        test_widgets(|tester| {
2431            let physics: waft_widgets::ScrollPhysicsRef =
2432                Rc::new(NeverScrollableScrollPhysics::new());
2433
2434            for r#type in [StepperType::Vertical, StepperType::Horizontal] {
2435                pump(
2436                    tester,
2437                    Stepper::new(vec![sized_step("Step 1", 100.0, 100.0)])
2438                        .physics(physics.clone())
2439                        .r#type(r#type),
2440                );
2441
2442                let list_view_physics = stepper_list_view(tester, |list_view| {
2443                    list_view.scroll_view_data().physics.clone()
2444                })
2445                .expect("the list view has physics");
2446                assert!(Rc::ptr_eq(&list_view_physics, &physics), "{type:?}");
2447            }
2448        });
2449    }
2450
2451    #[test]
2452    fn scroll_controller_is_passed_to_the_stepper_listview() {
2453        test_widgets(|tester| {
2454            let controller = ScrollController::default(&mut tester.cell.borrow_mut());
2455            for r#type in [StepperType::Vertical, StepperType::Horizontal] {
2456                pump(
2457                    tester,
2458                    Stepper::new(vec![sized_step("Step 1", 100.0, 100.0)])
2459                        .controller(controller.erase())
2460                        .r#type(r#type),
2461                );
2462
2463                let list_view_controller = stepper_list_view(tester, |list_view| {
2464                    list_view.scroll_view_data().controller.clone()
2465                })
2466                .expect("the list view has a controller");
2467                assert_eq!(
2468                    *list_view_controller,
2469                    controller.as_controller(),
2470                    "{type:?}"
2471                );
2472            }
2473            controller.dispose(&mut tester.cell.borrow_mut());
2474        });
2475    }
2476
2477    // Regression test for https://github.com/flutter/flutter/pull/77732
2478    #[test]
2479    #[expect(
2480        deprecated,
2481        reason = "Dart's case compares against `Color.withOpacity` and `ColorScheme.background`"
2482    )]
2483    fn stepper_horizontal_size_test_circle_colors() {
2484        test_widgets(|tester| {
2485            let build_frame =
2486                |tester: &mut WidgetTester, is_active: bool, brightness: Brightness| {
2487                    let theme = match brightness {
2488                        Brightness::Dark => ThemeData::dark(&tester.cell.borrow(), None),
2489                        Brightness::Light => light_theme(tester),
2490                    };
2491                    pump_in_scaffold(
2492                        tester,
2493                        theme,
2494                        Stepper::new(vec![text_step("step", "content").is_active(is_active)])
2495                            .r#type(StepperType::Horizontal)
2496                            .into_widget(),
2497                    );
2498                };
2499
2500            // Light theme
2501            let light = light_theme(tester).color_scheme.clone();
2502            build_frame(tester, true, Brightness::Light);
2503            assert_eq!(circle_color(tester, "1"), Some(light.primary()));
2504            build_frame(tester, false, Brightness::Light);
2505            tester.pump_and_settle();
2506            assert_eq!(
2507                circle_color(tester, "1"),
2508                Some(light.on_surface().with_opacity(0.38))
2509            );
2510
2511            // Dark theme
2512            let dark = ThemeData::dark(&tester.cell.borrow(), None)
2513                .color_scheme
2514                .clone();
2515            build_frame(tester, true, Brightness::Dark);
2516            tester.pump_and_settle();
2517            assert_eq!(circle_color(tester, "1"), Some(dark.secondary()));
2518            build_frame(tester, false, Brightness::Dark);
2519            tester.pump_and_settle();
2520            assert_eq!(circle_color(tester, "1"), Some(dark.background()));
2521        });
2522    }
2523
2524    /// Dart's `tester.firstWidget<Material>(find.descendant(of: find.byType(Stepper),
2525    /// matching: find.byType(Material))).elevation` for a 200 by 75 horizontal stepper.
2526    fn horizontal_stepper_elevation(tester: &mut WidgetTester, stepper: Stepper) -> f64 {
2527        let theme = light_theme(tester);
2528        tester.pump_widget(material_app(
2529            theme,
2530            Material::new()
2531                .child(
2532                    SizedBox::new()
2533                        .width(200.0)
2534                        .height(75.0)
2535                        .child(stepper.r#type(StepperType::Horizontal)),
2536                )
2537                .into_widget(),
2538        ));
2539        tester.widget(
2540            find::descendant(find::by_type::<Stepper>(), find::by_type::<Material>()).first(),
2541            |material: &Material| material.elevation,
2542        )
2543    }
2544
2545    #[test]
2546    fn stepper_custom_elevation() {
2547        test_widgets(|tester| {
2548            const ELEVATION: f64 = 4.0;
2549            let stepper =
2550                Stepper::new(vec![text_step("Regular title", "Text content")]).elevation(ELEVATION);
2551            assert_eq!(horizontal_stepper_elevation(tester, stepper), ELEVATION);
2552        });
2553    }
2554
2555    #[test]
2556    fn stepper_with_default_elevation() {
2557        test_widgets(|tester| {
2558            let stepper = Stepper::new(vec![text_step("Regular title", "Text content")]);
2559            assert_eq!(horizontal_stepper_elevation(tester, stepper), 2.0);
2560        });
2561    }
2562
2563    /// Dart's `_TappableColorWidget`: a 50 by 50 box keyed `tap-me` that turns from
2564    /// `untapped_color` to `tapped_color` when tapped.
2565    struct TappableColorWidget {
2566        key: KeyRef,
2567        tapped_color: Color,
2568        untapped_color: Color,
2569    }
2570
2571    impl fmt::Debug for TappableColorWidget {
2572        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2573            f.debug_struct("TappableColorWidget")
2574                .finish_non_exhaustive()
2575        }
2576    }
2577
2578    struct TappableColorWidgetState {
2579        state: StateData<TappableColorWidget>,
2580        color: Option<Color>,
2581    }
2582
2583    impl fmt::Debug for TappableColorWidgetState {
2584        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2585            f.debug_struct("TappableColorWidgetState")
2586                .finish_non_exhaustive()
2587        }
2588    }
2589
2590    impl StatefulWidget for TappableColorWidget {
2591        type State = TappableColorWidgetState;
2592
2593        fn key(&self) -> Option<&KeyRef> {
2594            Some(&self.key)
2595        }
2596
2597        fn create_state(&self) -> TappableColorWidgetState {
2598            TappableColorWidgetState {
2599                state: StateData::new(),
2600                color: None,
2601            }
2602        }
2603    }
2604
2605    impl State for TappableColorWidgetState {
2606        type Widget = TappableColorWidget;
2607        waft_widgets::state_accessors!();
2608
2609        fn init_state(self: Handle<Self>, app: &mut App) {
2610            app.get_mut(self).color = Some(self.widget(app).untapped_color);
2611        }
2612
2613        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2614            let color = app.get(self).color.expect("set in init_state");
2615            GestureDetector::new()
2616                .on_tap(Listener::new(move |app| {
2617                    let tapped_color = self.widget(app).tapped_color;
2618                    self.set_state(app, |state| state.color = Some(tapped_color));
2619                }))
2620                .child(
2621                    Container::new()
2622                        .key(ValueKey::new("tap-me".to_owned()).into())
2623                        .height(50.0)
2624                        .width(50.0)
2625                        .color(color),
2626                )
2627                .into_widget()
2628        }
2629    }
2630
2631    #[test]
2632    fn stepper_horizontal_preserves_state() {
2633        test_widgets(|tester| {
2634            let untapped_color = Colors::BLUE.primary();
2635            let tapped_color = Colors::RED.primary();
2636            let index = Rc::new(Cell::new(0_usize));
2637            let builder = {
2638                let index = Rc::clone(&index);
2639                StatefulBuilder::new(move |_app, _context, set_state| {
2640                    let tapped = Rc::clone(&index);
2641                    Stepper::new(vec![
2642                        Step::new(
2643                            Text::new("Step 1"),
2644                            TappableColorWidget {
2645                                key: ValueKey::new("tappable-color".to_owned()).into(),
2646                                tapped_color,
2647                                untapped_color,
2648                            },
2649                        ),
2650                        text_step("Step 2", "Step 2 Content"),
2651                    ])
2652                    .on_step_tapped(Rc::new(move |app, i| {
2653                        set_state(app, &mut |_app| tapped.set(i));
2654                    }))
2655                    .current_step(index.get())
2656                    .r#type(StepperType::Horizontal)
2657                    .into_widget()
2658                })
2659            };
2660            let theme = light_theme(tester);
2661            pump_in_scaffold(tester, theme, builder.into_widget());
2662
2663            // Set up a getter to examine the MacGuffin's color
2664            let get_color = |tester: &WidgetTester| {
2665                let colored_box = find::descendant(
2666                    find::by_key(ValueKey::new("tappable-color".to_owned())),
2667                    find::by_type::<ColoredBox>(),
2668                )
2669                .evaluate(tester)[0];
2670                colored_box_color(tester, colored_box)
2671            };
2672
2673            // We are on step 1
2674            assert_eq!(count(tester, find::text("Step 2 Content")), 0);
2675            assert_eq!(get_color(tester), untapped_color);
2676
2677            tester.tap(find::by_key(ValueKey::new("tap-me".to_owned())));
2678            tester.pump_and_settle();
2679            assert_eq!(get_color(tester), tapped_color);
2680
2681            // Now flip to step 2
2682            tester.tap(find::text("Step 2"));
2683            tester.pump_and_settle();
2684
2685            // Confirm that we did in fact flip to step 2
2686            assert_eq!(count(tester, find::text("Step 2 Content")), 1);
2687
2688            // Now go back to step 1
2689            tester.tap(find::text("Step 1"));
2690            tester.pump_and_settle();
2691
2692            // Confirm that we flipped back to step 1
2693            assert_eq!(count(tester, find::text("Step 2 Content")), 0);
2694
2695            // The color should still be `tappedColor`
2696            assert_eq!(get_color(tester), tapped_color);
2697        });
2698    }
2699
2700    #[test]
2701    fn stepper_with_alternative_label() {
2702        test_widgets(|tester| {
2703            let index = Rc::new(Cell::new(0_usize));
2704            let styles: Rc<RefCell<Option<(TextStyle, TextStyle, TextStyle)>>> =
2705                Rc::new(RefCell::new(None));
2706            let builder = {
2707                let index = Rc::clone(&index);
2708                let styles = Rc::clone(&styles);
2709                StatefulBuilder::new(move |app, context, set_state| {
2710                    let text_theme = Theme::of(app, context).text_theme.clone();
2711                    let body_large = text_theme.body_large.clone().expect("a body large style");
2712                    let body_medium = text_theme.body_medium.clone().expect("a body medium style");
2713                    let body_small = text_theme.body_small.clone().expect("a body small style");
2714                    *styles.borrow_mut() =
2715                        Some((body_large.clone(), body_medium.clone(), body_small.clone()));
2716                    let tapped = Rc::clone(&index);
2717                    Stepper::new(vec![
2718                        text_step("Title 1", "Content 1")
2719                            .label(Text::new("Label 1").style(body_small)),
2720                        text_step("Title 2", "Content 2")
2721                            .label(Text::new("Label 2").style(body_large)),
2722                        text_step("Title 3", "Content 3")
2723                            .label(Text::new("Label 3").style(body_medium)),
2724                    ])
2725                    .r#type(StepperType::Horizontal)
2726                    .current_step(index.get())
2727                    .on_step_tapped(Rc::new(move |app, i| {
2728                        set_state(app, &mut |_app| tapped.set(i));
2729                    }))
2730                    .into_widget()
2731                })
2732            };
2733            let theme = light_theme(tester);
2734            tester.pump_widget(material_app(
2735                theme,
2736                Material::new().child(builder).into_widget(),
2737            ));
2738            let (body_large_style, body_medium_style, body_small_style) =
2739                styles.borrow().clone().expect("the builder ran");
2740            let label_style = |tester: &WidgetTester, label: &str| {
2741                tester.widget(find::text(label), |text: &Text| text.style.clone())
2742            };
2743
2744            // Check Styles of Label Text Widgets before tapping steps
2745            assert_eq!(
2746                Some(body_small_style.clone()),
2747                label_style(tester, "Label 1")
2748            );
2749            assert_eq!(
2750                Some(body_medium_style.clone()),
2751                label_style(tester, "Label 3")
2752            );
2753
2754            // Tap to Step1 Label then, `index` become 0
2755            tester.tap(find::text("Label 1"));
2756            assert_eq!(index.get(), 0);
2757
2758            // Check Styles of Selected Label Text Widgets and Another Label Text Widget
2759            assert_eq!(
2760                Some(body_small_style.clone()),
2761                label_style(tester, &format!("Label {}", index.get() + 1))
2762            );
2763            assert_eq!(
2764                Some(body_large_style.clone()),
2765                label_style(tester, &format!("Label {}", index.get() + 2))
2766            );
2767
2768            // Tap to Step2 Label then, `index` become 1
2769            tester.tap(find::text("Label 2"));
2770            assert_eq!(index.get(), 1);
2771
2772            // Check Styles of Selected Label Text Widgets and Another Label Text Widget
2773            assert_eq!(
2774                Some(body_large_style),
2775                label_style(tester, &format!("Label {}", index.get() + 1))
2776            );
2777            assert_eq!(
2778                Some(body_medium_style),
2779                label_style(tester, &format!("Label {}", index.get() + 2))
2780            );
2781        });
2782    }
2783
2784    #[test]
2785    fn stepper_connector_style() {
2786        test_widgets(|tester| {
2787            let selected_color = Colors::BLACK;
2788            let disabled_color = Colors::WHITE;
2789            let index = Rc::new(Cell::new(0_i32));
2790            let builder = {
2791                let index = Rc::clone(&index);
2792                StatefulBuilder::new(move |_app, _context, set_state| {
2793                    let tapped = Rc::clone(&index);
2794                    Stepper::new(vec![
2795                        text_step("step1", "step1 content").is_active(index.get() >= 0),
2796                        text_step("step2", "step2 content").is_active(index.get() >= 1),
2797                    ])
2798                    .r#type(StepperType::Horizontal)
2799                    .connector_color(<dyn WidgetStateProperty<Color>>::resolve_with(
2800                        move |states| {
2801                            if states.contains(&WidgetState::Selected) {
2802                                selected_color
2803                            } else {
2804                                disabled_color
2805                            }
2806                        },
2807                    ))
2808                    .on_step_tapped(Rc::new(move |app, i| {
2809                        set_state(app, &mut |_app| tapped.set(i as i32));
2810                    }))
2811                    .current_step(index.get() as usize)
2812                    .into_widget()
2813                })
2814            };
2815            let theme = light_theme(tester);
2816            pump_in_scaffold(tester, theme, builder.into_widget());
2817
2818            let line_color = |tester: &WidgetTester| {
2819                let line = tester.element(find::descendant(
2820                    find::by_type::<Stepper>(),
2821                    find::by_type::<ColoredBox>(),
2822                ));
2823                colored_box_color(tester, line)
2824            };
2825
2826            // Step 1
2827            // check if I'm in step 1
2828            assert_eq!(count(tester, find::text("step1 content")), 1);
2829            assert_eq!(count(tester, find::text("step2 content")), 0);
2830
2831            assert_eq!(circle_color(tester, "1"), Some(selected_color));
2832            assert_eq!(circle_color(tester, "2"), Some(disabled_color));
2833            // in two steps case there will be single line
2834            assert_eq!(line_color(tester), selected_color);
2835
2836            // now hitting step two
2837            tester.tap(find::text("step2"));
2838            tester.pump_and_settle();
2839
2840            // check if I'm in step 1
2841            assert_eq!(count(tester, find::text("step1 content")), 0);
2842            assert_eq!(count(tester, find::text("step2 content")), 1);
2843
2844            assert_eq!(circle_color(tester, "1"), Some(selected_color));
2845            assert_eq!(circle_color(tester, "2"), Some(selected_color));
2846
2847            assert_eq!(line_color(tester), selected_color);
2848        });
2849    }
2850
2851    #[test]
2852    fn stepper_step_icon_builder_test() {
2853        test_widgets(|tester| {
2854            let logo_key: KeyRef = ValueKey::new("logo".to_owned()).into();
2855            let builder: StepIconBuilder = {
2856                let logo_key = logo_key.clone();
2857                Rc::new(move |_index, state| {
2858                    // Dart returns a `FlutterLogo(size: 18)`; any widget of that size will do.
2859                    (state == StepState::Complete).then(|| {
2860                        SizedBox::square(Some(18.0))
2861                            .key(logo_key.clone())
2862                            .into_widget()
2863                    })
2864                })
2865            };
2866            pump(
2867                tester,
2868                Stepper::new(vec![
2869                    sized_step("A", 100.0, 100.0).state(StepState::Complete),
2870                    sized_step("B", 100.0, 100.0).state(StepState::Editing),
2871                    sized_step("C", 100.0, 100.0).state(StepState::Error),
2872                ])
2873                .step_icon_builder(builder),
2874            );
2875
2876            // Finds the overridden widget for StepState.complete
2877            assert_eq!(count(tester, find::by_key(logo_key)), 1);
2878
2879            // StepState.editing and StepState.error should have a default icon
2880            assert_eq!(count(tester, find::by_icon(&Icons::edit())), 1);
2881            assert_eq!(count(tester, find::text("!")), 1);
2882        });
2883    }
2884
2885    #[test]
2886    fn step_style_test() {
2887        test_widgets(|tester| {
2888            let border = Border::all(Colors::BLACK, 1.0, BorderStyle::Solid, -1.0);
2889            let gradient = GradientRef::new(LinearGradient::new(vec![
2890                Colors::RED.primary(),
2891                Colors::BLUE.primary(),
2892            ]));
2893            let step_style = StepStyle::new()
2894                .with_color(Colors::WHITE)
2895                .with_error_color(Colors::ORANGE.primary())
2896                .with_connector_color(Colors::RED.primary())
2897                .with_connector_thickness(2.0)
2898                .with_border(border)
2899                .with_gradient(gradient.clone())
2900                .with_index_style(TextStyle::new().color(Colors::BLACK));
2901
2902            pump(
2903                tester,
2904                Stepper::new(vec![
2905                    text_step("Regular title", "Text content").step_style(step_style.clone()),
2906                ]),
2907            );
2908
2909            let style = tester.widget(find::by_type::<Stepper>(), |stepper: &Stepper| {
2910                stepper.steps[0].step_style.clone()
2911            });
2912            assert_eq!(style.as_ref(), Some(&step_style));
2913
2914            // copyWith
2915            let new_style = step_style
2916                .copy_with()
2917                .with_color(Colors::BLACK)
2918                .with_error_color(Colors::RED.primary())
2919                .with_connector_color(Colors::BLUE.primary())
2920                .with_connector_thickness(3.0)
2921                .with_border(border)
2922                .with_gradient(gradient)
2923                .with_index_style(TextStyle::new().color(Colors::BLACK));
2924
2925            assert_eq!(new_style.color, Some(Colors::BLACK));
2926            assert_eq!(new_style.error_color, Some(Colors::RED.primary()));
2927            assert_eq!(new_style.connector_color, Some(Colors::BLUE.primary()));
2928            assert_eq!(new_style.connector_thickness, Some(3.0));
2929            assert_eq!(new_style.border, step_style.border);
2930            assert_eq!(new_style.gradient, step_style.gradient);
2931            assert_eq!(new_style.index_style, step_style.index_style);
2932
2933            // merge
2934            let merged_style = step_style.merge(Some(&new_style));
2935
2936            assert_eq!(merged_style.color, Some(Colors::BLACK));
2937            assert_eq!(merged_style.error_color, Some(Colors::RED.primary()));
2938            assert_eq!(merged_style.connector_color, Some(Colors::BLUE.primary()));
2939            assert_eq!(merged_style.connector_thickness, Some(3.0));
2940            assert_eq!(merged_style.border, step_style.border);
2941            assert_eq!(merged_style.gradient, step_style.gradient);
2942            assert_eq!(merged_style.index_style, step_style.index_style);
2943        });
2944    }
2945
2946    #[test]
2947    fn a_step_style_color_fills_the_circle() {
2948        test_widgets(|tester| {
2949            let color = Color::new(0xFF123456);
2950            pump(
2951                tester,
2952                Stepper::new(vec![
2953                    text_step("A", "A").step_style(StepStyle::new().with_color(color)),
2954                ]),
2955            );
2956            assert_eq!(circle_color(tester, "1"), Some(color));
2957        });
2958    }
2959
2960    // This is a regression test for https://github.com/flutter/flutter/issues/144376.
2961    #[test]
2962    fn vertical_stepper_does_not_draw_connector_on_the_last_step() {
2963        test_widgets(|tester| {
2964            let theme = light_theme(tester);
2965            pump_in_scaffold(
2966                tester,
2967                theme,
2968                Stepper::new(vec![
2969                    text_step("step1", "step1 content"),
2970                    text_step("step2", "step2 content"),
2971                ])
2972                .current_step(1)
2973                .into_widget(),
2974            );
2975
2976            let last_connector_width = tester.widget(
2977                find::descendant(
2978                    find::by_type::<PositionedDirectional>(),
2979                    find::by_type::<Center>(),
2980                )
2981                .last(),
2982                |center: &Center| {
2983                    let child = center.child.as_ref().expect("the connector's box");
2984                    downcast_widget::<SizedBox>(&**child)
2985                        .expect("the connector is a SizedBox")
2986                        .width
2987                },
2988            );
2989
2990            assert_eq!(last_connector_width, Some(0.0));
2991        });
2992    }
2993
2994    /// Dart's `getContentClipRect().clipBehavior`: the `ClipRect` nearest above `step1 content`.
2995    fn content_clip_behavior(tester: &WidgetTester) -> Clip {
2996        tester.widget(
2997            find::ancestor(find::text("step1 content"), find::by_type::<ClipRect>()).first(),
2998            |clip_rect: &ClipRect| clip_rect.clip_behavior,
2999        )
3000    }
3001
3002    /// Dart's `buildStepper` of the clip behavior cases.
3003    fn pump_two_step_stepper(tester: &mut WidgetTester, stepper: Stepper) {
3004        let theme = light_theme(tester);
3005        pump_in_scaffold(tester, theme, stepper.into_widget());
3006    }
3007
3008    fn two_steps() -> Vec<Step> {
3009        vec![
3010            text_step("step1", "step1 content"),
3011            text_step("step2", "step2 content"),
3012        ]
3013    }
3014
3015    // This is a regression test for https://github.com/flutter/flutter/issues/66007.
3016    #[test]
3017    fn default_stepper_clip_behavior() {
3018        test_widgets(|tester| {
3019            for r#type in [StepperType::Vertical, StepperType::Horizontal] {
3020                pump_two_step_stepper(tester, Stepper::new(two_steps()).r#type(r#type));
3021                assert_eq!(content_clip_behavior(tester), Clip::None, "{type:?}");
3022            }
3023        });
3024    }
3025
3026    // This is a regression test for https://github.com/flutter/flutter/issues/66007.
3027    #[test]
3028    fn stepper_steps_can_be_clipped() {
3029        test_widgets(|tester| {
3030            for r#type in [StepperType::Vertical, StepperType::Horizontal] {
3031                pump_two_step_stepper(
3032                    tester,
3033                    Stepper::new(two_steps())
3034                        .clip_behavior(Clip::HardEdge)
3035                        .r#type(r#type),
3036                );
3037                assert_eq!(content_clip_behavior(tester), Clip::HardEdge, "{type:?}");
3038            }
3039        });
3040    }
3041
3042    // Regression test for https://github.com/flutter/flutter/issues/160156.
3043    #[test]
3044    fn vertical_stepper_border_displays_correctly() {
3045        test_widgets(|tester| {
3046            let index = Rc::new(Cell::new(0_usize));
3047            let connector_color = Color::new(0xff00ffff);
3048            let builder = {
3049                let index = Rc::clone(&index);
3050                StatefulBuilder::new(move |_app, _context, set_state| {
3051                    let tapped = Rc::clone(&index);
3052                    Stepper::new(two_steps())
3053                        .current_step(index.get())
3054                        .connector_color(Rc::new(WidgetStatePropertyAll::new(connector_color)))
3055                        .on_step_tapped(Rc::new(move |app, value| {
3056                            set_state(app, &mut |_app| tapped.set(value));
3057                        }))
3058                        .into_widget()
3059                })
3060            };
3061            let theme = light_theme(tester);
3062            pump_in_scaffold(tester, theme, builder.into_widget());
3063
3064            let find_connector = || {
3065                find::descendant(
3066                    find::by_type::<Stepper>(),
3067                    find::descendant(
3068                        find::by_type::<PositionedDirectional>(),
3069                        find::by_element_predicate("the connector", move |app, element| {
3070                            let is_connector_box =
3071                                downcast_widget::<ColoredBox>(&**element.widget(app)).is_some_and(
3072                                    |colored_box| colored_box.color.color() == connector_color,
3073                                );
3074                            let size = element.size(app);
3075                            is_connector_box
3076                                && size
3077                                    .is_some_and(|size| size.width() == 1.0 && size.height() > 0.0)
3078                        }),
3079                    ),
3080                )
3081            };
3082
3083            let verify_connector = |tester: &WidgetTester| {
3084                assert_eq!(count(tester, find_connector()), 1);
3085                let render = tester
3086                    .render_box_of(tester.element(find_connector()))
3087                    .as_object();
3088                let ops = tester.painted_ops_deep(render);
3089                assert!(paints(&ops, &[PaintCall::rect(Some(connector_color))]).is_ok());
3090            };
3091
3092            verify_connector(tester);
3093
3094            tester.tap(find::text("step2"));
3095
3096            const CHECK_COUNT: u32 = 5;
3097            let duration = K_THEME_ANIMATION_DURATION / (CHECK_COUNT + 1);
3098
3099            for _ in 0..CHECK_COUNT {
3100                tester.pump_by(duration);
3101                verify_connector(tester);
3102            }
3103        });
3104    }
3105
3106    #[test]
3107    fn vertical_stepper_active_step_has_fully_colored_connector_line() {
3108        test_widgets(|tester| {
3109            let active_color = Color::new(0xFF2196F3);
3110            let inactive_color = Color::new(0xFF9E9E9E);
3111            let theme = light_theme(tester);
3112            pump_in_scaffold(
3113                tester,
3114                theme,
3115                Stepper::new(vec![
3116                    text_step("step1", "step1 content").is_active(true),
3117                    text_step("step2", "step2 content"),
3118                ])
3119                .controls_builder(Rc::new(|_app, _context, _details| {
3120                    SizedBox::shrink().into_widget()
3121                }))
3122                .connector_thickness(3.0)
3123                .connector_color(<dyn WidgetStateProperty<Color>>::resolve_with(
3124                    move |states| {
3125                        if states.contains(&WidgetState::Selected) {
3126                            active_color
3127                        } else {
3128                            inactive_color
3129                        }
3130                    },
3131                ))
3132                .into_widget(),
3133            );
3134
3135            let connector_lines =
3136                find::by_widget_predicate("a 3-wide connector line", |_app, widget| {
3137                    downcast_widget::<ColoredBox>(widget).is_some_and(|colored_box| {
3138                        colored_box
3139                            .child
3140                            .as_ref()
3141                            .and_then(|child| downcast_widget::<SizedBox>(&**child))
3142                            .is_some_and(|sized_box| sized_box.width == Some(3.0))
3143                    })
3144                });
3145
3146            let lines = connector_lines.evaluate(tester);
3147            assert!(!lines.is_empty());
3148
3149            let colors: Vec<Color> = lines
3150                .into_iter()
3151                .map(|line| colored_box_color(tester, line))
3152                .collect();
3153            // Both top and bottom box should be colored.
3154            assert_eq!(
3155                colors
3156                    .iter()
3157                    .filter(|color| **color == active_color)
3158                    .count(),
3159                2
3160            );
3161            assert_eq!(colors.first(), Some(&active_color));
3162            assert_eq!(colors.last(), Some(&active_color));
3163        });
3164    }
3165
3166    #[test]
3167    fn stepper_does_not_crash_at_zero_area() {
3168        test_widgets(|tester| {
3169            for r#type in [StepperType::Vertical, StepperType::Horizontal] {
3170                let theme = light_theme(tester);
3171                pump_in_scaffold(
3172                    tester,
3173                    theme,
3174                    SizedBox::shrink()
3175                        .child(
3176                            Stepper::new(vec![text_step("X", "X"), text_step("Y", "Y")])
3177                                .r#type(r#type),
3178                        )
3179                        .into_widget(),
3180                );
3181                assert_eq!(tester.get_size(find::by_type::<Stepper>()), Size::ZERO);
3182            }
3183        });
3184    }
3185
3186    /// Dart's `Stepper custom headerPadding …`: how far the title moves left and down when the
3187    /// header padding becomes `custom_padding`.
3188    fn title_shift(
3189        tester: &mut WidgetTester,
3190        r#type: StepperType,
3191        custom_padding: EdgeInsets,
3192    ) -> (Rect, Rect) {
3193        let step = || vec![text_step("Step 1", "Content 1")];
3194        pump(tester, Stepper::new(step()).r#type(r#type));
3195        let default_title_rect = tester.get_rect(find::text("Step 1"));
3196
3197        pump(
3198            tester,
3199            Stepper::new(step())
3200                .r#type(r#type)
3201                .header_padding(custom_padding),
3202        );
3203        let custom_title_rect = tester.get_rect(find::text("Step 1"));
3204        (default_title_rect, custom_title_rect)
3205    }
3206
3207    #[test]
3208    fn stepper_custom_header_padding_for_vertical_stepper() {
3209        test_widgets(|tester| {
3210            // Custom padding: horizontal 12.0 (reduces left by 12.0), vertical 8.0 (increases top
3211            // by 8.0).
3212            let (default_title_rect, custom_title_rect) = title_shift(
3213                tester,
3214                StepperType::Vertical,
3215                EdgeInsets::symmetric(8.0, 12.0),
3216            );
3217
3218            assert!(custom_title_rect.left < default_title_rect.left);
3219            assert_more_or_less_equals(default_title_rect.left - custom_title_rect.left, 12.0);
3220            assert_eq!(default_title_rect.top, 24.0);
3221            assert!(custom_title_rect.top > default_title_rect.top);
3222            assert_eq!(custom_title_rect.top, 32.0);
3223            assert_more_or_less_equals(custom_title_rect.top - default_title_rect.top, 8.0);
3224        });
3225    }
3226
3227    #[test]
3228    fn stepper_custom_header_padding_for_horizontal_stepper() {
3229        test_widgets(|tester| {
3230            // Custom padding: horizontal 16.0 (reduces left by 8.0 from default 24.0), vertical 8.0
3231            // (increases top by 8.0).
3232            let (default_title_rect, custom_title_rect) = title_shift(
3233                tester,
3234                StepperType::Horizontal,
3235                EdgeInsets::symmetric(8.0, 16.0),
3236            );
3237
3238            assert!(custom_title_rect.left < default_title_rect.left);
3239            assert_more_or_less_equals(default_title_rect.left - custom_title_rect.left, 8.0);
3240            assert_eq!(default_title_rect.top, 24.0);
3241            assert!(custom_title_rect.top > default_title_rect.top);
3242            assert_eq!(custom_title_rect.top, 32.0);
3243            assert_more_or_less_equals(custom_title_rect.top - default_title_rect.top, 8.0);
3244        });
3245    }
3246
3247    #[test]
3248    fn stepper_custom_content_padding_for_horizontal_stepper() {
3249        test_widgets(|tester| {
3250            let custom_padding: EdgeInsetsGeometry = EdgeInsets::all(16.0).into();
3251            pump(
3252                tester,
3253                Stepper::new(vec![text_step("Step 1", "Content 1")])
3254                    .r#type(StepperType::Horizontal)
3255                    .content_padding(custom_padding),
3256            );
3257
3258            // The content is in a ListView, verify its padding
3259            let padding =
3260                stepper_list_view(tester, |list_view| list_view.box_scroll_view_data().padding);
3261            assert_eq!(padding, Some(custom_padding));
3262        });
3263    }
3264
3265    #[test]
3266    fn stepper_custom_content_padding_for_vertical_stepper() {
3267        test_widgets(|tester| {
3268            pump(
3269                tester,
3270                Stepper::new(vec![text_step("Step 1", "Content 1")])
3271                    .content_padding(EdgeInsetsDirectional::only(48.0, 0.0, 16.0, 16.0)),
3272            );
3273
3274            // Find the Padding widget that wraps the step content and verify the effective
3275            // padding.
3276            let expected = EdgeInsets::only(48.0, 0.0, 16.0, 16.0);
3277            assert!(paddings_above(tester, "Content 1").contains(&expected));
3278        });
3279    }
3280
3281    #[test]
3282    fn stepper_default_content_padding_for_horizontal_stepper() {
3283        test_widgets(|tester| {
3284            pump(
3285                tester,
3286                Stepper::new(vec![text_step("Step 1", "Content 1")])
3287                    .r#type(StepperType::Horizontal),
3288            );
3289
3290            // Verify the default padding is applied to ListView
3291            let padding =
3292                stepper_list_view(tester, |list_view| list_view.box_scroll_view_data().padding);
3293            assert_eq!(padding, Some(EdgeInsets::all(24.0).into()));
3294        });
3295    }
3296
3297    /// The padding nearest above `Content 1`, resolved left to right: Dart's
3298    /// `tester.widget<Padding>(contentPadding.first).padding.resolve(TextDirection.ltr)`.
3299    fn content_padding_of(tester: &mut WidgetTester, stepper: Stepper) -> EdgeInsets {
3300        pump(tester, stepper);
3301        paddings_above(tester, "Content 1")[0]
3302    }
3303
3304    #[test]
3305    fn stepper_vertical_content_padding_includes_step_icon_margin_start_value() {
3306        test_widgets(|tester| {
3307            let padding = content_padding_of(
3308                tester,
3309                Stepper::new(vec![text_step("Step 1", "Content 1")])
3310                    .step_icon_margin(EdgeInsets::only(16.0, 0.0, 8.0, 0.0))
3311                    .content_padding(EdgeInsetsDirectional::only(40.0, 0.0, 20.0, 16.0)),
3312            );
3313
3314            // The effective padding should be the content padding plus the icon margin's left:
3315            // start: 40.0 + 16.0 = 56.0
3316            assert_eq!(padding, EdgeInsets::only(56.0, 0.0, 20.0, 16.0));
3317        });
3318    }
3319
3320    #[test]
3321    fn stepper_vertical_default_content_padding_includes_step_icon_margin_start_value() {
3322        test_widgets(|tester| {
3323            let padding = content_padding_of(
3324                tester,
3325                Stepper::new(vec![text_step("Step 1", "Content 1")])
3326                    .step_icon_margin(EdgeInsets::only(10.0, 0.0, 0.0, 0.0)),
3327            );
3328
3329            // Default padding is start: 60.0, end: 24.0, bottom: 24.0
3330            // Plus stepIconMargin.left: 10.0
3331            // Expected start: 60.0 + 10.0 = 70.0
3332            assert_eq!(padding, EdgeInsets::only(70.0, 0.0, 24.0, 24.0));
3333        });
3334    }
3335
3336    #[test]
3337    fn stepper_vertical_content_padding_without_step_icon_margin_uses_default() {
3338        test_widgets(|tester| {
3339            let padding =
3340                content_padding_of(tester, Stepper::new(vec![text_step("Step 1", "Content 1")]));
3341
3342            // Default padding without stepIconMargin
3343            assert_eq!(padding, EdgeInsets::only(60.0, 0.0, 24.0, 24.0));
3344        });
3345    }
3346}