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