Skip to main content

nsh_core/element/
prop.rs

1//! A component's prop as the component reads it ([`Prop`]): a `Copy` handle
2//! of a value or a binding in the reactive graph.
3
4use std::{fmt, marker::PhantomData, rc::Rc};
5
6use super::{IntoReactive, Memo, Reactive, ReadSignal, Signal, computed, reactive::Node, signal};
7
8/// A prop of a component that runs once (a field of its `#[derive(Props)]`
9/// struct): read it in a binding, `props.max.get()`, and the binding runs
10/// again when it changes. `Copy`, like a signal: closures capture it as it
11/// is.
12///
13/// A Rust parent passes a value, a signal, a memo or a closure (`.into()`,
14/// [`Prop::bind`]); JS passes values, one prop at a time. In the
15/// component's instance each prop is a signal of its own, so a new value
16/// from JS (or a parent's binding) reaches only what read it.
17pub struct Prop<T: 'static> {
18    node: Node,
19    origin: Origin,
20    _t: PhantomData<fn() -> T>,
21}
22
23/// What a prop's node is.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25enum Origin {
26    /// A signal made for the value it was given: a parent's region making
27    /// the element again passes the value on, not the node.
28    Value,
29    /// A signal, memo or binding of the parent's, read as it is.
30    Bound,
31    /// An instance's: a signal of its own (which follows the binding a
32    /// parent passed, if one did).
33    Held,
34}
35
36impl<T> Clone for Prop<T> {
37    fn clone(&self) -> Self {
38        *self
39    }
40}
41
42impl<T> Copy for Prop<T> {}
43
44/// The same node.
45impl<T> PartialEq for Prop<T> {
46    fn eq(&self, other: &Self) -> bool {
47        self.node == other.node
48    }
49}
50
51impl<T> fmt::Debug for Prop<T> {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(f, "Prop({:?})", self.node)
54    }
55}
56
57impl<T: Clone + PartialEq + Default + 'static> Default for Prop<T> {
58    fn default() -> Self {
59        Self::new(T::default())
60    }
61}
62
63impl<T: Clone + PartialEq + 'static> From<T> for Prop<T> {
64    fn from(value: T) -> Self {
65        Self::new(value)
66    }
67}
68
69impl From<&'static str> for Prop<super::SharedString> {
70    fn from(value: &'static str) -> Self {
71        Self::new(value.into())
72    }
73}
74
75impl From<String> for Prop<super::SharedString> {
76    fn from(value: String) -> Self {
77        Self::new(value.into())
78    }
79}
80
81/// An optional text given as text (`label: "Name".into()`).
82impl From<&'static str> for Prop<Option<super::SharedString>> {
83    fn from(value: &'static str) -> Self {
84        Self::new(Some(value.into()))
85    }
86}
87
88impl From<String> for Prop<Option<super::SharedString>> {
89    fn from(value: String) -> Self {
90        Self::new(Some(value.into()))
91    }
92}
93
94impl From<super::SharedString> for Prop<Option<super::SharedString>> {
95    fn from(value: super::SharedString) -> Self {
96        Self::new(Some(value))
97    }
98}
99
100/// An optional flag given as a flag (`.cover(false)`): set, where left out
101/// is a default of the component's own.
102impl From<bool> for Prop<Option<bool>> {
103    fn from(value: bool) -> Self {
104        Self::new(Some(value))
105    }
106}
107
108macro_rules! from_handles {
109    ($($handle:ident),*) => {$(
110        impl<T: Clone + PartialEq + 'static> From<$handle<T>> for Prop<T> {
111            fn from(value: $handle<T>) -> Self {
112                Self::of(value.node(), Origin::Bound)
113            }
114        }
115    )*};
116}
117
118from_handles!(Signal, ReadSignal, Memo);
119
120impl<T: Clone + PartialEq + 'static> From<Reactive<T>> for Prop<T> {
121    fn from(value: Reactive<T>) -> Self {
122        match value {
123            Reactive::Static(v) => Self::new(v),
124            Reactive::Bound(f) => Self::bind(move || f()),
125        }
126    }
127}
128
129impl<T: Clone + PartialEq + 'static> Prop<T> {
130    /// A prop given `value` (a signal of the current owner).
131    pub fn new(value: T) -> Self {
132        Self::of(signal(value).node(), Origin::Value)
133    }
134
135    /// A prop bound to `f` (a memo of the current owner): run again when
136    /// what it reads changes.
137    pub fn bind(f: impl Fn() -> T + 'static) -> Self {
138        Self::of(computed(f).node(), Origin::Bound)
139    }
140
141    fn of(node: Node, origin: Origin) -> Self {
142        Self {
143            node,
144            origin,
145            _t: PhantomData,
146        }
147    }
148
149    /// The value, subscribing the running computation.
150    #[track_caller]
151    pub fn get(&self) -> T {
152        self.with(T::clone)
153    }
154
155    /// `f` of the value, subscribing the running computation.
156    #[track_caller]
157    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
158        self.node.with::<T, R>("a prop", f)
159    }
160
161    /// The value, without subscribing.
162    #[track_caller]
163    pub fn get_untracked(&self) -> T {
164        super::untracked(|| self.get())
165    }
166
167    /// `f` of the value, without subscribing.
168    #[track_caller]
169    pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
170        super::untracked(|| self.with(f))
171    }
172
173    /// The prop of an instance, made when its view is: a value it was given
174    /// stays in the signal it was made with (the instance's props are made
175    /// under an owner that lives as long as the instance); a parent's
176    /// binding is followed by a signal of the instance's own, which a
177    /// computation of the current owner (the instance's) writes.
178    #[doc(hidden)]
179    pub fn __hold(&self) -> Self {
180        match self.origin {
181            Origin::Held => *self,
182            Origin::Value => Self::of(self.node, Origin::Held),
183            Origin::Bound => {
184                let binding = *self;
185                let node = signal(binding.get_untracked()).node();
186                // The binding is of the region that made the element: when
187                // that region runs again it goes, and the instance with it
188                // once the core releases its host. A write doing both may
189                // still reach this effect first; there is nothing to follow.
190                super::reactive::render_effect(move || {
191                    if binding.node.is_live() {
192                        node.set::<T>(binding.get());
193                    }
194                });
195                Self::of(node, Origin::Held)
196            }
197        }
198    }
199
200    /// Takes `value`: a signal of the prop's own (made for a value, or an
201    /// instance's) takes a static value, updating what read it; otherwise
202    /// the prop becomes the new one (an instance's, before its view is
203    /// made). Whether it changed.
204    #[doc(hidden)]
205    pub fn __set(&mut self, value: Reactive<T>) -> bool {
206        match (self.origin, value) {
207            (Origin::Value | Origin::Held, Reactive::Static(v)) => {
208                // An equal value is no change: nothing is written (the
209                // prop's signal would compare it again and notify no one).
210                let changed = self.with_untracked(|old| *old != v);
211                if changed {
212                    self.node.set::<T>(v);
213                }
214                changed
215            }
216            (Origin::Held, Reactive::Bound(_)) => {
217                log::error!(
218                    target: "js",
219                    "a component's prop takes a binding only when its element is made"
220                );
221                false
222            }
223            (_, value) => {
224                *self = Self::from(value);
225                true
226            }
227        }
228    }
229
230    /// An instance's prop, before its view is made, takes what `new` gives:
231    /// its value when it was given a value, else its binding.
232    #[doc(hidden)]
233    pub fn __update_from(&mut self, new: &Self) -> bool {
234        if new.origin == Origin::Value {
235            return self.__set(Reactive::Static(new.get_untracked()));
236        }
237        if self == new {
238            return false;
239        }
240        *self = *new;
241        true
242    }
243}
244
245/// The app's children placed here, all at one place (`.child(props.children)`).
246impl super::IntoElement for Prop<super::Children> {
247    fn into_element(self) -> super::AnyElement {
248        self.get_untracked().into_element()
249    }
250}
251
252/// The app's children, to wrap one by one (`.children_each(props.children, ..)`).
253impl From<Prop<super::Children>> for super::Children {
254    fn from(children: Prop<super::Children>) -> Self {
255        children.get_untracked()
256    }
257}
258
259impl Prop<Option<super::Slot>> {
260    /// The slot where the app fills it, styled by `style`: it comes and
261    /// goes as the app fills and empties it.
262    pub fn place(
263        self,
264        style: impl Fn(super::SlotElement) -> super::SlotElement + 'static,
265    ) -> super::AnyElement {
266        super::dynamic(move || self.get().map(|slot| style(slot.element())))
267    }
268}
269
270/// A prop passed on, to an element's setter or a child's prop: bound to it
271/// (`text(props.title)`).
272impl<T: Clone + PartialEq + 'static> IntoReactive<T> for Prop<T> {
273    fn into_reactive(self) -> Reactive<T> {
274        Reactive::Bound(Rc::new(move || self.get()))
275    }
276}
277
278/// What a component's prop setter takes (`button().disabled(..)`): a value
279/// of a type that becomes a `T` (set once; a `T` for an `Option<T>`, and a
280/// string for an optional text), a [`Signal`], [`Memo`],
281/// [`ReadSignal`], [`Prop`] or [`Reactive`] of `T`, or a closure returning
282/// what becomes a `T` (bound: run again when what it reads changes). `M`
283/// tells them apart: it is inferred, never written.
284#[diagnostic::on_unimplemented(
285    message = "`{Self}` is not a prop of `{T}`",
286    label = "not a prop of `{T}`",
287    note = "a prop is a value that becomes a `{T}`, a signal, memo or prop of it, or a closure `move || ..` returning one"
288)]
289pub trait IntoProp<T, M> {
290    /// As a value or a binding.
291    fn into_prop(self) -> Reactive<T>;
292}
293
294/// How a value is a prop ([`IntoProp`]).
295#[doc(hidden)]
296pub struct PropValue(());
297
298/// How a closure is a prop ([`IntoProp`]).
299#[doc(hidden)]
300pub struct PropClosure(());
301
302/// How a reactive handle is a prop ([`IntoProp`]).
303#[doc(hidden)]
304pub struct PropHandle(());
305
306/// How a string is an optional text prop ([`IntoProp`]).
307#[doc(hidden)]
308pub struct PropText(());
309
310/// A string as a set text prop (`.accessibility_label("Save")`).
311impl IntoProp<Option<super::SharedString>, PropText> for &'static str {
312    fn into_prop(self) -> Reactive<Option<super::SharedString>> {
313        Reactive::Static(Some(self.into()))
314    }
315}
316
317/// A string as a set text prop.
318impl IntoProp<Option<super::SharedString>, PropText> for String {
319    fn into_prop(self) -> Reactive<Option<super::SharedString>> {
320        Reactive::Static(Some(self.into()))
321    }
322}
323
324/// A URL as a set image prop (`.src("https://…")`).
325impl IntoProp<Option<super::ImageSrc>, PropText> for &'static str {
326    fn into_prop(self) -> Reactive<Option<super::ImageSrc>> {
327        Reactive::Static(Some(self.into()))
328    }
329}
330
331/// A URL as a set image prop.
332impl IntoProp<Option<super::ImageSrc>, PropText> for String {
333    fn into_prop(self) -> Reactive<Option<super::ImageSrc>> {
334        Reactive::Static(Some(self.into()))
335    }
336}
337
338/// A crate's image as a set image prop (`.src(asset!("ada.png"))`).
339impl IntoProp<Option<super::ImageSrc>, PropText> for super::ImageAsset {
340    fn into_prop(self) -> Reactive<Option<super::ImageSrc>> {
341        Reactive::Static(Some(self.into()))
342    }
343}
344
345impl<T, U: Into<T>> IntoProp<T, PropValue> for U {
346    fn into_prop(self) -> Reactive<T> {
347        Reactive::Static(self.into())
348    }
349}
350
351impl<T: 'static, U: Into<T>, F: Fn() -> U + 'static> IntoProp<T, PropClosure> for F {
352    fn into_prop(self) -> Reactive<T> {
353        Reactive::Bound(Rc::new(move || self().into()))
354    }
355}
356
357macro_rules! prop_handles {
358    ($($handle:ident),*) => {$(
359        impl<T: Clone + PartialEq + 'static> IntoProp<T, PropHandle> for $handle<T> {
360            fn into_prop(self) -> Reactive<T> {
361                self.into_reactive()
362            }
363        }
364    )*};
365}
366
367prop_handles!(Signal, ReadSignal, Memo, Prop);
368
369impl<T> IntoProp<T, PropHandle> for Reactive<T> {
370    fn into_prop(self) -> Reactive<T> {
371        self
372    }
373}
374
375/// A field's new value from JS (`None`: unset, back to its default `init`):
376/// what each arm of `#[derive(Props)]`'s `set` does, once per type rather
377/// than once per field.
378fn take_prop<T: Clone + 'static>(
379    value: Option<super::AnyValue>,
380    js: &'static str,
381    init: fn() -> T,
382) -> Result<T, super::PropError> {
383    match value {
384        Some(v) => v.take::<T>().ok_or_else(|| of_another_type(js)),
385        None => Ok(init()),
386    }
387}
388
389#[cold]
390#[inline(never)]
391fn of_another_type(js: &'static str) -> super::PropError {
392    super::PropError(format!("`{js}`: a value of another type"))
393}
394
395/// `#[derive(Props)]`'s `set` of a `Prop<T>` field `js`: whether it changed.
396#[inline(never)]
397pub fn set_held<T: Clone + PartialEq + 'static>(
398    prop: &mut Prop<T>,
399    value: Option<super::AnyValue>,
400    js: &'static str,
401    init: fn() -> T,
402) -> Result<bool, super::PropError> {
403    Ok(prop.__set(Reactive::Static(take_prop(value, js, init)?)))
404}
405
406/// `#[derive(Props)]`'s `set` of a plain field `js`: whether it changed.
407#[inline(never)]
408pub fn set_plain<T: Clone + PartialEq + 'static>(
409    field: &mut T,
410    value: Option<super::AnyValue>,
411    js: &'static str,
412    init: fn() -> T,
413) -> Result<bool, super::PropError> {
414    let value = take_prop(value, js, init)?;
415    let changed = *field != value;
416    *field = value;
417    Ok(changed)
418}