nsh-core 0.8.1

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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
//! The host prop values that are objects or unions (sources, accessibility
//! descriptions, list layouts) and the props whose whole variant is
//! decoded by hand (`#[prop(with = …)]`): the shapes JS sends them in.

use super::host::{HostCx, HostInput, HostList, HostValue, field};
use crate::{
    AccessibilityCurrent, AccessibilityProp, AccessibilityRole, AccessibilityState, AutoFill,
    CellSlot, EdgeInsets, HeaderItem, HeaderItemContent, HeaderSystemItem, ImageScales,
    ImageSource, KeyboardTaps, ListContentStyle, MacOsBackdrop, MacOsBackdropBlending,
    MacOsBackdropMaterial, MacOsBackdropState, ModalProp, Prop, RevealOptions, ScreenProp,
    ScrollAlignment, ScrollProp, StatusBarSetting, StatusBarStyle, Viewability, WindowsBackdrop,
    WindowsBackdropMaterial,
    element::{ElementTarget, ScrollEdgeTarget, TsTypes},
    geometry::{Bounds, Percentage, Points, point, size},
    mount::ModalConfig,
    ops::OverlayProp,
    overlay::{OverlayAnchor, TooltipContent},
    props::{AccessibilityActionDef, AccessibilityValue, Checked, PanActivation, Ripple},
};

/// `"none"`, `"all"`, `"text"`, or the canonical keystrokes a view captures
/// (`"mod+k"`, `"shift+tab"`): parsed once here with the shortcut rules
/// and this platform's `mod`, which the engine's environment names
/// ([`crate::element::try_apple_keys`]); a JS host decoding outside that
/// environment calls [`crate::js::host::decode_capture_keys`] with its own
/// convention.
/// Another string clears the rule with a warning; an invalid keystroke in
/// the array is reported and left out.
impl HostValue for crate::KeyCapture {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        let apple = crate::element::try_apple_keys().unwrap_or(false);
        super::host::decode_capture_keys(input, cx, apple)
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "\"none\" | \"all\" | \"text\" | readonly string[]".into()
    }
}

fn number<I: HostInput>(input: &I, key: &str) -> Option<f32> {
    input
        .field(key)
        .and_then(|v| v.as_number())
        .map(|n| n as f32)
}

/// Field `key` of `input` as a number of points.
fn points<I: HostInput>(input: &I, key: &str) -> Option<Points> {
    number(input, key).map(Points)
}

/// The `scales` of an image asset (its first [`crate::ops::SCALES_READ`]
/// entries); values that are not [`crate::IMAGE_SCALES`] are left out.
fn scales<I: HostInput>(input: &I) -> ImageScales {
    let Some(list) = input.field("scales").and_then(|s| s.as_list()) else {
        return ImageScales::NONE;
    };
    (0..list.len().min(crate::ops::SCALES_READ))
        .filter_map(|i| list.item(i)?.as_number())
        .map(|n| n as f32)
        .collect()
}

/// `"https://…"` or a bundled asset `{ url, size: { width, height }, scales }`.
impl HostValue for ImageSource {
    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
        if let Some(url) = input.as_string() {
            return (!url.is_empty()).then(|| ImageSource {
                uri: url.into(),
                size: None,
                scales: ImageScales::NONE,
                data: None,
            });
        }
        let url = input.field("url")?.as_string()?;
        let extent = input.field("size");
        let size = match extent
            .as_ref()
            .map(|e| (number(e, "width"), number(e, "height")))
        {
            Some((Some(w), Some(h))) => Some(size(Points(w), Points(h))),
            _ => None,
        };
        Some(ImageSource {
            uri: url.into(),
            size,
            scales: scales(input),
            data: None,
        })
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "string | ImageAsset".into()
    }
}

/// `ref.reveal(options)`: `{ vertical?, horizontal?, animated? }`, each
/// missing one its default. None for an alignment that is not one, so the
/// call throws rather than scrolling somewhere the app did not ask for.
impl HostValue for RevealOptions {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        let mut options = RevealOptions::default();
        if input.is_nullish() {
            return Some(options);
        }
        if !input.is_object() {
            return None;
        }
        let mut alignment = |key: &str, default: ScrollAlignment| match input.field(key) {
            Some(value) if !value.is_nullish() => {
                <ScrollAlignment as HostValue>::decode(&value, cx)
            }
            _ => Some(default),
        };
        options.vertical = alignment("vertical", options.vertical)?;
        options.horizontal = alignment("horizontal", options.horizontal)?;
        if let Some(animated) = input.field("animated").and_then(|a| a.as_bool()) {
            options.animated = animated;
        }
        Some(options)
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let alignment = <ScrollAlignment as HostValue>::ts_type(types);
        types.declare("RevealOptions", |_| {
            format!(
                "/** How `reveal` places a view in the scroll views around it. */\n\
                 export interface RevealOptions {{\n  \
                 /** Along vertical scroll views; `\"start\"` by default. */\n  \
                 vertical?: {alignment};\n  \
                 /** Along horizontal scroll views; `\"nearest\"` by default. */\n  \
                 horizontal?: {alignment};\n  \
                 /** Animate the scrolls; `true` by default. */\n  \
                 animated?: boolean;\n}}"
            )
        })
    }
}

/// A list's `contentStyle`: the padding properties (numbers),
/// `gap` / `rowGap` / `columnGap`, and cross-axis `alignItems`.
impl HostValue for ListContentStyle {
    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
        let n = |key| points(input, key);
        let all = n("padding").unwrap_or_default();
        let inline = n("paddingHorizontal").unwrap_or(all);
        let block = n("paddingVertical").unwrap_or(all);
        let gap = n("gap").unwrap_or_default();
        let align_items = input
            .field("alignItems")
            .and_then(|v| v.as_string())
            .and_then(|v| match v.as_str() {
                "stretch" => Some(taffy::AlignItems::STRETCH),
                "flex-start" => Some(taffy::AlignItems::FLEX_START),
                "center" => Some(taffy::AlignItems::CENTER),
                "flex-end" => Some(taffy::AlignItems::FLEX_END),
                _ => None,
            });
        Some(ListContentStyle {
            padding: EdgeInsets {
                top: n("paddingTop").unwrap_or(block),
                right: n("paddingRight").unwrap_or(inline),
                bottom: n("paddingBottom").unwrap_or(block),
                left: n("paddingLeft").unwrap_or(inline),
            },
            row_gap: n("rowGap").unwrap_or(gap),
            column_gap: n("columnGap").unwrap_or(gap),
            align_items,
        })
    }

    fn ts_type(types: &mut TsTypes) -> String {
        types.declare("ListContentStyle", |_| {
            "/** Padding, gaps and cell alignment of a list's content (`contentStyle`). */\n\
             export interface ListContentStyle {\n  padding?: number;\n  paddingHorizontal?: number;\n  \
             paddingVertical?: number;\n  paddingTop?: number;\n  paddingRight?: number;\n  \
             paddingBottom?: number;\n  paddingLeft?: number;\n  gap?: number;\n  rowGap?: number;\n  \
             columnGap?: number;\n  alignItems?: \"stretch\" | \"flex-start\" | \"center\" | \"flex-end\";\n}"
                .into()
        })
    }
}

/// `macos={{ backdrop }}`: `{ material, blending, state }`, each field
/// falling back to its default when left out or unknown.
impl HostValue for MacOsBackdrop {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        Some(MacOsBackdrop {
            material: field::<MacOsBackdropMaterial, _>(input, "material", cx).unwrap_or_default(),
            blending: field::<MacOsBackdropBlending, _>(input, "blending", cx).unwrap_or_default(),
            state: field::<MacOsBackdropState, _>(input, "state", cx).unwrap_or_default(),
        })
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let material = <MacOsBackdropMaterial as HostValue>::ts_type(types);
        let blending = <MacOsBackdropBlending as HostValue>::ts_type(types);
        let state = <MacOsBackdropState as HostValue>::ts_type(types);
        types.declare("MacOsBackdrop", |_| {
            format!(
                "/** The material a view draws with on macOS (`macos={{{{ backdrop }}}}`). */\n\
                 export interface MacOsBackdrop {{\n  material?: {material};\n  \
                 blending?: {blending};\n  state?: {state};\n}}"
            )
        })
    }
}

/// `ios={{ scrollEdgeElement }}`: `{ scrollView, edge }`, the scroll
/// view a ref holds and the edge (`"bottom"` when left out or unknown);
/// without a scroll view it is none.
impl HostValue for ScrollEdgeTarget {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        let scroll_view = input.field("scrollView")?.node()?;
        let edge = field::<crate::ScrollEdge, _>(input, "edge", cx).unwrap_or_default();
        Some(ScrollEdgeTarget::of_node(scroll_view, edge))
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let edge = <crate::ScrollEdge as HostValue>::ts_type(types);
        types.declare("ScrollEdgeElement", |_| {
            format!(
                "/** The scroll view a view floats over and the edge of it the view sits at \
                 (`ios={{{{ scrollEdgeElement }}}}`). */\n\
                 export interface ScrollEdgeElement {{\n  scrollView: ViewRef;\n  \
                 edge?: {edge};\n}}"
            )
        })
    }
}

impl HostValue for WindowsBackdrop {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        Some(Self {
            material: field(input, "material", cx)?,
        })
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let material = <WindowsBackdropMaterial as HostValue>::ts_type(types);
        types.declare("WindowsBackdrop", |_| {
            format!(
                "/** The material a view draws with on Windows (`windows={{{{ backdrop }}}}`). */\n\
                 export interface WindowsBackdrop {{\n  material: {material};\n}}"
            )
        })
    }
}

/// A dialog's `detents`, `detent`, `defaultDetent` and
/// `largestUndimmedDetent`: `"medium"`, `"large"`, `{ height }` or
/// `{ fraction }`; anything else is left out with a warning.
impl HostValue for crate::SheetDetent {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        use crate::SheetDetent;
        if input.is_nullish() {
            return None;
        }
        if let Some(name) = input.as_string() {
            match name.as_str() {
                "medium" => return Some(SheetDetent::Medium),
                "large" => return Some(SheetDetent::Large),
                _ => {}
            }
        } else if input.is_object() {
            let number = |key| input.field(key).and_then(|v| v.as_number());
            let detent = match number("height") {
                Some(height) => SheetDetent::of_height(height),
                None => number("fraction").and_then(SheetDetent::of_fraction),
            };
            if detent.is_some() {
                return detent;
            }
        }
        cx.warn(
            r#"detent: expected "medium", "large", `{ height }` (0 or more) or `{ fraction }` (0 to 1)"#,
        );
        None
    }

    fn ts_type(types: &mut TsTypes) -> String {
        <crate::SheetDetent as crate::element::JsValue>::ts_type(types)
    }
}

/// A page's or dialog's `statusBar`: `{ foreground, hidden, animated }`
/// (`StatusBar`, declared with the navigation in `nsh/base`); the fields
/// left out keep what is below. An unknown `foreground` is left out.
impl HostValue for StatusBarSetting {
    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        let flag = |key| input.field(key).and_then(|v| v.as_bool());
        Some(StatusBarSetting {
            style: input
                .field("foreground")
                .and_then(|v| v.as_string())
                .and_then(|s| StatusBarStyle::from_name(&s)),
            hidden: flag("hidden"),
            animated: flag("animated"),
        })
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "StatusBar".into()
    }
}

impl HostValue for Viewability {
    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
        Some(Viewability {
            view_area_coverage_threshold: number(input, "viewAreaCoverageThreshold")
                .map(Percentage),
            item_visible_threshold: number(input, "itemVisibleThreshold").map(Percentage),
        })
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "ViewabilityConfig".into()
    }
}

/// `{ activeOffsetX, activeOffsetY, failOffsetX, failOffsetY, direction,
/// edge }` (points, the sign ignored; an unknown `direction` or `edge` is
/// left out).
impl HostValue for PanActivation {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        let offset = |key| points(input, key).map(Points::abs);
        Some(PanActivation {
            active_offset_x: offset("activeOffsetX"),
            active_offset_y: offset("activeOffsetY"),
            fail_offset_x: offset("failOffsetX"),
            fail_offset_y: offset("failOffsetY"),
            direction: field(input, "direction", cx),
            edge: field(input, "edge", cx),
        })
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let direction = <crate::PanDirection as HostValue>::ts_type(types);
        let edge = <crate::PanEdge as HostValue>::ts_type(types);
        types.declare("PanActivation", |_| {
            format!(
                "/** When a view's pans activate (`panActivation`; react-native-gesture-handler's\n \
                 * `activeOffsetX` / `failOffsetY`), decided natively on the main thread as the\n \
                 * finger moves: past an active offset the view becomes the responder, its `pan`\n \
                 * starts and the scroll views around it can no longer take the touches; past a\n \
                 * fail offset first it never does, and they keep them. Distances in points along\n \
                 * one axis, either direction; without active offsets it activates after 10 points. */\n\
                 export interface PanActivation {{\n  \
                 activeOffsetX?: number;\n  activeOffsetY?: number;\n  \
                 failOffsetX?: number;\n  failOffsetY?: number;\n  \
                 /** The one way it activates in: a drag the other way, or mostly across it, fails it. */\n  \
                 direction?: {direction};\n  \
                 /** Only a finger that goes down within 20 points of this edge of the screen (the\n   \
                 * window on desktops, the page on the web) starts it, moving away from the edge. */\n  \
                 edge?: {edge};\n}}"
            )
        })
    }
}

/// `{ disabled, selected, checked: true | false | "mixed", busy, expanded,
/// pressed: true | false | "mixed", current: true | false | "page" | ...,
/// hasPopup, invalid }`.
impl HostValue for AccessibilityState {
    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
        let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
        let tristate = |key| {
            let value = input.field(key);
            match value.as_ref().and_then(|c| c.as_bool()) {
                Some(true) => Some(Checked::True),
                Some(false) => Some(Checked::False),
                None => value
                    .and_then(|c| c.as_string())
                    .filter(|s| s == "mixed")
                    .map(|_| Checked::Mixed),
            }
        };
        let current = input.field("current");
        Some(AccessibilityState {
            disabled: flag("disabled"),
            selected: flag("selected"),
            checked: tristate("checked"),
            busy: flag("busy"),
            expanded: input.field("expanded").and_then(|v| v.as_bool()),
            pressed: tristate("pressed"),
            has_popup: flag("hasPopup"),
            invalid: flag("invalid"),
            // `false` and unknown words are no current item, as ARIA has it.
            current: match current.as_ref().and_then(|c| c.as_bool()) {
                Some(true) => Some(AccessibilityCurrent::True),
                Some(false) => None,
                None => match current.and_then(|c| c.as_string()).as_deref() {
                    Some("page") => Some(AccessibilityCurrent::Page),
                    Some("step") => Some(AccessibilityCurrent::Step),
                    Some("location") => Some(AccessibilityCurrent::Location),
                    Some("date") => Some(AccessibilityCurrent::Date),
                    Some("time") => Some(AccessibilityCurrent::Time),
                    Some("true") => Some(AccessibilityCurrent::True),
                    _ => None,
                },
            },
        })
    }

    fn ts_type(types: &mut TsTypes) -> String {
        types.declare("AccessibilityState", |_| {
            "/** The state assistive technologies report (`accessibilityState`). */\n\
             export interface AccessibilityState {\n  disabled?: boolean;\n  selected?: boolean;\n  \
             checked?: boolean | \"mixed\";\n  busy?: boolean;\n  expanded?: boolean;\n  \
             /** A toggle button that is on or off (ARIA's `aria-pressed`). */\n  \
             pressed?: boolean | \"mixed\";\n  \
             /** The current item of a set (ARIA's `aria-current`): a pagination's page, a wizard's step. */\n  \
             current?: boolean | \"page\" | \"step\" | \"location\" | \"date\" | \"time\";\n  \
             /** Opens a popup, a menu or a list (ARIA's `aria-haspopup`); `expanded` says whether it is open. */\n  \
             hasPopup?: boolean;\n  \
             /** The content does not pass the app's checks (ARIA's `aria-invalid`): a rejected field. */\n  \
             invalid?: boolean;\n}"
                .into()
        })
    }
}

/// `{ min, max, now, text }`.
impl HostValue for AccessibilityValue {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        Some(AccessibilityValue {
            min: number(input, "min"),
            max: number(input, "max"),
            now: number(input, "now"),
            text: field(input, "text", cx),
        })
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "{ min?: number; max?: number; now?: number; text?: string }".into()
    }
}

/// `{ name, label }`; without a name there is no action.
impl HostValue for AccessibilityActionDef {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        Some(AccessibilityActionDef {
            name: field(input, "name", cx)?,
            label: field(input, "label", cx),
        })
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "{ name: string; label?: string }".into()
    }
}

/// The `autoComplete` names of the TypeScript type ([`AutoFill::parse`]
/// takes a few more).
const AUTO_COMPLETE: &[&str] = &[
    "off",
    "username",
    "password",
    "current-password",
    "new-password",
    "one-time-code",
    "sms-otp",
    "email",
    "tel",
    "name",
    "given-name",
    "family-name",
    "additional-name",
    "nickname",
    "organization",
    "street-address",
    "address-line1",
    "address-line2",
    "address-level1",
    "address-level2",
    "postal-code",
    "country",
    "cc-number",
    "cc-exp",
    "cc-csc",
    "cc-name",
    "url",
    "birthdate-full",
];

/// iOS's `textContentType` names.
const TEXT_CONTENT_TYPE: &[&str] = &[
    "none",
    "username",
    "password",
    "newPassword",
    "oneTimeCode",
    "emailAddress",
    "telephoneNumber",
    "name",
    "givenName",
    "middleName",
    "familyName",
    "nickname",
    "organizationName",
    "fullStreetAddress",
    "streetAddressLine1",
    "streetAddressLine2",
    "addressCity",
    "addressState",
    "postalCode",
    "countryName",
    "creditCardNumber",
    "creditCardExpiration",
    "creditCardSecurityCode",
    "creditCardName",
    "URL",
    "birthdate",
];

/// `autoComplete` values or iOS's `textContentType` names; others are the
/// platform's default (and a warning).
impl HostValue for AutoFill {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        let name = input.as_string()?;
        let fill = AutoFill::parse(&name);
        if fill.is_none() {
            cx.warn(format!(
                "{name:?} is not a supported autoComplete / textContentType value"
            ));
        }
        fill
    }

    /// Either list of names: the decoder takes both.
    fn ts_type(types: &mut TsTypes) -> String {
        let union = |names: &[&str]| {
            names
                .iter()
                .map(|n| format!("{n:?}"))
                .collect::<Vec<_>>()
                .join(" | ")
        };
        let web = types.declare("AutoComplete", |_| {
            format!(
                "/** What an input holds, for autofill (React Native's `autoComplete` values). */\n\
                 export type AutoComplete = {};",
                union(AUTO_COMPLETE)
            )
        });
        let ios = types.declare("TextContentType", |_| {
            format!(
                "/** iOS's names for `autoComplete` values. */\nexport type TextContentType = {};",
                union(TEXT_CONTENT_TYPE)
            )
        });
        format!("{web} | {ios}")
    }
}

/// `{ color, borderless, radius, foreground }`.
impl HostValue for Ripple {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
        Some(Ripple {
            color: field(input, "color", cx),
            borderless: flag("borderless"),
            radius: points(input, "radius"),
            foreground: flag("foreground"),
        })
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "{ color?: ColorValue; borderless?: boolean; radius?: number; foreground?: boolean }".into()
    }
}

/// An iOS bar button: `{ key?, systemItem | symbol (title?) | label,
/// disabled?, menu? }`. Handlers (`onPress`, menu `onSelect`) are taken by
/// the JS runtime when it sets the prop; this decode leaves their ids at 0.
impl HostValue for HeaderItem {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        let system = field::<HeaderSystemItem, _>(input, "systemItem", cx);
        let symbol = field::<std::sync::Arc<str>, _>(input, "symbol", cx);
        let label_content = field::<std::sync::Arc<str>, _>(input, "label", cx);
        let title = field::<std::sync::Arc<str>, _>(input, "title", cx);
        let content = match (system, symbol, label_content.clone(), title) {
            (Some(item), None, _, None) => HeaderItemContent::SystemItem(item),
            (None, Some(name), _, None) => HeaderItemContent::Symbol(name),
            (None, Some(symbol), _, Some(title)) => {
                HeaderItemContent::SymbolTitle { symbol, title }
            }
            (None, None, Some(text), None) => HeaderItemContent::Label(text),
            _ => {
                cx.warn(
                    "header item needs exactly one of systemItem, symbol, or label \
                     (title only with symbol)",
                );
                return None;
            }
        };
        // `label` is the button's title when it is the content; otherwise
        // VoiceOver's label (re-read when content was system/symbol).
        let label = match &content {
            HeaderItemContent::Label(_) => None,
            _ => label_content,
        };
        let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
        let menu = input.field("menu").and_then(|v| {
            v.as_list()?;
            Some(
                v.items()
                    .iter()
                    .filter_map(|item| decode_menu_item(item, cx))
                    .collect::<Vec<_>>(),
            )
        });
        Some(HeaderItem {
            key: field(input, "key", cx),
            content,
            label,
            disabled: flag("disabled"),
            press_id: 0,
            menu,
            shares_background: input
                .field("sharesBackground")
                .and_then(|v| v.as_bool())
                .unwrap_or(true),
        })
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let system = HeaderSystemItem::ts_type(types);
        types.declare("HeaderItem", |_| {
            format!(
                "/** An iOS navigation-bar button (`ios.headerLeftItems`,\n\
                 * `ios.headerRightItems`). `title` shows after `symbol` in one\n\
                 * button (VoiceOver reads it unless `label` is set).\n\
                 * `menu` takes `nsh/desktop`'s `MenuItem` items (`onSelect` per\n\
                 * item; `destructive`, `inline`, `symbol` as documented there).\n\
                 * `onPress` runs when the button has no menu. `sharesBackground:\n\
                 * false` gives the button its own glass capsule on iOS 26+. */\n\
                 export type HeaderItem = {{\n  key?: string;\n  disabled?: boolean;\n  \
                 sharesBackground?: boolean;\n  \
                 onPress?: () => void;\n  menu?: import(\"nsh/desktop\").MenuItem[];\n}} & (\n  \
                 {{ systemItem: {system}; symbol?: never; title?: never; label?: string }} \
                 | {{ symbol: string; title?: string; systemItem?: never; label?: string }} \
                 | {{ label: string; systemItem?: never; symbol?: never; title?: never }}\n);"
            )
        })
    }
}

/// One `nsh/desktop` menu item without its handlers (ids stay 0); JS's
/// special path for `headerLeftItems` / `headerRightItems` assigns ids and
/// keeps the functions.
fn decode_menu_item<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<crate::desktop::MenuItem> {
    use crate::{
        desktop::{MenuAction, MenuItem},
        keymap::When,
    };
    if !input.is_object() {
        return None;
    }
    if input.field("type").and_then(|v| v.as_string()).as_deref() == Some("separator") {
        return Some(MenuItem::Separator);
    }
    let flag = |key| input.field(key).and_then(|v| v.as_bool());
    let label = field::<String, _>(input, "label", cx).unwrap_or_default();
    let enabled = !flag("disabled").unwrap_or(false);
    let icon = field::<ImageSource, _>(input, "icon", cx);
    let symbol = field::<String, _>(input, "symbol", cx);
    if let Some(items_input) = input.field("submenu") {
        let items = items_input
            .items()
            .iter()
            .filter_map(|item| decode_menu_item(item, cx))
            .collect();
        return Some(MenuItem::Submenu {
            label,
            enabled,
            items,
            icon,
            symbol,
            inline: flag("inline").unwrap_or(false),
        });
    }
    let role = field::<String, _>(input, "role", cx).and_then(|name| menu_role(&name));
    if label.is_empty() && role.is_none() {
        return None;
    }
    Some(MenuItem::Action(MenuAction {
        id: 0,
        label,
        shortcut: None,
        enabled,
        checked: flag("checked"),
        role,
        when: When::Always,
        icon,
        symbol,
        destructive: flag("destructive").unwrap_or(false),
    }))
}

fn menu_role(name: &str) -> Option<crate::desktop::MenuRole> {
    crate::desktop::MenuRole::from_name(name)
}

// --- Whole variants ---------------------------------------------------------

/// `selectionMenu`: `nsh/desktop`'s `MenuItem` items. Handlers (`onSelect`)
/// are taken by the JS runtime when it sets the prop; this decode leaves
/// their ids at 0.
pub(crate) fn selection_menu<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Prop> {
    if input.is_nullish() {
        return Some(Prop::SelectionMenu(Vec::new()));
    }
    input.as_list()?;
    Some(Prop::SelectionMenu(
        input
            .items()
            .iter()
            .filter_map(|item| decode_menu_item(item, cx))
            .collect(),
    ))
}

/// `slot`: a recycling slot (a number) or a role.
pub(crate) fn slot<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::Slot(match input.as_string() {
        Some(role) => match role.as_str() {
            "header" => CellSlot::Header,
            "footer" => CellSlot::Footer,
            _ => CellSlot::Empty,
        },
        None => CellSlot::Item(input.as_number().unwrap_or(0.0) as u32),
    }))
}

/// `splice`: `[at, removed, inserted]`.
pub(crate) fn splice<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    let items = input.items();
    let at = |i: usize| {
        items
            .get(i)
            .and_then(|v| v.as_number())
            .unwrap_or(0.0)
            .max(0.0) as u32
    };
    Some(Prop::Splice(at(0), at(1), at(2)))
}

/// `stickyHeaderIndices`: the indexes, negative ones skipped.
pub(crate) fn sticky<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::StickyIndices(
        input
            .items()
            .iter()
            .filter_map(|v| v.as_number())
            .filter(|v| *v >= 0.0)
            .map(|v| v as u32)
            .collect(),
    ))
}

/// `selection`: `{ start, end }` (a caret without `end`); nothing without
/// `start`.
pub(crate) fn selection<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    let field = |key| input.field(key).and_then(|v| v.as_number());
    let start = field("start")?.max(0.0) as u32;
    Some(Prop::Selection(
        start,
        field("end").map_or(start, |e| e.max(0.0) as u32),
    ))
}

/// `pan`: `{ x, y }` animated values.
pub(crate) fn pan<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    let axis = |key| input.field(key).and_then(|v| v.animated_node());
    Some(Prop::PanValues(axis("x"), axis("y")))
}

/// `pinch`: `{ scale }`.
pub(crate) fn pinch<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::PinchValue(
        input.field("scale").and_then(|v| v.animated_node()),
    ))
}

/// `anchor`: a host element (a ref), `{ x, y }`, `{ origin, size }`, or
/// nothing.
pub(crate) fn overlay_anchor<I: HostInput>(input: &I, _: &mut HostCx) -> Option<OverlayProp> {
    let bounds = || {
        let origin = input.field("origin")?;
        let extent = input.field("size")?;
        Some(Bounds {
            origin: point(points(&origin, "x")?, points(&origin, "y")?),
            size: size(
                points(&extent, "width")?.max(Points::ZERO),
                points(&extent, "height")?.max(Points::ZERO),
            ),
        })
    };
    let anchor = match (input.node(), points(input, "x"), points(input, "y")) {
        (Some(id), ..) => OverlayAnchor::Node(id),
        (None, Some(x), Some(y)) => OverlayAnchor::Point(point(x, y)),
        _ => bounds().map_or(OverlayAnchor::None, OverlayAnchor::Bounds),
    };
    Some(OverlayProp::Anchor(anchor))
}

/// `accessibilityActiveDescendant`: an element (a ref), or nothing.
pub(crate) fn active_descendant<I: HostInput>(
    input: &I,
    _: &mut HostCx,
) -> Option<AccessibilityProp> {
    Some(AccessibilityProp::ActiveDescendant(
        input.node().map(ElementTarget::of_node),
    ))
}

/// `accessibilityControls`: an element (a ref), or nothing.
pub(crate) fn accessibility_controls<I: HostInput>(
    input: &I,
    _: &mut HostCx,
) -> Option<AccessibilityProp> {
    Some(AccessibilityProp::Controls(
        input.node().map(ElementTarget::of_node),
    ))
}

/// `accessibilityDescribedBy`: an element (a ref), or nothing.
pub(crate) fn accessibility_described_by<I: HostInput>(
    input: &I,
    _: &mut HostCx,
) -> Option<AccessibilityProp> {
    Some(AccessibilityProp::DescribedBy(
        input.node().map(ElementTarget::of_node),
    ))
}

/// `tooltip`: an element (a node JS made), or nothing.
pub(crate) fn tooltip<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    let content = input
        .node()
        .map_or(TooltipContent::None, TooltipContent::Node);
    Some(Prop::Tooltip(content))
}

/// `rotation`: `{ angle }`.
pub(crate) fn rotation<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::RotationValue(
        input.field("angle").and_then(|v| v.animated_node()),
    ))
}

/// `scrollValue`: an animated value.
pub(crate) fn scroll_value<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::ScrollValue(input.animated_node()))
}

/// `pullValue`: an animated value.
pub(crate) fn pull_value<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::PullValue(input.animated_node()))
}

/// `stickyHeaderOffset`: a number, or an animated value.
pub(crate) fn sticky_offset<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    match input.as_number() {
        Some(n) => Some(Prop::StickyOffset(Points(n as f32))),
        None => input
            .animated_node()
            .map(|node| Prop::StickyOffsetNode(Some(node))),
    }
}

/// `hitSlop`: one number for every edge, or the edges.
pub(crate) fn hit_slop<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Prop> {
    Some(Prop::HitSlop(match input.as_number() {
        Some(n) => EdgeInsets::all(Points(n as f32)),
        None => EdgeInsets::decode(input, cx).unwrap_or_default(),
    }))
}

/// `classList`: the names whose value is truthy.
pub(crate) fn class_list<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::ClassList(
        input
            .entries()
            .into_iter()
            .filter(|(_, on)| on.truthy())
            .map(|(name, _)| name.into())
            .collect(),
    ))
}

/// `tailwindTheme`: JSON; nothing without it.
pub(crate) fn tailwind_theme<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::TailwindTheme(input.as_string()?.into()))
}

/// `snapToWindowMargin`: points, finite and not negative.
pub(crate) fn snap_to_window_margin<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    let n = input.as_number()?;
    (n.is_finite() && n >= 0.0).then(|| Prop::SnapToWindowMargin(Points(n as f32)))
}

/// `uiTheme`: JSON; nothing without it.
pub(crate) fn ui_theme<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::UiTheme(input.as_string()?.into()))
}

/// `role`: one of the role names; others are no role (and a
/// warning).
pub(crate) fn role<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<AccessibilityProp> {
    let role = AccessibilityRole::decode(input, cx);
    if role.is_none()
        && let Some(name) = input.as_string().filter(|n| !n.is_empty())
    {
        cx.warn(format!("unknown role `{name}`"));
    }
    Some(AccessibilityProp::Role(role.unwrap_or_default()))
}

/// `accessibilityLevel`: a whole number from 1; anything else is none.
pub(crate) fn accessibility_level<I: HostInput>(
    input: &I,
    _: &mut HostCx,
) -> Option<AccessibilityProp> {
    let level = input
        .as_number()
        .filter(|n| *n >= 1.0 && n.fract() == 0.0 && *n <= f64::from(u32::MAX))
        .map(|n| n as u32);
    Some(AccessibilityProp::Level(level))
}

/// `importantForAccessibility`.
pub(crate) fn important<I: HostInput>(input: &I, _: &mut HostCx) -> Option<AccessibilityProp> {
    Some(match input.as_string().as_deref() {
        Some("yes") => AccessibilityProp::Important(Some(true), false),
        Some("no") => AccessibilityProp::Important(Some(false), false),
        Some("no-hide-descendants") => AccessibilityProp::Important(Some(false), true),
        _ => AccessibilityProp::Important(None, false),
    })
}

/// `decelerationRate`: `"fast"`, `"normal"` (React Native's iOS rates:
/// velocity kept per millisecond) or the rate.
pub(crate) fn deceleration<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
    Some(ScrollProp::Deceleration(match input.as_string() {
        Some(s) => match s.as_str() {
            "fast" => 0.99,
            "normal" => 0.998,
            _ => 0.0,
        },
        None => input.as_number().unwrap_or(0.0) as f32,
    }))
}

/// `maintainVisibleContentPosition`: `{ autoscrollToBottomThreshold, animated }`.
pub(crate) fn visible_content<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::FollowEnd(
        points(input, "autoscrollToBottomThreshold").map(|t| t.max(Points::ZERO)),
        input
            .field("animated")
            .and_then(|a| a.as_bool())
            .unwrap_or(false),
    ))
}

/// `refreshIndicator`: `{ height }`.
pub(crate) fn refresh_indicator<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
    Some(ScrollProp::RefreshIndicator(
        points(input, "height").map(|h| h.max(Points::ZERO)),
    ))
}

/// `contentOffset`: `{ x, y }`.
pub(crate) fn content_offset<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
    let n = |key| points(input, key).unwrap_or_default();
    Some(ScrollProp::ContentOffset(point(n("x"), n("y"))))
}

/// `scrollbar`: a boolean, or the object of a theme (kept as JSON for the
/// set that draws the built-in bar).
pub(crate) fn scrollbar<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
    Some(Prop::Scrollbar(match input.as_bool() {
        Some(shows) => shows.into(),
        None if input.is_object() => {
            crate::ScrollbarSetting::Themed(std::sync::Arc::new(json_of(input, 0, &mut {
                JSON_ENTRIES
            })))
        }
        None => crate::ScrollbarSetting::Shown,
    }))
}

/// Deepest nesting [`json_of`] reads.
const JSON_DEPTH: u32 = 64;
/// Most array items and object fields [`json_of`] reads in all.
const JSON_ENTRIES: usize = 1 << 20;

/// `input` as JSON: what is neither a boolean, number, string, array nor
/// object (a function) is `null`, and so is what is nested more than
/// [`JSON_DEPTH`] deep or past `left` entries (of [`JSON_ENTRIES`]): the
/// app's value is read natively, where neither the time budget nor the
/// interpreter's stack limit applies, and one that holds itself would
/// recurse until the engine thread's stack overflows.
fn json_of<I: HostInput>(input: &I, depth: u32, left: &mut usize) -> crate::JsonValue {
    use crate::JsonValue;
    if let Some(b) = input.as_bool() {
        return JsonValue::Bool(b);
    }
    if let Some(n) = input.as_number() {
        return serde_json::Number::from_f64(n).map_or(JsonValue::Null, JsonValue::Number);
    }
    if let Some(s) = input.as_string() {
        return JsonValue::String(s);
    }
    if depth >= JSON_DEPTH {
        return JsonValue::Null;
    }
    if let Some(list) = input.as_list() {
        let mut items = Vec::new();
        for i in 0..list.len() {
            if *left == 0 {
                break;
            }
            *left -= 1;
            if let Some(item) = list.item(i) {
                items.push(json_of(&item, depth + 1, left));
            }
        }
        return JsonValue::Array(items);
    }
    if input.is_object() {
        let mut fields = serde_json::Map::new();
        for (key, value) in input.entries() {
            if *left == 0 {
                break;
            }
            *left -= 1;
            fields.insert(key, json_of(&value, depth + 1, left));
        }
        return JsonValue::Object(fields);
    }
    JsonValue::Null
}

/// `keyboardShouldPersistTaps`: a boolean or `"never"` / `"always"` /
/// `"handled"`.
pub(crate) fn keyboard_taps<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
    Some(ScrollProp::KeyboardTaps(match input.as_bool() {
        Some(true) => KeyboardTaps::Always,
        Some(false) => KeyboardTaps::Never,
        None => match input.as_string().as_deref() {
            Some("always") => KeyboardTaps::Always,
            Some("handled") => KeyboardTaps::Handled,
            _ => KeyboardTaps::Never,
        },
    }))
}

/// A dialog's `supportedOrientations`: the orientation names.
pub(crate) fn orientations<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ModalProp> {
    Some(ModalProp::Orientations(orientation_bits(input)))
}

/// A page's `supportedOrientations`: the orientation names.
pub(crate) fn page_orientations<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScreenProp> {
    Some(ScreenProp::Orientations(orientation_bits(input)))
}

/// The [`ModalConfig::PORTRAIT`] bits of a list of orientation names; a
/// name it does not know adds none.
fn orientation_bits<I: HostInput>(input: &I) -> u8 {
    let mut bits = 0;
    for name in input.items() {
        bits |= match name.as_string().as_deref() {
            Some("portrait") => ModalConfig::PORTRAIT,
            Some("portrait-upside-down") => ModalConfig::PORTRAIT_UPSIDE_DOWN,
            Some("landscape") => ModalConfig::LANDSCAPE_LEFT | ModalConfig::LANDSCAPE_RIGHT,
            Some("landscape-left") => ModalConfig::LANDSCAPE_LEFT,
            Some("landscape-right") => ModalConfig::LANDSCAPE_RIGHT,
            _ => 0,
        };
    }
    bits
}

/// A shader's `uniforms`: `{ name: value }`, a value a number, a CSS color,
/// an animated value or a list of them; what is none of them is left out
/// with a warning.
impl HostValue for crate::shader::ShaderUniforms {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        let mut values = Vec::new();
        for (name, value) in input.entries() {
            match uniform_value(&value, 0) {
                Some(v) => values.push((name.as_str().into(), v)),
                None => cx.warn(format!(
                    "uniform `{name}`: a number, a color, an animated value or a list of them"
                )),
            }
        }
        Some(crate::shader::ShaderUniforms(values))
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let value = types.declare("ShaderUniform", |_| {
            "/** A value of a shader's uniform: a number (`f32`, `i32`, `u32`), a color\n \
             * (`vec3f` / `vec4f`, sRGB 0..1), an animated value, or a list of them (a\n \
             * vector's components, an `array<vec4f, N>`'s items). */\n\
             export type ShaderUniform = number | ColorValue | AnimatedNode | readonly ShaderUniform[];"
                .into()
        });
        format!("Record<string, {value}>")
    }
}

/// A page's or a dialog's `transitionShader`: `{ source, uniforms?,
/// duration? }`.
impl HostValue for crate::shader::NavShaderSpec {
    fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
        if !input.is_object() {
            return None;
        }
        let mut source = None;
        let mut uniforms = crate::shader::ShaderUniforms::default();
        let mut duration = None;
        for (name, value) in input.entries() {
            match name.as_str() {
                "source" => source = value.as_string(),
                "uniforms" => {
                    uniforms = crate::shader::ShaderUniforms::decode(&value, cx).unwrap_or_default()
                }
                "duration" => duration = value.as_number().map(|d| d as f32),
                _ => {}
            }
        }
        Some(crate::shader::NavShaderSpec {
            source: source?.as_str().into(),
            uniforms,
            duration,
        })
    }

    fn ts_type(types: &mut TsTypes) -> String {
        let uniforms = crate::shader::ShaderUniforms::ts_type(types);
        format!("{{ source: string; uniforms?: {uniforms}; duration?: number }}")
    }
}

/// An effect's `progress`: a number or an animated value.
impl HostValue for crate::shader::ShaderProgress {
    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
        if let Some(n) = input.as_number() {
            return Some(crate::shader::ShaderProgress::Number(
                crate::geometry::Percentage(n as f32),
            ));
        }
        input
            .animated_node()
            .map(crate::shader::ShaderProgress::Animated)
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "number | AnimatedNode".into()
    }
}

/// A transition's `value`: a string, a number or a boolean.
impl HostValue for crate::shader::TransitionKey {
    fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
        if let Some(b) = input.as_bool() {
            return Some(crate::shader::TransitionKey::Bool(b));
        }
        if let Some(n) = input.as_number() {
            return Some(crate::shader::TransitionKey::number(n));
        }
        input
            .as_string()
            .map(|s| crate::shader::TransitionKey::String(s.as_str().into()))
    }

    fn ts_type(_: &mut TsTypes) -> String {
        "string | number | boolean".into()
    }
}

fn uniform_value<I: HostInput>(input: &I, depth: u32) -> Option<crate::shader::UniformValue> {
    use crate::shader::UniformValue;
    if let Some(n) = input.as_number() {
        return Some(UniformValue::Number(n as f32));
    }
    if let Some(s) = input.as_string() {
        return crate::Color::parse(&s).map(UniformValue::Color);
    }
    if let Some(node) = input.animated_node() {
        return Some(UniformValue::Animated(node));
    }
    let list = input.as_list()?;
    // Vectors in arrays: two levels.
    if depth > 1 {
        return None;
    }
    (0..list.len())
        .map(|i| {
            list.item(i)
                .and_then(|item| uniform_value(&item, depth + 1))
        })
        .collect::<Option<Vec<_>>>()
        .map(UniformValue::List)
}