Skip to main content

freya_components/
portal.rs

1use std::{
2    collections::HashMap,
3    fmt::Debug,
4    hash::{
5        DefaultHasher,
6        Hash,
7        Hasher,
8    },
9    time::Duration,
10};
11
12use freya_animation::prelude::*;
13use freya_core::{
14    prelude::*,
15    scope_id::ScopeId,
16};
17use torin::{
18    prelude::{
19        Area,
20        Point2D,
21        Position,
22        Size2D,
23    },
24    size::Size,
25};
26
27#[derive(PartialEq)]
28pub struct Portal<T> {
29    key: DiffKey,
30    children: Vec<Element>,
31    id: T,
32    function: Function,
33    duration: Duration,
34    ease: Ease,
35    layout: LayoutData,
36    show: bool,
37    dependency: Option<u64>,
38}
39
40impl<T> ChildrenExt for Portal<T> {
41    fn children_mut(&mut self) -> &mut Vec<Element> {
42        &mut self.children
43    }
44}
45
46impl<T> Portal<T> {
47    pub fn new(id: T) -> Self {
48        Self {
49            key: DiffKey::None,
50            children: vec![],
51            id,
52            function: Function::default(),
53            duration: Duration::from_millis(750),
54            ease: Ease::default(),
55            layout: LayoutData::default(),
56            show: true,
57            dependency: None,
58        }
59    }
60
61    /// Set the easing function. See `Function` for all the types.
62    pub fn function(mut self, function: impl Into<Function>) -> Self {
63        self.function = function.into();
64        self
65    }
66
67    pub fn duration(mut self, duration: Duration) -> Self {
68        self.duration = duration;
69        self
70    }
71
72    pub fn ease(mut self, ease: Ease) -> Self {
73        self.ease = ease;
74        self
75    }
76
77    pub fn show(mut self, show: bool) -> Self {
78        self.show = show;
79        self
80    }
81
82    /// Only animate when this value changes, other layout changes move the portal instantly.
83    pub fn animation_dependency(mut self, dependency: impl Hash) -> Self {
84        let mut hasher = DefaultHasher::default();
85        dependency.hash(&mut hasher);
86        self.dependency = Some(hasher.finish());
87        self
88    }
89}
90
91impl<T> LayoutExt for Portal<T> {
92    fn layout_mut(&mut self) -> &mut LayoutData {
93        &mut self.layout
94    }
95}
96
97impl<T> ContainerSizeExt for Portal<T> {}
98
99impl<T> KeyExt for Portal<T> {
100    fn key_mut(&mut self) -> &mut DiffKey {
101        &mut self.key
102    }
103}
104
105impl<T: Clone + Eq + Hash + Debug + 'static> Component for Portal<T> {
106    fn render(&self) -> impl IntoElement {
107        let mut positions = use_hook(|| match try_consume_context::<PortalsMap<T>>() {
108            Some(ctx) => ctx,
109            None => {
110                let ctx = PortalsMap {
111                    ids: State::create_in_scope(HashMap::default(), ScopeId::ROOT),
112                };
113                provide_context_for_scope_id(ctx.clone(), ScopeId::ROOT);
114                ctx
115            }
116        });
117        let id = self.id.clone();
118        let dependency = self.dependency;
119        // Area left by the previous mount of this same portal
120        let init_size = use_hook(move || {
121            positions
122                .ids
123                .write()
124                .remove(&id)
125                .filter(|(_, last)| dependency.is_none() || *last != dependency)
126                .map(|(area, _)| area)
127        });
128        let mut previous_size = use_state::<Option<Area>>(|| None);
129        let mut current_size = use_state::<Option<Area>>(|| None);
130        let mut last_dependency = use_state::<Option<u64>>(|| None);
131        let mut should_animate = use_state(|| false);
132
133        let mut animation = use_animation_with_dependencies(
134            &(
135                self.function,
136                self.duration,
137                self.ease,
138                previous_size(),
139                current_size(),
140            ),
141            move |conf, (function, duration, ease, previous_size, current_size)| {
142                conf.on_change(OnChange::Nothing);
143                let from_size = previous_size.or(init_size).unwrap_or_default();
144                let to_size = current_size.unwrap_or_default();
145                (
146                    AnimNum::new(from_size.origin.x, to_size.origin.x)
147                        .duration(*duration)
148                        .ease(*ease)
149                        .function(*function),
150                    AnimNum::new(from_size.origin.y, to_size.origin.y)
151                        .duration(*duration)
152                        .ease(*ease)
153                        .function(*function),
154                    AnimNum::new(from_size.size.width, to_size.size.width)
155                        .duration(*duration)
156                        .ease(*ease)
157                        .function(*function),
158                    AnimNum::new(from_size.size.height, to_size.size.height)
159                        .duration(*duration)
160                        .ease(*ease)
161                        .function(*function),
162                )
163            },
164        );
165
166        // Rest the portal once the animation stops
167        use_hook(move || {
168            Effect::create_sync(move || {
169                if !*animation.is_running().read() {
170                    should_animate.set_if_modified(false);
171                }
172            });
173        });
174
175        // Area the children are placed at
176        let at_rest = !should_animate() && current_size.read().is_some();
177        let area = if at_rest {
178            current_size.read().unwrap_or_default()
179        } else {
180            let (x, y, width, height) = animation.get().value();
181            Area::new(Point2D::new(x, y), Size2D::new(width, height))
182        };
183
184        // Resting portals are placed by the layout rather than positioned globally
185        let is_new = init_size.is_none() && current_size.read().is_none();
186        let is_stacked = self.dependency.is_some()
187            && (is_new || (at_rest && self.dependency == *last_dependency.read()));
188        let global_area = (!is_stacked).then_some(area);
189
190        let id = self.id.clone();
191        let show = self.show;
192
193        rect()
194            .a11y_focusable(false)
195            .on_sized(move |e: Event<SizedEventData>| {
196                if !show || *current_size.peek() == Some(e.area) {
197                    return;
198                }
199
200                positions
201                    .ids
202                    .write()
203                    .insert(id.clone(), (e.area, dependency));
204
205                // Portals with a dependency only animate when it changes
206                let dependency_changed =
207                    dependency.is_none() || *last_dependency.peek() != dependency;
208                last_dependency.set_if_modified(dependency);
209                let animate =
210                    dependency_changed && (init_size.is_some() || current_size.peek().is_some());
211
212                previous_size.set(current_size());
213                current_size.set(Some(e.area));
214                should_animate.set_if_modified(animate);
215
216                spawn(async move {
217                    if animate {
218                        animation.start();
219                    } else {
220                        animation.finish();
221                    }
222                });
223            })
224            .width(self.layout.width.clone())
225            .height(self.layout.height.clone())
226            .child(
227                rect()
228                    .map(global_area, |el, area| {
229                        el.offset_x(area.min_x())
230                            .offset_y(area.min_y())
231                            .position(Position::new_global())
232                    })
233                    .child(
234                        rect()
235                            .width(global_area.map_or(Size::fill(), |area| Size::px(area.width())))
236                            .height(
237                                global_area.map_or(Size::fill(), |area| Size::px(area.height())),
238                            )
239                            // Only show the element after it has been sized
240                            .opacity(if is_stacked || !is_new { 1. } else { 0. })
241                            .children(if self.show {
242                                self.children.clone()
243                            } else {
244                                vec![]
245                            }),
246                    ),
247            )
248    }
249
250    fn render_key(&self) -> DiffKey {
251        self.key.clone().or(self.default_key())
252    }
253}
254
255#[derive(Clone)]
256pub struct PortalsMap<T: Clone + PartialEq + 'static> {
257    pub ids: State<HashMap<T, (Area, Option<u64>)>>,
258}