nsh-core 0.5.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Elements that change: [`dynamic`], [`when`] and [`each`] (TS:
//! `{() => …}`, `<If>`, `<Each>`).
//!
//! Each is a region of its parent's children and a binding: when what it
//! reads changes, its elements are made again (a [`when`]'s only when its
//! condition flips; an [`each`]'s only for the rows that came, keeping the
//! others) and the core reconciles the region's nodes alone.

use std::{
    cell::{Cell, RefCell},
    collections::HashMap,
    hash::Hash,
    rc::Rc,
};

use super::{
    AnyElement, IntoElement, IntoReactive, Owner, Reactive, ReadSignal, Signal, SignalEquals,
    builder::ElKind, cleanup, computed, create_root, signal, signal_with, untracked,
};
use crate::Tag;

/// What a region shows, and how it changes.
#[derive(Clone)]
pub(crate) enum Region {
    /// Made again whenever what it read changes.
    Dynamic(Rc<dyn Fn() -> Vec<AnyElement>>),
    /// One branch or the other, made again when the condition flips.
    If {
        when: Reactive<bool>,
        then: Rc<dyn Fn() -> Vec<AnyElement>>,
        otherwise: Option<Rc<dyn Fn() -> Vec<AnyElement>>>,
    },
    /// A row per item, by key.
    Each(Rc<dyn EachRows>),
    /// A view, or its fallback once something under it failed.
    Catch {
        view: Rc<dyn Fn() -> Vec<AnyElement>>,
        fallback: Rc<dyn Fn(super::ComponentError, Reset) -> Vec<AnyElement>>,
    },
}

/// An element of a region's new run: one made in this run (with the owner
/// its bindings belong to: the run's, or its row's), or one kept from
/// before ([`ElKind::Keep`]).
pub(crate) struct RegionElement {
    pub(crate) owner: Option<Owner>,
    pub(crate) element: AnyElement,
}

impl RegionElement {
    /// Whether it can still be applied: the run that made it was not
    /// replaced, nor its row disposed, before the core applied it (a
    /// listener that flips a branch there and back queues both runs; what
    /// the first made, its props too, went with it).
    pub(crate) fn applies(&self) -> bool {
        self.owner.is_none_or(|owner| owner.is_live())
    }
}

/// An owner of its own for a run of a region, under its binding: what the
/// run makes (signals, the listeners and bindings of its elements, tasks)
/// is its and goes when the region runs again or goes, while the binding
/// stays, as an [`each`]'s rows are theirs. A node of a replaced run keeps
/// its handlers until the core reconciles the region, in the commit; an
/// event already queued for it then finds its listener's owner gone.
fn run_owner() -> Owner {
    let (owner, ()) = create_root(|| ());
    cleanup(move || owner.dispose());
    owner
}

impl Region {
    /// Makes the region a binding under the current owner: `show` gets its
    /// elements now and each time they change.
    pub(crate) fn bind(&self, show: Rc<dyn Fn(Vec<RegionElement>)>) {
        match self {
            Region::Dynamic(f) => {
                let f = f.clone();
                super::reactive::render_effect(move || {
                    let owner = run_owner();
                    // `scope` keeps the binding tracking what `f` reads.
                    let elements = owner
                        .scope(|| f())
                        .into_iter()
                        .map(|element| RegionElement {
                            owner: Some(owner),
                            element,
                        })
                        .collect();
                    show(elements);
                });
            }
            Region::If {
                when,
                then,
                otherwise,
            } => {
                // The branch is made again only when the condition flips.
                let when = when.clone();
                let condition = computed(move || when.get());
                let (then, otherwise) = (then.clone(), otherwise.clone());
                super::reactive::render_effect(move || {
                    let branch = if condition.get() {
                        Some(&then)
                    } else {
                        otherwise.as_ref()
                    };
                    let owner = run_owner();
                    let elements =
                        untracked(|| owner.scope(|| branch.map(|f| f()).unwrap_or_default()))
                            .into_iter()
                            .map(|element| RegionElement {
                                owner: Some(owner),
                                element,
                            })
                            .collect();
                    show(elements);
                });
            }
            Region::Each(rows) => rows.clone().bind(show),
            Region::Catch { view, fallback } => {
                let (view, fallback) = (view.clone(), fallback.clone());
                let failed = signal_with(None::<super::ComponentError>, SignalEquals::Never);
                super::reactive::render_effect(move || {
                    let error = failed.get();
                    // The view is under the boundary, the fallback is not
                    // (what fails in it goes to the boundary above).
                    if error.is_none() {
                        super::reactive::register_boundary(failed);
                    }
                    // The run's owner is under the binding, where the
                    // boundary is: `boundary_of` finds it from there.
                    let owner = run_owner();
                    let elements = untracked(|| {
                        owner.scope(|| match error {
                            Some(error) => fallback(error, Reset(failed)),
                            None => view(),
                        })
                    })
                    .into_iter()
                    .map(|element| RegionElement {
                        owner: Some(owner),
                        element,
                    })
                    .collect();
                    show(elements);
                });
            }
        }
    }
}

/// What can be a region's elements: one element, none (`()`), an
/// `Option`, a `Vec` or an array of them.
pub trait IntoElements {
    /// As elements.
    fn into_elements(self) -> Vec<AnyElement>;
}

impl<T: IntoElement> IntoElements for T {
    fn into_elements(self) -> Vec<AnyElement> {
        vec![self.into_element()]
    }
}

impl<T: IntoElement> IntoElements for Option<T> {
    fn into_elements(self) -> Vec<AnyElement> {
        self.map(IntoElement::into_element).into_iter().collect()
    }
}

impl<T: IntoElement> IntoElements for Vec<T> {
    fn into_elements(self) -> Vec<AnyElement> {
        self.into_iter().map(IntoElement::into_element).collect()
    }
}

impl<T: IntoElement, const N: usize> IntoElements for [T; N] {
    fn into_elements(self) -> Vec<AnyElement> {
        self.into_iter().map(IntoElement::into_element).collect()
    }
}

impl IntoElements for () {
    fn into_elements(self) -> Vec<AnyElement> {
        Vec::new()
    }
}

fn region(region: Region) -> AnyElement {
    let mut node = super::ElNode::new(Tag::View);
    node.kind = ElKind::Region(region);
    AnyElement(node)
}

/// Elements made again whenever what `f` reads changes (TS: a child that is
/// a function, `{() => …}`). Prefer [`when`] for a choice and [`each`] for a
/// list: they keep what did not change.
pub fn dynamic<E: IntoElements>(f: impl Fn() -> E + 'static) -> AnyElement {
    region(Region::Dynamic(Rc::new(move || f().into_elements())))
}

/// `view`'s elements, or `fallback`'s once something under them failed (a
/// panic in a binding, a listener, an effect or a component's view, TS:
/// `<ErrorBoundary>`): the failed part goes, and the fallback shows the
/// error; its [`Reset`] makes the view again. What fails in the fallback
/// goes to the boundary above.
pub fn catch_error<E: IntoElements, F: IntoElements>(
    view: impl Fn() -> E + 'static,
    fallback: impl Fn(super::ComponentError, Reset) -> F + 'static,
) -> AnyElement {
    region(Region::Catch {
        view: Rc::new(move || view().into_elements()),
        fallback: Rc::new(move |error, reset| fallback(error, reset).into_elements()),
    })
}

/// What tries a [`catch_error`]'s view again (TS: the fallback's `reset`).
#[derive(Clone, Copy)]
pub struct Reset(Signal<Option<super::ComponentError>>);

impl Reset {
    /// Makes the view again, in place of the fallback.
    pub fn reset(&self) {
        self.0.set(None);
    }
}

/// `then`'s elements while a condition holds, else `otherwise`'s (TS: `<If
/// when={…} else={…}>`), made by [`when`]. A branch is made when the
/// condition flips to it, and what it made goes when it flips away.
pub struct If {
    when: Reactive<bool>,
    then: Rc<dyn Fn() -> Vec<AnyElement>>,
    otherwise: Option<Rc<dyn Fn() -> Vec<AnyElement>>>,
}

impl If {
    /// `then` while `when` holds, as [`when`] makes it.
    #[deprecated(note = "use `when(condition, then)`, as `view()` makes a view")]
    pub fn new<E: IntoElements>(
        when: impl IntoReactive<bool>,
        then: impl Fn() -> E + 'static,
    ) -> Self {
        self::when(when, then)
    }

    /// `otherwise` while the condition does not hold (TS: `else={…}`).
    pub fn otherwise<E: IntoElements>(mut self, otherwise: impl Fn() -> E + 'static) -> Self {
        self.otherwise = Some(Rc::new(move || otherwise().into_elements()));
        self
    }
}

/// `then`'s elements while `condition` (a value, a signal or a closure)
/// holds (TS: `<If when={…}>`); [`If::otherwise`] adds what shows while it
/// does not (TS: `else={…}`). A branch is made when the condition flips to
/// it, and what it made goes when it flips away.
///
/// GPUI has no counterpart: its views render again on every change, so a
/// branch there is decided in each render, with `FluentBuilder::when` /
/// `when_else` (NSH's [`super::FluentBuilder`] is that, decided once). NSH's
/// components run once (`docs/dev/reactive-components.md`), so what comes
/// and goes is a region bound to its condition: this one, named after TSX's
/// `<If when>`, its other branch `otherwise` as `else` is a keyword.
pub fn when<E: IntoElements>(
    condition: impl IntoReactive<bool>,
    then: impl Fn() -> E + 'static,
) -> If {
    If {
        when: condition.into_reactive(),
        then: Rc::new(move || then().into_elements()),
        otherwise: None,
    }
}

impl IntoElement for If {
    fn into_element(self) -> AnyElement {
        region(Region::If {
            when: self.when,
            then: self.then,
            otherwise: self.otherwise,
        })
    }
}

/// A row per item of a list, identified by key (TS: `<Each of={…}
/// key="id">{(item, index) => …}</Each>`), made by [`each`].
pub struct Each;

impl Each {
    /// The rows of `items`, as [`each`] makes them.
    #[deprecated(note = "use `each(items, key, row)`, as `view()` makes a view")]
    #[allow(clippy::new_ret_no_self, reason = "TS's <Each> is an element")]
    pub fn new<T, K, E>(
        items: impl IntoReactive<Vec<T>>,
        key: impl Fn(&T) -> K + 'static,
        row: impl Fn(ReadSignal<T>, ReadSignal<usize>) -> E + 'static,
    ) -> AnyElement
    where
        T: Clone + PartialEq + 'static,
        K: Hash + Eq + Clone + 'static,
        E: IntoElements,
    {
        each(items, key, row)
    }
}

/// A row per item of `items` (a value, a signal or a closure), each made by
/// `row(item, index)` and known by `key(item)` (TS: `<Each of={…}
/// key="id">{(item, index) => …}</Each>`). A row is made when its key comes
/// and goes with it; one that stays keeps its nodes and bindings, and gets
/// its item and index as signals that follow it.
pub fn each<T, K, E>(
    items: impl IntoReactive<Vec<T>>,
    key: impl Fn(&T) -> K + 'static,
    row: impl Fn(ReadSignal<T>, ReadSignal<usize>) -> E + 'static,
) -> AnyElement
where
    T: Clone + PartialEq + 'static,
    K: Hash + Eq + Clone + 'static,
    E: IntoElements,
{
    region(Region::Each(Rc::new(Rows {
        items: items.into_reactive(),
        key: Box::new(key),
        row: Box::new(move |item, index| row(item, index).into_elements()),
        state: RefCell::new(Vec::new()),
        next: Cell::new(0),
    })))
}

/// The rows of an [`Each`], with their type erased.
pub(crate) trait EachRows {
    /// Binds the rows (see [`Region::bind`]).
    fn bind(self: Rc<Self>, show: Rc<dyn Fn(Vec<RegionElement>)>);
}

/// What makes a row's elements from its item and index.
type RowFn<T> = Box<dyn Fn(ReadSignal<T>, ReadSignal<usize>) -> Vec<AnyElement>>;

struct Rows<T: 'static, K> {
    items: Reactive<Vec<T>>,
    key: Box<dyn Fn(&T) -> K>,
    row: RowFn<T>,
    /// The live rows, in order.
    state: RefCell<Vec<Row<T, K>>>,
    /// The id of the next row made (its elements' keys).
    next: Cell<u64>,
}

struct Row<T: 'static, K> {
    key: K,
    id: u64,
    item: Signal<T>,
    index: Signal<usize>,
    owner: Owner,
    /// How many elements it made.
    count: usize,
}

/// The key of a row's `i`th element: unique to the row, whatever its key.
fn element_key(id: u64, i: usize) -> super::SharedString {
    format!("\u{1}{id}.{i}").into()
}

/// Keeps the `count` elements of row `id` where they are, in `out`. Out of
/// line, as [`show_row`]: [`Rows::update`] is made for every item and key
/// type.
#[cfg_attr(target_arch = "wasm32", inline(never))]
fn keep_row(out: &mut Vec<RegionElement>, id: u64, count: usize) {
    for i in 0..count {
        let mut kept = super::ElNode::new(Tag::View);
        kept.kind = ElKind::Keep;
        kept.key = Some(element_key(id, i));
        out.push(RegionElement {
            owner: None,
            element: AnyElement(kept),
        });
    }
}

/// Adds the elements a new row `id`, of `owner`, made to `out`.
#[cfg_attr(target_arch = "wasm32", inline(never))]
fn show_row(out: &mut Vec<RegionElement>, id: u64, owner: Owner, elements: Vec<AnyElement>) {
    for (i, mut element) in elements.into_iter().enumerate() {
        element.0.key = Some(element_key(id, i));
        out.push(RegionElement {
            owner: Some(owner),
            element,
        });
    }
}

impl<T: Clone + PartialEq + 'static, K: Hash + Eq + Clone + 'static> EachRows for Rows<T, K> {
    fn bind(self: Rc<Self>, show: Rc<dyn Fn(Vec<RegionElement>)>) {
        // The rows go with the region's owner.
        let rows = self.clone();
        cleanup(move || {
            for row in rows.state.take() {
                row.owner.dispose();
            }
        });
        super::reactive::render_effect(move || {
            let items = self.items.get();
            let out = untracked(|| self.update(items));
            show(out);
        });
    }
}

impl<T: Clone + PartialEq + 'static, K: Hash + Eq + Clone + 'static> Rows<T, K> {
    /// The rows of `items`: the rows of keys that stay are kept (their item
    /// and index updated), new ones made, the others disposed.
    fn update(&self, items: Vec<T>) -> Vec<RegionElement> {
        let mut old: HashMap<K, Row<T, K>> = self
            .state
            .take()
            .into_iter()
            .map(|row| (row.key.clone(), row))
            .collect();
        let mut rows = Vec::with_capacity(items.len());
        let mut out = Vec::new();
        for (index, item) in items.into_iter().enumerate() {
            let key = (self.key)(&item);
            // A key twice: the second is a row of its own.
            match old.remove(&key) {
                Some(row) => {
                    row.item.set(item);
                    row.index.set(index);
                    keep_row(&mut out, row.id, row.count);
                    rows.push(row);
                }
                None => {
                    let id = self.next.get();
                    self.next.set(id + 1);
                    let (owner, (item, index, elements)) = create_root(|| {
                        let item = signal(item);
                        let index = signal(index);
                        let elements = (self.row)(item.read_only(), index.read_only());
                        (item, index, elements)
                    });
                    let count = elements.len();
                    show_row(&mut out, id, owner, elements);
                    rows.push(Row {
                        key,
                        id,
                        item,
                        index,
                        owner,
                        count,
                    });
                }
            }
        }
        for row in old.into_values() {
            row.owner.dispose();
        }
        self.state.replace(rows);
        out
    }
}