waft-widgets 0.16.0

Widget framework and widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! Flutter counterpart: `widgets/expansible.dart`.

use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;

use waft_animation::{
    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStyle, Curve,
    CurvedAnimation, Curves, Tween,
};
use waft_foundation::{
    App, ChangeNotifier, ChangeNotifierData, Handle, ListenableObject, Listener, OptionRetained,
};
use waft_rendering::MainAxisSize;
use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};

use crate::framework::{
    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::basic::{Align, ClipRect, Column, Offstage};
use crate::widgets::page_storage::PageStorage;
use crate::widgets::ticker_provider::{
    SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData, TickerMode,
};
use crate::widgets::transitions::AnimatedBuilder;
use waft_animation::Drive;
use waft_foundation::Ref;

/// The type of the callback that returns the header or body of an [`Expansible`].
///
/// The `animation` argument exposes the underlying expanding or collapsing
/// animation, which has a value of 0 when the [`Expansible`] is completely
/// collapsed and 1 when it is completely expanded. This can be used to drive
/// animations that sync up with the expanding or collapsing animation, such as
/// rotating an icon.
///
/// See also:
///
///   * [`Expansible::header_builder`], which is of this type.
///   * [`Expansible::body_builder`], which is also of this type.
pub type ExpansibleComponentBuilder =
    Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>) -> WidgetRef>;

/// The type of the callback that uses the header and body of an [`Expansible`]
/// widget to build the widget.
///
/// The `header` argument is the header returned by [`Expansible::header_builder`].
/// The `body` argument is the body returned by [`Expansible::body_builder`] wrapped
/// in an [`Offstage`] to hide the body when the [`Expansible`] is collapsed.
///
/// The `animation` argument exposes the underlying expanding or collapsing
/// animation, which has a value of 0 when the [`Expansible`] is completely
/// collapsed and 1 when it is completely expanded. This can be used to drive
/// animations that sync up with the expanding or collapsing animation, such as
/// rotating an icon.
///
/// See also:
///
///   * [`Expansible::expansible_builder`], which is of this type.
pub type ExpansibleBuilder =
    Rc<dyn Fn(&mut App, BuildContext, &WidgetRef, &WidgetRef, AnimationRef<f64>) -> WidgetRef>;

/// A controller for managing the expansion state of an [`Expansible`].
///
/// This is a [`ChangeNotifier`] that notifies its listeners if the value of
/// [`is_expanded`](Self::is_expanded) changes.
///
/// This controller provides methods to programmatically expand or collapse the
/// widget, and it allows external components to query the current expansion
/// state.
///
/// The controller's [`expand`](Self::expand) and [`collapse`](Self::collapse) methods cause
/// the [`Expansible`] to rebuild, so they may not be called from a build method.
///
/// Remember to [`dispose`](Self::dispose) of the [`ExpansibleController`] when it is no
/// longer needed. This will ensure all resources used by the object are discarded.
#[derive(Debug, Default)]
pub struct ExpansibleController {
    change_notifier: ChangeNotifierData,
    is_expanded: bool,
}

impl ExpansibleController {
    /// Creates a controller to be used with [`Expansible::controller`].
    pub fn new(app: &mut App) -> Ref<ExpansibleController> {
        app.create(ExpansibleController::default())
    }

    fn set_expansion_state(self: Handle<Self>, app: &mut App, new_value: bool) {
        if new_value != app.get(self).is_expanded {
            app.get_mut(self).is_expanded = new_value;
            self.notify_listeners(app);
        }
    }

    /// Whether the expansible widget built with this controller is in expanded
    /// state.
    ///
    /// This property doesn't take the animation into account. It reports `true`
    /// even if the expansion animation is not completed.
    ///
    /// To be notified when this property changes, add a listener to the
    /// controller.
    ///
    /// See also:
    ///
    ///  * [`expand`](Self::expand), which expands the expansible widget.
    ///  * [`collapse`](Self::collapse), which collapses the expansible widget.
    pub fn is_expanded(self: Handle<Self>, app: &App) -> bool {
        app.get(self).is_expanded
    }

    /// Expands the [`Expansible`] that was built with this controller.
    ///
    /// If the widget is already in the expanded state (see
    /// [`is_expanded`](Self::is_expanded)), calling this method has no effect.
    ///
    /// Calling this method may cause the [`Expansible`] to rebuild, so it may
    /// not be called from a build method.
    ///
    /// Calling this method will notify registered listeners of this controller
    /// that the expansion state has changed.
    ///
    /// See also:
    ///
    ///  * [`collapse`](Self::collapse), which collapses the expansible widget.
    ///  * [`is_expanded`](Self::is_expanded) to check whether the expansible widget is
    ///    expanded.
    pub fn expand(self: Handle<Self>, app: &mut App) {
        self.set_expansion_state(app, true);
    }

    /// Collapses the [`Expansible`] that was built with this controller.
    ///
    /// If the widget is already in the collapsed state (see
    /// [`is_expanded`](Self::is_expanded)), calling this method has no effect.
    ///
    /// Calling this method may cause the [`Expansible`] to rebuild, so it may not
    /// be called from a build method.
    ///
    /// Calling this method will notify registered listeners of this controller
    /// that the expansion state has changed.
    ///
    /// See also:
    ///
    ///  * [`expand`](Self::expand), which expands the [`Expansible`].
    ///  * [`is_expanded`](Self::is_expanded) to check whether the [`Expansible`] is expanded.
    pub fn collapse(self: Handle<Self>, app: &mut App) {
        self.set_expansion_state(app, false);
    }

    /// Convenience method for toggling the current [`is_expanded`](Self::is_expanded) status.
    ///
    /// Calling this method may cause the [`Expansible`] to rebuild, so it may not
    /// be called from a build method.
    ///
    /// Calling this method will notify registered listeners of this controller
    /// that the expansion state has changed.
    ///
    /// See also:
    ///
    ///  * [`expand`](Self::expand), which expands the [`Expansible`].
    ///  * [`collapse`](Self::collapse), which collapses the [`Expansible`].
    ///  * [`is_expanded`](Self::is_expanded) to check whether the [`Expansible`] is expanded.
    pub fn toggle(self: Handle<Self>, app: &mut App) {
        if self.is_expanded(app) {
            self.collapse(app);
        } else {
            self.expand(app);
        }
    }

    /// Discards any resources used by the object.
    pub fn dispose(self: Handle<Self>, app: &mut App) {
        ChangeNotifierData::dispose(app, self);
    }

    /// Finds the [`ExpansibleController`] for the closest [`Expansible`] instance
    /// that encloses the given context.
    ///
    /// If no [`Expansible`] encloses the given context, calling this method panics.
    ///
    /// To return `None` if there is no [`Expansible`] use [`maybe_of`](Self::maybe_of)
    /// instead.
    ///
    /// Typical usage of the [`of`](Self::of) function is to call it from
    /// within the `build` method of a descendant of an [`Expansible`].
    pub fn of(app: &App, context: BuildContext) -> Handle<ExpansibleController> {
        ExpansibleController::maybe_of(app, context).expect(
            "ExpansibleController::of() called with a context that does not contain an \
             Expansible. No Expansible ancestor could be found starting from the context that \
             was passed to ExpansibleController::of(). This usually happens when the context \
             provided is from the same StatefulWidget as that whose build function actually \
             creates the Expansible widget being sought.",
        )
    }

    /// Finds the [`Expansible`] from the closest instance of this class that
    /// encloses the given context and returns its [`ExpansibleController`].
    ///
    /// If no [`Expansible`] encloses the given context then returns `None`.
    /// To panic instead, use [`of`](Self::of).
    ///
    /// See also:
    ///
    ///  * [`of`](Self::of), a similar function to this one that panics if no [`Expansible`]
    ///    encloses the given context.
    pub fn maybe_of(app: &App, context: BuildContext) -> Option<Handle<ExpansibleController>> {
        context
            .find_ancestor_state_of_type::<ExpansibleState>(app)
            .map(|state| state.widget(app).controller.handle())
    }
}

impl ChangeNotifier for ExpansibleController {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

/// A [`StatefulWidget`] that expands and collapses.
///
/// An [`Expansible`] consists of a header, which is always shown, and a
/// body, which is hidden in its collapsed state and shown in its expanded
/// state.
///
/// The [`Expansible`] is expanded or collapsed with an animation driven by an
/// [`AnimationController`]. When the widget is expanded, the height of its body
/// animates from 0 to its fully expanded height.
///
/// This widget is typically used with `ListView` to create an "expand /
/// collapse" list entry. When used with scrolling widgets like `ListView`, a
/// unique `PageStorageKey` must be specified as the [`key`](Self::key), to enable the
/// [`Expansible`] to save and restore its expanded state when it is scrolled
/// in and out of view.
///
/// Provide [`header_builder`](Self::header_builder) and
/// [`body_builder`](Self::body_builder) callbacks to build the header and body widgets. An
/// additional [`expansible_builder`](Self::expansible_builder) callback can be provided to
/// further customize the layout of the widget.
///
/// The [`Expansible`] does not inherently toggle the expansion state. To toggle
/// the expansion state, call [`ExpansibleController::expand`] and
/// [`ExpansibleController::collapse`] as needed, most typically when the header
/// returned in [`header_builder`](Self::header_builder) is tapped.
///
/// See also:
///
///  * `ExpansionTile`, a Material-styled widget that expands and collapses.
pub struct Expansible {
    /// See [`Widget::key`](crate::Widget::key).
    pub key: Option<KeyRef>,

    /// Expands and collapses the widget.
    ///
    /// The controller manages the expansion state and toggles the expansion.
    pub controller: Ref<ExpansibleController>,

    /// Builds the always-displayed header.
    ///
    /// Many use cases involve toggling the expansion state when this header is
    /// tapped. To toggle the expansion state, call [`ExpansibleController::expand`]
    /// or [`ExpansibleController::collapse`].
    pub header_builder: ExpansibleComponentBuilder,

    /// Builds the collapsible body.
    ///
    /// When this widget is expanded, the height of its body animates from 0 to
    /// its fully extended height.
    pub body_builder: ExpansibleComponentBuilder,

    /// Used to override the expansion animation curve and duration.
    ///
    /// If [`AnimationStyle::duration`] is provided, it will be used instead of
    /// [`duration`](Self::duration). If not provided, [`duration`](Self::duration) is used,
    /// which defaults to 200ms.
    ///
    /// If [`AnimationStyle::curve`] is provided, it will be used to override
    /// [`curve`](Self::curve). If it is `None`, then [`curve`](Self::curve) will be used.
    /// Otherwise, defaults to [`Curves::ease`].
    ///
    /// If [`AnimationStyle::reverse_curve`] is provided, it will be used to
    /// override [`reverse_curve`](Self::reverse_curve). If it is `None`, then
    /// [`reverse_curve`](Self::reverse_curve) will be used.
    ///
    /// To disable the theme animation, use [`AnimationStyle::NO_ANIMATION`].
    pub animation_style: Option<AnimationStyle>,

    /// The duration of the expansion animation.
    ///
    /// Defaults to a duration of 200ms.
    ///
    /// This property is deprecated, use [`animation_style`](Self::animation_style) instead.
    #[deprecated(
        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
    )]
    pub duration: Duration,

    /// The curve of the expansion animation.
    ///
    /// Defaults to [`Curves::ease`].
    ///
    /// This property is deprecated, use [`animation_style`](Self::animation_style) instead.
    #[deprecated(
        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
    )]
    pub curve: Rc<dyn Curve>,

    /// The reverse curve of the expansion animation.
    ///
    /// If `None`, uses [`curve`](Self::curve) in both directions.
    ///
    /// This property is deprecated, use [`animation_style`](Self::animation_style) instead.
    #[deprecated(
        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
    )]
    pub reverse_curve: Option<Rc<dyn Curve>>,

    /// Whether the state of the body is maintained when the widget expands or
    /// collapses.
    ///
    /// If true, the body is kept in the tree while the widget is
    /// collapsed. Otherwise, the body is removed from the tree when the
    /// widget is collapsed and recreated upon expansion.
    ///
    /// Defaults to true.
    pub maintain_state: bool,

    /// Builds the widget with the results of [`header_builder`](Self::header_builder) and
    /// [`body_builder`](Self::body_builder).
    ///
    /// Defaults to placing the header and body in a [`Column`].
    pub expansible_builder: ExpansibleBuilder,
}

impl Expansible {
    /// Creates an instance of [`Expansible`]; Dart's optional named arguments are the
    /// setters.
    #[allow(deprecated)]
    pub fn new(
        header_builder: ExpansibleComponentBuilder,
        body_builder: ExpansibleComponentBuilder,
        controller: Ref<ExpansibleController>,
    ) -> Expansible {
        Expansible {
            key: None,
            controller,
            header_builder,
            body_builder,
            animation_style: None,
            duration: Duration::from_millis(200),
            curve: Curves::ease(),
            reverse_curve: None,
            maintain_state: true,
            expansible_builder: Rc::new(Expansible::default_expansible_builder),
        }
    }

    /// Dart `Expansible(key:)`.
    pub fn key(mut self, key: KeyRef) -> Expansible {
        self.key = Some(key);
        self
    }

    /// Dart `Expansible(expansibleBuilder:)`.
    pub fn expansible_builder(mut self, expansible_builder: ExpansibleBuilder) -> Expansible {
        self.expansible_builder = expansible_builder;
        self
    }

    /// Dart `Expansible(animationStyle:)`.
    pub fn animation_style(mut self, animation_style: AnimationStyle) -> Expansible {
        self.animation_style = Some(animation_style);
        self
    }

    /// Dart `Expansible(duration:)`.
    #[deprecated(
        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
    )]
    #[allow(deprecated)]
    pub fn duration(mut self, duration: Duration) -> Expansible {
        self.duration = duration;
        self
    }

    /// Dart `Expansible(curve:)`.
    #[deprecated(
        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
    )]
    #[allow(deprecated)]
    pub fn curve(mut self, curve: Rc<dyn Curve>) -> Expansible {
        self.curve = curve;
        self
    }

    /// Dart `Expansible(reverseCurve:)`.
    #[deprecated(
        note = "Use animation_style instead. This feature was deprecated after v3.38.0-0.2.pre."
    )]
    #[allow(deprecated)]
    pub fn reverse_curve(mut self, reverse_curve: Rc<dyn Curve>) -> Expansible {
        self.reverse_curve = Some(reverse_curve);
        self
    }

    /// Dart `Expansible(maintainState:)`.
    pub fn maintain_state(mut self, maintain_state: bool) -> Expansible {
        self.maintain_state = maintain_state;
        self
    }

    /// Dart's `_defaultExpansibleBuilder`.
    fn default_expansible_builder(
        _app: &mut App,
        _context: BuildContext,
        header: &WidgetRef,
        body: &WidgetRef,
        _animation: AnimationRef<f64>,
    ) -> WidgetRef {
        Column::new()
            .main_axis_size(MainAxisSize::Min)
            .children([header.clone(), body.clone()])
            .into_widget()
    }
}

impl Debug for Expansible {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Expansible")
            .field("controller", &self.controller)
            .field("maintain_state", &self.maintain_state)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for Expansible {
    type State = ExpansibleState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_state(&self) -> ExpansibleState {
        ExpansibleState {
            state: StateData::new(),
            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
            animation_controller: None,
            height_factor_tween: None,
            height_factor: None,
        }
    }
}

/// Dart's `_ExpansibleState`.
pub struct ExpansibleState {
    state: StateData<Expansible>,
    single_ticker_provider: SingleTickerProviderStateMixinData,
    /// Created in `init_state`, because a state is created without the [`App`].
    animation_controller: Option<Ref<AnimationController>>,
    height_factor_tween: Option<Ref<Tween<f64>>>,
    height_factor: Option<Ref<CurvedAnimation>>,
}

impl ExpansibleState {
    fn animation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
        app.get(self)
            .animation_controller
            .handle()
            .expect("created in init_state")
    }

    fn height_factor(self: Handle<Self>, app: &App) -> Handle<CurvedAnimation> {
        app.get(self)
            .height_factor
            .handle()
            .expect("created in init_state")
    }

    #[allow(deprecated)]
    fn duration(widget: &Expansible) -> Duration {
        widget
            .animation_style
            .as_ref()
            .and_then(|style| style.duration)
            .unwrap_or(widget.duration)
    }

    #[allow(deprecated)]
    fn curve(widget: &Expansible) -> Rc<dyn Curve> {
        widget
            .animation_style
            .as_ref()
            .and_then(|style| style.curve.clone())
            .unwrap_or_else(|| widget.curve.clone())
    }

    #[allow(deprecated)]
    fn reverse_curve(widget: &Expansible) -> Option<Rc<dyn Curve>> {
        widget
            .animation_style
            .as_ref()
            .and_then(|style| style.reverse_curve.clone())
            .or_else(|| widget.reverse_curve.clone())
    }

    fn toggle_expansion(self: Handle<Self>, app: &mut App) {
        let controller = self.widget(app).controller.handle();
        let animation_controller = self.animation_controller(app);
        if controller.is_expanded(app) {
            animation_controller.forward(app, None);
        } else {
            let reversal = animation_controller.reverse(app, None);
            reversal.when_complete(
                app,
                Listener::new(move |app| {
                    if !self.mounted(app) {
                        return;
                    }
                    self.set_state(app, |_state| {
                        // Rebuild without the body.
                    });
                }),
            );
        }
        let is_expanded = controller.is_expanded(app);
        let context = self.context(app);
        if let Some(bucket) = PageStorage::maybe_of(app, context) {
            bucket.write_state(app, context, Rc::new(is_expanded), None);
        }
        self.set_state(app, |_state| {
            // Rebuild with the header and the animating body.
        });
    }
}

impl SingleTickerProviderStateMixin for ExpansibleState {
    fn single_ticker_provider_data(
        self: Handle<Self>,
        app: &App,
    ) -> &SingleTickerProviderStateMixinData {
        &app.get(self).single_ticker_provider
    }

    fn single_ticker_provider_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut SingleTickerProviderStateMixinData {
        &mut app.get_mut(self).single_ticker_provider
    }
}

/// Dart's `vsync: this`.
impl TickerProviderObject for ExpansibleState {
    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
    }
}

impl State for ExpansibleState {
    type Widget = Expansible;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let duration = ExpansibleState::duration(self.widget(app));
        let animation_controller = AnimationController::new(
            app,
            None,
            Some(duration),
            None,
            0.0,
            1.0,
            AnimationBehavior::Normal,
            self,
        );
        app.get_mut(self).animation_controller = Some(animation_controller.clone());
        let controller = self.widget(app).controller.handle();
        let context = self.context(app);
        let stored = PageStorage::maybe_of(app, context)
            .and_then(|bucket| bucket.read_state(app, context, None))
            .and_then(|data| data.downcast_ref::<bool>().copied());
        let initially_expanded = stored.unwrap_or_else(|| controller.is_expanded(app));
        if initially_expanded {
            animation_controller.set_value(app, 1.0);
            controller.expand(app);
        } else {
            controller.collapse(app);
        }
        let height_factor_tween = Tween::new(app, Some(0.0), Some(1.0));
        let parent = animation_controller.drive(app, height_factor_tween.clone());
        let curve = ExpansibleState::curve(self.widget(app));
        let reverse_curve = ExpansibleState::reverse_curve(self.widget(app));
        let height_factor = CurvedAnimation::new(app, parent, curve, reverse_curve);
        let state = app.get_mut(self);
        state.height_factor_tween = Some(height_factor_tween);
        state.height_factor = Some(height_factor);
        controller.add_listener(app, Listener::handle_method(self, Self::toggle_expansion));
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Expansible) {
        let old_duration = ExpansibleState::duration(old_widget);
        let old_curve = ExpansibleState::curve(old_widget);
        let old_reverse_curve = ExpansibleState::reverse_curve(old_widget);
        let curve = ExpansibleState::curve(self.widget(app));
        let reverse_curve = ExpansibleState::reverse_curve(self.widget(app));
        let duration = ExpansibleState::duration(self.widget(app));

        let height_factor = self.height_factor(app);
        if !Rc::ptr_eq(&curve, &old_curve) {
            app.get_mut(height_factor).curve = curve;
        }
        if !curves_identical(&reverse_curve, &old_reverse_curve) {
            app.get_mut(height_factor).reverse_curve = reverse_curve;
        }
        if duration != old_duration {
            app.get_mut(self.animation_controller(app)).duration = Some(duration);
        }
        let controller = self.widget(app).controller.handle();
        if controller != old_widget.controller {
            old_widget
                .controller
                .remove_listener(app, &Listener::handle_method(self, Self::toggle_expansion));
            controller.add_listener(app, Listener::handle_method(self, Self::toggle_expansion));
            if old_widget.controller.is_expanded(app) != controller.is_expanded(app) {
                self.toggle_expansion(app);
            }
        }
    }

    fn activate(self: Handle<Self>, app: &mut App) {
        SingleTickerProviderStateMixin::activate(self, app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let controller = self.widget(app).controller.handle();
        controller.remove_listener(app, &Listener::handle_method(self, Self::toggle_expansion));
        let animation_controller = self.animation_controller(app);
        animation_controller.dispose(app);
        let height_factor = self.height_factor(app);
        height_factor.dispose(app);
        SingleTickerProviderStateMixin::dispose(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let animation_controller = self.animation_controller(app);
        let controller = self.widget(app).controller.handle();
        let is_expanded = controller.is_expanded(app);
        debug_assert!(!animation_controller.is_dismissed(app) || !is_expanded);
        let closed = !is_expanded && animation_controller.is_dismissed(app);
        let should_remove_body = closed && !self.widget(app).maintain_state;

        let animation: AnimationRef<f64> = app
            .get(self)
            .animation_controller
            .as_ref()
            .expect("created in init_state")
            .erase();
        let body_builder = self.widget(app).body_builder.clone();
        let body = body_builder(app, context, animation.clone());
        let result = Offstage::new()
            .offstage(closed)
            .child(TickerMode::new(!closed, body))
            .into_widget();

        let header_builder = self.widget(app).header_builder.clone();
        let expansible_builder = self.widget(app).expansible_builder.clone();
        let height_factor = app
            .get(self)
            .height_factor
            .clone()
            .expect("created in init_state");
        let listenable = Rc::new(animation.clone());
        let mut builder = AnimatedBuilder::new(listenable, move |app, context, child| {
            let header = header_builder(app, context, animation.clone());
            let mut align = Align::new().height_factor(height_factor.value(app));
            if let Some(child) = child {
                align = align.child(child.clone());
            }
            let body = ClipRect::new().child(align).into_widget();
            expansible_builder(app, context, &header, &body, animation.clone())
        });
        if !should_remove_body {
            builder = builder.child(result);
        }
        builder.into_widget()
    }
}

/// Dart's `Curve? != Curve?`, which is identity on the `const` curve instances.
fn curves_identical(a: &Option<Rc<dyn Curve>>, b: &Option<Rc<dyn Curve>>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use waft_embedder::{Size, TextDirection};
    use waft_rendering::{
        AnyRenderObject, BoxConstraints, RenderBox, RenderClipRect, RenderConstrainedBox,
        RenderConstrainedBoxBase, RenderHandle, RenderOffstage, RendererBinding,
    };

    use super::*;
    use crate::framework::{LeafRenderObjectWidget, RenderObjectWidget};
    use crate::testing::{WidgetTester, test_widgets};
    use crate::widgets::basic::{Directionality, SizedBox};
    use crate::widgets::page_storage::{PageStorageBucket, PageStorageKey};

    /// `SizedBox` in miniature, so a subtree's height is easy to read back.
    #[derive(Debug)]
    struct Sized {
        size: Size,
    }

    impl RenderObjectWidget for Sized {
        type RenderObject = RenderConstrainedBox;

        fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
            RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
        }

        fn update_render_object(
            &self,
            app: &mut App,
            _context: BuildContext,
            render_object: RenderHandle<RenderConstrainedBox>,
        ) {
            render_object.set_additional_constraints(app, BoxConstraints::tight(self.size));
        }
    }

    impl LeafRenderObjectWidget for Sized {}

    fn sized(width: f64, height: f64) -> Sized {
        Sized {
            size: Size::new(width, height),
        }
    }

    fn header_builder() -> ExpansibleComponentBuilder {
        Rc::new(|_app, _context, _animation| sized(100.0, 20.0).into_widget())
    }

    fn body_builder(builds: &Rc<Cell<u32>>) -> ExpansibleComponentBuilder {
        let builds = Rc::clone(builds);
        Rc::new(move |_app, _context, _animation| {
            builds.set(builds.get() + 1);
            sized(100.0, 40.0).into_widget()
        })
    }

    fn expansible(controller: Ref<ExpansibleController>, builds: &Rc<Cell<u32>>) -> Expansible {
        Expansible::new(header_builder(), body_builder(builds), controller)
    }

    fn ltr(widget: Expansible) -> Directionality {
        Directionality::new(TextDirection::Ltr, widget)
    }

    fn children(app: &App, object: AnyRenderObject) -> Vec<AnyRenderObject> {
        let mut children = Vec::new();
        object.visit_children(app, &mut |child| children.push(child));
        children
    }

    fn only_child(app: &App, object: AnyRenderObject) -> Option<AnyRenderObject> {
        children(app, object).first().copied()
    }

    /// The `Column` the default expansible builder returns: the view's render child.
    fn column(tester: &WidgetTester) -> AnyRenderObject {
        let mut app = tester.cell.borrow_mut();
        let binding = RendererBinding::instance(&mut app);
        binding.render_views(&app)[0]
            .child(&app)
            .expect("a child")
            .as_object()
    }

    /// The `Column`'s second child: the `ClipRect` wrapping the body.
    fn body_clip(tester: &WidgetTester) -> AnyRenderObject {
        let column = column(tester);
        children(&tester.cell.borrow(), column)[1]
    }

    fn body_height(tester: &WidgetTester) -> f64 {
        let clip = body_clip(tester);
        clip.as_box()
            .expect("a box")
            .size(&tester.cell.borrow())
            .height()
    }

    /// The `Align` under the body's `ClipRect`.
    fn body_align(tester: &WidgetTester) -> AnyRenderObject {
        let clip = body_clip(tester);
        only_child(&tester.cell.borrow(), clip).expect("the Align")
    }

    fn offstage(tester: &WidgetTester) -> bool {
        let align = body_align(tester);
        let app = tester.cell.borrow();
        only_child(&app, align)
            .expect("the Offstage")
            .downcast::<RenderOffstage>(&app)
            .expect("a RenderOffstage")
            .offstage(&app)
    }

    fn body_is_in_the_tree(tester: &WidgetTester) -> bool {
        let align = body_align(tester);
        only_child(&tester.cell.borrow(), align).is_some()
    }

    // expansible_test.dart 'Expansible expands and collapses'
    #[test]
    fn an_expansible_expands_and_collapses_through_its_controller() {
        test_widgets(|tester| {
            let controller = tester.update(ExpansibleController::new);
            let builds = Rc::new(Cell::new(0));
            tester.pump_widget(ltr(expansible(controller.clone(), &builds)));
            assert!(!controller.is_expanded(&tester.cell.borrow()));
            assert_eq!(body_height(tester), 0.0);
            assert!(offstage(tester), "the body is hidden when closed");

            tester.update(|app| controller.expand(app));
            tester.pump();
            assert!(controller.is_expanded(&tester.cell.borrow()));
            assert!(!offstage(tester), "the body is on stage at once");
            tester.pump_and_settle();
            assert_eq!(body_height(tester), 40.0);

            tester.update(|app| controller.collapse(app));
            tester.pump();
            tester.pump_and_settle();
            assert_eq!(body_height(tester), 0.0);
            assert!(offstage(tester), "offstage again once dismissed");

            tester.update(|app| controller.dispose(app));
        });
    }

    // expansible_test.dart 'Expansible maintainState'
    #[test]
    fn a_collapsed_expansible_removes_its_body_when_maintain_state_is_false() {
        test_widgets(|tester| {
            let controller = tester.update(ExpansibleController::new);
            let builds = Rc::new(Cell::new(0));
            tester.pump_widget(ltr(
                expansible(controller.clone(), &builds).maintain_state(false)
            ));
            assert!(
                !body_is_in_the_tree(tester),
                "the body is not in the tree while closed"
            );

            tester.update(|app| controller.expand(app));
            tester.pump();
            assert!(body_is_in_the_tree(tester), "expanding puts it back");
            assert!(!offstage(tester));

            tester.update(|app| controller.dispose(app));
        });
    }

    #[test]
    fn a_collapsed_expansible_keeps_its_body_when_maintain_state_is_true() {
        test_widgets(|tester| {
            let controller = tester.update(ExpansibleController::new);
            let builds = Rc::new(Cell::new(0));
            tester.pump_widget(ltr(expansible(controller.clone(), &builds)));
            assert_eq!(builds.get(), 1, "the body is built but offstage");
            assert!(offstage(tester));

            tester.update(|app| controller.dispose(app));
        });
    }

    // expansible_test.dart 'Expansible restores state from PageStorage'
    #[test]
    fn an_expansible_restores_its_expanded_state_from_page_storage() {
        test_widgets(|tester| {
            let bucket = tester.update(PageStorageBucket::new);
            let controller = tester.update(ExpansibleController::new);
            let builds = Rc::new(Cell::new(0));
            let page = |controller| {
                PageStorage::new(
                    bucket.clone(),
                    Directionality::new(
                        TextDirection::Ltr,
                        expansible(controller, &builds).key(PageStorageKey::new("tile").into_key()),
                    ),
                )
                .into_widget()
            };
            tester.pump_widget(page(controller.clone()));
            tester.update(|app| controller.expand(app));
            tester.pump();
            tester.pump_and_settle();
            assert_eq!(body_height(tester), 40.0);

            // A fresh controller and state, as a tile scrolled out of view and back gets.
            let replacement = tester.update(ExpansibleController::new);
            tester.pump_widget(SizedBox::new());
            tester.pump_widget(page(replacement.clone()));
            assert!(
                replacement.is_expanded(&tester.cell.borrow()),
                "the bucket told the new state it was open"
            );
            assert_eq!(body_height(tester), 40.0);

            tester.update(|app| {
                controller.dispose(app);
                replacement.dispose(app);
            });
        });
    }

    // expansible_test.dart 'ExpansibleController.of'
    #[test]
    fn expansible_controller_of_finds_the_enclosing_expansible() {
        test_widgets(|tester| {
            let controller = tester.update(ExpansibleController::new);
            let found: Rc<Cell<Option<Handle<ExpansibleController>>>> = Rc::new(Cell::new(None));
            let header: ExpansibleComponentBuilder = Rc::new({
                let found = Rc::clone(&found);
                move |app, context, _animation| {
                    found.set(Some(ExpansibleController::of(app, context)));
                    sized(100.0, 20.0).into_widget()
                }
            });
            let builds = Rc::new(Cell::new(0));
            tester.pump_widget(ltr(Expansible::new(
                header,
                body_builder(&builds),
                controller.clone(),
            )));
            assert_eq!(found.get(), Some(controller.handle()));

            tester.update(|app| controller.dispose(app));
        });
    }

    #[test]
    fn a_custom_expansible_builder_replaces_the_default_column() {
        test_widgets(|tester| {
            let controller = tester.update(ExpansibleController::new);
            let builds = Rc::new(Cell::new(0));
            let widget = expansible(controller.clone(), &builds).expansible_builder(Rc::new(
                |_app, _context, _header, body, _animation| body.clone(),
            ));
            tester.pump_widget(ltr(widget));
            // Only the body's `ClipRect` is left under the view, whose tight constraints it fills.
            let root = column(tester);
            let app = tester.cell.borrow();
            assert!(root.downcast::<RenderClipRect>(&app).is_some());
            assert_eq!(root.as_box().expect("a box").size(&app).height(), 600.0);
            drop(app);

            tester.update(|app| controller.dispose(app));
        });
    }
}