nsh-core 0.5.1

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
//! A component's prop as the component reads it ([`Prop`]): a `Copy` handle
//! of a value or a binding in the reactive graph.

use std::{fmt, marker::PhantomData, rc::Rc};

use super::{IntoReactive, Memo, Reactive, ReadSignal, Signal, computed, reactive::Node, signal};

/// A prop of a component that runs once (a field of its `#[derive(Props)]`
/// struct): read it in a binding, `props.max.get()`, and the binding runs
/// again when it changes. `Copy`, like a signal: closures capture it as it
/// is.
///
/// A Rust parent passes a value, a signal, a memo or a closure (`.into()`,
/// [`Prop::bind`]); JS passes values, one prop at a time. In the
/// component's instance each prop is a signal of its own, so a new value
/// from JS (or a parent's binding) reaches only what read it.
pub struct Prop<T: 'static> {
    node: Node,
    origin: Origin,
    _t: PhantomData<fn() -> T>,
}

/// What a prop's node is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Origin {
    /// A signal made for the value it was given: a parent's region making
    /// the element again passes the value on, not the node.
    Value,
    /// A signal, memo or binding of the parent's, read as it is.
    Bound,
    /// An instance's: a signal of its own (which follows the binding a
    /// parent passed, if one did).
    Held,
}

impl<T> Clone for Prop<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Prop<T> {}

/// The same node.
impl<T> PartialEq for Prop<T> {
    fn eq(&self, other: &Self) -> bool {
        self.node == other.node
    }
}

impl<T> fmt::Debug for Prop<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Prop({:?})", self.node)
    }
}

impl<T: Clone + PartialEq + Default + 'static> Default for Prop<T> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T: Clone + PartialEq + 'static> From<T> for Prop<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl From<&'static str> for Prop<super::SharedString> {
    fn from(value: &'static str) -> Self {
        Self::new(value.into())
    }
}

impl From<String> for Prop<super::SharedString> {
    fn from(value: String) -> Self {
        Self::new(value.into())
    }
}

/// An optional text given as text (`label: "Name".into()`).
impl From<&'static str> for Prop<Option<super::SharedString>> {
    fn from(value: &'static str) -> Self {
        Self::new(Some(value.into()))
    }
}

impl From<String> for Prop<Option<super::SharedString>> {
    fn from(value: String) -> Self {
        Self::new(Some(value.into()))
    }
}

impl From<super::SharedString> for Prop<Option<super::SharedString>> {
    fn from(value: super::SharedString) -> Self {
        Self::new(Some(value))
    }
}

macro_rules! from_handles {
    ($($handle:ident),*) => {$(
        impl<T: Clone + PartialEq + 'static> From<$handle<T>> for Prop<T> {
            fn from(value: $handle<T>) -> Self {
                Self::of(value.node(), Origin::Bound)
            }
        }
    )*};
}

from_handles!(Signal, ReadSignal, Memo);

impl<T: Clone + PartialEq + 'static> From<Reactive<T>> for Prop<T> {
    fn from(value: Reactive<T>) -> Self {
        match value {
            Reactive::Static(v) => Self::new(v),
            Reactive::Bound(f) => Self::bind(move || f()),
        }
    }
}

impl<T: Clone + PartialEq + 'static> Prop<T> {
    /// A prop given `value` (a signal of the current owner).
    pub fn new(value: T) -> Self {
        Self::of(signal(value).node(), Origin::Value)
    }

    /// A prop bound to `f` (a memo of the current owner): run again when
    /// what it reads changes.
    pub fn bind(f: impl Fn() -> T + 'static) -> Self {
        Self::of(computed(f).node(), Origin::Bound)
    }

    fn of(node: Node, origin: Origin) -> Self {
        Self {
            node,
            origin,
            _t: PhantomData,
        }
    }

    /// The value, subscribing the running computation.
    #[track_caller]
    pub fn get(&self) -> T {
        self.with(T::clone)
    }

    /// `f` of the value, subscribing the running computation.
    #[track_caller]
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        self.node.with::<T, R>("a prop", f)
    }

    /// The value, without subscribing.
    #[track_caller]
    pub fn get_untracked(&self) -> T {
        super::untracked(|| self.get())
    }

    /// `f` of the value, without subscribing.
    #[track_caller]
    pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        super::untracked(|| self.with(f))
    }

    /// The prop of an instance, made when its view is: a value it was given
    /// stays in the signal it was made with (the instance's props are made
    /// under an owner that lives as long as the instance); a parent's
    /// binding is followed by a signal of the instance's own, which a
    /// computation of the current owner (the instance's) writes.
    #[doc(hidden)]
    pub fn __hold(&self) -> Self {
        match self.origin {
            Origin::Held => *self,
            Origin::Value => Self::of(self.node, Origin::Held),
            Origin::Bound => {
                let binding = *self;
                let node = signal(binding.get_untracked()).node();
                // The binding is of the region that made the element: when
                // that region runs again it goes, and the instance with it
                // once the core releases its host. A write doing both may
                // still reach this effect first; there is nothing to follow.
                super::reactive::render_effect(move || {
                    if binding.node.is_live() {
                        node.set::<T>(binding.get());
                    }
                });
                Self::of(node, Origin::Held)
            }
        }
    }

    /// Takes `value`: a signal of the prop's own (made for a value, or an
    /// instance's) takes a static value, updating what read it; otherwise
    /// the prop becomes the new one (an instance's, before its view is
    /// made). Whether it changed.
    #[doc(hidden)]
    pub fn __set(&mut self, value: Reactive<T>) -> bool {
        match (self.origin, value) {
            (Origin::Value | Origin::Held, Reactive::Static(v)) => {
                // An equal value is no change: nothing is written (the
                // prop's signal would compare it again and notify no one).
                let changed = self.with_untracked(|old| *old != v);
                if changed {
                    self.node.set::<T>(v);
                }
                changed
            }
            (Origin::Held, Reactive::Bound(_)) => {
                log::error!(
                    target: "js",
                    "a component's prop takes a binding only when its element is made"
                );
                false
            }
            (_, value) => {
                *self = Self::from(value);
                true
            }
        }
    }

    /// An instance's prop, before its view is made, takes what `new` gives:
    /// its value when it was given a value, else its binding.
    #[doc(hidden)]
    pub fn __update_from(&mut self, new: &Self) -> bool {
        if new.origin == Origin::Value {
            return self.__set(Reactive::Static(new.get_untracked()));
        }
        if self == new {
            return false;
        }
        *self = *new;
        true
    }
}

/// The app's children placed here, all at one place (`.child(props.children)`).
impl super::IntoElement for Prop<super::Children> {
    fn into_element(self) -> super::AnyElement {
        self.get_untracked().into_element()
    }
}

/// The app's children, to wrap one by one (`.children_each(props.children, ..)`).
impl From<Prop<super::Children>> for super::Children {
    fn from(children: Prop<super::Children>) -> Self {
        children.get_untracked()
    }
}

impl Prop<Option<super::Slot>> {
    /// The slot where the app fills it, styled by `style`: it comes and
    /// goes as the app fills and empties it.
    pub fn place(
        self,
        style: impl Fn(super::SlotElement) -> super::SlotElement + 'static,
    ) -> super::AnyElement {
        super::dynamic(move || self.get().map(|slot| style(slot.element())))
    }
}

/// A prop passed on, to an element's setter or a child's prop: bound to it
/// (`text(props.title)`).
impl<T: Clone + PartialEq + 'static> IntoReactive<T> for Prop<T> {
    fn into_reactive(self) -> Reactive<T> {
        Reactive::Bound(Rc::new(move || self.get()))
    }
}

/// What a component's prop setter takes (`button().disabled(..)`): a value
/// of a type that becomes a `T` (set once; a `T` for an `Option<T>`, and a
/// string for an optional text), a [`Signal`], [`Memo`],
/// [`ReadSignal`], [`Prop`] or [`Reactive`] of `T`, or a closure returning
/// what becomes a `T` (bound: run again when what it reads changes). `M`
/// tells them apart: it is inferred, never written.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a prop of `{T}`",
    label = "not a prop of `{T}`",
    note = "a prop is a value that becomes a `{T}`, a signal, memo or prop of it, or a closure `move || ..` returning one"
)]
pub trait IntoProp<T, M> {
    /// As a value or a binding.
    fn into_prop(self) -> Reactive<T>;
}

/// How a value is a prop ([`IntoProp`]).
#[doc(hidden)]
pub struct PropValue(());

/// How a closure is a prop ([`IntoProp`]).
#[doc(hidden)]
pub struct PropClosure(());

/// How a reactive handle is a prop ([`IntoProp`]).
#[doc(hidden)]
pub struct PropHandle(());

/// How a string is an optional text prop ([`IntoProp`]).
#[doc(hidden)]
pub struct PropText(());

/// A string as a set text prop (`.accessibility_label("Save")`).
impl IntoProp<Option<super::SharedString>, PropText> for &'static str {
    fn into_prop(self) -> Reactive<Option<super::SharedString>> {
        Reactive::Static(Some(self.into()))
    }
}

/// A string as a set text prop.
impl IntoProp<Option<super::SharedString>, PropText> for String {
    fn into_prop(self) -> Reactive<Option<super::SharedString>> {
        Reactive::Static(Some(self.into()))
    }
}

/// A URL as a set image prop (`.src("https://…")`).
impl IntoProp<Option<super::ImageSrc>, PropText> for &'static str {
    fn into_prop(self) -> Reactive<Option<super::ImageSrc>> {
        Reactive::Static(Some(self.into()))
    }
}

/// A URL as a set image prop.
impl IntoProp<Option<super::ImageSrc>, PropText> for String {
    fn into_prop(self) -> Reactive<Option<super::ImageSrc>> {
        Reactive::Static(Some(self.into()))
    }
}

/// A crate's image as a set image prop (`.src(asset!("ada.png"))`).
impl IntoProp<Option<super::ImageSrc>, PropText> for super::ImageAsset {
    fn into_prop(self) -> Reactive<Option<super::ImageSrc>> {
        Reactive::Static(Some(self.into()))
    }
}

impl<T, U: Into<T>> IntoProp<T, PropValue> for U {
    fn into_prop(self) -> Reactive<T> {
        Reactive::Static(self.into())
    }
}

impl<T: 'static, U: Into<T>, F: Fn() -> U + 'static> IntoProp<T, PropClosure> for F {
    fn into_prop(self) -> Reactive<T> {
        Reactive::Bound(Rc::new(move || self().into()))
    }
}

macro_rules! prop_handles {
    ($($handle:ident),*) => {$(
        impl<T: Clone + PartialEq + 'static> IntoProp<T, PropHandle> for $handle<T> {
            fn into_prop(self) -> Reactive<T> {
                self.into_reactive()
            }
        }
    )*};
}

prop_handles!(Signal, ReadSignal, Memo, Prop);

impl<T> IntoProp<T, PropHandle> for Reactive<T> {
    fn into_prop(self) -> Reactive<T> {
        self
    }
}

/// A field's new value from JS (`None`: unset, back to its default `init`):
/// what each arm of `#[derive(Props)]`'s `set` does, once per type rather
/// than once per field.
fn take_prop<T: Clone + 'static>(
    value: Option<super::AnyValue>,
    js: &'static str,
    init: fn() -> T,
) -> Result<T, super::PropError> {
    match value {
        Some(v) => v.take::<T>().ok_or_else(|| of_another_type(js)),
        None => Ok(init()),
    }
}

#[cold]
#[inline(never)]
fn of_another_type(js: &'static str) -> super::PropError {
    super::PropError(format!("`{js}`: a value of another type"))
}

/// `#[derive(Props)]`'s `set` of a `Prop<T>` field `js`: whether it changed.
#[inline(never)]
pub fn set_held<T: Clone + PartialEq + 'static>(
    prop: &mut Prop<T>,
    value: Option<super::AnyValue>,
    js: &'static str,
    init: fn() -> T,
) -> Result<bool, super::PropError> {
    Ok(prop.__set(Reactive::Static(take_prop(value, js, init)?)))
}

/// `#[derive(Props)]`'s `set` of a plain field `js`: whether it changed.
#[inline(never)]
pub fn set_plain<T: Clone + PartialEq + 'static>(
    field: &mut T,
    value: Option<super::AnyValue>,
    js: &'static str,
    init: fn() -> T,
) -> Result<bool, super::PropError> {
    let value = take_prop(value, js, init)?;
    let changed = *field != value;
    *field = value;
    Ok(changed)
}