nsh-core 0.7.2

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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! [`Rows`]: the rows of data a component takes from JS (`data: T[]`), read
//! natively as columns of numbers and of texts by key, and [`RowAccessor`]:
//! how it reads a value of each row (a key, or the app's function of a
//! row), and [`RowText`]: how it reads a text of each row (a label beside
//! a value, a category).

use std::{fmt, rc::Rc, sync::Arc};

use super::{
    Callback, JsValue, PropError, SharedString, TsTypes,
    callback::CallbackHandle,
    class::{Arg, Ret},
    js::{JsHost, JsIn, JsKind, JsOwned},
};

/// Rows of data a component takes, `T[]` in TypeScript (its props generic
/// over `T`: `#[props(generic)]`): JS objects whose number and string
/// fields are read once, when JS sets the prop, into a column per key, so
/// the component reads its values by key ([`Rows::column`]) without
/// calling into JS again. A field that is not a number on some row
/// (missing, `null`, a string) is `NaN` there: a gap.
#[derive(Clone, Default)]
pub struct Rows {
    len: usize,
    columns: Vec<(SharedString, Arc<[f64]>)>,
    /// The string fields, a column per key (empty where a row has none):
    /// what [`RowText`] reads of a field that holds text.
    texts: Vec<(SharedString, Arc<[SharedString]>)>,
    /// The JS array, kept to hand its rows to the app's functions
    /// ([`RowAccessor::Js`]); none for rows made in Rust.
    js: Option<Rc<dyn CallbackHandle>>,
}

impl fmt::Debug for Rows {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Rows")
            .field("len", &self.len)
            .field("columns", &self.columns)
            .field("texts", &self.texts)
            .finish_non_exhaustive()
    }
}

impl Rows {
    /// `len` rows with the number fields `columns` (each `len` long;
    /// shorter ones end in gaps).
    pub fn from_columns(
        len: usize,
        columns: impl IntoIterator<Item = (SharedString, Vec<f64>)>,
    ) -> Self {
        let columns = columns
            .into_iter()
            .map(|(key, mut values)| {
                values.resize(len, f64::NAN);
                (key, values.into())
            })
            .collect();
        Self {
            len,
            columns,
            texts: Vec::new(),
            js: None,
        }
    }

    /// Row `index` as the app's JS value, for a function of the app's
    /// ([`RowAccessor::Js`]); `None` for rows made in Rust.
    pub fn row(&self, index: usize) -> Option<RowRef> {
        (index < self.len).then(|| RowRef {
            rows: self.js.clone(),
            index,
        })
    }

    /// How many rows there are.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether there are none.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The values of field `key`, one per row (`NaN` where a row has no
    /// number there); `None` when no row has a number there.
    pub fn column(&self, key: &str) -> Option<&[f64]> {
        self.columns
            .iter()
            .find(|(k, _)| &**k == key)
            .map(|(_, values)| &**values)
    }

    /// The texts of string field `key`, one per row (empty where a row has
    /// no string there); `None` when no row has one.
    fn text_column(&self, key: &str) -> Option<&[SharedString]> {
        self.texts
            .iter()
            .find(|(k, _)| &**k == key)
            .map(|(_, texts)| &**texts)
    }

    /// The keys with numbers, in the order they first appear.
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.columns.iter().map(|(k, _)| &**k)
    }
}

/// Equal rows hold the same numbers (gaps included, which `NaN`'s own
/// comparison would tell apart) and texts: a prop set to equal rows
/// changes nothing.
impl PartialEq for Rows {
    fn eq(&self, other: &Self) -> bool {
        self.len == other.len
            && self.columns.len() == other.columns.len()
            && self.columns.iter().zip(&other.columns).all(|(a, b)| {
                a.0 == b.0
                    && a.1.len() == b.1.len()
                    && a.1
                        .iter()
                        .zip(b.1.iter())
                        .all(|(x, y)| x.to_bits() == y.to_bits())
            })
            && self.texts == other.texts
    }
}

impl JsValue for Rows {
    fn ts_type(_types: &mut TsTypes) -> String {
        "T[]".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        let len = value
            .array_len()?
            .ok_or_else(|| value.expected("an array of objects"))?;
        let mut columns: Vec<(SharedString, Vec<f64>)> = Vec::new();
        let mut texts: Vec<(SharedString, Vec<SharedString>)> = Vec::new();
        for i in 0..len {
            let row = value.index(i)?;
            let row = row.get();
            if row.kind() != JsKind::Object {
                continue;
            }
            for key in row.keys()? {
                let field = row.field(&key)?;
                let field = field.get();
                if let Some(n) = field.as_number() {
                    let at = match columns.iter().position(|(k, _)| **k == *key) {
                        Some(at) => at,
                        None => {
                            columns.push((SharedString::from(key), vec![f64::NAN; len]));
                            columns.len() - 1
                        }
                    };
                    columns[at].1[i] = n;
                } else if field.kind() == JsKind::String {
                    let Some(text) = field.as_string() else {
                        continue;
                    };
                    let at = match texts.iter().position(|(k, _)| **k == *key) {
                        Some(at) => at,
                        None => {
                            let column = vec![SharedString::default(); len];
                            texts.push((SharedString::from(key), column));
                            texts.len() - 1
                        }
                    };
                    texts[at].1[i] = text.into();
                }
            }
        }
        let mut rows = Rows::from_columns(len, columns);
        rows.texts = texts.into_iter().map(|(k, t)| (k, t.into())).collect();
        rows.js = value.host().retain(value.raw());
        Ok(rows)
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        // The numbers and texts it read, one object per row.
        let mut rows = Vec::with_capacity(self.len);
        for i in 0..self.len {
            let row = JsOwned::new(host, host.new_object()?);
            for (key, values) in &self.columns {
                let n = values[i];
                if !n.is_nan() {
                    host.set_field(row.get().raw(), key, host.new_number(n))?;
                }
            }
            for (key, texts) in &self.texts {
                if !texts[i].is_empty() {
                    host.set_field(row.get().raw(), key, host.new_string(&texts[i])?)?;
                }
            }
            rows.push(row);
        }
        let raws = rows.into_iter().map(JsOwned::into_raw).collect();
        Ok(JsOwned::new(host, host.new_array(raws)?))
    }
}

/// A row of [`Rows`] as the app's JS value: the first argument of the
/// app's function of a row ([`RowAccessor::Js`]), the object the app put
/// in its array (`undefined` for rows made in Rust, and by default).
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct RowRef {
    rows: Option<Rc<dyn CallbackHandle>>,
    index: usize,
}

impl Ret for RowRef {
    fn ts_type(_types: &mut TsTypes) -> String {
        "T".into()
    }

    fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let Some(array) = self.rows.as_ref().and_then(|r| r.value(host)) else {
            return Ok(JsOwned::new(host, host.undefined()));
        };
        let array = JsOwned::new(host, array);
        let row = array.get().index(self.index)?;
        Ok(row)
    }
}

/// How a component reads a value of each of its [`Rows`] (TS
/// `Extract<keyof T, string> | ((d: T, index: number) => number)`): the
/// number field of a name, read natively; or the app's function of a row
/// and its index, which a component calls once per row when the rows or
/// the function change, in the next JS turn, and never while it draws or
/// follows the pointer (so the function is pure: the same row, the same
/// number).
#[derive(Clone)]
pub enum RowAccessor {
    /// The number field `key`.
    Key(SharedString),
    /// The app's JS function of a row and its index.
    Js(Callback<(RowRef, u32), f64>),
    /// A Rust function of a row's index, for components made in Rust.
    Rust(Rc<dyn Fn(usize) -> f64>),
}

impl RowAccessor {
    /// The field `key`.
    pub fn key(key: impl Into<SharedString>) -> Self {
        RowAccessor::Key(key.into())
    }

    /// The value of row `index` that `f` gives (Rust).
    pub fn from_fn(f: impl Fn(usize) -> f64 + 'static) -> Self {
        RowAccessor::Rust(Rc::new(f))
    }

    /// The values of `rows` when they need no JS (a key or a Rust
    /// function); `None` for a JS function ([`RowAccessor::values`]).
    pub fn values_now(&self, rows: &Rows) -> Option<Arc<[f64]>> {
        match self {
            RowAccessor::Key(key) => Some(
                rows.column(key)
                    .map(Arc::from)
                    .unwrap_or_else(|| vec![f64::NAN; rows.len()].into()),
            ),
            RowAccessor::Rust(f) => Some((0..rows.len()).map(|i| f(i)).collect()),
            RowAccessor::Js(_) => None,
        }
    }

    /// The values of `rows`: a JS function is called once per row, in the
    /// next JS turn (a row whose call throws or returns no number is
    /// `NaN`, a gap).
    pub async fn values(&self, rows: &Rows) -> Arc<[f64]> {
        if let Some(values) = self.values_now(rows) {
            return values;
        }
        let RowAccessor::Js(f) = self else {
            unreachable!("the other accessors need no JS")
        };
        let answers: Vec<_> = (0..rows.len())
            .filter_map(|i| rows.row(i).map(|row| f.call_async((row, i as u32))))
            .collect();
        let mut out = Vec::with_capacity(answers.len());
        for answer in answers {
            out.push(match answer.await {
                Ok(v) if v.is_finite() => v,
                _ => f64::NAN,
            });
        }
        out.into()
    }
}

impl fmt::Debug for RowAccessor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RowAccessor::Key(key) => f.debug_tuple("Key").field(key).finish(),
            RowAccessor::Js(_) => f.write_str("Js"),
            RowAccessor::Rust(_) => f.write_str("Rust"),
        }
    }
}

/// The same key, or the same function.
impl PartialEq for RowAccessor {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (RowAccessor::Key(a), RowAccessor::Key(b)) => a == b,
            (RowAccessor::Js(a), RowAccessor::Js(b)) => Rc::ptr_eq(a.handle(), b.handle()),
            (RowAccessor::Rust(a), RowAccessor::Rust(b)) => Rc::ptr_eq(a, b),
            _ => false,
        }
    }
}

impl From<&str> for RowAccessor {
    fn from(key: &str) -> Self {
        RowAccessor::key(key.to_owned())
    }
}

impl JsValue for RowAccessor {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Extract<keyof T, string> | ((d: T, index: number) => number)".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        match value.kind() {
            JsKind::String => <SharedString as JsValue>::from_js(value).map(RowAccessor::Key),
            JsKind::Function => {
                <Callback<(RowRef, u32), f64> as Arg>::from_js(value).map(RowAccessor::Js)
            }
            _ => Err(value.expected("a field name or a function of a row")),
        }
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        match self {
            RowAccessor::Key(key) => key.to_js(host),
            // A function stays the app's: it is not handed back.
            _ => Ok(JsOwned::new(host, host.undefined())),
        }
    }
}

/// How a component reads a text of each of its [`Rows`] (TS
/// `Extract<keyof T, string> | ((d: T, index: number) => string)`): the
/// field of a name, its string or its number written as JS writes it
/// (`String(n)`), read natively; or the app's function of a row and its
/// index, for text the app formats (units, separators, its locale), which
/// a component calls once per row when the rows or the function change,
/// in the next JS turn, and never while it draws (so the function is
/// pure: the same row, the same text). [`RowAccessor`]'s twin for what a
/// component shows as text, such as a value beside a bar, or reads as a
/// category.
#[derive(Clone)]
pub enum RowText {
    /// The field `key`: its string, or its number as JS writes it.
    Key(SharedString),
    /// The app's JS function of a row and its index.
    Js(Callback<(RowRef, u32), SharedString>),
    /// A Rust function of a row's index, for components made in Rust.
    Rust(Rc<dyn Fn(usize) -> SharedString>),
}

impl RowText {
    /// The field `key`: its strings, and its numbers as JS writes them.
    pub fn key(key: impl Into<SharedString>) -> Self {
        RowText::Key(key.into())
    }

    /// The text of row `index` that `f` gives (Rust).
    pub fn from_fn(f: impl Fn(usize) -> SharedString + 'static) -> Self {
        RowText::Rust(Rc::new(f))
    }

    /// The texts of `rows` when they need no JS (a key or a Rust
    /// function); `None` for a JS function ([`RowText::texts`]). A row
    /// without a string or a number in the field has no text (empty).
    pub fn texts_now(&self, rows: &Rows) -> Option<Arc<[SharedString]>> {
        match self {
            RowText::Key(key) => {
                let (numbers, texts) = (rows.column(key), rows.text_column(key));
                Some(
                    (0..rows.len())
                        .map(|i| match numbers.map(|n| n[i]) {
                            Some(n) if !n.is_nan() => js_number_text(n),
                            _ => texts.map(|t| t[i].clone()).unwrap_or_default(),
                        })
                        .collect(),
                )
            }
            RowText::Rust(f) => Some((0..rows.len()).map(|i| f(i)).collect()),
            RowText::Js(_) => None,
        }
    }

    /// The texts of `rows`: a JS function is called once per row, in the
    /// next JS turn (a row whose call throws or returns no string has no
    /// text).
    pub async fn texts(&self, rows: &Rows) -> Arc<[SharedString]> {
        if let Some(texts) = self.texts_now(rows) {
            return texts;
        }
        let RowText::Js(f) = self else {
            unreachable!("the other texts need no JS")
        };
        let answers: Vec<_> = (0..rows.len())
            .filter_map(|i| rows.row(i).map(|row| f.call_async((row, i as u32))))
            .collect();
        let mut out = Vec::with_capacity(answers.len());
        for answer in answers {
            out.push(answer.await.unwrap_or_default());
        }
        out.into()
    }
}

/// `n` as JS's `String(n)` writes the numbers rows hold: whole numbers
/// without a fraction, `-0` as `0`, nothing for a gap (`NaN`).
fn js_number_text(n: f64) -> SharedString {
    if n.is_nan() {
        return SharedString::default();
    }
    if n == 0.0 {
        return "0".into();
    }
    if n.is_infinite() {
        return if n > 0.0 { "Infinity" } else { "-Infinity" }.into();
    }
    // Rust writes 1820.0 as "1820" and 0.25 as "0.25", as JS does, short
    // of the exponents JS switches to past 1e21 and below 1e-6.
    format!("{n}").into()
}

impl fmt::Debug for RowText {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RowText::Key(key) => f.debug_tuple("Key").field(key).finish(),
            RowText::Js(_) => f.write_str("Js"),
            RowText::Rust(_) => f.write_str("Rust"),
        }
    }
}

/// The same key, or the same function.
impl PartialEq for RowText {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (RowText::Key(a), RowText::Key(b)) => a == b,
            (RowText::Js(a), RowText::Js(b)) => Rc::ptr_eq(a.handle(), b.handle()),
            (RowText::Rust(a), RowText::Rust(b)) => Rc::ptr_eq(a, b),
            _ => false,
        }
    }
}

impl From<&str> for RowText {
    fn from(key: &str) -> Self {
        RowText::key(key.to_owned())
    }
}

impl JsValue for RowText {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Extract<keyof T, string> | ((d: T, index: number) => string)".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        match value.kind() {
            JsKind::String => <SharedString as JsValue>::from_js(value).map(RowText::Key),
            JsKind::Function => {
                <Callback<(RowRef, u32), SharedString> as Arg>::from_js(value).map(RowText::Js)
            }
            _ => Err(value.expected("a field name or a function of a row")),
        }
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        match self {
            RowText::Key(key) => key.to_js(host),
            // A function stays the app's: it is not handed back.
            _ => Ok(JsOwned::new(host, host.undefined())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn columns_by_key_with_gaps() {
        let rows = Rows::from_columns(
            3,
            [
                ("price".into(), vec![1.0, 2.0, 3.0]),
                ("avg".into(), vec![1.5]),
            ],
        );
        assert_eq!(rows.len(), 3);
        assert_eq!(rows.column("price"), Some(&[1.0, 2.0, 3.0][..]));
        let avg = rows.column("avg").unwrap();
        assert_eq!(avg[0], 1.5);
        assert!(avg[1].is_nan() && avg[2].is_nan());
        assert_eq!(rows.column("time"), None);
        assert_eq!(rows.keys().collect::<Vec<_>>(), ["price", "avg"]);
        // Gaps compare equal.
        assert_eq!(rows, rows.clone());
    }

    /// A field and a Rust function read at once; a field no row has is
    /// all gaps; the same key or function is equal, another is not.
    #[test]
    fn accessors_read_a_value_of_each_row() {
        let rows = Rows::from_columns(3, [("price".into(), vec![1.0, 2.0, 3.0])]);
        let key = RowAccessor::key("price");
        assert_eq!(key.values_now(&rows).as_deref(), Some(&[1.0, 2.0, 3.0][..]));
        let missing = RowAccessor::key("time").values_now(&rows).unwrap();
        assert!(missing.len() == 3 && missing.iter().all(|v| v.is_nan()));
        let twice = RowAccessor::from_fn(|i| i as f64 * 2.0);
        assert_eq!(
            twice.values_now(&rows).as_deref(),
            Some(&[0.0, 2.0, 4.0][..])
        );
        assert_eq!(key, RowAccessor::from("price"));
        assert_eq!(twice, twice.clone());
        assert_ne!(twice, RowAccessor::from_fn(|i| i as f64 * 2.0));
        // Rust rows have no JS value to hand a function.
        assert!(rows.row(0).is_some_and(|r| r.rows.is_none()));
        assert!(rows.row(3).is_none());
    }

    /// A field's numbers as JS writes them, gaps empty; a Rust function's
    /// texts; the same key or function is equal.
    #[test]
    fn texts_read_a_text_of_each_row() {
        let rows = Rows::from_columns(4, [("v".into(), vec![1820.0, 0.25, -0.0, f64::NAN])]);
        let key = RowText::key("v");
        let texts = key.texts_now(&rows).unwrap();
        assert_eq!(
            texts.iter().map(|t| &**t).collect::<Vec<_>>(),
            ["1820", "0.25", "0", ""]
        );
        let missing = RowText::key("w").texts_now(&rows).unwrap();
        assert!(missing.len() == 4 && missing.iter().all(|t| t.is_empty()));
        let named = RowText::from_fn(|i| format!("#{i}").into());
        assert_eq!(&*named.texts_now(&rows).unwrap()[3], "#3");
        assert_eq!(key, RowText::from("v"));
        assert_ne!(named, RowText::from_fn(|i| format!("#{i}").into()));
    }

    /// A field's strings as they are (a category), its numbers as JS
    /// writes them where a row holds one; rows with different texts are
    /// different rows.
    #[test]
    fn texts_read_a_string_field_as_it_is() {
        let mut rows = Rows::from_columns(3, [("region".into(), vec![f64::NAN, 7.0])]);
        let before = rows.clone();
        rows.texts = vec![(
            "region".into(),
            ["EMEA", "", "APAC"].map(SharedString::from).into(),
        )];
        let texts = RowText::key("region").texts_now(&rows).unwrap();
        assert_eq!(
            texts.iter().map(|t| &**t).collect::<Vec<_>>(),
            ["EMEA", "7", "APAC"]
        );
        assert_ne!(rows, before);
        assert_eq!(rows.text_column("region").map(<[_]>::len), Some(3));
        assert_eq!(rows.text_column("name"), None);
    }
}