nsh-core 0.7.2

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! Values crossing between JS and Rust: shared strings, and the direct
//! conversion of props, event data, arguments and results from and to JS
//! values ([`JsValue`]) with their TypeScript types.

use std::{borrow::Borrow, fmt, ops::Deref, sync::Arc};

use super::js::{JsHost, JsIn, JsKind, JsOwned};
use crate::{JsonValue, style::Color};

/// A cheaply cloned string: a static string or a shared one.
#[derive(Clone)]
pub struct SharedString(Repr);

#[derive(Clone)]
enum Repr {
    Static(&'static str),
    Shared(Arc<str>),
}

impl SharedString {
    /// A static string, without allocating.
    pub const fn new_static(s: &'static str) -> Self {
        Self(Repr::Static(s))
    }

    /// The string.
    pub fn as_str(&self) -> &str {
        match &self.0 {
            Repr::Static(s) => s,
            Repr::Shared(s) => s,
        }
    }

    pub(crate) fn to_arc(&self) -> Arc<str> {
        match &self.0 {
            Repr::Static(s) => Arc::from(*s),
            Repr::Shared(s) => s.clone(),
        }
    }
}

impl Default for SharedString {
    fn default() -> Self {
        Self::new_static("")
    }
}

impl Deref for SharedString {
    type Target = str;

    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl AsRef<str> for SharedString {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for SharedString {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl PartialEq for SharedString {
    fn eq(&self, other: &Self) -> bool {
        let (a, b) = (self.as_str(), other.as_str());
        std::ptr::eq(a, b) || a == b
    }
}

impl Eq for SharedString {}

impl std::hash::Hash for SharedString {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_str().hash(state)
    }
}

impl PartialEq<str> for SharedString {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&str> for SharedString {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl fmt::Debug for SharedString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl fmt::Display for SharedString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&'static str> for SharedString {
    fn from(s: &'static str) -> Self {
        Self::new_static(s)
    }
}

impl From<String> for SharedString {
    fn from(s: String) -> Self {
        Self(Repr::Shared(s.into()))
    }
}

impl From<Arc<str>> for SharedString {
    fn from(s: Arc<str>) -> Self {
        Self(Repr::Shared(s))
    }
}

impl From<&SharedString> for SharedString {
    fn from(s: &SharedString) -> Self {
        s.clone()
    }
}

/// A prop value JS sent that does not fit the prop's type.
#[derive(Debug, Clone, PartialEq)]
pub struct PropError(pub String);

impl PropError {
    /// "expected `ty`, got `value`".
    pub fn expected(ty: &str, value: &JsonValue) -> Self {
        let mut got = value.to_string();
        if got.len() > 40 {
            got.truncate(40);
            got.push('…');
        }
        Self(format!("expected {ty}, got {got}"))
    }
}

impl fmt::Display for PropError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for PropError {}

/// The named TypeScript types the declarations use (`AlertButton`,
/// `BarStyle`), declared once each.
#[derive(Debug, Clone, Default)]
pub struct TsTypes {
    types: std::collections::BTreeMap<&'static str, String>,
}

impl TsTypes {
    /// Type `name`, declared by `declaration` (`interface ... {}` or
    /// `type ... = ...;`, with its doc comment) the first time.
    pub fn declare(
        &mut self,
        name: &'static str,
        declaration: impl FnOnce(&mut TsTypes) -> String,
    ) -> String {
        if !self.types.contains_key(name) {
            // Present while it is built: a type naming itself stops here.
            self.types.insert(name, String::new());
            let text = declaration(self);
            self.types.insert(name, text);
        }
        name.to_owned()
    }

    /// Class `def`'s type: its name (the class is declared with the set's
    /// classes, which include every class a registered signature names:
    /// [`super::Registry::class`]).
    pub fn class(&mut self, def: &'static super::ClassDef) -> String {
        def.name.to_owned()
    }

    /// Adds `other`'s types.
    pub(crate) fn merge(&mut self, other: &TsTypes) {
        for (name, text) in &other.types {
            self.types.entry(name).or_insert_with(|| text.clone());
        }
    }

    pub(crate) fn declarations(&self) -> impl Iterator<Item = &str> {
        self.types.values().map(String::as_str)
    }
}

/// A function giving a TypeScript type (declaring the named types it uses).
pub type TsType = fn(&mut TsTypes) -> String;

/// `T`'s [`JsValue::ts_type`], or one giving nothing in builds without
/// declarations ([`super::DECLARATIONS`]): what generated code calls, so
/// runtimes link none of the TypeScript.
#[doc(hidden)]
pub const fn ts_of<T: JsValue>() -> TsType {
    if super::DECLARATIONS {
        T::ts_type
    } else {
        |_| String::new()
    }
}

/// An enum of unit variants that is a string union in JS
/// (`#[derive(PropEnum)]` implements it).
pub trait PropEnum: JsValue {
    /// The variant's JS name (`SemiBold` is `"semiBold"`).
    fn js_name(&self) -> &'static str;
}

/// A type props, event data, and the arguments and results of classes and
/// functions can have: how it converts from and to JS values (directly,
/// in the JS call or when JS receives it) and its TypeScript type.
/// `#[derive(PropEnum)]` implements it for enums of unit variants,
/// `#[derive(JsObject)]` for structs.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot cross to JS",
    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"
)]
pub trait JsValue: Sized {
    /// Its TypeScript type (`string`, `AlertButton`), declaring the named
    /// types it uses in `types`.
    fn ts_type(types: &mut TsTypes) -> String;

    /// The value of JS value `value`.
    fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;

    /// The value as a JS value of `host`.
    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
}

impl JsValue for bool {
    fn ts_type(_types: &mut TsTypes) -> String {
        "boolean".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        value.as_bool().ok_or_else(|| value.expected("a boolean"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(host, host.new_bool(*self)))
    }
}

/// Whether `n` is a whole number in the range of a `bits`-bit integer: what
/// an integer parameter, prop or field takes (a fraction, `NaN`,
/// `Infinity` or a value out of range is a mistake, not something to round
/// or clamp).
pub(crate) fn fits(n: f64, signed: bool, bits: u32) -> bool {
    if !n.is_finite() || n.fract() != 0.0 {
        return false;
    }
    let (lo, hi) = if signed {
        let half = 2f64.powi(bits as i32 - 1);
        (-half, half)
    } else {
        (0.0, 2f64.powi(bits as i32))
    };
    n >= lo && n < hi
}

macro_rules! number {
    ($check:ident: $($ty:ty),*) => {$(
        impl JsValue for $ty {
            fn ts_type(_types: &mut TsTypes) -> String {
                "number".into()
            }

            fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
                let n = value.as_number().ok_or_else(|| value.expected("a number"))?;
                number!(@$check $ty, n, value);
                Ok(n as $ty)
            }

            /// Above 2^53 an integer is the nearest number JS has.
            fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
                Ok(JsOwned::new(host, host.new_number(*self as f64)))
            }
        }
    )*};
    // A float takes any number.
    (@any $ty:ty, $n:ident, $value:ident) => {};
    (@whole $ty:ty, $n:ident, $value:ident) => {
        if !fits($n, <$ty>::MIN != 0, <$ty>::BITS) {
            return Err($value.expected(concat!("an integer that fits ", stringify!($ty))));
        }
    };
}

number!(any: f32, f64);

/// A number of points.
impl JsValue for crate::geometry::Points {
    fn ts_type(_types: &mut TsTypes) -> String {
        "number".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        f32::from_js(value).map(Self)
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        self.0.to_js(host)
    }
}

/// An angle, a number of radians (as `Math.PI` and the canvas's `arc`
/// take them).
impl JsValue for crate::geometry::Radians {
    fn ts_type(_types: &mut TsTypes) -> String {
        "number".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        f32::from_js(value).map(Self)
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        self.0.to_js(host)
    }
}

/// A fraction, a number (`0.35` is 35%, as `opacity` takes it).
impl JsValue for crate::geometry::Percentage {
    fn ts_type(_types: &mut TsTypes) -> String {
        "number".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        f32::from_js(value).map(Self)
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        self.0.to_js(host)
    }
}

/// A length of points or a percentage of a reference length the prop
/// names, as CSS writes them: a number of points, or `"50%"` (TS
/// ``number | `${number}%` ``). A length in rems, which only Rust makes,
/// reads back as its CSS text (`"1.5rem"`).
impl JsValue for crate::geometry::DefiniteLength {
    fn ts_type(_types: &mut TsTypes) -> String {
        "number | `${number}%`".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        use crate::geometry::{AbsoluteLength, DefiniteLength, Percentage, Points};
        if let Some(n) = value.as_number() {
            return Ok(DefiniteLength::Absolute(AbsoluteLength::Points(Points(
                n as f32,
            ))));
        }
        value
            .as_string()
            .as_deref()
            .and_then(percent)
            .map(|p| DefiniteLength::Fraction(Percentage(p / 100.0)))
            .ok_or_else(|| value.expected("a number of points or a percentage (\"50%\")"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        use crate::geometry::{AbsoluteLength, DefiniteLength};
        match *self {
            DefiniteLength::Absolute(AbsoluteLength::Points(p)) => p.to_js(host),
            DefiniteLength::Absolute(AbsoluteLength::Rems(r)) => {
                Ok(JsOwned::new(host, host.new_string(&format!("{}rem", r.0))?))
            }
            DefiniteLength::Fraction(f) => Ok(JsOwned::new(
                host,
                host.new_string(&format!("{}%", f.0 * 100.0))?,
            )),
        }
    }
}

/// The number of a CSS percentage (`"62.5%"` is 62.5); `None` for
/// anything else.
fn percent(text: &str) -> Option<f32> {
    let n: f32 = text.trim().strip_suffix('%')?.trim_end().parse().ok()?;
    n.is_finite().then_some(n)
}
number!(whole: i16, i32, i64, u16, u32, u64, usize);

/// A whole number of pixels (an image's size).
impl JsValue for crate::geometry::DevicePixels {
    fn ts_type(types: &mut TsTypes) -> String {
        i32::ts_type(types)
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        i32::from_js(value).map(Self)
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        self.0.to_js(host)
    }
}

/// A size in pixels: TS's `PixelSize` (`{ width, height }`).
impl JsValue for crate::geometry::Size<crate::geometry::DevicePixels> {
    fn ts_type(_types: &mut TsTypes) -> String {
        "PixelSize".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if value.kind() != JsKind::Object {
            return Err(value.expected("an object with width and height"));
        }
        let side = |key: &str| -> Result<crate::geometry::DevicePixels, PropError> {
            let v = value.field(key)?;
            crate::geometry::DevicePixels::from_js(v.get())
                .map_err(|e| PropError(format!("`{key}`: {e}")))
        };
        Ok(Self::new(side("width")?, side("height")?))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let owned = JsOwned::new(host, host.new_object()?);
        let object = owned.get().raw();
        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
        Ok(owned)
    }
}

/// A field of a JS object, its key named in the error.
fn field_of<T: JsValue>(value: JsIn<'_>, key: &str) -> Result<T, PropError> {
    let v = value.field(key)?;
    T::from_js(v.get()).map_err(|e| PropError(format!("`{key}`: {e}")))
}

/// Reads a derived object's field, preserving absence separately from a
/// nullable value so the caller can apply its declared default.
#[doc(hidden)]
#[cfg_attr(target_arch = "wasm32", inline(never))]
pub fn object_field<T: JsValue>(
    value: JsIn<'_>,
    key: &str,
    nullable: bool,
) -> Result<Option<T>, PropError> {
    // Share the host calls and error formatting across fields of one type.
    // Inlining this into every style part bloats the web runtime.
    let owned = value.field(key)?;
    let value = owned.get();
    if value.kind() == JsKind::Undefined || (!nullable && value.is_nullish()) {
        Ok(None)
    } else {
        T::from_js(value)
            .map(Some)
            .map_err(|e| PropError(format!("`{key}`: {e}")))
    }
}

/// A position in points: TS's `Point` (`{ x, y }`), as events carry it.
impl JsValue for crate::geometry::Point<crate::geometry::Points> {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Point".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if value.kind() != JsKind::Object {
            return Err(value.expected("an object with x and y"));
        }
        Ok(Self::new(field_of(value, "x")?, field_of(value, "y")?))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let owned = JsOwned::new(host, host.new_object()?);
        let object = owned.get().raw();
        host.set_field(object, "x", self.x.to_js(host)?.into_raw())?;
        host.set_field(object, "y", self.y.to_js(host)?.into_raw())?;
        Ok(owned)
    }
}

/// A size in points: TS's `Size` (`{ width, height }`).
impl JsValue for crate::geometry::Size<crate::geometry::Points> {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Size".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if value.kind() != JsKind::Object {
            return Err(value.expected("an object with width and height"));
        }
        Ok(Self::new(
            field_of(value, "width")?,
            field_of(value, "height")?,
        ))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let owned = JsOwned::new(host, host.new_object()?);
        let object = owned.get().raw();
        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
        Ok(owned)
    }
}

/// What an image shows, as `<Image>`'s `src` takes it (a Rust component's
/// image prop): decoded by `<Image>`'s own decoder and declared with its
/// type, so the two take the same values (a URL, an `asset:/` or `data:`
/// URI, a `blob:` URL, an imported `ImageAsset` with its size and scales).
/// A `blob:` URL takes its blob's bytes from the VM, as `<Image>`'s does
/// ([`super::JsHost::image_blob`]). An empty string is an empty source: no
/// image.
impl JsValue for super::ImageSrc {
    fn ts_type(types: &mut TsTypes) -> String {
        <crate::ImageSource as crate::js::host::HostValue>::ts_type(types)
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        use crate::js::host::{HostCx, HostValue};
        // A source is a string or a small object, decoded when the prop is
        // set: through JSON, `<Image>`'s decoder reads it as it reads a
        // host prop.
        let json = value.to_json()?;
        let input = super::animated::JsonInput(Some(&json));
        match crate::ImageSource::decode(&input, &mut HostCx::default()) {
            Some(source) => {
                let (uri, data) = match source.uri.starts_with("blob:") {
                    true => match value.host().image_blob(&source.uri) {
                        Some((key, data)) => (key, Some(data)),
                        None => (source.uri, None),
                    },
                    false => (source.uri, None),
                };
                Ok(Self {
                    uri: uri.into(),
                    size: source.size.map(|s| (s.width.0, s.height.0)),
                    scales: source.scales,
                    data,
                })
            }
            None if json.as_str() == Some("") => Ok("".into()),
            None => Err(value.expected("a URL or an imported image")),
        }
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        if self.size.is_none() && self.scales.is_empty() {
            return self.uri.to_js(host);
        }
        let owned = JsOwned::new(host, host.new_object()?);
        let object = owned.get().raw();
        host.set_field(object, "url", self.uri.to_js(host)?.into_raw())?;
        if let Some((w, h)) = self.size {
            let size =
                crate::geometry::size(crate::geometry::Points(w), crate::geometry::Points(h));
            host.set_field(object, "size", size.to_js(host)?.into_raw())?;
        }
        if !self.scales.is_empty() {
            let scales: Vec<f32> = self.scales.iter().collect();
            host.set_field(object, "scales", scales.to_js(host)?.into_raw())?;
        }
        Ok(owned)
    }
}

/// A rectangle in points: TS's `Bounds` (`{ origin, size }`), as events
/// carry it.
impl JsValue for crate::geometry::Bounds<crate::geometry::Points> {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Bounds".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if value.kind() != JsKind::Object {
            return Err(value.expected("an object with origin and size"));
        }
        Ok(Self::new(
            field_of(value, "origin")?,
            field_of(value, "size")?,
        ))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let owned = JsOwned::new(host, host.new_object()?);
        let object = owned.get().raw();
        host.set_field(object, "origin", self.origin.to_js(host)?.into_raw())?;
        host.set_field(object, "size", self.size.to_js(host)?.into_raw())?;
        Ok(owned)
    }
}

/// A length on each side, in points, as a host element's `hitSlop` takes
/// it (TS `number | Partial<Edges>`): one number for every side, or the
/// sides named, each left out 0. A Rust component's prop of the host
/// prop's meaning (`Button`'s `hitSlop`) takes the same values. To JS it
/// is the four sides.
impl JsValue for crate::geometry::Edges<crate::geometry::Points> {
    fn ts_type(_types: &mut TsTypes) -> String {
        "number | Partial<Edges>".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        use crate::geometry::Points;
        let length = |n: Option<f64>| match n {
            Some(n) if n.is_finite() => Ok(Points(n as f32)),
            _ => Err(value.expected("a number or `{ top?, right?, bottom?, left? }`")),
        };
        if let Some(n) = value.as_number() {
            return length(Some(n)).map(Self::all);
        }
        if value.kind() != JsKind::Object {
            return Err(value.expected("a number or `{ top?, right?, bottom?, left? }`"));
        }
        let side = |key: &str| -> Result<Points, PropError> {
            let field = value.field(key)?;
            let field = field.get();
            match field.is_nullish() {
                true => Ok(Points(0.0)),
                false => length(field.as_number()),
            }
        };
        Ok(Self {
            top: side("top")?,
            right: side("right")?,
            bottom: side("bottom")?,
            left: side("left")?,
        })
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let owned = JsOwned::new(host, host.new_object()?);
        let object = owned.get().raw();
        host.set_field(object, "top", self.top.to_js(host)?.into_raw())?;
        host.set_field(object, "right", self.right.to_js(host)?.into_raw())?;
        host.set_field(object, "bottom", self.bottom.to_js(host)?.into_raw())?;
        host.set_field(object, "left", self.left.to_js(host)?.into_raw())?;
        Ok(owned)
    }
}

/// The modifier keys held: TS's `Modifiers` (`{ control, alt, shift,
/// platform, altGraph }`, GPUI's names), as press events carry them. A missing key
/// is not held.
impl JsValue for crate::keymap::Modifiers {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Modifiers".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if value.kind() != JsKind::Object {
            return Err(value.expected("an object of modifier keys"));
        }
        let held = |key: &str| -> Result<bool, PropError> {
            Ok(field_of::<Option<bool>>(value, key)?.unwrap_or(false))
        };
        Ok(Self {
            ctrl: held("control")?,
            alt: held("alt")?,
            shift: held("shift")?,
            cmd: held("platform")?,
            alt_graph: held("altGraph")?,
        })
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let owned = JsOwned::new(host, host.new_object()?);
        let object = owned.get().raw();
        for (key, held) in [
            ("control", self.ctrl),
            ("alt", self.alt),
            ("shift", self.shift),
            ("platform", self.cmd),
            ("altGraph", self.alt_graph),
        ] {
            host.set_field(object, key, held.to_js(host)?.into_raw())?;
        }
        Ok(owned)
    }
}

impl JsValue for SharedString {
    fn ts_type(_types: &mut TsTypes) -> String {
        "string".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        value
            .as_string()
            .map(Into::into)
            .ok_or_else(|| value.expected("a string"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(host, host.new_string(self.as_str())?))
    }
}

impl JsValue for String {
    fn ts_type(_types: &mut TsTypes) -> String {
        "string".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        value.as_string().ok_or_else(|| value.expected("a string"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(host, host.new_string(self)?))
    }
}

/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`), as
/// [`Color`] takes it: the color of Rust components' props.
impl JsValue for crate::Hsla {
    fn ts_type(types: &mut TsTypes) -> String {
        Color::ts_type(types)
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        Color::from_js(value).map(Into::into)
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Color::from(*self).to_js(host)
    }
}

/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`).
impl JsValue for Color {
    fn ts_type(_types: &mut TsTypes) -> String {
        "string".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        value
            .as_string()
            .as_deref()
            .and_then(Color::parse)
            .ok_or_else(|| value.expected("a color"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(
            host,
            host.new_string(&format!("#{:08x}", self.0))?,
        ))
    }
}

/// A node JS passes (an element, a `ref`: TS `ViewRef`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeRef(pub crate::NodeId);

impl JsValue for NodeRef {
    fn ts_type(_types: &mut TsTypes) -> String {
        "ViewRef".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        value
            .host()
            .node(value.raw())
            .map(NodeRef)
            .ok_or_else(|| value.expected("a node"))
    }

    /// The node's JS object (`null` once JS let it go).
    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(host, host.node_value(self.0)))
    }
}

/// Any value, as JSON (a real JSON API's data: `JSON.stringify`'s view of
/// the value).
impl JsValue for JsonValue {
    fn ts_type(_types: &mut TsTypes) -> String {
        "unknown".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        match value.kind() {
            JsKind::Undefined => Ok(JsonValue::Null),
            _ => value.to_json(),
        }
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(host, host.json(self)?))
    }
}

/// `null` (and `undefined`) is `None`.
impl<T: JsValue> JsValue for Option<T> {
    fn ts_type(types: &mut TsTypes) -> String {
        format!("{} | null", T::ts_type(types))
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if value.is_nullish() {
            Ok(None)
        } else {
            T::from_js(value).map(Some)
        }
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        match self {
            Some(v) => v.to_js(host),
            None => Ok(JsOwned::new(host, host.null())),
        }
    }
}

/// Bytes are a `Uint8Array` (a `Buffer` is one too), not an array of
/// numbers: `u8` is no [`JsValue`], so this and the arrays below never
/// overlap.
impl JsValue for Vec<u8> {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Uint8Array".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        value
            .as_bytes()
            .ok_or_else(|| value.expected("a Uint8Array"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        Ok(JsOwned::new(host, host.new_bytes(self)?))
    }
}

/// An object of strings by name (`process.env`): `Record<string, string>`.
impl JsValue for std::collections::BTreeMap<String, String> {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Record<string, string>".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        if value.kind() != JsKind::Object {
            return Err(value.expected("an object of strings"));
        }
        let JsonValue::Object(fields) = value.to_json()? else {
            return Err(value.expected("an object of strings"));
        };
        fields
            .into_iter()
            .map(|(key, v)| match v {
                JsonValue::String(s) => Ok((key, s)),
                other => Err(PropError::expected("a string", &other)),
            })
            .collect()
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let object = JsOwned::new(host, host.new_object()?);
        for (key, value) in self {
            host.set_field(object.get().raw(), key, host.new_string(value)?)?;
        }
        Ok(object)
    }
}

/// A time is a `Date` (its milliseconds since the Unix epoch).
impl JsValue for std::time::SystemTime {
    fn ts_type(_types: &mut TsTypes) -> String {
        "Date".into()
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        let millis = value
            .as_date()
            .filter(|m| m.is_finite())
            .ok_or_else(|| value.expected("a valid Date"))?;
        let since = std::time::Duration::from_secs_f64(millis.abs() / 1000.0);
        let time = if millis < 0.0 {
            std::time::UNIX_EPOCH.checked_sub(since)
        } else {
            std::time::UNIX_EPOCH.checked_add(since)
        };
        time.ok_or_else(|| value.expected("a Date in range"))
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        let millis = match self.duration_since(std::time::UNIX_EPOCH) {
            Ok(since) => since.as_secs_f64() * 1000.0,
            Err(before) => -before.duration().as_secs_f64() * 1000.0,
        };
        Ok(JsOwned::new(host, host.new_date(millis)?))
    }
}

impl<T: JsValue> JsValue for Vec<T> {
    fn ts_type(types: &mut TsTypes) -> String {
        format!("({})[]", T::ts_type(types))
    }

    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
        let len = value
            .array_len()?
            .ok_or_else(|| value.expected("an array"))?;
        // The length is JS's (the host limits what it reads): reserve a
        // bounded amount up front.
        let mut out = Vec::with_capacity(len.min(1024));
        for i in 0..len {
            let item = value.index(i)?;
            out.push(T::from_js(item.get()).map_err(|e| PropError(format!("[{i}]: {e}")))?);
        }
        Ok(out)
    }

    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        // Owned until the array takes them: an item failing frees the
        // ones made before.
        let mut items = Vec::with_capacity(self.len());
        for item in self {
            items.push(item.to_js(host)?);
        }
        let raws = items.into_iter().map(JsOwned::into_raw).collect();
        Ok(JsOwned::new(host, host.new_array(raws)?))
    }
}

#[cfg(test)]
mod tests {
    use super::{JsIn, JsValue, percent};
    use crate::element::{JsObject, json_host::JsonHost};

    #[derive(Debug, PartialEq, JsObject)]
    #[prop(exact)]
    struct ObjectFields {
        required: String,
        optional: Option<String>,
        #[prop(default)]
        count: u32,
        #[prop(default = 7)]
        custom: u32,
        #[prop(default = Some(9))]
        nullable: Option<u32>,
    }

    #[test]
    fn object_fields_keep_defaults_nulls_and_error_paths() {
        let host = JsonHost::default();
        let read = |json| {
            let raw = host.value(json);
            ObjectFields::from_js(JsIn::new(&host, raw))
        };
        let absent = read(serde_json::json!({ "required": "ok" })).unwrap();
        assert_eq!(
            absent,
            ObjectFields {
                required: "ok".into(),
                optional: None,
                count: 0,
                custom: 7,
                nullable: Some(9),
            }
        );
        let nulls = read(serde_json::json!({
            "required": "ok", "optional": null, "count": null, "custom": null, "nullable": null,
        }))
        .unwrap();
        assert_eq!(
            nulls,
            ObjectFields {
                nullable: None,
                ..absent
            }
        );
        let values = read(serde_json::json!({
            "required": "yes", "optional": "there", "count": 2, "custom": 3, "nullable": 4,
        }))
        .unwrap();
        assert_eq!(
            values,
            ObjectFields {
                required: "yes".into(),
                optional: Some("there".into()),
                count: 2,
                custom: 3,
                nullable: Some(4),
            }
        );
        for json in [
            serde_json::json!({}),
            serde_json::json!({ "required": null }),
        ] {
            assert_eq!(read(json).unwrap_err().0, "`required` is missing");
        }
        assert_eq!(
            read(serde_json::json!({ "required": "ok", "unknown": true }))
                .unwrap_err()
                .0,
            "unknown field `unknown`",
        );
        let error = read(serde_json::json!({ "required": "ok", "count": "bad" }))
            .unwrap_err()
            .0;
        assert!(error.starts_with("`count`: "), "{error}");
    }

    /// Fields of one `Option` type in a row are read and written in a
    /// loop: as each would be on its own.
    #[derive(Debug, Default, PartialEq, JsObject)]
    struct Runs {
        first: Option<u32>,
        a: Option<String>,
        b: Option<String>,
        c: Option<String>,
        d: Option<String>,
        #[prop(skip_none)]
        e: Option<u32>,
        #[prop(skip_none)]
        f: Option<u32>,
        #[prop(skip_none)]
        g: Option<u32>,
        #[prop(skip_none)]
        h: Option<u32>,
        #[prop(default = Some(1))]
        last: Option<u32>,
    }

    #[test]
    fn runs_of_option_fields_read_and_write_as_fields() {
        let host = JsonHost::default();
        let read = |json| Runs::from_js(JsIn::new(&host, host.value(json)));
        let runs = read(serde_json::json!({
            "first": 1, "a": "a", "c": null, "d": "d", "f": 6, "h": 8,
        }))
        .unwrap();
        assert_eq!(
            runs,
            Runs {
                first: Some(1),
                a: Some("a".into()),
                d: Some("d".into()),
                f: Some(6),
                h: Some(8),
                last: Some(1),
                ..Runs::default()
            }
        );
        assert_eq!(
            host.read(runs.to_js(&host).unwrap()),
            Some(serde_json::json!({
                "first": 1, "a": "a", "b": null, "c": null, "d": "d", "f": 6, "h": 8, "last": 1,
            }))
        );
        let error = read(serde_json::json!({ "a": "a", "c": 3, "g": "bad" }))
            .unwrap_err()
            .0;
        assert!(error.starts_with("`c`: "), "{error}");
    }

    /// An image prop takes what `<Image>`'s `src` takes, read by the same
    /// decoder and declared with the same type: a URL, an imported asset
    /// with its size and scales, an empty string (no image); anything else
    /// is refused. It goes back to JS in the form it came in.
    #[test]
    fn image_sources_read_as_images_read_them() {
        use crate::element::{ImageSrc, TsTypes};
        let host = JsonHost::default();
        let read = |json| ImageSrc::from_js(JsIn::new(&host, host.value(json)));
        let url = read(serde_json::json!("https://example.com/ada.png")).unwrap();
        assert_eq!(url, ImageSrc::from("https://example.com/ada.png"));
        assert_eq!(
            host.read(url.to_js(&host).unwrap()),
            Some(serde_json::json!("https://example.com/ada.png"))
        );
        let asset = serde_json::json!({
            "url": "asset:/ada.png",
            "size": { "width": 48, "height": 48 },
            "scales": [1, 2, 2.5, 3],
        });
        let read_asset = read(asset).unwrap();
        assert_eq!(read_asset.size, Some((48.0, 48.0)));
        assert_eq!(
            read_asset.scales.iter().collect::<Vec<_>>(),
            [1.0, 2.0, 3.0]
        );
        // Written back, it reads as the same asset (whatever form its
        // numbers take in JSON).
        let written = host.read(read_asset.to_js(&host).unwrap()).unwrap();
        assert_eq!(read(written).unwrap(), read_asset);
        assert!(read(serde_json::json!("")).unwrap().is_empty());
        // A host without blobs keeps a `blob:` URL as it is, with no bytes.
        let blob = read(serde_json::json!("blob:nsh://app/1")).unwrap();
        assert_eq!((blob.uri.as_str(), blob.data), ("blob:nsh://app/1", None));
        for bad in [
            serde_json::json!(3),
            serde_json::json!({ "uri": "https://example.com/a.png" }),
            serde_json::json!(true),
        ] {
            assert!(read(bad.clone()).is_err(), "{bad}");
        }
        assert_eq!(
            ImageSrc::ts_type(&mut TsTypes::default()),
            <crate::ImageSource as crate::js::host::HostValue>::ts_type(&mut TsTypes::default())
        );
    }

    /// A percentage as CSS writes it; anything else is not one.
    #[test]
    fn percentages_read_as_css_writes_them() {
        assert_eq!(percent("50%"), Some(50.0));
        assert_eq!(percent(" 62.5 %"), Some(62.5));
        assert_eq!(percent("-10%"), Some(-10.0));
        assert_eq!(percent("50"), None);
        assert_eq!(percent("50px"), None);
        assert_eq!(percent("%"), None);
        assert_eq!(percent("NaN%"), None);
    }
}