Skip to main content

nsh_core/element/
value.rs

1//! Values crossing between JS and Rust: shared strings, and the direct
2//! conversion of props, event data, arguments and results from and to JS
3//! values ([`JsValue`]) with their TypeScript types.
4
5use std::{borrow::Borrow, fmt, ops::Deref, sync::Arc};
6
7use super::js::{JsHost, JsIn, JsKind, JsOwned};
8use crate::{JsonValue, style::Color};
9
10/// A cheaply cloned string: a static string or a shared one.
11#[derive(Clone)]
12pub struct SharedString(Repr);
13
14#[derive(Clone)]
15enum Repr {
16    Static(&'static str),
17    Shared(Arc<str>),
18}
19
20impl SharedString {
21    /// A static string, without allocating.
22    pub const fn new_static(s: &'static str) -> Self {
23        Self(Repr::Static(s))
24    }
25
26    /// The string.
27    pub fn as_str(&self) -> &str {
28        match &self.0 {
29            Repr::Static(s) => s,
30            Repr::Shared(s) => s,
31        }
32    }
33
34    pub(crate) fn to_arc(&self) -> Arc<str> {
35        match &self.0 {
36            Repr::Static(s) => Arc::from(*s),
37            Repr::Shared(s) => s.clone(),
38        }
39    }
40}
41
42impl Default for SharedString {
43    fn default() -> Self {
44        Self::new_static("")
45    }
46}
47
48impl Deref for SharedString {
49    type Target = str;
50
51    fn deref(&self) -> &str {
52        self.as_str()
53    }
54}
55
56impl AsRef<str> for SharedString {
57    fn as_ref(&self) -> &str {
58        self.as_str()
59    }
60}
61
62impl Borrow<str> for SharedString {
63    fn borrow(&self) -> &str {
64        self.as_str()
65    }
66}
67
68impl PartialEq for SharedString {
69    fn eq(&self, other: &Self) -> bool {
70        let (a, b) = (self.as_str(), other.as_str());
71        std::ptr::eq(a, b) || a == b
72    }
73}
74
75impl Eq for SharedString {}
76
77impl std::hash::Hash for SharedString {
78    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
79        self.as_str().hash(state)
80    }
81}
82
83impl PartialEq<str> for SharedString {
84    fn eq(&self, other: &str) -> bool {
85        self.as_str() == other
86    }
87}
88
89impl PartialEq<&str> for SharedString {
90    fn eq(&self, other: &&str) -> bool {
91        self.as_str() == *other
92    }
93}
94
95impl fmt::Debug for SharedString {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        fmt::Debug::fmt(self.as_str(), f)
98    }
99}
100
101impl fmt::Display for SharedString {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str(self.as_str())
104    }
105}
106
107impl From<&'static str> for SharedString {
108    fn from(s: &'static str) -> Self {
109        Self::new_static(s)
110    }
111}
112
113impl From<String> for SharedString {
114    fn from(s: String) -> Self {
115        Self(Repr::Shared(s.into()))
116    }
117}
118
119impl From<Arc<str>> for SharedString {
120    fn from(s: Arc<str>) -> Self {
121        Self(Repr::Shared(s))
122    }
123}
124
125impl From<&SharedString> for SharedString {
126    fn from(s: &SharedString) -> Self {
127        s.clone()
128    }
129}
130
131/// A prop value JS sent that does not fit the prop's type.
132#[derive(Debug, Clone, PartialEq)]
133pub struct PropError(pub String);
134
135impl PropError {
136    /// "expected `ty`, got `value`".
137    pub fn expected(ty: &str, value: &JsonValue) -> Self {
138        let mut got = value.to_string();
139        if got.len() > 40 {
140            got.truncate(40);
141            got.push('…');
142        }
143        Self(format!("expected {ty}, got {got}"))
144    }
145}
146
147impl fmt::Display for PropError {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        f.write_str(&self.0)
150    }
151}
152
153impl std::error::Error for PropError {}
154
155/// The named TypeScript types the declarations use (`AlertButton`,
156/// `BarStyle`), declared once each.
157#[derive(Debug, Clone, Default)]
158pub struct TsTypes {
159    types: std::collections::BTreeMap<&'static str, String>,
160}
161
162impl TsTypes {
163    /// Type `name`, declared by `declaration` (`interface ... {}` or
164    /// `type ... = ...;`, with its doc comment) the first time.
165    pub fn declare(
166        &mut self,
167        name: &'static str,
168        declaration: impl FnOnce(&mut TsTypes) -> String,
169    ) -> String {
170        if !self.types.contains_key(name) {
171            // Present while it is built: a type naming itself stops here.
172            self.types.insert(name, String::new());
173            let text = declaration(self);
174            self.types.insert(name, text);
175        }
176        name.to_owned()
177    }
178
179    /// Class `def`'s type: its name (the class is declared with the set's
180    /// classes, which include every class a registered signature names:
181    /// [`super::Registry::class`]).
182    pub fn class(&mut self, def: &'static super::ClassDef) -> String {
183        def.name.to_owned()
184    }
185
186    /// Adds `other`'s types.
187    pub(crate) fn merge(&mut self, other: &TsTypes) {
188        for (name, text) in &other.types {
189            self.types.entry(name).or_insert_with(|| text.clone());
190        }
191    }
192
193    pub(crate) fn declarations(&self) -> impl Iterator<Item = &str> {
194        self.types.values().map(String::as_str)
195    }
196}
197
198/// A function giving a TypeScript type (declaring the named types it uses).
199pub type TsType = fn(&mut TsTypes) -> String;
200
201/// `T`'s [`JsValue::ts_type`], or one giving nothing in builds without
202/// declarations ([`super::DECLARATIONS`]): what generated code calls, so
203/// runtimes link none of the TypeScript.
204#[doc(hidden)]
205pub const fn ts_of<T: JsValue>() -> TsType {
206    if super::DECLARATIONS {
207        T::ts_type
208    } else {
209        |_| String::new()
210    }
211}
212
213/// An enum of unit variants that is a string union in JS
214/// (`#[derive(PropEnum)]` implements it).
215pub trait PropEnum: JsValue {
216    /// The variant's JS name (`SemiBold` is `"semiBold"`).
217    fn js_name(&self) -> &'static str;
218}
219
220/// A type props, event data, and the arguments and results of classes and
221/// functions can have: how it converts from and to JS values (directly,
222/// in the JS call or when JS receives it) and its TypeScript type.
223/// `#[derive(PropEnum)]` implements it for enums of unit variants,
224/// `#[derive(JsObject)]` for structs.
225#[diagnostic::on_unimplemented(
226    message = "`{Self}` cannot cross to JS",
227    note = "a `#[class]` / `#[module]` member returning `Later<T>` (or `Result<Later<T>, E>`) must spell that type out: the macro reads the signature's tokens and does not see through a type alias"
228)]
229pub trait JsValue: Sized {
230    /// Its TypeScript type (`string`, `AlertButton`), declaring the named
231    /// types it uses in `types`.
232    fn ts_type(types: &mut TsTypes) -> String;
233
234    /// The value of JS value `value`.
235    fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
236
237    /// The value as a JS value of `host`.
238    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
239}
240
241impl JsValue for bool {
242    fn ts_type(_types: &mut TsTypes) -> String {
243        "boolean".into()
244    }
245
246    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
247        value.as_bool().ok_or_else(|| value.expected("a boolean"))
248    }
249
250    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
251        Ok(JsOwned::new(host, host.new_bool(*self)))
252    }
253}
254
255/// Whether `n` is a whole number in the range of a `bits`-bit integer: what
256/// an integer parameter, prop or field takes (a fraction, `NaN`,
257/// `Infinity` or a value out of range is a mistake, not something to round
258/// or clamp).
259pub(crate) fn fits(n: f64, signed: bool, bits: u32) -> bool {
260    if !n.is_finite() || n.fract() != 0.0 {
261        return false;
262    }
263    let (lo, hi) = if signed {
264        let half = 2f64.powi(bits as i32 - 1);
265        (-half, half)
266    } else {
267        (0.0, 2f64.powi(bits as i32))
268    };
269    n >= lo && n < hi
270}
271
272macro_rules! number {
273    ($check:ident: $($ty:ty),*) => {$(
274        impl JsValue for $ty {
275            fn ts_type(_types: &mut TsTypes) -> String {
276                "number".into()
277            }
278
279            fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
280                let n = value.as_number().ok_or_else(|| value.expected("a number"))?;
281                number!(@$check $ty, n, value);
282                Ok(n as $ty)
283            }
284
285            /// Above 2^53 an integer is the nearest number JS has.
286            fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
287                Ok(JsOwned::new(host, host.new_number(*self as f64)))
288            }
289        }
290    )*};
291    // A float takes any number.
292    (@any $ty:ty, $n:ident, $value:ident) => {};
293    (@whole $ty:ty, $n:ident, $value:ident) => {
294        if !fits($n, <$ty>::MIN != 0, <$ty>::BITS) {
295            return Err($value.expected(concat!("an integer that fits ", stringify!($ty))));
296        }
297    };
298}
299
300number!(any: f32, f64);
301
302/// A number of points.
303impl JsValue for crate::geometry::Points {
304    fn ts_type(_types: &mut TsTypes) -> String {
305        "number".into()
306    }
307
308    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
309        f32::from_js(value).map(Self)
310    }
311
312    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
313        self.0.to_js(host)
314    }
315}
316
317/// An angle, a number of radians (as `Math.PI` and the canvas's `arc`
318/// take them).
319impl JsValue for crate::geometry::Radians {
320    fn ts_type(_types: &mut TsTypes) -> String {
321        "number".into()
322    }
323
324    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
325        f32::from_js(value).map(Self)
326    }
327
328    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
329        self.0.to_js(host)
330    }
331}
332
333/// A fraction, a number (`0.35` is 35%, as `opacity` takes it).
334impl JsValue for crate::geometry::Percentage {
335    fn ts_type(_types: &mut TsTypes) -> String {
336        "number".into()
337    }
338
339    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
340        f32::from_js(value).map(Self)
341    }
342
343    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
344        self.0.to_js(host)
345    }
346}
347
348/// A length of points or a percentage of a reference length the prop
349/// names, as CSS writes them: a number of points, or `"50%"` (TS
350/// ``number | `${number}%` ``). A length in rems, which only Rust makes,
351/// reads back as its CSS text (`"1.5rem"`).
352impl JsValue for crate::geometry::DefiniteLength {
353    fn ts_type(_types: &mut TsTypes) -> String {
354        "number | `${number}%`".into()
355    }
356
357    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
358        use crate::geometry::{AbsoluteLength, DefiniteLength, Percentage, Points};
359        if let Some(n) = value.as_number() {
360            return Ok(DefiniteLength::Absolute(AbsoluteLength::Points(Points(
361                n as f32,
362            ))));
363        }
364        value
365            .as_string()
366            .as_deref()
367            .and_then(percent)
368            .map(|p| DefiniteLength::Fraction(Percentage(p / 100.0)))
369            .ok_or_else(|| value.expected("a number of points or a percentage (\"50%\")"))
370    }
371
372    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
373        use crate::geometry::{AbsoluteLength, DefiniteLength};
374        match *self {
375            DefiniteLength::Absolute(AbsoluteLength::Points(p)) => p.to_js(host),
376            DefiniteLength::Absolute(AbsoluteLength::Rems(r)) => {
377                Ok(JsOwned::new(host, host.new_string(&format!("{}rem", r.0))?))
378            }
379            DefiniteLength::Fraction(f) => Ok(JsOwned::new(
380                host,
381                host.new_string(&format!("{}%", f.0 * 100.0))?,
382            )),
383        }
384    }
385}
386
387/// The number of a CSS percentage (`"62.5%"` is 62.5); `None` for
388/// anything else.
389fn percent(text: &str) -> Option<f32> {
390    let n: f32 = text.trim().strip_suffix('%')?.trim_end().parse().ok()?;
391    n.is_finite().then_some(n)
392}
393number!(whole: i16, i32, i64, u16, u32, u64, usize);
394
395/// A whole number of pixels (an image's size).
396impl JsValue for crate::geometry::DevicePixels {
397    fn ts_type(types: &mut TsTypes) -> String {
398        i32::ts_type(types)
399    }
400
401    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
402        i32::from_js(value).map(Self)
403    }
404
405    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
406        self.0.to_js(host)
407    }
408}
409
410/// A size in pixels: TS's `PixelSize` (`{ width, height }`).
411impl JsValue for crate::geometry::Size<crate::geometry::DevicePixels> {
412    fn ts_type(_types: &mut TsTypes) -> String {
413        "PixelSize".into()
414    }
415
416    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
417        if value.kind() != JsKind::Object {
418            return Err(value.expected("an object with width and height"));
419        }
420        let side = |key: &str| -> Result<crate::geometry::DevicePixels, PropError> {
421            let v = value.field(key)?;
422            crate::geometry::DevicePixels::from_js(v.get())
423                .map_err(|e| PropError(format!("`{key}`: {e}")))
424        };
425        Ok(Self::new(side("width")?, side("height")?))
426    }
427
428    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
429        let owned = JsOwned::new(host, host.new_object()?);
430        let object = owned.get().raw();
431        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
432        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
433        Ok(owned)
434    }
435}
436
437/// A field of a JS object, its key named in the error.
438fn field_of<T: JsValue>(value: JsIn<'_>, key: &str) -> Result<T, PropError> {
439    let v = value.field(key)?;
440    T::from_js(v.get()).map_err(|e| PropError(format!("`{key}`: {e}")))
441}
442
443/// Reads a derived object's field, preserving absence separately from a
444/// nullable value so the caller can apply its declared default.
445#[doc(hidden)]
446#[cfg_attr(target_arch = "wasm32", inline(never))]
447pub fn object_field<T: JsValue>(
448    value: JsIn<'_>,
449    key: &str,
450    nullable: bool,
451) -> Result<Option<T>, PropError> {
452    // Share the host calls and error formatting across fields of one type.
453    // Inlining this into every style part bloats the web runtime.
454    let owned = value.field(key)?;
455    let value = owned.get();
456    if value.kind() == JsKind::Undefined || (!nullable && value.is_nullish()) {
457        Ok(None)
458    } else {
459        T::from_js(value)
460            .map(Some)
461            .map_err(|e| PropError(format!("`{key}`: {e}")))
462    }
463}
464
465/// A position in points: TS's `Point` (`{ x, y }`), as events carry it.
466impl JsValue for crate::geometry::Point<crate::geometry::Points> {
467    fn ts_type(_types: &mut TsTypes) -> String {
468        "Point".into()
469    }
470
471    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
472        if value.kind() != JsKind::Object {
473            return Err(value.expected("an object with x and y"));
474        }
475        Ok(Self::new(field_of(value, "x")?, field_of(value, "y")?))
476    }
477
478    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
479        let owned = JsOwned::new(host, host.new_object()?);
480        let object = owned.get().raw();
481        host.set_field(object, "x", self.x.to_js(host)?.into_raw())?;
482        host.set_field(object, "y", self.y.to_js(host)?.into_raw())?;
483        Ok(owned)
484    }
485}
486
487/// A size in points: TS's `Size` (`{ width, height }`).
488impl JsValue for crate::geometry::Size<crate::geometry::Points> {
489    fn ts_type(_types: &mut TsTypes) -> String {
490        "Size".into()
491    }
492
493    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
494        if value.kind() != JsKind::Object {
495            return Err(value.expected("an object with width and height"));
496        }
497        Ok(Self::new(
498            field_of(value, "width")?,
499            field_of(value, "height")?,
500        ))
501    }
502
503    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
504        let owned = JsOwned::new(host, host.new_object()?);
505        let object = owned.get().raw();
506        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
507        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
508        Ok(owned)
509    }
510}
511
512/// What an image shows, as `<Image>`'s `src` takes it (a Rust component's
513/// image prop): decoded by `<Image>`'s own decoder and declared with its
514/// type, so the two take the same values (a URL, an `asset:/` or `data:`
515/// URI, a `blob:` URL, an imported `ImageAsset` with its size and scales).
516/// A `blob:` URL takes its blob's bytes from the VM, as `<Image>`'s does
517/// ([`super::JsHost::image_blob`]). An empty string is an empty source: no
518/// image.
519impl JsValue for super::ImageSrc {
520    fn ts_type(types: &mut TsTypes) -> String {
521        <crate::ImageSource as crate::js::host::HostValue>::ts_type(types)
522    }
523
524    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
525        use crate::js::host::{HostCx, HostValue};
526        // A source is a string or a small object, decoded when the prop is
527        // set: through JSON, `<Image>`'s decoder reads it as it reads a
528        // host prop.
529        let json = value.to_json()?;
530        let input = super::animated::JsonInput(Some(&json));
531        match crate::ImageSource::decode(&input, &mut HostCx::default()) {
532            Some(source) => {
533                let (uri, data) = match source.uri.starts_with("blob:") {
534                    true => match value.host().image_blob(&source.uri) {
535                        Some((key, data)) => (key, Some(data)),
536                        None => (source.uri, None),
537                    },
538                    false => (source.uri, None),
539                };
540                Ok(Self {
541                    uri: uri.into(),
542                    size: source.size.map(|s| (s.width.0, s.height.0)),
543                    scales: source.scales,
544                    data,
545                })
546            }
547            None if json.as_str() == Some("") => Ok("".into()),
548            None => Err(value.expected("a URL or an imported image")),
549        }
550    }
551
552    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
553        if self.size.is_none() && self.scales.is_empty() {
554            return self.uri.to_js(host);
555        }
556        let owned = JsOwned::new(host, host.new_object()?);
557        let object = owned.get().raw();
558        host.set_field(object, "url", self.uri.to_js(host)?.into_raw())?;
559        if let Some((w, h)) = self.size {
560            let size =
561                crate::geometry::size(crate::geometry::Points(w), crate::geometry::Points(h));
562            host.set_field(object, "size", size.to_js(host)?.into_raw())?;
563        }
564        if !self.scales.is_empty() {
565            let scales: Vec<f32> = self.scales.iter().collect();
566            host.set_field(object, "scales", scales.to_js(host)?.into_raw())?;
567        }
568        Ok(owned)
569    }
570}
571
572/// A rectangle in points: TS's `Bounds` (`{ origin, size }`), as events
573/// carry it.
574impl JsValue for crate::geometry::Bounds<crate::geometry::Points> {
575    fn ts_type(_types: &mut TsTypes) -> String {
576        "Bounds".into()
577    }
578
579    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
580        if value.kind() != JsKind::Object {
581            return Err(value.expected("an object with origin and size"));
582        }
583        Ok(Self::new(
584            field_of(value, "origin")?,
585            field_of(value, "size")?,
586        ))
587    }
588
589    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
590        let owned = JsOwned::new(host, host.new_object()?);
591        let object = owned.get().raw();
592        host.set_field(object, "origin", self.origin.to_js(host)?.into_raw())?;
593        host.set_field(object, "size", self.size.to_js(host)?.into_raw())?;
594        Ok(owned)
595    }
596}
597
598/// A length on each side, in points, as a host element's `hitSlop` takes
599/// it (TS `number | Partial<Edges>`): one number for every side, or the
600/// sides named, each left out 0. A Rust component's prop of the host
601/// prop's meaning (`Button`'s `hitSlop`) takes the same values. To JS it
602/// is the four sides.
603impl JsValue for crate::geometry::Edges<crate::geometry::Points> {
604    fn ts_type(_types: &mut TsTypes) -> String {
605        "number | Partial<Edges>".into()
606    }
607
608    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
609        use crate::geometry::Points;
610        let length = |n: Option<f64>| match n {
611            Some(n) if n.is_finite() => Ok(Points(n as f32)),
612            _ => Err(value.expected("a number or `{ top?, right?, bottom?, left? }`")),
613        };
614        if let Some(n) = value.as_number() {
615            return length(Some(n)).map(Self::all);
616        }
617        if value.kind() != JsKind::Object {
618            return Err(value.expected("a number or `{ top?, right?, bottom?, left? }`"));
619        }
620        let side = |key: &str| -> Result<Points, PropError> {
621            let field = value.field(key)?;
622            let field = field.get();
623            match field.is_nullish() {
624                true => Ok(Points(0.0)),
625                false => length(field.as_number()),
626            }
627        };
628        Ok(Self {
629            top: side("top")?,
630            right: side("right")?,
631            bottom: side("bottom")?,
632            left: side("left")?,
633        })
634    }
635
636    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
637        let owned = JsOwned::new(host, host.new_object()?);
638        let object = owned.get().raw();
639        host.set_field(object, "top", self.top.to_js(host)?.into_raw())?;
640        host.set_field(object, "right", self.right.to_js(host)?.into_raw())?;
641        host.set_field(object, "bottom", self.bottom.to_js(host)?.into_raw())?;
642        host.set_field(object, "left", self.left.to_js(host)?.into_raw())?;
643        Ok(owned)
644    }
645}
646
647/// The modifier keys held: TS's `Modifiers` (`{ control, alt, shift,
648/// platform, altGraph }`, GPUI's names), as press events carry them. A missing key
649/// is not held.
650impl JsValue for crate::keymap::Modifiers {
651    fn ts_type(_types: &mut TsTypes) -> String {
652        "Modifiers".into()
653    }
654
655    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
656        if value.kind() != JsKind::Object {
657            return Err(value.expected("an object of modifier keys"));
658        }
659        let held = |key: &str| -> Result<bool, PropError> {
660            Ok(field_of::<Option<bool>>(value, key)?.unwrap_or(false))
661        };
662        Ok(Self {
663            ctrl: held("control")?,
664            alt: held("alt")?,
665            shift: held("shift")?,
666            cmd: held("platform")?,
667            alt_graph: held("altGraph")?,
668        })
669    }
670
671    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
672        let owned = JsOwned::new(host, host.new_object()?);
673        let object = owned.get().raw();
674        for (key, held) in [
675            ("control", self.ctrl),
676            ("alt", self.alt),
677            ("shift", self.shift),
678            ("platform", self.cmd),
679            ("altGraph", self.alt_graph),
680        ] {
681            host.set_field(object, key, held.to_js(host)?.into_raw())?;
682        }
683        Ok(owned)
684    }
685}
686
687impl JsValue for SharedString {
688    fn ts_type(_types: &mut TsTypes) -> String {
689        "string".into()
690    }
691
692    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
693        value
694            .as_string()
695            .map(Into::into)
696            .ok_or_else(|| value.expected("a string"))
697    }
698
699    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
700        Ok(JsOwned::new(host, host.new_string(self.as_str())?))
701    }
702}
703
704impl JsValue for String {
705    fn ts_type(_types: &mut TsTypes) -> String {
706        "string".into()
707    }
708
709    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
710        value.as_string().ok_or_else(|| value.expected("a string"))
711    }
712
713    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
714        Ok(JsOwned::new(host, host.new_string(self)?))
715    }
716}
717
718/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`), as
719/// [`Color`] takes it: the color of Rust components' props.
720impl JsValue for crate::Hsla {
721    fn ts_type(types: &mut TsTypes) -> String {
722        Color::ts_type(types)
723    }
724
725    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
726        Color::from_js(value).map(Into::into)
727    }
728
729    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
730        Color::from(*self).to_js(host)
731    }
732}
733
734/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`).
735impl JsValue for Color {
736    fn ts_type(_types: &mut TsTypes) -> String {
737        "string".into()
738    }
739
740    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
741        value
742            .as_string()
743            .as_deref()
744            .and_then(Color::parse)
745            .ok_or_else(|| value.expected("a color"))
746    }
747
748    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
749        Ok(JsOwned::new(
750            host,
751            host.new_string(&format!("#{:08x}", self.0))?,
752        ))
753    }
754}
755
756/// A node JS passes (an element, a `ref`: TS `ViewRef`).
757#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
758pub struct NodeRef(pub crate::NodeId);
759
760impl JsValue for NodeRef {
761    fn ts_type(_types: &mut TsTypes) -> String {
762        "ViewRef".into()
763    }
764
765    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
766        value
767            .host()
768            .node(value.raw())
769            .map(NodeRef)
770            .ok_or_else(|| value.expected("a node"))
771    }
772
773    /// The node's JS object (`null` once JS let it go).
774    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
775        Ok(JsOwned::new(host, host.node_value(self.0)))
776    }
777}
778
779/// Any value, as JSON (a real JSON API's data: `JSON.stringify`'s view of
780/// the value).
781impl JsValue for JsonValue {
782    fn ts_type(_types: &mut TsTypes) -> String {
783        "unknown".into()
784    }
785
786    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
787        match value.kind() {
788            JsKind::Undefined => Ok(JsonValue::Null),
789            _ => value.to_json(),
790        }
791    }
792
793    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
794        Ok(JsOwned::new(host, host.json(self)?))
795    }
796}
797
798/// `null` (and `undefined`) is `None`.
799impl<T: JsValue> JsValue for Option<T> {
800    fn ts_type(types: &mut TsTypes) -> String {
801        format!("{} | null", T::ts_type(types))
802    }
803
804    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
805        if value.is_nullish() {
806            Ok(None)
807        } else {
808            T::from_js(value).map(Some)
809        }
810    }
811
812    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
813        match self {
814            Some(v) => v.to_js(host),
815            None => Ok(JsOwned::new(host, host.null())),
816        }
817    }
818}
819
820/// Bytes are a `Uint8Array` (a `Buffer` is one too), not an array of
821/// numbers: `u8` is no [`JsValue`], so this and the arrays below never
822/// overlap.
823impl JsValue for Vec<u8> {
824    fn ts_type(_types: &mut TsTypes) -> String {
825        "Uint8Array".into()
826    }
827
828    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
829        value
830            .as_bytes()
831            .ok_or_else(|| value.expected("a Uint8Array"))
832    }
833
834    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
835        Ok(JsOwned::new(host, host.new_bytes(self)?))
836    }
837}
838
839/// An object of strings by name (`process.env`): `Record<string, string>`.
840impl JsValue for std::collections::BTreeMap<String, String> {
841    fn ts_type(_types: &mut TsTypes) -> String {
842        "Record<string, string>".into()
843    }
844
845    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
846        if value.kind() != JsKind::Object {
847            return Err(value.expected("an object of strings"));
848        }
849        let JsonValue::Object(fields) = value.to_json()? else {
850            return Err(value.expected("an object of strings"));
851        };
852        fields
853            .into_iter()
854            .map(|(key, v)| match v {
855                JsonValue::String(s) => Ok((key, s)),
856                other => Err(PropError::expected("a string", &other)),
857            })
858            .collect()
859    }
860
861    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
862        let object = JsOwned::new(host, host.new_object()?);
863        for (key, value) in self {
864            host.set_field(object.get().raw(), key, host.new_string(value)?)?;
865        }
866        Ok(object)
867    }
868}
869
870/// A time is a `Date` (its milliseconds since the Unix epoch).
871impl JsValue for std::time::SystemTime {
872    fn ts_type(_types: &mut TsTypes) -> String {
873        "Date".into()
874    }
875
876    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
877        let millis = value
878            .as_date()
879            .filter(|m| m.is_finite())
880            .ok_or_else(|| value.expected("a valid Date"))?;
881        let since = std::time::Duration::from_secs_f64(millis.abs() / 1000.0);
882        let time = if millis < 0.0 {
883            std::time::UNIX_EPOCH.checked_sub(since)
884        } else {
885            std::time::UNIX_EPOCH.checked_add(since)
886        };
887        time.ok_or_else(|| value.expected("a Date in range"))
888    }
889
890    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
891        let millis = match self.duration_since(std::time::UNIX_EPOCH) {
892            Ok(since) => since.as_secs_f64() * 1000.0,
893            Err(before) => -before.duration().as_secs_f64() * 1000.0,
894        };
895        Ok(JsOwned::new(host, host.new_date(millis)?))
896    }
897}
898
899impl<T: JsValue> JsValue for Vec<T> {
900    fn ts_type(types: &mut TsTypes) -> String {
901        format!("({})[]", T::ts_type(types))
902    }
903
904    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
905        let len = value
906            .array_len()?
907            .ok_or_else(|| value.expected("an array"))?;
908        // The length is JS's (the host limits what it reads): reserve a
909        // bounded amount up front.
910        let mut out = Vec::with_capacity(len.min(1024));
911        for i in 0..len {
912            let item = value.index(i)?;
913            out.push(T::from_js(item.get()).map_err(|e| PropError(format!("[{i}]: {e}")))?);
914        }
915        Ok(out)
916    }
917
918    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
919        // Owned until the array takes them: an item failing frees the
920        // ones made before.
921        let mut items = Vec::with_capacity(self.len());
922        for item in self {
923            items.push(item.to_js(host)?);
924        }
925        let raws = items.into_iter().map(JsOwned::into_raw).collect();
926        Ok(JsOwned::new(host, host.new_array(raws)?))
927    }
928}
929
930#[cfg(test)]
931mod tests {
932    use super::{JsIn, JsValue, percent};
933    use crate::element::{JsObject, json_host::JsonHost};
934
935    #[derive(Debug, PartialEq, JsObject)]
936    #[prop(exact)]
937    struct ObjectFields {
938        required: String,
939        optional: Option<String>,
940        #[prop(default)]
941        count: u32,
942        #[prop(default = 7)]
943        custom: u32,
944        #[prop(default = Some(9))]
945        nullable: Option<u32>,
946    }
947
948    #[test]
949    fn object_fields_keep_defaults_nulls_and_error_paths() {
950        let host = JsonHost::default();
951        let read = |json| {
952            let raw = host.value(json);
953            ObjectFields::from_js(JsIn::new(&host, raw))
954        };
955        let absent = read(serde_json::json!({ "required": "ok" })).unwrap();
956        assert_eq!(
957            absent,
958            ObjectFields {
959                required: "ok".into(),
960                optional: None,
961                count: 0,
962                custom: 7,
963                nullable: Some(9),
964            }
965        );
966        let nulls = read(serde_json::json!({
967            "required": "ok", "optional": null, "count": null, "custom": null, "nullable": null,
968        }))
969        .unwrap();
970        assert_eq!(
971            nulls,
972            ObjectFields {
973                nullable: None,
974                ..absent
975            }
976        );
977        let values = read(serde_json::json!({
978            "required": "yes", "optional": "there", "count": 2, "custom": 3, "nullable": 4,
979        }))
980        .unwrap();
981        assert_eq!(
982            values,
983            ObjectFields {
984                required: "yes".into(),
985                optional: Some("there".into()),
986                count: 2,
987                custom: 3,
988                nullable: Some(4),
989            }
990        );
991        for json in [
992            serde_json::json!({}),
993            serde_json::json!({ "required": null }),
994        ] {
995            assert_eq!(read(json).unwrap_err().0, "`required` is missing");
996        }
997        assert_eq!(
998            read(serde_json::json!({ "required": "ok", "unknown": true }))
999                .unwrap_err()
1000                .0,
1001            "unknown field `unknown`",
1002        );
1003        let error = read(serde_json::json!({ "required": "ok", "count": "bad" }))
1004            .unwrap_err()
1005            .0;
1006        assert!(error.starts_with("`count`: "), "{error}");
1007    }
1008
1009    /// Fields of one `Option` type in a row are read and written in a
1010    /// loop: as each would be on its own.
1011    #[derive(Debug, Default, PartialEq, JsObject)]
1012    struct Runs {
1013        first: Option<u32>,
1014        a: Option<String>,
1015        b: Option<String>,
1016        c: Option<String>,
1017        d: Option<String>,
1018        #[prop(skip_none)]
1019        e: Option<u32>,
1020        #[prop(skip_none)]
1021        f: Option<u32>,
1022        #[prop(skip_none)]
1023        g: Option<u32>,
1024        #[prop(skip_none)]
1025        h: Option<u32>,
1026        #[prop(default = Some(1))]
1027        last: Option<u32>,
1028    }
1029
1030    #[test]
1031    fn runs_of_option_fields_read_and_write_as_fields() {
1032        let host = JsonHost::default();
1033        let read = |json| Runs::from_js(JsIn::new(&host, host.value(json)));
1034        let runs = read(serde_json::json!({
1035            "first": 1, "a": "a", "c": null, "d": "d", "f": 6, "h": 8,
1036        }))
1037        .unwrap();
1038        assert_eq!(
1039            runs,
1040            Runs {
1041                first: Some(1),
1042                a: Some("a".into()),
1043                d: Some("d".into()),
1044                f: Some(6),
1045                h: Some(8),
1046                last: Some(1),
1047                ..Runs::default()
1048            }
1049        );
1050        assert_eq!(
1051            host.read(runs.to_js(&host).unwrap()),
1052            Some(serde_json::json!({
1053                "first": 1, "a": "a", "b": null, "c": null, "d": "d", "f": 6, "h": 8, "last": 1,
1054            }))
1055        );
1056        let error = read(serde_json::json!({ "a": "a", "c": 3, "g": "bad" }))
1057            .unwrap_err()
1058            .0;
1059        assert!(error.starts_with("`c`: "), "{error}");
1060    }
1061
1062    /// An image prop takes what `<Image>`'s `src` takes, read by the same
1063    /// decoder and declared with the same type: a URL, an imported asset
1064    /// with its size and scales, an empty string (no image); anything else
1065    /// is refused. It goes back to JS in the form it came in.
1066    #[test]
1067    fn image_sources_read_as_images_read_them() {
1068        use crate::element::{ImageSrc, TsTypes};
1069        let host = JsonHost::default();
1070        let read = |json| ImageSrc::from_js(JsIn::new(&host, host.value(json)));
1071        let url = read(serde_json::json!("https://example.com/ada.png")).unwrap();
1072        assert_eq!(url, ImageSrc::from("https://example.com/ada.png"));
1073        assert_eq!(
1074            host.read(url.to_js(&host).unwrap()),
1075            Some(serde_json::json!("https://example.com/ada.png"))
1076        );
1077        let asset = serde_json::json!({
1078            "url": "asset:/ada.png",
1079            "size": { "width": 48, "height": 48 },
1080            "scales": [1, 2, 2.5, 3],
1081        });
1082        let read_asset = read(asset).unwrap();
1083        assert_eq!(read_asset.size, Some((48.0, 48.0)));
1084        assert_eq!(
1085            read_asset.scales.iter().collect::<Vec<_>>(),
1086            [1.0, 2.0, 3.0]
1087        );
1088        // Written back, it reads as the same asset (whatever form its
1089        // numbers take in JSON).
1090        let written = host.read(read_asset.to_js(&host).unwrap()).unwrap();
1091        assert_eq!(read(written).unwrap(), read_asset);
1092        assert!(read(serde_json::json!("")).unwrap().is_empty());
1093        // A host without blobs keeps a `blob:` URL as it is, with no bytes.
1094        let blob = read(serde_json::json!("blob:nsh://app/1")).unwrap();
1095        assert_eq!((blob.uri.as_str(), blob.data), ("blob:nsh://app/1", None));
1096        for bad in [
1097            serde_json::json!(3),
1098            serde_json::json!({ "uri": "https://example.com/a.png" }),
1099            serde_json::json!(true),
1100        ] {
1101            assert!(read(bad.clone()).is_err(), "{bad}");
1102        }
1103        assert_eq!(
1104            ImageSrc::ts_type(&mut TsTypes::default()),
1105            <crate::ImageSource as crate::js::host::HostValue>::ts_type(&mut TsTypes::default())
1106        );
1107    }
1108
1109    /// A percentage as CSS writes it; anything else is not one.
1110    #[test]
1111    fn percentages_read_as_css_writes_them() {
1112        assert_eq!(percent("50%"), Some(50.0));
1113        assert_eq!(percent(" 62.5 %"), Some(62.5));
1114        assert_eq!(percent("-10%"), Some(-10.0));
1115        assert_eq!(percent("50"), None);
1116        assert_eq!(percent("50px"), None);
1117        assert_eq!(percent("%"), None);
1118        assert_eq!(percent("NaN%"), None);
1119    }
1120}