Skip to main content

mitsuami_core/
flow.rs

1//! Control flow: conditional and list rendering.
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::hash::Hash;
6use std::rc::Rc;
7
8use mitsuami_reactive::{IntoValue, Owner, Value, computed, effect, on_cleanup, untrack};
9
10use crate::ui::Ui;
11use crate::view::{AnyView, Children, View};
12use crate::widget::{NodeId, WidgetKind};
13
14type Branch = Rc<dyn Fn() -> Vec<AnyView>>;
15
16fn branch<C: Children>(children: impl Fn() -> C + 'static) -> Branch {
17    Rc::new(move || {
18        let mut views = Vec::new();
19        children().into_views(&mut views);
20        views
21    })
22}
23
24/// Renders `then` while `when` is true, otherwise the optional fallback.
25/// Vue's `v-if` / `v-else`. Either is any children: a view, or a tuple of
26/// them, which take their places in the parent as if written there.
27/// Switching branches disposes the old branch's nodes and reactive state.
28pub struct Show {
29    when: Value<bool>,
30    then: Branch,
31    fallback: Option<Branch>,
32}
33
34impl Show {
35    pub fn new<C: Children>(when: impl IntoValue<bool>, then: impl Fn() -> C + 'static) -> Show {
36        Show { when: when.into_value(), then: branch(then), fallback: None }
37    }
38
39    pub fn fallback<C: Children>(mut self, fallback: impl Fn() -> C + 'static) -> Show {
40        self.fallback = Some(branch(fallback));
41        self
42    }
43}
44
45impl View for Show {
46    fn build(self, ui: &Ui) -> NodeId {
47        let fragment = ui.create(WidgetKind::Fragment, Vec::new());
48        let Show { when, then, fallback } = self;
49        let ui = ui.clone();
50        let render = move |condition: bool| {
51            let branch = if condition { Some(&then) } else { fallback.as_ref() };
52            if let Some(branch) = branch {
53                for view in branch() {
54                    let child = view.build(&ui);
55                    ui.append_child(fragment, child);
56                    let ui = ui.clone();
57                    on_cleanup(move || ui.destroy(child));
58                }
59            }
60        };
61        match when {
62            Value::Static(condition) => render(condition),
63            Value::Dynamic(f) => {
64                let condition = computed(move || f());
65                effect(move || {
66                    let c = condition.get();
67                    untrack(|| render(c));
68                });
69            }
70        }
71        fragment
72    }
73}
74
75type KeyFn<T, K> = Rc<dyn Fn(&T) -> K>;
76type RenderFn<T> = Rc<dyn Fn(T) -> AnyView>;
77
78/// Keyed list rendering. Vue's `v-for` with `:key`.
79///
80/// Items are matched by key between updates: existing rows keep their nodes
81/// and state (and are moved if needed), new keys render new rows, and rows
82/// whose key disappeared are disposed. A row is rendered once per key; put
83/// signals inside items for per-row updates. Keys should be unique: a key
84/// that comes again renders its later rows anew on every update.
85pub struct For<T: 'static, K: 'static> {
86    each: Value<Vec<T>>,
87    key: KeyFn<T, K>,
88    render: RenderFn<T>,
89}
90
91impl<T: Clone + 'static, K: Eq + Hash + 'static> For<T, K> {
92    pub fn new<V: View>(
93        each: impl IntoValue<Vec<T>>,
94        key: impl Fn(&T) -> K + 'static,
95        render: impl Fn(T) -> V + 'static,
96    ) -> For<T, K> {
97        For { each: each.into_value(), key: Rc::new(key), render: Rc::new(move |item| AnyView::new(render(item))) }
98    }
99}
100
101impl<T: Clone + 'static, K: Eq + Hash + 'static> View for For<T, K> {
102    fn build(self, ui: &Ui) -> NodeId {
103        let fragment = ui.create(WidgetKind::Fragment, Vec::new());
104        // Row scopes hang off a dedicated scope in the *building* owner, so
105        // they survive re-runs of the list effect. With no owner, the rows
106        // and the effect go with the fragment.
107        let scope = ui.owner_or_node_scope(fragment);
108        let rows_scope = scope.child();
109        let rows: Rc<RefCell<Vec<(K, NodeId, Owner)>>> = Rc::default();
110        let For { each, key, render } = self;
111        let ui = ui.clone();
112        let update = move || {
113            let items = each.get();
114            untrack(|| {
115                let mut old: HashMap<K, (NodeId, Owner)> = HashMap::new();
116                // Rows of a key that came twice: one is kept, and the others
117                // are let go of with the rows that went, not leaked.
118                let mut gone = Vec::new();
119                for (k, id, owner) in rows.borrow_mut().drain(..) {
120                    gone.extend(old.insert(k, (id, owner)));
121                }
122                let mut next = Vec::with_capacity(items.len());
123                for item in items {
124                    let k = key(&item);
125                    let (id, owner) = match old.remove(&k) {
126                        Some(existing) => existing,
127                        None => {
128                            let owner = rows_scope.child();
129                            let id = owner.with(|| render(item).build(&ui));
130                            (id, owner)
131                        }
132                    };
133                    next.push((k, id, owner));
134                }
135                // Rows that went are out of the fragment before they're
136                // destroyed, so each needn't be looked for among the others.
137                ui.set_children(fragment, next.iter().map(|(_, id, _)| *id).collect());
138                for (id, owner) in gone.into_iter().chain(old.into_values()) {
139                    owner.dispose();
140                    ui.destroy(id);
141                }
142                *rows.borrow_mut() = next;
143            });
144        };
145        scope.with(|| effect(update));
146        fragment
147    }
148}
149
150// `view!` tags. `<Show when=…>` and `<For each=… key=… let:item>` need
151// their required attributes before their children; each step is a type of
152// its own, so a missing one is a compile error.
153
154impl Show {
155    #[doc(hidden)]
156    pub fn __tag() -> ShowWithoutWhen {
157        ShowWithoutWhen { fallback: None }
158    }
159}
160
161#[doc(hidden)]
162pub struct ShowWithoutWhen {
163    fallback: Option<Branch>,
164}
165
166impl ShowWithoutWhen {
167    pub fn when(self, when: impl IntoValue<bool>) -> ShowWhen {
168        ShowWhen { when: when.into_value(), fallback: self.fallback }
169    }
170
171    pub fn fallback<C: Children>(mut self, fallback: impl Fn() -> C + 'static) -> ShowWithoutWhen {
172        self.fallback = Some(branch(fallback));
173        self
174    }
175}
176
177#[doc(hidden)]
178pub struct ShowWhen {
179    when: Value<bool>,
180    fallback: Option<Branch>,
181}
182
183impl ShowWhen {
184    pub fn fallback<C: Children>(mut self, fallback: impl Fn() -> C + 'static) -> ShowWhen {
185        self.fallback = Some(branch(fallback));
186        self
187    }
188
189    pub fn __children<C: Children>(self, then: impl Fn() -> C + 'static) -> Show {
190        Show { when: self.when, then: branch(then), fallback: self.fallback }
191    }
192}
193
194impl For<(), ()> {
195    #[doc(hidden)]
196    pub fn __tag() -> ForWithoutEach {
197        ForWithoutEach
198    }
199}
200
201#[doc(hidden)]
202pub struct ForWithoutEach;
203
204impl ForWithoutEach {
205    pub fn each<T: Clone + 'static>(self, each: impl IntoValue<Vec<T>>) -> ForWithoutKey<T> {
206        ForWithoutKey { each: each.into_value() }
207    }
208}
209
210#[doc(hidden)]
211pub struct ForWithoutKey<T: 'static> {
212    each: Value<Vec<T>>,
213}
214
215impl<T: Clone + 'static> ForWithoutKey<T> {
216    pub fn key<K: Eq + Hash + 'static>(self, key: impl Fn(&T) -> K + 'static) -> ForKeyed<T, K> {
217        ForKeyed { each: self.each, key: Rc::new(key) }
218    }
219}
220
221#[doc(hidden)]
222pub struct ForKeyed<T: 'static, K: 'static> {
223    each: Value<Vec<T>>,
224    key: KeyFn<T, K>,
225}
226
227impl<T: Clone + 'static, K: Eq + Hash + 'static> ForKeyed<T, K> {
228    pub fn __children<V: View>(self, render: impl Fn(T) -> V + 'static) -> For<T, K> {
229        For { each: self.each, key: self.key, render: Rc::new(move |item| AnyView::new(render(item))) }
230    }
231}