floem/views/
dyn_container.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use std::any::Any;

use floem_reactive::{as_child_of_current_scope, create_updater, Scope};

use crate::{
    animate::RepeatMode,
    context::UpdateCx,
    view::{AnyView, View},
    IntoView, ViewId,
};

#[macro_export]
macro_rules! dyn_view {
    ($signal:ident, $new:ident => $body:expr) => {
        dyn_container(
            move || {
                use floem::reactive::SignalGet;
                $signal.get()
            },
            move |$new| $body,
        )
    };

    ($signal:ident => $body:expr) => {
        dyn_container(
            move || {
                use floem::reactive::SignalGet;
                $signal.get()
            },
            move |$signal| $body,
        )
    };
}

type ChildFn<T> = dyn Fn(T) -> (AnyView, Scope);

/// A container for a dynamically updating View. See [`dyn_container`]
pub struct DynamicContainer<T: 'static> {
    id: ViewId,
    child_id: ViewId,
    child_scope: Scope,
    child_fn: Box<ChildFn<T>>,
    next_val_state: Option<(T, ViewId, Scope)>,
    num_started_animations: u16,
}

/// A container for a dynamically updating View
///
/// ## Example
/// ```
/// use floem::{
///     reactive::{create_rw_signal, SignalGet, SignalUpdate},
///     views::{dyn_container, label, toggle_button, v_stack, Decorators},
///     IntoView, View,
/// };
///
/// #[derive(Clone)]
/// enum ViewSwitcher {
///     One,
///     Two,
/// }
///
/// fn app_view() -> impl View {
///     let view = create_rw_signal(ViewSwitcher::One);
///     v_stack((
///         toggle_button(|| true)
///             .on_toggle(move |is_on| {
///                 if is_on {
///                     view.update(|val| *val = ViewSwitcher::One);
///                 } else {
///                     view.update(|val| *val = ViewSwitcher::Two);
///                 }
///             })
///             .style(|s| s.margin_bottom(20)),
///         dyn_container(
///             move || view.get(),
///             move |value| match value {
///                 ViewSwitcher::One => label(|| "One").into_any(),
///                 ViewSwitcher::Two => v_stack((label(|| "Stacked"), label(|| "Two"))).into_any(),
///             },
///         ),
///     ))
///     .style(|s| {
///         s.width_full()
///             .height_full()
///             .items_center()
///             .justify_center()
///             .row_gap(10)
///     })
/// }
/// ```
pub fn dyn_container<CF: Fn(T) -> IV + 'static, T: 'static, IV: IntoView>(
    update_view: impl Fn() -> T + 'static,
    child_fn: CF,
) -> DynamicContainer<T> {
    let id = ViewId::new();

    let initial = create_updater(update_view, move |new_state| {
        id.update_state(DynMessage::Val(Box::new(new_state)));
    });

    let child_fn = Box::new(as_child_of_current_scope(move |e| child_fn(e).into_any()));
    let (child, child_scope) = child_fn(initial);
    let child_id = child.id();
    id.set_children(vec![child]);
    DynamicContainer {
        id,
        child_scope,
        child_id,
        child_fn,
        next_val_state: None,
        num_started_animations: 0,
    }
}
enum DynMessage {
    Val(Box<dyn Any>),
    CompletedAnimation,
}

impl<T: 'static> View for DynamicContainer<T> {
    fn id(&self) -> ViewId {
        self.id
    }

    fn debug_name(&self) -> std::borrow::Cow<'static, str> {
        "Dynamic Container".into()
    }

    fn update(&mut self, cx: &mut UpdateCx, state: Box<dyn Any>) {
        if let Ok(message) = state.downcast::<DynMessage>() {
            match *message {
                DynMessage::Val(val) => {
                    if let Ok(val) = val.downcast::<T>() {
                        self.new_val(cx, *val);
                    }
                }
                DynMessage::CompletedAnimation => {
                    self.num_started_animations = self.num_started_animations.saturating_sub(1);
                    if self.num_started_animations == 0 {
                        let next_val_state = self
                            .next_val_state
                            .take()
                            .expect("when waiting for animations the next value will be stored and all message effects should have been dropped by dropping the child id if another value was sent before the animations finished");
                        self.swap_val(cx, next_val_state);
                    }
                }
            }
        }
    }
}
impl<T> DynamicContainer<T> {
    fn new_val(&mut self, cx: &mut UpdateCx, val: T) {
        let id = self.id;

        let old_child_scope = self.child_scope;
        let old_child_id = self.child_id;

        if self.num_started_animations > 0 {
            // another update was sent before the animations finished processing
            let next_state = self
                .next_val_state
                .take()
                .expect("valid when waiting for animations");
            // force swap
            self.swap_val(cx, next_state);
            self.num_started_animations = 0;
        }

        self.num_started_animations =
            animations_recursive_on_remove(id, old_child_id, old_child_scope);

        let next_state = (val, old_child_id, old_child_scope);
        if self.num_started_animations == 0 {
            // after recursively checking, no animations were found that needed to be started
            self.swap_val(cx, next_state);
        } else {
            self.next_val_state = Some(next_state);
        }
    }

    fn swap_val(&mut self, cx: &mut UpdateCx, next_val_state: (T, ViewId, Scope)) {
        let (val, old_child_id, old_child_scope) = next_val_state;
        let (new_child, new_child_scope) = (self.child_fn)(val);
        self.child_id = new_child.id();
        self.id.set_children(vec![new_child]);
        self.child_scope = new_child_scope;
        cx.app_state_mut().remove_view(old_child_id);
        old_child_scope.dispose();
        animations_recursive_on_create(self.child_id);
        self.id.request_all();
    }
}

fn animations_recursive_on_remove(id: ViewId, child_id: ViewId, child_scope: Scope) -> u16 {
    let mut wait_for = 0;
    let state = child_id.state();
    let mut state = state.borrow_mut();
    let animations = &mut state.animations.stack;
    let mut request_style = false;
    for anim in animations {
        if anim.run_on_remove && !matches!(anim.repeat_mode, RepeatMode::LoopForever) {
            anim.reverse_once.set(true);
            anim.start_mut();
            request_style = true;
            wait_for += 1;
            let trigger = anim.on_visual_complete;
            child_scope.create_updater(
                move || trigger.track(),
                move |_| {
                    id.update_state(DynMessage::CompletedAnimation);
                },
            );
        }
    }
    drop(state);
    if request_style {
        child_id.request_style();
    }

    child_id
        .children()
        .into_iter()
        .fold(wait_for, |acc, child_id| {
            acc + animations_recursive_on_remove(id, child_id, child_scope)
        })
}
fn animations_recursive_on_create(child_id: ViewId) {
    let state = child_id.state();
    let mut state = state.borrow_mut();
    let animations = &mut state.animations.stack;
    let mut request_style = false;
    for anim in animations {
        if anim.run_on_create && !matches!(anim.repeat_mode, RepeatMode::LoopForever) {
            anim.start_mut();
            request_style = true;
        }
    }
    drop(state);
    if request_style {
        child_id.request_style();
    }

    child_id
        .children()
        .into_iter()
        .for_each(animations_recursive_on_create);
}