Skip to main content

waft_widgets/widgets/
expansible.rs

1//! Flutter counterpart: `widgets/expansible.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_animation::{
8    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStyle, Curve,
9    CurvedAnimation, Curves, Tween,
10};
11use waft_foundation::{
12    App, ChangeNotifier, ChangeNotifierData, Handle, ListenableObject, Listener, OptionRetained,
13};
14use waft_rendering::MainAxisSize;
15use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
16
17use crate::framework::{
18    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
19};
20use crate::widgets::basic::{Align, ClipRect, Column, Offstage};
21use crate::widgets::page_storage::PageStorage;
22use crate::widgets::ticker_provider::{
23    SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData, TickerMode,
24};
25use crate::widgets::transitions::AnimatedBuilder;
26use waft_animation::Drive;
27use waft_foundation::Ref;
28
29/// The type of the callback that returns the header or body of an [`Expansible`].
30///
31/// The `animation` argument exposes the underlying expanding or collapsing
32/// animation, which has a value of 0 when the [`Expansible`] is completely
33/// collapsed and 1 when it is completely expanded. This can be used to drive
34/// animations that sync up with the expanding or collapsing animation, such as
35/// rotating an icon.
36///
37/// See also:
38///
39///   * [`Expansible::header_builder`], which is of this type.
40///   * [`Expansible::body_builder`], which is also of this type.
41pub type ExpansibleComponentBuilder =
42    Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef>;
43
44/// The type of the callback that uses the header and body of an [`Expansible`]
45/// widget to build the widget.
46///
47/// The `header` argument is the header returned by [`Expansible::header_builder`].
48/// The `body` argument is the body returned by [`Expansible::body_builder`] wrapped
49/// in an [`Offstage`] to hide the body when the [`Expansible`] is collapsed.
50///
51/// The `animation` argument exposes the underlying expanding or collapsing
52/// animation, which has a value of 0 when the [`Expansible`] is completely
53/// collapsed and 1 when it is completely expanded. This can be used to drive
54/// animations that sync up with the expanding or collapsing animation, such as
55/// rotating an icon.
56///
57/// See also:
58///
59///   * [`Expansible::expansible_builder`], which is of this type.
60pub type ExpansibleBuilder =
61    Rc<dyn Fn(&mut App, BuildContext, &WidgetRef, &WidgetRef, AnimationRef<f64>) -> WidgetRef>;
62
63/// A controller for managing the expansion state of an [`Expansible`].
64///
65/// This is a [`ChangeNotifier`] that notifies its listeners if the value of
66/// [`is_expanded`](Self::is_expanded) changes.
67///
68/// This controller provides methods to programmatically expand or collapse the
69/// widget, and it allows external components to query the current expansion
70/// state.
71///
72/// The controller's [`expand`](Self::expand) and [`collapse`](Self::collapse) methods cause
73/// the [`Expansible`] to rebuild, so they may not be called from a build method.
74///
75/// Remember to [`dispose`](Self::dispose) of the [`ExpansibleController`] when it is no
76/// longer needed. This will ensure all resources used by the object are discarded.
77#[derive(Debug, Default)]
78pub struct ExpansibleController {
79    change_notifier: ChangeNotifierData,
80    is_expanded: bool,
81}
82
83impl ExpansibleController {
84    /// Creates a controller to be used with [`Expansible::controller`].
85    pub fn new(app: &mut App) -> Ref<ExpansibleController> {
86        app.create(ExpansibleController::default())
87    }
88
89    fn set_expansion_state(self: Handle<Self>, app: &mut App, new_value: bool) {
90        if new_value != app.get(self).is_expanded {
91            app.get_mut(self).is_expanded = new_value;
92            self.notify_listeners(app);
93        }
94    }
95
96    /// Whether the expansible widget built with this controller is in expanded
97    /// state.
98    ///
99    /// This property doesn't take the animation into account. It reports `true`
100    /// even if the expansion animation is not completed.
101    ///
102    /// To be notified when this property changes, add a listener to the
103    /// controller.
104    ///
105    /// See also:
106    ///
107    ///  * [`expand`](Self::expand), which expands the expansible widget.
108    ///  * [`collapse`](Self::collapse), which collapses the expansible widget.
109    pub fn is_expanded(self: Handle<Self>, app: &App) -> bool {
110        app.get(self).is_expanded
111    }
112
113    /// Expands the [`Expansible`] that was built with this controller.
114    ///
115    /// If the widget is already in the expanded state (see
116    /// [`is_expanded`](Self::is_expanded)), calling this method has no effect.
117    ///
118    /// Calling this method may cause the [`Expansible`] to rebuild, so it may
119    /// not be called from a build method.
120    ///
121    /// Calling this method will notify registered listeners of this controller
122    /// that the expansion state has changed.
123    ///
124    /// See also:
125    ///
126    ///  * [`collapse`](Self::collapse), which collapses the expansible widget.
127    ///  * [`is_expanded`](Self::is_expanded) to check whether the expansible widget is
128    ///    expanded.
129    pub fn expand(self: Handle<Self>, app: &mut App) {
130        self.set_expansion_state(app, true);
131    }
132
133    /// Collapses the [`Expansible`] that was built with this controller.
134    ///
135    /// If the widget is already in the collapsed state (see
136    /// [`is_expanded`](Self::is_expanded)), calling this method has no effect.
137    ///
138    /// Calling this method may cause the [`Expansible`] to rebuild, so it may not
139    /// be called from a build method.
140    ///
141    /// Calling this method will notify registered listeners of this controller
142    /// that the expansion state has changed.
143    ///
144    /// See also:
145    ///
146    ///  * [`expand`](Self::expand), which expands the [`Expansible`].
147    ///  * [`is_expanded`](Self::is_expanded) to check whether the [`Expansible`] is expanded.
148    pub fn collapse(self: Handle<Self>, app: &mut App) {
149        self.set_expansion_state(app, false);
150    }
151
152    /// Convenience method for toggling the current [`is_expanded`](Self::is_expanded) status.
153    ///
154    /// Calling this method may cause the [`Expansible`] to rebuild, so it may not
155    /// be called from a build method.
156    ///
157    /// Calling this method will notify registered listeners of this controller
158    /// that the expansion state has changed.
159    ///
160    /// See also:
161    ///
162    ///  * [`expand`](Self::expand), which expands the [`Expansible`].
163    ///  * [`collapse`](Self::collapse), which collapses the [`Expansible`].
164    ///  * [`is_expanded`](Self::is_expanded) to check whether the [`Expansible`] is expanded.
165    pub fn toggle(self: Handle<Self>, app: &mut App) {
166        if self.is_expanded(app) {
167            self.collapse(app);
168        } else {
169            self.expand(app);
170        }
171    }
172
173    /// Discards any resources used by the object.
174    pub fn dispose(self: Handle<Self>, app: &mut App) {
175        ChangeNotifierData::dispose(app, self);
176    }
177
178    /// Finds the [`ExpansibleController`] for the closest [`Expansible`] instance
179    /// that encloses the given context.
180    ///
181    /// If no [`Expansible`] encloses the given context, calling this method panics.
182    ///
183    /// To return `None` if there is no [`Expansible`] use [`maybe_of`](Self::maybe_of)
184    /// instead.
185    ///
186    /// Typical usage of the [`of`](Self::of) function is to call it from
187    /// within the `build` method of a descendant of an [`Expansible`].
188    pub fn of(app: &App, context: BuildContext) -> Handle<ExpansibleController> {
189        ExpansibleController::maybe_of(app, context).expect(
190            "ExpansibleController::of() called with a context that does not contain an \
191             Expansible. No Expansible ancestor could be found starting from the context that \
192             was passed to ExpansibleController::of(). This usually happens when the context \
193             provided is from the same StatefulWidget as that whose build function actually \
194             creates the Expansible widget being sought.",
195        )
196    }
197
198    /// Finds the [`Expansible`] from the closest instance of this class that
199    /// encloses the given context and returns its [`ExpansibleController`].
200    ///
201    /// If no [`Expansible`] encloses the given context then returns `None`.
202    /// To panic instead, use [`of`](Self::of).
203    ///
204    /// See also:
205    ///
206    ///  * [`of`](Self::of), a similar function to this one that panics if no [`Expansible`]
207    ///    encloses the given context.
208    pub fn maybe_of(app: &App, context: BuildContext) -> Option<Handle<ExpansibleController>> {
209        context
210            .find_ancestor_state_of_type::<ExpansibleState>(app)
211            .map(|state| state.widget(app).controller.handle())
212    }
213}
214
215impl ChangeNotifier for ExpansibleController {
216    fn change_notifier_data(&self) -> &ChangeNotifierData {
217        &self.change_notifier
218    }
219
220    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
221        &mut self.change_notifier
222    }
223}
224
225/// A [`StatefulWidget`] that expands and collapses.
226///
227/// An [`Expansible`] consists of a header, which is always shown, and a
228/// body, which is hidden in its collapsed state and shown in its expanded
229/// state.
230///
231/// The [`Expansible`] is expanded or collapsed with an animation driven by an
232/// [`AnimationController`]. When the widget is expanded, the height of its body
233/// animates from 0 to its fully expanded height.
234///
235/// This widget is typically used with `ListView` to create an "expand /
236/// collapse" list entry. When used with scrolling widgets like `ListView`, a
237/// unique `PageStorageKey` must be specified as the [`key`](Self::key), to enable the
238/// [`Expansible`] to save and restore its expanded state when it is scrolled
239/// in and out of view.
240///
241/// Provide [`header_builder`](Self::header_builder) and
242/// [`body_builder`](Self::body_builder) callbacks to build the header and body widgets. An
243/// additional [`expansible_builder`](Self::expansible_builder) callback can be provided to
244/// further customize the layout of the widget.
245///
246/// The [`Expansible`] does not inherently toggle the expansion state. To toggle
247/// the expansion state, call [`ExpansibleController::expand`] and
248/// [`ExpansibleController::collapse`] as needed, most typically when the header
249/// returned in [`header_builder`](Self::header_builder) is tapped.
250///
251/// See also:
252///
253///  * `ExpansionTile`, a Material-styled widget that expands and collapses.
254pub struct Expansible {
255    /// See [`Widget::key`](crate::Widget::key).
256    pub key: Option<KeyRef>,
257
258    /// Expands and collapses the widget.
259    ///
260    /// The controller manages the expansion state and toggles the expansion.
261    pub controller: Ref<ExpansibleController>,
262
263    /// Builds the always-displayed header.
264    ///
265    /// Many use cases involve toggling the expansion state when this header is
266    /// tapped. To toggle the expansion state, call [`ExpansibleController::expand`]
267    /// or [`ExpansibleController::collapse`].
268    pub header_builder: ExpansibleComponentBuilder,
269
270    /// Builds the collapsible body.
271    ///
272    /// When this widget is expanded, the height of its body animates from 0 to
273    /// its fully extended height.
274    pub body_builder: ExpansibleComponentBuilder,
275
276    /// Used to override the expansion animation curve and duration.
277    ///
278    /// If [`AnimationStyle::duration`] is provided, it will be used instead of
279    /// [`duration`](Self::duration). If not provided, [`duration`](Self::duration) is used,
280    /// which defaults to 200ms.
281    ///
282    /// If [`AnimationStyle::curve`] is provided, it will be used to override
283    /// [`curve`](Self::curve). If it is `None`, then [`curve`](Self::curve) will be used.
284    /// Otherwise, defaults to [`Curves::ease`].
285    ///
286    /// If [`AnimationStyle::reverse_curve`] is provided, it will be used to
287    /// override [`reverse_curve`](Self::reverse_curve). If it is `None`, then
288    /// [`reverse_curve`](Self::reverse_curve) will be used.
289    ///
290    /// To disable the theme animation, use [`AnimationStyle::NO_ANIMATION`].
291    pub animation_style: Option<AnimationStyle>,
292
293    /// The duration of the expansion animation.
294    ///
295    /// Defaults to a duration of 200ms.
296    ///
297    /// This property is deprecated, use [`animation_style`](Self::animation_style) instead.
298    #[deprecated(
299        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
300    )]
301    pub duration: Duration,
302
303    /// The curve of the expansion animation.
304    ///
305    /// Defaults to [`Curves::ease`].
306    ///
307    /// This property is deprecated, use [`animation_style`](Self::animation_style) instead.
308    #[deprecated(
309        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
310    )]
311    pub curve: Rc<dyn Curve>,
312
313    /// The reverse curve of the expansion animation.
314    ///
315    /// If `None`, uses [`curve`](Self::curve) in both directions.
316    ///
317    /// This property is deprecated, use [`animation_style`](Self::animation_style) instead.
318    #[deprecated(
319        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
320    )]
321    pub reverse_curve: Option<Rc<dyn Curve>>,
322
323    /// Whether the state of the body is maintained when the widget expands or
324    /// collapses.
325    ///
326    /// If true, the body is kept in the tree while the widget is
327    /// collapsed. Otherwise, the body is removed from the tree when the
328    /// widget is collapsed and recreated upon expansion.
329    ///
330    /// Defaults to true.
331    pub maintain_state: bool,
332
333    /// Builds the widget with the results of [`header_builder`](Self::header_builder) and
334    /// [`body_builder`](Self::body_builder).
335    ///
336    /// Defaults to placing the header and body in a [`Column`].
337    pub expansible_builder: ExpansibleBuilder,
338}
339
340impl Expansible {
341    /// Creates an instance of [`Expansible`]; Dart's optional named arguments are the
342    /// setters.
343    #[allow(deprecated)]
344    pub fn new(
345        header_builder: ExpansibleComponentBuilder,
346        body_builder: ExpansibleComponentBuilder,
347        controller: Ref<ExpansibleController>,
348    ) -> Expansible {
349        Expansible {
350            key: None,
351            controller,
352            header_builder,
353            body_builder,
354            animation_style: None,
355            duration: Duration::from_millis(200),
356            curve: Curves::ease(),
357            reverse_curve: None,
358            maintain_state: true,
359            expansible_builder: Rc::new(Expansible::default_expansible_builder),
360        }
361    }
362
363    /// Dart `Expansible(key:)`.
364    pub fn key(mut self, key: KeyRef) -> Expansible {
365        self.key = Some(key);
366        self
367    }
368
369    /// Dart `Expansible(expansibleBuilder:)`.
370    pub fn expansible_builder(mut self, expansible_builder: ExpansibleBuilder) -> Expansible {
371        self.expansible_builder = expansible_builder;
372        self
373    }
374
375    /// Dart `Expansible(animationStyle:)`.
376    pub fn animation_style(mut self, animation_style: AnimationStyle) -> Expansible {
377        self.animation_style = Some(animation_style);
378        self
379    }
380
381    /// Dart `Expansible(duration:)`.
382    #[deprecated(
383        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
384    )]
385    #[allow(deprecated)]
386    pub fn duration(mut self, duration: Duration) -> Expansible {
387        self.duration = duration;
388        self
389    }
390
391    /// Dart `Expansible(curve:)`.
392    #[deprecated(
393        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
394    )]
395    #[allow(deprecated)]
396    pub fn curve(mut self, curve: Rc<dyn Curve>) -> Expansible {
397        self.curve = curve;
398        self
399    }
400
401    /// Dart `Expansible(reverseCurve:)`.
402    #[deprecated(
403        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
404    )]
405    #[allow(deprecated)]
406    pub fn reverse_curve(mut self, reverse_curve: Rc<dyn Curve>) -> Expansible {
407        self.reverse_curve = Some(reverse_curve);
408        self
409    }
410
411    /// Dart `Expansible(maintainState:)`.
412    pub fn maintain_state(mut self, maintain_state: bool) -> Expansible {
413        self.maintain_state = maintain_state;
414        self
415    }
416
417    /// Dart's `_defaultExpansibleBuilder`.
418    fn default_expansible_builder(
419        _app: &mut App,
420        _context: BuildContext,
421        header: &WidgetRef,
422        body: &WidgetRef,
423        _animation: AnimationRef<f64>,
424    ) -> WidgetRef {
425        Column::new()
426            .main_axis_size(MainAxisSize::Min)
427            .children([header.clone(), body.clone()])
428            .into_widget()
429    }
430}
431
432impl Debug for Expansible {
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        f.debug_struct("Expansible")
435            .field("controller", &self.controller)
436            .field("maintain_state", &self.maintain_state)
437            .finish_non_exhaustive()
438    }
439}
440
441impl StatefulWidget for Expansible {
442    type State = ExpansibleState;
443
444    fn key(&self) -> Option<&KeyRef> {
445        self.key.as_ref()
446    }
447
448    fn create_state(&self) -> ExpansibleState {
449        ExpansibleState {
450            state: StateData::new(),
451            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
452            animation_controller: None,
453            height_factor_tween: None,
454            height_factor: None,
455        }
456    }
457}
458
459/// Dart's `_ExpansibleState`.
460pub struct ExpansibleState {
461    state: StateData<Expansible>,
462    single_ticker_provider: SingleTickerProviderStateMixinData,
463    /// Created in `init_state`, because a state is created without the [`App`].
464    animation_controller: Option<Ref<AnimationController>>,
465    height_factor_tween: Option<Ref<Tween<f64>>>,
466    height_factor: Option<Ref<CurvedAnimation>>,
467}
468
469impl ExpansibleState {
470    fn animation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
471        app.get(self)
472            .animation_controller
473            .handle()
474            .expect("created in init_state")
475    }
476
477    fn height_factor(self: Handle<Self>, app: &App) -> Handle<CurvedAnimation> {
478        app.get(self)
479            .height_factor
480            .handle()
481            .expect("created in init_state")
482    }
483
484    #[allow(deprecated)]
485    fn duration(widget: &Expansible) -> Duration {
486        widget
487            .animation_style
488            .as_ref()
489            .and_then(|style| style.duration)
490            .unwrap_or(widget.duration)
491    }
492
493    #[allow(deprecated)]
494    fn curve(widget: &Expansible) -> Rc<dyn Curve> {
495        widget
496            .animation_style
497            .as_ref()
498            .and_then(|style| style.curve.clone())
499            .unwrap_or_else(|| widget.curve.clone())
500    }
501
502    #[allow(deprecated)]
503    fn reverse_curve(widget: &Expansible) -> Option<Rc<dyn Curve>> {
504        widget
505            .animation_style
506            .as_ref()
507            .and_then(|style| style.reverse_curve.clone())
508            .or_else(|| widget.reverse_curve.clone())
509    }
510
511    fn toggle_expansion(self: Handle<Self>, app: &mut App) {
512        let controller = self.widget(app).controller.handle();
513        let animation_controller = self.animation_controller(app);
514        if controller.is_expanded(app) {
515            animation_controller.forward(app, None);
516        } else {
517            let reversal = animation_controller.reverse(app, None);
518            reversal.when_complete(
519                app,
520                Listener::new(move |app| {
521                    if !self.mounted(app) {
522                        return;
523                    }
524                    self.set_state(app, |_state| {
525                        // Rebuild without the body.
526                    });
527                }),
528            );
529        }
530        let is_expanded = controller.is_expanded(app);
531        let context = self.context(app);
532        if let Some(bucket) = PageStorage::maybe_of(app, context) {
533            bucket.write_state(app, context, Rc::new(is_expanded), None);
534        }
535        self.set_state(app, |_state| {
536            // Rebuild with the header and the animating body.
537        });
538    }
539}
540
541impl SingleTickerProviderStateMixin for ExpansibleState {
542    fn single_ticker_provider_data(
543        self: Handle<Self>,
544        app: &App,
545    ) -> &SingleTickerProviderStateMixinData {
546        &app.get(self).single_ticker_provider
547    }
548
549    fn single_ticker_provider_data_mut(
550        self: Handle<Self>,
551        app: &mut App,
552    ) -> &mut SingleTickerProviderStateMixinData {
553        &mut app.get_mut(self).single_ticker_provider
554    }
555}
556
557/// Dart's `vsync: this`.
558impl TickerProviderObject for ExpansibleState {
559    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
560        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
561    }
562}
563
564impl State for ExpansibleState {
565    type Widget = Expansible;
566    crate::state_accessors!();
567
568    fn init_state(self: Handle<Self>, app: &mut App) {
569        let duration = ExpansibleState::duration(self.widget(app));
570        let animation_controller = AnimationController::new(
571            app,
572            None,
573            Some(duration),
574            None,
575            0.0,
576            1.0,
577            AnimationBehavior::Normal,
578            self,
579        );
580        app.get_mut(self).animation_controller = Some(animation_controller.clone());
581        let controller = self.widget(app).controller.handle();
582        let context = self.context(app);
583        let stored = PageStorage::maybe_of(app, context)
584            .and_then(|bucket| bucket.read_state(app, context, None))
585            .and_then(|data| data.downcast_ref::<bool>().copied());
586        let initially_expanded = stored.unwrap_or_else(|| controller.is_expanded(app));
587        if initially_expanded {
588            animation_controller.set_value(app, 1.0);
589            controller.expand(app);
590        } else {
591            controller.collapse(app);
592        }
593        let height_factor_tween = Tween::new(app, Some(0.0), Some(1.0));
594        let parent = animation_controller.drive(app, height_factor_tween.clone());
595        let curve = ExpansibleState::curve(self.widget(app));
596        let reverse_curve = ExpansibleState::reverse_curve(self.widget(app));
597        let height_factor = CurvedAnimation::new(app, parent, curve, reverse_curve);
598        let state = app.get_mut(self);
599        state.height_factor_tween = Some(height_factor_tween);
600        state.height_factor = Some(height_factor);
601        controller.add_listener(app, Listener::handle_method(self, Self::toggle_expansion));
602    }
603
604    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Expansible) {
605        let old_duration = ExpansibleState::duration(old_widget);
606        let old_curve = ExpansibleState::curve(old_widget);
607        let old_reverse_curve = ExpansibleState::reverse_curve(old_widget);
608        let curve = ExpansibleState::curve(self.widget(app));
609        let reverse_curve = ExpansibleState::reverse_curve(self.widget(app));
610        let duration = ExpansibleState::duration(self.widget(app));
611
612        let height_factor = self.height_factor(app);
613        if !Rc::ptr_eq(&curve, &old_curve) {
614            app.get_mut(height_factor).curve = curve;
615        }
616        if !curves_identical(&reverse_curve, &old_reverse_curve) {
617            app.get_mut(height_factor).reverse_curve = reverse_curve;
618        }
619        if duration != old_duration {
620            app.get_mut(self.animation_controller(app)).duration = Some(duration);
621        }
622        let controller = self.widget(app).controller.handle();
623        if controller != old_widget.controller {
624            old_widget
625                .controller
626                .remove_listener(app, &Listener::handle_method(self, Self::toggle_expansion));
627            controller.add_listener(app, Listener::handle_method(self, Self::toggle_expansion));
628            if old_widget.controller.is_expanded(app) != controller.is_expanded(app) {
629                self.toggle_expansion(app);
630            }
631        }
632    }
633
634    fn activate(self: Handle<Self>, app: &mut App) {
635        SingleTickerProviderStateMixin::activate(self, app);
636    }
637
638    fn dispose(self: Handle<Self>, app: &mut App) {
639        let controller = self.widget(app).controller.handle();
640        controller.remove_listener(app, &Listener::handle_method(self, Self::toggle_expansion));
641        let animation_controller = self.animation_controller(app);
642        animation_controller.dispose(app);
643        let height_factor = self.height_factor(app);
644        height_factor.dispose(app);
645        SingleTickerProviderStateMixin::dispose(self, app);
646    }
647
648    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
649        let animation_controller = self.animation_controller(app);
650        let controller = self.widget(app).controller.handle();
651        let is_expanded = controller.is_expanded(app);
652        debug_assert!(!animation_controller.is_dismissed(app) || !is_expanded);
653        let closed = !is_expanded && animation_controller.is_dismissed(app);
654        let should_remove_body = closed && !self.widget(app).maintain_state;
655
656        let animation: AnimationRef<f64> = app
657            .get(self)
658            .animation_controller
659            .as_ref()
660            .expect("created in init_state")
661            .erase();
662        let body_builder = self.widget(app).body_builder.clone();
663        let body = body_builder(app, context, animation.clone());
664        let result = Offstage::new()
665            .offstage(closed)
666            .child(TickerMode::new(!closed, body))
667            .into_widget();
668
669        let header_builder = self.widget(app).header_builder.clone();
670        let expansible_builder = self.widget(app).expansible_builder.clone();
671        let height_factor = app
672            .get(self)
673            .height_factor
674            .clone()
675            .expect("created in init_state");
676        let listenable = Rc::new(animation.clone());
677        let mut builder = AnimatedBuilder::new(listenable, move |app, context, child| {
678            let header = header_builder(app, context, animation.clone());
679            let mut align = Align::new().height_factor(height_factor.value(app));
680            if let Some(child) = child {
681                align = align.child(child.clone());
682            }
683            let body = ClipRect::new().child(align).into_widget();
684            expansible_builder(app, context, &header, &body, animation.clone())
685        });
686        if !should_remove_body {
687            builder = builder.child(result);
688        }
689        builder.into_widget()
690    }
691}
692
693/// Dart's `Curve? != Curve?`, which is identity on the `const` curve instances.
694fn curves_identical(a: &Option<Rc<dyn Curve>>, b: &Option<Rc<dyn Curve>>) -> bool {
695    match (a, b) {
696        (None, None) => true,
697        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
698        _ => false,
699    }
700}
701
702#[cfg(test)]
703mod tests {
704    use std::cell::Cell;
705
706    use waft_embedder::{Size, TextDirection};
707    use waft_rendering::{
708        AnyRenderObject, BoxConstraints, RenderBox, RenderClipRect, RenderConstrainedBox,
709        RenderConstrainedBoxBase, RenderHandle, RenderOffstage, RendererBinding,
710    };
711
712    use super::*;
713    use crate::framework::{LeafRenderObjectWidget, RenderObjectWidget};
714    use crate::testing::{WidgetTester, test_widgets};
715    use crate::widgets::basic::{Directionality, SizedBox};
716    use crate::widgets::page_storage::{PageStorageBucket, PageStorageKey};
717
718    /// `SizedBox` in miniature, so a subtree's height is easy to read back.
719    #[derive(Debug)]
720    struct Sized {
721        size: Size,
722    }
723
724    impl RenderObjectWidget for Sized {
725        type RenderObject = RenderConstrainedBox;
726
727        fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
728            RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
729        }
730
731        fn update_render_object(
732            &self,
733            app: &mut App,
734            _context: BuildContext,
735            render_object: RenderHandle<RenderConstrainedBox>,
736        ) {
737            render_object.set_additional_constraints(app, BoxConstraints::tight(self.size));
738        }
739    }
740
741    impl LeafRenderObjectWidget for Sized {}
742
743    fn sized(width: f64, height: f64) -> Sized {
744        Sized {
745            size: Size::new(width, height),
746        }
747    }
748
749    fn header_builder() -> ExpansibleComponentBuilder {
750        Rc::new(|_app, _context, _animation| sized(100.0, 20.0).into_widget())
751    }
752
753    fn body_builder(builds: &Rc<Cell<u32>>) -> ExpansibleComponentBuilder {
754        let builds = Rc::clone(builds);
755        Rc::new(move |_app, _context, _animation| {
756            builds.set(builds.get() + 1);
757            sized(100.0, 40.0).into_widget()
758        })
759    }
760
761    fn expansible(controller: Ref<ExpansibleController>, builds: &Rc<Cell<u32>>) -> Expansible {
762        Expansible::new(header_builder(), body_builder(builds), controller)
763    }
764
765    fn ltr(widget: Expansible) -> Directionality {
766        Directionality::new(TextDirection::Ltr, widget)
767    }
768
769    fn children(app: &App, object: AnyRenderObject) -> Vec<AnyRenderObject> {
770        let mut children = Vec::new();
771        object.visit_children(app, &mut |child| children.push(child));
772        children
773    }
774
775    fn only_child(app: &App, object: AnyRenderObject) -> Option<AnyRenderObject> {
776        children(app, object).first().copied()
777    }
778
779    /// The `Column` the default expansible builder returns: the view's render child.
780    fn column(tester: &WidgetTester) -> AnyRenderObject {
781        let mut app = tester.cell.borrow_mut();
782        let binding = RendererBinding::instance(&mut app);
783        binding.render_views(&app)[0]
784            .child(&app)
785            .expect("a child")
786            .as_object()
787    }
788
789    /// The `Column`'s second child: the `ClipRect` wrapping the body.
790    fn body_clip(tester: &WidgetTester) -> AnyRenderObject {
791        let column = column(tester);
792        children(&tester.cell.borrow(), column)[1]
793    }
794
795    fn body_height(tester: &WidgetTester) -> f64 {
796        let clip = body_clip(tester);
797        clip.as_box()
798            .expect("a box")
799            .size(&tester.cell.borrow())
800            .height()
801    }
802
803    /// The `Align` under the body's `ClipRect`.
804    fn body_align(tester: &WidgetTester) -> AnyRenderObject {
805        let clip = body_clip(tester);
806        only_child(&tester.cell.borrow(), clip).expect("the Align")
807    }
808
809    fn offstage(tester: &WidgetTester) -> bool {
810        let align = body_align(tester);
811        let app = tester.cell.borrow();
812        only_child(&app, align)
813            .expect("the Offstage")
814            .downcast::<RenderOffstage>(&app)
815            .expect("a RenderOffstage")
816            .offstage(&app)
817    }
818
819    fn body_is_in_the_tree(tester: &WidgetTester) -> bool {
820        let align = body_align(tester);
821        only_child(&tester.cell.borrow(), align).is_some()
822    }
823
824    // expansible_test.dart 'Expansible expands and collapses'
825    #[test]
826    fn an_expansible_expands_and_collapses_through_its_controller() {
827        test_widgets(|tester| {
828            let controller = tester.update(ExpansibleController::new);
829            let builds = Rc::new(Cell::new(0));
830            tester.pump_widget(ltr(expansible(controller.clone(), &builds)));
831            assert!(!controller.is_expanded(&tester.cell.borrow()));
832            assert_eq!(body_height(tester), 0.0);
833            assert!(offstage(tester), "the body is hidden when closed");
834
835            tester.update(|app| controller.expand(app));
836            tester.pump();
837            assert!(controller.is_expanded(&tester.cell.borrow()));
838            assert!(!offstage(tester), "the body is on stage at once");
839            tester.pump_and_settle();
840            assert_eq!(body_height(tester), 40.0);
841
842            tester.update(|app| controller.collapse(app));
843            tester.pump();
844            tester.pump_and_settle();
845            assert_eq!(body_height(tester), 0.0);
846            assert!(offstage(tester), "offstage again once dismissed");
847
848            tester.update(|app| controller.dispose(app));
849        });
850    }
851
852    // expansible_test.dart 'Expansible maintainState'
853    #[test]
854    fn a_collapsed_expansible_removes_its_body_when_maintain_state_is_false() {
855        test_widgets(|tester| {
856            let controller = tester.update(ExpansibleController::new);
857            let builds = Rc::new(Cell::new(0));
858            tester.pump_widget(ltr(
859                expansible(controller.clone(), &builds).maintain_state(false)
860            ));
861            assert!(
862                !body_is_in_the_tree(tester),
863                "the body is not in the tree while closed"
864            );
865
866            tester.update(|app| controller.expand(app));
867            tester.pump();
868            assert!(body_is_in_the_tree(tester), "expanding puts it back");
869            assert!(!offstage(tester));
870
871            tester.update(|app| controller.dispose(app));
872        });
873    }
874
875    #[test]
876    fn a_collapsed_expansible_keeps_its_body_when_maintain_state_is_true() {
877        test_widgets(|tester| {
878            let controller = tester.update(ExpansibleController::new);
879            let builds = Rc::new(Cell::new(0));
880            tester.pump_widget(ltr(expansible(controller.clone(), &builds)));
881            assert_eq!(builds.get(), 1, "the body is built but offstage");
882            assert!(offstage(tester));
883
884            tester.update(|app| controller.dispose(app));
885        });
886    }
887
888    // expansible_test.dart 'Expansible restores state from PageStorage'
889    #[test]
890    fn an_expansible_restores_its_expanded_state_from_page_storage() {
891        test_widgets(|tester| {
892            let bucket = tester.update(PageStorageBucket::new);
893            let controller = tester.update(ExpansibleController::new);
894            let builds = Rc::new(Cell::new(0));
895            let page = |controller| {
896                PageStorage::new(
897                    bucket.clone(),
898                    Directionality::new(
899                        TextDirection::Ltr,
900                        expansible(controller, &builds).key(PageStorageKey::new("tile").into_key()),
901                    ),
902                )
903                .into_widget()
904            };
905            tester.pump_widget(page(controller.clone()));
906            tester.update(|app| controller.expand(app));
907            tester.pump();
908            tester.pump_and_settle();
909            assert_eq!(body_height(tester), 40.0);
910
911            // A fresh controller and state, as a tile scrolled out of view and back gets.
912            let replacement = tester.update(ExpansibleController::new);
913            tester.pump_widget(SizedBox::new());
914            tester.pump_widget(page(replacement.clone()));
915            assert!(
916                replacement.is_expanded(&tester.cell.borrow()),
917                "the bucket told the new state it was open"
918            );
919            assert_eq!(body_height(tester), 40.0);
920
921            tester.update(|app| {
922                controller.dispose(app);
923                replacement.dispose(app);
924            });
925        });
926    }
927
928    // expansible_test.dart 'ExpansibleController.of'
929    #[test]
930    fn expansible_controller_of_finds_the_enclosing_expansible() {
931        test_widgets(|tester| {
932            let controller = tester.update(ExpansibleController::new);
933            let found: Rc<Cell<Option<Handle<ExpansibleController>>>> = Rc::new(Cell::new(None));
934            let header: ExpansibleComponentBuilder = Rc::new({
935                let found = Rc::clone(&found);
936                move |app, context, _animation| {
937                    found.set(Some(ExpansibleController::of(app, context)));
938                    sized(100.0, 20.0).into_widget()
939                }
940            });
941            let builds = Rc::new(Cell::new(0));
942            tester.pump_widget(ltr(Expansible::new(
943                header,
944                body_builder(&builds),
945                controller.clone(),
946            )));
947            assert_eq!(found.get(), Some(controller.handle()));
948
949            tester.update(|app| controller.dispose(app));
950        });
951    }
952
953    #[test]
954    fn a_custom_expansible_builder_replaces_the_default_column() {
955        test_widgets(|tester| {
956            let controller = tester.update(ExpansibleController::new);
957            let builds = Rc::new(Cell::new(0));
958            let widget = expansible(controller.clone(), &builds).expansible_builder(Rc::new(
959                |_app, _context, _header, body, _animation| body.clone(),
960            ));
961            tester.pump_widget(ltr(widget));
962            // Only the body's `ClipRect` is left under the view, whose tight constraints it fills.
963            let root = column(tester);
964            let app = tester.cell.borrow();
965            assert!(root.downcast::<RenderClipRect>(&app).is_some());
966            assert_eq!(root.as_box().expect("a box").size(&app).height(), 600.0);
967            drop(app);
968
969            tester.update(|app| controller.dispose(app));
970        });
971    }
972}