Skip to main content

waft_material/
expansion_tile.rs

1//! Flutter counterpart: material_ui's `expansion_tile.dart`.
2//!
3//! The state announcement `SemanticsService.sendAnnouncement` makes when the tile expands or
4//! collapses (with the iOS `Timer` that delays it) waits with the semantics tree.
5
6use std::fmt;
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_animation::{
11    Animatable, AnimationRef, AnimationStyle, ColorTween, Curve, CurveTween, Curves, Drive, Tween,
12};
13use waft_embedder::{Clip, Color, TargetPlatform};
14use waft_foundation::{App, Handle, ListenableObject, Listener, Ref, ValueChanged};
15use waft_painting::{
16    Alignment, AlignmentGeometry, Border, BorderSide, Decoration, EdgeInsetsGeometry,
17    ShapeBorderRef, ShapeDecoration,
18};
19use waft_rendering::{AccessibilityFocusBlockType, CrossAxisAlignment, MainAxisSize};
20use waft_widgets::{
21    Align, BuildContext, Column, DecoratedBox, Expansible, ExpansibleController, Icon, IntoWidget,
22    KeyRef, Padding, RotationTransition, Semantics, State, StateData, StatefulWidget, WidgetRef,
23    WidgetStatesController,
24};
25
26use crate::colors::Colors;
27use crate::expansion_tile_theme::{
28    ExpansionTileTheme, ExpansionTileThemeData, ExpansionTileThemeDataGetters,
29};
30use crate::generated::expansion_tile_defaults_m3::ExpansionTileDefaultsM3;
31use crate::icons::Icons;
32use crate::list_tile::{ListTile, ListTileControlAffinity};
33use crate::list_tile_theme::ListTileTheme;
34use crate::material::{Material, MaterialType, ShapeBorderTween};
35use crate::material_localizations::MaterialLocalizations;
36use crate::theme::Theme;
37use crate::theme_data::{ThemeData, VisualDensity};
38use crate::theme_data_getters::DefaultsContext;
39
40const K_EXPAND: Duration = Duration::from_millis(200);
41
42/// Enables control over a single [`ExpansionTile`]'s expanded/collapsed state.
43///
44/// It can be useful to expand or collapse an [`ExpansionTile`]
45/// programmatically, for example to reconfigure an existing expansion
46/// tile based on a system event. To do so, create an [`ExpansionTile`]
47/// with an [`ExpansionTileController`] that's owned by a stateful widget
48/// or look up the tile's automatically created [`ExpansionTileController`]
49/// with [`ExpansibleController::of`].
50///
51/// Typical usage of the [`ExpansibleController::of`] function is to call it from within the
52/// `build` method of a descendant of an [`ExpansionTile`].
53///
54/// When the [`ExpansionTile`] is actually created in the same `build`
55/// function as the callback that refers to the controller, then the
56/// `context` argument to the `build` function can't be used to find
57/// the [`ExpansionTileController`] (since it's "above" the widget
58/// being returned in the widget tree). In cases like that you can
59/// add a `Builder` widget, which provides a new scope with a
60/// [`BuildContext`] that is "under" the [`ExpansionTile`].
61///
62/// A more efficient solution is to split your build function into
63/// several widgets. This introduces a new context from which you
64/// can obtain the [`ExpansionTileController`]. With this approach you
65/// would have an outer widget that creates the [`ExpansionTile`]
66/// populated by instances of your new inner widgets, and then in
67/// these inner widgets you would use `ExpansionTileController::of`.
68///
69/// The  [`ExpansibleController::expand`] and [`ExpansibleController::collapse`]
70/// methods cause the [`ExpansionTile`] to rebuild, so they may not be called from
71/// a build method.
72///
73/// Remember to dispose of the [`ExpansionTileController`] when it is no longer
74/// needed. This will ensure we discard any resources used by the object.
75#[deprecated(
76    note = "Use ExpansibleController instead. This feature was deprecated after v3.31.0-0.1.pre."
77)]
78pub type ExpansionTileController = ExpansibleController;
79
80/// A single-line [`ListTile`] with an expansion arrow icon that expands or collapses
81/// the tile to reveal or hide the [`children`](Self::children).
82///
83/// This widget is typically used with `ListView` to create an "expand /
84/// collapse" list entry. When used with scrolling widgets like `ListView`, a
85/// unique `PageStorageKey` must be specified as the [`key`](Self::key), to enable the
86/// [`ExpansionTile`] to save and restore its expanded state when it is scrolled
87/// in and out of view.
88///
89/// This class overrides the `ListTileThemeData::icon_color` and `ListTileThemeData::text_color`
90/// theme properties for its [`ListTile`]. These colors animate between values when
91/// the tile is expanded and collapsed: between [`icon_color`](Self::icon_color),
92/// [`collapsed_icon_color`](Self::collapsed_icon_color) and
93/// between [`text_color`](Self::text_color) and [`collapsed_text_color`](Self::collapsed_text_color).
94///
95/// The expansion arrow icon is shown on the right by default in left-to-right languages
96/// (i.e. the trailing edge). This can be changed using [`control_affinity`](Self::control_affinity).
97/// This maps to the [`leading`](Self::leading) and [`trailing`](Self::trailing) properties of
98/// [`ExpansionTile`].
99///
100/// ## Accessibility
101///
102/// The accessibility behavior of [`ExpansionTile`] is platform adaptive, based on
103/// the device's actual platform rather than the theme's platform setting. This
104/// ensures that assistive technologies like VoiceOver on iOS and macOS receive
105/// the correct platform-specific semantics hints, even when the app's theme is
106/// configured to mimic a different platform's appearance.
107///
108/// See also:
109///
110///  * [`ListTile`], useful for creating expansion tile [`children`](Self::children) when the
111///    expansion tile represents a sublist.
112///  * The "Expand and collapse" section of
113///    <https://material.io/components/lists#types>
114pub struct ExpansionTile {
115    pub key: Option<KeyRef>,
116
117    /// A widget to display before the title.
118    ///
119    /// Typically a `CircleAvatar` widget.
120    ///
121    /// Depending on the value of [`control_affinity`](Self::control_affinity), the
122    /// [`leading`](Self::leading) widget may replace the rotating expansion arrow icon.
123    pub leading: Option<WidgetRef>,
124
125    /// The primary content of the list item.
126    ///
127    /// Typically a `Text` widget.
128    pub title: WidgetRef,
129
130    /// Additional content displayed below the title.
131    ///
132    /// Typically a `Text` widget.
133    pub subtitle: Option<WidgetRef>,
134
135    /// Called when the tile expands or collapses.
136    ///
137    /// When the tile starts expanding, this function is called with the value
138    /// true. When the tile starts collapsing, this function is called with
139    /// the value false.
140    ///
141    /// Instead of providing this property, consider adding this callback as a
142    /// listener to a provided [`controller`](Self::controller).
143    pub on_expansion_changed: Option<ValueChanged<bool>>,
144
145    /// The widgets that are displayed when the tile expands.
146    ///
147    /// Typically [`ListTile`] widgets.
148    pub children: Vec<WidgetRef>,
149
150    /// The color to display behind the sublist when expanded.
151    ///
152    /// If this property is `None` then [`ExpansionTileThemeData::background_color`] is used.
153    /// If that is also `None` then `Colors::TRANSPARENT` is used.
154    ///
155    /// See also:
156    ///
157    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
158    ///   [`ExpansionTileThemeData`].
159    pub background_color: Option<Color>,
160
161    /// When not `None`, defines the background color of tile when the sublist is collapsed.
162    ///
163    /// If this property is `None` then
164    /// [`ExpansionTileThemeData::collapsed_background_color`] is used. If that is also `None`
165    /// then `Colors::TRANSPARENT` is used.
166    ///
167    /// See also:
168    ///
169    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
170    ///   [`ExpansionTileThemeData`].
171    pub collapsed_background_color: Option<Color>,
172
173    /// A widget to display after the title.
174    ///
175    /// Depending on the value of [`control_affinity`](Self::control_affinity), the
176    /// [`trailing`](Self::trailing) widget may replace the rotating expansion arrow icon.
177    pub trailing: Option<WidgetRef>,
178
179    /// Specifies if the [`ExpansionTile`] should build a default trailing icon if
180    /// [`trailing`](Self::trailing) is `None`.
181    pub show_trailing_icon: bool,
182
183    /// Specifies if the list tile is initially expanded (true) or collapsed (false).
184    ///
185    /// Alternatively, a provided [`controller`](Self::controller) can be used to initially
186    /// expand the tile if [`ExpansibleController::expand`] is called before this widget is
187    /// built.
188    ///
189    /// Defaults to false.
190    pub initially_expanded: bool,
191
192    /// Specifies whether the state of the children is maintained when the tile expands and
193    /// collapses.
194    ///
195    /// When true, the children are kept in the tree while the tile is collapsed.
196    /// When false (default), the children are removed from the tree when the tile is
197    /// collapsed and recreated upon expansion.
198    pub maintain_state: bool,
199
200    /// Specifies padding for the [`ListTile`].
201    ///
202    /// Analogous to `ListTile::content_padding`, this property defines the insets for
203    /// the [`leading`](Self::leading), [`title`](Self::title), [`subtitle`](Self::subtitle)
204    /// and [`trailing`](Self::trailing) widgets. It does not inset the expanded
205    /// [`children`](Self::children) widgets.
206    ///
207    /// If this property is `None` then [`ExpansionTileThemeData::tile_padding`] is used. If
208    /// that is also `None` then the tile's padding is `EdgeInsets.symmetric(horizontal: 16.0)`.
209    ///
210    /// See also:
211    ///
212    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
213    ///   [`ExpansionTileThemeData`].
214    pub tile_padding: Option<EdgeInsetsGeometry>,
215
216    /// Specifies the alignment of [`children`](Self::children), which are arranged in a column
217    /// when the tile is expanded.
218    ///
219    /// The internals of the expanded tile make use of a [`Column`] widget for
220    /// [`children`](Self::children), and [`Align`] widget to align the column. The
221    /// [`expanded_alignment`](Self::expanded_alignment) parameter is passed directly into the
222    /// [`Align`].
223    ///
224    /// Modifying this property controls the alignment of the column within the
225    /// expanded tile, not the alignment of [`children`](Self::children) widgets within the
226    /// column. To align each child within [`children`](Self::children), see
227    /// [`expanded_cross_axis_alignment`](Self::expanded_cross_axis_alignment).
228    ///
229    /// The width of the column is the width of the widest child widget in
230    /// [`children`](Self::children).
231    ///
232    /// If this property is `None` then [`ExpansionTileThemeData::expanded_alignment`]is used.
233    /// If that is also `None` then the value of [`expanded_alignment`](Self::expanded_alignment)
234    /// is [`Alignment::CENTER`].
235    ///
236    /// See also:
237    ///
238    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
239    ///   [`ExpansionTileThemeData`].
240    pub expanded_alignment: Option<AlignmentGeometry>,
241
242    /// Specifies the alignment of each child within [`children`](Self::children) when the
243    /// tile is expanded.
244    ///
245    /// The internals of the expanded tile make use of a [`Column`] widget for
246    /// [`children`](Self::children), and the `cross_axis_alignment` parameter is passed
247    /// directly into the [`Column`].
248    ///
249    /// Modifying this property controls the cross axis alignment of each child
250    /// within its [`Column`]. The width of the [`Column`] that houses
251    /// [`children`](Self::children) will be the same as the widest child widget in
252    /// [`children`](Self::children). The width of the [`Column`] might not be equal to the
253    /// width of the expanded tile.
254    ///
255    /// To align the [`Column`] along the expanded tile, use the
256    /// [`expanded_alignment`](Self::expanded_alignment) property instead.
257    ///
258    /// When the value is `None`, the value of
259    /// [`expanded_cross_axis_alignment`](Self::expanded_cross_axis_alignment) is
260    /// [`CrossAxisAlignment::Center`].
261    pub expanded_cross_axis_alignment: Option<CrossAxisAlignment>,
262
263    /// Specifies padding for [`children`](Self::children).
264    ///
265    /// If this property is `None` then [`ExpansionTileThemeData::children_padding`] is used.
266    /// If that is also `None` then the value of [`children_padding`](Self::children_padding)
267    /// is `EdgeInsets.zero`.
268    ///
269    /// See also:
270    ///
271    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
272    ///   [`ExpansionTileThemeData`].
273    pub children_padding: Option<EdgeInsetsGeometry>,
274
275    /// The icon color of tile's expansion arrow icon when the sublist is expanded.
276    ///
277    /// Used to override to the `ListTileThemeData::icon_color`.
278    ///
279    /// If this property is `None` then [`ExpansionTileThemeData::icon_color`] is used. If that
280    /// is also `None` then the value of `ColorScheme::primary` is used.
281    ///
282    /// See also:
283    ///
284    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
285    ///   [`ExpansionTileThemeData`].
286    pub icon_color: Option<Color>,
287
288    /// The icon color of tile's expansion arrow icon when the sublist is collapsed.
289    ///
290    /// Used to override to the `ListTileThemeData::icon_color`.
291    ///
292    /// If this property is `None` then [`ExpansionTileThemeData::collapsed_icon_color`] is
293    /// used. If that is also `None` and `ThemeData::use_material3` is true,
294    /// `ColorScheme::on_surface` is used. Otherwise, defaults to
295    /// `ThemeData::unselected_widget_color` color.
296    ///
297    /// See also:
298    ///
299    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
300    ///   [`ExpansionTileThemeData`].
301    pub collapsed_icon_color: Option<Color>,
302
303    /// The color of the tile's titles when the sublist is expanded.
304    ///
305    /// Used to override to the `ListTileThemeData::text_color`.
306    ///
307    /// If this property is `None` then [`ExpansionTileThemeData::text_color`] is used. If that
308    /// is also `None` then and `ThemeData::use_material3` is true, color of the
309    /// `TextTheme::body_large` will be used for the [`title`](Self::title) and
310    /// [`subtitle`](Self::subtitle). Otherwise, defaults to `ColorScheme::primary` color.
311    ///
312    /// See also:
313    ///
314    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
315    ///   [`ExpansionTileThemeData`].
316    pub text_color: Option<Color>,
317
318    /// The color of the tile's titles when the sublist is collapsed.
319    ///
320    /// Used to override to the `ListTileThemeData::text_color`.
321    ///
322    /// If this property is `None` then [`ExpansionTileThemeData::collapsed_text_color`] is
323    /// used. If that is also `None` and `ThemeData::use_material3` is true, color of the
324    /// `TextTheme::body_large` will be used for the [`title`](Self::title) and
325    /// [`subtitle`](Self::subtitle). Otherwise, defaults to color of the
326    /// `TextTheme::title_medium`.
327    ///
328    /// See also:
329    ///
330    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
331    ///   [`ExpansionTileThemeData`].
332    pub collapsed_text_color: Option<Color>,
333
334    /// The tile's border shape when the sublist is expanded.
335    ///
336    /// If this property is `None`, the [`ExpansionTileThemeData::shape`] is used. If that
337    /// is also `None`, a [`Border`] with vertical sides default to `ThemeData::divider_color`
338    /// is used
339    ///
340    /// See also:
341    ///
342    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
343    ///   [`ExpansionTileThemeData`].
344    pub shape: Option<ShapeBorderRef>,
345
346    /// The tile's border shape when the sublist is collapsed.
347    ///
348    /// If this property is `None`, the [`ExpansionTileThemeData::collapsed_shape`] is used. If
349    /// that is also `None`, a [`Border`] with vertical sides default to Color
350    /// `Colors::TRANSPARENT` is used
351    ///
352    /// See also:
353    ///
354    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
355    ///   [`ExpansionTileThemeData`].
356    pub collapsed_shape: Option<ShapeBorderRef>,
357
358    /// The content will be clipped (or not) according to this option.
359    ///
360    /// If this is not `None` and a custom collapsed or expanded shape is provided,
361    /// the value of [`clip_behavior`](Self::clip_behavior) will be used to clip the expansion
362    /// tile.
363    ///
364    /// If this property is `None`, the [`ExpansionTileThemeData::clip_behavior`] is used. If
365    /// that is also `None`, defaults to [`Clip::AntiAlias`].
366    ///
367    /// See also:
368    ///
369    /// * [`ExpansionTileTheme::of`], which returns the nearest [`ExpansionTileTheme`]'s
370    ///   [`ExpansionTileThemeData`].
371    pub clip_behavior: Option<Clip>,
372
373    /// Typically used to force the expansion arrow icon to the tile's leading or trailing
374    /// edge.
375    ///
376    /// By default, the value of [`control_affinity`](Self::control_affinity) is
377    /// [`ListTileControlAffinity::Platform`], which means that the expansion arrow icon will
378    /// appear on the tile's trailing edge.
379    pub control_affinity: Option<ListTileControlAffinity>,
380
381    /// If provided, the controller can be used to expand and collapse tiles.
382    ///
383    /// In cases where control over the tile's state is needed from a callback
384    /// triggered by a widget within the tile, [`ExpansibleController::of`] may be
385    /// more convenient than supplying a controller.
386    pub controller: Option<Ref<ExpansibleController>>,
387
388    /// Whether this list tile is part of a vertically dense list.
389    ///
390    /// If this property is `None` then its value is based on `ListTileThemeData::dense`.
391    ///
392    /// Dense list tiles default to a smaller height.
393    pub dense: Option<bool>,
394
395    /// The splash color of the ink response when the tile is tapped.
396    ///
397    /// This color is passed directly to the underlying [`ListTile`]'s
398    /// `splash_color` property, which controls the ink ripple (splash)
399    /// animation when the tile is tapped. Internally, [`ListTile`] uses
400    /// an `InkWell` (which handles the actual splash effect), and so the
401    /// provided color will apply to that ripple.
402    ///
403    /// If `None`, the splash color will default to the current theme’s
404    /// `ThemeData::splash_color`.
405    ///
406    /// See also:
407    ///
408    /// * `ListTile::splash_color`, which sets the ink splash for the tile.
409    /// * `InkWell::splash_color`, which determines the color of the ripple
410    ///   effect in Material widgets.
411    /// * `ThemeData::splash_color`, which provides a fallback color.
412    pub splash_color: Option<Color>,
413
414    /// Defines how compact the expansion tile's layout will be.
415    ///
416    /// Compactness for components is defined by [`VisualDensity`]; see
417    /// `ThemeData::visual_density`.
418    pub visual_density: Option<VisualDensity>,
419
420    /// The minimum height allocated for the [`ListTile`] widget.
421    ///
422    /// If this is `None`, default tile heights are 56.0, 72.0, and 88.0 for one,
423    /// two, and three lines of text respectively. If `ListTile::dense` is true,
424    /// these defaults are changed to 48.0, 64.0, and 76.0.
425    pub min_tile_height: Option<f64>,
426
427    /// Whether detected gestures should provide acoustic and/or haptic feedback.
428    ///
429    /// For example, on Android a tap will produce a clicking sound and a
430    /// long-press will produce a short vibration, when feedback is enabled.
431    ///
432    /// When `ListTile::enable_feedback` is `None`, `ListTileThemeData::enable_feedback`
433    /// is used; when that is also `None`, the default is true.
434    pub enable_feedback: Option<bool>,
435
436    /// Whether this expansion tile is interactive.
437    ///
438    /// If false, the internal [`ListTile`] will be disabled, changing its
439    /// appearance according to the theme and disabling user interaction.
440    ///
441    /// Even if disabled, the expansion can still be toggled programmatically
442    /// through an [`ExpansionTileController`].
443    pub enabled: bool,
444
445    /// Used to override the expansion animation curve and duration.
446    ///
447    /// If [`AnimationStyle::duration`] is provided, it will be used to override
448    /// the expansion animation duration. If it is `None`, then [`AnimationStyle::duration`]
449    /// from the [`ExpansionTileThemeData::expansion_animation_style`] will be used.
450    /// Otherwise, defaults to 200ms.
451    ///
452    /// If [`AnimationStyle::curve`] is provided, it will be used to override
453    /// the expansion animation curve. If it is `None`, then [`AnimationStyle::curve`]
454    /// from the [`ExpansionTileThemeData::expansion_animation_style`] will be used.
455    /// Otherwise, defaults to [`Curves::ease_in`].
456    ///
457    /// If [`AnimationStyle::reverse_curve`] is provided, it will be used to override
458    /// the collapse animation curve. If it is `None`, then [`AnimationStyle::reverse_curve`]
459    /// from the [`ExpansionTileThemeData::expansion_animation_style`] will be used.
460    /// Otherwise, the same curve will be used as for expansion.
461    ///
462    /// To disable the theme animation, use [`AnimationStyle::NO_ANIMATION`].
463    pub expansion_animation_style: Option<AnimationStyle>,
464
465    /// Whether to add button:true to the semantics if onTap is provided.
466    /// This is a temporary flag to help changing the behavior of ListTile onTap semantics.
467    pub internal_add_semantic_for_on_tap: bool,
468
469    /// The controller that notifies when the widget's `WidgetState`s change.
470    ///
471    /// This allows listening to and controlling states such as
472    /// `WidgetState::Hovered`, `WidgetState::Focused`, `WidgetState::Pressed`,
473    /// and `WidgetState::Disabled` for the tile's header.
474    ///
475    /// If `None`, the backing [`ListTile`] will create and manage its own
476    /// `WidgetStatesController`.
477    pub states_controller: Option<Ref<WidgetStatesController>>,
478}
479
480impl ExpansionTile {
481    /// Creates a single-line [`ListTile`] with an expansion arrow icon that expands or
482    /// collapses the tile to reveal or hide the [`children`](Self::children); Dart's optional
483    /// named arguments are the setters.
484    #[cfg_attr(debug_assertions, track_caller)]
485    pub fn new<K>(title: impl IntoWidget<K>) -> ExpansionTile {
486        ExpansionTile {
487            key: None,
488            leading: None,
489            title: title.into_widget(),
490            subtitle: None,
491            on_expansion_changed: None,
492            children: Vec::new(),
493            background_color: None,
494            collapsed_background_color: None,
495            trailing: None,
496            show_trailing_icon: true,
497            initially_expanded: false,
498            maintain_state: false,
499            tile_padding: None,
500            expanded_alignment: None,
501            expanded_cross_axis_alignment: None,
502            children_padding: None,
503            icon_color: None,
504            collapsed_icon_color: None,
505            text_color: None,
506            collapsed_text_color: None,
507            shape: None,
508            collapsed_shape: None,
509            clip_behavior: None,
510            control_affinity: None,
511            controller: None,
512            dense: None,
513            splash_color: None,
514            visual_density: None,
515            min_tile_height: None,
516            enable_feedback: Some(true),
517            enabled: true,
518            expansion_animation_style: None,
519            internal_add_semantic_for_on_tap: false,
520            states_controller: None,
521        }
522    }
523
524    /// Dart `ExpansionTile(key:)`.
525    pub fn key(mut self, key: KeyRef) -> ExpansionTile {
526        self.key = Some(key);
527        self
528    }
529
530    /// Dart `ExpansionTile(leading:)`.
531    #[cfg_attr(debug_assertions, track_caller)]
532    pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> ExpansionTile {
533        self.leading = Some(leading.into_widget());
534        self
535    }
536
537    /// Dart `ExpansionTile(subtitle:)`.
538    #[cfg_attr(debug_assertions, track_caller)]
539    pub fn subtitle<K>(mut self, subtitle: impl IntoWidget<K>) -> ExpansionTile {
540        self.subtitle = Some(subtitle.into_widget());
541        self
542    }
543
544    /// Dart `ExpansionTile(onExpansionChanged:)`.
545    pub fn on_expansion_changed(
546        mut self,
547        on_expansion_changed: ValueChanged<bool>,
548    ) -> ExpansionTile {
549        self.on_expansion_changed = Some(on_expansion_changed);
550        self
551    }
552
553    /// Dart `ExpansionTile(children:)`.
554    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> ExpansionTile {
555        self.children = children.into_iter().collect();
556        self
557    }
558
559    /// Dart `ExpansionTile(trailing:)`.
560    #[cfg_attr(debug_assertions, track_caller)]
561    pub fn trailing<K>(mut self, trailing: impl IntoWidget<K>) -> ExpansionTile {
562        self.trailing = Some(trailing.into_widget());
563        self
564    }
565
566    /// Dart `ExpansionTile(showTrailingIcon:)`.
567    pub fn show_trailing_icon(mut self, show_trailing_icon: bool) -> ExpansionTile {
568        self.show_trailing_icon = show_trailing_icon;
569        self
570    }
571
572    /// Dart `ExpansionTile(initiallyExpanded:)`.
573    pub fn initially_expanded(mut self, initially_expanded: bool) -> ExpansionTile {
574        self.initially_expanded = initially_expanded;
575        self
576    }
577
578    /// Dart `ExpansionTile(maintainState:)`.
579    pub fn maintain_state(mut self, maintain_state: bool) -> ExpansionTile {
580        self.maintain_state = maintain_state;
581        self
582    }
583
584    /// Dart `ExpansionTile(tilePadding:)`.
585    pub fn tile_padding(mut self, tile_padding: impl Into<EdgeInsetsGeometry>) -> ExpansionTile {
586        self.tile_padding = Some(tile_padding.into());
587        self
588    }
589
590    /// Dart `ExpansionTile(expandedCrossAxisAlignment:)`.
591    pub fn expanded_cross_axis_alignment(
592        mut self,
593        expanded_cross_axis_alignment: CrossAxisAlignment,
594    ) -> ExpansionTile {
595        debug_assert!(
596            expanded_cross_axis_alignment != CrossAxisAlignment::Baseline,
597            "CrossAxisAlignment.baseline is not supported since the expanded children \
598             are aligned in a column, not a row. Try to use another constant.",
599        );
600        self.expanded_cross_axis_alignment = Some(expanded_cross_axis_alignment);
601        self
602    }
603
604    /// Dart `ExpansionTile(expandedAlignment:)`.
605    pub fn expanded_alignment(
606        mut self,
607        expanded_alignment: impl Into<AlignmentGeometry>,
608    ) -> ExpansionTile {
609        self.expanded_alignment = Some(expanded_alignment.into());
610        self
611    }
612
613    /// Dart `ExpansionTile(childrenPadding:)`.
614    pub fn children_padding(
615        mut self,
616        children_padding: impl Into<EdgeInsetsGeometry>,
617    ) -> ExpansionTile {
618        self.children_padding = Some(children_padding.into());
619        self
620    }
621
622    /// Dart `ExpansionTile(backgroundColor:)`.
623    pub fn background_color(mut self, background_color: Color) -> ExpansionTile {
624        self.background_color = Some(background_color);
625        self
626    }
627
628    /// Dart `ExpansionTile(collapsedBackgroundColor:)`.
629    pub fn collapsed_background_color(
630        mut self,
631        collapsed_background_color: Color,
632    ) -> ExpansionTile {
633        self.collapsed_background_color = Some(collapsed_background_color);
634        self
635    }
636
637    /// Dart `ExpansionTile(textColor:)`.
638    pub fn text_color(mut self, text_color: Color) -> ExpansionTile {
639        self.text_color = Some(text_color);
640        self
641    }
642
643    /// Dart `ExpansionTile(collapsedTextColor:)`.
644    pub fn collapsed_text_color(mut self, collapsed_text_color: Color) -> ExpansionTile {
645        self.collapsed_text_color = Some(collapsed_text_color);
646        self
647    }
648
649    /// Dart `ExpansionTile(iconColor:)`.
650    pub fn icon_color(mut self, icon_color: Color) -> ExpansionTile {
651        self.icon_color = Some(icon_color);
652        self
653    }
654
655    /// Dart `ExpansionTile(collapsedIconColor:)`.
656    pub fn collapsed_icon_color(mut self, collapsed_icon_color: Color) -> ExpansionTile {
657        self.collapsed_icon_color = Some(collapsed_icon_color);
658        self
659    }
660
661    /// Dart `ExpansionTile(shape:)`.
662    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> ExpansionTile {
663        self.shape = Some(shape.into());
664        self
665    }
666
667    /// Dart `ExpansionTile(collapsedShape:)`.
668    pub fn collapsed_shape(mut self, collapsed_shape: impl Into<ShapeBorderRef>) -> ExpansionTile {
669        self.collapsed_shape = Some(collapsed_shape.into());
670        self
671    }
672
673    /// Dart `ExpansionTile(clipBehavior:)`.
674    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ExpansionTile {
675        self.clip_behavior = Some(clip_behavior);
676        self
677    }
678
679    /// Dart `ExpansionTile(controlAffinity:)`.
680    pub fn control_affinity(mut self, control_affinity: ListTileControlAffinity) -> ExpansionTile {
681        self.control_affinity = Some(control_affinity);
682        self
683    }
684
685    /// Dart `ExpansionTile(controller:)`.
686    pub fn controller(mut self, controller: Ref<ExpansibleController>) -> ExpansionTile {
687        self.controller = Some(controller);
688        self
689    }
690
691    /// Dart `ExpansionTile(dense:)`.
692    pub fn dense(mut self, dense: bool) -> ExpansionTile {
693        self.dense = Some(dense);
694        self
695    }
696
697    /// Dart `ExpansionTile(splashColor:)`.
698    pub fn splash_color(mut self, splash_color: Color) -> ExpansionTile {
699        self.splash_color = Some(splash_color);
700        self
701    }
702
703    /// Dart `ExpansionTile(visualDensity:)`.
704    pub fn visual_density(mut self, visual_density: VisualDensity) -> ExpansionTile {
705        self.visual_density = Some(visual_density);
706        self
707    }
708
709    /// Dart `ExpansionTile(minTileHeight:)`.
710    pub fn min_tile_height(mut self, min_tile_height: f64) -> ExpansionTile {
711        self.min_tile_height = Some(min_tile_height);
712        self
713    }
714
715    /// Dart `ExpansionTile(enableFeedback:)`.
716    pub fn enable_feedback(mut self, enable_feedback: bool) -> ExpansionTile {
717        self.enable_feedback = Some(enable_feedback);
718        self
719    }
720
721    /// Dart `ExpansionTile(enabled:)`.
722    pub fn enabled(mut self, enabled: bool) -> ExpansionTile {
723        self.enabled = enabled;
724        self
725    }
726
727    /// Dart `ExpansionTile(expansionAnimationStyle:)`.
728    pub fn expansion_animation_style(
729        mut self,
730        expansion_animation_style: AnimationStyle,
731    ) -> ExpansionTile {
732        self.expansion_animation_style = Some(expansion_animation_style);
733        self
734    }
735
736    /// Dart `ExpansionTile(internalAddSemanticForOnTap:)`.
737    pub fn internal_add_semantic_for_on_tap(
738        mut self,
739        internal_add_semantic_for_on_tap: bool,
740    ) -> ExpansionTile {
741        self.internal_add_semantic_for_on_tap = internal_add_semantic_for_on_tap;
742        self
743    }
744
745    /// Dart `ExpansionTile(statesController:)`.
746    pub fn states_controller(
747        mut self,
748        states_controller: Ref<WidgetStatesController>,
749    ) -> ExpansionTile {
750        self.states_controller = Some(states_controller);
751        self
752    }
753}
754
755impl fmt::Debug for ExpansionTile {
756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757        f.debug_struct("ExpansionTile")
758            .field("initially_expanded", &self.initially_expanded)
759            .field("maintain_state", &self.maintain_state)
760            .field("controller", &self.controller)
761            .field("enabled", &self.enabled)
762            .finish_non_exhaustive()
763    }
764}
765
766impl StatefulWidget for ExpansionTile {
767    type State = ExpansionTileState;
768
769    fn key(&self) -> Option<&KeyRef> {
770        self.key.as_ref()
771    }
772
773    fn create_state(&self) -> ExpansionTileState {
774        ExpansionTileState {
775            state: StateData::new(),
776            ease_in_tween: None,
777            ease_out_tween: None,
778            half_tween: None,
779            border_tween: ShapeBorderTween::new(None, None),
780            header_color_tween: None,
781            icon_color_tween: None,
782            background_color_tween: None,
783            icon_turns: None,
784            border: None,
785            header_color: None,
786            icon_color: None,
787            background_color: None,
788            expansion_tile_theme: ExpansionTileThemeData::new(),
789            tile_controller: None,
790            curve: Curves::ease_in(),
791            reverse_curve: None,
792            duration: K_EXPAND,
793        }
794    }
795}
796
797/// Dart's `_ExpansionTileState`.
798pub struct ExpansionTileState {
799    state: StateData<ExpansionTile>,
800    /// Dart's `static final` `_easeInTween`, `_easeOutTween` and `_halfTween`, and the
801    /// `ColorTween`s Dart's field initializers make, created in `init_state` because an arena
802    /// object needs the [`App`].
803    ease_in_tween: Option<Ref<CurveTween>>,
804    ease_out_tween: Option<Ref<CurveTween>>,
805    half_tween: Option<Ref<Tween<f64>>>,
806    border_tween: ShapeBorderTween,
807    header_color_tween: Option<Ref<ColorTween>>,
808    icon_color_tween: Option<Ref<ColorTween>>,
809    background_color_tween: Option<Ref<ColorTween>>,
810    icon_turns: Option<AnimationRef<f64>>,
811    border: Option<AnimationRef<Option<ShapeBorderRef>>>,
812    header_color: Option<AnimationRef<Option<Color>>>,
813    icon_color: Option<AnimationRef<Option<Color>>>,
814    background_color: Option<AnimationRef<Option<Color>>>,
815    expansion_tile_theme: ExpansionTileThemeData,
816    tile_controller: Option<Ref<ExpansibleController>>,
817    curve: Rc<dyn Curve>,
818    reverse_curve: Option<Rc<dyn Curve>>,
819    duration: Duration,
820}
821
822impl ExpansionTileState {
823    fn tile_controller(self: Handle<Self>, app: &App) -> Ref<ExpansibleController> {
824        app.get(self)
825            .tile_controller
826            .clone()
827            .expect("created in init_state")
828    }
829
830    fn ease_in_tween(self: Handle<Self>, app: &App) -> Ref<CurveTween> {
831        app.get(self)
832            .ease_in_tween
833            .clone()
834            .expect("created in init_state")
835    }
836
837    fn ease_out_tween(self: Handle<Self>, app: &App) -> Ref<CurveTween> {
838        app.get(self)
839            .ease_out_tween
840            .clone()
841            .expect("created in init_state")
842    }
843
844    fn on_expansion_changed(self: Handle<Self>, app: &mut App) {
845        let is_expanded = self.tile_controller(app).is_expanded(app);
846        if let Some(on_expansion_changed) = self.widget(app).on_expansion_changed.clone() {
847            on_expansion_changed(app, is_expanded);
848        }
849    }
850
851    // Platform or null affinity defaults to trailing.
852    fn effective_affinity(self: Handle<Self>, app: &mut App) -> ListTileControlAffinity {
853        let context = self.context(app);
854        let list_tile_theme = ListTileTheme::of(app, context);
855        let affinity = self
856            .widget(app)
857            .control_affinity
858            .or(list_tile_theme.control_affinity)
859            .unwrap_or(ListTileControlAffinity::Trailing);
860        match affinity {
861            ListTileControlAffinity::Leading => ListTileControlAffinity::Leading,
862            ListTileControlAffinity::Trailing | ListTileControlAffinity::Platform => {
863                ListTileControlAffinity::Trailing
864            }
865        }
866    }
867
868    fn build_icon(
869        self: Handle<Self>,
870        app: &mut App,
871        _context: BuildContext,
872        animation: AnimationRef<f64>,
873    ) -> Option<WidgetRef> {
874        let half_tween = app
875            .get(self)
876            .half_tween
877            .clone()
878            .expect("created in init_state");
879        let ease_in_tween = self.ease_in_tween(app);
880        let icon_turns = animation.drive(app, half_tween.chain(ease_in_tween));
881        app.get_mut(self).icon_turns = Some(icon_turns.clone());
882        Some(
883            RotationTransition::new(icon_turns)
884                .child(Icon::new(Some(Icons::expand_more())))
885                .into_widget(),
886        )
887    }
888
889    fn build_leading_icon(
890        self: Handle<Self>,
891        app: &mut App,
892        context: BuildContext,
893        animation: AnimationRef<f64>,
894    ) -> Option<WidgetRef> {
895        if self.effective_affinity(app) != ListTileControlAffinity::Leading {
896            return None;
897        }
898        self.build_icon(app, context, animation)
899    }
900
901    fn build_trailing_icon(
902        self: Handle<Self>,
903        app: &mut App,
904        context: BuildContext,
905        animation: AnimationRef<f64>,
906    ) -> Option<WidgetRef> {
907        if self.effective_affinity(app) != ListTileControlAffinity::Trailing {
908            return None;
909        }
910        self.build_icon(app, context, animation)
911    }
912
913    fn build_header(
914        self: Handle<Self>,
915        app: &mut App,
916        context: BuildContext,
917        animation: AnimationRef<f64>,
918    ) -> WidgetRef {
919        let ease_in_tween = self.ease_in_tween(app);
920        let icon_color_tween = app
921            .get(self)
922            .icon_color_tween
923            .clone()
924            .expect("created in init_state");
925        let header_color_tween = app
926            .get(self)
927            .header_color_tween
928            .clone()
929            .expect("created in init_state");
930        let icon_color = animation.drive(app, icon_color_tween.chain(ease_in_tween.clone()));
931        let header_color = animation.drive(app, header_color_tween.chain(ease_in_tween));
932        let state = app.get_mut(self);
933        state.icon_color = Some(icon_color.clone());
934        state.header_color = Some(header_color.clone());
935        let tile_controller = self.tile_controller(app);
936        let is_expanded = tile_controller.is_expanded(app);
937        let localizations = <dyn MaterialLocalizations>::of(app, context);
938        let on_tap_hint = if is_expanded {
939            localizations.expansion_tile_expanded_tap_hint()
940        } else {
941            localizations.expansion_tile_collapsed_tap_hint()
942        };
943        let semantics_hint = match app.platform().target_platform() {
944            TargetPlatform::IOS | TargetPlatform::MacOS => {
945                if is_expanded {
946                    format!(
947                        "{}\n {}",
948                        localizations.collapsed_hint(),
949                        localizations.expansion_tile_expanded_hint()
950                    )
951                } else {
952                    format!(
953                        "{}\n {}",
954                        localizations.expanded_hint(),
955                        localizations.expansion_tile_collapsed_hint()
956                    )
957                }
958            }
959            _ => {
960                if is_expanded {
961                    localizations.collapsed_hint()
962                } else {
963                    localizations.expanded_hint()
964                }
965            }
966        };
967
968        let widget = self.widget(app);
969        let leading = widget.leading.clone();
970        let title = widget.title.clone();
971        let subtitle = widget.subtitle.clone();
972        let show_trailing_icon = widget.show_trailing_icon;
973        let trailing = widget.trailing.clone();
974        let leading = match leading {
975            Some(leading) => Some(leading),
976            None => self.build_leading_icon(app, context, animation.clone()),
977        };
978        let trailing = if show_trailing_icon {
979            match trailing {
980                Some(trailing) => Some(trailing),
981                None => self.build_trailing_icon(app, context, animation),
982            }
983        } else {
984            None
985        };
986
987        let widget = self.widget(app);
988        let expansion_tile_theme = &app.get(self).expansion_tile_theme;
989        let on_tap = if is_expanded {
990            Listener::handle_method(tile_controller.handle(), ExpansibleController::collapse)
991        } else {
992            Listener::handle_method(tile_controller.handle(), ExpansibleController::expand)
993        };
994        let mut tile = ListTile::new()
995            .enabled(widget.enabled)
996            .on_tap(on_tap)
997            .title(title);
998        tile.dense = widget.dense;
999        tile.splash_color = widget.splash_color;
1000        tile.visual_density = widget.visual_density;
1001        tile.enable_feedback = widget.enable_feedback;
1002        tile.content_padding = widget.tile_padding.or(expansion_tile_theme.tile_padding);
1003        tile.leading = leading;
1004        tile.subtitle = subtitle;
1005        tile.trailing = trailing;
1006        tile.min_tile_height = widget.min_tile_height;
1007        tile.internal_add_semantic_for_on_tap = widget.internal_add_semantic_for_on_tap;
1008        tile.states_controller = widget.states_controller.clone();
1009
1010        let theme_icon_color = expansion_tile_theme.icon_color;
1011        let mut child = ListTileTheme::merge(tile);
1012        if let Some(icon_color) = icon_color.value(app).or(theme_icon_color) {
1013            child = child.icon_color(icon_color);
1014        }
1015        if let Some(text_color) = header_color.value(app) {
1016            child = child.text_color(text_color);
1017        }
1018
1019        let header = Semantics::new()
1020            .hint(semantics_hint.clone())
1021            .on_tap_hint(on_tap_hint)
1022            .child(child);
1023        if app.platform().target_platform() == TargetPlatform::Android {
1024            // Live region used to announce state changes (e.g., "expanded" or "collapsed")
1025            // without taking focus.
1026            // The container ensures the live region forms the node that blockNode
1027            // removes from focus traversal.
1028            return Semantics::new()
1029                .container(true)
1030                .label(semantics_hint)
1031                .live_region(true)
1032                .accessibility_focus_block_type(AccessibilityFocusBlockType::BlockNode)
1033                .child(header)
1034                .into_widget();
1035        }
1036        header.into_widget()
1037    }
1038
1039    fn build_body(
1040        self: Handle<Self>,
1041        app: &mut App,
1042        _context: BuildContext,
1043        _animation: AnimationRef<f64>,
1044    ) -> WidgetRef {
1045        let widget = self.widget(app);
1046        let expansion_tile_theme = &app.get(self).expansion_tile_theme;
1047        Align::new()
1048            .alignment(
1049                widget
1050                    .expanded_alignment
1051                    .or(expansion_tile_theme.expanded_alignment)
1052                    .unwrap_or(Alignment::CENTER.into()),
1053            )
1054            .child(
1055                Padding::new(
1056                    widget
1057                        .children_padding
1058                        .or(expansion_tile_theme.children_padding)
1059                        .unwrap_or(EdgeInsetsGeometry::ZERO),
1060                )
1061                .child(
1062                    Column::new()
1063                        .cross_axis_alignment(
1064                            widget
1065                                .expanded_cross_axis_alignment
1066                                .unwrap_or(CrossAxisAlignment::Center),
1067                        )
1068                        .children(widget.children.clone()),
1069                ),
1070            )
1071            .into_widget()
1072    }
1073
1074    fn build_expansible(
1075        self: Handle<Self>,
1076        app: &mut App,
1077        _context: BuildContext,
1078        header: &WidgetRef,
1079        body: &WidgetRef,
1080        animation: AnimationRef<f64>,
1081    ) -> WidgetRef {
1082        let ease_out_tween = self.ease_out_tween(app);
1083        let background_color_tween = app
1084            .get(self)
1085            .background_color_tween
1086            .clone()
1087            .expect("created in init_state");
1088        let border_tween = app.get(self).border_tween.clone();
1089        let background_color =
1090            animation.drive(app, background_color_tween.chain(ease_out_tween.clone()));
1091        let border = animation.drive(app, border_tween.chain(ease_out_tween));
1092        let state = app.get_mut(self);
1093        state.background_color = Some(background_color.clone());
1094        state.border = Some(border.clone());
1095        let expansion_tile_theme = &app.get(self).expansion_tile_theme;
1096        let background_color = background_color
1097            .value(app)
1098            .or(expansion_tile_theme.background_color)
1099            .unwrap_or(Colors::TRANSPARENT);
1100        let expansion_tile_border = border
1101            .value(app)
1102            .unwrap_or_else(|| ShapeBorderRef::new(transparent_border()));
1103        let widget = self.widget(app);
1104        let clip_behavior = widget
1105            .clip_behavior
1106            .or(expansion_tile_theme.clip_behavior)
1107            .unwrap_or(Clip::AntiAlias);
1108
1109        let decoration =
1110            ShapeDecoration::new(expansion_tile_border.clone()).color(background_color);
1111
1112        let mut tile = Padding::new(decoration.padding())
1113            .child(
1114                Column::new()
1115                    .main_axis_size(MainAxisSize::Min)
1116                    .children([header.clone(), body.clone()]),
1117            )
1118            .into_widget();
1119
1120        let is_shape_provided = widget.shape.is_some()
1121            || expansion_tile_theme.shape.is_some()
1122            || widget.collapsed_shape.is_some()
1123            || expansion_tile_theme.collapsed_shape.is_some();
1124
1125        if is_shape_provided {
1126            return Material::new()
1127                .clip_behavior(clip_behavior)
1128                .color(background_color)
1129                .shape(expansion_tile_border)
1130                .child(tile)
1131                .into_widget();
1132        }
1133
1134        // If the background color is not transparent, wrap the tile in a Material widget.
1135        // This is needed to ensure that the ListTile background color or ink splashes
1136        // are visible. A DecoratedBox with a non-transparent color will hide the
1137        // background color or ink splashes of the ListTile.
1138        if background_color.a > 0.0 {
1139            tile = Material::new()
1140                .r#type(MaterialType::Transparency)
1141                .child(tile)
1142                .into_widget();
1143        }
1144
1145        DecoratedBox::new(decoration).child(tile).into_widget()
1146    }
1147
1148    fn update_animation_duration(self: Handle<Self>, app: &mut App) {
1149        let state = app.get(self);
1150        let duration = self
1151            .widget(app)
1152            .expansion_animation_style
1153            .as_ref()
1154            .and_then(|style| style.duration)
1155            .or_else(|| {
1156                state
1157                    .expansion_tile_theme
1158                    .expansion_animation_style
1159                    .as_ref()
1160                    .and_then(|style| style.duration)
1161            })
1162            .unwrap_or(Duration::from_millis(200));
1163        app.get_mut(self).duration = duration;
1164    }
1165
1166    fn update_shape_border(self: Handle<Self>, app: &mut App, theme: &ThemeData) {
1167        let state = app.get(self);
1168        let widget = self.widget(app);
1169        let begin = widget
1170            .collapsed_shape
1171            .clone()
1172            .or_else(|| state.expansion_tile_theme.collapsed_shape.clone())
1173            .unwrap_or_else(|| ShapeBorderRef::new(transparent_border()));
1174        let end = widget
1175            .shape
1176            .clone()
1177            .or_else(|| state.expansion_tile_theme.shape.clone())
1178            .unwrap_or_else(|| {
1179                ShapeBorderRef::new(Border {
1180                    top: BorderSide {
1181                        color: theme.divider_color,
1182                        ..BorderSide::default()
1183                    },
1184                    bottom: BorderSide {
1185                        color: theme.divider_color,
1186                        ..BorderSide::default()
1187                    },
1188                    ..Border::default()
1189                })
1190            });
1191        let border_tween = &mut app.get_mut(self).border_tween;
1192        border_tween.begin = Some(begin);
1193        border_tween.end = Some(end);
1194    }
1195
1196    fn update_header_color(
1197        self: Handle<Self>,
1198        app: &mut App,
1199        defaults: &dyn ExpansionTileThemeDataGetters,
1200    ) {
1201        let state = app.get(self);
1202        let widget = self.widget(app);
1203        let begin = widget
1204            .collapsed_text_color
1205            .or(state.expansion_tile_theme.collapsed_text_color);
1206        let end = widget.text_color.or(state.expansion_tile_theme.text_color);
1207        let header_color_tween = state
1208            .header_color_tween
1209            .clone()
1210            .expect("created in init_state");
1211        let begin = begin.or_else(|| defaults.collapsed_text_color(app));
1212        let end = end.or_else(|| defaults.text_color(app));
1213        header_color_tween.set_begin(app, begin);
1214        header_color_tween.set_end(app, end);
1215    }
1216
1217    fn update_icon_color(
1218        self: Handle<Self>,
1219        app: &mut App,
1220        defaults: &dyn ExpansionTileThemeDataGetters,
1221    ) {
1222        let state = app.get(self);
1223        let widget = self.widget(app);
1224        let begin = widget
1225            .collapsed_icon_color
1226            .or(state.expansion_tile_theme.collapsed_icon_color);
1227        let end = widget.icon_color.or(state.expansion_tile_theme.icon_color);
1228        let icon_color_tween = state
1229            .icon_color_tween
1230            .clone()
1231            .expect("created in init_state");
1232        let begin = begin.or_else(|| defaults.collapsed_icon_color(app));
1233        let end = end.or_else(|| defaults.icon_color(app));
1234        icon_color_tween.set_begin(app, begin);
1235        icon_color_tween.set_end(app, end);
1236    }
1237
1238    fn update_background_color(self: Handle<Self>, app: &mut App) {
1239        let state = app.get(self);
1240        let widget = self.widget(app);
1241        let begin = widget
1242            .collapsed_background_color
1243            .or(state.expansion_tile_theme.collapsed_background_color);
1244        let end = widget
1245            .background_color
1246            .or(state.expansion_tile_theme.background_color);
1247        let background_color_tween = state
1248            .background_color_tween
1249            .clone()
1250            .expect("created in init_state");
1251        background_color_tween.set_begin(app, begin);
1252        background_color_tween.set_end(app, end);
1253    }
1254
1255    fn update_height_factor_curve(self: Handle<Self>, app: &mut App) {
1256        let state = app.get(self);
1257        let widget_style = self.widget(app).expansion_animation_style.as_ref();
1258        let theme_style = state
1259            .expansion_tile_theme
1260            .expansion_animation_style
1261            .as_ref();
1262        let curve = widget_style
1263            .and_then(|style| style.curve.clone())
1264            .or_else(|| theme_style.and_then(|style| style.curve.clone()))
1265            .unwrap_or_else(Curves::ease_in);
1266        let reverse_curve = widget_style
1267            .and_then(|style| style.reverse_curve.clone())
1268            .or_else(|| theme_style.and_then(|style| style.reverse_curve.clone()));
1269        let state = app.get_mut(self);
1270        state.curve = curve;
1271        state.reverse_curve = reverse_curve;
1272    }
1273
1274    /// Dart's `theme.useMaterial3 ? _ExpansionTileDefaultsM3(context) :
1275    /// _ExpansionTileDefaultsM2(context)`.
1276    fn defaults(
1277        context: BuildContext,
1278        theme: &ThemeData,
1279    ) -> Box<dyn ExpansionTileThemeDataGetters> {
1280        if theme.use_material3 {
1281            Box::new(ExpansionTileDefaultsM3::new(context))
1282        } else {
1283            Box::new(ExpansionTileDefaultsM2::new(context))
1284        }
1285    }
1286}
1287
1288/// The `Border(top: BorderSide(color: Colors.transparent), bottom: BorderSide(color:
1289/// Colors.transparent))` Dart writes as a `const` where no shape is given.
1290fn transparent_border() -> Border {
1291    Border {
1292        top: BorderSide {
1293            color: Colors::TRANSPARENT,
1294            ..BorderSide::default()
1295        },
1296        bottom: BorderSide {
1297            color: Colors::TRANSPARENT,
1298            ..BorderSide::default()
1299        },
1300        ..Border::default()
1301    }
1302}
1303
1304impl State for ExpansionTileState {
1305    type Widget = ExpansionTile;
1306    waft_widgets::state_accessors!();
1307
1308    fn init_state(self: Handle<Self>, app: &mut App) {
1309        let ease_in_tween = CurveTween::new(app, Curves::ease_in());
1310        let ease_out_tween = CurveTween::new(app, Curves::ease_out());
1311        let half_tween = Tween::new(app, Some(0.0), Some(0.5));
1312        let header_color_tween = ColorTween::new(app, None, None);
1313        let icon_color_tween = ColorTween::new(app, None, None);
1314        let background_color_tween = ColorTween::new(app, None, None);
1315        let tile_controller = match self.widget(app).controller.clone() {
1316            Some(controller) => controller,
1317            None => ExpansibleController::new(app),
1318        };
1319        let state = app.get_mut(self);
1320        state.ease_in_tween = Some(ease_in_tween);
1321        state.ease_out_tween = Some(ease_out_tween);
1322        state.half_tween = Some(half_tween);
1323        state.header_color_tween = Some(header_color_tween);
1324        state.icon_color_tween = Some(icon_color_tween);
1325        state.background_color_tween = Some(background_color_tween);
1326        state.curve = Curves::ease_in();
1327        state.duration = K_EXPAND;
1328        state.tile_controller = Some(tile_controller.clone());
1329        if self.widget(app).initially_expanded {
1330            tile_controller.expand(app);
1331        }
1332        tile_controller.add_listener(
1333            app,
1334            Listener::handle_method(self, Self::on_expansion_changed),
1335        );
1336    }
1337
1338    fn dispose(self: Handle<Self>, app: &mut App) {
1339        let tile_controller = self.tile_controller(app);
1340        tile_controller.remove_listener(
1341            app,
1342            &Listener::handle_method(self, Self::on_expansion_changed),
1343        );
1344        if self.widget(app).controller.is_none() {
1345            tile_controller.dispose(app);
1346        }
1347    }
1348
1349    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ExpansionTile) {
1350        let context = self.context(app);
1351        let theme = Theme::of(app, context);
1352        let expansion_tile_theme = ExpansionTileTheme::of(app, context);
1353        app.get_mut(self).expansion_tile_theme = expansion_tile_theme;
1354        let defaults = ExpansionTileState::defaults(context, &theme);
1355        let widget = self.widget(app);
1356        if widget.collapsed_shape != old_widget.collapsed_shape || widget.shape != old_widget.shape
1357        {
1358            self.update_shape_border(app, &theme);
1359        }
1360        let widget = self.widget(app);
1361        if widget.collapsed_text_color != old_widget.collapsed_text_color
1362            || widget.text_color != old_widget.text_color
1363        {
1364            self.update_header_color(app, &*defaults);
1365        }
1366        let widget = self.widget(app);
1367        if widget.collapsed_icon_color != old_widget.collapsed_icon_color
1368            || widget.icon_color != old_widget.icon_color
1369        {
1370            self.update_icon_color(app, &*defaults);
1371        }
1372        let widget = self.widget(app);
1373        if widget.background_color != old_widget.background_color
1374            || widget.collapsed_background_color != old_widget.collapsed_background_color
1375        {
1376            self.update_background_color(app);
1377        }
1378        if self.widget(app).expansion_animation_style != old_widget.expansion_animation_style {
1379            self.update_animation_duration(app);
1380            self.update_height_factor_curve(app);
1381        }
1382        let controller = self.widget(app).controller.clone();
1383        if controller != old_widget.controller {
1384            let tile_controller = self.tile_controller(app);
1385            tile_controller.remove_listener(
1386                app,
1387                &Listener::handle_method(self, Self::on_expansion_changed),
1388            );
1389            if old_widget.controller.is_none() {
1390                tile_controller.dispose(app);
1391            }
1392
1393            let tile_controller = match controller {
1394                Some(controller) => controller,
1395                None => ExpansibleController::new(app),
1396            };
1397            app.get_mut(self).tile_controller = Some(tile_controller.clone());
1398            tile_controller.add_listener(
1399                app,
1400                Listener::handle_method(self, Self::on_expansion_changed),
1401            );
1402        }
1403    }
1404
1405    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1406        let context = self.context(app);
1407        let theme = Theme::of(app, context);
1408        let expansion_tile_theme = ExpansionTileTheme::of(app, context);
1409        app.get_mut(self).expansion_tile_theme = expansion_tile_theme;
1410        let defaults = ExpansionTileState::defaults(context, &theme);
1411        self.update_animation_duration(app);
1412        self.update_shape_border(app, &theme);
1413        self.update_header_color(app, &*defaults);
1414        self.update_icon_color(app, &*defaults);
1415        self.update_background_color(app);
1416        self.update_height_factor_curve(app);
1417    }
1418
1419    #[allow(deprecated)]
1420    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1421        let state = app.get(self);
1422        let mut expansible = Expansible::new(
1423            Rc::new(move |app, context, animation| self.build_header(app, context, animation)),
1424            Rc::new(move |app, context, animation| self.build_body(app, context, animation)),
1425            self.tile_controller(app),
1426        )
1427        .curve(state.curve.clone())
1428        .duration(state.duration)
1429        .maintain_state(self.widget(app).maintain_state)
1430        .expansible_builder(Rc::new(move |app, context, header, body, animation| {
1431            self.build_expansible(app, context, header, body, animation)
1432        }));
1433        expansible.reverse_curve = state.reverse_curve.clone();
1434        expansible.into_widget()
1435    }
1436}
1437
1438impl fmt::Debug for ExpansionTileState {
1439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1440        f.debug_struct("ExpansionTileState")
1441            .field("tile_controller", &self.tile_controller)
1442            .field("duration", &self.duration)
1443            .finish_non_exhaustive()
1444    }
1445}
1446
1447/// Dart's `_ExpansionTileDefaultsM2`.
1448struct ExpansionTileDefaultsM2 {
1449    /// Dart's `super(..)` arguments.
1450    expansion_tile_theme_data: ExpansionTileThemeData,
1451    context: DefaultsContext,
1452}
1453
1454impl ExpansionTileDefaultsM2 {
1455    fn new(context: BuildContext) -> ExpansionTileDefaultsM2 {
1456        ExpansionTileDefaultsM2 {
1457            expansion_tile_theme_data: ExpansionTileThemeData::new(),
1458            context: DefaultsContext::new(context),
1459        }
1460    }
1461}
1462
1463impl ExpansionTileThemeDataGetters for ExpansionTileDefaultsM2 {
1464    fn expansion_tile_theme_data(&self) -> &ExpansionTileThemeData {
1465        &self.expansion_tile_theme_data
1466    }
1467
1468    fn text_color(&self, app: &mut App) -> Option<Color> {
1469        Some(self.context.colors(app).primary())
1470    }
1471
1472    fn icon_color(&self, app: &mut App) -> Option<Color> {
1473        Some(self.context.colors(app).primary())
1474    }
1475
1476    fn collapsed_text_color(&self, app: &mut App) -> Option<Color> {
1477        self.context
1478            .text_theme(app)
1479            .title_medium
1480            .as_ref()
1481            .expect("the theme's text theme has a title medium style")
1482            .color
1483            .as_deref()
1484            .copied()
1485    }
1486
1487    fn collapsed_icon_color(&self, app: &mut App) -> Option<Color> {
1488        Some(self.context.theme(app).unselected_widget_color)
1489    }
1490}
1491
1492#[cfg(test)]
1493pub(crate) mod tests {
1494    use std::cell::{Cell, RefCell};
1495    use waft_painting::ShapeBorder;
1496
1497    use waft_embedder::{Offset, Radius, Rect, TargetPlatform, TextDirection};
1498    use waft_painting::{
1499        AlignmentDirectional, BorderRadius, BorderStyle, EdgeInsets, RoundedRectangleBorder,
1500        StadiumBorder, TextStyle,
1501    };
1502    use waft_rendering::RenderBox as _;
1503    use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
1504    use waft_widgets::{
1505        Animated, AnyElement, Builder, Center, ColoredBox, DefaultTextStyle, Directionality,
1506        GlobalKey, IconTheme, SingleChildScrollView, SizedBox, StatefulBuilder, Text,
1507    };
1508
1509    use waft_widgets::testing::{
1510        TargetPlatformVariant, TestPointer, WidgetTester, assert_more_or_less_equals_within,
1511        expect, find, finds_nothing, finds_one_widget, test_widgets, test_widgets_variant,
1512    };
1513
1514    use super::*;
1515    use crate::color_scheme::ColorScheme;
1516    use crate::filled_button::FilledButton;
1517    use crate::list_tile_theme::ListTileThemeData;
1518    use crate::material::RenderInkFeatures;
1519    use crate::motion::Easing;
1520    use crate::scaffold::Scaffold;
1521    use crate::test_support::{PaintInspection, is_same_color_as, material_app};
1522    use crate::text_theme::TextTheme;
1523    use waft_foundation::HandleId;
1524    use waft_rendering::testing::{PaintCall, assert_paints};
1525
1526    const DIVIDER_COLOR: Color = Color::new(0x1f333333);
1527    const UNSELECTED_WIDGET_COLOR: Color = Colors::BLACK54;
1528    const HEADER_COLOR: Color = Colors::BLACK45;
1529
1530    fn foreground_color() -> Color {
1531        Colors::BLUE_ACCENT.shade200()
1532    }
1533
1534    /// Dart's `ThemeData()`.
1535    pub(crate) fn m3(app: &App) -> ThemeData {
1536        ThemeData::builder().build(app)
1537    }
1538
1539    /// Dart's `ThemeData(useMaterial3: false)`.
1540    pub(crate) fn m2(app: &App) -> ThemeData {
1541        ThemeData::builder().use_material3(false).build(app)
1542    }
1543
1544    /// Dart's `tester.pumpWidget(MaterialApp(theme: theme, home: home))`.
1545    pub(crate) fn pump_app<K>(
1546        tester: &mut WidgetTester,
1547        theme: impl FnOnce(&App) -> ThemeData,
1548        home: impl IntoWidget<K>,
1549    ) {
1550        let theme = theme(&tester.cell.borrow());
1551        tester.pump_widget(material_app(theme, home.into_widget()));
1552    }
1553
1554    /// The colour a [`test_icon`] or [`test_text`] was last built with.
1555    pub(crate) type Probe = Rc<Cell<Option<Color>>>;
1556
1557    pub(crate) fn probe() -> Probe {
1558        Rc::new(Cell::new(None))
1559    }
1560
1561    /// Dart's `TestIcon`: an `Icon(Icons.expand_more)` that keeps the `IconTheme` colour it was
1562    /// built with.
1563    pub(crate) fn test_icon(color: &Probe) -> WidgetRef {
1564        let color = Rc::clone(color);
1565        Builder::new(move |app, context| {
1566            color.set(IconTheme::of(app, context).color.as_deref().copied());
1567            Icon::new(Some(Icons::expand_more())).into_widget()
1568        })
1569        .into_widget()
1570    }
1571
1572    /// Dart's `TestText(text)`: a `Text` that keeps the `DefaultTextStyle` colour it was built
1573    /// with.
1574    pub(crate) fn test_text(text: &'static str, color: &Probe) -> WidgetRef {
1575        let color = Rc::clone(color);
1576        Builder::new(move |app, context| {
1577            color.set(
1578                DefaultTextStyle::of(app, context)
1579                    .style
1580                    .color
1581                    .as_deref()
1582                    .copied(),
1583            );
1584            Text::new(text).into_widget()
1585        })
1586        .into_widget()
1587    }
1588
1589    /// Dart's `tester.getRect(find.byKey(key))`.
1590    pub(crate) fn key_rect(tester: &WidgetTester, key: &GlobalKey) -> Rect {
1591        tester.get_rect(key)
1592    }
1593
1594    /// Dart's `tester.getSize(find.byKey(key)).height`.
1595    pub(crate) fn height(tester: &WidgetTester, key: &GlobalKey) -> f64 {
1596        key_rect(tester, key).height()
1597    }
1598
1599    /// Dart's `tester.getRect(find.byType(ListTile))`.
1600    pub(crate) fn list_tile_rect(tester: &WidgetTester) -> Rect {
1601        let found = find::by_type::<ListTile>().evaluate(tester);
1602        assert_eq!(found.len(), 1, "one ListTile");
1603        tester.get_rect(found[0])
1604    }
1605
1606    /// Dart's `tester.getRect(find.byIcon(Icons.expand_more))`.
1607    pub(crate) fn expand_more_rect(tester: &WidgetTester) -> Rect {
1608        tester.get_rect(tester.element(find::by_icon(&Icons::expand_more()).first()))
1609    }
1610
1611    /// Dart's `tester.getRect(find.byType(Column).last)`.
1612    fn last_column_rect(tester: &WidgetTester) -> Rect {
1613        let last = *find::by_type::<Column>()
1614            .evaluate(tester)
1615            .last()
1616            .expect("a Column");
1617        tester.get_rect(last)
1618    }
1619
1620    /// Dart's `tester.getRect(find.byType(Padding).last)`.
1621    pub(crate) fn last_padding_rect(tester: &WidgetTester) -> Rect {
1622        let last = *find::by_type::<Padding>()
1623            .evaluate(tester)
1624            .last()
1625            .expect("a Padding");
1626        tester.get_rect(last)
1627    }
1628
1629    fn element_of(tester: &WidgetTester, key: &GlobalKey) -> AnyElement {
1630        key.current_context(&tester.cell.borrow_mut())
1631            .expect("the keyed widget is mounted")
1632    }
1633
1634    /// The colour of Dart's `tester.firstWidget<DecoratedBox>(find.descendant(of:
1635    /// find.byKey(key), matching: find.byType(DecoratedBox))).decoration as ShapeDecoration`,
1636    /// with the colours of its `Border` shape's top and bottom sides.
1637    fn decoration_of(tester: &WidgetTester, key: &GlobalKey) -> (Option<Color>, Color, Color) {
1638        let first = tester.element(
1639            find::descendant(find::by_global_key(key), find::by_type::<DecoratedBox>()).first(),
1640        );
1641        tester.widget(first, |decorated_box: &DecoratedBox| {
1642            let decoration = decorated_box
1643                .decoration
1644                .as_any()
1645                .downcast_ref::<ShapeDecoration>()
1646                .expect("a ShapeDecoration");
1647            let border = decoration
1648                .shape
1649                .as_any()
1650                .downcast_ref::<Border>()
1651                .expect("a Border");
1652            (
1653                decoration.color.as_deref().copied(),
1654                border.top.color,
1655                border.bottom.color,
1656            )
1657        })
1658    }
1659
1660    /// Dart's `getMaterial(tester)`: the first `Material` below the `ExpansionTile`, as its
1661    /// shape, colour and clip behaviour.
1662    pub(crate) fn tile_material(
1663        tester: &WidgetTester,
1664    ) -> (Option<ShapeBorderRef>, Option<Color>, Clip) {
1665        let material = tester.element(
1666            find::descendant(
1667                find::by_type::<ExpansionTile>().at(0),
1668                find::by_type::<Material>(),
1669            )
1670            .first(),
1671        );
1672        tester.widget(material, |material: &Material| {
1673            (
1674                material.shape.clone(),
1675                material.color,
1676                material.clip_behavior,
1677            )
1678        })
1679    }
1680
1681    fn the_list_tile<R>(tester: &WidgetTester, read: impl FnOnce(&ListTile) -> R) -> R {
1682        let found = find::by_type::<ListTile>().evaluate(tester);
1683        assert_eq!(found.len(), 1, "one ListTile");
1684        tester.widget(found[0], read)
1685    }
1686
1687    fn is_widget<W: 'static>(widget: &Option<WidgetRef>) -> bool {
1688        widget
1689            .as_ref()
1690            .is_some_and(|widget| waft_widgets::downcast_widget::<W>(&**widget).is_some())
1691    }
1692
1693    pub(crate) fn sized(width: f64, height: f64) -> WidgetRef {
1694        SizedBox::new().width(width).height(height).into_widget()
1695    }
1696
1697    fn keyed_sized(key: &GlobalKey, width: f64, height: f64) -> WidgetRef {
1698        SizedBox::new()
1699            .key(key.clone().into())
1700            .width(width)
1701            .height(height)
1702            .into_widget()
1703    }
1704
1705    fn list_tile(key: Option<&GlobalKey>, title: &str) -> WidgetRef {
1706        let tile = ListTile::new().title(Text::new(title));
1707        match key {
1708            Some(key) => tile.key(key.clone().into()),
1709            None => tile,
1710        }
1711        .into_widget()
1712    }
1713
1714    fn initial_state_case(tester: &mut WidgetTester) {
1715        let top_key = GlobalKey::new();
1716        let expanded_key = GlobalKey::new();
1717        let collapsed_key = GlobalKey::new();
1718        let default_key = GlobalKey::new();
1719        let expanded_tile_key = GlobalKey::new();
1720        let collapsed_tile_key = GlobalKey::new();
1721        let default_tile_key = GlobalKey::new();
1722
1723        pump_app(
1724            tester,
1725            |app| ThemeData::builder().divider_color(DIVIDER_COLOR).build(app),
1726            Material::new().child(
1727                SingleChildScrollView::new().child(
1728                    Column::new().children([
1729                        list_tile(Some(&top_key), "Top"),
1730                        ExpansionTile::new(Text::new("Expanded"))
1731                            .key(expanded_key.clone().into())
1732                            .initially_expanded(true)
1733                            .background_color(Colors::RED.primary())
1734                            .children([list_tile(Some(&expanded_tile_key), "0")])
1735                            .into_widget(),
1736                        ExpansionTile::new(Text::new("Collapsed"))
1737                            .key(collapsed_key.clone().into())
1738                            .children([list_tile(Some(&collapsed_tile_key), "0")])
1739                            .into_widget(),
1740                        ExpansionTile::new(Text::new("Default"))
1741                            .key(default_key.clone().into())
1742                            .children([list_tile(Some(&default_tile_key), "0")])
1743                            .into_widget(),
1744                    ]),
1745                ),
1746            ),
1747        );
1748
1749        let tile_height = height(tester, &expanded_tile_key);
1750        assert_eq!(
1751            height(tester, &top_key),
1752            height(tester, &expanded_key) - tile_height - 2.0
1753        );
1754        assert_eq!(
1755            height(tester, &top_key),
1756            height(tester, &collapsed_key) - 2.0
1757        );
1758        assert_eq!(height(tester, &top_key), height(tester, &default_key) - 2.0);
1759
1760        let (color, top, bottom) = decoration_of(tester, &expanded_key);
1761        assert_eq!(color, Some(Colors::RED.primary()));
1762        assert_eq!(top, DIVIDER_COLOR);
1763        assert_eq!(bottom, DIVIDER_COLOR);
1764
1765        let (color, top, bottom) = decoration_of(tester, &collapsed_key);
1766        assert_eq!(color, Some(Colors::TRANSPARENT));
1767        assert_eq!(top, Colors::TRANSPARENT);
1768        assert_eq!(bottom, Colors::TRANSPARENT);
1769
1770        tester.tap(find::text("Expanded"));
1771        tester.tap(find::text("Collapsed"));
1772        tester.tap(find::text("Default"));
1773
1774        tester.pump();
1775
1776        // Pump to the middle of the animation for expansion.
1777        tester.pump_by(Duration::from_millis(100));
1778        let (color, top, bottom) = decoration_of(tester, &collapsed_key);
1779        assert_eq!(color, Some(Colors::TRANSPARENT));
1780        assert!(
1781            is_same_color_as(top, Color::new(0x15222222)),
1782            "top side {top:?}"
1783        );
1784        assert!(
1785            is_same_color_as(bottom, Color::new(0x15222222)),
1786            "bottom side {bottom:?}"
1787        );
1788
1789        // Pump all the way to the end now.
1790        tester.pump_by(Duration::from_secs(1));
1791
1792        let tile_height = height(tester, &collapsed_tile_key);
1793        assert_eq!(
1794            height(tester, &top_key),
1795            height(tester, &expanded_key) - 2.0
1796        );
1797        assert_eq!(
1798            height(tester, &top_key),
1799            height(tester, &collapsed_key) - tile_height - 2.0
1800        );
1801        assert_eq!(
1802            height(tester, &top_key),
1803            height(tester, &default_key) - tile_height - 2.0
1804        );
1805
1806        // Expanded should be collapsed now.
1807        let (color, top, bottom) = decoration_of(tester, &expanded_key);
1808        assert_eq!(color, Some(Colors::TRANSPARENT));
1809        assert_eq!(top, Colors::TRANSPARENT);
1810        assert_eq!(bottom, Colors::TRANSPARENT);
1811
1812        // Collapsed should be expanded now.
1813        let (color, top, bottom) = decoration_of(tester, &collapsed_key);
1814        assert_eq!(color, Some(Colors::TRANSPARENT));
1815        assert_eq!(top, DIVIDER_COLOR);
1816        assert_eq!(bottom, DIVIDER_COLOR);
1817    }
1818
1819    /// "ExpansionTile initial state", on iOS.
1820    #[test]
1821    fn expansion_tile_initial_state_on_ios() {
1822        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
1823            initial_state_case(tester)
1824        });
1825    }
1826
1827    /// "ExpansionTile initial state", on macOS.
1828    #[test]
1829    fn expansion_tile_initial_state_on_macos() {
1830        test_widgets_variant(
1831            TargetPlatformVariant::only(TargetPlatform::MacOS),
1832            initial_state_case,
1833        );
1834    }
1835
1836    fn theme_dependencies_case(tester: &mut WidgetTester) {
1837        let expanded_title = probe();
1838        let collapsed_title = probe();
1839        let expanded_icon = probe();
1840        let collapsed_icon = probe();
1841
1842        pump_app(
1843            tester,
1844            |app| {
1845                ThemeData::builder()
1846                    .use_material3(false)
1847                    .color_scheme(
1848                        ColorScheme::from_swatch()
1849                            .build()
1850                            .copy_with()
1851                            .with_primary(foreground_color()),
1852                    )
1853                    .unselected_widget_color(UNSELECTED_WIDGET_COLOR)
1854                    .text_theme(TextTheme::new().title_medium(TextStyle::new().color(HEADER_COLOR)))
1855                    .build(app)
1856            },
1857            Material::new().child(
1858                SingleChildScrollView::new().child(
1859                    Column::new().children([
1860                        list_tile(None, "Top"),
1861                        ExpansionTile::new(test_text("Expanded", &expanded_title))
1862                            .initially_expanded(true)
1863                            .background_color(Colors::RED.primary())
1864                            .trailing(test_icon(&expanded_icon))
1865                            .children([list_tile(None, "0")])
1866                            .into_widget(),
1867                        ExpansionTile::new(test_text("Collapsed", &collapsed_title))
1868                            .trailing(test_icon(&collapsed_icon))
1869                            .children([list_tile(None, "0")])
1870                            .into_widget(),
1871                    ]),
1872                ),
1873            ),
1874        );
1875
1876        assert_eq!(expanded_title.get(), Some(foreground_color()));
1877        assert_eq!(collapsed_title.get(), Some(HEADER_COLOR));
1878        assert_eq!(expanded_icon.get(), Some(foreground_color()));
1879        assert_eq!(collapsed_icon.get(), Some(UNSELECTED_WIDGET_COLOR));
1880
1881        // Tap both tiles to change their state: collapse and extend respectively
1882        tester.tap(find::text("Expanded"));
1883        tester.tap(find::text("Collapsed"));
1884        tester.pump();
1885        tester.pump_by(Duration::from_secs(1));
1886        tester.pump_by(Duration::from_secs(1));
1887
1888        assert_eq!(expanded_title.get(), Some(HEADER_COLOR));
1889        assert_eq!(collapsed_title.get(), Some(foreground_color()));
1890        assert_eq!(expanded_icon.get(), Some(UNSELECTED_WIDGET_COLOR));
1891        assert_eq!(collapsed_icon.get(), Some(foreground_color()));
1892    }
1893
1894    /// "ExpansionTile Theme dependencies", on iOS.
1895    #[test]
1896    fn expansion_tile_theme_dependencies_on_ios() {
1897        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
1898            theme_dependencies_case(tester)
1899        });
1900    }
1901
1902    /// "ExpansionTile Theme dependencies", on macOS.
1903    #[test]
1904    fn expansion_tile_theme_dependencies_on_macos() {
1905        test_widgets_variant(
1906            TargetPlatformVariant::only(TargetPlatform::MacOS),
1907            theme_dependencies_case,
1908        );
1909    }
1910
1911    /// "ExpansionTile subtitle".
1912    #[test]
1913    fn expansion_tile_subtitle() {
1914        test_widgets(|tester| {
1915            pump_app(
1916                tester,
1917                m3,
1918                Scaffold::new().body(
1919                    ExpansionTile::new(Text::new("Title"))
1920                        .subtitle(Text::new("Subtitle"))
1921                        .children([list_tile(None, "0")]),
1922                ),
1923            );
1924
1925            expect(tester, &find::text("Subtitle"), finds_one_widget());
1926        });
1927    }
1928
1929    /// "ExpansionTile maintainState".
1930    #[test]
1931    fn expansion_tile_maintain_state() {
1932        test_widgets(|tester| {
1933            pump_app(
1934                tester,
1935                |app| {
1936                    ThemeData::builder()
1937                        .platform(TargetPlatform::IOS)
1938                        .divider_color(DIVIDER_COLOR)
1939                        .build(app)
1940                },
1941                Material::new().child(
1942                    SingleChildScrollView::new().child(
1943                        Column::new().children([
1944                            ExpansionTile::new(Text::new("Tile 1"))
1945                                .maintain_state(true)
1946                                .children([Text::new("Maintaining State").into_widget()])
1947                                .into_widget(),
1948                            ExpansionTile::new(Text::new("Title 2"))
1949                                .children([Text::new("Discarding State").into_widget()])
1950                                .into_widget(),
1951                        ]),
1952                    ),
1953                ),
1954            );
1955
1956            // This text should be offstage while ExpansionTile collapsed
1957            expect(
1958                tester,
1959                &find::text("Maintaining State").skip_offstage(false),
1960                finds_one_widget(),
1961            );
1962            expect(tester, &find::text("Maintaining State"), finds_nothing());
1963            // This text shouldn't be there while ExpansionTile collapsed
1964            expect(tester, &find::text("Discarding State"), finds_nothing());
1965        });
1966    }
1967
1968    /// "ExpansionTile padding test".
1969    #[test]
1970    fn expansion_tile_padding_test() {
1971        test_widgets(|tester| {
1972            pump_app(
1973                tester,
1974                m3,
1975                Material::new().child(
1976                    Center::new().child(
1977                        ExpansionTile::new(Text::new("Hello"))
1978                            .tile_padding(EdgeInsets::from_ltrb(8.0, 12.0, 4.0, 10.0)),
1979                    ),
1980                ),
1981            );
1982
1983            let title_rect = tester.get_rect(find::text("Hello"));
1984            let trailing_rect = expand_more_rect(tester);
1985            let list_tile_rect = list_tile_rect(tester);
1986            let taller_widget = if title_rect.height() > trailing_rect.height() {
1987                title_rect
1988            } else {
1989                trailing_rect
1990            };
1991
1992            // Check the positions of title and trailing Widgets, after padding is applied.
1993            assert_eq!(list_tile_rect.left, title_rect.left - 8.0);
1994            assert_eq!(list_tile_rect.right, trailing_rect.right + 4.0);
1995
1996            // Calculate the remaining height of ListTile from the default height.
1997            let remaining_height = 56.0 - taller_widget.height();
1998            assert_eq!(
1999                list_tile_rect.top,
2000                taller_widget.top - remaining_height / 2.0 - 12.0
2001            );
2002            assert_eq!(
2003                list_tile_rect.bottom,
2004                taller_widget.bottom + remaining_height / 2.0 + 10.0
2005            );
2006        });
2007    }
2008
2009    /// `MaterialApp(home: [Directionality(textDirection:)] Material(child: Center(child: tile)))`,
2010    /// then a tap on "title" and a settle.
2011    fn pump_expanded_centered(
2012        tester: &mut WidgetTester,
2013        text_direction: Option<TextDirection>,
2014        tile: ExpansionTile,
2015    ) {
2016        let material = Material::new()
2017            .child(Center::new().child(tile))
2018            .into_widget();
2019        let home = match text_direction {
2020            Some(text_direction) => Directionality::new(text_direction, material).into_widget(),
2021            None => material,
2022        };
2023        pump_app(tester, m3, home);
2024        tester.tap(find::text("title"));
2025        tester.pump_and_settle();
2026    }
2027
2028    /// "ExpansionTile expandedAlignment test".
2029    #[test]
2030    fn expansion_tile_expanded_alignment_test() {
2031        test_widgets(|tester| {
2032            pump_expanded_centered(
2033                tester,
2034                None,
2035                ExpansionTile::new(Text::new("title"))
2036                    .expanded_alignment(Alignment::CENTER_LEFT)
2037                    .children([sized(100.0, 100.0), sized(80.0, 100.0)]),
2038            );
2039
2040            let column_rect = last_column_rect(tester);
2041
2042            // The expandedAlignment is used to define the alignment of the Column widget in
2043            // expanded tile, not the alignment of the children inside the Column.
2044            assert_eq!(column_rect.left, 0.0);
2045            // The width of the Column is the width of the largest child. The largest width
2046            // being 100.0, the offset of the right edge of Column from X-axis should be 100.0.
2047            assert_eq!(column_rect.right, 100.0);
2048        });
2049    }
2050
2051    /// "ExpansionTile expandedAlignment with directional test".
2052    #[test]
2053    fn expansion_tile_expanded_alignment_with_directional_test() {
2054        test_widgets(|tester| {
2055            pump_expanded_centered(
2056                tester,
2057                Some(TextDirection::Rtl),
2058                ExpansionTile::new(Text::new("title"))
2059                    .expanded_alignment(AlignmentDirectional::TOP_END)
2060                    .children([sized(100.0, 100.0), sized(80.0, 100.0)]),
2061            );
2062
2063            let column_rect = last_column_rect(tester);
2064
2065            // The expandedAlignment is used to define the alignment of the Column widget in
2066            // expanded tile, not the alignment of the children inside the Column.
2067            assert_eq!(column_rect.left, 0.0);
2068            // The width of the Column is the width of the largest child. The largest width
2069            // being 100.0, the offset of the right edge of Column from X-axis should be 100.0.
2070            assert_eq!(column_rect.right, 100.0);
2071        });
2072    }
2073
2074    /// "ExpansionTile expandedCrossAxisAlignment test".
2075    #[test]
2076    fn expansion_tile_expanded_cross_axis_alignment_test() {
2077        test_widgets(|tester| {
2078            let child0_key = GlobalKey::new();
2079            let child1_key = GlobalKey::new();
2080            pump_expanded_centered(
2081                tester,
2082                None,
2083                ExpansionTile::new(Text::new("title"))
2084                    // Set the column's alignment to Alignment.centerRight to test
2085                    // CrossAxisAlignment of children widgets. This helps distinguish the
2086                    // effect of expandedAlignment and expandedCrossAxisAlignment later in the
2087                    // test.
2088                    .expanded_alignment(Alignment::CENTER_RIGHT)
2089                    .expanded_cross_axis_alignment(CrossAxisAlignment::Start)
2090                    .children([
2091                        keyed_sized(&child0_key, 100.0, 100.0),
2092                        keyed_sized(&child1_key, 80.0, 100.0),
2093                    ]),
2094            );
2095
2096            let column_rect = last_column_rect(tester);
2097            let child0_rect = key_rect(tester, &child0_key);
2098            let child1_rect = key_rect(tester, &child1_key);
2099
2100            // Since expandedAlignment is set to Alignment.centerRight, the column of children
2101            // should be aligned to the center right of the expanded tile. This provides
2102            // confirmation that the expandedCrossAxisAlignment.start is 700.0, where
2103            // columnRect.left is.
2104            assert_eq!(column_rect.right, 800.0);
2105            // The width of the Column is the width of the largest child. The largest width
2106            // being 100.0, the offset of the left edge of Column from X-axis should be 700.0.
2107            assert_eq!(column_rect.left, 700.0);
2108
2109            // Considering the value of expandedCrossAxisAlignment is CrossAxisAlignment.start,
2110            // the offset of the left edge of both the children from X-axis should be 700.0.
2111            assert_eq!(child0_rect.left, 700.0);
2112            assert_eq!(child1_rect.left, 700.0);
2113        });
2114    }
2115
2116    /// "ExpansionTile expandedCrossAxisAlignment with directional expandedAlignment test".
2117    #[test]
2118    fn expansion_tile_expanded_cross_axis_alignment_with_directional_expanded_alignment_test() {
2119        test_widgets(|tester| {
2120            let child0_key = GlobalKey::new();
2121            let child1_key = GlobalKey::new();
2122            pump_expanded_centered(
2123                tester,
2124                Some(TextDirection::Rtl),
2125                ExpansionTile::new(Text::new("title"))
2126                    // Set the column's alignment to AlignmentDirectional.centerStart to test
2127                    // CrossAxisAlignment of children widgets. This helps distinguish the
2128                    // effect of expandedAlignment and expandedCrossAxisAlignment later in the
2129                    // test.
2130                    .expanded_alignment(AlignmentDirectional::CENTER_START)
2131                    .expanded_cross_axis_alignment(CrossAxisAlignment::End)
2132                    .children([
2133                        keyed_sized(&child0_key, 100.0, 100.0),
2134                        keyed_sized(&child1_key, 80.0, 100.0),
2135                    ]),
2136            );
2137
2138            let column_rect = last_column_rect(tester);
2139            let child0_rect = key_rect(tester, &child0_key);
2140            let child1_rect = key_rect(tester, &child1_key);
2141
2142            // With `textDirection` set to `TextDirection.rtl`,
2143            // `AlignmentDirectional.centerStart` resolves to `Alignment.centerRight`. The column
2144            // of children should be aligned to the center right of the expanded tile.
2145            assert_eq!(column_rect.right, 800.0);
2146            // The width of the Column is the width of the largest child. The largest width
2147            // being 100.0, the offset of the left edge of Column from X-axis should be 700.0.
2148            assert_eq!(column_rect.left, 700.0);
2149
2150            // With `textDirection` set to `TextDirection.rtl`, `CrossAxisAlignment.end` aligns
2151            // children to the left. The offset of the left edge of both children from the
2152            // X-axis should be 700.0.
2153            assert_eq!(child0_rect.left, 700.0);
2154            assert_eq!(child1_rect.left, 700.0);
2155        });
2156    }
2157
2158    /// "CrossAxisAlignment.baseline is not allowed".
2159    #[test]
2160    #[cfg(debug_assertions)]
2161    #[should_panic(
2162        expected = "CrossAxisAlignment.baseline is not supported since the expanded children \
2163                    are aligned in a column, not a row. Try to use another constant."
2164    )]
2165    fn cross_axis_alignment_baseline_is_not_allowed() {
2166        let _ = ExpansionTile::new(Text::new("title"))
2167            .initially_expanded(true)
2168            .expanded_cross_axis_alignment(CrossAxisAlignment::Baseline);
2169    }
2170
2171    /// "expandedCrossAxisAlignment and expandedAlignment default values".
2172    #[test]
2173    fn expanded_cross_axis_alignment_and_expanded_alignment_default_values() {
2174        test_widgets(|tester| {
2175            let child1_key = GlobalKey::new();
2176            pump_expanded_centered(
2177                tester,
2178                None,
2179                ExpansionTile::new(Text::new("title"))
2180                    .children([sized(100.0, 100.0), keyed_sized(&child1_key, 80.0, 100.0)]),
2181            );
2182
2183            let column_rect = last_column_rect(tester);
2184            let child1_rect = key_rect(tester, &child1_key);
2185
2186            // The default viewport size is Size(800, 600).
2187            // By default the value of extendedAlignment is Alignment.center, hence the offset
2188            // of left and right edges from x axis should be equal.
2189            assert_eq!(column_rect.left, 800.0 - column_rect.right);
2190
2191            // By default the value of extendedCrossAxisAlignment is CrossAxisAlignment.center,
2192            // hence the offset of left and right edges from Column should be equal.
2193            assert_eq!(
2194                child1_rect.left - column_rect.left,
2195                column_rect.right - child1_rect.right
2196            );
2197        });
2198    }
2199
2200    /// "childrenPadding default value".
2201    #[test]
2202    fn children_padding_default_value() {
2203        test_widgets(|tester| {
2204            pump_expanded_centered(
2205                tester,
2206                None,
2207                ExpansionTile::new(Text::new("title")).children([sized(100.0, 100.0)]),
2208            );
2209
2210            let column_rect = last_column_rect(tester);
2211            let padding_rect = last_padding_rect(tester);
2212
2213            // By default, the value of childrenPadding is EdgeInsets.zero, hence offset
2214            // of all the edges from x-axis and y-axis should be equal for Padding and Column.
2215            assert_eq!(column_rect.top, padding_rect.top);
2216            assert_eq!(column_rect.left, padding_rect.left);
2217            assert_eq!(column_rect.right, padding_rect.right);
2218            assert_eq!(column_rect.bottom, padding_rect.bottom);
2219        });
2220    }
2221
2222    /// "ExpansionTile childrenPadding test".
2223    #[test]
2224    fn expansion_tile_children_padding_test() {
2225        test_widgets(|tester| {
2226            pump_expanded_centered(
2227                tester,
2228                None,
2229                ExpansionTile::new(Text::new("title"))
2230                    .children_padding(EdgeInsets::from_ltrb(10.0, 8.0, 12.0, 4.0))
2231                    .children([sized(100.0, 100.0)]),
2232            );
2233
2234            let column_rect = last_column_rect(tester);
2235            let padding_rect = last_padding_rect(tester);
2236
2237            // Check the offset of all the edges from x-axis and y-axis after childrenPadding
2238            // is applied.
2239            assert_eq!(column_rect.left, padding_rect.left + 10.0);
2240            assert_eq!(column_rect.top, padding_rect.top + 8.0);
2241            assert_eq!(column_rect.right, padding_rect.right - 12.0);
2242            assert_eq!(column_rect.bottom, padding_rect.bottom - 4.0);
2243        });
2244    }
2245
2246    /// "ExpansionTile.collapsedBackgroundColor".
2247    #[test]
2248    fn expansion_tile_collapsed_background_color() {
2249        test_widgets(|tester| {
2250            let expansion_tile_key = GlobalKey::new();
2251            let background_color = Colors::RED.primary();
2252            let collapsed_background_color = Colors::BROWN.primary();
2253
2254            pump_app(
2255                tester,
2256                m3,
2257                Material::new().child(
2258                    ExpansionTile::new(Text::new("Title"))
2259                        .key(expansion_tile_key.clone().into())
2260                        .background_color(background_color)
2261                        .collapsed_background_color(collapsed_background_color)
2262                        .children([sized(100.0, 100.0)]),
2263                ),
2264            );
2265
2266            let (color, _, _) = decoration_of(tester, &expansion_tile_key);
2267            assert_eq!(color, Some(collapsed_background_color));
2268
2269            tester.tap(find::text("Title"));
2270            tester.pump_and_settle();
2271
2272            let (color, _, _) = decoration_of(tester, &expansion_tile_key);
2273            assert_eq!(color, Some(background_color));
2274        });
2275    }
2276
2277    /// "ExpansionTile default iconColor, textColor".
2278    #[test]
2279    fn expansion_tile_default_icon_color_text_color() {
2280        test_widgets(|tester| {
2281            let icon_color = probe();
2282            let text_color = probe();
2283
2284            pump_app(
2285                tester,
2286                m3,
2287                Material::new().child(
2288                    ExpansionTile::new(test_text("title", &text_color))
2289                        .trailing(test_icon(&icon_color))
2290                        .children([sized(100.0, 100.0)]),
2291                ),
2292            );
2293
2294            let theme = m3(&tester.cell.borrow());
2295            assert_eq!(
2296                icon_color.get(),
2297                Some(theme.color_scheme.on_surface_variant())
2298            );
2299            assert_eq!(text_color.get(), Some(theme.color_scheme.on_surface()));
2300
2301            tester.tap(find::text("title"));
2302            tester.pump_and_settle();
2303
2304            assert_eq!(icon_color.get(), Some(theme.color_scheme.primary()));
2305            assert_eq!(text_color.get(), Some(theme.color_scheme.on_surface()));
2306        });
2307    }
2308
2309    /// "ExpansionTile iconColor, textColor".
2310    #[test]
2311    fn expansion_tile_icon_color_text_color() {
2312        test_widgets(|tester| {
2313            // Regression test for https://github.com/flutter/flutter/pull/78281
2314            let icon_color = Color::new(0xff00ff00);
2315            let collapsed_icon_color = Color::new(0xff0000ff);
2316            let text_color = Color::new(0xff00ffff);
2317            let collapsed_text_color = Color::new(0xffff00ff);
2318            let icon = probe();
2319            let text = probe();
2320
2321            pump_app(
2322                tester,
2323                m3,
2324                Material::new().child(
2325                    ExpansionTile::new(test_text("title", &text))
2326                        .icon_color(icon_color)
2327                        .collapsed_icon_color(collapsed_icon_color)
2328                        .text_color(text_color)
2329                        .collapsed_text_color(collapsed_text_color)
2330                        .trailing(test_icon(&icon))
2331                        .children([sized(100.0, 100.0)]),
2332                ),
2333            );
2334
2335            assert_eq!(icon.get(), Some(collapsed_icon_color));
2336            assert_eq!(text.get(), Some(collapsed_text_color));
2337
2338            tester.tap(find::text("title"));
2339            tester.pump_and_settle();
2340
2341            assert_eq!(icon.get(), Some(icon_color));
2342            assert_eq!(text.get(), Some(text_color));
2343        });
2344    }
2345
2346    /// What the first `Material` below the `ExpansionTile` and its subtree draw.
2347    fn tile_material_painted(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
2348        let material = tester.element(
2349            find::descendant(
2350                find::by_type::<ExpansionTile>().at(0),
2351                find::by_type::<Material>(),
2352            )
2353            .first(),
2354        );
2355        tester.painted_ops(tester.render_object(material))
2356    }
2357
2358    /// "ExpansionTile shows hover color with opaque backgroundColor".
2359    #[test]
2360    fn expansion_tile_shows_hover_color_with_opaque_background_color() {
2361        test_widgets(|tester| {
2362            let hover_color = Colors::GREEN.primary();
2363            let background_color = Colors::BLUE.primary();
2364
2365            pump_app(
2366                tester,
2367                |app| ThemeData::builder().hover_color(hover_color).build(app),
2368                Material::new().child(
2369                    ExpansionTile::new(Text::new("Title"))
2370                        .collapsed_background_color(background_color),
2371                ),
2372            );
2373
2374            // Hover the tile.
2375            let mut gesture = TestPointer::mouse(1, 0);
2376            tester.add_pointer(&mut gesture, Offset::ZERO);
2377            tester.pump();
2378            let center = tester.get_rect(find::text("Title")).center();
2379            tester.move_to(&mut gesture, center, false);
2380            tester.pump_and_settle();
2381
2382            // Dart's `paints..rect(color: Colors.transparent)..rect(color: hoverColor)`: a draw
2383            // with a transparent paint is not recorded at all, so the tile's transparent ink
2384            // decoration has no entry and the hover highlight is the first draw.
2385            assert_paints(
2386                &tile_material_painted(tester),
2387                &[PaintCall::rect(Some(hover_color))],
2388            );
2389        });
2390    }
2391
2392    /// "ExpansionTile shows focus color with opaque backgroundColor".
2393    #[test]
2394    fn expansion_tile_shows_focus_color_with_opaque_background_color() {
2395        test_widgets(|tester| {
2396            let focus_color = Colors::PINK.primary();
2397            let background_color = Colors::AMBER.primary();
2398
2399            pump_app(
2400                tester,
2401                |app| ThemeData::builder().focus_color(focus_color).build(app),
2402                Material::new().child(
2403                    ExpansionTile::new(Text::new("Title"))
2404                        .collapsed_background_color(background_color),
2405                ),
2406            );
2407
2408            // Focus the tile.
2409            tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
2410            tester.pump_and_settle();
2411
2412            // Dart's `paints..rect(color: Colors.transparent)..rect(color: focusColor)`: a draw
2413            // with a transparent paint is not recorded at all, so the tile's transparent ink
2414            // decoration has no entry and the focus highlight is the first draw.
2415            assert_paints(
2416                &tile_material_painted(tester),
2417                &[PaintCall::rect(Some(focus_color))],
2418            );
2419        });
2420    }
2421
2422    fn some_shape(shape: impl ShapeBorder + 'static) -> Option<ShapeBorderRef> {
2423        Some(ShapeBorderRef::new(shape))
2424    }
2425
2426    /// "ExpansionTile Border".
2427    #[test]
2428    fn expansion_tile_border() {
2429        test_widgets(|tester| {
2430            let collapsed_shape = Border {
2431                top: BorderSide {
2432                    color: Colors::BLUE.primary(),
2433                    ..BorderSide::default()
2434                },
2435                bottom: BorderSide {
2436                    color: Colors::GREEN.primary(),
2437                    ..BorderSide::default()
2438                },
2439                ..Border::default()
2440            };
2441            let shape = Border::all(
2442                Colors::RED.primary(),
2443                1.0,
2444                BorderStyle::Solid,
2445                BorderSide::STROKE_ALIGN_INSIDE,
2446            );
2447
2448            pump_app(
2449                tester,
2450                m3,
2451                Material::new().child(
2452                    ExpansionTile::new(Text::new("ExpansionTile"))
2453                        .collapsed_shape(collapsed_shape)
2454                        .shape(shape)
2455                        .children([list_tile(None, "0")]),
2456                ),
2457            );
2458
2459            // When a custom shape is provided, ExpansionTile will use the
2460            // Material widget to draw the shape and background color
2461            // instead of a Container.
2462            let (material_shape, _, clip_behavior) = tile_material(tester);
2463            // ExpansionTile should be collapsed initially.
2464            assert_eq!(material_shape, some_shape(collapsed_shape));
2465            assert_eq!(clip_behavior, Clip::AntiAlias);
2466
2467            tester.tap(find::text("ExpansionTile"));
2468            tester.pump_and_settle();
2469
2470            // ExpansionTile should be Expanded now.
2471            let (material_shape, _, clip_behavior) = tile_material(tester);
2472            assert_eq!(material_shape, some_shape(shape));
2473            assert_eq!(clip_behavior, Clip::AntiAlias);
2474        });
2475    }
2476
2477    fn pump_affinity(tester: &mut WidgetTester, tile: ExpansionTile) {
2478        pump_app(tester, m3, Material::new().child(tile));
2479    }
2480
2481    /// "ExpansionTile platform controlAffinity test".
2482    #[test]
2483    fn expansion_tile_platform_control_affinity_test() {
2484        test_widgets(|tester| {
2485            pump_affinity(tester, ExpansionTile::new(Text::new("Title")));
2486
2487            the_list_tile(tester, |list_tile| {
2488                assert!(list_tile.leading.is_none());
2489                assert!(is_widget::<Animated<RotationTransition>>(
2490                    &list_tile.trailing
2491                ));
2492            });
2493        });
2494    }
2495
2496    /// "ExpansionTile trailing controlAffinity test".
2497    #[test]
2498    fn expansion_tile_trailing_control_affinity_test() {
2499        test_widgets(|tester| {
2500            pump_affinity(
2501                tester,
2502                ExpansionTile::new(Text::new("Title"))
2503                    .control_affinity(ListTileControlAffinity::Trailing),
2504            );
2505
2506            the_list_tile(tester, |list_tile| {
2507                assert!(list_tile.leading.is_none());
2508                assert!(is_widget::<Animated<RotationTransition>>(
2509                    &list_tile.trailing
2510                ));
2511            });
2512        });
2513    }
2514
2515    /// "ExpansionTile leading controlAffinity test".
2516    #[test]
2517    fn expansion_tile_leading_control_affinity_test() {
2518        test_widgets(|tester| {
2519            pump_affinity(
2520                tester,
2521                ExpansionTile::new(Text::new("Title"))
2522                    .control_affinity(ListTileControlAffinity::Leading),
2523            );
2524
2525            the_list_tile(tester, |list_tile| {
2526                assert!(is_widget::<Animated<RotationTransition>>(
2527                    &list_tile.leading
2528                ));
2529                assert!(list_tile.trailing.is_none());
2530            });
2531        });
2532    }
2533
2534    /// "ExpansionTile override rotating icon test".
2535    #[test]
2536    fn expansion_tile_override_rotating_icon_test() {
2537        test_widgets(|tester| {
2538            pump_affinity(
2539                tester,
2540                ExpansionTile::new(Text::new("Title"))
2541                    .leading(Icon::new(Some(Icons::info())))
2542                    .control_affinity(ListTileControlAffinity::Leading),
2543            );
2544
2545            the_list_tile(tester, |list_tile| {
2546                assert!(is_widget::<Icon>(&list_tile.leading));
2547                assert!(list_tile.trailing.is_none());
2548            });
2549        });
2550    }
2551
2552    /// The values a case's `StatefulBuilder` builds its tile with, and a button sets.
2553    struct TileValues {
2554        shape: ShapeBorderRef,
2555        text_color: Color,
2556        background_color: Color,
2557        icon_color: Color,
2558    }
2559
2560    fn rounded(radius: f64) -> RoundedRectangleBorder {
2561        RoundedRectangleBorder::new(
2562            BorderSide::NONE,
2563            BorderRadius::all(Radius::circular(radius)).into(),
2564        )
2565    }
2566
2567    /// The `StatefulBuilder` of the "properties can be updated with setState" cases: a
2568    /// `Column` of the tile `tile` builds from the values, and a button that sets `update`.
2569    fn updatable_tile(
2570        values: Rc<RefCell<TileValues>>,
2571        update: fn() -> TileValues,
2572        tile: fn(&TileValues, ExpansionTile) -> ExpansionTile,
2573        icon: &Probe,
2574        text: &Probe,
2575    ) -> WidgetRef {
2576        let icon = Rc::clone(icon);
2577        let text = Rc::clone(text);
2578        StatefulBuilder::new(move |_app, _context, set_state| {
2579            let on_pressed = {
2580                let values = Rc::clone(&values);
2581                Listener::new(move |app| {
2582                    set_state(app, &mut |_app| *values.borrow_mut() = update());
2583                })
2584            };
2585            Column::new()
2586                .children([
2587                    tile(
2588                        &values.borrow(),
2589                        ExpansionTile::new(test_text("title", &text))
2590                            .trailing(test_icon(&icon))
2591                            .children([sized(100.0, 100.0)]),
2592                    )
2593                    .into_widget(),
2594                    // This button is used to update the ExpansionTile properties.
2595                    FilledButton::new(
2596                        Some(on_pressed),
2597                        Some(Text::new("Update collapsed properties")),
2598                    )
2599                    .into_widget(),
2600                ])
2601                .into_widget()
2602        })
2603        .into_widget()
2604    }
2605
2606    /// "Collapsed ExpansionTile properties can be updated with setState".
2607    #[test]
2608    fn collapsed_expansion_tile_properties_can_be_updated_with_set_state() {
2609        test_widgets(|tester| {
2610            let icon = probe();
2611            let text = probe();
2612            let values = Rc::new(RefCell::new(TileValues {
2613                shape: ShapeBorderRef::new(rounded(4.0)),
2614                text_color: Color::new(0xffffffff),
2615                background_color: Color::new(0xffff0000),
2616                icon_color: Color::new(0xffffffff),
2617            }));
2618
2619            pump_app(
2620                tester,
2621                m3,
2622                Material::new().child(updatable_tile(
2623                    values,
2624                    || TileValues {
2625                        shape: ShapeBorderRef::new(rounded(16.0)),
2626                        text_color: Color::new(0xff000000),
2627                        background_color: Color::new(0xffffff00),
2628                        icon_color: Color::new(0xff000000),
2629                    },
2630                    |values, tile| {
2631                        tile.collapsed_shape(values.shape.clone())
2632                            .collapsed_text_color(values.text_color)
2633                            .collapsed_background_color(values.background_color)
2634                            .collapsed_icon_color(values.icon_color)
2635                    },
2636                    &icon,
2637                    &text,
2638                )),
2639            );
2640
2641            // When a custom shape is provided, ExpansionTile will use the
2642            // Material widget to draw the shape and background color
2643            // instead of a Container.
2644            let (shape, color, clip_behavior) = tile_material(tester);
2645
2646            // Test initial ExpansionTile properties.
2647            assert_eq!(shape, some_shape(rounded(4.0)));
2648            assert_eq!(color, Some(Color::new(0xffff0000)));
2649            assert_eq!(clip_behavior, Clip::AntiAlias);
2650            assert_eq!(icon.get(), Some(Color::new(0xffffffff)));
2651            assert_eq!(text.get(), Some(Color::new(0xffffffff)));
2652
2653            // Tap the button to update the ExpansionTile properties.
2654            tester.tap(find::text("Update collapsed properties"));
2655            tester.pump_and_settle();
2656
2657            let (shape, color, clip_behavior) = tile_material(tester);
2658
2659            // Test updated ExpansionTile properties.
2660            assert_eq!(shape, some_shape(rounded(16.0)));
2661            assert_eq!(color, Some(Color::new(0xffffff00)));
2662            assert_eq!(clip_behavior, Clip::AntiAlias);
2663            assert_eq!(icon.get(), Some(Color::new(0xff000000)));
2664            assert_eq!(text.get(), Some(Color::new(0xff000000)));
2665        });
2666    }
2667
2668    /// "Expanded ExpansionTile properties can be updated with setState".
2669    #[test]
2670    fn expanded_expansion_tile_properties_can_be_updated_with_set_state() {
2671        test_widgets(|tester| {
2672            let icon = probe();
2673            let text = probe();
2674            let values = Rc::new(RefCell::new(TileValues {
2675                shape: ShapeBorderRef::new(rounded(12.0)),
2676                text_color: Color::new(0xff00ffff),
2677                background_color: Color::new(0xff0000ff),
2678                icon_color: Color::new(0xff00ffff),
2679            }));
2680
2681            pump_app(
2682                tester,
2683                m3,
2684                Material::new().child(updatable_tile(
2685                    values,
2686                    || TileValues {
2687                        shape: ShapeBorderRef::new(rounded(6.0)),
2688                        text_color: Color::new(0xffffffff),
2689                        background_color: Color::new(0xff123456),
2690                        icon_color: Color::new(0xffffffff),
2691                    },
2692                    |values, tile| {
2693                        tile.shape(values.shape.clone())
2694                            .text_color(values.text_color)
2695                            .background_color(values.background_color)
2696                            .icon_color(values.icon_color)
2697                    },
2698                    &icon,
2699                    &text,
2700                )),
2701            );
2702
2703            // Tap to expand the ExpansionTile.
2704            tester.tap(find::text("title"));
2705            tester.pump_and_settle();
2706
2707            // When a custom shape is provided, ExpansionTile will use the
2708            // Material widget to draw the shape and background color
2709            // instead of a Container.
2710            let (shape, color, clip_behavior) = tile_material(tester);
2711
2712            // Test initial ExpansionTile properties.
2713            assert_eq!(shape, some_shape(rounded(12.0)));
2714            assert_eq!(color, Some(Color::new(0xff0000ff)));
2715            assert_eq!(clip_behavior, Clip::AntiAlias);
2716            assert_eq!(icon.get(), Some(Color::new(0xff00ffff)));
2717            assert_eq!(text.get(), Some(Color::new(0xff00ffff)));
2718
2719            // Tap the button to update the ExpansionTile properties.
2720            tester.tap(find::text("Update collapsed properties"));
2721            tester.pump_and_settle();
2722
2723            let (shape, color, clip_behavior) = tile_material(tester);
2724
2725            // Test updated ExpansionTile properties.
2726            assert_eq!(shape, some_shape(rounded(6.0)));
2727            assert_eq!(color, Some(Color::new(0xff123456)));
2728            assert_eq!(clip_behavior, Clip::AntiAlias);
2729            assert_eq!(icon.get(), Some(Color::new(0xffffffff)));
2730            assert_eq!(text.get(), Some(Color::new(0xffffffff)));
2731        });
2732    }
2733
2734    /// The steps the "Override ExpansionTile animation" cases share: `pump(style)` pumps the
2735    /// tile with the animation style, given where each case gives it.
2736    pub(crate) fn animation_style_case(
2737        tester: &mut WidgetTester,
2738        pump: impl Fn(&mut WidgetTester, &GlobalKey, Option<AnimationStyle>),
2739        reverse_curve: bool,
2740    ) {
2741        let expansion_tile_key = GlobalKey::new();
2742        let height = |tester: &WidgetTester| height(tester, &expansion_tile_key);
2743
2744        pump(tester, &expansion_tile_key, None);
2745
2746        // Test initial ExpansionTile height.
2747        assert_eq!(height(tester), 58.0);
2748
2749        // Test the default expansion animation.
2750        tester.tap(find::text("title"));
2751        tester.pump();
2752        // Advance the animation by 1/4 of its duration.
2753        tester.pump_by(Duration::from_millis(50));
2754
2755        assert_more_or_less_equals_within(height(tester), 67.4, 0.1);
2756
2757        // Advance the animation by 2/4 of its duration.
2758        tester.pump_by(Duration::from_millis(50));
2759
2760        assert_more_or_less_equals_within(height(tester), 89.6, 0.1);
2761
2762        // Advance the animation to the end.
2763        tester.pump_and_settle();
2764
2765        assert_eq!(height(tester), 158.0);
2766
2767        // Tap to collapse the ExpansionTile.
2768        tester.tap(find::text("title"));
2769        tester.pump_and_settle();
2770
2771        // Override the animation duration.
2772        pump(
2773            tester,
2774            &expansion_tile_key,
2775            Some(AnimationStyle::new(
2776                None,
2777                Some(Duration::from_millis(800)),
2778                None,
2779                None,
2780            )),
2781        );
2782        tester.pump_and_settle();
2783
2784        // Test the overridden animation duration.
2785        tester.tap(find::text("title"));
2786        tester.pump();
2787        // Advance the animation by 1/4 of its duration.
2788        tester.pump_by(Duration::from_millis(200));
2789
2790        assert_more_or_less_equals_within(height(tester), 67.4, 0.1);
2791
2792        // Advance the animation by 2/4 of its duration.
2793        tester.pump_by(Duration::from_millis(200));
2794
2795        assert_more_or_less_equals_within(height(tester), 89.6, 0.1);
2796
2797        // Advance the animation to the end.
2798        tester.pump_and_settle();
2799
2800        assert_eq!(height(tester), 158.0);
2801
2802        // Tap to collapse the ExpansionTile.
2803        tester.tap(find::text("title"));
2804        tester.pump_and_settle();
2805
2806        // Override the animation curve.
2807        pump(
2808            tester,
2809            &expansion_tile_key,
2810            Some(AnimationStyle::new(
2811                Some(Easing::emphasized_decelerate()),
2812                None,
2813                reverse_curve.then(Easing::emphasized_accelerate),
2814                None,
2815            )),
2816        );
2817        tester.pump_and_settle();
2818
2819        // Test the overridden animation curve.
2820        tester.tap(find::text("title"));
2821        tester.pump();
2822        // Advance the animation by 1/4 of its duration.
2823        tester.pump_by(Duration::from_millis(50));
2824
2825        assert_more_or_less_equals_within(height(tester), 141.2, 0.1);
2826
2827        // Advance the animation by 2/4 of its duration.
2828        tester.pump_by(Duration::from_millis(50));
2829
2830        assert_more_or_less_equals_within(height(tester), 153.0, 0.1);
2831
2832        // Advance the animation to the end.
2833        tester.pump_and_settle();
2834
2835        assert_eq!(height(tester), 158.0);
2836
2837        if reverse_curve {
2838            // Test the overridden reverse (collapse) animation curve.
2839            tester.tap(find::text("title"));
2840            tester.pump();
2841            // Advance the animation by 1/4 of its duration.
2842            tester.pump_by(Duration::from_millis(50));
2843
2844            assert_more_or_less_equals_within(height(tester), 98.6, 0.1);
2845
2846            // Advance the animation by 2/4 of its duration.
2847            tester.pump_by(Duration::from_millis(50));
2848
2849            assert_more_or_less_equals_within(height(tester), 73.4, 0.1);
2850
2851            // Advance the animation to the end.
2852            tester.pump_and_settle();
2853
2854            assert_eq!(height(tester), 58.0);
2855        } else {
2856            // Tap to collapse the ExpansionTile.
2857            tester.tap(find::text("title"));
2858        }
2859
2860        // Test no animation.
2861        pump(
2862            tester,
2863            &expansion_tile_key,
2864            Some(AnimationStyle::NO_ANIMATION),
2865        );
2866
2867        // Tap to expand the ExpansionTile.
2868        tester.tap(find::text("title"));
2869        tester.pump();
2870
2871        assert_eq!(height(tester), 158.0);
2872    }
2873
2874    /// "Override ExpansionTile animation using AnimationStyle".
2875    #[test]
2876    fn override_expansion_tile_animation_using_animation_style() {
2877        test_widgets(|tester| {
2878            animation_style_case(
2879                tester,
2880                |tester, key, animation_style| {
2881                    let mut tile = ExpansionTile::new(test_text("title", &probe()))
2882                        .key(key.clone().into())
2883                        .children([sized(100.0, 100.0)]);
2884                    tile.expansion_animation_style = animation_style;
2885                    pump_app(tester, m3, Material::new().child(Center::new().child(tile)));
2886                },
2887                true,
2888            );
2889        });
2890    }
2891
2892    /// "Default clipBehavior when a shape is provided".
2893    #[test]
2894    fn default_clip_behavior_when_a_shape_is_provided() {
2895        test_widgets(|tester| {
2896            pump_app(
2897                tester,
2898                m3,
2899                Scaffold::new().body(
2900                    ExpansionTile::new(Text::new("Title"))
2901                        .subtitle(Text::new("Subtitle"))
2902                        .shape(StadiumBorder::default())
2903                        .children([list_tile(None, "0")]),
2904                ),
2905            );
2906
2907            assert_eq!(tile_material(tester).2, Clip::AntiAlias);
2908        });
2909    }
2910
2911    /// "Can override clipBehavior when a shape is provided".
2912    #[test]
2913    fn can_override_clip_behavior_when_a_shape_is_provided() {
2914        test_widgets(|tester| {
2915            pump_app(
2916                tester,
2917                m3,
2918                Scaffold::new().body(
2919                    ExpansionTile::new(Text::new("Title"))
2920                        .subtitle(Text::new("Subtitle"))
2921                        .shape(StadiumBorder::default())
2922                        .clip_behavior(Clip::None)
2923                        .children([list_tile(None, "0")]),
2924                ),
2925            );
2926
2927            assert_eq!(tile_material(tester).2, Clip::None);
2928        });
2929    }
2930
2931    /// Material 2: "ExpansionTile default iconColor, textColor".
2932    #[test]
2933    fn material2_expansion_tile_default_icon_color_text_color() {
2934        test_widgets(|tester| {
2935            let icon_color = probe();
2936            let text_color = probe();
2937
2938            pump_app(
2939                tester,
2940                m2,
2941                Material::new().child(
2942                    ExpansionTile::new(test_text("title", &text_color))
2943                        .trailing(test_icon(&icon_color))
2944                        .children([sized(100.0, 100.0)]),
2945                ),
2946            );
2947
2948            let theme = m2(&tester.cell.borrow());
2949            assert_eq!(icon_color.get(), Some(theme.unselected_widget_color));
2950            assert_eq!(
2951                text_color.get(),
2952                theme
2953                    .text_theme
2954                    .title_medium
2955                    .as_ref()
2956                    .and_then(|style| style.color.as_deref().copied())
2957            );
2958
2959            tester.tap(find::text("title"));
2960            tester.pump_and_settle();
2961
2962            assert_eq!(icon_color.get(), Some(theme.color_scheme.primary()));
2963            assert_eq!(text_color.get(), Some(theme.color_scheme.primary()));
2964        });
2965    }
2966
2967    /// Material 2: "Material2 - ExpansionTile draws inkwell splash on top of background color".
2968    #[test]
2969    fn material2_expansion_tile_draws_inkwell_splash_on_top_of_background_color() {
2970        test_widgets(|tester| {
2971            let expansion_tile_key = GlobalKey::new();
2972            let collapsed_background_color = Color::new(0xff00ff00);
2973            let background_color = Color::new(0xffff0000);
2974
2975            pump_app(
2976                tester,
2977                m2,
2978                Material::new().child(
2979                    Center::new().child(
2980                        Padding::new(EdgeInsets::symmetric(0.0, 24.0)).child(
2981                            ExpansionTile::new(test_text("title", &probe()))
2982                                .key(expansion_tile_key.clone().into())
2983                                .shape(rounded(16.0))
2984                                .collapsed_background_color(collapsed_background_color)
2985                                .background_color(background_color)
2986                                .collapsed_shape(rounded(16.0))
2987                                .trailing(test_icon(&probe()))
2988                                .children([sized(100.0, 100.0)]),
2989                        ),
2990                    ),
2991                ),
2992            );
2993
2994            // Tap and hold the ExpansionTile to trigger ink splash.
2995            let center = key_rect(tester, &expansion_tile_key).center();
2996            let mut gesture = TestPointer::touch(1);
2997            tester.down(&mut gesture, center);
2998            // Start the splash animation.
2999            tester.pump();
3000            // Splash is underway.
3001            tester.pump_by(Duration::from_millis(100));
3002
3003            let ink_features = tester.first::<RenderInkFeatures>();
3004            let splash_color = m2(&tester.cell.borrow()).splash_color;
3005            // Check if the ink splash is drawn on top of the background color.
3006            assert_paints(
3007                &tester.painted_ops(ink_features.as_object()),
3008                &[
3009                    PaintCall::rrect(Some(collapsed_background_color)),
3010                    PaintCall::circle(Some(splash_color)),
3011                ],
3012            );
3013
3014            // Finish gesture to release resources.
3015            tester.up(&gesture);
3016            tester.pump_and_settle();
3017        });
3018    }
3019
3020    /// "ExpansionTileController isExpanded, expand() and collapse()".
3021    #[test]
3022    fn expansion_tile_controller_is_expanded_expand_and_collapse() {
3023        test_widgets(|tester| {
3024            let controller = ExpansibleController::new(&mut tester.cell.borrow_mut());
3025
3026            pump_app(
3027                tester,
3028                m3,
3029                Material::new().child(
3030                    ExpansionTile::new(Text::new("Title"))
3031                        .controller(controller.clone())
3032                        .children([Text::new("Child 0").into_widget()]),
3033                ),
3034            );
3035
3036            let is_expanded = |tester: &WidgetTester| controller.is_expanded(&tester.cell.borrow());
3037            expect(tester, &find::text("Child 0"), finds_nothing());
3038            assert!(!is_expanded(tester));
3039            controller.expand(&mut tester.cell.borrow_mut());
3040            assert!(is_expanded(tester));
3041            tester.pump_and_settle();
3042            expect(tester, &find::text("Child 0"), finds_one_widget());
3043            assert!(is_expanded(tester));
3044            controller.collapse(&mut tester.cell.borrow_mut());
3045            assert!(!is_expanded(tester));
3046            tester.pump_and_settle();
3047            expect(tester, &find::text("Child 0"), finds_nothing());
3048
3049            controller.dispose(&mut tester.cell.borrow_mut());
3050        });
3051    }
3052
3053    /// "Calling ExpansionTileController.expand/collapsed has no effect if it is already
3054    /// expanded/collapsed".
3055    #[test]
3056    fn calling_expansion_tile_controller_expand_collapsed_has_no_effect_if_it_is_already_expanded_collapsed()
3057     {
3058        test_widgets(|tester| {
3059            let controller = ExpansibleController::new(&mut tester.cell.borrow_mut());
3060
3061            pump_app(
3062                tester,
3063                m3,
3064                Material::new().child(
3065                    ExpansionTile::new(Text::new("Title"))
3066                        .controller(controller.clone())
3067                        .initially_expanded(true)
3068                        .children([Text::new("Child 0").into_widget()]),
3069                ),
3070            );
3071
3072            let is_expanded = |tester: &WidgetTester| controller.is_expanded(&tester.cell.borrow());
3073            expect(tester, &find::text("Child 0"), finds_one_widget());
3074            assert!(is_expanded(tester));
3075            controller.expand(&mut tester.cell.borrow_mut());
3076            assert!(is_expanded(tester));
3077            tester.pump();
3078            assert!(!tester.has_running_animations());
3079            expect(tester, &find::text("Child 0"), finds_one_widget());
3080            controller.collapse(&mut tester.cell.borrow_mut());
3081            assert!(!is_expanded(tester));
3082            tester.pump();
3083            assert!(tester.has_running_animations());
3084            tester.pump_and_settle();
3085            assert!(!is_expanded(tester));
3086            expect(tester, &find::text("Child 0"), finds_nothing());
3087            controller.collapse(&mut tester.cell.borrow_mut());
3088            assert!(!is_expanded(tester));
3089            tester.pump();
3090            assert!(!tester.has_running_animations());
3091
3092            controller.dispose(&mut tester.cell.borrow_mut());
3093        });
3094    }
3095
3096    /// "Call to ExpansionTileController.of()".
3097    #[test]
3098    fn call_to_expansion_tile_controller_of() {
3099        test_widgets(|tester| {
3100            let title_key = GlobalKey::new();
3101            let child_key = GlobalKey::new();
3102            pump_app(
3103                tester,
3104                m3,
3105                Material::new().child(
3106                    ExpansionTile::new(Text::new("Title").key(title_key.clone().into()))
3107                        .initially_expanded(true)
3108                        .children([Text::new("Child 0")
3109                            .key(child_key.clone().into())
3110                            .into_widget()]),
3111                ),
3112            );
3113
3114            let child = element_of(tester, &child_key);
3115            let title = element_of(tester, &title_key);
3116            let app = tester.cell.borrow();
3117            let controller1 = ExpansibleController::of(&app, child);
3118            assert!(controller1.is_expanded(&app));
3119
3120            let controller2 = ExpansibleController::of(&app, title);
3121            assert!(controller2.is_expanded(&app));
3122
3123            assert_eq!(controller1, controller2);
3124        });
3125    }
3126
3127    /// "Call to ExpansionTile.maybeOf()".
3128    #[test]
3129    fn call_to_expansion_tile_maybe_of() {
3130        test_widgets(|tester| {
3131            let title_key = GlobalKey::new();
3132            let non_descendant_key = GlobalKey::new();
3133            pump_app(
3134                tester,
3135                m3,
3136                Material::new().child(
3137                    Column::new().children([
3138                        ExpansionTile::new(Text::new("Title").key(title_key.clone().into()))
3139                            .children([Text::new("Child 0").into_widget()])
3140                            .into_widget(),
3141                        Text::new("Non descendant")
3142                            .key(non_descendant_key.clone().into())
3143                            .into_widget(),
3144                    ]),
3145                ),
3146            );
3147
3148            let title = element_of(tester, &title_key);
3149            let non_descendant = element_of(tester, &non_descendant_key);
3150            let app = tester.cell.borrow();
3151            let controller1 = ExpansibleController::maybe_of(&app, title);
3152            assert!(controller1.is_some());
3153            assert_eq!(
3154                controller1.map(|controller| controller.is_expanded(&app)),
3155                Some(false)
3156            );
3157
3158            let controller2 = ExpansibleController::maybe_of(&app, non_descendant);
3159            assert!(controller2.is_none());
3160        });
3161    }
3162
3163    /// "Check if dense, splashColor, enableFeedback, visualDensity parameter is working".
3164    #[test]
3165    fn check_if_dense_splash_color_enable_feedback_visual_density_parameter_is_working() {
3166        test_widgets(|tester| {
3167            let dense = true;
3168            let splash_color = Colors::BLUE.primary();
3169            let enable_feedback = false;
3170            let visual_density = VisualDensity::COMPACT;
3171
3172            pump_app(
3173                tester,
3174                m3,
3175                Material::new().child(
3176                    Column::new().children([
3177                        ExpansionTile::new(Text::new("Title"))
3178                            .dense(dense)
3179                            .splash_color(splash_color)
3180                            .enable_feedback(enable_feedback)
3181                            .visual_density(visual_density)
3182                            .children([Text::new("Child 0").into_widget()])
3183                            .into_widget(),
3184                        Text::new("Non descendant").into_widget(),
3185                    ]),
3186                ),
3187            );
3188
3189            the_list_tile(tester, |tile| {
3190                assert_eq!(tile.dense, Some(dense));
3191                assert_eq!(tile.splash_color, Some(splash_color));
3192                assert_eq!(tile.enable_feedback, Some(enable_feedback));
3193                assert_eq!(tile.visual_density, Some(visual_density));
3194            });
3195        });
3196    }
3197
3198    /// Dart's `tester.tap(find.widgetWithText(ExpansionTile, text))`.
3199    fn tap_tile(tester: &mut WidgetTester) {
3200        let tile = tester.element(find::by_type::<ExpansionTile>().at(0));
3201        let center = tester.get_rect(tile).center();
3202        tester.tap_at(center, 1);
3203    }
3204
3205    /// "ExpansionTileController should not toggle if disabled".
3206    #[test]
3207    fn expansion_tile_controller_should_not_toggle_if_disabled() {
3208        test_widgets(|tester| {
3209            let controller = ExpansibleController::new(&mut tester.cell.borrow_mut());
3210
3211            pump_app(
3212                tester,
3213                m3,
3214                Material::new().child(
3215                    ExpansionTile::new(Text::new("Title"))
3216                        .enabled(false)
3217                        .controller(controller.clone())
3218                        .children([Text::new("Child 0").into_widget()]),
3219                ),
3220            );
3221
3222            let is_expanded = |tester: &WidgetTester| controller.is_expanded(&tester.cell.borrow());
3223            expect(tester, &find::text("Child 0"), finds_nothing());
3224            assert!(!is_expanded(tester));
3225            tap_tile(tester);
3226            tester.pump_and_settle();
3227            expect(tester, &find::text("Child 0"), finds_nothing());
3228            assert!(!is_expanded(tester));
3229            controller.expand(&mut tester.cell.borrow_mut());
3230            tester.pump_and_settle();
3231            expect(tester, &find::text("Child 0"), finds_one_widget());
3232            assert!(is_expanded(tester));
3233            tap_tile(tester);
3234            tester.pump_and_settle();
3235            expect(tester, &find::text("Child 0"), finds_one_widget());
3236            assert!(is_expanded(tester));
3237
3238            controller.dispose(&mut tester.cell.borrow_mut());
3239        });
3240    }
3241
3242    /// Dart's `tester.getSize(find.descendant(of: find.byType(ExpansionTile), matching:
3243    /// find.byType(ColoredBox))).width`.
3244    fn title_width(tester: &WidgetTester) -> f64 {
3245        let colored_box = find::descendant(
3246            find::by_type::<ExpansionTile>().first(),
3247            find::by_type::<ColoredBox>(),
3248        );
3249        tester.get_rect(colored_box).width()
3250    }
3251
3252    /// "ExpansionTile does not include the default trailing icon when showTrailingIcon: false
3253    /// (#145268)".
3254    #[test]
3255    fn expansion_tile_does_not_include_the_default_trailing_icon_when_show_trailing_icon_false() {
3256        test_widgets(|tester| {
3257            pump_app(
3258                tester,
3259                m3,
3260                Material::new().child(
3261                    ExpansionTile::new(
3262                        ColoredBox::new(Colors::RED.primary()).child(Text::new("Title")),
3263                    )
3264                    .enabled(false)
3265                    .tile_padding(EdgeInsetsGeometry::ZERO)
3266                    .show_trailing_icon(false),
3267                ),
3268            );
3269
3270            assert_eq!(title_width(tester), WidgetTester::SIZE.width());
3271        });
3272    }
3273
3274    /// "ExpansionTile with smaller trailing widget allocates at least 32.0 units of space
3275    /// (preserves original behavior) (#145268)".
3276    #[test]
3277    fn expansion_tile_with_smaller_trailing_widget_allocates_at_least_32_units_of_space() {
3278        test_widgets(|tester| {
3279            pump_app(
3280                tester,
3281                m3,
3282                Material::new().child(
3283                    ExpansionTile::new(
3284                        ColoredBox::new(Colors::RED.primary()).child(Text::new("Title")),
3285                    )
3286                    .enabled(false)
3287                    .tile_padding(EdgeInsetsGeometry::ZERO)
3288                    .trailing(SizedBox::shrink()),
3289                ),
3290            );
3291
3292            assert_eq!(title_width(tester), WidgetTester::SIZE.width() - 32.0);
3293        });
3294    }
3295
3296    /// "ExpansionTile uses ListTileTheme controlAffinity".
3297    #[test]
3298    fn expansion_tile_uses_list_tile_theme_control_affinity() {
3299        test_widgets(|tester| {
3300            let build_view = |tester: &mut WidgetTester, control_affinity| {
3301                pump_app(
3302                    tester,
3303                    m3,
3304                    ListTileTheme::new(
3305                        Material::new().child(ExpansionTile::new(Text::new("ExpansionTile"))),
3306                    )
3307                    .data(ListTileThemeData::new().control_affinity(control_affinity)),
3308                );
3309            };
3310            let top_left = |tester: &WidgetTester| {
3311                let found = find::text("ExpansionTile").evaluate(tester);
3312                assert_eq!(found.len(), 1, "one ExpansionTile title");
3313                tester.get_rect(found[0]).top_left()
3314            };
3315
3316            build_view(tester, ListTileControlAffinity::Leading);
3317            assert_eq!(top_left(tester), Offset::new(56.0, 17.0));
3318
3319            build_view(tester, ListTileControlAffinity::Trailing);
3320            assert_eq!(top_left(tester), Offset::new(16.0, 17.0));
3321
3322            build_view(tester, ListTileControlAffinity::Platform);
3323            assert_eq!(top_left(tester), Offset::new(16.0, 17.0));
3324        });
3325    }
3326
3327    /// "ExpansionTile can accept a new controller".
3328    #[test]
3329    fn expansion_tile_can_accept_a_new_controller() {
3330        test_widgets(|tester| {
3331            let controller1 = ExpansibleController::new(&mut tester.cell.borrow_mut());
3332            let controller2 = ExpansibleController::new(&mut tester.cell.borrow_mut());
3333            let tile = |controller| {
3334                Material::new().child(
3335                    ExpansionTile::new(Text::new("Title"))
3336                        .controller(controller)
3337                        .initially_expanded(true)
3338                        .children([Text::new("Child 0").into_widget()]),
3339                )
3340            };
3341
3342            pump_app(tester, m3, tile(controller1.clone()));
3343
3344            expect(tester, &find::text("Child 0"), finds_one_widget());
3345            assert!(controller1.is_expanded(&tester.cell.borrow()));
3346            controller1.collapse(&mut tester.cell.borrow_mut());
3347            assert!(!controller1.is_expanded(&tester.cell.borrow()));
3348            tester.pump_and_settle();
3349            expect(tester, &find::text("Child 0"), finds_nothing());
3350
3351            pump_app(tester, m3, tile(controller2.clone()));
3352
3353            expect(tester, &find::text("Child 0"), finds_nothing());
3354            controller2.expand(&mut tester.cell.borrow_mut());
3355            assert!(controller2.is_expanded(&tester.cell.borrow()));
3356            tester.pump_and_settle();
3357            expect(tester, &find::text("Child 0"), finds_one_widget());
3358
3359            controller1.dispose(&mut tester.cell.borrow_mut());
3360            controller2.dispose(&mut tester.cell.borrow_mut());
3361        });
3362    }
3363
3364    /// "ExpansionTile can accept a new controller with a different state".
3365    #[test]
3366    fn expansion_tile_can_accept_a_new_controller_with_a_different_state() {
3367        test_widgets(|tester| {
3368            let controller1 = ExpansibleController::new(&mut tester.cell.borrow_mut());
3369            let controller2 = ExpansibleController::new(&mut tester.cell.borrow_mut());
3370            let tile = |controller| {
3371                Material::new().child(
3372                    ExpansionTile::new(Text::new("Title"))
3373                        .controller(controller)
3374                        .children([Text::new("Child 0").into_widget()]),
3375                )
3376            };
3377
3378            pump_app(tester, m3, tile(controller1.clone()));
3379
3380            expect(tester, &find::text("Child 0"), finds_nothing());
3381            assert!(!controller1.is_expanded(&tester.cell.borrow()));
3382            controller1.expand(&mut tester.cell.borrow_mut());
3383            assert!(controller1.is_expanded(&tester.cell.borrow()));
3384            tester.pump_and_settle();
3385            expect(tester, &find::text("Child 0"), finds_one_widget());
3386
3387            pump_app(tester, m3, tile(controller2.clone()));
3388
3389            tester.pump_and_settle();
3390
3391            assert!(
3392                find::text("Child 0").evaluate(tester).is_empty(),
3393                "The widget should update to the state of the new controller"
3394            );
3395            controller2.expand(&mut tester.cell.borrow_mut());
3396            assert!(controller2.is_expanded(&tester.cell.borrow()));
3397            tester.pump_and_settle();
3398            expect(tester, &find::text("Child 0"), finds_one_widget());
3399
3400            controller1.dispose(&mut tester.cell.borrow_mut());
3401            controller2.dispose(&mut tester.cell.borrow_mut());
3402        });
3403    }
3404
3405    /// "ExpansionTile forwards statesController to ListTile".
3406    #[test]
3407    fn expansion_tile_forwards_states_controller_to_list_tile() {
3408        test_widgets(|tester| {
3409            let controller = WidgetStatesController::new(&mut tester.cell.borrow_mut(), None);
3410
3411            pump_app(
3412                tester,
3413                m3,
3414                Material::new().child(
3415                    ExpansionTile::new(Text::new("Tile")).states_controller(controller.clone()),
3416                ),
3417            );
3418
3419            the_list_tile(tester, |list_tile| {
3420                assert_eq!(list_tile.states_controller, Some(controller));
3421            });
3422        });
3423    }
3424
3425    /// "ExpansionTile forwards null statesController to ListTile".
3426    #[test]
3427    fn expansion_tile_forwards_null_states_controller_to_list_tile() {
3428        test_widgets(|tester| {
3429            pump_app(
3430                tester,
3431                m3,
3432                Material::new().child(ExpansionTile::new(Text::new("Tile"))),
3433            );
3434
3435            the_list_tile(tester, |list_tile| {
3436                assert_eq!(list_tile.states_controller, None);
3437            });
3438        });
3439    }
3440
3441    /// The `onExpansionChanged` the docs describe: called with true when the tile starts
3442    /// expanding and false when it starts collapsing.
3443    #[test]
3444    fn on_expansion_changed_is_called_when_the_tile_starts_expanding_and_collapsing() {
3445        test_widgets(|tester| {
3446            let changes = Rc::new(RefCell::new(Vec::new()));
3447            let on_expansion_changed: ValueChanged<bool> = {
3448                let changes = Rc::clone(&changes);
3449                Rc::new(move |_app, is_expanded| changes.borrow_mut().push(is_expanded))
3450            };
3451
3452            pump_app(
3453                tester,
3454                m3,
3455                Material::new().child(
3456                    ExpansionTile::new(Text::new("Title"))
3457                        .on_expansion_changed(on_expansion_changed)
3458                        .children([Text::new("Child 0").into_widget()]),
3459                ),
3460            );
3461
3462            tester.tap(find::text("Title"));
3463            assert_eq!(*changes.borrow(), [true]);
3464            tester.pump_and_settle();
3465            tester.tap(find::text("Title"));
3466            assert_eq!(*changes.borrow(), [true, false]);
3467            tester.pump_and_settle();
3468        });
3469    }
3470
3471    /// "ExpansionTile supports being embedded in a WidgetSpan".
3472    #[test]
3473    fn expansion_tile_supports_being_embedded_in_a_widget_span() {
3474        test_widgets(|tester| {
3475            use waft_painting::TextSpan;
3476            use waft_widgets::WidgetSpan;
3477
3478            let tile = ExpansionTile::new(Text::new("Header"))
3479                .children([Text::new("Details").into_widget()]);
3480            pump_app(
3481                tester,
3482                m3,
3483                Scaffold::new().body(Text::rich(
3484                    TextSpan::new()
3485                        .children(vec![WidgetSpan::new(tile).into_span()])
3486                        .into_span(),
3487                )),
3488            );
3489            expect(tester, &find::text("Header"), finds_one_widget());
3490        });
3491    }
3492
3493    /// Not a Dart case: a tile that made its own controller and is then given one disposes its
3494    /// own while the `Expansible` below still compares it with the new one, as Dart's does.
3495    #[test]
3496    fn a_tile_without_a_controller_that_is_given_one_follows_it() {
3497        test_widgets(|tester| {
3498            let controller = ExpansibleController::new(&mut tester.cell.borrow_mut());
3499            let tile = || {
3500                ExpansionTile::new(Text::new("Title"))
3501                    .children([Text::new("Child 0").into_widget()])
3502            };
3503
3504            pump_app(tester, m3, Material::new().child(tile()));
3505            expect(tester, &find::text("Child 0"), finds_nothing());
3506
3507            pump_app(
3508                tester,
3509                m3,
3510                Material::new().child(tile().controller(controller.clone())),
3511            );
3512            expect(tester, &find::text("Child 0"), finds_nothing());
3513
3514            controller.toggle(&mut tester.cell.borrow_mut());
3515            tester.pump_and_settle();
3516            assert!(controller.is_expanded(&tester.cell.borrow()));
3517            expect(tester, &find::text("Child 0"), finds_one_widget());
3518
3519            controller.toggle(&mut tester.cell.borrow_mut());
3520            tester.pump_and_settle();
3521            expect(tester, &find::text("Child 0"), finds_nothing());
3522
3523            pump_app(tester, m3, SizedBox::new());
3524            controller.dispose(&mut tester.cell.borrow_mut());
3525        });
3526    }
3527
3528    /// The animations a tile drove for its header and its decoration.
3529    fn driven_animations(tester: &WidgetTester) -> [HandleId; 5] {
3530        let tile = tester.element(find::by_type::<ExpansionTile>().at(0));
3531        let app = tester.cell.borrow();
3532        let state = app.get(
3533            tile.state_handle::<ExpansionTileState>(&app)
3534                .expect("an ExpansionTile's element holds its state"),
3535        );
3536        [
3537            state.header_color.clone().expect("built").id(),
3538            state.icon_color.clone().expect("built").id(),
3539            state.background_color.clone().expect("built").id(),
3540            state.border.clone().expect("built").id(),
3541            state.icon_turns.clone().expect("built").id(),
3542        ]
3543    }
3544
3545    /// Not a Dart case: what Dart's collector does with the animations each frame's header,
3546    /// icon and decoration drive. Each is freed at the checkpoint after the tile drives the
3547    /// next one, and the last ones after the tile goes.
3548    #[test]
3549    fn a_tile_keeps_only_the_animations_of_its_latest_frame() {
3550        test_widgets(|tester| {
3551            pump_app(
3552                tester,
3553                m3,
3554                Material::new().child(
3555                    ExpansionTile::new(Text::new("Title"))
3556                        .children([Text::new("Child 0").into_widget()]),
3557                ),
3558            );
3559            let first = driven_animations(tester);
3560
3561            tester.tap(find::text("Title"));
3562            tester.pump_by(Duration::from_millis(50));
3563            let mid_expansion = driven_animations(tester);
3564            {
3565                let app = tester.cell.borrow();
3566                assert!(first.iter().all(|&animation| !app.contains(animation)));
3567                assert!(
3568                    mid_expansion
3569                        .iter()
3570                        .all(|&animation| app.contains(animation))
3571                );
3572            }
3573
3574            tester.pump_and_settle();
3575            let last = driven_animations(tester);
3576            pump_app(tester, m3, SizedBox::new());
3577            let app = tester.cell.borrow();
3578            assert!(
3579                mid_expansion
3580                    .iter()
3581                    .chain(&last)
3582                    .all(|&animation| !app.contains(animation))
3583            );
3584        });
3585    }
3586}