Skip to main content

nsh_core/ui/
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}
312number!(whole: i16, i32, i64, u16, u32, u64, usize);
313
314/// A whole number of pixels (an image's size).
315impl JsValue for crate::geometry::DevicePixels {
316    fn ts_type(types: &mut TsTypes) -> String {
317        i32::ts_type(types)
318    }
319
320    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
321        i32::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 size in pixels: TS's `Size` (`{ width, height }`).
330impl JsValue for crate::geometry::Size<crate::geometry::DevicePixels> {
331    fn ts_type(_types: &mut TsTypes) -> String {
332        "Size".into()
333    }
334
335    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
336        if value.kind() != JsKind::Object {
337            return Err(value.expected("an object with width and height"));
338        }
339        let side = |key: &str| -> Result<crate::geometry::DevicePixels, PropError> {
340            let v = value.field(key)?;
341            crate::geometry::DevicePixels::from_js(v.get())
342                .map_err(|e| PropError(format!("`{key}`: {e}")))
343        };
344        Ok(Self::new(side("width")?, side("height")?))
345    }
346
347    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
348        let owned = JsOwned::new(host, host.new_object()?);
349        let object = owned.get().raw();
350        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
351        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
352        Ok(owned)
353    }
354}
355
356impl JsValue for SharedString {
357    fn ts_type(_types: &mut TsTypes) -> String {
358        "string".into()
359    }
360
361    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
362        value
363            .as_string()
364            .map(Into::into)
365            .ok_or_else(|| value.expected("a string"))
366    }
367
368    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
369        Ok(JsOwned::new(host, host.new_string(self.as_str())?))
370    }
371}
372
373impl JsValue for String {
374    fn ts_type(_types: &mut TsTypes) -> String {
375        "string".into()
376    }
377
378    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
379        value.as_string().ok_or_else(|| value.expected("a string"))
380    }
381
382    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
383        Ok(JsOwned::new(host, host.new_string(self)?))
384    }
385}
386
387/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`), as
388/// [`Color`] takes it: the color of Rust components' props.
389impl JsValue for crate::Hsla {
390    fn ts_type(types: &mut TsTypes) -> String {
391        Color::ts_type(types)
392    }
393
394    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
395        Color::from_js(value).map(Into::into)
396    }
397
398    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
399        Color::from(*self).to_js(host)
400    }
401}
402
403/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`).
404impl JsValue for Color {
405    fn ts_type(_types: &mut TsTypes) -> String {
406        "string".into()
407    }
408
409    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
410        value
411            .as_string()
412            .as_deref()
413            .and_then(Color::parse)
414            .ok_or_else(|| value.expected("a color"))
415    }
416
417    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
418        Ok(JsOwned::new(
419            host,
420            host.new_string(&format!("#{:08x}", self.0))?,
421        ))
422    }
423}
424
425/// A node JS passes (a `YNode`, a `ref`).
426#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
427pub struct NodeRef(pub crate::NodeId);
428
429impl JsValue for NodeRef {
430    fn ts_type(_types: &mut TsTypes) -> String {
431        "YNode".into()
432    }
433
434    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
435        value
436            .host()
437            .node(value.raw())
438            .map(NodeRef)
439            .ok_or_else(|| value.expected("a node"))
440    }
441
442    /// The node's JS object (`null` once JS let it go).
443    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
444        Ok(JsOwned::new(host, host.node_value(self.0)))
445    }
446}
447
448/// Any value, as JSON (a real JSON API's data: `JSON.stringify`'s view of
449/// the value).
450impl JsValue for JsonValue {
451    fn ts_type(_types: &mut TsTypes) -> String {
452        "unknown".into()
453    }
454
455    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
456        match value.kind() {
457            JsKind::Undefined => Ok(JsonValue::Null),
458            _ => value.to_json(),
459        }
460    }
461
462    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
463        Ok(JsOwned::new(host, host.json(self)?))
464    }
465}
466
467/// `null` (and `undefined`) is `None`.
468impl<T: JsValue> JsValue for Option<T> {
469    fn ts_type(types: &mut TsTypes) -> String {
470        format!("{} | null", T::ts_type(types))
471    }
472
473    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
474        if value.is_nullish() {
475            Ok(None)
476        } else {
477            T::from_js(value).map(Some)
478        }
479    }
480
481    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
482        match self {
483            Some(v) => v.to_js(host),
484            None => Ok(JsOwned::new(host, host.null())),
485        }
486    }
487}
488
489/// Bytes are a `Uint8Array` (a `Buffer` is one too), not an array of
490/// numbers: `u8` is no [`JsValue`], so this and the arrays below never
491/// overlap.
492impl JsValue for Vec<u8> {
493    fn ts_type(_types: &mut TsTypes) -> String {
494        "Uint8Array".into()
495    }
496
497    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
498        value
499            .as_bytes()
500            .ok_or_else(|| value.expected("a Uint8Array"))
501    }
502
503    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
504        Ok(JsOwned::new(host, host.new_bytes(self)?))
505    }
506}
507
508/// An object of strings by name (`process.env`): `Record<string, string>`.
509impl JsValue for std::collections::BTreeMap<String, String> {
510    fn ts_type(_types: &mut TsTypes) -> String {
511        "Record<string, string>".into()
512    }
513
514    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
515        if value.kind() != JsKind::Object {
516            return Err(value.expected("an object of strings"));
517        }
518        let JsonValue::Object(fields) = value.to_json()? else {
519            return Err(value.expected("an object of strings"));
520        };
521        fields
522            .into_iter()
523            .map(|(key, v)| match v {
524                JsonValue::String(s) => Ok((key, s)),
525                other => Err(PropError::expected("a string", &other)),
526            })
527            .collect()
528    }
529
530    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
531        let object = JsOwned::new(host, host.new_object()?);
532        for (key, value) in self {
533            host.set_field(object.get().raw(), key, host.new_string(value)?)?;
534        }
535        Ok(object)
536    }
537}
538
539/// A time is a `Date` (its milliseconds since the Unix epoch).
540impl JsValue for std::time::SystemTime {
541    fn ts_type(_types: &mut TsTypes) -> String {
542        "Date".into()
543    }
544
545    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
546        let millis = value
547            .as_date()
548            .filter(|m| m.is_finite())
549            .ok_or_else(|| value.expected("a valid Date"))?;
550        let since = std::time::Duration::from_secs_f64(millis.abs() / 1000.0);
551        let time = if millis < 0.0 {
552            std::time::UNIX_EPOCH.checked_sub(since)
553        } else {
554            std::time::UNIX_EPOCH.checked_add(since)
555        };
556        time.ok_or_else(|| value.expected("a Date in range"))
557    }
558
559    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
560        let millis = match self.duration_since(std::time::UNIX_EPOCH) {
561            Ok(since) => since.as_secs_f64() * 1000.0,
562            Err(before) => -before.duration().as_secs_f64() * 1000.0,
563        };
564        Ok(JsOwned::new(host, host.new_date(millis)?))
565    }
566}
567
568impl<T: JsValue> JsValue for Vec<T> {
569    fn ts_type(types: &mut TsTypes) -> String {
570        format!("({})[]", T::ts_type(types))
571    }
572
573    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
574        let len = value
575            .array_len()?
576            .ok_or_else(|| value.expected("an array"))?;
577        // The length is JS's (the host limits what it reads): reserve a
578        // bounded amount up front.
579        let mut out = Vec::with_capacity(len.min(1024));
580        for i in 0..len {
581            let item = value.index(i)?;
582            out.push(T::from_js(item.get()).map_err(|e| PropError(format!("[{i}]: {e}")))?);
583        }
584        Ok(out)
585    }
586
587    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
588        // Owned until the array takes them: an item failing frees the
589        // ones made before.
590        let mut items = Vec::with_capacity(self.len());
591        for item in self {
592            items.push(item.to_js(host)?);
593        }
594        let raws = items.into_iter().map(JsOwned::into_raw).collect();
595        Ok(JsOwned::new(host, host.new_array(raws)?))
596    }
597}