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