Skip to main content

repose_core/
shared.rs

1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5use crate::animation::{AnimatedValue, AnimationSpec};
6use crate::animation_driver;
7use crate::geometry::Rect;
8use crate::request_frame;
9use crate::runtime::{ComposerSlots, replace_composer_slots};
10use crate::scope::Scope;
11use crate::scope_cache::with_scope_key;
12use crate::view::View;
13
14static NEXT_MOVABLE_ID: AtomicU64 = AtomicU64::new(0);
15
16/// State-preserving content that can move between composition locations.
17///
18/// Create one [`MovableContent::new`] and keep the handle alive (in
19/// `remember`, a `remember_mutable`, or a field), then call
20/// [`invoke`](Self::invoke) at the location where it should compose.
21/// Remembered state inside the content follows the handle instead of the call
22/// site, so moving the invocation preserves it.
23pub struct MovableContent<T: 'static> {
24    inner: Rc<MovableInner<T>>,
25}
26
27struct MovableInner<T: 'static> {
28    content: Box<dyn Fn(T) -> View>,
29    scope: Scope,
30    key: String,
31    slots: RefCell<ComposerSlots>,
32}
33
34impl<T: 'static> MovableContent<T> {
35    pub fn new(content: impl Fn(T) -> View + 'static) -> Self {
36        let id = NEXT_MOVABLE_ID.fetch_add(1, Ordering::Relaxed);
37        Self {
38            inner: Rc::new(MovableInner {
39                content: Box::new(content),
40                scope: Scope::new(),
41                key: format!("movable:{id}"),
42                slots: RefCell::new(ComposerSlots::default()),
43            }),
44        }
45    }
46
47    pub fn invoke(&self, value: T) -> View {
48        let inner = &*self.inner;
49        let content = &inner.content;
50        let key = inner.key.as_str();
51        let slots = &mut *inner.slots.borrow_mut();
52        with_own_slots(slots, || {
53            inner.scope.run(|| with_scope_key(key, || content(value)))
54        })
55    }
56}
57
58impl<T: 'static> Clone for MovableContent<T> {
59    fn clone(&self) -> Self {
60        Self {
61            inner: self.inner.clone(),
62        }
63    }
64}
65
66impl<T: 'static> Drop for MovableInner<T> {
67    fn drop(&mut self) {
68        self.scope.clone().dispose();
69    }
70}
71
72fn with_own_slots<R>(target: &mut ComposerSlots, f: impl FnOnce() -> R) -> R {
73    target.cursor = 0;
74    target.auto_counts.clear();
75    let outer = replace_composer_slots(std::mem::take(target));
76    struct Restore<'a> {
77        target: &'a mut ComposerSlots,
78        outer: Option<ComposerSlots>,
79    }
80    impl Drop for Restore<'_> {
81        fn drop(&mut self) {
82            let outer = self.outer.take().expect("movable slots restored twice");
83            let mut inner = replace_composer_slots(outer);
84            inner.slots.truncate(inner.cursor);
85            inner.slot_callers.truncate(inner.cursor);
86            *self.target = inner;
87        }
88    }
89    let _restore = Restore {
90        target,
91        outer: Some(outer),
92    };
93    f()
94}
95
96static NEXT_SHARED_ID: AtomicU64 = AtomicU64::new(0);
97
98/// Identity and bounds animation shared by one or more elements.
99///
100/// Attach it with [`Modifier::shared_element`](crate::Modifier::shared_element).
101/// When the node that owns the state changes location, or a different node
102/// claims the same state, the painted element eases from the last bounds to the
103/// new layout bounds. When several nodes claim one state in a frame, the last
104/// painted one drives the transition and the others are not painted.
105#[derive(Clone)]
106pub struct SharedElementState {
107    inner: Rc<SharedElementInner>,
108}
109
110struct SharedElementInner {
111    id: u64,
112    spec: AnimationSpec,
113    animation: RefCell<AnimatedValue<Rect>>,
114    target: Cell<Rect>,
115    known: Cell<bool>,
116    tick_key: String,
117}
118
119impl SharedElementState {
120    pub fn new() -> Self {
121        Self::with_spec(AnimationSpec::spring_gentle())
122    }
123
124    pub fn with_spec(spec: AnimationSpec) -> Self {
125        let id = NEXT_SHARED_ID.fetch_add(1, Ordering::Relaxed);
126        Self {
127            inner: Rc::new(SharedElementInner {
128                id,
129                spec,
130                animation: RefCell::new(AnimatedValue::new(Rect::default(), spec)),
131                target: Cell::new(Rect::default()),
132                known: Cell::new(false),
133                tick_key: format!("shared_element:{id}"),
134            }),
135        }
136    }
137
138    pub fn id(&self) -> u64 {
139        self.inner.id
140    }
141
142    #[doc(hidden)]
143    pub fn prepare(&self, bounds: Rect) -> Rect {
144        let inner = &*self.inner;
145        if !inner.known.replace(true) {
146            let mut animation = inner.animation.borrow_mut();
147            *animation = AnimatedValue::new(bounds, inner.spec);
148            inner.target.set(bounds);
149            return bounds;
150        }
151
152        if !rect_close(inner.target.get(), bounds) {
153            inner.target.set(bounds);
154            let mut animation = inner.animation.borrow_mut();
155            animation.set_target(bounds);
156            drop(animation);
157            self.register_tick();
158        }
159
160        let animation = inner.animation.borrow();
161        let current = *animation.get();
162        let animating = animation.is_animating();
163        drop(animation);
164        if animating {
165            request_frame();
166        }
167        current
168    }
169
170    #[doc(hidden)]
171    pub fn is_animating(&self) -> bool {
172        self.inner.animation.borrow().is_animating()
173    }
174
175    fn register_tick(&self) {
176        let inner = self.inner.clone();
177        let key = self.inner.tick_key.clone();
178        animation_driver::register(
179            key,
180            Rc::new(RefCell::new(move || {
181                let still = inner.animation.borrow_mut().update();
182                if still {
183                    request_frame();
184                }
185                still
186            })),
187        );
188    }
189}
190
191impl Default for SharedElementState {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197fn rect_close(a: Rect, b: Rect) -> bool {
198    (a.x - b.x).abs() <= 0.01
199        && (a.y - b.y).abs() <= 0.01
200        && (a.w - b.w).abs() <= 0.01
201        && (a.h - b.h).abs() <= 0.01
202}