Skip to main content

waft_material/
expansion_panel.rs

1//! Flutter counterpart: material_ui's `expansion_panel.dart`.
2
3use std::fmt;
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_animation::{Curves, Interval};
8use waft_embedder::Color;
9use waft_foundation::{AnyEq, App, Handle, HandleId, Listener, ValueKey};
10use waft_painting::{EdgeInsets, EdgeInsetsDirectional};
11use waft_rendering::BoxConstraints;
12use waft_widgets::{
13    AnimatedContainer, AnimatedCrossFade, BuildContext, Column, ConstrainedBox, CrossFadeState,
14    Expanded, IgnorePointer, IntoWidget, KeyRef, LimitedBox, MergeSemantics, Padding, Row,
15    Semantics, SizedBox, State, StateData, StatefulWidget, WidgetRef,
16};
17
18use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
19use crate::expand_icon::ExpandIcon;
20use crate::ink_well::InkWell;
21use crate::material_localizations::MaterialLocalizations;
22use crate::mergeable_material::{
23    MaterialGap, MaterialSlice, MergeableMaterial, MergeableMaterialItem,
24};
25use crate::shadows::k_elevation_to_shadow;
26use crate::theme::K_THEME_ANIMATION_DURATION;
27
28const K_PANEL_HEADER_COLLAPSED_HEIGHT: f64 = K_MIN_INTERACTIVE_DIMENSION;
29const K_PANEL_HEADER_EXPANDED_DEFAULT_PADDING: EdgeInsets =
30    EdgeInsets::symmetric(64.0 - K_PANEL_HEADER_COLLAPSED_HEIGHT, 0.0);
31const K_EXPAND_ICON_PADDING: EdgeInsets = EdgeInsets::all(12.0);
32
33/// Signature for the callback that's called when an [`ExpansionPanel`] is expanded or
34/// collapsed.
35///
36/// The position of the panel within an [`ExpansionPanelList`] is given by `panel_index`.
37pub type ExpansionPanelCallback = Rc<dyn Fn(&mut App, usize, bool)>;
38
39/// Signature for the callback that's called when the header of the [`ExpansionPanel`] needs to
40/// rebuild.
41pub type ExpansionPanelHeaderBuilder = Rc<dyn Fn(&mut App, BuildContext, bool) -> WidgetRef>;
42
43/// A material expansion panel. It has a header and a body and can be either expanded or
44/// collapsed. The body of the panel is only visible when it is expanded.
45///
46/// Expansion panels are only intended to be used as children for [`ExpansionPanelList`].
47#[derive(Clone)]
48pub struct ExpansionPanel {
49    /// The widget builder that builds the expansion panels' header.
50    pub header_builder: ExpansionPanelHeaderBuilder,
51    /// The body of the expansion panel that's displayed below the header.
52    ///
53    /// This widget is visible only when the panel is expanded.
54    pub body: WidgetRef,
55    /// Whether the panel is expanded.
56    pub is_expanded: bool,
57    /// Defines the splash color of the panel if [`can_tap_on_header`](Self::can_tap_on_header)
58    /// is true, or the splash color of the expand/collapse IconButton if it is false.
59    pub splash_color: Option<Color>,
60    /// Defines the highlight color of the panel if
61    /// [`can_tap_on_header`](Self::can_tap_on_header) is true, or the highlight color of the
62    /// expand/collapse IconButton if it is false.
63    pub highlight_color: Option<Color>,
64    /// Whether tapping on the panel's header will expand/collapse it.
65    pub can_tap_on_header: bool,
66    /// Defines the background color of the panel.
67    ///
68    /// Defaults to `ThemeData::card_color`.
69    pub background_color: Option<Color>,
70}
71
72impl ExpansionPanel {
73    /// Creates an expansion panel to be used as a child for [`ExpansionPanelList`]; Dart's
74    /// optional named arguments are the setters.
75    #[cfg_attr(debug_assertions, track_caller)]
76    pub fn new<K>(header_builder: ExpansionPanelHeaderBuilder, body: impl IntoWidget<K>) -> Self {
77        ExpansionPanel {
78            header_builder,
79            body: body.into_widget(),
80            is_expanded: false,
81            splash_color: None,
82            highlight_color: None,
83            can_tap_on_header: false,
84            background_color: None,
85        }
86    }
87
88    /// Dart `ExpansionPanel(isExpanded:)`.
89    pub fn is_expanded(mut self, is_expanded: bool) -> Self {
90        self.is_expanded = is_expanded;
91        self
92    }
93
94    /// Dart `ExpansionPanel(canTapOnHeader:)`.
95    pub fn can_tap_on_header(mut self, can_tap_on_header: bool) -> Self {
96        self.can_tap_on_header = can_tap_on_header;
97        self
98    }
99
100    /// Dart `ExpansionPanel(backgroundColor:)`.
101    pub fn background_color(mut self, background_color: Color) -> Self {
102        self.background_color = Some(background_color);
103        self
104    }
105
106    /// Dart `ExpansionPanel(splashColor:)`.
107    pub fn splash_color(mut self, splash_color: Color) -> Self {
108        self.splash_color = Some(splash_color);
109        self
110    }
111
112    /// Dart `ExpansionPanel(highlightColor:)`.
113    pub fn highlight_color(mut self, highlight_color: Color) -> Self {
114        self.highlight_color = Some(highlight_color);
115        self
116    }
117}
118
119impl fmt::Debug for ExpansionPanel {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.debug_struct("ExpansionPanel")
122            .field("is_expanded", &self.is_expanded)
123            .field("can_tap_on_header", &self.can_tap_on_header)
124            .finish_non_exhaustive()
125    }
126}
127
128/// Dart's `==` on two radio values: the values', not the shared pointers'.
129fn same_value(a: &Rc<dyn AnyEq>, b: &Rc<dyn AnyEq>) -> bool {
130    a == b
131}
132
133/// An expansion panel that allows for radio-like functionality. This means that at any given
134/// time, at most, one [`ExpansionPanelRadio`] can remain expanded.
135///
136/// A unique identifier [`value`](Self::value) must be assigned to each panel. This identifier
137/// allows the [`ExpansionPanelList`] to determine which [`ExpansionPanelRadio`] instance should
138/// be expanded.
139///
140/// See [`ExpansionPanelList::radio`] for a sample implementation.
141#[derive(Clone)]
142pub struct ExpansionPanelRadio {
143    /// Dart's `extends ExpansionPanel`: the fields it inherits.
144    pub panel: ExpansionPanel,
145    /// The value that uniquely identifies a radio panel so that the currently selected radio
146    /// panel can be identified.
147    pub value: Rc<dyn AnyEq>,
148}
149
150impl ExpansionPanelRadio {
151    /// An expansion panel that allows for radio functionality; Dart's optional named arguments
152    /// are the setters.
153    #[cfg_attr(debug_assertions, track_caller)]
154    pub fn new<K>(
155        value: impl AnyEq,
156        header_builder: ExpansionPanelHeaderBuilder,
157        body: impl IntoWidget<K>,
158    ) -> Self {
159        ExpansionPanelRadio {
160            panel: ExpansionPanel::new(header_builder, body),
161            value: Rc::new(value),
162        }
163    }
164
165    /// Dart `ExpansionPanelRadio(canTapOnHeader:)`.
166    pub fn can_tap_on_header(mut self, can_tap_on_header: bool) -> Self {
167        self.panel = self.panel.can_tap_on_header(can_tap_on_header);
168        self
169    }
170
171    /// Dart `ExpansionPanelRadio(backgroundColor:)`.
172    pub fn background_color(mut self, background_color: Color) -> Self {
173        self.panel = self.panel.background_color(background_color);
174        self
175    }
176
177    /// Dart `ExpansionPanelRadio(splashColor:)`.
178    pub fn splash_color(mut self, splash_color: Color) -> Self {
179        self.panel = self.panel.splash_color(splash_color);
180        self
181    }
182
183    /// Dart `ExpansionPanelRadio(highlightColor:)`.
184    pub fn highlight_color(mut self, highlight_color: Color) -> Self {
185        self.panel = self.panel.highlight_color(highlight_color);
186        self
187    }
188}
189
190impl fmt::Debug for ExpansionPanelRadio {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        f.debug_struct("ExpansionPanelRadio")
193            .field("panel", &self.panel)
194            .finish_non_exhaustive()
195    }
196}
197
198/// A material expansion panel list that lays out its children and animates expansions.
199///
200/// The [`expansion_callback`](Self::expansion_callback) is called when the expansion state
201/// changes. For normal [`ExpansionPanelList`] widgets, it is the responsibility of the parent
202/// widget to rebuild the [`ExpansionPanelList`] with updated values for
203/// [`ExpansionPanel::is_expanded`]. For [`ExpansionPanelList::radio`] widgets, the open state is
204/// tracked internally and the callback is invoked both for the previously open panel, which is
205/// closing, and the previously closed panel, which is opening.
206pub struct ExpansionPanelList {
207    pub key: Option<KeyRef>,
208    /// The children of the expansion panel list. They are laid out in a similar fashion to
209    /// `ListBody`.
210    pub children: Vec<ExpansionPanel>,
211    /// The callback that gets called whenever one of the expand/collapse buttons is pressed.
212    /// The arguments passed to the callback are the index of the pressed panel and whether the
213    /// panel is currently expanded or not.
214    pub expansion_callback: Option<ExpansionPanelCallback>,
215    /// The duration of the expansion animation.
216    pub animation_duration: Duration,
217    // Whether multiple panels can be open simultaneously.
218    allow_only_one_panel_open: bool,
219    // Dart's `ExpansionPanelRadio.value` of each child of a radio list, in order; empty
220    // otherwise.
221    radio_values: Vec<Rc<dyn AnyEq>>,
222    /// The value of the panel that initially begins open. (This value is only used when
223    /// initializing with the [`ExpansionPanelList::radio`] constructor.)
224    pub initial_open_panel_value: Option<Rc<dyn AnyEq>>,
225    /// The padding that surrounds the panel header when expanded.
226    ///
227    /// By default, 16px of space is added to the header vertically (above and below) during
228    /// expansion.
229    pub expanded_header_padding: EdgeInsets,
230    /// Defines color for the divider when [`ExpansionPanel::is_expanded`] is false.
231    ///
232    /// If `divider_color` is `None`, then `DividerThemeData::color` is used. If that is `None`,
233    /// then `ThemeData::divider_color` is used.
234    pub divider_color: Option<Color>,
235    /// Defines elevation for the [`ExpansionPanel`] while it's expanded.
236    ///
237    /// By default, the value of elevation is 2.
238    pub elevation: f64,
239    /// The color of the icon. Defaults to `Colors::BLACK54` when the theme's brightness is
240    /// light and to `Colors::WHITE60` when it is dark.
241    pub expand_icon_color: Option<Color>,
242    /// Defines the [`MaterialGap::size`] of the gap between panels when expanded.
243    ///
244    /// Defaults to 16.0.
245    pub material_gap_size: f64,
246}
247
248impl ExpansionPanelList {
249    /// Creates an expansion panel list widget. The `expansion_callback` is triggered when an
250    /// expansion panel expand/collapse button is pushed; Dart's optional named arguments are
251    /// the setters.
252    pub fn new() -> ExpansionPanelList {
253        ExpansionPanelList {
254            key: None,
255            children: Vec::new(),
256            expansion_callback: None,
257            animation_duration: K_THEME_ANIMATION_DURATION,
258            allow_only_one_panel_open: false,
259            radio_values: Vec::new(),
260            initial_open_panel_value: None,
261            expanded_header_padding: K_PANEL_HEADER_EXPANDED_DEFAULT_PADDING,
262            divider_color: None,
263            elevation: 2.0,
264            expand_icon_color: None,
265            material_gap_size: 16.0,
266        }
267    }
268
269    /// Creates a radio expansion panel list widget.
270    ///
271    /// This widget allows for at most one panel in the list to be open. The expansion panel
272    /// callback is triggered when an expansion panel expand/collapse button is pushed. The
273    /// `children` are radio panels, each with a unique value.
274    pub fn radio(children: impl IntoIterator<Item = ExpansionPanelRadio>) -> ExpansionPanelList {
275        let (children, radio_values) = children
276            .into_iter()
277            .map(|radio| (radio.panel, radio.value))
278            .unzip();
279        ExpansionPanelList {
280            children,
281            allow_only_one_panel_open: true,
282            radio_values,
283            ..ExpansionPanelList::new()
284        }
285    }
286
287    /// Dart `ExpansionPanelList(key:)`.
288    pub fn key(mut self, key: KeyRef) -> ExpansionPanelList {
289        self.key = Some(key);
290        self
291    }
292
293    /// Dart `ExpansionPanelList(children:)`.
294    pub fn children(
295        mut self,
296        children: impl IntoIterator<Item = ExpansionPanel>,
297    ) -> ExpansionPanelList {
298        debug_assert!(
299            !self.allow_only_one_panel_open,
300            "a radio list takes its children in ExpansionPanelList::radio"
301        );
302        self.children = children.into_iter().collect();
303        self
304    }
305
306    /// Dart `ExpansionPanelList(expansionCallback:)`.
307    pub fn expansion_callback(
308        mut self,
309        expansion_callback: ExpansionPanelCallback,
310    ) -> ExpansionPanelList {
311        self.expansion_callback = Some(expansion_callback);
312        self
313    }
314
315    /// Dart `ExpansionPanelList(animationDuration:)`.
316    pub fn animation_duration(mut self, animation_duration: Duration) -> ExpansionPanelList {
317        self.animation_duration = animation_duration;
318        self
319    }
320
321    /// Dart `ExpansionPanelList.radio(initialOpenPanelValue:)`.
322    pub fn initial_open_panel_value(mut self, value: impl AnyEq) -> ExpansionPanelList {
323        self.initial_open_panel_value = Some(Rc::new(value));
324        self
325    }
326
327    /// Dart `ExpansionPanelList(expandedHeaderPadding:)`.
328    pub fn expanded_header_padding(
329        mut self,
330        expanded_header_padding: EdgeInsets,
331    ) -> ExpansionPanelList {
332        self.expanded_header_padding = expanded_header_padding;
333        self
334    }
335
336    /// Dart `ExpansionPanelList(dividerColor:)`.
337    pub fn divider_color(mut self, divider_color: Color) -> ExpansionPanelList {
338        self.divider_color = Some(divider_color);
339        self
340    }
341
342    /// Dart `ExpansionPanelList(elevation:)`.
343    pub fn elevation(mut self, elevation: f64) -> ExpansionPanelList {
344        self.elevation = elevation;
345        self
346    }
347
348    /// Dart `ExpansionPanelList(expandIconColor:)`.
349    pub fn expand_icon_color(mut self, expand_icon_color: Color) -> ExpansionPanelList {
350        self.expand_icon_color = Some(expand_icon_color);
351        self
352    }
353
354    /// Dart `ExpansionPanelList(materialGapSize:)`.
355    pub fn material_gap_size(mut self, material_gap_size: f64) -> ExpansionPanelList {
356        self.material_gap_size = material_gap_size;
357        self
358    }
359}
360
361impl Default for ExpansionPanelList {
362    fn default() -> ExpansionPanelList {
363        ExpansionPanelList::new()
364    }
365}
366
367impl fmt::Debug for ExpansionPanelList {
368    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369        f.debug_struct("ExpansionPanelList")
370            .field("children", &self.children.len())
371            .field("elevation", &self.elevation)
372            .finish_non_exhaustive()
373    }
374}
375
376impl StatefulWidget for ExpansionPanelList {
377    type State = ExpansionPanelListState;
378
379    fn key(&self) -> Option<&KeyRef> {
380        self.key.as_ref()
381    }
382
383    fn create_state(&self) -> ExpansionPanelListState {
384        ExpansionPanelListState {
385            state: StateData::new(),
386            current_open_panel: None,
387        }
388    }
389}
390
391/// Dart's `_ExpansionPanelListState`.
392pub struct ExpansionPanelListState {
393    state: StateData<ExpansionPanelList>,
394    // Dart keeps the open `ExpansionPanelRadio`; its value is all that is read.
395    current_open_panel: Option<Rc<dyn AnyEq>>,
396}
397
398impl ExpansionPanelListState {
399    fn all_identifiers_unique(self: Handle<Self>, app: &App) -> bool {
400        let list = self.widget(app);
401        let mut unique: Vec<&Rc<dyn AnyEq>> = Vec::new();
402        for value in &list.radio_values {
403            if !unique.iter().any(|seen| same_value(seen, value)) {
404                unique.push(value);
405            }
406        }
407        unique.len() == list.children.len()
408    }
409
410    fn is_child_expanded(self: Handle<Self>, app: &App, index: usize) -> bool {
411        let list = self.widget(app);
412        if list.allow_only_one_panel_open {
413            let radio_value = &list.radio_values[index];
414            return app
415                .get(self)
416                .current_open_panel
417                .as_ref()
418                .is_some_and(|open| same_value(open, radio_value));
419        }
420        list.children[index].is_expanded
421    }
422
423    fn handle_pressed(self: Handle<Self>, app: &mut App, is_expanded: bool, index: usize) {
424        if self.widget(app).allow_only_one_panel_open {
425            let pressed_child = self.widget(app).radio_values[index].clone();
426
427            // If another ExpansionPanelRadio was already open, apply its expansionCallback (if
428            // any) to false, because it's closing.
429            for child_index in 0..self.widget(app).children.len() {
430                let callback = self.widget(app).expansion_callback.clone();
431                let child = &self.widget(app).radio_values[child_index];
432                let is_open = app
433                    .get(self)
434                    .current_open_panel
435                    .as_ref()
436                    .is_some_and(|open| same_value(open, child));
437                if let Some(callback) = callback
438                    && child_index != index
439                    && is_open
440                {
441                    callback(app, child_index, false);
442                }
443            }
444
445            self.set_state(app, |state| {
446                state.current_open_panel = if is_expanded {
447                    None
448                } else {
449                    Some(pressed_child)
450                };
451            });
452        }
453        // !is_expanded is passed because, when handle_pressed runs, the state of the panel to
454        // expand is not yet expanded.
455        if let Some(callback) = self.widget(app).expansion_callback.clone() {
456            callback(app, index, !is_expanded);
457        }
458    }
459
460    fn search_panel_by_value(
461        self: Handle<Self>,
462        app: &App,
463        value: Option<&Rc<dyn AnyEq>>,
464    ) -> Option<Rc<dyn AnyEq>> {
465        let value = value?;
466        self.widget(app)
467            .radio_values
468            .iter()
469            .find(|panel| same_value(panel, value))
470            .cloned()
471    }
472
473    fn header(
474        self: Handle<Self>,
475        app: &mut App,
476        context: BuildContext,
477        index: usize,
478        child: &ExpansionPanel,
479    ) -> WidgetRef {
480        let list = self.widget(app);
481        let animation_duration = list.animation_duration;
482        let expanded_header_padding = list.expanded_header_padding;
483        let expand_icon_color = list.expand_icon_color;
484        let expanded = self.is_child_expanded(app, index);
485        let header_widget = (child.header_builder)(app, context, expanded);
486
487        let mut expand_icon =
488            ExpandIcon::new(Some(Rc::new(move |app: &mut App, is_expanded: bool| {
489                self.handle_pressed(app, is_expanded, index)
490            })))
491            .is_expanded(expanded)
492            .padding(K_EXPAND_ICON_PADDING);
493        if let Some(color) = expand_icon_color {
494            expand_icon = expand_icon.color(color);
495        }
496        if let Some(splash_color) = child.splash_color {
497            expand_icon = expand_icon.splash_color(splash_color);
498        }
499        if let Some(highlight_color) = child.highlight_color {
500            expand_icon = expand_icon.highlight_color(highlight_color);
501        }
502        let mut expand_icon_padded = Padding::new(EdgeInsetsDirectional::only(0.0, 0.0, 8.0, 0.0))
503            .child(
504                IgnorePointer::new()
505                    .ignoring(child.can_tap_on_header)
506                    .child(expand_icon),
507            )
508            .into_widget();
509
510        if !child.can_tap_on_header {
511            let localizations = <dyn MaterialLocalizations>::of(app, context);
512            expand_icon_padded = Semantics::new()
513                .label(if expanded {
514                    localizations.expanded_icon_tap_hint()
515                } else {
516                    localizations.collapsed_icon_tap_hint()
517                })
518                .container(true)
519                .child(expand_icon_padded)
520                .into_widget();
521        }
522        let header = Row::new()
523            .children(vec![
524                Expanded::new(
525                    AnimatedContainer::new(animation_duration)
526                        .curve(Curves::fast_out_slow_in())
527                        .margin(if expanded {
528                            expanded_header_padding
529                        } else {
530                            EdgeInsets::ZERO
531                        })
532                        .child(
533                            ConstrainedBox::new(
534                                BoxConstraints::new().min_height(K_PANEL_HEADER_COLLAPSED_HEIGHT),
535                            )
536                            .child(header_widget),
537                        ),
538                )
539                .into_widget(),
540                expand_icon_padded,
541            ])
542            .into_widget();
543        if !child.can_tap_on_header {
544            return header;
545        }
546        let mut ink_well = InkWell::new()
547            .on_tap(Listener::new(move |app: &mut App| {
548                let expanded = self.is_child_expanded(app, index);
549                self.handle_pressed(app, expanded, index);
550            }))
551            .child(header);
552        if let Some(splash_color) = child.splash_color {
553            ink_well = ink_well.splash_color(splash_color);
554        }
555        if let Some(highlight_color) = child.highlight_color {
556            ink_well = ink_well.highlight_color(highlight_color);
557        }
558        MergeSemantics::new().child(ink_well).into_widget()
559    }
560
561    fn body(self: Handle<Self>, app: &App, index: usize, child: &ExpansionPanel) -> WidgetRef {
562        AnimatedCrossFade::new(
563            LimitedBox::new()
564                .max_width(0.0)
565                .child(SizedBox::new().width(f64::INFINITY).height(0.0)),
566            child.body.clone(),
567            if self.is_child_expanded(app, index) {
568                CrossFadeState::ShowSecond
569            } else {
570                CrossFadeState::ShowFirst
571            },
572            self.widget(app).animation_duration,
573        )
574        .first_curve(Rc::new(Interval::new(0.0, 0.6, Curves::fast_out_slow_in())))
575        .second_curve(Rc::new(Interval::new(0.4, 1.0, Curves::fast_out_slow_in())))
576        .size_curve(Curves::fast_out_slow_in())
577        .into_widget()
578    }
579}
580
581impl fmt::Debug for ExpansionPanelListState {
582    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583        f.debug_struct("ExpansionPanelListState")
584            .finish_non_exhaustive()
585    }
586}
587
588impl State for ExpansionPanelListState {
589    type Widget = ExpansionPanelList;
590    waft_widgets::state_accessors!();
591
592    fn init_state(self: Handle<Self>, app: &mut App) {
593        if self.widget(app).allow_only_one_panel_open {
594            debug_assert!(
595                self.all_identifiers_unique(app),
596                "All ExpansionPanelRadio identifier values must be unique."
597            );
598            let initial_open_panel_value = self.widget(app).initial_open_panel_value.clone();
599            if initial_open_panel_value.is_some() {
600                app.get_mut(self).current_open_panel =
601                    self.search_panel_by_value(app, initial_open_panel_value.as_ref());
602            }
603        }
604    }
605
606    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ExpansionPanelList) {
607        if self.widget(app).allow_only_one_panel_open {
608            debug_assert!(
609                self.all_identifiers_unique(app),
610                "All ExpansionPanelRadio identifier values must be unique."
611            );
612            // If the previous widget was non-radio ExpansionPanelList, initialize the open panel
613            // to widget.initial_open_panel_value.
614            if !old_widget.allow_only_one_panel_open {
615                let initial_open_panel_value = self.widget(app).initial_open_panel_value.clone();
616                app.get_mut(self).current_open_panel =
617                    self.search_panel_by_value(app, initial_open_panel_value.as_ref());
618            }
619        } else {
620            app.get_mut(self).current_open_panel = None;
621        }
622    }
623
624    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
625        let elevation = self.widget(app).elevation;
626        debug_assert!(
627            elevation.fract() == 0.0 && k_elevation_to_shadow(elevation as i32).is_some(),
628            "Invalid value for elevation. See the kElevationToShadow constant for possible \
629             elevation values."
630        );
631
632        let children = self.widget(app).children.clone();
633        let material_gap_size = self.widget(app).material_gap_size;
634        let mut items: Vec<MergeableMaterialItem> = Vec::new();
635
636        for (index, child) in children.iter().enumerate() {
637            if self.is_child_expanded(app, index)
638                && index != 0
639                && !self.is_child_expanded(app, index - 1)
640            {
641                items.push(
642                    MaterialGap::new(salted_key(context, index * 2 - 1))
643                        .size(material_gap_size)
644                        .into(),
645                );
646            }
647
648            let header = self.header(app, context, index, child);
649            let body = self.body(app, index, child);
650            let mut slice = MaterialSlice::new(
651                salted_key(context, index * 2),
652                Column::new().children(vec![header, body]),
653            );
654            if let Some(background_color) = child.background_color {
655                slice = slice.color(background_color);
656            }
657            items.push(slice.into());
658
659            if self.is_child_expanded(app, index) && index != children.len() - 1 {
660                items.push(
661                    MaterialGap::new(salted_key(context, index * 2 + 1))
662                        .size(material_gap_size)
663                        .into(),
664                );
665            }
666        }
667
668        let mut material = MergeableMaterial::new()
669            .has_dividers(true)
670            .elevation(elevation)
671            .children(items);
672        if let Some(divider_color) = self.widget(app).divider_color {
673            material = material.divider_color(divider_color);
674        }
675        material.into_widget()
676    }
677}
678
679/// Dart's `_SaltedKey<BuildContext, int>`: a local key that is this list's own, never equal to
680/// a key the app gives.
681fn salted_key(context: BuildContext, value: usize) -> KeyRef {
682    #[derive(Debug, PartialEq, Hash)]
683    struct SaltedKey(HandleId, usize);
684    KeyRef::from(ValueKey::new(SaltedKey(context.id(), value)))
685}
686
687#[cfg(test)]
688mod tests {
689    use std::cell::{Cell, RefCell};
690    use std::rc::Rc;
691    use std::time::Duration;
692
693    use waft_embedder::{Color, Rect};
694    use waft_foundation::{App, Handle, Listener, ValueKey};
695    use waft_painting::{AlignmentGeometry, BoxDecoration, DecorationRef, EdgeInsets};
696    use waft_rendering::AnyRenderBox;
697    use waft_widgets::testing::{
698        Finder, WidgetTester, assert_f32_equals, expect, find, finds_n_widgets, finds_nothing,
699        finds_one_widget, test_widgets,
700    };
701    use waft_widgets::{
702        AnimatedContainer, AnimatedSize, BuildContext, Column, Container, DecoratedBox,
703        IgnorePointer, IntoWidget, KeyRef, LayoutBuilder, ListView, Placeholder,
704        SingleChildScrollView, SizedBox, State, StateData, StateSetter, StatefulBuilder,
705        StatefulWidget, Text, WidgetRef, downcast_widget,
706    };
707
708    use super::{
709        ExpansionPanel, ExpansionPanelCallback, ExpansionPanelHeaderBuilder, ExpansionPanelList,
710        ExpansionPanelRadio,
711    };
712    use crate::app::MaterialApp;
713    use crate::colors::Colors;
714    use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
715    use crate::expand_icon::ExpandIcon;
716    use crate::floating_action_button::FloatingActionButton;
717    use crate::icon_button::IconButton;
718    use crate::ink_well::InkWell;
719    use crate::list_tile::ListTile;
720    use crate::mergeable_material::{MergeableMaterial, MergeableMaterialItem};
721    use crate::scaffold::Scaffold;
722    use crate::theme::K_THEME_ANIMATION_DURATION;
723
724    /// Dart's `SimpleExpansionPanelListTestWidget`: two panels, each toggled by the list's
725    /// callback.
726    #[derive(Debug)]
727    struct SimpleExpansionPanelListTestWidget {
728        first_panel_key: Option<KeyRef>,
729        second_panel_key: Option<KeyRef>,
730        can_tap_on_header: bool,
731        divider_color: Option<Color>,
732        elevation: f64,
733        /// If `None`, the default `ExpansionPanelList`'s expanded header padding value is
734        /// applied via [`default_expanded_header_padding`](Self::default_expanded_header_padding).
735        expanded_header_padding: Option<EdgeInsets>,
736    }
737
738    impl SimpleExpansionPanelListTestWidget {
739        fn new() -> SimpleExpansionPanelListTestWidget {
740            SimpleExpansionPanelListTestWidget {
741                first_panel_key: None,
742                second_panel_key: None,
743                can_tap_on_header: false,
744                divider_color: None,
745                elevation: 2.0,
746                expanded_header_padding: None,
747            }
748        }
749
750        fn first_panel_key(mut self, key: KeyRef) -> SimpleExpansionPanelListTestWidget {
751            self.first_panel_key = Some(key);
752            self
753        }
754
755        fn second_panel_key(mut self, key: KeyRef) -> SimpleExpansionPanelListTestWidget {
756            self.second_panel_key = Some(key);
757            self
758        }
759
760        fn can_tap_on_header(
761            mut self,
762            can_tap_on_header: bool,
763        ) -> SimpleExpansionPanelListTestWidget {
764            self.can_tap_on_header = can_tap_on_header;
765            self
766        }
767
768        fn divider_color(mut self, divider_color: Color) -> SimpleExpansionPanelListTestWidget {
769            self.divider_color = Some(divider_color);
770            self
771        }
772
773        fn elevation(mut self, elevation: f64) -> SimpleExpansionPanelListTestWidget {
774            self.elevation = elevation;
775            self
776        }
777
778        fn expanded_header_padding(
779            mut self,
780            expanded_header_padding: EdgeInsets,
781        ) -> SimpleExpansionPanelListTestWidget {
782            self.expanded_header_padding = Some(expanded_header_padding);
783            self
784        }
785
786        /// Mirrors the default expanded header padding as its source constants are private.
787        fn default_expanded_header_padding() -> EdgeInsets {
788            ExpansionPanelList::new().expanded_header_padding
789        }
790    }
791
792    struct SimpleExpansionPanelListTestWidgetState {
793        state: StateData<SimpleExpansionPanelListTestWidget>,
794        extended_state: [bool; 2],
795    }
796
797    impl StatefulWidget for SimpleExpansionPanelListTestWidget {
798        type State = SimpleExpansionPanelListTestWidgetState;
799
800        fn create_state(&self) -> SimpleExpansionPanelListTestWidgetState {
801            SimpleExpansionPanelListTestWidgetState {
802                state: StateData::new(),
803                extended_state: [false, false],
804            }
805        }
806    }
807
808    impl State for SimpleExpansionPanelListTestWidgetState {
809        type Widget = SimpleExpansionPanelListTestWidget;
810        waft_widgets::state_accessors!();
811
812        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
813            let widget = self.widget(app);
814            let first_panel_key = widget.first_panel_key.clone();
815            let second_panel_key = widget.second_panel_key.clone();
816            let can_tap_on_header = widget.can_tap_on_header;
817            let divider_color = widget.divider_color;
818            let elevation = widget.elevation;
819            let expanded_header_padding = widget.expanded_header_padding.unwrap_or_else(
820                SimpleExpansionPanelListTestWidget::default_expanded_header_padding,
821            );
822            let extended_state = app.get(self).extended_state;
823            let mut list = ExpansionPanelList::new()
824                .expanded_header_padding(expanded_header_padding)
825                .expansion_callback(Rc::new(move |app: &mut App, index: usize, _is_expanded| {
826                    self.set_state(app, |state| {
827                        state.extended_state[index] = !state.extended_state[index];
828                    });
829                }))
830                .elevation(elevation)
831                .children([
832                    ExpansionPanel::new(
833                        text_header("A", "B", first_panel_key),
834                        SizedBox::new().height(100.0),
835                    )
836                    .can_tap_on_header(can_tap_on_header)
837                    .is_expanded(extended_state[0]),
838                    ExpansionPanel::new(
839                        text_header("C", "D", second_panel_key),
840                        SizedBox::new().height(100.0),
841                    )
842                    .can_tap_on_header(can_tap_on_header)
843                    .is_expanded(extended_state[1]),
844                ]);
845            list.divider_color = divider_color;
846            list.into_widget()
847        }
848    }
849
850    impl std::fmt::Debug for SimpleExpansionPanelListTestWidgetState {
851        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
852            f.debug_struct("SimpleExpansionPanelListTestWidgetState")
853                .field("extended_state", &self.extended_state)
854                .finish_non_exhaustive()
855        }
856    }
857
858    /// Dart's `(context, isExpanded) => Text(isExpanded ? expanded : collapsed, key: key)`.
859    fn text_header(
860        collapsed: &'static str,
861        expanded: &'static str,
862        key: Option<KeyRef>,
863    ) -> ExpansionPanelHeaderBuilder {
864        Rc::new(move |_app, _context, is_expanded| {
865            let text = Text::new(if is_expanded { expanded } else { collapsed });
866            match &key {
867                Some(key) => text.key(key.clone()).into_widget(),
868                None => text.into_widget(),
869            }
870        })
871    }
872
873    /// Dart's `(context, isExpanded) => widget`, the same whether expanded or not.
874    fn fixed_header(widget: impl Fn() -> WidgetRef + 'static) -> ExpansionPanelHeaderBuilder {
875        Rc::new(move |_app, _context, _is_expanded| widget())
876    }
877
878    /// Dart's `ExpansionPanel(headerBuilder: Text(isExpanded ? expanded : collapsed), body:
879    /// SizedBox(height: 100.0))`.
880    fn panel(collapsed: &'static str, expanded: &'static str) -> ExpansionPanel {
881        ExpansionPanel::new(
882            text_header(collapsed, expanded, None),
883            SizedBox::new().height(100.0),
884        )
885    }
886
887    /// Dart's `ExpansionPanelRadio(headerBuilder: Text(isExpanded ? expanded : collapsed),
888    /// body: SizedBox(height: 100.0), value: value)`.
889    fn radio_panel(
890        value: i32,
891        collapsed: &'static str,
892        expanded: &'static str,
893    ) -> ExpansionPanelRadio {
894        ExpansionPanelRadio::new(
895            value,
896            text_header(collapsed, expanded, None),
897            SizedBox::new().height(100.0),
898        )
899    }
900
901    /// The three radio panels A/B, C/D and E/F of value 0, 1 and 2.
902    fn demo_items_radio() -> Vec<ExpansionPanelRadio> {
903        vec![
904            radio_panel(0, "A", "B"),
905            radio_panel(1, "C", "D"),
906            radio_panel(2, "E", "F"),
907        ]
908    }
909
910    fn key(name: &'static str) -> KeyRef {
911        KeyRef::from(ValueKey::new(name))
912    }
913
914    /// Dart's `MaterialApp(home: SingleChildScrollView(child: child))`.
915    fn scroll_app<K>(child: impl IntoWidget<K>) -> WidgetRef {
916        MaterialApp::new()
917            .home(SingleChildScrollView::new().child(child))
918            .into_widget()
919    }
920
921    /// An expansion callback that records each call.
922    fn recording_callback(history: &Rc<RefCell<Vec<(usize, bool)>>>) -> ExpansionPanelCallback {
923        let history = Rc::clone(history);
924        Rc::new(move |_app, index, is_expanded| history.borrow_mut().push((index, is_expanded)))
925    }
926
927    /// Dart's `tester.renderObject(find.byType(ExpansionPanelList))` as a `RenderBox`.
928    fn expansion_panel_list_box(tester: &WidgetTester) -> AnyRenderBox {
929        tester
930            .render_object(find::by_type::<ExpansionPanelList>())
931            .as_box()
932            .expect("ExpansionPanelList renders a box")
933    }
934
935    /// Dart's `box.size.height`.
936    fn height(tester: &WidgetTester, render_box: AnyRenderBox) -> f64 {
937        tester.get_size(render_box).height()
938    }
939
940    /// Dart's `find.ancestor(of: find.byKey(key), matching: find.byType(AnimatedContainer)).first`.
941    fn header_container(key: &KeyRef) -> Finder {
942        find::ancestor(
943            find::by_key(key.clone()),
944            find::by_type::<AnimatedContainer>(),
945        )
946        .first()
947    }
948
949    /// Dart's `decoration as BoxDecoration`.
950    fn box_decoration(decoration: &DecorationRef) -> BoxDecoration {
951        decoration
952            .as_any()
953            .downcast_ref::<BoxDecoration>()
954            .expect("the decoration is a BoxDecoration")
955            .clone()
956    }
957
958    /// Dart's `tester.widget(find.byType(DecoratedBox).last)`'s `decoration.border!.top.color`.
959    fn last_decorated_box_top_border_color(tester: &WidgetTester) -> Color {
960        let decoration = tester.widget(
961            find::by_type::<DecoratedBox>().last(),
962            |decorated_box: &DecoratedBox| box_decoration(&decorated_box.decoration),
963        );
964        decoration
965            .border
966            .expect("the decoration has a border")
967            .top()
968            .color
969    }
970
971    /// Dart's `tester.widget<MergeableMaterial>(find.byType(MergeableMaterial)).children`.
972    fn mergeable_material_children(tester: &WidgetTester) -> Vec<MergeableMaterialItem> {
973        tester.widget(
974            find::by_type::<MergeableMaterial>(),
975            |material: &MergeableMaterial| material.children.clone(),
976        )
977    }
978
979    /// Dart's `(item as MaterialSlice).color`.
980    fn slice_color(item: &MergeableMaterialItem) -> Option<Color> {
981        match item {
982            MergeableMaterialItem::Slice(slice) => slice.color,
983            MergeableMaterialItem::Gap(_) => panic!("the item is a MaterialSlice"),
984        }
985    }
986
987    #[test]
988    fn expansion_panel_list_test() {
989        test_widgets(|tester| {
990            let captured_index = Rc::new(Cell::new(None));
991            let captured_is_expanded = Rc::new(Cell::new(None));
992            let callback = {
993                let captured_index = Rc::clone(&captured_index);
994                let captured_is_expanded = Rc::clone(&captured_is_expanded);
995                move || -> ExpansionPanelCallback {
996                    let captured_index = Rc::clone(&captured_index);
997                    let captured_is_expanded = Rc::clone(&captured_is_expanded);
998                    Rc::new(move |_app, index, is_expanded| {
999                        captured_index.set(Some(index));
1000                        captured_is_expanded.set(Some(is_expanded));
1001                    })
1002                }
1003            };
1004
1005            tester.pump_widget(scroll_app(
1006                ExpansionPanelList::new()
1007                    .expansion_callback(callback())
1008                    .children([panel("A", "B")]),
1009            ));
1010
1011            expect(tester, &find::text("A"), finds_one_widget());
1012            expect(tester, &find::text("B"), finds_nothing());
1013            let mut render_box = expansion_panel_list_box(tester);
1014            let old_height = height(tester, render_box);
1015            expect(tester, &find::by_type::<ExpandIcon>(), finds_one_widget());
1016            tester.tap(find::by_type::<ExpandIcon>());
1017            assert_eq!(captured_index.get(), Some(0));
1018            assert_eq!(captured_is_expanded.get(), Some(true));
1019            render_box = expansion_panel_list_box(tester);
1020            assert_eq!(height(tester, render_box), old_height);
1021
1022            // Now, expand the child panel.
1023            tester.pump_widget(scroll_app(
1024                ExpansionPanelList::new()
1025                    .expansion_callback(callback())
1026                    // this is the addition
1027                    .children([panel("A", "B").is_expanded(true)]),
1028            ));
1029            tester.pump_by(Duration::from_millis(200));
1030
1031            expect(tester, &find::text("A"), finds_nothing());
1032            expect(tester, &find::text("B"), finds_one_widget());
1033            render_box = expansion_panel_list_box(tester);
1034            // 100 + some margin
1035            assert!(height(tester, render_box) - old_height >= 100.0);
1036        });
1037    }
1038
1039    #[test]
1040    fn multiple_panel_list_test() {
1041        test_widgets(|tester| {
1042            tester.pump_widget(MaterialApp::new().home(ListView::new().children(vec![
1043                    ExpansionPanelList::new()
1044                        .children([panel("A", "B").is_expanded(true)])
1045                        .into_widget(),
1046                    ExpansionPanelList::new()
1047                        .children([panel("C", "D").is_expanded(true)])
1048                        .into_widget(),
1049                ])));
1050            tester.pump_by(Duration::from_millis(200));
1051
1052            expect(tester, &find::text("A"), finds_nothing());
1053            expect(tester, &find::text("B"), finds_one_widget());
1054            expect(tester, &find::text("C"), finds_nothing());
1055            expect(tester, &find::text("D"), finds_one_widget());
1056        });
1057    }
1058
1059    #[test]
1060    fn open_close_animations() {
1061        test_widgets(|tester| {
1062            const K_SIZE_ANIMATION_DURATION: Duration = Duration::from_millis(1000);
1063            // The MaterialGaps animate in using kThemeAnimationDuration (hardcoded), which
1064            // should be less than our test size animation length. So we can assume that they
1065            // appear immediately. Here we just verify that our assumption is true.
1066            assert!(K_THEME_ANIMATION_DURATION < K_SIZE_ANIMATION_DURATION / 2);
1067
1068            let build = |a: bool, b: bool, c: bool| -> WidgetRef {
1069                let placeholder_header =
1070                    || fixed_header(|| Placeholder::new().fallback_height(12.0).into_widget());
1071                MaterialApp::new()
1072                    .home(Column::new().children(vec![
1073                        ExpansionPanelList::new()
1074                            .animation_duration(K_SIZE_ANIMATION_DURATION)
1075                            .children([
1076                                ExpansionPanel::new(
1077                                    placeholder_header(),
1078                                    SizedBox::new()
1079                                        .height(100.0)
1080                                        .child(Placeholder::new().fallback_height(12.0)),
1081                                )
1082                                .is_expanded(a),
1083                                ExpansionPanel::new(
1084                                    placeholder_header(),
1085                                    SizedBox::new().height(100.0).child(Placeholder::new()),
1086                                )
1087                                .is_expanded(b),
1088                                ExpansionPanel::new(
1089                                    placeholder_header(),
1090                                    SizedBox::new().height(100.0).child(Placeholder::new()),
1091                                )
1092                                .is_expanded(c),
1093                            ])
1094                            .into_widget(),
1095                    ]))
1096                    .into_widget()
1097            };
1098            let animated_size = |index: usize| find::by_type::<AnimatedSize>().at(index);
1099
1100            tester.pump_widget(build(false, false, false));
1101            assert_eq!(find::by_type::<AnimatedSize>().evaluate(tester).len(), 3);
1102            assert_eq!(
1103                tester.get_rect(animated_size(0)),
1104                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1105            );
1106            assert_eq!(
1107                tester.get_rect(animated_size(1)),
1108                Rect::from_ltwh(0.0, 97.0, 800.0, 0.0)
1109            );
1110            assert_eq!(
1111                tester.get_rect(animated_size(2)),
1112                Rect::from_ltwh(0.0, 146.0, 800.0, 0.0)
1113            );
1114
1115            tester.pump_by(Duration::from_millis(200));
1116            assert_eq!(
1117                tester.get_rect(animated_size(0)),
1118                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1119            );
1120            assert_eq!(
1121                tester.get_rect(animated_size(1)),
1122                Rect::from_ltwh(0.0, 97.0, 800.0, 0.0)
1123            );
1124            assert_eq!(
1125                tester.get_rect(animated_size(2)),
1126                Rect::from_ltwh(0.0, 146.0, 800.0, 0.0)
1127            );
1128
1129            tester.pump_widget(build(false, true, false));
1130            assert_eq!(
1131                tester.get_rect(animated_size(0)),
1132                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1133            );
1134            assert_eq!(
1135                tester.get_rect(animated_size(1)),
1136                Rect::from_ltwh(0.0, 97.0, 800.0, 0.0)
1137            );
1138            assert_eq!(
1139                tester.get_rect(animated_size(2)),
1140                Rect::from_ltwh(0.0, 146.0, 800.0, 0.0)
1141            );
1142
1143            tester.pump_by(K_SIZE_ANIMATION_DURATION / 2);
1144            assert_eq!(
1145                tester.get_rect(animated_size(0)),
1146                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1147            );
1148            let rect1 = tester.get_rect(animated_size(1));
1149            assert_eq!(rect1.left, 0.0);
1150            // 16.0 material gap, plus 12.0 top and bottom margins added to the header
1151            assert!(
1152                rect1.top > 113.0 && rect1.top < 113.0 + 16.0 + 24.0,
1153                "{rect1:?}"
1154            );
1155            assert_eq!(rect1.width(), 800.0);
1156            assert!(rect1.height() > 0.0 && rect1.height() < 100.0, "{rect1:?}");
1157            let rect2 = tester.get_rect(animated_size(2));
1158            // the 16.0 comes from the MaterialGap being introduced, the 48.0 is the header height.
1159            // Dart's exact `expect(rect2, ...)`: positions go through valo's `f32` matrices.
1160            assert_f32_equals(
1161                rect2,
1162                Rect::from_ltwh(0.0, rect1.bottom + 16.0 + 48.0, 800.0, 0.0),
1163            );
1164
1165            tester.pump_widget(build(false, false, false));
1166            assert_eq!(
1167                tester.get_rect(animated_size(0)),
1168                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1169            );
1170            assert_eq!(tester.get_rect(animated_size(1)), rect1);
1171            assert_eq!(tester.get_rect(animated_size(2)), rect2);
1172
1173            tester.pump_widget(build(false, false, true));
1174            assert_eq!(
1175                tester.get_rect(animated_size(0)),
1176                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1177            );
1178            assert_eq!(tester.get_rect(animated_size(1)), rect1);
1179            assert_eq!(tester.get_rect(animated_size(2)), rect2);
1180
1181            // a few no-op pumps to make sure there's nothing fishy going on
1182            tester.pump();
1183            tester.pump();
1184            tester.pump();
1185            assert_eq!(
1186                tester.get_rect(animated_size(0)),
1187                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1188            );
1189            assert_eq!(tester.get_rect(animated_size(1)), rect1);
1190            assert_eq!(tester.get_rect(animated_size(2)), rect2);
1191
1192            tester.pump_and_settle();
1193            assert_eq!(
1194                tester.get_rect(animated_size(0)),
1195                Rect::from_ltwh(0.0, 48.0, 800.0, 0.0)
1196            );
1197            assert_eq!(
1198                tester.get_rect(animated_size(1)),
1199                Rect::from_ltwh(0.0, 48.0 + 1.0 + 48.0, 800.0, 0.0)
1200            );
1201            assert_eq!(
1202                tester.get_rect(animated_size(2)),
1203                Rect::from_ltwh(
1204                    0.0,
1205                    48.0 + 1.0 + 48.0 + 16.0 + 16.0 + 48.0 + 16.0,
1206                    800.0,
1207                    100.0
1208                )
1209            );
1210        });
1211    }
1212
1213    #[test]
1214    fn radio_mode_has_max_of_one_panel_open_at_a_time() {
1215        test_widgets(|tester| {
1216            let expansion_list_radio = ExpansionPanelList::radio(demo_items_radio());
1217
1218            tester.pump_widget(scroll_app(expansion_list_radio));
1219
1220            // Initializes with all panels closed
1221            expect(tester, &find::text("A"), finds_one_widget());
1222            expect(tester, &find::text("B"), finds_nothing());
1223            expect(tester, &find::text("C"), finds_one_widget());
1224            expect(tester, &find::text("D"), finds_nothing());
1225            expect(tester, &find::text("E"), finds_one_widget());
1226            expect(tester, &find::text("F"), finds_nothing());
1227
1228            let mut render_box = expansion_panel_list_box(tester);
1229            let mut old_height = height(tester, render_box);
1230
1231            expect(tester, &find::by_type::<ExpandIcon>(), finds_n_widgets(3));
1232
1233            tester.tap(find::by_type::<ExpandIcon>().at(0));
1234
1235            render_box = expansion_panel_list_box(tester);
1236            assert_eq!(height(tester, render_box), old_height);
1237
1238            tester.pump_by(Duration::from_millis(200));
1239            tester.pump_and_settle();
1240
1241            // Now the first panel is open
1242            expect(tester, &find::text("A"), finds_nothing());
1243            expect(tester, &find::text("B"), finds_one_widget());
1244            expect(tester, &find::text("C"), finds_one_widget());
1245            expect(tester, &find::text("D"), finds_nothing());
1246            expect(tester, &find::text("E"), finds_one_widget());
1247            expect(tester, &find::text("F"), finds_nothing());
1248
1249            render_box = expansion_panel_list_box(tester);
1250            // 100 + some margin
1251            assert!(height(tester, render_box) - old_height >= 100.0);
1252
1253            tester.tap(find::by_type::<ExpandIcon>().at(1));
1254
1255            render_box = expansion_panel_list_box(tester);
1256            old_height = height(tester, render_box);
1257
1258            tester.pump_by(Duration::from_millis(200));
1259
1260            // Now the first panel is closed and the second should be opened
1261            expect(tester, &find::text("A"), finds_one_widget());
1262            expect(tester, &find::text("B"), finds_nothing());
1263            expect(tester, &find::text("C"), finds_nothing());
1264            expect(tester, &find::text("D"), finds_one_widget());
1265            expect(tester, &find::text("E"), finds_one_widget());
1266            expect(tester, &find::text("F"), finds_nothing());
1267
1268            assert!(height(tester, render_box) >= old_height);
1269
1270            // Dart's `demoItemsRadio.removeAt(0)` mutates the list the mounted widget holds,
1271            // which nothing rebuilds from; a Rust widget's children cannot be changed in place.
1272            tester.pump_and_settle();
1273
1274            // Now the first panel should be opened
1275            expect(tester, &find::text("C"), finds_nothing());
1276            expect(tester, &find::text("D"), finds_one_widget());
1277            expect(tester, &find::text("E"), finds_one_widget());
1278            expect(tester, &find::text("F"), finds_nothing());
1279
1280            let demo_items = [panel("A", "B"), panel("C", "D"), panel("E", "F")];
1281
1282            let expansion_list = ExpansionPanelList::new().children(demo_items);
1283
1284            tester.pump_widget(scroll_app(expansion_list));
1285
1286            // We've reinitialized with a regular expansion panel so they should all be closed
1287            // again
1288            expect(tester, &find::text("A"), finds_one_widget());
1289            expect(tester, &find::text("B"), finds_nothing());
1290            expect(tester, &find::text("C"), finds_one_widget());
1291            expect(tester, &find::text("D"), finds_nothing());
1292            expect(tester, &find::text("E"), finds_one_widget());
1293            expect(tester, &find::text("F"), finds_nothing());
1294        });
1295    }
1296
1297    #[test]
1298    fn radio_mode_calls_expansion_callback_once_if_other_panels_closed() {
1299        test_widgets(|tester| {
1300            let callback_history = Rc::new(RefCell::new(Vec::new()));
1301            let expansion_list_radio = ExpansionPanelList::radio(demo_items_radio())
1302                .expansion_callback(recording_callback(&callback_history));
1303
1304            tester.pump_widget(scroll_app(expansion_list_radio));
1305
1306            // Initializes with all panels closed
1307            expect(tester, &find::text("A"), finds_one_widget());
1308            expect(tester, &find::text("B"), finds_nothing());
1309            expect(tester, &find::text("C"), finds_one_widget());
1310            expect(tester, &find::text("D"), finds_nothing());
1311            expect(tester, &find::text("E"), finds_one_widget());
1312            expect(tester, &find::text("F"), finds_nothing());
1313
1314            // Open one panel
1315            tester.tap(find::by_type::<ExpandIcon>().at(1));
1316            tester.pump_and_settle();
1317
1318            // Callback is invoked once with appropriate arguments
1319            assert_eq!(callback_history.borrow().len(), 1);
1320            assert_eq!(callback_history.borrow().last(), Some(&(1, true)));
1321
1322            // Close the same panel
1323            tester.tap(find::by_type::<ExpandIcon>().at(1));
1324            tester.pump_and_settle();
1325
1326            // Callback is invoked once with appropriate arguments
1327            assert_eq!(callback_history.borrow().len(), 2);
1328            assert_eq!(callback_history.borrow().last(), Some(&(1, false)));
1329        });
1330    }
1331
1332    #[test]
1333    fn radio_mode_calls_expansion_callback_twice_if_other_panel_open_prior() {
1334        test_widgets(|tester| {
1335            let callback_history = Rc::new(RefCell::new(Vec::new()));
1336            let expansion_list_radio = ExpansionPanelList::radio(demo_items_radio())
1337                .expansion_callback(recording_callback(&callback_history));
1338
1339            tester.pump_widget(scroll_app(expansion_list_radio));
1340
1341            // Initializes with all panels closed
1342            expect(tester, &find::text("A"), finds_one_widget());
1343            expect(tester, &find::text("B"), finds_nothing());
1344            expect(tester, &find::text("C"), finds_one_widget());
1345            expect(tester, &find::text("D"), finds_nothing());
1346            expect(tester, &find::text("E"), finds_one_widget());
1347            expect(tester, &find::text("F"), finds_nothing());
1348
1349            // Open one panel
1350            tester.tap(find::by_type::<ExpandIcon>().at(1));
1351            tester.pump_and_settle();
1352
1353            // Callback is invoked once with appropriate arguments
1354            assert_eq!(callback_history.borrow().len(), 1);
1355            let mut callback_results =
1356                callback_history.borrow()[callback_history.borrow().len() - 1];
1357            assert_eq!(callback_results, (1, true));
1358
1359            // Close a different panel
1360            tester.tap(find::by_type::<ExpandIcon>().at(2));
1361            tester.pump_and_settle();
1362
1363            // Callback is invoked the first time with correct arguments
1364            assert_eq!(callback_history.borrow().len(), 3);
1365            callback_results = callback_history.borrow()[callback_history.borrow().len() - 2];
1366            assert_eq!(callback_results, (1, false));
1367
1368            // Callback is invoked the second time with correct arguments
1369            callback_results = callback_history.borrow()[callback_history.borrow().len() - 1];
1370            assert_eq!(callback_results, (2, true));
1371        });
1372    }
1373
1374    #[test]
1375    fn expansion_panel_list_radio_callback_displays_true_or_false_based_on_the_visibility_of_a_list_item()
1376     {
1377        test_widgets(|tester| {
1378            let last_expanded = Rc::new(Cell::new(None));
1379            let top_element_expanded = Rc::new(Cell::new(false));
1380            let bottom_element_expanded = Rc::new(Cell::new(false));
1381
1382            let demo_items_radio = vec![
1383                // topElement
1384                radio_panel(0, "A", "B"),
1385                // bottomElement
1386                radio_panel(1, "C", "D"),
1387            ];
1388
1389            let expansion_list_radio = ExpansionPanelList::radio(demo_items_radio)
1390                .expansion_callback({
1391                    let last_expanded = Rc::clone(&last_expanded);
1392                    let top_element_expanded = Rc::clone(&top_element_expanded);
1393                    let bottom_element_expanded = Rc::clone(&bottom_element_expanded);
1394                    Rc::new(move |_app, index, is_expanded| {
1395                        last_expanded.set(Some(index));
1396                        if index == 0 {
1397                            top_element_expanded.set(is_expanded);
1398                            bottom_element_expanded.set(false);
1399                        } else {
1400                            top_element_expanded.set(false);
1401                            bottom_element_expanded.set(is_expanded);
1402                        }
1403                    })
1404                });
1405
1406            tester.pump_widget(scroll_app(expansion_list_radio));
1407
1408            // Initializes with all panels closed.
1409            expect(tester, &find::text("A"), finds_one_widget());
1410            expect(tester, &find::text("B"), finds_nothing());
1411            expect(tester, &find::text("C"), finds_one_widget());
1412            expect(tester, &find::text("D"), finds_nothing());
1413
1414            tester.tap(find::by_type::<ExpandIcon>().at(0));
1415            tester.pump_by(Duration::from_millis(200));
1416            tester.pump_and_settle();
1417
1418            // Now the first panel is open.
1419            expect(tester, &find::text("A"), finds_nothing());
1420            expect(tester, &find::text("B"), finds_one_widget());
1421            expect(tester, &find::text("C"), finds_one_widget());
1422            expect(tester, &find::text("D"), finds_nothing());
1423
1424            assert_eq!(last_expanded.get(), Some(0));
1425            assert!(top_element_expanded.get());
1426
1427            tester.tap(find::by_type::<ExpandIcon>().at(1));
1428            tester.pump_by(Duration::from_millis(200));
1429            tester.pump_and_settle();
1430
1431            // Open the other panel and ensure the first is now closed.
1432            assert_eq!(last_expanded.get(), Some(1));
1433            assert!(bottom_element_expanded.get());
1434            assert!(!top_element_expanded.get());
1435            expect(tester, &find::text("D"), finds_one_widget());
1436            expect(tester, &find::text("A"), finds_one_widget());
1437
1438            tester.tap(find::by_type::<ExpandIcon>().at(1));
1439            tester.pump_by(Duration::from_millis(200));
1440            tester.pump_and_settle();
1441
1442            // Close the item that was expanded should now be false.
1443            assert_eq!(last_expanded.get(), Some(1));
1444            assert!(!bottom_element_expanded.get());
1445
1446            // All panels should be closed.
1447            expect(tester, &find::text("A"), finds_one_widget());
1448            expect(tester, &find::text("B"), finds_nothing());
1449            expect(tester, &find::text("C"), finds_one_widget());
1450            expect(tester, &find::text("D"), finds_nothing());
1451        });
1452    }
1453
1454    #[test]
1455    fn did_update_widget_accounts_for_toggling_between_expansion_panel_list_and_expansion_pane_list_radio()
1456     {
1457        test_widgets(|tester| {
1458            let is_radio_list = Rc::new(Cell::new(false));
1459            let panel_expansion_state = Rc::new(RefCell::new([false, false, false]));
1460
1461            let build_radio_expansion_panel_list =
1462                || ExpansionPanelList::radio(demo_items_radio()).initial_open_panel_value(2);
1463
1464            let build_expansion_panel_list = {
1465                let panel_expansion_state = Rc::clone(&panel_expansion_state);
1466                move |set_state: StateSetter| {
1467                    let expansion_state = *panel_expansion_state.borrow();
1468                    let toggled = Rc::clone(&panel_expansion_state);
1469                    ExpansionPanelList::new()
1470                        .expansion_callback(Rc::new(move |app: &mut App, index: usize, _| {
1471                            set_state(app, &mut |_app| {
1472                                let mut state = toggled.borrow_mut();
1473                                state[index] = !state[index];
1474                            });
1475                        }))
1476                        .children([
1477                            panel("A", "B").is_expanded(expansion_state[0]),
1478                            panel("C", "D").is_expanded(expansion_state[1]),
1479                            panel("E", "F").is_expanded(expansion_state[2]),
1480                        ])
1481                }
1482            };
1483
1484            tester.pump_widget(StatefulBuilder::new({
1485                let is_radio_list = Rc::clone(&is_radio_list);
1486                move |_app, _context, set_state| {
1487                    let list = if is_radio_list.get() {
1488                        build_radio_expansion_panel_list()
1489                    } else {
1490                        build_expansion_panel_list(set_state.clone())
1491                    };
1492                    let is_radio_list = Rc::clone(&is_radio_list);
1493                    MaterialApp::new()
1494                        .home(
1495                            Scaffold::new()
1496                                .body(SingleChildScrollView::new().child(list))
1497                                .floating_action_button(FloatingActionButton::new(Some(
1498                                    Listener::new(move |app: &mut App| {
1499                                        set_state(app, &mut |_app| {
1500                                            is_radio_list.set(!is_radio_list.get());
1501                                        });
1502                                    }),
1503                                ))),
1504                        )
1505                        .into_widget()
1506                }
1507            }));
1508
1509            expect(tester, &find::text("A"), finds_one_widget());
1510            expect(tester, &find::text("B"), finds_nothing());
1511            expect(tester, &find::text("C"), finds_one_widget());
1512            expect(tester, &find::text("D"), finds_nothing());
1513            expect(tester, &find::text("E"), finds_one_widget());
1514            expect(tester, &find::text("F"), finds_nothing());
1515
1516            tester.tap(find::by_type::<ExpandIcon>().at(0));
1517            tester.tap(find::by_type::<ExpandIcon>().at(1));
1518            tester.pump_and_settle();
1519
1520            expect(tester, &find::text("A"), finds_nothing());
1521            expect(tester, &find::text("B"), finds_one_widget());
1522            expect(tester, &find::text("C"), finds_nothing());
1523            expect(tester, &find::text("D"), finds_one_widget());
1524            expect(tester, &find::text("E"), finds_one_widget());
1525            expect(tester, &find::text("F"), finds_nothing());
1526
1527            // ExpansionPanelList --> ExpansionPanelList.radio
1528            tester.tap(find::by_type::<FloatingActionButton>());
1529            tester.pump_and_settle();
1530
1531            expect(tester, &find::text("A"), finds_one_widget());
1532            expect(tester, &find::text("B"), finds_nothing());
1533            expect(tester, &find::text("C"), finds_one_widget());
1534            expect(tester, &find::text("D"), finds_nothing());
1535            expect(tester, &find::text("E"), finds_nothing());
1536            expect(tester, &find::text("F"), finds_one_widget());
1537
1538            // ExpansionPanelList.radio --> ExpansionPanelList
1539            tester.tap(find::by_type::<FloatingActionButton>());
1540            tester.pump_and_settle();
1541
1542            expect(tester, &find::text("A"), finds_nothing());
1543            expect(tester, &find::text("B"), finds_one_widget());
1544            expect(tester, &find::text("C"), finds_nothing());
1545            expect(tester, &find::text("D"), finds_one_widget());
1546            expect(tester, &find::text("E"), finds_one_widget());
1547            expect(tester, &find::text("F"), finds_nothing());
1548        });
1549    }
1550
1551    #[test]
1552    fn no_duplicate_global_keys_at_layout_build_time() {
1553        // Regression test for https://github.com/flutter/flutter/issues/13780
1554        test_widgets(|tester| {
1555            tester.pump_widget(StatefulBuilder::new(|_app, _context, set_state| {
1556                MaterialApp::new()
1557                    // Wrapping with LayoutBuilder or other widgets that augment layout/build
1558                    // order should not create duplicate keys
1559                    .home(
1560                        LayoutBuilder::new(move |_app, _context, _constraints| {
1561                            let set_state = set_state.clone();
1562                            SingleChildScrollView::new()
1563                                .child(
1564                                    ExpansionPanelList::radio(demo_items_radio())
1565                                        .expansion_callback(Rc::new(
1566                                            move |app: &mut App, _index, is_expanded| {
1567                                                if !is_expanded {
1568                                                    // setState invocation required to trigger
1569                                                    // _ExpansionPanelListState.didUpdateWidget, which
1570                                                    // causes duplicate keys to be generated in the
1571                                                    // regression
1572                                                    set_state(app, &mut |_app| {});
1573                                                }
1574                                            },
1575                                        )),
1576                                )
1577                                .into_widget()
1578                        })
1579                        .into_widget(),
1580                    )
1581                    .into_widget()
1582            }));
1583
1584            // Initializes with all panels closed
1585            expect(tester, &find::text("A"), finds_one_widget());
1586            expect(tester, &find::text("B"), finds_nothing());
1587            expect(tester, &find::text("C"), finds_one_widget());
1588            expect(tester, &find::text("D"), finds_nothing());
1589            expect(tester, &find::text("E"), finds_one_widget());
1590            expect(tester, &find::text("F"), finds_nothing());
1591
1592            // Open a panel
1593            tester.tap(find::by_type::<ExpandIcon>().at(1));
1594            tester.pump_and_settle();
1595
1596            let panel_expansion_state = Rc::new(RefCell::new([false, false]));
1597
1598            tester.pump_widget(StatefulBuilder::new(move |_app, _context, set_state| {
1599                let panel_expansion_state = Rc::clone(&panel_expansion_state);
1600                MaterialApp::new()
1601                    .home(
1602                        Scaffold::new().body(
1603                            // Wrapping with LayoutBuilder or other widgets that augment
1604                            // layout/build order should not create duplicate keys
1605                            LayoutBuilder::new(move |_app, _context, _constraints| {
1606                                let set_state = set_state.clone();
1607                                let expansion_state = *panel_expansion_state.borrow();
1608                                let toggled = Rc::clone(&panel_expansion_state);
1609                                SingleChildScrollView::new()
1610                                .child(
1611                                    ExpansionPanelList::new()
1612                                        .expansion_callback(Rc::new(
1613                                            move |app: &mut App, index: usize, is_expanded: bool| {
1614                                                // setState invocation required to trigger
1615                                                // _ExpansionPanelListState.didUpdateWidget,
1616                                                // which causes duplicate keys to be generated
1617                                                // in the regression
1618                                                set_state(app, &mut |_app| {
1619                                                    toggled.borrow_mut()[index] = !is_expanded;
1620                                                });
1621                                            },
1622                                        ))
1623                                        .children([
1624                                            panel("A", "B").is_expanded(expansion_state[0]),
1625                                            panel("C", "D").is_expanded(expansion_state[1]),
1626                                        ]),
1627                                )
1628                                .into_widget()
1629                            })
1630                            .into_widget(),
1631                        ),
1632                    )
1633                    .into_widget()
1634            }));
1635
1636            // initializes with all panels closed
1637            expect(tester, &find::text("A"), finds_one_widget());
1638            expect(tester, &find::text("B"), finds_nothing());
1639            expect(tester, &find::text("C"), finds_one_widget());
1640            expect(tester, &find::text("D"), finds_nothing());
1641
1642            // open a panel
1643            tester.tap(find::by_type::<ExpandIcon>().at(1));
1644            tester.pump_and_settle();
1645        });
1646    }
1647
1648    #[test]
1649    fn ensure_can_tap_on_header_is_false_by_default() {
1650        let expansion_panel = ExpansionPanel::new(
1651            fixed_header(|| Text::new("Demo").into_widget()),
1652            SizedBox::new().height(100.0),
1653        );
1654
1655        assert!(!expansion_panel.can_tap_on_header);
1656    }
1657
1658    #[test]
1659    fn toggle_expansion_panel_radio_when_tapping_header_and_can_tap_on_header_is_true() {
1660        test_widgets(|tester| {
1661            let first_panel_key = key("firstPanelKey");
1662            let second_panel_key = key("secondPanelKey");
1663
1664            let demo_items_radio = [
1665                ExpansionPanelRadio::new(
1666                    0,
1667                    text_header("A", "B", Some(first_panel_key.clone())),
1668                    SizedBox::new().height(100.0),
1669                )
1670                .can_tap_on_header(true),
1671                ExpansionPanelRadio::new(
1672                    1,
1673                    text_header("C", "D", Some(second_panel_key.clone())),
1674                    SizedBox::new().height(100.0),
1675                )
1676                .can_tap_on_header(true),
1677            ];
1678
1679            let expansion_list_radio = ExpansionPanelList::radio(demo_items_radio);
1680
1681            tester.pump_widget(scroll_app(expansion_list_radio));
1682
1683            // Initializes with all panels closed
1684            expect(tester, &find::text("A"), finds_one_widget());
1685            expect(tester, &find::text("B"), finds_nothing());
1686            expect(tester, &find::text("C"), finds_one_widget());
1687            expect(tester, &find::text("D"), finds_nothing());
1688
1689            tester.tap(find::by_key(first_panel_key));
1690            tester.pump_and_settle();
1691
1692            // Now the first panel is open
1693            expect(tester, &find::text("A"), finds_nothing());
1694            expect(tester, &find::text("B"), finds_one_widget());
1695            expect(tester, &find::text("C"), finds_one_widget());
1696            expect(tester, &find::text("D"), finds_nothing());
1697
1698            tester.tap(find::by_key(second_panel_key));
1699            tester.pump_and_settle();
1700
1701            // Now the second panel is open
1702            expect(tester, &find::text("A"), finds_one_widget());
1703            expect(tester, &find::text("B"), finds_nothing());
1704            expect(tester, &find::text("C"), finds_nothing());
1705            expect(tester, &find::text("D"), finds_one_widget());
1706        });
1707    }
1708
1709    #[test]
1710    fn toggle_expansion_panel_when_tapping_header_and_can_tap_on_header_is_true() {
1711        test_widgets(|tester| {
1712            let first_panel_key = key("firstPanelKey");
1713            let second_panel_key = key("secondPanelKey");
1714
1715            tester.pump_widget(scroll_app(
1716                SimpleExpansionPanelListTestWidget::new()
1717                    .first_panel_key(first_panel_key.clone())
1718                    .second_panel_key(second_panel_key.clone())
1719                    .can_tap_on_header(true),
1720            ));
1721
1722            // Initializes with all panels closed
1723            expect(tester, &find::text("A"), finds_one_widget());
1724            expect(tester, &find::text("B"), finds_nothing());
1725            expect(tester, &find::text("C"), finds_one_widget());
1726            expect(tester, &find::text("D"), finds_nothing());
1727
1728            tester.tap(find::by_key(first_panel_key.clone()));
1729            tester.pump_and_settle();
1730
1731            // The first panel is open
1732            expect(tester, &find::text("A"), finds_nothing());
1733            expect(tester, &find::text("B"), finds_one_widget());
1734            expect(tester, &find::text("C"), finds_one_widget());
1735            expect(tester, &find::text("D"), finds_nothing());
1736
1737            tester.tap(find::by_key(first_panel_key));
1738            tester.pump_and_settle();
1739
1740            // The first panel is closed
1741            expect(tester, &find::text("A"), finds_one_widget());
1742            expect(tester, &find::text("B"), finds_nothing());
1743            expect(tester, &find::text("C"), finds_one_widget());
1744            expect(tester, &find::text("D"), finds_nothing());
1745
1746            tester.tap(find::by_key(second_panel_key.clone()));
1747            tester.pump_and_settle();
1748
1749            // The second panel is open
1750            expect(tester, &find::text("A"), finds_one_widget());
1751            expect(tester, &find::text("B"), finds_nothing());
1752            expect(tester, &find::text("C"), finds_nothing());
1753            expect(tester, &find::text("D"), finds_one_widget());
1754
1755            tester.tap(find::by_key(second_panel_key));
1756            tester.pump_and_settle();
1757
1758            // The second panel is closed
1759            expect(tester, &find::text("A"), finds_one_widget());
1760            expect(tester, &find::text("B"), finds_nothing());
1761            expect(tester, &find::text("C"), finds_one_widget());
1762            expect(tester, &find::text("D"), finds_nothing());
1763        });
1764    }
1765
1766    #[test]
1767    fn do_not_toggle_expansion_panel_when_tapping_header_and_can_tap_on_header_is_false() {
1768        test_widgets(|tester| {
1769            let first_panel_key = key("firstPanelKey");
1770            let second_panel_key = key("secondPanelKey");
1771
1772            tester.pump_widget(scroll_app(
1773                SimpleExpansionPanelListTestWidget::new()
1774                    .first_panel_key(first_panel_key.clone())
1775                    .second_panel_key(second_panel_key.clone()),
1776            ));
1777
1778            // Initializes with all panels closed
1779            expect(tester, &find::text("A"), finds_one_widget());
1780            expect(tester, &find::text("B"), finds_nothing());
1781            expect(tester, &find::text("C"), finds_one_widget());
1782            expect(tester, &find::text("D"), finds_nothing());
1783
1784            tester.tap(find::by_key(first_panel_key));
1785            tester.pump_and_settle();
1786
1787            // The first panel is closed
1788            expect(tester, &find::text("A"), finds_one_widget());
1789            expect(tester, &find::text("B"), finds_nothing());
1790            expect(tester, &find::text("C"), finds_one_widget());
1791            expect(tester, &find::text("D"), finds_nothing());
1792
1793            tester.tap(find::by_key(second_panel_key));
1794            tester.pump_and_settle();
1795
1796            // The second panel is closed
1797            expect(tester, &find::text("A"), finds_one_widget());
1798            expect(tester, &find::text("B"), finds_nothing());
1799            expect(tester, &find::text("C"), finds_one_widget());
1800            expect(tester, &find::text("D"), finds_nothing());
1801        });
1802    }
1803
1804    #[test]
1805    fn do_not_toggle_expansion_panel_radio_when_tapping_header_and_can_tap_on_header_is_false() {
1806        test_widgets(|tester| {
1807            let first_panel_key = key("firstPanelKey");
1808            let second_panel_key = key("secondPanelKey");
1809
1810            let demo_items_radio = [
1811                ExpansionPanelRadio::new(
1812                    0,
1813                    text_header("A", "B", Some(first_panel_key.clone())),
1814                    SizedBox::new().height(100.0),
1815                ),
1816                ExpansionPanelRadio::new(
1817                    1,
1818                    text_header("C", "D", Some(second_panel_key.clone())),
1819                    SizedBox::new().height(100.0),
1820                ),
1821            ];
1822
1823            let expansion_list_radio = ExpansionPanelList::radio(demo_items_radio);
1824
1825            tester.pump_widget(scroll_app(expansion_list_radio));
1826
1827            // Initializes with all panels closed
1828            expect(tester, &find::text("A"), finds_one_widget());
1829            expect(tester, &find::text("B"), finds_nothing());
1830            expect(tester, &find::text("C"), finds_one_widget());
1831            expect(tester, &find::text("D"), finds_nothing());
1832
1833            tester.tap(find::by_key(first_panel_key));
1834            tester.pump_and_settle();
1835
1836            // The first panel is closed
1837            expect(tester, &find::text("A"), finds_one_widget());
1838            expect(tester, &find::text("B"), finds_nothing());
1839            expect(tester, &find::text("C"), finds_one_widget());
1840            expect(tester, &find::text("D"), finds_nothing());
1841
1842            tester.tap(find::by_key(second_panel_key));
1843            tester.pump_and_settle();
1844
1845            // The second panel is closed
1846            expect(tester, &find::text("A"), finds_one_widget());
1847            expect(tester, &find::text("B"), finds_nothing());
1848            expect(tester, &find::text("C"), finds_one_widget());
1849            expect(tester, &find::text("D"), finds_nothing());
1850        });
1851    }
1852
1853    #[test]
1854    fn correct_default_header_padding() {
1855        test_widgets(|tester| {
1856            let first_panel_key = key("firstPanelKey");
1857
1858            tester.pump_widget(scroll_app(
1859                SimpleExpansionPanelListTestWidget::new()
1860                    .first_panel_key(first_panel_key.clone())
1861                    .can_tap_on_header(true),
1862            ));
1863
1864            // The panel is closed
1865            expect(tester, &find::text("A"), finds_one_widget());
1866            expect(tester, &find::text("B"), finds_nothing());
1867
1868            // No padding applied to closed header
1869            let mut size = tester.get_size(header_container(&first_panel_key));
1870            assert_eq!(size.height(), 48.0); // _kPanelHeaderCollapsedHeight
1871            assert_eq!(size.width(), 744.0);
1872
1873            // Now, expand the child panel.
1874            tester.tap(find::by_key(first_panel_key.clone()));
1875            tester.pump_and_settle();
1876
1877            // The panel is expanded
1878            expect(tester, &find::text("A"), finds_nothing());
1879            expect(tester, &find::text("B"), finds_one_widget());
1880
1881            // Padding is added to expanded header
1882            size = tester.get_size(header_container(&first_panel_key));
1883            // _kPanelHeaderCollapsedHeight + 24.0 (double default padding)
1884            assert_eq!(size.height(), 80.0);
1885            assert_eq!(size.width(), 744.0);
1886        });
1887    }
1888
1889    // Regression test for https://github.com/flutter/flutter/issues/5848.
1890    #[test]
1891    fn the_animated_container_and_icon_button_have_the_same_height_of_48px() {
1892        test_widgets(|tester| {
1893            let first_panel_key = key("firstPanelKey");
1894
1895            tester.pump_widget(scroll_app(
1896                SimpleExpansionPanelListTestWidget::new()
1897                    .first_panel_key(first_panel_key.clone())
1898                    .can_tap_on_header(true),
1899            ));
1900
1901            // The panel is closed.
1902            expect(tester, &find::text("A"), finds_one_widget());
1903            expect(tester, &find::text("B"), finds_nothing());
1904
1905            // No padding applied to closed header.
1906            let box_of_container = tester.get_size(header_container(&first_panel_key));
1907            let box_of_icon_button = tester.get_size(find::by_type::<IconButton>().first());
1908            assert_eq!(box_of_container.height(), box_of_icon_button.height());
1909            // Header should have 48px height according to Material 2 Design spec.
1910            assert_eq!(box_of_container.height(), 48.0);
1911        });
1912    }
1913
1914    #[test]
1915    fn the_animated_container_s_height_is_at_least_k_min_interactive_dimension() {
1916        test_widgets(|tester| {
1917            let first_panel_key = key("firstPanelKey");
1918
1919            tester.pump_widget(scroll_app(
1920                SimpleExpansionPanelListTestWidget::new()
1921                    .first_panel_key(first_panel_key.clone())
1922                    .can_tap_on_header(true),
1923            ));
1924
1925            // The panel is closed
1926            expect(tester, &find::text("A"), finds_one_widget());
1927            expect(tester, &find::text("B"), finds_nothing());
1928
1929            // No padding applied to closed header
1930            let size = tester.get_size(header_container(&first_panel_key));
1931            assert!(size.height() >= K_MIN_INTERACTIVE_DIMENSION);
1932        });
1933    }
1934
1935    #[test]
1936    fn correct_custom_header_padding() {
1937        test_widgets(|tester| {
1938            let first_panel_key = key("firstPanelKey");
1939
1940            tester.pump_widget(scroll_app(
1941                SimpleExpansionPanelListTestWidget::new()
1942                    .first_panel_key(first_panel_key.clone())
1943                    .can_tap_on_header(true)
1944                    .expanded_header_padding(EdgeInsets::symmetric(40.0, 0.0)),
1945            ));
1946
1947            // The panel is closed
1948            expect(tester, &find::text("A"), finds_one_widget());
1949            expect(tester, &find::text("B"), finds_nothing());
1950
1951            // No padding applied to closed header
1952            let mut size = tester.get_size(header_container(&first_panel_key));
1953            assert_eq!(size.height(), 48.0); // _kPanelHeaderCollapsedHeight
1954            assert_eq!(size.width(), 744.0);
1955
1956            // Now, expand the child panel.
1957            tester.tap(find::by_key(first_panel_key.clone()));
1958            tester.pump_and_settle();
1959
1960            // The panel is expanded
1961            expect(tester, &find::text("A"), finds_nothing());
1962            expect(tester, &find::text("B"), finds_one_widget());
1963
1964            // Padding is added to expanded header
1965            size = tester.get_size(header_container(&first_panel_key));
1966            // _kPanelHeaderCollapsedHeight + 80.0 (double padding)
1967            assert_eq!(size.height(), 128.0);
1968            assert_eq!(size.width(), 744.0);
1969        });
1970    }
1971
1972    #[test]
1973    fn expansion_panel_list_respects_divider_color() {
1974        test_widgets(|tester| {
1975            let divider_color = Colors::RED.primary();
1976            tester.pump_widget(scroll_app(
1977                SimpleExpansionPanelListTestWidget::new().divider_color(divider_color),
1978            ));
1979
1980            // For the last DecoratedBox, we will have a Border.top with the provided
1981            // dividerColor.
1982            assert_eq!(last_decorated_box_top_border_color(tester), divider_color);
1983        });
1984    }
1985
1986    #[test]
1987    fn expansion_panel_list_radio_respects_divider_color() {
1988        test_widgets(|tester| {
1989            let divider_color = Colors::RED.primary();
1990            tester.pump_widget(scroll_app(
1991                ExpansionPanelList::radio([
1992                    ExpansionPanelRadio::new(
1993                        0,
1994                        text_header("A", "B", Some(key("firstKey"))),
1995                        SizedBox::new().height(100.0),
1996                    ),
1997                    ExpansionPanelRadio::new(
1998                        1,
1999                        text_header("C", "D", Some(key("secondKey"))),
2000                        SizedBox::new().height(100.0),
2001                    ),
2002                ])
2003                .divider_color(divider_color),
2004            ));
2005
2006            // For the last DecoratedBox, we will have a Border.top with the provided
2007            // dividerColor.
2008            assert_eq!(last_decorated_box_top_border_color(tester), divider_color);
2009        });
2010    }
2011
2012    #[test]
2013    fn expansion_panel_list_respects_expand_icon_color() {
2014        test_widgets(|tester| {
2015            let expand_icon_color = Colors::BLUE.primary();
2016            tester.pump_widget(scroll_app(
2017                ExpansionPanelList::new()
2018                    .expand_icon_color(expand_icon_color)
2019                    .children([ExpansionPanel::new(
2020                        fixed_header(|| SizedBox::shrink().into_widget()),
2021                        SizedBox::shrink(),
2022                    )
2023                    .can_tap_on_header(true)]),
2024            ));
2025
2026            let color = tester.widget(find::by_type::<ExpandIcon>(), |expand_icon: &ExpandIcon| {
2027                expand_icon.color
2028            });
2029
2030            assert_eq!(color, Some(expand_icon_color));
2031        });
2032    }
2033
2034    #[test]
2035    fn expansion_panel_list_radio_respects_expand_icon_color() {
2036        test_widgets(|tester| {
2037            let expand_icon_color = Colors::BLUE.primary();
2038            tester.pump_widget(scroll_app(
2039                ExpansionPanelList::radio([ExpansionPanelRadio::new(
2040                    true,
2041                    fixed_header(|| SizedBox::shrink().into_widget()),
2042                    SizedBox::shrink(),
2043                )
2044                .can_tap_on_header(true)])
2045                .expand_icon_color(expand_icon_color),
2046            ));
2047
2048            let color = tester.widget(find::by_type::<ExpandIcon>(), |expand_icon: &ExpandIcon| {
2049                expand_icon.color
2050            });
2051
2052            assert_eq!(color, Some(expand_icon_color));
2053        });
2054    }
2055
2056    #[test]
2057    fn elevation_is_propagated_properly_to_mergeable_material() {
2058        test_widgets(|tester| {
2059            const ELEVATION: f64 = 8.0;
2060            let mergeable_material_elevation = |tester: &WidgetTester| {
2061                tester.widget(
2062                    find::by_type::<MergeableMaterial>(),
2063                    |material: &MergeableMaterial| material.elevation,
2064                )
2065            };
2066
2067            // Test for ExpansionPanelList.
2068            tester.pump_widget(scroll_app(
2069                SimpleExpansionPanelListTestWidget::new().elevation(ELEVATION),
2070            ));
2071
2072            assert_eq!(mergeable_material_elevation(tester), ELEVATION);
2073
2074            // Test for ExpansionPanelList.radio.
2075            tester.pump_widget(scroll_app(
2076                ExpansionPanelList::radio([
2077                    ExpansionPanelRadio::new(
2078                        0,
2079                        text_header("A", "B", Some(key("firstKey"))),
2080                        SizedBox::new().height(100.0),
2081                    ),
2082                    ExpansionPanelRadio::new(
2083                        1,
2084                        text_header("C", "D", Some(key("secondKey"))),
2085                        SizedBox::new().height(100.0),
2086                    ),
2087                ])
2088                .elevation(ELEVATION),
2089            ));
2090
2091            assert_eq!(mergeable_material_elevation(tester), ELEVATION);
2092        });
2093    }
2094
2095    #[test]
2096    #[should_panic(
2097        expected = "Invalid value for elevation. See the kElevationToShadow constant for possible \
2098                    elevation values."
2099    )]
2100    fn using_a_value_non_defined_value_throws_assertion_error() {
2101        test_widgets(|tester| {
2102            // It should throw an AssertionError since, 19 is not defined in kElevationToShadow.
2103            tester.pump_widget(scroll_app(
2104                SimpleExpansionPanelListTestWidget::new().elevation(19.0),
2105            ));
2106        });
2107    }
2108
2109    #[test]
2110    fn expansion_panel_panel_color_test() {
2111        test_widgets(|tester| {
2112            let first_panel_color = Colors::RED.primary();
2113            let second_panel_color = Colors::BROWN.primary();
2114
2115            tester.pump_widget(scroll_app(
2116                ExpansionPanelList::new()
2117                    .expansion_callback(Rc::new(|_app, _index, _is_expanded| {}))
2118                    .children([
2119                        ExpansionPanel::new(
2120                            fixed_header(|| Text::new("A").into_widget()),
2121                            SizedBox::new().height(100.0),
2122                        )
2123                        .background_color(first_panel_color),
2124                        ExpansionPanel::new(
2125                            fixed_header(|| Text::new("B").into_widget()),
2126                            SizedBox::new().height(100.0),
2127                        )
2128                        .background_color(second_panel_color),
2129                    ]),
2130            ));
2131
2132            let children = mergeable_material_children(tester);
2133
2134            assert_eq!(
2135                slice_color(children.first().unwrap()),
2136                Some(first_panel_color)
2137            );
2138            assert_eq!(
2139                slice_color(children.last().unwrap()),
2140                Some(second_panel_color)
2141            );
2142        });
2143    }
2144
2145    #[test]
2146    fn expansion_panel_radio_background_color_test() {
2147        test_widgets(|tester| {
2148            let first_panel_color = Colors::RED.primary();
2149            let second_panel_color = Colors::BROWN.primary();
2150
2151            tester.pump_widget(scroll_app(ExpansionPanelList::radio([
2152                ExpansionPanelRadio::new(
2153                    0,
2154                    fixed_header(|| Text::new("A").into_widget()),
2155                    SizedBox::new().height(100.0),
2156                )
2157                .background_color(first_panel_color),
2158                ExpansionPanelRadio::new(
2159                    1,
2160                    fixed_header(|| Text::new("B").into_widget()),
2161                    SizedBox::new().height(100.0),
2162                )
2163                .background_color(second_panel_color),
2164            ])));
2165
2166            let children = mergeable_material_children(tester);
2167
2168            assert_eq!(
2169                slice_color(children.first().unwrap()),
2170                Some(first_panel_color)
2171            );
2172            assert_eq!(
2173                slice_color(children.last().unwrap()),
2174                Some(second_panel_color)
2175            );
2176        });
2177    }
2178
2179    #[test]
2180    fn expansion_panel_list_material_gap_size_defaults_to_16_0() {
2181        test_widgets(|tester| {
2182            tester.pump_widget(scroll_app(
2183                ExpansionPanelList::new().children([ExpansionPanel::new(
2184                    fixed_header(|| SizedBox::shrink().into_widget()),
2185                    SizedBox::shrink(),
2186                )
2187                .can_tap_on_header(true)]),
2188            ));
2189
2190            let material_gap_size = tester.widget(
2191                find::by_type::<ExpansionPanelList>(),
2192                |expansion_panel_list: &ExpansionPanelList| expansion_panel_list.material_gap_size,
2193            );
2194            assert_eq!(material_gap_size, 16.0);
2195        });
2196    }
2197
2198    #[test]
2199    fn expansion_panel_list_respects_material_gap_size() {
2200        test_widgets(|tester| {
2201            let build_widget_for_test = |material_gap_size: f64| {
2202                scroll_app(
2203                    ExpansionPanelList::new()
2204                        .material_gap_size(material_gap_size)
2205                        .children([
2206                            ExpansionPanel::new(
2207                                fixed_header(|| SizedBox::shrink().into_widget()),
2208                                SizedBox::shrink(),
2209                            )
2210                            .is_expanded(true)
2211                            .can_tap_on_header(true),
2212                            ExpansionPanel::new(
2213                                fixed_header(|| SizedBox::shrink().into_widget()),
2214                                SizedBox::shrink(),
2215                            )
2216                            .can_tap_on_header(true),
2217                        ]),
2218                )
2219            };
2220            let expect_one_gap_of = |tester: &WidgetTester, size: f64| {
2221                let children = mergeable_material_children(tester);
2222                assert_eq!(children.len(), 3);
2223                let gaps: Vec<f64> = children
2224                    .iter()
2225                    .filter_map(|item| match item {
2226                        MergeableMaterialItem::Gap(gap) => Some(gap.size),
2227                        MergeableMaterialItem::Slice(_) => None,
2228                    })
2229                    .collect();
2230                assert_eq!(gaps.len(), 1);
2231                assert_eq!(children.len() - gaps.len(), 2);
2232                for gap_size in gaps {
2233                    assert_eq!(gap_size, size);
2234                }
2235            };
2236
2237            tester.pump_widget(build_widget_for_test(0.0));
2238            tester.pump_and_settle();
2239            expect_one_gap_of(tester, 0.0);
2240
2241            tester.pump_widget(build_widget_for_test(20.0));
2242            tester.pump_and_settle();
2243            expect_one_gap_of(tester, 20.0);
2244
2245            // Dart's default `materialGapSize = 16`.
2246            tester.pump_widget(build_widget_for_test(16.0));
2247            tester.pump_and_settle();
2248            expect_one_gap_of(tester, 16.0);
2249        });
2250    }
2251
2252    #[test]
2253    fn ensure_icon_button_splash_color_and_highlight_color_are_correctly_set_when_can_tap_on_header_is_false()
2254     {
2255        test_widgets(|tester| {
2256            let expected_splash_color = Colors::GREEN.primary();
2257            let expected_highlight_color = Colors::YELLOW.primary();
2258
2259            tester.pump_widget(scroll_app(
2260                ExpansionPanelList::new().children([ExpansionPanel::new(
2261                    fixed_header(|| ListTile::new().title(Text::new("Panel 1")).into_widget()),
2262                    ListTile::new().title(Text::new("Content for Panel 1")),
2263                )
2264                .splash_color(expected_splash_color)
2265                .highlight_color(expected_highlight_color)]),
2266            ));
2267
2268            tester.tap(find::text("Panel 1"));
2269            tester.pump_and_settle();
2270
2271            let (splash_color, highlight_color) = tester.widget(
2272                find::by_type::<IconButton>().first(),
2273                |icon_button: &IconButton| (icon_button.splash_color, icon_button.highlight_color),
2274            );
2275            assert_eq!(splash_color, Some(expected_splash_color));
2276            assert_eq!(highlight_color, Some(expected_highlight_color));
2277        });
2278    }
2279
2280    #[test]
2281    fn ensure_ink_well_splash_color_and_highlight_color_are_correctly_set_when_can_tap_on_header_is_true()
2282     {
2283        test_widgets(|tester| {
2284            let expected_splash_color = Colors::GREEN.primary();
2285            let expected_highlight_color = Colors::YELLOW.primary();
2286
2287            tester.pump_widget(scroll_app(
2288                ExpansionPanelList::new().children([ExpansionPanel::new(
2289                    fixed_header(|| {
2290                        Container::new()
2291                            .padding(EdgeInsets::all(16.0))
2292                            .alignment(AlignmentGeometry::CENTER_LEFT)
2293                            .child(Text::new("Panel 1"))
2294                            .into_widget()
2295                    }),
2296                    ListTile::new().title(Text::new("Content for Panel 1")),
2297                )
2298                .can_tap_on_header(true)
2299                .splash_color(expected_splash_color)
2300                .highlight_color(expected_highlight_color)]),
2301            ));
2302
2303            tester.pump_and_settle();
2304
2305            let ink_well_finder = find::descendant(
2306                find::by_type::<ExpansionPanelList>(),
2307                find::by_widget_predicate("an InkWell with an onTap", |_app, widget| {
2308                    downcast_widget::<InkWell>(widget)
2309                        .is_some_and(|ink_well| ink_well.ink_response.on_tap.is_some())
2310                }),
2311            );
2312
2313            let (splash_color, highlight_color) =
2314                tester.widget(ink_well_finder.first(), |ink_well: &InkWell| {
2315                    (
2316                        ink_well.ink_response.splash_color,
2317                        ink_well.ink_response.highlight_color,
2318                    )
2319                });
2320            assert_eq!(splash_color, Some(expected_splash_color));
2321            assert_eq!(highlight_color, Some(expected_highlight_color));
2322        });
2323    }
2324
2325    #[test]
2326    fn expand_icon_ignores_pointer_tap_events_when_can_tap_on_header_is_true() {
2327        test_widgets(|tester| {
2328            let build_widget = |can_tap_on_header: bool| {
2329                scroll_app(
2330                    ExpansionPanelList::new().children([ExpansionPanel::new(
2331                        fixed_header(|| ListTile::new().title(Text::new("Panel")).into_widget()),
2332                        ListTile::new().title(Text::new("Content for Panel")),
2333                    )
2334                    .can_tap_on_header(can_tap_on_header)]),
2335                )
2336            };
2337
2338            tester.pump_widget(build_widget(false));
2339
2340            let ignore_pointer_finder = find::descendant(
2341                find::by_type::<ExpansionPanelList>(),
2342                find::by_type::<IgnorePointer>(),
2343            )
2344            .first();
2345
2346            let ignoring = |tester: &WidgetTester, finder: &Finder| {
2347                tester.widget(finder, |ignore_pointer: &IgnorePointer| {
2348                    ignore_pointer.ignoring
2349                })
2350            };
2351            assert!(!ignoring(tester, &ignore_pointer_finder));
2352
2353            tester.pump_widget(build_widget(true));
2354            tester.pump_and_settle();
2355
2356            assert!(ignoring(tester, &ignore_pointer_finder));
2357        });
2358    }
2359}