Skip to main content

waft_widgets/widgets/
transitions.rs

1//! Flutter counterpart: `widgets/transitions.dart`.
2//!
3//! `SliverFadeTransition` waits with the slivers, and [`FadeTransition`]'s
4//! `alwaysIncludeSemantics` with accessibility.
5
6use std::any::TypeId;
7use std::f64::consts::PI;
8use std::fmt::{self, Debug};
9use std::rc::Rc;
10
11use waft_animation::{Animatable, AnimationRef, AnyAnimation};
12use waft_embedder::{FilterQuality, Matrix4, Offset, Rect, Size, TextAlign, TextDirection};
13use waft_foundation::{
14    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listenable, Listener,
15};
16use waft_painting::{Alignment, AlignmentGeometry, Axis, DecorationRef, TextOverflow, TextStyle};
17use waft_rendering::{
18    AnyRenderObject, DecorationPosition, RelativeRect, RenderAnimatedOpacity,
19    RenderAnimatedOpacityMixin, RenderBox, RenderHandle,
20};
21
22use crate::framework::{
23    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, State,
24    StateData, Stateful, StatefulWidget, WidgetRef, downcast_widget, short_type_name,
25};
26use crate::widgets::basic::{Align, ClipRect, FractionalTranslation, Positioned, Transform};
27use crate::widgets::container::DecoratedBox;
28use crate::widgets::text::DefaultTextStyle;
29
30/// A widget that rebuilds when the given [`Listenable`] changes value.
31///
32/// [`AnimatedWidget`] is most commonly used with `Animation` objects, which are
33/// [`Listenable`], but it can be used with any [`Listenable`], including
34/// `ChangeNotifier` and `ValueNotifier`.
35///
36/// [`AnimatedWidget`] is most useful for widgets that are otherwise stateless. To
37/// use [`AnimatedWidget`], implement this trait with its [`build`](Self::build) function;
38/// the value becomes a tree node with `.into_widget()`, like every widget kind.
39///
40/// ## Relationship to `ImplicitlyAnimatedWidget`s
41///
42/// [`AnimatedWidget`]s (and their subclasses) take an explicit [`Listenable`] as
43/// argument, which is usually an `Animation` derived from an
44/// `AnimationController`. In most cases, the lifecycle of that
45/// `AnimationController` has to be managed manually by the developer.
46/// In contrast to that, `ImplicitlyAnimatedWidget`s (and their subclasses)
47/// automatically manage their own internal `AnimationController` making those
48/// classes easier to use as no external `Animation` has to be provided by the
49/// developer. If you only need to set a target value for the animation and
50/// configure its duration/curve, consider using (a subclass of)
51/// `ImplicitlyAnimatedWidget`s instead of (a subclass of) this class.
52///
53/// ## Common animated widgets
54///
55/// A number of animated widgets ship with the framework. They are usually named
56/// `FooTransition`, where `Foo` is the name of the non-animated
57/// version of that widget. The subclasses of this class should not be confused
58/// with subclasses of `ImplicitlyAnimatedWidget` (see above), which are usually
59/// named `AnimatedFoo`. Commonly used animated widgets include:
60///
61///  * `ListenableBuilder`, which uses a builder pattern that is useful for
62///    complex [`Listenable`] use cases.
63///  * `AnimatedBuilder`, which uses a builder pattern that is useful for
64///    complex `Animation` use cases.
65///  * `AlignTransition`, which is an animated version of `Align`.
66///  * `DecoratedBoxTransition`, which is an animated version of `DecoratedBox`.
67///  * `DefaultTextStyleTransition`, which is an animated version of
68///    `DefaultTextStyle`.
69///  * `PositionedTransition`, which is an animated version of `Positioned`.
70///  * `RelativePositionedTransition`, which is an animated version of
71///    `Positioned`.
72///  * `RotationTransition`, which animates the rotation of a widget.
73///  * `ScaleTransition`, which animates the scale of a widget.
74///  * `SizeTransition`, which animates its own size.
75///  * `SlideTransition`, which animates the position of a widget relative to
76///    its normal position.
77///  * [`FadeTransition`], which is an animated version of `Opacity`.
78///  * `AnimatedModalBarrier`, which is an animated version of `ModalBarrier`.
79pub trait AnimatedWidget: Debug + 'static {
80    /// See [`Widget::key`](crate::Widget::key).
81    fn key(&self) -> Option<&KeyRef> {
82        None
83    }
84
85    /// The [`Listenable`] to which this widget is listening.
86    ///
87    /// Commonly an `Animation` or a `ChangeNotifier`.
88    ///
89    /// Dart compares the old and new widget's listenable by identity; here that is
90    /// `Rc::ptr_eq`, so a widget that keeps one `Rc` and clones it into each rebuilt
91    /// value keeps its subscription, and one that wraps a handle anew each call is
92    /// re-subscribed on every update (the same listener set either way).
93    fn listenable(&self) -> Rc<dyn Listenable>;
94
95    /// Override this method to build widgets that depend on the state of the
96    /// listenable (e.g., the current value of the animation).
97    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef;
98
99    /// Dart's `AnimatedWidget.debugFillProperties`, which a subclass's own body calls where
100    /// Dart writes `super`.
101    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
102        let listenable = self.listenable();
103        let identity = Rc::as_ptr(&listenable) as *const () as usize as u64;
104        properties.add(DiagnosticsProperty::<String>::new(
105            "listenable",
106            Some(waft_foundation::describe_identity("Listenable", identity)),
107        ));
108    }
109}
110
111/// The kind tag of [`IntoWidget`] for an [`AnimatedWidget`].
112pub struct AnimatedKind;
113
114/// The [`StatefulWidget`] an [`AnimatedWidget`] becomes; its state is Dart's
115/// `_AnimatedState`. Subclasses typically do not override `createState`, so this is the
116/// one state every animated widget gets.
117pub struct Animated<W: AnimatedWidget>(pub W);
118
119impl<W: AnimatedWidget> IntoWidget<AnimatedKind> for W {
120    #[cfg_attr(debug_assertions, track_caller)]
121    fn into_widget(self) -> WidgetRef {
122        Rc::new(Stateful(
123            Animated(self),
124            crate::CreationLocation::of_caller(),
125        ))
126    }
127}
128
129impl<W: AnimatedWidget> StatefulWidget for Animated<W> {
130    type State = AnimatedState<W>;
131
132    fn key(&self) -> Option<&KeyRef> {
133        self.0.key()
134    }
135
136    fn type_name(&self) -> &'static str {
137        short_type_name::<W>()
138    }
139
140    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
141        self.0.debug_fill_properties(properties);
142    }
143
144    fn create_state(&self) -> AnimatedState<W> {
145        AnimatedState {
146            state: StateData::new(),
147        }
148    }
149}
150
151impl<W: AnimatedWidget> Debug for Animated<W> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        self.0.fmt(f)
154    }
155}
156
157/// Dart's `_AnimatedState`.
158pub struct AnimatedState<W: AnimatedWidget> {
159    state: StateData<Animated<W>>,
160}
161
162impl<W: AnimatedWidget> State for AnimatedState<W> {
163    type Widget = Animated<W>;
164    crate::state_accessors!();
165
166    fn init_state(self: Handle<Self>, app: &mut App) {
167        let listenable = self.widget(app).0.listenable();
168        listenable.add_listener(app, Listener::handle_method(self, Self::handle_change));
169    }
170
171    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Animated<W>) {
172        let listenable = self.widget(app).0.listenable();
173        let old_listenable = old_widget.0.listenable();
174        if !Rc::ptr_eq(&listenable, &old_listenable) {
175            old_listenable
176                .remove_listener(app, &Listener::handle_method(self, Self::handle_change));
177            listenable.add_listener(app, Listener::handle_method(self, Self::handle_change));
178        }
179    }
180
181    fn dispose(self: Handle<Self>, app: &mut App) {
182        let listenable = self.widget(app).0.listenable();
183        listenable.remove_listener(app, &Listener::handle_method(self, Self::handle_change));
184    }
185
186    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
187        let widget = context.widget(app).clone();
188        downcast_widget::<Animated<W>>(&*widget)
189            .expect("an AnimatedState builds its AnimatedWidget")
190            .0
191            .build(app, context)
192    }
193}
194
195impl<W: AnimatedWidget> AnimatedState<W> {
196    fn handle_change(self: Handle<Self>, app: &mut App) {
197        if !self.mounted(app) {
198            return;
199        }
200        self.set_state(app, |_state| {
201            // The listenable's state is our build state, and it changed already.
202        });
203    }
204}
205
206/// Signature for a builder used to control a page's exit transition.
207///
208/// When a new route enters the stack, the `animation` argument is typically
209/// used to control the enter and exit transition of the topmost route. The exit
210/// transition of the route just below the new route is controlled with the
211/// `secondary_animation`, which also controls the transition of the old route
212/// when the topmost route is popped off the stack.
213///
214/// Typically used as the argument for `ModalRoute::delegated_transition`.
215///
216/// `ModalRoute` compares the builder a route offers with the one the route above offers, as
217/// Dart compares two function values: [`new`](Self::new) equals only its clones;
218/// [`function`](Self::function) equals any other built from the same function, as two
219/// tear-offs of one static method are identical (see the porting skill's callback-identity
220/// pattern).
221#[derive(Clone)]
222pub struct DelegatedTransitionBuilder {
223    builder: Rc<DelegatedTransitionBuilderFn>,
224    identity: DelegatedTransitionBuilderIdentity,
225}
226
227/// The function a [`DelegatedTransitionBuilder`] calls.
228type DelegatedTransitionBuilderFn = dyn Fn(
229    &mut App,
230    BuildContext,
231    AnimationRef<f64>,
232    AnimationRef<f64>,
233    bool,
234    Option<&WidgetRef>,
235) -> Option<WidgetRef>;
236
237/// Equality key: closures compare by allocation, functions by the `TypeId` of the function
238/// item.
239#[derive(Clone, Copy, PartialEq)]
240enum DelegatedTransitionBuilderIdentity {
241    Closure,
242    Function(TypeId),
243}
244
245impl DelegatedTransitionBuilder {
246    /// Wraps a closure; it equals only its clones.
247    pub fn new(
248        builder: impl Fn(
249            &mut App,
250            BuildContext,
251            AnimationRef<f64>,
252            AnimationRef<f64>,
253            bool,
254            Option<&WidgetRef>,
255        ) -> Option<WidgetRef>
256        + 'static,
257    ) -> DelegatedTransitionBuilder {
258        DelegatedTransitionBuilder {
259            builder: Rc::new(builder),
260            identity: DelegatedTransitionBuilderIdentity::Closure,
261        }
262    }
263
264    /// A function, comparable like a Dart tear-off of a static method.
265    ///
266    /// Pass the function by name. A fn pointer or capturing closure is rejected: it has no
267    /// canonical identity.
268    pub fn function<F>(builder: F) -> DelegatedTransitionBuilder
269    where
270        F: Fn(
271                &mut App,
272                BuildContext,
273                AnimationRef<f64>,
274                AnimationRef<f64>,
275                bool,
276                Option<&WidgetRef>,
277            ) -> Option<WidgetRef>
278            + 'static,
279    {
280        const {
281            assert!(
282                std::mem::size_of::<F>() == 0,
283                "pass the function by name: a fn pointer or capturing closure has no canonical \
284                 identity"
285            )
286        };
287        DelegatedTransitionBuilder {
288            builder: Rc::new(builder),
289            identity: DelegatedTransitionBuilderIdentity::Function(TypeId::of::<F>()),
290        }
291    }
292
293    /// Calls the builder.
294    pub fn call(
295        &self,
296        app: &mut App,
297        context: BuildContext,
298        animation: AnimationRef<f64>,
299        secondary_animation: AnimationRef<f64>,
300        allow_snapshotting: bool,
301        child: Option<&WidgetRef>,
302    ) -> Option<WidgetRef> {
303        (self.builder)(
304            app,
305            context,
306            animation,
307            secondary_animation,
308            allow_snapshotting,
309            child,
310        )
311    }
312}
313
314impl PartialEq for DelegatedTransitionBuilder {
315    fn eq(&self, other: &DelegatedTransitionBuilder) -> bool {
316        match (self.identity, other.identity) {
317            (
318                DelegatedTransitionBuilderIdentity::Closure,
319                DelegatedTransitionBuilderIdentity::Closure,
320            ) => Rc::ptr_eq(&self.builder, &other.builder),
321            (mine, theirs) => mine == theirs,
322        }
323    }
324}
325
326impl Debug for DelegatedTransitionBuilder {
327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328        f.write_str("DelegatedTransitionBuilder")
329    }
330}
331
332/// Animates the position of a widget relative to its normal position.
333///
334/// The translation is expressed as an [`Offset`] scaled to the child's size. For
335/// example, an [`Offset`] with a `dx` of 0.25 will result in a horizontal
336/// translation of one quarter the width of the child.
337///
338/// By default, the offsets are applied in the coordinate system of the canvas
339/// (so positive x offsets move the child towards the right). If a
340/// [`text_direction`](Self::text_direction) is provided, then the offsets are applied in the
341/// reading direction, so in right-to-left text, positive x offsets move towards the
342/// left, and in left-to-right text, positive x offsets move towards the right.
343///
344/// See also:
345///
346///  * [`AlignTransition`], an animated version of an `Align` that animates its
347///    `Align::alignment` property.
348///  * [`PositionedTransition`], a widget that animates its child from a start
349///    position to an end position over the lifetime of the animation.
350///  * [`RelativePositionedTransition`], a widget that transitions its child's
351///    position based on the value of a rectangle relative to a bounding box.
352#[derive(Debug)]
353pub struct SlideTransition {
354    /// See [`Widget::key`](crate::Widget::key).
355    pub key: Option<KeyRef>,
356
357    /// The animation that controls the position of the child.
358    ///
359    /// If the current value of the position animation is `(dx, dy)`, the child
360    /// will be translated horizontally by `width * dx` and vertically by
361    /// `height * dy`, after applying the [`text_direction`](Self::text_direction) if available.
362    pub position: AnimationRef<Offset>,
363
364    /// The direction to use for the x offset described by the [`position`](Self::position).
365    ///
366    /// If [`text_direction`](Self::text_direction) is `None`, the x offset is applied in the
367    /// coordinate system of the canvas (so positive x offsets move the child towards the
368    /// right).
369    ///
370    /// If [`text_direction`](Self::text_direction) is [`TextDirection::Rtl`], the x offset is
371    /// applied in the reading direction such that x offsets move the child towards the left.
372    ///
373    /// If [`text_direction`](Self::text_direction) is [`TextDirection::Ltr`], the x offset is
374    /// applied in the reading direction such that x offsets move the child towards the right.
375    pub text_direction: Option<TextDirection>,
376
377    /// Whether hit testing should be affected by the slide animation.
378    ///
379    /// If false, hit testing will proceed as if the child was not translated at
380    /// all. Setting this value to false is useful for fast animations where you
381    /// expect the user to commonly interact with the child widget in its final
382    /// location and you want the user to benefit from "muscle memory".
383    pub transform_hit_tests: bool,
384
385    /// The widget below this widget in the tree.
386    pub child: Option<WidgetRef>,
387}
388
389impl SlideTransition {
390    /// Creates a fractional translation transition.
391    pub fn new(position: AnimationRef<Offset>) -> SlideTransition {
392        SlideTransition {
393            key: None,
394            position,
395            text_direction: None,
396            transform_hit_tests: true,
397            child: None,
398        }
399    }
400
401    /// Dart `SlideTransition(key:)`.
402    pub fn key(mut self, key: KeyRef) -> SlideTransition {
403        self.key = Some(key);
404        self
405    }
406
407    /// Dart `SlideTransition(textDirection:)`.
408    pub fn text_direction(mut self, text_direction: TextDirection) -> SlideTransition {
409        self.text_direction = Some(text_direction);
410        self
411    }
412
413    /// Dart `SlideTransition(transformHitTests:)`.
414    pub fn transform_hit_tests(mut self, transform_hit_tests: bool) -> SlideTransition {
415        self.transform_hit_tests = transform_hit_tests;
416        self
417    }
418
419    /// Dart `SlideTransition(child:)`.
420    #[cfg_attr(debug_assertions, track_caller)]
421    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SlideTransition {
422        self.child = Some(child.into_widget());
423        self
424    }
425}
426
427impl AnimatedWidget for SlideTransition {
428    fn key(&self) -> Option<&KeyRef> {
429        self.key.as_ref()
430    }
431
432    fn listenable(&self) -> Rc<dyn Listenable> {
433        Rc::new(self.position.clone())
434    }
435
436    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
437        let mut offset = self.position.value(app);
438        if self.text_direction == Some(TextDirection::Rtl) {
439            offset = Offset::new(-offset.dx(), offset.dy());
440        }
441        let mut translation =
442            FractionalTranslation::new(offset).transform_hit_tests(self.transform_hit_tests);
443        if let Some(child) = &self.child {
444            translation = translation.child(child.clone());
445        }
446        translation.into_widget()
447    }
448}
449
450/// Signature for the callback to [`MatrixTransition::on_transform`].
451///
452/// Computes a [`Matrix4`] to be used in the [`MatrixTransition`] transformed widget
453/// from the [`MatrixTransition::animation`] value.
454pub type TransformCallback = Rc<dyn Fn(f64) -> Matrix4>;
455
456/// Animates the [`Matrix4`] of a transformed widget.
457///
458/// The [`on_transform`](Self::on_transform) callback computes a [`Matrix4`] from the animated
459/// value, it is called every time the [`animation`](Self::animation) changes its value.
460///
461/// See also:
462///
463///  * [`ScaleTransition`], which animates the scale of a widget, by providing a
464///    matrix which scales along the X and Y axis.
465///  * [`RotationTransition`], which animates the rotation of a widget, by
466///    providing a matrix which rotates along the Z axis.
467pub struct MatrixTransition {
468    /// See [`Widget::key`](crate::Widget::key).
469    pub key: Option<KeyRef>,
470
471    /// The callback to compute a [`Matrix4`] from the [`animation`](Self::animation). It's
472    /// called every time [`animation`](Self::animation) changes its value.
473    pub on_transform: TransformCallback,
474
475    /// The animation that controls the matrix of the child.
476    ///
477    /// The matrix will be computed from the animation with the
478    /// [`on_transform`](Self::on_transform) callback.
479    pub animation: AnimationRef<f64>,
480
481    /// The alignment of the origin of the coordinate system in which the
482    /// transform takes place, relative to the size of the box.
483    ///
484    /// For example, to set the origin of the transform to bottom middle, you can
485    /// use an alignment of (0.0, 1.0).
486    pub alignment: Alignment,
487
488    /// The filter quality with which to apply the transform as a bitmap operation.
489    ///
490    /// When the animation is stopped (either in `AnimationStatus::Dismissed` or
491    /// `AnimationStatus::Completed`), the filter quality argument will be ignored.
492    ///
493    /// The transform will be applied by re-rendering the child if
494    /// [`filter_quality`](Self::filter_quality) is `None`, otherwise it controls the quality
495    /// of an `ImageFilter.matrix` applied to a bitmap rendering of the child.
496    pub filter_quality: Option<FilterQuality>,
497
498    /// The widget below this widget in the tree.
499    pub child: Option<WidgetRef>,
500}
501
502impl MatrixTransition {
503    /// Creates a matrix transition.
504    ///
505    /// The [`alignment`](Self::alignment) defaults to [`Alignment::CENTER`].
506    pub fn new(
507        animation: AnimationRef<f64>,
508        on_transform: impl Fn(f64) -> Matrix4 + 'static,
509    ) -> MatrixTransition {
510        MatrixTransition {
511            key: None,
512            on_transform: Rc::new(on_transform),
513            animation,
514            alignment: Alignment::CENTER,
515            filter_quality: None,
516            child: None,
517        }
518    }
519
520    /// Dart `MatrixTransition(key:)`.
521    pub fn key(mut self, key: KeyRef) -> MatrixTransition {
522        self.key = Some(key);
523        self
524    }
525
526    /// Dart `MatrixTransition(alignment:)`.
527    pub fn alignment(mut self, alignment: Alignment) -> MatrixTransition {
528        self.alignment = alignment;
529        self
530    }
531
532    /// Dart `MatrixTransition(filterQuality:)`.
533    pub fn filter_quality(mut self, filter_quality: FilterQuality) -> MatrixTransition {
534        self.filter_quality = Some(filter_quality);
535        self
536    }
537
538    /// Dart `MatrixTransition(child:)`.
539    #[cfg_attr(debug_assertions, track_caller)]
540    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> MatrixTransition {
541        self.child = Some(child.into_widget());
542        self
543    }
544
545    /// `MatrixTransition.build`'s body, shared with [`ScaleTransition`] and
546    /// [`RotationTransition`].
547    fn build_transform(
548        app: &App,
549        animation: AnyAnimation<f64>,
550        transform: Matrix4,
551        alignment: Alignment,
552        filter_quality: Option<FilterQuality>,
553        child: Option<&WidgetRef>,
554    ) -> WidgetRef {
555        // The ImageFilter layer created by setting filterQuality will introduce
556        // a saveLayer call. This is usually worthwhile when animating the layer,
557        // but leaving it in the layer tree before the animation has started or after
558        // it has finished significantly hurts performance.
559        let mut transform =
560            Transform::new(transform).alignment(AlignmentGeometry::Alignment(alignment));
561        transform.filter_quality = if animation.is_animating(app) {
562            filter_quality
563        } else {
564            None
565        };
566        if let Some(child) = child {
567            transform = transform.child(child.clone());
568        }
569        transform.into_widget()
570    }
571}
572
573impl Debug for MatrixTransition {
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        f.debug_struct("MatrixTransition")
576            .field("animation", &self.animation)
577            .field("alignment", &self.alignment)
578            .field("filter_quality", &self.filter_quality)
579            .field("child", &self.child)
580            .finish_non_exhaustive()
581    }
582}
583
584impl AnimatedWidget for MatrixTransition {
585    fn key(&self) -> Option<&KeyRef> {
586        self.key.as_ref()
587    }
588
589    fn listenable(&self) -> Rc<dyn Listenable> {
590        Rc::new(self.animation.clone())
591    }
592
593    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
594        let transform = (self.on_transform)(self.animation.value(app));
595        MatrixTransition::build_transform(
596            app,
597            self.animation.handle(),
598            transform,
599            self.alignment,
600            self.filter_quality,
601            self.child.as_ref(),
602        )
603    }
604}
605
606/// Animates the scale of a transformed widget.
607///
608/// See also:
609///
610///  * [`PositionedTransition`], a widget that animates its child from a start
611///    position to an end position over the lifetime of the animation.
612///  * [`RelativePositionedTransition`], a widget that transitions its child's
613///    position based on the value of a rectangle relative to a bounding box.
614///  * [`SizeTransition`], a widget that animates its own size and clips and
615///    aligns its child.
616#[derive(Debug)]
617pub struct ScaleTransition {
618    /// See [`Widget::key`](crate::Widget::key).
619    pub key: Option<KeyRef>,
620
621    /// See [`MatrixTransition::animation`]; read it as
622    /// [`scale`](Self::scale).
623    pub animation: AnimationRef<f64>,
624
625    /// See [`MatrixTransition::alignment`].
626    pub alignment: Alignment,
627
628    /// See [`MatrixTransition::filter_quality`].
629    pub filter_quality: Option<FilterQuality>,
630
631    /// The widget below this widget in the tree.
632    pub child: Option<WidgetRef>,
633}
634
635impl ScaleTransition {
636    /// Creates a scale transition.
637    ///
638    /// The [`alignment`](Self::alignment) defaults to [`Alignment::CENTER`].
639    pub fn new(scale: AnimationRef<f64>) -> ScaleTransition {
640        ScaleTransition {
641            key: None,
642            animation: scale,
643            alignment: Alignment::CENTER,
644            filter_quality: None,
645            child: None,
646        }
647    }
648
649    /// The animation that controls the scale of the child.
650    pub fn scale(&self) -> AnyAnimation<f64> {
651        self.animation.handle()
652    }
653
654    /// Dart `ScaleTransition(key:)`.
655    pub fn key(mut self, key: KeyRef) -> ScaleTransition {
656        self.key = Some(key);
657        self
658    }
659
660    /// Dart `ScaleTransition(alignment:)`.
661    pub fn alignment(mut self, alignment: Alignment) -> ScaleTransition {
662        self.alignment = alignment;
663        self
664    }
665
666    /// Dart `ScaleTransition(filterQuality:)`.
667    pub fn filter_quality(mut self, filter_quality: FilterQuality) -> ScaleTransition {
668        self.filter_quality = Some(filter_quality);
669        self
670    }
671
672    /// Dart `ScaleTransition(child:)`.
673    #[cfg_attr(debug_assertions, track_caller)]
674    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ScaleTransition {
675        self.child = Some(child.into_widget());
676        self
677    }
678
679    /// The callback that controls the scale of the child.
680    ///
681    /// If the current value of the animation is v, the child will be
682    /// painted v times its normal size.
683    fn handle_scale_matrix(value: f64) -> Matrix4 {
684        Matrix4::scale(value as f32, value as f32)
685    }
686}
687
688impl AnimatedWidget for ScaleTransition {
689    fn key(&self) -> Option<&KeyRef> {
690        self.key.as_ref()
691    }
692
693    fn listenable(&self) -> Rc<dyn Listenable> {
694        Rc::new(self.animation.clone())
695    }
696
697    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
698        let transform = ScaleTransition::handle_scale_matrix(self.animation.value(app));
699        MatrixTransition::build_transform(
700            app,
701            self.animation.handle(),
702            transform,
703            self.alignment,
704            self.filter_quality,
705            self.child.as_ref(),
706        )
707    }
708}
709
710/// Animates the rotation of a widget.
711///
712/// See also:
713///
714///  * [`ScaleTransition`], a widget that animates the scale of a transformed
715///    widget.
716///  * [`SizeTransition`], a widget that animates its own size and clips and
717///    aligns its child.
718#[derive(Debug)]
719pub struct RotationTransition {
720    /// See [`Widget::key`](crate::Widget::key).
721    pub key: Option<KeyRef>,
722
723    /// See [`MatrixTransition::animation`]; read it as [`turns`](Self::turns).
724    pub animation: AnimationRef<f64>,
725
726    /// See [`MatrixTransition::alignment`].
727    pub alignment: Alignment,
728
729    /// See [`MatrixTransition::filter_quality`].
730    pub filter_quality: Option<FilterQuality>,
731
732    /// The widget below this widget in the tree.
733    pub child: Option<WidgetRef>,
734}
735
736impl RotationTransition {
737    /// Creates a rotation transition.
738    pub fn new(turns: AnimationRef<f64>) -> RotationTransition {
739        RotationTransition {
740            key: None,
741            animation: turns,
742            alignment: Alignment::CENTER,
743            filter_quality: None,
744            child: None,
745        }
746    }
747
748    /// The animation that controls the rotation of the child.
749    pub fn turns(&self) -> AnyAnimation<f64> {
750        self.animation.handle()
751    }
752
753    /// Dart `RotationTransition(key:)`.
754    pub fn key(mut self, key: KeyRef) -> RotationTransition {
755        self.key = Some(key);
756        self
757    }
758
759    /// Dart `RotationTransition(alignment:)`.
760    pub fn alignment(mut self, alignment: Alignment) -> RotationTransition {
761        self.alignment = alignment;
762        self
763    }
764
765    /// Dart `RotationTransition(filterQuality:)`.
766    pub fn filter_quality(mut self, filter_quality: FilterQuality) -> RotationTransition {
767        self.filter_quality = Some(filter_quality);
768        self
769    }
770
771    /// Dart `RotationTransition(child:)`.
772    #[cfg_attr(debug_assertions, track_caller)]
773    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RotationTransition {
774        self.child = Some(child.into_widget());
775        self
776    }
777
778    /// The callback that controls the rotation of the child.
779    ///
780    /// If the current value of the animation is v, the child will be rotated
781    /// v * 2 * pi radians before being painted.
782    fn handle_turns_matrix(value: f64) -> Matrix4 {
783        Matrix4::rotation((value * PI * 2.0) as f32)
784    }
785}
786
787impl AnimatedWidget for RotationTransition {
788    fn key(&self) -> Option<&KeyRef> {
789        self.key.as_ref()
790    }
791
792    fn listenable(&self) -> Rc<dyn Listenable> {
793        Rc::new(self.animation.clone())
794    }
795
796    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
797        let transform = RotationTransition::handle_turns_matrix(self.animation.value(app));
798        MatrixTransition::build_transform(
799            app,
800            self.animation.handle(),
801            transform,
802            self.alignment,
803            self.filter_quality,
804            self.child.as_ref(),
805        )
806    }
807}
808
809/// Animates its own size and clips and aligns its child.
810///
811/// [`SizeTransition`] acts as a `ClipRect` that animates either its width or its
812/// height, depending upon the value of [`axis`](Self::axis). The alignment of the child is
813/// specified by the [`alignment`](Self::alignment).
814///
815/// Like most widgets, [`SizeTransition`] will conform to the constraints it is
816/// given, so be sure to put it in a context where it can change size. For
817/// instance, if you place it into a `Container` with a fixed size, then the
818/// [`SizeTransition`] will not be able to change size, and will appear to do
819/// nothing.
820///
821/// See also:
822///
823///  * `AnimatedCrossFade`, for a widget that automatically animates between
824///    the sizes of two children, fading between them.
825///  * [`ScaleTransition`], a widget that scales the size of the child instead of
826///    clipping it.
827///  * [`PositionedTransition`], a widget that animates its child from a start
828///    position to an end position over the lifetime of the animation.
829///  * [`RelativePositionedTransition`], a widget that transitions its child's
830///    position based on the value of a rectangle relative to a bounding box.
831#[derive(Debug)]
832pub struct SizeTransition {
833    /// See [`Widget::key`](crate::Widget::key).
834    pub key: Option<KeyRef>,
835
836    /// [`Axis::Horizontal`] if [`size_factor`](Self::size_factor) modifies the width,
837    /// otherwise [`Axis::Vertical`].
838    pub axis: Axis,
839
840    /// The animation that controls the (clipped) size of the child.
841    ///
842    /// The width or height (depending on the [`axis`](Self::axis) value) of this widget will
843    /// be its intrinsic width or height multiplied by
844    /// [`size_factor`](Self::size_factor)'s value at the current point in the animation.
845    ///
846    /// If the value of [`size_factor`](Self::size_factor) is less than one, the child will be
847    /// clipped in the appropriate axis.
848    pub size_factor: AnimationRef<f64>,
849
850    /// Describes how to align the child along the axis that
851    /// [`size_factor`](Self::size_factor) is modifying.
852    ///
853    /// A value of -1.0 indicates the top when [`axis`](Self::axis) is [`Axis::Vertical`], and
854    /// the start when [`axis`](Self::axis) is [`Axis::Horizontal`]. The start is on the left
855    /// when the text direction in effect is [`TextDirection::Ltr`] and on the right when it
856    /// is [`TextDirection::Rtl`].
857    ///
858    /// A value of 1.0 indicates the bottom or end, depending upon the [`axis`](Self::axis).
859    ///
860    /// A value of 0.0 (the default) indicates the center for either [`axis`](Self::axis)
861    /// value.
862    ///
863    /// This property has been deprecated and superseded by
864    /// [`alignment`](Self::alignment). Existing usages can be migrated as follows:
865    /// - If [`axis`](Self::axis) is [`Axis::Horizontal`], replace with
866    ///   `AlignmentGeometry::xy(axis_alignment.unwrap_or(0.0), -1.0)`.
867    /// - If [`axis`](Self::axis) is [`Axis::Vertical`], replace with
868    ///   `AlignmentGeometry::xy(-1.0, axis_alignment.unwrap_or(0.0))`.
869    #[deprecated(
870        note = "Use alignment instead. This property provides full control over both axes, \
871                which is an improvement over the old axisAlignment. This feature was \
872                deprecated after v3.41.0-1.0.pre."
873    )]
874    pub axis_alignment: Option<f64>,
875
876    /// The alignment of the child within the parent during the transition.
877    pub alignment: Option<AlignmentGeometry>,
878
879    /// The factor by which to multiply the cross axis size of the child.
880    ///
881    /// If the value of [`fixed_cross_axis_size_factor`](Self::fixed_cross_axis_size_factor)
882    /// is less than one, the child will be clipped along the appropriate axis.
883    ///
884    /// If `None` (the default), the cross axis size is as large as the parent.
885    pub fixed_cross_axis_size_factor: Option<f64>,
886
887    /// The widget below this widget in the tree.
888    pub child: Option<WidgetRef>,
889}
890
891impl SizeTransition {
892    /// Creates a size transition.
893    ///
894    /// The [`axis`](Self::axis) defaults to [`Axis::Vertical`]. The
895    /// [`alignment`](Self::alignment) defaults to the center of the modified axis, which
896    /// centers the child within the parent during the transition.
897    #[allow(deprecated)]
898    pub fn new(size_factor: AnimationRef<f64>) -> SizeTransition {
899        SizeTransition {
900            key: None,
901            axis: Axis::Vertical,
902            size_factor,
903            axis_alignment: None,
904            alignment: None,
905            fixed_cross_axis_size_factor: None,
906            child: None,
907        }
908    }
909
910    /// Dart `SizeTransition(key:)`.
911    pub fn key(mut self, key: KeyRef) -> SizeTransition {
912        self.key = Some(key);
913        self
914    }
915
916    /// Dart `SizeTransition(axis:)`.
917    pub fn axis(mut self, axis: Axis) -> SizeTransition {
918        self.axis = axis;
919        self
920    }
921
922    /// Dart `SizeTransition(axisAlignment:)`.
923    #[deprecated(
924        note = "Use alignment instead. This property provides full control over both axes, \
925                which is an improvement over the old axisAlignment. This feature was \
926                deprecated after v3.41.0-1.0.pre."
927    )]
928    #[allow(deprecated)]
929    pub fn axis_alignment(mut self, axis_alignment: f64) -> SizeTransition {
930        debug_assert!(
931            self.alignment.is_none(),
932            "Cannot provide both axisAlignment and alignment as axisAlignment has been \
933             deprecated and superseded by alignment."
934        );
935        self.axis_alignment = Some(axis_alignment);
936        self
937    }
938
939    /// Dart `SizeTransition(alignment:)`.
940    #[allow(deprecated)]
941    pub fn alignment(mut self, alignment: AlignmentGeometry) -> SizeTransition {
942        debug_assert!(
943            self.axis_alignment.is_none(),
944            "Cannot provide both axisAlignment and alignment as axisAlignment has been \
945             deprecated and superseded by alignment."
946        );
947        self.alignment = Some(alignment);
948        self
949    }
950
951    /// Dart `SizeTransition(fixedCrossAxisSizeFactor:)`.
952    pub fn fixed_cross_axis_size_factor(
953        mut self,
954        fixed_cross_axis_size_factor: f64,
955    ) -> SizeTransition {
956        debug_assert!(fixed_cross_axis_size_factor >= 0.0);
957        self.fixed_cross_axis_size_factor = Some(fixed_cross_axis_size_factor);
958        self
959    }
960
961    /// Dart `SizeTransition(child:)`.
962    #[cfg_attr(debug_assertions, track_caller)]
963    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SizeTransition {
964        self.child = Some(child.into_widget());
965        self
966    }
967}
968
969impl AnimatedWidget for SizeTransition {
970    fn key(&self) -> Option<&KeyRef> {
971        self.key.as_ref()
972    }
973
974    fn listenable(&self) -> Rc<dyn Listenable> {
975        Rc::new(self.size_factor.clone())
976    }
977
978    #[allow(deprecated)]
979    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
980        let axis_alignment = self.axis_alignment.unwrap_or(0.0);
981        let alignment = self.alignment.unwrap_or(match self.axis {
982            Axis::Horizontal => AlignmentGeometry::directional(axis_alignment, -1.0),
983            Axis::Vertical => AlignmentGeometry::directional(-1.0, axis_alignment),
984        });
985        let size_factor = self.size_factor.value(app).max(0.0);
986        let (height_factor, width_factor) = match self.axis {
987            Axis::Vertical => (Some(size_factor), self.fixed_cross_axis_size_factor),
988            Axis::Horizontal => (self.fixed_cross_axis_size_factor, Some(size_factor)),
989        };
990        let mut align = Align::new().alignment(alignment);
991        if let Some(height_factor) = height_factor {
992            align = align.height_factor(height_factor);
993        }
994        if let Some(width_factor) = width_factor {
995            align = align.width_factor(width_factor);
996        }
997        if let Some(child) = &self.child {
998            align = align.child(child.clone());
999        }
1000        ClipRect::new().child(align).into_widget()
1001    }
1002}
1003
1004/// Animates the opacity of a widget.
1005///
1006/// For a widget that automatically animates between the sizes of two children,
1007/// fading between them, see `AnimatedCrossFade`.
1008///
1009/// ## Hit testing
1010///
1011/// Setting the [`opacity`](Self::opacity) to zero does not prevent hit testing from being
1012/// applied to the descendants of the [`FadeTransition`] widget. This can be
1013/// confusing for the user, who may not see anything, and may believe the area
1014/// of the interface where the [`FadeTransition`] is hiding a widget to be
1015/// non-interactive.
1016///
1017/// With certain widgets, such as `Flow`, that compute their positions only when
1018/// they are painted, this can actually lead to bugs (from unexpected geometry
1019/// to exceptions), because those widgets are not painted by the
1020/// [`FadeTransition`] widget at all when the [`opacity`](Self::opacity) animation reaches
1021/// zero.
1022///
1023/// To avoid such problems, it is generally a good idea to combine this widget
1024/// with an `IgnorePointer` that one enables when the [`opacity`](Self::opacity) animation
1025/// reaches zero. This prevents interactions with any children in the subtree
1026/// when the [`child`](Self::child) is not visible. For performance reasons, when
1027/// implementing this, care should be taken not to rebuild the relevant widget (e.g. by
1028/// calling `State::set_state`) except at the transition point.
1029///
1030/// See also:
1031///
1032///  * `Opacity`, which does not animate changes in opacity.
1033///  * `AnimatedOpacity`, which animates changes in opacity without taking an
1034///    explicit `Animation` argument.
1035#[derive(Debug)]
1036pub struct FadeTransition {
1037    /// See [`Widget::key`](crate::Widget::key).
1038    pub key: Option<KeyRef>,
1039
1040    /// The animation that controls the opacity of the child.
1041    ///
1042    /// If the current value of the opacity animation is v, the child will be
1043    /// painted with an opacity of v. For example, if v is 0.5, the child will be
1044    /// blended 50% with its background. Similarly, if v is 0.0, the child will be
1045    /// completely transparent.
1046    pub opacity: AnimationRef<f64>,
1047
1048    /// The widget below this widget in the tree.
1049    pub child: Option<WidgetRef>,
1050}
1051
1052impl FadeTransition {
1053    /// Creates an opacity transition.
1054    pub fn new(opacity: AnimationRef<f64>) -> FadeTransition {
1055        FadeTransition {
1056            key: None,
1057            opacity,
1058            child: None,
1059        }
1060    }
1061
1062    /// Dart `FadeTransition(key:)`.
1063    pub fn key(mut self, key: KeyRef) -> FadeTransition {
1064        self.key = Some(key);
1065        self
1066    }
1067
1068    /// Dart `FadeTransition(child:)`.
1069    #[cfg_attr(debug_assertions, track_caller)]
1070    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> FadeTransition {
1071        self.child = Some(child.into_widget());
1072        self
1073    }
1074}
1075
1076impl RenderObjectWidget for FadeTransition {
1077    type RenderObject = RenderAnimatedOpacity;
1078
1079    fn key(&self) -> Option<&KeyRef> {
1080        self.key.as_ref()
1081    }
1082
1083    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1084        properties.add(DiagnosticsProperty::<String>::new(
1085            "opacity",
1086            Some(self.opacity.to_string(app)),
1087        ));
1088    }
1089
1090    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1091        RenderAnimatedOpacity::new(app, self.opacity.clone(), None).as_object()
1092    }
1093
1094    fn update_render_object(
1095        &self,
1096        app: &mut App,
1097        _context: BuildContext,
1098        render_object: RenderHandle<RenderAnimatedOpacity>,
1099    ) {
1100        render_object.set_opacity(app, self.opacity.clone());
1101    }
1102}
1103
1104impl SingleChildRenderObjectWidget for FadeTransition {
1105    fn child(&self) -> Option<&WidgetRef> {
1106        self.child.as_ref()
1107    }
1108}
1109
1110/// An interpolation between two relative rects.
1111///
1112/// This class specializes the interpolation of `Tween<RelativeRect>` to
1113/// use [`RelativeRect::lerp`].
1114///
1115/// See `Tween` for a discussion on how to use interpolation objects.
1116///
1117/// Unlike the tweens in `waft_animation`, this one is a value rather than an arena
1118/// object: the orphan rule leaves no local type in
1119/// `impl Animatable<RelativeRect> for Ref<RelativeRectTween>`. A driven animation
1120/// therefore holds a clone, and writing [`begin`](Self::begin) or [`end`](Self::end)
1121/// afterwards does not reach it.
1122#[derive(Clone, Debug)]
1123pub struct RelativeRectTween {
1124    /// The value this variable has at the beginning of the animation.
1125    pub begin: Option<RelativeRect>,
1126
1127    /// The value this variable has at the end of the animation.
1128    pub end: Option<RelativeRect>,
1129}
1130
1131impl RelativeRectTween {
1132    /// Creates a [`RelativeRect`] tween.
1133    ///
1134    /// The [`begin`](Self::begin) and [`end`](Self::end) properties may be `None`; the `None`
1135    /// value is treated as [`RelativeRect::FILL`].
1136    pub fn new(begin: Option<RelativeRect>, end: Option<RelativeRect>) -> RelativeRectTween {
1137        RelativeRectTween { begin, end }
1138    }
1139
1140    /// Returns the value this variable has at the given animation clock value.
1141    pub fn lerp(&self, t: f64) -> RelativeRect {
1142        RelativeRect::lerp(self.begin, self.end, t)
1143            .expect("RelativeRectTween.begin or end must be set before use")
1144    }
1145}
1146
1147impl Animatable<RelativeRect> for RelativeRectTween {
1148    fn transform(&self, _app: &App, t: f64) -> RelativeRect {
1149        if t == 0.0 {
1150            return self.begin.expect("Tween.begin must be set before use");
1151        }
1152        if t == 1.0 {
1153            return self.end.expect("Tween.end must be set before use");
1154        }
1155        self.lerp(t)
1156    }
1157}
1158
1159/// Animated version of `Positioned` which takes a specific
1160/// `Animation<RelativeRect>` to transition the child's position from a start
1161/// position to an end position over the lifetime of the animation.
1162///
1163/// Only works if it's the child of a `Stack`.
1164///
1165/// See also:
1166///
1167///  * `AnimatedPositioned`, which transitions a child's position without
1168///    taking an explicit `Animation` argument.
1169///  * [`RelativePositionedTransition`], a widget that transitions its child's
1170///    position based on the value of a rectangle relative to a bounding box.
1171///  * [`SlideTransition`], a widget that animates the position of a widget
1172///    relative to its normal position.
1173///  * [`AlignTransition`], an animated version of an `Align` that animates its
1174///    `Align::alignment` property.
1175///  * [`ScaleTransition`], a widget that animates the scale of a transformed
1176///    widget.
1177///  * [`SizeTransition`], a widget that animates its own size and clips and
1178///    aligns its child.
1179#[derive(Debug)]
1180pub struct PositionedTransition {
1181    /// See [`Widget::key`](crate::Widget::key).
1182    pub key: Option<KeyRef>,
1183
1184    /// The animation that controls the child's size and position.
1185    pub rect: AnimationRef<RelativeRect>,
1186
1187    /// The widget below this widget in the tree.
1188    pub child: WidgetRef,
1189}
1190
1191impl PositionedTransition {
1192    /// Creates a transition for `Positioned`.
1193    #[cfg_attr(debug_assertions, track_caller)]
1194    pub fn new<K>(
1195        rect: AnimationRef<RelativeRect>,
1196        child: impl IntoWidget<K>,
1197    ) -> PositionedTransition {
1198        PositionedTransition {
1199            key: None,
1200            rect,
1201            child: child.into_widget(),
1202        }
1203    }
1204
1205    /// Dart `PositionedTransition(key:)`.
1206    pub fn key(mut self, key: KeyRef) -> PositionedTransition {
1207        self.key = Some(key);
1208        self
1209    }
1210}
1211
1212impl AnimatedWidget for PositionedTransition {
1213    fn key(&self) -> Option<&KeyRef> {
1214        self.key.as_ref()
1215    }
1216
1217    fn listenable(&self) -> Rc<dyn Listenable> {
1218        Rc::new(self.rect.clone())
1219    }
1220
1221    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1222        Positioned::from_relative_rect(self.rect.value(app), self.child.clone()).into_widget()
1223    }
1224}
1225
1226/// Animated version of `Positioned` which transitions the child's position
1227/// based on the value of [`rect`](Self::rect) relative to a bounding box with the
1228/// specified [`size`](Self::size).
1229///
1230/// Only works if it's the child of a `Stack`.
1231///
1232/// See also:
1233///
1234///  * [`PositionedTransition`], a widget that animates its child from a start
1235///    position to an end position over the lifetime of the animation.
1236///  * [`AlignTransition`], an animated version of an `Align` that animates its
1237///    `Align::alignment` property.
1238///  * [`ScaleTransition`], a widget that animates the scale of a transformed
1239///    widget.
1240///  * [`SizeTransition`], a widget that animates its own size and clips and
1241///    aligns its child.
1242///  * [`SlideTransition`], a widget that animates the position of a widget
1243///    relative to its normal position.
1244#[derive(Debug)]
1245pub struct RelativePositionedTransition {
1246    /// See [`Widget::key`](crate::Widget::key).
1247    pub key: Option<KeyRef>,
1248
1249    /// The animation that controls the child's size and position.
1250    ///
1251    /// If the animation returns a `None` [`Rect`], the rect is assumed to be
1252    /// [`Rect::ZERO`].
1253    ///
1254    /// See also:
1255    ///
1256    ///  * [`size`](Self::size), which gets the size of the box that the `Positioned` widget's
1257    ///    offsets are relative to.
1258    pub rect: AnimationRef<Option<Rect>>,
1259
1260    /// The `Positioned` widget's offsets are relative to a box of this
1261    /// size whose origin is 0,0.
1262    pub size: Size,
1263
1264    /// The widget below this widget in the tree.
1265    pub child: WidgetRef,
1266}
1267
1268impl RelativePositionedTransition {
1269    /// Create an animated version of `Positioned`.
1270    ///
1271    /// Each frame, the `Positioned` widget will be configured to represent the
1272    /// current value of the [`rect`](Self::rect) argument assuming that the stack has the
1273    /// given [`size`](Self::size).
1274    #[cfg_attr(debug_assertions, track_caller)]
1275    pub fn new<K>(
1276        rect: AnimationRef<Option<Rect>>,
1277        size: Size,
1278        child: impl IntoWidget<K>,
1279    ) -> RelativePositionedTransition {
1280        RelativePositionedTransition {
1281            key: None,
1282            rect,
1283            size,
1284            child: child.into_widget(),
1285        }
1286    }
1287
1288    /// Dart `RelativePositionedTransition(key:)`.
1289    pub fn key(mut self, key: KeyRef) -> RelativePositionedTransition {
1290        self.key = Some(key);
1291        self
1292    }
1293}
1294
1295impl AnimatedWidget for RelativePositionedTransition {
1296    fn key(&self) -> Option<&KeyRef> {
1297        self.key.as_ref()
1298    }
1299
1300    fn listenable(&self) -> Rc<dyn Listenable> {
1301        Rc::new(self.rect.clone())
1302    }
1303
1304    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1305        let offsets =
1306            RelativeRect::from_size(self.rect.value(app).unwrap_or(Rect::ZERO), self.size);
1307        Positioned::new(self.child.clone())
1308            .top(offsets.top)
1309            .right(offsets.right)
1310            .bottom(offsets.bottom)
1311            .left(offsets.left)
1312            .into_widget()
1313    }
1314}
1315
1316/// Animated version of a [`DecoratedBox`] that animates the different properties
1317/// of its `Decoration`.
1318///
1319/// See also:
1320///
1321///  * [`DecoratedBox`], which also draws a `Decoration` but is not animated.
1322///  * `AnimatedContainer`, a more full-featured container that also animates on
1323///    decoration using an internal animation.
1324#[derive(Debug)]
1325pub struct DecoratedBoxTransition {
1326    /// See [`Widget::key`](crate::Widget::key).
1327    pub key: Option<KeyRef>,
1328
1329    /// Animation of the decoration to paint.
1330    ///
1331    /// Can be created using a `DecorationTween` interpolating typically between
1332    /// two `BoxDecoration`.
1333    pub decoration: AnimationRef<DecorationRef>,
1334
1335    /// Whether to paint the box decoration behind or in front of the child.
1336    pub position: DecorationPosition,
1337
1338    /// The widget below this widget in the tree.
1339    pub child: WidgetRef,
1340}
1341
1342impl DecoratedBoxTransition {
1343    /// Creates an animated [`DecoratedBox`] whose `Decoration` animation updates
1344    /// the widget.
1345    ///
1346    /// See also:
1347    ///
1348    ///  * [`DecoratedBox::new`]
1349    #[cfg_attr(debug_assertions, track_caller)]
1350    pub fn new<K>(
1351        decoration: AnimationRef<DecorationRef>,
1352        child: impl IntoWidget<K>,
1353    ) -> DecoratedBoxTransition {
1354        DecoratedBoxTransition {
1355            key: None,
1356            decoration,
1357            position: DecorationPosition::Background,
1358            child: child.into_widget(),
1359        }
1360    }
1361
1362    /// Dart `DecoratedBoxTransition(key:)`.
1363    pub fn key(mut self, key: KeyRef) -> DecoratedBoxTransition {
1364        self.key = Some(key);
1365        self
1366    }
1367
1368    /// Dart `DecoratedBoxTransition(position:)`.
1369    pub fn position(mut self, position: DecorationPosition) -> DecoratedBoxTransition {
1370        self.position = position;
1371        self
1372    }
1373}
1374
1375impl AnimatedWidget for DecoratedBoxTransition {
1376    fn key(&self) -> Option<&KeyRef> {
1377        self.key.as_ref()
1378    }
1379
1380    fn listenable(&self) -> Rc<dyn Listenable> {
1381        Rc::new(self.decoration.clone())
1382    }
1383
1384    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1385        DecoratedBox::new(self.decoration.value(app))
1386            .position(self.position)
1387            .child(self.child.clone())
1388            .into_widget()
1389    }
1390}
1391
1392/// Animated version of an `Align` that animates its `Align::alignment` property.
1393///
1394/// See also:
1395///
1396///  * `AnimatedAlign`, which animates changes to the [`alignment`](Self::alignment) without
1397///    taking an explicit `Animation` argument.
1398///  * [`PositionedTransition`], a widget that animates its child from a start
1399///    position to an end position over the lifetime of the animation.
1400///  * [`RelativePositionedTransition`], a widget that transitions its child's
1401///    position based on the value of a rectangle relative to a bounding box.
1402///  * [`SizeTransition`], a widget that animates its own size and clips and
1403///    aligns its child.
1404///  * [`SlideTransition`], a widget that animates the position of a widget
1405///    relative to its normal position.
1406#[derive(Debug)]
1407pub struct AlignTransition {
1408    /// See [`Widget::key`](crate::Widget::key).
1409    pub key: Option<KeyRef>,
1410
1411    /// The animation that controls the child's alignment.
1412    pub alignment: AnimationRef<AlignmentGeometry>,
1413
1414    /// If non-`None`, the child's width factor, see `Align::width_factor`.
1415    pub width_factor: Option<f64>,
1416
1417    /// If non-`None`, the child's height factor, see `Align::height_factor`.
1418    pub height_factor: Option<f64>,
1419
1420    /// The widget below this widget in the tree.
1421    pub child: WidgetRef,
1422}
1423
1424impl AlignTransition {
1425    /// Creates an animated `Align` whose [`AlignmentGeometry`] animation updates
1426    /// the widget.
1427    ///
1428    /// See also:
1429    ///
1430    ///  * `Align::new`.
1431    #[cfg_attr(debug_assertions, track_caller)]
1432    pub fn new<K>(
1433        alignment: AnimationRef<AlignmentGeometry>,
1434        child: impl IntoWidget<K>,
1435    ) -> AlignTransition {
1436        AlignTransition {
1437            key: None,
1438            alignment,
1439            width_factor: None,
1440            height_factor: None,
1441            child: child.into_widget(),
1442        }
1443    }
1444
1445    /// Dart `AlignTransition(key:)`.
1446    pub fn key(mut self, key: KeyRef) -> AlignTransition {
1447        self.key = Some(key);
1448        self
1449    }
1450
1451    /// Dart `AlignTransition(widthFactor:)`.
1452    pub fn width_factor(mut self, width_factor: f64) -> AlignTransition {
1453        self.width_factor = Some(width_factor);
1454        self
1455    }
1456
1457    /// Dart `AlignTransition(heightFactor:)`.
1458    pub fn height_factor(mut self, height_factor: f64) -> AlignTransition {
1459        self.height_factor = Some(height_factor);
1460        self
1461    }
1462}
1463
1464impl AnimatedWidget for AlignTransition {
1465    fn key(&self) -> Option<&KeyRef> {
1466        self.key.as_ref()
1467    }
1468
1469    fn listenable(&self) -> Rc<dyn Listenable> {
1470        Rc::new(self.alignment.clone())
1471    }
1472
1473    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1474        let mut align = Align::new().alignment(self.alignment.value(app));
1475        if let Some(width_factor) = self.width_factor {
1476            align = align.width_factor(width_factor);
1477        }
1478        if let Some(height_factor) = self.height_factor {
1479            align = align.height_factor(height_factor);
1480        }
1481        align.child(self.child.clone()).into_widget()
1482    }
1483}
1484
1485/// Animated version of a [`DefaultTextStyle`] that animates the different properties
1486/// of its [`TextStyle`].
1487///
1488/// See also:
1489///
1490///  * `AnimatedDefaultTextStyle`, which animates changes in text style without
1491///    taking an explicit `Animation` argument.
1492///  * [`DefaultTextStyle`], which also defines a [`TextStyle`] for its descendants
1493///    but is not animated.
1494#[derive(Debug)]
1495pub struct DefaultTextStyleTransition {
1496    /// See [`Widget::key`](crate::Widget::key).
1497    pub key: Option<KeyRef>,
1498
1499    /// The animation that controls the descendants' text style.
1500    pub style: AnimationRef<TextStyle>,
1501
1502    /// How the text should be aligned horizontally.
1503    pub text_align: Option<TextAlign>,
1504
1505    /// Whether the text should break at soft line breaks.
1506    ///
1507    /// See [`DefaultTextStyle::soft_wrap`] for more details.
1508    pub soft_wrap: bool,
1509
1510    /// How visual overflow should be handled.
1511    pub overflow: TextOverflow,
1512
1513    /// An optional maximum number of lines for the text to span, wrapping if necessary.
1514    ///
1515    /// See [`DefaultTextStyle::max_lines`] for more details.
1516    pub max_lines: Option<i32>,
1517
1518    /// The widget below this widget in the tree.
1519    pub child: WidgetRef,
1520}
1521
1522impl DefaultTextStyleTransition {
1523    /// Creates an animated [`DefaultTextStyle`] whose [`TextStyle`] animation updates
1524    /// the widget.
1525    #[cfg_attr(debug_assertions, track_caller)]
1526    pub fn new<K>(
1527        style: AnimationRef<TextStyle>,
1528        child: impl IntoWidget<K>,
1529    ) -> DefaultTextStyleTransition {
1530        DefaultTextStyleTransition {
1531            key: None,
1532            style,
1533            text_align: None,
1534            soft_wrap: true,
1535            overflow: TextOverflow::Clip,
1536            max_lines: None,
1537            child: child.into_widget(),
1538        }
1539    }
1540
1541    /// Dart `DefaultTextStyleTransition(key:)`.
1542    pub fn key(mut self, key: KeyRef) -> DefaultTextStyleTransition {
1543        self.key = Some(key);
1544        self
1545    }
1546
1547    /// Dart `DefaultTextStyleTransition(textAlign:)`.
1548    pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyleTransition {
1549        self.text_align = Some(text_align);
1550        self
1551    }
1552
1553    /// Dart `DefaultTextStyleTransition(softWrap:)`.
1554    pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyleTransition {
1555        self.soft_wrap = soft_wrap;
1556        self
1557    }
1558
1559    /// Dart `DefaultTextStyleTransition(overflow:)`.
1560    pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyleTransition {
1561        self.overflow = overflow;
1562        self
1563    }
1564
1565    /// Dart `DefaultTextStyleTransition(maxLines:)`.
1566    pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyleTransition {
1567        self.max_lines = Some(max_lines);
1568        self
1569    }
1570}
1571
1572impl AnimatedWidget for DefaultTextStyleTransition {
1573    fn key(&self) -> Option<&KeyRef> {
1574        self.key.as_ref()
1575    }
1576
1577    fn listenable(&self) -> Rc<dyn Listenable> {
1578        Rc::new(self.style.clone())
1579    }
1580
1581    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1582        let mut default_text_style =
1583            DefaultTextStyle::new(self.style.value(app), self.child.clone())
1584                .soft_wrap(self.soft_wrap)
1585                .overflow(self.overflow);
1586        if let Some(text_align) = self.text_align {
1587            default_text_style = default_text_style.text_align(text_align);
1588        }
1589        if let Some(max_lines) = self.max_lines {
1590            default_text_style = default_text_style.max_lines(max_lines);
1591        }
1592        default_text_style.into_widget()
1593    }
1594}
1595
1596/// A builder that builds a widget given a child.
1597///
1598/// The child is passed into the builder to allow the builder to reuse a widget that does
1599/// not depend on the listenable, as [`ListenableBuilder`] and `AnimatedBuilder` do.
1600pub type TransitionBuilder = Rc<dyn Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef>;
1601
1602/// A general-purpose widget for building a widget subtree when a `Listenable` changes.
1603///
1604/// [`ListenableBuilder`] is useful for more complex widgets that wish to listen to changes in
1605/// other objects as part of a larger build function. To use [`ListenableBuilder`], construct
1606/// the widget and pass it a [`builder`](Self::builder) function.
1607///
1608/// Any subtype of `Listenable` (such as a `ChangeNotifier`, `ValueNotifier`, or `Animation`)
1609/// can be used with a [`ListenableBuilder`] to rebuild only certain parts of a widget when
1610/// the `Listenable` notifies its listeners. Although they have identical implementations, if
1611/// an `Animation` is being listened to, consider using an `AnimatedBuilder` instead for
1612/// better readability.
1613///
1614/// ## Performance optimizations
1615///
1616/// If the [`builder`](Self::builder) function contains a subtree that does not depend on the
1617/// [`listenable`](Self::listenable), it is more efficient to build that subtree once instead
1618/// of rebuilding it on every change of the listenable.
1619///
1620/// Performance is optimized by building the subtree once and passing it as the
1621/// [`child`](Self::child); the builder receives it as its third argument.
1622pub struct ListenableBuilder {
1623    pub key: Option<KeyRef>,
1624    /// The `Listenable` supplied to the constructor.
1625    ///
1626    /// Also accessible through `animation` for an `AnimatedBuilder`.
1627    pub listenable: Rc<dyn Listenable>,
1628    /// Called every time the [`listenable`](Self::listenable) notifies about a change.
1629    ///
1630    /// The child given to the builder should typically be part of the returned widget tree.
1631    pub builder: TransitionBuilder,
1632    /// The child widget to pass to the [`builder`](Self::builder).
1633    ///
1634    /// If a [`builder`](Self::builder) callback's return value contains a subtree that does
1635    /// not depend on the listenable, it's more efficient to build that subtree once instead
1636    /// of rebuilding it on every change of the listenable.
1637    ///
1638    /// If the pre-built subtree is passed as the [`child`](Self::child) parameter, the
1639    /// [`ListenableBuilder`] will pass it back to the [`builder`](Self::builder) function so
1640    /// that it can be incorporated into the build.
1641    ///
1642    /// Using this pre-built child is entirely optional, but can improve performance
1643    /// significantly in some cases and is therefore a good practice.
1644    pub child: Option<WidgetRef>,
1645}
1646
1647/// Dart's `class AnimatedBuilder extends ListenableBuilder`, which only renames the
1648/// listenable `animation`: the same widget.
1649pub type AnimatedBuilder = ListenableBuilder;
1650
1651impl ListenableBuilder {
1652    /// Creates a builder that responds to changes in `listenable`.
1653    pub fn new(
1654        listenable: Rc<dyn Listenable>,
1655        builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
1656    ) -> ListenableBuilder {
1657        ListenableBuilder {
1658            key: None,
1659            listenable,
1660            builder: Rc::new(builder),
1661            child: None,
1662        }
1663    }
1664
1665    /// Dart `ListenableBuilder(key:)`.
1666    pub fn key(mut self, key: KeyRef) -> ListenableBuilder {
1667        self.key = Some(key);
1668        self
1669    }
1670
1671    /// Dart `ListenableBuilder(child:)`.
1672    #[cfg_attr(debug_assertions, track_caller)]
1673    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ListenableBuilder {
1674        self.child = Some(child.into_widget());
1675        self
1676    }
1677
1678    /// The `Listenable` supplied to the constructor (Dart's `AnimatedBuilder.animation`).
1679    pub fn animation(&self) -> Rc<dyn Listenable> {
1680        Rc::clone(&self.listenable)
1681    }
1682}
1683
1684impl Debug for ListenableBuilder {
1685    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1686        f.debug_struct("ListenableBuilder")
1687            .field("child", &self.child)
1688            .finish_non_exhaustive()
1689    }
1690}
1691
1692impl AnimatedWidget for ListenableBuilder {
1693    fn key(&self) -> Option<&KeyRef> {
1694        self.key.as_ref()
1695    }
1696
1697    fn listenable(&self) -> Rc<dyn Listenable> {
1698        Rc::clone(&self.listenable)
1699    }
1700
1701    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1702        (self.builder)(app, context, self.child.as_ref())
1703    }
1704}
1705
1706#[cfg(test)]
1707mod tests {
1708    use std::cell::Cell;
1709    use std::time::Duration;
1710    use waft_animation::Drive;
1711    use waft_foundation::AppCell;
1712    use waft_foundation::Ref;
1713
1714    use waft_animation::{AnimationBehavior, AnimationController, CallbackAnimatable};
1715    use waft_embedder::Color;
1716    use waft_foundation::{ChangeNotifier, ValueNotifier};
1717    use waft_painting::{AnyColor, BoxDecoration};
1718    use waft_rendering::{
1719        BoxConstraints, ContainerRenderObjectMixin, RenderAligningShiftedBox, RenderConstrainedBox,
1720        RenderConstrainedBoxBase, RenderFractionalTranslation, RenderObjectWithChildMixin,
1721        RenderTransform,
1722    };
1723    use waft_scheduler::{Ticker, TickerCallback, TickerProvider};
1724
1725    use super::*;
1726    use crate::framework::LeafRenderObjectWidget;
1727    use crate::test_harness::Harness;
1728    use crate::testing::assert_f32_equals;
1729    use crate::widgets::basic::{Builder, Directionality, SizedBox, Stack};
1730
1731    /// flutter_test's `TestVSync`: vends ordinary tickers, in no view.
1732    struct TestVSync;
1733
1734    impl TickerProvider for TestVSync {
1735        fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1736            Ticker::new(app, on_tick, None)
1737        }
1738    }
1739
1740    /// `SizedBox` in miniature.
1741    #[derive(Debug)]
1742    struct Sized {
1743        size: Size,
1744    }
1745
1746    impl RenderObjectWidget for Sized {
1747        type RenderObject = RenderConstrainedBox;
1748
1749        fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1750            RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
1751        }
1752
1753        fn update_render_object(
1754            &self,
1755            app: &mut App,
1756            _context: BuildContext,
1757            render_object: RenderHandle<RenderConstrainedBox>,
1758        ) {
1759            render_object.set_additional_constraints(app, BoxConstraints::tight(self.size));
1760        }
1761    }
1762
1763    impl LeafRenderObjectWidget for Sized {}
1764
1765    fn new_controller(app: &mut App) -> Ref<AnimationController> {
1766        AnimationController::new(
1767            app,
1768            None,
1769            Some(Duration::from_millis(100)),
1770            None,
1771            0.0,
1772            1.0,
1773            AnimationBehavior::Normal,
1774            TestVSync,
1775        )
1776    }
1777
1778    fn fade(opacity: AnimationRef<f64>) -> WidgetRef {
1779        FadeTransition::new(opacity)
1780            .child(Sized {
1781                size: Size::new(10.0, 10.0),
1782            })
1783            .into_widget()
1784    }
1785
1786    fn fade_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderAnimatedOpacity> {
1787        harness
1788            .render_root(app)
1789            .child(app)
1790            .expect("a child")
1791            .as_object()
1792            .downcast::<RenderAnimatedOpacity>(app)
1793            .expect("a RenderAnimatedOpacity")
1794    }
1795
1796    fn root_child_size(harness: &Harness, app: &App) -> Size {
1797        harness
1798            .render_root(app)
1799            .child(app)
1800            .expect("a child")
1801            .size(app)
1802    }
1803
1804    /// The render object directly under the test root, as `T`.
1805    fn under_root<T: waft_rendering::RenderObject>(
1806        harness: &Harness,
1807        app: &App,
1808    ) -> RenderHandle<T> {
1809        harness
1810            .render_root(app)
1811            .child(app)
1812            .expect("a child")
1813            .as_object()
1814            .downcast::<T>(app)
1815            .expect("the expected render object")
1816    }
1817
1818    /// Under a [`Directionality`], for the widgets that resolve a directional alignment.
1819    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
1820        Directionality::new(TextDirection::Ltr, child).into_widget()
1821    }
1822
1823    fn ten_by_ten() -> Sized {
1824        Sized {
1825            size: Size::new(10.0, 10.0),
1826        }
1827    }
1828
1829    // transitions_test.dart 'SlideTransition transformHitTests'
1830    #[test]
1831    fn a_slide_transition_translates_by_the_animation_and_flips_in_rtl() {
1832        let cell = AppCell::new();
1833        let mut app = cell.borrow_mut();
1834        let controller = new_controller(&mut app);
1835        let position = controller.drive(
1836            &mut app,
1837            CallbackAnimatable::from_callback(|t| Offset::new(t, t * 2.0)),
1838        );
1839        let slide = |text_direction: Option<TextDirection>| {
1840            let mut transition = SlideTransition::new(position.clone())
1841                .transform_hit_tests(false)
1842                .child(ten_by_ten());
1843            if let Some(text_direction) = text_direction {
1844                transition = transition.text_direction(text_direction);
1845            }
1846            transition.into_widget()
1847        };
1848        let harness = Harness::mount(&mut app, slide(None));
1849        harness.pump(&mut app);
1850        controller.set_value(&mut app, 0.5);
1851        harness.pump(&mut app);
1852        let translation: RenderHandle<RenderFractionalTranslation> = under_root(&harness, &app);
1853        assert_eq!(translation.translation(&app), Offset::new(0.5, 1.0));
1854        assert!(!translation.transform_hit_tests(&app));
1855
1856        harness.set_child(&mut app, slide(Some(TextDirection::Rtl)));
1857        harness.pump(&mut app);
1858        assert_eq!(translation.translation(&app), Offset::new(-0.5, 1.0));
1859
1860        harness.set_child(&mut app, slide(Some(TextDirection::Ltr)));
1861        harness.pump(&mut app);
1862        assert_eq!(translation.translation(&app), Offset::new(0.5, 1.0));
1863
1864        controller.dispose(&mut app);
1865    }
1866
1867    // transitions_test.dart 'MatrixTransition animates'
1868    #[test]
1869    fn a_matrix_transition_paints_the_matrix_its_callback_returns() {
1870        let cell = AppCell::new();
1871        let mut app = cell.borrow_mut();
1872        let controller = new_controller(&mut app);
1873        let widget = MatrixTransition::new(controller.erase(), |value| {
1874            Matrix4::translation(value as f32 * 100.0, 0.0)
1875        })
1876        .alignment(Alignment::TOP_LEFT)
1877        .child(ten_by_ten())
1878        .into_widget();
1879        let harness = Harness::mount(&mut app, widget);
1880        harness.pump(&mut app);
1881        let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
1882        assert_eq!(
1883            transform.alignment(&app),
1884            Some(AlignmentGeometry::Alignment(Alignment::TOP_LEFT))
1885        );
1886
1887        controller.set_value(&mut app, 0.5);
1888        harness.pump(&mut app);
1889        let child = transform.child(&app).expect("the sized child");
1890        assert_f32_equals(
1891            child.local_to_global(&app, Offset::ZERO, None),
1892            Offset::new(50.0, 0.0),
1893        );
1894
1895        controller.dispose(&mut app);
1896    }
1897
1898    // transitions_test.dart 'ScaleTransition animates'
1899    #[test]
1900    fn a_scale_transition_scales_about_its_alignment() {
1901        let cell = AppCell::new();
1902        let mut app = cell.borrow_mut();
1903        let controller = new_controller(&mut app);
1904        let widget = ScaleTransition::new(controller.erase())
1905            .child(ten_by_ten())
1906            .into_widget();
1907        let harness = Harness::mount(&mut app, widget);
1908        controller.set_value(&mut app, 0.5);
1909        harness.pump(&mut app);
1910
1911        let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
1912        assert_eq!(
1913            transform.alignment(&app),
1914            Some(AlignmentGeometry::Alignment(Alignment::CENTER))
1915        );
1916        let child = transform.child(&app).expect("the sized child");
1917        // Half size about the 10x10 child's centre: its top-left lands at (2.5, 2.5).
1918        assert_f32_equals(
1919            child.local_to_global(&app, Offset::ZERO, None),
1920            Offset::new(2.5, 2.5),
1921        );
1922
1923        controller.set_value(&mut app, 1.0);
1924        harness.pump(&mut app);
1925        assert_f32_equals(
1926            child.local_to_global(&app, Offset::ZERO, None),
1927            Offset::ZERO,
1928        );
1929
1930        controller.dispose(&mut app);
1931    }
1932
1933    // transitions_test.dart 'RotationTransition animates'
1934    #[test]
1935    fn a_rotation_transition_turns_a_full_circle_per_unit() {
1936        let cell = AppCell::new();
1937        let mut app = cell.borrow_mut();
1938        let controller = new_controller(&mut app);
1939        let widget = RotationTransition::new(controller.erase())
1940            .child(ten_by_ten())
1941            .into_widget();
1942        let harness = Harness::mount(&mut app, widget);
1943        controller.set_value(&mut app, 0.25);
1944        harness.pump(&mut app);
1945
1946        let transform: RenderHandle<RenderTransform> = under_root(&harness, &app);
1947        let child = transform.child(&app).expect("the sized child");
1948        // A quarter turn clockwise about the 10x10 child's centre.
1949        assert_f32_equals(
1950            child.local_to_global(&app, Offset::ZERO, None),
1951            Offset::new(10.0, 0.0),
1952        );
1953
1954        controller.set_value(&mut app, 0.5);
1955        harness.pump(&mut app);
1956        assert_f32_equals(
1957            child.local_to_global(&app, Offset::ZERO, None),
1958            Offset::new(10.0, 10.0),
1959        );
1960
1961        controller.dispose(&mut app);
1962    }
1963
1964    /// Whether a layer of `harness`'s tree is an `ImageFilterLayer` whose filter prints as
1965    /// `ImageFilter.matrix(…)`.
1966    fn has_matrix_filter_layer(harness: &Harness, app: &App) -> bool {
1967        harness.layers(app).into_iter().any(|layer| {
1968            app.handle::<waft_rendering::ImageFilterLayer>(layer.id())
1969                .and_then(|filter_layer| filter_layer.image_filter(app))
1970                .is_some_and(|filter| filter.to_string().starts_with("ImageFilter.matrix("))
1971        })
1972    }
1973
1974    /// transitions_test.dart's 'uses ImageFilter when provided with FilterQuality argument',
1975    /// for the transition `transition` builds over the animation it is handed.
1976    fn uses_an_image_filter_while_animating(
1977        transition: impl FnOnce(AnimationRef<f64>) -> WidgetRef,
1978    ) {
1979        let cell = AppCell::new();
1980        let mut app = cell.borrow_mut();
1981        let controller = new_controller(&mut app);
1982        let animation = waft_animation::Tween::new(&mut app, Some(0.0), Some(1.0))
1983            .animate(&mut app, controller.erase());
1984        let harness = Harness::mount(&mut app, ltr(transition(animation)));
1985        harness.pump(&mut app);
1986
1987        // Validate that expensive layer is not left in tree before animation has started.
1988        assert!(!has_matrix_filter_layer(&harness, &app));
1989
1990        for value in [0.25, 0.5, 0.75] {
1991            controller.set_value(&mut app, value);
1992            harness.pump(&mut app);
1993            assert!(has_matrix_filter_layer(&harness, &app), "at {value}");
1994        }
1995
1996        controller.set_value(&mut app, 1.0);
1997        harness.pump(&mut app);
1998
1999        // Validate that expensive layer is not left in tree after animation has finished.
2000        assert!(!has_matrix_filter_layer(&harness, &app));
2001
2002        controller.dispose(&mut app);
2003    }
2004
2005    #[test]
2006    fn a_matrix_transition_uses_an_image_filter_when_provided_with_a_filter_quality() {
2007        uses_an_image_filter_while_animating(|animation| {
2008            MatrixTransition::new(animation, |_value| Matrix4::IDENTITY)
2009                .filter_quality(FilterQuality::None)
2010                .child(ten_by_ten())
2011                .into_widget()
2012        });
2013    }
2014
2015    #[test]
2016    fn a_scale_transition_uses_an_image_filter_when_provided_with_a_filter_quality() {
2017        uses_an_image_filter_while_animating(|animation| {
2018            ScaleTransition::new(animation)
2019                .filter_quality(FilterQuality::None)
2020                .child(ten_by_ten())
2021                .into_widget()
2022        });
2023    }
2024
2025    #[test]
2026    fn a_rotation_transition_uses_an_image_filter_when_provided_with_a_filter_quality() {
2027        uses_an_image_filter_while_animating(|animation| {
2028            RotationTransition::new(animation)
2029                .filter_quality(FilterQuality::None)
2030                .child(ten_by_ten())
2031                .into_widget()
2032        });
2033    }
2034
2035    // transitions_test.dart 'SizeTransition clamps negative size factors'
2036    #[test]
2037    fn a_size_transition_clips_its_child_to_the_size_factor() {
2038        let cell = AppCell::new();
2039        let mut app = cell.borrow_mut();
2040        let controller = new_controller(&mut app);
2041        let widget = SizeTransition::new(controller.erase())
2042            .child(ten_by_ten())
2043            .into_widget();
2044        let harness = Harness::mount(&mut app, ltr(widget));
2045        harness.pump(&mut app);
2046        let clip: RenderHandle<waft_rendering::RenderClipRect> = under_root(&harness, &app);
2047        assert_eq!(clip.size(&app).height(), 0.0);
2048
2049        controller.set_value(&mut app, 0.5);
2050        harness.pump(&mut app);
2051        assert_eq!(clip.size(&app).height(), 5.0);
2052        assert_eq!(
2053            clip.size(&app).width(),
2054            crate::test_harness::VIEW_WIDTH,
2055            "the cross axis is as large as the parent"
2056        );
2057
2058        controller.set_value(&mut app, 1.0);
2059        harness.pump(&mut app);
2060        assert_eq!(clip.size(&app).height(), 10.0);
2061
2062        controller.dispose(&mut app);
2063    }
2064
2065    #[test]
2066    fn a_horizontal_size_transition_fixes_its_cross_axis_factor() {
2067        let cell = AppCell::new();
2068        let mut app = cell.borrow_mut();
2069        let controller = new_controller(&mut app);
2070        let widget = SizeTransition::new(controller.erase())
2071            .axis(Axis::Horizontal)
2072            .fixed_cross_axis_size_factor(1.0)
2073            .child(ten_by_ten())
2074            .into_widget();
2075        let harness = Harness::mount(&mut app, ltr(widget));
2076        controller.set_value(&mut app, 0.5);
2077        harness.pump(&mut app);
2078        let clip: RenderHandle<waft_rendering::RenderClipRect> = under_root(&harness, &app);
2079        assert_eq!(clip.size(&app), Size::new(5.0, 10.0));
2080
2081        controller.dispose(&mut app);
2082    }
2083
2084    // transitions_test.dart 'PositionedTransition animates'
2085    #[test]
2086    fn a_positioned_transition_places_its_child_by_the_relative_rect() {
2087        let cell = AppCell::new();
2088        let mut app = cell.borrow_mut();
2089        let controller = new_controller(&mut app);
2090        let tween = RelativeRectTween::new(
2091            Some(RelativeRect::from_ltrb(0.0, 0.0, 200.0, 100.0)),
2092            Some(RelativeRect::from_ltrb(100.0, 50.0, 0.0, 0.0)),
2093        );
2094        let rect = controller.drive(&mut app, tween);
2095        let widget = Stack::new()
2096            .children([PositionedTransition::new(rect.clone(), ten_by_ten()).into_widget()])
2097            .into_widget();
2098        let harness = Harness::mount(&mut app, ltr(widget));
2099        controller.set_value(&mut app, 0.5);
2100        harness.pump(&mut app);
2101
2102        let stack: RenderHandle<waft_rendering::RenderStack> = under_root(&harness, &app);
2103        let child = stack.first_child(&app).expect("the positioned child");
2104        assert_f32_equals(
2105            child.local_to_global(&app, Offset::ZERO, None),
2106            Offset::new(50.0, 25.0),
2107        );
2108        assert_eq!(child.size(&app), Size::new(150.0, 125.0));
2109
2110        controller.dispose(&mut app);
2111    }
2112
2113    // transitions_test.dart 'RelativePositionedTransition animates'
2114    #[test]
2115    fn a_relative_positioned_transition_places_its_child_inside_the_given_size() {
2116        let cell = AppCell::new();
2117        let mut app = cell.borrow_mut();
2118        let controller = new_controller(&mut app);
2119        let rect = controller.drive(
2120            &mut app,
2121            CallbackAnimatable::from_callback(|t| {
2122                Some(Rect::from_ltwh(t * 40.0, t * 20.0, 30.0, 15.0))
2123            }),
2124        );
2125        let widget = Stack::new()
2126            .children([RelativePositionedTransition::new(
2127                rect.clone(),
2128                Size::new(100.0, 100.0),
2129                ten_by_ten(),
2130            )
2131            .into_widget()])
2132            .into_widget();
2133        let harness = Harness::mount(&mut app, ltr(widget));
2134        controller.set_value(&mut app, 0.5);
2135        harness.pump(&mut app);
2136
2137        let stack: RenderHandle<waft_rendering::RenderStack> = under_root(&harness, &app);
2138        let child = stack.first_child(&app).expect("the positioned child");
2139        // The rect (20, 10, 50, 25) inside a 100x100 box, applied to the 300x200 stack.
2140        assert_f32_equals(
2141            child.local_to_global(&app, Offset::ZERO, None),
2142            Offset::new(20.0, 10.0),
2143        );
2144        assert_eq!(
2145            child.size(&app),
2146            Size::new(
2147                crate::test_harness::VIEW_WIDTH - 20.0 - 50.0,
2148                crate::test_harness::VIEW_HEIGHT - 10.0 - 75.0,
2149            )
2150        );
2151
2152        controller.dispose(&mut app);
2153    }
2154
2155    // transitions_test.dart 'DecoratedBoxTransition test'
2156    #[test]
2157    fn a_decorated_box_transition_hands_the_animated_decoration_to_its_render_object() {
2158        let cell = AppCell::new();
2159        let mut app = cell.borrow_mut();
2160        let controller = new_controller(&mut app);
2161        let decoration = controller.drive(
2162            &mut app,
2163            CallbackAnimatable::from_callback(|t| {
2164                DecorationRef::new(BoxDecoration::new().color(Color::from_argb(
2165                    (t * 255.0).round() as i32,
2166                    0,
2167                    0,
2168                    0,
2169                )))
2170            }),
2171        );
2172        let widget = DecoratedBoxTransition::new(decoration.clone(), ten_by_ten())
2173            .position(DecorationPosition::Foreground)
2174            .into_widget();
2175        let harness = Harness::mount(&mut app, widget);
2176        controller.set_value(&mut app, 0.5);
2177        harness.pump(&mut app);
2178
2179        let decorated: RenderHandle<waft_rendering::RenderDecoratedBox> =
2180            under_root(&harness, &app);
2181        assert_eq!(decorated.position(&app), DecorationPosition::Foreground);
2182        let painted = decorated
2183            .decoration(&app)
2184            .as_any()
2185            .downcast_ref::<BoxDecoration>()
2186            .expect("a BoxDecoration");
2187        assert_eq!(
2188            painted.color.as_ref().map(AnyColor::color),
2189            Some(Color::from_argb(128, 0, 0, 0))
2190        );
2191
2192        controller.dispose(&mut app);
2193    }
2194
2195    // transitions_test.dart 'AlignTransition animates'
2196    #[test]
2197    fn an_align_transition_hands_the_animated_alignment_to_its_render_object() {
2198        let cell = AppCell::new();
2199        let mut app = cell.borrow_mut();
2200        let controller = new_controller(&mut app);
2201        let alignment = controller.drive(
2202            &mut app,
2203            CallbackAnimatable::from_callback(|t| AlignmentGeometry::xy(t, -t)),
2204        );
2205        let widget = AlignTransition::new(alignment.clone(), ten_by_ten())
2206            .width_factor(2.0)
2207            .height_factor(3.0)
2208            .into_widget();
2209        let harness = Harness::mount(&mut app, widget);
2210        controller.set_value(&mut app, 0.5);
2211        harness.pump(&mut app);
2212
2213        let positioned: RenderHandle<waft_rendering::RenderPositionedBox> =
2214            under_root(&harness, &app);
2215        assert_eq!(
2216            RenderAligningShiftedBox::alignment(positioned, &app),
2217            AlignmentGeometry::xy(0.5, -0.5)
2218        );
2219        assert_eq!(positioned.width_factor(&app), Some(2.0));
2220        assert_eq!(positioned.height_factor(&app), Some(3.0));
2221        assert_eq!(positioned.size(&app), Size::new(20.0, 30.0));
2222
2223        controller.dispose(&mut app);
2224    }
2225
2226    // transitions_test.dart 'DefaultTextStyleTransition test'
2227    #[test]
2228    fn a_default_text_style_transition_publishes_the_animated_style() {
2229        let cell = AppCell::new();
2230        let mut app = cell.borrow_mut();
2231        let controller = new_controller(&mut app);
2232        let style = controller.drive(
2233            &mut app,
2234            CallbackAnimatable::from_callback(|t| TextStyle::new().font_size(10.0 + t * 10.0)),
2235        );
2236        let seen: Rc<Cell<f64>> = Rc::new(Cell::new(0.0));
2237        let child = Builder {
2238            key: None,
2239            builder: Rc::new({
2240                let seen = Rc::clone(&seen);
2241                move |app, context| {
2242                    let default = DefaultTextStyle::of(app, context);
2243                    seen.set(default.style.font_size.expect("a font size"));
2244                    ten_by_ten().into_widget()
2245                }
2246            }),
2247        };
2248        let widget = DefaultTextStyleTransition::new(style.clone(), child)
2249            .max_lines(3)
2250            .overflow(TextOverflow::Ellipsis)
2251            .soft_wrap(false)
2252            .into_widget();
2253        let harness = Harness::mount(&mut app, widget);
2254        controller.set_value(&mut app, 0.5);
2255        harness.pump(&mut app);
2256        assert_eq!(seen.get(), 15.0);
2257
2258        controller.set_value(&mut app, 1.0);
2259        harness.pump(&mut app);
2260        assert_eq!(seen.get(), 20.0);
2261
2262        controller.dispose(&mut app);
2263    }
2264
2265    // transitions_test.dart 'FadeTransition animates'
2266    #[test]
2267    fn a_fade_transition_hands_its_animation_to_the_render_object() {
2268        let cell = AppCell::new();
2269        let mut app = cell.borrow_mut();
2270        let controller = new_controller(&mut app);
2271        let harness = Harness::mount(&mut app, fade(controller.erase()));
2272        harness.pump(&mut app);
2273        let render_object = fade_under_root(&harness, &app);
2274        assert_eq!(render_object.opacity(&app), controller.view());
2275        assert_eq!(render_object.opacity(&app).value(&app), 0.0);
2276        assert!(
2277            !render_object.as_object().is_repaint_boundary(&app),
2278            "fully transparent"
2279        );
2280
2281        for value in [0.25, 0.5, 0.75, 1.0] {
2282            controller.set_value(&mut app, value);
2283            harness.pump(&mut app);
2284            assert_eq!(render_object.opacity(&app).value(&app), value);
2285        }
2286        assert!(
2287            render_object.as_object().is_repaint_boundary(&app),
2288            "the render object heard the controller"
2289        );
2290
2291        let other = new_controller(&mut app);
2292        harness.set_child(&mut app, fade(other.erase()));
2293        harness.pump(&mut app);
2294        assert_eq!(
2295            fade_under_root(&harness, &app),
2296            render_object,
2297            "reconfigured in place"
2298        );
2299        assert_eq!(render_object.opacity(&app), other.view());
2300
2301        controller.dispose(&mut app);
2302        other.dispose(&mut app);
2303    }
2304
2305    /// An animated widget sized by a notifier's value.
2306    #[derive(Debug)]
2307    struct Grower {
2308        notifier: Ref<ValueNotifier<f64>>,
2309        builds: Rc<Cell<u32>>,
2310    }
2311
2312    impl AnimatedWidget for Grower {
2313        fn listenable(&self) -> Rc<dyn Listenable> {
2314            Rc::new(self.notifier.clone())
2315        }
2316
2317        fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
2318            self.builds.set(self.builds.get() + 1);
2319            let width = *app.get(&self.notifier).value();
2320            Sized {
2321                size: Size::new(width, 10.0),
2322            }
2323            .into_widget()
2324        }
2325    }
2326
2327    fn has_listeners(app: &App, notifier: Handle<ValueNotifier<f64>>) -> bool {
2328        app.get(notifier).change_notifier_data().has_listeners()
2329    }
2330
2331    #[test]
2332    fn an_animated_widget_rebuilds_when_its_listenable_notifies() {
2333        let cell = AppCell::new();
2334        let mut app = cell.borrow_mut();
2335        let notifier = app.create(ValueNotifier::new(10.0));
2336        let builds = Rc::new(Cell::new(0));
2337        let harness = Harness::mount(
2338            &mut app,
2339            Grower {
2340                notifier: notifier.clone(),
2341                builds: Rc::clone(&builds),
2342            }
2343            .into_widget(),
2344        );
2345        harness.pump(&mut app);
2346        assert_eq!(builds.get(), 1);
2347        assert!(has_listeners(&app, notifier.handle()));
2348        assert_eq!(root_child_size(&harness, &app), Size::new(10.0, 10.0));
2349
2350        notifier.set_value(&mut app, 20.0);
2351        assert_eq!(builds.get(), 1, "rebuilt at the next frame, not inline");
2352        harness.pump(&mut app);
2353        assert_eq!(builds.get(), 2);
2354        assert_eq!(root_child_size(&harness, &app), Size::new(20.0, 10.0));
2355    }
2356
2357    #[test]
2358    fn an_animated_widget_follows_a_new_listenable_and_unsubscribes_on_unmount() {
2359        let cell = AppCell::new();
2360        let mut app = cell.borrow_mut();
2361        let first = app.create(ValueNotifier::new(10.0));
2362        let second = app.create(ValueNotifier::new(30.0));
2363        let builds = Rc::new(Cell::new(0));
2364        let grower = |notifier| {
2365            Grower {
2366                notifier,
2367                builds: Rc::clone(&builds),
2368            }
2369            .into_widget()
2370        };
2371        let harness = Harness::mount(&mut app, grower(first.clone()));
2372        harness.pump(&mut app);
2373
2374        harness.set_child(&mut app, grower(second.clone()));
2375        harness.pump(&mut app);
2376        assert!(
2377            !has_listeners(&app, first.handle()),
2378            "did_update_widget left the old listenable"
2379        );
2380        assert!(has_listeners(&app, second.handle()));
2381        assert_eq!(root_child_size(&harness, &app), Size::new(30.0, 10.0));
2382
2383        harness.set_child(
2384            &mut app,
2385            Sized {
2386                size: Size::new(5.0, 5.0),
2387            }
2388            .into_widget(),
2389        );
2390        harness.pump(&mut app);
2391        assert!(
2392            !has_listeners(&app, second.handle()),
2393            "dispose removed the listener"
2394        );
2395        let builds_before = builds.get();
2396        second.set_value(&mut app, 40.0);
2397        harness.pump(&mut app);
2398        assert_eq!(
2399            builds.get(),
2400            builds_before,
2401            "a disposed state never builds again"
2402        );
2403    }
2404
2405    #[test]
2406    fn a_listenable_builder_rebuilds_on_notify_and_hands_back_its_child() {
2407        let cell = AppCell::new();
2408        let mut app = cell.borrow_mut();
2409        let notifier = app.create(ValueNotifier::new(0i32));
2410        let builds = Rc::new(Cell::new(0));
2411        let child: WidgetRef = SizedBox::square(Some(4.0)).into_widget();
2412        let same_child = Rc::new(Cell::new(true));
2413        let widget = AnimatedBuilder::new(Rc::new(notifier.clone()), {
2414            let builds = Rc::clone(&builds);
2415            let same_child = Rc::clone(&same_child);
2416            let child = child.clone();
2417            move |_app, _context, passed| {
2418                builds.set(builds.get() + 1);
2419                same_child.set(passed.is_some_and(|passed| Rc::ptr_eq(passed, &child)));
2420                passed.expect("the child is passed back").clone()
2421            }
2422        })
2423        .child(child.clone());
2424        let harness = Harness::mount(&mut app, widget.into_widget());
2425        harness.pump(&mut app);
2426        assert_eq!(builds.get(), 1);
2427        assert!(same_child.get());
2428
2429        notifier.set_value(&mut app, 1);
2430        harness.pump(&mut app);
2431        assert_eq!(builds.get(), 2);
2432    }
2433}