lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
//! A stack of screens, as a phone's apps move between theirs: [`StackOutlet`] in the place of an
//! [`Outlet`](super::Outlet).
//!
//! The router's history is the stack. Every entry from the first to the current one that has a route at this
//! outlet is a screen, and stays mounted under the ones pushed over it, with its state and its scroll: only the
//! top one is laid out and painted, and the one under it while the top one is on its way in or out.
//!
//! - A push brings the new screen in from the right, over the one before, which gives way a little and dims.
//! - Going back takes the top screen out to the right, and it is unmounted when it is gone.
//! - A finger in from the left edge drags the top screen with it; lifted far enough or fast enough it goes back, and
//!   otherwise the screen returns.
//! - A replace, and any other change of the history, swaps the screens without a move.
//!
//! With a [`NavigationBar`] the outlet draws a bar over its screens: the top screen's title, and the way back
//! with the title of the screen under it. A screen says what the bar shows with
//! [`Ctx::navigation_item`](crate::app::ctx::Ctx::navigation_item). The titles move with the screens.

use std::{
  any::Any,
  sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
  },
  time::Duration,
};

use parking_lot::Mutex;

use super::router_component::render_route_match;
use crate::{
  animation::{Easing, Transition},
  app::{
    component::Component,
    ctx::{Ctx, Timeout},
    events::{EdgePanEvent, GesturePhase, LongPressEvent, NavigationCommand, NavigationSource, ScreenEdge},
    window::SafeAreaInsets,
  },
  components::{Column, KeyboardKind, ReturnKey, Row, ScrollVertical, Stack, Text, TextInput, TextOverflow},
  core::{ElementRef, Signal},
  layout::{
    Alignment, StackAlignment,
    layout_kind::{Justify, ScrollState},
    text_style::{FontWeight, TextStyle},
  },
  node::{Element, color::Color, dimension::Dimension, transform::Transform2D},
  router::{
    Navigator, StackEntry,
    route_match::{OutletDepth, RouteMatch, RouterMatches, StackState},
  },
  time::Instant,
  ui::{Recipe, Themed, engine_look::EngineLook, names},
};

/// How a [`StackOutlet`]'s screens and bar move. The values it starts with were set by eye beside the
/// platform's, not measured against it; an app that knows better gives its own with
/// [`StackOutletProps::motion`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StackMotion {
  /// How long a screen takes to come in or go out. It follows a spring ([`Easing::Spring`]), which starts at
  /// the speed a finger let the screen go with. Taken when the outlet is made.
  pub duration: Duration,
  /// How far the screen under gives way while one is over it, as a share of the width.
  pub parallax: f32,
  /// How dark the screen under gets, from 0 to 1.
  pub dim: f32,
  /// How far across a finger from the edge takes the top screen for it to go back when lifted, as a share of
  /// the width.
  pub back_share: f32,
  /// The speed of the finger that takes the screen back from anywhere, in logical pixels a second.
  pub back_speed: f32,
  /// How long the bar's title and color take to come and go as a large title scrolls out of view and back.
  pub title_fade: Duration,
  /// How much larger a large title gets as its content is pulled down: 1.1 is a tenth larger.
  pub large_title_growth: f32,
  /// The pull, in logical pixels, that takes it there.
  pub large_title_pull: f32,
}

impl Default for StackMotion {
  fn default() -> Self {
    Self {
      duration: Duration::from_millis(500),
      parallax: 0.3,
      dim: 0.1,
      back_share: 0.5,
      back_speed: 500.0,
      title_fade: Duration::from_millis(200),
      large_title_growth: 1.1,
      large_title_pull: 150.0,
    }
  }
}

/// The parts of the recipe of the shades a [`StackOutlet`] draws, kept under the name `phone_stack` with
/// [`StackMotion`]: each has a fill and an opacity.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StackPart {
  /// What darkens the screen under the one that moves in or out, at the move's [`StackMotion::dim`] times the
  /// part's opacity.
  Shade,
  /// What darkens the stack behind the list of the screens under, which a long press on the way back opens.
  MenuShade,
}

names!(StackPart {
  Shade => "shade",
  MenuShade => "menu_shade",
});

/// 0.62's shades: black, the one under a moving screen at the move's dim and the one behind the list at a fifth.
const LEGACY_SHADE: Color = Color::new(0, 0, 0, 255);

impl Themed for StackMotion {
  const NAME: &'static str = "phone_stack";
  type Renderer = ();

  /// The design's: both shades in the scrim, which carries its own alpha, light or dark as the theme is; the one
  /// behind the list all of it.
  fn recipe() -> Recipe {
    use crate::app::theme::PaletteColor::Scrim;
    Recipe::new()
      .base(StackPart::Shade, |s| s.background(Scrim).opacity(1.0))
      .base(StackPart::MenuShade, |s| s.background(Scrim).opacity(1.0))
  }
}

impl StackMotion {
  /// 0.62's shades: the recipe [`UiDefinition::legacy`](crate::ui::UiDefinition::legacy) gives the stack.
  pub(crate) fn legacy_recipe() -> Recipe {
    Recipe::new()
      .base(StackPart::Shade, |s| s.background(LEGACY_SHADE).opacity(1.0))
      .base(StackPart::MenuShade, |s| s.background(LEGACY_SHADE).opacity(MENU_DIM))
  }
}

/// The shades a stack draws, in the theme of what is being built.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct StackShades {
  pub(crate) shade: Color,
  pub(crate) shade_opacity: f32,
  pub(crate) menu: Color,
  pub(crate) menu_opacity: f32,
}

impl StackShades {
  pub(crate) fn current() -> Self {
    let look = EngineLook::of::<StackMotion>(&[]);
    Self {
      shade: look.background(StackPart::Shade, LEGACY_SHADE),
      shade_opacity: look.opacity(StackPart::Shade, 1.0),
      menu: look.background(StackPart::MenuShade, LEGACY_SHADE),
      menu_opacity: look.opacity(StackPart::MenuShade, MENU_DIM),
    }
  }
}

/// A frame is painted with the screens where the move starts before they are sent on their way: a transition
/// goes from what was last painted.
const BEGIN: Duration = Duration::from_millis(1);
/// How long after a move's duration the screens are taken to have arrived.
const SETTLE_AFTER: Duration = Duration::from_millis(50);
/// No finger is dragging the top screen.
const NO_DRAG: f32 = -1.0;
/// The way back's arrow, its stroke, and the space between it and the label.
const CHEVRON_WIDTH: f32 = 11.0;
const CHEVRON_HEIGHT: f32 = 20.0;
const CHEVRON_STROKE: f32 = 2.6;
const BACK_SPACING: f32 = 5.0;
/// The point size the platform's arrow is asked for at: the label's.
#[cfg(all(target_os = "ios", feature = "raster"))]
const CHEVRON_POINT_SIZE: f32 = 17.0;
/// From the bar's edge to where the way back's label starts, and the least space between the label and the
/// title.
const BACK_LEADING: f32 = 9.0 + CHEVRON_WIDTH + BACK_SPACING;
const BACK_GAP: f32 = 8.0;
const MENU_MOVE: Duration = Duration::from_millis(250);
const MENU_DIM: f32 = 0.2;
const MENU_OPENING: Duration = Duration::from_millis(400);
/// About how wide the word for going back is in the bar's text, until it is laid out.
const BACK_WIDTH: f32 = 40.0;
const FILL: Dimension = Dimension::Pct(100.0);

/// The bar a [`StackOutlet`] draws over its screens, and its colors. The bar is as high as a phone's, 44
/// logical pixels under the safe area's top. Its colors come from the theme, through the recipe it keeps under the
/// name `phone_navigation_bar` ([`NavigationBarPart`]): the design's roles, light or dark as the theme is, and the
/// colors of 0.62 in [`ThemeDefinition::legacy`](crate::app::theme::ThemeDefinition::legacy). They are read where
/// the bar is made, in the theme of what is being built.
///
/// The board draws a design system's bar of a phone's screen (Mobile/App Bar, Mobile/Large Title) that `lurq::ui`
/// does not have yet; a bar across a desktop window is [`ui::Navbar`](crate::ui::Navbar).
#[derive(Clone, Debug, PartialEq)]
pub struct NavigationBar {
  pub background: Color,
  /// The way back, and what a screen puts at the bar's trailing end by default.
  pub tint: Color,
  pub title: Color,
  /// The line under the bar.
  pub border: Color,
  /// How much a screen's content is blurred where it shows through the bar: the content of a screen whose
  /// list goes under the bar ([`StackOutlet::large_title_scroll`]), where the bar's `background` is not all
  /// there. 0 is no blur.
  pub blur: f32,
  /// A large title is as much larger as the person asked text to be (a phone's Dynamic Type), up to so many
  /// times its size: the bar's own title and labels keep theirs, as the platform's do. 1 keeps the large
  /// title's size too.
  pub large_title_max_scale: f32,
  /// How high the bar is, and how high in a window lower than `low_window`: a phone held on its side, which
  /// has no large titles either.
  pub height: f32,
  pub low_height: f32,
  pub low_window: f32,
  /// The title in the bar.
  pub title_size: f32,
  pub title_weight: FontWeight,
  /// The bar's other text: the way back, a search field, the list of the screens under.
  pub text_size: f32,
  /// A large title: its text, the room it takes, and how far it and a search field stand in from the sides.
  pub large_title_size: f32,
  pub large_title_weight: FontWeight,
  pub large_title_height: f32,
  pub inset: f32,
  /// What the way back says when the title of the screen under has no room, or there is none: the word for
  /// going back. Empty, it is the app's locale's ([`Locale::common`](crate::core::Locale::common)'s `back`).
  pub back: String,
  /// Whether a long press on the way back lists the screens under, and how wide the list is.
  pub back_menu: bool,
  pub back_menu_width: f32,
  /// A prompt over the title: its text and the room it takes.
  pub prompt_size: f32,
  pub prompt_height: f32,
  /// How high a screen's toolbar is.
  pub toolbar_height: f32,
  /// A search field: how high it is, and its color and its placeholder's, in place of ones made from
  /// `title`.
  pub search_height: f32,
  pub search_background: Option<Color>,
  pub search_placeholder: Option<Color>,
}

impl NavigationBar {
  /// This bar as the person's settings for the whole system have it: a large title at their text size,
  /// nothing showing through with transparency reduced or contrast increased, and a line under it that is
  /// all there with contrast increased.
  fn adapted(mut self, system: &crate::app::window::SystemSettings, text_scale: f32) -> Self {
    let scale = text_scale.clamp(1.0_f32.min(text_scale), self.large_title_max_scale.max(1.0));
    self.large_title_size *= scale;
    self.large_title_height *= scale;
    if system.reduce_transparency || system.increase_contrast {
      self.background = Color::new(self.background.r(), self.background.g(), self.background.b(), 255);
      self.blur = 0.0;
    }
    if system.increase_contrast {
      self.border = Color::new(self.border.r(), self.border.g(), self.border.b(), 255);
    }
    self
  }

  /// A bar sized as the platform's, in the colors of the theme of what is being built.
  pub fn new() -> Self {
    let look = EngineLook::of::<Self>(&[]);
    Self {
      background: look.background(NavigationBarPart::Root, legacy::BACKGROUND),
      tint: look.foreground(NavigationBarPart::Action, legacy::TINT),
      title: look.foreground(NavigationBarPart::Title, legacy::TITLE),
      border: look.background(NavigationBarPart::Separator, legacy::BORDER),
      blur: 40.0,
      large_title_max_scale: 1.5,
      height: 44.0,
      low_height: 32.0,
      low_window: 480.0,
      title_size: 17.0,
      title_weight: FontWeight::SemiBold,
      text_size: 17.0,
      large_title_size: 34.0,
      large_title_weight: FontWeight::Bold,
      large_title_height: 52.0,
      inset: 16.0,
      back: String::new(),
      back_menu: true,
      back_menu_width: 250.0,
      prompt_size: 13.0,
      prompt_height: 22.0,
      toolbar_height: 44.0,
      search_height: 36.0,
      search_background: None,
      search_placeholder: None,
    }
  }

  /// 0.62's colors: the recipe [`UiDefinition::legacy`](crate::ui::UiDefinition::legacy) gives the bar.
  pub(crate) fn legacy_recipe() -> Recipe {
    Recipe::new()
      .base(NavigationBarPart::Root, |s| s.background(legacy::BACKGROUND))
      .base(NavigationBarPart::Separator, |s| s.background(legacy::BORDER))
      .base(NavigationBarPart::Title, |s| s.foreground(legacy::TITLE))
      .base(NavigationBarPart::Action, |s| s.foreground(legacy::TINT))
  }

  /// A dark bar of 0.62.
  #[deprecated(
    since = "0.63.0",
    note = "the theme's appearance gives the dark colors: `NavigationBar::new()` built in a dark theme is dark"
  )]
  pub fn dark() -> Self {
    Self {
      background: Color::new(28, 28, 30, 204),
      tint: Color::from_hex("#0a84ff"),
      title: Color::from_hex("#ffffff"),
      border: Color::from_hex("#38383a"),
      ..Self::new()
    }
  }

  /// The platform's bar of 0.62 for an appearance.
  #[deprecated(
    since = "0.63.0",
    note = "the theme's appearance gives the colors: `NavigationBar::new()` is light or dark as the theme is"
  )]
  #[allow(deprecated)]
  pub fn for_appearance(appearance: crate::app::window::Appearance) -> Self {
    match appearance {
      crate::app::window::Appearance::Light => Self {
        background: legacy::BACKGROUND,
        tint: legacy::TINT,
        title: legacy::TITLE,
        border: legacy::BORDER,
        ..Self::new()
      },
      crate::app::window::Appearance::Dark => Self::dark(),
    }
  }

  pub fn background(mut self, color: Color) -> Self {
    self.background = color;
    self
  }

  pub fn tint(mut self, color: Color) -> Self {
    self.tint = color;
    self
  }

  pub fn title(mut self, color: Color) -> Self {
    self.title = color;
    self
  }

  pub fn border(mut self, color: Color) -> Self {
    self.border = color;
    self
  }

  pub fn blur(mut self, radius: f32) -> Self {
    self.blur = radius;
    self
  }

  /// The word for going back; see the field.
  pub fn back(mut self, word: impl Into<String>) -> Self {
    self.back = word.into();
    self
  }

  /// Whether a long press on the way back lists the screens under.
  pub fn back_menu(mut self, enabled: bool) -> Self {
    self.back_menu = enabled;
    self
  }
}

impl Default for NavigationBar {
  fn default() -> Self {
    Self::new()
  }
}

/// The parts of the recipe of a [`NavigationBar`]'s colors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NavigationBarPart {
  /// The bar: its fill is the bar's `background`.
  Root,
  /// The line under the bar: its fill.
  Separator,
  /// The title: its foreground.
  Title,
  /// The way back and what a screen puts at the bar's trailing end by default: its foreground, the bar's `tint`.
  Action,
}

names!(NavigationBarPart {
  Root => "root",
  Separator => "separator",
  Title => "title",
  Action => "action",
});

/// The colors of 0.62's light bar: what the legacy theme gives, and what a theme with no recipe for the bar keeps.
mod legacy {
  use crate::node::color::Color;

  pub(super) const BACKGROUND: Color = Color::new(249, 249, 249, 224);
  pub(super) const TINT: Color = Color::new(0x00, 0x7a, 0xff, 255);
  pub(super) const TITLE: Color = Color::new(0, 0, 0, 255);
  pub(super) const BORDER: Color = Color::new(0xc6, 0xc6, 0xc8, 255);
}

impl Themed for NavigationBar {
  const NAME: &'static str = "phone_navigation_bar";
  type Renderer = ();

  /// The design's (`pencil/lurq-design-system.pen`, Mobile/App Bar): the bar on the background over a line of
  /// the border, its title, its way back and its actions in the foreground.
  fn recipe() -> Recipe {
    use crate::app::theme::PaletteColor::{Background, Border, Foreground};
    Recipe::new()
      .base(NavigationBarPart::Root, |s| s.background(Background))
      .base(NavigationBarPart::Separator, |s| s.background(Border))
      .base(NavigationBarPart::Title, |s| s.foreground(Foreground))
      .base(NavigationBarPart::Action, |s| s.foreground(Foreground))
  }
}

/// What a screen of a [`StackOutlet`] shows in the outlet's bar, and whether a finger from the edge takes it
/// back. A screen gives it in its `render` with
/// [`Ctx::navigation_item`](crate::app::ctx::Ctx::navigation_item).
#[derive(Clone, Default)]
pub struct NavigationItem {
  pub title: String,
  pub back_title: Option<String>,
  pub back_gesture: bool,
  pub leading: Option<Element>,
  pub trailing: Option<Element>,
  pub title_view: Option<Element>,
  pub bar_hidden: bool,
  pub hides_tab_bar: bool,
  pub large_title: bool,
  pub prompt: Option<String>,
  pub toolbar: Option<Element>,
  pub search: Option<NavigationSearch>,
  pub large_title_view: Option<Element>,
  pub search_view: Option<Element>,
}

/// A search field at the top of a screen's content, under its title: [`NavigationItem::search`]. It scrolls
/// away with the content. While it is typed into it takes the bar's place: the bar and a large title go, and
/// a way to cancel comes beside the field, which clears it and puts the keyboard away.
#[derive(Clone)]
pub struct NavigationSearch {
  /// What is typed, for the screen to read and to set.
  pub text: Signal<String>,
  pub placeholder: String,
  /// What the way to cancel says.
  pub cancel: String,
  /// While the field is searched in, it takes the bar's place and a large title goes, as the platform's
  /// search does unless told not to. With `false` the bar and the title stay where they are.
  pub hides_bar: bool,
}

impl NavigationSearch {
  pub fn new(text: Signal<String>) -> Self {
    Self {
      text,
      placeholder: crate::ui::current_locale().common.search.to_string(),
      cancel: crate::ui::current_locale().common.cancel.to_string(),
      hides_bar: true,
    }
  }

  /// Whether the bar and a large title give way to the field while it is searched in.
  pub fn hides_bar(mut self, hides: bool) -> Self {
    self.hides_bar = hides;
    self
  }

  pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
    self.placeholder = placeholder.into();
    self
  }

  pub fn cancel(mut self, cancel: impl Into<String>) -> Self {
    self.cancel = cancel.into();
    self
  }

  /// What tells one search field from another.
  fn key(&self) -> (usize, &str, &str, bool) {
    (self.text.id(), &self.placeholder, &self.cancel, self.hides_bar)
  }
}

impl NavigationItem {
  pub fn new(title: impl Into<String>) -> Self {
    Self {
      title: title.into(),
      back_title: None,
      back_gesture: true,
      leading: None,
      trailing: None,
      title_view: None,
      bar_hidden: false,
      hides_tab_bar: false,
      large_title: false,
      prompt: None,
      toolbar: None,
      search: None,
      large_title_view: None,
      search_view: None,
    }
  }

  /// What the way back says on the screen pushed over this one, in place of this one's title.
  pub fn back_title(mut self, title: impl Into<String>) -> Self {
    self.back_title = Some(title.into());
    self
  }

  /// Whether a finger in from the left edge takes this screen back; it does unless set otherwise. A screen
  /// with something unsaved turns it off. The bar's way back is not affected.
  pub fn back_gesture(mut self, enabled: bool) -> Self {
    self.back_gesture = enabled;
    self
  }

  /// What is at the bar's leading end in place of the way back: a control of the screen's own. It is shown on
  /// the bottom screen too, which has no way back. Shown as [`trailing`](Self::trailing) is.
  pub fn leading(mut self, element: impl Into<Element>) -> Self {
    self.leading = Some(element.into());
    self
  }

  /// What is at the bar's trailing end while this screen is the top one. The bar shows it as it was when the
  /// item's title, back title or back gesture last changed.
  pub fn trailing(mut self, element: impl Into<Element>) -> Self {
    self.trailing = Some(element.into());
    self
  }

  /// What stands in the middle of the bar in place of the title: a control, a picture. The title still names
  /// the screen on the way back to it. Shown as [`trailing`](Self::trailing) is.
  pub fn title_view(mut self, element: impl Into<Element>) -> Self {
    self.title_view = Some(element.into());
    self
  }

  /// Takes the bar away while this screen is the top one: the screen then reaches the top of the outlet, under
  /// the status bar, and keeps clear of it by the safe area itself.
  pub fn bar_hidden(mut self, hidden: bool) -> Self {
    self.bar_hidden = hidden;
    self
  }

  /// Takes the bar of tabs under the stack ([`TabOutlet`](super::TabOutlet)) out of view while this screen
  /// is the top one: the bar goes with the screen that comes in over it, and comes back with the one under.
  pub fn hides_tab_bar(mut self, hides: bool) -> Self {
    self.hides_tab_bar = hides;
    self
  }

  /// Shows the title large, at the top of the screen's content, where it scrolls away with the content; the
  /// bar's own title comes in once it has. The screen puts its content in
  /// [`StackOutlet::large_title_scroll`], which draws the large title over it and scrolls the two.
  pub fn large_title(mut self, large: bool) -> Self {
    self.large_title = large;
    self
  }

  /// A line of small text over the title, for which the bar grows.
  pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
    self.prompt = Some(prompt.into());
    self
  }

  /// What is across the bottom of the outlet while this screen is the top one, over the home indicator's
  /// room and in the bar's color: a row of the screen's controls. The screen itself ends above it, and has
  /// no bottom of the safe area to keep clear of. Shown as [`trailing`](Self::trailing) is.
  pub fn toolbar(mut self, element: impl Into<Element>) -> Self {
    self.toolbar = Some(element.into());
    self
  }

  /// A search field at the top of the screen's content, which
  /// [`StackOutlet::large_title_scroll`] draws; see [`NavigationSearch`].
  pub fn search(mut self, search: NavigationSearch) -> Self {
    self.search = Some(search);
    self
  }

  /// What [`StackOutlet::large_title_scroll`] draws in the large title's place: a title of the screen's own
  /// making, which scrolls away with the content as the outlet's does. It is not carried to a way back when
  /// a screen is pushed over this one. Asks for a large title too.
  pub fn large_title_view(mut self, element: impl Into<Element>) -> Self {
    self.large_title_view = Some(element.into());
    self.large_title = true;
    self
  }

  /// What [`StackOutlet::large_title_scroll`] draws in the search field's place: a field of the screen's own.
  /// It says when it is searched in with [`StackOutlet::searching`], for the bar and a large title to give
  /// it their place.
  pub fn search_view(mut self, element: impl Into<Element>) -> Self {
    self.search_view = Some(element.into());
    self
  }

  /// Whether the item holds an element of the screen's, which cannot be told from the one it held before.
  fn has_elements(&self) -> bool {
    self.leading.is_some()
      || self.trailing.is_some()
      || self.title_view.is_some()
      || self.toolbar.is_some()
      || self.large_title_view.is_some()
      || self.search_view.is_some()
  }

  fn same_as(&self, other: &Self) -> bool {
    self.title == other.title
      && self.back_title == other.back_title
      && self.back_gesture == other.back_gesture
      && self.leading.is_some() == other.leading.is_some()
      && self.trailing.is_some() == other.trailing.is_some()
      && self.title_view.is_some() == other.title_view.is_some()
      && self.bar_hidden == other.bar_hidden
      && self.hides_tab_bar == other.hides_tab_bar
      && self.large_title == other.large_title
      && self.prompt == other.prompt
      && self.toolbar.is_some() == other.toolbar.is_some()
      && self.large_title_view.is_some() == other.large_title_view.is_some()
      && self.search_view.is_some() == other.search_view.is_some()
      && self.search.as_ref().map(NavigationSearch::key) == other.search.as_ref().map(NavigationSearch::key)
  }
}

/// Where a screen's [`NavigationItem`] goes: provided to each screen of a [`StackOutlet`].
#[derive(Clone)]
pub(crate) struct NavigationSlot {
  item: Arc<Mutex<NavigationItem>>,
  /// The outlet reads this in its render, to be rendered again when an item changes.
  changed: Signal<u64>,
  /// What scrolls the screen's content under a large title, and how far a finger has pulled that content
  /// down past its top, which the large title grows with.
  scroll: ScrollState,
  pull: Signal<f32>,
  /// See [`LayerBar`].
  large: ElementRef,
  flying: Signal<bool>,
  /// How much a large title grows, and over what pull ([`StackMotion`]).
  growth: (f32, f32),
  /// The bar's colors and sizes: the outlet's, or a plain bar's where the outlet has none of its own.
  style: Arc<NavigationBar>,
  /// The screen's search field has the focus.
  searching: Signal<bool>,
  /// See [`LayerBar`].
  top: Signal<f32>,
  under: Arc<AtomicBool>,
  /// The outlet draws a screen's toolbar: it has a bar of its own.
  toolbars: bool,
  /// Whether the screen has a toolbar, and whether it hides the bar of tabs: what it keeps clear of at the
  /// bottom follows.
  bottom: Signal<(bool, bool)>,
  /// Whether the screen is the one in front, which it is given to read.
  front: crate::app::ctx::InFront,
}

impl NavigationSlot {
  pub(crate) fn set(&self, item: NavigationItem) {
    let same = {
      let mut current = self.item.lock();
      // An element the screen gave cannot be told from the one it gave before: the bar is drawn anew for
      // every render of a screen that gives one, to show it as it now is.
      let same = current.same_as(&item) && !item.has_elements();
      *current = item;
      same
    };
    if !same {
      self.changed.update(|version| *version += 1);
    }
    // What the screen's holder is made by, apart: it is not made again for every render of a screen that
    // gives an element, which would render the screen again, and so without end.
    let bottom = {
      let item = self.item.lock();
      (item.toolbar.is_some() && !item.bar_hidden, item.hides_tab_bar)
    };
    if self.bottom.get_untracked() != bottom {
      self.bottom.set(bottom);
    }
  }
}

/// What a bar of an app's own is drawn from: [`StackOutletProps::bar_with`].
#[derive(Clone)]
pub struct NavigationBarState {
  /// The screen in front: the top one, or the one on its way out.
  pub top: NavigationBarScreen,
  /// The screen behind it, while the two move or a finger drags the front one.
  pub under: Option<NavigationBarScreen>,
  /// How far out of view the front screen is, from 0, in place, to 1, gone. It is where the screens are going
  /// when `duration` is not zero, and where they are put when it is: under a finger.
  pub out: f32,
  /// How long the screens take to get there, and the curve they follow. Giving a part of the bar a
  /// transition of this duration and easing moves it with the screens.
  pub duration: Duration,
  pub easing: Easing,
  /// The outlet's width.
  pub width: f32,
  pub safe_area: SafeAreaInsets,
  pub navigator: Navigator,
  /// What the way back says on each screen under the top one, the nearest first: what the outlet's own bar
  /// lists on a long press. `navigator.back_by(n)` goes to the n-th of them.
  pub under_titles: Vec<String>,
  /// The window is too low for large titles, as a phone held on its side is; the outlet's own bar is lower
  /// then too.
  pub low: bool,
}

/// A screen's part in a [`NavigationBarState`].
#[derive(Clone)]
pub struct NavigationBarScreen {
  pub item: NavigationItem,
  /// What the way back from this screen says: the title of the screen under it, or what that screen gave
  /// for it. `None` on the bottom screen.
  pub back_label: Option<String>,
  /// The screen's large title is in view in its content: the outlet's own bar shows no title then, and no
  /// color of its own.
  pub large_title_in_view: bool,
  /// The screen is searching: its search field is typed into or holds text. The outlet's own bar gives its
  /// place to the field then.
  pub searching: bool,
}

/// Draws a bar from the state of the stack. It is called at each render of the outlet.
pub type NavigationBarBuilder = Arc<dyn Fn(&NavigationBarState) -> Element + Send + Sync>;

#[derive(Clone)]
enum Bar {
  Standard(NavigationBar),
  Custom(NavigationBarBuilder),
}

#[derive(Clone, Default)]
pub struct StackOutletProps {
  bar: Option<Bar>,
  background: Option<Color>,
  motion: StackMotion,
}

impl PartialEq for StackOutletProps {
  fn eq(&self, other: &Self) -> bool {
    let same_bar = match (&self.bar, &other.bar) {
      (None, None) => true,
      (Some(Bar::Standard(a)), Some(Bar::Standard(b))) => a == b,
      (Some(Bar::Custom(a)), Some(Bar::Custom(b))) => Arc::ptr_eq(a, b),
      _ => false,
    };
    same_bar && self.background == other.background && self.motion == other.motion
  }
}

impl std::fmt::Debug for StackOutletProps {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("StackOutletProps")
      .field("bar", &self.bar.is_some())
      .field("background", &self.background)
      .finish()
  }
}

impl StackOutletProps {
  pub fn new() -> Self {
    Self::default()
  }

  /// Draws a bar over the screens.
  pub fn bar(mut self, bar: NavigationBar) -> Self {
    self.bar = Some(Bar::Standard(bar));
    self
  }

  /// Draws a bar of the app's own over the screens: what `builder` returns for the state of the stack, across
  /// the top of the outlet at the height it takes. The builder keeps its content clear of the status bar by
  /// the state's safe area, and moves it with the screens by the state's `out`, `duration` and `easing`.
  /// Make the builder once and keep it: a new one at each render renders the outlet again.
  pub fn bar_with(mut self, builder: NavigationBarBuilder) -> Self {
    self.bar = Some(Bar::Custom(builder));
    self
  }

  /// How the screens and the bar move, in place of [`StackMotion::default`].
  pub fn motion(mut self, motion: StackMotion) -> Self {
    self.motion = motion;
    self
  }

  /// What is behind each screen. A screen that paints no background of its own shows the one under it
  /// through while it moves.
  pub fn background(mut self, color: Color) -> Self {
    self.background = Some(color);
    self
  }
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for StackOutletProps {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

struct Layer {
  entry: StackEntry,
  matches: Arc<Vec<RouteMatch>>,
  bar: LayerBar,
}

/// What a screen keeps of its part of the bar from one render to the next.
#[derive(Clone)]
struct LayerBar {
  item: Arc<Mutex<NavigationItem>>,
  /// The title as it is laid out in the bar, and the way back's whole label laid out unseen: how wide each is
  /// says whether the label has room beside the title (`after_layout`).
  title: ElementRef,
  back_probe: ElementRef,
  /// How much of the way back's label there is room for.
  label_fit: LabelFit,
  /// What scrolls the screen's content under a large title, and whether that title has scrolled out of view
  /// (`after_layout`).
  scroll: ScrollState,
  title_gone: Arc<AtomicBool>,
  pull: Signal<f32>,
  /// The large title as it is laid out in the content, and the way back's label as it is laid out in the bar:
  /// the two places a title goes between as a screen is pushed over this one or taken off it.
  large: ElementRef,
  label: ElementRef,
  /// The large title is on its way between the two, drawn by the outlet: the screen's own is not shown.
  flying: Signal<bool>,
  /// The word for going back, laid out unseen for its width.
  short_probe: ElementRef,
  /// The screen's search field has the focus.
  searching: Signal<bool>,
  /// How much of the screen the bar is over, from the top: as the outlet last rendered it, and as the
  /// screen was told (`after_layout`).
  top_now: Arc<Mutex<f32>>,
  top: Signal<f32>,
  /// The screen's list goes on under the bar and keeps its content clear of it itself
  /// ([`StackOutlet::large_title_scroll`]): the outlet does not keep the screen clear.
  under: Arc<AtomicBool>,
  /// See [`NavigationSlot`].
  bottom: Signal<(bool, bool)>,
  /// The screen is the top of the stack: what it reads as being in front (`Ctx::is_in_front`).
  front: Signal<bool>,
}

impl Default for LayerBar {
  fn default() -> Self {
    Self {
      item: Arc::default(),
      title: ElementRef::default(),
      back_probe: ElementRef::default(),
      label_fit: LabelFit::Whole,
      scroll: ScrollState::new(),
      title_gone: Arc::default(),
      pull: Signal::new(0.0),
      large: ElementRef::default(),
      label: ElementRef::default(),
      flying: Signal::new(false),
      short_probe: ElementRef::default(),
      searching: Signal::new(false),
      top_now: Arc::default(),
      top: Signal::new(0.0),
      under: Arc::default(),
      bottom: Signal::new((false, false)),
      front: Signal::new(true),
    }
  }
}

#[derive(Clone, Copy, PartialEq)]
enum Motion {
  None,
  /// The top screen is coming in; `started` once a frame was painted with it out of view.
  Entering {
    started: bool,
  },
  /// The screen that was on top (`Shown::leaving`) is going out; `started` once a frame was painted with it
  /// where it was.
  Leaving {
    started: bool,
  },
  /// A finger let the top screen go short of going back, and it returns.
  Returning,
}

struct Shown {
  layers: Vec<Layer>,
  leaving: Option<Layer>,
  motion: Motion,
  /// The outlet's width when it was last rendered.
  width: f32,
  /// A move was set up by the last render and waits for its frame to send the screens on their way.
  begin_due: bool,
  /// How high a large title is, as the outlet's bar last had it.
  large_title_height: f32,
  /// The speed a finger let the front screen go with, towards where it is going, as a share of the way left
  /// per the move's duration; 0 for a move no finger started.
  velocity: f64,
  /// How far out of view the bar of tabs under the stack is for its screens, and the bar's part of the
  /// outlet's context, which is told so after layout.
  tab_bar: super::tabs::BarMove,
  tab_link: Option<super::tabs::TabBarLink>,
  /// Where the top screen's list was at the last layout, and whether it was last scrolled down: a bar of
  /// tabs that gets out of the way of a list being read is told so.
  last_scroll: f32,
  scrolled_down: bool,
  /// The sheet the stack is in, which is told the top screen's list.
  sheet: Option<super::sheet::SheetScroll>,
}

/// A router's outlet that keeps a stack of screens, as a phone's apps do: a screen pushed slides in over the one
/// under it, a finger from the edge takes it back, and a [`NavigationBar`] over them names the screen and the way
/// back. It is the engine's navigation, with no counterpart in `lurq::ui`; its bar takes the theme's colors.
pub struct StackOutlet {
  shown: Arc<Mutex<Shown>>,
  /// Bumped for a render that no signal of the router's asks for: a move's next step, a changed item.
  changed: Signal<u64>,
  /// How far a finger has dragged the top screen, or [`NO_DRAG`].
  drag: Signal<f32>,
  begin: Timeout,
  settle: Timeout,
  /// The outlet as it is laid out: where its corner is in the window.
  origin: ElementRef,
  /// The list of the screens under the top one, which a long press on the way back opens.
  menu: BackMenu,
  /// The top screen as it is laid out: where going back from the way back or a finger from the edge starts, so that
  /// the screen hears it first (`on_history_back`).
  screen: ElementRef,
}

/// Goes back from the stack's top screen, as Alt+← does from the focus: the screen's `on_history_back` first, then
/// the router ([`NavigationCommand`]).
type GoBack = Arc<dyn Fn() + Send + Sync>;

impl Component for StackOutlet {
  type Props = StackOutletProps;

  fn create(ctx: &mut Ctx) -> Self {
    let shown = Arc::new(Mutex::new(Shown {
      layers: Vec::new(),
      leaving: None,
      motion: Motion::None,
      width: 0.0,
      begin_due: false,
      large_title_height: 0.0,
      velocity: 0.0,
      tab_bar: super::tabs::BarMove::SHOWN,
      tab_link: None,
      last_scroll: 0.0,
      scrolled_down: false,
      sheet: None,
    }));
    let changed = Signal::new(0u64);
    let drag = Signal::new(NO_DRAG);
    let begin = ctx.create_timeout(BEGIN, {
      let (shown, changed, drag) = (shown.clone(), changed.clone(), drag.clone());
      move || {
        if let Motion::Entering { started } | Motion::Leaving { started } = &mut shown.lock().motion {
          *started = true;
        }
        drag.set(NO_DRAG);
        changed.update(|version| *version += 1);
      }
    });
    let duration = ctx.props::<StackOutletProps>().motion.duration;
    let settle = ctx.create_timeout(duration + SETTLE_AFTER, {
      let (shown, changed) = (shown.clone(), changed.clone());
      move || {
        {
          let mut shown = shown.lock();
          shown.motion = Motion::None;
          shown.leaving = None;
          shown.velocity = 0.0;
        }
        changed.update(|version| *version += 1);
      }
    });
    Self {
      shown,
      changed,
      drag,
      begin,
      settle,
      origin: ElementRef::default(),
      screen: ElementRef::default(),
      menu: BackMenu {
        open: Signal::new(false),
        opened_at: Arc::default(),
      },
    }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let props = ctx.props::<StackOutletProps>().clone();
    let motion = props.motion;
    let shades = StackShades::current();
    let depth = ctx.use_context::<OutletDepth>().unwrap_or(OutletDepth(0)).0 + 1;
    let Some(navigator) = ctx.use_context::<Navigator>() else {
      return ctx.children().first().cloned().unwrap_or_else(Element::new);
    };
    // What the stack is in, where that is a tab that is shown or not.
    let around = ctx.use_context::<crate::app::ctx::InFront>();
    let history = ctx.history_runner();
    let go_back: GoBack = {
      let (history, screen) = (history.clone(), self.screen.clone());
      Arc::new(move || history.run_in(&screen, NavigationCommand::Back))
    };
    // Rendered again when the history moves, a move takes its next step or a finger drags.
    let _ = navigator.path().get();
    let _ = self.changed.get();
    let drag = self.drag.get();
    let menu_open = self.menu.open.get();

    // The screens: the entries at the history's end that have a route at this outlet.
    let mut entries = Vec::new();
    for entry in navigator.handle.stack().into_iter().rev() {
      let matches = navigator.handle.inner.routes.resolve(&entry.path);
      if matches.len() <= depth {
        break;
      }
      entries.push((entry, Arc::new(matches)));
    }
    entries.reverse();
    if entries.is_empty() {
      return ctx.children().first().cloned().unwrap_or_else(Element::new);
    }

    // What a bar of tabs under the stack already keeps clear is not the stack's to keep clear again.
    let safe_area = ctx.safe_area();
    let window = ctx.window();
    let width = window.logical_width();
    // What the person asked of the whole system: no moves across the screen, nothing showing through.
    let system = window.system;
    let reduce_motion = system.reduce_motion;
    let text_scale = ctx.theme().text_scale();
    // A window too low for it has no large titles, as a phone on its side has none.
    let style = Arc::new(
      match &props.bar {
        Some(Bar::Standard(bar)) => bar.clone(),
        _ => NavigationBar::new(),
      }
      .adapted(&system, text_scale),
    );
    let low = window.logical_height() < style.low_window;
    let bar_height = if low { style.low_height } else { style.height };

    let mut shown = self.shown.lock();
    shown.width = width;
    shown.large_title_height = style.large_title_height;
    let before: Vec<u64> = shown.layers.iter().map(|layer| layer.entry.id).collect();
    let after: Vec<u64> = entries.iter().map(|(entry, _)| entry.id).collect();
    if before != after {
      let pushed = !before.is_empty() && after.len() > before.len() && after[..before.len()] == before[..];
      let popped = before.len() > after.len() && before[..after.len()] == after[..];
      let mut old = std::mem::take(&mut shown.layers);
      let top = old.pop();
      shown.leaving = None;
      shown.motion = Motion::None;
      if popped {
        shown.leaving = top;
        shown.motion = Motion::Leaving { started: false };
        if drag < 0.0 {
          // No finger let it go: it sets off from rest.
          shown.velocity = 0.0;
        }
      } else {
        old.extend(top);
        if pushed {
          shown.motion = Motion::Entering { started: false };
          shown.velocity = 0.0;
        }
      }
      shown.layers = entries
        .into_iter()
        .map(|(entry, matches)| {
          let bar = old
            .iter()
            .find(|layer| layer.entry.id == entry.id)
            .map(|layer| layer.bar.clone())
            .unwrap_or_default();
          Layer { entry, matches, bar }
        })
        .collect();
      self.begin.cancel();
      if shown.motion == Motion::None {
        self.settle.cancel();
      } else {
        // The move starts once this frame, with the screens where it starts from, is laid out: `after_layout`.
        shown.begin_due = true;
        self.settle.restart();
      }
    }

    // The screen in front and the one behind it, how far out of view the front one is, as a share of the
    // width, and whether they are on their way there or put there.
    let count = shown.layers.len();
    let dragged = if drag >= 0.0 && width > 0.0 {
      (drag / width).clamp(0.0, 1.0)
    } else {
      0.0
    };
    let below = count.checked_sub(2).map(|index| shown.layers[index].entry.id);
    let top = shown.layers.last().map(|layer| layer.entry.id);
    let (front, back, out, moving) = match shown.motion {
      Motion::Entering { started } => (top, below, if started { 0.0 } else { 1.0 }, started),
      Motion::Leaving { started } => (
        shown.leaving.as_ref().map(|layer| layer.entry.id),
        top,
        if started { 1.0 } else { dragged },
        started,
      ),
      Motion::Returning => (top, below, 0.0, true),
      Motion::None if drag >= 0.0 && below.is_some() => (top, below, dragged, false),
      Motion::None => (top, None, 0.0, false),
    };

    // Every node that moves has its transition from its first frame, which is what lets one start from where
    // the node was painted; put where a finger has it, the transition takes no time.
    let pace = if moving { motion.duration } else { Duration::ZERO };
    let curve = Easing::Spring {
      velocity: shown.velocity,
    };
    let slide = Transition::transform().duration(pace).easing(curve);
    let fade = Transition::opacity().duration(pace).easing(curve);
    let mut screens = Stack::new().size(FILL, FILL).clip();
    for layer in shown.layers.iter().chain(shown.leaving.iter()) {
      let id = Some(layer.entry.id);
      // How much of the screen the bar is over. The screen is told before it is rendered, so that a list of
      // its own starts clear of the bar in its first frame; what the screen then says of itself (no bar, a
      // prompt) is taken up after it.
      let top_of = |layer: &Layer| {
        let (bar_hidden, prompted) = {
          let item = layer.bar.item.lock();
          (item.bar_hidden, item.prompt.is_some())
        };
        match &props.bar {
          Some(Bar::Standard(_)) if !bar_hidden => {
            let items = if layer.bar.searching.get() {
              0.0
            } else {
              bar_height + if prompted { style.prompt_height } else { 0.0 }
            };
            safe_area.top + items + 0.5
          }
          _ => 0.0,
        }
      };
      let before = top_of(layer);
      if layer.bar.top.get_untracked() != before {
        layer.bar.top.set(before);
      }
      // The screen at the end of the history is the one in front, from the moment it is: one pushed while
      // it comes in, the one under a screen that goes back while that goes out, and not the one seen under
      // a screen a finger drags, until the finger lets go and the history goes back.
      let in_front = id == top;
      if layer.bar.front.get_untracked() != in_front {
        layer.bar.front.set(in_front);
      }
      let content = ctx.mount_keyed_offstage::<StackLayer>(
        &layer.entry.id.to_string(),
        StackLayerProps {
          id: layer.entry.id,
          path: layer.entry.path.clone(),
          matches: layer.matches.clone(),
          depth,
          state: layer.entry.state.clone(),
          slot: NavigationSlot {
            item: layer.bar.item.clone(),
            changed: self.changed.clone(),
            scroll: layer.bar.scroll.clone(),
            pull: layer.bar.pull.clone(),
            large: layer.bar.large.clone(),
            flying: layer.bar.flying.clone(),
            growth: (motion.large_title_growth, motion.large_title_pull),
            style: style.clone(),
            searching: layer.bar.searching.clone(),
            top: layer.bar.top.clone(),
            under: layer.bar.under.clone(),
            toolbars: matches!(props.bar, Some(Bar::Standard(_))),
            bottom: layer.bar.bottom.clone(),
            front: crate::app::ctx::InFront::new(layer.bar.front.clone(), around.clone()),
          },
        },
        id == front || id == back,
      );
      // The bar is over the screens. A screen whose list goes on under it keeps its own content clear; any
      // other is kept clear here, by as much as its bar is high.
      let top = top_of(layer);
      *layer.bar.top_now.lock() = top;
      let clear = if layer.bar.under.load(Ordering::Acquire) {
        0.0
      } else {
        top
      };
      // Every screen has its holder, shown or not, in the order of the stack: a node keeps its identity, and
      // with it where it was last painted, by its place among its siblings.
      // With motion reduced a screen does not cross the window: it fades in over the one behind, which
      // stays where it is, as the platform's do.
      let offset = if reduce_motion {
        0.0
      } else if id == front {
        out * width
      } else if id == back {
        -motion.parallax * width * (1.0 - out)
      } else {
        0.0
      };
      let mut holder = Stack::new()
        .key(format!("stack-screen-{}", layer.entry.id))
        .size(FILL, FILL)
        .padding_top(clear)
        .child(content)
        .ref_element(if shown.layers.last().is_some_and(|last| std::ptr::eq(last, layer)) {
          self.screen.clone()
        } else {
          ElementRef::default()
        })
        .opacity(if reduce_motion && id == front { 1.0 - out } else { 1.0 })
        .transform(Transform2D::translate(offset, 0.0));
      if let Some(background) = props.background {
        holder = holder.background(background);
      }
      if id == back {
        let shade = Row::new()
          .size(FILL, FILL)
          .background(shades.shade)
          .opacity(motion.dim * shades.shade_opacity * (1.0 - out))
          .pointer_events_none();
        holder = holder.child(shade.transition(fade.clone()));
      }
      screens = screens.child(holder.transition(slide.clone()).transition(fade.clone()));
    }

    let screens = screens.on_edge_pan({
      let (shown, drag, changed) = (self.shown.clone(), self.drag.clone(), self.changed.clone());
      let shown_all = self.shown.clone();
      let (navigator, settle, history, screen) = (
        navigator.clone(),
        self.settle.clone(),
        history.clone(),
        self.screen.clone(),
      );
      move |event: EdgePanEvent| {
        if event.edge != ScreenEdge::Left {
          return;
        }
        let mut shown = shown.lock();
        if shown.layers.len() < 2 {
          return;
        }
        // The stack's: the history is not also moved by the swipe this would end as.
        event.prevent_default();
        event.stop_propagation();
        let allowed = shown
          .layers
          .last()
          .is_some_and(|layer| layer.bar.item.lock().back_gesture);
        if !allowed || shown.motion != Motion::None {
          return;
        }
        match event.phase {
          GesturePhase::Start | GesturePhase::Change => {
            drop(shown);
            drag.set(event.translation.max(0.0));
          }
          GesturePhase::End => {
            let far = event.translation > shown.width * motion.back_share || event.velocity > motion.back_speed;
            // The speed the screen goes on with: the finger's, towards where the screen is going, over the
            // way it has left.
            let (towards, left) = if far {
              (event.velocity, shown.width - event.translation)
            } else {
              (-event.velocity, event.translation)
            };
            shown.velocity = if left > 1.0 {
              f64::from(towards.max(0.0) * motion.duration.as_secs_f32() / left)
            } else {
              0.0
            };
            if far {
              // The screen goes on out from where the finger left it, as the stack goes back: the drag is let go once
              // that has started. Going back runs as from any other source, from the top screen: where the screen
              // takes it (something unsaved, a question first) or nothing moves this stack, the screen comes back.
              drop(shown);
              let before = navigator.handle.current_entry();
              let (navigator, shown, drag, settle, changed) = (
                navigator.clone(),
                shown_all.clone(),
                drag.clone(),
                settle.clone(),
                changed.clone(),
              );
              history.run_in_then(&screen, NavigationCommand::Back, NavigationSource::Edge, move |_| {
                if navigator.handle.current_entry() != before {
                  return;
                }
                shown.lock().motion = Motion::Returning;
                drag.set(NO_DRAG);
                settle.restart();
                changed.update(|version| *version += 1);
              });
            } else {
              shown.motion = Motion::Returning;
              drop(shown);
              drag.set(NO_DRAG);
              settle.restart();
              changed.update(|version| *version += 1);
            }
          }
        }
      }
    });

    // The bar of tabs under the stack goes with a screen that hides it, as far as that screen is in.
    {
      let hides = |id: Option<u64>| {
        shown
          .layers
          .iter()
          .chain(shown.leaving.iter())
          .find(|layer| Some(layer.entry.id) == id)
          .map(|layer| if layer.bar.item.lock().hides_tab_bar { 1.0 } else { 0.0 })
      };
      let front_hides: f32 = hides(front).unwrap_or(0.0);
      let hidden = front_hides * (1.0 - out) + hides(back).unwrap_or(front_hides) * out;
      shown.tab_bar = super::tabs::BarMove { hidden, pace, curve };
      shown.tab_link = ctx.use_context::<super::tabs::TabBarLink>();
      shown.sheet = ctx.use_context::<super::sheet::SheetScroll>();
    }

    let Some(bar) = props.bar else {
      return screens.into();
    };
    let bar = match bar {
      Bar::Standard(bar) => bar.adapted(&system, text_scale),
      Bar::Custom(builder) => {
        let layers: Vec<&Layer> = shown.layers.iter().chain(shown.leaving.iter()).collect();
        let screen_of = |id: Option<u64>| {
          let index = layers.iter().position(|layer| Some(layer.entry.id) == id)?;
          let layer = layers[index];
          let item = layer.bar.item.lock().clone();
          Some(NavigationBarScreen {
            large_title_in_view: item.large_title && !low && !layer.bar.title_gone.load(Ordering::Acquire),
            searching: layer.bar.searching.get(),
            item,
            back_label: index
              .checked_sub(1)
              .map(|under| back_label_of(&layers[under].bar.item.lock(), &style.back)),
          })
        };
        let Some(top) = screen_of(front) else {
          return screens.into();
        };
        let state = NavigationBarState {
          top,
          under: screen_of(back),
          out,
          duration: pace,
          easing: curve,
          width,
          safe_area,
          navigator: navigator.clone(),
          under_titles: shown
            .layers
            .iter()
            .rev()
            .skip(1)
            .map(|layer| back_label_of(&layer.bar.item.lock(), &style.back))
            .collect(),
          low,
        };
        drop(shown);
        return Column::new()
          .size(FILL, FILL)
          .child(builder(&state))
          .child(Column::new().width(FILL).flex(1.0).child(screens))
          .into();
      }
    };

    // The bar: the front screen's item, and the back screen's while they move.
    let layers: Vec<&Layer> = shown.layers.iter().chain(shown.leaving.iter()).collect();
    let part_of = |id: Option<u64>| {
      let index = layers.iter().position(|layer| Some(layer.entry.id) == id)?;
      let layer = layers[index];
      let back_label = index
        .checked_sub(1)
        .map(|under| back_label_of(&layers[under].bar.item.lock(), &style.back));
      // Taken and let go here: a lock taken inside the struct below would be held to its end.
      let item = layer.bar.item.lock().clone();
      let title_shown = !item.large_title || low || layer.bar.title_gone.load(Ordering::Acquire);
      Some(BarPart {
        item,
        back_label,
        label_fit: layer.bar.label_fit,
        title: layer.bar.title.clone(),
        back_probe: layer.bar.back_probe.clone(),
        title_shown,
        title_fade: motion.title_fade,
        // The bar less, at each side, the least a way back takes: its arrow and the word for it.
        title_room: (width - safe_area.left - safe_area.right - 2.0 * (BACK_LEADING + BACK_WIDTH + BACK_GAP)).max(0.0),
        label: layer.bar.label.clone(),
        label_hidden: false,
        short_probe: layer.bar.short_probe.clone(),
        searching: layer.bar.searching.get(),
        button_shapes: system.button_shapes,
      })
    };
    let (back_part, mut front_part) = (part_of(back), part_of(front));
    // The screens under the top one, the nearest first: what a long press on the way back lists.
    let menu_titles: Vec<String> = shown
      .layers
      .iter()
      .rev()
      .skip(1)
      .map(|layer| back_label_of(&layer.bar.item.lock(), &style.back))
      .collect();

    // A large title in view on the screen behind goes to the front screen's way back as that screen comes
    // in, and back as it goes out: one title, drawn here over both, between the two places.
    let layer_of = |id: Option<u64>| layers.iter().copied().find(|layer| Some(layer.entry.id) == id);
    let flight = match (layer_of(back), layer_of(front), &back_part, &front_part) {
      (Some(under), Some(over), Some(under_part), Some(over_part))
        if under_part.item.large_title
          && under_part.item.large_title_view.is_none()
          && !low
          && !under.bar.title_gone.load(Ordering::Acquire)
          && !under_part.item.bar_hidden
          && !over_part.item.bar_hidden
          && over_part.item.leading.is_none()
          && over_part.back_label.is_some()
          && under.bar.large.is_attached() =>
      {
        let origin = self.origin.rect();
        let large = under.bar.large.rect();
        let label = over.bar.label.rect();
        // Until the label is laid out, at the push's first frame, it is taken to be where the title is: the
        // title is all there is to see then.
        let label = if over.bar.label.is_attached() && label.2 > 0.0 {
          label
        } else {
          (
            large.0,
            large.1,
            large.2 * bar.text_size / bar.large_title_size,
            large.3 * bar.text_size / bar.large_title_size,
          )
        };
        (large.2 > 0.0 && large.3 > 0.0).then(|| Flight {
          title: under_part.item.title.clone(),
          says: match over_part.label_fit {
            LabelFit::Whole => over_part.back_label.clone().unwrap_or_default(),
            LabelFit::Short => back_word(&bar),
            LabelFit::Arrow => String::new(),
          },
          large: (large.0 - origin.0, large.1 - origin.1, large.2, large.3),
          label: (label.0 - origin.0, label.1 - origin.1, label.2, label.3),
        })
      }
      _ => None,
    };
    for layer in &layers {
      let flying = flight.is_some() && Some(layer.entry.id) == back;
      if layer.bar.flying.get_untracked() != flying {
        layer.bar.flying.set(flying);
      }
    }
    if let (Some(_), Some(part)) = (&flight, &mut front_part) {
      part.label_hidden = true;
    }
    let overlay = Stack::new().size(FILL, FILL).pointer_events_none();
    let overlay = match &flight {
      Some(flight) => flight.draw(overlay, &bar, out, pace, curve),
      None => overlay,
    };
    // Between two screens, what the bar has of each is between theirs, as far as the front one is out: its
    // height, its color, the line under it and the toolbar come and go with the screens, and with a finger,
    // and not after them.
    let between = |of: &dyn Fn(&BarPart) -> f32| {
      let front = front_part.as_ref().map_or(1.0, of);
      front * (1.0 - out) + back_part.as_ref().map_or(front, of) * out
    };
    // Whether there is a bar at all, how much of it is over the status bar's room (none while a screen
    // searches: the field takes the bar's place), the room a prompt takes, and whether it has its color.
    let shown_share = between(&|part| if part.item.bar_hidden { 0.0 } else { 1.0 });
    let bar_share = between(&|part| if part.searching { 0.0 } else { 1.0 });
    let prompt_share = between(&|part| if part.item.prompt.is_some() { 1.0 } else { 0.0 });
    let lined = between(&|part| if part.title_shown { 1.0 } else { 0.0 });
    let toolbar_share = between(&|part| {
      if part.item.toolbar.is_some() && !part.item.bar_hidden {
        1.0
      } else {
        0.0
      }
    });
    let (line_pace, line_curve) = if moving {
      (pace, curve)
    } else if back.is_some() {
      (Duration::ZERO, curve)
    } else {
      (motion.title_fade, Easing::EASE)
    };
    let fade = |opacity: f32| {
      move |element: Row| {
        element
          .opacity(opacity)
          .transition(Transition::opacity().duration(pace).easing(curve))
      }
    };
    let toolbar_of = |part: &Option<BarPart>, opacity: f32, front: bool| {
      let tools = part.as_ref()?.item.toolbar.clone()?;
      let row = Row::new()
        .width(FILL)
        .height(bar.toolbar_height)
        .align_items(Alignment::Center)
        .padding_horizontal(16.0)
        .child(tools);
      let row = if front { row } else { row.pointer_events_none() };
      Some(fade(opacity)(row))
    };
    let mut tools = Stack::new().width(FILL).height(bar.toolbar_height);
    for tool in [
      toolbar_of(&back_part, out, false),
      toolbar_of(&front_part, 1.0 - out, true),
    ]
    .into_iter()
    .flatten()
    {
      tools = tools.child(tool);
    }

    let items_height = bar_height + bar.prompt_height * prompt_share;
    let mut items = Stack::new()
      .width(FILL)
      .height(items_height)
      .stack_align(StackAlignment::BottomStart);
    if let Some(part) = back_part {
      items = items.child(bar_item(
        &bar,
        &go_back,
        part,
        out,
        if reduce_motion {
          0.0
        } else {
          -(1.0 - out) * width * motion.parallax
        },
        pace,
        curve,
        false,
        &self.menu,
        bar_height,
      ));
    }
    if let Some(part) = front_part {
      items = items.child(bar_item(
        &bar,
        &go_back,
        part,
        1.0 - out,
        if reduce_motion { 0.0 } else { out * width * 0.5 },
        pace,
        curve,
        true,
        &self.menu,
        bar_height,
      ));
    }
    drop(shown);

    // The bar, over the top of the screens: what is under it shows through, blurred, where the bar's color
    // lets it.
    let over = Column::new()
      .width(FILL)
      .child(
        Column::new()
          .width(FILL)
          .height((safe_area.top + items_height * bar_share) * shown_share)
          .clip()
          // Over a large title still in view the bar has no color of its own: it is one with what is behind
          // the screens.
          .background(Color::new(
            bar.background.r(),
            bar.background.g(),
            bar.background.b(),
            (f32::from(bar.background.a()) * lined).round() as u8,
          ))
          .backdrop_blur(bar.blur * lined)
          .transition(Transition::height().duration(line_pace).easing(line_curve))
          .transition(Transition::background_color().duration(line_pace).easing(line_curve))
          .transition(Transition::backdrop_blur().duration(line_pace).easing(line_curve))
          .child(
            Column::new()
              .width(FILL)
              .padding_top(safe_area.top)
              .padding_left(safe_area.left)
              .padding_right(safe_area.right)
              .child(items),
          ),
      )
      .child(
        Row::new()
          .width(FILL)
          .height(0.5 * shown_share)
          .background(bar.border)
          .opacity(lined * bar_share)
          .transition(Transition::opacity().duration(line_pace).easing(line_curve)),
      );
    // A screen's toolbar: across the bottom, over the home indicator's room and over the screen, whose list
    // shows through it as it does through the bar.
    let toolbar = Column::new()
      .width(FILL)
      .height((bar.toolbar_height + safe_area.bottom + 0.5) * toolbar_share)
      .clip()
      .align(Alignment::End)
      .transition(Transition::height().duration(line_pace).easing(line_curve))
      .background(bar.background)
      .backdrop_blur(bar.blur)
      .child(Row::new().width(FILL).height(0.5).background(bar.border))
      .child(
        Column::new()
          .width(FILL)
          .padding_left(safe_area.left)
          .padding_right(safe_area.right)
          .child(tools),
      );
    let mut whole = Stack::new()
      .size(FILL, FILL)
      .ref_element(self.origin.clone())
      .stack_align(StackAlignment::TopStart)
      .child(screens)
      .child(toolbar)
      .child(over)
      .child(overlay);
    if bar.back_menu && !menu_titles.is_empty() {
      // The list of the screens under, over everything: a tap on a screen's name goes back to it, and a tap
      // anywhere else puts the list away. It is always there, unseen and untouched while closed, so that it
      // comes and goes with a move of its own.
      let opening = Transition::all()
        .duration(MENU_MOVE)
        .easing(Easing::Spring { velocity: 0.0 });
      let mut list = Column::new()
        .width(bar.back_menu_width)
        .background(bar.background)
        .backdrop_blur(bar.blur)
        .border_inside(0.5, bar.border)
        .rounded(13.0)
        .clip()
        .absolute_position(safe_area.left + 8.0, safe_area.top + bar_height + 4.0)
        .opacity(if menu_open { 1.0 } else { 0.0 })
        .transform(Transform2D::scale_uniform(if menu_open { 1.0 } else { 0.8 }))
        .transition(opening);
      for (steps, title) in menu_titles.iter().enumerate() {
        let (navigator, open) = (navigator.clone(), self.menu.open.clone());
        let steps = steps + 1;
        if steps > 1 {
          list = list.child(Row::new().width(FILL).height(0.5).background(bar.border));
        }
        list = list.child(
          Row::new()
            .width(FILL)
            .height(bar.height)
            .align_items(Alignment::Center)
            .padding_horizontal(bar.inset)
            .child(
              Text::styled(
                title,
                TextStyle {
                  font_size: bar.text_size,
                  color: bar.title,
                  ..TextStyle::default()
                },
              )
              .nowrap(),
            )
            .on_click(move |_| {
              open.set(false);
              navigator.back_by(steps);
            }),
        );
      }
      let close = self.menu.clone();
      let layer = Stack::new()
        .size(FILL, FILL)
        .child(
          Row::new()
            .size(FILL, FILL)
            .background(shades.menu)
            .opacity(if menu_open { shades.menu_opacity } else { 0.0 })
            .transition(Transition::opacity().duration(MENU_MOVE))
            .on_click(move |_| {
              // The list came up under the finger that opened it, whose lift is not a tap beside the list.
              let just_opened = close.opened_at.lock().is_some_and(|at| at.elapsed() < MENU_OPENING);
              if !just_opened {
                close.open.set(false);
              }
            }),
        )
        .child(list);
      whole = whole.child(if menu_open { layer } else { layer.pointer_events_none() });
    }
    whole.into()
  }

  fn after_layout(&self) {
    let mut shown = self.shown.lock();
    if std::mem::take(&mut shown.begin_due) {
      self.begin.restart();
    }
    if let Some(link) = &shown.tab_link
      && link.0.get_untracked() != shown.tab_bar
    {
      link.0.set(shown.tab_bar);
    }
    // A sheet the stack is in gives a finger to its top screen's list, and takes it at that list's top.
    if let (Some(sheet), Some(top)) = (&shown.sheet, shown.layers.last()) {
      let list = top.bar.under.load(Ordering::Acquire).then(|| top.bar.scroll.clone());
      let mut told = sheet.0.lock();
      let same = match (&*told, &list) {
        (Some(a), Some(b)) => a.same(b),
        (None, None) => true,
        _ => false,
      };
      if !same {
        *told = list;
      }
    }
    // Which way the top screen's list last went, by more than a finger's tremble; at its top it has gone
    // nowhere.
    if let Some(at) = shown.layers.last().map(|layer| layer.bar.scroll.scroll_y()) {
      let moved = at - shown.last_scroll;
      if at <= 0.0 {
        shown.scrolled_down = false;
      } else if moved > 4.0 {
        shown.scrolled_down = true;
      } else if moved < -4.0 {
        shown.scrolled_down = false;
      }
      if moved.abs() > 4.0 || at <= 0.0 {
        shown.last_scroll = at;
      }
      if let Some(link) = &shown.tab_link
        && link.1.get_untracked() != shown.scrolled_down
      {
        link.1.set(shown.scrolled_down);
      }
    }
    for layer in shown.layers.iter().chain(shown.leaving.iter()) {
      let top = *layer.bar.top_now.lock();
      if layer.bar.top.get_untracked() != top {
        layer.bar.top.set(top);
      }
    }
    // Whether each way back has room for its label beside the title, now that both are laid out. The title
    // is in the middle of the bar, so the label has half of what the title leaves.
    let (width, large_title_height) = (shown.width, shown.large_title_height);
    let shown = &mut *shown;
    let mut changed = false;
    for layer in shown.layers.iter_mut().chain(shown.leaving.iter_mut()) {
      if !layer.bar.title.is_attached() || !layer.bar.back_probe.is_attached() {
        continue;
      }
      let room = (width - layer.bar.title.width()) / 2.0 - BACK_LEADING - BACK_GAP;
      let short = if layer.bar.short_probe.is_attached() {
        layer.bar.short_probe.width()
      } else {
        BACK_WIDTH
      };
      let fit = if layer.bar.back_probe.width() <= room {
        LabelFit::Whole
      } else if short <= room {
        LabelFit::Short
      } else {
        LabelFit::Arrow
      };
      changed |= std::mem::replace(&mut layer.bar.label_fit, fit) != fit;
    }
    // Whether each large title has scrolled out of view, all but its last few points: the bar's own title
    // comes in then. Looked at after every layout, which every scroll ends in, however it was scrolled.
    for layer in shown.layers.iter().chain(shown.leaving.iter()) {
      let gone = layer.bar.scroll.scroll_y() > large_title_height - 8.0;
      changed |= layer.bar.title_gone.swap(gone, Ordering::AcqRel) != gone;
      // And how far the content is pulled down past its top: the large title is drawn anew for it.
      let pull = (-layer.bar.scroll.overscroll().1).max(0.0);
      if (layer.bar.pull.get_untracked() - pull).abs() > 0.25 {
        layer.bar.pull.set(pull);
      }
    }
    if changed {
      self.changed.update(|version| *version += 1);
    }
  }
}

/// How much of a way back's label the bar has room for, beside the title.
#[derive(Clone, Copy, PartialEq)]
enum LabelFit {
  /// The title of the screen under.
  Whole,
  /// The word for going back.
  Short,
  /// Neither: the arrow alone.
  Arrow,
}

/// The word for going back: the bar's, or the app's locale's where the bar has none.
fn back_word(bar: &NavigationBar) -> String {
  if bar.back.is_empty() {
    crate::ui::current_locale().common.back.to_string()
  } else {
    bar.back.clone()
  }
}

/// What the way back to a screen says.
fn back_label_of(under: &NavigationItem, back: &str) -> String {
  match &under.back_title {
    Some(title) => title.clone(),
    None if under.title.is_empty() && back.is_empty() => crate::ui::current_locale().common.back.to_string(),
    None if under.title.is_empty() => back.to_owned(),
    None => under.title.clone(),
  }
}

/// The list a long press on the way back opens: whether it is open, and when it opened, since the finger
/// that opened it is then still down and its lift is not a tap.
#[derive(Clone)]
struct BackMenu {
  open: Signal<bool>,
  opened_at: Arc<Mutex<Option<Instant>>>,
}

/// A large title on its way between the content of the screen behind and the way back of the screen in
/// front: where it is at each end, in the outlet, and what it says there.
struct Flight {
  title: String,
  says: String,
  large: (f32, f32, f32, f32),
  label: (f32, f32, f32, f32),
}

impl Flight {
  /// Adds the title to `overlay`, `out` of the way from the label to the content. Where the label says the
  /// title, one text goes between the two, shrinking and taking the label's color as it nears it. Where it says
  /// something else ("Back"), the large one shrinks and fades as it nears the label, and the label grows and
  /// fades as it nears the content.
  fn draw(&self, overlay: Stack, bar: &NavigationBar, out: f32, pace: Duration, curve: Easing) -> Stack {
    let between = |at_label: f32, at_large: f32| at_label + (at_large - at_label) * out;
    let centre = (
      between(self.label.0 + self.label.2 / 2.0, self.large.0 + self.large.2 / 2.0),
      between(self.label.1 + self.label.3 / 2.0, self.large.1 + self.large.3 / 2.0),
    );
    let part = |says: &str, size: f32, weight: FontWeight, color: Color, laid: (f32, f32), scale: f32, opacity: f32| {
      Text::styled(
        says,
        TextStyle {
          font_size: size,
          weight,
          color,
          ..TextStyle::default()
        },
      )
      .nowrap()
      // Laid out at the outlet's corner, scaled about its middle and then put where it goes.
      .transform(
        Transform2D::translate(centre.0 - laid.0 / 2.0, centre.1 - laid.1 / 2.0)
          .then(&Transform2D::scale_uniform(scale)),
      )
      .opacity(opacity)
      .transition(Transition::transform().duration(pace).easing(curve))
      .transition(Transition::opacity().duration(pace).easing(curve))
    };
    let ratio = if self.large.3 > 0.0 && self.label.3 > 0.0 {
      self.label.3 / self.large.3
    } else {
      bar.text_size / bar.large_title_size
    };
    // The way back says the title: one text goes between the two, and turns from the title's color to the way
    // back's. Two of it fading across each other, bold over regular, are seen as one title drawn twice.
    if self.says == self.title {
      let mix = |at_label: u8, at_large: u8| between(f32::from(at_label), f32::from(at_large)).round() as u8;
      let (label, large) = (bar.tint, bar.title);
      return overlay.child(
        part(
          &self.title,
          bar.large_title_size,
          bar.large_title_weight,
          // The default color, which names none: the text takes the foreground below.
          TextStyle::default().color,
          (self.large.2, self.large.3),
          between(ratio, 1.0),
          1.0,
        )
        .foreground(Color::new(
          mix(label.r(), large.r()),
          mix(label.g(), large.g()),
          mix(label.b(), large.b()),
          mix(label.a(), large.a()),
        ))
        .transition(Transition::foreground().duration(pace).easing(curve)),
      );
    }
    overlay
      .child(part(
        &self.title,
        bar.large_title_size,
        bar.large_title_weight,
        bar.title,
        (self.large.2, self.large.3),
        between(ratio, 1.0),
        out,
      ))
      .child(part(
        &self.says,
        bar.text_size,
        FontWeight::Normal,
        bar.tint,
        (self.label.2, self.label.3),
        between(1.0, 1.0 / ratio),
        1.0 - out,
      ))
  }
}

/// One screen's part of the bar.
struct BarPart {
  item: NavigationItem,
  /// What the way back says when there is room; `None` on the screen at the bottom, which has none.
  back_label: Option<String>,
  label_fit: LabelFit,
  title: ElementRef,
  back_probe: ElementRef,
  /// The title is in the bar: always, but for a large title that is still in view in the content.
  title_shown: bool,
  title_fade: Duration,
  /// The most room the title has: what it does not fit in, it gives up with an ellipsis.
  title_room: f32,
  /// The way back's label as it is laid out, and whether it is left out of view: while the outlet carries
  /// the title of the screen under to it or away.
  label: ElementRef,
  label_hidden: bool,
  short_probe: ElementRef,
  /// The screen's search field is being typed into: it has the bar's place.
  searching: bool,
  /// What can be pressed is to look so: the way back's label is underlined.
  button_shapes: bool,
}

/// One screen's part of the bar: its title in the middle, the way back before it and what the screen put at
/// the end. `shift` is how far the title is from the middle.
fn bar_item(
  bar: &NavigationBar,
  go_back: &GoBack,
  part: BarPart,
  opacity: f32,
  shift: f32,
  pace: Duration,
  curve: Easing,
  front: bool,
  menu: &BackMenu,
  bar_height: f32,
) -> Element {
  let text = |content: &str, weight: FontWeight, color: Color| {
    Text::styled(
      content,
      TextStyle {
        font_size: if weight == bar.title_weight {
          bar.title_size
        } else {
          bar.text_size
        },
        weight,
        color,
        ..TextStyle::default()
      },
    )
    .nowrap()
  };
  let middle: Element = match &part.item.title_view {
    Some(view) => view.clone(),
    None => text(&part.item.title, bar.title_weight, bar.title)
      .max_width(part.title_room)
      .text_overflow(TextOverflow::Elipsis)
      .into(),
  };
  let title = Row::new()
    .size(FILL, FILL)
    .align_items(Alignment::Center)
    .justify(Justify::Center)
    .pointer_events_none()
    .child(
      Row::new()
        .ref_element(part.title.clone())
        .child(middle)
        .opacity(if part.title_shown { 1.0 } else { 0.0 })
        .transition(Transition::opacity().duration(part.title_fade)),
    )
    .transform(Transform2D::translate(shift, 0.0))
    .transition(Transition::transform().duration(pace).easing(curve));

  let mut whole = Stack::new().width(FILL).height(bar_height).child(title);
  let mut sides = Row::new().size(FILL, FILL).align_items(Alignment::Center);
  if let Some(leading) = &part.item.leading {
    sides = sides.child(
      Row::new()
        .align_items(Alignment::Center)
        .padding_left(8.0)
        .child(leading.clone()),
    );
  } else if let Some(label) = &part.back_label {
    let go_back = go_back.clone();
    let short = back_word(bar);
    let says = match part.label_fit {
      LabelFit::Whole => label.as_str(),
      LabelFit::Short => short.as_str(),
      LabelFit::Arrow => "",
    };
    sides = sides.child(
      Row::new()
        .id("navigation-back")
        .align_items(Alignment::Center)
        .height(FILL)
        .padding_left(BACK_LEADING - CHEVRON_WIDTH - BACK_SPACING)
        .padding_right(12.0)
        .spacing(BACK_SPACING)
        .child(chevron(bar.tint))
        .child(
          Column::new()
            .child(
              text(says, FontWeight::Normal, bar.tint)
                .ref_element(part.label.clone())
                .opacity(if part.label_hidden { 0.0 } else { 1.0 }),
            )
            // With button shapes asked for, a line under the label says it can be pressed.
            .child(Row::new().width(FILL).height(1.0).background(bar.tint).opacity(
              if part.button_shapes && !part.label_hidden && !says.is_empty() {
                1.0
              } else {
                0.0
              },
            )),
        )
        .on_click({
          let menu = menu.clone();
          move |_| {
            // The lift of the press that opened the list is not a tap.
            if !menu.open.get_untracked() {
              go_back();
            }
          }
        })
        .on_long_press({
          let menu = menu.clone();
          let enabled = bar.back_menu;
          move |_: LongPressEvent| {
            if enabled {
              *menu.opened_at.lock() = Some(Instant::now());
              menu.open.set(true);
            }
          }
        }),
    );
    // The word for going back, and the whole label, laid out and not seen, for their widths.
    whole = whole.child(
      Row::new().opacity(0.0).pointer_events_none().child(
        Row::new()
          .ref_element(part.short_probe.clone())
          .child(text(&back_word(bar), FontWeight::Normal, bar.tint)),
      ),
    );
    whole =
      whole.child(
        Row::new().opacity(0.0).pointer_events_none().child(
          Row::new()
            .ref_element(part.back_probe.clone())
            .child(text(label, FontWeight::Normal, bar.tint)),
        ),
      );
  }
  sides = sides.child(Row::new().flex(1.0));
  if let Some(trailing) = &part.item.trailing {
    sides = sides.child(
      Row::new()
        .align_items(Alignment::Center)
        .padding_right(8.0)
        .child(trailing.clone()),
    );
  }

  let main = whole.child(sides);
  // A prompt stands over the title, in the bar's own room for it.
  let mut whole = Column::new().width(FILL);
  if let Some(prompt) = &part.item.prompt {
    whole = whole.child(
      Row::new()
        .width(FILL)
        .height(bar.prompt_height)
        .align_items(Alignment::End)
        .justify(Justify::Center)
        .pointer_events_none()
        .child(
          Text::styled(
            prompt,
            TextStyle {
              font_size: bar.prompt_size,
              color: bar.title,
              ..TextStyle::default()
            },
          )
          .nowrap(),
        ),
    );
  }
  let mut whole = whole.child(main).opacity(opacity);
  if !front {
    whole = whole.pointer_events_none();
  }
  whole
    .transition(Transition::opacity().duration(pace).easing(curve))
    .into()
}

/// The way back's arrow: the platform's symbol on iOS with the `raster` feature, and otherwise two strokes
/// that meet at a point on the left, drawn after it.
#[allow(deprecated)]
fn chevron(color: Color) -> Element {
  // The platform's own, where there is a platform to ask and images to show it with.
  #[cfg(all(target_os = "ios", feature = "raster"))]
  if let Some(symbol) = crate::app::ios_symbol::symbol("chevron.backward", CHEVRON_POINT_SIZE, color) {
    return crate::components::Image::new(symbol.image)
      .width(symbol.width)
      .height(symbol.height)
      .into();
  }
  // Each stroke goes from the point, at the middle of the left side, to a corner on the right.
  let (rise, run) = (
    CHEVRON_HEIGHT / 2.0 - CHEVRON_STROKE / 2.0,
    CHEVRON_WIDTH - CHEVRON_STROKE,
  );
  let length = rise.hypot(run) + CHEVRON_STROKE;
  let angle = rise.atan2(run);
  let stroke = |up: bool| {
    let (centre_x, centre_y) = (
      CHEVRON_STROKE / 2.0 + run / 2.0,
      CHEVRON_HEIGHT / 2.0 + if up { -rise / 2.0 } else { rise / 2.0 },
    );
    Row::new()
      .width(length)
      .height(CHEVRON_STROKE)
      .rounded(CHEVRON_STROKE / 2.0)
      .background(color)
      .transform(
        Transform2D::translate(centre_x - length / 2.0, centre_y - CHEVRON_STROKE / 2.0)
          .then(&Transform2D::rotate(if up { -angle } else { angle })),
      )
  };
  Stack::new()
    .width(CHEVRON_WIDTH)
    .height(CHEVRON_HEIGHT)
    .child(stroke(true))
    .child(stroke(false))
    .into()
}

impl StackOutlet {
  /// A screen's content under its large title ([`NavigationItem::large_title`]), the two scrolling as one: the
  /// title goes up out of view with the content, and the bar's own title comes in when it has. Call it in the
  /// screen's `render`, after `ctx.navigation_item`. Outside a stack, or for a screen whose item asks for no
  /// large title, it is the content in a list that scrolls.
  pub fn large_title_scroll(ctx: &mut Ctx, content: impl Into<Element>) -> ScrollVertical {
    let Some(slot) = ctx.use_context::<NavigationSlot>() else {
      return ScrollVertical::new(content.into());
    };
    let item = slot.item.lock().clone();
    let style = slot.style.clone();
    // While the search field is typed into, it stands where the bar was and there is no large title.
    let searching = (item.search.is_some() || item.search_view.is_some()) && slot.searching.get();
    let mut over = Column::new().width(FILL);
    // A window too low for it, a phone on its side, has the title in the bar alone.
    let tall = ctx.window().logical_height() >= style.low_window;
    if let (Some(view), true) = (&item.large_title_view, item.large_title && tall) {
      // The screen's own title, in the same place and with no height while the screen searches.
      over = over.child(
        Row::new()
          .width(FILL)
          .ref_element(slot.large.clone())
          .height(if searching { Dimension::Px(0.0) } else { Dimension::Auto })
          .clip()
          .child(view.clone()),
      );
    } else if item.large_title && tall {
      // Still there while the screen searches, with no height: taken out, the field under it would be
      // another element, and the one being typed into would be gone.
      over = over.child(ctx.mount_keyed::<LargeTitle>(
        "navigation-large-title",
        LargeTitleProps {
          title: item.title.clone(),
          style: style.clone(),
          pull: slot.pull.clone(),
          large: slot.large.clone(),
          flying: slot.flying.clone(),
          growth: slot.growth,
          folded: searching,
        },
      ));
    }
    if let Some(view) = &item.search_view {
      over = over.child(Row::new().width(FILL).child(view.clone()));
    } else if let Some(search) = &item.search {
      over = over.child(ctx.mount_keyed::<SearchField>(
        "navigation-search",
        SearchFieldProps {
          search: search.clone(),
          style: style.clone(),
          searching: slot.searching.clone(),
        },
      ));
    }
    // The list goes on under the bar, and under a bar of tabs: its content is what keeps clear of them.
    if !slot.under.swap(true, Ordering::AcqRel) {
      slot.changed.update(|version| *version += 1);
    }
    let bottom = ctx.safe_area().bottom;
    ScrollVertical::new(
      Column::new()
        .width(FILL)
        .padding_top(slot.top.get())
        .padding_bottom(bottom)
        .child(over.child(content.into())),
    )
    .with_scroll_state(slot.scroll.clone())
  }

  /// Whether this screen is searching, to read and to set; `None` outside a stack. The outlet's own search
  /// field sets it. A field of the screen's own ([`NavigationItem::search_view`]) sets it itself, when it is
  /// given the focus and when its search is cancelled.
  pub fn searching(ctx: &mut Ctx) -> Option<Signal<bool>> {
    ctx.use_context::<NavigationSlot>().map(|slot| slot.searching)
  }

  /// How much of this screen the bar is over, from the top: what the list of
  /// [`large_title_scroll`](Self::large_title_scroll) keeps its content clear of. 0 outside a stack. For what
  /// stands over that list at its top, as the spinner of a [`PullToRefresh`](super::PullToRefresh) does.
  pub fn bar_inset(ctx: &mut Ctx) -> f32 {
    ctx.use_context::<NavigationSlot>().map_or(0.0, |slot| slot.top.get())
  }

  /// The state of the list [`large_title_scroll`](Self::large_title_scroll) makes for this screen, to set it
  /// up or to scroll it; `None` outside a stack.
  pub fn screen_scroll(ctx: &mut Ctx) -> Option<ScrollState> {
    ctx.use_context::<NavigationSlot>().map(|slot| slot.scroll)
  }

  /// A stack of screens with no bar.
  pub fn mount(ctx: &mut Ctx) -> Element {
    ctx.mount::<Self>(StackOutletProps::default())
  }

  pub fn mount_with(ctx: &mut Ctx, props: StackOutletProps) -> Element {
    ctx.mount::<Self>(props)
  }
}

#[derive(Clone)]
struct SearchFieldProps {
  search: NavigationSearch,
  style: Arc<NavigationBar>,
  searching: Signal<bool>,
}

impl PartialEq for SearchFieldProps {
  fn eq(&self, other: &Self) -> bool {
    self.search.key() == other.search.key() && self.style == other.style && self.searching.id() == other.searching.id()
  }
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for SearchFieldProps {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

/// A screen's search field: a rounded field with a magnifying glass, and beside it, while it is typed into,
/// the way to cancel.
struct SearchField {
  /// Counts the taps on the way to cancel, and the last of them the field has acted on.
  cancelled: Signal<u64>,
  acted: Mutex<u64>,
  focused: Signal<bool>,
}

impl Component for SearchField {
  type Props = SearchFieldProps;

  fn create(_ctx: &mut Ctx) -> Self {
    Self {
      cancelled: Signal::new(0),
      acted: Mutex::new(0),
      focused: Signal::new(false),
    }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let props = ctx.props::<SearchFieldProps>().clone();
    // The search goes on while the field has the focus, and after, while something is typed in it: until it
    // is cancelled. The outlet and the screen are told when that changes.
    let searching = self.focused.get() || !props.search.text.get().is_empty();
    // A field that leaves the bar where it is does not say it is searched in: nothing gives way to it.
    let takes_bar = searching && props.search.hides_bar;
    if props.searching.get_untracked() != takes_bar {
      props.searching.set(takes_bar);
    }
    // A tap on the way to cancel puts the keyboard away: the field loses the focus after this render.
    let cancelled = self.cancelled.get();
    if std::mem::replace(&mut *self.acted.lock(), cancelled) != cancelled {
      ctx.blur();
    }
    let bar = &props.style;
    let faint = |alpha: u8| Color::new(bar.title.r(), bar.title.g(), bar.title.b(), alpha);
    let (ground, placeholder) = (
      bar.search_background.unwrap_or(faint(30)),
      bar.search_placeholder.unwrap_or(faint(150)),
    );
    let style = |color: Color| TextStyle {
      font_size: bar.text_size,
      color,
      ..TextStyle::default()
    };
    let (focused, blurred) = (self.focused.clone(), self.focused.clone());
    let field = Row::new()
      .flex(1.0)
      .height(bar.search_height)
      .align_items(Alignment::Center)
      .padding_horizontal(8.0)
      .spacing(6.0)
      .rounded(10.0)
      .background(ground)
      .child(magnifier(placeholder))
      .child(
        TextInput::new(props.search.text.clone())
          .placeholder(&props.search.placeholder)
          .placeholder_style(style(placeholder))
          .text_style(style(bar.title))
          .single_line()
          .keyboard(KeyboardKind::Search)
          .return_key(ReturnKey::Search)
          .flex(1.0)
          .on_focus(move || focused.set(true))
          .on_blur(move || blurred.set(false)),
      );
    let mut row = Row::new()
      .id("navigation-search")
      .width(FILL)
      .align_items(Alignment::Center)
      .padding_horizontal(bar.inset)
      .padding_top(if takes_bar { 8.0 } else { 0.0 })
      .padding_bottom(8.0)
      .spacing(12.0)
      .child(field);
    if searching {
      let (text, cancelled) = (props.search.text.clone(), self.cancelled.clone());
      row = row.child(
        Row::new()
          .id("navigation-search-cancel")
          .height(bar.search_height)
          .align_items(Alignment::Center)
          .child(Text::styled(&props.search.cancel, style(bar.tint)).nowrap())
          .on_click(move |_| {
            text.set(String::new());
            cancelled.update(|count| *count += 1);
          }),
      );
    }
    row
  }
}

/// A magnifying glass: the platform's symbol where there is one to ask, and otherwise a ring with a handle.
#[allow(deprecated)]
fn magnifier(color: Color) -> Element {
  #[cfg(all(target_os = "ios", feature = "raster"))]
  if let Some(symbol) = crate::app::ios_symbol::symbol("magnifyingglass", 15.0, color) {
    return crate::components::Image::new(symbol.image)
      .width(symbol.width)
      .height(symbol.height)
      .into();
  }
  Stack::new()
    .width(16.0)
    .height(16.0)
    .child(
      Row::new()
        .width(11.0)
        .height(11.0)
        .rounded(5.5)
        .border_inside(1.6, color)
        .absolute_position(1.0, 1.0),
    )
    .child(
      Row::new()
        .width(6.0)
        .height(1.6)
        .rounded(0.8)
        .background(color)
        .absolute_position(9.5, 11.5)
        .transform(Transform2D::rotate_deg(45.0)),
    )
    .into()
}

#[derive(Clone)]
struct LargeTitleProps {
  title: String,
  style: Arc<NavigationBar>,
  pull: Signal<f32>,
  large: ElementRef,
  flying: Signal<bool>,
  growth: (f32, f32),
  /// The title takes no room: the screen is searching.
  folded: bool,
}

impl PartialEq for LargeTitleProps {
  fn eq(&self, other: &Self) -> bool {
    self.title == other.title
      && self.style == other.style
      && self.pull.id() == other.pull.id()
      && self.growth == other.growth
      && self.folded == other.folded
  }
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for LargeTitleProps {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

/// A screen's large title. It grows a little as the content is pulled down past its top, from its leading
/// edge, as the platform's does: a component of its own, so that only it is rendered for each point pulled.
struct LargeTitle;

impl Component for LargeTitle {
  type Props = LargeTitleProps;

  fn create(_ctx: &mut Ctx) -> Self {
    Self
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let props = ctx.props::<LargeTitleProps>().clone();
    let (growth, pull) = props.growth;
    let grown = if pull > 0.0 {
      1.0 + props.pull.get().min(pull) / pull * (growth - 1.0)
    } else {
      1.0
    };
    Row::new()
      .width(FILL)
      .height(if props.folded {
        0.0
      } else {
        props.style.large_title_height
      })
      .clip()
      .align_items(Alignment::Center)
      .padding_horizontal(props.style.inset)
      .child(
        Text::styled(
          &props.title,
          TextStyle {
            font_size: props.style.large_title_size * grown,
            weight: props.style.large_title_weight,
            color: props.style.title,
            ..TextStyle::default()
          },
        )
        .nowrap()
        .id("navigation-large-title")
        .ref_element(props.large.clone())
        // While the outlet carries the title to or from a way back, this one is not seen.
        .opacity(if props.flying.get() { 0.0 } else { 1.0 }),
      )
  }
}

#[derive(Clone)]
struct StackLayerProps {
  id: u64,
  path: String,
  matches: Arc<Vec<RouteMatch>>,
  depth: usize,
  state: Option<Arc<dyn Any + Send + Sync>>,
  slot: NavigationSlot,
}

impl PartialEq for StackLayerProps {
  fn eq(&self, other: &Self) -> bool {
    // A bar given again in other colors (the system turned dark) reaches the screen's large title, which is
    // drawn in the screen's render.
    self.id == other.id && self.path == other.path && self.depth == other.depth && self.slot.style == other.slot.style
  }
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for StackLayerProps {
  fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}

/// One screen: the route of its history entry, which reads its own params and state whatever the router's
/// current path is.
struct StackLayer;

impl Component for StackLayer {
  type Props = StackLayerProps;

  fn create(_ctx: &mut Ctx) -> Self {
    Self
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let props = ctx.props::<StackLayerProps>().clone();
    ctx.provide(RouterMatches(props.matches.clone()));
    ctx.provide(OutletDepth(props.depth));
    ctx.provide(StackState(props.state.clone()));
    // What the screen says of itself it says in its own render, after this one: this one is run again when
    // that changes what the screen keeps clear of.
    let (has_toolbar, hides_tab_bar) = props.slot.bottom.get();
    let toolbar = props.slot.toolbars && has_toolbar;
    if toolbar {
      // The toolbar is over the screen, above whatever bar is under the stack: the screen keeps clear of
      // both.
      let under = match ctx.use_context::<crate::app::ctx::BottomBarInset>() {
        Some(crate::app::ctx::BottomBarInset::Over(height)) if !hides_tab_bar => height,
        _ => 0.0,
      };
      ctx.provide_if_changed(crate::app::ctx::BottomBarInset::Over(
        under + props.slot.style.toolbar_height + 0.5,
      ));
    } else if hides_tab_bar {
      // A screen that hides the bar of tabs has no bar over its content to keep clear of.
      ctx.provide_if_changed(crate::app::ctx::BottomBarInset::Over(0.0));
    }
    ctx.provide(props.slot.front.clone());
    ctx.provide(props.slot.clone());
    match props.matches.get(props.depth) {
      Some(route_match) => render_route_match(ctx, route_match),
      None => Element::new(),
    }
  }
}