nsh-core 0.1.0

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
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
use std::sync::Arc;

use nsh_animation::AnimationOp;

use crate::{
    js::host::HostProps,
    props::{AccessibilityProp, EdgeInsets, LayoutAnimation, PointerEvents},
    style::{Color, EllipsizeMode, Style, StylePatch},
    ui::PropEnum,
};

/// Identifier of a node, assigned by the JS renderer.
///
/// Ids are small, dense and increasing, so the core indexes them directly.
pub type NodeId = u32;

/// Id of the surface root view. It exists before any JS runs.
pub const ROOT_ID: NodeId = 1;

/// Element tag of a host node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tag {
    /// A container view (`<view>`).
    View,
    /// A text block, or a span when nested in another text (`<text>`).
    Text,
    /// An image (`<image>`).
    Image,
    /// A scrolling container (`<scroll>`).
    Scroll,
    /// A virtualized list (`<list>`, created by the runtime's `List`).
    List,
    /// A recycled list cell (created by the runtime's `List`).
    Cell,
    /// A text field, or a text area when `multiline` (`<input>`).
    Input,
    /// A native navigation stack (`<stack>`); its children are screens.
    Stack,
    /// One screen of a stack (`<screen>`), laid out at the stack's size.
    Screen,
    /// A modal presented over everything (`<modal>`), laid out at the size
    /// the platform presents it at.
    Modal,
    /// A view placed in a screen's native header (`<headeritem slot>`),
    /// sized to its content.
    HeaderItem,
    /// A bar over the keyboard of the inputs naming its `nativeID`
    /// (`<inputaccessory>`, iOS), as wide as the window and as tall as its
    /// content.
    InputAccessory,
    /// A 2D drawing (`<canvas>`, filled by [`Op::Draw`]).
    Canvas,
    /// A web page (`<webview>`).
    WebView,
    /// A video player (`<video>`).
    Video,
    /// A component the embedding app registered (`<native component>`,
    /// created by `nsh/native`'s `nativeComponent`).
    Native,
}

impl Tag {
    /// Parses a host element's name (what `nsh:rt`'s `element` takes).
    #[inline]
    pub fn from_name(name: &str) -> Option<Tag> {
        Some(match name {
            "view" => Tag::View,
            "text" => Tag::Text,
            "image" => Tag::Image,
            "scroll" => Tag::Scroll,
            "list" => Tag::List,
            "cell" => Tag::Cell,
            "input" => Tag::Input,
            "stack" => Tag::Stack,
            "screen" => Tag::Screen,
            "modal" => Tag::Modal,
            "headeritem" => Tag::HeaderItem,
            "inputaccessory" => Tag::InputAccessory,
            "canvas" => Tag::Canvas,
            "webview" => Tag::WebView,
            "video" => Tag::Video,
            "native" => Tag::Native,
            _ => return None,
        })
    }
}

macro_rules! events {
    ($($variant:ident = $prop:literal: $doc:literal,)*) => {
        /// An event a node can listen to.
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        #[repr(u8)]
        pub enum EventKind {
            $(#[doc = $doc] $variant,)*
        }

        impl EventKind {
            /// Every kind, in discriminant order (`ALL[k as usize] == k`).
            pub const ALL: &'static [EventKind] = &[$(EventKind::$variant,)*];

            /// Parses an event prop name such as `onPress`.
            #[inline]
            pub fn from_prop(name: &str) -> Option<EventKind> {
                match name {
                    $($prop => Some(EventKind::$variant),)*
                    _ => None,
                }
            }

            /// The JS prop name of this event.
            #[inline]
            pub const fn prop_name(self) -> &'static str {
                match self {
                    $(EventKind::$variant => $prop,)*
                }
            }
        }
    };
}

// The order is part of the platform protocols (`encode.rs`, `Native.java`):
// append new kinds at the end.
events! {
    Press = "onPress": "A tap / click.",
    LongPress = "onLongPress": "A press held for about half a second.",
    PanStart = "onPanStart": "A drag started (payload: [`EventPayload::Pan`]).",
    PanEnd = "onPanEnd": "A drag ended (payload: [`EventPayload::Pan`] with velocity).",
    Refresh = "onRefresh": "Pull-to-refresh was triggered on a scroll or list.",
    EndReached = "onEndReached": "A list was scrolled close to its end.",
    ScrollEnd = "onScrollEnd": "Scrolling came to rest (payload: [`EventPayload::Scroll`]).",
    Load = "onLoad": "An image loaded (payload: [`EventPayload::Image`]).",
    Error = "onError": "An image failed to load (payload: [`EventPayload::Error`]).",
    ChangeText = "onChangeText": "The user edited an input (payload: [`EventPayload::Text`]).",
    SubmitEditing = "onSubmitEditing": "The return key was pressed in an input (payload: [`EventPayload::Text`]).",
    Focus = "onFocus": "An input became focused.",
    Blur = "onBlur": "An input lost focus.",
    PressIn = "onPressIn": "A finger went down on a pressable view.",
    PressOut = "onPressOut": "The press ended, inside or outside the view.",
    Layout = "onLayout": "The frame changed (payload: [`EventPayload::Layout`], relative to the parent).",
    PinchStart = "onPinchStart": "A pinch started (payload: `scale`, `velocity`).",
    PinchEnd = "onPinchEnd": "A pinch ended (payload: `scale`, `velocity`).",
    RotationStart = "onRotationStart": "A two-finger rotation started (payload: `rotation`, `velocity`).",
    RotationEnd = "onRotationEnd": "A two-finger rotation ended (payload: `rotation`, `velocity`).",
    AccessibilityAction = "onAccessibilityAction": "An assistive technology performed an action (payload: `actionName`).",
    Dismiss = "onDismiss": "A screen was popped or a modal dismissed by the user or the system.",
    RequestClose = "onRequestClose": "The user asked to close a modal (back button, swipe down).",
    Show = "onShow": "A modal finished appearing.",
    Insets = "onInsets": "The insets of a screen or modal changed (payload: `top`, `right`, `bottom`, `left`).",
    LoadStart = "onLoadStart": "A web view, video or image started loading.",
    Message = "onMessage": "A web page posted a message (payload: `data`).",
    NavigationStateChange = "onNavigationStateChange": "A web view navigated (payload: `url`, `title`, `loading`, `canGoBack`, `canGoForward`).",
    Progress = "onProgress": "Video playback progressed (payload: `currentTime`, `duration`).",
    End = "onEnd": "A video played to its end.",
    Buffer = "onBuffer": "A video started or stopped buffering (payload: `isBuffering`).",
    ViewableItemsChanged = "onViewableItemsChanged": "The range of visible list items changed (payload: `first`, `last`).",
    BackPress = "onBackPress": "The Android back button was pressed and nothing native handled it (root only).",
    Scroll = "onScroll": "A scroll view moved, at most once per frame (payload: `x`, `y`, `contentWidth`, `contentHeight`, `width`, `height`).",
    ScrollBeginDrag = "onScrollBeginDrag": "The user started dragging a scroll view (payload: [`EventPayload::Scroll`]).",
    ScrollEndDrag = "onScrollEndDrag": "The user let go of a scroll view (payload: [`EventPayload::Scroll`]).",
    MomentumScrollBegin = "onMomentumScrollBegin": "A scroll view started gliding after a fling (payload: [`EventPayload::Scroll`]).",
    MomentumScrollEnd = "onMomentumScrollEnd": "A scroll view stopped gliding (payload: [`EventPayload::Scroll`]).",
    Dialog = "onDialog": "An alert or action sheet closed (root only; payload: `id`, `index`, -1 when dismissed).",
    Touch = "onTouch": "Touches on the view or inside it, for the JS touch and responder handlers (payload: [`EventPayload::Touch`]).",
    SelectionChange = "onSelectionChange": "The selection (or caret) of an input moved (payload: `start`, `end` in UTF-16 units).",
    KeyPress = "onKeyPress": "A key was pressed in an input (payload: `key`: the character, `Backspace` or `Enter`).",
    LoadEnd = "onLoadEnd": "An image finished loading, or failed.",
    ImageInfo = "onImageInfo": "An `Image.getSize` / `Image.prefetch` request finished (root only; payload: `id`, `width` and `height` in pixels, or `error`).",
    TextLayout = "onTextLayout": "A text block was laid out (payload: [`EventPayload::TextLayout`]).",
    ContentSizeChange = "onContentSizeChange": "The size of an input's text changed (payload: `width`, `height`; raised by the core).",
    BackRequest = "onBackRequest": "The user tried to leave a screen with `preventBack` (back button, header back button).",
    NativeEvent = "onNativeEvent": "A registered native component emitted an event (payload: [`EventPayload::Native`]).",
    Clipboard = "onClipboard": "A clipboard read finished (root only; payload: `id`, `has`: whether it holds text, `text`: the text, unless only `has` was asked).",
    KeyCommand = "onKeyCommand": "A key matched a binding of `nsh/keymap` (root only; payload: the binding's id, [`crate::keymap::KeyBinding::id`]).",
    Menu = "onMenu": "A menu item was chosen: the application menu's or a context menu's (root only; desktops; payload: `id`), or a context menu closed (`closed`: true, after its item).",
    HoverIn = "onHoverIn": "The mouse came over the view or a view inside it (macOS, Linux and GPUI; never on touches).",
    HoverOut = "onHoverOut": "The mouse left the view and the views inside it, or the window (macOS, Linux and GPUI).",
}

/// What an input holds, for the system's autofill and suggestions
/// (`autoComplete`, `textContentType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AutoFill {
    /// The platform decides.
    #[default]
    Default,
    /// No autofill.
    Off,
    /// Account name.
    Username,
    /// Existing password.
    Password,
    /// A password being chosen.
    NewPassword,
    /// A code from a text message or e-mail.
    OneTimeCode,
    /// E-mail address.
    Email,
    /// Phone number.
    Tel,
    /// Full name.
    Name,
    /// First name.
    GivenName,
    /// Last name.
    FamilyName,
    /// Middle name.
    MiddleName,
    /// Nickname.
    Nickname,
    /// Company.
    Organization,
    /// Street address, all lines.
    StreetAddress,
    /// First address line.
    AddressLine1,
    /// Second address line.
    AddressLine2,
    /// City.
    City,
    /// State or region.
    Region,
    /// Postal code.
    PostalCode,
    /// Country.
    Country,
    /// Credit card number.
    CreditCardNumber,
    /// Credit card expiry date.
    CreditCardExpiration,
    /// Credit card security code.
    CreditCardSecurityCode,
    /// Name on the credit card.
    CreditCardName,
    /// Web address.
    Url,
    /// Birth date.
    Birthdate,
}

impl AutoFill {
    /// Parses React Native's `autoComplete` values and iOS's
    /// `textContentType` names.
    pub fn parse(name: &str) -> Option<Self> {
        Some(match name {
            "off" | "none" => Self::Off,
            "username" | "username-new" => Self::Username,
            "password" | "current-password" => Self::Password,
            "new-password" | "newPassword" | "password-new" => Self::NewPassword,
            "one-time-code" | "oneTimeCode" | "sms-otp" => Self::OneTimeCode,
            "email" | "emailAddress" => Self::Email,
            "tel" | "telephoneNumber" | "tel-national" | "tel-device" | "tel-country-code" => {
                Self::Tel
            }
            "name" | "name-full" => Self::Name,
            "given-name" | "givenName" | "name-given" => Self::GivenName,
            "family-name" | "familyName" | "name-family" => Self::FamilyName,
            "additional-name" | "middleName" | "name-middle" => Self::MiddleName,
            "nickname" => Self::Nickname,
            "organization" | "organizationName" => Self::Organization,
            "street-address" | "fullStreetAddress" | "postal-address" => Self::StreetAddress,
            "address-line1" | "streetAddressLine1" => Self::AddressLine1,
            "address-line2" | "streetAddressLine2" => Self::AddressLine2,
            "address-level2" | "addressCity" | "postal-address-locality" => Self::City,
            "address-level1" | "addressState" | "postal-address-region" => Self::Region,
            "postal-code" | "postalCode" => Self::PostalCode,
            "country" | "countryName" | "postal-address-country" => Self::Country,
            "cc-number" | "creditCardNumber" => Self::CreditCardNumber,
            "cc-exp" | "creditCardExpiration" | "cc-exp-month" | "cc-exp-year" => {
                Self::CreditCardExpiration
            }
            "cc-csc" | "creditCardSecurityCode" => Self::CreditCardSecurityCode,
            "cc-name" | "creditCardName" => Self::CreditCardName,
            "url" | "URL" => Self::Url,
            "birthdate-full" | "birthdate" | "birthdate-day" | "birthdate-month"
            | "birthdate-year" => Self::Birthdate,
            _ => return None,
        })
    }
}

/// The phase of a [`TouchEvent`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TouchPhase {
    /// Fingers went down (the changed points).
    Start,
    /// Fingers moved.
    Move,
    /// Fingers lifted (the changed points).
    End,
    /// The system or a native gesture took the touches over.
    Cancel,
}

/// One finger of a [`TouchEvent`], in points.
#[derive(Debug, Clone, PartialEq)]
pub struct TouchPoint {
    /// Identifies the finger while it is down.
    pub id: u32,
    /// The view under the finger when it went down.
    pub target: NodeId,
    /// The views around `target` (it included) that listen to touches,
    /// innermost first.
    pub path: Vec<NodeId>,
    /// Position in the surface.
    pub page_x: f32,
    /// Position in the surface.
    pub page_y: f32,
    /// Position in `target`.
    pub location_x: f32,
    /// Position in `target`.
    pub location_y: f32,
    /// This finger is one the event is about (it went down, moved or
    /// lifted).
    pub changed: bool,
}

/// Touches for the JS responder system.
#[derive(Debug, Clone, PartialEq)]
pub struct TouchEvent {
    /// What happened.
    pub phase: TouchPhase,
    /// Milliseconds since an arbitrary origin.
    pub timestamp: f64,
    /// The fingers down during the event (with those that lifted).
    pub points: Vec<TouchPoint>,
    /// A view around the fingers whose `panActivation` the platform
    /// activated with this event: it becomes the responder.
    pub activated: Option<NodeId>,
}

/// A set of [`EventKind`]s.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct EventMask(u64);

impl std::ops::BitOr for EventMask {
    type Output = EventMask;

    #[inline]
    fn bitor(self, other: EventMask) -> EventMask {
        EventMask(self.0 | other.0)
    }
}

impl EventMask {
    /// Returns true if `event` is in the set.
    #[inline]
    pub const fn contains(self, event: EventKind) -> bool {
        self.0 & (1 << event as u8) != 0
    }

    /// The raw bit set, indexed by `EventKind as u8`.
    #[inline]
    pub const fn bits(self) -> u64 {
        self.0
    }

    /// Adds or removes `event`.
    #[inline]
    pub fn set(&mut self, event: EventKind, enabled: bool) {
        if enabled {
            self.0 |= 1 << event as u8;
        } else {
            self.0 &= !(1 << event as u8);
        }
    }

    /// Returns true if no event is set.
    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

/// A value in an event payload.
#[derive(Debug, Clone, PartialEq)]
pub enum PayloadValue {
    /// A number.
    Number(f64),
    /// A boolean.
    Bool(bool),
    /// A string.
    Str(String),
    /// `null`.
    Null,
}

/// Data delivered with an event.
#[derive(Debug, Clone, PartialEq)]
pub enum EventPayload {
    /// No data.
    None,
    /// A single value handed to the handler as is (`onValueChange(value)`).
    Value(PayloadValue),
    /// An object with named fields.
    Map(Vec<(&'static str, PayloadValue)>),
    /// A frame relative to the parent (`onLayout`).
    Layout {
        /// Left edge.
        x: f32,
        /// Top edge.
        y: f32,
        /// Width.
        width: f32,
        /// Height.
        height: f32,
    },
    /// A drag: translation since the start and velocity (points / second).
    Pan {
        /// Horizontal translation.
        translation_x: f32,
        /// Vertical translation.
        translation_y: f32,
        /// Horizontal velocity.
        velocity_x: f32,
        /// Vertical velocity.
        velocity_y: f32,
        /// The `pan.x` value now (`None` without one).
        value_x: Option<f32>,
        /// The `pan.y` value now.
        value_y: Option<f32>,
    },
    /// A scroll position.
    Scroll {
        /// Horizontal content offset.
        x: f32,
        /// Vertical content offset.
        y: f32,
    },
    /// A loaded image's source size in pixels (before downsampling).
    Image {
        /// Width.
        width: f32,
        /// Height.
        height: f32,
    },
    /// An error message.
    Error {
        /// The message.
        message: String,
    },
    /// The text of an input after an edit.
    Text {
        /// The whole text.
        text: String,
        /// Number of edits the input has reported so far. A value set by JS
        /// based on an older edit is stale and must not overwrite newer
        /// typing.
        count: u32,
    },
    /// Touches (`onTouch`).
    Touch(Box<TouchEvent>),
    /// The lines of a text block.
    TextLayout(Vec<crate::text::TextLine>),
    /// An event of a registered native component: its name and data (any
    /// JSON value), handed to JS as `{ name, data }`.
    Native {
        /// The event (`regionChange`).
        name: Arc<str>,
        /// Its data.
        data: crate::JsonValue,
    },
}

impl TouchEvent {
    /// Folds a later move into this pending one: the later positions,
    /// changed if either moved them, and either's activated pan.
    pub fn merge_move(&mut self, later: TouchEvent) {
        let mut later = later;
        for p in &mut later.points {
            if let Some(old) = self.points.iter().find(|o| o.id == p.id) {
                p.changed |= old.changed;
            }
        }
        later.activated = later.activated.or(self.activated);
        *self = later;
    }
}

/// How an image fits its box.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum ResizeMode {
    /// Fill the box, cropping (default).
    #[default]
    Cover,
    /// Fit inside the box, letterboxing.
    Contain,
    /// Stretch to the box.
    Stretch,
    /// Center at natural size.
    Center,
}

/// An image source.
#[derive(Debug, Clone, PartialEq)]
pub struct ImageSource {
    /// `https://…`, `asset:/path` (bundled file) or a file path.
    pub uri: Arc<str>,
    /// Natural size in points, when known up front (bundled assets): used
    /// as the intrinsic layout size.
    pub size: Option<(f32, f32)>,
}

/// Keyboard layout of an input (`keyboardType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum KeyboardType {
    /// Full keyboard.
    #[default]
    Default,
    /// Digits only (`number-pad`): no sign, no decimal separator.
    #[prop(rename = "number-pad")]
    Number,
    /// Digits and a decimal separator (`decimal-pad`).
    #[prop(rename = "decimal-pad")]
    Decimal,
    /// Numbers (`numeric`, React Native's): iOS's decimal pad, Android's
    /// number keyboard with a sign and a decimal separator.
    Numeric,
    /// Digits, a sign and punctuation (`numbers-and-punctuation`): iOS's
    /// numbers and punctuation keyboard, Android's signed decimal number
    /// keyboard (the closest it has).
    #[prop(rename = "numbers-and-punctuation")]
    NumbersAndPunctuation,
    /// E-mail addresses (`email-address`).
    #[prop(rename = "email-address")]
    Email,
    /// Phone numbers (`phone-pad`).
    #[prop(rename = "phone-pad")]
    Phone,
    /// URLs (`url`).
    Url,
}

/// The keyboard's look (`keyboardAppearance`, iOS).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum KeyboardAppearance {
    /// The system's: follows the app's appearance (default).
    #[default]
    Default,
    /// Light.
    Light,
    /// Dark.
    Dark,
}

/// Label of the return key (`returnKeyType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum ReturnKeyType {
    /// Return / new line.
    #[default]
    Default,
    /// Done.
    Done,
    /// Go.
    Go,
    /// Next.
    Next,
    /// Search.
    Search,
    /// Send.
    Send,
}

/// What return does in an input (`submitBehavior`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum SubmitBehavior {
    /// Reports `onSubmitEditing` and keeps the focus.
    Submit,
    /// Reports `onSubmitEditing` and unfocuses the input.
    #[default]
    BlurAndSubmit,
    /// Inserts a line break (multiline inputs; a single line submits).
    Newline,
}

/// Automatic capitalization (`autoCapitalize`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum AutoCapitalize {
    /// Never.
    None,
    /// First letter of each sentence (default).
    #[default]
    Sentences,
    /// First letter of each word.
    Words,
    /// Every letter.
    Characters,
}

/// When a scroll view dismisses the keyboard (`keyboardDismissMode`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum KeyboardDismissMode {
    /// Never (default).
    #[default]
    None,
    /// As soon as a drag starts.
    #[prop(rename = "on-drag")]
    OnDrag,
    /// Follows the finger while dragging down (iOS).
    Interactive,
}

/// Which point of a page a snapping scroll view aligns to its start.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum SnapAlignment {
    /// The snap point at the viewport's start.
    #[default]
    Start,
    /// At its center.
    Center,
    /// At its end.
    End,
}

/// Whether a tap in a scroll view dismisses the keyboard
/// (`keyboardShouldPersistTaps`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum KeyboardTaps {
    /// The tap dismisses the keyboard and reaches nothing else (default).
    #[default]
    Never,
    /// Taps never dismiss the keyboard.
    Always,
    /// Taps that nothing handles dismiss the keyboard.
    Handled,
}

/// How an `<image>` is shown, besides its source.
#[derive(Debug, Clone, PartialEq, HostProps)]
pub enum ImageProp {
    /// `defaultSource`: shown until `src` has loaded (best a local asset).
    #[prop(js = "defaultSource", on = IMAGE)]
    DefaultSource(Option<ImageSource>),
    /// `blurRadius`: blurs the image by this radius in points (decoded once, off
    /// the main thread).
    #[prop(js = "blurRadius", on = IMAGE)]
    BlurRadius(f32),
    /// `fadeDuration`: how long a loaded image fades in, in milliseconds
    /// (default: the platform's, 0 on iOS and 300 on Android, like React
    /// Native).
    #[prop(js = "fadeDuration", min = 0, on = IMAGE)]
    FadeDuration(Option<f32>),
}

/// A behavior property of a scroll view or list.
#[derive(Debug, Clone, PartialEq, HostProps)]
pub enum ScrollProp {
    /// `pagingEnabled`: stops at multiples of the viewport.
    #[prop(js = "pagingEnabled", on = SCROLLING)]
    Paging(bool),
    /// `snapToInterval`: stops at multiples of this length (0: off).
    #[prop(js = "snapToInterval", on = SCROLLING)]
    SnapInterval(f32),
    /// `snapToOffsets`: stops at these offsets.
    #[prop(js = "snapToOffsets", on = SCROLLING)]
    SnapOffsets(Vec<f32>),
    /// `snapToAlignment`: which point of an item aligns with the viewport with
    /// `snapToInterval`.
    #[prop(js = "snapToAlignment", on = SCROLLING)]
    SnapAlignment(SnapAlignment),
    /// `decelerationRate`: how fast a fling slows down: `"normal"`, `"fast"`, or
    /// the velocity kept per millisecond (0.998 / 0.99; 0 is the platform's
    /// default).
    #[prop(js = "decelerationRate", with = crate::js::host_values::deceleration, reset = ScrollProp::Deceleration(0.0), ts = "\"normal\" | \"fast\" | number", on = SCROLLING)]
    Deceleration(f32),
    /// `bounces`: overscroll past the edges (default true).
    #[prop(js = "bounces", default = true, on = SCROLLING)]
    Bounces(bool),
    /// `contentInset`: room around the content.
    #[prop(js = "contentInset", on = SCROLLING)]
    ContentInset(EdgeInsets),
    /// `contentOffset`: where it starts.
    #[prop(js = "contentOffset", with = crate::js::host_values::content_offset, once, ts = "{ x?: number; y?: number }", on = SCROLLING)]
    ContentOffset(f32, f32),
    /// `keyboardShouldPersistTaps`: whether a tap dismisses the keyboard: `"never"`
    /// (default: the tap only dismisses it), `"always"` (never dismisses),
    /// `"handled"` (unless something handles the tap).
    #[prop(js = "keyboardShouldPersistTaps", with = crate::js::host_values::keyboard_taps, reset = ScrollProp::KeyboardTaps(KeyboardTaps::Never), ts = "\"never\" | \"always\" | \"handled\" | boolean", on = SCROLLING)]
    KeyboardTaps(KeyboardTaps),
    /// `scrollEventThrottle`: minimum milliseconds between `onScroll` events (at
    /// most one per frame anyway).
    #[prop(js = "scrollEventThrottle", on = SCROLLING)]
    EventThrottle(f32),
    /// `disableIntervalMomentum`: a fling moves one snap point at most.
    #[prop(js = "disableIntervalMomentum", on = SCROLLING)]
    DisableIntervalMomentum(bool),
    /// `minimumZoomScale`: the smallest zoom (default 1).
    #[prop(js = "minimumZoomScale", default = 1.0, on = SCROLL)]
    MinZoom(f32),
    /// `maximumZoomScale`: pinching zooms the content when it is above
    /// `minimumZoomScale` (default 1 both); zoomed in, it scrolls both ways.
    #[prop(js = "maximumZoomScale", default = 1.0, on = SCROLL)]
    MaxZoom(f32),
    /// `zoomScale`: zooms to this scale when it changes (the user's zoom is kept
    /// otherwise).
    #[prop(js = "zoomScale", default = 1.0, on = SCROLL)]
    Zoom(f32),
    /// `bouncesZoom`: pinching may go past the limits and springs back (default
    /// true).
    #[prop(js = "bouncesZoom", default = true, on = SCROLL)]
    BouncesZoom(bool),
    /// `pinchGestureEnabled`: the user can pinch to zoom (default true).
    #[prop(js = "pinchGestureEnabled", default = true, on = SCROLL)]
    Pinch(bool),
    /// `centerContent`: content smaller than the viewport (zoomed out) is centered.
    #[prop(js = "centerContent", on = SCROLL)]
    CenterContent(bool),
}

/// What a list cell holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CellSlot {
    /// A recycled item cell in this slot.
    Item(u32),
    /// `ListHeaderComponent`.
    Header,
    /// `ListFooterComponent`.
    Footer,
    /// `ListEmptyComponent` (shown while there are no items).
    Empty,
}

/// A list's `contentContainerStyle`: padding around the content and gaps
/// between rows and columns.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ListContentStyle {
    /// Padding around the content.
    pub padding: EdgeInsets,
    /// Gap between rows (vertical lists) / columns (horizontal lists).
    pub row_gap: f32,
    /// Gap between columns (`numColumns`) of vertical lists.
    pub column_gap: f32,
}

/// When list items count as viewable (React Native's `viewabilityConfig`).
/// Without thresholds, any visible pixel does.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Viewability {
    /// Percent of the viewport an item must cover.
    pub view_area_percent: Option<f32>,
    /// Percent of an item that must be visible.
    pub item_visible_percent: Option<f32>,
}

/// Where a header item goes (`<headeritem slot>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum HeaderSlot {
    /// Leading, after the back button.
    #[default]
    Left,
    /// Trailing.
    Right,
    /// Replaces the title.
    Title,
}

/// How a screen enters and leaves (`animation`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum ScreenAnimation {
    /// The platform's push / pop transition.
    #[default]
    Default,
    /// Cross-fade.
    Fade,
    /// No animation.
    None,
}

/// A screen option (`<screen title headerShown ...>`).
#[derive(Debug, Clone, PartialEq, HostProps)]
pub enum ScreenProp {
    /// `title`: the header's title.
    #[prop(js = "title", on = SCREEN)]
    Title(Option<Arc<str>>),
    /// `headerShown`: the header shows (default true).
    #[prop(js = "headerShown", default = true, on = SCREEN)]
    HeaderShown(bool),
    /// `headerLargeTitle` (iOS, desktop): a large title; the content scrolls under
    /// the header.
    #[prop(ios = "headerLargeTitle", desktop = "headerLargeTitle", on = SCREEN)]
    HeaderLargeTitle(bool),
    /// `headerTransparent`: the content extends under the header.
    #[prop(js = "headerTransparent", on = SCREEN)]
    HeaderTransparent(bool),
    /// `headerTintColor`: the back button and bar buttons.
    #[prop(js = "headerTintColor", on = SCREEN)]
    HeaderTintColor(Option<Color>),
    /// `headerBackgroundColor`.
    #[prop(js = "headerBackgroundColor", on = SCREEN)]
    HeaderBackgroundColor(Option<Color>),
    /// `headerTitleColor`.
    #[prop(js = "headerTitleColor", on = SCREEN)]
    HeaderTitleColor(Option<Color>),
    /// `headerBackTitle` (iOS, desktop): the label of the back button leading back
    /// to this screen.
    #[prop(ios = "headerBackTitle", desktop = "headerBackTitle", on = SCREEN)]
    HeaderBackTitle(Option<Arc<str>>),
    /// `headerBackVisible`: the back button shows (default true).
    #[prop(js = "headerBackVisible", default = true, on = SCREEN)]
    HeaderBackVisible(bool),
    /// `gestureEnabled`: the interactive back gesture (iOS swipe back, Android
    /// predictive back following the finger); the back buttons pop either way
    /// (default true).
    #[prop(js = "gestureEnabled", default = true, on = SCREEN)]
    GestureEnabled(bool),
    /// `preventBack`: the user cannot leave the screen: no swipe back, and the back
    /// buttons (header, Android back) call `onBackRequest` instead of popping, e.g.
    /// to confirm discarding changes and then `pop()`. Decided natively when the
    /// system asks, so set it before the user acts.
    #[prop(js = "preventBack", on = SCREEN)]
    PreventBack(bool),
    /// `animation`: how the screen enters and leaves.
    #[prop(js = "animation", on = SCREEN)]
    Animation(ScreenAnimation),
}

/// How a modal appears (`animationType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum ModalAnimation {
    /// Slides up from the bottom (default).
    #[default]
    Slide,
    /// Fades in.
    Fade,
    /// Appears at once.
    None,
}

/// How a modal covers the screen (`presentationStyle`, iOS and desktop).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub enum ModalPresentation {
    /// Covers the whole screen (default).
    #[default]
    FullScreen,
    /// A sheet that leaves the presenting content visible behind it.
    PageSheet,
    /// A smaller centered sheet on large screens.
    FormSheet,
}

/// A modal option.
#[derive(Debug, Clone, Copy, PartialEq, HostProps)]
pub enum ModalProp {
    /// `animationType`: how the modal appears.
    #[prop(js = "animationType", on = MODAL)]
    Animation(ModalAnimation),
    /// `presentationStyle` (iOS, desktop): `"pageSheet"` / `"formSheet"` keep what is
    /// behind visible (on a desktop: a card centered in the window).
    #[prop(ios = "presentationStyle", desktop = "presentationStyle", on = MODAL)]
    Presentation(ModalPresentation),
    /// `transparent`: the background shows what is behind.
    #[prop(js = "transparent", on = MODAL)]
    Transparent(bool),
    /// `statusBarTranslucent` (Android): the content reaches under the status bar
    /// (default: it starts below).
    #[prop(android = "statusBarTranslucent", on = MODAL)]
    StatusBarTranslucent(bool),
    /// `supportedOrientations` (iOS): the orientations it allows (default: the
    /// presenter's).
    ///
    /// [`crate::ModalConfig::PORTRAIT`] bits.
    #[prop(ios = "supportedOrientations", with = crate::js::host_values::orientations, reset = ModalProp::Orientations(0), ts = "(\"portrait\" | \"portrait-upside-down\" | \"landscape\" | \"landscape-left\" | \"landscape-right\")[]", on = MODAL)]
    Orientations(u8),
    /// `dismissible`: the user closes it natively (iOS sheet swiped down, Android
    /// back button), then `onRequestClose` and `onDismiss` follow. Without it
    /// (default) those only ask to close.
    #[prop(js = "dismissible", on = MODAL)]
    Dismissible(bool),
}

/// An imperative call on a native view (`ref.focus()` and the like).
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    /// Focus an input (show the keyboard).
    Focus,
    /// Unfocus an input; on the root view, unfocus whatever is focused.
    Blur,
    /// Scroll a scroll view to an offset.
    ScrollTo {
        /// Horizontal offset.
        x: f32,
        /// Vertical offset.
        y: f32,
        /// Animate the change.
        animated: bool,
    },
    /// Animate the layout changes of the next commit (on the root).
    LayoutAnimation(LayoutAnimation),
    /// Leave the app (Android back handling; on the root).
    ExitApp,
    /// What the back button does when none of the app's listeners took
    /// it: the innermost stack pops (or asks, with `preventBack`); with
    /// none, the app leaves on Android (on the root).
    Back,
    /// Reload a web view.
    Reload,
    /// Go back in a web view's history.
    GoBack,
    /// Go forward in a web view's history.
    GoForward,
    /// Stop loading a web view.
    StopLoading,
    /// Run JavaScript in a web view's page.
    InjectJavaScript(String),
    /// Send a message to a web view's page (`window.onmessage` data).
    PostMessage(String),
    /// Seek a video to a time in seconds.
    Seek(f64),
    /// Scroll a list to an item (resolved by the core into `ScrollTo`).
    ScrollToIndex {
        /// The item.
        index: u32,
        /// Animate the change.
        animated: bool,
        /// Where the item ends up: 0 at the start of the viewport, 1 at the
        /// end, 0.5 in the middle.
        view_position: f32,
        /// Extra distance from that position.
        view_offset: f32,
    },
    /// Zoom a zoomable scroll view to `scale`, with the content point
    /// (`x`, `y`) (points, unzoomed) in the middle of the viewport, or
    /// around the viewport's middle.
    ZoomTo {
        /// The zoom scale (clamped to the view's limits).
        scale: f32,
        /// The content point to center.
        center: Option<(f32, f32)>,
        /// Animate the change.
        animated: bool,
    },
    /// Scroll a list to the end of its content.
    ScrollToEnd {
        /// Animate the change.
        animated: bool,
    },
    /// Set the status bar (on the root): what the platform shows.
    StatusBar(StatusBarConfig),
    /// Change what functions set for the status bar (on the root): the
    /// core merges it under the settings components render and sends
    /// [`Command::StatusBar`] when the result changes.
    SetStatusBar(StatusBarSetting),
    /// Show an alert or action sheet (on the root); the answer comes back
    /// as [`EventKind::Dialog`].
    Dialog(Box<Dialog>),
    /// A JS responder took the touches on this view: `block` keeps native
    /// scroll views around it from taking them over.
    SetJsResponder {
        /// Block native scrolling.
        block: bool,
    },
    /// The JS responder let go (on the root).
    ClearJsResponder,
    /// Select a range of an input (UTF-16 units; equal for a caret).
    SetSelection {
        /// Start.
        start: u32,
        /// End.
        end: u32,
    },
    /// Show a short message (Android toast; on the root).
    Toast {
        /// The message.
        text: String,
        /// Show it longer.
        long: bool,
    },
    /// Have the screen reader read a message (on the root).
    Announce(String),
    /// Load the image at `uri` (keeping its bytes for views that show it
    /// next) and report its pixel size as [`EventKind::ImageInfo`] `id`
    /// (on the root).
    ImageInfo {
        /// The request.
        id: u32,
        /// URL or `asset:/` URI.
        uri: String,
    },
    /// Move the screen reader's focus to this view.
    AccessibilityFocus,
    /// Measure the view with this commit's layout (`ref.measure()`):
    /// answered by the core as a `$return` event on the root for call
    /// `call` ([`crate::Measurement`] as JSON, or null when the view is not
    /// laid out); never mounted.
    Measure {
        /// The call to answer.
        call: u32,
    },
    /// Put `text` on the system clipboard (on the root; `Clipboard.setString`).
    SetClipboard(String),
    /// Read the system clipboard and report it as [`EventKind::Clipboard`]
    /// `id` (on the root): `has` and, unless `has_only`, `text`. Asking
    /// only whether it holds text does not read it (no iOS paste notice).
    ReadClipboard {
        /// The request.
        id: u32,
        /// Only whether it holds text (`Clipboard.hasString`).
        has_only: bool,
    },
    /// A desktop command (on the root; `nsh/desktop`): the window, its
    /// title bar, menus. Mobile platforms ignore it.
    Desktop(Box<crate::desktop::DesktopCommand>),
    /// A call on a registered native component (`ref.command(name, args)`).
    Native {
        /// The command.
        name: Arc<str>,
        /// Its arguments (any JSON value).
        args: crate::JsonValue,
    },
}

/// The children's opacity while an underlay shows, by default.
pub const UNDERLAY_OPACITY: f32 = 0.85;

/// The status bar's look.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StatusBarStyle {
    /// The platform's default for the appearance.
    #[default]
    Default,
    /// Light content (for dark backgrounds).
    Light,
    /// Dark content (for light backgrounds).
    Dark,
}

/// The status bar (React Native's `StatusBar`).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct StatusBarConfig {
    /// Content color.
    pub style: StatusBarStyle,
    /// Hidden.
    pub hidden: bool,
    /// Animate the change.
    pub animated: bool,
    /// Background (Android before edge-to-edge only).
    pub background: Option<Color>,
}

/// A status bar setting: what it sets; the fields it leaves out keep the
/// settings below it.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct StatusBarSetting {
    /// Content color.
    pub style: Option<StatusBarStyle>,
    /// Hidden.
    pub hidden: Option<bool>,
    /// Animate the change.
    pub animated: Option<bool>,
    /// Background (Android before edge-to-edge only).
    pub background: Option<Color>,
}

impl StatusBarSetting {
    /// This setting over `below`.
    pub fn over(self, below: Self) -> Self {
        Self {
            style: self.style.or(below.style),
            hidden: self.hidden.or(below.hidden),
            animated: self.animated.or(below.animated),
            background: self.background.or(below.background),
        }
    }
}

/// How a dialog button looks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DialogButtonStyle {
    /// A regular button.
    #[default]
    Default,
    /// The cancel button.
    Cancel,
    /// A destructive action.
    Destructive,
}

/// A dialog button.
#[derive(Debug, Clone, PartialEq)]
pub struct DialogButton {
    /// Label.
    pub text: String,
    /// Look.
    pub style: DialogButtonStyle,
}

/// An alert, or with `sheet` an action sheet.
#[derive(Debug, Clone, PartialEq)]
pub struct Dialog {
    /// Echoed in the answer.
    pub id: u32,
    /// Title.
    pub title: Option<String>,
    /// Message.
    pub message: Option<String>,
    /// Buttons, or the sheet's options.
    pub buttons: Vec<DialogButton>,
    /// Tapping outside (or the back button) dismisses it.
    pub cancelable: bool,
    /// An action sheet rather than an alert.
    pub sheet: bool,
}

/// A non-style property of a host node.
#[derive(Debug, Clone, PartialEq, HostProps)]
pub enum Prop {
    /// `component`: which registered native component a `<native>`
    /// element is (set once, before it is mounted).
    #[prop(js = "component", internal)]
    Component(Arc<str>),
    /// `componentSlot`: this view holds the JSX a Rust component's host got
    /// for slot `name` (created by the generated glue).
    #[prop(js = "componentSlot", internal)]
    ComponentSlot(Arc<str>),
    /// A property of a registered native component (`$name` from JS):
    /// any JSON value, `None` to remove it.
    ComponentProp(Arc<str>, Option<crate::JsonValue>),
    /// `src`: a URL, `asset:/path`, or an imported asset.
    #[prop(js = "src", on = IMAGE)]
    Source(Option<ImageSource>),
    /// `resizeMode`: how an image (or a video) fits its box.
    #[prop(js = "resizeMode", on = IMAGE | VIDEO)]
    ResizeMode(ResizeMode),
    /// `horizontal`: scrolls sideways.
    #[prop(js = "horizontal", on = SCROLL | LIST)]
    Horizontal(bool),
    /// Scrolling behavior of a scroll view or list.
    #[prop(nested)]
    Scroll(ScrollProp),
    /// `showsIndicator`: the scroll indicator shows (default true).
    #[prop(js = "showsIndicator", default = true, on = SCROLL | LIST)]
    ShowsIndicator(bool),
    /// `refreshing`: the pull-to-refresh spinner shows.
    #[prop(js = "refreshing", on = SCROLL | LIST)]
    Refreshing(bool),
    /// Number of items of a list.
    #[prop(js = "count", internal)]
    Count(u32),
    /// `estimatedItemSize`: the size of items not measured yet, in points (default
    /// 50).
    #[prop(js = "estimatedItemSize", default = 50.0, on = LIST)]
    EstimatedItemSize(f32),
    /// The recycling slot (or the role) of a list cell, set once by the
    /// runtime.
    #[prop(js = "slot", with = crate::js::host_values::slot, internal)]
    Slot(CellSlot),
    /// `numColumns`: items per row (vertical lists).
    #[prop(js = "numColumns", default = 1, min = 1, on = LIST)]
    Columns(u32),
    /// The items of a list changed: `removed` at `at` became `inserted`
    /// (precedes the new `Count`).
    #[prop(js = "splice", with = crate::js::host_values::splice, internal)]
    Splice(u32, u32, u32),
    /// `inverted`: laid out from the end, item 0 last (chat style); starts scrolled
    /// to the end and keeps its distance from the end as content changes.
    #[prop(js = "inverted", on = LIST)]
    Inverted(bool),
    /// `maintainVisibleContentPosition`: with `autoscrollToBottomThreshold`, a list
    /// (not inverted) at the end of its content, or within that many points of it,
    /// stays at the end as the content grows or the viewport shrinks (a reply
    /// streaming into its last item); scrolled further up, it keeps the visible
    /// content where it is. Items inserted above the visible ones never move them.
    #[prop(js = "maintainVisibleContentPosition", with = crate::js::host_values::visible_content, reset = Prop::FollowEnd(None), ts = "{ autoscrollToBottomThreshold?: number }", on = LIST)]
    FollowEnd(Option<f32>),
    /// `stickyHeaderIndices`: items that stick to the start while scrolled past
    /// (one column, not inverted).
    #[prop(js = "stickyHeaderIndices", with = crate::js::host_values::sticky, reset = Prop::StickyIndices(Vec::new()), on = LIST)]
    StickyIndices(Vec<u32>),
    /// `contentContainerStyle`: padding and gaps of the content.
    #[prop(js = "contentContainerStyle", on = LIST)]
    ListContent(ListContentStyle),
    /// `viewabilityConfig`: when items count as viewable.
    #[prop(js = "viewabilityConfig", on = LIST)]
    Viewability(Viewability),
    /// How close to the end `onEndReached` fires, in viewports.
    #[prop(js = "endReachedThreshold", default = 1.0, internal)]
    EndReachedThreshold(f32),
    /// The item index a list cell now renders (set by the runtime after
    /// each bind, in the same batch as the cell's new content).
    #[prop(js = "cellIndex", internal)]
    CellIndex(u32),
    /// `scrollValue`: a native value fed with the scroll offset (main axis), for
    /// scroll-linked effects.
    #[prop(js = "scrollValue", with = crate::js::host_values::scroll_value, reset = Prop::ScrollValue(None), ts = "NativeValue", on = SCROLL | LIST)]
    ScrollValue(Option<nsh_animation::NodeId>),
    /// `pan`: drags drive these native values (points) on the UI thread.
    #[prop(js = "pan", with = crate::js::host_values::pan, reset = Prop::PanValues(None, None), ts = "{ x?: NativeValue; y?: NativeValue }")]
    PanValues(Option<nsh_animation::NodeId>, Option<nsh_animation::NodeId>),
    /// `numberOfLines`: the most lines shown; 0 (default) is unlimited.
    #[prop(js = "numberOfLines", on = TEXT)]
    NumberOfLines(u32),
    /// `ellipsizeMode`: where text that does not fit `numberOfLines` is cut.
    #[prop(js = "ellipsizeMode", on = TEXT)]
    EllipsizeMode(EllipsizeMode),
    /// `value`: the text, controlled by JS.
    #[prop(js = "value", on = INPUT)]
    Value(String),
    /// `defaultValue`: the initial text.
    #[prop(js = "defaultValue", once, on = INPUT)]
    DefaultValue(String),
    /// `placeholder`: shown while the input is empty.
    #[prop(js = "placeholder", on = INPUT)]
    Placeholder(String),
    /// `placeholderTextColor`.
    #[prop(js = "placeholderTextColor", on = INPUT)]
    PlaceholderColor(Option<Color>),
    /// `secureTextEntry`: the text is hidden (passwords).
    #[prop(js = "secureTextEntry", on = INPUT)]
    Secure(bool),
    /// `keyboardType`: the keyboard layout.
    #[prop(js = "keyboardType", on = INPUT)]
    KeyboardType(KeyboardType),
    /// `keyboardAppearance` (iOS): the keyboard's light or dark look;
    /// Android's keyboards follow the system's theme.
    #[prop(ios = "keyboardAppearance", on = INPUT)]
    KeyboardAppearance(KeyboardAppearance),
    /// `returnKeyType`: the label of the return key.
    #[prop(js = "returnKeyType", on = INPUT)]
    ReturnKeyType(ReturnKeyType),
    /// `autoCapitalize`: automatic capitalization (default `"sentences"`).
    #[prop(js = "autoCapitalize", on = INPUT)]
    AutoCapitalize(AutoCapitalize),
    /// `autoCorrect`: the system's corrections (default true).
    #[prop(js = "autoCorrect", default = true, on = INPUT)]
    AutoCorrect(bool),
    /// `multiline`: several lines; return inserts a line break.
    #[prop(js = "multiline", on = INPUT)]
    Multiline(bool),
    /// `maxLength`: the most characters the user can enter.
    #[prop(js = "maxLength", on = INPUT)]
    MaxLength(Option<u32>),
    /// `editable`: the user can change the text (default true).
    #[prop(js = "editable", default = true, on = INPUT)]
    Editable(bool),
    /// `blurOnSubmit`: return unfocuses a single-line input (default true); false
    /// keeps the keyboard up, e.g. to send several messages. `submitBehavior`
    /// wins over it.
    #[prop(js = "blurOnSubmit", default = true, on = INPUT)]
    BlurOnSubmit(bool),
    /// `submitBehavior`: what return does: `"submit"` (reports
    /// `onSubmitEditing`, keeps the focus), `"blurAndSubmit"` (also
    /// unfocuses), `"newline"` (inserts a line break; multiline inputs
    /// only). Default: `"blurAndSubmit"` for one line, `"newline"` for
    /// several. A multiline input that submits still takes line breaks
    /// from Shift+Return or Option / Alt+Return on desktops.
    #[prop(js = "submitBehavior", on = INPUT)]
    SubmitBehavior(Option<SubmitBehavior>),
    /// `autoFocus`: focused when it appears.
    #[prop(js = "autoFocus", on = INPUT)]
    AutoFocus(bool),
    /// `caretHidden`: no caret is drawn.
    #[prop(js = "caretHidden", on = INPUT)]
    CaretHidden(bool),
    /// `inputAccessoryViewID`: the `nativeID` of an `InputAccessoryView`
    /// (`nsh/ios`) shown over the keyboard while the input has focus.
    #[prop(ios = "inputAccessoryViewID", on = INPUT)]
    InputAccessoryViewId(Option<Box<str>>),
    /// `nativeID`: names the view for others (an input accessory's for
    /// `inputAccessoryViewID`).
    #[prop(js = "nativeID")]
    NativeId(Option<Box<str>>),
    /// `selectionColor`: an input's caret and selection, the highlight of a
    /// `selectable` text's selection.
    #[prop(js = "selectionColor", on = INPUT | TEXT)]
    SelectionColor(Option<Color>),
    /// `autoComplete` (iOS: also `textContentType`): what an input holds, for
    /// autofill (React Native's values, e.g. "username", "current-password",
    /// "new-password", "one-time-code", "email", "tel", "postal-code", "cc-number",
    /// "off").
    #[prop(js = "autoComplete", ios = "textContentType", on = INPUT)]
    AutoFill(AutoFill),
    /// `selection`: the controlled selection (UTF-16 units; `end` defaults to
    /// `start`, a caret).
    #[prop(js = "selection", with = crate::js::host_values::selection, once, ts = "{ start: number; end?: number }", on = INPUT)]
    Selection(u32, u32),
    /// `keyboardDismissMode`: whether dragging dismisses the keyboard.
    #[prop(js = "keyboardDismissMode", on = SCROLL | LIST)]
    KeyboardDismissMode(KeyboardDismissMode),
    /// `pointerEvents`: touch handling of the view and its children (React Native
    /// semantics).
    #[prop(js = "pointerEvents")]
    PointerEvents(PointerEvents),
    /// `hitSlop`: extends the touch area beyond the bounds.
    #[prop(js = "hitSlop", with = crate::js::host_values::hit_slop, reset = Prop::HitSlop(EdgeInsets::default()), ts = "number | { top?: number; right?: number; bottom?: number; left?: number }")]
    HitSlop(EdgeInsets),
    /// `panActivation`: the view's touch responder waits for a pan that the
    /// platform activates past an offset on one axis (and fails past one on
    /// the other), deciding on the main thread so the scroll views around
    /// it keep the touches until then.
    #[prop(js = "panActivation")]
    PanActivation(Option<crate::props::PanActivation>),
    /// `activeOpacity`: the opacity while pressed (native, no JS round trip).
    #[prop(js = "activeOpacity", min = 0, max = 1)]
    ActiveOpacity(Option<f32>),
    /// `underlayColor`: the background while pressed; the children fade to
    /// `underlayOpacity` (native, no JS round trip).
    #[prop(js = "underlayColor")]
    UnderlayColor(Option<Color>),
    /// `underlayOpacity`: the children's opacity while `underlayColor` shows
    /// (default 0.85).
    #[prop(js = "underlayOpacity", default = UNDERLAY_OPACITY, min = 0, max = 1)]
    UnderlayOpacity(f32),
    /// The surface lays out right to left (on the root, from
    /// `I18nManager`).
    #[prop(js = "layoutDirectionRtl", internal)]
    LayoutDirection(bool),
    /// The app's appearance (on the root, from `nsh.json` and
    /// `setColorScheme`).
    #[prop(js = "appearance", internal)]
    Appearance(crate::platform::Appearance),
    /// The surface's keyboard shortcuts (on the root, from `nsh/keymap`):
    /// the whole table, mounted as [`crate::MountItem::Keymap`].
    Keymap(std::sync::Arc<crate::keymap::Keymap>),
    /// Padding added to the style's own (safe areas, the keyboard), in
    /// points on the physical edges; set by components
    /// (`Element::inset_padding`), never by JS.
    InsetPadding(EdgeInsets),
    /// Margin added to the style's own (`KeyboardAvoidingView`'s
    /// `height` behavior), in points on the physical edges; set by
    /// components.
    InsetMargin(EdgeInsets),
    /// `class`: Tailwind CSS classes (`"flex-row gap-2 p-4 bg-white
    /// dark:bg-zinc-900"`), resolved natively. Later classes win over earlier ones;
    /// `style` wins over both.
    #[prop(js = "class")]
    Class(Box<str>),
    /// `classList`: classes applied while their value is truthy (`{ "opacity-50":
    /// busy() }`).
    #[prop(js = "classList", with = crate::js::host_values::class_list, reset = Prop::ClassList(Vec::new()), ts = "Record<string, boolean | null | undefined>")]
    ClassList(Vec<Box<str>>),
    /// The app's Tailwind theme (JSON, on the root).
    #[prop(js = "tailwindTheme", with = crate::js::host_values::tailwind_theme, internal)]
    TailwindTheme(Box<str>),
    /// The theme of Rust components (`nsh.json` `theme`, JSON), on the
    /// root.
    #[prop(js = "uiTheme", with = crate::js::host_values::ui_theme, internal)]
    UiTheme(Box<str>),
    /// An image option.
    #[prop(nested)]
    Image(ImageProp),
    /// `delayLongPress`: milliseconds before a press becomes a long press (default
    /// 500).
    #[prop(js = "delayLongPress", min = 0)]
    LongPressDelay(Option<f32>),
    /// `ripple` (Android): the material ripple while pressed.
    #[prop(android = "ripple")]
    Ripple(Option<crate::props::Ripple>),
    /// `elevation` (Android): the material shadow (points), from the view's shape.
    #[prop(android = "elevation")]
    Elevation(f32),
    /// An accessibility property.
    #[prop(nested)]
    Accessibility(AccessibilityProp),
    /// `testID`: an identifier for UI tests.
    #[prop(js = "testID")]
    TestId(Option<Arc<str>>),
    /// `windowDrag` (desktops): pressing the view drags the window, as its
    /// title bar would (double-clicking maximizes it); `false` keeps a part
    /// of a draggable view clickable. The nearest view that sets it
    /// decides; text fields and views with press or touch handlers inside
    /// a draggable view stay clickable without it.
    #[prop(desktop = "windowDrag")]
    WindowDrag(Option<bool>),
    /// `allowFontScaling`: follow the system text size (default true).
    #[prop(js = "allowFontScaling", default = true, on = TEXT | INPUT)]
    AllowFontScaling(bool),
    /// `maxFontSizeMultiplier`: the upper bound of the system scale (0 is none).
    #[prop(js = "maxFontSizeMultiplier", min = 0, on = TEXT | INPUT)]
    MaxFontSizeMultiplier(f32),
    /// `selectable`: a long press offers to copy the text.
    #[prop(js = "selectable", on = TEXT)]
    Selectable(bool),
    /// `adjustsFontSizeToFit`: shrink the font until the text fits its lines
    /// (`numberOfLines`) and box.
    #[prop(js = "adjustsFontSizeToFit", on = TEXT)]
    AdjustsFontSizeToFit(bool),
    /// `minimumFontScale`: how far `adjustsFontSizeToFit` shrinks at most (0..1).
    #[prop(js = "minimumFontScale", min = 0, max = 1, on = TEXT)]
    MinimumFontScale(f32),
    /// `pinch`: two-finger pinches drive `scale` natively.
    #[prop(js = "pinch", with = crate::js::host_values::pinch, reset = Prop::PinchValue(None), ts = "{ scale?: NativeValue }")]
    PinchValue(Option<nsh_animation::NodeId>),
    /// `rotation`: two-finger rotations drive `angle` (degrees) natively.
    #[prop(js = "rotation", with = crate::js::host_values::rotation, reset = Prop::RotationValue(None), ts = "{ angle?: NativeValue }")]
    RotationValue(Option<nsh_animation::NodeId>),
    /// A screen option.
    #[prop(nested)]
    Screen(ScreenProp),
    /// A modal option.
    #[prop(nested)]
    Modal(ModalProp),
    /// `<headeritem slot>`.
    #[prop(js = "headerSlot", internal)]
    HeaderSlot(HeaderSlot),
    /// A property of a native control (web view, video), or `disabled`.
    #[prop(nested)]
    Native(NativeProp),
}

/// Where a web view loads from.
#[derive(Debug, Clone, PartialEq)]
pub enum WebSource {
    /// Nothing.
    None,
    /// A URL.
    Uri(Arc<str>),
    /// HTML, with the URL relative links resolve against.
    Html {
        /// The page.
        html: Arc<str>,
        /// Base URL.
        base_url: Option<Arc<str>>,
    },
}

/// A property of a native control.
#[derive(Debug, Clone, PartialEq, HostProps)]
pub enum NativeProp {
    /// `disabled` (any element): ignores presses (no press feedback either),
    /// applies `disabled:` classes and disables controls.
    #[prop(js = "disabled")]
    Disabled(bool),
    /// `source` of a web view or video: a URL, `{ uri }`, or (web views) `{ html,
    /// baseUrl }`.
    #[prop(js = "source", default = WebSource::None, on = WEBVIEW | VIDEO)]
    Source(WebSource),
    /// `injectedJavaScript` (web views): runs after each page loads.
    #[prop(js = "injectedJavaScript", on = WEBVIEW)]
    InjectedJavaScript(Option<Arc<str>>),
    /// `injectedJavaScriptBeforeContentLoaded` (web views): runs before each page's
    /// own scripts.
    #[prop(js = "injectedJavaScriptBeforeContentLoaded", on = WEBVIEW)]
    InjectedJavaScriptBefore(Option<Arc<str>>),
    /// `userAgent` (web views): the browser's user agent string.
    #[prop(js = "userAgent", on = WEBVIEW)]
    UserAgent(Option<Arc<str>>),
    /// `scrollEnabled`: the user can scroll it (default true).
    #[prop(js = "scrollEnabled", default = true, on = WEBVIEW | SCROLLING)]
    ScrollEnabled(bool),
    /// `javaScriptEnabled` (web views): pages run scripts (default true).
    #[prop(js = "javaScriptEnabled", default = true, on = WEBVIEW)]
    JavaScriptEnabled(bool),
    /// `allowsBackForwardNavigationGestures` (iOS web views; desktop ones on
    /// macOS, with two-finger trackpad swipes): swipe back and forward.
    #[prop(
        ios = "allowsBackForwardNavigationGestures",
        desktop = "allowsBackForwardNavigationGestures",
        on = WEBVIEW
    )]
    BackForwardGestures(bool),
    /// `paused` (videos): playback is paused.
    #[prop(js = "paused", on = VIDEO)]
    Paused(bool),
    /// `muted` (videos): no sound.
    #[prop(js = "muted", on = VIDEO)]
    Muted(bool),
    /// `volume` (videos): 0..1.
    #[prop(js = "volume", default = 1.0, on = VIDEO)]
    Volume(f32),
    /// `rate` (videos): the playback speed.
    #[prop(js = "rate", default = 1.0, on = VIDEO)]
    Rate(f32),
    /// `repeat` (videos): plays again from the start at the end.
    #[prop(js = "repeat", on = VIDEO)]
    Repeat(bool),
    /// Video `resizeMode`.
    #[prop(reset = NativeProp::VideoResizeMode(ResizeMode::Contain))]
    VideoResizeMode(ResizeMode),
    /// `controls` (videos): the platform's playback controls.
    #[prop(js = "controls", on = VIDEO)]
    Controls(bool),
    /// `progressUpdateInterval` (videos): milliseconds between `onProgress` events
    /// (250 by default).
    #[prop(js = "progressUpdateInterval", default = 250.0, on = VIDEO)]
    ProgressInterval(f32),
}

/// A mutation produced by the JS renderer.
#[derive(Debug)]
pub enum Op {
    /// What a canvas draws (replaces the previous drawing).
    Draw {
        /// The canvas.
        id: NodeId,
        /// The recorded operations.
        drawing: Box<crate::canvas::Drawing>,
    },
    /// Creates a detached element node.
    Create {
        /// New node id.
        id: NodeId,
        /// Element tag.
        tag: Tag,
    },
    /// Creates a detached raw text node.
    CreateText {
        /// New node id.
        id: NodeId,
        /// Text content.
        text: String,
    },
    /// Replaces the content of a raw text node.
    SetText {
        /// Text node id.
        id: NodeId,
        /// New content.
        text: String,
    },
    /// Replaces the whole style of a node.
    SetStyle {
        /// Node id.
        id: NodeId,
        /// The new style; boxed because layout styles are large.
        style: Box<Style>,
        /// The declarations `style` was built from, applied again over the
        /// node's class styles.
        patch: StylePatch,
    },
    /// Sets a non-style property.
    SetProp {
        /// Node id.
        id: NodeId,
        /// The property.
        prop: Prop,
    },
    /// Enables or disables an event listener on a node.
    Listen {
        /// Node id.
        id: NodeId,
        /// Event kind.
        event: EventKind,
        /// Whether a handler is attached.
        enabled: bool,
    },
    /// Inserts (or moves) `child` into `parent` before `before`, or appends.
    Insert {
        /// Parent node id.
        parent: NodeId,
        /// Child node id.
        child: NodeId,
        /// Sibling to insert before; `None` appends.
        before: Option<NodeId>,
    },
    /// Detaches `child` from `parent`. The child stays alive until released.
    Remove {
        /// Parent node id.
        parent: NodeId,
        /// Child node id.
        child: NodeId,
    },
    /// The JS node was garbage collected: free the node and its native view.
    Release {
        /// Node id.
        id: NodeId,
    },
    /// An animation graph change, forwarded to the platform in order.
    Animation(AnimationOp),
    /// An imperative call on a node's native view.
    Command {
        /// Node id.
        id: NodeId,
        /// The call.
        command: Command,
    },
}