nsh-core 0.5.1

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
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
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
//! The host elements beyond views, texts and images: inputs, scroll views,
//! navigation stacks and their screens, modals, canvases, web views, videos
//! and the embedder's native components, with their props and typed events. Their props are the
//! core's [`Prop`]s, kept per element and diffed by kind: a prop an
//! element's binding (or a region's element made again) no longer sets
//! goes back to its default, as when JS clears it.

use std::sync::Arc;

use super::{
    Accessible, AnyElement, Interactive, IntoReactive,
    builder::{ElNode, Element, IntoElement, IntoListener, Listener, ParentElement},
    events::{
        self, CaretEvent, Composition, HintReason, NativeEvent, OverlayPosition, Selection,
        VideoInfo, VideoProgress, WebNavigation,
    },
};
use crate::{
    AudioSession, AutoCapitalize, AutoFill, Color, EventKind, HeaderSlot, Hsla, JsonValue,
    KeyboardAppearance, KeyboardType, ModalAnimation, ModalPresentation, ModalProp, NativeProp,
    OverlayProp, PasteBehavior, PasteEvent, Points, Prop, ResizeMode, ReturnKeyType, Rgba,
    ScreenAnimation, ScreenProp, ScrollProp, Size, StatusBarSetting, SubmitBehavior, Tag,
    WebSource,
    canvas::{
        CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
        Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp, ViewPaint,
    },
    geometry::{Bounds, Corners, Percentage, Point, Radians, ScaledPixels},
    js::host::HostProps,
    overlay::{Align, OverlayAnchor, Placement},
    style::SvgPaint,
};

/// Whether `a` and `b` set the same property (their values aside).
pub(crate) fn same_kind(a: &Prop, b: &Prop) -> bool {
    match (a, b) {
        (Prop::ComponentProp(a, _), Prop::ComponentProp(b, _)) => a == b,
        (Prop::ComponentPropBinding(a, _), Prop::ComponentPropBinding(b, _)) => a == b,
        (Prop::RustProp(a, _), Prop::RustProp(b, _)) => a == b,
        _ => HostProps::same_kind(a, b),
    }
}

/// `prop`'s property at its default (what clearing it from JS sets), for
/// the props elements set; `None` for those set once.
pub(crate) fn reset(prop: &Prop) -> Option<Prop> {
    match prop {
        Prop::ComponentProp(name, _) => Some(Prop::ComponentProp(name.clone(), None)),
        Prop::ComponentPropBinding(name, _) => Some(Prop::ComponentPropBinding(name.clone(), None)),
        Prop::RustProp(name, _) => Some(Prop::RustProp(name, None)),
        _ => HostProps::reset(prop),
    }
}

/// Sets `prop` on `node`, replacing the value of the same property.
pub(crate) fn set(node: &mut ElNode, prop: Prop) {
    set_in(&mut node.attrs.props, prop);
}

crate::static_reactive!(Color: Color);
crate::static_reactive!(Hsla: Hsla, Rgba, Color);
crate::static_reactive!(crate::AccessibilityRole: crate::AccessibilityRole);
crate::static_reactive!(AutoCapitalize: AutoCapitalize);
crate::static_reactive!(AutoFill: AutoFill);
crate::static_reactive!(crate::HeaderSystemItem: crate::HeaderSystemItem);
crate::static_reactive!(KeyboardAppearance: KeyboardAppearance);
crate::static_reactive!(KeyboardType: KeyboardType);
crate::static_reactive!(ModalAnimation: ModalAnimation);
crate::static_reactive!(ModalPresentation: ModalPresentation);
crate::static_reactive!(ResizeMode: ResizeMode);
crate::static_reactive!(ReturnKeyType: ReturnKeyType);
crate::static_reactive!(SubmitBehavior: SubmitBehavior);
crate::static_reactive!(PasteBehavior: PasteBehavior);
crate::static_reactive!(crate::EllipsizeMode: crate::EllipsizeMode);
crate::static_reactive!(JsonValue: JsonValue);
crate::static_reactive!(StatusBarSetting: StatusBarSetting, crate::StatusBarStyle);
crate::static_reactive!(Placement: Placement);
crate::static_reactive!(Align: Align);

/// Sets `prop` among `props`, replacing one of its kind.
pub(crate) fn set_in(props: &mut Vec<Prop>, prop: Prop) {
    match props.iter_mut().find(|p| same_kind(p, &prop)) {
        Some(p) => *p = prop,
        None => props.push(prop),
    }
}

/// Sets the prop `prop` makes of `value`: now when it is static, else as a
/// bound part.
pub(crate) fn bind_prop<T: 'static>(
    node: &mut ElNode,
    value: impl IntoReactive<T>,
    prop: impl Fn(T) -> Prop + 'static,
) {
    node.bind_attr(value, move |attrs, v| set_in(&mut attrs.props, prop(v)));
}

/// Adds a typed listener of `kind`.
fn listen<T: ?Sized + ToOwned + 'static>(
    node: &mut ElNode,
    kind: EventKind,
    listener: Listener<T>,
    decode: events::Decode<T>,
) {
    node.handlers.push((kind, events::typed(listener, decode)));
}

macro_rules! host_element {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        #[derive(Clone)]
        pub struct $name(ElNode);

        impl Element for $name {
            fn node(&mut self) -> &mut ElNode {
                &mut self.0
            }
        }

        impl IntoElement for $name {
            fn into_element(self) -> AnyElement {
                AnyElement(self.0)
            }
        }

        impl Accessible for $name {}
        impl Interactive for $name {}

        impl super::builder::IntoTooltip for $name {
            fn apply_tooltip(self, node: &mut ElNode) {
                self.into_element().apply_tooltip(node);
            }
        }

        // Not every element has props of its own and events.
        #[allow(dead_code)]
        impl $name {
            fn set(mut self, prop: Prop) -> Self {
                set(&mut self.0, prop);
                self
            }

            fn bind_prop<T: 'static>(
                mut self,
                value: impl IntoReactive<T>,
                prop: impl Fn(T) -> Prop + 'static,
            ) -> Self {
                bind_prop(&mut self.0, value, prop);
                self
            }

            fn listen<T: ?Sized + ToOwned + 'static>(
                mut self,
                kind: EventKind,
                listener: Listener<T>,
                decode: events::Decode<T>,
            ) -> Self {
                listen(&mut self.0, kind, listener, decode);
                self
            }
        }
    };
}

host_element! {
    /// A text field (`<input>`), made by [`input`]: one line, or several
    /// with [`Input::multiline`]. Its text style comes from its styles.
    Input
}

host_element! {
    /// A scroll view (`<scroll>`), made by [`scroll`]: its children are its
    /// content.
    Scroll
}

host_element! {
    /// A native navigation stack (`<stack>`, TS: `NavStack` of `nsh/base`),
    /// made by `nsh_base::nav_stack`:
    /// UINavigationController on iOS (swipe back, native header), a stack
    /// with a toolbar and predictive back on Android. Its children are its
    /// [`Screen`]s, bottom to top.
    Stack
}

host_element! {
    /// One page of a [`Stack`] (`<screen>`, TS: `NavPage` of `nsh/base`),
    /// made by `nsh_base::nav_page`: its header options and its content (its
    /// children).
    Screen
}

host_element! {
    /// A dialog (`<modal>`, TS: `Dialog` of `nsh/base`), made by
    /// `nsh_base::dialog`: presented while it is in the view, over everything
    /// else; its children are its content.
    Modal
}

host_element! {
    /// A bar over the keyboard (`<inputaccessory>`, TS: `InputAccessoryView`
    /// of `nsh/ios`), made by [`input_accessory_view`]: its children are its
    /// content.
    InputAccessoryView
}

host_element! {
    /// A view drawn with a [`Drawing`] (`<canvas>`), made by [`canvas`].
    CanvasView
}

host_element! {
    /// An SVG drawn as authored, made by [`svg`].
    Svg
}

host_element! {
    /// A view whose box a shader draws under its children (`<shader>`, TS:
    /// `Shader` of `nsh`), made by [`shader`] ([`crate::shader`]).
    ShaderView
}

host_element! {
    /// A web page (`<webview>`), made by [`web_view`].
    WebView
}

host_element! {
    /// A video player (`<video>`), made by [`video`].
    Video
}

host_element! {
    /// A native component the embedding app registered (`<native>`), made
    /// by [`native`].
    NativeView
}

host_element! {
    /// Its children on top of the root view it is in (`<overlay>`, TS:
    /// `Overlay` of `nsh`), made by [`overlay`]: the surface, or the dialog
    /// around it; outside its parent's layout and clipping, while it stays
    /// where it is for everything else (context, events, lifetime).
    Overlay
}

impl ParentElement for Overlay {}
impl ParentElement for ShaderView {}
impl ParentElement for Scroll {}
impl ParentElement for Stack {}
impl ParentElement for Screen {}
impl ParentElement for Modal {}

/// Android has no input accessories: there the bar keeps no content.
impl ParentElement for InputAccessoryView {
    fn child<M>(mut self, child: impl super::IntoChild<M>) -> Self {
        if !cfg!(target_os = "android") {
            child.__push_into(&mut self.0.children);
        }
        self
    }

    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
        if !cfg!(target_os = "android") {
            self.0
                .children
                .extend(children.into_iter().map(|c| c.into_element().0));
        }
        self
    }
}

/// An overlay: its children shown on top of the root view it is in (the
/// surface, or the dialog around it), above what that root view shows and
/// the overlays shown before it, while it is in the view (in a region:
/// [`super::If`]). Without an anchor it is laid out as a `position: fixed`
/// box of the root view (`.absolute().inset_0()` covers it); with one
/// ([`Overlay::anchor`], [`Overlay::anchor_point`]) it goes on a side of it
/// and follows it ([`crate::overlay`]).
pub fn overlay() -> Overlay {
    Overlay(ElNode::new(Tag::Overlay))
}

/// A text field.
pub fn input() -> Input {
    Input(ElNode::new(Tag::Input))
}

/// A vertical scroll view ([`Scroll::horizontal`] for a horizontal one).
pub fn scroll() -> Scroll {
    Scroll(ElNode::new(Tag::Scroll))
}

/// A native navigation stack of [`screen`]s: put a screen in to push it,
/// leave it out to pop it. Give each screen a [`Element::key`] (its route)
/// so the screens below keep their state.
///
/// The core's part of `nsh_base::nav_stack`, which apps use.
#[doc(hidden)]
pub fn stack() -> Stack {
    Stack(ElNode::new(Tag::Stack))
}

/// A screen of a [`stack`]. What it shows reads its insets below the
/// header ([`super::Scope::insets`]).
///
/// The core's part of `nsh_base::nav_page`, which apps use.
#[doc(hidden)]
pub fn screen() -> Screen {
    let mut node = ElNode::new(Tag::Screen);
    // Its insets come with this event.
    node.handlers.push((EventKind::Insets, Listener::noop()));
    Screen(node)
}

/// A modal presenting its children. Put it in the view to present it (in
/// a region: [`super::If`]), leave it out to dismiss it.
///
/// The core's part of `nsh_base::dialog`, which apps use.
#[doc(hidden)]
pub fn modal() -> Modal {
    let mut node = ElNode::new(Tag::Modal);
    // Its insets (`Scope::insets` inside it) come with this event.
    node.handlers.push((EventKind::Insets, Listener::noop()));
    Modal(node)
}

/// A bar shown over the keyboard of the inputs whose
/// [`Input::input_accessory`] is `native_id` (iOS's `inputAccessoryView`):
/// as wide as the window and as tall as its content, moving with the
/// keyboard natively. It takes no room where the view places it; on
/// Android, which has no input accessories, it is an empty hidden view.
pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
    let tag = if cfg!(target_os = "android") {
        Tag::View
    } else {
        Tag::InputAccessory
    };
    let mut node = ElNode::new(tag);
    if cfg!(target_os = "android") {
        node.style.value(
            crate::StyleKey::Display,
            crate::PropertyValue::Display(taffy::Display::None),
        );
    } else {
        set(&mut node, Prop::NativeId(Some(native_id.into())));
    }
    InputAccessoryView(node)
}

/// A canvas showing what `painter` recorded (animated values in it move
/// natively). A closure draws in a binding: `canvas(move || draw(theme()))`
/// draws again when what it read changes (a size kept from `on_layout`,
/// the appearance).
pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
    let mut node = ElNode::new(Tag::Canvas);
    node.bind_attr(painter, |attrs, painter: Painter| {
        attrs.drawing = Some(Arc::new(painter.drawing));
        attrs.bound = painter.nodes;
    });
    CanvasView(node)
}

crate::static_reactive!(Painter: Painter, Drawing);

/// An SVG image drawn as authored, in its own colors, as an `<svg>` written
/// inline in a web page draws: `svg(asset!("logo.svg"))`, a URL, a file or
/// the markup itself (`svg(ImageSrc::svg_markup(include_str!("logo.svg")))`).
/// Its `currentColor` is the element's text color (`color`, inherited), so
/// an icon drawn with `stroke="currentColor"` follows the theme and the
/// app's `text-*` classes. It lays out at the SVG's `width` and `height`
/// (else its `viewBox`'s size) where its style sets no size, keeping that
/// aspect ratio where it sets one side, as an image does; its `viewBox`
/// is fitted into the box it gets as its `preserveAspectRatio` says.
///
/// On the native backends it is a canvas of the SVG's shapes, which the
/// platform draws at its device pixels: sharp at every size and scale. Its
/// bytes load as an image's do (the shared loader and its caches); the
/// drawing is parsed once per source and kept in the decoded images'
/// budget (`docs/dev/images.md`), leased while an element shows it. Inline
/// markup and a drawing in memory show in the first frame; others when
/// they load. A source that cannot be drawn draws nothing (logged). The
/// web runtime shows it as an image the browser draws, with its
/// `currentColor` written out as the element's text color.
pub fn svg(src: impl IntoReactive<super::ImageSrc>) -> Svg {
    #[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
    {
        let mut node = ElNode::new(Tag::Canvas);
        let shown = svg_drawing(src);
        node.bind_attr(
            move || shown.get(),
            |attrs, drawing| attrs.drawing = drawing,
        );
        Svg(node)
    }
    #[cfg(not(all(feature = "svg", not(target_arch = "wasm32"))))]
    {
        let mut node = ElNode::new(Tag::Image);
        node.style.value(
            crate::StyleKey::ObjectFit,
            crate::PropertyValue::ObjectFit(Some(ResizeMode::Contain)),
        );
        node.bind_attr(src, |attrs, src| attrs.src = Some(src));
        // The platform draws it: its `currentColor` is the text color.
        set(
            &mut node,
            Prop::Image(crate::ImageProp::SvgCurrentColor(true)),
        );
        Svg(node)
    }
}

/// The drawing an [`svg`] of `src` shows: here and now when its bytes are
/// in hand (inline markup) or it is in memory, else once it loads. A
/// source that changes drops the load running and the lease of the
/// drawing shown.
#[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
fn svg_drawing(
    src: impl IntoReactive<super::ImageSrc>,
) -> super::reactive::Signal<Option<Arc<Drawing>>> {
    use super::reactive::{SignalEquals, render_effect, signal_with, stored, untracked};
    let src = src.into_reactive();
    let shown = signal_with(None::<Arc<Drawing>>, SignalEquals::Never);
    let lease = stored(crate::image::Lease::none());
    let task = stored(None::<super::Spawned<()>>);
    render_effect(move || {
        let src = match &src {
            super::Reactive::Static(src) => src.clone(),
            super::Reactive::Bound(f) => f(),
        };
        untracked(|| {
            drop(task.replace(None));
            let context = crate::image::loader::context();
            let source = crate::ImageSource {
                uri: src.uri.as_str().into(),
                size: None,
                scales: crate::ImageScales::NONE,
                data: None,
            }
            .inline();
            let Some(location) = context.locate(&source) else {
                log::warn!("svg: unsupported source `{}`", source.uri);
                shown.set(None);
                lease.replace(crate::image::Lease::none());
                return;
            };
            if let Some((drawing, held)) = crate::svg::drawings::now(&location) {
                shown.set(Some(drawing));
                lease.replace(held);
                return;
            }
            let load = crate::svg::drawings::load(location, context);
            task.replace(Some(super::spawn(async move {
                let (drawing, held) = load.await;
                shown.set(Some(drawing));
                lease.replace(held);
            })));
        });
    });
    shown
}

/// A view whose box a shader draws, under its children: give it the
/// program with [`ShaderView::source`] and its uniforms with
/// [`ShaderView::uniform`]. Without a program it draws nothing of its own.
pub fn shader() -> ShaderView {
    ShaderView(ElNode::new(Tag::Shader))
}

/// A view whose children draw through a shader: give it the program with
/// [`ShaderView::source`], which reads what they draw with
/// `sample_content`. Without a program the children draw as they are.
pub fn shader_effect() -> ShaderView {
    ShaderView(ElNode::new(Tag::ShaderEffect))
}

/// A view whose children change through a shader when its
/// [`ShaderView::value`] changes: `sample_from` is a picture of what they
/// drew, `sample_to` what they draw now, `nsh.progress` how far it is.
/// Without a program it cross-fades ([`ShaderView::fallback`]).
pub fn shader_transition() -> ShaderView {
    ShaderView(ElNode::new(Tag::ShaderTransition))
}

/// The whole surface drawn through a shader, which reads it with
/// `sample_content`. It takes no space and has no children.
pub fn screen_effect() -> ShaderView {
    ShaderView(ElNode::new(Tag::ScreenEffect))
}

/// The whole surface changing through a shader when its
/// [`ShaderView::value`] changes, as [`shader_transition`] does for its
/// children. It takes no space and has no children.
pub fn screen_transition() -> ShaderView {
    ShaderView(ElNode::new(Tag::ScreenTransition))
}

crate::static_reactive!(crate::shader::Shader: crate::shader::Shader);

/// A value [`ShaderView::uniform`] takes ([`IntoUniform`]).
pub struct Uniform(UniformSource);

enum UniformSource {
    Value(super::Reactive<crate::shader::UniformValue>),
    Animated(super::AnimatedNode),
}

/// What [`ShaderView::uniform`] takes: a number, a color or a list, bound
/// or not, or an animated value (`&AnimatedValue`, `&AnimatedNode`).
pub trait IntoUniform {
    /// As a [`Uniform`].
    fn into_uniform(self) -> Uniform;
}

impl<T: IntoReactive<crate::shader::UniformValue>> IntoUniform for T {
    fn into_uniform(self) -> Uniform {
        Uniform(UniformSource::Value(self.into_reactive()))
    }
}

impl IntoUniform for &super::AnimatedValue {
    fn into_uniform(self) -> Uniform {
        Uniform(UniformSource::Animated(super::Animated::animated_node(
            self,
        )))
    }
}

impl IntoUniform for &super::AnimatedNode {
    fn into_uniform(self) -> Uniform {
        Uniform(UniformSource::Animated(*self))
    }
}
crate::static_reactive!(
    crate::shader::UniformValue: crate::shader::UniformValue,
    f32,
    i32,
    Color,
    Hsla,
    [f32; 2],
    [f32; 3],
    [f32; 4],
    Vec<crate::shader::UniformValue>
);

impl ShaderView {
    /// The program that draws its box, compiled once with
    /// [`Shader::compile`](crate::shader::Shader::compile) (a bound one
    /// draws the new program when it changes).
    pub fn source(self, shader: impl IntoReactive<crate::shader::Shader>) -> Self {
        self.bind_prop(shader, |s| Prop::Shader(Some(s)))
    }

    /// Sets the member `name` of the shader's `struct Uniforms` to `value`
    /// ([`IntoUniform`]): a number, a color or a list (a vector, an array of
    /// `vec4f`), which a bound value (`move || …`) sets again when it
    /// changes; or an animated value (`&wave`, a number, or colors for a
    /// `vec3f` / `vec4f`), which the platform writes on every frame it
    /// changes, without the engine (one whose owner is gone counts as 0).
    pub fn uniform(mut self, name: &str, value: impl IntoUniform) -> Self {
        let name: Arc<str> = name.into();
        let value = match value.into_uniform().0 {
            UniformSource::Value(value) => value,
            UniformSource::Animated(node) => {
                let value = match node.live() {
                    Some(node) => {
                        let id = node.id();
                        self.0.attrs.bound.push(node);
                        crate::shader::UniformValue::Animated(id)
                    }
                    None => crate::shader::UniformValue::Number(0.0),
                };
                super::Reactive::Static(value)
            }
        };
        self.0.bind_attr(value, move |attrs, value| {
            let mut uniforms = attrs
                .props
                .iter()
                .find_map(|p| match p {
                    Prop::Uniforms(u) => Some(u.clone()),
                    _ => None,
                })
                .unwrap_or_default();
            match uniforms.0.iter_mut().find(|(n, _)| *n == name) {
                Some(entry) => entry.1 = value,
                None => uniforms.0.push((name.clone(), value)),
            }
            set_in(&mut attrs.props, Prop::Uniforms(uniforms));
        });
        self
    }

    /// Stops its clock (`nsh.time` keeps its value), or starts it again.
    pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
        self.bind_prop(paused, Prop::ShaderPaused)
    }

    /// An effect's `nsh.progress`, a fraction (a bound one sets it again
    /// when it changes).
    pub fn progress(self, progress: impl IntoReactive<Percentage>) -> Self {
        self.bind_prop(progress, |p| {
            Prop::ShaderProgress(crate::shader::ShaderProgress::Number(p))
        })
    }

    /// An effect's `nsh.progress` moved by an animated value, which the
    /// platform writes on every frame it changes, without the engine.
    pub fn animated_progress(mut self, value: &impl super::Animated) -> Self {
        let progress = match value.animated_node().live() {
            Some(node) => {
                let id = node.id();
                self.0.attrs.bound.push(node);
                crate::shader::ShaderProgress::Animated(id)
            }
            None => crate::shader::ShaderProgress::Number(Percentage(0.0)),
        };
        self.set(Prop::ShaderProgress(progress))
    }

    /// How far beyond its box, in points, an effect or a transition draws
    /// and its pictures reach (`maxSampleOffset`).
    pub fn max_sample_offset(self, offset: Points) -> Self {
        self.set(Prop::MaxSampleOffset(offset))
    }

    /// A transition's value: when it changes, the transition runs (not for
    /// the first one).
    pub fn value(self, value: impl IntoReactive<crate::shader::TransitionKey>) -> Self {
        self.bind_prop(value, |v| Prop::TransitionValue(Some(v)))
    }

    /// How long a transition runs (300 ms by default).
    pub fn duration(self, duration: std::time::Duration) -> Self {
        self.set(Prop::TransitionDuration(Some(
            duration.as_secs_f32() * 1000.0,
        )))
    }

    /// What a transition without a program runs: a cross-fade (the
    /// default) or nothing.
    pub fn fallback(self, fallback: crate::TransitionFallback) -> Self {
        self.set(Prop::TransitionFallback(fallback))
    }
}

crate::static_reactive!(crate::shader::TransitionKey: crate::shader::TransitionKey);

/// A web view loading `url` (a bound one loads again when it changes).
pub fn web_view(url: impl IntoReactive<String>) -> WebView {
    WebView(ElNode::new(Tag::WebView)).bind_prop(url, |url: String| {
        Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
    })
}

/// A web view showing the page `html`, its relative links resolved against
/// `base_url` (TS: `html` and `baseUrl`).
pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
    WebView(ElNode::new(Tag::WebView)).html(html, base_url)
}

/// A video playing the file or stream at `url` (a bound one plays the new
/// one when it changes).
pub fn video(url: impl IntoReactive<String>) -> Video {
    Video(ElNode::new(Tag::Video)).bind_prop(url, |url: String| {
        Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
    })
}

/// The embedder's native component registered as `name`.
pub fn native(name: &str) -> NativeView {
    NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
}

impl Input {
    /// The text, when the component controls it (update it from
    /// [`Self::on_change`]).
    pub fn value(self, text: impl IntoReactive<String>) -> Self {
        self.bind_prop(text, |text: String| Prop::Value(text))
    }

    /// The first text, when the input keeps its own.
    pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
        self.bind_prop(text, |text: String| Prop::DefaultValue(text))
    }

    /// Shown while it is empty.
    pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
        self.bind_prop(text, |text: String| Prop::Placeholder(text))
    }

    /// The placeholder's color (`cx.color(theme.muted_foreground)`).
    pub fn placeholder_color(self, color: impl IntoReactive<Hsla>) -> Self {
        self.bind_prop(color, |color: Hsla| {
            Prop::PlaceholderColor(Some(color.into()))
        })
    }

    /// The selection highlight's color (on iOS also the caret's, unless
    /// [`Self::caret_color`] is set: UIKit tints both with one).
    pub fn selection_color(self, color: impl IntoReactive<Hsla>) -> Self {
        self.bind_prop(color, |color: Hsla| {
            Prop::SelectionColor(Some(color.into()))
        })
    }

    /// The caret's color.
    pub fn caret_color(self, color: impl IntoReactive<Hsla>) -> Self {
        self.bind_prop(color, |color: Hsla| Prop::CaretColor(Some(color.into())))
    }

    /// Hides what is typed (passwords; TS: `masked`).
    pub fn masked(self, secure: impl IntoReactive<bool>) -> Self {
        self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
    }

    /// The software keyboard's layout.
    pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
        self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
    }

    /// The software keyboard's light or dark look (iOS; TS:
    /// `ios={{ keyboardAppearance }}`).
    pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
        self.bind_prop(appearance, |appearance: KeyboardAppearance| {
            Prop::KeyboardAppearance(appearance)
        })
    }

    /// The return key's label.
    pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
        self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
    }

    /// Automatic capitals.
    pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
        self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
    }

    /// The system's corrections (default on): spelling and, on iOS and
    /// macOS, smart quotes, dashes and text replacement.
    pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
        self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
    }

    /// What it holds, for autofill and suggestions.
    pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
        self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
    }

    /// Several lines, growing with the text (return adds a line).
    pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
        self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
    }

    /// Whether a multiline input's scroll bar shows (default yes): the
    /// platform's indicator, or the app's built-in bar once it set one.
    pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
        self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
    }

    /// At most `length` characters.
    pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
        self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
    }

    /// The text can be selected and copied but not changed.
    pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
        self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
    }

    /// What return does (`submitBehavior`; default: submit and unfocus for
    /// one line, a line break for several).
    pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
        self.bind_prop(behavior, |behavior: SubmitBehavior| {
            Prop::SubmitBehavior(Some(behavior))
        })
    }

    /// What a paste does (`pasteBehavior`; default: insert its text).
    /// [`Self::on_paste`] hears what was pasted either way.
    pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
        self.bind_prop(behavior, Prop::PasteBehavior)
    }

    /// The user pasted: the text, the files with their bytes (a
    /// screenshot) and local files' URLs, before the text it inserts is
    /// reported.
    pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
        self.listen(EventKind::Paste, listener.into_listener(), events::paste)
    }

    /// Focused when it appears.
    pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
        self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
    }

    /// The caret is drawn (default yes; TS: `caret`).
    pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
        self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
    }

    /// Shows the input accessory with this `nativeID` over the keyboard
    /// ([`input_accessory_view`]; iOS).
    pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
        self.bind_prop(native_id, |id: String| {
            Prop::InputAccessoryViewId(Some(id.into()))
        })
    }

    /// Selects `(start, end)` (UTF-16 units; a caret when equal) when the
    /// input is made and whenever the value changes (TS: the controlled
    /// `selectedRange`); the user moves it on from there
    /// ([`Self::on_selection_change`]).
    pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
        self.bind_prop(range, |(start, end): (u32, u32)| {
            Prop::Selection(start, end)
        })
    }

    /// The text changed (the new text).
    pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
        self.listen(
            EventKind::ChangeText,
            listener.into_listener(),
            events::text,
        )
    }

    /// The return (enter) key was pressed (the text).
    pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
        self.listen(
            EventKind::SubmitEditing,
            listener.into_listener(),
            events::text,
        )
    }

    /// The selection or caret moved.
    pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
        self.listen(
            EventKind::SelectionChange,
            listener.into_listener(),
            events::selection,
        )
    }

    /// The caret moved: with the selection, or as the text scrolled or
    /// wrapped again ([`CaretEvent`]: where it is, in the input and in the
    /// root view).
    pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
        self.listen(
            EventKind::CaretMove,
            listener.into_listener(),
            events::caret,
        )
    }

    /// A key was pressed: the character, `Backspace` or `Enter`.
    pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
        self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
    }

    /// An input method's composition started, changed or ended (the text
    /// being composed, empty once it ends): the text is the input's only
    /// once committed, reported by [`Self::on_change`] first.
    pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
        self.listen(
            EventKind::CompositionChange,
            listener.into_listener(),
            events::composition,
        )
    }

    /// The text's size changed (multiline inputs growing).
    pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
        self.listen(
            EventKind::ContentSizeChange,
            listener.into_listener(),
            events::size,
        )
    }
}

impl Scroll {
    /// Scrolls horizontally.
    pub fn horizontal(self) -> Self {
        self.set(Prop::Horizontal(true))
    }

    /// Whether the scroll indicator shows (default yes).
    pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
        self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
    }

    /// Pinch zoom between `min` and `max`.
    pub fn zoom_range(self, min: f32, max: f32) -> Self {
        self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
            .set(Prop::Scroll(ScrollProp::MaxZoom(max)))
    }

    /// The zoom.
    pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
        self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
    }

    /// Pinches may go past the zoom limits and spring back (default yes;
    /// TS: `bouncesZoom`).
    pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
        self.bind_prop(bounces, |bounces: bool| {
            Prop::Scroll(ScrollProp::BouncesZoom(bounces))
        })
    }

    /// The user can pinch to zoom (default yes; TS: `zoomable`).
    pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
        self.bind_prop(enabled, |enabled: bool| {
            Prop::Scroll(ScrollProp::Pinch(enabled))
        })
    }

    /// Content smaller than the view sits in its center (zoomed images).
    pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
        self.bind_prop(center, |center: bool| {
            Prop::Scroll(ScrollProp::CenterContent(center))
        })
    }
}

impl super::Scrollable for Scroll {}

impl Screen {
    fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
        let mut node = ElNode::new(Tag::HeaderItem);
        node.key = Some(key.into());
        set(&mut node, Prop::HeaderSlot(slot));
        node.children.push(item.into_element().0);
        self.0.children.push(node);
        self
    }

    /// The header's title.
    pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
        self.bind_prop(title, |t| {
            Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
        })
    }

    /// Whether the header shows (default true).
    pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
        self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
    }

    /// Whether the system tab bar leaves while this page is on top (default
    /// false), moving with the transition (iOS and Android).
    pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
        self.bind_prop(hides, |v| {
            Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
        })
    }

    /// A large title (iOS); the content scrolls under the header.
    pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
        self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
    }

    /// The content extends under the header.
    pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
        self.bind_prop(transparent, |v| {
            Prop::Screen(ScreenProp::HeaderTransparent(v))
        })
    }

    /// The header's colors: `backgroundColor`, `color` (the title's) and
    /// `tintColor` (the buttons'), as [`super::Style::from_decls`] makes
    /// them (TS: `headerStyle`); a style of typed styles applies as
    /// [`Self::header_style_with`]'s do.
    pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
        let style = match style.into_reactive() {
            // Its bound parts are read in the binding, which follows them.
            super::Reactive::Static(s) if s.1.is_bound() => {
                super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
            }
            style => style,
        };
        self.0.bind_attr(style, |a, s: super::Style| {
            set_in(&mut a.props, Prop::HeaderStyle(s.0));
            if !s.1.is_empty() {
                let typed = s.1.resolved();
                let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
                set_in(&mut a.props, Prop::HeaderClassList(list));
            }
        });
        self
    }

    /// The header's colors as typed styles: the background
    /// ([`super::Styled::bg`]), the title's color
    /// ([`super::Styled::text_color`]) and the buttons'
    /// ([`super::Styled::tint_color`]), theme colors following the
    /// appearance natively (TS: `headerClass`). `f` runs again when what it
    /// reads changes. [`Self::header_style`] wins over it, key by key.
    pub fn header_style_with(
        self,
        f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
    ) -> Self {
        let list = move || {
            let style = f(super::StyleRefinement::default()).resolved();
            (!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
        };
        self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
            Prop::HeaderClassList(list)
        })
    }

    /// The label of the back button leading back to this screen (iOS).
    pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
        self.bind_prop(title, |t| {
            Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
        })
    }

    /// The trailing header button is UIKit's own, drawn instead of the
    /// `header_right` view (iOS; a press on it presses that view's first
    /// pressable view).
    pub fn header_right_system_item(
        self,
        item: impl IntoReactive<crate::HeaderSystemItem>,
    ) -> Self {
        self.bind_prop(item, |item| {
            Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
        })
    }

    /// The leading header button is UIKit's own, drawn instead of the
    /// `header_left` view (iOS; a press on it presses that view's first
    /// pressable view).
    pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
        self.bind_prop(item, |item| {
            Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
        })
    }

    /// The trailing header button is UIKit's own showing the SF Symbol of
    /// this name, drawn instead of the `header_right` view (iOS; a press on
    /// it presses that view's first pressable view).
    pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
        self.bind_prop(name, |n| {
            Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
        })
    }

    /// The leading header button is UIKit's own showing the SF Symbol of
    /// this name, drawn instead of the `header_left` view (iOS; a press on
    /// it presses that view's first pressable view).
    pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
        self.bind_prop(name, |n| {
            Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
        })
    }

    /// Whether the back button shows (default true).
    pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
        self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
    }

    /// The interactive back gesture pops (iOS swipe back, Android
    /// predictive back); the back buttons pop either way (default true).
    pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
        self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
    }

    /// The back buttons and the swipe back pop the screen (default true);
    /// false keeps it, reporting [`Self::on_back_press`] instead. Decided
    /// natively when the system asks, so set it before the user acts.
    pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
        self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
    }

    /// How the screen enters and leaves.
    pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
        self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
    }

    /// The program it comes and goes through instead of its
    /// [`Self::animation`] (TS: `transitionShader`); `None` (a binding can
    /// go back to it) leaves the change to the animation.
    pub fn transition_shader(
        self,
        shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
    ) -> Self {
        self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
            Prop::TransitionShader(s.map(Into::into))
        })
    }

    /// What the status bar shows while the screen is up (iOS and Android;
    /// TS: `statusBar`): over the screens below it and the app's default,
    /// field by field, as a view controller's `preferredStatusBarStyle`.
    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
    }

    /// An element at the header's start (instead of the back button).
    pub fn header_left(self, item: impl IntoElement) -> Self {
        self.header_item(HeaderSlot::Left, "header-left", item)
    }

    /// An element at the header's end.
    pub fn header_right(self, item: impl IntoElement) -> Self {
        self.header_item(HeaderSlot::Right, "header-right", item)
    }

    /// An element replacing the title.
    pub fn header_title(self, item: impl IntoElement) -> Self {
        self.header_item(HeaderSlot::Title, "header-title", item)
    }

    /// The app's header on platforms without a system header (desktops,
    /// the web): placed at the top of the screen, as wide as it and as tall
    /// as it lays out, with the content below it (TS: `header`).
    pub fn header(self, item: impl IntoElement) -> Self {
        self.header_item(HeaderSlot::Header, "header", item)
    }

    /// The user popped the screen natively (back button, swipe): leave it
    /// out of the view (its region).
    pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
    }

    /// The user pressed back on the screen (every back press, whether or
    /// not [`Self::pop_on_back`] let it pop).
    pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(
            EventKind::BackRequest,
            listener.into_listener(),
            events::unit,
        )
    }
}

impl Overlay {
    /// Places it against the element carrying `anchor` (rendered before
    /// it), following it as it moves: on the [`Self::placement`] side, on
    /// the other when only that one has room, kept inside the safe area.
    pub fn anchor(self, anchor: &super::ElementRef) -> Self {
        let anchor = *anchor;
        self.bind_prop(
            move || match anchor.node() {
                Some(id) => OverlayAnchor::Node(id),
                None => OverlayAnchor::None,
            },
            |a| Prop::Overlay(OverlayProp::Anchor(a)),
        )
    }

    /// Lays the element carrying `cover`, inside it, over its anchor (a
    /// select's selected item over the trigger) instead of placing it on
    /// a side ([`crate::overlay::OverlayConfig::cover`]). A ref is not
    /// tracked: `shown` (tracked) says when that element is rendered, as
    /// its `on_layout` can tell.
    pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
        let cover = *cover;
        self.bind_prop(
            move || if shown() { cover.node() } else { None },
            |id| Prop::Overlay(OverlayProp::Cover(id)),
        )
    }

    /// Places it beside the element carrying `anchor`, outside the edges
    /// of the one carrying `edges` (the menu around it), as a submenu
    /// beside its row ([`OverlayAnchor::Beside`]).
    pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
        let (anchor, edges) = (*anchor, *edges);
        self.bind_prop(
            move || match (anchor.node(), edges.node()) {
                (Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
                (Some(id), None) => OverlayAnchor::Node(id),
                _ => OverlayAnchor::None,
            },
            |a| Prop::Overlay(OverlayProp::Anchor(a)),
        )
    }

    /// Places it against what the element carrying `anchor` draws: the box
    /// around its children, so a trigger in a wrapper its parent stretches
    /// is placed against what shows ([`OverlayAnchor::Content`]). A ref a
    /// component gives its slot goes by the app's element's own box,
    /// whether a TSX or a Rust app filled the slot.
    pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
        let anchor = *anchor;
        self.bind_prop(
            move || match anchor.node() {
                Some(id) => OverlayAnchor::Content(id),
                None => OverlayAnchor::None,
            },
            |a| Prop::Overlay(OverlayProp::Anchor(a)),
        )
    }

    /// Places it against a point of the root view (a touch's `page`: a
    /// menu where the pointer is).
    pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
        self.bind_prop(point, |p| {
            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
        })
    }

    /// Places it against a box of the root view: an input's caret
    /// ([`CaretEvent::page_bounds`]), where suggestions for what is being
    /// typed open.
    pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
        self.bind_prop(bounds, |b| {
            Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
        })
    }

    /// The side of the anchor it goes on (default below).
    pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
        self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
    }

    /// How it lines up with the anchor along that side (default centered).
    pub fn align(self, align: impl IntoReactive<Align>) -> Self {
        self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
    }

    /// The gap between the anchor and it.
    pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
        self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
    }

    /// The distance it keeps from the edges of the safe area.
    pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
        self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
    }

    /// A press went down outside it, its anchor and the overlays inside it
    /// (where, in the root view). Closing is the listener's: leave it out
    /// of the view.
    pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
        self.listen(
            EventKind::PressOutside,
            listener.into_listener(),
            events::page_point,
        )
    }

    /// Escape or the Android back button, while it is the top overlay
    /// listening (it takes them from those below, the pages and
    /// [`super::on_back_press`]).
    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
    }

    /// Makes it a hint (a tooltip): shown once the pointer rested on its
    /// anchor (its parent without one) for `delay`, until the pointer
    /// leaves or presses the anchor, on the desktops only, and while the
    /// keyboard focus is on the anchor (or in it, outside an overlay), in
    /// every idiom, until the focus leaves; Escape hides it. It is placed
    /// against the anchor and should not take the pointer
    /// ([`Interactive::pointer_events`] none). [`Self::hint_open`] decides
    /// instead of the pointer.
    pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
        self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
    }

    /// A hint shown (`Some(true)`) or hidden (`Some(false)`) whatever the
    /// pointer does: its owner follows [`Self::on_hint_show`] /
    /// [`Self::on_hint_hide`] (a `Tooltip` controlled by the app). `None`:
    /// the pointer decides.
    pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
        self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
    }

    /// The pointer rested on a hint's anchor for its delay, or the
    /// keyboard focus came to it: it asks to show (and shows, unless
    /// [`Self::hint_open`] decides), with why.
    pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
        self.listen(
            EventKind::Show,
            listener.into_listener(),
            events::hint_reason,
        )
    }

    /// The pointer left or pressed a hint's anchor, the focus left it,
    /// Escape was pressed or the hint left the view, after it asked to
    /// show: it asks to hide, with why.
    pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
        self.listen(
            EventKind::Dismiss,
            listener.into_listener(),
            events::hint_reason,
        )
    }

    /// The core placed it against its anchor: the side it went on, its
    /// frame and the room on that side.
    pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
        self.listen(
            EventKind::Position,
            listener.into_listener(),
            events::overlay_position,
        )
    }
}

impl Modal {
    /// How it comes in (default: slides up).
    pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
        self.bind_prop(animation, |animation: ModalAnimation| {
            Prop::Modal(ModalProp::Animation(animation))
        })
    }

    /// The program it comes and goes through instead of its
    /// [`Self::animation`] (TS: `transitionShader`); `None` (a binding can
    /// go back to it) leaves the change to the animation.
    pub fn transition_shader(
        self,
        shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
    ) -> Self {
        self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
            Prop::TransitionShader(s.map(Into::into))
        })
    }

    /// Full screen, or a sheet (iOS).
    pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
        self.bind_prop(presentation, |presentation: ModalPresentation| {
            Prop::Modal(ModalProp::Presentation(presentation))
        })
    }

    /// What the status bar shows while it is presented (iOS and Android;
    /// TS: `statusBar`): over what is below it, field by field.
    pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
        self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
    }

    /// Under the status bar (Android).
    pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
        self.bind_prop(translucent, |translucent: bool| {
            Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
        })
    }

    /// The orientations it allows while it is presented (iOS; default:
    /// those of what presents it).
    pub fn supported_orientations(
        self,
        orientations: impl IntoIterator<Item = Orientation>,
    ) -> Self {
        let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
        self.set(Prop::Modal(ModalProp::Orientations(bits)))
    }

    /// Escape and the Android back button close it natively (default
    /// true); either way they report [`Self::on_cancel`].
    pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
    }

    /// A press on a backdrop the platform presents itself (a native
    /// sheet's) closes it (default true); a backdrop the app renders is
    /// the app's to handle.
    pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
        self.bind_prop(close, |v: bool| {
            Prop::Modal(ModalProp::CloseOnBackdropPress(v))
        })
    }

    /// Swiping a sheet down closes it natively (default true).
    pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
        self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
    }

    /// The user tried to close it (Escape or back, a backdrop press, a
    /// swipe down), whether or not it closed: leave it out of the view
    /// (its region) to close it.
    pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(
            EventKind::RequestClose,
            listener.into_listener(),
            events::unit,
        )
    }

    /// It finished appearing.
    pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(EventKind::Show, listener.into_listener(), events::unit)
    }

    /// The user or the system closed it.
    pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
    }
}

/// An orientation of the screen ([`Modal::supported_orientations`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
    /// Upright.
    Portrait,
    /// Upside down.
    PortraitUpsideDown,
    /// Either landscape.
    Landscape,
    /// Landscape, the top on the left.
    LandscapeLeft,
    /// Landscape, the top on the right.
    LandscapeRight,
}

impl Orientation {
    fn bits(self) -> u8 {
        use crate::ModalConfig as M;
        match self {
            Orientation::Portrait => M::PORTRAIT,
            Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
            Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
            Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
            Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
        }
    }
}

impl WebView {
    /// Loads `html` (relative links against `base_url`) instead of a URL;
    /// a bound page loads again when it changes.
    pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
        let base_url: Option<Arc<str>> = base_url.map(Into::into);
        self.bind_prop(html, move |html: String| {
            Prop::Native(NativeProp::Source(WebSource::Html {
                html: html.into(),
                base_url: base_url.clone(),
            }))
        })
    }

    /// Runs after each page loads.
    pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
        self.bind_prop(script, |script: String| {
            Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
        })
    }

    /// Runs before each page's own scripts.
    pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
        self.bind_prop(script, |script: String| {
            Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
        })
    }

    /// The user agent it sends.
    pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
        self.bind_prop(agent, |agent: String| {
            Prop::Native(NativeProp::UserAgent(Some(agent.into())))
        })
    }

    /// Scrolls (default yes).
    pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
        self.bind_prop(enabled, |enabled: bool| {
            Prop::Native(NativeProp::Scrollable(enabled))
        })
    }

    /// Runs the pages' JavaScript (default yes).
    pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
        self.bind_prop(enabled, |enabled: bool| {
            Prop::Native(NativeProp::JavaScriptEnabled(enabled))
        })
    }

    /// Swipes go back and forward (iOS).
    pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
        self.bind_prop(enabled, |enabled: bool| {
            Prop::Native(NativeProp::BackForwardGestures(enabled))
        })
    }

    /// Keeps the page's website data (cookies, storage, the cache) only
    /// as long as the web view, apart from the app's other web views
    /// (default no; Android: no HTTP cache and no saved form data). Read
    /// when the web view is made, so it takes a value, not a signal.
    pub fn incognito(self, incognito: bool) -> Self {
        self.set(Prop::Native(NativeProp::Incognito(incognito)))
    }

    /// Serves the page the URLs of `scheme` (`"app-image"` for
    /// `<img src="app-image:1">`) from the app: `handler` answers each
    /// request with bytes and a MIME type
    /// ([`WebResourceRequest::respond`](crate::web_resource::WebResourceRequest::respond)),
    /// now or later and from any thread, and the web engine loads them as
    /// it loads any subresource, with no `data:` URL or script in between
    /// (iOS and macOS, Linux). The platform calls `handler` on its main
    /// thread, so it returns at once and leaves slow work to a thread of
    /// its own. Several schemes are several calls; one called again
    /// replaces its handler. `scheme` is a letter followed by letters,
    /// digits, `+`, `-` or `.`, none of the web's or the system's (`http`,
    /// `file`, `data`, ...): another is ignored with a warning. Read when
    /// the web view is made, as [`incognito`](Self::incognito)
    /// ([`crate::web_resource`]).
    pub fn url_scheme(
        self,
        scheme: &str,
        handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
    ) -> Self {
        let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
            Ok(scheme) => scheme,
            Err(e) => {
                log::warn!(target: "js", "web view: {e}");
                return self;
            }
        };
        let mut schemes = self
            .0
            .attrs
            .props
            .iter()
            .find_map(|p| match p {
                Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
                _ => None,
            })
            .unwrap_or_default();
        schemes.retain(|s| s.scheme() != scheme.scheme());
        schemes.push(scheme);
        self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
    }

    /// A page started loading.
    pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
        self.listen(
            EventKind::LoadStart,
            listener.into_listener(),
            events::navigation,
        )
    }

    /// A page loaded.
    pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
        self.listen(
            EventKind::Load,
            listener.into_listener(),
            events::navigation,
        )
    }

    /// A page failed to load (the message).
    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
        self.listen(EventKind::Error, listener.into_listener(), events::message)
    }

    /// The platform shows no web view here: it has no web engine, or its
    /// engine failed to start (the message; TS: `onError` with `code`
    /// `"ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"`). [`on_error`](Self::on_error)
    /// hears it too. [`web_view_available`](crate::element::web_view_available)
    /// asks ahead.
    pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
        self.listen(
            EventKind::Error,
            listener.into_listener(),
            events::unavailable,
        )
    }

    /// The page called `window.nsh.postMessage(data)`.
    pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
        self.listen(EventKind::Message, listener.into_listener(), events::data)
    }

    /// It navigated.
    pub fn on_navigation_state_change<M>(
        self,
        listener: impl IntoListener<WebNavigation, M>,
    ) -> Self {
        self.listen(
            EventKind::NavigationStateChange,
            listener.into_listener(),
            events::navigation,
        )
    }
}

impl Video {
    /// Paused.
    pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
        self.bind_prop(paused, |paused: bool| {
            Prop::Native(NativeProp::Paused(paused))
        })
    }

    /// Without sound.
    pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
        self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
    }

    /// 0..1.
    pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
        self.bind_prop(volume, |volume: f32| {
            Prop::Native(NativeProp::Volume(volume))
        })
    }

    /// Playback speed.
    pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
        self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
    }

    /// Starts over at the end.
    pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
        self.bind_prop(repeat, |repeat: bool| {
            Prop::Native(NativeProp::Repeat(repeat))
        })
    }

    /// The platform's playback controls.
    pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
        self.bind_prop(controls, |controls: bool| {
            Prop::Native(NativeProp::Controls(controls))
        })
    }

    /// Milliseconds between [`Self::on_progress`] events (default 250).
    pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
        self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
    }

    /// What its sound does to the rest of the device's audio while it
    /// plays (default: the app's audio settings).
    pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
        self.bind_prop(session, |session: AudioSession| {
            Prop::Native(NativeProp::AudioSession(session))
        })
    }

    /// It started loading.
    pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
    }

    /// It loaded: length and size.
    pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
        self.listen(EventKind::Load, listener.into_listener(), events::video)
    }

    /// It played on.
    pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
        self.listen(
            EventKind::Progress,
            listener.into_listener(),
            events::progress,
        )
    }

    /// It played to its end.
    pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
        self.listen(EventKind::End, listener.into_listener(), events::unit)
    }

    /// It started (`true`) or stopped buffering.
    pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
        self.listen(
            EventKind::Buffer,
            listener.into_listener(),
            events::buffering,
        )
    }

    /// It failed (the message).
    pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
        self.listen(EventKind::Error, listener.into_listener(), events::message)
    }
}

impl NativeView {
    /// Its prop `name` (any JSON value), as JS's `nativeComponent` passes it;
    /// a bound one is passed again when it changes.
    pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
        let name: Arc<str> = name.into();
        self.bind_prop(value, move |value| {
            Prop::ComponentProp(name.clone(), Some(value))
        })
    }

    /// Binds its prop `name` to an animated value: the platform hands the
    /// value (a number or a color) to the component on every frame it
    /// changes, with no engine work per frame (JS: an animated value given
    /// to a `nativeComponent` prop). A value set with [`Self::prop`] under
    /// that name waits until the binding goes.
    pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
        if let Some(node) = value.animated_node().live() {
            set(
                &mut self.0,
                Prop::ComponentPropBinding(name.into(), Some(node.id())),
            );
            self.0.attrs.bound.push(node);
        }
        self
    }

    /// It emitted an event.
    pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
        self.listen(
            EventKind::NativeEvent,
            listener.into_listener(),
            events::native,
        )
    }
}

/// A number in a drawing: a constant, or an animated value the canvas reads
/// while it draws (it draws again natively as the value moves).
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasArg(pub(crate) CanvasArgKind);

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum CanvasArgKind {
    Const(f32),
    Node(super::LiveNode),
}

impl From<f32> for CanvasArg {
    fn from(n: f32) -> Self {
        Self(CanvasArgKind::Const(n))
    }
}

/// A length (coordinates, sizes, line widths, radii).
impl From<Points> for CanvasArg {
    fn from(n: Points) -> Self {
        Self(CanvasArgKind::Const(n.0))
    }
}

/// An angle (arcs, rotations).
impl From<Radians> for CanvasArg {
    fn from(n: Radians) -> Self {
        Self(CanvasArgKind::Const(n.0))
    }
}

/// An animated value whose owner is gone counts as 0.
impl<A: super::Animated> From<&A> for CanvasArg {
    fn from(a: &A) -> Self {
        Self(match a.animated_node().live() {
            Some(node) => CanvasArgKind::Node(node),
            None => CanvasArgKind::Const(0.0),
        })
    }
}

/// What a drawing fills or strokes with (`fillStyle` / `strokeStyle`): a
/// color, a gradient ([`CanvasGradient::linear`], `radial`, `conic`), or a
/// animated value interpolating colors
/// ([`super::AnimatedNode::interpolate_colors`]), read as it moves.
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasPaint(CanvasPaintKind);

#[derive(Debug, Clone, PartialEq)]
enum CanvasPaintKind {
    Color(Color),
    Gradient(Arc<CanvasGradient>),
    Node(super::LiveNode),
}

impl From<Color> for CanvasPaint {
    fn from(color: Color) -> Self {
        Self(CanvasPaintKind::Color(color))
    }
}

impl From<Hsla> for CanvasPaint {
    fn from(color: Hsla) -> Self {
        Color::from(color).into()
    }
}

impl From<Rgba> for CanvasPaint {
    fn from(color: Rgba) -> Self {
        Color::from(color).into()
    }
}

impl From<CanvasGradient> for CanvasPaint {
    fn from(gradient: CanvasGradient) -> Self {
        Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
    }
}

impl From<Arc<CanvasGradient>> for CanvasPaint {
    fn from(gradient: Arc<CanvasGradient>) -> Self {
        Self(CanvasPaintKind::Gradient(gradient))
    }
}

/// An animated value whose owner is gone paints nothing (transparent).
impl<A: super::Animated> From<&A> for CanvasPaint {
    fn from(a: &A) -> Self {
        Self(match a.animated_node().live() {
            Some(node) => CanvasPaintKind::Node(node),
            None => CanvasPaintKind::Color(Color::TRANSPARENT),
        })
    }
}

/// Records a [`Drawing`] with the HTML Canvas 2D operations (Rust names):
/// `Painter::new().fill_color(red).fill_rect(px(0.0), px(0.0), w, h).finish()`.
/// Coordinates are points from the canvas's top left. Numbers and paints
/// may be animated values (the canvas draws again natively as they move);
/// operations without a method here are built by hand with
/// [`Painter::num`], [`Painter::paint`] and [`Painter::op`]. Text is
/// measured with [`super::measure_text`].
#[derive(Debug, Clone, Default)]
pub struct Painter {
    drawing: Drawing,
    /// The nodes of the animated values the drawing reads, held with it.
    nodes: Vec<super::LiveNode>,
}

impl Painter {
    /// An empty drawing.
    pub fn new() -> Self {
        Self::default()
    }

    /// The drawing.
    pub fn finish(self) -> Drawing {
        self.drawing
    }

    /// `value` as a number of this drawing, for an operation built by hand
    /// ([`Self::op`]): an animated value becomes a slot the canvas reads while
    /// it draws, kept alive with the drawing.
    pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
        match value.into().0 {
            CanvasArgKind::Const(n) => Num::Const(n),
            CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
        }
    }

    /// `paint` as a paint of this drawing, for an operation built by hand
    /// ([`Self::op`]).
    pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
        match paint.into().0 {
            CanvasPaintKind::Color(color) => Paint::Color(color),
            CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
            CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
        }
    }

    fn slot(&mut self, node: super::LiveNode) -> u16 {
        let slot = self.drawing.slot(node.id());
        self.nodes.push(node);
        slot
    }

    /// Adds `node`: a part of the drawing that assistive technologies and
    /// UI tests see as an element of its own ([`crate::canvas::CanvasNode`]).
    pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
        self.drawing.nodes.push(node);
        self
    }

    /// Records `op` (one built by hand: its numbers and paints from
    /// [`Self::num`] and [`Self::paint`]).
    pub fn op(mut self, op: CanvasOp) -> Self {
        self.drawing.ops.push(op);
        self
    }

    fn path(self, op: PathOp) -> Self {
        self.op(CanvasOp::Path(op))
    }

    /// Whether `point` (in the canvas, as a touch's location) is inside the
    /// current path by `rule`, with the transform, as recorded so far (TS:
    /// `cx.isPointInPath(x, y, rule)`). Answered from the geometry here,
    /// with no platform round trip; a number given as an animated value
    /// counts as 0, as in TS. To find what is under a tap, build the
    /// canvas's painter in a function the press handler calls too.
    pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
        crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
    }

    /// Whether `point` is on the stroke of the current path with the line
    /// width and cap recorded so far (TS: `cx.isPointInStroke(x, y)`;
    /// round joins, no dashes). See [`Self::is_point_in_path`].
    pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
        crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
    }

    /// Whether `point` is inside `path` by `rule`, with the transform
    /// recorded so far (TS: `cx.isPointInPath(path2d, x, y, rule)`): the
    /// shape [`Self::fill_path`] drew under a tap. See
    /// [`Self::is_point_in_path`].
    pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
        crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
    }

    /// Whether `point` is on the stroke of `path` with the transform, line
    /// width and cap recorded so far (TS: `cx.isPointInStroke(path2d, x,
    /// y)`). See [`Self::is_point_in_path`].
    pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
        crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
    }

    /// Saves the state (styles, transform, clip).
    pub fn save(self) -> Self {
        self.op(CanvasOp::Save)
    }

    /// Restores the state saved last.
    pub fn restore(self) -> Self {
        self.op(CanvasOp::Restore)
    }

    /// Moves the origin.
    pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.op(CanvasOp::Translate(x, y))
    }

    /// Scales the axes.
    pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.op(CanvasOp::Scale(x, y))
    }

    /// Rotates the axes, clockwise (a [`Radians`], or an animated value of
    /// radians).
    pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
        let a = self.num(angle);
        self.op(CanvasOp::Rotate(a))
    }

    /// Multiplies the transform by the matrix `[a c e; b d f]`
    /// (`transform`).
    pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
        let m = m.map(|n| self.num(n));
        self.op(CanvasOp::Transform(m))
    }

    /// Replaces the transform with the matrix `[a c e; b d f]`
    /// (`setTransform`).
    pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
        let m = m.map(|n| self.num(n));
        self.op(CanvasOp::SetTransform(m))
    }

    /// Back to no transform (`resetTransform`).
    pub fn reset_transform(self) -> Self {
        self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
    }

    /// Starts a new path.
    pub fn begin_path(self) -> Self {
        self.op(CanvasOp::BeginPath)
    }

    /// Starts a subpath at (`x`, `y`).
    pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.path(PathOp::MoveTo(x, y))
    }

    /// A straight line to (`x`, `y`).
    pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        let (x, y) = (self.num(x), self.num(y));
        self.path(PathOp::LineTo(x, y))
    }

    /// A quadratic Bézier curve to `to` (`quadraticCurveTo`).
    pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
        let c = |v: Points| Num::Const(v.0);
        self.path(PathOp::QuadTo([
            c(control.x),
            c(control.y),
            c(to.x),
            c(to.y),
        ]))
    }

    /// A cubic Bézier curve to `to` (`bezierCurveTo`).
    pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
        let c = |v: Points| Num::Const(v.0);
        self.path(PathOp::CubicTo([
            c(c1.x),
            c(c1.y),
            c(c2.x),
            c(c2.y),
            c(to.x),
            c(to.y),
        ]))
    }

    /// A circular arc around (`x`, `y`); angles clockwise from the x axis
    /// ([`Radians`], or animated values of radians).
    pub fn arc(
        self,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        radius: impl Into<CanvasArg>,
        start: impl Into<CanvasArg>,
        end: impl Into<CanvasArg>,
    ) -> Self {
        self.arc_in(x, y, radius, start, end, false)
    }

    /// [`Self::arc`] drawn counterclockwise.
    pub fn arc_counterclockwise(
        self,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        radius: impl Into<CanvasArg>,
        start: impl Into<CanvasArg>,
        end: impl Into<CanvasArg>,
    ) -> Self {
        self.arc_in(x, y, radius, start, end, true)
    }

    fn arc_in(
        mut self,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        radius: impl Into<CanvasArg>,
        start: impl Into<CanvasArg>,
        end: impl Into<CanvasArg>,
        ccw: bool,
    ) -> Self {
        let (x, y, radius, start, end) = (
            self.num(x),
            self.num(y),
            self.num(radius),
            self.num(start),
            self.num(end),
        );
        self.path(PathOp::Arc {
            x,
            y,
            radius,
            start,
            end,
            ccw,
        })
    }

    /// An arc of `radius` tangent to the lines to `p1` and on to `p2`
    /// (`arcTo`): a rounded corner.
    pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
        let c = |v: Points| Num::Const(v.0);
        self.path(PathOp::ArcTo([
            c(p1.x),
            c(p1.y),
            c(p2.x),
            c(p2.y),
            c(radius),
        ]))
    }

    /// An elliptical arc around `center` with radii `radii` turned by
    /// `rotation`; angles clockwise (`counterclockwise` draws the other
    /// way).
    pub fn ellipse(
        self,
        center: Point<Points>,
        radii: Size<Points>,
        rotation: Radians,
        start: Radians,
        end: Radians,
        counterclockwise: bool,
    ) -> Self {
        let c = Num::Const;
        self.path(PathOp::Ellipse {
            geometry: [
                c(center.x.0),
                c(center.y.0),
                c(radii.width.0),
                c(radii.height.0),
                c(rotation.0),
            ],
            start: c(start.0),
            end: c(end.0),
            ccw: counterclockwise,
        })
    }

    /// A rectangle subpath.
    pub fn rect(self, rect: Bounds<Points>) -> Self {
        self.path(PathOp::Rect(nums(rect)))
    }

    /// A rectangle subpath with round corners (one radius for all).
    pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
        self.round_rect_corners(rect, Corners::all(radius))
    }

    /// A rectangle subpath with round corners.
    pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
        let c = |v: Points| Num::Const(v.0);
        self.path(PathOp::RoundRect(
            nums(rect),
            [
                c(radii.top_left),
                c(radii.top_right),
                c(radii.bottom_right),
                c(radii.bottom_left),
            ],
        ))
    }

    /// A straight line back to the subpath's start.
    pub fn close_path(self) -> Self {
        self.path(PathOp::Close)
    }

    /// Fills the current path.
    pub fn fill(self) -> Self {
        self.fill_with(FillRule::NonZero)
    }

    /// Fills the current path by `rule`.
    pub fn fill_with(self, rule: FillRule) -> Self {
        self.op(CanvasOp::Fill(None, rule))
    }

    /// Fills `path` (TS: `fill(path2d)`; parse SVG data once with
    /// [`crate::canvas::svg_path`]).
    pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
        self.op(CanvasOp::Fill(Some(path.clone()), rule))
    }

    /// Fills SVG path data (parsed now: [`Self::fill_path`] reuses a
    /// parsed path).
    pub fn fill_svg(self, data: &str) -> Self {
        self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
    }

    /// Strokes the current path.
    pub fn stroke(self) -> Self {
        self.op(CanvasOp::Stroke(None))
    }

    /// Strokes `path` (TS: `stroke(path2d)`).
    pub fn stroke_path(self, path: &Path) -> Self {
        self.op(CanvasOp::Stroke(Some(path.clone())))
    }

    /// Strokes SVG path data (parsed now).
    pub fn stroke_svg(self, data: &str) -> Self {
        self.stroke_path(&crate::canvas::svg_path(data))
    }

    /// Clips to the current path.
    pub fn clip(self) -> Self {
        self.clip_with(FillRule::NonZero)
    }

    /// Clips to the current path by `rule`.
    pub fn clip_with(self, rule: FillRule) -> Self {
        self.op(CanvasOp::Clip(None, rule))
    }

    /// Clips to `path` (TS: `clip(path2d)`).
    pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
        self.op(CanvasOp::Clip(Some(path.clone()), rule))
    }

    /// Fills a rectangle (its numbers [`Points`], or animated values).
    pub fn fill_rect(
        mut self,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        w: impl Into<CanvasArg>,
        h: impl Into<CanvasArg>,
    ) -> Self {
        let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
        self.op(CanvasOp::FillRect([x, y, w, h]))
    }

    /// Strokes a rectangle.
    pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
        self.op(CanvasOp::StrokeRect(nums(rect)))
    }

    /// Makes a rectangle transparent.
    pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
        self.op(CanvasOp::ClearRect(nums(rect)))
    }

    /// Fills with `color`.
    pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
        self.fill_style(color.into())
    }

    /// Strokes with `color`.
    pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
        self.stroke_style(color.into())
    }

    /// Fills with `paint`: a color, a gradient or an animated value of colors
    /// (`fillStyle`).
    pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
        let paint = self.paint(paint);
        self.op(CanvasOp::FillStyle(paint))
    }

    /// Fills with the canvas view's `fill` style (CSS's, inherited from the
    /// views around it; `currentColor` is its text color), or `initial`
    /// where nothing sets one: shapes a component draws take the app's
    /// `fill-*` classes, and follow them and the appearance without being
    /// drawn again ([`Drawing::view_paints`]).
    pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
        self.view_paint(
            ViewPaint::Fill(initial),
            CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
        )
    }

    /// Strokes with the canvas view's `stroke` style, or `initial` where
    /// nothing sets one ([`Self::fill_style_from_view`]).
    pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
        self.view_paint(
            ViewPaint::Stroke(initial),
            CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
        )
    }

    /// Strokes as wide as the canvas view's `strokeWidth` style (1 where
    /// nothing sets one, CSS's initial value).
    pub fn line_width_from_view(self) -> Self {
        self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
    }

    /// Dashes strokes as the canvas view's `strokeDasharray` style does
    /// (solid where nothing sets one).
    pub fn line_dash_from_view(self) -> Self {
        self.view_paint(
            ViewPaint::StrokeDasharray,
            CanvasOp::LineDash(Arc::from([])),
        )
    }

    /// Fills the current path with the canvas view's background: its
    /// `backgroundColor` and its `backgroundImage` gradients (`bg-*`,
    /// `bg-linear-*` classes, the appearance's colors), positioned over
    /// `area` (this drawing's coordinates) as over a box of that size. The
    /// view then draws no background of its own: the background shows only
    /// where the path fills, as CSS's `clip-path` shows a box's
    /// ([`ViewPaint::Background`]). The canvas's state is kept around the
    /// fill.
    pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
        self.view_paint(
            ViewPaint::Background {
                area,
                rule: FillRule::NonZero,
            },
            CanvasOp::Fill(None, FillRule::NonZero),
        )
    }

    fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
        let at = self.drawing.ops.len() as u32;
        self.drawing.view_paints.push((at, view));
        self.op(placeholder)
    }

    /// Strokes with `paint` (`strokeStyle`).
    pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
        let paint = self.paint(paint);
        self.op(CanvasOp::StrokeStyle(paint))
    }

    /// The stroke width.
    pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
        let w = self.num(width);
        self.op(CanvasOp::LineWidth(w))
    }

    /// How strokes end.
    pub fn line_cap(self, cap: LineCap) -> Self {
        self.op(CanvasOp::LineCap(cap))
    }

    /// How stroke segments join.
    pub fn line_join(self, join: LineJoin) -> Self {
        self.op(CanvasOp::LineJoin(join))
    }

    /// How far mitered joins reach, in line widths (`miterLimit`; at least
    /// 1).
    pub fn miter_limit(self, limit: f32) -> Self {
        self.op(CanvasOp::MiterLimit(limit.max(1.0)))
    }

    /// Dashes: lengths of dashes and gaps.
    pub fn line_dash(self, segments: &[Points]) -> Self {
        self.op(CanvasOp::LineDash(segments.into()))
    }

    /// Where the dashes start along the line (`lineDashOffset`; an animated
    /// value marches them).
    pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
        let o = self.num(offset);
        self.op(CanvasOp::LineDashOffset(o))
    }

    /// The opacity of what is drawn next.
    pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
        let a = self.num(alpha);
        self.op(CanvasOp::GlobalAlpha(a))
    }

    /// How what is drawn next combines with the canvas.
    pub fn composite(self, composite: Composite) -> Self {
        self.op(CanvasOp::Composite(composite))
    }

    /// Shadows of what is drawn next.
    pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
        self.op(CanvasOp::ShadowColor(Color::from(color.into())))
            .op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
            .op(CanvasOp::ShadowOffset(offset))
    }

    /// The font (CSS `font` shorthand: `"600 14px Inter"`); an invalid one
    /// keeps the previous font, as in HTML.
    pub fn font(self, font: &str) -> Self {
        match CanvasFont::parse(font) {
            Some(font) => self.op(CanvasOp::Font(font)),
            None => self,
        }
    }

    /// The number forms of text (TS: `fontVariantNumeric`): with
    /// [`crate::style::FontVariant::TABULAR_NUMS`] figures have equal widths, so changing
    /// values do not jitter; `FontVariant::default()` keeps the font's.
    pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
        self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
            numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
        )))
    }

    /// Where text sits relative to its x.
    pub fn text_align(self, align: CanvasTextAlign) -> Self {
        self.op(CanvasOp::TextAlign(align))
    }

    /// Where text sits relative to its y.
    pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
        self.op(CanvasOp::TextBaseline(baseline))
    }

    /// Fills `text` at (`x`, `y`).
    pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        self.text(text, x, y, None, false)
    }

    /// Fills `text` at (`x`, `y`), narrowed to fit `max_width`.
    pub fn fill_text_max_width(
        self,
        text: &str,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        max_width: Points,
    ) -> Self {
        self.text(text, x, y, Some(max_width), false)
    }

    /// Strokes the outline of `text` at (`x`, `y`).
    pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
        self.text(text, x, y, None, true)
    }

    /// Strokes the outline of `text` at (`x`, `y`), narrowed to fit
    /// `max_width`.
    pub fn stroke_text_max_width(
        self,
        text: &str,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        max_width: Points,
    ) -> Self {
        self.text(text, x, y, Some(max_width), true)
    }

    fn text(
        mut self,
        text: &str,
        x: impl Into<CanvasArg>,
        y: impl Into<CanvasArg>,
        max_width: Option<Points>,
        stroke: bool,
    ) -> Self {
        let (text, x, y) = (text.into(), self.num(x), self.num(y));
        self.op(if stroke {
            CanvasOp::StrokeText {
                text,
                x,
                y,
                max_width,
            }
        } else {
            CanvasOp::FillText {
                text,
                x,
                y,
                max_width,
            }
        })
    }

    /// Draws the image at `uri` (a URL or `asset:/path`) into `dest`.
    pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
        self.draw_image_part(uri, None, dest)
    }

    /// Draws the part `source` of the image at `uri` (in the image's
    /// pixels; `None`: all of it) into `dest`.
    pub fn draw_image_part(
        self,
        uri: &str,
        source: Option<Bounds<ScaledPixels>>,
        dest: Bounds<Points>,
    ) -> Self {
        self.op(CanvasOp::DrawImage {
            image: CanvasImage { uri: uri.into() },
            source,
            dest: nums(dest),
        })
    }
}

/// `[x, y, w, h]` of `rect`, as a recorded rectangle's numbers.
fn nums(rect: Bounds<Points>) -> [Num; 4] {
    [
        rect.origin.x,
        rect.origin.y,
        rect.size.width,
        rect.size.height,
    ]
    .map(|v| Num::Const(v.0))
}

impl From<Drawing> for Painter {
    fn from(drawing: Drawing) -> Self {
        Self {
            drawing,
            nodes: Vec::new(),
        }
    }
}

crate::static_reactive!(ScreenAnimation: ScreenAnimation);

/// A program where an optional one goes (`.transition_shader(wipe)`).
impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
    fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
        super::Reactive::Static(Some(self))
    }
}

/// A backdrop where an optional one goes (`.macos_backdrop(backdrop)`).
impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
    fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
        super::Reactive::Static(Some(self))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        element::{
            AnimatedValue,
            reactive::{Runtime, create_root, signal},
        },
        shader::{ShaderUniforms, UniformValue},
    };

    fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
        attrs
            .props
            .iter()
            .find_map(|p| match p {
                Prop::Uniforms(u) => Some(u.clone()),
                _ => None,
            })
            .unwrap_or_default()
    }

    /// The animation nodes released since the last call.
    fn released(executor: &super::super::task::Executor) -> usize {
        executor
            .take_actions()
            .into_iter()
            .filter(|a| {
                matches!(
                    a,
                    super::super::task::Action::Animation(
                        crate::animation::AnimationOp::Release { .. }
                    )
                )
            })
            .count()
    }

    fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
        u.0.iter()
            .find(|(n, _)| &**n == name)
            .map(|(_, v)| v.clone())
    }

    #[test]
    fn screens_and_modals_take_a_transition_shader() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let source = "struct Uniforms { edge: f32 }\n\
            fn shade(uv: vec2f) -> vec4f {\n    \
            return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
        let shader = crate::shader::Shader::compile(source).expect("compiles");
        let wipe = crate::shader::TransitionShader::new(shader)
            .uniform("edge", 1.0_f32)
            .duration(std::time::Duration::from_millis(400));
        let expected = crate::shader::NavShaderSpec {
            source: source.into(),
            uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
            duration: Some(400.0),
        };
        let spec = |attrs: &super::super::builder::Attrs| {
            attrs.props.iter().find_map(|p| match p {
                Prop::TransitionShader(s) => Some(s.clone()),
                _ => None,
            })
        };
        let page = screen().transition_shader(wipe.clone()).0;
        assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
        let dialog = modal().transition_shader(wipe.clone()).0;
        assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
        // A binding goes back to the page's or the dialog's own animation.
        let on = signal(true);
        let bound = screen()
            .transition_shader(move || on.get().then(|| wipe.clone()))
            .0;
        assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
        on.set(false);
        assert_eq!(spec(&bound.resolved_attrs()), Some(None));
    }

    #[test]
    fn uniform_takes_static_bound_and_animated_values() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = std::rc::Rc::new(super::super::task::Executor::default());
        let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
        let speed = signal(1.0_f32);
        let view = shader()
            .uniform("center", [0.5_f32, 0.5])
            .uniform("wave", &wave)
            .uniform("speed", move || speed.get());
        let node = view.0;

        // The static and animated ones are set at once; the animated one by
        // its node, which the element holds.
        let set = uniforms(&node.attrs);
        assert_eq!(
            value(&set, "center"),
            Some(UniformValue::List(vec![
                UniformValue::Number(0.5),
                UniformValue::Number(0.5)
            ]))
        );
        let id = wave.node().live().expect("live").id();
        assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
        assert_eq!(
            node.attrs.bound.len(),
            1,
            "the element holds the animated node"
        );
        assert_eq!(
            value(&set, "speed"),
            None,
            "a bound one is applied when resolved"
        );

        // The bound one follows its signal.
        assert_eq!(
            value(&uniforms(&node.resolved_attrs()), "speed"),
            Some(UniformValue::Number(1.0))
        );
        speed.set(2.0);
        assert_eq!(
            value(&uniforms(&node.resolved_attrs()), "speed"),
            Some(UniformValue::Number(2.0))
        );

        // The node outlives the owner of the handle it came from.
        value_owner.dispose();
        assert_eq!(released(&executor), 0, "the view keeps the animated node");
        drop(node);
        assert_eq!(released(&executor), 1, "and lets it go with the view");
    }

    #[test]
    fn a_later_uniform_replaces_one_of_the_same_name() {
        let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
        let set = uniforms(&view.0.attrs);
        assert_eq!(set.0.len(), 1);
        assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
    }

    #[test]
    fn web_view_url_scheme_builder_collects_schemes() {
        let web = web_view_html("<img src=\"a:1\">", None)
            .url_scheme("a", |request| request.fail())
            .url_scheme("b", |request| request.fail())
            // Replaces `a`'s handler.
            .url_scheme("A", |request| request.fail())
            // Not a scheme the app may serve: ignored.
            .url_scheme("https", |request| request.fail());
        let schemes: Vec<String> = web
            .0
            .attrs
            .props
            .iter()
            .find_map(|p| match p {
                Prop::Native(NativeProp::UrlSchemes(list)) => {
                    Some(list.iter().map(|s| s.scheme().to_owned()).collect())
                }
                _ => None,
            })
            .unwrap();
        assert_eq!(schemes, ["b", "a"]);
    }
}