Skip to main content

cranpose_ui/
animate_content_size.rs

1//! `Modifier::animate_content_size`: a size that follows its content's.
2//!
3//! Mirrors Jetpack Compose's `Modifier.animateContentSize`. The node
4//! measures its content at the constraints it gets, then reports a size that
5//! animates toward the content's, so a parent lays out again while the size
6//! moves.
7
8use std::{
9    cell::RefCell,
10    hash::{Hash, Hasher},
11};
12
13use cranpose_animation::{Animatable, AnimationType, Spring, spring};
14use cranpose_core::{RuntimeHandle, current_runtime_handle};
15use cranpose_foundation::{
16    Constraints, DelegatableNode, InvalidationKind, LayoutModifierNode, Measurable, ModifierNode,
17    ModifierNodeContext, ModifierNodeElement, NodeCapabilities, NodeState,
18};
19use cranpose_ui_graphics::Size;
20use cranpose_ui_layout::{LayoutDirection, LayoutModifierMeasureResult, round_to_px};
21
22use crate::modifier::{Modifier, inspector_metadata};
23
24impl Modifier {
25    /// Animates the size of this modifier when the size of its content
26    /// changes: the parent sees a size that moves to the new one, and the
27    /// content is clipped to it. The content shows at the start of the
28    /// animating size. The first size the content has appears without an
29    /// animation. A change of the content while the size moves retargets the
30    /// animation from the size that shows.
31    ///
32    /// Mirrors Jetpack Compose: `Modifier.animateContentSize()`, whose default
33    /// animation is a spring of medium-low stiffness that does not bounce.
34    /// The finished listener is absent.
35    pub fn animate_content_size(self) -> Self {
36        self.animate_content_size_with(spring(
37            Spring::DampingRatioNoBouncy,
38            Spring::StiffnessMediumLow,
39        ))
40    }
41
42    /// [`animate_content_size`](Self::animate_content_size) that animates with
43    /// `animation`: Compose's `animationSpec` argument.
44    pub fn animate_content_size_with(self, animation: AnimationType) -> Self {
45        let element = SizeAnimationElement {
46            animation,
47            direction: crate::layout_direction::layout_direction(),
48            runtime: current_runtime_handle(),
49        };
50        let modifier = Self::with_element(element).with_inspector_metadata(inspector_metadata(
51            "animateContentSize",
52            move |info| {
53                info.add_property("animationSpec", format!("{animation:?}"));
54            },
55        ));
56        self.clip_to_bounds().then(modifier)
57    }
58}
59
60// Equal to another with the same animation and layout direction: the runtime
61// is where the animation runs, which a modifier built in one composition has
62// the whole time.
63#[derive(Clone)]
64struct SizeAnimationElement {
65    animation: AnimationType,
66    direction: LayoutDirection,
67    runtime: Option<RuntimeHandle>,
68}
69
70impl std::fmt::Debug for SizeAnimationElement {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("SizeAnimationElement")
73            .field("animation", &self.animation)
74            .field("direction", &self.direction)
75            .finish_non_exhaustive()
76    }
77}
78
79impl PartialEq for SizeAnimationElement {
80    fn eq(&self, other: &Self) -> bool {
81        self.animation == other.animation && self.direction == other.direction
82    }
83}
84
85impl Hash for SizeAnimationElement {
86    fn hash<H: Hasher>(&self, state: &mut H) {
87        std::mem::discriminant(&self.animation).hash(state);
88        self.direction.hash(state);
89    }
90}
91
92impl ModifierNodeElement for SizeAnimationElement {
93    type Node = SizeAnimationNode;
94
95    fn create(&self) -> Self::Node {
96        SizeAnimationNode {
97            animation: self.animation,
98            direction: self.direction,
99            runtime: self.runtime.clone(),
100            size: RefCell::new(None),
101            state: NodeState::new(),
102        }
103    }
104
105    fn update(&self, node: &mut Self::Node) {
106        node.animation = self.animation;
107        node.direction = self.direction;
108    }
109
110    fn capabilities(&self) -> NodeCapabilities {
111        NodeCapabilities::LAYOUT
112    }
113}
114
115struct SizeAnimationNode {
116    animation: AnimationType,
117    direction: LayoutDirection,
118    runtime: Option<RuntimeHandle>,
119    // The size that shows, from the first measure on.
120    size: RefCell<Option<Animatable<Size>>>,
121    state: NodeState,
122}
123
124impl SizeAnimationNode {
125    // The size that shows for content of size `target`: it starts at the
126    // first size the content has and moves to each new one, a whole number of
127    // device pixels short of it.
128    fn shown(&self, target: Size, density: f32) -> Size {
129        let animatable = {
130            let mut size = self.size.borrow_mut();
131            if size.is_none() {
132                let runtime = self.runtime.clone().or_else(current_runtime_handle);
133                *size = runtime.map(|runtime| Animatable::new(target, runtime));
134            }
135            size.clone()
136        };
137        let Some(mut animatable) = animatable else {
138            return target;
139        };
140        if animatable.target() != target {
141            animatable.animateTo(target, self.animation);
142        }
143        let value = animatable.state().value();
144        Size::new(
145            target.width - round_to_px(target.width - value.width, density),
146            target.height - round_to_px(target.height - value.height, density),
147        )
148    }
149}
150
151impl DelegatableNode for SizeAnimationNode {
152    fn node_state(&self) -> &NodeState {
153        &self.state
154    }
155}
156
157impl ModifierNode for SizeAnimationNode {
158    fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
159        Some(self)
160    }
161
162    // A node that a recycled item reuses starts at the first size of its new
163    // content.
164    fn on_reset(&mut self) {
165        self.size.get_mut().take();
166    }
167
168    fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
169        Some(self)
170    }
171
172    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
173        context.invalidate(InvalidationKind::Layout);
174    }
175}
176
177impl LayoutModifierNode for SizeAnimationNode {
178    fn measure(
179        &self,
180        context: &mut dyn ModifierNodeContext,
181        measurable: &dyn Measurable,
182        constraints: Constraints,
183    ) -> LayoutModifierMeasureResult {
184        let placeable = measurable.measure(constraints);
185        let target = Size::new(placeable.width(), placeable.height());
186        let shown = self.shown(target, context.density());
187        let (width, height) = constraints.constrain(shown.width, shown.height);
188        // The content starts where the layout starts: at the right edge in a
189        // right-to-left layout.
190        let x = self.direction.place_x(0.0, width, target.width);
191        LayoutModifierMeasureResult::new(Size::new(width, height), x, 0.0)
192    }
193}