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
//! Ready-made widgets: free functions returning a bundle, so they compose inside `children![]` and
//! with [`crate::observe`]. Each carries a [`Role`], and [`crate::apply_skin`] styles it from the
//! skin; none of them takes a colour or a size.

use std::ops::RangeInclusive;

use bevy::ecs::lifecycle::HookContext;
use bevy::ecs::relationship::RelatedSpawner;
use bevy::ecs::spawn::{SpawnIter, SpawnRelatedBundle, SpawnWith, SpawnableList};
use bevy::ecs::world::DeferredWorld;
use bevy::input_focus::tab_navigation::{TabGroup, TabIndex};
use bevy::picking::cursor::EntityCursor;
use bevy::picking::hover::Hovered;
use bevy::prelude::*;
use bevy::text::{EditableText, Justify, LineBreak, TextCursorStyle};
use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation;
use bevy::ui::{Checked, FixedNode};
use bevy::ui_widgets::{
    Checkbox, ControlOrientation, ScrollArea, Scrollbar, ScrollbarThumb, SelectAllOnFocus, Slider,
    SliderOrientation, SliderRange, SliderStep, SliderThumb, SliderValue, TabActivation, TabList,
    TextInput, TrackClick, checkbox_self_update, observe, slider_self_update,
};
use bevy::window::SystemCursorIcon;

use crate::binding::{
    Binding, BindingValue, binding_on_activate, binding_on_key_input, binding_self_update,
};
use crate::choice::{
    ChoiceCount, ChoiceValue, StepBy, arrow_on_click, arrow_on_press, choice_on_activate,
    choice_on_key_input, choice_on_move, choice_self_update,
};
use crate::color::{
    ColorSwatch, ColorValue, SwatchHalf, color_on_key_input, color_on_text, color_self_update,
    swatch_on_activate,
};
use crate::dock::Dock;
use crate::dock_layout::DockLayout;
use crate::hold::{
    HoldToConfirm, hold_on_cancel, hold_on_drag_end, hold_on_press, hold_on_release,
};
use crate::icon::{Icon, IconSource};
use crate::list::ListView;
use crate::menu::{MenuBar, MenuItem, MenuTitle, bar_on_cancel, menu_panel};
use crate::meter::Meter;
use crate::model::{
    PadStyle, format_number, hex_text, meter_fraction, radial_place, slider_fraction, slider_text,
};
use crate::nav::Dialog;
use crate::number::{
    NumberInput, NumberRange, NumberStep, NumberValue, VecPart, VecValue, number_on_cancel,
    number_on_drag, number_on_drag_end, number_on_drag_start, number_on_key_input, number_on_step,
    number_on_text, number_self_update, vec_part_on_change,
};
use crate::options::{OptionRow, option_on_change};
use crate::palette::{
    CommandPalette, NO_MATCH, PALETTE_HINT, PALETTE_ROWS, PaletteCount, PaletteInput, PaletteNote,
    PaletteRow, palette_on_acquire, palette_on_activate, palette_on_cancel, palette_on_click,
    palette_on_move,
};
use crate::popover::{
    Placement, PopoverPanel, placement_of, popover_on_cancel, stop_acquire, stop_click, stop_press,
    stop_release,
};
use crate::progress::{Progress, Spinner};
use crate::prompt::{Prompt, PromptsAnchor};
use crate::radial::{
    RadialCount, RadialItem, RadialSlot, RadialValue, radial_on_activate, radial_on_key_input,
    radial_on_pointer_move, radial_on_press, radial_self_update,
};
use crate::region::FocusRegion;
use crate::section::{SectionHeader, SectionOpen, header_on_activate, section_self_update};
use crate::select::{SELECT_HINT, SELECT_NO_MATCH, Select, select_on_activate};
use crate::skin::Role;
use crate::slots::{Slot, SlotGrid, SlotItems};
use crate::split::{
    Split, SplitAxis, SplitDivider, divider_on_cancel, divider_on_click, divider_on_drag,
    divider_on_drag_end, divider_on_drag_start, divider_on_key_input, divider_on_press,
    divider_on_release, split_self_update, toggle_split,
};
use crate::status::{StatusBar, StatusGroup, StatusItem};
use crate::table::{Column, RowSource, table_bundle};
use crate::tabs::{TabsCount, TabsValue, tabs_on_select, tabs_self_update};
use crate::text::{
    AreaField, TextHint, TextInputOf, TextInputValue, text_on_key_input, text_row_on_acquire,
    text_self_update,
};
use crate::toast::{ToastBundle, ToastKind};
use crate::toolbar::{
    GroupIndex, GroupOption, OptionContent, ToggleGroupCount, ToggleGroupValue, Toolbar,
    group_self_update, option_on_activate,
};
use crate::tooltip::Tooltip;
use crate::tree::{Tree, TreeNode, TreeView};

/// A control's label is one line: the row is as wide as its label and its control need, so a label
/// that wraps was wrapped by a rounding error in the row's width (a label 210 px wide in a row that
/// came out a hair under 210 stood on two lines at 125% text, and the row was twice as tall).
pub(crate) const ONE_LINE: TextLayout = TextLayout::new(Justify::Left, LineBreak::NoWrap);

/// How many keyboard or D-pad steps span a [`slider`]'s range.
const SLIDER_STEPS: f32 = 20.0;

/// The least length of a list's thumb, in logical px (about half a comfortable target), so a long
/// list leaves something to grab.
const LIST_MIN_THUMB: f32 = 24.0;

/// A [`split`] divider's grip, the pill in the middle of its channel: its thickness and its length,
/// in logical px. A design default: a quiet pill, the length of a thumb's grab.
const SPLIT_GRIP_THICKNESS: f32 = 4.0;
const SPLIT_GRIP_LENGTH: f32 = 40.0;

/// How many characters of the body text a [`text_input`]'s field shows at once ("0"'s width each):
/// 16 and one more, because Bevy keeps one character of room after the caret for the next one to be
/// typed, so a name that fills a [`TextLimit`](crate::TextLimit) of 16 shows whole with its caret
/// instead of scrolling its first letter away. Longer text scrolls in it, so the row never changes
/// size.
const TEXT_INPUT_CHARS: f32 = 17.0;

/// How many character advances wide a [`text_area`]'s field is: a text input's and a half.
const TEXT_AREA_CHARS: f32 = 26.0;

/// A text field's caret, as a share of the font size: 2 px at the body size, a hair thinner than
/// Bevy's 0.2 so it does not cover a letter's stem.
const TEXT_CARET_WIDTH: f32 = 0.1;

/// How many characters of the body text a [`number_field`]'s field shows: "-12345.67" and the
/// caret's room. A number that needs more scrolls in it, so the row never changes size while the
/// player scrubs.
const NUMBER_FIELD_CHARS: f32 = 10.0;

/// The same for each component of a [`vec_field`], three of which stand in a row.
const VEC_FIELD_CHARS: f32 = 8.0;

/// How many characters wide a colour field is: `#RRGGBBAA` and the room Bevy keeps after a caret at its end.
const COLOR_FIELD_CHARS: f32 = 10.0;

/// How far a choice's chevron is moved to put its ink in the middle of its arrow, in percent of
/// its own width. A square turned an eighth of a turn has its two drawn sides on one side of its
/// centre: they run from the centre line out to the corner, which is half a diagonal away, so
/// the ink's middle is a quarter of the diagonal, `1 / (2 √2)` of the side, off the centre.
pub(crate) const CHEVRON_INK_SHIFT: f32 = 50.0 * std::f32::consts::FRAC_1_SQRT_2;

/// A toggle's state at spawn. A bundle cannot carry [`Checked`] only when the toggle starts on
/// (`Option<Checked>` is not a bundle), so this puts it on the entity as it is added and goes.
#[derive(Component)]
#[component(on_add = start_state)]
struct StartsOn(bool);

fn start_state(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
    let on = world.get::<StartsOn>(entity).is_some_and(|start| start.0);
    let mut commands = world.commands();
    let mut toggle = commands.entity(entity);
    toggle.remove::<StartsOn>();
    if on {
        toggle.insert(Checked);
    }
}

/// A full-window column that centres its children: the root of a menu screen or a HUD. It is a tab
/// group, so Tab cycles through the buttons on it.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((screen(), children![label("Hello")]));
/// # }
/// ```
///
/// It is layout, not a surface: its empty part is [`Pickable::IGNORE`], so a HUD built on it lets
/// the pointer through to the sprites, meshes and other UI roots under it, while the widgets on it
/// ([`panel`], [`button`], [`meter`]…) still take the pointer. A click on the empty part still
/// blurs the interface: it lands on whatever is below, or on the window, and Bevy clears focus
/// there. A menu screen that must swallow the pointer opts back in on the entity (a tuple bundle
/// cannot carry two `Pickable`s, so `(screen(), Pickable::default())` panics):
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(screen()).insert(Pickable::default());
/// # }
/// ```
pub fn screen() -> impl Bundle {
    (
        Node {
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            flex_direction: FlexDirection::Column,
            align_items: AlignItems::Center,
            justify_content: JustifyContent::Center,
            ..default()
        },
        Role::Screen,
        TabGroup::new(0),
        Pickable::IGNORE,
    )
}

/// A framed, padded column on the skin's surface colour.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((panel(), children![heading("Inventory"), label("Empty")]));
/// # }
/// ```
pub fn panel() -> impl Bundle {
    (
        Node {
            flex_direction: FlexDirection::Column,
            ..default()
        },
        Role::Panel,
    )
}

/// A column filled with one step of the skin's surface ladder, [`crate::GooeySkin::surfaces`], and
/// nothing else: no padding, frame or corner, which a host takes from the skin's tokens
/// ([`crate::GooeySkin::space`], [`crate::GooeySkin::corner`]). `level` 0 is the lowest step; a level past the top
/// is the top.
///
/// A tool nests its grounds: a panel's ground, a row on it, a field in the row, each a step above the
/// one it stands in.
///
/// A bundle cannot carry a `Node` twice: for a surface with its own padding, size or corners, spawn
/// your own `Node` with [`Role::Surface`] instead (`(Role::Surface(2), Node { padding: .. , ..default() })`).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((surface(1), children![(surface(2), children![label("A row")])]));
/// # }
/// ```
pub fn surface(level: u8) -> impl Bundle {
    (
        Node {
            flex_direction: FlexDirection::Column,
            ..default()
        },
        Role::Surface(level),
    )
}

/// A column of buttons, stretched to the widest.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((menu(), children![button("New game"), button("Continue")]));
/// # }
/// ```
pub fn menu() -> impl Bundle {
    (
        Node {
            flex_direction: FlexDirection::Column,
            align_items: AlignItems::Stretch,
            ..default()
        },
        Role::Menu,
    )
}

/// Heading text, in the skin's heading size and font.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(heading("Paused"));
/// # }
/// ```
pub fn heading(text: impl Into<String>) -> impl Bundle {
    (Text::new(text), Role::Heading)
}

/// Body text, in the skin's text size and font.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(label("Health"));
/// # }
/// ```
pub fn label(text: impl Into<String>) -> impl Bundle {
    (Text::new(text), Role::Label)
}

/// A button: Bevy's headless [`bevy::ui_widgets::Button`], reachable by Tab and by arrows and the
/// D-pad, styled by its state. Observe [`crate::Activate`] on it to act.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((button("Resume"), observe(|_: On<Activate>| info!("resume"))));
/// # }
/// ```
pub fn button(text: impl Into<String>) -> impl Bundle {
    (
        Node {
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        bevy::ui_widgets::Button,
        Role::Button,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        children![(Text::new(text), Role::ButtonText)],
    )
}

/// A button that confirms only when it is held, for an act the player cannot take back (delete a
/// save, quit without saving, abandon a run). Hold Enter, Space or the pad's South while it has
/// focus, or the primary pointer button while the pointer is over it, for `seconds`: a bar under
/// the label fills at an even rate and, at the end, one [`crate::HoldConfirmed`] is sent. Letting
/// go early (or the pointer leaving, or focus moving) confirms nothing and the bar unwinds four
/// times as fast as it filled; a new press resumes from where it stands.
///
/// It is a [`button`] to the skin and sends no [`crate::Activate`]: observe
/// [`crate::HoldConfirmed`]. A hold is a motor barrier (XAG 107), so the player can shorten it or
/// replace it with a tap through [`crate::HoldSettings`], and a screen reader's Click confirms at
/// once. Put what the button does in its label ("Hold to delete"): the bar is the only sign.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     hold_button("Hold to delete save", 1.2),
///     observe(|_: On<HoldConfirmed>| info!("deleted")),
/// ));
/// # }
/// ```
pub fn hold_button(text: impl Into<String>, seconds: f32) -> impl Bundle {
    (
        Node {
            flex_direction: FlexDirection::Column,
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        HoldToConfirm { seconds },
        Role::Button,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        bevy::a11y::AccessibilityNode(accesskit::Node::new(accesskit::Role::Button)),
        observe(hold_on_press),
        observe(hold_on_release),
        observe(hold_on_drag_end),
        observe(hold_on_cancel),
        children![
            (Text::new(text), Role::ButtonText),
            (
                Node::default(),
                Role::HoldTrack,
                children![(Node::default(), Role::HoldFill)]
            )
        ],
    )
}

/// A HUD meter (health, stamina, progress): a framed track with a fill `value / max` of its length.
/// The frame marks the whole length against the panel; the fill sits one border inside it, with
/// concentric rounded corners. It is [`crate::GooeySkin::meter_height`] high times the text scale,
/// so it grows with the player's size option. Change its [`Meter`] component to move it: a loss
/// drops the fill at once and leaves the lost length behind it, in the skin's danger colour, for
/// a moment before it drains; a gain eases up ([`crate::MotionSettings::off`] makes both instant).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(meter(75.0, 100.0));
/// # }
/// ```
pub fn meter(value: f32, max: f32) -> impl Bundle {
    (
        Node::default(),
        Role::Meter,
        Meter { value, max },
        children![
            (
                Node {
                    width: Val::Percent(meter_fraction(value, max) * 100.0),
                    height: Val::Percent(100.0),
                    ..default()
                },
                // Over the trail, which starts at the bar's left edge and shows only past the fill.
                ZIndex(1),
                Role::MeterFill
            ),
            (
                Node {
                    width: Val::Percent(0.0),
                    height: Val::Percent(100.0),
                    ..default()
                },
                Role::MeterTrail
            )
        ],
    )
}

/// Work that takes ten seconds or more (a save, a bake, a download): a track like a meter's with
/// its fill `fraction` of the length (clamped to `0.0..=1.0`; anything else is reported once, see
/// [`crate::ProgressClamped`]) and, under it, the words of its [`crate::ProgressText`]: which step
/// of how many and about how long is left, "3 of 7: Measuring meshes, about 20 s left". Change its
/// [`crate::Progress`] to move it; edit the `ProgressText` in place.
///
/// Pick the indicator by how long the work takes (Nielsen's response-time limits): under about a
/// second nothing, a [`spinner`] for two to ten seconds, this for ten and more. There is no static
/// variant.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     progress(3.0 / 7.0),
///     ProgressText {
///         step: Some((3, 7, "Measuring meshes".into())),
///         eta_seconds: Some(20.0),
///     },
/// ));
/// # }
/// ```
pub fn progress(fraction: f32) -> impl Bundle {
    (
        Node {
            flex_direction: FlexDirection::Column,
            ..default()
        },
        Role::Progress,
        Progress(fraction),
        children![
            (
                Node::default(),
                Role::Meter,
                children![(
                    Node {
                        width: Val::Percent(meter_fraction(fraction, 1.0) * 100.0),
                        height: Val::Percent(100.0),
                        ..default()
                    },
                    Role::MeterFill
                )],
            ),
            (
                // No width of its own and the bar's width as its least: the words never decide
                // how wide the bar is, so it keeps its size as they change, and a long line
                // wraps inside it.
                Node {
                    display: Display::None,
                    width: Val::Px(0.0),
                    min_width: Val::Percent(100.0),
                    ..default()
                },
                Text::new(String::new()),
                Role::ProgressLine,
            ),
        ],
    )
}

/// Work whose length is not known, or that takes two to ten seconds: a ring with one lit quarter
/// turning once every [`crate::model::SPINNER_PERIOD_SECS`] on real time, so it keeps turning
/// while the game is paused. For ten seconds and more use a [`progress`]; there is no static
/// variant.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(spinner());
/// # }
/// ```
pub fn spinner() -> impl Bundle {
    (Node::default(), Role::Spinner, Spinner)
}

/// A small image the skin sizes and tints: `source` is the host's own art, a whole image or one
/// cell of an atlas. It is a step of the skin's [`crate::GooeySkin::type_scale`] square (the
/// body's line by default, [`crate::IconSize`]), so it is as tall as the text beside it at any text
/// size, and tinted by its [`crate::IconTone`]: the image is multiplied by a colour of the skin,
/// so draw it white on transparent. Inside a [`button`] it follows the button's state as the text
/// does. An image that is missing draws an empty box of the right size and reports once
/// ([`crate::IconMissing`]).
///
/// An icon takes no input and no focus, so a click on one lands on the button it is in. Put a
/// visible label beside it: an icon alone is a guess.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands, assets: Res<AssetServer>) {
/// let delete = commands.spawn(button("Delete")).id();
/// commands.spawn((
///     icon(IconSource::Image(assets.load("trash.png"))),
///     IconTone::Danger,
///     ChildOf(delete),
/// ));
/// # }
/// ```
pub fn icon(source: IconSource) -> impl Bundle {
    (Node::default(), Role::Icon, Icon(source), Pickable::IGNORE)
}

/// A switch for an option that takes effect the moment it flips (Fullscreen, Subtitles): a row with
/// the label on the left and a framed track with a sliding knob on the right. It is Bevy's headless
/// [`bevy::ui_widgets::Checkbox`], so a click anywhere on the row, Enter, Space and the pad's South
/// button flip it, and Tab, the arrows and the D-pad reach it. It keeps its own state, [`Checked`]
/// on the entity; observe `ValueChange<bool>` on it to apply the setting. The knob's place says
/// whether it is on, so the state survives a colour-blind player; the label never changes with it.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     toggle("Subtitles", true),
///     observe(|change: On<ValueChange<bool>>| info!("subtitles: {}", change.value)),
/// ));
/// # }
/// ```
pub fn toggle(label: impl Into<String>, on: bool) -> impl Bundle {
    (
        Node {
            justify_content: JustifyContent::SpaceBetween,
            align_items: AlignItems::Center,
            ..default()
        },
        Checkbox,
        StartsOn(on),
        Role::Toggle,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        observe(checkbox_self_update),
        children![
            (Text::new(label), ONE_LINE, Role::ControlText),
            (
                Node {
                    align_items: AlignItems::Center,
                    ..default()
                },
                Role::ToggleTrack,
                children![(Node::default(), Role::ToggleKnob)],
            ),
        ],
    )
}

/// A slider for a value the player scrubs (volume, brightness, sensitivity): a row with the label
/// and the value on one line and a rail under them with a thumb on it. It is Bevy's headless
/// [`bevy::ui_widgets::Slider`], and the whole row is the target: a click anywhere on it puts the
/// thumb under the pointer and a drag goes on from there. With it focused, Left and Right (keys or
/// the D-pad, held to repeat) step the value by a twentieth of the range, Home and End jump to the
/// ends, and Up and Down still move focus on, so one press is enough on a pad.
///
/// The value reads as a percentage for a range of 0 to 1 and as the number otherwise
/// ([`crate::slider_text`]). It keeps its own value, [`SliderValue`] on the entity; observe
/// `ValueChange<f32>` on it to apply the setting as it changes (`is_final` is false while a drag is
/// going). To step by something else, insert a [`SliderStep`] after spawning.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     slider("Music", 0.7, 0.0..=1.0),
///     observe(|change: On<ValueChange<f32>>| info!("music: {}", change.value)),
/// ));
/// # }
/// ```
pub fn slider(label: impl Into<String>, value: f32, range: RangeInclusive<f32>) -> impl Bundle {
    let (min, max) = range.into_inner();
    let fraction = slider_fraction(value, min, max);
    (
        Node {
            flex_direction: FlexDirection::Column,
            ..default()
        },
        Slider {
            track_click: TrackClick::Snap,
            orientation: SliderOrientation::Horizontal,
        },
        SliderValue(value),
        SliderRange::new(min, max),
        SliderStep((max - min) / SLIDER_STEPS),
        Role::Slider,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        observe(slider_self_update),
        children![
            (
                Node {
                    justify_content: JustifyContent::SpaceBetween,
                    align_items: AlignItems::Center,
                    ..default()
                },
                Role::SliderHeader,
                children![
                    (Text::new(label), ONE_LINE, Role::ControlText),
                    (
                        Text::new(slider_text(value, min, max)),
                        ONE_LINE,
                        Role::SliderReadout
                    ),
                ],
            ),
            (
                Node {
                    align_items: AlignItems::Center,
                    ..default()
                },
                Role::SliderTrack,
                children![
                    (
                        Node {
                            position_type: PositionType::Absolute,
                            ..default()
                        },
                        Role::SliderRail,
                        children![(
                            Node {
                                width: Val::Percent(fraction * 100.0),
                                height: Val::Percent(100.0),
                                ..default()
                            },
                            Role::SliderFill,
                        )],
                    ),
                    (
                        Node {
                            flex_grow: fraction,
                            ..default()
                        },
                        Role::SliderGap,
                    ),
                    (Node::default(), Role::SliderThumb, SliderThumb),
                ],
            ),
        ],
    )
}

/// A choice for a setting that takes one of a few named values (Low, Medium, High; Easy, Normal,
/// Hard): a row with the label on the left and the selected option on the right between two
/// arrows. It is Bevy's headless [`bevy::ui_widgets::Button`] with a state, so Tab, the arrows and
/// the D-pad reach it, and with it focused Left and Right (keys or the D-pad, held to repeat) step
/// to the previous and next option and stop at the ends, Home and End jump to the first and last,
/// and Up and Down still move focus on, so a pad steps a column of settings with no mode to enter.
/// A click on an arrow steps once, and Enter, Space, the pad's South button and a click anywhere
/// else on the row cycle to the next option, wrapping from the last to the first, so every option is
/// reachable by one repeated press. The arrow that cannot step is dimmed.
///
/// Every option takes the same room, the widest's, so stepping never moves the arrows under the
/// player's thumb. It keeps its own state, [`ChoiceValue`] on the entity (the index of the
/// selected option); observe `ValueChange<usize>` on it to apply the setting when it changes.
/// Observe that, not `Activate`: only a cycle is an `Activate`, a step is not. A `selected` past the
/// last option reads as the last.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     choice("Quality", ["Low", "Medium", "High"], 1),
///     observe(|change: On<ValueChange<usize>>| info!("quality: option {}", change.value)),
/// ));
/// # }
/// ```
pub fn choice<S: Into<String>>(
    label: impl Into<String>,
    options: impl IntoIterator<Item = S>,
    selected: usize,
) -> impl Bundle {
    let options: Vec<String> = options.into_iter().map(Into::into).collect();
    let count = options.len();
    let selected = selected.min(count.saturating_sub(1));
    (
        Node {
            justify_content: JustifyContent::SpaceBetween,
            align_items: AlignItems::Center,
            ..default()
        },
        bevy::ui_widgets::Button,
        ChoiceValue(selected),
        ChoiceCount(count),
        Role::Choice,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        observe(choice_self_update),
        observe(choice_on_move),
        observe(choice_on_activate),
        observe(choice_on_key_input),
        children![
            (
                Text::new(label),
                ONE_LINE,
                Role::ControlText,
                Pickable::IGNORE
            ),
            (
                Node {
                    align_items: AlignItems::Center,
                    ..default()
                },
                Pickable::IGNORE,
                children![
                    choice_arrow(-1),
                    (
                        Node {
                            display: Display::Grid,
                            align_items: AlignItems::Center,
                            ..default()
                        },
                        Role::ChoiceCell,
                        Pickable::IGNORE,
                        Children::spawn(SpawnIter(options.into_iter().enumerate().map(
                            move |(index, text)| {
                                (
                                    Node {
                                        grid_row: GridPlacement::start(1),
                                        grid_column: GridPlacement::start(1),
                                        justify_self: JustifySelf::Center,
                                        ..default()
                                    },
                                    Text::new(text),
                                    ONE_LINE,
                                    Role::ChoiceOption,
                                    Pickable::IGNORE,
                                    if index == selected {
                                        Visibility::Inherited
                                    } else {
                                        Visibility::Hidden
                                    },
                                )
                            },
                        ))),
                    ),
                    choice_arrow(1),
                ],
            ),
        ],
    )
}

/// One of the options screen's rows for the settings this crate itself reads: a [`choice`] over
/// the steps of `kind`, which edits one field of its resource and shows it.
fn option_row(kind: OptionRow, label: impl Into<String>) -> impl Bundle {
    (
        choice(label, kind.options(), 0),
        kind,
        observe(option_on_change),
    )
}

/// The player's **text size**: a [`choice`] row over 100%, 125%, 150% and 200%
/// ([`TEXT_SIZE_STEPS`](crate::TEXT_SIZE_STEPS)) that sets
/// [`GooeySkin::text_scale`](crate::GooeySkin::text_scale), so every
/// heading, label, button, dialog, toast and legend grows the frame the player steps it (WCAG 2.2 SC
/// 1.4.4 and Xbox Accessibility Guideline 101 ask for 200%). `label` is the row's name, in the
/// host's language.
///
/// The skin is the one place the setting lives. The row moves to the step nearest the skin's
/// `text_scale` the frame it is spawned and whenever the skin changes, with no
/// [`ValueChange`](crate::ValueChange), so a
/// loaded save shows on it; a value between two steps shows the nearest and is left alone until
/// the player steps. A player's step writes `text_scale` and no other field. It is a [`choice`] in
/// every other way: it takes `Tooltip`, `InteractionDisabled` and a game's own
/// `ValueChange<usize>` observer (the index into `TEXT_SIZE_STEPS`), and a game that wants other
/// steps writes a `choice` and its own observer. Needs [`GooeyStylePlugin`](crate::GooeyStylePlugin).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((panel(), children![heading("Display"), text_size("Text size")]));
/// # }
/// ```
pub fn text_size(label: impl Into<String>) -> impl Bundle {
    option_row(OptionRow::TextSize, label)
}

/// The player's **interface size**: a [`choice`] row over 75%, 100%, 125% and 150%
/// ([`INTERFACE_SIZE_STEPS`](crate::INTERFACE_SIZE_STEPS)) that sets
/// [`UiScaleSettings::scale`](crate::UiScaleSettings::scale),
/// which enlarges everything, where [`text_size`] enlarges text alone: on top of the window's own
/// share, so 125% is 1.25 times what the window would draw. `label` is the row's name, in the host's
/// language.
///
/// It behaves as [`text_size`] does: the scale is the one place the setting lives, the row follows
/// it with no event, and a step writes `scale` and nothing else (not `reference_short_side`).
/// Needs [`GooeyStylePlugin`](crate::GooeyStylePlugin) for the row and
/// [`GooeyScalePlugin`](crate::GooeyScalePlugin) for the setting; without the second the row steps
/// and nothing is drawn differently.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((panel(), children![heading("Display"), interface_size("Interface size")]));
/// # }
/// ```
pub fn interface_size(label: impl Into<String>) -> impl Bundle {
    option_row(OptionRow::InterfaceSize, label)
}

/// The player's **controller**: a [`choice`] row over Xbox, PlayStation and Switch
/// ([`PAD_STYLES`](crate::PAD_STYLES)) that sets
/// [`BindingSettings::pad_style`](crate::BindingSettings::pad_style), so every
/// [`binding`] row and [`prompts`] legend names a pad's buttons as the player's controller prints
/// them ("A" or "Cross", "B" or "Circle"). `label` is the row's name, in the host's language; the
/// options are the makers' names. The crate does not detect a pad's make: the setting starts at the
/// host's [`BindingSettings`](crate::BindingSettings) (Xbox by default) and this row is how the
/// player changes it.
///
/// It behaves as [`text_size`] does: the resource is the one place the setting lives, the row
/// follows it with no event, and a step writes `pad_style` and nothing else.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((panel(), children![heading("Controls"), pad_style("Controller")]));
/// # }
/// ```
pub fn pad_style(label: impl Into<String>) -> impl Bundle {
    option_row(OptionRow::PadStyle, label)
}

/// The player's **theme**: a [`choice`] row over Dark, Parchment, High contrast and Tool
/// ([`SkinPreset::ALL`](crate::SkinPreset::ALL)) that sets the colours of
/// [`GooeySkin`](crate::GooeySkin), so the whole interface changes look in the frame the player
/// steps it, and the high-contrast one holds every colour to 7:1 ([`GooeySkin::high_contrast`](crate::GooeySkin::high_contrast);
/// Xbox Accessibility Guideline 102 asks a game for such a mode). `label` is the row's name, in the
/// host's language; the options are English words ([`SkinPreset::name`](crate::SkinPreset::name)),
/// and a host that localises writes a `choice` over its own strings with
/// [`SkinPreset::ALL`](crate::SkinPreset::ALL) and
/// [`GooeySkin::with_colours_of`](crate::GooeySkin::with_colours_of).
///
/// It behaves as [`text_size`] does: the skin is the one place the setting lives, the row follows it
/// with no event (the preset whose colours are nearest, so a skin the game tuned shows the nearest
/// and is left alone until the player steps), and a step writes the colours and no other field: the
/// player's text size, and a game's own gap and padding, stay as they were. A game that starts in
/// high contrast because the platform asks inserts `GooeySkin::high_contrast()` and the row shows it.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((panel(), children![heading("Display"), skin_preset("Theme")]));
/// # }
/// ```
pub fn skin_preset(label: impl Into<String>) -> impl Bundle {
    option_row(OptionRow::SkinPreset, label)
}

/// One of a choice's two arrows: a target as wide as a button, with the chevron drawn in it. The
/// chevron is a square with two borders turned an eighth of a turn, so it is a line of the skin's
/// weight and not a glyph the host's font may lack; it is moved by the share of its own width that
/// puts its ink, not its square, in the middle of the target.
fn choice_arrow(step: i32) -> impl Bundle {
    let (mark, shift) = if step < 0 {
        (Role::ChoiceBack, CHEVRON_INK_SHIFT)
    } else {
        (Role::ChoiceForward, -CHEVRON_INK_SHIFT)
    };
    (
        Node {
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        Role::ChoiceArrow,
        StepBy(step),
        Hovered::default(),
        observe(arrow_on_press),
        observe(arrow_on_click),
        children![(
            Node::default(),
            UiTransform {
                translation: Val2::percent(shift, 0.0),
                rotation: Rot2::degrees(45.0),
                ..default()
            },
            mark,
            Pickable::IGNORE,
        )],
    )
}

/// How far from the middle of a [`radial`] the items stand, as a share of its width: 36%, which
/// keeps an item of eight characters at the side of the ring inside the disc's edge.
const RADIAL_RING_FRACTION: f32 = 0.36;

/// A **radial menu**: a weapon wheel, an emote wheel, a build menu. The items stand on a ring
/// round a disc, item 0 at the top and the rest clockwise, and the player points at one and
/// chooses it. With a pad, push a stick (either one) toward the item, and press South; with a
/// pointer, move over the item's side of the disc and click, the whole wedge being the target; with
/// a keyboard, step with the arrows (Right and Down forward, Left and Up back, wrapping round),
/// Home and End, and press Enter or Space. The highlighted item is lit and its name is read in
/// the middle of the disc, where the thumb is. A stick that is only brushed, or a pointer in the
/// middle, leaves the highlight where it is.
///
/// It is Bevy's headless [`bevy::ui_widgets::Button`] and a tab stop, so a game that opens it for
/// the player gives it focus (`AutoFocus`). It keeps its state in [`RadialValue`] (the highlighted
/// item) and sends `ValueChange<usize>`: with `is_final: false` as the highlight moves, and with
/// `is_final: true` for the item chosen, even when the highlight did not move. Apply the choice on
/// the final one. To choose when a hold button is let go ("release to select"), trigger `Activate`
/// on the radial then. The disc is [`Role::Radial`] and 26 text sizes across, so it grows with
/// [`GooeySkin::text_scale`](crate::GooeySkin::text_scale); three to eight short labels read best.
/// An item is a name, or a [`RadialItem`] with a picture to draw in its place (the name is then
/// read in the middle). Name the wheel for a screen reader with `AccessibleLabel`.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     radial(["Pistol", "Rifle", "Shotgun", "Grenade"], 0),
///     observe(|change: On<ValueChange<usize>>| {
///         if change.is_final {
///             info!("equip item {}", change.value);
///         }
///     }),
/// ));
/// # }
/// ```
pub fn radial<I: Into<RadialItem>>(
    items: impl IntoIterator<Item = I>,
    selected: usize,
) -> impl Bundle {
    let items: Vec<RadialItem> = items.into_iter().map(Into::into).collect();
    let count = items.len();
    let selected = selected.min(count.saturating_sub(1));
    let name = items
        .get(selected)
        .map(|item| item.label.clone())
        .unwrap_or_default();
    let middle = |ring: f32, (x, y): (f32, f32)| Node {
        position_type: PositionType::Absolute,
        left: Val::Percent(50.0 + x * ring * 100.0),
        top: Val::Percent(50.0 - y * ring * 100.0),
        ..default()
    };
    let pull_back = UiTransform {
        translation: Val2::percent(-50.0, -50.0),
        ..default()
    };
    (
        Node::default(),
        bevy::ui_widgets::Button,
        RadialValue(selected),
        RadialCount(count),
        Role::Radial,
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        observe(radial_self_update),
        observe(radial_on_activate),
        observe(radial_on_key_input),
        observe(radial_on_pointer_move),
        observe(radial_on_press),
        Children::spawn((
            Spawn((
                Node {
                    position_type: PositionType::Absolute,
                    left: Val::Percent(50.0),
                    top: Val::Percent(50.0),
                    width: Val::Percent(RADIAL_RING_FRACTION * 200.0),
                    height: Val::Percent(RADIAL_RING_FRACTION * 200.0),
                    ..default()
                },
                pull_back,
                Role::RadialTrack,
                Pickable::IGNORE,
            )),
            SpawnIter(items.into_iter().enumerate().map(move |(index, item)| {
                let RadialItem { label, icon } = item;
                (
                    middle(RADIAL_RING_FRACTION, radial_place(index, count)),
                    pull_back,
                    Role::RadialSlot,
                    RadialSlot(index, label.clone()),
                    Pickable::IGNORE,
                    Children::spawn(SpawnWith(move |slot: &mut RelatedSpawner<ChildOf>| {
                        match icon {
                            Some(source) => slot.spawn((
                                Node::default(),
                                Role::RadialIcon,
                                Icon(source),
                                Pickable::IGNORE,
                            )),
                            None => slot.spawn((
                                Text::new(label),
                                ONE_LINE,
                                Role::RadialText,
                                Pickable::IGNORE,
                            )),
                        };
                    })),
                )
            })),
            Spawn((
                middle(0.0, (0.0, 0.0)),
                pull_back,
                Text::new(name),
                ONE_LINE,
                Role::RadialCentre,
                Pickable::IGNORE,
            )),
        )),
    )
}

/// An inventory: a grid of square slots, `columns` to a row, each holding an item or empty
/// (`None`), in reading order. A backpack, a hotbar, a chest, a shop shelf. The contents are data,
/// [`SlotItems`] on the root: change it and the grid follows in the same frame, however many
/// slots it has. A [`Slot`] is an item's name, its picture, its count and a tooltip line; a slot
/// with a picture draws it (tinted by the skin, so draw it white on transparent) and one without
/// draws its name, and a count above one sits in the corner.
///
/// Every slot is a real widget: Bevy's headless [`bevy::ui_widgets::Button`] with a focus ring and
/// a tooltip. The grid is one tab stop ([`SlotCursor`](crate::SlotCursor): Tab enters on the slot the player last had
/// and leaves on the next press), the arrows and the D-pad walk it, Home and End go to the ends of
/// the row and with Ctrl of the grid. Choosing a slot (Enter, Space, South or a click) sends one
/// `ValueChange<usize>` with `is_final: true` on the grid, empty or not; moving focus onto a slot
/// sends one with `is_final: false`.
///
/// Moving an item is the crate's own drag and drop: the pointer drags a filled slot onto any
/// slot (of this grid or another), and the keyboard and gamepad lift, steer and drop it
/// ([`DragSettings`](crate::DragSettings)). The drop is one [`SlotMoved`](crate::SlotMoved) on the target grid; [`SlotMoved::apply`](crate::SlotMoved::apply)
/// swaps the two slots, which is all a game with no rules needs. A slot is
/// [`GooeySkin::text_size`](crate::GooeySkin::text_size) times four square, so it follows the
/// player's text size. Wrap it in a [`list`] to scroll a long one.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands
///     .spawn(slot_grid(
///         5,
///         [
///             Some(Slot::new("Sword")),
///             Some(Slot::new("Arrows").count(24)),
///             None,
///             None,
///             None,
///         ],
///     ))
///     .observe(|moved: On<SlotMoved>, mut grids: Query<&mut SlotItems>| {
///         moved.apply(&mut grids);
///     })
///     .observe(|chosen: On<ValueChange<usize>>| {
///         if chosen.is_final {
///             info!("use slot {}", chosen.value);
///         }
///     });
/// # }
/// ```
pub fn slot_grid(columns: usize, items: impl IntoIterator<Item = Option<Slot>>) -> impl Bundle {
    let columns = columns.max(1);
    (
        Node {
            display: Display::Grid,
            grid_template_columns: RepeatedGridTrack::auto(columns as u16),
            ..default()
        },
        Role::SlotGrid,
        SlotGrid { columns },
        SlotItems(items.into_iter().collect()),
    )
}

/// A row that rebinds one action: the action's name on the left and a keycap on the right showing
/// the key, mouse button or pad button it is bound to ("Space", "Right Click", "A"). It is Bevy's
/// headless [`bevy::ui_widgets::Button`], so Tab, the arrows and the D-pad reach it, and Enter,
/// Space, the pad's South button or a click start a capture: the keycap lights and says what it
/// waits for, and the player's next press is the new binding. A key row hears any key or mouse
/// button (the primary one too: the pointer cannot press anything while a row waits), and a pad row
/// any pad button; Escape (and, on a pad row, Start) exits without binding, and cannot be bound
/// (see [`crate::BindingSettings`]). While a row waits nothing else hears the player: arrows,
/// Tab, the D-pad and Back move and close nothing.
///
/// The row keeps its state in [`BindingValue`] and sends `ValueChange<Binding>` once for each
/// change; observe that to store the player's choice. Pressing the input the row already holds ends
/// the capture with no change. Which action an input belongs to, and what to do when two actions
/// share one, is the game's: [`Binding`] is `Eq + Hash`, and setting another row's [`BindingValue`]
/// swaps. The row never changes size, waiting or not.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     binding("Jump", Binding::Key(KeyCode::Space)),
///     observe(|change: On<ValueChange<Binding>>| info!("jump is now {:?}", change.value)),
/// ));
/// # }
/// ```
pub fn binding(label: impl Into<String>, value: Binding) -> impl Bundle {
    let part = |text: String, role: Role, visibility: Visibility| {
        (
            Node {
                grid_row: GridPlacement::start(1),
                grid_column: GridPlacement::start(1),
                justify_self: JustifySelf::Center,
                ..default()
            },
            Text::new(text),
            ONE_LINE,
            role,
            visibility,
            Pickable::IGNORE,
        )
    };
    (
        Node {
            justify_content: JustifyContent::SpaceBetween,
            align_items: AlignItems::Center,
            ..default()
        },
        bevy::ui_widgets::Button,
        BindingValue(value),
        Role::Binding,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        observe(binding_self_update),
        observe(binding_on_activate),
        observe(binding_on_key_input),
        children![
            (
                Text::new(label),
                ONE_LINE,
                Role::ControlText,
                Pickable::IGNORE
            ),
            (
                Node {
                    display: Display::Grid,
                    align_items: AlignItems::Center,
                    ..default()
                },
                Role::BindingCap,
                Pickable::IGNORE,
                // Both texts stand in the one cell, the name and the prompt, so the keycap is as
                // wide as the wider; `update_bindings` fills them and shows one.
                children![
                    part(
                        value.label(PadStyle::default()),
                        Role::BindingText,
                        Visibility::Inherited
                    ),
                    part(String::new(), Role::BindingPrompt, Visibility::Hidden),
                ],
            ),
        ],
    )
}

/// A row for a line of text the player types (a name, a seed, a server address): the label on the
/// left, outside the field and always visible, and a framed field on the right that holds 16
/// characters, and the caret's room, at the body size and scrolls past that, so the row never
/// changes size while the player types. The field is Bevy's headless `TextInput`, so it has a
/// caret, selection, copy and paste and the platform's input methods; a click on the field, the
/// label or the row's padding focuses it, and a focused field takes the keys at once, with no step
/// to begin typing.
///
/// Left, Right, Home and End are the caret's; Up, Down and Tab leave the field, and so does the
/// D-pad (a pad cannot type: the platform's keyboard types through the same key events, and a
/// host opens it when [`TextEditing`](crate::TextEditing) is added to the row). Escape ends the
/// edit and, inside a [`dialog`], is Back as everywhere ([`Cancel`](crate::Cancel)). A field's
/// frame stays lit while it holds focus, even after a pointer press hid every other ring.
///
/// The row keeps its state in [`TextInputValue`] and sends `ValueChange<String>` for each edit
/// that changes the text (`is_final` is false), and once more with `is_final` when the edit ends:
/// Enter (a submit, even with nothing changed) or focus leaving the field after a change. Add
/// [`TextHint`](crate::TextHint) for muted words while the field is empty and
/// [`TextLimit`](crate::TextLimit) for a most characters, on the row:
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     text_input("Name", ""),
///     TextHint("Enter a name".into()),
///     TextLimit(16),
///     observe(|change: On<ValueChange<String>>| {
///         if change.is_final {
///             info!("the player is called {}", change.value);
///         }
///     }),
/// ));
/// # }
/// ```
pub fn text_input(label: impl Into<String>, value: impl Into<String>) -> impl Bundle {
    text_row(Some(label.into()), value.into(), Some(TEXT_INPUT_CHARS))
}

/// A frame for what the host draws itself (a 3D view, a map, a canvas): it fills the room its
/// parent leaves, is a tab stop, shows the focus ring while it has focus, and is a
/// [`FocusRegion::host`]: with focus in it the arrow keys are the host's (read them from
/// `ButtonInput<KeyCode>`), Tab and F6 still leave, so the keyboard is never trapped. Put what
/// draws into it (a `ViewportNode`, an image) as children or on the entity itself, and
/// `.insert(DropTarget::<T>::new())` makes it a place pieces are dropped.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// fn pan(keys: Res<ButtonInput<KeyCode>>, focus: Res<bevy::input_focus::InputFocus>, view: Single<Entity, With<Role>>) {
///     // Read the arrows when the viewport has focus; gooey moves no focus meanwhile.
///     if focus.get() == Some(*view) && keys.pressed(KeyCode::ArrowLeft) {
///         // pan left
///     }
/// }
/// # fn setup(mut commands: Commands) { commands.spawn(viewport()); }
/// ```
pub fn viewport() -> impl Bundle {
    (
        Node {
            flex_grow: 1.0,
            align_self: AlignSelf::Stretch,
            ..default()
        },
        Role::Viewport,
        FocusRegion::host(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
    )
}

/// A row with a text field several lines high: the label over a framed field that wraps its
/// words at its width and scrolls past `rows` lines, for notes and descriptions. It is a
/// [`text_input`] in every other way: [`crate::TextInputValue`] is the text, a game's write shows in
/// the same frame with no event, [`crate::TextHint`], [`crate::TextLimit`] (a paste is cut at it),
/// [`crate::FieldProblem`] and [`crate::TextEditing`] go on the row, and every edit is one
/// [`ValueChange<String>`](bevy::ui_widgets::ValueChange) on it.
///
/// **Enter adds a line** and Up and Down move the caret between lines. **Ctrl+Enter or Cmd+Enter
/// ends the edit**: one final change with the text, the field kept. Tab, and Escape, leave the
/// field as in a [`text_input`] (it never traps the keyboard); a pad's D-pad moves focus off it.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn setup(mut commands: Commands) {
/// commands.spawn((
///     text_area("Notes", "", 5),
///     TextLimit(500),
///     observe(|change: On<ValueChange<String>>| {
///         if change.is_final {
///             info!("saved {} characters", change.value.chars().count());
///         }
///     }),
/// ));
/// # }
/// ```
pub fn text_area(label: impl Into<String>, value: impl Into<String>, rows: usize) -> impl Bundle {
    text_row_as(
        Role::TextArea,
        Some(label.into()),
        value.into(),
        Some(TEXT_AREA_CHARS),
        RowKind::Area(rows.max(1)),
    )
}

/// The row under [`text_input`]: a label if it has one and the field, which is `chars` character
/// advances wide, or fills the room its parent leaves when `chars` is `None` (a command palette's
/// field has no label and the card's whole width).
pub(crate) fn text_row(label: Option<String>, value: String, chars: Option<f32>) -> impl Bundle {
    let role = if chars.is_none() {
        Role::PaletteField
    } else {
        Role::TextInput
    };
    text_row_as(role, label, value, chars, RowKind::Text)
}

/// What a text row is for: text, a number (Up and Down step its field and the text cursor is over
/// it, so the row's own resize cursor, the scrub's, is on its label and padding only) or a colour
/// (a swatch between the label and the field, and Escape puts the colour's text back).
#[derive(Clone, Copy)]
enum RowKind {
    Text,
    /// A field `usize` lines high: Enter adds a line.
    Area(usize),
    Number,
    Colour(Srgba),
}

/// [`text_row`] with its row's `role` and what it is `kind` of row.
fn text_row_as(
    role: Role,
    label: Option<String>,
    value: String,
    chars: Option<f32>,
    kind: RowKind,
) -> impl Bundle {
    let fills = chars.is_none();
    let area = matches!(kind, RowKind::Area(_));
    (
        Node {
            flex_direction: if area {
                FlexDirection::Column
            } else {
                FlexDirection::Row
            },
            justify_content: if area {
                JustifyContent::FlexStart
            } else {
                JustifyContent::SpaceBetween
            },
            align_items: if area {
                AlignItems::Stretch
            } else {
                AlignItems::Center
            },
            width: if fills {
                Val::Percent(100.0)
            } else {
                Val::Auto
            },
            ..default()
        },
        role,
        TextInputValue(value.clone()),
        observe(text_self_update),
        observe(text_row_on_acquire),
        Children::spawn(SpawnWith(move |row: &mut RelatedSpawner<ChildOf>| {
            let root = row.target_entity();
            if let Some(label) = label {
                row.spawn((
                    Text::new(label),
                    ONE_LINE,
                    Role::ControlText,
                    Pickable::IGNORE,
                ));
            }
            if let RowKind::Colour(colour) = kind {
                row.spawn(color_swatch(root, colour));
            }
            row.spawn((
                Node {
                    flex_grow: if fills { 1.0 } else { 0.0 },
                    ..default()
                },
                Role::TextCell,
            ))
            .with_children(|cell| {
                let mut field = cell.spawn((
                    Node {
                        flex_shrink: 0.0,
                        flex_grow: if fills { 1.0 } else { 0.0 },
                        overflow: Overflow::clip(),
                        ..default()
                    },
                    TextInput,
                    EditableText {
                        visible_width: chars,
                        visible_lines: match kind {
                            RowKind::Area(rows) => Some(rows as f32),
                            _ => Some(1.0),
                        },
                        allow_newlines: area,
                        cursor_width: TEXT_CARET_WIDTH,
                        ..EditableText::new(&value)
                    },
                    if area {
                        TextLayout::default()
                    } else {
                        TextLayout::no_wrap()
                    },
                    TextCursorStyle::default(),
                    Role::TextField,
                    TextInputOf(root),
                    Hovered::default(),
                    TabIndex(0),
                    AutoDirectionalNavigation::default(),
                    observe(text_on_key_input),
                ));
                match kind {
                    RowKind::Text => {}
                    RowKind::Area(_) => {
                        field.insert(AreaField);
                    }
                    RowKind::Number => {
                        field.insert((
                            NumberInput,
                            SelectAllOnFocus,
                            EntityCursor::System(SystemCursorIcon::Text),
                            observe(number_on_key_input),
                            observe(number_on_step),
                        ));
                    }
                    RowKind::Colour(_) => {
                        field.insert((SelectAllOnFocus, observe(color_on_key_input)));
                    }
                }
                cell.spawn((
                    Node {
                        position_type: PositionType::Absolute,
                        display: Display::None,
                        overflow: Overflow::clip(),
                        ..default()
                    },
                    Text::new(String::new()),
                    TextLayout::no_wrap(),
                    Role::TextHint,
                    TextInputOf(root),
                    Pickable::IGNORE,
                ));
            });
        })),
    )
}

/// What a number row adds to its text row: the number and how it moves, the hint that shows a
/// mixed value, the scrub (a drag that begins on the row's label or padding) and the observers that
/// turn typing, steps and drags into one [`ValueChange<f32>`].
fn number_parts(value: f32, step: f32, range: RangeInclusive<f32>) -> impl Bundle {
    (
        NumberValue(value),
        NumberStep(step),
        NumberRange {
            min: *range.start(),
            max: *range.end(),
        },
        TextHint(String::new()),
        EntityCursor::System(SystemCursorIcon::ColResize),
        (
            observe(number_self_update),
            observe(number_on_text),
            observe(number_on_drag_start),
            observe(number_on_drag),
            observe(number_on_drag_end),
            observe(number_on_cancel),
        ),
    )
}

/// A row with a number: a label and a framed field the player types a number in, scrubs with a
/// drag and steps with a key or the D-pad. `step` is how far one pixel of drag, one Up or Down
/// press or one D-pad press moves it (and the digits the field shows: 0.1 shows one), and `range`
/// is the least and greatest the player can make it.
///
/// Press on the label (or the row's padding) and drag left or right to scrub: 50 px at a step of
/// 0.1 is 5.0, Shift takes a tenth of that rate and Ctrl ten times it. Click the field and type;
/// Enter, or leaving the field, applies it (a number outside the range is held to its end;
/// anything that is not a number, an expression such as `1.5*2` included, is refused with its
/// reason as a [`NumberRefused`](crate::NumberRefused)); Escape puts the old number back. Up and
/// Down on the focused field step it (Shift ten steps) and Left, Right, Home and End are the
/// caret's; the D-pad's Left and Right step it and its Up and Down move focus; Tab leaves. A
/// drag is never the only way (WCAG 2.5.7): the typed field is the other.
///
/// The row keeps its number in [`NumberValue`] and sends `ValueChange<f32>` for each change the
/// player makes: `is_final` is false while a drag is scrubbing and true when it ends, on Enter,
/// when focus leaves after an edit and for a step. Put [`MixedValue`](crate::MixedValue) on the row
/// for a multi-selection whose members differ: the field is empty and shows a muted
/// [`MIXED_HINT`](crate::MIXED_HINT).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     number_field("Health", 100.0, 0.5, 0.0..=250.0),
///     observe(|change: On<ValueChange<f32>>| {
///         if change.is_final {
///             info!("health is {}", change.value);
///         }
///     }),
/// ));
/// # }
/// ```
pub fn number_field(
    label: impl Into<String>,
    value: f32,
    step: f32,
    range: RangeInclusive<f32>,
) -> impl Bundle {
    (
        text_row_as(
            Role::TextInput,
            Some(label.into()),
            format_number(value, step),
            Some(NUMBER_FIELD_CHARS),
            RowKind::Number,
        ),
        number_parts(value, step, range),
    )
}

/// A row with a label and one [`number_field`] for each of `N` numbers (X, Y, Z and W, then 5, 6 …),
/// as a position or a scale: each component's letter is its scrub handle, and each has the
/// typing, steps, range and refusals of a number field. `step` and `range` are every component's.
///
/// The row keeps its numbers in [`VecValue`](crate::VecValue), and a change the player makes is a
/// [`VecChange`](crate::VecChange) on the row: the component, its new value and the whole vector.
/// For a multi-selection whose members differ in some components, put
/// [`VecMixed`](crate::VecMixed) on the row: those components are empty with a muted
/// [`MIXED_HINT`](crate::MIXED_HINT), and a
/// change to one is for that component only.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     vec_field("Position", [0.0, 1.5, -2.0], 0.1, -1000.0..=1000.0),
///     observe(|change: On<VecChange>| {
///         if change.is_final {
///             info!("position is {:?}", change.values);
///         }
///     }),
/// ));
/// # }
/// ```
pub fn vec_field<const N: usize>(
    label: impl Into<String>,
    values: [f32; N],
    step: f32,
    range: RangeInclusive<f32>,
) -> impl Bundle {
    let label = label.into();
    let (min, max) = (*range.start(), *range.end());
    (
        Node {
            justify_content: JustifyContent::SpaceBetween,
            align_items: AlignItems::Center,
            ..default()
        },
        Role::TextInput,
        VecValue(values.to_vec()),
        NumberStep(step),
        NumberRange { min, max },
        Children::spawn(SpawnWith(move |row: &mut RelatedSpawner<ChildOf>| {
            let root = row.target_entity();
            row.spawn((
                Text::new(label),
                ONE_LINE,
                Role::ControlText,
                Pickable::IGNORE,
            ));
            row.spawn((Node::default(), Role::NumberParts))
                .with_children(|parts| {
                    for (index, value) in values.into_iter().enumerate() {
                        parts.spawn((
                            text_row_as(
                                Role::NumberPart,
                                Some(axis_name(index)),
                                format_number(value, step),
                                Some(VEC_FIELD_CHARS),
                                RowKind::Number,
                            ),
                            number_parts(value, step, min..=max),
                            VecPart { root, index },
                            observe(vec_part_on_change),
                        ));
                    }
                });
        })),
    )
}

/// A row with a colour: a label, a swatch and a framed field showing the colour as hex, which the
/// player types (`#ff8800`, `#f80`, `ff8800`; `#ff880080` with an alpha) or picks. Enter or leaving
/// the field applies what was typed; anything that is not a hex colour is refused with its reason
/// as a [`ColorRefused`](crate::ColorRefused) and the field shows the colour again; Escape puts
/// the old colour back.
///
/// The swatch is a button (Tab, Enter, Space, South or a click): it opens a picker below it and a
/// second press closes it, Escape too. The picker is a saturation and value area (a pointer press
/// and drag, or the arrows, Shift ten times as far) over three strips for hue, brightness and
/// alpha, which are sliders (Left, Right, Home, End and the D-pad); a pad sets the saturation with
/// the D-pad's Left and Right on the area and the rest with the strips. The colour applies as it
/// is picked and there is nothing to confirm. The swatch is split: the colour opaque on the left
/// and at its alpha on the right.
///
/// The row keeps its colour in [`ColorValue`](crate::ColorValue) and sends `ValueChange<Srgba>`
/// for each change the player makes: `is_final` is false while a drag is rolling the colour and
/// true when it ends, on Enter, when focus leaves after an edit and for a key or D-pad step. Put
/// [`MixedValue`](crate::MixedValue) on the row for a multi-selection whose members differ: the
/// field is empty and shows a muted [`MIXED_HINT`](crate::MIXED_HINT).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     color_field("Tint", Srgba::hex("#ff8800").unwrap()),
///     observe(|change: On<ValueChange<Srgba>>| {
///         if change.is_final {
///             info!("tint is {}", hex_text(change.value.to_f32_array()));
///         }
///     }),
/// ));
/// # }
/// ```
pub fn color_field(label: impl Into<String>, value: Srgba) -> impl Bundle {
    (
        text_row_as(
            Role::TextInput,
            Some(label.into()),
            hex_text(value.to_f32_array()),
            Some(COLOR_FIELD_CHARS),
            RowKind::Colour(value),
        ),
        ColorValue(value),
        TextHint(String::new()),
        observe(color_self_update),
        observe(color_on_text),
    )
}

/// The swatch of a [`color_field`]: a button, a target square, split in two halves (the colour
/// opaque and at its alpha). Pressing it opens the picker. The auto margin on its left pushes it
/// and the field to the row's right edge.
fn color_swatch(row: Entity, value: Srgba) -> impl Bundle {
    (
        Node {
            margin: UiRect::left(Val::Auto),
            ..default()
        },
        bevy::ui_widgets::Button,
        Role::ColorSwatch,
        ColorSwatch(row),
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        observe(swatch_on_activate),
        children![
            (
                Node {
                    flex_grow: 1.0,
                    ..default()
                },
                Role::ColorSwatchHalf,
                SwatchHalf { row, alpha: false },
                BackgroundColor(Color::Srgba(value.with_alpha(1.0))),
                Pickable::IGNORE,
            ),
            (
                Node {
                    flex_grow: 1.0,
                    ..default()
                },
                Role::ColorSwatchHalf,
                SwatchHalf { row, alpha: true },
                BackgroundColor(Color::Srgba(value)),
                Pickable::IGNORE,
            ),
        ],
    )
}

/// The letter of a vec field's `index`th component: X, Y, Z, W, and then its number from 5.
fn axis_name(index: usize) -> String {
    match index {
        0 => "X".into(),
        1 => "Y".into(),
        2 => "Z".into(),
        3 => "W".into(),
        n => (n + 1).to_string(),
    }
}

/// One hint of what an input does: a keycap and the words for it ("Esc  Back"). The keycap shows
/// the input of the device the player used last, the keyboard's or the pad's from `keys`, in the
/// words of a [`binding`] row ("Esc", "Enter", "A" or "Cross"), and follows the player the frame
/// they pick up the other ([`InputDevice`](crate::InputDevice)). A key is a rounded keycap and a
/// pad button is fully round, in the same colours.
///
/// The words are yours (the crate has none to translate). [`Prompt::SELECT`] and [`Prompt::BACK`]
/// are the two the crate itself acts on: Enter and the pad's South button select, Escape and the
/// pad's East button send a [`Cancel`](crate::Cancel). For an action of the game's own, build the
/// pair with [`Prompt::new`]. A prompt is a hint, not a control: the pointer goes through it and it
/// is never a tab stop. It stands anywhere; put it in a [`prompts`] legend for the corner of the
/// screen.
///
/// A game that lets the player rebind the action keeps the prompt true by setting the [`Prompt`]
/// component (the keycap follows in the same frame):
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     prompts(),
///     children![
///         prompt("Select", Prompt::SELECT),
///         prompt("Back", Prompt::BACK),
///         prompt(
///             "Inventory",
///             Prompt::new(Binding::Key(KeyCode::KeyI), Binding::Pad(GamepadButton::North)),
///         ),
///     ],
/// ));
/// # }
/// ```
pub fn prompt(label: impl Into<String>, keys: Prompt) -> impl Bundle {
    (
        Node {
            align_items: AlignItems::Center,
            ..default()
        },
        Role::Prompt,
        keys,
        Pickable::IGNORE,
        children![
            (
                // Named for the keyboard's input; `update_prompts` writes the device's.
                Text::new(keys.keyboard.label(PadStyle::default())),
                TextLayout::new(Justify::Center, LineBreak::NoWrap),
                Role::PromptKey,
                Pickable::IGNORE,
            ),
            (Text::new(label), Role::Label, Pickable::IGNORE),
        ],
    )
}

/// The legend of a screen: a slim bar of [`prompt`]s in its parent's bottom-left corner (see
/// [`prompts_at`] for another), 5% in from
/// the edges (the safe area of a television), where Xbox's guideline 112 puts "select" and "back"
/// on every screen, in the same place and order. It is a bar on the skin's panel colour, so its
/// words read over any game world. It is laid out apart from its parent's other children (absolute,
/// so it moves nothing) and is no wider than 90% of its parent: a longer legend squeezes its words
/// and never leaves the window. The pointer goes through it.
///
/// Put it in the full-window node of a screen ([`screen`]) or of a [`dialog`], which stands over the
/// screen's own and shows the hints that apply in the dialog:
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     screen(),
///     children![
///         (panel(), children![heading("Settings"), button("Back")]),
///         (prompts(), children![prompt("Select", Prompt::SELECT), prompt("Back", Prompt::BACK)]),
///     ],
/// ));
/// # }
/// ```
pub fn prompts() -> impl Bundle {
    prompts_at(PromptsAnchor::default())
}

/// A [`prompts`] legend in the corner or at the edge the game chooses: `prompts_at(
/// PromptsAnchor::BottomRight)` for a game whose own HUD holds the bottom-left. Everything else
/// is [`prompts`]'s: 5% in from the edges it touches, no wider than 90% of its parent, nothing
/// else moves. Choose one anchor and use it on every screen and dialog, which is what Xbox's
/// guideline 112 asks. The anchor is a component: insert another and the legend moves.
pub fn prompts_at(anchor: PromptsAnchor) -> impl Bundle {
    (
        Node {
            position_type: PositionType::Absolute,
            align_items: AlignItems::Center,
            ..default()
        },
        Role::Prompts,
        anchor,
        Pickable::IGNORE,
    )
}

/// A column of rows that scrolls when they do not all fit: save slots, an inventory, a key-binding
/// screen, a long settings page. `rows` is how many rows tall it stands, in the units of a button
/// and the gap beside it, so `4.5` shows four rows and half of the fifth, which cuts it, the sign
/// that more is below. The rows are the list's children, in `children![…]`: any widget, each its
/// own tab stop.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     panel(),
///     children![
///         heading("Load game"),
///         list(
///             4.5,
///             children![
///                 button("Meadow, 12:40"),
///                 button("Harbour, 09:15"),
///                 button("Mill, 03:02"),
///                 button("Cellar, 01:48"),
///                 button("Orchard, 00:20"),
///                 button("Autosave"),
///             ]
///         ),
///     ],
/// ));
/// # }
/// ```
///
/// The wheel and a trackpad scroll it, a drag on the thumb moves it and a click on the rail pages a
/// viewport, and it follows focus: moving to a row with a key, the D-pad or Tab scrolls it by the
/// least that leaves the next row whole and the one after it cut in sight, and PageUp, PageDown and
/// the pad's triggers move a viewport at a time. A click on a half-visible row focuses it and does
/// not scroll under the pointer. The rail shows only while the rows do not fit. A list shows every
/// row it holds, so it is for tens of rows, not thousands.
///
/// The entity this returns holds the rows' viewport, a [`ListView`] (its first child), and the
/// rail; to scroll from code, set the `ScrollPosition` on the [`ListView`].
pub fn list<L>(rows: f32, items: SpawnRelatedBundle<ChildOf, L>) -> impl Bundle
where
    L: SpawnableList<ChildOf> + Send + Sync + 'static,
{
    (
        Node {
            flex_direction: FlexDirection::Column,
            ..default()
        },
        Role::List,
        Children::spawn(SpawnWith(move |parent: &mut RelatedSpawner<ChildOf>| {
            let view = parent
                .spawn((
                    Node {
                        display: Display::Block,
                        overflow: Overflow::scroll_y(),
                        ..default()
                    },
                    Role::ListView,
                    ListView { rows },
                    ScrollArea,
                    // The rows sit in one column that never shrinks: a viewport holding them
                    // directly squeezes them to fit its height, down to their `min_height`, and a
                    // button squeezed by a few pixels clips its own text.
                    children![(
                        Node {
                            flex_direction: FlexDirection::Column,
                            flex_shrink: 0.0,
                            ..default()
                        },
                        Role::ListRows,
                        items,
                    )],
                ))
                .id();
            parent.spawn(list_rail(view));
        })),
    )
}

/// A list's rail: the scrollbar down the viewport's right edge. The thumb has no `Node`: Bevy
/// lays it out itself, after layout, from the viewport. The rail is hidden until `update_lists`
/// finds the rows do not fit.
pub(crate) fn list_rail(view: Entity) -> impl Bundle {
    (
        Node {
            position_type: PositionType::Absolute,
            top: Val::Px(0.0),
            bottom: Val::Px(0.0),
            right: Val::Px(0.0),
            display: Display::None,
            ..default()
        },
        Role::ListRail,
        Scrollbar::new(view, ControlOrientation::Vertical, LIST_MIN_THUMB),
        children![(
            Role::ListThumb,
            ScrollbarThumb {
                border_radius: BorderRadius::MAX,
                border: UiRect::ZERO,
            },
            Hovered::default(),
        )],
    )
}

/// A table of ten thousand rows in a dozen entities: a header of `columns` over rows from a
/// [`RowSource`], of which only the rows in view are spawned (the rows in view and one more,
/// whatever the length). A click on a sortable header sorts by the column (the first click
/// ascending, each next one turning it round) and sends [`SortBy`](crate::SortBy); a column's
/// right edge is dragged to size it (Ctrl and Left or Right on its focused header does it 16 px a
/// press, for no drag); a click selects a row (see [`SelectMode`](crate::SelectMode): one by
/// default, `Multi` for Ctrl and Shift) and sends `ValueChange<TableSelection>`
/// ([`TableSelection`](crate::TableSelection)), and a double click or Enter opens it
/// ([`RowActivated`](crate::RowActivated)). Rows change through the [`Table`](crate::Table)
/// component and the player keeps their place.
///
/// The table is one tab stop with a cursor row, like a list box: Up, Down, the Page keys, Home and
/// End (the first and last rows of the data) move it, Space selects it, and the D-pad, the
/// triggers and South do the same on a pad. Every row is a button's height and every cell one
/// line, cut at its column's edge: a row never changes size, which is what lets the table skip the
/// rows it does not draw. It stands [`TableRows`](crate::TableRows) rows tall (8.5 unless the game
/// says) with a rail that shows while there is more.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// let rows: Vec<Vec<String>> = (0..10_000)
///     .map(|i| vec![format!("Item {i}"), format!("{}", i * 7 % 100)])
///     .collect();
/// commands.spawn((
///     panel(),
///     children![(
///         table([Column::new("Name").width(14.0), Column::new("Qty").width(6.0)], rows),
///         SelectMode::Multi,
///         observe(|sort: On<SortBy>| info!("sorted by {}", sort.column)),
///         observe(|opened: On<RowActivated>| info!("opened row {}", opened.key)),
///     )],
/// ));
/// # }
/// ```
pub fn table(columns: impl IntoIterator<Item = Column>, rows: impl RowSource) -> impl Bundle {
    table_bundle(columns, rows, false)
}

/// A tree: nodes that open and close, as many as you have, in a handful of entities. A node is a
/// [`TreeNode`] (a key that is its identity, a label, its children, open or closed to start); the
/// player opens one with a click on its chevron or Right and closes it with a click or Left, and
/// the tree shows only the nodes whose parents are open, a row each, a button's height, the
/// children indented one level more. A closed node keeps its descendants' state (reopened, they
/// are as they were). It is the [`table`]'s rows in one column: the same scrolling, virtualized
/// pool (an outliner of 10,000 nodes is a screenful of entities), the same cursor and selection
/// by key ([`SelectMode`](crate::SelectMode) `Single` by default, `Multi` for Ctrl and Shift), the
/// same `ValueChange<TableSelection>` ([`TableSelection`](crate::TableSelection)) and
/// [`RowActivated`](crate::RowActivated) for Enter and a double click.
///
/// One tab stop with a cursor row. Up, Down, Home, End and the Page keys move it over the nodes
/// shown; Right opens a closed node and goes to the first child of an open one; Left closes an
/// open node and goes to the parent of any other; `*` opens every sibling of the cursor node; and
/// typing goes to the next node whose label starts with what was typed (within a second). The
/// D-pad and South do the same on a pad. [`TreeToggled`](crate::TreeToggled) tells the game what
/// the player opened or closed. Nodes change through the [`Table`](crate::Table) component
/// (`table.source_mut::<Tree>()`: [`Tree::insert`], [`Tree::remove`], [`Tree::set_open`]); a
/// removed node that was selected passes the selection to its next sibling, else the one before,
/// else its parent.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     panel(),
///     children![(
///         tree([TreeNode::new(1, "World").expanded().children([
///             TreeNode::new(2, "Camera"),
///             TreeNode::new(3, "Lights").child(TreeNode::new(4, "Sun")),
///         ])]),
///         SelectMode::Multi,
///         observe(|picked: On<ValueChange<TableSelection>>| info!("{:?}", picked.value.0)),
///     )],
/// ));
/// # }
/// ```
pub fn tree(nodes: impl IntoIterator<Item = TreeNode>) -> impl Bundle {
    (
        table_bundle([Column::new("").unsortable()], Tree::new(nodes), true),
        TreeView,
    )
}

/// Tabs: a strip of one- or two-word labels above pages of widgets, one page shown at a time. The
/// i-th label opens the i-th page, each a [`tab_page`] in `children![…]`; `selected` is the page
/// shown first. A settings screen is the use: Audio, Display and Controls, each its own page of
/// [`toggle`]s, [`slider`]s and [`choice`]s.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     panel(),
///     children![
///         heading("Settings"),
///         (
///             tabs(
///                 ["Audio", "Display"],
///                 0,
///                 children![
///                     tab_page(children![slider("Volume", 0.7, 0.0..=1.0), toggle("Subtitles", true)]),
///                     tab_page(children![choice("Quality", ["Low", "High"], 1)]),
///                 ]
///             ),
///             observe(|change: On<ValueChange<usize>>| info!("page {}", change.value)),
///         ),
///     ],
/// ));
/// # }
/// ```
///
/// The selected tab is lit and its page shown; a click on a tab, Left and Right on a focused tab
/// (they wrap), and the D-pad's Left and Right select it. **`LB` and `RB`** (and Ctrl+PageUp and
/// Ctrl+PageDown) turn the page from anywhere in the widget, so a pad player never has to go back
/// to the strip ([`step_tabs`](crate::step_tabs)); focus stays in the page and lands on the new
/// page's first widget ([`land_tab_focus`](crate::land_tab_focus)). Down from a tab goes into the
/// page and Up from the page goes to the selected tab.
///
/// Every page takes the room of the largest, so turning a page moves nothing: keep a handful of
/// short labels, and let the pages be about the same height. The entity this returns holds
/// [`TabsValue`](crate::TabsValue), the selected index (read it, or set it to turn the page from
/// code), and reports each change a player makes as a [`ValueChange<usize>`](crate::ValueChange)
/// on itself.
pub fn tabs<S: Into<String>>(
    labels: impl IntoIterator<Item = S>,
    selected: usize,
    pages: impl Bundle,
) -> impl Bundle {
    tabs_in(
        labels.into_iter().map(|label| (label.into(), ())),
        selected,
        pages,
        false,
    )
}

/// [`tabs`] with a bundle on each tab (the dock's marker and drag observers), and, with `fill`, a
/// widget that takes all the room its parent gives it, its page area included, so a panel in a
/// dock group can fill the group.
pub(crate) fn tabs_in<B: Bundle>(
    labels: impl IntoIterator<Item = (String, B)>,
    selected: usize,
    pages: impl Bundle,
    fill: bool,
) -> impl Bundle {
    let labels: Vec<(String, B)> = labels.into_iter().collect();
    let count = labels.len();
    let selected = selected.min(count.saturating_sub(1));
    let (grow, least) = if fill {
        (1.0, Val::Px(0.0))
    } else {
        (0.0, Val::Auto)
    };
    (
        Node {
            flex_direction: FlexDirection::Column,
            flex_grow: grow,
            min_width: least,
            min_height: least,
            ..default()
        },
        Role::Tabs,
        TabsValue(selected),
        TabsCount(count),
        observe(tabs_self_update),
        Children::spawn(SpawnWith(move |parent: &mut RelatedSpawner<ChildOf>| {
            // Bevy's list: Left and Right on a tab move focus and select it at once, and a click
            // selects. Its answer is an entity; `tabs_on_select` turns it into the place. One
            // column per tab, `1fr` each, so the columns are equal, as wide as the widest label
            // and its padding, and the strip is never narrower than that: the panel it stands in
            // grows to fit its labels and never squeezes one.
            parent.spawn((
                if fill {
                    // A dock's strip keeps its tabs as wide as their labels, left-aligned, and
                    // wraps to a second line when a narrow group cannot hold them: every tab is
                    // always there to see and to reach.
                    Node {
                        flex_wrap: FlexWrap::Wrap,
                        align_content: AlignContent::FlexStart,
                        ..default()
                    }
                } else {
                    Node {
                        display: Display::Grid,
                        grid_template_columns: vec![RepeatedGridTrack::flex(
                            u16::try_from(count).unwrap_or(u16::MAX),
                            1.0,
                        )],
                        ..default()
                    }
                },
                TabList {
                    orientation: ControlOrientation::Horizontal,
                    activation: TabActivation::Automatic,
                },
                Role::TabList,
                observe(tabs_on_select),
                Children::spawn(SpawnIter(
                    labels.into_iter().map(|(label, extra)| tab(label, extra)),
                )),
            ));
            // One grid cell for every page, so the widget is as large as the largest.
            parent.spawn((
                Node {
                    display: Display::Grid,
                    flex_grow: grow,
                    min_width: least,
                    min_height: least,
                    overflow: if fill {
                        Overflow::clip()
                    } else {
                        Overflow::visible()
                    },
                    ..default()
                },
                Role::TabPages,
                pages,
            ));
        })),
    )
}

/// One tab of a strip: a button-sized target with its label, which Bevy's `TabList` selects on a
/// click and on Left and Right.
fn tab(label: String, extra: impl Bundle) -> impl Bundle {
    (
        Node {
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        bevy::ui_widgets::Tab,
        Role::Tab,
        Hovered::default(),
        AutoDirectionalNavigation::default(),
        extra,
        children![(Text::new(label), Role::TabText)],
    )
}

/// One page of [`tabs`]: a column of widgets spaced like a [`menu`], shown while its tab is
/// selected. Its widgets are the page's children, in `children![…]`. It stands hidden until
/// [`update_tabs`](crate::update_tabs) shows it, so a page never draws on top of another.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(tabs(
///     ["Game", "Video"],
///     0,
///     children![
///         tab_page(children![button("Resume"), button("Save")]),
///         tab_page(children![toggle("Fullscreen", false)]),
///     ],
/// ));
/// # }
/// ```
pub fn tab_page(widgets: impl Bundle) -> impl Bundle {
    (
        Node {
            flex_direction: FlexDirection::Column,
            grid_row: GridPlacement::start(1),
            grid_column: GridPlacement::start(1),
            ..default()
        },
        Role::TabPage,
        Visibility::Hidden,
        widgets,
    )
}

/// Two panes side by side or one above the other, with a divider between them that the player
/// moves: a docked layout, an inventory beside a map, a log under a viewport. The panes' content is
/// yours, any bundle each (a [`panel`] fills its pane on both axes); the divider is a channel with a
/// grip in the middle, a target the pointer lands on without aiming, that takes focus like any
/// widget.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     split(
///         SplitAxis::Horizontal,
///         (panel(), children![heading("Items")]),
///         (panel(), children![heading("Map")]),
///     ),
///     SplitFraction(0.3),
///     SplitMin::new(200.0, 320.0),
///     observe(|change: On<ValueChange<f32>>| info!("the split is at {}", change.value)),
/// ));
/// # }
/// ```
///
/// The split fills its parent, so stand it in a node of the size you want (a [`screen`] is the
/// window). It keeps its state in [`SplitFraction`](crate::SplitFraction) (the first pane's share of
/// the room the divider leaves; 0.5 until you insert another with it, as above) and each pane's
/// least size in [`SplitMin`](crate::SplitMin) (none until you say). It reports each change a
/// player makes as a
/// [`ValueChange<f32>`](crate::ValueChange) on itself, `is_final` false while a drag goes on; a
/// value the game sets moves the panes with no event.
///
/// A drag of `d` pixels changes the fraction by `d` over the room, and never takes a pane below its
/// minimum; a window too small for both minimums takes the room from the second pane first. With
/// the divider focused the arrows along the split's axis (Left and Right for
/// [`SplitAxis::Horizontal`], Up and Down for [`SplitAxis::Vertical`]) and the D-pad move it
/// ([`SPLIT_KEY_STEP_PX`](crate::SPLIT_KEY_STEP_PX) a press, a held direction repeating), Home and
/// End take the first pane to its smallest and largest, and Enter, the pad's South button and a
/// double click collapse the first pane to its minimum or give it back ([`split_by_pad`](crate::split_by_pad)); the other
/// arrows move focus on. Give the divider `InteractionDisabled` to fix the layout.
pub fn split(axis: SplitAxis, first: impl Bundle, second: impl Bundle) -> impl Bundle {
    split_in(axis, children![first], children![second])
}

/// [`split`] with each pane's children given as a bundle of its own (`children![..]`, or the
/// dock's adoption of a node it built), instead of one child each.
pub(crate) fn split_in(axis: SplitAxis, first: impl Bundle, second: impl Bundle) -> impl Bundle {
    (
        Node {
            flex_direction: match axis {
                SplitAxis::Horizontal => FlexDirection::Row,
                SplitAxis::Vertical => FlexDirection::Column,
            },
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            ..default()
        },
        Split::new(axis),
        Role::Split,
        observe(split_self_update),
        children![split_pane(first), split_divider(axis), split_pane(second)],
    )
}

/// One pane of a [`split`]: a clipped cell of one `1fr` track, so content sized to its own content
/// fills the pane, and one too big for it is cut and never widens it. Its share is
/// [`update_splits`](crate::update_splits)'. `content` is the pane's children.
fn split_pane(content: impl Bundle) -> impl Bundle {
    (
        Node {
            display: Display::Grid,
            grid_template_columns: vec![GridTrack::flex(1.0)],
            grid_template_rows: vec![GridTrack::flex(1.0)],
            flex_basis: Val::Px(0.0),
            flex_grow: 0.5,
            overflow: Overflow::clip(),
            ..default()
        },
        Role::SplitPane,
        content,
    )
}

/// A [`split`]'s divider: a focusable channel with a grip, whose pointer and key handling is
/// `split.rs`'s.
fn split_divider(axis: SplitAxis) -> impl Bundle {
    let (width, height) = match axis {
        SplitAxis::Horizontal => (SPLIT_GRIP_THICKNESS, SPLIT_GRIP_LENGTH),
        SplitAxis::Vertical => (SPLIT_GRIP_LENGTH, SPLIT_GRIP_THICKNESS),
    };
    let cursor = match axis {
        SplitAxis::Horizontal => SystemCursorIcon::ColResize,
        SplitAxis::Vertical => SystemCursorIcon::RowResize,
    };
    (
        (
            Node {
                justify_content: JustifyContent::Center,
                align_items: AlignItems::Center,
                flex_shrink: 0.0,
                ..default()
            },
            SplitDivider::new(axis),
            Role::SplitDivider,
            Hovered::default(),
            TabIndex(0),
            AutoDirectionalNavigation::default(),
            EntityCursor::System(cursor),
        ),
        (
            observe(divider_on_press),
            observe(divider_on_release),
            observe(divider_on_drag_start),
            observe(divider_on_drag),
            observe(divider_on_drag_end),
            observe(divider_on_cancel),
            observe(divider_on_click),
            observe(divider_on_key_input),
            observe(toggle_split),
        ),
        children![(
            Node {
                width: Val::Px(width),
                height: Val::Px(height),
                ..default()
            },
            Role::SplitGrip,
            Pickable::IGNORE,
        )],
    )
}

/// A modal dialog: a veil over the whole window that centres its children and holds focus. When it
/// opens, focus moves to its first button (or to the one carrying Bevy's `AutoFocus`, the way to
/// pick the least destructive default); Tab, the arrows and the D-pad stay inside it; and when it
/// closes, focus returns to the button that opened it. Its contents are yours, in `children![…]`;
/// close it with `commands.entity(dialog).despawn()`, from a button's `Activate` and from an
/// observer of [`crate::Cancel`] on the dialog (Escape and the pad's B send one).
///
/// A [`panel`] that is a direct child of the dialog is the dialog, and looks like one: 21 to 36 body
/// text sizes wide (420 to 720 px at the default size, wider with a larger
/// [`text_scale`](crate::GooeySkin::text_scale)), one and a half times a screen panel's padding and
/// gap, an opaque fill, and its frame in [`outline`](crate::GooeySkin::outline). Put a [`heading`]
/// in it for the main instruction, a [`label`] for what the choice costs, and a [`menu`] of the
/// choices. The scrim keeps the window's outer 5% clear, so a long body wraps and the dialog never
/// reaches the bezel.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy::input_focus::AutoFocus;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     dialog(),
///     observe(|cancel: On<Cancel>, mut commands: Commands| commands.entity(cancel.entity).despawn()),
///     children![(panel(), children![
///         heading("Leave the game?"),
///         label("Progress since the last autosave is lost."),
///         (menu(), children![button("Leave"), (button("Stay"), AutoFocus)]),
///     ])],
/// ));
/// # }
/// ```
pub fn dialog() -> impl Bundle {
    (
        Node {
            position_type: PositionType::Absolute,
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            align_items: AlignItems::Center,
            justify_content: JustifyContent::Center,
            ..default()
        },
        Role::Scrim,
        Dialog::default(),
        GlobalZIndex(100),
        TabGroup {
            order: 0,
            modal: true,
        },
    )
}

/// A workbench of panels the player arranges: a tree of splits and tab groups built from a
/// [`DockLayout`](crate::DockLayout), which is plain data (serde with the `serde` feature), so it can be saved,
/// loaded and reset. What a panel shows is spawned once by the function registered under its id in
/// the [`PanelRegistry`](crate::PanelRegistry); the dock builds the tree, and a panel's page is moved, never rebuilt,
/// when the layout changes.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// fn ui(mut commands: Commands, mut panels: ResMut<PanelRegistry>) {
///     panels
///         .register("scene", "Scene", |page| {
///             page.with_child(label("Nothing selected"));
///         })
///         .register("assets", "Assets", |page| {
///             page.with_child(button("Import"));
///         })
///         .register("log", "Log", |page| {
///             page.with_child(label("Ready"));
///         });
///     commands.spawn((
///         dock(DockLayout::split(
///             SplitAxis::Horizontal,
///             0.3,
///             DockLayout::group(["scene", "assets"]),
///             DockLayout::group(["log"]),
///         )),
///         observe(|changed: On<DockLayoutChanged>| info!("save {:?}", changed.layout)),
///     ));
/// }
/// ```
///
/// The dock fills its parent. Every group is a [`panel`] with a strip of tabs; each divider is a
/// [`split`]'s, with its keys and its 96 px minimum pane. The player rearranges the layout by
/// picking a tab up: a card with its title follows the pointer, and the part of the dock the panel
/// will take is lit before it is let go (on a group's strip, into the group at that place; over
/// its middle, as a tab; over an edge, in a group of its own on that side; at the dock's own
/// edge, a quarter of the dock). Escape puts it back. Without a pointer, **Ctrl+Shift and an
/// arrow** on a focused tab moves its panel to the nearest group that way, or to that edge of the
/// dock. Each change is one [`DockLayoutChanged`](crate::DockLayoutChanged) with the layout now
/// shown; write a layout to [`Dock`](crate::Dock) to load or reset it.
///
/// A panel id the registry does not know, or one the layout names twice, is left out and reported
/// once as a [`DockPanelSkipped`](crate::DockPanelSkipped); a group left with no panel collapses.
pub fn dock(layout: DockLayout) -> impl Bundle {
    (
        Node {
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            ..default()
        },
        Role::Dock,
        Dock(layout),
        children![
            // One grid cell of `1fr`, so the node the layout is built as fills the dock whatever
            // it is.
            (
                Node {
                    display: Display::Grid,
                    grid_template_columns: vec![GridTrack::flex(1.0)],
                    grid_template_rows: vec![GridTrack::flex(1.0)],
                    width: Val::Percent(100.0),
                    height: Val::Percent(100.0),
                    ..default()
                },
                Role::DockBody,
            ),
            (
                Node {
                    display: Display::None,
                    position_type: PositionType::Absolute,
                    ..default()
                },
                Role::DockDrop,
                Pickable::IGNORE,
            ),
            (
                Node {
                    display: Display::None,
                    position_type: PositionType::Absolute,
                    ..default()
                },
                Text::new(""),
                Role::DockGhost,
                Pickable::IGNORE,
            ),
        ],
    )
}

/// A command palette: a modal field over a searchable list of the game's [`crate::CommandList`], each
/// command with its chord and, when it is off, why. Spawn it when the player presses the game's
/// own chord (Ctrl+Shift+P, say); it takes focus, and everything else is the palette's.
///
/// The player types a few letters of a command ("opn prj" finds "File: Open Project"; recently run
/// commands come first), Up and Down move the lit row while focus stays in the field, Enter or a
/// click runs it, Escape or a click outside closes it. Running sends one [`crate::RunCommand`] with the
/// command's id and despawns the palette, focus back where it was; a command that is off shows its
/// reason where its chord would be and runs nothing. See [`crate::PaletteCommand`] for the list's items.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// fn setup(mut commands: Commands) {
///     commands.insert_resource(CommandList(vec![
///         PaletteCommand::new("project.open", "Open Project")
///             .category("File")
///             .shortcut(Shortcut::primary(KeyCode::KeyO)),
///         PaletteCommand::new("project.save", "Save").disabled("No project is open"),
///     ]));
/// }
///
/// fn open_palette(keys: Res<ButtonInput<KeyCode>>, mut commands: Commands) {
///     if Shortcut::new(Modifiers::PRIMARY | Modifiers::SHIFT, KeyCode::KeyP).just_pressed(&keys) {
///         commands.spawn(command_palette());
///     }
/// }
///
/// fn plug(app: &mut App) {
///     app.add_systems(Startup, setup)
///         .add_systems(Update, open_palette.run_if(not(is_text_editing)))
///         .add_observer(|run: On<RunCommand>| info!("run {}", run.id));
/// }
/// ```
///
/// Up to eight rows show at once and scroll under the lit one (fewer when large text or a short
/// window leaves no room, so the card never leaves the window). The field's hint ("Type a command")
/// and the line for no match ("No command matches") are English, as a menu's "Nothing here" is.
pub fn command_palette() -> impl Bundle {
    palette_card(CommandPalette::default(), PALETTE_HINT, NO_MATCH)
}

/// A searchable list: the command palette's card over `state`, with `hint` in its field and
/// `no_match` for an empty result. A [`select`] opens one over its own options.
fn palette_card(state: CommandPalette, hint: &'static str, no_match: &'static str) -> impl Bundle {
    (
        Node {
            position_type: PositionType::Absolute,
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            align_items: AlignItems::FlexStart,
            justify_content: JustifyContent::Center,
            ..default()
        },
        Role::Scrim,
        Dialog::default(),
        GlobalZIndex(100),
        TabGroup {
            order: 0,
            modal: true,
        },
        state,
        observe(palette_on_cancel),
        observe(palette_on_acquire),
        observe(palette_on_click),
        Children::spawn(SpawnWith(move |scrim: &mut RelatedSpawner<ChildOf>| {
            let palette = scrim.target_entity();
            scrim
                .spawn((Node::default(), Role::Palette))
                .with_children(|card| {
                    card.spawn((
                        text_row(None, String::new(), None),
                        PaletteInput(palette),
                        TextHint(hint.into()),
                    ));
                    card.spawn(Node {
                        flex_direction: FlexDirection::Column,
                        ..default()
                    })
                    .with_children(|rows| {
                        for slot in 0..PALETTE_ROWS {
                            rows.spawn(palette_row(palette, slot));
                        }
                        rows.spawn((
                            Node {
                                display: Display::None,
                                ..default()
                            },
                            Text::new(no_match),
                            Role::MenuNote,
                            ONE_LINE,
                            PaletteNote(palette),
                            Pickable::IGNORE,
                        ));
                    });
                    card.spawn((
                        Node {
                            display: Display::None,
                            ..default()
                        },
                        Text::new(String::new()),
                        Role::PaletteCount,
                        ONE_LINE,
                        PaletteCount(palette),
                        Pickable::IGNORE,
                    ));
                });
        })),
    )
}

/// One of a palette's reused rows: a command's words and its chord or reason, hidden until
/// [`update_palette`] gives it a command.
fn palette_row(palette: Entity, slot: usize) -> impl Bundle {
    (
        Node {
            display: Display::None,
            ..default()
        },
        bevy::ui_widgets::Button,
        Role::PaletteRow,
        PaletteRow { palette, slot },
        observe(palette_on_activate),
        observe(palette_on_move),
        children![
            (
                Text::new(String::new()),
                Role::MenuText,
                ONE_LINE,
                Pickable::IGNORE
            ),
            (
                Text::new(String::new()),
                Role::MenuShortcut,
                ONE_LINE,
                Pickable::IGNORE
            ),
        ],
    )
}

/// A panel that opens beside `anchor`, stays inside the window, and closes when the player
/// presses anywhere else or backs out.
///
/// Spawn it as a child of nothing: the bundle makes it a child of the anchor, so despawning the
/// anchor closes it. Put any widgets in `children![…]`: a [`menu`] of buttons, a [`list`], a
/// [`label`]. It is a card in the skin's look (an opaque fill, a frame in
/// [`outline`](crate::GooeySkin::outline), a shadow) over everything but a [`dialog`] it was
/// opened from and a [`Tooltip`](crate::Tooltip), and it is placed by Bevy's `Popover`: on the
/// [`Placement`] side of the anchor, flipped to the other side or slid along the anchor's edge
/// when the window leaves no room, and placed again when the window is resized.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands, edit_button: Entity) {
/// commands.spawn((
///     popover(edit_button, Placement::Below),
///     children![button("Copy"), button("Paste")],
/// ));
/// # }
/// ```
///
/// It does not take focus: it is for a combo box's list, a hover card, a panel the player reads.
/// Escape (or the pad's B) closes it from the anchor or from inside it, and a pointer press
/// anywhere that is not the panel or the anchor closes it, each sending one
/// [`PopoverClosed`](crate::PopoverClosed)
/// before it is despawned; the press goes on to what it landed on. A press on the anchor does not
/// close it, so the anchor's own `Activate` can toggle it: despawn the popover there when one is
/// open (it is the [`PopoverPanel`](crate::PopoverPanel) whose `anchor` is the button). A press on the panel never
/// presses the anchor, even though the panel is its child. For a menu that takes focus, use
/// [`popover_modal`].
pub fn popover(anchor: Entity, placement: Placement) -> impl Bundle {
    popover_panel(anchor, placement, false)
}

/// A [`popover`] that holds focus, as a menu does: focus moves into it when it opens (to its first
/// widget, or the one carrying Bevy's `AutoFocus`), Tab, the arrows and the D-pad stay inside it,
/// Escape or the pad's B closes it, and when it closes focus goes back to the widget that was
/// focused when it opened. It is the same scope as a [`dialog`] without the veil.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands, file_button: Entity) {
/// commands.spawn((
///     popover_modal(file_button, Placement::Below),
///     observe(|closed: On<PopoverClosed>| info!("menu closed: {:?}", closed.reason)),
///     children![button("New"), button("Open"), button("Save")],
/// ));
/// # }
/// ```
pub fn popover_modal(anchor: Entity, placement: Placement) -> impl Bundle {
    (
        popover_panel(anchor, placement, true),
        Dialog::default(),
        TabGroup {
            order: 0,
            modal: true,
        },
    )
}

/// What [`popover`] and [`popover_modal`] share. Born `Display::None` and hidden: [`crate::apply_skin`]
/// shows it, styled, in the frame it is spawned, and [`crate::reveal_popovers`] draws it the frame
/// after, once its text is laid out, so it is never drawn bare or at the wrong width.
fn popover_panel(anchor: Entity, placement: Placement, modal: bool) -> impl Bundle {
    (
        Node {
            position_type: PositionType::Absolute,
            display: Display::None,
            ..default()
        },
        Visibility::Hidden,
        Role::Popover,
        placement_of(placement, 0.0, 0.0),
        // Laid out on the window, not inside its anchor: its width is the room the window leaves
        // and not the anchor's (a narrow button would wrap every line to a word), and no clip of a
        // scrolling list or a panel it hangs from reaches it.
        FixedNode,
        BoxShadow::default(),
        // Over a dialog (100), under a tooltip (200).
        GlobalZIndex(150),
        PopoverPanel::new(anchor, placement, modal),
        ChildOf(anchor),
        observe(popover_on_cancel),
        (
            observe(stop_press),
            observe(stop_release),
            observe(stop_click),
            observe(stop_acquire),
        ),
    )
}

/// A menu bar: a row of [`menu_title`]s across the top of its parent, each opening a menu of
/// commands. F10, or Alt pressed and let go on its own, puts focus on the first title; Left and
/// Right walk the titles (wrapping), Down, Enter, Space or a click opens one with focus on its
/// first item, a pointer moving onto another title switches menus while one is open, and Escape
/// (or the pad's B) closes the menu and then gives focus back to where F10 took it from. Inside a
/// menu Right opens a [`submenu`] or moves on to the next title's menu, Left closes a submenu or
/// moves to the previous title's, and Up, Down, Home and End walk the items.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(menu_bar(children![
///     menu_title(
///         "File",
///         children![
///             (
///                 menu_item("Open...").with_shortcut(Shortcut::primary(KeyCode::KeyO)),
///                 observe(|_: On<Activate>| info!("open")),
///             ),
///             separator(),
///             submenu("Recent", children![menu_item("level-1.ron")]),
///         ]
///     ),
///     menu_title(
///         "View",
///         children![
///             check_item("Grid", true),
///             separator(),
///             radio_item("Small", false),
///             radio_item("Large", true),
///         ]
///     ),
/// ]));
/// # }
/// ```
///
/// The bar is the panel's colour with one line under it and blocks the pointer. It is a row of
/// whatever you pass, so it takes any widget beside the titles (a [`label`] pushed right, say).
pub fn menu_bar(titles: impl Bundle) -> impl Bundle {
    (
        Node {
            width: Val::Percent(100.0),
            ..default()
        },
        Role::MenuBar,
        MenuBar::default(),
        observe(bar_on_cancel),
        titles,
    )
}

/// A title of a [`menu_bar`]: a button with the menu `items` (a `children![]` of [`menu_item`],
/// [`check_item`], [`radio_item`], [`separator`] and [`submenu`]) that opens under it. The menu is
/// spawned once with the title and shown by opening it, so an `observe(..)` on an item stays
/// where you wrote it. Its title stays lit while its menu is open.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(menu_bar(children![menu_title(
///     "Edit",
///     children![menu_item("Undo"), menu_item("Redo")]
/// )]));
/// # }
/// ```
pub fn menu_title(label: impl Into<String>, items: impl Bundle) -> impl Bundle {
    (
        Node {
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        bevy::ui_widgets::Button,
        Role::MenuTitle,
        MenuTitle,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        children![(Text::new(label), Role::MenuTitleText), menu_panel(items)],
    )
}

/// A command in a menu: a row with `label` that sends [`Activate`](crate::Activate) when chosen by Enter, Space, the
/// pad's South button or a click, and closes the menu. Chain [`MenuItem::with_shortcut`] to show
/// its chord at the end of the row, and add [`Disabled`](crate::Disabled) to make it unavailable
/// with a reason.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     menu_item("Save").with_shortcut(Shortcut::primary(KeyCode::KeyS)),
///     observe(|_: On<Activate>| info!("save")),
/// ));
/// # }
/// ```
pub fn menu_item(label: impl Into<String>) -> MenuItem {
    MenuItem::command(label)
}

/// A menu item that is on or off: it keeps its state in Bevy's [`Checked`] (a tick in the mark
/// slot while on) and flips it on every choice, sending a [`ValueChange<bool>`](crate::ValueChange) with the new value.
/// The menu closes, like any command.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     check_item("Show grid", true),
///     observe(|change: On<ValueChange<bool>>| info!("grid: {}", change.value)),
/// ));
/// # }
/// ```
pub fn check_item(label: impl Into<String>, checked: bool) -> MenuItem {
    MenuItem::check(label, checked)
}

/// One of a run of choices in a menu, exactly one of which is on: choosing it sets its own
/// [`Checked`] (a dot in the mark slot) and clears the [`radio_item`]s next to it, up to the
/// nearest [`separator`] or other kind of row either way, and sends a [`ValueChange<bool>`](crate::ValueChange) with
/// `true` for it. Choosing the one that is on changes nothing and sends nothing.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((Node::default(), children![
///     radio_item("Small", false),
///     radio_item("Large", true),
/// ]));
/// # }
/// ```
pub fn radio_item(label: impl Into<String>, checked: bool) -> MenuItem {
    MenuItem::radio(label, checked)
}

/// A menu item that opens another menu `items` to its right (Right, Enter, Space or a click opens
/// it; Left or Escape closes it and puts focus back on the item). A submenu with nothing in it
/// says "Nothing here". Add [`Disabled`](crate::Disabled) to the item to make it unavailable.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(submenu("Recent", children![menu_item("level-1.ron"), menu_item("level-2.ron")]));
/// # }
/// ```
pub fn submenu(label: impl Into<String>, items: impl Bundle) -> impl Bundle {
    (MenuItem::submenu(label), children![menu_panel(items)])
}

/// A menu that belongs to a thing: spawn it once, anywhere, and name it with
/// [`ContextMenu`](crate::ContextMenu) on whatever should open it. A secondary click on the thing
/// opens it at the pointer (flipping at the window's edge), and Shift+F10 or the Menu key with
/// focus on the thing, or a widget under it, opens it below that widget. `items` are the rows of a
/// menu ([`menu_item`], [`check_item`], [`radio_item`], [`submenu`], [`separator`]), live
/// entities, so a game's `observe(..)` sits on the item; [`ContextTarget`](crate::ContextTarget)
/// says which thing it was opened for. Closed, it is drawn nowhere and in no focus scope; open, it
/// is a modal popover, so Escape, B or a press outside close it and give focus back.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn setup(mut commands: Commands) {
/// let menu = commands
///     .spawn(context_menu(children![
///         menu_item("Rename").with_shortcut(Shortcut::new(Modifiers::NONE, KeyCode::F2)),
///         separator(),
///         menu_item("Delete"),
///     ]))
///     .id();
/// commands.spawn((button("Row"), ContextMenu(menu)));
/// # }
/// ```
pub fn context_menu(items: impl Bundle) -> impl Bundle {
    menu_panel(items)
}

/// A line between two groups of a menu. It is not focusable and the pointer goes through it to
/// the card, and it ends a run of [`radio_item`]s.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((Node::default(), children![menu_item("Open"), separator(), menu_item("Quit")]));
/// # }
/// ```
pub fn separator() -> impl Bundle {
    (Node::default(), Role::MenuSeparator, Pickable::IGNORE)
}

/// A line of news at the edge of the screen: "Game saved", "Quest updated". Spawn it from any
/// system, with no layout and nothing else to set up; it stands as long as its message takes to
/// read, fades out and removes itself ([`crate::Toast`], [`crate::ToastSettings`]).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// fn save(mut commands: Commands) {
///     commands.spawn(toast("Game saved"));
/// }
/// ```
///
/// It takes no input and no focus, so it never gets in the way of what is under it; it is not
/// announced to screen readers. See [`Toast`](crate::Toast) for its lifecycle. Add a button with
/// [`ToastBundle::action`] (`toast("Item deleted").action("Undo", "undo")`, which then has one
/// thing that takes input: the button) and make it stand until dismissed with
/// [`ToastBundle::sticky`]; identical toasts arriving close together are merged into one that
/// reads "x3", and every toast is kept in the [`ToastLog`](crate::ToastLog).
pub fn toast(text: impl Into<String>) -> ToastBundle {
    ToastBundle::new(ToastKind::Info, text.into())
}

/// A [`toast`] for a refusal or a failure ("Inventory full", "Could not save"): the same line with
/// a mark in [`crate::GooeySkin::danger`] where an ordinary one's is the accent. The words say it
/// too; the mark is never the only sign.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// fn full(mut commands: Commands) {
///     commands.spawn(toast_alert("Inventory full"));
/// }
/// ```
pub fn toast_alert(text: impl Into<String>) -> ToastBundle {
    ToastBundle::new(ToastKind::Alert, text.into())
}

/// A tool's bar: a full-width row of [`icon_button`]s, [`toggle_group`]s, [`toolbar_separator`]s and
/// any other widget, on the menu bar's surface with one quiet line under it. When the items do not
/// fit the bar's width the **last** ones hide and a "More" button appears whose menu lists them;
/// choosing a row there activates the item ([`fit_bars`](crate::fit_bars)).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands, server: Res<AssetServer>) {
/// let glyph = |name: &str| IconSource::Image(server.load(name.to_string()));
/// commands.spawn(toolbar(children![
///     (
///         icon_button(glyph("save.png"), Tooltip::new("Save").with_shortcut(Shortcut::primary(KeyCode::KeyS))),
///         observe(|_: On<Activate>| info!("save")),
///     ),
///     toolbar_separator(),
///     (
///         toggle_group(
///             [
///                 GroupOption::icon(glyph("move.png"), Tooltip::new("Move")),
///                 GroupOption::icon(glyph("paint.png"), Tooltip::new("Paint")),
///             ],
///             0,
///         ),
///         observe(|mode: On<ValueChange<usize>>| info!("tool {}", mode.value)),
///     ),
/// ]));
/// # }
/// ```
///
/// The bar fills its parent's width and its items never decide it, so a window narrower than the
/// items overflows them instead of widening the bar. Put it where the width is the window's or a
/// panel's own (a [`screen`], a split pane, a column other widgets size): alone in a parent that
/// sizes to its content it has no width to fill. Every control is a tab stop and the arrows and
/// the D-pad move focus along the row.
pub fn toolbar(items: impl Bundle) -> impl Bundle {
    (
        // No width of its own and its parent's as its least: the items never decide how wide the
        // bar is (a bar sized by its items would be as wide as them in a window too narrow for
        // them, and never overflow), and the bar fills the room its parent has.
        Node {
            width: Val::Px(0.0),
            min_width: Val::Percent(100.0),
            ..default()
        },
        Role::Toolbar,
        Toolbar::default(),
        items,
    )
}

/// A toolbar's button: a target-sized square with a picture and no words, so `tooltip` is its
/// name, shown on hover and on visible focus (with its shortcut, if it has one) and listed in the
/// bar's "More" menu when it does not fit. Observe [`Activate`](crate::Activate) on it like any
/// [`button`]; the picture is tinted by the button's state ([`icon`]).
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands, server: Res<AssetServer>) {
/// commands.spawn((
///     icon_button(IconSource::Image(server.load("undo.png")), Tooltip::new("Undo")),
///     observe(|_: On<Activate>| info!("undo")),
/// ));
/// # }
/// ```
pub fn icon_button(source: IconSource, tooltip: Tooltip) -> impl Bundle {
    (
        Node {
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        bevy::ui_widgets::Button,
        Role::Button,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        tooltip,
        children![icon(source)],
    )
}

/// A row of options of which exactly one is on, like a toolbar's tool modes: the one on is lit in
/// the accent, like the selected tab. Choosing another with Enter, Space, South or a click sends
/// one [`ValueChange<usize>`](crate::ValueChange) on the group (the index of the option) and moves
/// the light; choosing the one that is on sends nothing. The state is
/// [`ToggleGroupValue`](crate::ToggleGroupValue): set it to change the mode from code, and the
/// group follows with no event.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     toggle_group([GroupOption::text("Edit"), GroupOption::text("Play")], 0),
///     observe(|mode: On<ValueChange<usize>>| info!("mode {}", mode.value)),
/// ));
/// # }
/// ```
pub fn toggle_group(
    options: impl IntoIterator<Item = GroupOption>,
    selected: usize,
) -> impl Bundle {
    let options: Vec<GroupOption> = options.into_iter().collect();
    let count = options.len();
    let selected = selected.min(count.saturating_sub(1));
    (
        Node::default(),
        Role::ToggleGroup,
        ToggleGroupValue(selected),
        ToggleGroupCount(count),
        observe(group_self_update),
        Children::spawn(SpawnWith(move |parent: &mut RelatedSpawner<ChildOf>| {
            for (index, option) in options.into_iter().enumerate() {
                let mut entity = parent.spawn((
                    Node {
                        justify_content: JustifyContent::Center,
                        align_items: AlignItems::Center,
                        ..default()
                    },
                    bevy::ui_widgets::Button,
                    Role::GroupOption,
                    GroupIndex(index),
                    Hovered::default(),
                    TabIndex(0),
                    AutoDirectionalNavigation::default(),
                    observe(option_on_activate),
                ));
                if let Some(tooltip) = option.tooltip {
                    entity.insert(tooltip);
                }
                match option.content {
                    OptionContent::Text(label) => {
                        entity.with_child((Text::new(label), Role::TabText, ONE_LINE));
                    }
                    OptionContent::Icon(source) => {
                        entity.with_child(icon(source));
                    }
                }
            }
        })),
    )
}

/// A thin vertical line between two groups of a [`toolbar`]. (The menu's [`separator`] is the
/// horizontal one.)
pub fn toolbar_separator() -> impl Bundle {
    (Node::default(), Role::ToolbarSeparator, Pickable::IGNORE)
}

/// A tool's status line along the foot of the window: workspace state on the left, the context's
/// on the right, each a row of [`status_item`]s. When the window is too narrow the lowest
/// [`StatusPriority`](crate::StatusPriority) hides first, the right group's before the left's
/// ([`fit_bars`](crate::fit_bars)); a hidden item returns when the room does.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(status_bar(
///     children![status_item("main"), (status_item("2 problems"), StatusKind::Warning)],
///     children![(status_item("UTF-8"), StatusPriority(10)), status_item("Ln 4, Col 12")],
/// ));
/// # }
/// ```
pub fn status_bar(left: impl Bundle, right: impl Bundle) -> impl Bundle {
    (
        // As a toolbar's: the items never decide the bar's width, its parent's room does.
        Node {
            width: Val::Px(0.0),
            min_width: Val::Percent(100.0),
            ..default()
        },
        Role::StatusBar,
        StatusBar,
        children![
            (
                Node {
                    flex_grow: 1.0,
                    min_width: Val::Px(0.0),
                    ..default()
                },
                Role::StatusGroup,
                StatusGroup { left: true },
                left,
            ),
            (
                Node {
                    flex_shrink: 0.0,
                    ..default()
                },
                Role::StatusGroup,
                StatusGroup { left: false },
                right,
            ),
        ],
    )
}

/// One entry of a [`status_bar`]: a short line of text a target high that sends
/// [`Activate`](crate::Activate) on Enter, Space, South or a click, and takes a
/// [`Tooltip`](crate::Tooltip), a [`StatusKind`](crate::StatusKind) and a
/// [`StatusPriority`](crate::StatusPriority). Edit its [`Text`] child to change the words.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     status_item("Saving..."),
///     StatusKind::Warning,
///     Tooltip::new("Open the notification log"),
///     observe(|_: On<Activate>| info!("log")),
/// ));
/// # }
/// ```
pub fn status_item(text: impl Into<String>) -> impl Bundle {
    (
        Node::default(),
        bevy::ui_widgets::Button,
        Role::StatusItem,
        StatusItem,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        children![
            (Node::default(), Role::StatusMark, Pickable::IGNORE),
            (Text::new(text), Role::ButtonText, ONE_LINE),
        ],
    )
}

/// A [`status_item`] that also shows a short [`progress`] bar after its words, for a task that
/// runs while the player works: change the [`Progress`](crate::Progress) on the bar (the item's
/// second child's child) or query for it.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn(status_progress("Baking", 0.4));
/// # }
/// ```
pub fn status_progress(text: impl Into<String>, fraction: f32) -> impl Bundle {
    (
        Node::default(),
        bevy::ui_widgets::Button,
        Role::StatusItem,
        StatusItem,
        Hovered::default(),
        TabIndex(0),
        AutoDirectionalNavigation::default(),
        children![
            (Node::default(), Role::StatusMark, Pickable::IGNORE),
            (Text::new(text), Role::ButtonText, ONE_LINE),
            progress(fraction),
        ],
    )
}

/// A row that chooses one of a list of options: a [`choice`] with up to eight, and above eight a
/// searchable list. The row looks and steps like a choice (Left and Right, Home and End, the
/// D-pad), and its state is the same [`ChoiceValue`](crate::ChoiceValue); with more than
/// [`SELECT_FILTER_ABOVE`](crate::SELECT_FILTER_ABOVE) options Enter, Space, South or a click
/// opens a list instead of cycling: type to narrow it, Up and Down (or the D-pad) move the lit
/// option, Enter, South or a click chooses it and Escape leaves the value alone. Choosing sends one
/// [`ValueChange<usize>`](crate::ValueChange) on the row, with the option's index in the list you
/// gave, and none when the lit option is the one already chosen.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     select("Language", ["English", "Deutsch", "Español", "Français", "Italiano", "Nederlands",
///         "Polski", "Português", "Svenska", "Türkçe"], 0),
///     observe(|change: On<ValueChange<usize>>| info!("language {}", change.value)),
/// ));
/// # }
/// ```
///
/// While the list is open the options are matched by the same fuzzy rule as the command palette
/// ("par" finds "Paraguay"), keeping the list's own order among equal matches; with none the card
/// says "No option matches" and Enter chooses nothing. Like the palette it is a card at the top of
/// the window and not under the row.
pub fn select<S: Into<String>>(
    label: impl Into<String>,
    options: impl IntoIterator<Item = S>,
    selected: usize,
) -> impl Bundle {
    let options: Vec<String> = options.into_iter().map(Into::into).collect();
    (
        choice(label, options.clone(), selected),
        Select::new(options),
        observe(select_on_activate),
    )
}

/// The list a [`select`] opens: the palette's card over the select's own options, with the one the
/// row has lit.
pub(crate) fn select_list(select: Entity, options: &[String], selected: usize) -> impl Bundle {
    palette_card(
        CommandPalette::for_select(select, options, selected),
        SELECT_HINT,
        SELECT_NO_MATCH,
    )
}

/// A collapsible section: a header you press to fold the group of widgets under it away, so a long
/// inspector or settings screen stays scannable. `children` is any bundle (`children![..]`); a
/// section inside it is a nested section. Enter, Space, South and a click on the header toggle it
/// and send one [`ValueChange<bool>`](crate::ValueChange) on the section (the new state); the state
/// is [`SectionOpen`](crate::SectionOpen), which the game may set (no event). A closed section is
/// only its header: its widgets are not laid out and focus never stops in them, and focus inside
/// one that closes goes to the header. A section with nothing in it shows "Empty".
///
/// Add a [`SectionId`](crate::SectionId) and the section keeps its state across a despawn and a
/// respawn ([`SectionStates`](crate::SectionStates)): `open` is only its first choice.
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((
///     panel(),
///     children![
///         (
///             section("Physics", true, children![slider("Gravity", 9.8, 0.0..=20.0), toggle("Wind", false)]),
///             SectionId::new("physics"),
///         ),
///         section("Debug", false, children![toggle("Show colliders", false)]),
///     ],
/// ));
/// # }
/// ```
pub fn section(title: impl Into<String>, open: bool, children: impl Bundle) -> impl Bundle {
    let title = title.into();
    (
        Node {
            flex_direction: FlexDirection::Column,
            ..default()
        },
        Role::Section,
        SectionOpen(open),
        observe(section_self_update),
        Children::spawn(SpawnWith(move |parent: &mut RelatedSpawner<ChildOf>| {
            parent.spawn((
                Node {
                    justify_content: JustifyContent::FlexStart,
                    align_items: AlignItems::Center,
                    ..default()
                },
                bevy::ui_widgets::Button,
                Role::Button,
                SectionHeader,
                Hovered::default(),
                TabIndex(0),
                AutoDirectionalNavigation::default(),
                observe(header_on_activate),
                Children::spawn(SpawnWith(move |header: &mut RelatedSpawner<ChildOf>| {
                    let chevron = |role, at: Vec2, shown: bool| {
                        (
                            Node {
                                display: if shown { Display::Flex } else { Display::None },
                                ..default()
                            },
                            UiTransform {
                                translation: Val2::percent(at.x, at.y),
                                rotation: Rot2::degrees(45.0),
                                ..default()
                            },
                            role,
                            Pickable::IGNORE,
                        )
                    };
                    header.spawn(chevron(
                        Role::TreeClosed,
                        Vec2::new(-CHEVRON_INK_SHIFT, 0.0),
                        !open,
                    ));
                    header.spawn(chevron(
                        Role::TreeOpen,
                        Vec2::new(0.0, -CHEVRON_INK_SHIFT),
                        open,
                    ));
                    header.spawn((
                        Text::new(title),
                        Role::ButtonText,
                        ONE_LINE,
                        Pickable::IGNORE,
                    ));
                })),
            ));
            parent.spawn((
                Node {
                    flex_direction: FlexDirection::Column,
                    display: if open { Display::Flex } else { Display::None },
                    ..default()
                },
                if open {
                    Visibility::Inherited
                } else {
                    Visibility::Hidden
                },
                Role::SectionBody,
                children,
            ));
            parent.spawn((
                Node {
                    display: Display::None,
                    ..default()
                },
                Text::new("Empty"),
                Role::SectionNote,
                Pickable::IGNORE,
            ));
        })),
    )
}

/// The log of every toast, as a list the player can scroll and read: "0:07  Item deleted", the
/// newest first, so a toast that faded before it was read can be found. Put it in a panel or a
/// dialog of your own; it is a [`list`] of buttons (rows are tab stops, so the keys and the D-pad
/// scroll it like any list), and an alert's words start with "! ".
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_gooey::*;
/// # fn ui(mut commands: Commands) {
/// commands.spawn((panel(), children![heading("Notifications"), notification_center()]));
/// # }
/// ```
///
/// It reads the [`ToastLog`](crate::ToastLog), which keeps the last 200 toasts; clear it to
/// empty the center.
pub fn notification_center() -> impl Bundle {
    (
        Node {
            flex_direction: FlexDirection::Column,
            ..default()
        },
        Role::NotificationCenter,
        crate::notification::NotificationCenter,
        children![list(NOTIFICATION_ROWS, children![])],
    )
}

/// How many rows of the log the center shows before it scrolls.
const NOTIFICATION_ROWS: f32 = 5.5;