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_side_effect(move || {
168            if !*animation.is_running().read() {
169                should_animate.set_if_modified(false);
170            }
171        });
172
173        // Area the children are placed at
174        let at_rest = !should_animate() && current_size.read().is_some();
175        let area = if at_rest {
176            current_size.read().unwrap_or_default()
177        } else {
178            let (x, y, width, height) = animation.get().value();
179            Area::new(Point2D::new(x, y), Size2D::new(width, height))
180        };
181
182        // Resting portals are placed by the layout rather than positioned globally
183        let is_new = init_size.is_none() && current_size.read().is_none();
184        let is_stacked = self.dependency.is_some()
185            && (is_new || (at_rest && self.dependency == *last_dependency.read()));
186        let global_area = (!is_stacked).then_some(area);
187
188        let id = self.id.clone();
189        let show = self.show;
190
191        rect()
192            .a11y_focusable(false)
193            .on_sized(move |e: Event<SizedEventData>| {
194                if !show || *current_size.peek() == Some(e.area) {
195                    return;
196                }
197
198                positions
199                    .ids
200                    .write()
201                    .insert(id.clone(), (e.area, dependency));
202
203                // Portals with a dependency only animate when it changes
204                let dependency_changed =
205                    dependency.is_none() || *last_dependency.peek() != dependency;
206                last_dependency.set_if_modified(dependency);
207                let animate =
208                    dependency_changed && (init_size.is_some() || current_size.peek().is_some());
209
210                previous_size.set(current_size());
211                current_size.set(Some(e.area));
212                should_animate.set_if_modified(animate);
213
214                spawn(async move {
215                    if animate {
216                        animation.start();
217                    } else {
218                        animation.finish();
219                    }
220                });
221            })
222            .width(self.layout.width.clone())
223            .height(self.layout.height.clone())
224            .child(
225                rect()
226                    .map(global_area, |el, area| {
227                        el.offset_x(area.min_x())
228                            .offset_y(area.min_y())
229                            .position(Position::new_global())
230                    })
231                    .child(
232                        rect()
233                            .width(global_area.map_or(Size::fill(), |area| Size::px(area.width())))
234                            .height(
235                                global_area.map_or(Size::fill(), |area| Size::px(area.height())),
236                            )
237                            // Only show the element after it has been sized
238                            .opacity(if is_stacked || !is_new { 1. } else { 0. })
239                            .children(if self.show {
240                                self.children.clone()
241                            } else {
242                                vec![]
243                            }),
244                    ),
245            )
246    }
247
248    fn render_key(&self) -> DiffKey {
249        self.key.clone().or(self.default_key())
250    }
251}
252
253#[derive(Clone)]
254pub struct PortalsMap<T: Clone + PartialEq + 'static> {
255    pub ids: State<HashMap<T, (Area, Option<u64>)>>,
256}