nsh-js 0.7.2

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
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
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
//! Navigation and dialogs: `createNavStack`, `NavStack`, `NavPage` and
//! `Dialog` (`nsh/base` exports them: `Registry::native_values`).
//!
//! A stack renders each route of its state with the app's function into a
//! native page (UINavigationController on iOS, a stack with a toolbar on
//! Android); pages stay mounted while their route is in the stack. A page
//! the user pops natively removes its route. Pages and dialogs provide
//! their insets to what they render (`safeAreaInsets`).
//!
//! NSH draws no look of its own: the desktops and the web show a page's
//! `header` slot at its top (the core places it) and nothing else; a
//! dialog renders the app's popup and, when styled, its backdrop, inside a
//! native layer that has no look either.
//!
//! The handlers of a page's and a dialog's native events are the
//! runtime's: they keep the stack in step and call the app's props
//! (`onDismiss`, `onBackPress`, `onOpen`, `onClose`, `onCancel`,
//! `onOpenChange`), so the app's names are not the core's events'.

use std::{
    collections::{HashMap, VecDeque},
    ffi::{CStr, CString, c_int},
    ptr,
};

use nsh_core::{EventKind, Tag};
use rquickjs::qjs;

use crate::{
    dom,
    modules::{Export, Item, Ts},
    reactive::{self, arg},
};

type JsValue = qjs::JSValue;
type JsContext = qjs::JSContext;

const UNDEFINED: JsValue = qjs::JS_UNDEFINED;

type DataFn = unsafe extern "C" fn(
    *mut JsContext,
    JsValue,
    c_int,
    *mut JsValue,
    c_int,
    *mut JsValue,
) -> JsValue;

fn native(cx: *mut JsContext, f: DataFn, length: c_int, data: &mut [JsValue]) -> JsValue {
    // SAFETY: the function keeps dups of `data`.
    unsafe {
        qjs::JS_NewCFunctionData(
            cx,
            Some(f),
            length,
            0,
            data.len() as c_int,
            data.as_mut_ptr(),
        )
    }
}

fn get(cx: *mut JsContext, obj: JsValue, key: &CStr) -> JsValue {
    // SAFETY: a property read of a live value.
    unsafe {
        if !qjs::JS_IsObject(obj) {
            return UNDEFINED;
        }
        qjs::JS_GetPropertyStr(cx, obj, key.as_ptr())
    }
}

fn free(cx: *mut JsContext, v: JsValue) {
    // SAFETY: an owned value.
    unsafe { qjs::JS_FreeValue(cx, v) };
}

/// `nsh/base`'s navigation and dialogs (its `Registry::native_values`).
pub(crate) const EXPORTS: &[Item] = &[
    (
        "createNavStack",
        Export::Function(create_nav_stack, 1),
        Ts::function(
            "The state of a `<NavStack>`: its routes, starting with `routes`.",
            &["<R>(routes: R[]): NavStackState<R>"],
        ),
    ),
    (
        "NavStack",
        Export::Function(stack, 1),
        Ts::function(
            "A native navigation stack: UINavigationController on iOS (swipe back,\nnative header), a stack with a toolbar and predictive back on Android.\nPages stay mounted (with their state) while they are in the stack.",
            &["<R>(props: NavStackProps<R>): JSX.Element"],
        ),
    ),
    (
        "NavPage",
        Export::Function(screen, 1),
        Ts::function(
            "One page of a `<NavStack>`: its `header` (desktops, the web) and the system\nheader's options (iOS, Android).",
            &["(props: NavPageProps): JSX.Element"],
        ),
    ),
    (
        "Dialog",
        Export::Function(modal, 1),
        Ts::function(
            "A modal surface over everything else, in its own native window layer\n(`presentation` picks its form on iOS). It owns no look: `class` and `style`\nstyle the popup, `backdropClass` and `backdropStyle` a backdrop behind it.",
            &["(props: DialogProps): JSX.Element"],
        ),
    ),
];

/// The types of the navigation's exports.
pub(crate) const TYPES: &str = r#"/** The routes of a `<NavStack>`: the app's values; each push is a page of its own, the same route pushed twice included. */
export interface NavStackState<R> {
  /** The routes, bottom to top (reactive). */
  routes: Accessor<readonly R[]>;
  /** Pushes a page. */
  push(route: R): void;
  /** Pops `count` pages (default 1; at least one stays). */
  pop(count?: number): void;
  /** Pops back to the first page. */
  popToRoot(): void;
  /** Replaces the top page. */
  replace(route: R): void;
  /** Replaces the pages with `routes`; a route that stays (the same value)
   * keeps its page and its state. */
  setRoutes(routes: R[]): void;
  /** Removes the topmost page of `route`, wherever it is. */
  remove(route: R): void;
}

export interface NavStackProps<R> {
  state: NavStackState<R>;
  /** Finds the stack in tests and `nsh test --trace`. */
  testID?: string;
  style?: StyleProp<ViewStyle>;
  class?: string;
  /** Renders a route; return a `<NavPage>` for header options. */
  children: (route: R, index: Accessor<number>) => JSX.Element;
  /** The routes changed: pushed, popped, replaced or set by the app, or a
   * page the user went back from (a back button, a swipe, the browser's
   * back). After the change is rendered; not for the routes the stack
   * starts with. */
  onChange?: (event: NavStackChangeEvent<R>) => void;
}

/** What a `<NavStack>`'s `onChange` gets. */
export interface NavStackChangeEvent<R> {
  /** The routes now, bottom to top. */
  routes: readonly R[];
}

/** The color of the status bar's content. */
export type StatusBarForeground = "auto" | "light" | "dark";

/** What the status bar shows while a page or dialog is up (`statusBar`; iOS
 * and Android). The fields left out keep what is below: the pages under it
 * and the app's default (`nsh.json` `statusBar`). */
export interface StatusBar {
  /** The content's color: "light" for dark backgrounds, "dark" for light ones, "auto" the platform's for the appearance. */
  foreground?: StatusBarForeground;
  /** Hidden. */
  hidden?: boolean;
  /** Animate the change when the page or dialog comes and goes. */
  animated?: boolean;
}

/** The colors of a page's system header (iOS and Android). */
export interface HeaderStyle {
  backgroundColor?: ColorValue;
  /** The title's. */
  color?: ColorValue;
  /** The back button's and the bar buttons'. */
  tintColor?: ColorValue;
}

export interface NavPageProps extends NavPageHostProps {
  /** Finds the page in tests and `nsh test --trace`. */
  testID?: string;
  ios?: IOSNavPageHostProps;
  android?: AndroidNavPageHostProps;
  /** The app's header on the desktops and the web, which have no system
   * header: placed at the top of the page, as wide as the page and as tall
   * as it lays out, with the content below it. NSH draws nothing else
   * there (no title, no back button); iOS and Android show their system
   * header instead. */
  header?: JSX.Element;
  /** iOS and Android: the system header's leading item. */
  headerLeft?: JSX.Element;
  /** iOS and Android: the system header's trailing item. */
  headerRight?: JSX.Element;
  /** iOS and Android: replaces the system header's title. */
  headerTitle?: JSX.Element;
  /** iOS and Android: the system header's colors. */
  headerStyle?: HeaderStyle;
  /** iOS and Android: the system header's colors as classes (`bg-*`,
   * `text-*` for the title, `tint-*` for the buttons); `headerStyle` wins
   * over them. */
  headerClass?: string;
  /** The user popped the page (back button, swipe); its route is gone. */
  onDismiss?: () => void;
  /** The user pressed back on the page (the header's back button, Android
   * back, Escape / Alt+Left / the mouse's back button on the desktops, the
   * browser's back), whether or not `popOnBack` let it pop. */
  onBackPress?: () => void;
  style?: StyleProp<ViewStyle>;
  class?: string;
  children?: JSX.Element;
}

/** What closed a dialog: Escape or the back button (`"cancel"`), a press
 * on its backdrop part, a sheet swiped down. */
export type DialogChangeReason = "cancel" | "backdropPress" | "swipe";

export interface DialogProps extends DialogHostProps {
  /** Finds the dialog in tests and `nsh test --trace`. */
  testID?: string;
  /** Shown while true (default). */
  open?: boolean;
  /** How it comes in and goes (default `"slide"`). */
  animation?: "slide" | "fade" | "none";
  /** What screen readers call it as the focus enters it: its title. */
  accessibilityLabel?: string;
  /** What screen readers read after its name: its message (an alert
   * dialog's "This can't be undone."). */
  accessibilityDescription?: string;
  /** What it is for screen readers (default `"dialog"`): `"alertdialog"`
   * for one that asks the user to confirm something or tells them
   * something urgent. */
  role?: "dialog" | "alertdialog";
  /** It finished appearing. */
  onOpen?: () => void;
  /** It went away: the user closed it, or the app removed it. */
  onClose?: () => void;
  /** The user tried to close it (Escape, back, a backdrop press, a swipe
   * down), whether or not a `closeOn*` flag let it close. */
  onCancel?: () => void;
  /** The user closed it (the `closeOn*` flag of what they did let it
   * close): it closes whatever `open` says, so keep `open` in sync (set it
   * to false here); while `open` stays true it stays closed, and it opens
   * again when `open` goes from false to true. */
  onOpenChange?: (event: { open: boolean; reason: DialogChangeReason }) => void;
  /** The popup's style: the view holding the children. The dialog itself
   * has no look: on the desktops and the web it is a transparent layer over
   * the window (`presentation` is ignored there). */
  style?: StyleProp<ViewStyle>;
  /** The popup's classes. */
  class?: string;
  /** The backdrop's style: with this or `backdropClass`, a view filling the
   * dialog behind the popup (none otherwise), whose presses are close
   * attempts (`"backdropPress"`, closing when `closeOnBackdropPress`). */
  backdropStyle?: StyleProp<ViewStyle>;
  /** The backdrop's classes (see `backdropStyle`). */
  backdropClass?: string;
  /** Finds the backdrop in tests and `nsh test --trace`. */
  backdropTestID?: string;
  children?: JSX.Element;
  ios?: IOSDialogHostProps;
  android?: AndroidDialogHostProps;
}
"#;

// --- The navigator --------------------------------------------------------------

/// The routes (a JS array) as values (owned), none for other values;
/// `None` (an exception pending) when the array's length throws or is
/// longer than [`dom::MAX_ARRAY_ITEMS`].
fn routes_of(cx: *mut JsContext, routes: JsValue) -> Option<Vec<JsValue>> {
    // SAFETY: an inline tag check.
    if !unsafe { qjs::JS_IsArray(routes) } {
        return Some(Vec::new());
    }
    // Read natively: a sparse array is as long as it says.
    let len = dom::checked_len(cx, routes)?;
    // SAFETY: reads of a live array.
    Some(
        (0..len)
            .map(|i| unsafe { qjs::JS_GetPropertyUint32(cx, routes, i) })
            .collect(),
    )
}

/// `createNavStack(routes)`: the route stack of a `<NavStack>`.
unsafe extern "C" fn create_nav_stack(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let initial = arg(argc, argv, 0);
    // SAFETY: an inline tag check.
    if !unsafe { qjs::JS_IsArray(initial) } {
        // SAFETY: throwing in the calling context.
        return unsafe {
            qjs::JS_ThrowTypeError(cx, c"createNavStack: an array of routes".as_ptr())
        };
    }
    let Some(routes) = routes_of(cx, initial) else {
        return qjs::JS_EXCEPTION;
    };
    let mut entries: Vec<JsValue> = routes.into_iter().map(|route| entry(cx, route)).collect();
    // SAFETY: a new array taking the entries.
    let entries = unsafe { qjs::JS_NewArrayFrom(cx, entries.len() as c_int, entries.as_mut_ptr()) };
    let signal = reactive::new_signal(cx, entries);
    free(cx, entries);
    // SAFETY: a new object taking the functions.
    let nav = unsafe { qjs::JS_NewObject(cx) };
    let methods: [(&CStr, c_int, c_int); 6] = [
        (c"push", 1, 0),
        (c"pop", 1, 1),
        (c"popToRoot", 0, 2),
        (c"replace", 1, 3),
        (c"setRoutes", 1, 4),
        (c"remove", 1, 5),
    ];
    for (name, length, magic) in methods {
        let mut data = [signal];
        // SAFETY: the function keeps a dup of the signal; the object takes it.
        unsafe {
            let f =
                qjs::JS_NewCFunctionData(cx, Some(navigate), length, magic, 1, data.as_mut_ptr());
            qjs::JS_SetPropertyStr(cx, nav, name.as_ptr(), f);
        }
    }
    // `routes`: a read-only accessor.
    let read = native(cx, read_routes, 0, &mut [signal]);
    let routes = reactive::memo(cx, read, false);
    // SAFETY: the object takes the accessor and the signal, the latter
    // hidden (not enumerable, not writable): `<NavStack>` renders its entries.
    unsafe {
        qjs::JS_SetPropertyStr(cx, nav, c"routes".as_ptr(), routes);
        qjs::JS_DefinePropertyValueStr(cx, nav, ENTRIES.as_ptr(), signal, 0);
    }
    nav
}

/// The hidden property of a navigator holding its entries' signal.
const ENTRIES: &CStr = c"__nshEntries";

/// One screen of a navigator: an object of its own around the route, so a
/// route pushed twice is two screens, and the user popping one removes
/// that one (takes `route`).
fn entry(cx: *mut JsContext, route: JsValue) -> JsValue {
    // SAFETY: a new object taking the route.
    unsafe {
        let entry = qjs::JS_NewObject(cx);
        qjs::JS_SetPropertyStr(cx, entry, c"route".as_ptr(), route);
        entry
    }
}

/// The route of an entry (owned).
fn route_of(cx: *mut JsContext, entry: JsValue) -> JsValue {
    get(cx, entry, c"route")
}

/// What `===` compares a route by, where it can be looked up: a string by
/// its atom (one per content), an object by identity.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum RouteKey {
    Atom(qjs::JSAtom),
    Object(usize),
}

/// `route`'s key (borrowed; an atom made is the caller's), `None` for a
/// route `===` compares otherwise (a number, a symbol, ...).
fn route_key(cx: *mut JsContext, route: JsValue) -> Option<RouteKey> {
    // SAFETY: inline tag and pointer reads of a live value, an atom made of
    // a string (owned by the caller) or a pending exception cleared.
    unsafe {
        if qjs::JS_IsObject(route) {
            return Some(RouteKey::Object(qjs::JS_VALUE_GET_PTR(route) as usize));
        }
        if qjs::JS_IsString(route) {
            let atom = qjs::JS_ValueToAtom(cx, route);
            if atom != qjs::JS_ATOM_NULL {
                return Some(RouteKey::Atom(atom));
            }
            qjs::JS_FreeValue(cx, qjs::JS_GetException(cx));
        }
    }
    None
}

/// A stack's entries by route (`setRoutes`): a route's first unused entry
/// is found without comparing the route with every entry, so replacing n
/// routes with n others takes n lookups, not n² reads of entries' routes
/// in a native loop the time budget cannot interrupt. Routes without a
/// key are compared one by one, as before.
struct RouteIndex {
    keyed: HashMap<RouteKey, VecDeque<usize>>,
    others: Vec<usize>,
    /// The atoms of `keyed` (owned).
    atoms: Vec<qjs::JSAtom>,
}

impl RouteIndex {
    /// The routes of `entries` (borrowed, kept alive until [`free`]d: the
    /// keys of objects are their addresses).
    ///
    /// [`free`]: RouteIndex::free
    fn new(cx: *mut JsContext, entries: &[JsValue]) -> Self {
        let mut index = RouteIndex {
            keyed: HashMap::new(),
            others: Vec::new(),
            atoms: Vec::new(),
        };
        for (i, &e) in entries.iter().enumerate() {
            let route = route_of(cx, e);
            match route_key(cx, route) {
                Some(key) => {
                    if let RouteKey::Atom(atom) = key {
                        index.atoms.push(atom);
                    }
                    index.keyed.entry(key).or_default().push_back(i);
                }
                None => index.others.push(i),
            }
            free(cx, route);
        }
        index
    }

    /// The first entry of `entries` not taken yet whose route is `route`
    /// (borrowed), now taken.
    fn take(&mut self, cx: *mut JsContext, entries: &[JsValue], route: JsValue) -> Option<usize> {
        let Some(key) = route_key(cx, route) else {
            let at = self.others.iter().position(|&i| {
                let r = route_of(cx, entries[i]);
                // SAFETY: an identity comparison of live values.
                let same = unsafe { qjs::JS_IsStrictEqual(cx, r, route) };
                free(cx, r);
                same
            })?;
            return Some(self.others.remove(at));
        };
        let at = self.keyed.get_mut(&key).and_then(VecDeque::pop_front);
        if let RouteKey::Atom(atom) = key {
            // SAFETY: the atom made for this lookup.
            unsafe { qjs::JS_FreeAtom(cx, atom) };
        }
        at
    }

    fn free(self, cx: *mut JsContext) {
        for atom in self.atoms {
            // SAFETY: an atom this index made.
            unsafe { qjs::JS_FreeAtom(cx, atom) };
        }
    }
}

unsafe extern "C" fn read_routes(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value: the entries' signal.
    let entries = unsafe { qjs::JS_Call(cx, *data, UNDEFINED, 0, ptr::null_mut()) };
    let Some(entries_got) = routes_of(cx, entries) else {
        free(cx, entries);
        return qjs::JS_EXCEPTION;
    };
    let mut routes: Vec<JsValue> = entries_got
        .into_iter()
        .map(|e| {
            let route = route_of(cx, e);
            free(cx, e);
            route
        })
        .collect();
    free(cx, entries);
    // SAFETY: a new array taking the routes.
    unsafe { qjs::JS_NewArrayFrom(cx, routes.len() as c_int, routes.as_mut_ptr()) }
}

/// The stack state's functions, by magic: push, pop, popToRoot, replace,
/// setRoutes, remove; 6: remove one entry (the user popped its page).
unsafe extern "C" fn navigate(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value (the signal); values got are freed or moved.
    let signal = unsafe { *data };
    let current = reactive::peek(cx, signal);
    let Some(mut routes) = routes_of(cx, current) else {
        return qjs::JS_EXCEPTION;
    };
    let a0 = arg(argc, argv, 0);
    let dup = |v: JsValue| unsafe { qjs::JS_DupValue(cx, v) };
    match magic {
        // A stack is read as the arrays apps hand in are: one longer than
        // the bound could no longer be navigated, so it does not grow past it.
        0 if routes.len() >= dom::MAX_ARRAY_ITEMS as usize => {
            for e in routes {
                free(cx, e);
            }
            let message = CString::new(format!(
                "nsh: a navigation stack holds at most {} screens",
                dom::MAX_ARRAY_ITEMS
            ))
            .unwrap_or_default();
            // SAFETY: throwing in the calling context.
            return unsafe { qjs::JS_ThrowRangeError(cx, c"%s".as_ptr(), message.as_ptr()) };
        }
        0 => routes.push(entry(cx, dup(a0))),
        1 => {
            let mut count = 1f64;
            // SAFETY: converting a live value.
            if !unsafe { qjs::JS_IsUndefined(a0) } {
                unsafe { qjs::JS_ToFloat64(cx, &mut count, a0) };
            }
            let keep = routes.len().saturating_sub(count.max(0.0) as usize).max(1);
            for v in routes.drain(keep.min(routes.len())..) {
                free(cx, v);
            }
        }
        2 => {
            for v in routes.drain(1.min(routes.len())..) {
                free(cx, v);
            }
        }
        3 => {
            if let Some(v) = routes.pop() {
                free(cx, v);
            }
            routes.push(entry(cx, dup(a0)));
        }
        4 => {
            // A route that stays keeps its page (its entry), in order: the
            // first unused entry of the same route.
            let Some(next) = routes_of(cx, a0) else {
                for e in routes {
                    free(cx, e);
                }
                return qjs::JS_EXCEPTION;
            };
            let entries = std::mem::take(&mut routes);
            let mut index = RouteIndex::new(cx, &entries);
            let mut old: Vec<Option<JsValue>> = entries.iter().copied().map(Some).collect();
            routes = next
                .into_iter()
                .map(|route| {
                    let kept = index.take(cx, &entries, route).and_then(|i| old[i].take());
                    match kept {
                        Some(e) => {
                            free(cx, route);
                            e
                        }
                        None => entry(cx, route),
                    }
                })
                .collect();
            index.free(cx);
            for e in old.into_iter().flatten() {
                free(cx, e);
            }
        }
        5 => {
            // The topmost screen showing the route.
            let at = routes.iter().rposition(|&e| {
                let route = route_of(cx, e);
                // SAFETY: an identity comparison of live values.
                let same = unsafe { qjs::JS_IsStrictEqual(cx, route, a0) };
                free(cx, route);
                same
            });
            if let Some(at) = at {
                free(cx, routes.remove(at));
            }
        }
        _ => {
            // SAFETY: identity comparisons of live values.
            if let Some(at) = routes
                .iter()
                .position(|&e| unsafe { qjs::JS_IsStrictEqual(cx, e, a0) })
            {
                free(cx, routes.remove(at));
            }
        }
    }
    // SAFETY: a new array taking the routes.
    let next = unsafe { qjs::JS_NewArrayFrom(cx, routes.len() as c_int, routes.as_mut_ptr()) };
    reactive::set_signal(cx, signal, next);
    reactive::finish_value(cx, UNDEFINED)
}

// --- Stack ------------------------------------------------------------------------

/// `<NavStack state>{(route, index) => <NavPage …>}</NavStack>`.
unsafe extern "C" fn stack(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let props = arg(argc, argv, 0);
    let node = match dom::create_element(cx, Tag::Stack) {
        Ok(node) => node,
        Err(e) => return e,
    };
    let result = (|| -> Result<(), JsValue> {
        dom::spread_except(cx, node, props, &["state", "children", "onChange"])?;
        let change = native(cx, stack_change, 1, &mut [props]);
        reactive::user_effect(cx, change);
        let navigator = get(cx, props, c"state");
        let entries = get(cx, navigator, ENTRIES);
        free(cx, navigator);
        let render = native(cx, stack_row, 2, &mut [props]);
        // SAFETY: `each(entries, render)`: a row per pushed screen.
        let mut args = [entries, render];
        let rows = unsafe { crate::dom::each(cx, UNDEFINED, 2, args.as_mut_ptr()) };
        free(cx, entries);
        free(cx, render);
        // SAFETY: an inline tag check.
        if unsafe { qjs::JS_IsException(rows) } {
            return Err(rows);
        }
        let r = dom::insert_value_at(cx, node, rows, None);
        free(cx, rows);
        r
    })();
    match result {
        Ok(()) => reactive::finish_value(cx, node),
        Err(e) => {
            free(cx, node);
            e
        }
    }
}

/// The stack's `onChange({ routes })`: an effect reading its routes, which
/// calls the app after each change (not for the routes it starts with).
unsafe extern "C" fn stack_change(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value (the stack's props).
    let props = unsafe { *data };
    // SAFETY: an inline tag check of the last run's value.
    let first = unsafe { qjs::JS_IsUndefined(arg(argc, argv, 0)) };
    let navigator = get(cx, props, c"state");
    let read = get(cx, navigator, c"routes");
    free(cx, navigator);
    // SAFETY: the state's accessor, tracked.
    let routes = unsafe { qjs::JS_Call(cx, read, UNDEFINED, 0, ptr::null_mut()) };
    free(cx, read);
    // SAFETY: an inline tag check.
    if unsafe { qjs::JS_IsException(routes) } {
        return routes;
    }
    if !first {
        // Untracked: a handler that changes is no change of the routes.
        let failed = reactive::untracked_with(cx, || {
            let on_change = get(cx, props, c"onChange");
            // SAFETY: an inline check; the event object takes a dup of `routes`.
            if !unsafe { qjs::JS_IsFunction(cx, on_change) } {
                free(cx, on_change);
                return None;
            }
            let event = unsafe { qjs::JS_NewObject(cx) };
            unsafe {
                qjs::JS_SetPropertyStr(cx, event, c"routes".as_ptr(), qjs::JS_DupValue(cx, routes))
            };
            let mut args = [event];
            // SAFETY: the app's function.
            let r = unsafe { qjs::JS_Call(cx, on_change, UNDEFINED, 1, args.as_mut_ptr()) };
            free(cx, event);
            free(cx, on_change);
            // SAFETY: an inline tag check.
            if unsafe { qjs::JS_IsException(r) } {
                return Some(r);
            }
            free(cx, r);
            None
        });
        if let Some(e) = failed {
            free(cx, routes);
            return e;
        }
    }
    free(cx, routes);
    qjs::JS_TRUE
}

/// One route of a stack: its screen (the app's `<NavPage>`, or one around
/// what it rendered); a native pop removes the route.
unsafe extern "C" fn stack_row(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value (the stack's props); `item` is an accessor.
    let props = unsafe { *data };
    let (item, index) = (arg(argc, argv, 0), arg(argc, argv, 1));
    let entry = reactive::untracked_with(cx, || unsafe {
        qjs::JS_Call(cx, item, UNDEFINED, 0, ptr::null_mut())
    });
    let route = route_of(cx, entry);
    let children = get(cx, props, c"children");
    let mut args = [route, index];
    // SAFETY: the app's function, called untracked.
    let rendered = reactive::untracked_with(cx, || unsafe {
        qjs::JS_Call(cx, children, UNDEFINED, 2, args.as_mut_ptr())
    });
    free(cx, children);
    // SAFETY: an inline tag check.
    free(cx, route);
    if unsafe { qjs::JS_IsException(rendered) } {
        free(cx, entry);
        return rendered;
    }
    let navigator = get(cx, props, c"state");
    let entries = get(cx, navigator, ENTRIES);
    free(cx, navigator);
    let popped = native(cx, pop_route, 0, &mut [entries, entry]);
    free(cx, entries);
    free(cx, entry);
    // An accessor (e.g. a component made hot) may render another screen
    // later.
    let result =
        if unsafe { qjs::JS_IsFunction(cx, rendered) } && dom::node_id(cx, rendered).is_none() {
            let wrap = native(cx, screen_of_accessor, 0, &mut [rendered, popped]);
            reactive::memo(cx, wrap, false)
        } else {
            screen_for(cx, rendered, popped)
        };
    free(cx, rendered);
    free(cx, popped);
    result
}

unsafe extern "C" fn pop_route(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values: the navigator's entries and the entry.
    let mut args = [unsafe { *data.add(1) }];
    // SAFETY: `navigate` removing that entry (magic 6) from the signal.
    unsafe { navigate(cx, UNDEFINED, 1, args.as_mut_ptr(), 6, data) }
}

unsafe extern "C" fn screen_of_accessor(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values: the accessor and the pop callback.
    let (accessor, popped) = unsafe { (*data, *data.add(1)) };
    let mut rendered = unsafe { qjs::JS_Call(cx, accessor, UNDEFINED, 0, ptr::null_mut()) };
    // A component rendering another gives an accessor around the next one
    // (each made hot is one): read them all, tracked, down to what the
    // innermost rendered, so a `<NavPage>` there is the screen itself and
    // an edit of any of them renders the screen again.
    while !unsafe { qjs::JS_IsException(rendered) }
        && unsafe { qjs::JS_IsFunction(cx, rendered) }
        && dom::node_id(cx, rendered).is_none()
    {
        // SAFETY: an owned function, freed once called.
        let next = unsafe { qjs::JS_Call(cx, rendered, UNDEFINED, 0, ptr::null_mut()) };
        free(cx, rendered);
        rendered = next;
    }
    if unsafe { qjs::JS_IsException(rendered) } {
        return rendered;
    }
    let r = reactive::untracked_with(cx, || screen_for(cx, rendered, popped));
    free(cx, rendered);
    r
}

/// The screen for what a route rendered (borrowed): itself when it is one,
/// else a screen around it; told about native pops (`popped`).
fn screen_for(cx: *mut JsContext, rendered: JsValue, popped: JsValue) -> JsValue {
    let node = if dom::node_tag(cx, rendered) == Some(Tag::Screen) {
        // SAFETY: a dup returned.
        unsafe { qjs::JS_DupValue(cx, rendered) }
    } else {
        // SAFETY: new props for a screen around the content.
        let props = unsafe { qjs::JS_NewObject(cx) };
        unsafe {
            qjs::JS_SetPropertyStr(
                cx,
                props,
                c"children".as_ptr(),
                qjs::JS_DupValue(cx, rendered),
            );
        }
        let mut args = [props];
        let node = unsafe { screen(cx, UNDEFINED, 1, args.as_mut_ptr()) };
        free(cx, props);
        node
    };
    // SAFETY: an inline tag check.
    if !unsafe { qjs::JS_IsException(node) } {
        dom::set_popped(cx, node, popped);
    }
    node
}

// --- Screen -------------------------------------------------------------------------

/// The insets a screen or modal reports, with `initial` until it does:
/// `[insets accessor, onInsets handler]` (owned).
fn native_insets(cx: *mut JsContext, top_zero: bool) -> (JsValue, JsValue) {
    let reported = reactive::new_signal(cx, qjs::JS_NULL);
    let read = native(
        cx,
        read_insets,
        0,
        &mut [
            reported,
            if top_zero {
                qjs::JS_TRUE
            } else {
                qjs::JS_FALSE
            },
        ],
    );
    let insets = reactive::memo(cx, read, false);
    let on = native(cx, on_insets, 1, &mut [reported]);
    free(cx, reported);
    (insets, on)
}

unsafe extern "C" fn read_insets(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values: the reported insets signal and whether the
    // top is the header's (0 until reported).
    unsafe {
        let (reported, top_zero) = (*data, qjs::JS_ToBool(cx, *data.add(1)) == 1);
        let v = qjs::JS_Call(cx, reported, UNDEFINED, 0, ptr::null_mut());
        if qjs::JS_IsException(v) || !qjs::JS_IsNull(v) {
            return v;
        }
        let safe_area = crate::env::reexport(cx, "safeArea");
        let area = qjs::JS_Call(cx, safe_area, UNDEFINED, 0, ptr::null_mut());
        qjs::JS_FreeValue(cx, safe_area);
        if !top_zero || qjs::JS_IsException(area) {
            return area;
        }
        let copy = qjs::JS_NewObject(cx);
        for key in [c"right", c"bottom", c"left"] {
            qjs::JS_SetPropertyStr(cx, copy, key.as_ptr(), get(cx, area, key));
        }
        qjs::JS_SetPropertyStr(cx, copy, c"top".as_ptr(), qjs::JS_NewFloat64(0.0));
        qjs::JS_FreeValue(cx, area);
        copy
    }
}

unsafe extern "C" fn on_insets(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value (the signal); a copy of the event's insets.
    unsafe {
        let e = arg(argc, argv, 0);
        let copy = qjs::JS_NewObject(cx);
        for key in [c"top", c"right", c"bottom", c"left"] {
            qjs::JS_SetPropertyStr(cx, copy, key.as_ptr(), get(cx, e, key));
        }
        reactive::set_signal(cx, *data, copy);
    }
    reactive::finish_value(cx, UNDEFINED)
}

/// What a provider of the insets context renders: `children` (a reader
/// of the app's props) with `insets`.
fn with_insets(cx: *mut JsContext, insets: JsValue, children: JsValue) -> JsValue {
    let context = crate::env::insets_context(cx);
    let provider = get(cx, context, c"Provider");
    // SAFETY: provider props: the value, and the children as a getter.
    unsafe {
        let props = qjs::JS_NewObject(cx);
        qjs::JS_SetPropertyStr(cx, props, c"value".as_ptr(), qjs::JS_DupValue(cx, insets));
        let atom = qjs::JS_NewAtom(cx, c"children".as_ptr());
        qjs::JS_DefineProperty(
            cx,
            props,
            atom,
            UNDEFINED,
            children,
            UNDEFINED,
            (qjs::JS_PROP_HAS_GET | qjs::JS_PROP_HAS_ENUMERABLE | qjs::JS_PROP_ENUMERABLE) as c_int,
        );
        qjs::JS_FreeAtom(cx, atom);
        let mut args = [props];
        let r = qjs::JS_Call(cx, provider, UNDEFINED, 1, args.as_mut_ptr());
        qjs::JS_FreeValue(cx, props);
        qjs::JS_FreeValue(cx, provider);
        r
    }
}

/// A getter of `props[key]`.
fn reader(cx: *mut JsContext, props: JsValue, key: &str) -> JsValue {
    // SAFETY: a new string the function keeps a dup of.
    let k = unsafe { qjs::JS_NewStringLen(cx, key.as_ptr().cast(), key.len() as _) };
    let f = native(cx, read_prop, 0, &mut [props, k]);
    free(cx, k);
    f
}

unsafe extern "C" fn read_prop(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values (props, key).
    unsafe {
        let Some(key) = dom::string_arg(cx, *data.add(1)) else {
            return qjs::JS_EXCEPTION;
        };
        let k = CString::new(key).unwrap_or_default();
        get(cx, *data, &k)
    }
}

/// `<NavPage title … header headerLeft headerRight headerTitle>`: one page
/// of a stack, with its header options.
unsafe extern "C" fn screen(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let props = arg(argc, argv, 0);
    let node = match dom::create_element(cx, Tag::Screen) {
        Ok(node) => node,
        Err(e) => return e,
    };
    let result = (|| -> Result<(), JsValue> {
        dom::spread_except(
            cx,
            node,
            props,
            &[
                "children",
                "header",
                "headerLeft",
                "headerRight",
                "headerTitle",
                "onDismiss",
                "onBackPress",
                "onInsets",
            ],
        )?;
        let (insets, on_insets) = native_insets(cx, true);
        let id = dom::node_id(cx, node).expect("a node");
        let r = dom::set_handler(cx, id, EventKind::Insets, on_insets);
        free(cx, on_insets);
        r?;
        let dismiss = native(cx, on_dismiss, 0, &mut [node, props]);
        let r = dom::set_handler(cx, id, EventKind::Dismiss, dismiss);
        free(cx, dismiss);
        r?;
        // Only when the app listens: the event mask tells the platform
        // whether a back press goes to JS at all.
        let listens = get(cx, props, c"onBackPress");
        // SAFETY: an inline check of a live value.
        let listens_fn = unsafe { !qjs::JS_IsUndefined(listens) && !qjs::JS_IsNull(listens) };
        free(cx, listens);
        if listens_fn {
            forward(cx, id, EventKind::BackRequest, props, "onBackPress")?;
        }
        // The header's slots, then the content with the screen's insets.
        let mut parts = Vec::new();
        for (slot, key) in [
            ("left", "headerLeft"),
            ("right", "headerRight"),
            ("title", "headerTitle"),
            ("header", "header"),
        ] {
            let content = reader(cx, props, key);
            // SAFETY: a new string the function keeps a dup of.
            let name = unsafe { qjs::JS_NewStringLen(cx, slot.as_ptr().cast(), slot.len() as _) };
            let item = native(cx, header_item, 0, &mut [content, name]);
            free(cx, content);
            free(cx, name);
            parts.push(reactive::memo(cx, item, false));
        }
        let children = reader(cx, props, "children");
        let content = with_insets(cx, insets, children);
        free(cx, children);
        free(cx, insets);
        // SAFETY: an inline tag check.
        if unsafe { qjs::JS_IsException(content) } {
            for p in parts {
                free(cx, p);
            }
            return Err(content);
        }
        parts.push(content);
        let all = unsafe { qjs::JS_NewArrayFrom(cx, parts.len() as c_int, parts.as_mut_ptr()) };
        let r = dom::insert_value_at(cx, node, all, None);
        free(cx, all);
        r
    })();
    match result {
        Ok(()) => reactive::finish_value(cx, node),
        Err(e) => {
            free(cx, node);
            e
        }
    }
}

/// A header slot: an item holding the app's content, while it has some.
unsafe extern "C" fn header_item(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values: the content's reader and the slot's name.
    unsafe {
        let (content, name) = (*data, *data.add(1));
        let c = qjs::JS_Call(cx, content, UNDEFINED, 0, ptr::null_mut());
        if qjs::JS_IsException(c) {
            return c;
        }
        if qjs::JS_IsNull(c)
            || qjs::JS_IsUndefined(c)
            || (qjs::JS_IsBool(c) && !qjs::JS_VALUE_GET_BOOL(c))
        {
            qjs::JS_FreeValue(cx, c);
            return qjs::JS_NULL;
        }
        reactive::untracked_with(cx, || {
            let item = match dom::create_element(cx, Tag::HeaderItem) {
                Ok(item) => item,
                Err(e) => {
                    qjs::JS_FreeValue(cx, c);
                    return e;
                }
            };
            let r = dom::set_prop_value(cx, item, "headerSlot", name)
                .and_then(|()| dom::insert_value_at(cx, item, c, None));
            qjs::JS_FreeValue(cx, c);
            match r {
                Ok(()) => item,
                Err(e) => {
                    qjs::JS_FreeValue(cx, item);
                    e
                }
            }
        })
    }
}

/// A page's dismissal: a native pop tells the stack, then the app
/// (`onDismiss`).
unsafe extern "C" fn on_dismiss(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values: the node and the props; values got are
    // freed.
    unsafe {
        let (node, props) = (*data, *data.add(1));
        let popped = dom::popped(cx, node);
        if qjs::JS_IsFunction(cx, popped) {
            let r = qjs::JS_Call(cx, popped, UNDEFINED, 0, ptr::null_mut());
            qjs::JS_FreeValue(cx, popped);
            if qjs::JS_IsException(r) {
                return r;
            }
            qjs::JS_FreeValue(cx, r);
        } else {
            qjs::JS_FreeValue(cx, popped);
        }
        let own = get(cx, props, c"onDismiss");
        let r = if qjs::JS_IsFunction(cx, own) {
            qjs::JS_Call(cx, own, UNDEFINED, 0, ptr::null_mut())
        } else {
            UNDEFINED
        };
        qjs::JS_FreeValue(cx, own);
        r
    }
}

// --- Handlers of the app's props -------------------------------------------------

/// Sets the handler of `event` on node `id` to one calling `props[key]`
/// (read when the event comes) with the event's arguments.
fn forward(
    cx: *mut JsContext,
    id: nsh_core::NodeId,
    event: EventKind,
    props: JsValue,
    key: &str,
) -> Result<(), JsValue> {
    // SAFETY: a new string the function keeps a dup of.
    let k = unsafe { qjs::JS_NewStringLen(cx, key.as_ptr().cast(), key.len() as _) };
    let f = native(cx, call_prop, 1, &mut [props, k]);
    free(cx, k);
    let r = dom::set_handler(cx, id, event, f);
    free(cx, f);
    r
}

unsafe extern "C" fn call_prop(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values (props, key); the arguments are borrowed.
    unsafe {
        let Some(key) = dom::string_arg(cx, *data.add(1)) else {
            return qjs::JS_EXCEPTION;
        };
        let k = CString::new(key).unwrap_or_default();
        let f = get(cx, *data, &k);
        let r = if qjs::JS_IsFunction(cx, f) {
            qjs::JS_Call(cx, f, UNDEFINED, argc, argv)
        } else {
            UNDEFINED
        };
        free(cx, f);
        r
    }
}

// --- Dialog -------------------------------------------------------------------------

/// `<Dialog open onOpenChange …>`: content over everything else, in its
/// own native window layer, while it is open: `open` is not false and the
/// user did not close it ([`close_attempt`]).
///
/// What shows is the app's: the popup (a view with the dialog's `class`
/// and `style`, holding the children) and, only when the app styles one
/// (`backdropClass` / `backdropStyle`), a backdrop behind it filling the
/// layer, whose presses are close attempts (`"backdropPress"`).
unsafe extern "C" fn modal(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let props = arg(argc, argv, 0);
    // Closed by the user while `open` stayed true: `closed` (a plain
    // object's flag, which the run resets without writing a signal it
    // reads) and `tick`, which runs it again.
    // SAFETY: a new object.
    let state = unsafe { qjs::JS_NewObject(cx) };
    let tick = reactive::new_signal(cx, qjs::JS_NewFloat64(0.0));
    let run = native(cx, modal_run, 0, &mut [props, state, tick]);
    free(cx, state);
    free(cx, tick);
    let shown = reactive::memo(cx, run, false);
    reactive::finish_value(cx, shown)
}

/// The `closed` flag of a dialog's state object.
fn closed_by_user(cx: *mut JsContext, state: JsValue) -> bool {
    let v = get(cx, state, c"closed");
    // SAFETY: an inline check of a live value.
    let closed = unsafe { qjs::JS_IsBool(v) && qjs::JS_VALUE_GET_BOOL(v) };
    free(cx, v);
    closed
}

fn set_closed_by_user(cx: *mut JsContext, state: JsValue, closed: bool) {
    // SAFETY: a property write of a live object.
    unsafe {
        qjs::JS_SetPropertyStr(
            cx,
            state,
            c"closed".as_ptr(),
            if closed { qjs::JS_TRUE } else { qjs::JS_FALSE },
        );
    }
}

unsafe extern "C" fn modal_run(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: three data values (props, state, tick).
    let (props, state, tick) = unsafe { (*data, *data.add(1), *data.add(2)) };
    // Tracked: a close by the user runs this again.
    let t = unsafe { qjs::JS_Call(cx, tick, UNDEFINED, 0, ptr::null_mut()) };
    free(cx, t);
    let open = get(cx, props, c"open");
    // SAFETY: an inline check of a live value.
    let closed = unsafe { qjs::JS_IsBool(open) && !qjs::JS_VALUE_GET_BOOL(open) };
    free(cx, open);
    if closed {
        // The app followed (or closed it itself): the next `open` shows it.
        set_closed_by_user(cx, state, false);
        return qjs::JS_NULL;
    }
    if closed_by_user(cx, state) {
        return qjs::JS_NULL;
    }
    reactive::untracked_with(cx, || {
        let node = match dom::create_element(cx, Tag::Modal) {
            Ok(node) => node,
            Err(e) => return e,
        };
        let result = (|| -> Result<(), JsValue> {
            dom::spread_except(
                cx,
                node,
                props,
                &[
                    "children",
                    "open",
                    "animation",
                    "role",
                    "class",
                    "style",
                    "backdropClass",
                    "backdropStyle",
                    "backdropTestID",
                    "onInsets",
                    "onOpen",
                    "onClose",
                    "onCancel",
                    "onOpenChange",
                ],
            )?;
            // A dialog with a backdrop slides its popup itself and fades
            // the rest: the platforms slide the whole layer, the backdrop
            // with it.
            let slide = slides_popup(cx, props);
            if slide {
                // SAFETY: a new string the prop takes.
                let fade = unsafe { qjs::JS_NewStringLen(cx, c"fade".as_ptr(), 4) };
                dom::set_prop_value(cx, node, "animation", fade)?;
            } else {
                let read = reader(cx, props, "animation");
                let r = dom::bind_prop_with(cx, node, "animation", read);
                free(cx, read);
                r?;
            }
            // A dialog for screen readers unless the app says otherwise
            // (`"alertdialog"`), named by its `accessibilityLabel`.
            let read = native(cx, dialog_role, 0, &mut [props]);
            let r = dom::bind_prop_with(cx, node, "role", read);
            free(cx, read);
            r?;
            let (insets, on_insets) = native_insets(cx, false);
            let id = dom::node_id(cx, node).expect("a node");
            let r = dom::set_handler(cx, id, EventKind::Insets, on_insets);
            free(cx, on_insets);
            r?;
            forward(cx, id, EventKind::Show, props, "onOpen")?;
            forward(cx, id, EventKind::Dismiss, props, "onClose")?;
            let cancel = native(cx, on_cancel, 1, &mut [props, state, tick]);
            let r = dom::set_handler(cx, id, EventKind::RequestClose, cancel);
            free(cx, cancel);
            r?;
            // The backdrop part, while the app styles one.
            let has = native(cx, has_backdrop, 0, &mut [props]);
            let make = native(cx, backdrop_part, 0, &mut [props, state, tick]);
            let backdrop = dom::cond_value(cx, has, make);
            free(cx, has);
            free(cx, make);
            // SAFETY: an inline tag check.
            if unsafe { qjs::JS_IsException(backdrop) } {
                free(cx, insets);
                return Err(backdrop);
            }
            let popup = popup_part(cx, props, insets, slide);
            free(cx, insets);
            let popup = match popup {
                Ok(popup) => popup,
                Err(e) => {
                    free(cx, backdrop);
                    return Err(e);
                }
            };
            let mut parts = [backdrop, popup];
            // SAFETY: a new array taking the parts.
            let all = unsafe { qjs::JS_NewArrayFrom(cx, 2, parts.as_mut_ptr()) };
            let r = dom::insert_value_at(cx, node, all, None);
            free(cx, all);
            r
        })();
        match result {
            Ok(()) => node,
            Err(e) => {
                free(cx, node);
                e
            }
        }
    })
}

/// Whether dialog `props` slides its popup itself: it has a backdrop, it
/// slides (the default), the user did not ask for less motion, and its
/// `style` has no `translate` of its own (the slide's would replace it).
fn slides_popup(cx: *mut JsContext, props: JsValue) -> bool {
    // SAFETY: the props borrowed as the function's one data value; it
    // returns a boolean.
    let has = unsafe { has_backdrop(cx, UNDEFINED, 0, ptr::null_mut(), 0, [props].as_mut_ptr()) };
    // SAFETY: an inline read of a boolean.
    if unsafe { !qjs::JS_VALUE_GET_BOOL(has) } {
        return false;
    }
    let animation = get(cx, props, c"animation");
    // SAFETY: an inline check of a live value.
    let unset = unsafe { qjs::JS_IsUndefined(animation) || qjs::JS_IsNull(animation) };
    let slides = unset || dom::string_arg(cx, animation).is_some_and(|a| a == "slide");
    free(cx, animation);
    let style = get(cx, props, c"style");
    let translate = get(cx, style, c"translate");
    // SAFETY: inline checks of live values.
    let own = unsafe { !qjs::JS_IsUndefined(translate) && !qjs::JS_IsNull(translate) };
    free(cx, translate);
    free(cx, style);
    slides && !own && !crate::env::current(cx).reduce_motion
}

/// The popup: a view with the dialog's `class` and `style` holding its
/// children (with the dialog's `insets`, borrowed); owned. `slide`: it
/// comes up from the window's bottom edge (the layer fades).
fn popup_part(
    cx: *mut JsContext,
    props: JsValue,
    insets: JsValue,
    slide: bool,
) -> Result<JsValue, JsValue> {
    let popup = dom::create_element(cx, Tag::View)?;
    let result = (|| -> Result<(), JsValue> {
        let read = reader(cx, props, "class");
        let r = dom::bind_prop_with(cx, popup, "class", read);
        free(cx, read);
        r?;
        if slide {
            let height = crate::env::current(cx).window.height.0 as f64;
            let offset = crate::animated::new_value(cx, height.max(1.0))?;
            let read = native(cx, slid_style, 0, &mut [props, offset]);
            let r = dom::bind_prop_with(cx, popup, "style", read);
            free(cx, read);
            if r.is_ok() {
                crate::animated::run_timing(cx, offset, 0.0, 320.0, [0.2, 0.8, 0.2, 1.0]);
            }
            free(cx, offset);
            r?;
        } else {
            let read = reader(cx, props, "style");
            let r = dom::bind_prop_with(cx, popup, "style", read);
            free(cx, read);
            r?;
        }
        let children = reader(cx, props, "children");
        let content = with_insets(cx, insets, children);
        free(cx, children);
        // SAFETY: an inline tag check.
        if unsafe { qjs::JS_IsException(content) } {
            return Err(content);
        }
        let r = dom::insert_value_at(cx, popup, content, None);
        free(cx, content);
        r
    })();
    match result {
        Ok(()) => Ok(popup),
        Err(e) => {
            free(cx, popup);
            Err(e)
        }
    }
}

/// The popup's style while it slides: the dialog's `style`, then a
/// `translate` down by the offset, which runs to 0.
unsafe extern "C" fn slid_style(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values (the props, the offset), borrowed; new
    // values owned by the arrays and objects that take them.
    unsafe {
        let (props, offset) = (*data, *data.add(1));
        let mut axes = [qjs::JS_NewFloat64(0.0), qjs::JS_DupValue(cx, offset)];
        let translate = qjs::JS_NewArrayFrom(cx, 2, axes.as_mut_ptr());
        let motion = qjs::JS_NewObject(cx);
        qjs::JS_SetPropertyStr(cx, motion, c"translate".as_ptr(), translate);
        let mut both = [get(cx, props, c"style"), motion];
        qjs::JS_NewArrayFrom(cx, 2, both.as_mut_ptr())
    }
}

/// Whether the app styles a backdrop (`backdropClass` or `backdropStyle`).
unsafe extern "C" fn has_backdrop(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value (the props).
    let props = unsafe { *data };
    let mut has = false;
    for key in [c"backdropClass", c"backdropStyle"] {
        let v = get(cx, props, key);
        // SAFETY: inline checks of a live value.
        has |= unsafe { !qjs::JS_IsUndefined(v) && !qjs::JS_IsNull(v) };
        free(cx, v);
    }
    if has { qjs::JS_TRUE } else { qjs::JS_FALSE }
}

/// The dialog's role for assistive technologies: the app's `role`, else
/// `"dialog"`.
unsafe extern "C" fn dialog_role(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value (the props).
    let props = unsafe { *data };
    let role = get(cx, props, c"role");
    // SAFETY: an inline check of a live value.
    if unsafe { qjs::JS_IsUndefined(role) || qjs::JS_IsNull(role) } {
        free(cx, role);
        // SAFETY: a new string the caller takes.
        return unsafe { qjs::JS_NewStringLen(cx, c"dialog".as_ptr(), 6) };
    }
    role
}

/// The backdrop: a view filling the dialog behind the popup, with the
/// app's `backdropClass` and `backdropStyle` and no look of its own; a
/// press on it is a close attempt (`"backdropPress"`).
unsafe extern "C" fn backdrop_part(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: three data values (props, state, tick).
    let props = unsafe { *data };
    let view = match dom::create_element(cx, Tag::View) {
        Ok(view) => view,
        Err(e) => return e,
    };
    let result = (|| -> Result<(), JsValue> {
        let class = native(cx, backdrop_class, 0, &mut [props]);
        let r = dom::bind_prop_with(cx, view, "class", class);
        free(cx, class);
        r?;
        let style = reader(cx, props, "backdropStyle");
        let r = dom::bind_prop_with(cx, view, "style", style);
        free(cx, style);
        r?;
        let test_id = reader(cx, props, "backdropTestID");
        let r = dom::bind_prop_with(cx, view, "testID", test_id);
        free(cx, test_id);
        r?;
        // SAFETY: the three data values, which the function keeps dups of.
        let press = native(cx, backdrop_press, 0, unsafe {
            std::slice::from_raw_parts_mut(data, 3)
        });
        let r = dom::set_prop_value(cx, view, "onPress", press);
        free(cx, press);
        r?;
        // Its presses are the pointer's: no stop of Tab, which would hold
        // the dialog's focus where Return closes it.
        dom::set_prop_value(cx, view, "focusable", qjs::JS_FALSE)
    })();
    match result {
        Ok(()) => view,
        Err(e) => {
            free(cx, view);
            e
        }
    }
}

/// The backdrop's classes: filling the dialog, then the app's.
unsafe extern "C" fn backdrop_class(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: one data value (the props).
    let v = get(cx, unsafe { *data }, c"backdropClass");
    // SAFETY: an inline tag check.
    let own = if unsafe { qjs::JS_IsString(v) } {
        dom::string_arg(cx, v).unwrap_or_default()
    } else {
        String::new()
    };
    free(cx, v);
    let class = format!("absolute inset-0 {own}");
    // SAFETY: a new string.
    unsafe { qjs::JS_NewStringLen(cx, class.as_ptr().cast(), class.len() as _) }
}

unsafe extern "C" fn backdrop_press(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: three data values (props, state, tick).
    let (props, state, tick) = unsafe { (*data, *data.add(1), *data.add(2)) };
    close_attempt(cx, props, state, tick, "backdropPress")
}

/// The platform reports that the user tried to close a dialog natively
/// (payload: `reason`).
unsafe extern "C" fn on_cancel(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: three data values (props, state, tick); the event is
    // borrowed.
    let (props, state, tick) = unsafe { (*data, *data.add(1), *data.add(2)) };
    let e = arg(argc, argv, 0);
    let value = get(cx, e, c"reason");
    // SAFETY: an inline tag check.
    let reason = if unsafe { qjs::JS_IsString(value) } {
        dom::string_arg(cx, value).unwrap_or_default()
    } else {
        String::new()
    };
    free(cx, value);
    let reason = match reason.as_str() {
        "backdropPress" => "backdropPress",
        "swipe" => "swipe",
        _ => "cancel",
    };
    close_attempt(cx, props, state, tick, reason)
}

/// The user tried to close a dialog: `onCancel`, then, when the
/// `closeOn*` flag of what they did lets it close, `onOpenChange({ open:
/// false, reason })` and the dialog closes (a platform that closed it natively
/// already reports `onClose`; otherwise removing it does).
fn close_attempt(
    cx: *mut JsContext,
    props: JsValue,
    state: JsValue,
    tick: JsValue,
    reason: &str,
) -> JsValue {
    let flag: &CStr = match reason {
        "backdropPress" => c"closeOnBackdropPress",
        "swipe" => c"closeOnSwipe",
        _ => c"closeOnEscape",
    };
    let call = |key: &CStr, args: &mut [JsValue]| -> JsValue {
        let f = get(cx, props, key);
        // SAFETY: a call of the app's function with borrowed arguments.
        let r = unsafe {
            if qjs::JS_IsFunction(cx, f) {
                qjs::JS_Call(cx, f, UNDEFINED, args.len() as c_int, args.as_mut_ptr())
            } else {
                UNDEFINED
            }
        };
        free(cx, f);
        r
    };
    let r = call(c"onCancel", &mut []);
    // SAFETY: an inline tag check.
    if unsafe { qjs::JS_IsException(r) } {
        return r;
    }
    free(cx, r);
    let closes = get(cx, props, flag);
    // SAFETY: an inline check of a live value.
    let kept = unsafe { qjs::JS_IsBool(closes) && !qjs::JS_VALUE_GET_BOOL(closes) };
    free(cx, closes);
    if kept || closed_by_user(cx, state) {
        return UNDEFINED;
    }
    reactive::batch_with(cx, || {
        // One object, as every event (`api-naming.md` "Payloads").
        // SAFETY: a new object owning a new string (`JS_SetPropertyStr`
        // takes it), freed after the call.
        let event = unsafe {
            let event = qjs::JS_NewObject(cx);
            qjs::JS_SetPropertyStr(cx, event, c"open".as_ptr(), qjs::JS_FALSE);
            let reason = qjs::JS_NewStringLen(cx, reason.as_ptr().cast(), reason.len() as _);
            qjs::JS_SetPropertyStr(cx, event, c"reason".as_ptr(), reason);
            event
        };
        let r = call(c"onOpenChange", &mut [event]);
        free(cx, event);
        // SAFETY: an inline tag check.
        if unsafe { qjs::JS_IsException(r) } {
            return r;
        }
        free(cx, r);
        // Closed whether or not the app keeps `open` in sync.
        set_closed_by_user(cx, state, true);
        let n = reactive::peek_number(cx, tick).unwrap_or(0.0);
        reactive::set_signal(cx, tick, qjs::JS_NewFloat64(n + 1.0));
        reactive::finish_value(cx, UNDEFINED)
    })
}