Skip to main content

nsh_core/element/
flow.rs

1//! Elements that change: [`dynamic`], [`when`] and [`each`] (TS:
2//! `{() => …}`, `<If>`, `<Each>`).
3//!
4//! Each is a region of its parent's children and a binding: when what it
5//! reads changes, its elements are made again (a [`when`]'s only when its
6//! condition flips; an [`each`]'s only for the rows that came, keeping the
7//! others) and the core reconciles the region's nodes alone.
8
9use std::{
10    cell::{Cell, RefCell},
11    collections::HashMap,
12    hash::Hash,
13    rc::Rc,
14};
15
16use super::{
17    AnyElement, ElNode, IntoElement, IntoReactive, Owner, Reactive, ReadSignal, SharedString,
18    Signal, SignalEquals, builder::ElKind, cleanup, computed, create_root, signal, signal_with,
19    untracked,
20};
21use crate::Tag;
22
23/// What a region shows, and how it changes.
24#[derive(Clone)]
25pub(crate) enum Region {
26    /// Made again whenever what it read changes.
27    Dynamic(Rc<dyn Fn() -> Vec<AnyElement>>),
28    /// One branch or the other, made again when the condition flips.
29    If {
30        when: Reactive<bool>,
31        then: Rc<dyn Fn() -> Vec<AnyElement>>,
32        otherwise: Option<Rc<dyn Fn() -> Vec<AnyElement>>>,
33    },
34    /// A row per item, by key.
35    Each(Rc<dyn EachRows>),
36    /// A view, or its fallback once something under it failed.
37    Catch {
38        view: Rc<dyn Fn() -> Vec<AnyElement>>,
39        fallback: Rc<dyn Fn(super::ComponentError, Reset) -> Vec<AnyElement>>,
40    },
41}
42
43/// An element of a region's new run.
44pub(crate) enum RegionElement {
45    /// Made in this run, with the owner its bindings belong to: the run's,
46    /// or its row's. (Boxed: a run of an [`each`] is mostly rows kept, and
47    /// the list of them is made on every update.)
48    Made { owner: Owner, element: Box<ElNode> },
49    /// The element of this key stays as it is: of a row of an [`each`] that
50    /// was there before.
51    Kept(SharedString),
52}
53
54impl RegionElement {
55    fn made(owner: Owner, element: AnyElement) -> Self {
56        Self::Made {
57            owner,
58            element: Box::new(element.0),
59        }
60    }
61
62    /// Whether it can still be applied: the run that made it was not
63    /// replaced, nor its row disposed, before the core applied it (a
64    /// listener that flips a branch there and back queues both runs; what
65    /// the first made, its props too, went with it).
66    pub(crate) fn applies(&self) -> bool {
67        match self {
68            Self::Made { owner, .. } => owner.is_live(),
69            Self::Kept(_) => true,
70        }
71    }
72}
73
74/// An owner of its own for a run of a region, under its binding: what the
75/// run makes (signals, the listeners and bindings of its elements, tasks)
76/// is its and goes when the region runs again or goes, while the binding
77/// stays, as an [`each`]'s rows are theirs. A node of a replaced run keeps
78/// its handlers until the core reconciles the region, in the commit; an
79/// event already queued for it then finds its listener's owner gone.
80fn run_owner() -> Owner {
81    let (owner, ()) = create_root(|| ());
82    cleanup(move || owner.dispose());
83    owner
84}
85
86impl Region {
87    /// Makes the region a binding under the current owner: `show` gets its
88    /// elements now and each time they change.
89    pub(crate) fn bind(&self, show: Rc<dyn Fn(Vec<RegionElement>)>) {
90        match self {
91            Region::Dynamic(f) => {
92                let f = f.clone();
93                super::reactive::render_effect(move || {
94                    let owner = run_owner();
95                    // `scope` keeps the binding tracking what `f` reads.
96                    let elements = owner
97                        .scope(|| f())
98                        .into_iter()
99                        .map(|element| RegionElement::made(owner, element))
100                        .collect();
101                    show(elements);
102                });
103            }
104            Region::If {
105                when,
106                then,
107                otherwise,
108            } => {
109                // The branch is made again only when the condition flips.
110                let when = when.clone();
111                let condition = computed(move || when.get());
112                let (then, otherwise) = (then.clone(), otherwise.clone());
113                super::reactive::render_effect(move || {
114                    let branch = if condition.get() {
115                        Some(&then)
116                    } else {
117                        otherwise.as_ref()
118                    };
119                    let owner = run_owner();
120                    let elements =
121                        untracked(|| owner.scope(|| branch.map(|f| f()).unwrap_or_default()))
122                            .into_iter()
123                            .map(|element| RegionElement::made(owner, element))
124                            .collect();
125                    show(elements);
126                });
127            }
128            Region::Each(rows) => rows.clone().bind(show),
129            Region::Catch { view, fallback } => {
130                let (view, fallback) = (view.clone(), fallback.clone());
131                let failed = signal_with(None::<super::ComponentError>, SignalEquals::Never);
132                super::reactive::render_effect(move || {
133                    let error = failed.get();
134                    // The view is under the boundary, the fallback is not
135                    // (what fails in it goes to the boundary above).
136                    if error.is_none() {
137                        super::reactive::register_boundary(failed);
138                    }
139                    // The run's owner is under the binding, where the
140                    // boundary is: `boundary_of` finds it from there.
141                    let owner = run_owner();
142                    let elements = untracked(|| {
143                        owner.scope(|| match error {
144                            Some(error) => fallback(error, Reset(failed)),
145                            None => view(),
146                        })
147                    })
148                    .into_iter()
149                    .map(|element| RegionElement::made(owner, element))
150                    .collect();
151                    show(elements);
152                });
153            }
154        }
155    }
156}
157
158/// What can be a region's elements: one element, none (`()`), an
159/// `Option`, a `Vec` or an array of them.
160pub trait IntoElements {
161    /// As elements.
162    fn into_elements(self) -> Vec<AnyElement>;
163}
164
165impl<T: IntoElement> IntoElements for T {
166    fn into_elements(self) -> Vec<AnyElement> {
167        vec![self.into_element()]
168    }
169}
170
171impl<T: IntoElement> IntoElements for Option<T> {
172    fn into_elements(self) -> Vec<AnyElement> {
173        self.map(IntoElement::into_element).into_iter().collect()
174    }
175}
176
177impl<T: IntoElement> IntoElements for Vec<T> {
178    fn into_elements(self) -> Vec<AnyElement> {
179        self.into_iter().map(IntoElement::into_element).collect()
180    }
181}
182
183impl<T: IntoElement, const N: usize> IntoElements for [T; N] {
184    fn into_elements(self) -> Vec<AnyElement> {
185        self.into_iter().map(IntoElement::into_element).collect()
186    }
187}
188
189impl IntoElements for () {
190    fn into_elements(self) -> Vec<AnyElement> {
191        Vec::new()
192    }
193}
194
195fn region(region: Region) -> AnyElement {
196    let mut node = super::ElNode::new(Tag::View);
197    node.kind = ElKind::Region(region);
198    AnyElement(node)
199}
200
201/// Elements made again whenever what `f` reads changes (TS: a child that is
202/// a function, `{() => …}`). Prefer [`when`] for a choice and [`each`] for a
203/// list: they keep what did not change.
204pub fn dynamic<E: IntoElements>(f: impl Fn() -> E + 'static) -> AnyElement {
205    region(Region::Dynamic(Rc::new(move || f().into_elements())))
206}
207
208/// `view`'s elements, or `fallback`'s once something under them failed (a
209/// panic in a binding, a listener, an effect or a component's view, TS:
210/// `<ErrorBoundary>`): the failed part goes, and the fallback shows the
211/// error; its [`Reset`] makes the view again. What fails in the fallback
212/// goes to the boundary above.
213pub fn catch_error<E: IntoElements, F: IntoElements>(
214    view: impl Fn() -> E + 'static,
215    fallback: impl Fn(super::ComponentError, Reset) -> F + 'static,
216) -> AnyElement {
217    region(Region::Catch {
218        view: Rc::new(move || view().into_elements()),
219        fallback: Rc::new(move |error, reset| fallback(error, reset).into_elements()),
220    })
221}
222
223/// What tries a [`catch_error`]'s view again (TS: the fallback's `reset`).
224#[derive(Clone, Copy)]
225pub struct Reset(Signal<Option<super::ComponentError>>);
226
227impl Reset {
228    /// Makes the view again, in place of the fallback.
229    pub fn reset(&self) {
230        self.0.set(None);
231    }
232}
233
234/// `then`'s elements while a condition holds, else `otherwise`'s (TS: `<If
235/// when={…} else={…}>`), made by [`when`]. A branch is made when the
236/// condition flips to it, and what it made goes when it flips away.
237pub struct If {
238    when: Reactive<bool>,
239    then: Rc<dyn Fn() -> Vec<AnyElement>>,
240    otherwise: Option<Rc<dyn Fn() -> Vec<AnyElement>>>,
241}
242
243impl If {
244    /// `then` while `when` holds, as [`when`] makes it.
245    #[deprecated(note = "use `when(condition, then)`, as `view()` makes a view")]
246    pub fn new<E: IntoElements>(
247        when: impl IntoReactive<bool>,
248        then: impl Fn() -> E + 'static,
249    ) -> Self {
250        self::when(when, then)
251    }
252
253    /// `otherwise` while the condition does not hold (TS: `else={…}`).
254    pub fn otherwise<E: IntoElements>(mut self, otherwise: impl Fn() -> E + 'static) -> Self {
255        self.otherwise = Some(Rc::new(move || otherwise().into_elements()));
256        self
257    }
258}
259
260/// `then`'s elements while `condition` (a value, a signal or a closure)
261/// holds (TS: `<If when={…}>`); [`If::otherwise`] adds what shows while it
262/// does not (TS: `else={…}`). A branch is made when the condition flips to
263/// it, and what it made goes when it flips away.
264///
265/// GPUI has no counterpart: its views render again on every change, so a
266/// branch there is decided in each render, with `FluentBuilder::when` /
267/// `when_else` (NSH's [`super::FluentBuilder`] is that, decided once). NSH's
268/// components run once (`docs/dev/reactive-components.md`), so what comes
269/// and goes is a region bound to its condition: this one, named after TSX's
270/// `<If when>`, its other branch `otherwise` as `else` is a keyword.
271pub fn when<E: IntoElements>(
272    condition: impl IntoReactive<bool>,
273    then: impl Fn() -> E + 'static,
274) -> If {
275    If {
276        when: condition.into_reactive(),
277        then: Rc::new(move || then().into_elements()),
278        otherwise: None,
279    }
280}
281
282impl IntoElement for If {
283    fn into_element(self) -> AnyElement {
284        region(Region::If {
285            when: self.when,
286            then: self.then,
287            otherwise: self.otherwise,
288        })
289    }
290}
291
292/// A row per item of a list, identified by key (TS: `<Each of={…}
293/// key="id">{(item, index) => …}</Each>`), made by [`each`].
294pub struct Each;
295
296impl Each {
297    /// The rows of `items`, as [`each`] makes them.
298    #[deprecated(note = "use `each(items, key, row)`, as `view()` makes a view")]
299    #[allow(clippy::new_ret_no_self, reason = "TS's <Each> is an element")]
300    pub fn new<T, K, E>(
301        items: impl IntoReactive<Vec<T>>,
302        key: impl Fn(&T) -> K + 'static,
303        row: impl Fn(ReadSignal<T>, ReadSignal<usize>) -> E + 'static,
304    ) -> AnyElement
305    where
306        T: Clone + PartialEq + 'static,
307        K: Hash + Eq + Clone + 'static,
308        E: IntoElements,
309    {
310        each(items, key, row)
311    }
312}
313
314/// A row per item of `items` (a value, a signal or a closure), each made by
315/// `row(item, index)` and known by `key(item)` (TS: `<Each of={…}
316/// key="id">{(item, index) => …}</Each>`). A row is made when its key comes
317/// and goes with it; one that stays keeps its nodes and bindings, and gets
318/// its item and index as signals that follow it.
319pub fn each<T, K, E>(
320    items: impl IntoReactive<Vec<T>>,
321    key: impl Fn(&T) -> K + 'static,
322    row: impl Fn(ReadSignal<T>, ReadSignal<usize>) -> E + 'static,
323) -> AnyElement
324where
325    T: Clone + PartialEq + 'static,
326    K: Hash + Eq + Clone + 'static,
327    E: IntoElements,
328{
329    region(Region::Each(Rc::new(Rows {
330        items: items.into_reactive(),
331        key: Box::new(key),
332        row: Box::new(move |item, index| row(item, index).into_elements()),
333        state: RefCell::new(Vec::new()),
334        distinct: Cell::new(true),
335        next: Cell::new(0),
336    })))
337}
338
339/// The rows of an [`Each`], with their type erased.
340pub(crate) trait EachRows {
341    /// Binds the rows (see [`Region::bind`]).
342    fn bind(self: Rc<Self>, show: Rc<dyn Fn(Vec<RegionElement>)>);
343}
344
345/// What makes a row's elements from its item and index.
346type RowFn<T> = Box<dyn Fn(ReadSignal<T>, ReadSignal<usize>) -> Vec<AnyElement>>;
347
348struct Rows<T: 'static, K> {
349    items: Reactive<Vec<T>>,
350    key: Box<dyn Fn(&T) -> K>,
351    row: RowFn<T>,
352    /// The live rows, in order.
353    state: RefCell<Vec<Row<T, K>>>,
354    /// Whether the rows' keys are known to differ from each other: a row
355    /// whose key comes in its place again is then the row of that key,
356    /// found without a map of them all ([`Rows::update`]).
357    distinct: Cell<bool>,
358    /// The id of the next row made (its elements' keys).
359    next: Cell<u64>,
360}
361
362struct Row<T: 'static, K> {
363    key: K,
364    item: Signal<T>,
365    index: Signal<usize>,
366    owner: Owner,
367    /// The keys of the elements it made.
368    elements: Box<[SharedString]>,
369}
370
371/// How many rows made in one update are looked for among the others, each
372/// key compared with every other, to know the keys still differ; past it
373/// the next update finds out with its map.
374const MADE_COMPARED: usize = 8;
375
376/// The key of a row's `i`th element: unique to the row, whatever its key.
377fn element_key(id: u64, i: usize) -> SharedString {
378    format!("\u{1}{id}.{i}").into()
379}
380
381/// Keeps a row's elements, of the keys `elements`, where they are, in
382/// `out`. Out of line, as [`show_row`]: [`Rows::update`] is made for every
383/// item and key type.
384#[cfg_attr(target_arch = "wasm32", inline(never))]
385fn keep_row(out: &mut Vec<RegionElement>, elements: &[SharedString]) {
386    out.extend(elements.iter().cloned().map(RegionElement::Kept));
387}
388
389/// Adds the elements a new row `id`, of `owner`, made to `out`; their keys.
390#[cfg_attr(target_arch = "wasm32", inline(never))]
391fn show_row(
392    out: &mut Vec<RegionElement>,
393    id: u64,
394    owner: Owner,
395    elements: Vec<AnyElement>,
396) -> Box<[SharedString]> {
397    elements
398        .into_iter()
399        .enumerate()
400        .map(|(i, mut element)| {
401            let key = element_key(id, i);
402            element.0.key = Some(key.clone());
403            out.push(RegionElement::made(owner, element));
404            key
405        })
406        .collect()
407}
408
409/// Writes `value` to `signal` unless it holds an equal one, which a write
410/// would only compare and drop: a row that stays is mostly as it was.
411fn follow<V: PartialEq + 'static>(signal: Signal<V>, value: V) {
412    if !signal.with_untracked(|held| *held == value) {
413        signal.set(value);
414    }
415}
416
417impl<T: Clone + PartialEq + 'static, K: Hash + Eq + Clone + 'static> EachRows for Rows<T, K> {
418    fn bind(self: Rc<Self>, show: Rc<dyn Fn(Vec<RegionElement>)>) {
419        // The rows go with the region's owner.
420        let rows = self.clone();
421        cleanup(move || {
422            for row in rows.state.take() {
423                row.owner.dispose();
424            }
425        });
426        super::reactive::render_effect(move || {
427            let items = self.items.get();
428            let out = untracked(|| self.update(items));
429            show(out);
430        });
431    }
432}
433
434impl<T: Clone + PartialEq + 'static, K: Hash + Eq + Clone + 'static> Rows<T, K> {
435    /// The rows of `items`: the rows of keys that stay are kept (their item
436    /// and index updated), new ones made, the others disposed.
437    ///
438    /// A list mostly changes at one place (a row's item, a row added at the
439    /// end), so the rows are first passed in order, each kept while the key
440    /// in its place is its own: no map, and nothing written for a row whose
441    /// item is equal. Only from the first place whose key is another are
442    /// the rows left looked up by key.
443    fn update(&self, items: Vec<T>) -> Vec<RegionElement> {
444        let mut old = self.state.take().into_iter();
445        let mut rows = Vec::with_capacity(items.len());
446        let mut out = Vec::with_capacity(items.len());
447        let mut items = items.into_iter().enumerate();
448        // The first item that is not the row in its place, with its key.
449        let mut first = None;
450        // With a key twice among the rows, a map of them all decides which
451        // row of that key stays, as it always did.
452        let mut by_key = !self.distinct.get();
453        if !by_key {
454            for (index, item) in items.by_ref() {
455                let key = (self.key)(&item);
456                if old.as_slice().first().is_none_or(|row| row.key != key) {
457                    first = Some((index, item, key));
458                    by_key = true;
459                    break;
460                }
461                let Some(row) = old.next() else { break };
462                // (Its index is its place already.)
463                follow(row.item, item);
464                keep_row(&mut out, &row.elements);
465                rows.push(row);
466            }
467        }
468        // Where the rows made are, as many as are compared with the others.
469        let mut made = Vec::new();
470        if by_key {
471            let mut left: HashMap<K, Row<T, K>> =
472                old.by_ref().map(|row| (row.key.clone(), row)).collect();
473            let rest = items.map(|(index, item)| {
474                let key = (self.key)(&item);
475                (index, item, key)
476            });
477            for (index, item, key) in first.into_iter().chain(rest) {
478                // A key twice: the second is a row of its own.
479                match left.remove(&key) {
480                    Some(row) => {
481                        follow(row.item, item);
482                        follow(row.index, index);
483                        keep_row(&mut out, &row.elements);
484                        rows.push(row);
485                    }
486                    None => {
487                        let id = self.next.get();
488                        self.next.set(id + 1);
489                        let (owner, (item, index, elements)) = create_root(|| {
490                            let item = signal(item);
491                            let index = signal(index);
492                            let elements = (self.row)(item.read_only(), index.read_only());
493                            (item, index, elements)
494                        });
495                        let elements = show_row(&mut out, id, owner, elements);
496                        if made.len() <= MADE_COMPARED {
497                            made.push(rows.len());
498                        }
499                        rows.push(Row {
500                            key,
501                            item,
502                            index,
503                            owner,
504                            elements,
505                        });
506                    }
507                }
508            }
509            for row in left.into_values() {
510                row.owner.dispose();
511            }
512        }
513        // The items ended before the rows did.
514        for row in old {
515            row.owner.dispose();
516        }
517        // The rows kept have keys that differ (they were in their places, or
518        // came out of the map); a row made may have the key of any other.
519        self.distinct.set(
520            made.len() <= MADE_COMPARED
521                && made.iter().all(|&at| {
522                    let key = &rows[at].key;
523                    rows.iter()
524                        .enumerate()
525                        .all(|(other, row)| other == at || row.key != *key)
526                }),
527        );
528        self.state.replace(rows);
529        out
530    }
531}