bevy_gooey 0.35.0

Game interfaces made easy for Bevy: a skin, ready-made game widgets (buttons, panels, menus, HUD meters, tooltips, modal dialogs) and keyboard and gamepad navigation, on Bevy's own headless widgets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
//! The engine-free maths under the skin: contrast, compositing, meter fill, the interface's scale
//! against the window and line weights on whole device pixels.
//!
//! Plain functions over `[r, g, b]` arrays in sRGB and plain sizes, testable without an app.
//! [`crate::GooeySkin::problems`] is built on them, and a host or an editor may call them to check
//! its own colours; [`crate::scale_with_window`] on [`window_ui_scale`]; [`crate::apply_skin`] on
//! [`snap_line_width`].

/// The least contrast body text may have against its background: WCAG 2.2, success criterion 1.4.3.
pub const TEXT_CONTRAST: f32 = 4.5;

/// The least contrast a focus indicator or another part of a control may have against what is next
/// to it: WCAG 2.2, success criteria 1.4.11 and 2.4.13.
pub const NON_TEXT_CONTRAST: f32 = 3.0;

/// The contrast a high-contrast mode holds every part of the interface to, against what it is drawn
/// on: WCAG 2.2 success criterion 1.4.6 (Level AAA), and Xbox Accessibility Guideline 102's "7:1 for
/// all UI elements". See [`crate::GooeySkin::high_contrast`].
pub const ENHANCED_CONTRAST: f32 = 7.0;

/// The smallest a pointer target may be, in logical pixels: WCAG 2.2, success criterion 2.5.8.
pub const MIN_TARGET_PX: f32 = 24.0;

/// The default [`crate::GooeySkin::min_target`], in logical pixels: a target a thumb or a pad's
/// focus jump lands on comfortably (WCAG 2.2, success criterion 2.5.5, is 44 px).
pub const COMFORT_TARGET_PX: f32 = 44.0;

/// The WCAG relative luminance of an sRGB colour, from 0 (black) to 1 (white).
///
/// ```
/// assert_eq!(bevy_gooey::relative_luminance([1.0, 1.0, 1.0]), 1.0);
/// ```
pub fn relative_luminance(srgb: [f32; 3]) -> f32 {
    let linear = srgb.map(|c| {
        if c <= 0.04045 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    });
    0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
}

/// The WCAG contrast ratio of two sRGB colours, from 1:1 (the same) to 21:1 (black on white).
///
/// ```
/// let ratio = bevy_gooey::contrast_ratio([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]);
/// assert!((ratio - 21.0).abs() < 0.01);
/// ```
pub fn contrast_ratio(a: [f32; 3], b: [f32; 3]) -> f32 {
    let (la, lb) = (relative_luminance(a), relative_luminance(b));
    (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}

/// The least CIE L\* two adjacent surfaces of a skin's ladder may differ by: a just-noticeable
/// difference of a large flat field is about 2, and a comfortable one about 4. See
/// [`crate::GooeySkin::surfaces`].
pub const ELEVATION_STEP: f32 = 2.0;

/// The least CIE L\* a skin's pressed fill and its hovered fill may differ by, so a control with
/// the pointer down is told apart from one under it: the comfortable step (4) of
/// [`ELEVATION_STEP`]'s note, since WCAG 1.4.11 sets no number for two states that do not appear
/// side by side. See [`crate::GooeySkin::pressed`].
pub const STATE_STEP: f32 = 4.0;

/// The CIE 1976 lightness L\* of an sRGB colour, from 0 (black) to 100 (white): a perceptually
/// near-uniform scale, so equal differences look like equal steps (WCAG's contrast ratio, with its
/// flare term, is the wrong instrument between two near-blacks).
///
/// ```
/// assert_eq!(bevy_gooey::cie_lightness([0.0, 0.0, 0.0]), 0.0);
/// assert!((bevy_gooey::cie_lightness([1.0, 1.0, 1.0]) - 100.0).abs() < 0.01);
/// ```
pub fn cie_lightness(srgb: [f32; 3]) -> f32 {
    const EPSILON: f32 = 216.0 / 24389.0;
    const KAPPA: f32 = 24389.0 / 27.0;
    let y = relative_luminance(srgb);
    if y <= EPSILON {
        KAPPA * y
    } else {
        116.0 * y.cbrt() - 16.0
    }
}

/// `fg` at `alpha` laid over an opaque `bg`, per channel: what the eye sees of a translucent panel.
/// `alpha` is clamped to `0..=1`.
///
/// ```
/// assert_eq!(bevy_gooey::composite([1.0, 1.0, 1.0], 0.5, [0.0, 0.0, 0.0]), [0.5, 0.5, 0.5]);
/// ```
pub fn composite(fg: [f32; 3], alpha: f32, bg: [f32; 3]) -> [f32; 3] {
    let a = alpha.clamp(0.0, 1.0);
    [
        fg[0] * a + bg[0] * (1.0 - a),
        fg[1] * a + bg[1] * (1.0 - a),
        fg[2] * a + bg[2] * (1.0 - a),
    ]
}

/// How full a meter is, from 0 to 1. Never NaN: a non-finite value, a non-finite maximum or a
/// maximum at or below zero reads as empty.
///
/// ```
/// assert_eq!(bevy_gooey::meter_fraction(25.0, 100.0), 0.25);
/// ```
pub fn meter_fraction(value: f32, max: f32) -> f32 {
    if max > 0.0 && max.is_finite() && value.is_finite() {
        (value / max).clamp(0.0, 1.0)
    } else {
        0.0
    }
}

/// How fast a meter's fill rises to a higher value: the time constant, seconds, of an ease-out
/// (95% of the way in three of them, so about 0.24 s).
pub const METER_GAIN_TAU_SECONDS: f32 = 0.08;
/// How long a meter's trail of lost length stands before it drains, seconds.
pub const METER_TRAIL_HOLD_SECONDS: f32 = 0.45;
/// How fast a meter's trail drains once its hold is over, in whole lengths of the bar a second.
pub const METER_TRAIL_RATE: f32 = 1.5;
/// A meter fraction this near its target is its target (under a device pixel on any bar).
pub const METER_SNAP: f32 = 0.002;

/// The fractions of its length a meter draws: the `fill` (the value) and the `trail` behind it, the
/// length that was lost, which never falls below the fill. `hold` is how long the trail still
/// stands before it drains.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MeterShown {
    /// The fill's fraction of the bar, `0.0..=1.0`.
    pub fill: f32,
    /// The trail's fraction, `fill..=1.0`: the fill's length before a loss, draining to the fill.
    pub trail: f32,
    /// Seconds before the trail starts to drain.
    pub hold: f32,
}

/// One step of a meter's motion: `shown` after `dt` seconds of a bar that now reads `target`
/// (`0.0..=1.0`). A loss drops the fill to the target at once and leaves a trail where it was, held
/// for [`METER_TRAIL_HOLD_SECONDS`] and then drained at [`METER_TRAIL_RATE`] (a second loss during
/// the hold does not restart it); a gain eases the fill up with a time constant of
/// [`METER_GAIN_TAU_SECONDS`] and raises the trail with it. Every length is multiplied by
/// `duration_scale`; at zero (or any value that is not finite and above zero) the result is the
/// target and no trail. A `target` that is not finite reads as empty.
///
/// ```
/// # use bevy_gooey::{MeterShown, meter_motion};
/// let full = MeterShown { fill: 1.0, trail: 1.0, hold: 0.0 };
/// let hit = meter_motion(full, 0.6, 0.016, 1.0);
/// assert_eq!(hit.fill, 0.6); // exact the frame it lands
/// assert_eq!(hit.trail, 1.0); // the lost length lingers
/// ```
pub fn meter_motion(shown: MeterShown, target: f32, dt: f32, duration_scale: f32) -> MeterShown {
    let target = if target.is_finite() {
        target.clamp(0.0, 1.0)
    } else {
        0.0
    };
    if !(duration_scale.is_finite() && duration_scale > 0.0) {
        return MeterShown {
            fill: target,
            trail: target,
            hold: 0.0,
        };
    }
    let dt = if dt.is_finite() { dt.max(0.0) } else { 0.0 } / duration_scale;
    let mut next = shown;
    // A trail already standing keeps its own clock: only a loss with none starts one.
    let mut fresh = false;
    if target < shown.fill {
        next.fill = target;
        if shown.trail <= shown.fill {
            next.trail = shown.fill;
            next.hold = METER_TRAIL_HOLD_SECONDS;
            fresh = true;
        }
    } else if target > shown.fill {
        let step = 1.0 - (-dt / METER_GAIN_TAU_SECONDS).exp();
        next.fill = shown.fill + (target - shown.fill) * step;
        if target - next.fill < METER_SNAP {
            next.fill = target;
        }
    }
    next.trail = next.trail.max(next.fill);
    if next.trail > next.fill {
        if !fresh {
            let over = dt - next.hold;
            next.hold = (next.hold - dt).max(0.0);
            if over > 0.0 {
                next.trail = (next.trail - METER_TRAIL_RATE * over).max(next.fill);
            }
        }
        if next.trail - next.fill < METER_SNAP {
            next.trail = next.fill;
        }
    }
    if next.trail <= next.fill {
        next.hold = 0.0;
    }
    next
}

/// The `UiScale` that keeps an interface's share of a `width` × `height` window (logical px): the
/// window's shorter side over `reference_short_side`, times the player's `scale`. `None` when there
/// is no usable scale: a window with no size (minimised), or a reference or a scale that is not
/// above zero.
///
/// ```
/// assert_eq!(bevy_gooey::window_ui_scale(2560.0, 1440.0, 720.0, 1.0), Some(2.0));
/// ```
pub fn window_ui_scale(
    width: f32,
    height: f32,
    reference_short_side: f32,
    scale: f32,
) -> Option<f32> {
    let ui = width.min(height) / reference_short_side * scale;
    (reference_short_side > 0.0 && scale > 0.0 && ui > 0.0 && ui.is_finite()).then_some(ui)
}

/// How close to a whole device pixel a line already is to count as that pixel: a thousandth.
const SNAP_TOLERANCE: f32 = 1.0e-3;

/// A line weight `length` (logical px) snapped so it draws as a whole number of device pixels at
/// `scale` device pixels per logical px: CSS's "snap a length as a border width". Above one device
/// pixel it rounds down, below one it rounds up to one, and zero stays zero. Returns logical px.
///
/// Bevy lays a node out at `scale × length` and rounds each edge from the node's position, so a
/// 4.5 px border draws 4 px on one side and 5 px on another; a whole-pixel border draws the same on
/// every side. The result is chosen so that `scale * result`, as `f32`, is exactly the whole number
/// wherever an `f32` allows it, and otherwise the least length above it, never below.
///
/// A length or scale that is not finite and above zero is returned unchanged.
///
/// ```
/// // 3 px at 1.5x would be 4.5 device px: it is drawn 4.
/// let line = bevy_gooey::snap_line_width(3.0, 1.5);
/// assert_eq!(line * 1.5, 4.0);
/// ```
pub fn snap_line_width(length: f32, scale: f32) -> f32 {
    let usable = |x: f32| x.is_finite() && x > 0.0;
    if !usable(length) || !usable(scale) {
        return length;
    }
    let device = (length * scale + SNAP_TOLERANCE).floor().max(1.0);
    let mut logical = device / scale;
    // Division and multiplication each round, so step by ulps until the product is exact, or
    // failing that, the least one above: a product an ulp short rounds a pixel short.
    for _ in 0..4 {
        let drawn = logical * scale;
        if drawn < device {
            logical = logical.next_up();
        } else if drawn > device && logical.next_down() * scale >= device {
            logical = logical.next_down();
        } else {
            break;
        }
    }
    logical
}

/// How long a held D-pad direction waits before it repeats on a [`crate::slider`], in seconds. A
/// design default: the delay of a keyboard's own repeat.
pub const PAD_REPEAT_DELAY: f32 = 0.4;

/// How many repeats a second a held D-pad direction makes on a [`crate::slider`], once the delay
/// is over. A design default: with a twentieth of the range a step, a 0 to 1 slider sweeps in about
/// two seconds.
pub const PAD_REPEAT_RATE: f32 = 12.0;

/// How far a stick must be pushed, as a share of its travel (after the pad's own dead zone), to
/// count as the player using a pad: [`crate::track_input_device`] switches
/// [`crate::InputDevice`] to the pad on a push this far. Half its travel is a deliberate push, and
/// leaves a drifting or brushed stick alone. A design default.
pub const STICK_PUSH: f32 = 0.5;

/// How far a stick must be pushed, as a share of its travel, to point a [`crate::radial`] at an
/// item: half, a deliberate push. Inside it the highlight stays where it is, so a stick drifting
/// through the middle on its way back never flickers between items. A design default, the same
/// half as [`STICK_PUSH`].
pub const RADIAL_STICK_PUSH: f32 = 0.5;

/// How far from the middle of a [`crate::radial`] the pointer must be to point at an item, as a
/// share of the disc's radius. Inside it the highlight stays, which is the dead zone a pointer
/// needs for the same reason a stick does. A design default.
pub const RADIAL_DEAD_ZONE: f32 = 0.25;

/// The item of `count` on a ring that the direction `(x, y)` points into, with `y` up: item 0 is at
/// the top and the rest follow clockwise, each owning the wedge of `360 / count` degrees centred on
/// it. The edge between two wedges belongs to the clockwise one. A direction of no length, or a
/// non-finite one, and a ring of one, pick item 0; a ring of none picks nothing, so `None`.
///
/// ```
/// use bevy_gooey::radial_pick;
/// assert_eq!(radial_pick(0.0, 1.0, 4), Some(0)); // up
/// assert_eq!(radial_pick(1.0, 0.0, 4), Some(1)); // right
/// assert_eq!(radial_pick(0.0, -1.0, 4), Some(2)); // down
/// assert_eq!(radial_pick(-1.0, 0.0, 4), Some(3)); // left
/// assert_eq!(radial_pick(1.0, 1.0, 8), Some(1)); // up and right
/// assert_eq!(radial_pick(1.0, 1.0, 0), None);
/// ```
pub fn radial_pick(x: f32, y: f32, count: usize) -> Option<usize> {
    if count == 0 {
        return None;
    }
    if !(x.is_finite() && y.is_finite()) || (x == 0.0 && y == 0.0) {
        return Some(0);
    }
    let turns = (x.atan2(y) / std::f32::consts::TAU).rem_euclid(1.0);
    // The half-wedge nudge puts a wedge's edge in the clockwise item; the epsilon keeps an angle
    // that float error leaves a hair short of the edge (a diagonal of an even ring) on that side.
    Some(((turns * count as f32 + 0.5 + 1e-4).floor() as usize) % count)
}

/// Where item `index` of `count` stands on a ring, as the offset from the middle in half-widths of
/// the disc: `(x, y)` with `y` up, on a circle of radius 1. Item 0 is at the top, the rest clockwise
/// (the same order as [`radial_pick`]). An `index` past the ring wraps.
///
/// ```
/// let (x, y) = bevy_gooey::radial_place(1, 4);
/// assert!((x - 1.0).abs() < 1e-6 && y.abs() < 1e-6); // the right
/// ```
pub fn radial_place(index: usize, count: usize) -> (f32, f32) {
    if count == 0 {
        return (0.0, 1.0);
    }
    let angle = (index % count) as f32 / count as f32 * std::f32::consts::TAU;
    (angle.sin(), angle.cos())
}

/// The item a step of `delta` from `value` reaches on a ring of `count`: wrapping round both ways,
/// as a ring has no end. A `value` past the ring counts as the last item. Zero for a ring of none.
///
/// ```
/// use bevy_gooey::radial_step;
/// assert_eq!(radial_step(3, 4, 1), 0);
/// assert_eq!(radial_step(0, 4, -1), 3);
/// assert_eq!(radial_step(1, 8, 10), 3);
/// ```
pub fn radial_step(value: usize, count: usize, delta: i32) -> usize {
    if count == 0 {
        return 0;
    }
    let at = value.min(count - 1) as i64;
    (at + i64::from(delta)).rem_euclid(count as i64) as usize
}

/// The slot Home or End moves a grid's cursor to, in a grid `columns` wide holding `len` slots in
/// reading order: the first or last slot of `index`'s row (the last row may be short), or with
/// `whole` the first or last slot of the grid. Never past the last slot, and `0` for an empty
/// grid.
///
/// ```
/// use bevy_gooey::slot_edge;
/// // Seven slots, three wide: rows 0-2, 3-5, 6.
/// assert_eq!(slot_edge(4, 3, 7, false, false), 3);
/// assert_eq!(slot_edge(4, 3, 7, true, false), 5);
/// assert_eq!(slot_edge(6, 3, 7, true, false), 6);
/// assert_eq!(slot_edge(4, 3, 7, true, true), 6);
/// ```
pub fn slot_edge(index: usize, columns: usize, len: usize, end: bool, whole: bool) -> usize {
    let Some(last) = len.checked_sub(1) else {
        return 0;
    };
    let columns = columns.max(1);
    match (end, whole) {
        (false, true) => 0,
        (true, true) => last,
        (false, false) => index.min(last) / columns * columns,
        (true, false) => (index.min(last) / columns * columns + columns - 1).min(last),
    }
}

/// How far along its range a slider's thumb is, from 0 to 1. Never NaN: a value outside the range
/// is clamped to an end, and a range that is not finite or has no length reads as the start.
///
/// ```
/// assert_eq!(bevy_gooey::slider_fraction(25.0, 0.0, 100.0), 0.25);
/// assert_eq!(bevy_gooey::slider_fraction(2.0, 0.0, 1.0), 1.0);
/// ```
pub fn slider_fraction(value: f32, min: f32, max: f32) -> f32 {
    if min.is_finite() && max.is_finite() && value.is_finite() && max > min {
        ((value - min) / (max - min)).clamp(0.0, 1.0)
    } else {
        0.0
    }
}

/// The text a [`crate::slider`] shows for its value: a percentage when the range is 0 to 1 (a
/// volume, a brightness), the plain number otherwise, rounded to two decimals with trailing zeros
/// dropped. A value outside the range reads as the end it is clamped to, and one that is not finite
/// as 0.
///
/// ```
/// assert_eq!(bevy_gooey::slider_text(0.7, 0.0, 1.0), "70%");
/// assert_eq!(bevy_gooey::slider_text(1.25, 0.5, 2.0), "1.25");
/// assert_eq!(bevy_gooey::slider_text(40.0, 0.0, 100.0), "40");
/// ```
pub fn slider_text(value: f32, min: f32, max: f32) -> String {
    let value = if value.is_finite() { value } else { 0.0 };
    let value = if min.is_finite() && max.is_finite() && min <= max {
        value.clamp(min, max)
    } else {
        value
    };
    if min == 0.0 && max == 1.0 {
        return format!("{}%", (value * 100.0).round());
    }
    let text = format!("{value:.2}");
    let text = text.trim_end_matches('0').trim_end_matches('.');
    // A value that rounds to nothing is "0", never "-0".
    if text == "-0" || text.is_empty() {
        "0".into()
    } else {
        text.into()
    }
}

/// Where a [`crate::choice`] lands when it steps `delta` options from `selected` among `len`:
/// clamped to the first and the last, never wrapping, so a player who steps past the end sees that
/// it is the end. With no options it stays at 0, and a `selected` already past the end counts as
/// the last.
///
/// ```
/// assert_eq!(bevy_gooey::choice_step(1, 3, 1), 2);
/// assert_eq!(bevy_gooey::choice_step(2, 3, 1), 2);
/// assert_eq!(bevy_gooey::choice_step(0, 3, -1), 0);
/// ```
pub fn choice_step(selected: usize, len: usize, delta: i32) -> usize {
    let last = len.saturating_sub(1);
    let from = selected.min(last);
    if delta < 0 {
        from.saturating_sub(delta.unsigned_abs() as usize)
    } else {
        from.saturating_add(delta as usize).min(last)
    }
}

/// The option after `selected` among `len`, wrapping from the last to the first: what Enter, Space,
/// the pad's South button and a click on a [`crate::choice`]'s value do, so one repeated press
/// reaches every option. With no options it stays at 0.
///
/// ```
/// assert_eq!(bevy_gooey::choice_next(0, 3), 1);
/// assert_eq!(bevy_gooey::choice_next(2, 3), 0);
/// ```
pub fn choice_next(selected: usize, len: usize) -> usize {
    if len == 0 {
        0
    } else {
        (selected.min(len - 1) + 1) % len
    }
}

/// The text sizes a [`crate::text_size`] row offers, as [`crate::GooeySkin::text_scale`] values:
/// 100%, 125%, 150% and 200%. The top is the Xbox Accessibility Guideline 101's, and every step is
/// one `tests/large_text.rs` lays the widgets out at, because WCAG 2.2 SC 1.4.4 asks for "no loss
/// of content or functionality at these incremental steps". A design default.
pub const TEXT_SIZE_STEPS: [f32; 4] = [1.0, 1.25, 1.5, 2.0];

/// The interface sizes an [`crate::interface_size`] row offers, as [`crate::UiScaleSettings::scale`]
/// values: 75%, 100%, 125% and 150%. Smaller than 100% for the player who wants the interface to
/// "obscure less of the gameplay", and 150% at the top, as EVE Online's UI scaling is (both from the
/// Game Accessibility Guidelines). A design default.
pub const INTERFACE_SIZE_STEPS: [f32; 4] = [0.75, 1.0, 1.25, 1.5];

/// The controller families a [`crate::pad_style`] row offers, in [`PadStyle`]'s own order.
pub const PAD_STYLES: [PadStyle; 3] = [PadStyle::Xbox, PadStyle::PlayStation, PadStyle::Switch];

/// The index of the step in `steps` nearest `value`: what a settings row shows for a value the game
/// set. A value halfway between two steps takes the lower one (the first, for steps in ascending
/// order), a value past either end takes that end, and a value that is not a number (or no steps)
/// gives 0.
///
/// ```
/// use bevy_gooey::{TEXT_SIZE_STEPS, nearest_step};
/// assert_eq!(nearest_step(&TEXT_SIZE_STEPS, 1.5), 2);
/// assert_eq!(nearest_step(&TEXT_SIZE_STEPS, 1.1), 0);
/// assert_eq!(nearest_step(&TEXT_SIZE_STEPS, 9.0), 3);
/// ```
pub fn nearest_step(steps: &[f32], value: f32) -> usize {
    if value.is_nan() || steps.is_empty() {
        return 0;
    }
    // Past either end is that end, however far: a huge value is as far from every step in floats.
    let mut lowest = 0;
    let mut highest = 0;
    for (index, step) in steps.iter().enumerate() {
        if *step < steps[lowest] {
            lowest = index;
        }
        if *step > steps[highest] {
            highest = index;
        }
    }
    if value <= steps[lowest] {
        return lowest;
    }
    if value >= steps[highest] {
        return highest;
    }
    let mut nearest = lowest;
    let mut distance = f32::INFINITY;
    for (index, step) in steps.iter().enumerate() {
        let away = (step - value).abs();
        if away < distance {
            nearest = index;
            distance = away;
        }
    }
    nearest
}

/// Where a [`crate::tabs`] widget lands when it steps `delta` tabs from `selected` among `len`:
/// round the strip, wrapping from the last to the first and from the first to the last, however
/// large the step (the bumpers, Ctrl+PageUp and Ctrl+PageDown, the D-pad and the arrows all step
/// one). A strip is one direction, so it loops; a [`crate::choice`] is a value with ends and stops
/// ([`choice_step`]). With no tabs it stays at 0, and a `selected` already past the end counts as
/// the last.
///
/// ```
/// assert_eq!(bevy_gooey::tab_step(0, 3, 1), 1);
/// assert_eq!(bevy_gooey::tab_step(2, 3, 1), 0);
/// assert_eq!(bevy_gooey::tab_step(0, 3, -1), 2);
/// ```
pub fn tab_step(selected: usize, len: usize, delta: i32) -> usize {
    if len == 0 {
        return 0;
    }
    let from = selected.min(len - 1) as i64;
    (from + i64::from(delta)).rem_euclid(len as i64) as usize
}

/// The family of controller whose button names a [`crate::binding`] row shows: the same physical
/// button is "A" on an Xbox pad, "Cross" on a PlayStation one and "B" on a Nintendo Switch one.
/// The crate does not detect a pad's make; the host sets it in [`crate::BindingSettings`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PadStyle {
    /// A, B, X, Y, LB, RB, LT, RT, View, Menu.
    #[default]
    Xbox,
    /// Cross, Circle, Square, Triangle, L1, R1, L2, R2, Create, Options.
    PlayStation,
    /// B, A, Y, X, L, R, ZL, ZR, -, +: the face buttons by position, so South is "B".
    Switch,
}

impl PadStyle {
    /// The family's name as its maker writes it: "Xbox", "PlayStation", "Switch". What a
    /// [`crate::pad_style`] row shows for it.
    pub fn name(self) -> &'static str {
        match self {
            Self::Xbox => "Xbox",
            Self::PlayStation => "PlayStation",
            Self::Switch => "Switch",
        }
    }
}

/// The words printed on a key's cap, from the name of its Bevy `KeyCode` variant (`format!("{:?}",
/// key)`): the key's *location* named as a US keyboard prints it, so `KeyW` is "W" on every
/// layout (a stored key is a place, not a letter; see `docs/research/binding.md`).
/// Modifiers lead with their side ("Left Shift"), the arrows end in "Arrow", punctuation is the
/// mark itself, and any other name is cut into words ("PageUp" is "Page Up").
///
/// ```
/// assert_eq!(bevy_gooey::key_name("KeyW"), "W");
/// assert_eq!(bevy_gooey::key_name("Digit1"), "1");
/// assert_eq!(bevy_gooey::key_name("ShiftLeft"), "Left Shift");
/// assert_eq!(bevy_gooey::key_name("ArrowUp"), "Up Arrow");
/// assert_eq!(bevy_gooey::key_name("Escape"), "Esc");
/// assert_eq!(bevy_gooey::key_name("PageDown"), "Page Down");
/// ```
pub fn key_name(code: &str) -> String {
    let fixed = match code {
        "Escape" => "Esc",
        "Delete" => "Del",
        "Insert" => "Ins",
        "ContextMenu" => "Menu",
        "Backquote" => "`",
        "Backslash" | "IntlBackslash" => "\\",
        "BracketLeft" => "[",
        "BracketRight" => "]",
        "Comma" => ",",
        "Equal" => "=",
        "Minus" => "-",
        "Period" => ".",
        "Quote" => "'",
        "Semicolon" => ";",
        "Slash" => "/",
        "NumpadAdd" => "Num +",
        "NumpadSubtract" => "Num -",
        "NumpadMultiply" => "Num *",
        "NumpadDivide" => "Num /",
        "NumpadDecimal" => "Num .",
        "NumpadComma" => "Num ,",
        "NumpadEqual" => "Num =",
        "NumpadEnter" => "Num Enter",
        _ => "",
    };
    if !fixed.is_empty() {
        return fixed.to_owned();
    }
    if code.starts_with("Unidentified") {
        return "Unknown key".to_owned();
    }
    for side in ["Left", "Right"] {
        if let Some(modifier) = code.strip_suffix(side) {
            let name = match modifier {
                "Shift" => "Shift",
                "Control" => "Ctrl",
                "Alt" => "Alt",
                "Super" => "Super",
                "Meta" => "Meta",
                "Hyper" => "Hyper",
                _ => continue,
            };
            return format!("{side} {name}");
        }
    }
    if let Some(direction) = code.strip_prefix("Arrow") {
        return format!("{direction} Arrow");
    }
    for prefix in ["Key", "Digit"] {
        if let Some(rest) = code.strip_prefix(prefix)
            && rest.chars().count() == 1
        {
            return rest.to_owned();
        }
    }
    if let Some(rest) = code.strip_prefix("Numpad")
        && rest.chars().all(|c| c.is_ascii_digit())
        && !rest.is_empty()
    {
        return format!("Num {rest}");
    }
    words(code)
}

/// The words of a mouse button, from the name of its Bevy `MouseButton` variant: "Left Click",
/// "Right Click", "Middle Click", the side buttons as "Mouse 4" and "Mouse 5" and any other by its
/// number ("Mouse 6").
///
/// ```
/// assert_eq!(bevy_gooey::mouse_name("Left"), "Left Click");
/// assert_eq!(bevy_gooey::mouse_name("Back"), "Mouse 4");
/// assert_eq!(bevy_gooey::mouse_name("Other(6)"), "Mouse 6");
/// ```
pub fn mouse_name(button: &str) -> String {
    match button {
        "Left" => "Left Click".to_owned(),
        "Right" => "Right Click".to_owned(),
        "Middle" => "Middle Click".to_owned(),
        "Back" => "Mouse 4".to_owned(),
        "Forward" => "Mouse 5".to_owned(),
        other => match numbered(other) {
            Some(n) => format!("Mouse {n}"),
            None => words(other),
        },
    }
}

/// The words of a gamepad button, from the name of its Bevy `GamepadButton` variant, in the
/// vocabulary of `style`: `South` is "A", "Cross" or "B"; the shoulders "LB", "L1" or "L"; the D-pad
/// "D-pad Up" on all three. A button with no name of its own is "Button n".
///
/// ```
/// use bevy_gooey::model::PadStyle;
/// assert_eq!(bevy_gooey::pad_name("South", PadStyle::Xbox), "A");
/// assert_eq!(bevy_gooey::pad_name("South", PadStyle::PlayStation), "Cross");
/// assert_eq!(bevy_gooey::pad_name("RightTrigger2", PadStyle::Switch), "ZR");
/// assert_eq!(bevy_gooey::pad_name("DPadUp", PadStyle::Xbox), "D-pad Up");
/// ```
pub fn pad_name(button: &str, style: PadStyle) -> String {
    // Xbox, PlayStation, Switch.
    let (xbox, playstation, switch) = match button {
        "South" => ("A", "Cross", "B"),
        "East" => ("B", "Circle", "A"),
        "North" => ("Y", "Triangle", "X"),
        "West" => ("X", "Square", "Y"),
        "C" => ("C", "C", "C"),
        "Z" => ("Z", "Z", "Z"),
        "LeftTrigger" => ("LB", "L1", "L"),
        "LeftTrigger2" => ("LT", "L2", "ZL"),
        "RightTrigger" => ("RB", "R1", "R"),
        "RightTrigger2" => ("RT", "R2", "ZR"),
        "Select" => ("View", "Create", "-"),
        "Start" => ("Menu", "Options", "+"),
        "Mode" => ("Guide", "PS", "Home"),
        "LeftThumb" => ("LS", "L3", "L3"),
        "RightThumb" => ("RS", "R3", "R3"),
        "DPadUp" => ("D-pad Up", "D-pad Up", "D-pad Up"),
        "DPadDown" => ("D-pad Down", "D-pad Down", "D-pad Down"),
        "DPadLeft" => ("D-pad Left", "D-pad Left", "D-pad Left"),
        "DPadRight" => ("D-pad Right", "D-pad Right", "D-pad Right"),
        other => {
            return match numbered(other) {
                Some(n) => format!("Button {n}"),
                None => words(other),
            };
        }
    };
    match style {
        PadStyle::Xbox => xbox,
        PadStyle::PlayStation => playstation,
        PadStyle::Switch => switch,
    }
    .to_owned()
}

/// Whether a key's `KeyCode` variant name is a modifier (`ShiftLeft`, `ControlRight`, `AltLeft`,
/// `SuperLeft`, `MetaRight`, `HyperLeft`, or the bare `Meta`), the keys a chord holds and never one
/// it is.
///
/// ```
/// assert!(bevy_gooey::model::is_modifier_key("ControlLeft"));
/// assert!(!bevy_gooey::model::is_modifier_key("KeyK"));
/// ```
pub fn is_modifier_key(code: &str) -> bool {
    ["Shift", "Control", "Alt", "Super", "Meta", "Hyper"]
        .iter()
        .any(|name| {
            code.strip_prefix(name)
                .is_some_and(|side| matches!(side, "" | "Left" | "Right"))
        })
}

/// The words of a key chord as the platform spells them, from a `KeyCode` variant name and the
/// modifiers held, `[ctrl, shift, alt, meta]`.
///
/// Apple's order is Control, Option, Shift, Command, as symbols with nothing between ("⇧⌘P"),
/// and a few keys wear glyphs (Return, Delete, Escape, Tab, the arrows). Elsewhere it is
/// Microsoft's order: Windows logo (named "Super"), Ctrl, Alt, Shift, joined by "+"
/// ("Ctrl+Shift+P"). `meta` is the Command key on a mac and the Windows or Super key elsewhere.
///
/// ```
/// use bevy_gooey::model::shortcut_label;
/// assert_eq!(shortcut_label("KeyP", [true, true, false, false], false), "Ctrl+Shift+P");
/// assert_eq!(shortcut_label("KeyP", [false, true, false, true], true), "⇧⌘P");
/// ```
pub fn shortcut_label(code: &str, [ctrl, shift, alt, meta]: [bool; 4], mac: bool) -> String {
    let mut out = String::new();
    if mac {
        for (held, glyph) in [(ctrl, '⌃'), (alt, '⌥'), (shift, '⇧'), (meta, '⌘')] {
            if held {
                out.push(glyph);
            }
        }
        out.push_str(match code {
            "Enter" => "↩",
            "Backspace" => "⌫",
            "Delete" => "⌦",
            "Escape" => "⎋",
            "Tab" => "⇥",
            "ArrowUp" => "↑",
            "ArrowDown" => "↓",
            "ArrowLeft" => "←",
            "ArrowRight" => "→",
            other => return out + &key_name(other),
        });
        return out;
    }
    for (held, name) in [
        (meta, "Super"),
        (ctrl, "Ctrl"),
        (alt, "Alt"),
        (shift, "Shift"),
    ] {
        if held {
            out.push_str(name);
            out.push('+');
        }
    }
    out + &key_name(code)
}

/// Every pair of commands bound to the same shortcut, in the order they are listed: one pair per
/// two commands that clash, so three on one chord make three pairs, and a command is never paired
/// with itself. Generic over the shortcut, so any `PartialEq` chord type (the crate's
/// [`Shortcut`](crate::Shortcut)) works and this module holds no engine type. The check does not
/// guess contexts: a command that is live in one mode only is the caller's to filter out first.
///
/// ```
/// use bevy_gooey::model::shortcut_conflicts;
/// let keymap = [("Save", "Ctrl+S"), ("Save all", "Ctrl+Shift+S"), ("Stash", "Ctrl+S")];
/// assert_eq!(shortcut_conflicts(&keymap), vec![("Save".to_owned(), "Stash".to_owned())]);
/// ```
pub fn shortcut_conflicts<S: PartialEq>(keymap: &[(&str, S)]) -> Vec<(String, String)> {
    let mut clashes = Vec::new();
    for (index, (first, shortcut)) in keymap.iter().enumerate() {
        for (second, other) in &keymap[index + 1..] {
            if shortcut == other {
                clashes.push(((*first).to_owned(), (*second).to_owned()));
            }
        }
    }
    clashes
}

/// A fuzzy match of `query` against `text`, higher is better, `None` when it does not match: how a
/// [`command palette`](crate::command_palette) ranks what the player typed ("opn prj") against
/// what a row says ("File: Open Project").
///
/// The query is split on whitespace and every term must occur in `text` as a subsequence, ignoring
/// case; the terms may match in any order. A term is aligned where it scores best: a point per
/// character, more for a character that starts a word (after a space or punctuation, or a capital
/// after a small letter) or follows the one before it, less for each character skipped between
/// two. The terms' scores add, and at the same alignment a shorter text outranks a longer. A query
/// with no terms matches everything, and only the length orders them.
///
/// ```
/// use bevy_gooey::model::fuzzy_score;
/// let open = fuzzy_score("opn prj", "Open Project").unwrap();
/// assert!(open > fuzzy_score("opn prj", "Reopen Project").unwrap());
/// assert!(fuzzy_score("opn prj", "Open Project Settings").unwrap() < open);
/// assert_eq!(fuzzy_score("xyz", "Open Project"), None);
/// ```
pub fn fuzzy_score(query: &str, text: &str) -> Option<u32> {
    const MATCH: i32 = 16;
    const WORD_START: i32 = 12;
    const CONSECUTIVE: i32 = 10;
    const GAP: i32 = 2;
    const LEAD_CAP: i32 = 4;
    const NO_MATCH: i32 = i32::MIN / 2;

    let chars: Vec<char> = text.chars().collect();
    let lower: Vec<char> = chars
        .iter()
        .map(|c| c.to_lowercase().next().unwrap_or(*c))
        .collect();
    let starts: Vec<bool> = chars
        .iter()
        .enumerate()
        .map(|(i, c)| {
            i == 0
                || !chars[i - 1].is_alphanumeric()
                || (c.is_uppercase() && chars[i - 1].is_lowercase())
        })
        .collect();

    let mut total: i32 = 0;
    for term in query.split_whitespace() {
        let term: Vec<char> = term
            .chars()
            .map(|c| c.to_lowercase().next().unwrap_or(c))
            .collect();
        // `prev[j]`: the best score of the term's characters so far with the last one at `j`.
        let mut prev = vec![NO_MATCH; chars.len()];
        for (i, wanted) in term.iter().enumerate() {
            let mut cur = vec![NO_MATCH; chars.len()];
            // The best way to have matched the characters before this one at least a gap away,
            // less the gap's cost, as the scan moves right.
            let mut gapped = NO_MATCH;
            for j in 0..chars.len() {
                if j >= 2 {
                    gapped = (gapped - GAP).max(prev[j - 2].saturating_sub(GAP));
                }
                if lower[j] != *wanted {
                    continue;
                }
                let here = MATCH + if starts[j] { WORD_START } else { 0 };
                let before = if i == 0 {
                    -(j as i32).min(LEAD_CAP)
                } else {
                    let next_to = if j >= 1 && prev[j - 1] > NO_MATCH {
                        prev[j - 1] + CONSECUTIVE
                    } else {
                        NO_MATCH
                    };
                    next_to.max(gapped)
                };
                if before > NO_MATCH {
                    cur[j] = here + before;
                }
            }
            prev = cur;
        }
        let best = prev.into_iter().max().filter(|&score| score > NO_MATCH)?;
        total += best.max(1);
    }
    let short = 255 - chars.len().min(255) as i32;
    Some(total.max(0) as u32 * 256 + short as u32)
}

/// `n` of a variant printed as `Other(n)`.
fn numbered(name: &str) -> Option<&str> {
    name.strip_prefix("Other(")?.strip_suffix(')')
}

/// A variant name cut into words at each capital that follows a lower-case letter or a digit:
/// "CapsLock" is "Caps Lock".
fn words(name: &str) -> String {
    let mut out = String::with_capacity(name.len() + 2);
    let mut before: Option<char> = None;
    for c in name.chars() {
        if c.is_uppercase() && before.is_some_and(|b| b.is_lowercase() || b.is_ascii_digit()) {
            out.push(' ');
        }
        out.push(c);
        before = Some(c);
    }
    out
}

/// How many repeats a held button has made between two moments, `held_before` and `held_now`
/// seconds after it went down: none until `delay`, then `per_second` a second, the first at
/// `delay` itself. The press itself is not a repeat. Zero for a delay or rate that is not usable.
///
/// ```
/// // Held 0.35 s then 0.45 s: the first repeat, at 0.4 s, falls in between.
/// assert_eq!(bevy_gooey::repeat_steps(0.35, 0.45, 0.4, 10.0), 1);
/// // Held through a whole second at once, delay 0.5 s: the repeats at 0.5, 0.6 … 1.0 s.
/// assert_eq!(bevy_gooey::repeat_steps(0.0, 1.0, 0.5, 10.0), 6);
/// ```
pub fn repeat_steps(held_before: f32, held_now: f32, delay: f32, per_second: f32) -> u32 {
    let due = |held: f32| {
        if held >= delay && held.is_finite() {
            ((held - delay) * per_second).floor() as u32 + 1
        } else {
            0
        }
    };
    let usable = |x: f32| x.is_finite() && x >= 0.0;
    if usable(delay) && per_second.is_finite() && per_second > 0.0 && held_now > held_before {
        due(held_now).saturating_sub(due(held_before))
    } else {
        0
    }
}

/// How long a toast stands fully shown, in seconds: `(base_seconds + characters ÷ chars_per_second)
/// × scale`. The reading time is the message's length at a reading speed (Netflix holds timed text to
/// 20 characters a second for adults), the base is the time to notice a thing at the edge of the eye,
/// and the scale is the player's own (Xbox Accessibility Guideline 116: adjustable up to at least ten
/// times the default).
///
/// Never negative, infinite or NaN: a base or a reading speed that is not finite and above zero
/// counts for nothing (no base, no reading time), and a scale that is not finite and above zero
/// gives no time at all.
///
/// ```
/// // "Game saved" at the defaults: 2 s to notice and half a second to read.
/// assert_eq!(bevy_gooey::toast_hold(10, 2.0, 20.0, 1.0), 2.5);
/// ```
pub fn toast_hold(characters: usize, base_seconds: f32, chars_per_second: f32, scale: f32) -> f32 {
    let usable = |x: f32| x.is_finite() && x > 0.0;
    let base = if usable(base_seconds) {
        base_seconds
    } else {
        0.0
    };
    let reading = if usable(chars_per_second) {
        characters as f32 / chars_per_second
    } else {
        0.0
    };
    if usable(scale) {
        (base + reading) * scale
    } else {
        0.0
    }
}

/// How long a toast lives in all: its fade in, `hold` fully shown and its fade out. A `fade` that is
/// not finite and above zero is no fade.
///
/// ```
/// assert_eq!(bevy_gooey::toast_life(2.5, 0.25), 3.0);
/// ```
pub fn toast_life(hold: f32, fade: f32) -> f32 {
    let fade = if fade.is_finite() && fade > 0.0 {
        fade
    } else {
        0.0
    };
    let hold = if hold.is_finite() && hold > 0.0 {
        hold
    } else {
        0.0
    };
    hold + 2.0 * fade
}

/// How opaque a toast is `age` seconds after it was spawned, from 0 to 1: rising over the first
/// `fade`, whole for `hold`, then falling over the last `fade` (see [`toast_life`]). With no fade
/// it is whole for `hold` and then gone. Never NaN: an age that is not finite or is negative reads
/// as not yet shown.
///
/// ```
/// assert_eq!(bevy_gooey::toast_alpha(0.0, 2.5, 0.25), 0.0);
/// assert_eq!(bevy_gooey::toast_alpha(1.0, 2.5, 0.25), 1.0);
/// assert_eq!(bevy_gooey::toast_alpha(3.0, 2.5, 0.25), 0.0);
/// ```
pub fn toast_alpha(age: f32, hold: f32, fade: f32) -> f32 {
    if !age.is_finite() || age < 0.0 {
        return 0.0;
    }
    let hold = if hold.is_finite() && hold > 0.0 {
        hold
    } else {
        0.0
    };
    if !(fade.is_finite() && fade > 0.0) {
        return if age < hold { 1.0 } else { 0.0 };
    }
    let rising = age / fade;
    let falling = (hold + 2.0 * fade - age) / fade;
    rising.min(falling).clamp(0.0, 1.0)
}

/// How much of its room a toast has opened `age` seconds after it was spawned, from 0 to 1: the
/// fade's envelope ([`toast_alpha`]) eased out (`1 − (1 − alpha)³`), so a new toast opens its room
/// quickly while it is still faint and settles, and a leaving one holds its room while it fades
/// and closes it at the end. The toasts around it glide with it, because the room is layout. With
/// no fade it is whole for `hold` and then gone.
///
/// ```
/// assert_eq!(bevy_gooey::toast_grow(0.0, 2.5, 0.25), 0.0);
/// assert_eq!(bevy_gooey::toast_grow(1.0, 2.5, 0.25), 1.0);
/// assert!(bevy_gooey::toast_grow(0.125, 2.5, 0.25) > 0.8);
/// ```
pub fn toast_grow(age: f32, hold: f32, fade: f32) -> f32 {
    let left = 1.0 - toast_alpha(age, hold, fade);
    1.0 - left * left * left
}

/// A time since the app started as a clock reads it: `m:ss`, and `h:mm:ss` from an hour. A time that
/// is not finite or is negative reads as zero.
///
/// ```
/// assert_eq!(bevy_gooey::clock_text(7.4), "0:07");
/// assert_eq!(bevy_gooey::clock_text(754.0), "12:34");
/// assert_eq!(bevy_gooey::clock_text(3723.0), "1:02:03");
/// assert_eq!(bevy_gooey::clock_text(f32::NAN), "0:00");
/// ```
pub fn clock_text(seconds: f32) -> String {
    let total = if seconds.is_finite() && seconds > 0.0 {
        seconds as u64
    } else {
        0
    };
    let (hours, minutes, secs) = (total / 3600, total / 60 % 60, total % 60);
    if hours > 0 {
        format!("{hours}:{minutes:02}:{secs:02}")
    } else {
        format!("{minutes}:{secs:02}")
    }
}

/// How tall a list stands to show `rows` rows, in the units of its inputs: `rows × (row + gap)`,
/// `row` the height of one row and `gap` the space between two, so each row counts with the gap
/// after it. `4.5` is four rows and half a pitch of the fifth, which cuts it, the signifier that
/// more is below (NN/g, *Scrolling and Attention*); `4.0` ends a gap past the fourth row. Zero for
/// a count that is not finite and above zero.
///
/// ```
/// // Four and a half rows of 48 px with 10 px between: four rows and 29 px of the fifth.
/// assert_eq!(bevy_gooey::list_height(4.5, 48.0, 10.0), 4.5 * 58.0);
/// assert_eq!(bevy_gooey::list_height(4.0, 48.0, 10.0), 4.0 * 58.0);
/// assert_eq!(bevy_gooey::list_height(f32::NAN, 48.0, 10.0), 0.0);
/// ```
pub fn list_height(rows: f32, row: f32, gap: f32) -> f32 {
    if rows.is_finite() && rows > 0.0 && row.is_finite() && gap.is_finite() {
        (rows * (row + gap)).max(0.0)
    } else {
        0.0
    }
}

/// The scroll position that brings a span into a list's viewport with context round it, measured
/// from the start of the scrolled content: the span `top..bottom` (a focused widget), a viewport
/// `view` tall at `scroll`, a furthest scroll `max`, and `margin` of list to leave beyond the span.
///
/// The least scroll that leaves `margin` of list on the side the span would leave through, so the
/// player always sees what is next (revealing only to the edge glues the focus to the bottom pixel
/// of the viewport with nothing in sight below it). The margin is cut to what the viewport can hold
/// beside the span. A span taller than the viewport scrolls to its top, the part read first; a move
/// of more than one viewport centres the span instead of creeping to the edge; the answer is
/// always within `0..=max`, and `scroll` itself when the span is already comfortably inside.
/// Nothing usable (a viewport of no height, a value that is not finite) leaves `scroll` alone.
///
/// ```
/// // A 160 px viewport at the top of a 440 px list of 40 px rows, a margin of one row: the fourth
/// // row (120..160) wants the fifth in sight too, 160 + 40 − 160 = 40 px of scroll, and from there
/// // the fifth (160..200) wants 200 + 40 − 160 = 80.
/// assert_eq!(bevy_gooey::scroll_to_reveal(120.0, 160.0, 160.0, 0.0, 280.0, 40.0), 40.0);
/// assert_eq!(bevy_gooey::scroll_to_reveal(160.0, 200.0, 160.0, 40.0, 280.0, 40.0), 80.0);
/// // The third row (80..120) already has a row below it in view: nothing to do.
/// assert_eq!(bevy_gooey::scroll_to_reveal(80.0, 120.0, 160.0, 0.0, 280.0, 40.0), 0.0);
/// // The last row stops at the end of the list, not a margin past it.
/// assert_eq!(bevy_gooey::scroll_to_reveal(400.0, 440.0, 160.0, 200.0, 280.0, 40.0), 280.0);
/// ```
pub fn scroll_to_reveal(
    top: f32,
    bottom: f32,
    view: f32,
    scroll: f32,
    max: f32,
    margin: f32,
) -> f32 {
    let usable = [top, bottom, view, scroll, max, margin]
        .iter()
        .all(|x| x.is_finite());
    let max = max.max(0.0);
    if !usable || view <= 0.0 || bottom < top {
        return if scroll.is_finite() {
            scroll.clamp(0.0, max)
        } else {
            0.0
        };
    }
    let height = bottom - top;
    // A span taller than the viewport is read from its top, whichever way it is reached.
    if height > view {
        return top.clamp(0.0, max);
    }
    // What the viewport can hold beside the span, so a short viewport asks for the most margin it
    // can keep rather than a margin on each side it cannot have both of.
    let margin = margin.max(0.0).min((view - height) * 0.5);
    let want = if top - margin < scroll {
        top - margin
    } else if bottom + margin > scroll + view {
        bottom + margin - view
    } else {
        scroll
    };
    // Further than a viewport is a jump, not a step: put the span in the middle.
    let want = if (want - scroll).abs() > view {
        (top + bottom) * 0.5 - view * 0.5
    } else {
        want
    };
    want.clamp(0.0, max)
}

/// A scroll position moved on to the top of a row, so a list that follows focus always stands with a
/// row flush at the top of its viewport, as it does at rest, and the row it cuts at the bottom is
/// cut the same way at every step: `want` is where [`scroll_to_reveal`] asked to go from `scroll`,
/// and `tops` are the rows' tops in the same units. Moving down it takes the first row top at or
/// after `want`, moving up the last at or before it (half a unit of slack for rounded layout), so
/// it never scrolls less than was asked. `None` when no row top lies that way (the end of the
/// list: the caller keeps `want`, which then ends flush with the last row) or `want` is no move.
///
/// ```
/// let tops = [0.0, 57.0, 114.0, 171.0];
/// // A step of 46.8 down, from the top, goes on to the next row's top.
/// assert_eq!(bevy_gooey::snap_to_row(46.8, 0.0, &tops), Some(57.0));
/// // A step up from 171 that asks for 120 stops at the row top above it.
/// assert_eq!(bevy_gooey::snap_to_row(120.0, 171.0, &tops), Some(114.0));
/// // Past the last row top there is nothing to snap to.
/// assert_eq!(bevy_gooey::snap_to_row(190.0, 114.0, &tops), None);
/// ```
pub fn snap_to_row(want: f32, scroll: f32, tops: &[f32]) -> Option<f32> {
    if !(want.is_finite() && scroll.is_finite()) || (want - scroll).abs() < f32::EPSILON {
        return None;
    }
    let usable = tops.iter().copied().filter(|t| t.is_finite());
    if want > scroll {
        usable
            .filter(|&t| t >= want - 0.5)
            .min_by(|a, b| a.total_cmp(b))
    } else {
        usable
            .filter(|&t| t <= want + 0.5)
            .max_by(|a, b| a.total_cmp(b))
    }
}

/// Which of a list's rows a page away from the focused one is, for PageUp and PageDown: `from` is
/// the focused row's centre along the list, `centres` the rows' centres in the same units, and
/// `page` how far to go, positive for down and negative for up. The row furthest from `from` in
/// that direction that is still within a page of it; if even the next row is further than a page
/// away (tall rows), the next row. `None` when no row lies that way. Rows less than half a unit
/// from `from` count as its own row; of rows at one distance the first is taken.
///
/// ```
/// let rows = [20.0, 70.0, 120.0, 170.0, 220.0, 270.0];
/// // From the first row, a 150-unit page lands on the row at 170.
/// assert_eq!(bevy_gooey::page_target(20.0, &rows, 150.0), Some(3));
/// // Up from the last row, the same page lands on the row at 120.
/// assert_eq!(bevy_gooey::page_target(270.0, &rows, -150.0), Some(2));
/// // Nothing lies below the last row.
/// assert_eq!(bevy_gooey::page_target(270.0, &rows, 150.0), None);
/// // A page shorter than the pitch still takes one step.
/// assert_eq!(bevy_gooey::page_target(20.0, &rows, 10.0), Some(1));
/// ```
pub fn page_target(from: f32, centres: &[f32], page: f32) -> Option<usize> {
    if !(from.is_finite() && page.is_finite() && page != 0.0) {
        return None;
    }
    let ahead = |centre: f32| (centre - from) * page.signum();
    let mut nearest: Option<(usize, f32)> = None;
    let mut farthest: Option<(usize, f32)> = None;
    for (i, &centre) in centres.iter().enumerate() {
        let d = ahead(centre);
        if d.is_nan() || d < 0.5 {
            continue;
        }
        if nearest.is_none_or(|(_, n)| d < n) {
            nearest = Some((i, d));
        }
        if d <= page.abs() && farthest.is_none_or(|(_, f)| d > f) {
            farthest = Some((i, d));
        }
    }
    farthest.or(nearest).map(|(i, _)| i)
}

/// How far a key moves a [`crate::split`]'s divider, in logical pixels: an arrow press steps by this,
/// and a held key repeats. A design default: a pane's edge is a pixel thing, and a step the size of
/// a gap is visible and reaches any size in a few presses.
pub const SPLIT_KEY_STEP_PX: f32 = 16.0;

/// The smallest sizes, in logical pixels, a [`crate::split`]'s two panes may have in `extent`
/// pixels (the split's length less its divider), as `(first, second)`. The minimums asked for
/// when they fit; when `extent` is smaller than the two together, the second pane gives way first
/// down to nothing and the first keeps its own minimum while it can. Negative and non-finite
/// inputs count as zero.
///
/// ```
/// assert_eq!(bevy_gooey::split_mins(500.0, 100.0, 80.0), (100.0, 80.0));
/// // 150 px cannot hold both: the second side collapses first.
/// assert_eq!(bevy_gooey::split_mins(150.0, 100.0, 80.0), (100.0, 50.0));
/// assert_eq!(bevy_gooey::split_mins(60.0, 100.0, 80.0), (60.0, 0.0));
/// ```
pub fn split_mins(extent: f32, min_first: f32, min_second: f32) -> (f32, f32) {
    let usable = |x: f32| if x.is_finite() { x.max(0.0) } else { 0.0 };
    let extent = usable(extent);
    let first = usable(min_first).min(extent);
    let second = usable(min_second).min(extent - first);
    (first, second)
}

/// A [`crate::split`]'s fraction held to its panes' minimums: `fraction` (the first pane's share
/// of `extent`) clamped to the range [`split_mins`] leaves, and to 0 to 1. Never NaN; with no room
/// (`extent` zero or less) only the 0 to 1 clamp applies.
///
/// ```
/// // 400 px of room, minimums 100 and 80: the first pane's share stays within 0.25 and 0.8.
/// assert_eq!(bevy_gooey::split_clamp(0.1, 400.0, 100.0, 80.0), 0.25);
/// assert_eq!(bevy_gooey::split_clamp(0.9, 400.0, 100.0, 80.0), 0.8);
/// assert_eq!(bevy_gooey::split_clamp(0.5, 400.0, 100.0, 80.0), 0.5);
/// ```
pub fn split_clamp(fraction: f32, extent: f32, min_first: f32, min_second: f32) -> f32 {
    let fraction = if fraction.is_finite() {
        fraction.clamp(0.0, 1.0)
    } else {
        0.0
    };
    if !(extent.is_finite() && extent > 0.0) {
        return fraction;
    }
    let (first, second) = split_mins(extent, min_first, min_second);
    fraction.clamp(first / extent, 1.0 - second / extent)
}

/// Where a [`crate::split`]'s fraction lands when a divider that started at `start` is moved
/// `distance` logical pixels along the split's axis: `start + distance / extent`, held to the
/// minimums ([`split_clamp`]). A drag of 100 px changes the fraction by `100 / extent`.
///
/// ```
/// let moved = bevy_gooey::split_drag(0.5, 100.0, 800.0, 0.0, 0.0);
/// assert!((moved - 0.625).abs() < 1e-6);
/// // Dragged a long way past the end it stops at the second pane's minimum.
/// assert_eq!(bevy_gooey::split_drag(0.5, 5000.0, 800.0, 0.0, 200.0), 0.75);
/// ```
pub fn split_drag(start: f32, distance: f32, extent: f32, min_first: f32, min_second: f32) -> f32 {
    if extent.is_finite() && extent > 0.0 && distance.is_finite() {
        split_clamp(start + distance / extent, extent, min_first, min_second)
    } else {
        split_clamp(start, extent, min_first, min_second)
    }
}

/// The least a pane of a [`crate::dock`]'s split may be, in logical pixels: a panel narrower than
/// this is worse than none, and a drop that made one could not be undone by a drag.
pub const DOCK_PANE_MIN_PX: f32 = 96.0;

/// How much of a group's width or height, at each end, is an edge for [`dock_zone`]: the outer
/// quarter is an edge, the middle half is the group.
pub const DOCK_EDGE_FRACTION: f32 = 0.25;

/// The share of a whole dock a panel dropped on its edge takes ([`dock_drop_rect`]).
pub const DOCK_EDGE_SHARE: f32 = 0.25;

/// Where a dragged panel of a [`crate::dock`] lands relative to a group: into it, or against one of
/// its edges (a split of the group on that side).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DockZone {
    /// Into the group, as one of its tabs.
    Into,
    /// A group of its own to the left.
    Left,
    /// A group of its own to the right.
    Right,
    /// A group of its own above.
    Top,
    /// A group of its own below.
    Bottom,
}

/// The zone of a group `width` by `height` that the point `(x, y)`, from the group's top-left, is
/// in: the middle half of both sides is [`DockZone::Into`], and anywhere else the edge nearest the
/// point (by its share of the side). A degenerate group is all `Into`.
///
/// ```
/// use bevy_gooey::{DockZone, dock_zone};
/// assert_eq!(dock_zone(400.0, 200.0, 200.0, 100.0), DockZone::Into);
/// assert_eq!(dock_zone(400.0, 200.0, 20.0, 100.0), DockZone::Left);
/// assert_eq!(dock_zone(400.0, 200.0, 200.0, 190.0), DockZone::Bottom);
/// ```
pub fn dock_zone(width: f32, height: f32, x: f32, y: f32) -> DockZone {
    if !(width > 0.0 && height > 0.0 && x.is_finite() && y.is_finite()) {
        return DockZone::Into;
    }
    let (nx, ny) = ((x / width).clamp(0.0, 1.0), (y / height).clamp(0.0, 1.0));
    let edge = DOCK_EDGE_FRACTION;
    if (edge..=1.0 - edge).contains(&nx) && (edge..=1.0 - edge).contains(&ny) {
        return DockZone::Into;
    }
    let nearest = [
        (nx, DockZone::Left),
        (1.0 - nx, DockZone::Right),
        (ny, DockZone::Top),
        (1.0 - ny, DockZone::Bottom),
    ];
    nearest
        .into_iter()
        .fold((f32::MAX, DockZone::Into), |best, now| {
            if now.0 < best.0 { now } else { best }
        })
        .1
}

/// The edge of a whole dock `width` by `height` that the point `(x, y)` is within `band` of, the
/// nearest if two (a corner), or `None` away from every edge (or outside the dock). Dropping on
/// one splits the whole layout rather than a group.
///
/// ```
/// use bevy_gooey::{DockZone, dock_edge_zone};
/// assert_eq!(dock_edge_zone(800.0, 400.0, 10.0, 200.0, 24.0), Some(DockZone::Left));
/// assert_eq!(dock_edge_zone(800.0, 400.0, 400.0, 200.0, 24.0), None);
/// ```
pub fn dock_edge_zone(width: f32, height: f32, x: f32, y: f32, band: f32) -> Option<DockZone> {
    if !(x >= 0.0 && y >= 0.0 && x <= width && y <= height) {
        return None;
    }
    [
        (x, DockZone::Left),
        (width - x, DockZone::Right),
        (y, DockZone::Top),
        (height - y, DockZone::Bottom),
    ]
    .into_iter()
    .filter(|(distance, _)| *distance < band)
    .min_by(|a, b| a.0.total_cmp(&b.0))
    .map(|(_, zone)| zone)
}

/// The part of a group (or, with `whole`, of the whole dock) `width` by `height` that a panel
/// dropped in `zone` will take, as `(x, y, width, height)` from the top-left: all of the group for
/// [`DockZone::Into`], half of it for an edge ([`DOCK_EDGE_SHARE`] of the whole dock). The overlay
/// that shows the landing is drawn from it, so it is exactly the layout the drop makes.
pub fn dock_drop_rect(
    zone: DockZone,
    width: f32,
    height: f32,
    whole: bool,
) -> (f32, f32, f32, f32) {
    let share = if whole { DOCK_EDGE_SHARE } else { 0.5 };
    match zone {
        DockZone::Into => (0.0, 0.0, width, height),
        DockZone::Left => (0.0, 0.0, width * share, height),
        DockZone::Right => (width * (1.0 - share), 0.0, width * share, height),
        DockZone::Top => (0.0, 0.0, width, height * share),
        DockZone::Bottom => (0.0, height * (1.0 - share), width, height * share),
    }
}

/// The place among a group's tabs a panel dropped at `(x, y)` lands in, for tabs that may stand in
/// several rows: `tabs` are each tab's `(centre x, top, bottom)` in order, and a tab is before the
/// point when it lies wholly above it, or is in the point's row and its centre is left of `x`. `0`
/// is before the first tab and `tabs.len()` after the last.
///
/// ```
/// let row = [(50.0, 0.0, 40.0), (150.0, 0.0, 40.0), (250.0, 0.0, 40.0)];
/// assert_eq!(bevy_gooey::dock_tab_slot(&row, 160.0, 20.0), 2);
/// assert_eq!(bevy_gooey::dock_tab_slot(&[], 10.0, 10.0), 0);
/// // A second row: a point in it is after the whole first row.
/// let two = [(50.0, 0.0, 40.0), (150.0, 0.0, 40.0), (50.0, 46.0, 86.0)];
/// assert_eq!(bevy_gooey::dock_tab_slot(&two, 20.0, 60.0), 2);
/// ```
pub fn dock_tab_slot(tabs: &[(f32, f32, f32)], x: f32, y: f32) -> usize {
    tabs.iter()
        .filter(|&&(centre, _, bottom)| bottom <= y || (centre < x && y < bottom))
        .count()
}

/// The one of `others` (centres of groups) nearest to `from`, in the direction `toward` names
/// (an edge zone; [`DockZone::Into`] has no direction), or `None` when none lies that way. A group
/// off to the side counts against the one straight ahead: distance along the direction, with
/// twice the sideways distance.
///
/// ```
/// use bevy_gooey::{DockZone, dock_neighbour};
/// let others = [(100.0, 50.0), (400.0, 60.0), (400.0, 300.0)];
/// assert_eq!(dock_neighbour((200.0, 50.0), &others, DockZone::Right), Some(1));
/// assert_eq!(dock_neighbour((200.0, 50.0), &others, DockZone::Top), None);
/// ```
pub fn dock_neighbour(from: (f32, f32), others: &[(f32, f32)], toward: DockZone) -> Option<usize> {
    let (dx, dy) = match toward {
        DockZone::Into => return None,
        DockZone::Left => (-1.0, 0.0),
        DockZone::Right => (1.0, 0.0),
        DockZone::Top => (0.0, -1.0),
        DockZone::Bottom => (0.0, 1.0),
    };
    others
        .iter()
        .enumerate()
        .filter_map(|(index, &(x, y))| {
            let (vx, vy) = (x - from.0, y - from.1);
            let ahead = vx * dx + vy * dy;
            let aside = vx * dy - vy * dx;
            (ahead > 1.0).then_some((index, ahead * ahead + 4.0 * aside * aside))
        })
        .min_by(|a, b| a.1.total_cmp(&b.1))
        .map(|(index, _)| index)
}

/// The order of two cells' text for a table's sort: runs of digits compare by value ("2" before
/// "10", "007" the same number as "7"), everything else letter by letter without regard to case,
/// and what is still equal falls back to the exact bytes, so the order is total and stable.
///
/// ```
/// use std::cmp::Ordering::{Equal, Greater, Less};
/// assert_eq!(bevy_gooey::natural_cmp("Item 2", "Item 10"), Less);
/// assert_eq!(bevy_gooey::natural_cmp("item 10", "Item 2"), Greater);
/// assert_eq!(bevy_gooey::natural_cmp("apple", "Banana"), Less);
/// assert_eq!(bevy_gooey::natural_cmp("a", "a"), Equal);
/// ```
pub fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    // The digits at the start of `s` (ASCII, so a byte length is a char length), without the
    // zeros that lead them.
    fn digits(s: &str) -> (&str, usize) {
        let run = s.bytes().take_while(u8::is_ascii_digit).count();
        (s[..run].trim_start_matches('0'), run)
    }
    let (mut x, mut y) = (a, b);
    loop {
        match (x.chars().next(), y.chars().next()) {
            (None, None) => return a.cmp(b),
            (None, Some(_)) => return Ordering::Less,
            (Some(_), None) => return Ordering::Greater,
            (Some(p), Some(q)) if p.is_ascii_digit() && q.is_ascii_digit() => {
                let ((m, taken_x), (n, taken_y)) = (digits(x), digits(y));
                let order = m.len().cmp(&n.len()).then_with(|| m.cmp(n));
                if order != Ordering::Equal {
                    return order;
                }
                (x, y) = (&x[taken_x..], &y[taken_y..]);
            }
            (Some(p), Some(q)) => {
                let order = p.to_lowercase().cmp(q.to_lowercase());
                if order != Ordering::Equal {
                    return order;
                }
                (x, y) = (&x[p.len_utf8()..], &y[q.len_utf8()..]);
            }
        }
    }
}

/// The first row a virtualized table draws: the row the `scroll` offset has at its top, held so
/// that `pool` rows from it are all rows (`len` rows in all, each `pitch` tall). A scroll past the
/// end, a pool larger than the data or a pitch that is not usable answer with a valid first row.
///
/// ```
/// assert_eq!(bevy_gooey::table_window(0.0, 40.0, 10, 1000), 0);
/// assert_eq!(bevy_gooey::table_window(400.0, 40.0, 10, 1000), 10);
/// assert_eq!(bevy_gooey::table_window(399.0, 40.0, 10, 1000), 9);
/// // The last rows: the pool never runs past the data.
/// assert_eq!(bevy_gooey::table_window(1e9, 40.0, 10, 1000), 990);
/// assert_eq!(bevy_gooey::table_window(400.0, 40.0, 10, 4), 0);
/// assert_eq!(bevy_gooey::table_window(f32::NAN, 40.0, 10, 1000), 0);
/// ```
pub fn table_window(scroll: f32, pitch: f32, pool: usize, len: usize) -> usize {
    let last = len.saturating_sub(pool);
    if !(scroll.is_finite() && pitch.is_finite()) || pitch <= 0.0 || scroll <= 0.0 {
        return 0;
    }
    ((scroll / pitch).floor() as usize).min(last)
}

/// A move of a table's cursor row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TableStep {
    /// One row up.
    Up,
    /// One row down.
    Down,
    /// A page up.
    PageUp,
    /// A page down.
    PageDown,
    /// The first row of the data.
    First,
    /// The last row of the data, not of the rows drawn.
    Last,
}

/// Where a table's cursor goes: from display row `from` (none yet) by `step`, in `len` rows with
/// `page` rows to a page. Never past either end; `None` when there are no rows. With no cursor
/// yet, any step but Up and PageUp lands on the first row and those two on the last, so the first
/// key press lands somewhere in sight of where the player was going.
///
/// ```
/// use bevy_gooey::TableStep::*;
/// assert_eq!(bevy_gooey::table_step(Some(5), Down, 10, 4), Some(6));
/// assert_eq!(bevy_gooey::table_step(Some(9), Down, 10, 4), Some(9));
/// assert_eq!(bevy_gooey::table_step(Some(5), PageDown, 10, 4), Some(9));
/// assert_eq!(bevy_gooey::table_step(Some(2), PageUp, 10, 4), Some(0));
/// assert_eq!(bevy_gooey::table_step(Some(2), Last, 10_000, 4), Some(9_999));
/// assert_eq!(bevy_gooey::table_step(None, Down, 10, 4), Some(0));
/// assert_eq!(bevy_gooey::table_step(None, Up, 10, 4), Some(9));
/// assert_eq!(bevy_gooey::table_step(Some(0), Down, 0, 4), None);
/// ```
pub fn table_step(from: Option<usize>, step: TableStep, len: usize, page: usize) -> Option<usize> {
    let last = len.checked_sub(1)?;
    let page = page.max(1);
    let Some(from) = from.map(|f| f.min(last)) else {
        return Some(match step {
            TableStep::Up | TableStep::PageUp | TableStep::Last => last,
            TableStep::Down | TableStep::PageDown | TableStep::First => 0,
        });
    };
    Some(match step {
        TableStep::Up => from.saturating_sub(1),
        TableStep::Down => (from + 1).min(last),
        TableStep::PageUp => from.saturating_sub(page),
        TableStep::PageDown => (from + page).min(last),
        TableStep::First => 0,
        TableStep::Last => last,
    })
}

/// The scroll that keeps a table's anchor row where it stood when its rows change under it: the
/// row that was `old_first` at the top of the view, `scroll` pixels down, is now display row
/// `new_index` (`None`: it is gone, so the scroll stays), `pitch` pixels to a row, held to `max`.
///
/// ```
/// // 100 rows come in above the row that was at the top, 5 px into row 50.
/// assert_eq!(bevy_gooey::table_anchor(2005.0, 40.0, 50, Some(150), 1e9), 6005.0);
/// // The anchor row is gone: stay.
/// assert_eq!(bevy_gooey::table_anchor(2005.0, 40.0, 50, None, 1e9), 2005.0);
/// // Held to the end of the data.
/// assert_eq!(bevy_gooey::table_anchor(2005.0, 40.0, 50, Some(150), 3000.0), 3000.0);
/// ```
pub fn table_anchor(
    scroll: f32,
    pitch: f32,
    old_first: usize,
    new_index: Option<usize>,
    max: f32,
) -> f32 {
    let moved = new_index.map_or(scroll, |new| {
        scroll + (new as f32 - old_first as f32) * pitch
    });
    if moved.is_finite() {
        moved.clamp(0.0, max.max(0.0))
    } else {
        0.0
    }
}

/// The least a table's column may be, in body text sizes: room for a letter and a sort mark.
pub const TABLE_LEAST_COLUMN: f32 = 3.0;

/// A column's width after its edge moves `by` pixels from `start` (all in logical pixels), never
/// under `least`.
///
/// ```
/// assert_eq!(bevy_gooey::column_resize(100.0, 40.0, 48.0), 140.0);
/// assert_eq!(bevy_gooey::column_resize(100.0, -90.0, 48.0), 48.0);
/// assert_eq!(bevy_gooey::column_resize(100.0, f32::NAN, 48.0), 100.0);
/// ```
pub fn column_resize(start: f32, by: f32, least: f32) -> f32 {
    let wide = start + by;
    if wide.is_finite() {
        wide.max(least)
    } else {
        start.max(least)
    }
}

/// How long a pause ends a typed prefix, in seconds: characters typed within this long of each
/// other make one prefix (the APG's "rapid succession"), a longer pause starts it over.
pub const TYPE_AHEAD_SECS: f32 = 1.0;

/// The indent of one tree level, and the width of a node's disclosure chevron, in logical pixels
/// for body text `text_px` high: a text size and a half, never under [`MIN_TARGET_PX`] (WCAG 2.5.8).
///
/// ```
/// assert_eq!(bevy_gooey::tree_indent(16.0), 24.0);
/// assert_eq!(bevy_gooey::tree_indent(32.0), 48.0);
/// assert_eq!(bevy_gooey::tree_indent(10.0), 24.0);
/// ```
pub fn tree_indent(text_px: f32) -> f32 {
    (text_px * 1.5).max(MIN_TARGET_PX)
}

/// For nodes in depth-first order with the given `depths` (the first is 0 and no depth is more
/// than one past the one before it), where each node's subtree ends: the index of the first node
/// after it that is not its descendant (`depths.len()` for the last subtree). A node with no
/// children ends at the next index.
///
/// ```
/// // a ( b ( c ) d ) e
/// assert_eq!(bevy_gooey::tree_ends(&[0, 1, 2, 1, 0]), vec![4, 3, 3, 4, 5]);
/// ```
pub fn tree_ends(depths: &[u32]) -> Vec<usize> {
    let mut ends = vec![depths.len(); depths.len()];
    let mut open: Vec<usize> = Vec::new();
    for (i, &depth) in depths.iter().enumerate() {
        while let Some(&top) = open.last() {
            if depths[top] < depth {
                break;
            }
            ends[top] = i;
            open.pop();
        }
        open.push(i);
    }
    ends
}

/// The nodes a tree shows, in order: every node whose ancestors are all open. `ends` is
/// [`tree_ends`] and `open` each node's own state; a closed node's descendants are skipped
/// whatever their own state, so closing a node loses nothing below it.
///
/// ```
/// let ends = bevy_gooey::tree_ends(&[0, 1, 2, 1, 0]);
/// // a is open, b is closed (c is open but hidden), e is closed.
/// let open = [true, false, true, false, false];
/// assert_eq!(bevy_gooey::tree_visible(&ends, &open), vec![0, 1, 3, 4]);
/// ```
pub fn tree_visible(ends: &[usize], open: &[bool]) -> Vec<usize> {
    let mut shown = Vec::new();
    let mut i = 0;
    while i < ends.len() {
        shown.push(i);
        i = if open.get(i).copied().unwrap_or(false) {
            i + 1
        } else {
            ends[i]
        };
    }
    shown
}

/// The parent of node `index`: the nearest node before it that is shallower. `None` for a root.
///
/// ```
/// let depths = [0, 1, 2, 1, 0];
/// assert_eq!(bevy_gooey::tree_parent(&depths, 2), Some(1));
/// assert_eq!(bevy_gooey::tree_parent(&depths, 3), Some(0));
/// assert_eq!(bevy_gooey::tree_parent(&depths, 4), None);
/// ```
pub fn tree_parent(depths: &[u32], index: usize) -> Option<usize> {
    let depth = *depths.get(index)?;
    (0..index).rev().find(|&j| depths[j] < depth)
}

/// Who takes the place of node `index` when its subtree is removed: its next sibling, else its
/// previous sibling, else its parent. `None` for the only node there is.
///
/// ```
/// // a ( b c ) d ( e )
/// let depths = [0, 1, 1, 0, 1];
/// let ends = bevy_gooey::tree_ends(&depths);
/// assert_eq!(bevy_gooey::tree_heir(&depths, &ends, 1), Some(2)); // next sibling
/// assert_eq!(bevy_gooey::tree_heir(&depths, &ends, 2), Some(1)); // the one before
/// assert_eq!(bevy_gooey::tree_heir(&depths, &ends, 4), Some(3)); // an only child: the parent
/// assert_eq!(bevy_gooey::tree_heir(&depths, &ends, 0), Some(3)); // a root: the next root
/// assert_eq!(bevy_gooey::tree_heir(&[0], &[1], 0), None);
/// ```
pub fn tree_heir(depths: &[u32], ends: &[usize], index: usize) -> Option<usize> {
    let depth = *depths.get(index)?;
    let next = *ends.get(index)?;
    if depths.get(next) == Some(&depth) {
        return Some(next);
    }
    (0..index).rev().find(|&j| depths[j] <= depth)
}

/// Where type-ahead takes the cursor: in `len` rows with the cursor on `from`, the first row that
/// `hit` accepts, looking forward and wrapping. A one-character prefix starts after the cursor row
/// (typing "c" again goes on to the next row starting with "c"); a longer one starts on it (typing
/// "ca" while on "Camera" stays). `None` when no row matches.
///
/// ```
/// let rows = ["Camera", "Cube", "Light", "Cube2"];
/// let hit = |prefix: &'static str| move |i: usize| rows[i].to_lowercase().starts_with(prefix);
/// assert_eq!(bevy_gooey::type_ahead(4, None, 1, hit("c")), Some(0));
/// assert_eq!(bevy_gooey::type_ahead(4, Some(0), 1, hit("c")), Some(1));
/// assert_eq!(bevy_gooey::type_ahead(4, Some(3), 1, hit("c")), Some(0));
/// assert_eq!(bevy_gooey::type_ahead(4, Some(1), 2, hit("cu")), Some(1));
/// assert_eq!(bevy_gooey::type_ahead(4, Some(1), 1, hit("z")), None);
/// ```
pub fn type_ahead(
    len: usize,
    from: Option<usize>,
    prefix_len: usize,
    hit: impl Fn(usize) -> bool,
) -> Option<usize> {
    let start = match from {
        None => 0,
        Some(f) if prefix_len <= 1 => f + 1,
        Some(f) => f,
    };
    (0..len).map(|k| (start + k) % len.max(1)).find(|&i| hit(i))
}

/// Why [`parse_number`] would not read some text as a number. The words are for the player
/// ([`std::fmt::Display`]): a game shows them beside the field, the crate sends them with
/// [`crate::NumberRefused`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum NumberError {
    /// Nothing was typed.
    Empty,
    /// An expression such as `1.5*2`: a number field takes a number, not a sum.
    Expression,
    /// Letters, or digits in the wrong places.
    NotANumber,
    /// A number too large to hold, or `inf` or `NaN`.
    NotFinite,
}

impl std::fmt::Display for NumberError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Empty => "type a number",
            Self::Expression => "type a number, not an expression",
            Self::NotANumber => "that is not a number",
            Self::NotFinite => "that number is too large",
        })
    }
}

/// The number a player typed: spaces round it are ignored, a leading `+`, `-` or `−` (U+2212) is
/// a sign, and a decimal point and an exponent (`1e3`) are read; the decimal comma is not. An
/// expression (`1.5*2`, `3+4`, `(2)`) is refused as [`NumberError::Expression`], never evaluated.
///
/// ```
/// use bevy_gooey::{NumberError, parse_number};
/// assert_eq!(parse_number(" 2.5 "), Ok(2.5));
/// assert_eq!(parse_number("−3"), Ok(-3.0));
/// assert_eq!(parse_number("1e3"), Ok(1000.0));
/// assert_eq!(parse_number("1.5*2"), Err(NumberError::Expression));
/// assert_eq!(parse_number("abc"), Err(NumberError::NotANumber));
/// assert_eq!(parse_number(""), Err(NumberError::Empty));
/// ```
pub fn parse_number(text: &str) -> Result<f32, NumberError> {
    let text = text.trim();
    if text.is_empty() {
        return Err(NumberError::Empty);
    }
    let text = text.replace('\u{2212}', "-");
    let mut previous = None;
    for (i, c) in text.char_indices() {
        let sign = matches!(c, '+' | '-');
        let exponent_sign = sign && matches!(previous, Some('e' | 'E'));
        if matches!(c, '*' | '/' | '(' | ')' | '^' | '%' | '\u{d7}' | '\u{f7}')
            || (sign && i > 0 && !exponent_sign)
        {
            return Err(NumberError::Expression);
        }
        previous = Some(c);
    }
    match text.parse::<f32>() {
        Ok(n) if n.is_finite() => Ok(n),
        Ok(_) => Err(NumberError::NotFinite),
        Err(_) => Err(NumberError::NotANumber),
    }
}

/// The digits after the point that show every multiple of `step` exactly: 1 for 0.1, 2 for 0.25,
/// 0 for 1 or 5, at most 6. A step that is not a positive number shows 2.
///
/// ```
/// assert_eq!(bevy_gooey::number_decimals(0.1), 1);
/// assert_eq!(bevy_gooey::number_decimals(0.25), 2);
/// assert_eq!(bevy_gooey::number_decimals(5.0), 0);
/// ```
pub fn number_decimals(step: f32) -> usize {
    if !(step.is_finite() && step > 0.0) {
        return 2;
    }
    (0..=6)
        .find(|&d| {
            let scale = 10f32.powi(d);
            ((step * scale).round() / scale - step).abs() <= step * 1e-4
        })
        .map_or(6, |d| d as usize)
}

/// A number as a field shows it: the digits of `step` (see [`number_decimals`]) and more when the
/// value needs them (the fewest, up to 6, that read back as the same number), so the text never
/// says a different number than the value. Never `-0`.
///
/// ```
/// assert_eq!(bevy_gooey::format_number(5.0, 0.1), "5.0");
/// assert_eq!(bevy_gooey::format_number(1.55, 0.1), "1.55");
/// assert_eq!(bevy_gooey::format_number(-0.0, 0.1), "0.0");
/// assert_eq!(bevy_gooey::format_number(42.0, 1.0), "42");
/// ```
pub fn format_number(value: f32, step: f32) -> String {
    let base = number_decimals(step);
    if !value.is_finite() {
        return format!("{value}");
    }
    let value = if value == 0.0 { 0.0 } else { value };
    (base..=6)
        .map(|d| format!("{value:.d$}"))
        .find(|s| s.parse::<f32>().is_ok_and(|n| n == value))
        .unwrap_or_else(|| format!("{value:.6}"))
}

/// What a drag of `distance` logical pixels makes of a number that was `start` when the press
/// began: `start + distance × step`, so 50 px at a step of 0.1 is 5.0. `fine` (Shift) takes a
/// tenth of the rate and `coarse` (Ctrl) ten times it; the result is rounded to the digits of the
/// rate, so there is no `5.000001`, and held to `min..=max`.
///
/// ```
/// use bevy_gooey::scrub_value;
/// assert_eq!(scrub_value(0.0, 50.0, 0.1, 0.0, 100.0, false, false), 5.0);
/// assert_eq!(scrub_value(0.0, 50.0, 0.1, 0.0, 100.0, true, false), 0.5);
/// assert_eq!(scrub_value(0.0, 50.0, 0.1, 0.0, 100.0, false, true), 50.0);
/// assert_eq!(scrub_value(0.0, 5000.0, 0.1, 0.0, 100.0, false, false), 100.0);
/// ```
pub fn scrub_value(
    start: f32,
    distance: f32,
    step: f32,
    min: f32,
    max: f32,
    fine: bool,
    coarse: bool,
) -> f32 {
    let rate = step
        * if fine {
            0.1
        } else if coarse {
            10.0
        } else {
            1.0
        };
    let raw = start + distance * rate;
    if !raw.is_finite() {
        return start;
    }
    let scale = 10f32.powi(number_decimals(rate).max(number_decimals(step)) as i32);
    hold((raw * scale).round() / scale, min, max)
}

/// A number moved by `steps` of `step` (negative goes down), rounded to the digits of the step and
/// held to `min..=max`. A key, the D-pad or an arrow press is one step; Shift is ten.
///
/// ```
/// use bevy_gooey::step_value;
/// assert_eq!(step_value(0.3, 1.0, 0.1, 0.0, 1.0), 0.4);
/// assert_eq!(step_value(0.95, 10.0, 0.1, 0.0, 1.0), 1.0);
/// ```
pub fn step_value(value: f32, steps: f32, step: f32, min: f32, max: f32) -> f32 {
    let scale = 10f32.powi(number_decimals(step) as i32);
    hold(((value + steps * step) * scale).round() / scale, min, max)
}

/// `value` held to `min..=max`, whichever order the two came in, and never a panic on a NaN.
pub(crate) fn hold(value: f32, min: f32, max: f32) -> f32 {
    value.clamp(min.min(max), max.max(min))
}

/// Why a [`crate::color_field`] would not take what the player typed; it reads as words
/// ([`std::fmt::Display`]) and is sent with [`crate::ColorRefused`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HexError {
    /// Nothing was typed.
    Empty,
    /// Not 3, 4, 6 or 8 digits.
    Length,
    /// A character that is not a hex digit.
    NotHex,
}

impl std::fmt::Display for HexError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Empty => "type a colour, like #ff8800",
            Self::Length => "a colour is 3, 4, 6 or 8 hex digits",
            Self::NotHex => "that is not a hex colour",
        })
    }
}

/// The colour a player typed as hex: `#RGB`, `#RGBA`, `#RRGGBB` or `#RRGGBBAA`, the `#` optional,
/// either case, spaces round it ignored. Returns sRGB red, green, blue and alpha, each a byte over
/// 255 (`#f80` is `#ff8800`, as in CSS and as Blender takes shorthand).
///
/// ```
/// use bevy_gooey::{HexError, parse_hex};
/// assert_eq!(parse_hex("#ff8800"), Ok([1.0, 136.0 / 255.0, 0.0, 1.0]));
/// assert_eq!(parse_hex("f80"), parse_hex("#FF8800"));
/// assert_eq!(parse_hex("#f80"), parse_hex("#ff8800ff"));
/// assert_eq!(parse_hex("#ff880"), Err(HexError::Length));
/// assert_eq!(parse_hex("orange"), Err(HexError::NotHex));
/// assert_eq!(parse_hex(" "), Err(HexError::Empty));
/// ```
pub fn parse_hex(text: &str) -> Result<[f32; 4], HexError> {
    let text = text.trim();
    let digits = text.strip_prefix('#').unwrap_or(text).trim();
    if digits.is_empty() {
        return Err(HexError::Empty);
    }
    if !digits.is_ascii() {
        return Err(HexError::NotHex);
    }
    if !matches!(digits.len(), 3 | 4 | 6 | 8) {
        return if digits.bytes().all(|b| b.is_ascii_hexdigit()) {
            Err(HexError::Length)
        } else {
            Err(HexError::NotHex)
        };
    }
    let mut bytes = [255u8; 4];
    let short = digits.len() <= 4;
    for (i, slot) in bytes
        .iter_mut()
        .take(digits.len() / if short { 1 } else { 2 })
        .enumerate()
    {
        let part = if short {
            &digits[i..=i]
        } else {
            &digits[2 * i..2 * i + 2]
        };
        let n = u8::from_str_radix(part, 16).map_err(|_| HexError::NotHex)?;
        *slot = if short { n * 17 } else { n };
    }
    Ok(bytes.map(|b| f32::from(b) / 255.0))
}

/// A colour as the hex a field shows: `#RRGGBB` in capitals, with `AA` after it only when the alpha
/// is not full, so the text says no more than the colour. `rgba` is sRGB, each channel 0 to 1.
///
/// ```
/// assert_eq!(bevy_gooey::hex_text([1.0, 136.0 / 255.0, 0.0, 1.0]), "#FF8800");
/// assert_eq!(bevy_gooey::hex_text([0.0, 0.0, 0.0, 0.5]), "#00000080");
/// ```
pub fn hex_text(rgba: [f32; 4]) -> String {
    let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8;
    let [r, g, b, a] = rgba.map(byte);
    if a == 255 {
        format!("#{r:02X}{g:02X}{b:02X}")
    } else {
        format!("#{r:02X}{g:02X}{b:02X}{a:02X}")
    }
}

/// A hue in degrees (any number: 360 is 0), a saturation and a value (each held to 0 to 1) as sRGB
/// red, green and blue.
///
/// ```
/// assert_eq!(bevy_gooey::hsv_to_rgb(0.0, 1.0, 1.0), [1.0, 0.0, 0.0]);
/// assert_eq!(bevy_gooey::hsv_to_rgb(360.0, 1.0, 1.0), [1.0, 0.0, 0.0]);
/// assert_eq!(bevy_gooey::hsv_to_rgb(120.0, 0.0, 0.5), [0.5, 0.5, 0.5]);
/// ```
pub fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> [f32; 3] {
    let h = if hue.is_finite() {
        hue.rem_euclid(360.0) / 60.0
    } else {
        0.0
    };
    let s = saturation.clamp(0.0, 1.0);
    let v = value.clamp(0.0, 1.0);
    let chroma = v * s;
    let x = chroma * (1.0 - (h % 2.0 - 1.0).abs());
    let m = v - chroma;
    let (r, g, b) = match h as u8 {
        0 => (chroma, x, 0.0),
        1 => (x, chroma, 0.0),
        2 => (0.0, chroma, x),
        3 => (0.0, x, chroma),
        4 => (x, 0.0, chroma),
        _ => (chroma, 0.0, x),
    };
    [r + m, g + m, b + m]
}

/// The hue (degrees, 0 up to 360), saturation and value of an sRGB colour. A grey has no hue and a
/// black has no saturation either, so those come back as they were in `previous`
/// (`[hue, saturation, value]`): dragging a picker to black and back, or typing a grey, does not
/// forget the hue the player was on.
///
/// ```
/// use bevy_gooey::rgb_to_hsv;
/// assert_eq!(rgb_to_hsv([0.0, 1.0, 0.0], [0.0; 3]), [120.0, 1.0, 1.0]);
/// // A grey keeps the hue it was given.
/// assert_eq!(rgb_to_hsv([0.5, 0.5, 0.5], [200.0, 0.4, 0.9]), [200.0, 0.0, 0.5]);
/// // Black keeps the hue and the saturation.
/// assert_eq!(rgb_to_hsv([0.0, 0.0, 0.0], [200.0, 0.4, 0.9]), [200.0, 0.4, 0.0]);
/// ```
pub fn rgb_to_hsv(rgb: [f32; 3], previous: [f32; 3]) -> [f32; 3] {
    const EPSILON: f32 = 1e-6;
    let [r, g, b] = rgb;
    let max = r.max(g).max(b);
    let delta = max - r.min(g).min(b);
    if max <= EPSILON {
        return [previous[0], previous[1], 0.0];
    }
    if delta <= EPSILON {
        return [previous[0], 0.0, max];
    }
    let hue = if max == r {
        ((g - b) / delta).rem_euclid(6.0)
    } else if max == g {
        (b - r) / delta + 2.0
    } else {
        (r - g) / delta + 4.0
    };
    [hue * 60.0, delta / max, max]
}

/// The saturation and value a pointer at `offset` (px from the area's top-left corner) means in a
/// colour area whose frame leaves the inside `inner_size` at `inner_origin`: saturation grows to
/// the right, value upwards, both held to 0 to 1 so a drag that leaves the area holds at its edge.
/// A frame with no inside reads as the middle.
///
/// ```
/// use bevy_gooey::area_values;
/// assert_eq!(area_values([100.0, 0.0], [0.0, 0.0], [100.0, 50.0]), [1.0, 1.0]);
/// assert_eq!(area_values([0.0, 50.0], [0.0, 0.0], [100.0, 50.0]), [0.0, 0.0]);
/// assert_eq!(area_values([-30.0, 25.0], [0.0, 0.0], [100.0, 50.0]), [0.0, 0.5]);
/// ```
pub fn area_values(offset: [f32; 2], inner_origin: [f32; 2], inner_size: [f32; 2]) -> [f32; 2] {
    let along = |p: f32, origin: f32, size: f32| {
        if size > 0.0 && p.is_finite() {
            ((p - origin) / size).clamp(0.0, 1.0)
        } else {
            0.5
        }
    };
    [
        along(offset[0], inner_origin[0], inner_size[0]),
        1.0 - along(offset[1], inner_origin[1], inner_size[1]),
    ]
}

/// One turn of a [`spinner`](crate::spinner), in seconds.
pub const SPINNER_PERIOD_SECS: f32 = 0.9;

/// How far a spinner has turned `elapsed` seconds into real time, radians in `0..TAU`. A pure
/// function of the clock, so a stalled frame does not slow it and a pause does not stop it.
///
/// ```
/// let quarter = bevy_gooey::model::SPINNER_PERIOD_SECS / 4.0;
/// assert!((bevy_gooey::model::spinner_angle(quarter) - std::f32::consts::FRAC_PI_2).abs() < 1e-5);
/// ```
pub fn spinner_angle(elapsed: f32) -> f32 {
    if !elapsed.is_finite() {
        return 0.0;
    }
    let turns = (elapsed / SPINNER_PERIOD_SECS).rem_euclid(1.0);
    turns * std::f32::consts::TAU
}

/// From this many seconds left a cooldown is read in whole seconds; under it, in tenths.
pub const COOLDOWN_WHOLE_SECONDS_FROM: f32 = 3.0;

/// Float noise (0.3 * 10 is 3.0000001) must not push a round number up a step.
const COOLDOWN_ROUND_SLACK: f32 = 1e-3;

/// The words on a cooldown's chip for `remaining` seconds: `m:ss` from a minute, whole seconds
/// rounded up from [`COOLDOWN_WHOLE_SECONDS_FROM`], tenths rounded up below it, so a second that
/// is not over does not read as the next one down and the last tenth is "0.1", never "0.0".
/// Empty at zero, below it, or when not finite (a ready widget draws no chip).
///
/// ```
/// use bevy_gooey::model::cooldown_text;
/// assert_eq!(cooldown_text(65.2), "1:06");
/// assert_eq!(cooldown_text(12.0), "12");
/// assert_eq!(cooldown_text(5.01), "6");
/// assert_eq!(cooldown_text(2.31), "2.4");
/// assert_eq!(cooldown_text(0.0), "");
/// ```
pub fn cooldown_text(remaining: f32) -> String {
    if !remaining.is_finite() || remaining <= 0.0 {
        return String::new();
    }
    if remaining < COOLDOWN_WHOLE_SECONDS_FROM {
        let tenths = ((remaining * 10.0 - COOLDOWN_ROUND_SLACK).ceil() as u32).max(1);
        return format!("{}.{}", tenths / 10, tenths % 10);
    }
    let seconds = (remaining - COOLDOWN_ROUND_SLACK).ceil() as u32;
    if seconds >= 60 {
        format!("{}:{:02}", seconds / 60, seconds % 60)
    } else {
        seconds.to_string()
    }
}

/// The same time as a screen reader should say it: "1 second remaining", "6 seconds remaining",
/// "1 minute 5 seconds remaining". Empty when `remaining` is zero, below it or not finite.
///
/// ```
/// use bevy_gooey::model::cooldown_words;
/// assert_eq!(cooldown_words(5.01), "6 seconds remaining");
/// assert_eq!(cooldown_words(0.4), "1 second remaining");
/// assert_eq!(cooldown_words(65.0), "1 minute 5 seconds remaining");
/// ```
pub fn cooldown_words(remaining: f32) -> String {
    if !remaining.is_finite() || remaining <= 0.0 {
        return String::new();
    }
    let seconds = ((remaining - COOLDOWN_ROUND_SLACK).ceil() as u32).max(1);
    let (minutes, rest) = (seconds / 60, seconds % 60);
    let plural = |n: u32, unit: &str| format!("{n} {unit}{}", if n == 1 { "" } else { "s" });
    match (minutes, rest) {
        (0, s) => format!("{} remaining", plural(s, "second")),
        (m, 0) => format!("{} remaining", plural(m, "minute")),
        (m, s) => format!("{} {} remaining", plural(m, "minute"), plural(s, "second")),
    }
}

/// The angle, clockwise from twelve o'clock, that a cooldown's clear wedge has opened to: `0` the
/// moment it starts (all dimmed) to `TAU` when `remaining` reaches zero. A duration that is not
/// positive or not finite counts as fully dimmed while any time remains, and `remaining` outside
/// `0..=duration` is held to the nearest end.
///
/// ```
/// use bevy_gooey::model::cooldown_sweep;
/// assert!((cooldown_sweep(6.0, 8.0) - std::f32::consts::FRAC_PI_2).abs() < 1e-5);
/// assert_eq!(cooldown_sweep(8.0, 8.0), 0.0);
/// ```
pub fn cooldown_sweep(remaining: f32, duration: f32) -> f32 {
    if !remaining.is_finite() || remaining <= 0.0 {
        return std::f32::consts::TAU;
    }
    if !duration.is_finite() || duration <= 0.0 {
        return 0.0;
    }
    (1.0 - (remaining / duration).clamp(0.0, 1.0)) * std::f32::consts::TAU
}

/// How many times faster a hold's bar unwinds than it filled: committing is deliberate, backing out
/// is free. A design default (`docs/research/hold-button.md`).
pub const HOLD_UNWIND_RATE: f32 = 4.0;
/// The most a hold's duration is stretched by the player's setting, a factor on the game's seconds.
pub const HOLD_SCALE_MAX: f32 = 4.0;

/// The seconds a hold takes: the game's `seconds` times the player's `scale` (held to `0.0` to
/// [`HOLD_SCALE_MAX`], NaN read as `1.0`). Zero, or a `seconds` that is not a positive finite
/// number, is a tap: the hold is replaced by a press that confirms when it is let go.
///
/// ```
/// use bevy_gooey::model::hold_seconds;
/// assert_eq!(hold_seconds(1.2, 1.0), 1.2);
/// assert_eq!(hold_seconds(1.2, 0.5), 0.6);
/// assert_eq!(hold_seconds(1.2, 0.0), 0.0);
/// assert_eq!(hold_seconds(f32::NAN, 1.0), 0.0);
/// ```
pub fn hold_seconds(seconds: f32, scale: f32) -> f32 {
    if !seconds.is_finite() || seconds <= 0.0 {
        return 0.0;
    }
    let scale = if scale.is_nan() {
        1.0
    } else {
        scale.clamp(0.0, HOLD_SCALE_MAX)
    };
    seconds * scale
}

/// A hold's progress, `0.0` to `1.0`, after `dt` seconds. Held, it rises by `dt / seconds` (a tap,
/// `seconds` of zero, is full at once); let go, it unwinds [`HOLD_UNWIND_RATE`] times as fast as it
/// rose, never taking more than half a second to empty, or at once when `instant` (the player's
/// reduced motion).
///
/// ```
/// use bevy_gooey::model::hold_step;
/// assert_eq!(hold_step(0.0, 0.3, 1.2, true, false), 0.25);
/// assert_eq!(hold_step(0.5, 0.1, 1.2, true, false), 0.5 + 0.1 / 1.2);
/// assert_eq!(hold_step(0.5, 10.0, 1.2, false, false), 0.0);
/// assert_eq!(hold_step(0.5, 0.01, 1.2, false, true), 0.0);
/// assert_eq!(hold_step(0.0, 0.0, 0.0, true, false), 1.0);
/// ```
pub fn hold_step(progress: f32, dt: f32, seconds: f32, held: bool, instant: bool) -> f32 {
    let progress = if progress.is_finite() {
        progress.clamp(0.0, 1.0)
    } else {
        0.0
    };
    let dt = if dt.is_finite() { dt.max(0.0) } else { 0.0 };
    if held {
        if seconds <= 0.0 {
            return 1.0;
        }
        return (progress + dt / seconds).min(1.0);
    }
    if instant {
        return 0.0;
    }
    let unwind = seconds.clamp(0.4, 2.0) / HOLD_UNWIND_RATE;
    (progress - dt / unwind).max(0.0)
}

/// How far a dialog's card rises into place, logical px.
pub const DIALOG_SLIDE_PX: f32 = 12.0;
/// How long a dialog's card takes to rise into place, seconds.
pub const DIALOG_SLIDE_SECONDS: f32 = 0.18;
/// How far a popover (a menu, a select list, a colour picker) slides from its anchor, logical px.
pub const POPOVER_SLIDE_PX: f32 = 6.0;
/// How long a popover takes to slide into place, seconds.
pub const POPOVER_SLIDE_SECONDS: f32 = 0.12;

/// How far a motion that takes `seconds` has come `age` seconds in, from 0 to 1, on a cubic
/// ease-out (`1 − (1 − t)³`): it starts quickly and settles, which NN/g gives as the easing of
/// something that arrives. An `age` below nothing is 0, one past `seconds` is 1, and a length that is
/// not positive (or not finite) is over already.
///
/// ```
/// use bevy_gooey::model::ease_out;
/// assert_eq!(ease_out(0.0, 0.2), 0.0);
/// assert_eq!(ease_out(0.2, 0.2), 1.0);
/// assert!(ease_out(0.1, 0.2) > 0.8);
/// assert_eq!(ease_out(0.1, 0.0), 1.0);
/// ```
pub fn ease_out(age: f32, seconds: f32) -> f32 {
    if seconds.is_nan() || seconds <= 0.0 || seconds.is_infinite() || age.is_nan() {
        return 1.0;
    }
    let left = 1.0 - (age / seconds).clamp(0.0, 1.0);
    1.0 - left * left * left
}

/// How long is left, in words: "about 20 s left", "about 3 min left", "about 1 h 5 min left". Under
/// ten seconds it counts the seconds, to a minute it rounds to five, to an hour to the minute and
/// past one to five minutes, because an estimate never has the precision it prints. A time that is
/// not finite or below zero is empty; under a second it says so.
///
/// ```
/// assert_eq!(bevy_gooey::model::eta_words(20.0), "about 20 s left");
/// assert_eq!(bevy_gooey::model::eta_words(3900.0), "about 1 h 5 min left");
/// ```
pub fn eta_words(seconds: f32) -> String {
    if !seconds.is_finite() || seconds < 0.0 {
        return String::new();
    }
    if seconds < 1.0 {
        return "less than a second left".to_string();
    }
    let whole = seconds.round() as u64;
    if whole < 10 {
        return format!("about {whole} s left");
    }
    if whole < 58 {
        return format!("about {} s left", (whole + 2) / 5 * 5);
    }
    if whole < 3600 {
        let minutes = (whole + 30) / 60;
        if minutes < 60 {
            return format!("about {minutes} min left");
        }
    }
    // From an hour: whole hours and the minutes to the nearest five.
    let total = (whole + 150) / 300 * 5;
    let (hours, minutes) = (total / 60, total % 60);
    if minutes == 0 {
        format!("about {hours} h left")
    } else {
        format!("about {hours} h {minutes} min left")
    }
}

/// The line under a progress bar: "3 of 7: Measuring meshes, about 20 s left". Either part may be
/// missing, and with neither the line is empty.
///
/// ```
/// use bevy_gooey::model::progress_text;
/// assert_eq!(
///     progress_text(Some((3, 7, "Measuring meshes")), Some(20.0)),
///     "3 of 7: Measuring meshes, about 20 s left"
/// );
/// assert_eq!(progress_text(None, Some(4.0)), "about 4 s left");
/// ```
pub fn progress_text(step: Option<(u32, u32, &str)>, eta_seconds: Option<f32>) -> String {
    let step = step.map(|(at, of, name)| {
        if name.is_empty() {
            format!("{at} of {of}")
        } else {
            format!("{at} of {of}: {name}")
        }
    });
    let left = eta_seconds.map(eta_words).filter(|words| !words.is_empty());
    match (step, left) {
        (Some(step), Some(left)) => format!("{step}, {left}"),
        (Some(only), None) | (None, Some(only)) => only,
        (None, None) => String::new(),
    }
}

/// Which items of a bar stay when its room is short: `true` for each of `widths` that is shown.
///
/// Everything shows when it fits `room` (items `gap` apart). Otherwise `reserve` (the room a "More"
/// button takes, its gap included, `0.0` for a bar with none) is kept free and items hide **lowest
/// rank first, the later of equal ranks first**, until the rest fit. Hidden items take no room and
/// no gap; non-finite or negative widths count as nothing.
///
/// ```
/// use bevy_gooey::model::bar_fit;
/// // Three 100 px items, 8 px apart: 316 px. In 300 px the last one hides.
/// assert_eq!(bar_fit(&[100.0; 3], &[0; 3], 8.0, 300.0, 0.0), [true, true, false]);
/// // The lowest rank goes first, wherever it stands.
/// assert_eq!(bar_fit(&[100.0; 3], &[5, 1, 5], 8.0, 300.0, 0.0), [true, false, true]);
/// ```
pub fn bar_fit(widths: &[f32], ranks: &[u32], gap: f32, room: f32, reserve: f32) -> Vec<bool> {
    let width = |w: f32| if w.is_finite() { w.max(0.0) } else { 0.0 };
    let needed = |shown: &[bool]| {
        let (sum, count) = widths
            .iter()
            .zip(shown)
            .filter(|(_, shown)| **shown)
            .fold((0.0, 0usize), |(sum, count), (w, _)| {
                (sum + width(*w), count + 1)
            });
        sum + gap * count.saturating_sub(1) as f32
    };
    let mut shown = vec![true; widths.len()];
    if needed(&shown) <= room {
        return shown;
    }
    let room = room - reserve;
    while needed(&shown) > room {
        let next = (0..widths.len())
            .filter(|&i| shown[i])
            .min_by_key(|&i| (ranks.get(i).copied().unwrap_or(0), std::cmp::Reverse(i)));
        match next {
            Some(i) => shown[i] = false,
            None => break,
        }
    }
    shown
}

/// A direction on the screen, `y` growing down, in which a carried payload's mark moves.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Toward {
    /// Towards the top of the screen.
    Up,
    /// Towards the bottom.
    Down,
    /// Towards the left.
    Left,
    /// Towards the right.
    Right,
}

/// The least distance along a direction, in logical pixels, for a target to lie "that way".
const TOWARD_EPSILON: f32 = 0.5;

/// Which of `rects` (`[x0, y0, x1, y1]`, `y` down) a payload carried by key moves to from `from`
/// when the player presses `toward`: the nearest whose centre lies strictly that way. The score is
/// the distance along the direction plus twice the distance across it, the usual weight of spatial
/// navigation, so a target straight ahead beats a nearer one far to the side; the lowest wins and a
/// tie goes to the lower index. `None` when nothing lies that way (the mark stays where it is).
///
/// ```
/// use bevy_gooey::{Toward, target_toward};
/// let from = [0., 0., 10., 10.];
/// let rects = [[20., 0., 30., 10.], [20., 40., 30., 50.], [-30., 0., -20., 10.]];
/// assert_eq!(target_toward(from, &rects, Toward::Right), Some(0));
/// assert_eq!(target_toward(from, &rects, Toward::Left), Some(2));
/// assert_eq!(target_toward(from, &rects, Toward::Up), None);
/// ```
pub fn target_toward(from: [f32; 4], rects: &[[f32; 4]], toward: Toward) -> Option<usize> {
    let centre = |r: &[f32; 4]| [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0];
    let origin = centre(&from);
    let mut best: Option<(usize, f32)> = None;
    for (index, rect) in rects.iter().enumerate() {
        let at = centre(rect);
        let (dx, dy) = (at[0] - origin[0], at[1] - origin[1]);
        let (along, across) = match toward {
            Toward::Right => (dx, dy.abs()),
            Toward::Left => (-dx, dy.abs()),
            Toward::Down => (dy, dx.abs()),
            Toward::Up => (-dy, dx.abs()),
        };
        if along.is_nan() || along <= TOWARD_EPSILON || !across.is_finite() {
            continue;
        }
        let score = along + 2.0 * across;
        if best.is_none_or(|(_, lowest)| score < lowest) {
            best = Some((index, score));
        }
    }
    best.map(|(index, _)| index)
}

/// The next (or previous) of `rects` in reading order (top to bottom by the top edge, left to right
/// by the left edge, ties by index), wrapping at the ends: the step of a payload carried by key
/// that is not a direction (PageDown, a bumper). With no `current` the first is next and the last
/// is previous. `None` only when there are no rects.
///
/// ```
/// use bevy_gooey::target_step;
/// let rects = [[0., 50., 10., 60.], [0., 0., 10., 10.], [20., 0., 30., 10.]];
/// assert_eq!(target_step(&rects, None, true), Some(1));
/// assert_eq!(target_step(&rects, Some(1), true), Some(2));
/// assert_eq!(target_step(&rects, Some(0), true), Some(1));
/// ```
pub fn target_step(rects: &[[f32; 4]], current: Option<usize>, forward: bool) -> Option<usize> {
    let mut order: Vec<usize> = (0..rects.len()).collect();
    order.sort_by(|&a, &b| {
        rects[a][1]
            .total_cmp(&rects[b][1])
            .then(rects[a][0].total_cmp(&rects[b][0]))
            .then(a.cmp(&b))
    });
    let last = order.len().checked_sub(1)?;
    let at = current.and_then(|c| order.iter().position(|&i| i == c));
    let next = match (at, forward) {
        (None, true) => 0,
        (None, false) => last,
        (Some(at), true) => (at + 1) % order.len(),
        (Some(at), false) => (at + last) % order.len(),
    };
    Some(order[next])
}

/// Whether the box `[min, max]` lies wholly outside the rectangle `[view_min, view_max]`: no
/// overlap at all, so nothing of it would be drawn. Touching edges count as inside.
///
/// ```
/// use bevy_gooey::box_outside;
/// assert!(box_outside((1300.0, 10.0), (1340.0, 40.0), (0.0, 0.0), (1280.0, 720.0)));
/// assert!(!box_outside((1270.0, 10.0), (1310.0, 40.0), (0.0, 0.0), (1280.0, 720.0)));
/// ```
pub fn box_outside(
    min: (f32, f32),
    max: (f32, f32),
    view_min: (f32, f32),
    view_max: (f32, f32),
) -> bool {
    max.0 < view_min.0 || min.0 > view_max.0 || max.1 < view_min.1 || min.1 > view_max.1
}

/// Where a point outside the rectangle `[min, max]` is pinned to its edge: on the ray from
/// `centre` toward `point`, so the pinned position still says which way the point lies. A point
/// inside is returned as it is. The result is never outside the rectangle (an empty one, `min`
/// past `max`, gives `centre`).
///
/// ```
/// use bevy_gooey::pin_to_edge;
/// // Far to the right of a 1280 x 720 viewport, level with its middle: on the right edge.
/// assert_eq!(pin_to_edge((5000.0, 360.0), (640.0, 360.0), (64.0, 36.0), (1216.0, 684.0)), (1216.0, 360.0));
/// // Inside: unchanged.
/// assert_eq!(pin_to_edge((100.0, 100.0), (640.0, 360.0), (64.0, 36.0), (1216.0, 684.0)), (100.0, 100.0));
/// ```
pub fn pin_to_edge(
    point: (f32, f32),
    centre: (f32, f32),
    min: (f32, f32),
    max: (f32, f32),
) -> (f32, f32) {
    if min.0 > max.0 || min.1 > max.1 || !point.0.is_finite() || !point.1.is_finite() {
        return centre;
    }
    if point.0 >= min.0 && point.0 <= max.0 && point.1 >= min.1 && point.1 <= max.1 {
        return point;
    }
    let (dx, dy) = (point.0 - centre.0, point.1 - centre.1);
    let reach = |d: f32, from: f32, lo: f32, hi: f32| {
        if d > 0.0 {
            (hi - from) / d
        } else if d < 0.0 {
            (lo - from) / d
        } else {
            f32::INFINITY
        }
    };
    let s = reach(dx, centre.0, min.0, max.0).min(reach(dy, centre.1, min.1, max.1));
    let s = if s.is_finite() { s.max(0.0) } else { 0.0 };
    (
        (centre.0 + dx * s).clamp(min.0, max.0),
        (centre.1 + dy * s).clamp(min.1, max.1),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_stick_points_into_the_wedge_of_the_item_it_faces() {
        for count in 1..=12usize {
            for item in 0..count {
                let (x, y) = radial_place(item, count);
                assert_eq!(radial_pick(x, y, count), Some(item), "{item} of {count}");
                // Short of the wedge's edge on either side still picks it.
                let half = std::f32::consts::TAU / count as f32 * 0.45;
                let angle = item as f32 / count as f32 * std::f32::consts::TAU;
                for off in [-half, half] {
                    let (a, b) = ((angle + off).sin(), (angle + off).cos());
                    assert_eq!(radial_pick(a, b, count), Some(item), "{item} of {count}");
                }
            }
        }
    }

    #[test]
    fn the_edge_between_two_wedges_belongs_to_the_clockwise_one() {
        // Four items: the diagonal up-right is the edge of 0 and 1.
        assert_eq!(radial_pick(1.0, 1.0, 4), Some(1));
        assert_eq!(radial_pick(1.0, -1.0, 4), Some(2));
        assert_eq!(radial_pick(-1.0, -1.0, 4), Some(3));
        assert_eq!(radial_pick(-1.0, 1.0, 4), Some(0));
        // A length is no part of the direction.
        assert_eq!(radial_pick(0.01, 0.0, 4), Some(1));
        assert_eq!(radial_pick(500.0, 0.0, 4), Some(1));
    }

    #[test]
    fn a_ring_of_nothing_picks_nothing_and_a_blank_direction_picks_the_first() {
        assert_eq!(radial_pick(1.0, 0.0, 0), None);
        assert_eq!(radial_pick(0.0, 0.0, 5), Some(0));
        assert_eq!(radial_pick(f32::NAN, 1.0, 5), Some(0));
        assert_eq!(radial_pick(1.0, 0.0, 1), Some(0));
        assert_eq!(radial_step(0, 0, 1), 0);
    }

    #[test]
    fn a_step_wraps_both_ways_and_a_value_past_the_ring_is_the_last_item() {
        assert_eq!(radial_step(7, 8, 1), 0);
        assert_eq!(radial_step(0, 8, -1), 7);
        assert_eq!(radial_step(2, 8, -19), 7);
        assert_eq!(radial_step(99, 8, 1), 0);
        assert_eq!(radial_step(3, 8, 0), 3);
    }

    #[test]
    fn a_carried_payload_steers_to_the_nearest_target_that_way() {
        let from = [0., 0., 10., 10.];
        // Straight ahead and far beats near and far to the side.
        let rects = [
            [30., 0., 40., 10.],
            [12., 30., 22., 40.],
            [-30., 0., -20., 10.],
        ];
        assert_eq!(target_toward(from, &rects, Toward::Right), Some(0));
        assert_eq!(target_toward(from, &rects, Toward::Left), Some(2));
        assert_eq!(target_toward(from, &rects, Toward::Down), Some(1));
        assert_eq!(target_toward(from, &rects, Toward::Up), None);
        // A target on the same centre (the one the mark is on) is no step, and nothing is None.
        assert_eq!(target_toward(from, &[from], Toward::Right), None);
        assert_eq!(target_toward(from, &[], Toward::Right), None);
    }

    #[test]
    fn stepping_through_targets_goes_in_reading_order_and_wraps() {
        let rects = [[0., 50., 10., 60.], [0., 0., 10., 10.], [20., 0., 30., 10.]];
        assert_eq!(target_step(&rects, Some(2), true), Some(0));
        assert_eq!(target_step(&rects, Some(0), true), Some(1));
        assert_eq!(target_step(&rects, Some(1), false), Some(0));
        assert_eq!(target_step(&rects, None, false), Some(0));
        assert_eq!(target_step(&rects, Some(7), true), Some(1));
        assert_eq!(target_step(&[], None, true), None);
    }

    #[test]
    fn white_on_black_is_21_to_1() {
        assert!((contrast_ratio([1., 1., 1.], [0., 0., 0.]) - 21.0).abs() < 0.01);
        let x = [0.3, 0.6, 0.2];
        assert_eq!(contrast_ratio(x, x), 1.0);
    }

    #[test]
    fn the_meter_fraction_is_clamped_and_never_nan() {
        assert_eq!(meter_fraction(25.0, 100.0), 0.25);
        assert_eq!(meter_fraction(150.0, 100.0), 1.0);
        assert_eq!(meter_fraction(-5.0, 100.0), 0.0);
        assert_eq!(meter_fraction(5.0, 0.0), 0.0);
        assert_eq!(meter_fraction(f32::NAN, 100.0), 0.0);
        assert_eq!(meter_fraction(5.0, f32::INFINITY), 0.0);
    }

    fn settled(at: f32) -> MeterShown {
        MeterShown {
            fill: at,
            trail: at,
            hold: 0.0,
        }
    }

    #[test]
    fn a_loss_is_exact_at_once_and_leaves_a_trail_that_holds_then_drains_to_the_fill() {
        let mut s = meter_motion(settled(1.0), 0.4, 0.016, 1.0);
        assert_eq!((s.fill, s.trail), (0.4, 1.0));
        // Held: 0.4 s later the trail has not moved.
        for _ in 0..25 {
            s = meter_motion(s, 0.4, 0.016, 1.0);
        }
        assert_eq!(s.trail, 1.0);
        // Then it only falls, never below the fill, and ends on it.
        let mut last = s.trail;
        let mut seconds = 0.0;
        while s.trail > s.fill {
            s = meter_motion(s, 0.4, 0.016, 1.0);
            assert!(s.trail <= last && s.trail >= s.fill, "{s:?}");
            last = s.trail;
            seconds += 0.016;
            assert!(seconds < 2.0, "never drained: {s:?}");
        }
        // 0.6 of the bar at 1.5 a second is 0.4 s, plus the hold's remainder.
        assert!(seconds < 0.6, "{seconds}");
        assert_eq!(s, settled(0.4));
    }

    #[test]
    fn a_second_loss_in_the_hold_does_not_restart_it() {
        let mut s = meter_motion(settled(1.0), 0.8, 0.016, 1.0);
        for _ in 0..20 {
            s = meter_motion(s, 0.8, 0.016, 1.0);
        }
        let hold_before = s.hold;
        let s = meter_motion(s, 0.5, 0.016, 1.0);
        assert_eq!(s.fill, 0.5);
        assert_eq!(s.trail, 1.0, "the trail is still the first loss's start");
        assert!((s.hold - (hold_before - 0.016)).abs() < 1e-5, "{s:?}");
    }

    #[test]
    fn a_gain_eases_up_never_overshoots_and_leaves_no_trail() {
        let mut s = settled(0.2);
        let mut last = s.fill;
        let mut first = true;
        let mut seconds = 0.0;
        while s.fill < 0.9 {
            s = meter_motion(s, 0.9, 0.016, 1.0);
            if first {
                assert!(s.fill > 0.2 && s.fill < 0.9, "partway: {s:?}");
                first = false;
            }
            assert!(s.fill > last && s.fill <= 0.9, "{s:?}");
            assert_eq!(s.trail, s.fill, "a gain draws no trail");
            last = s.fill;
            seconds += 0.016;
            assert!(seconds < 0.6, "too slow: {s:?}");
        }
        assert_eq!(s, settled(0.9));
    }

    #[test]
    fn a_gain_during_a_trail_lifts_the_trail_with_the_fill() {
        let mut s = meter_motion(settled(0.5), 0.2, 0.016, 1.0);
        assert_eq!((s.fill, s.trail), (0.2, 0.5));
        for _ in 0..200 {
            s = meter_motion(s, 0.9, 0.016, 1.0);
            assert!(s.trail >= s.fill);
        }
        assert_eq!(s, settled(0.9));
    }

    #[test]
    fn the_scale_stretches_every_length_and_zero_is_the_target_at_once() {
        // Scale 2: after 0.64 s (the hold is 0.9 s long) the trail has not moved.
        let mut s = meter_motion(settled(1.0), 0.0, 0.0, 2.0);
        for _ in 0..40 {
            s = meter_motion(s, 0.0, 0.016, 2.0);
        }
        assert_eq!(s.trail, 1.0);
        // Off, a bad scale and a bad clock are the target and no trail.
        for scale in [0.0, -1.0, f32::NAN, f32::INFINITY] {
            assert_eq!(meter_motion(settled(1.0), 0.3, 0.016, scale), settled(0.3));
            assert_eq!(meter_motion(settled(0.1), 0.7, 0.016, scale), settled(0.7));
        }
        // A bad dt is a zero step, and a bad target is empty.
        let s = meter_motion(settled(0.5), 0.9, f32::NAN, 1.0);
        assert_eq!(s.fill, 0.5);
        assert_eq!(
            meter_motion(settled(0.5), f32::NAN, 0.016, 0.0),
            settled(0.0)
        );
    }

    #[test]
    fn the_shorter_side_over_the_reference_sets_the_scale() {
        assert_eq!(window_ui_scale(1280.0, 720.0, 720.0, 1.0), Some(1.0));
        assert_eq!(window_ui_scale(1920.0, 1080.0, 720.0, 1.0), Some(1.5));
        assert_eq!(window_ui_scale(3840.0, 2160.0, 720.0, 1.0), Some(3.0));
        // Portrait and ultrawide: the shorter side decides.
        assert_eq!(window_ui_scale(720.0, 1280.0, 720.0, 1.0), Some(1.0));
        assert_eq!(window_ui_scale(3440.0, 1440.0, 720.0, 1.0), Some(2.0));
        // The player's size multiplies the window's.
        assert_eq!(window_ui_scale(1920.0, 1080.0, 720.0, 1.25), Some(1.875));
        // A window smaller than the reference draws a smaller interface, in proportion.
        assert_eq!(window_ui_scale(640.0, 360.0, 720.0, 1.0), Some(0.5));
    }

    #[test]
    fn no_window_or_an_invalid_setting_gives_no_scale() {
        assert_eq!(window_ui_scale(0.0, 0.0, 720.0, 1.0), None);
        assert_eq!(window_ui_scale(1280.0, 0.0, 720.0, 1.0), None);
        assert_eq!(window_ui_scale(1280.0, 720.0, 0.0, 1.0), None);
        assert_eq!(window_ui_scale(1280.0, 720.0, -720.0, -1.0), None);
        assert_eq!(window_ui_scale(1280.0, 720.0, 720.0, 0.0), None);
        assert_eq!(window_ui_scale(1280.0, 720.0, f32::NAN, 1.0), None);
        assert_eq!(window_ui_scale(1280.0, 720.0, 720.0, f32::INFINITY), None);
    }

    #[test]
    fn a_line_rounds_down_to_whole_device_pixels_and_never_below_one() {
        // The default 3 px border at the window scales the crate draws.
        let device = |length: f32, scale: f32| snap_line_width(length, scale) * scale;
        assert_eq!(device(3.0, 1.0), 3.0);
        assert_eq!(device(3.0, 800.0 / 720.0), 3.0);
        assert_eq!(device(3.0, 1.25), 3.0);
        assert_eq!(device(3.0, 1.5), 4.0);
        assert_eq!(device(3.0, 2.0), 6.0);
        assert_eq!(device(3.0, 3.0), 9.0);
        // Under one device pixel: one. Zero: none.
        assert_eq!(device(0.25, 1.0), 1.0);
        assert_eq!(device(1.0, 0.5), 1.0);
        assert_eq!(snap_line_width(0.0, 1.5), 0.0);
        // Already whole, within float noise: kept, not rounded a pixel down.
        assert_eq!(device(4.0 / 1.5, 1.5), 4.0);
    }

    #[test]
    fn a_snapped_line_is_never_a_hair_short_of_its_pixel() {
        // An ulp short of `n` is what Bevy's rounding turns into `n − 1` on a half-pixel edge.
        for height in 360..=4320 {
            let scale = height as f32 / 720.0;
            for length in [1.0, 2.0, 3.0, 5.0, 8.0] {
                let drawn = snap_line_width(length, scale) * scale;
                let whole = (length * scale + 1.0e-3).floor().max(1.0);
                assert!(
                    drawn >= whole && drawn - whole < 1.0e-5,
                    "{length} px at {height} px tall draws {drawn}"
                );
            }
        }
        // Exact at the common window heights.
        for height in [720, 768, 800, 900, 1050, 1080, 1200, 1440, 1600, 2160] {
            let scale = height as f32 / 720.0;
            let drawn = snap_line_width(3.0, scale) * scale;
            assert_eq!(
                drawn,
                drawn.floor(),
                "3 px at {height} px tall draws {drawn}"
            );
        }
    }

    #[test]
    fn an_unusable_length_or_scale_is_left_alone() {
        assert_eq!(snap_line_width(-3.0, 1.5), -3.0);
        assert!(snap_line_width(f32::NAN, 1.5).is_nan());
        assert_eq!(snap_line_width(3.0, 0.0), 3.0);
        assert_eq!(snap_line_width(3.0, f32::INFINITY), 3.0);
    }

    #[test]
    fn a_sliders_fraction_is_clamped_and_never_nan() {
        assert_eq!(slider_fraction(25.0, 0.0, 100.0), 0.25);
        assert_eq!(slider_fraction(1.25, 0.5, 2.0), 0.5);
        assert_eq!(slider_fraction(-3.0, 0.0, 1.0), 0.0);
        assert_eq!(slider_fraction(9.0, 0.0, 1.0), 1.0);
        // No range to be along: the start.
        assert_eq!(slider_fraction(5.0, 5.0, 5.0), 0.0);
        assert_eq!(slider_fraction(5.0, 9.0, 1.0), 0.0);
        assert_eq!(slider_fraction(f32::NAN, 0.0, 1.0), 0.0);
        assert_eq!(slider_fraction(0.5, 0.0, f32::INFINITY), 0.0);
    }

    #[test]
    fn a_sliders_text_is_a_percentage_for_zero_to_one_and_the_number_otherwise() {
        assert_eq!(slider_text(0.7, 0.0, 1.0), "70%");
        assert_eq!(slider_text(0.0, 0.0, 1.0), "0%");
        assert_eq!(slider_text(1.0, 0.0, 1.0), "100%");
        // A float that is a hair under 0.7 still reads 70.
        assert_eq!(slider_text(0.1 + 0.6, 0.0, 1.0), "70%");
        assert_eq!(slider_text(40.0, 0.0, 100.0), "40");
        assert_eq!(slider_text(1.25, 0.5, 2.0), "1.25");
        assert_eq!(slider_text(1.5, 0.5, 2.0), "1.5");
        assert_eq!(slider_text(0.333, 0.0, 2.0), "0.33");
        assert_eq!(slider_text(-0.001, -1.0, 1.0), "0");
        assert_eq!(slider_text(-2.5, -5.0, 5.0), "-2.5");
        // Outside the range it reads the end it is clamped to; not finite, 0.
        assert_eq!(slider_text(7.0, 0.0, 1.0), "100%");
        assert_eq!(slider_text(300.0, 0.0, 100.0), "100");
        assert_eq!(slider_text(f32::NAN, 0.0, 100.0), "0");
    }

    #[test]
    fn a_held_direction_repeats_after_the_delay_at_the_same_pace_at_any_frame_rate() {
        // Nothing before the delay, the first repeat at it.
        assert_eq!(repeat_steps(0.0, 0.3, 0.5, 10.0), 0);
        assert_eq!(repeat_steps(0.3, 0.5, 0.5, 10.0), 1);
        // The same total however the time is cut into frames.
        let total = |frame: f32| {
            let (mut held, mut steps) = (0.0_f32, 0);
            while held < 2.0 {
                let next = held + frame;
                steps += repeat_steps(held, next, 0.5, 10.0);
                held = next;
            }
            (steps, held)
        };
        for frame in [1.0 / 144.0, 1.0 / 60.0, 1.0 / 20.0, 0.25, 1.0] {
            let (steps, held) = total(frame);
            let expected = repeat_steps(0.0, held, 0.5, 10.0);
            assert_eq!(steps, expected, "{frame} s frames");
        }
        // A frame that does not advance, or goes back, repeats nothing.
        assert_eq!(repeat_steps(1.0, 1.0, 0.5, 10.0), 0);
        assert_eq!(repeat_steps(1.0, 0.5, 0.5, 10.0), 0);
    }

    #[test]
    fn an_unusable_repeat_setting_repeats_nothing() {
        assert_eq!(repeat_steps(0.0, 5.0, 0.5, 0.0), 0);
        assert_eq!(repeat_steps(0.0, 5.0, 0.5, -10.0), 0);
        assert_eq!(repeat_steps(0.0, 5.0, f32::NAN, 10.0), 0);
        assert_eq!(repeat_steps(0.0, 5.0, 0.5, f32::INFINITY), 0);
        assert_eq!(repeat_steps(0.0, f32::INFINITY, 0.5, 10.0), 0);
    }

    #[test]
    fn a_toast_stands_as_long_as_its_message_takes_to_read_times_the_players_scale() {
        // The defaults: 2 s to notice, 20 characters a second.
        assert_eq!(toast_hold(10, 2.0, 20.0, 1.0), 2.5);
        assert_eq!(toast_hold(100, 2.0, 20.0, 1.0), 7.0);
        assert_eq!(toast_hold(0, 2.0, 20.0, 1.0), 2.0);
        // XAG 116: the player may stretch it tenfold, and the message still counts.
        assert_eq!(toast_hold(100, 2.0, 20.0, 10.0), 70.0);
        assert!(toast_hold(40, 2.0, 20.0, 1.0) < toast_hold(41, 2.0, 20.0, 1.0));
    }

    #[test]
    fn an_unusable_hold_setting_never_gives_a_negative_infinite_or_nan_time() {
        for scale in [-1.0, 0.0, f32::NAN, f32::INFINITY] {
            assert_eq!(toast_hold(10, 2.0, 20.0, scale), 0.0);
        }
        // No reading speed means no reading time, not an infinite one.
        for speed in [0.0, -5.0, f32::NAN, f32::INFINITY] {
            assert_eq!(toast_hold(10, 2.0, speed, 1.0), 2.0);
        }
        for base in [-2.0, f32::NAN, f32::NEG_INFINITY] {
            assert_eq!(toast_hold(10, base, 20.0, 1.0), 0.5);
        }
    }

    #[test]
    fn a_toast_fades_in_holds_and_fades_out_over_its_life() {
        let (hold, fade) = (2.0, 0.5);
        assert_eq!(toast_life(hold, fade), 3.0);
        assert_eq!(toast_alpha(0.0, hold, fade), 0.0);
        assert_eq!(toast_alpha(0.25, hold, fade), 0.5);
        assert_eq!(toast_alpha(0.5, hold, fade), 1.0);
        assert_eq!(toast_alpha(2.5, hold, fade), 1.0);
        assert_eq!(toast_alpha(2.75, hold, fade), 0.5);
        assert_eq!(toast_alpha(3.0, hold, fade), 0.0);
        assert_eq!(toast_alpha(10.0, hold, fade), 0.0);
    }

    #[test]
    fn a_toast_with_no_fade_appears_whole_and_goes_at_once() {
        for fade in [0.0, -1.0, f32::NAN] {
            assert_eq!(toast_alpha(0.0, 2.0, fade), 1.0);
            assert_eq!(toast_alpha(1.99, 2.0, fade), 1.0);
            assert_eq!(toast_alpha(2.0, 2.0, fade), 0.0);
            assert_eq!(toast_life(2.0, fade), 2.0);
            assert_eq!(toast_grow(0.0, 2.0, fade), 1.0);
            assert_eq!(toast_grow(2.0, 2.0, fade), 0.0);
        }
    }

    #[test]
    fn a_toast_shortened_while_fading_in_still_ends_and_is_never_out_of_range() {
        // A hold cut to nothing: the fade in meets the fade out, and alpha stays in 0..=1.
        for step in 0..=40 {
            let age = step as f32 * 0.025;
            let alpha = toast_alpha(age, 0.0, 0.5);
            assert!((0.0..=1.0).contains(&alpha), "age {age}: {alpha}");
        }
        assert_eq!(toast_alpha(1.0, 0.0, 0.5), 0.0);
        assert_eq!(toast_alpha(f32::NAN, 2.0, 0.5), 0.0);
        assert_eq!(toast_alpha(-1.0, 2.0, 0.5), 0.0);
    }

    #[test]
    fn a_toast_opens_its_room_early_holds_it_and_closes_it_at_the_end() {
        let (hold, fade) = (2.0, 0.5);
        assert_eq!(toast_grow(0.0, hold, fade), 0.0);
        assert_eq!(toast_grow(1.0, hold, fade), 1.0);
        assert_eq!(toast_grow(3.0, hold, fade), 0.0);
        // Entering: more than half the room is open by the time a quarter of the fade is.
        assert!(toast_grow(0.125, hold, fade) > 0.5);
        // Leaving: most of the room is still there half way through the fade out, and it only
        // closes as the toast is nearly gone.
        assert!(toast_grow(2.75, hold, fade) > 0.8);
        assert!(toast_grow(2.95, hold, fade) < 0.5);
        // Never out of range, and never opens while the toast fades out.
        let mut last = 0.0;
        for step in 0..=20 {
            let grow = toast_grow(step as f32 * 0.025, hold, fade);
            assert!((0.0..=1.0).contains(&grow));
            assert!(
                grow >= last,
                "the room closed while entering at step {step}"
            );
            last = grow;
        }
        for age in [f32::NAN, -1.0, 100.0] {
            assert_eq!(toast_grow(age, hold, fade), 0.0);
        }
    }

    #[test]
    fn a_choice_steps_to_its_ends_and_stops_there() {
        // One step each way inside the list, then held against either end.
        assert_eq!(choice_step(1, 4, 1), 2);
        assert_eq!(choice_step(1, 4, -1), 0);
        assert_eq!(choice_step(3, 4, 1), 3);
        assert_eq!(choice_step(0, 4, -1), 0);
        // A jump of any size lands on an end, and a step of nothing stays put.
        assert_eq!(choice_step(1, 4, i32::MAX), 3);
        assert_eq!(choice_step(2, 4, i32::MIN), 0);
        assert_eq!(choice_step(2, 4, 0), 2);
        // A value past the end (a game set it carelessly) is read as the last option.
        assert_eq!(choice_step(9, 4, 0), 3);
        assert_eq!(choice_step(9, 4, -1), 2);
        // Nothing to choose from: nowhere to go, and no panic.
        assert_eq!(choice_step(0, 0, 1), 0);
        assert_eq!(choice_step(5, 0, -1), 0);
    }

    #[test]
    fn a_choice_cycles_round_when_activated() {
        assert_eq!(choice_next(0, 3), 1);
        assert_eq!(choice_next(2, 3), 0);
        assert_eq!(choice_next(0, 1), 0);
        assert_eq!(
            choice_next(9, 3),
            0,
            "past the end reads as the last, then wraps"
        );
        assert_eq!(choice_next(0, 0), 0);
    }

    #[test]
    fn tabs_step_round_the_strip_in_both_directions() {
        assert_eq!(tab_step(1, 3, 1), 2);
        assert_eq!(tab_step(1, 3, -1), 0);
        // Off either end it wraps to the other.
        assert_eq!(tab_step(2, 3, 1), 0);
        assert_eq!(tab_step(0, 3, -1), 2);
        // A step of nothing stays put, and a whole turn is back where it started.
        assert_eq!(tab_step(1, 3, 0), 1);
        assert_eq!(tab_step(1, 3, 3), 1);
        assert_eq!(tab_step(1, 3, -7), 0);
        assert_eq!(tab_step(0, 3, i32::MIN), 1);
        // One tab is always the one tab.
        assert_eq!(tab_step(0, 1, 1), 0);
        assert_eq!(tab_step(0, 1, -1), 0);
        // A value past the end (a game set it carelessly) is read as the last tab.
        assert_eq!(tab_step(9, 3, 0), 2);
        assert_eq!(tab_step(9, 3, 1), 0);
        // No tabs: nowhere to go, and no panic.
        assert_eq!(tab_step(0, 0, 1), 0);
        assert_eq!(tab_step(5, 0, -1), 0);
    }

    #[test]
    fn a_list_stands_a_pitch_tall_for_each_row() {
        assert_eq!(list_height(1.0, 48.0, 10.0), 58.0);
        assert_eq!(list_height(2.0, 48.0, 10.0), 116.0);
        assert_eq!(list_height(4.5, 48.0, 10.0), 261.0);
        assert_eq!(list_height(0.5, 48.0, 10.0), 29.0);
        for rows in [0.0, -2.0, f32::NAN, f32::INFINITY] {
            assert_eq!(list_height(rows, 48.0, 10.0), 0.0, "rows {rows}");
        }
    }

    #[test]
    fn a_reveal_keeps_the_next_row_in_sight_and_stays_put_when_it_can() {
        // Rows of 40 with a 160 viewport, a margin of one row, in a 440 list (280 of scroll).
        let reveal =
            |top: f32, scroll: f32| scroll_to_reveal(top, top + 40.0, 160.0, scroll, 280.0, 40.0);
        assert_eq!(reveal(0.0, 0.0), 0.0);
        assert_eq!(reveal(40.0, 0.0), 0.0, "a row below it in view: stay");
        assert_eq!(
            reveal(80.0, 0.0),
            0.0,
            "the third row still has the fourth in view"
        );
        assert_eq!(
            reveal(120.0, 0.0),
            40.0,
            "the fourth brings its next row in"
        );
        assert_eq!(reveal(160.0, 40.0), 80.0);
        // Walking back up: the margin is kept above the row too.
        assert_eq!(reveal(120.0, 200.0), 80.0);
        assert_eq!(
            reveal(0.0, 80.0),
            0.0,
            "the first row stops at the top, not a margin above"
        );
        // The ends of the list clamp: nothing scrolls past them.
        assert_eq!(reveal(400.0, 200.0), 280.0);
    }

    #[test]
    fn a_reveal_of_a_far_row_centres_it_and_a_tall_row_shows_its_top() {
        // A jump of more than a viewport (a click, a page, a rebuilt list) centres the row.
        assert_eq!(
            scroll_to_reveal(300.0, 340.0, 100.0, 0.0, 400.0, 0.0),
            270.0
        );
        assert_eq!(
            scroll_to_reveal(100.0, 140.0, 100.0, 400.0, 400.0, 0.0),
            70.0
        );
        // A row taller than the viewport is read from its top, whichever way it is reached.
        assert_eq!(
            scroll_to_reveal(150.0, 300.0, 100.0, 0.0, 300.0, 40.0),
            150.0
        );
        assert_eq!(
            scroll_to_reveal(150.0, 300.0, 100.0, 250.0, 300.0, 40.0),
            150.0
        );
        // A viewport too short for row and margin keeps what margin it can.
        assert_eq!(scroll_to_reveal(80.0, 120.0, 60.0, 0.0, 300.0, 40.0), 70.0);
    }

    #[test]
    fn a_reveal_never_leaves_the_list_and_ignores_what_it_cannot_read() {
        assert_eq!(scroll_to_reveal(0.0, 40.0, 100.0, 50.0, 300.0, 40.0), 0.0);
        assert_eq!(
            scroll_to_reveal(390.0, 430.0, 100.0, 0.0, 300.0, 40.0),
            300.0
        );
        // A list that fits has nowhere to scroll.
        assert_eq!(scroll_to_reveal(60.0, 100.0, 200.0, 30.0, 0.0, 40.0), 0.0);
        assert_eq!(scroll_to_reveal(60.0, 100.0, 200.0, 30.0, -5.0, 40.0), 0.0);
        // No viewport, or a value that is not a number: the scroll stays (clamped), never NaN.
        assert_eq!(scroll_to_reveal(60.0, 100.0, 0.0, 30.0, 300.0, 40.0), 30.0);
        assert_eq!(
            scroll_to_reveal(f32::NAN, 100.0, 100.0, 30.0, 300.0, 40.0),
            30.0
        );
        assert_eq!(
            scroll_to_reveal(60.0, 100.0, 100.0, f32::NAN, 300.0, 40.0),
            0.0
        );
        assert_eq!(
            scroll_to_reveal(100.0, 60.0, 100.0, 30.0, 300.0, 40.0),
            30.0
        );
    }

    #[test]
    fn a_page_goes_a_viewport_and_stops_at_the_ends() {
        let rows = [20.0, 70.0, 120.0, 170.0, 220.0, 270.0];
        assert_eq!(page_target(20.0, &rows, 150.0), Some(3));
        assert_eq!(
            page_target(170.0, &rows, 150.0),
            Some(5),
            "the last row within a page"
        );
        assert_eq!(page_target(220.0, &rows, 150.0), Some(5));
        assert_eq!(
            page_target(270.0, &rows, 150.0),
            None,
            "nothing below the last row"
        );
        assert_eq!(page_target(270.0, &rows, -150.0), Some(2));
        assert_eq!(
            page_target(70.0, &rows, -150.0),
            Some(0),
            "the first row within a page"
        );
        assert_eq!(page_target(20.0, &rows, -150.0), None);
        // Tall rows, a short page: still one row.
        assert_eq!(page_target(20.0, &rows, 10.0), Some(1));
        assert_eq!(page_target(270.0, &rows, -10.0), Some(4));
        // Two columns of rows share their centres: the first at the distance is taken, and the
        // focused row's own neighbours at the same height are not "beyond".
        let grid = [20.0, 20.0, 70.0, 70.0];
        assert_eq!(page_target(20.0, &grid, 100.0), Some(2));
        // Nothing to page over, or a page that is no distance.
        assert_eq!(page_target(20.0, &[], 100.0), None);
        assert_eq!(page_target(20.0, &rows, 0.0), None);
        assert_eq!(page_target(f32::NAN, &rows, 100.0), None);
    }

    #[test]
    fn a_scroll_moves_on_to_a_row_top_and_never_short_of_what_was_asked() {
        let tops = [0.0, 57.0, 114.0, 171.0, 228.0];
        assert_eq!(snap_to_row(1.0, 0.0, &tops), Some(57.0));
        assert_eq!(
            snap_to_row(57.0, 0.0, &tops),
            Some(57.0),
            "already on a top"
        );
        assert_eq!(
            snap_to_row(56.6, 0.0, &tops),
            Some(57.0),
            "rounded layout, half a unit of slack"
        );
        assert_eq!(snap_to_row(58.0, 0.0, &tops), Some(114.0));
        // Up takes the top at or before the ask, so the row asked for stays in view.
        assert_eq!(snap_to_row(120.0, 228.0, &tops), Some(114.0));
        assert_eq!(snap_to_row(114.0, 228.0, &tops), Some(114.0));
        assert_eq!(snap_to_row(1.0, 228.0, &tops), Some(0.0));
        // No row top that way: the end of the list.
        assert_eq!(snap_to_row(229.0, 171.0, &tops), None);
        assert_eq!(snap_to_row(-5.0, 57.0, &tops), None);
        // No move, nothing to snap to, or nothing readable.
        assert_eq!(snap_to_row(57.0, 57.0, &tops), None);
        assert_eq!(snap_to_row(60.0, 0.0, &[]), None);
        assert_eq!(snap_to_row(f32::NAN, 0.0, &tops), None);
        assert_eq!(snap_to_row(60.0, 0.0, &[f32::NAN, 114.0]), Some(114.0));
    }
    #[test]
    fn a_key_is_named_as_its_cap_is_printed() {
        // Letters and digits are the mark, whatever the layout: a stored key is a place.
        assert_eq!(key_name("KeyQ"), "Q");
        assert_eq!(key_name("Digit0"), "0");
        assert_eq!(key_name("F5"), "F5");
        assert_eq!(key_name("F13"), "F13");
        // Modifiers lead with their side, so Left Shift and Right Shift are two caps.
        assert_eq!(key_name("ShiftLeft"), "Left Shift");
        assert_eq!(key_name("ControlRight"), "Right Ctrl");
        assert_eq!(key_name("AltLeft"), "Left Alt");
        assert_eq!(key_name("SuperRight"), "Right Super");
        // The arrows are not the "Left" and "Right" of a side.
        assert_eq!(key_name("ArrowLeft"), "Left Arrow");
        assert_eq!(key_name("ArrowDown"), "Down Arrow");
        // The numpad is told from the row of digits.
        assert_eq!(key_name("Numpad7"), "Num 7");
        assert_eq!(key_name("NumpadAdd"), "Num +");
        assert_eq!(key_name("NumpadEnter"), "Num Enter");
        // Punctuation is the mark, and a few long names are the short form on the cap.
        assert_eq!(key_name("Semicolon"), ";");
        assert_eq!(key_name("Backquote"), "`");
        assert_eq!(key_name("Escape"), "Esc");
        assert_eq!(key_name("Delete"), "Del");
        assert_eq!(key_name("Space"), "Space");
        assert_eq!(key_name("Enter"), "Enter");
        assert_eq!(key_name("Tab"), "Tab");
        // Any other name is cut into words.
        assert_eq!(key_name("PageUp"), "Page Up");
        assert_eq!(key_name("CapsLock"), "Caps Lock");
        assert_eq!(key_name("PrintScreen"), "Print Screen");
        assert_eq!(key_name("MediaPlayPause"), "Media Play Pause");
        assert_eq!(key_name("Unidentified(Windows(255))"), "Unknown key");
    }

    #[test]
    fn a_mouse_button_is_named_by_what_a_player_calls_it() {
        assert_eq!(mouse_name("Left"), "Left Click");
        assert_eq!(mouse_name("Right"), "Right Click");
        assert_eq!(mouse_name("Middle"), "Middle Click");
        assert_eq!(mouse_name("Back"), "Mouse 4");
        assert_eq!(mouse_name("Forward"), "Mouse 5");
        assert_eq!(mouse_name("Other(9)"), "Mouse 9");
    }

    #[test]
    fn a_pad_button_is_named_in_the_vocabulary_of_its_make() {
        // One place, three names: the face buttons by position.
        for (button, xbox, playstation, switch) in [
            ("South", "A", "Cross", "B"),
            ("East", "B", "Circle", "A"),
            ("North", "Y", "Triangle", "X"),
            ("West", "X", "Square", "Y"),
            ("LeftTrigger", "LB", "L1", "L"),
            ("RightTrigger2", "RT", "R2", "ZR"),
            ("Select", "View", "Create", "-"),
            ("Start", "Menu", "Options", "+"),
        ] {
            assert_eq!(pad_name(button, PadStyle::Xbox), xbox, "{button}");
            assert_eq!(
                pad_name(button, PadStyle::PlayStation),
                playstation,
                "{button}"
            );
            assert_eq!(pad_name(button, PadStyle::Switch), switch, "{button}");
        }
        // The D-pad reads the same on every pad, and an unnamed button has a number.
        for style in [PadStyle::Xbox, PadStyle::PlayStation, PadStyle::Switch] {
            assert_eq!(pad_name("DPadLeft", style), "D-pad Left");
            assert_eq!(pad_name("Other(14)", style), "Button 14");
        }
        assert_eq!(PadStyle::default(), PadStyle::Xbox);
    }

    #[test]
    fn a_value_shows_the_step_nearest_it() {
        let steps = TEXT_SIZE_STEPS;
        for (index, step) in steps.iter().enumerate() {
            assert_eq!(nearest_step(&steps, *step), index);
        }
        assert_eq!(nearest_step(&steps, 1.2), 1);
        assert_eq!(nearest_step(&steps, 1.7), 2);
        assert_eq!(nearest_step(&steps, 1.8), 3);
        // Halfway between two takes the lower, and so does a value in the lower half.
        assert_eq!(nearest_step(&steps, 1.125), 0);
        assert_eq!(nearest_step(&steps, 1.75), 2);
        // Past either end takes that end, whatever the distance.
        assert_eq!(nearest_step(&steps, 0.0), 0);
        assert_eq!(nearest_step(&steps, -3.0), 0);
        assert_eq!(nearest_step(&steps, 40.0), 3);
        assert_eq!(nearest_step(&steps, f32::INFINITY), 3);
        assert_eq!(nearest_step(&steps, f32::NEG_INFINITY), 0);
        // Not a number, or nothing to choose from, is the first.
        assert_eq!(nearest_step(&steps, f32::NAN), 0);
        assert_eq!(nearest_step(&[], 1.0), 0);
        assert_eq!(nearest_step(&INTERFACE_SIZE_STEPS, 0.9), 1);
    }

    #[test]
    fn a_pad_family_is_named_as_its_maker_writes_it() {
        let names: Vec<_> = PAD_STYLES.iter().map(|style| style.name()).collect();
        assert_eq!(names, ["Xbox", "PlayStation", "Switch"]);
    }
    #[test]
    fn a_fuzzy_query_is_a_subsequence_of_every_term_in_any_order() {
        assert!(fuzzy_score("opn prj", "File: Open Project").is_some());
        assert!(fuzzy_score("prj opn", "File: Open Project").is_some());
        assert!(fuzzy_score("OPEN", "open project").is_some());
        // A character the text lacks, or too few of one, is no match.
        assert_eq!(fuzzy_score("opz", "Open Project"), None);
        assert_eq!(fuzzy_score("ooo", "Open"), None);
        assert_eq!(fuzzy_score("a", ""), None);
        // A query with no terms matches all, shorter first.
        assert!(fuzzy_score("  ", "Save").unwrap() > fuzzy_score("", "Save As").unwrap());
    }

    #[test]
    fn a_word_start_and_a_run_beat_letters_picked_from_the_middle() {
        let score = |text| fuzzy_score("opn prj", text).unwrap();
        let open = score("Open Project");
        assert!(open > score("Reopen Project"));
        assert!(open > score("Open Prefabs, then Jump"));
        assert!(open > score("Open Project Settings"));
        // A capital after a small letter starts a word as a space does.
        assert!(fuzzy_score("op", "OpenProject").unwrap() > fuzzy_score("op", "stopper").unwrap());
        // Skipping characters costs: the same letters further apart score less.
        assert!(fuzzy_score("ab", "a b").unwrap() > fuzzy_score("ab", "a xxxx b").unwrap());
    }
    #[test]
    fn a_split_is_never_nan_and_holds_its_minimums_in_every_room() {
        for fraction in [-1.0, 0.0, 0.3, 1.0, 7.0, f32::NAN, f32::INFINITY] {
            for extent in [-5.0, 0.0, 40.0, 500.0, f32::NAN] {
                let held = split_clamp(fraction, extent, 100.0, 80.0);
                assert!(
                    (0.0..=1.0).contains(&held),
                    "{fraction} in {extent}: {held}"
                );
            }
        }
        // In a room that fits both, the panes keep their minimums at every fraction.
        for fraction in [0.0, 0.1, 0.5, 0.9, 1.0] {
            let held = split_clamp(fraction, 500.0, 100.0, 80.0);
            assert!(held * 500.0 >= 100.0 - 1e-3 && (1.0 - held) * 500.0 >= 80.0 - 1e-3);
        }
        // In a room that fits neither the second pane has nothing and the first all of it.
        assert_eq!(split_mins(30.0, 100.0, 80.0), (30.0, 0.0));
        assert_eq!(split_mins(-3.0, 100.0, 80.0), (0.0, 0.0));
        // A drag by nothing, or by NaN, stays where it is.
        assert_eq!(split_drag(0.4, 0.0, 500.0, 0.0, 0.0), 0.4);
        assert_eq!(split_drag(0.4, f32::NAN, 500.0, 0.0, 0.0), 0.4);
    }

    #[test]
    fn a_dock_zone_is_the_middle_half_or_the_nearest_edge() {
        // The middle half of both sides is the group; the quarter at each end an edge.
        assert_eq!(dock_zone(400.0, 200.0, 100.0, 50.0), DockZone::Into);
        assert_eq!(dock_zone(400.0, 200.0, 300.0, 150.0), DockZone::Into);
        assert_eq!(dock_zone(400.0, 200.0, 99.0, 100.0), DockZone::Left);
        assert_eq!(dock_zone(400.0, 200.0, 301.0, 100.0), DockZone::Right);
        assert_eq!(dock_zone(400.0, 200.0, 200.0, 49.0), DockZone::Top);
        assert_eq!(dock_zone(400.0, 200.0, 200.0, 151.0), DockZone::Bottom);
        // A corner goes to the edge it is nearer by share of the side: this point is 10% from the
        // left and 20% from the top.
        assert_eq!(dock_zone(400.0, 200.0, 40.0, 40.0), DockZone::Left);
        assert_eq!(dock_zone(400.0, 200.0, 80.0, 10.0), DockZone::Top);
        // Nothing to hit in a group with no size or a point that is not a number.
        assert_eq!(dock_zone(0.0, 200.0, 1.0, 1.0), DockZone::Into);
        assert_eq!(dock_zone(400.0, 200.0, f32::NAN, 1.0), DockZone::Into);
        // A point past the group still lands in the zone beside it.
        assert_eq!(dock_zone(400.0, 200.0, -50.0, 100.0), DockZone::Left);
    }

    #[test]
    fn the_dock_edge_band_picks_the_nearest_edge_and_nothing_inside() {
        assert_eq!(
            dock_edge_zone(800.0, 400.0, 790.0, 200.0, 24.0),
            Some(DockZone::Right)
        );
        assert_eq!(
            dock_edge_zone(800.0, 400.0, 5.0, 395.0, 24.0),
            Some(DockZone::Left)
        );
        assert_eq!(dock_edge_zone(800.0, 400.0, 30.0, 200.0, 24.0), None);
        assert_eq!(dock_edge_zone(800.0, 400.0, -1.0, 200.0, 24.0), None);
    }

    #[test]
    fn the_drop_rect_is_the_part_the_layout_will_give_the_panel() {
        assert_eq!(
            dock_drop_rect(DockZone::Into, 400.0, 200.0, false),
            (0.0, 0.0, 400.0, 200.0)
        );
        assert_eq!(
            dock_drop_rect(DockZone::Right, 400.0, 200.0, false),
            (200.0, 0.0, 200.0, 200.0)
        );
        assert_eq!(
            dock_drop_rect(DockZone::Bottom, 400.0, 200.0, true),
            (0.0, 150.0, 400.0, 50.0)
        );
    }

    #[test]
    fn a_neighbour_is_the_nearest_group_that_way() {
        let others = [(100.0, 50.0), (400.0, 60.0), (210.0, 300.0), (200.0, 50.0)];
        let from = (200.0, 50.0);
        assert_eq!(dock_neighbour(from, &others, DockZone::Left), Some(0));
        assert_eq!(dock_neighbour(from, &others, DockZone::Right), Some(1));
        assert_eq!(dock_neighbour(from, &others, DockZone::Bottom), Some(2));
        // Itself, level with it, is no neighbour; nor is one on the other side.
        assert_eq!(dock_neighbour(from, &others, DockZone::Top), None);
        assert_eq!(dock_neighbour(from, &others, DockZone::Into), None);
        assert_eq!(
            dock_tab_slot(&[(50.0, 0.0, 40.0), (150.0, 0.0, 40.0)], 100.0, 20.0),
            1
        );
    }

    #[test]
    fn a_typed_number_is_read_and_a_sum_a_word_or_an_overflow_is_refused_for_its_own_reason() {
        assert_eq!(parse_number("+5"), Ok(5.0));
        assert_eq!(parse_number("-.5"), Ok(-0.5));
        assert_eq!(parse_number("1e-3"), Ok(0.001));
        assert_eq!(parse_number("2E+2"), Ok(200.0));
        for sum in [
            "1-2", "3+4", "--3", "2*3", "6/2", "(2)", "2^3", "50%", "1e3-1",
        ] {
            assert_eq!(parse_number(sum), Err(NumberError::Expression), "{sum}");
        }
        for word in [".", "1.2.3", "1,5", "ten", "1e", "0x10"] {
            assert_eq!(parse_number(word), Err(NumberError::NotANumber), "{word}");
        }
        for big in ["inf", "NaN", "1e99"] {
            assert_eq!(parse_number(big), Err(NumberError::NotFinite), "{big}");
        }
        assert_eq!(parse_number("  "), Err(NumberError::Empty));
    }

    #[test]
    fn a_number_shows_the_digits_of_its_step_and_more_only_when_it_needs_them() {
        assert_eq!(format_number(-2.0, 0.1), "-2.0");
        assert_eq!(format_number(0.1 + 0.2, 0.1), "0.3");
        assert_eq!(format_number(99999.9, 0.1), "99999.9");
        assert_eq!(format_number(1.0 / 3.0, 0.1), "0.333333");
        assert_eq!(format_number(7.0, 0.25), "7.00");
        assert_eq!(format_number(-0.0, 1.0), "0");
        // A step that is no step shows two digits.
        assert_eq!(format_number(1.5, 0.0), "1.50");
        assert_eq!(number_decimals(f32::NAN), 2);
        assert_eq!(number_decimals(0.001), 3);
    }

    #[test]
    fn a_scrub_and_a_step_are_rounded_to_their_digits_and_held_to_the_range() {
        // Down and up by the same distance is where it began, with no 0.1 + 0.2 dust.
        let up = scrub_value(0.3, 3.0, 0.1, 0.0, 1.0, false, false);
        assert_eq!(up, 0.6);
        assert_eq!(scrub_value(up, -3.0, 0.1, 0.0, 1.0, false, false), 0.3);
        // Shift's finer rate keeps its extra digit and Ctrl keeps the step's own.
        assert_eq!(scrub_value(0.0, 3.0, 0.1, 0.0, 1.0, true, false), 0.03);
        assert_eq!(scrub_value(0.5, 5.0, 0.1, 0.0, 100.0, false, true), 5.5);
        // A range given the wrong way round is read either way, and a NaN distance never moves it.
        assert_eq!(scrub_value(1.0, 5.0, 0.1, 3.0, 0.0, false, false), 1.5);
        assert_eq!(scrub_value(1.0, f32::NAN, 0.1, 0.0, 9.0, false, false), 1.0);
        assert_eq!(step_value(0.1, 2.0, 0.1, 0.0, 1.0), 0.3);
        assert_eq!(step_value(0.1, -5.0, 0.1, 0.0, 1.0), 0.0);
    }

    #[test]
    fn hex_is_read_in_every_form_and_shown_the_shortest_true_way() {
        let orange = [1.0, 136.0 / 255.0, 0.0, 1.0];
        assert_eq!(parse_hex("#ff8800"), Ok(orange));
        assert_eq!(parse_hex("  FF8800 "), Ok(orange));
        assert_eq!(parse_hex("#f80"), Ok([1.0, 136.0 / 255.0, 0.0, 1.0]));
        assert_eq!(parse_hex("#f80c").map(|c| c[3]), Ok(204.0 / 255.0));
        assert_eq!(parse_hex("#ff880080").map(|c| c[3]), Ok(128.0 / 255.0));
        assert_eq!(parse_hex(""), Err(HexError::Empty));
        assert_eq!(parse_hex("#"), Err(HexError::Empty));
        assert_eq!(parse_hex("#ff88"), Ok(parse_hex("#ffff8888").unwrap()));
        assert_eq!(parse_hex("#ff880"), Err(HexError::Length));
        assert_eq!(parse_hex("#ff88000"), Err(HexError::Length));
        assert_eq!(parse_hex("#gg8800"), Err(HexError::NotHex));
        assert_eq!(parse_hex("#ff\u{e9}800"), Err(HexError::NotHex));
        assert_eq!(hex_text(orange), "#FF8800");
        assert_eq!(hex_text([1.0, 1.0, 1.0, 0.0]), "#FFFFFF00");
        // Whatever it shows, it reads back as the same bytes.
        for text in ["#000000", "#FFFFFF", "#12AB9C", "#12AB9C7F"] {
            assert_eq!(hex_text(parse_hex(text).unwrap()), text);
        }
    }

    #[test]
    fn hsv_round_trips_and_a_grey_or_a_black_keeps_what_it_cannot_say() {
        for (h, s, v) in [
            (0.0, 1.0, 1.0),
            (45.0, 0.5, 0.75),
            (200.0, 0.3, 0.2),
            (300.0, 1.0, 0.5),
        ] {
            let back = rgb_to_hsv(hsv_to_rgb(h, s, v), [0.0; 3]);
            assert!((back[0] - h).abs() < 1e-3, "{h} came back {}", back[0]);
            assert!((back[1] - s).abs() < 1e-5 && (back[2] - v).abs() < 1e-5);
        }
        assert_eq!(hsv_to_rgb(-60.0, 1.0, 1.0), hsv_to_rgb(300.0, 1.0, 1.0));
        assert_eq!(hsv_to_rgb(f32::NAN, 1.0, 1.0), [1.0, 0.0, 0.0]);
        assert_eq!(
            rgb_to_hsv([1.0, 1.0, 1.0], [10.0, 0.7, 0.3]),
            [10.0, 0.0, 1.0]
        );
        assert_eq!(
            rgb_to_hsv([0.0, 0.0, 0.0], [10.0, 0.7, 0.3]),
            [10.0, 0.7, 0.0]
        );
    }

    #[test]
    fn a_pointer_in_the_area_is_saturation_across_and_value_up_held_at_the_edge() {
        let at = |x, y| area_values([x, y], [2.0, 2.0], [96.0, 46.0]);
        assert_eq!(at(2.0, 48.0), [0.0, 0.0]);
        assert_eq!(at(98.0, 2.0), [1.0, 1.0]);
        assert_eq!(at(50.0, 25.0), [0.5, 0.5]);
        assert_eq!(at(-500.0, 900.0), [0.0, 0.0]);
        assert_eq!(area_values([5.0, 5.0], [0.0, 0.0], [0.0, 0.0]), [0.5, 0.5]);
    }

    #[test]
    fn time_left_is_in_words_with_the_precision_an_estimate_has() {
        assert_eq!(eta_words(0.4), "less than a second left");
        assert_eq!(eta_words(4.0), "about 4 s left");
        assert_eq!(eta_words(21.0), "about 20 s left");
        assert_eq!(eta_words(57.0), "about 55 s left");
        assert_eq!(eta_words(58.0), "about 1 min left");
        assert_eq!(eta_words(150.0), "about 3 min left");
        assert_eq!(eta_words(3570.0), "about 1 h left");
        assert_eq!(eta_words(3900.0), "about 1 h 5 min left");
        assert_eq!(eta_words(f32::NAN), "");
        assert_eq!(eta_words(-3.0), "");
    }

    #[test]
    fn an_ease_out_rises_monotonically_and_is_clamped() {
        let mut last = -1.0;
        for step in 0..=20 {
            let now = ease_out(step as f32 * 0.01, 0.2);
            assert!(now > last, "step {step}: {now} after {last}");
            last = now;
        }
        assert_eq!(ease_out(-1.0, 0.2), 0.0);
        assert_eq!(ease_out(9.0, 0.2), 1.0);
        assert_eq!(ease_out(0.1, f32::NAN), 1.0);
        assert_eq!(ease_out(f32::NAN, 0.2), 1.0);
    }

    #[test]
    fn the_progress_line_joins_a_step_and_the_time_left_and_drops_what_is_missing() {
        assert_eq!(
            progress_text(Some((3, 7, "Measuring meshes")), Some(20.0)),
            "3 of 7: Measuring meshes, about 20 s left"
        );
        assert_eq!(progress_text(Some((3, 7, "")), None), "3 of 7");
        assert_eq!(progress_text(None, Some(f32::INFINITY)), "");
        assert_eq!(progress_text(None, None), "");
    }

    #[test]
    fn a_spinner_turns_once_a_period_on_the_clock_and_never_leaves_its_range() {
        assert_eq!(spinner_angle(0.0), 0.0);
        let half = spinner_angle(SPINNER_PERIOD_SECS / 2.0);
        assert!((half - std::f32::consts::PI).abs() < 1e-5);
        assert!(spinner_angle(SPINNER_PERIOD_SECS * 7.25) < std::f32::consts::TAU);
        assert!(spinner_angle(-0.1) >= 0.0);
        assert_eq!(spinner_angle(f32::NAN), 0.0);
    }

    #[test]
    fn a_bar_hides_the_lowest_rank_first_and_the_later_of_equals() {
        let widths = [100.0; 4];
        // 4 × 100 + 3 × 10 = 430.
        assert_eq!(bar_fit(&widths, &[0; 4], 10.0, 430.0, 0.0), [true; 4]);
        assert_eq!(
            bar_fit(&widths, &[0; 4], 10.0, 429.0, 0.0),
            [true, true, true, false]
        );
        assert_eq!(
            bar_fit(&widths, &[3, 1, 3, 2], 10.0, 429.0, 0.0),
            [true, false, true, true]
        );
        assert_eq!(
            bar_fit(&widths, &[3, 1, 3, 2], 10.0, 300.0, 0.0),
            [true, false, true, false]
        );
        // Equal ranks: the last goes first, then the one before it.
        assert_eq!(
            bar_fit(&widths, &[0; 4], 10.0, 320.0, 0.0),
            [true, true, true, false]
        );
        assert_eq!(
            bar_fit(&widths, &[0; 4], 10.0, 210.0, 0.0),
            [true, true, false, false]
        );
    }

    #[test]
    fn a_bar_keeps_the_room_of_its_more_button_only_when_something_hides() {
        let widths = [100.0; 3];
        // 320 holds all three (316): the button is not needed, so its room is not kept.
        assert_eq!(bar_fit(&widths, &[0; 3], 8.0, 320.0, 60.0), [true; 3]);
        // 300 does not: 300 - 60 holds one item and a gap short of two (208), so only two fit.
        assert_eq!(
            bar_fit(&widths, &[0; 3], 8.0, 300.0, 60.0),
            [true, true, false]
        );
        assert_eq!(
            bar_fit(&widths, &[0; 3], 8.0, 250.0, 60.0),
            [true, false, false]
        );
    }

    #[test]
    fn a_bar_with_no_room_or_odd_widths_hides_all_and_never_loops() {
        assert_eq!(
            bar_fit(&[10.0, 10.0], &[0, 0], 4.0, -5.0, 0.0),
            [false, false]
        );
        assert_eq!(
            bar_fit(&[f32::NAN, 10.0], &[0, 0], 4.0, 14.0, 0.0),
            [true, true]
        );
        assert_eq!(bar_fit(&[], &[], 4.0, 0.0, 0.0), Vec::<bool>::new());
        // A rank list shorter than the widths ranks the rest 0.
        assert_eq!(
            bar_fit(&[50.0; 3], &[1], 0.0, 100.0, 0.0),
            [true, true, false]
        );
    }

    #[test]
    fn a_pinned_point_keeps_its_direction_and_never_leaves_the_rectangle() {
        let (centre, min, max) = ((640.0, 360.0), (64.0, 36.0), (1216.0, 684.0));
        // Up and to the right, steeper than the corner: it hits the top edge, on the same ray.
        let (x, y) = pin_to_edge((740.0, -3000.0), centre, min, max);
        assert!((y - 36.0).abs() < 1e-3, "{y}");
        let (rx, ry) = (x - centre.0, y - centre.1);
        let (ox, oy) = (740.0 - centre.0, -3000.0 - centre.1);
        assert!((rx * oy - ry * ox).abs() < 1.0, "off the ray: {rx} {ry}");
        // Every direction lands inside the rectangle.
        for i in 0..360 {
            let a = (i as f32).to_radians();
            let (px, py) = pin_to_edge(
                (centre.0 + a.cos() * 9000.0, centre.1 + a.sin() * 9000.0),
                centre,
                min,
                max,
            );
            assert!(
                (min.0..=max.0).contains(&px) && (min.1..=max.1).contains(&py),
                "{i}"
            );
        }
        // The centre itself, an empty rectangle and a NaN are safe.
        assert_eq!(pin_to_edge(centre, centre, min, max), centre);
        assert_eq!(pin_to_edge((9.0, 9.0), centre, max, min), centre);
        assert_eq!(pin_to_edge((f32::NAN, 0.0), centre, min, max), centre);
    }

    #[test]
    fn a_box_is_outside_only_when_none_of_it_overlaps_the_view() {
        let view = ((0.0, 0.0), (100.0, 100.0));
        assert!(box_outside((101.0, 0.0), (120.0, 10.0), view.0, view.1));
        assert!(box_outside((0.0, -30.0), (10.0, -1.0), view.0, view.1));
        assert!(!box_outside((90.0, 90.0), (130.0, 130.0), view.0, view.1));
        assert!(!box_outside((100.0, 0.0), (120.0, 10.0), view.0, view.1));
    }
}