1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
//! [`TextField`]: a single-line input field, **controlled** (its value comes from
//! the application state), with a caret, navigation and selection.
//!
//! The value is controlled; the **caret / selection** are edit state retained at
//! runtime ([`Edit`]), keyed by widget identity.
use frus_core::{Color, Point, Rect, ResolvedTextStyle, Scene, TextAlign, TextStyle};
use frus_layout::{Dimension, Style};
use frus_text::TextLayout;
use crate::autofill::AutofillHint;
use crate::disabled::DISABLED_CONTENT_OPACITY;
use crate::icons::IconData;
use crate::ime::{Capitalization, Ime, KeyboardType, TextInputAction};
use crate::interaction::{Key, Status};
use crate::runtime::Edit;
use crate::selectiontoolbar::{SelectionToolbar, ToolbarContext, ToolbarItem};
use crate::theme::Theme;
use crate::widget::Widget;
/// Padding either side of the content, both variants.
pub const FIELD_PADDING_X: f32 = 12.0;
/// Padding above and below the content in a [`filled`](TextField::filled) field.
///
/// The reference's Material 3 content padding is `(12, 8, 12, 8)` filled and
/// `(12, 20, 12, 12)` outlined. The asymmetry is not decoration: an outlined field's
/// floating label sits **on** the top border, so the top has to give it room, while a
/// filled one floats its label inside the box.
pub const FIELD_PADDING_Y: f32 = 8.0;
/// Padding above the content in an [`outlined`](TextField::outlined) field.
pub const FIELD_OUTLINED_PADDING_TOP: f32 = 20.0;
/// Padding below the content in an outlined field.
pub const FIELD_OUTLINED_PADDING_BOTTOM: f32 = 12.0;
/// Padding above and below the content in a [`dense`](TextField::dense) filled field —
/// the reference's `(12, 4, 12, 4)`.
pub const FIELD_DENSE_PADDING_Y: f32 = 4.0;
/// Padding above the content in a dense **outlined** field: the reference's
/// `(12, 16, 12, 8)`, which keeps room for the label on the border while giving back
/// everything else.
pub const FIELD_DENSE_OUTLINED_PADDING_TOP: f32 = 16.0;
/// Padding below the content in a dense outlined field.
pub const FIELD_DENSE_OUTLINED_PADDING_BOTTOM: f32 = 8.0;
/// Size of the value and of the resting label — the reference's `body_large`.
pub const FIELD_TEXT_SIZE: f32 = 16.0;
/// What the label shrinks to once it floats. The reference scales it rather than naming
/// a second size, so a field given a larger type keeps the same proportion.
pub const FIELD_LABEL_SCALE: f32 = 0.75;
/// Size of the helper and error line — the reference's `body_small`.
pub const FIELD_SUB_SIZE: f32 = 12.0;
/// Vertical gap between the box and the helper/error line, and above a floating label.
pub const FIELD_GAP: f32 = 4.0;
/// Margin either side of the floating label inside the border's **notch**, which is the
/// reference's `OutlineInputBorder.gapPadding`.
pub const FIELD_NOTCH_GAP: f32 = 4.0;
/// Corner radius of the box, and of a filled field's two top corners.
pub const FIELD_RADIUS: f32 = 4.0;
/// Border weight at rest, and once focused — the reference widens rather than recolours
/// alone, which is what makes focus readable without colour.
pub const FIELD_BORDER_WIDTH: f32 = 1.0;
/// Border weight of a focused field.
pub const FIELD_FOCUSED_BORDER_WIDTH: f32 = 2.0;
/// Side of a prefix/suffix icon (logical px) and the margin around it.
pub const FIELD_ICON_SIZE: f32 = 24.0;
const ICON_PAD: f32 = 6.0;
/// What a disabled field keeps of its colours.
///
/// An alias, kept for the name: the number is the framework's one disabled content
/// opacity, [`DISABLED_CONTENT_OPACITY`], and a field's 38 % moving independently of
/// every other control's would be a bug rather than a setting.
pub const FIELD_DISABLED_OPACITY: f32 = DISABLED_CONTENT_OPACITY;
/// Default masking character of a password field.
const OBSCURE_CHAR: char = '•';
/// When a field's label floats above the value (milestone 656) — the reference's
/// `FloatingLabelBehavior`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum FloatingLabelBehavior {
/// Inside the field, in the value's place, while it is empty and unfocused; floated
/// once it is focused or holds something. The default.
#[default]
Auto,
/// Always floated, so the hint shows in an empty field even before it is focused.
Always,
/// Never floated: inside an empty field, in the value's place, and gone once it holds
/// something — a hint that a screen reader still reads as the field's name.
Never,
}
/// Where a field's floated label sits along its top (milestone 656) — the reference's
/// `FloatingLabelAlignment`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum FloatingLabelAlignment {
/// At the start, over the value. The default.
#[default]
Start,
/// Centred along the field.
Center,
}
/// Which of the reference's two fields this is.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum TextFieldVariant {
/// A box the caller can see all the way round, the floating label notching its top
/// border. The default here.
#[default]
Outlined,
/// A tinted container with a single line under it, the label floating **inside** the
/// box. The line carries the state; the fill carries the affordance.
Filled,
/// **No container at all** — the reference's `InputBorder.none`. No fill, no box, no
/// line: only the value, the hint and whatever icons were asked for.
///
/// This is the field a widget puts *inside* something that is already a container. A
/// [`SearchBar`](crate::SearchBar) is a raised stadium with a field in it, and a field
/// that drew its own box inside that would be two containers deep with the outer one's
/// corners cut by the inner one's. The reference reaches for it in exactly those
/// places (`search_anchor.dart:1810`).
///
/// It lays out like [`Filled`](Self::Filled) — the label floats inside rather than
/// notching a border, there being no border to notch — and simply paints nothing
/// behind the content.
None,
}
/// The caret's shape (milestone 659): what the caller said, each unset part the reference's.
#[derive(Clone, Copy, Debug, PartialEq)]
struct CursorShape {
/// Its width; the reference's 2.
width: f32,
/// Its height; the line's when `None`.
height: Option<f32>,
/// Its corners' radius; 2 on Apple's platforms and square elsewhere when `None`, as the
/// reference's are.
radius: Option<f32>,
/// Whether it shows at all.
shown: bool,
}
impl Default for CursorShape {
fn default() -> Self {
Self {
width: 2.0,
height: None,
radius: None,
shown: true,
}
}
}
/// Everything a [`TextField`] paints, each answer the caller's, the theme's, or the
/// framework's — resolved in that order.
#[derive(Clone, Copy, Debug, Default)]
pub struct TextFieldStyle {
/// Container fill. A filled field defaults to the theme's high surface container; an
/// outlined one to nothing at all.
pub fill: Option<frus_core::Color>,
/// The border, or the underline, at rest.
pub border_color: Option<frus_core::Color>,
/// The border once focused.
pub focused_border_color: Option<frus_core::Color>,
/// Border, label and helper colour while an error is showing.
pub error_color: Option<frus_core::Color>,
/// The same, **under the pointer**: an errored field deepens on hover
/// (`input_decorator.dart:5981`). Unset, the scheme's `on_error_container`.
pub error_hover_color: Option<frus_core::Color>,
/// The value's colour.
pub text_color: Option<frus_core::Color>,
/// The label and the hint, at rest.
pub label_color: Option<frus_core::Color>,
/// The label once focused.
pub focused_label_color: Option<frus_core::Color>,
/// The helper line.
pub helper_color: Option<frus_core::Color>,
/// The prefix and suffix icons.
pub icon_color: Option<frus_core::Color>,
/// The handles under a touch selection. Unset, the scheme's `primary`
/// (`text_selection.dart:83`).
pub handle_color: Option<frus_core::Color>,
/// The caret (milestone 659). Unset, the theme's text selection's, then the scheme's
/// `primary`, as the reference's `cursorColor` is.
pub cursor_color: Option<frus_core::Color>,
/// The caret while an error is showing. Unset, the error colour.
pub cursor_error_color: Option<frus_core::Color>,
/// Corner radius.
pub radius: Option<f32>,
/// Border weight at rest.
pub border_width: Option<f32>,
/// Border weight once focused.
pub focused_border_width: Option<f32>,
/// Side of the prefix/suffix icons.
pub icon_size: Option<f32>,
/// Padding either side of the content.
pub padding_x: Option<f32>,
}
/// A single-line text input field, with optional **form decoration** (label, hint,
/// helper text, error). **Validity** stays decided by the application (a pure
/// function of the state); the field only displays its result through [`error`].
///
/// [`error`]: TextField::error
pub struct TextField<Msg = crate::callback::Callback> {
value: String,
size: f32,
width: Dimension,
/// Whether the width was given; if not, the field takes the width on offer, as the
/// reference's does (milestone 590).
sized: bool,
on_input: Option<Box<dyn Fn(String) -> Msg>>,
on_submit: Option<Msg>,
/// Sent for a press outside the field while it is focused; see
/// [`TextField::on_tap_outside`].
on_tap_outside: Option<Msg>,
/// What to tell the screen reader when `on_submit` fires — see [`TextField::announce`].
announce: Option<String>,
/// Label displayed above the field.
label: Option<String>,
/// Hint displayed **inside** the field while the value is empty.
placeholder: Option<String>,
/// Helper text below the field (hidden when an error is present).
helper: Option<String>,
/// Error message: when present, the border and the label switch to the error
/// colour and this text replaces the helper below the field.
error: Option<String>,
/// Masks the value (a password field): every character is rendered as
/// [`OBSCURE_CHAR`]. Editing acts on the real value; only the display changes.
obscure: bool,
/// What a masked character shows as; see [`TextField::obscuring_character`].
obscuring: char,
/// The caret's shape; see [`TextField::cursor_width`] and the others.
cursor: CursorShape,
/// Whether the field takes the focus when it appears; see [`TextField::autofocus`].
autofocus: bool,
/// Where the text sits inside the field. Single-line only; see
/// [`TextField::text_align`].
text_align: TextAlign,
/// Which keys the software keyboard offers; `None` = worked out from the field
/// (a masked field is a secret, a multi-line one takes newlines).
keyboard: Option<KeyboardType>,
/// What its action key does; `None` = likewise.
action: Option<TextInputAction>,
/// An icon **outside** the box, before it; see [`TextField::icon`].
icon: Option<IconData>,
/// Decorative icon on the left inside the box.
prefix: Option<IconData>,
/// Text just before the value; see [`TextField::prefix_text`].
prefix_text: Option<String>,
/// Text just after the value; see [`TextField::suffix_text`].
suffix_text: Option<String>,
/// When the label floats; see [`TextField::floating_label_behavior`].
floating: Option<FloatingLabelBehavior>,
/// Where it floats to; see [`TextField::floating_label_alignment`].
floating_alignment: Option<FloatingLabelAlignment>,
/// What the counter says instead of the count; see [`TextField::counter_text`].
counter_text: Option<String>,
/// Decorative icon on the right inside the box.
suffix: Option<IconData>,
/// Message emitted on a **click on the suffix icon** (a clear / reveal button…). Makes
/// the suffix clickable: a click there emits this message instead of placing the caret.
suffix_action: Option<Msg>,
/// **Multi-line** field: Enter inserts a line break (instead of submitting), the box
/// is `rows` lines tall and scrolls vertically to follow the caret.
multiline: bool,
/// Number of visible lines in multi-line mode, at least: the box is never shorter.
rows: u16,
/// The most lines the box grows to as the value wraps, `None` without a limit; equal
/// to `rows` for a box that does not grow. See [`TextField::max_lines`].
max_rows: Option<u16>,
/// Whether `rows` was said, by [`TextField::rows`] or [`TextField::min_lines`]: a box
/// given only a most starts at one line, as the reference's does.
rows_told: bool,
/// Which of the reference's two fields to draw.
variant: TextFieldVariant,
/// A field that is shown but cannot be edited: greyed out, and inert. It still
/// displays its value — the reference's disabled field is readable, not hidden.
enabled: bool,
/// A **dense** field: the same shape, less room around the content. What a table's
/// inline cell editor wants, and what a form does not.
dense: bool,
/// The most characters the field will hold; see [`TextField::max_length`].
max_length: Option<usize>,
/// What a typed character becomes before it reaches the value; see
/// [`TextField::input_filter`].
input_filter: Option<Box<dyn Fn(char) -> Option<char>>>,
/// Which letters the software keyboard capitalises; see
/// [`TextField::capitalization`].
capitalization: Capitalization,
/// A field whose value can be read, selected and copied but not changed; see
/// [`TextField::read_only`].
read_only: bool,
/// Per-call overrides; everything unset falls to the theme, then the framework.
style: TextFieldStyle,
/// What the field is for, so the platform can fill it in; see
/// [`TextField::autofill`].
autofill: Vec<AutofillHint>,
/// The application's say over the bar shown above a selection; see
/// [`TextField::selection_toolbar`].
toolbar_build: Option<ToolbarBuild<Msg>>,
/// The bar for each context, built the first time it is asked for and kept: the walk
/// borrows the widget it floats for a whole frame, so it has to live as long as the
/// field does.
toolbars:
[std::cell::OnceCell<Option<Box<dyn Widget<Msg>>>>; ToolbarContext::VARIANTS as usize],
}
/// What an application gives [`TextField::selection_toolbar`]: the context, and the default
/// list for it, answered with the list to show.
pub(crate) type ToolbarBuild<Msg> =
Box<dyn Fn(&ToolbarContext, Vec<ToolbarItem<Msg>>) -> Vec<ToolbarItem<Msg>>>;
impl TextField<crate::callback::Callback> {
/// Drives the field from `controller`: it shows the controller's text, and what is typed
/// in it is written to the controller.
///
/// This sets the field's text and its `on_input`, so it replaces both. To do more when
/// the text changes, listen to the controller.
pub fn controller(mut self, controller: &crate::TextEditingController) -> Self {
self.value = controller.text();
let write = controller.clone();
self.on_input(move |text| write.set_text(text))
}
}
/// A "word" character (letter/digit/`_`) for word jumps (Ctrl+Arrow).
fn is_word(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// Next word boundary **to the left** of `cursor`: skips the separators, then the word
/// (editor behaviour — it stops at the **start** of the previous word).
pub(crate) fn word_boundary_left(chars: &[char], cursor: usize) -> usize {
let mut i = cursor;
while i > 0 && !is_word(chars[i - 1]) {
i -= 1;
}
while i > 0 && is_word(chars[i - 1]) {
i -= 1;
}
i
}
/// Next word boundary **to the right**: skips the separators, then the word — it stops
/// **after** the next word.
pub(crate) fn word_boundary_right(chars: &[char], cursor: usize) -> usize {
let len = chars.len();
let mut i = cursor;
while i < len && !is_word(chars[i]) {
i += 1;
}
while i < len && is_word(chars[i]) {
i += 1;
}
i
}
/// Start of the **logical line** (after the previous `\n`, or 0) containing `cursor`.
pub(crate) fn line_start(chars: &[char], cursor: usize) -> usize {
let mut i = cursor;
while i > 0 && chars[i - 1] != '\n' {
i -= 1;
}
i
}
/// End of the **logical line** (before the next `\n`, or the end) containing `cursor`.
pub(crate) fn line_end(chars: &[char], cursor: usize) -> usize {
let len = chars.len();
let mut i = cursor;
while i < len && chars[i] != '\n' {
i += 1;
}
i
}
/// The side of a selection handle's box (`text_selection.dart:17`).
pub(crate) const HANDLE_SIZE: f32 = 22.0;
/// The two selection handles of `edit` over a text of `len` characters laid out as `layout`
/// and drawn with its top-left corner at `origin`, in the same coordinates as `origin` — see
/// [`Widget::selection_handles`]. Shared by every widget that shows a selection, so that a
/// paragraph's handles hang exactly as a field's do.
pub(crate) fn handles_in(
layout: &TextLayout,
origin: Point,
len: usize,
edit: &Edit,
) -> Option<[crate::SelectionHandle; 2]> {
let (start, end) = edit.selection_range()?;
let (start, end) = (start.min(len), end.min(len));
if start >= end {
return None;
}
Some([
handle_at(layout, origin, start, true),
handle_at(layout, origin, end, false),
])
}
/// One selection handle, hanging from character boundary `index` of a text laid out as
/// `layout` and drawn at `origin`.
pub(crate) fn handle_at(
layout: &TextLayout,
origin: Point,
index: usize,
start: bool,
) -> crate::SelectionHandle {
let caret = layout.caret_rect(index);
let x = origin.x + caret.x;
let top = origin.y + caret.y;
crate::SelectionHandle {
// The start handle hangs to the left of its position and the end one to the right
// (`text_selection.dart:115`), so that both point in at the text between them.
rect: Rect::new(
if start { x - HANDLE_SIZE } else { x },
top + caret.height,
HANDLE_SIZE,
HANDLE_SIZE,
),
line_center: Point::new(x, top + caret.height * 0.5),
}
}
/// Paints one selection handle, the start one when `start`, `offset` being where the widget's
/// local origin is on the surface.
pub(crate) fn paint_handle(
scene: &mut Scene,
handle: crate::SelectionHandle,
offset: Point,
color: Color,
start: bool,
) {
scene.fill_path(
&handle_path(handle.rect.translate(offset.x, offset.y), start),
color,
);
}
/// The box a bar over the selection is placed against: the selection's, line by line joined
/// into one box, or the caret's when nothing is selected — for a text laid out as `layout`
/// and drawn at `origin`.
pub(crate) fn selection_box_in(
layout: &TextLayout,
origin: Point,
len: usize,
edit: &Edit,
) -> Rect {
let selected = edit
.selection_range()
.map(|(start, end)| layout.selection_rects(start.min(len), end.min(len)))
.unwrap_or_default();
let mut boxed = selected.first().copied();
for rect in selected.iter().skip(1) {
boxed = boxed.map(|so_far| so_far.union(*rect));
}
let boxed = boxed.unwrap_or_else(|| layout.caret_rect(edit.cursor.min(len)));
boxed.translate(origin.x, origin.y)
}
/// Paints `handles` — a touch selection's two grips — in `color`, `offset` being where the
/// widget's local origin is on the surface.
pub(crate) fn paint_handles(
scene: &mut Scene,
handles: [crate::SelectionHandle; 2],
offset: Point,
color: Color,
) {
let [start, end] = handles;
let place = |r: Rect| r.translate(offset.x, offset.y);
scene.fill_path(&handle_path(place(start.rect), true), color);
scene.fill_path(&handle_path(place(end.rect), false), color);
}
/// The word around character `index` of `chars`, as a range — what a double click or a long
/// press selects. A separator selects itself; an empty text, the empty range.
pub(crate) fn word_range(chars: &[char], index: usize) -> Option<(usize, usize)> {
let len = chars.len();
if len == 0 {
return Some((0, 0));
}
let i = index.min(len - 1);
if !is_word(chars[i]) {
return Some((i, (i + 1).min(len)));
}
let mut start = i;
while start > 0 && is_word(chars[start - 1]) {
start -= 1;
}
let mut end = i + 1;
while end < len && is_word(chars[end]) {
end += 1;
}
Some((start, end))
}
/// The word around character `index` of `text`, as a range of characters — what a double click
/// in a [`SelectionArea`](crate::SelectionArea) selects.
pub fn word_bounds(text: &str, index: usize) -> (usize, usize) {
let chars: Vec<char> = text.chars().collect();
word_range(&chars, index).unwrap_or((0, 0))
}
/// Moves the caret as the arrow and home/end keys ask — a word at a time under Ctrl, to the
/// ends of the line or of the text — extending the selection under Shift. Returns whether
/// `key` was one of those. Shared by an editable field and a selectable paragraph, which move
/// the caret the same way and differ only in what else a key may do.
pub(crate) fn move_caret(
chars: &[char],
cursor: &mut usize,
anchor: &mut Option<usize>,
key: &Key,
) -> bool {
let len = chars.len();
let target = match key {
Key::Left { word, .. } => {
if *word {
word_boundary_left(chars, *cursor)
} else {
cursor.saturating_sub(1)
}
}
Key::Right { word, .. } => {
if *word {
word_boundary_right(chars, *cursor)
} else {
(*cursor + 1).min(len)
}
}
// Ctrl (`doc`): the bounds of the whole text; otherwise those of the logical line.
Key::Home { doc, .. } => {
if *doc {
0
} else {
line_start(chars, *cursor)
}
}
Key::End { doc, .. } => {
if *doc {
len
} else {
line_end(chars, *cursor)
}
}
_ => return false,
};
let shift = matches!(
key,
Key::Left { shift: true, .. }
| Key::Right { shift: true, .. }
| Key::Home { shift: true, .. }
| Key::End { shift: true, .. }
);
move_cursor(cursor, anchor, target, shift);
true
}
/// A selection handle's outline in `rect`: a disc with the corner nearest the text
/// squared off, so that it points at its end of the selection — up and right for the
/// start handle, which hangs to the left of its position, up and left for the end one.
fn handle_path(rect: Rect, start: bool) -> frus_core::Path {
use std::f32::consts::{FRAC_PI_2, PI};
let r = rect.width * 0.5;
let centre = Point::new(rect.x + r, rect.y + r);
if start {
// From the squared corner, top right, down to the disc's rightmost point, then
// round the bottom and the left to its top.
frus_core::Path::new()
.move_to(Point::new(rect.x + rect.width, rect.y))
.line_to(Point::new(rect.x + rect.width, centre.y))
.arc_to(centre, r, 0.0, 3.0 * FRAC_PI_2)
.close()
} else {
// From the squared corner, top left, along to the disc's top, then round the
// right and the bottom to its leftmost point.
frus_core::Path::new()
.move_to(Point::new(rect.x, rect.y))
.line_to(Point::new(centre.x, rect.y))
.arc_to(centre, r, -FRAC_PI_2, PI)
.close()
}
}
/// Moves the caret to `target`, handling the selection anchor according to Shift.
fn move_cursor(cursor: &mut usize, anchor: &mut Option<usize>, target: usize, shift: bool) {
if shift {
if anchor.is_none() {
*anchor = Some(*cursor);
}
} else {
*anchor = None;
}
*cursor = target;
}
impl<Msg> TextField<Msg> {
/// Creates a field displaying `value`.
pub fn new(value: impl Into<String>) -> Self {
Self {
value: value.into(),
size: FIELD_TEXT_SIZE,
width: Dimension::Length(220.0),
sized: false,
on_input: None,
on_submit: None,
on_tap_outside: None,
announce: None,
label: None,
placeholder: None,
helper: None,
error: None,
obscure: false,
obscuring: OBSCURE_CHAR,
cursor: CursorShape::default(),
autofocus: false,
text_align: TextAlign::Start,
keyboard: None,
action: None,
icon: None,
prefix: None,
prefix_text: None,
suffix_text: None,
floating: None,
floating_alignment: None,
counter_text: None,
suffix: None,
suffix_action: None,
multiline: false,
rows: 3,
max_rows: Some(3),
rows_told: false,
variant: TextFieldVariant::Outlined,
enabled: true,
dense: false,
max_length: None,
input_filter: None,
capitalization: Capitalization::Auto,
read_only: false,
style: TextFieldStyle::default(),
autofill: Vec::new(),
toolbar_build: None,
toolbars: Default::default(),
}
}
/// **Outlined**: a box the caller can see all the way round, the floating label
/// notching its top border. The default.
pub fn outlined(mut self) -> Self {
self.variant = TextFieldVariant::Outlined;
self
}
/// **Filled**: a tinted container with a single line under it, the label floating
/// inside the box rather than on its edge.
/// **No container**: no fill, no box, no line — the reference's `InputBorder.none`.
/// For a field inside something that is already a container. See
/// [`TextFieldVariant::None`].
pub fn borderless(mut self) -> Self {
self.variant = TextFieldVariant::None;
self
}
/// The **filled** variant: a tinted container with a single line under it, the label
/// floating inside. See [`TextFieldVariant::Filled`].
pub fn filled(mut self) -> Self {
self.variant = TextFieldVariant::Filled;
self
}
/// Chooses the variant directly, for a caller holding one in a variable.
pub fn variant(mut self, variant: TextFieldVariant) -> Self {
self.variant = variant;
self
}
/// Greys the field out and makes it inert. A disabled field still **shows** its
/// value: the reference dims it rather than hiding it, since it is usually the answer
/// to why the rest of a form is the way it is.
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Overrides part of the styling for this field alone. Anything left `None` falls to
/// the theme's [`TextFieldTheme`](crate::widgettheme::TextFieldTheme), then to the
/// framework's defaults.
pub fn style(mut self, style: TextFieldStyle) -> Self {
self.style = style;
self
}
/// Tightens the field: the reference's `isDense`, which trades the comfortable
/// padding for a control that fits inside a table row. The shape, the label and the
/// border are unchanged — only the room around the content.
pub fn dense(mut self, dense: bool) -> Self {
self.dense = dense;
self
}
/// Whether this field is outlined (a box) rather than filled (a container and a line).
fn is_outlined(&self) -> bool {
self.variant == TextFieldVariant::Outlined
}
/// Whether this field paints **no container** — see [`TextFieldVariant::None`].
fn is_borderless(&self) -> bool {
self.variant == TextFieldVariant::None
}
/// Padding either side of the content.
fn pad_x(&self) -> f32 {
self.style.padding_x.unwrap_or(FIELD_PADDING_X)
}
/// Padding above the content: an outlined field gives its floating label room on the
/// border, a filled one floats it inside the box and needs none.
fn pad_top(&self) -> f32 {
match (self.is_outlined(), self.dense) {
(true, false) => FIELD_OUTLINED_PADDING_TOP,
(true, true) => FIELD_DENSE_OUTLINED_PADDING_TOP,
(false, false) => FIELD_PADDING_Y,
(false, true) => FIELD_DENSE_PADDING_Y,
}
}
/// Padding below the content.
fn pad_bottom(&self) -> f32 {
match (self.is_outlined(), self.dense) {
(true, false) => FIELD_OUTLINED_PADDING_BOTTOM,
(true, true) => FIELD_DENSE_OUTLINED_PADDING_BOTTOM,
(false, false) => FIELD_PADDING_Y,
(false, true) => FIELD_DENSE_PADDING_Y,
}
}
/// The field's type, **resolved once**: the reader's font setting applied.
///
/// Everything that measures, shapes, hit-tests, places a caret or paints the field's
/// text goes through this one number. A caret placed from an unresolved size and
/// glyphs drawn from a resolved one land in different places, and the field is then
/// wrong for exactly the readers who most needed it to be right.
fn text_style(&self) -> ResolvedTextStyle {
TextStyle::new(self.size).resolved()
}
/// The helper line under the field — helper text, error, counter. See [`Self::text_style`].
fn sub_style(&self) -> ResolvedTextStyle {
TextStyle::new(FIELD_SUB_SIZE).resolved()
}
/// Size the label shrinks to once it floats — a proportion of the field's own type,
/// not a second number, so a field given larger text keeps the relationship.
fn label_size(&self) -> f32 {
self.text_style().size * FIELD_LABEL_SCALE
}
/// Side of the prefix/suffix icons.
fn icon_size(&self) -> f32 {
self.style.icon_size.unwrap_or(FIELD_ICON_SIZE)
}
/// Distance from the top of the box to the first line of text: the padding, plus the
/// room a filled field reserves for its floating label.
fn text_top(&self) -> f32 {
self.pad_top() + self.floating_label_height()
}
/// Room a **filled** field reserves above its content for the floating label. The
/// reference computes it as `4 + 0.75 × label size` rather than reserving a band
/// outside the box, which is why a filled field is taller than its text.
fn floating_label_height(&self) -> f32 {
if self.is_outlined() || self.label.is_none() {
0.0
} else {
FIELD_GAP + self.label_size()
}
}
/// This field's settings, resolved `caller ?? theme ?? framework`.
fn resolved(&self, theme: &Theme) -> TextFieldStyle {
let t = theme.widgets.text_field;
let pick = |a: Option<frus_core::Color>,
b: Option<frus_core::Color>,
c: frus_core::Color| { Some(a.or(b).unwrap_or(c)) };
TextFieldStyle {
fill: pick(
self.style.fill,
t.fill,
if self.is_outlined() || self.is_borderless() {
frus_core::Color::TRANSPARENT
} else {
// `input_decorator.dart:5968` — a filled field takes the most
// emphasis a container has.
theme.scheme.surface_container_highest
},
),
border_color: pick(
self.style.border_color,
t.border_color,
if self.is_outlined() {
theme.scheme.outline
} else {
theme.scheme.on_surface_variant
},
),
focused_border_color: pick(
self.style.focused_border_color,
t.focused_border_color,
theme.scheme.primary,
),
error_color: pick(self.style.error_color, t.error_color, theme.scheme.error),
error_hover_color: pick(
self.style.error_hover_color,
t.error_hover_color,
theme.scheme.on_error_container,
),
text_color: pick(self.style.text_color, t.text_color, theme.scheme.on_surface),
label_color: pick(
self.style.label_color,
t.label_color,
theme.scheme.on_surface_variant,
),
focused_label_color: pick(
self.style.focused_label_color,
t.focused_label_color,
theme.scheme.primary,
),
helper_color: pick(
self.style.helper_color,
t.helper_color,
theme.scheme.on_surface_variant,
),
icon_color: pick(
self.style.icon_color,
t.icon_color,
theme.scheme.on_surface_variant,
),
handle_color: pick(
self.style.handle_color,
t.handle_color,
theme.scheme.primary,
),
radius: Some(self.style.radius.or(t.radius).unwrap_or(FIELD_RADIUS)),
border_width: Some(
self.style
.border_width
.or(t.border_width)
.unwrap_or(FIELD_BORDER_WIDTH),
),
focused_border_width: Some(
self.style
.focused_border_width
.or(t.focused_border_width)
.unwrap_or(FIELD_FOCUSED_BORDER_WIDTH),
),
cursor_color: Some(
self.style
.cursor_color
.or(t.cursor_color)
.or(theme.widgets.text_selection.cursor_color)
.unwrap_or(theme.scheme.primary),
),
cursor_error_color: Some(
self.style
.cursor_error_color
.or(t.cursor_error_color)
.or(self.style.error_color)
.or(t.error_color)
.unwrap_or(theme.scheme.error),
),
icon_size: Some(self.icon_size()),
padding_x: Some(self.pad_x()),
}
}
/// What the field is **for** — a username, a new password, a one-time code, a postal
/// code — so that the platform's autofill service can fill it, and save it once the
/// form is submitted. See [`AutofillHint`].
///
/// A list, most telling first: a sign-in box that takes an email address is both
/// `[AutofillHint::Username, AutofillHint::Email]`. The fields of one form belong in
/// an [`AutofillGroup`](crate::AutofillGroup), or a password is shown to the service
/// with no username to save it under.
///
/// ```ignore
/// TextField::new(&app.code).autofill([AutofillHint::OneTimeCode])
/// ```
pub fn autofill(mut self, hints: impl IntoIterator<Item = AutofillHint>) -> Self {
self.autofill = hints.into_iter().collect();
self
}
/// Switches the field to **multi-line**: Enter inserts a line break (instead of
/// submitting), and the box shows `rows` lines (see [`rows`](Self::rows)).
pub fn multiline(mut self) -> Self {
self.multiline = true;
self
}
/// Number of visible lines in multi-line mode (at least 1). Implies
/// [`multiline`](Self::multiline).
pub fn rows(mut self, rows: u16) -> Self {
self.multiline = true;
self.rows = rows.max(1);
self.max_rows = Some(self.rows);
self.rows_told = true;
self
}
/// The **fewest lines** the box shows — the reference's `minLines`. Implies
/// [`multiline`](Self::multiline); with a [`max_lines`](Self::max_lines), the box grows
/// from these to those as the value wraps.
pub fn min_lines(mut self, lines: u16) -> Self {
self.multiline = true;
self.rows = lines.max(1);
self.rows_told = true;
self.max_rows = self.max_rows.map(|max| max.max(self.rows));
self
}
/// The **most lines** the box grows to as the value wraps, then scrolls — the
/// reference's `maxLines` (milestone 657). `None` grows without a limit. Given alone, the
/// box starts at one line, as the reference's does; `1` is a single-line field.
pub fn max_lines(mut self, lines: impl Into<Option<u16>>) -> Self {
let lines = lines.into();
if lines == Some(1) {
self.multiline = false;
self.rows = 1;
self.max_rows = Some(1);
return self;
}
self.multiline = true;
if !self.rows_told {
self.rows = 1;
}
self.max_rows = lines.map(|max| max.max(self.rows));
self
}
/// Masks the value (a password field): every character becomes a dot. Editing
/// stays normal; only the display is masked.
///
/// It also changes what the **software keyboard** is told, unless
/// [`keyboard_type`](Self::keyboard_type) says otherwise: a masked field is a
/// [`Password`](KeyboardType::Password), which is what stops the keyboard learning
/// what is typed into it. The dots are drawn by us and tell the keyboard nothing.
pub fn obscure(mut self, obscure: bool) -> Self {
self.obscure = obscure;
self
}
/// What each character of a masked value shows as — the reference's
/// `obscuringCharacter`. A dot unless told.
pub fn obscuring_character(mut self, character: char) -> Self {
self.obscuring = character;
self
}
/// The caret's colour (milestone 659). Unset, the theme's, then the scheme's `primary`.
pub fn cursor_color(mut self, color: Color) -> Self {
self.style.cursor_color = Some(color);
self
}
/// The caret's colour while an error is showing. Unset, the error colour.
pub fn cursor_error_color(mut self, color: Color) -> Self {
self.style.cursor_error_color = Some(color);
self
}
/// The caret's width, in logical pixels; the reference's 2 unless told.
pub fn cursor_width(mut self, width: f32) -> Self {
self.cursor.width = width.max(0.0);
self
}
/// The caret's height, centred on the line; the line's own unless told.
pub fn cursor_height(mut self, height: f32) -> Self {
self.cursor.height = Some(height.max(0.0));
self
}
/// The radius of the caret's corners. Unset, 2 on Apple's platforms and square
/// elsewhere, as the reference's are.
pub fn cursor_radius(mut self, radius: f32) -> Self {
self.cursor.radius = Some(radius.max(0.0));
self
}
/// Whether the caret shows while the field is focused — the reference's `showCursor`.
/// A field that hides it still takes keys and selections.
pub fn show_cursor(mut self, show: bool) -> Self {
self.cursor.shown = show;
self
}
/// Takes the keyboard's focus when the field appears — the reference's `autofocus`: the
/// field a screen exists to type into. Where the focus came from is given back when it
/// goes (milestone 605).
pub fn autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus;
self
}
/// Where the text sits inside the field: an amount to the right, a code centred.
///
/// [`Start`](TextAlign::Start) — the default — follows the reading direction, so a
/// field is left-aligned in English and right-aligned in Arabic.
/// [`Left`](TextAlign::Left) and [`Right`](TextAlign::Right) do not: a column of
/// figures wants the same edge whatever the prose around it is doing.
///
/// **Single-line fields only.** A multi-line one stays at the start, and that is a
/// boundary rather than an oversight: aligning wrapped text means moving each line
/// by its own width, and the caret and the click would then have to be told about
/// an offset that differs line by line. That belongs inside the text layout, where
/// the caret and the hit test already live, and not in a widget nudging a block
/// sideways behind their backs.
pub fn text_align(mut self, align: TextAlign) -> Self {
self.text_align = align;
self
}
/// How far the alignment pushes the text inside its content box.
///
/// Zero unless the text is **narrower** than the box: there is nothing to
/// distribute otherwise, and a right-aligned line longer than its field would be
/// shoved off the left edge — the one edge whose text must stay put, since that
/// is where reading starts and where the horizontal scroll brings the caret back to.
///
/// One function, used by the paint, the caret and the hit test alike. Three copies
/// of it would agree on every field until one of them did not, and the failure
/// would be a click landing several characters from where it was aimed.
///
/// It takes **no direction**, and that is deliberate rather than forgotten.
/// [`Widget::cursor_at`] is handed a rectangle and nothing else — no theme, so no
/// reading direction — so a push that depended on one could be applied by the paint
/// and not by the click. Every field in a right-to-left application would then take
/// its caret several characters from the tap, including every field that never asked
/// to be aligned at all. A push both sides can compute is worth more than one that is
/// right in a place the other cannot reach.
///
/// So `Start` is the left edge here and `End` the right. Following the reading
/// direction is the **text layout's** job, one layer down, where the caret and the
/// hit test already live and cannot disagree with the glyphs.
fn align_offset(&self, content_w: f32, text_w: f32) -> f32 {
if self.multiline {
return 0.0;
}
let slack = (content_w - text_w).max(0.0);
match self.text_align {
// Justification stretches the spaces between words, which a single line of
// input has no business doing: it would move the glyphs under the caret
// every time a space was typed.
TextAlign::Start | TextAlign::Left | TextAlign::Justify => 0.0,
TextAlign::End | TextAlign::Right => slack,
TextAlign::Center => slack / 2.0,
}
}
/// Which keys the software keyboard should offer — a phone keypad, an email
/// address, a number.
///
/// Untold, it is worked out from the field: a masked field is a secret, a
/// multi-line one takes newlines, and anything else is ordinary text.
pub fn keyboard_type(mut self, keyboard: KeyboardType) -> Self {
self.keyboard = Some(keyboard);
self
}
/// What the keyboard's action key does, and what it says — *Next* in a form,
/// *Search* over a query, *Send* on a message.
///
/// Untold, a multi-line field takes a newline and every other field says *Done*.
pub fn action(mut self, action: TextInputAction) -> Self {
self.action = Some(action);
self
}
/// The keyboard this field asks for, once the defaults have had their say.
fn ime_options(&self) -> Ime {
let keyboard = self.keyboard.unwrap_or({
// The order matters and only one way round makes sense: a masked field is
// a secret first and a text field second, and a multi-line secret is not a
// thing anybody types.
if self.obscure {
KeyboardType::Password
} else if self.multiline {
KeyboardType::Multiline
} else {
KeyboardType::Text
}
});
let action = self.action.unwrap_or(match keyboard {
// A field that takes several lines needs the key to *insert* one. Saying
// *Done* there is a keyboard that cannot type what the field is for.
KeyboardType::Multiline => TextInputAction::Newline,
_ => TextInputAction::Done,
});
Ime {
keyboard,
action,
capitalization: self.capitalization,
}
}
/// Decorative icon on the left inside the field.
pub fn prefix_icon(mut self, icon: IconData) -> Self {
self.prefix = Some(icon);
self
}
/// Decorative icon on the right inside the field.
pub fn suffix_icon(mut self, icon: IconData) -> Self {
self.suffix = Some(icon);
self
}
/// An icon **outside** the field, before its box — the reference's `icon`: the box, its
/// label and the line under it all start after it. It is 24 pixels (18 dense) with 16
/// before the box, in the icon colour.
pub fn icon(mut self, icon: IconData) -> Self {
self.icon = Some(icon);
self
}
/// Text **just before the value**, in the hint's style — a currency sign, a country
/// code, `https://` — the reference's `prefixText`. Its room is kept whether it shows or
/// not, and it shows while the label is floated: once the field is focused or holds
/// something, at once if the label always floats.
pub fn prefix_text(mut self, text: impl Into<String>) -> Self {
self.prefix_text = Some(text.into());
self
}
/// Text **just after the value**, in the hint's style — a unit, a domain — the
/// reference's `suffixText`. Shown as [`prefix_text`](Self::prefix_text) is.
pub fn suffix_text(mut self, text: impl Into<String>) -> Self {
self.suffix_text = Some(text.into());
self
}
/// When the label floats above the value. Unset, the theme's, then
/// [`FloatingLabelBehavior::Auto`].
pub fn floating_label_behavior(mut self, behavior: FloatingLabelBehavior) -> Self {
self.floating = Some(behavior);
self
}
/// Where the floated label sits along the field's top. Unset, the theme's, then
/// [`FloatingLabelAlignment::Start`].
pub fn floating_label_alignment(mut self, alignment: FloatingLabelAlignment) -> Self {
self.floating_alignment = Some(alignment);
self
}
/// What the counter under the field says, in place of the count a
/// [`max_length`](Self::max_length) puts there — the reference's `counterText`. An empty
/// text hides the counter, limit or not.
pub fn counter_text(mut self, text: impl Into<String>) -> Self {
self.counter_text = Some(text.into());
self
}
/// Makes the **suffix icon clickable**: a click on it emits `message` (a clear button,
/// a reveal-password button…) instead of placing the caret. Implies a suffix icon
/// (to be set through [`suffix_icon`](Self::suffix_icon)).
pub fn on_suffix(mut self, message: impl Into<Msg>) -> Self {
self.suffix_action = Some(message.into());
self
}
/// Does the local point `(x, y)` land on the **suffix's clickable zone** (on the right of
/// the input box)? Used both to route the click and to keep the caret out of it.
fn suffix_hit(&self, local_x: f32, local_y: f32, width: f32) -> bool {
if self.suffix.is_none() {
return false;
}
let zone_left = width - (self.icon_size() + ICON_PAD * 2.0);
let top = self.label_block();
let bottom = top + self.field_height_at(width);
local_x >= zone_left && local_y >= top && local_y <= bottom
}
/// A message for a **press outside the field while it is focused** — the reference's
/// `onTapOutside` (milestone 660), sent before the press moves the focus: a form that
/// saves a draft, or closes a suggestion list, when the user taps away.
pub fn on_tap_outside(mut self, message: impl Into<Msg>) -> Self {
self.on_tap_outside = Some(message.into());
self
}
/// Label displayed above the field.
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
/// Hint displayed inside the field while it is empty — and, for a field with no
/// [`label`](Self::label), the name a screen reader gives it.
pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
self.placeholder = Some(placeholder.into());
self
}
/// Helper text below the field (replaced by the error, if present).
pub fn helper(mut self, helper: impl Into<String>) -> Self {
self.helper = Some(helper.into());
self
}
/// Marks the field **in error**: red border and label, `message` displayed below
/// the field. Chain it only when the application's validation fails.
pub fn error(mut self, message: impl Into<String>) -> Self {
self.error = Some(message.into());
self
}
/// Sets the width, in logical pixels.
pub fn width(mut self, width: f32) -> Self {
self.width = Dimension::Length(width);
self.sized = true;
self
}
/// Sets the font size, in pixels.
pub fn size(mut self, size: f32) -> Self {
self.size = size;
self
}
/// The most characters the field will hold.
///
/// It is **enforced**, as the reference's default is: a keystroke past the limit does
/// not reach the value, and neither does the tail of a paste that would cross it —
/// the part that fits still lands, because dropping a whole paste for being one
/// character too long loses work the user can see they had.
///
/// It also puts a counter — `5/10` — at the end of the line below the box, where the
/// reference puts one, and reserves that line even when there is no helper text to
/// share it with.
///
/// The limit is in **characters**, not bytes: "é" is one, and a name in an alphabet
/// that is not Latin is counted the way its writer would count it.
pub fn max_length(mut self, max: usize) -> Self {
self.max_length = Some(max);
self
}
/// What each typed character becomes before it reaches the value: `None` drops it,
/// `Some(c)` puts `c` in instead of what was typed.
///
/// The reference's `inputFormatters` reshape the **whole value** after every
/// keystroke, which buys grouping (spaces every four digits of a card number) and
/// costs a caret: the formatter has to say where it went, and getting that wrong
/// puts the cursor in the middle of a group the reader did not touch. A filter that
/// works one character at a time cannot group, and cannot lose the caret either
/// — a dropped character simply never arrives, and a substituted one takes the same
/// place. That covers digits-only, letters-only, no-spaces and forced case, which is
/// nearly every field that filters at all.
///
/// It applies to what is **typed or pasted**, and a paste keeps whatever it can
/// rather than being refused whole — the same rule
/// [`max_length`](TextField::max_length) follows, for the same reason.
///
/// A value the **caller** supplied is left alone: it is the application's state, not
/// something typed, and rewriting it would be editing a value nobody edited.
///
/// ```ignore
/// TextField::new(&app.code).input_filter(|c| c.to_uppercase().next())
/// TextField::new(&app.tag).input_filter(|c| (!c.is_whitespace()).then_some(c))
/// ```
pub fn input_filter(mut self, filter: impl Fn(char) -> Option<char> + 'static) -> Self {
self.input_filter = Some(Box::new(filter));
self
}
/// Digits, and nothing else.
///
/// It also asks for a **number keypad**, unless one was named already: a field that
/// refuses everything but digits and then opens a QWERTY keyboard is a field whose
/// keys mostly do nothing. Naming a keyboard before or after this leaves that
/// choice standing, so the two builders can be written in either order.
pub fn digits_only(mut self) -> Self {
self.input_filter = Some(Box::new(|c| c.is_ascii_digit().then_some(c)));
self.keyboard = self.keyboard.or(Some(KeyboardType::Number));
self
}
/// Which letters the software keyboard capitalises by itself.
///
/// A **hint**: it is what the keyboard does to what it sends, and a reader who turns
/// it off still types what they meant to. A field that must hold capitals wants
/// [`input_filter`](TextField::input_filter) as well, which works whatever the
/// keyboard does and works on a desktop, where there is no keyboard to hint to.
pub fn capitalization(mut self, capitalization: Capitalization) -> Self {
self.capitalization = capitalization;
self
}
/// A field whose value can be read, selected and copied — but not changed.
///
/// It is **not** [`enabled(false)`](TextField::enabled), and the difference matters.
/// A disabled field is greyed out and inert: out of the tab order, no caret, nothing
/// to select. A read-only one looks and behaves like any other field except that
/// typing does nothing — you can focus it, move the caret through it, select a
/// reference number and copy it. That is what an identifier the application generated
/// wants, and greying it out would suggest it is unavailable rather than fixed.
pub fn read_only(mut self) -> Self {
self.read_only = true;
self
}
/// **What the bar over a selection offers** — Cut, Copy, Paste, Select all — decided by
/// the application (milestone 568, [#23]).
///
/// `build` is handed the [`ToolbarContext`] (is something selected, is there text to
/// paste, is everything selected already) and the field's **default list** for it, and
/// returns the list to show. Drop an item, reorder them, add one of the application's own
/// ([`ToolbarItem::custom`]) — or return an empty list, and no bar shows at all.
///
/// ```
/// use frus_widgets::{TextField, ToolbarItem};
///
/// #[derive(Clone)]
/// enum Msg { Translate }
///
/// // A field that never lets its text be pasted over, and offers a way to translate it.
/// let field: TextField<Msg> = TextField::new("Bonjour").selection_toolbar(|context, mut items| {
/// items.retain(|item| item.label() != "Paste");
/// if context.has_selection {
/// items.push(ToolbarItem::custom("Translate", Msg::Translate));
/// }
/// items
/// });
/// # let _ = field;
/// ```
///
/// The defaults already keep a secret: a masked field ([`obscure`](Self::obscure)) is
/// given neither Cut nor Copy, and a [`read_only`](Self::read_only) one neither Cut nor
/// Paste, so an application only has to change the list to depart from them.
///
/// [#23]: https://github.com/KalybosPro/frus/issues/23
pub fn selection_toolbar(
mut self,
build: impl Fn(&ToolbarContext, Vec<ToolbarItem<Msg>>) -> Vec<ToolbarItem<Msg>> + 'static,
) -> Self {
self.toolbar_build = Some(Box::new(build));
// Whatever was built for the old answer is not the answer any more.
self.toolbars = Default::default();
self
}
/// Closure producing a message from the field's new value.
pub fn on_input<R: crate::callback::IntoMsg<Msg>>(
mut self,
on_input: impl Fn(String) -> R + 'static,
) -> Self {
self.on_input = Some(Box::new(crate::callback::handler1(on_input)));
self
}
/// Message emitted on submission (the Enter key), without changing the value.
pub fn on_submit(mut self, message: impl Into<Msg>) -> Self {
self.on_submit = Some(message.into());
self
}
/// Text to speak through the screen reader's live region when [`Self::on_submit`]
/// fires — the field's own counterpart to a button's [`Widget::announce`](
/// crate::Widget::announce), which only ever fires on a click or a plain Enter and
/// so never sees a field's submit (#18). Compute it from the value the caller
/// already has — `TextField::new(draft).announce(format!("{draft} added"))` — since
/// by the time this fires, the widget it is read from is the one built **before**
/// the keystroke, still holding what is about to be cleared.
pub fn announce(mut self, message: impl Into<String>) -> Self {
self.announce = Some(message.into());
self
}
/// The **displayed** string: masked (one dot per character) for a password field,
/// the value as is otherwise. Same character count as the value → the caret and
/// the hit-test stay aligned index for index.
fn display(&self) -> String {
if self.obscure {
self.obscuring
.to_string()
.repeat(self.value.chars().count())
} else {
self.value.clone()
}
}
/// The **displayed** string shaped once: caret by index, hit-test, selection — one
/// consistent geometry (kerning). `wrap_width` = the soft-wrap width (multi-line) or
/// `None` (single-line: only explicit `\n` break).
fn layout(&self, wrap_width: Option<f32>) -> TextLayout {
let style = self.text_style();
TextLayout::wrapped(
&self.display(),
style.size,
style.weight,
style.italic,
wrap_width,
)
}
/// Width reserved for the prefix icon (0 if there is none).
fn prefix_icon_w(&self) -> f32 {
if self.prefix.is_some() {
self.icon_size() + ICON_PAD
} else {
0.0
}
}
/// Width reserved for the suffix icon (0 if there is none).
fn suffix_icon_w(&self) -> f32 {
if self.suffix.is_some() {
self.icon_size() + ICON_PAD
} else {
0.0
}
}
/// The width of an affix text, in the value's style.
fn affix_w(&self, text: &Option<String>) -> f32 {
text.as_ref().map_or(0.0, |text| {
frus_text::measure_resolved(text, &self.text_style()).width
})
}
/// Width reserved before the value inside the box: the prefix icon and the prefix text.
fn prefix_w(&self) -> f32 {
self.prefix_icon_w() + self.affix_w(&self.prefix_text)
}
/// Width reserved after the value inside the box: the suffix text and the suffix icon.
fn suffix_w(&self) -> f32 {
self.suffix_icon_w() + self.affix_w(&self.suffix_text)
}
/// The side of the icon outside the box: the reference's 24, 18 dense.
fn outer_icon_size(&self) -> f32 {
if self.dense {
18.0
} else {
24.0
}
}
/// The room before the box, for the icon outside it: its side and 16 more.
fn gutter(&self) -> f32 {
if self.icon.is_some() {
self.outer_icon_size() + 16.0
} else {
0.0
}
}
/// Where the value starts, from the widget's left edge: the room for the outer icon,
/// the padding, the prefix icon and the prefix text.
fn lead(&self) -> f32 {
self.gutter() + self.pad_x() + self.prefix_w()
}
/// When the label floats, the field's own word over the theme's.
fn floating_behavior(&self, theme: &Theme) -> FloatingLabelBehavior {
self.floating
.or(theme.widgets.text_field.floating_label_behavior)
.unwrap_or_default()
}
/// How far the label has floated, `0..=1`, for a focus at `fp`.
fn float_progress(&self, fp: f32, theme: &Theme) -> f32 {
match self.floating_behavior(theme) {
FloatingLabelBehavior::Always => 1.0,
FloatingLabelBehavior::Never => 0.0,
FloatingLabelBehavior::Auto if self.value.is_empty() => fp,
FloatingLabelBehavior::Auto => 1.0,
}
}
/// Text width (between the padding and the icons) for a given widget width.
/// Where the text is drawn inside the field, for `edit`: its layout and the top-left
/// corner of the text, in the field's **local** coordinates. The paint's own geometry —
/// the content's insets, the alignment, the horizontal scroll that follows the caret and
/// the retained vertical one — so that whatever is placed against the text (a handle, the
/// bar over a selection) is where the text is drawn.
fn text_frame(&self, width: f32, edit: &Edit, scroll_y: f32) -> (TextLayout, f32, f32) {
let len = self.value.chars().count();
let content_w = self.content_width(width);
let layout = self.layout(self.multiline.then_some(content_w));
let scroll = (layout.caret_rect(edit.cursor.min(len)).x - content_w).max(0.0);
let align = self.align_offset(content_w, layout.size().width);
let vscroll = if self.multiline {
let visible = self.field_height_at(width) - self.text_top() - self.pad_bottom();
scroll_y.clamp(0.0, (layout.size().height - visible).max(0.0))
} else {
0.0
};
let origin_x = self.lead() + align - scroll;
let origin_y = self.label_block() + self.text_top() - vscroll;
(layout, origin_x, origin_y)
}
/// The two selection handles for `edit`, in local coordinates — see
/// [`Widget::selection_handles`].
fn handles(
&self,
width: f32,
edit: &Edit,
scroll_y: f32,
) -> Option<[crate::SelectionHandle; 2]> {
let len = self.value.chars().count();
edit.selection_range()?;
let (layout, origin_x, origin_y) = self.text_frame(width, edit, scroll_y);
handles_in(&layout, Point::new(origin_x, origin_y), len, edit)
}
/// The box the bar over the selection is placed against: the selection's, line by line
/// joined into one box, or the caret's when nothing is selected.
fn selection_box(&self, width: f32, edit: &Edit, scroll_y: f32) -> Rect {
let len = self.value.chars().count();
let (layout, origin_x, origin_y) = self.text_frame(width, edit, scroll_y);
selection_box_in(&layout, Point::new(origin_x, origin_y), len, edit)
}
/// The bar's **default** list for `context`: what the reference offers, decided by the
/// three conditions and by what this field allows. A masked field gives its text to
/// nobody, so it offers neither Cut nor Copy; a read-only one keeps its text as it is,
/// so it offers no Cut and no Paste.
fn default_toolbar_items(&self, context: &ToolbarContext) -> Vec<ToolbarItem<Msg>> {
let editable = self.enabled && !self.read_only;
let mut items = Vec::new();
if context.has_selection && editable && !self.obscure {
items.push(ToolbarItem::cut());
}
if context.has_selection && !self.obscure {
items.push(ToolbarItem::copy());
}
if context.can_paste && editable {
items.push(ToolbarItem::paste());
}
if !context.all_selected {
items.push(ToolbarItem::select_all());
}
items
}
/// The value's width, between the paddings and the affixes, in a widget `width` wide.
fn content_width(&self, width: f32) -> f32 {
(width - self.lead() - self.pad_x() - self.suffix_w()).max(0.0)
}
/// Height reserved for the label above the box (0 if there is no label). In
/// `outlined` mode the floating label straddles the top border: only its **upper
/// half** must be reserved (the rest bites into the box), instead of a full band.
fn label_block(&self) -> f32 {
if self.label.is_some() {
if self.is_outlined() {
(frus_text::line_height(self.label_size()) * 0.5).ceil()
} else {
frus_text::line_height(self.label_size()) + FIELD_GAP
}
} else {
0.0
}
}
/// The counter shown at the end of the line below the box, when there is a limit.
fn counter(&self) -> Option<String> {
match &self.counter_text {
Some(text) if text.is_empty() => None,
Some(text) => Some(text.clone()),
None => self
.max_length
.map(|max| format!("{}/{}", self.value.chars().count(), max)),
}
}
/// Height reserved for the helper/error line below the box (0 if there is none).
fn sub_block(&self) -> f32 {
if self.error.is_some() || self.helper.is_some() || self.counter().is_some() {
// The helper style's **own** line, not one recomputed from its size: another
// of milestone 412's survivors, written against a bare constant rather than a
// style, which is the one formulation that sweep could not find.
self.sub_style().line_height() + FIELD_GAP
} else {
0.0
}
}
/// Height of the input box itself (decoration excluded) before the value is known to
/// wrap: one line in single-line mode, `rows` lines in multi-line mode.
fn field_height(&self) -> f32 {
let lines = if self.multiline {
self.rows.max(1) as f32
} else {
1.0
};
self.box_height(lines)
}
/// The box's height for `lines` lines of text.
fn box_height(&self, lines: f32) -> f32 {
(self.text_style().line_height() * lines + self.text_top() + self.pad_bottom()).ceil()
}
/// Whether the box grows with the value (milestone 657): multi-line, with more lines
/// allowed than it starts with.
fn grows(&self) -> bool {
self.multiline && self.max_rows != Some(self.rows)
}
/// How many lines the box shows in a widget `width` wide: the value's own, wrapped at
/// the content's width, held between the fewest and the most.
fn lines_at(&self, width: f32) -> f32 {
if !self.grows() {
return if self.multiline {
self.rows.max(1) as f32
} else {
1.0
};
}
let layout = self.layout(Some(self.content_width(width)));
let line_h = self.text_style().line_height();
let wrapped = if line_h > 0.0 {
(layout.size().height / line_h).round().max(1.0)
} else {
1.0
};
wrapped.clamp(
self.rows.max(1) as f32,
self.max_rows.map_or(f32::INFINITY, |max| max as f32),
)
}
/// The box's height in a widget `width` wide; see [`Self::lines_at`].
fn field_height_at(&self, width: f32) -> f32 {
self.box_height(self.lines_at(width))
}
}
impl<Msg: Clone + 'static> Widget<Msg> for TextField<Msg> {
/// **All the room on offer** on an axis nobody sized, as the reference's takes
/// (milestone 590) — unless it was told to grow, which says the same thing already.
fn fill_axes(&self, _theme: &Theme) -> crate::widget::FillAxes {
if false {
return crate::widget::FillAxes::NONE;
}
crate::widget::FillAxes {
horizontal: !self.sized,
vertical: false,
}
}
/// The default size is only a default: the room replaces it wherever the layout can
/// give the room, and it stands where the reference would have nothing to give.
fn soft_extent(&self) -> crate::widget::FillAxes {
crate::widget::FillAxes {
horizontal: !self.sized,
vertical: false,
}
}
fn style(&self) -> Style {
// A box that grows is as tall as its value makes it, which only the width says: it
// is measured instead (milestone 657).
let height = if self.grows() {
Dimension::Auto
} else {
Dimension::Length(self.label_block() + self.field_height() + self.sub_block())
};
Style {
width: self.width,
height,
..Default::default()
}
}
fn measure(&self, _theme: &Theme) -> Option<frus_layout::MeasureFn<'_>> {
if !self.grows() {
return None;
}
Some(Box::new(move |width, _| {
let width = width.unwrap_or(match self.width {
Dimension::Length(w) => w,
_ => 220.0,
});
// Whole pixels, rounded up: the label and helper bands are fractions of a
// line, and a box rounded down is one the field no longer fits in.
frus_core::Size::new(
width,
frus_core::fits(
self.label_block() + self.field_height_at(width) + self.sub_block(),
),
)
}))
}
fn measure_key(&self, _theme: &Theme) -> Option<u64> {
if !self.grows() {
return None;
}
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
self.display().hash(&mut hasher);
self.rows.hash(&mut hasher);
self.max_rows.hash(&mut hasher);
self.size.to_bits().hash(&mut hasher);
// Everything that moves the wrap or the bands around the box, as numbers: a key
// listing the builders would miss the next one to change them.
for part in [
self.lead(),
self.pad_x(),
self.suffix_w(),
self.text_top(),
self.pad_bottom(),
self.label_block(),
self.sub_block(),
] {
part.to_bits().hash(&mut hasher);
}
Some(hasher.finish())
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&[]
}
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
let s = self.resolved(theme);
// A disabled field keeps 38% of everything, following the reference, and never
// shows a focus: it cannot be focused, so a focus ring left over from before it
// was disabled would be a lie about what Tab will do.
let o = if self.enabled {
status.opacity
} else {
status.opacity * FIELD_DISABLED_OPACITY
};
let has_error = self.error.is_some() && self.enabled;
let fp = if self.enabled {
status.focus_progress.clamp(0.0, 1.0)
} else {
0.0
};
// **An errored field deepens under the pointer** (`input_decorator.dart:5981`,
// `:6004`, `:6053`): `error` at rest, `on_error_container` while hovered — and
// back to `error` once focused, because the reference tests focus **before**
// hover and a focused field is already saying everything it can.
//
// Continuous where the reference is discrete, which is this framework's habit
// with the pointer: `hover_progress` is a progression, not a flag.
let error_ink = s.error_color.unwrap().lerp(s.error_hover_color.unwrap(), {
let hover = if self.enabled {
status.hover_progress.clamp(0.0, 1.0)
} else {
0.0
};
hover * (1.0 - fp)
});
// Decoration: label above, input box in the middle, helper/error below. The
// box is the sub-rectangle where all the editing lives.
let label_block = self.label_block();
let gutter = self.gutter();
let field = Rect::new(
bounds.x + gutter,
bounds.y + label_block,
(bounds.width - gutter).max(0.0),
self.field_height_at(bounds.width),
);
// The icon outside the box, centred on it.
if let Some(icon) = self.icon {
let side = self.outer_icon_size();
let path = icon.placed(
side,
bounds.x,
field.y + (field.height - side) * 0.5,
theme.direction,
);
scene.fill_path(&path, s.icon_color.unwrap().fade(o));
}
// **Floating** label: at rest (an empty, unfocused field) it occupies the box,
// in the hint's place; focused OR filled, it floats above, shrunk. The
// position/size progress follows that "floating" (`t`); the **colour** follows
// the focus (`fp`) — a filled but unfocused field keeps a discreet label, not
// yet accented.
let float_t = self.float_progress(fp, theme);
// A label that never floats is a hint: gone once the field holds something.
let label_shown =
self.floating_behavior(theme) != FloatingLabelBehavior::Never || self.value.is_empty();
let content_left = bounds.x + self.lead();
// The label at rest sits where the value starts, after the prefix icon; the prefix
// text, hidden while it rests, is no part of it.
let label_rest = field.x + self.pad_x() + self.prefix_icon_w();
let centred = self
.floating_alignment
.or(theme.widgets.text_field.floating_label_alignment)
.unwrap_or_default()
== FloatingLabelAlignment::Center;
// Geometry of the floating label, interpolated between **rest** (inside the box,
// in the hint's place) and the **floated target**. That target differs with the
// style: `outlined` → on the top border (with a notch); otherwise → a reserved band.
let label_geom = self.label.as_ref().filter(|_| label_shown).map(|label| {
let rest = Point::new(label_rest, field.y + self.text_top());
let (fx, fy) = if self.is_outlined() {
// On the top border, which the notch opens behind it.
(
field.x + self.pad_x(),
field.y - frus_text::line_height(self.label_size()) * 0.5,
)
} else {
// Inside the container, in the room reserved above the content — a filled
// field never spills outside its own box.
(label_rest, field.y + self.pad_top())
};
// Centred, the floated label is centred on the box, at its floated size.
let fx = if centred {
let floated = frus_text::measure_resolved(
label,
&ResolvedTextStyle::exact(self.label_size()),
)
.width;
field.x + (field.width - floated) * 0.5
} else {
fx
};
let x = rest.x + (fx - rest.x) * float_t;
let y = rest.y + (fy - rest.y) * float_t;
let resolved = self.text_style().size;
let size = resolved + (self.label_size() - resolved) * float_t;
let color = if has_error {
error_ink
} else {
s.label_color
.unwrap()
.lerp(s.focused_label_color.unwrap(), fp)
};
(label.clone(), x, y, size, color)
});
// Helper/error line below the box (the error takes precedence over the helper).
let sub = self.error.as_ref().or(self.helper.as_ref());
if let Some(sub) = sub {
// The message itself does **not** deepen: `errorStyle` is `error` in every
// state (`input_decorator.dart:6100`). It is a sentence, not a control, and
// a sentence that changed colour under the pointer would be claiming to be
// one.
let color = if has_error {
s.error_color.unwrap()
} else {
s.helper_color.unwrap()
};
scene.text(
Point::new(field.x, field.y + field.height + FIELD_GAP),
sub.clone(),
&self.sub_style(),
color.fade(o),
);
}
// The counter shares that line, pushed to its far end — the reference's place for
// it, and the one that leaves the helper text where it was. It takes the helper's
// colour rather than the error's even while an error is showing: it is a fact
// about length, not a second complaint.
if let Some(counter) = self.counter() {
let width = frus_text::measure_resolved(&counter, &self.sub_style()).width;
scene.text(
Point::new(
bounds.x + bounds.width - width,
field.y + field.height + FIELD_GAP,
),
counter,
&self.sub_style(),
s.helper_color.unwrap().fade(o),
);
}
// The border follows the focus in **two** ways, as the reference does: the colour
// moves to the accent and the weight goes from 1 to 2. Either alone is legible;
// both together is what makes a focused field unmistakable without relying on
// colour, which not every reader has.
let border_color = if has_error {
error_ink
} else {
s.border_color
.unwrap()
.lerp(s.focused_border_color.unwrap(), fp)
}
.fade(o);
let rest_w = s.border_width.unwrap();
let border_width = rest_w + (s.focused_border_width.unwrap() - rest_w) * fp;
let radius = s.radius.unwrap();
let fill = s.fill.unwrap();
if self.is_borderless() {
// **Nothing.** The container belongs to whatever this field was put inside.
} else if self.is_outlined() {
scene.draw_rect(field, fill.fade(o), radius, border_width, border_color);
} else {
// Filled: a container with its **top** corners rounded, and a single line
// under it. A box all the way round would be the other variant wearing a fill.
scene.draw_rect(
field,
fill.fade(o),
frus_core::BorderRadius {
top_left: radius,
top_right: radius,
bottom_right: 0.0,
bottom_left: 0.0,
},
0.0,
frus_core::Color::TRANSPARENT,
);
scene.fill_rect(
Rect::new(
field.x,
field.y + field.height - border_width,
field.width,
border_width,
),
border_color,
);
}
// The label goes **after** the box, in both styles. Floated, it sits above the
// box and the order would not matter; at rest it sits *inside* it, in the
// hint's place, over an opaque surface. It used to be painted first and
// survived only because the renderer drew all text above everything — which it
// stopped doing in milestone 295, and the golden went blank.
if !self.is_outlined() {
if let Some((label, x, y, size, color)) = &label_geom {
// `exact`: `size` is already an interpolation between two **resolved**
// numbers, so resolving it again would apply the reader's setting twice.
let style = ResolvedTextStyle::exact(*size);
scene.text(Point::new(*x, *y), label.clone(), &style, color.fade(o));
}
}
// Outlined: the label's **notch**. The border segment behind the floating label
// is masked by a flat surface-coloured fill, then the label is painted on top.
// The notch only opens as the label rises (`float_t`).
if self.is_outlined() {
if let Some((label, x, y, size, color)) = &label_geom {
if float_t > 0.01 {
let label_w = frus_text::measure(label, self.label_size()).width;
let notch = Rect::new(
*x - FIELD_NOTCH_GAP,
field.y - (border_width + FIELD_NOTCH_GAP) * 0.5,
label_w + FIELD_NOTCH_GAP * 2.0,
border_width + FIELD_NOTCH_GAP,
);
scene.fill_rect(notch, theme.surface.fade(o * float_t));
}
scene.text(
Point::new(*x, *y),
label.clone(),
&ResolvedTextStyle::exact(*size),
color.fade(o),
);
}
}
// Decorative icons, vertically centred in the box (a discreet colour).
let icon_color = s.icon_color.unwrap().fade(o);
let icon_y = field.y + (field.height - self.icon_size()) * 0.5;
if let Some(prefix) = self.prefix {
let path = prefix.placed(
self.icon_size(),
field.x + ICON_PAD,
icon_y,
theme.direction,
);
scene.fill_path(&path, icon_color);
}
if let Some(suffix) = self.suffix {
let x = field.x + field.width - self.icon_size() - ICON_PAD;
// Highlight (milestone 208): a discreet halo behind the **clickable** suffix when
// the pointer hovers it (the absolute position is brought back to local through
// `bounds`). Purely visual.
if self.suffix_action.is_some() {
if let Some(hc) = status.hover_cursor {
if self.suffix_hit(hc.x - bounds.x, hc.y - bounds.y, bounds.width) {
let halo = Rect::new(
x - 4.0,
icon_y - 4.0,
self.icon_size() + 8.0,
self.icon_size() + 8.0,
);
scene.draw_rect(
halo,
theme.muted.fade(o * 0.18),
halo.height * 0.5,
0.0,
frus_core::Color::TRANSPARENT,
);
}
}
}
let path = suffix.placed(self.icon_size(), x, icon_y, theme.direction);
scene.fill_path(&path, icon_color);
}
let len = self.value.chars().count();
// The content is inset between the prefix/suffix icons, where there are any.
let content_x = content_left;
let content_w = self.content_width(bounds.width);
let text_y = field.y + self.text_top();
// Multi-line: the text **wraps** at the content width — the same `max_width` for
// the measure (caret/hit) and for the render → identical wraps.
let wrap = if self.multiline {
Some(content_w)
} else {
None
};
let layout = self.layout(wrap);
// The alignment's push, worked out once and used by the placeholder, the text,
// the selection, the underline and the caret — every one of which is drawn from
// `text_x` below.
let align = self.align_offset(content_w, layout.size().width);
// Hint (placeholder): displayed when the field is empty. If there is a label as
// well, the hint only reveals itself (fading in) once the label has floated —
// otherwise the two would overlap inside the box.
if self.value.is_empty() {
if let Some(placeholder) = &self.placeholder {
let ph_alpha = if self.label.is_some() { o * float_t } else { o };
if ph_alpha > 0.01 {
// The placeholder sits where the text will: a centred field whose
// hint hugs the left edge jumps the moment the first key lands.
let style = self.text_style();
let hint_w = frus_text::measure_resolved(placeholder, &style).width;
let hint_align = self.align_offset(content_w, hint_w);
scene.text(
Point::new(content_x + hint_align, text_y),
placeholder.clone(),
&style,
theme.muted.fade(ph_alpha),
);
}
}
}
// The affixes, in the hint's colour, shown as the label floats — or, with no label,
// once the field is focused or holds something (`input_decorator.dart:1830`).
let affix_alpha = if self.label.is_some() {
float_t
} else if self.value.is_empty() {
match self.floating_behavior(theme) {
FloatingLabelBehavior::Always => 1.0,
_ => fp,
}
} else {
1.0
} * o;
if affix_alpha > 0.01 {
let style = self.text_style();
if let Some(prefix) = &self.prefix_text {
scene.text(
Point::new(field.x + self.pad_x() + self.prefix_icon_w(), text_y),
prefix.clone(),
&style,
theme.muted.fade(affix_alpha),
);
}
if let Some(suffix) = &self.suffix_text {
let w = self.affix_w(&self.suffix_text);
scene.text(
Point::new(
field.x + field.width - self.pad_x() - self.suffix_icon_w() - w,
text_y,
),
suffix.clone(),
&style,
theme.muted.fade(affix_alpha),
);
}
}
// Scrolling to keep the caret visible: horizontal (always) and vertical
// (multi-line). Recomputed from the cursor, as on click (`cursor_at`).
let cursor = status.cursor.unwrap_or(len).min(len);
let caret = layout.caret_rect(cursor);
let scroll = if status.focused {
(caret.x - content_w).max(0.0)
} else {
0.0
};
let text_x = content_x + align - scroll;
// **Retained** vertical scroll (wheel/scrollbar, caret-following by the shell);
// clamped to how far the content overflows the box.
let vscroll = if self.multiline {
let overflow = (layout.size().height
- (field.height - self.text_top() - self.pad_bottom()))
.max(0.0);
status.scroll_y.clamp(0.0, overflow)
} else {
0.0
};
// Vertical origin of the content (offset by the multi-line scroll).
let text_top = text_y - vscroll;
// Clipped to the **content** frame — inside the padding, not the whole box.
// Clipping to the box let scrolled multi-line text ride up onto the top border,
// which is where an outlined field's floating label lives: the third line of a
// scrolled field was painted straight over the label naming it. It only became
// visible once the padding grew to the reference's, which is the useful kind of
// regression — the old 6 px hid it rather than avoided it.
let outer_clip = scene.current_clip();
let content_clip = outer_clip.intersect(Rect::new(
content_x,
field.y + self.text_top(),
content_w,
(field.height - self.text_top() - self.pad_bottom()).max(0.0),
));
scene.set_clip(content_clip);
// Selection highlight (below the text).
if status.focused {
if let Some((start, end)) = status.selection {
for r in layout.selection_rects(start.min(len), end.min(len)) {
scene.fill_rect(
Rect::new(text_x + r.x, text_top + r.y, r.width, r.height),
theme.selection.fade(o),
);
}
}
}
if !self.value.is_empty() {
let pos = Point::new(text_x, text_top);
let color = theme.on_surface.fade(o);
match wrap {
// Multi-line: the render wraps just as the measure did.
Some(max_w) => {
scene.text_wrapped(pos, self.display(), &self.text_style(), color, max_w)
}
None => scene.text(pos, self.display(), &self.text_style(), color),
}
}
// The IME **composition** region: underlined (provisional text). Drawn over the
// text, below the baseline.
if status.focused {
if let Some((start, end)) = status.composing {
let (start, end) = (start.min(len), end.min(len));
for r in layout.selection_rects(start, end) {
scene.fill_rect(
Rect::new(text_x + r.x, text_top + r.y + r.height - 1.5, r.width, 1.5),
theme.on_surface.fade(o * 0.7),
);
}
}
}
// The caret, in the shown half of its blink (milestone 513).
// In the reference's colour, `primary`, and the error's while one shows; its shape the
// caller's or the platform's (milestone 659).
if status.focused && !status.caret_hidden && self.cursor.shown {
let color = if has_error {
s.cursor_error_color.unwrap()
} else {
s.cursor_color.unwrap()
};
let height = self.cursor.height.unwrap_or(caret.height);
let radius =
self.cursor
.radius
.unwrap_or(if theme.platform.is_apple() { 2.0 } else { 0.0 });
scene.draw_rect(
Rect::new(
text_x + caret.x,
text_top + caret.y + (caret.height - height) * 0.5,
self.cursor.width,
height,
),
color.fade(o),
radius,
0.0,
Color::TRANSPARENT,
);
}
// The handles of a touch selection (milestone 511), outside the content clip:
// they hang below their line, past the text and, on the last line, past the box.
if status.focused && status.handles {
scene.set_clip(outer_clip);
let edit = Edit {
cursor,
anchor: status
.selection
.map(|(a, b)| if cursor == a { b } else { a }),
composing: None,
};
if let Some(handles) = self.handles(bounds.width, &edit, status.scroll_y) {
let color = s.handle_color.unwrap().fade(o);
paint_handles(scene, handles, Point::new(bounds.x, bounds.y), color);
}
}
}
fn on_click(&self) -> Option<Msg> {
None
}
fn positional_click(
&self,
local_x: f32,
local_y: f32,
width: f32,
_height: f32,
) -> Option<Msg> {
if !self.enabled {
return None;
}
if self.suffix_action.is_some() && self.suffix_hit(local_x, local_y, width) {
self.suffix_action.clone()
} else {
None
}
}
fn cursor_icon(
&self,
local_x: f32,
local_y: f32,
width: f32,
_height: f32,
) -> Option<crate::interaction::Cursor> {
// A hand over the **active** suffix icon (clear / reveal); elsewhere, no opinion.
if self.suffix_action.is_some() && self.suffix_hit(local_x, local_y, width) {
Some(crate::interaction::Cursor::Pointer)
} else {
None
}
}
fn on_edit(&self, edit: &mut Edit, key: &Key) -> Option<Msg> {
// A disabled field cannot be focused, so this should be unreachable — but a key
// arriving from a stale focus must not edit a value the caller has declared
// untouchable.
if !self.enabled {
return None;
}
let mut chars: Vec<char> = self.value.chars().collect();
let len = chars.len();
let mut cursor = edit.cursor.min(len);
let mut anchor = edit.anchor.map(|a| a.min(len));
let selection = anchor
.map(|a| (a.min(cursor), a.max(cursor)))
.filter(|(s, e)| s < e);
let mut changed = false;
match key {
Key::Text(text) => {
// The filter, one character at a time: a rejected one never arrives and
// a substituted one takes the same place, so the caret arithmetic below
// is the arithmetic it always was.
let inserted: Vec<char> = match &self.input_filter {
Some(filter) => text.chars().filter_map(filter).collect(),
None => text.chars().collect(),
};
// Nothing typed and nothing selected is nothing done: emitting the value
// unchanged would rebuild the tree for a keystroke that was refused.
// A selection **is** something done, even when what replaces it is
// empty, since the reference filters the value after the replacement.
if selection.is_some() || !inserted.is_empty() {
if let Some((s, e)) = selection {
chars.drain(s..e);
cursor = s;
}
let n = inserted.len();
chars.splice(cursor..cursor, inserted);
cursor += n;
anchor = None;
changed = true;
}
}
Key::Backspace => {
if let Some((s, e)) = selection {
chars.drain(s..e);
cursor = s;
changed = true;
} else if cursor > 0 {
chars.remove(cursor - 1);
cursor -= 1;
changed = true;
}
anchor = None;
}
Key::Delete => {
if let Some((s, e)) = selection {
chars.drain(s..e);
cursor = s;
changed = true;
} else if cursor < len {
chars.remove(cursor);
changed = true;
}
anchor = None;
}
// The caret's own keys: an arrow, a word under Ctrl, the ends of the line — of the
// whole field under Ctrl, which in a single-line field is the same.
Key::Left { .. } | Key::Right { .. } | Key::Home { .. } | Key::End { .. } => {
move_caret(&chars, &mut cursor, &mut anchor, key);
}
// Escape is none of editing's business (routed leaf→root by the shell).
Key::Escape => {}
Key::Enter if self.multiline => {
// Multi-line: Enter **inserts a line break** (no submission).
if let Some((s, e)) = selection {
chars.drain(s..e);
cursor = s;
}
chars.insert(cursor, '\n');
cursor += 1;
anchor = None;
changed = true;
}
Key::Enter => {
// Single-line: Enter submits — it does not alter the value, it emits the submission.
edit.cursor = cursor;
edit.anchor = anchor;
return self.on_submit.clone();
}
}
// Read-only: everything that only **moves** has already happened -- the caret,
// the selection, the word jumps -- and is kept. What is refused is the change,
// which is the whole of the difference between this and a disabled field, where
// there is no caret to move in the first place.
if self.read_only && changed {
return None;
}
// The limit, enforced the way the reference enforces it: what fits lands and the
// rest does not. Dropping a whole paste for being one character too long would
// lose work the user can see they had, and refusing the keystroke that crosses
// the limit is the same rule seen one character at a time.
//
// A value the **caller** supplied over the limit is left alone: it is the
// application's state, not something typed, and silently shortening it would be
// editing a value nobody edited. The counter shows it over.
if changed {
if let Some(max) = self.max_length {
if chars.len() > max {
chars.truncate(max);
cursor = cursor.min(max);
anchor = anchor.map(|a| a.min(max));
}
}
}
edit.cursor = cursor;
edit.anchor = anchor;
if changed {
let new_value: String = chars.into_iter().collect();
self.on_input.as_ref().map(|make| make(new_value))
} else {
None
}
}
fn ime(&self) -> Ime {
self.ime_options()
}
fn cursor_at(
&self,
local_x: f32,
local_y: f32,
width: f32,
scroll_cursor: usize,
) -> Option<usize> {
// A disabled field takes no caret: it is readable, not editable, and a caret
// sitting in it would promise otherwise.
if !self.enabled {
return None;
}
// A click on the **clickable suffix icon**: do not place a caret (the shell will
// emit its message through `positional_click`).
if self.suffix_action.is_some() && self.suffix_hit(local_x, local_y, width) {
return None;
}
// Rebuilds the same content geometry as the render (icon and decoration insets,
// wrapping, horizontal scroll), for an exact click. The **retained vertical
// scroll** is already folded into `local_y` by the shell.
let left = self.lead();
let content_w = self.content_width(width);
let layout = self.layout(if self.multiline {
Some(content_w)
} else {
None
});
let scroll = (layout.caret_rect(scroll_cursor).x - content_w).max(0.0);
// The same push the paint applied, from the same function. Without it a click on
// centred or right-aligned text lands wherever the glyphs *would* have been
// against the left edge, which is a caret appearing several characters from the
// tap.
let align = self.align_offset(content_w, layout.size().width);
// `local_*` are relative to the **widget's** top-left corner (label included):
// the label band and the padding are removed to land inside the text.
let target_x = local_x - left - align + scroll;
let target_y = local_y - self.label_block() - self.text_top();
Some(layout.hit_test(Point::new(target_x, target_y)))
}
fn text_metrics(&self, width: f32, cursor: usize) -> Option<(f32, f32, f32, f32)> {
if !self.multiline {
return None;
}
let layout = self.layout(Some(self.content_width(width)));
let caret = layout.caret_rect(cursor);
let visible = self.field_height_at(width) - self.text_top() - self.pad_bottom();
Some((layout.size().height, visible, caret.y, caret.height))
}
fn text_viewport(&self, rect: Rect) -> Option<Rect> {
if !self.multiline {
return None;
}
// The input box: below the label, as tall as the `rows`.
Some(Rect::new(
rect.x,
rect.y + self.label_block(),
rect.width,
self.field_height_at(rect.width),
))
}
fn caret_vertical(
&self,
width: f32,
cursor: usize,
down: bool,
page: bool,
goal_x: Option<f32>,
) -> Option<(usize, f32)> {
if !self.multiline {
return None;
}
let layout = self.layout(Some(self.content_width(width)));
let caret = layout.caret_rect(cursor);
let line_h = caret.height;
// Wanted column: the remembered target, otherwise the current column.
let x = goal_x.unwrap_or(caret.x);
// A step of one line, or of one page (the field's visible height, at least 1 line).
let step = if page {
(self.field_height_at(width) - self.text_top() - self.pad_bottom()).max(line_h)
} else {
line_h
};
let center = caret.y + line_h * 0.5;
let target_y = if down { center + step } else { center - step };
let full = layout.size().height;
if page {
// Page: clamped to the field (it is never left).
let clamped = target_y.clamp(0.0, (full - line_h * 0.5).max(0.0));
Some((layout.hit_test(Point::new(x, clamped)), x))
} else {
// Line: already on the first/last one → the shell moves the focus.
if target_y < 0.0 || target_y >= full {
return None;
}
Some((layout.hit_test(Point::new(x, target_y)), x))
}
}
fn text_value(&self) -> Option<&str> {
Some(&self.value)
}
/// A field that is read-only, or that cannot be focused, takes no typing.
fn takes_typing(&self) -> bool {
self.enabled && !self.read_only
}
fn replace_value(&self, value: String) -> Option<Msg> {
// The same two refusals `on_edit` makes, for the same reason: a field the caller
// has declared untouchable does not become touchable because the value being put
// back came out of it. No filter and no length limit, though — this value passed
// both on its way in, and running it through them again would let an undo land
// somewhere the field has never been.
if !self.enabled || self.read_only {
return None;
}
self.on_input.as_ref().map(|make| make(value))
}
fn semantics(&self) -> Option<frus_core::SemanticsProperties> {
let mut s = frus_core::SemanticsProperties::new(frus_core::Role::TextInput)
.value(self.value.clone());
// The label names the field — the placeholder when there is none, as the reference
// reads a hint out for a field that has no label, so a reader is never told only
// "edit" (milestone 710); an error is appended so it gets read out.
let name = self.label.as_ref().or(self.placeholder.as_ref());
let label = match (name, &self.error) {
(Some(l), Some(e)) => Some(format!("{l}, {e}")),
(Some(l), None) => Some(l.clone()),
(None, Some(e)) => Some(e.clone()),
(None, None) => None,
};
if let Some(label) = label {
s = s.label(label);
}
if !self.enabled {
s = s.disabled(true);
}
Some(s)
}
fn selected_text(&self, edit: &Edit) -> Option<String> {
// A masked field gives its text to nobody: what is shown is dots, and what is
// copied must not be the thing they hide.
if self.obscure {
return None;
}
let chars: Vec<char> = self.value.chars().collect();
let len = chars.len();
let cursor = edit.cursor.min(len);
let anchor = edit.anchor?.min(len);
let (start, end) = (anchor.min(cursor), anchor.max(cursor));
if start < end {
Some(chars[start..end].iter().collect())
} else {
None
}
}
fn word_at(&self, index: usize) -> Option<(usize, usize)> {
let chars: Vec<char> = self.value.chars().collect();
word_range(&chars, index)
}
fn selection_handles(
&self,
width: f32,
edit: &Edit,
scroll_y: f32,
) -> Option<[crate::SelectionHandle; 2]> {
self.handles(width, edit, scroll_y)
}
fn selection_toolbar(&self, context: ToolbarContext) -> Option<&dyn Widget<Msg>> {
self.toolbars[usize::from(context.variant())]
.get_or_init(|| {
let defaults = self.default_toolbar_items(&context);
let items = match &self.toolbar_build {
Some(build) => build(&context, defaults),
None => defaults,
};
(!items.is_empty()).then(|| {
let bar: Box<dyn Widget<Msg>> = Box::new(SelectionToolbar::new(items));
bar
})
})
.as_deref()
}
fn selection_anchor(&self, width: f32, edit: &Edit, scroll_y: f32) -> Option<Rect> {
Some(self.selection_box(width, edit, scroll_y))
}
fn autofill_hints(&self) -> &[AutofillHint] {
&self.autofill
}
fn autofocus(&self) -> bool {
self.autofocus && self.enabled
}
fn on_tap_outside(&self) -> Option<Msg> {
self.on_tap_outside.clone()
}
fn focusable(&self) -> bool {
self.enabled
}
fn draws_own_focus(&self) -> bool {
true
}
fn announce(&self) -> Option<String> {
self.announce.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::icons::Icons;
#[derive(Clone, Debug, PartialEq)]
enum Msg {
Changed(String),
Submitted,
}
/// **A field with no label is named by its placeholder** (milestone 710), as the reference
/// reads a hint out; a label wins over it, and an error is still appended.
#[test]
fn a_field_with_no_label_is_named_by_its_placeholder() {
let name = |field: TextField<Msg>| Widget::<Msg>::semantics(&field).and_then(|s| s.label);
assert_eq!(
name(TextField::new("").placeholder("New task")).as_deref(),
Some("New task")
);
assert_eq!(
name(TextField::new("").placeholder("e.g. Ada").label("Name")).as_deref(),
Some("Name")
);
assert_eq!(
name(TextField::new("").placeholder("New task").error("Required")).as_deref(),
Some("New task, Required")
);
assert_eq!(name(TextField::new("")), None);
}
fn input(value: &str) -> TextField<Msg> {
TextField::new(value).on_input(Msg::Changed)
}
/// Every rectangle a field paints, in order.
fn rects(field: &TextField<Msg>, theme: &Theme, w: f32, h: f32) -> Vec<frus_core::Primitive> {
let mut scene = Scene::new();
Widget::<Msg>::paint(
field,
Rect::new(0.0, 0.0, w, h),
Status::default(),
theme,
&mut scene,
);
scene
.primitives()
.iter()
.filter(|p| matches!(p, frus_core::Primitive::Rect { .. }))
.cloned()
.collect()
}
/// The reference's content padding is `(12, 8, 12, 8)` filled and `(12, 20, 12, 12)`
/// outlined, and the outlined asymmetry is the room its floating label takes on the
/// border. A field measured any other way is a field that does not line up beside
/// anything else drawn to the same specification.
#[test]
fn a_field_is_the_references_size() {
let line = input("x").text_style().line_height();
let outlined = input("x");
assert_eq!(
outlined.field_height(),
(line + FIELD_OUTLINED_PADDING_TOP + FIELD_OUTLINED_PADDING_BOTTOM).ceil()
);
// A filled field is tighter — until it carries a label, which it floats *inside*
// the box and therefore has to make room for.
let filled = input("x").filled();
assert_eq!(filled.field_height(), (line + FIELD_PADDING_Y * 2.0).ceil());
let labelled = input("x").filled().label("Name");
assert_eq!(
labelled.field_height() - filled.field_height(),
(FIELD_GAP + FIELD_TEXT_SIZE * FIELD_LABEL_SCALE).ceil()
);
// The label shrinks by a proportion, not to a fixed size: a field given larger
// text keeps the relationship.
assert_eq!(input("x").size(32.0).label_size(), 24.0);
}
/// A field is 56 px tall, which is right for a form and wrong inside a table row.
/// `dense` is the reference's answer, and it gives back the padding without changing
/// the shape, the label or the border.
#[test]
fn a_dense_field_gives_back_its_padding() {
let line = input("x").text_style().line_height();
assert_eq!(
input("x").dense(true).field_height(),
(line + FIELD_DENSE_OUTLINED_PADDING_TOP + FIELD_DENSE_OUTLINED_PADDING_BOTTOM).ceil()
);
assert_eq!(
input("x").filled().dense(true).field_height(),
(line + FIELD_DENSE_PADDING_Y * 2.0).ceil()
);
// It is only the room: a dense field is shorter than its roomy twin in both
// variants, and never taller.
for dense in [input("x").dense(true), input("x").filled().dense(true)] {
let roomy = if dense.is_outlined() {
input("x")
} else {
input("x").filled()
};
assert!(dense.field_height() < roomy.field_height());
}
}
/// A filled field is a container with **one line under it**; an outlined one is a box.
/// Drawing a fill inside a stroked box on all four sides would be the other variant
/// wearing a tint, which is the mistake this variant exists to avoid.
#[test]
fn a_filled_field_has_a_line_not_a_box() {
let theme = Theme::default();
let stroked = |field: &TextField<Msg>| {
rects(field, &theme, 220.0, 80.0)
.iter()
.filter(|p| {
matches!(p, frus_core::Primitive::Rect { border_width, .. } if *border_width > 0.0)
})
.count()
};
assert_eq!(
stroked(&input("x").outlined()),
1,
"outlined: one stroked box"
);
assert_eq!(stroked(&input("x").filled()), 0, "filled: nothing stroked");
// ...and the line is a filled rectangle the width of the field, at its foot.
let filled = input("x").filled();
let height = filled.field_height();
let has_underline = rects(&filled, &theme, 220.0, 80.0).iter().any(|p| {
matches!(
p,
frus_core::Primitive::Rect { rect, border_width, .. }
if *border_width == 0.0
&& (rect.width - 220.0).abs() < 0.5
&& (rect.height - FIELD_BORDER_WIDTH).abs() < 0.5
&& (rect.y + rect.height - height).abs() < 0.5
)
});
assert!(has_underline, "a filled field is underlined");
}
/// A disabled field keeps 38% of its colours and shows no focus — it cannot be
/// focused, so a ring left over from before would say the wrong thing about Tab.
#[test]
fn a_disabled_field_dims_and_never_looks_focused() {
let theme = Theme::default();
let focused = Status {
focus_progress: 1.0,
..Default::default()
};
let border = |field: &TextField<Msg>, status: Status| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
field,
Rect::new(0.0, 0.0, 220.0, 80.0),
status,
&theme,
&mut scene,
);
scene.primitives().iter().find_map(|p| match p {
frus_core::Primitive::Rect {
border_width,
border_color,
..
} if *border_width > 0.0 => Some((*border_width, *border_color)),
_ => None,
})
};
let (live_w, live_c) = border(&input("x"), focused).unwrap();
assert_eq!(
live_w, FIELD_FOCUSED_BORDER_WIDTH,
"focus widens the border"
);
assert_eq!(live_c.a, 1.0, "and it is fully opaque");
let (dead_w, dead_c) = border(&input("x").enabled(false), focused).unwrap();
assert_eq!(dead_w, FIELD_BORDER_WIDTH, "disabled: no focus weight");
assert!(
(dead_c.a - FIELD_DISABLED_OPACITY).abs() < 0.01,
"disabled: dimmed to the reference's 38%, got {}",
dead_c.a
);
}
/// Scrolled multi-line text must stay **inside the padding**, not merely inside the
/// box: the top border is where an outlined field's floating label lives, and text
/// clipped only to the box was painted straight over the label naming it.
#[test]
fn scrolled_text_is_clipped_below_the_label() {
let theme = Theme::default();
let field = input("one\ntwo\nthree\nfour\nfive\nsix")
.rows(3)
.label("Notes");
let mut scene = Scene::new();
Widget::<Msg>::paint(
&field,
Rect::new(0.0, 0.0, 220.0, 140.0),
Status {
scroll_y: 40.0,
..Default::default()
},
&theme,
&mut scene,
);
let box_top = field.label_block();
let clip = scene
.primitives()
.iter()
.find_map(|p| match p {
// The label and the helper are painted unclipped; the value is not, and
// its clip is the one under test.
frus_core::Primitive::Text { clip, .. } if clip.y > -1.0e6 => Some(*clip),
_ => None,
})
.expect("the value is clipped");
assert!(
clip.y >= box_top + field.text_top() - 0.5,
"the clip starts below the padding, not at the border: {} < {}",
clip.y,
box_top + field.text_top()
);
}
/// Greying a field out is not enough: it has to be out of the tab order, refuse a
/// caret, and ignore a key that reaches it from a focus set before it was disabled.
#[test]
fn a_disabled_field_is_inert() {
let live = input("hello");
let dead = input("hello").enabled(false);
assert!(Widget::<Msg>::focusable(&live));
assert!(!Widget::<Msg>::focusable(&dead), "out of the tab order");
assert!(
Widget::<Msg>::cursor_at(&live, 40.0, 30.0, 220.0, 0).is_some(),
"a live field takes a caret"
);
assert_eq!(
Widget::<Msg>::cursor_at(&dead, 40.0, 30.0, 220.0, 0),
None,
"a disabled field takes none"
);
let mut edit = Edit::default();
assert!(
Widget::on_edit(&dead, &mut edit, &Key::Text("x".into())).is_none(),
"and no key edits it"
);
let semantics = Widget::<Msg>::semantics(&dead).unwrap();
assert!(semantics.disabled, "a reader is told it is disabled");
}
/// `caller ?? theme ?? framework`, on a field that has all three to choose from.
#[test]
fn the_caller_outranks_the_theme_which_outranks_the_framework() {
let radius = |field: &TextField<Msg>, theme: &Theme| {
rects(field, theme, 220.0, 80.0)
.iter()
.find_map(|p| match p {
frus_core::Primitive::Rect {
border_width,
radius,
..
} if *border_width > 0.0 => Some(radius.top_left),
_ => None,
})
.unwrap()
};
let plain = Theme::default();
assert_eq!(radius(&input("x"), &plain), FIELD_RADIUS);
let mut themed = Theme::default();
themed.widgets.text_field.radius = Some(10.0);
assert_eq!(radius(&input("x"), &themed), 10.0);
let overridden = input("x").style(TextFieldStyle {
radius: Some(2.0),
..Default::default()
});
assert_eq!(radius(&overridden, &themed), 2.0);
}
#[test]
fn text_is_clipped_to_content_box() {
// Text longer than the field must be clipped to its content width (otherwise it
// overflows onto the neighbouring widgets).
let inp = input("a very long value that overflows the field width").width(100.0);
let mut scene = Scene::new();
Widget::<Msg>::paint(
&inp,
Rect::new(0.0, 0.0, 100.0, 30.0),
Status::default(),
&Theme::default(),
&mut scene,
);
let clip = scene
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Text { clip, .. } => Some(*clip),
_ => None,
})
.expect("text primitive");
assert!(
(clip.width - (100.0 - FIELD_PADDING_X * 2.0)).abs() < 0.5,
"clip = {clip:?}"
);
}
#[test]
fn composing_region_draws_an_underline() {
// The composed region adds thin rectangles (the underline) below the text,
// absent when no composition is in progress.
let inp = input("konnichiwa");
let base = Status {
focused: true,
cursor: Some(5),
..Default::default()
};
let composing = Status {
composing: Some((0, 5)),
..base
};
let count_thin_rects = |status: Status| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
&inp,
Rect::new(0.0, 0.0, 220.0, 30.0),
status,
&Theme::default(),
&mut scene,
);
scene
.primitives()
.iter()
.filter(|p| matches!(p, frus_core::Primitive::Rect { rect, .. } if rect.height <= 2.0 && rect.width > 2.0))
.count()
};
let plain = count_thin_rects(base);
let underlined = count_thin_rects(composing);
assert!(
underlined > plain,
"the composition must underline ({plain} → {underlined})"
);
}
#[test]
fn text_value_exposes_the_field_content() {
// The input context (IME suggestions) reads the field's value.
let inp = input("hello");
assert_eq!(Widget::<Msg>::text_value(&inp), Some("hello"));
}
#[test]
fn cursor_at_accounts_for_scroll() {
// A narrow field + long text → scrolling once the caret is at the end.
let inp = input("0123456789 abcdefghij");
// Without scrolling (cursor 0): a click on the left edge → index 0.
assert_eq!(
Widget::<Msg>::cursor_at(&inp, FIELD_PADDING_X, FIELD_OUTLINED_PADDING_TOP, 80.0, 0),
Some(0)
);
// Scrolled (caret at the end): a click on the right lands on a larger index than
// a click on the left (the offset is indeed taken into account).
let end = inp.value.chars().count();
let at_left =
Widget::<Msg>::cursor_at(&inp, FIELD_PADDING_X, FIELD_OUTLINED_PADDING_TOP, 80.0, end)
.unwrap();
let at_right =
Widget::<Msg>::cursor_at(&inp, 76.0, FIELD_OUTLINED_PADDING_TOP, 80.0, end).unwrap();
assert!(at_left > 0, "scrolled: the left edge is no longer index 0");
assert!(at_right > at_left, "a click on the right → a larger index");
}
#[test]
fn insert_at_cursor() {
let inp = input("ac");
let mut edit = Edit {
cursor: 1,
anchor: None,
composing: None,
};
assert_eq!(
inp.on_edit(&mut edit, &Key::Text("b".to_string())),
Some(Msg::Changed("abc".to_string()))
);
assert_eq!(edit.cursor, 2);
}
#[test]
fn shift_arrow_selects_then_delete() {
let inp = input("hello");
// Caret at the end, Shift+Left twice -> selects "lo".
let mut edit = Edit {
cursor: 5,
anchor: None,
composing: None,
};
inp.on_edit(
&mut edit,
&Key::Left {
shift: true,
word: false,
},
);
inp.on_edit(
&mut edit,
&Key::Left {
shift: true,
word: false,
},
);
assert_eq!(edit.selection_range(), Some((3, 5)));
// Backspace deletes the selection.
assert_eq!(
inp.on_edit(&mut edit, &Key::Backspace),
Some(Msg::Changed("hel".to_string()))
);
assert_eq!(edit.cursor, 3);
assert_eq!(edit.anchor, None);
}
#[test]
fn home_end_bounds() {
let inp = input("abc");
let mut edit = Edit {
cursor: 1,
anchor: None,
composing: None,
};
inp.on_edit(
&mut edit,
&Key::End {
shift: false,
doc: false,
},
);
assert_eq!(edit.cursor, 3);
inp.on_edit(
&mut edit,
&Key::Home {
shift: false,
doc: false,
},
);
assert_eq!(edit.cursor, 0);
}
#[test]
fn ctrl_arrow_jumps_by_word() {
let inp = input("foo bar baz");
// From the end, Ctrl+Left jumps to the start of "baz", then "bar", then "foo".
let mut edit = Edit {
cursor: 11,
anchor: None,
composing: None,
};
inp.on_edit(
&mut edit,
&Key::Left {
shift: false,
word: true,
},
);
assert_eq!(edit.cursor, 8, "start of \"baz\"");
inp.on_edit(
&mut edit,
&Key::Left {
shift: false,
word: true,
},
);
assert_eq!(edit.cursor, 4, "start of \"bar\"");
// Ctrl+Right jumps to the end of "bar", then "baz".
inp.on_edit(
&mut edit,
&Key::Right {
shift: false,
word: true,
},
);
assert_eq!(edit.cursor, 7, "fin de \"bar\"");
inp.on_edit(
&mut edit,
&Key::Right {
shift: false,
word: true,
},
);
assert_eq!(edit.cursor, 11, "fin de \"baz\"");
}
#[test]
fn home_end_are_line_relative_but_ctrl_spans_the_field() {
// "ab\ncd\nef": caret in the middle of the 2nd line (index 4, between c and d).
let inp = TextField::<Msg>::new("ab\ncd\nef")
.on_input(Msg::Changed)
.rows(3);
let mut edit = Edit {
cursor: 4,
anchor: None,
composing: None,
};
// Plain Home → the start of the current line (index 3), not of the field.
inp.on_edit(
&mut edit,
&Key::Home {
shift: false,
doc: false,
},
);
assert_eq!(edit.cursor, 3, "start of the 2nd line");
// Plain End → the end of the current line (index 5).
inp.on_edit(
&mut edit,
&Key::End {
shift: false,
doc: false,
},
);
assert_eq!(edit.cursor, 5, "end of the 2nd line");
// Ctrl+Home / Ctrl+End → the bounds of the whole field.
inp.on_edit(
&mut edit,
&Key::Home {
shift: false,
doc: true,
},
);
assert_eq!(edit.cursor, 0, "start of the field");
inp.on_edit(
&mut edit,
&Key::End {
shift: false,
doc: true,
},
);
assert_eq!(edit.cursor, 8, "end of the field");
}
#[test]
fn selected_text_reads_range() {
let inp = input("hello");
let edit = Edit {
cursor: 5,
anchor: Some(2),
composing: None,
};
assert_eq!(inp.selected_text(&edit), Some("llo".to_string()));
}
/// The words on the buttons of the bar a field shows for `context`, in order — `None`
/// when it shows none.
fn bar_words(field: &TextField<Msg>, context: ToolbarContext) -> Option<Vec<String>> {
let bar = Widget::<Msg>::selection_toolbar(field, context)?;
Some(
bar.children()
.iter()
.map(|button| {
button
.semantics()
.and_then(|semantics| semantics.label)
.unwrap_or_default()
})
.collect(),
)
}
fn context(has_selection: bool, can_paste: bool, all_selected: bool) -> ToolbarContext {
ToolbarContext {
has_selection,
can_paste,
all_selected,
}
}
/// **The default bar** is decided by the three conditions (milestone 568): Cut and Copy
/// want a selection, Paste wants something to paste, Select all wants something left
/// unselected — in the reference's order.
#[test]
fn the_default_bar_follows_the_three_conditions() {
let field = input("hello world");
let words = |ctx| bar_words(&field, ctx);
assert_eq!(
words(context(true, true, false)),
Some(vec![
"Cut".into(),
"Copy".into(),
"Paste".into(),
"Select all".into()
])
);
assert_eq!(
words(context(false, true, false)),
Some(vec!["Paste".into(), "Select all".into()])
);
assert_eq!(
words(context(true, false, true)),
Some(vec!["Cut".into(), "Copy".into()])
);
assert_eq!(words(context(false, false, true)), None, "nothing to offer");
}
/// **A field that keeps a secret gives none away**: a masked field offers neither Cut
/// nor Copy, and its selected text is not readable for the clipboard either — Ctrl+C
/// used to put the password itself on the clipboard.
#[test]
fn a_masked_field_offers_neither_cut_nor_copy_and_copies_nothing() {
let field = input("hunter2").obscure(true);
assert_eq!(
bar_words(&field, context(true, true, false)),
Some(vec!["Paste".into(), "Select all".into()])
);
let selected = Edit {
cursor: 7,
anchor: Some(0),
composing: None,
};
assert_eq!(field.selected_text(&selected), None);
// The same field unmasked copies as before.
assert_eq!(
input("hunter2").selected_text(&selected),
Some("hunter2".to_string())
);
}
/// A read-only field keeps its text as it is: it can be copied from and selected, not
/// cut from and not pasted into.
#[test]
fn a_read_only_field_offers_copy_and_select_all_only() {
let field = input("REF-0042").read_only();
assert_eq!(
bar_words(&field, context(true, true, false)),
Some(vec!["Copy".into(), "Select all".into()])
);
}
/// **The application has the last word** on the list: it is handed the context and the
/// defaults, and what it returns is what shows — an item dropped, one of its own added,
/// or an empty list for no bar.
#[test]
fn the_application_rewrites_the_list() {
let field = input("hello").selection_toolbar(|context, mut items| {
items.retain(|item| item.label() != "Paste");
if context.has_selection {
items.push(ToolbarItem::custom("Translate", Msg::Submitted));
}
items
});
assert_eq!(
bar_words(&field, context(true, true, false)),
Some(vec![
"Cut".into(),
"Copy".into(),
"Select all".into(),
"Translate".into()
])
);
assert_eq!(
bar_words(&field, context(false, true, false)),
Some(vec!["Select all".into()]),
"the custom item only for a selection"
);
let none = input("hello").selection_toolbar(|_, _| Vec::new());
assert_eq!(bar_words(&none, context(true, true, false)), None);
}
/// The application's own item sends its message, and a built-in one sends nothing (the
/// shell performs it).
#[test]
fn an_application_item_sends_its_message_and_a_built_in_one_does_not() {
let field = input("hello").selection_toolbar(|_, mut items| {
items.push(ToolbarItem::custom("Translate", Msg::Submitted));
items
});
let bar =
Widget::<Msg>::selection_toolbar(&field, context(true, false, false)).expect("a bar");
let buttons = bar.children();
let clicks: Vec<Option<Msg>> = buttons.iter().map(|b| b.on_click()).collect();
let actions: Vec<Option<crate::EditAction>> =
buttons.iter().map(|b| b.edit_action()).collect();
assert_eq!(clicks, vec![None, None, None, Some(Msg::Submitted)]);
assert_eq!(
actions,
vec![
Some(crate::EditAction::Cut),
Some(crate::EditAction::Copy),
Some(crate::EditAction::SelectAll),
None
]
);
}
/// The bar is placed against the **selection's** box, in the field's own coordinates:
/// wider for a longer selection, at the caret (no width) when nothing is selected.
#[test]
fn the_bar_is_anchored_on_the_selection_or_the_caret() {
let field = input("hello world");
let word = Edit {
cursor: 5,
anchor: Some(0),
composing: None,
};
let all = Edit {
cursor: 11,
anchor: Some(0),
composing: None,
};
let caret = Edit {
cursor: 5,
anchor: None,
composing: None,
};
let anchor =
|edit: &Edit| Widget::<Msg>::selection_anchor(&field, 200.0, edit, 0.0).unwrap();
assert!(anchor(&all).width > anchor(&word).width);
assert_eq!(anchor(&caret).width, 0.0);
assert!(anchor(&caret).height > 0.0);
// Where the selection's own handles stand is where its box begins and ends.
let handles = Widget::<Msg>::selection_handles(&field, 200.0, &word, 0.0).unwrap();
let word_box = anchor(&word);
assert!((word_box.x - handles[0].line_center.x).abs() < 0.5);
assert!((word_box.x + word_box.width - handles[1].line_center.x).abs() < 0.5);
}
#[test]
fn enter_submits_without_changing_value() {
let inp = input("acheter du lait").on_submit(Msg::Submitted);
let mut edit = Edit {
cursor: 3,
anchor: None,
composing: None,
};
// Enter: emits the submission, returns no value change.
assert_eq!(inp.on_edit(&mut edit, &Key::Enter), Some(Msg::Submitted));
assert_eq!(edit.cursor, 3); // caret unchanged
}
#[test]
fn enter_without_submit_is_noop() {
let inp = input("x");
let mut edit = Edit {
cursor: 1,
anchor: None,
composing: None,
};
assert_eq!(inp.on_edit(&mut edit, &Key::Enter), None);
}
/// Where the text was actually drawn: the x of the field's own text primitive.
fn drawn_text_x(field: &TextField<()>, width: f32) -> f32 {
let mut scene = Scene::new();
Widget::<()>::paint(
field,
Rect::new(0.0, 0.0, width, 56.0),
Status {
focused: false,
..Default::default()
},
&Theme::default(),
&mut scene,
);
scene
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Text { position, text, .. } if text == "42" => {
Some(position.x)
}
_ => None,
})
.expect("the value is drawn")
}
/// A field says nothing, and the text starts where it always did.
#[test]
fn a_field_that_says_nothing_starts_at_the_left() {
let plain: TextField<()> = TextField::new("42");
let started: TextField<()> = TextField::new("42").text_align(TextAlign::Start);
assert_eq!(drawn_text_x(&plain, 300.0), drawn_text_x(&started, 300.0));
}
/// Centred and right-aligned text moves, and moves the right way round.
#[test]
fn the_text_sits_where_it_was_told_to() {
let left = drawn_text_x(&TextField::<()>::new("42"), 300.0);
let centre = drawn_text_x(
&TextField::<()>::new("42").text_align(TextAlign::Center),
300.0,
);
let right = drawn_text_x(
&TextField::<()>::new("42").text_align(TextAlign::Right),
300.0,
);
assert!(left < centre, "centred is further right than left-aligned");
assert!(centre < right, "right-aligned is further right again");
// Centred is halfway: the two gaps either side match.
assert!(
((centre - left) - (right - centre)).abs() < 0.5,
"halfway: {left} {centre} {right}"
);
}
/// **The click has to agree with the paint.** A caret placed from the unaligned
/// geometry would appear several characters from the tap, and it is the kind of
/// wrongness nobody reports precisely — it just feels broken.
#[test]
fn a_click_lands_where_the_glyphs_are() {
let width = 300.0;
for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {
let field: TextField<()> = TextField::new("42").text_align(align);
let x = drawn_text_x(&field, width);
// A tap a hair to the left of the first glyph belongs before it\u2026
let before = Widget::<()>::cursor_at(&field, x - 1.0, 20.0, width, 0);
assert_eq!(before, Some(0), "{align:?}: before the first character");
// \u2026and one past the last glyph belongs after it.
let text_w = frus_text::measure("42", field.size).width;
let after = Widget::<()>::cursor_at(&field, x + text_w + 1.0, 20.0, width, 0);
assert_eq!(after, Some(2), "{align:?}: after the last character");
}
}
/// Nothing to distribute, nothing to push. A line wider than its field keeps its
/// left edge, which is where reading starts and where the horizontal scroll brings
/// the caret back to.
#[test]
fn text_wider_than_the_field_is_not_pushed_off_it() {
let long: TextField<()> = TextField::new("42").text_align(TextAlign::Right);
// A box far too narrow for the value: the slack is negative, so the push is nil.
assert_eq!(long.align_offset(4.0, 40.0), 0.0);
assert_eq!(long.align_offset(40.0, 40.0), 0.0);
}
/// A multi-line field stays at the start. Aligning wrapped text means moving each
/// line by its own width, which the caret and the click would have to be told about
/// line by line — that belongs inside the text layout, not in a widget nudging a
/// block sideways behind their backs.
#[test]
fn a_multiline_field_is_not_aligned() {
let note: TextField<()> = TextField::new("42")
.multiline()
.text_align(TextAlign::Center);
assert_eq!(note.align_offset(300.0, 40.0), 0.0);
// The same field on one line would have moved.
let one_line: TextField<()> = TextField::new("42").text_align(TextAlign::Center);
assert_eq!(one_line.align_offset(300.0, 40.0), 130.0);
}
/// The placeholder sits where the text will. A centred field whose hint hugs the
/// left edge jumps the moment the first key lands.
#[test]
fn the_placeholder_is_aligned_like_the_value() {
let hint_x = |align: TextAlign| {
let field: TextField<()> = TextField::new("").placeholder("Amount").text_align(align);
let mut scene = Scene::new();
Widget::<()>::paint(
&field,
Rect::new(0.0, 0.0, 300.0, 56.0),
Status::default(),
&Theme::default(),
&mut scene,
);
scene
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Text { position, text, .. } if text == "Amount" => {
Some(position.x)
}
_ => None,
})
.expect("the hint is drawn")
};
assert!(hint_x(TextAlign::Right) > hint_x(TextAlign::Center));
assert!(hint_x(TextAlign::Center) > hint_x(TextAlign::Left));
}
/// A filtered field drops what it will not take, and keeps the rest of a paste.
#[test]
fn a_filter_drops_what_it_will_not_take() {
let field: TextField<String> = TextField::new("").digits_only().on_input(|v| v);
let mut edit = Edit::default();
// A paste of a formatted number: the digits land, the spaces and dashes do not.
let out = Widget::on_edit(&field, &mut edit, &Key::Text("12 34-56".into()));
assert_eq!(out.as_deref(), Some("123456"));
assert_eq!(edit.cursor, 6, "the caret is past what actually arrived");
}
/// A refused keystroke is not an edit: emitting the value unchanged would rebuild
/// the tree for a key that did nothing.
#[test]
fn a_refused_keystroke_says_nothing() {
let field: TextField<String> = TextField::new("42").digits_only().on_input(|v| v);
let mut edit = Edit {
cursor: 2,
..Default::default()
};
assert_eq!(
Widget::on_edit(&field, &mut edit, &Key::Text("x".into())),
None
);
assert_eq!(edit.cursor, 2, "and the caret has not moved");
}
/// A **selection** replaced by nothing is still an edit: the selection is gone.
#[test]
fn a_refused_keystroke_over_a_selection_still_clears_it() {
let field: TextField<String> = TextField::new("1234").digits_only().on_input(|v| v);
let mut edit = Edit {
cursor: 3,
anchor: Some(1),
..Default::default()
};
let out = Widget::on_edit(&field, &mut edit, &Key::Text("x".into()));
assert_eq!(out.as_deref(), Some("14"));
assert_eq!(edit.cursor, 1);
}
/// A filter can **substitute** as well as drop, and the caret arithmetic is the same
/// because a substituted character takes the place of the one typed.
#[test]
fn a_filter_can_substitute() {
let field: TextField<String> = TextField::new("")
.input_filter(|c| c.to_uppercase().next())
.on_input(|v| v);
let mut edit = Edit::default();
let out = Widget::on_edit(&field, &mut edit, &Key::Text("ab".into()));
assert_eq!(out.as_deref(), Some("AB"));
assert_eq!(edit.cursor, 2);
}
/// A value the **caller** supplied is left alone: it is the application's state, not
/// something typed.
#[test]
fn a_filter_does_not_rewrite_what_the_caller_gave() {
let field: TextField<String> = TextField::new("a1b2").digits_only().on_input(|v| v);
let mut edit = Edit {
cursor: 4,
..Default::default()
};
let out = Widget::on_edit(&field, &mut edit, &Key::Text("3".into()));
assert_eq!(
out.as_deref(),
Some("a1b23"),
"only the keystroke is filtered"
);
}
/// Digits ask for a keypad, and a keyboard named either side of it stands.
#[test]
fn digits_only_asks_for_a_keypad_without_overruling_one() {
let plain: TextField<()> = TextField::new("").digits_only();
assert_eq!(Widget::<()>::ime(&plain).keyboard, KeyboardType::Number);
let before: TextField<()> = TextField::new("")
.keyboard_type(KeyboardType::Phone)
.digits_only();
assert_eq!(Widget::<()>::ime(&before).keyboard, KeyboardType::Phone);
let after: TextField<()> = TextField::new("")
.digits_only()
.keyboard_type(KeyboardType::Phone);
assert_eq!(Widget::<()>::ime(&after).keyboard, KeyboardType::Phone);
}
/// The capitalisation reaches the keyboard the field asks for.
#[test]
fn the_capitalisation_travels_with_the_field() {
let field: TextField<()> = TextField::new("").capitalization(Capitalization::Characters);
let ime = Widget::<()>::ime(&field);
assert_eq!(ime.capitalization, Capitalization::Characters);
assert_eq!(ime.android_input_type() & 0x0000_7000, 0x0000_1000);
}
/// A plain field asks for the plain keyboard, which is what every field used to
/// get whether it suited or not.
#[test]
fn a_plain_field_asks_for_the_plain_keyboard() {
let field: TextField<()> = TextField::new("hello");
assert_eq!(
Widget::<()>::ime(&field),
Ime {
keyboard: KeyboardType::Text,
action: TextInputAction::Done,
capitalization: Capitalization::Auto,
}
);
}
/// **A masked field is a secret, and the dots cannot say so.** `obscure` draws
/// dots on our side; the keyboard, told nothing, treated the field as ordinary
/// prose — learning the password into its personal dictionary and offering it
/// back as a suggestion later, on whatever screen came next.
#[test]
fn an_obscured_field_tells_the_keyboard_it_is_a_secret() {
let field: TextField<()> = TextField::new("hunter2").obscure(true);
let ime = Widget::<()>::ime(&field);
assert_eq!(ime.keyboard, KeyboardType::Password);
assert!(ime.keyboard.is_secret());
// TYPE_TEXT_VARIATION_PASSWORD, which is what stops the learning.
assert_eq!(ime.keyboard.android_input_type() & 0x0000_0ff0, 0x80);
}
/// A field that takes several lines needs the action key to **insert** one.
/// *Done* there is a keyboard that cannot type what the field is for.
#[test]
fn a_multiline_field_takes_a_newline_key() {
let field: TextField<()> = TextField::new("a note").multiline();
let ime = Widget::<()>::ime(&field);
assert_eq!(ime.keyboard, KeyboardType::Multiline);
assert_eq!(ime.action, TextInputAction::Newline);
// `rows` implies multiline, so it implies the same keyboard.
let rowed: TextField<()> = TextField::new("a note").rows(4);
assert_eq!(Widget::<()>::ime(&rowed).keyboard, KeyboardType::Multiline);
}
/// What the caller says beats what the field guessed — both halves, separately.
#[test]
fn what_the_caller_says_wins() {
let field: TextField<()> = TextField::new("")
.obscure(true)
.keyboard_type(KeyboardType::VisiblePassword);
assert_eq!(
Widget::<()>::ime(&field).keyboard,
KeyboardType::VisiblePassword
);
// A search box asks for Search without ceasing to be a text field.
let query: TextField<()> = TextField::new("").action(TextInputAction::Search);
let ime = Widget::<()>::ime(&query);
assert_eq!(ime.keyboard, KeyboardType::Text);
assert_eq!(ime.action, TextInputAction::Search);
// And a multi-line field can still be told to say Done.
let note: TextField<()> = TextField::new("").multiline().action(TextInputAction::Done);
assert_eq!(Widget::<()>::ime(¬e).action, TextInputAction::Done);
}
/// A field that says what it is gets the keyboard for it — a keypad for a phone
/// number, an `@` for an address.
#[test]
fn a_typed_field_gets_the_keyboard_for_it() {
let phone: TextField<()> = TextField::new("").keyboard_type(KeyboardType::Phone);
// TYPE_CLASS_PHONE
assert_eq!(Widget::<()>::ime(&phone).keyboard.android_input_type(), 3);
let email: TextField<()> = TextField::new("").keyboard_type(KeyboardType::Email);
let bits = Widget::<()>::ime(&email).keyboard.android_input_type();
// TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_EMAIL_ADDRESS, and no capitalisation:
// `Someone@` is an address that does not work.
assert_eq!(bits, 1 | 0x20);
}
#[test]
fn obscure_masks_the_displayed_text_but_not_the_value() {
// A password field: the render never contains the value in the clear, only dots;
// the real value stays reachable (editing, IME).
let theme = Theme::default();
let field = TextField::<Msg>::new("secret").obscure(true);
let mut scene = Scene::new();
let status = Status {
focused: true,
cursor: Some(6),
..Default::default()
};
Widget::<Msg>::paint(
&field,
Rect::new(0.0, 0.0, 220.0, 30.0),
status,
&theme,
&mut scene,
);
let drawn: Vec<&str> = scene
.primitives()
.iter()
.filter_map(|p| match p {
frus_core::Primitive::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect();
assert!(
drawn.iter().all(|t| !t.contains("secret")),
"the value must not leak"
);
assert!(
drawn.iter().any(|t| t.chars().all(|c| c == '•')),
"dots are drawn"
);
// The real value stays exposed to the input context.
assert_eq!(Widget::<Msg>::text_value(&field), Some("secret"));
}
#[test]
fn prefix_icon_draws_a_path_and_shifts_the_hit_test() {
// A prefix icon draws a path and offsets the content to the right: the same
// click lands on a smaller index than it would without one.
let theme = Theme::default();
let with_icon = input("hello world").prefix_icon(Icons::STAR);
let mut scene = Scene::new();
Widget::<Msg>::paint(
&with_icon,
Rect::new(0.0, 0.0, 220.0, 30.0),
Status::default(),
&theme,
&mut scene,
);
assert!(
scene
.primitives()
.iter()
.any(|p| matches!(p, frus_core::Primitive::Path { .. })),
"the prefix icon draws a path"
);
let plain = input("hello world");
let at_plain =
Widget::<Msg>::cursor_at(&plain, 60.0, FIELD_OUTLINED_PADDING_TOP, 220.0, 0).unwrap();
let at_icon =
Widget::<Msg>::cursor_at(&with_icon, 60.0, FIELD_OUTLINED_PADDING_TOP, 220.0, 0)
.unwrap();
assert!(
at_icon < at_plain,
"the prefix offsets the content ({at_plain} → {at_icon})"
);
}
#[test]
fn multiline_enter_inserts_a_newline_instead_of_submitting() {
// In multi-line mode, Enter inserts a "\n" (and emits no submission).
let inp = TextField::<Msg>::new("ab")
.on_input(Msg::Changed)
.multiline();
let mut edit = Edit {
cursor: 2,
anchor: None,
composing: None,
};
assert_eq!(
inp.on_edit(&mut edit, &Key::Enter),
Some(Msg::Changed("ab\n".to_string()))
);
assert_eq!(edit.cursor, 3);
// Single line: Enter submits (unchanged behaviour).
let single = input("ab").on_submit(Msg::Submitted);
let mut edit = Edit {
cursor: 2,
anchor: None,
composing: None,
};
assert_eq!(single.on_edit(&mut edit, &Key::Enter), Some(Msg::Submitted));
}
#[test]
fn multiline_wraps_long_lines_to_the_width() {
// A long line **without** any `\n` wraps onto several visual lines: a click well
// below the 1st line places the caret further into the text (a wrapped line under
// the first one), not at index 0.
let long = "word ".repeat(30); // 150 characters, no explicit break
let inp = TextField::<Msg>::new(long.trim_end())
.on_input(Msg::Changed)
.rows(4)
.width(160.0);
let line_h = inp.text_style().line_height();
let top = Widget::<Msg>::cursor_at(
&inp,
FIELD_PADDING_X + 2.0,
FIELD_OUTLINED_PADDING_TOP + 1.0,
160.0,
0,
)
.unwrap();
let wrapped = Widget::<Msg>::cursor_at(
&inp,
FIELD_PADDING_X + 2.0,
FIELD_OUTLINED_PADDING_TOP + line_h * 2.0 + 1.0,
160.0,
0,
)
.unwrap();
assert!(top < 10, "1st line: {top}");
assert!(
wrapped > top,
"a wrapped line further down → an index further on ({top} → {wrapped})"
);
}
#[test]
fn multiline_reports_overflow_and_scrolls_content() {
// Five lines in a box of two: the content overflows…
let inp = TextField::<Msg>::new("l1\nl2\nl3\nl4\nl5")
.on_input(Msg::Changed)
.rows(2)
.width(200.0);
let (content_h, visible_h, _, _) =
Widget::<Msg>::text_metrics(&inp, 200.0, 0).expect("a multi-line field");
assert!(
content_h > visible_h + 1.0,
"5 lines > a box of 2 ({content_h} vs {visible_h})"
);
// …and a retained scroll shifts the text upwards (a smaller position.y).
let text_top = |scroll: f32| {
let mut scene = Scene::new();
let status = Status {
focused: true,
cursor: Some(0),
scroll_y: scroll,
..Default::default()
};
Widget::<Msg>::paint(
&inp,
Rect::new(0.0, 0.0, 200.0, 80.0),
status,
&Theme::default(),
&mut scene,
);
scene
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Text { text, position, .. } if text.contains("l1") => {
Some(position.y)
}
_ => None,
})
.expect("the field's text")
};
assert!(
text_top(20.0) < text_top(0.0),
"scrolling raises the content"
);
}
#[test]
fn multiline_arrows_move_the_caret_between_lines() {
// "abc\ndefg\nhi": line 0 = indices 0..3, line 1 = 4..8, line 2 = 9..11.
let inp = TextField::<Msg>::new("abc\ndefg\nhi")
.on_input(Msg::Changed)
.rows(3)
.width(200.0);
// From the 1st line (index 1), moving down lands on the 2nd line.
let (down, _) = Widget::<Msg>::caret_vertical(&inp, 200.0, 1, true, false, None).unwrap();
assert!(
(4..=8).contains(&down),
"moves down to the 2nd line: {down}"
);
// 1st line, moving up → impossible (the shell moves the focus).
assert_eq!(
Widget::<Msg>::caret_vertical(&inp, 200.0, 1, false, false, None),
None
);
// Last line (index 10), moving down → impossible.
assert_eq!(
Widget::<Msg>::caret_vertical(&inp, 200.0, 10, true, false, None),
None
);
// 2nd line (index 5), moving up lands on the 1st.
let (up, _) = Widget::<Msg>::caret_vertical(&inp, 200.0, 5, false, false, None).unwrap();
assert!(up <= 3, "moves up to the 1st line: {up}");
// A single-line field: never any vertical movement.
assert_eq!(
Widget::<Msg>::caret_vertical(&input("abc"), 200.0, 1, true, false, None),
None
);
}
#[test]
fn multiline_goal_column_survives_a_short_line() {
// "hello\nhi\nworld": line 0 = 0..5, line 1 = 6..8 (short), line 2 = 9..14.
// Starting from column 5 (the end of "hello") and moving down: the 2nd line "hi"
// is too short (so the caret is clamped to its end), but the goal column returned
// stays ~the starting one, so moving down again lands back on column 5.
let inp = TextField::<Msg>::new("hello\nhi\nworld")
.on_input(Msg::Changed)
.rows(3)
.width(200.0);
let (mid, goal) = Widget::<Msg>::caret_vertical(&inp, 200.0, 5, true, false, None).unwrap();
assert!(
(6..=8).contains(&mid),
"a short line, clamped to its end: {mid}"
);
// A second jump reusing the goal column: without memory the caret would have
// stayed clamped to the end of "hi" (col. ~2); here it lands far into "world"
// (col. ~5), proving the original column survives the short line.
let (low, _) =
Widget::<Msg>::caret_vertical(&inp, 200.0, mid, true, false, Some(goal)).unwrap();
assert!(
(12..=14).contains(&low),
"goal column preserved into \"world\": {low}"
);
}
#[test]
fn multiline_page_jump_is_clamped_to_the_field() {
// Page up/down never leave the multi-line field: at the bounds the caret settles
// at the start / at the end and returns `Some` (not `None` → the field is kept).
let inp = TextField::<Msg>::new("a\nb\nc\nd\ne")
.on_input(Msg::Changed)
.rows(2)
.width(200.0);
// From the last line, PgDn settles at the bottom (the field is not left).
let (bottom, _) = Widget::<Msg>::caret_vertical(&inp, 200.0, 8, true, true, None).unwrap();
assert!(
bottom >= 7,
"PgDn clamped to the bottom of the field: {bottom}"
);
// From the 1st line, PgUp settles at the top.
let (top, _) = Widget::<Msg>::caret_vertical(&inp, 200.0, 0, false, true, None).unwrap();
assert!(top <= 1, "PgUp clamped to the top of the field: {top}");
}
#[test]
fn multiline_reserves_rows_of_height() {
// `rows(n)` reserves n lines; that is taller than a one-line field.
let one = match Widget::<Msg>::style(&input("x")).height {
Dimension::Length(h) => h,
_ => panic!("a fixed height"),
};
let four = match Widget::<Msg>::style(&TextField::<Msg>::new("x").rows(4)).height {
Dimension::Length(h) => h,
_ => panic!("a fixed height"),
};
assert!(
four > one * 2.0,
"4 lines much taller than one ({one} → {four})"
);
}
#[test]
fn multiline_hit_test_uses_the_click_line() {
// A click on the 2nd line places the caret inside "cd" (indices ≥ 3), not inside
// the "ab" of the 1st line.
let inp = TextField::<Msg>::new("ab\ncd")
.on_input(Msg::Changed)
.rows(3);
let line_h = inp.text_style().line_height();
// A top-left click → the 1st line (index ≤ 2).
let top = Widget::<Msg>::cursor_at(
&inp,
FIELD_PADDING_X + 1.0,
FIELD_OUTLINED_PADDING_TOP + 1.0,
220.0,
0,
)
.unwrap();
// A click one line lower → the 2nd line (index ≥ 3).
let below = Widget::<Msg>::cursor_at(
&inp,
FIELD_PADDING_X + 1.0,
FIELD_OUTLINED_PADDING_TOP + line_h + 1.0,
220.0,
0,
)
.unwrap();
assert!(top <= 2, "1st line: {top}");
assert!(below >= 3, "2nd line: {below}");
}
#[test]
fn floating_label_rests_in_box_then_floats_up() {
// The label rests inside the box (large, low) while the field is empty and
// unfocused, and floats above it (small, high) once focused.
let theme = Theme::default();
let field = TextField::<Msg>::new("").label("Name");
let label_geo = |status: Status| -> (f32, f32) {
let mut scene = Scene::new();
Widget::<Msg>::paint(
&field,
Rect::new(0.0, 30.0, 220.0, 60.0),
status,
&theme,
&mut scene,
);
scene
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Text {
text,
size,
position,
..
} if text == "Name" => Some((*size, position.y)),
_ => None,
})
.expect("a painted label")
};
let (rest_size, rest_y) = label_geo(Status::default());
let (float_size, float_y) = label_geo(Status {
focused: true,
focus_progress: 1.0,
..Default::default()
});
assert!(
rest_size > float_size,
"at rest the label is larger ({rest_size} → {float_size})"
);
assert!(
float_y < rest_y,
"once focused the label rises ({rest_y} → {float_y})"
);
}
/// **An errored field deepens under the pointer** (milestone 439).
///
/// `error` at rest, `on_error_container` while hovered, and `error` again once
/// focused — the reference tests focus **before** hover
/// (`input_decorator.dart:5977`), because a focused field is already saying
/// everything it can. The message below it does not move: `errorStyle` is `error` in
/// every state (`:6100`), it being a sentence rather than a control.
///
/// It is the first thing here to ask the scheme for `on_error_container`, which
/// arrived in milestone 429 with nothing wanting it.
#[test]
fn an_errored_field_deepens_under_the_pointer() {
let theme = Theme::default();
let field = input("x").label("Name").error("Required").outlined();
let painted = |status: Status| {
let mut scene = Scene::new();
Widget::<Msg>::paint(
&field,
Rect::new(0.0, 0.0, 220.0, 90.0),
status,
&theme,
&mut scene,
);
scene
};
// The border is the only stroked rectangle a field paints.
let border = |status: Status| {
painted(status)
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Rect {
border_color,
border_width,
..
} if *border_width > 0.0 => Some(*border_color),
_ => None,
})
.expect("an outlined field draws a border")
};
let message = |status: Status| {
painted(status)
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Text { text, color, .. } if text == "Required" => {
Some(*color)
}
_ => None,
})
.expect("the message is painted")
};
let rest = Status {
opacity: 1.0,
..Default::default()
};
let hovered = Status {
hover_progress: 1.0,
..rest
};
let both = Status {
focused: true,
focus_progress: 1.0,
..hovered
};
assert_eq!(border(rest), theme.scheme.error);
assert_eq!(
border(hovered),
theme.scheme.on_error_container,
"it deepens under the pointer"
);
assert_eq!(
border(both),
theme.scheme.error,
"and comes back once focused, which the reference tests first"
);
assert_ne!(
theme.scheme.error, theme.scheme.on_error_container,
"the two have to differ for any of the above to mean anything"
);
for status in [rest, hovered, both] {
assert_eq!(
message(status),
theme.scheme.error,
"the message is a sentence, not a control"
);
}
}
#[test]
fn decoration_grows_height_for_label_and_error() {
// A bare field reserves only the box; a label + an error add one line above and
// one below → the style is taller.
let bare_h = match Widget::<Msg>::style(&input("x")).height {
Dimension::Length(h) => h,
_ => panic!("a fixed height was expected"),
};
let decorated = input("x").label("Email").error("Required");
let deco_h = match Widget::<Msg>::style(&decorated).height {
Dimension::Length(h) => h,
_ => panic!("a fixed height was expected"),
};
assert!(
deco_h > bare_h,
"label + error grow the field ({bare_h} → {deco_h})"
);
}
#[test]
fn error_paints_the_border_in_the_error_color() {
// In error, the box's border switches to the theme's error colour.
let theme = Theme::default();
let field = input("x").error("bad");
let mut scene = Scene::new();
Widget::<Msg>::paint(
&field,
Rect::new(0.0, 0.0, 220.0, 60.0),
Status::default(),
&theme,
&mut scene,
);
let has_error_border = scene.primitives().iter().any(|p| {
matches!(
p,
frus_core::Primitive::Rect { border_color, border_width, .. }
if *border_width > 0.0 && *border_color == theme.error
)
});
assert!(has_error_border, "the border must be in the error colour");
}
#[test]
fn placeholder_shows_only_when_empty() {
// The hint only appears while the value is empty.
let theme = Theme::default();
let count_texts = |value: &str| {
let field = TextField::<Msg>::new(value).placeholder("Type here");
let mut scene = Scene::new();
Widget::<Msg>::paint(
&field,
Rect::new(0.0, 0.0, 220.0, 30.0),
Status::default(),
&theme,
&mut scene,
);
scene
.primitives()
.iter()
.filter(
|p| matches!(p, frus_core::Primitive::Text { text, .. } if text == "Type here"),
)
.count()
};
assert_eq!(count_texts(""), 1, "empty: the hint shows");
assert_eq!(count_texts("hi"), 0, "rempli : pas d'indice");
}
#[test]
fn clickable_suffix_emits_and_blocks_caret() {
let field = TextField::new("hello")
.suffix_icon(Icons::CLOSE)
.on_suffix(Msg::Submitted)
.width(220.0);
let (w, y) = (220.0, 12.0);
let x_suffix = w - 8.0; // near the right edge (the suffix's zone)
// A click on the suffix: emits the message, and does NOT place a caret.
assert_eq!(
Widget::<Msg>::positional_click(&field, x_suffix, y, w, 40.0),
Some(Msg::Submitted)
);
assert_eq!(Widget::<Msg>::cursor_at(&field, x_suffix, y, w, 0), None);
// A click in the body: no suffix, a caret is placed.
assert_eq!(
Widget::<Msg>::positional_click(&field, 20.0, y, w, 40.0),
None
);
assert!(Widget::<Msg>::cursor_at(&field, 20.0, y, w, 0).is_some());
// Without `on_suffix` the icon stays decorative (no positional click).
let deco = TextField::<Msg>::new("hello")
.suffix_icon(Icons::CLOSE)
.width(220.0);
assert_eq!(
Widget::<Msg>::positional_click(&deco, x_suffix, y, w, 40.0),
None
);
}
#[test]
fn hovering_active_suffix_paints_a_halo() {
let field = TextField::new("hello")
.suffix_icon(Icons::CLOSE)
.on_suffix(Msg::Submitted)
.width(220.0);
let bounds = Rect::new(0.0, 0.0, 220.0, 40.0);
// Counts the ~28x28 rectangles (the halo behind the suffix icon).
let halos = |status: Status| {
let mut scene = Scene::new();
Widget::<Msg>::paint(&field, bounds, status, &Theme::default(), &mut scene);
scene
.primitives()
.iter()
.filter(|p| match p {
frus_core::Primitive::Rect { rect, .. } => {
(rect.width - (FIELD_ICON_SIZE + 8.0)).abs() < 0.5
&& (rect.height - (FIELD_ICON_SIZE + 8.0)).abs() < 0.5
}
_ => false,
})
.count()
};
// Pointer over the suffix → one halo; elsewhere (the body) or without hover → none.
let over_suffix = Status {
hover_cursor: Some(Point::new(212.0, 20.0)),
..Default::default()
};
let over_body = Status {
hover_cursor: Some(Point::new(20.0, 20.0)),
..Default::default()
};
assert_eq!(halos(over_suffix), 1, "a halo on the hovered suffix");
assert_eq!(halos(over_body), 0, "no halo in the body");
assert_eq!(halos(Status::default()), 0, "no halo without hover");
}
#[test]
fn cursor_icon_is_pointer_over_active_suffix() {
use crate::interaction::Cursor;
let field = TextField::new("hello")
.suffix_icon(Icons::CLOSE)
.on_suffix(Msg::Submitted)
.width(220.0);
let (w, h, y) = (220.0, 40.0, 12.0);
// A hand over the suffix, nothing in the body.
assert_eq!(
Widget::<Msg>::cursor_icon(&field, w - 8.0, y, w, h),
Some(Cursor::Pointer)
);
assert_eq!(Widget::<Msg>::cursor_icon(&field, 20.0, y, w, h), None);
// A decorative suffix (no on_suffix): no hand.
let deco = TextField::<Msg>::new("hello")
.suffix_icon(Icons::CLOSE)
.width(220.0);
assert_eq!(Widget::<Msg>::cursor_icon(&deco, w - 8.0, y, w, h), None);
}
/// **Each handle stands for its own end of the selection** (milestone 511): the point
/// it carries, handed back to the field's own hit test, is that end — with a label and
/// an icon moving the text in, and with text scrolled sideways, which is where a
/// handle and its end would part company first. The shell drags a handle through
/// exactly this round trip.
#[test]
fn each_handle_stands_for_its_own_end_of_the_selection() {
let width = 220.0;
let fields = [
TextField::<Msg>::new("hello world").width(width),
TextField::<Msg>::new("hello world")
.label("Name")
.prefix_icon(Icons::CLOSE)
.width(width),
// Outlined, the label sits on the border and the box starts below it.
TextField::<Msg>::new("hello world")
.label("Name")
.outlined()
.width(width),
// Wider than its box, the caret at the far end: scrolled.
TextField::<Msg>::new("a sentence long enough to be scrolled along its box")
.width(width),
];
for field in &fields {
let len = field.value.chars().count();
let edit = Edit {
cursor: len,
anchor: Some(len - 5),
composing: None,
};
let [start, end] = Widget::<Msg>::selection_handles(field, width, &edit, 0.0)
.expect("a selection has handles");
for (handle, index) in [(start, len - 5), (end, len)] {
let at = handle.line_center;
assert_eq!(
Widget::<Msg>::cursor_at(field, at.x, at.y, width, edit.cursor),
Some(index),
"{:?}",
field.value
);
}
// Each hangs below its line and points in at the text: the corner the start
// one has squared off is its position, and the end one's likewise.
assert_eq!(start.rect.x + start.rect.width, start.line_center.x);
assert_eq!(end.rect.x, end.line_center.x);
assert!(start.rect.y > start.line_center.y && end.rect.y > end.line_center.y);
// And on the line the paint draws: the text's top, the line's middle, then the
// handle hanging from its bottom. A single line's hit test clamps the height, so
// only the paint can say the handles are at the right one.
let mut scene = Scene::new();
let status = Status {
focused: true,
cursor: Some(len),
selection: Some((len - 5, len)),
..Status::default()
};
Widget::<Msg>::paint(
field,
Rect::new(0.0, 0.0, width, 120.0),
status,
&Theme::default(),
&mut scene,
);
let top = scene
.primitives()
.iter()
.find_map(|p| match p {
frus_core::Primitive::Text { position, text, .. } if *text == field.value => {
Some(position.y)
}
_ => None,
})
.expect("the value is painted");
let half = start.line_center.y - top;
assert!(
half > 0.0 && (start.rect.y - top - 2.0 * half).abs() < 0.01,
"{:?}: text at {top}, line centre at {}, handle at {}",
field.value,
start.line_center.y,
start.rect.y
);
}
}
/// A multi-line field scrolled down carries its handles up with the text, and the
/// shell, folding the scroll back in as it does for a press, lands on the same ends.
#[test]
fn a_handle_rises_with_the_lines_a_field_scrolls_away() {
let width = 200.0;
let field = TextField::<Msg>::new("one\ntwo\nthree\nfour\nfive\nsix")
.multiline()
.rows(3)
.width(width);
// "five".
let edit = Edit {
cursor: 23,
anchor: Some(19),
composing: None,
};
let scroll = 20.0;
let still = Widget::<Msg>::selection_handles(&field, width, &edit, 0.0).unwrap();
let [start, end] = Widget::<Msg>::selection_handles(&field, width, &edit, scroll).unwrap();
assert!((still[0].line_center.y - start.line_center.y - scroll).abs() < 0.01);
for (handle, index) in [(start, 19), (end, 23)] {
let at = handle.line_center;
assert_eq!(
Widget::<Msg>::cursor_at(&field, at.x, at.y + scroll, width, edit.cursor),
Some(index)
);
}
}
/// Handles are painted for a selection the shell marks as a touch one, and for no
/// other: not for one made with a mouse, not in a field that has lost the focus. In
/// the scheme's primary, unless the field says otherwise.
#[test]
fn the_handles_are_painted_for_a_touch_selection_only() {
let theme = Theme::default();
let fills = |field: &TextField<Msg>, handles: bool, focused: bool| {
let mut scene = Scene::new();
let status = Status {
focused,
cursor: Some(11),
selection: Some((6, 11)),
handles,
..Status::default()
};
Widget::<Msg>::paint(
field,
Rect::new(10.0, 20.0, 220.0, 56.0),
status,
&theme,
&mut scene,
);
scene
.primitives()
.iter()
.filter_map(|p| match p {
frus_core::Primitive::Path { fill: Some(c), .. } => Some(*c),
_ => None,
})
.collect::<Vec<_>>()
};
let field = TextField::<Msg>::new("hello world").width(220.0);
assert_eq!(fills(&field, true, true), vec![theme.scheme.primary; 2]);
assert!(fills(&field, false, true).is_empty(), "a mouse selection");
assert!(fills(&field, true, false).is_empty(), "a field left behind");
let styled = TextField::<Msg>::new("hello world")
.width(220.0)
.style(TextFieldStyle {
handle_color: Some(frus_core::Color::WHITE),
..TextFieldStyle::default()
});
assert_eq!(fills(&styled, true, true), vec![frus_core::Color::WHITE; 2]);
}
/// The caret's hidden half paints no caret, and its shown half does (milestone 513).
#[test]
fn a_hidden_caret_is_not_painted() {
let theme = Theme::default();
let carets = |hidden: bool| {
let mut scene = Scene::new();
let status = Status {
focused: true,
cursor: Some(2),
caret_hidden: hidden,
..Status::default()
};
Widget::<Msg>::paint(
&TextField::<Msg>::new("hello").width(220.0),
Rect::new(0.0, 0.0, 220.0, 56.0),
status,
&theme,
&mut scene,
);
scene
.primitives()
.iter()
.filter(
|p| matches!(p, frus_core::Primitive::Rect { rect, .. } if rect.width == 2.0),
)
.count()
};
assert_eq!(carets(false), 1, "shown");
assert_eq!(carets(true), 0, "hidden");
}
#[test]
fn word_at_finds_word_bounds() {
let inp = input("hello there world");
// Any index inside a word yields that word's bounds; separators are excluded.
assert_eq!(inp.word_at(2), Some((0, 5))); // "hello"
assert_eq!(inp.word_at(13), Some((12, 17))); // "world"
}
}
#[cfg(test)]
mod limit_tests {
use super::*;
use crate::runtime::Edit;
#[derive(Clone, Debug, PartialEq)]
enum Msg {
Changed(String),
}
fn field(value: &str) -> TextField<Msg> {
TextField::new(value).on_input(Msg::Changed)
}
/// Types `text` at the end of the field's value and returns what came back.
fn typed(field: &TextField<Msg>, text: &str) -> (Option<Msg>, Edit) {
let end = field.value.chars().count();
let mut edit = Edit {
cursor: end,
anchor: None,
..Default::default()
};
let msg = Widget::on_edit(field, &mut edit, &Key::Text(text.to_string()));
(msg, edit)
}
fn value_of(msg: Option<Msg>) -> Option<String> {
msg.map(|Msg::Changed(v)| v)
}
/// A keystroke past the limit does not reach the value.
#[test]
fn a_keystroke_past_the_limit_goes_nowhere() {
let full = field("abcde").max_length(5);
assert_eq!(value_of(typed(&full, "f").0), Some("abcde".into()));
let room = field("abcd").max_length(5);
assert_eq!(value_of(typed(&room, "e").0), Some("abcde".into()));
}
/// A paste that crosses the limit lands the part that fits rather than being dropped
/// whole: losing work the user can see they had is the worse of the two answers.
#[test]
fn a_paste_that_crosses_the_limit_lands_what_fits() {
let f = field("ab").max_length(5);
let (msg, edit) = typed(&f, "cdefgh");
assert_eq!(value_of(msg), Some("abcde".into()));
assert_eq!(edit.cursor, 5, "the caret comes to rest at the end");
}
/// The limit is in **characters**, not bytes.
#[test]
fn the_limit_counts_characters_not_bytes() {
let f = field("").max_length(3);
assert_eq!(value_of(typed(&f, "éàü").0), Some("éàü".into()));
let full = field("éàü").max_length(3);
assert_eq!(value_of(typed(&full, "e").0), Some("éàü".into()));
}
/// A value the caller supplied over the limit is left alone — it is the application's
/// state, not something typed — and the counter says so.
#[test]
fn a_value_the_caller_set_over_the_limit_is_left_alone() {
let over = field("abcdefg").max_length(5);
assert_eq!(over.counter().as_deref(), Some("7/5"));
assert_eq!(over.value, "abcdefg");
}
/// The counter reserves the line below the box even with no helper to share it with.
#[test]
fn the_counter_reserves_the_line_it_sits_on() {
assert_eq!(
field("ab").sub_block(),
0.0,
"nothing to say, no room taken"
);
assert!(field("ab").max_length(5).sub_block() > 0.0);
assert_eq!(field("ab").max_length(5).counter().as_deref(), Some("2/5"));
}
/// Read-only refuses the **change** and keeps everything that only moves.
#[test]
fn read_only_refuses_the_change_and_keeps_the_caret() {
let f = field("hello").read_only();
assert_eq!(typed(&f, "x").0, None, "typing goes nowhere");
let mut edit = Edit {
cursor: 5,
anchor: None,
..Default::default()
};
assert_eq!(
Widget::on_edit(
&f,
&mut edit,
&Key::Left {
shift: false,
word: false
}
),
None
);
assert_eq!(edit.cursor, 4, "but the caret still moves");
let mut edit = Edit {
cursor: 5,
anchor: None,
..Default::default()
};
Widget::on_edit(
&f,
&mut edit,
&Key::Home {
shift: true,
doc: false,
},
);
assert_eq!(
(edit.cursor, edit.anchor),
(0, Some(5)),
"and a selection can still be made, so it can be copied"
);
}
/// Backspace is a change, so it is refused too — and leaves the caret alone.
#[test]
fn read_only_refuses_a_deletion() {
let f = field("hello").read_only();
let mut edit = Edit {
cursor: 5,
anchor: None,
..Default::default()
};
assert_eq!(Widget::on_edit(&f, &mut edit, &Key::Backspace), None);
assert_eq!(edit.cursor, 5);
}
/// It is not a disabled field: it keeps its caret and its place in the tab order.
#[test]
fn read_only_is_not_disabled() {
let read = field("REF-4417").read_only();
assert!(Widget::<Msg>::focusable(&read), "still in the tab order");
assert!(
Widget::<Msg>::cursor_at(&read, 20.0, 10.0, 200.0, 0).is_some(),
"and it still takes a caret, so a reference can be selected and copied"
);
let dead = field("REF-4417").enabled(false);
assert!(!Widget::<Msg>::focusable(&dead));
assert!(Widget::<Msg>::cursor_at(&dead, 20.0, 10.0, 200.0, 0).is_none());
}
}
/// The field's decoration, against the reference's (milestone 656).
#[cfg(test)]
mod decoration_tests {
use super::*;
use crate::Icons;
const W: f32 = 300.0;
/// Every text a field paints: what, where, in what colour.
fn texts(field: &TextField<()>, status: Status) -> Vec<(String, Point, Color)> {
let mut scene = Scene::new();
Widget::<()>::paint(
field,
Rect::new(0.0, 0.0, W, 80.0),
status,
&Theme::default(),
&mut scene,
);
scene
.primitives()
.iter()
.filter_map(|p| match p {
frus_core::Primitive::Text {
text,
position,
color,
..
} => Some((text.clone(), *position, *color)),
_ => None,
})
.collect()
}
fn find(texts: &[(String, Point, Color)], what: &str) -> Option<(Point, Color)> {
texts
.iter()
.find(|(text, ..)| text == what)
.map(|(_, at, color)| (*at, *color))
}
fn focused() -> Status {
Status {
focused: true,
focus_progress: 1.0,
..Default::default()
}
}
/// **The label's three behaviours**: auto rests inside an empty field and floats once
/// it holds something; always floats at once, so the hint shows; never rests inside an
/// empty field and is gone once it holds something.
#[test]
fn the_label_floats_as_it_is_told() {
let label_y =
|field: &TextField<()>, status| find(&texts(field, status), "Name").map(|(at, _)| at.y);
let auto = TextField::<()>::new("").label("Name");
let rest = label_y(&auto, Status::default()).unwrap();
let floated = label_y(&TextField::new("Ada").label("Name"), Status::default()).unwrap();
assert!(
floated < rest,
"auto floats once filled: {floated} < {rest}"
);
let always = TextField::<()>::new("")
.label("Name")
.placeholder("e.g. Ada")
.floating_label_behavior(FloatingLabelBehavior::Always);
let shown = texts(&always, Status::default());
assert_eq!(
find(&shown, "Name").unwrap().0.y,
floated,
"floated at rest"
);
assert!(find(&shown, "e.g. Ada").is_some(), "and the hint shows");
let never = |value: &str| {
TextField::<()>::new(value)
.label("Name")
.placeholder("e.g. Ada")
.floating_label_behavior(FloatingLabelBehavior::Never)
};
assert_eq!(
label_y(&never(""), focused()),
Some(rest),
"inside, even focused"
);
assert!(
find(&texts(&never(""), focused()), "e.g. Ada").is_none(),
"no hint"
);
assert_eq!(
label_y(&never("Ada"), Status::default()),
None,
"gone once filled"
);
let mut theme = Theme::default();
theme.widgets.text_field.floating_label_behavior = Some(FloatingLabelBehavior::Always);
let mut scene = Scene::new();
Widget::<()>::paint(
&TextField::<()>::new("").label("Name"),
Rect::new(0.0, 0.0, W, 80.0),
Status::default(),
&theme,
&mut scene,
);
let themed = scene.primitives().iter().find_map(|p| match p {
frus_core::Primitive::Text { text, position, .. } if text == "Name" => Some(position.y),
_ => None,
});
assert_eq!(themed, Some(floated), "the theme's word");
}
/// **A centred label floats to the middle** of the box, and rests at the start.
#[test]
fn a_centred_label_floats_to_the_middle() {
let x = |value: &str| {
let field = TextField::<()>::new(value)
.label("Name")
.floating_label_alignment(FloatingLabelAlignment::Center);
find(&texts(&field, Status::default()), "Name").unwrap().0.x
};
let width = frus_text::measure_resolved(
"Name",
&ResolvedTextStyle::exact(FIELD_TEXT_SIZE * FIELD_LABEL_SCALE),
)
.width;
assert!(((x("Ada") + width / 2.0) - W / 2.0).abs() < 0.5, "centred");
let rest = find(
&texts(&TextField::<()>::new("").label("Name"), Status::default()),
"Name",
)
.unwrap()
.0
.x;
assert_eq!(x(""), rest, "at rest, where the value starts");
}
/// **The affixes sit either side of the value**, in the hint's colour, and the value and
/// the caret move over for the prefix. They show once the label floats.
#[test]
fn the_affixes_sit_either_side_of_the_value() {
let theme = Theme::default();
let plain = TextField::<()>::new("42");
let priced = TextField::<()>::new("42")
.prefix_text("$")
.suffix_text("kg");
let shown = texts(&priced, Status::default());
let (dollar, colour) = find(&shown, "$").expect("the prefix");
let (value, _) = find(&shown, "42").unwrap();
let (unit, _) = find(&shown, "kg").expect("the suffix");
assert_eq!(colour, theme.muted, "the hint's colour");
let plain_x = find(&texts(&plain, Status::default()), "42").unwrap().0.x;
let style = TextStyle::new(FIELD_TEXT_SIZE).resolved();
let dollar_w = frus_text::measure_resolved("$", &style).width;
assert_eq!(dollar.x, plain_x, "the prefix where the value was");
assert!(
(value.x - (plain_x + dollar_w)).abs() < 1e-3,
"the value after it"
);
let unit_w = frus_text::measure_resolved("kg", &style).width;
assert!(
unit.x + unit_w <= W && unit.x > value.x,
"the suffix at the end"
);
// A click just after the prefix lands at the value's start.
let at = Widget::<()>::cursor_at(&priced, value.x + 0.5, 30.0, W, 0);
assert_eq!(at, Some(0));
// Empty and unfocused under a resting label, they wait; focused, they show.
let labelled = TextField::<()>::new("").label("Price").prefix_text("$");
assert!(find(&texts(&labelled, Status::default()), "$").is_none());
assert!(find(&texts(&labelled, focused()), "$").is_some());
// The resting label sits before the prefix, as the reference lays it out
// (`input_decorator.dart:1520`): the prefix is no part of where it rests.
let without = TextField::<()>::new("").label("Price");
assert_eq!(
find(&texts(&labelled, Status::default()), "Price")
.unwrap()
.0
.x,
find(&texts(&without, Status::default()), "Price")
.unwrap()
.0
.x
);
let bare = TextField::<()>::new("").prefix_text("$");
assert!(
find(&texts(&bare, Status::default()), "$").is_none(),
"no label: focus"
);
assert!(find(&texts(&bare, focused()), "$").is_some());
}
/// **The icon outside the box**: the box, its value and the line under it all start
/// after it, and a click is measured from there.
#[test]
fn the_outer_icon_moves_the_box_over() {
let plain = TextField::<()>::new("42").helper("Help");
let iconed = TextField::<()>::new("42").helper("Help").icon(Icons::STAR);
let before = texts(&plain, Status::default());
let after = texts(&iconed, Status::default());
for what in ["42", "Help"] {
let shift = find(&after, what).unwrap().0.x - find(&before, what).unwrap().0.x;
assert_eq!(shift, 40.0, "{what} moves over by 24 and 16");
}
let dense = TextField::<()>::new("42").dense(true).icon(Icons::STAR);
let dense_plain = TextField::<()>::new("42").dense(true);
let shift = find(&texts(&dense, Status::default()), "42").unwrap().0.x
- find(&texts(&dense_plain, Status::default()), "42")
.unwrap()
.0
.x;
assert_eq!(shift, 34.0, "18 and 16, dense");
let x = find(&after, "42").unwrap().0.x;
assert_eq!(
Widget::<()>::cursor_at(&iconed, x + 0.5, 30.0, W, 0),
Some(0)
);
// The box itself starts after the icon.
let boxes: Vec<Rect> = {
let mut scene = Scene::new();
Widget::<()>::paint(
&iconed,
Rect::new(0.0, 0.0, W, 80.0),
Status::default(),
&Theme::default(),
&mut scene,
);
scene
.primitives()
.iter()
.filter_map(|p| match p {
frus_core::Primitive::Rect { rect, .. } => Some(*rect),
_ => None,
})
.collect()
};
assert_eq!(boxes[0].x, 40.0);
assert_eq!(boxes[0].width, W - 40.0);
}
/// **The counter's text**: said instead of the count, and an empty one hides it.
#[test]
fn the_counter_says_what_it_is_told() {
let counted = TextField::<()>::new("abc").max_length(10);
assert!(find(&texts(&counted, Status::default()), "3/10").is_some());
let told = TextField::<()>::new("abc")
.max_length(10)
.counter_text("3 of 10");
let shown = texts(&told, Status::default());
assert!(find(&shown, "3 of 10").is_some() && find(&shown, "3/10").is_none());
let hidden = TextField::<()>::new("abc").max_length(10).counter_text("");
assert!(find(&texts(&hidden, Status::default()), "3/10").is_none());
assert_eq!(hidden.sub_block(), 0.0, "and its line is not kept");
let alone = TextField::<()>::new("abc").counter_text("Optional");
assert!(find(&texts(&alone, Status::default()), "Optional").is_some());
assert!(alone.sub_block() > 0.0);
}
}
/// A box that grows with its value (milestone 657).
#[cfg(test)]
mod lines_tests {
use super::*;
const W: f32 = 300.0;
/// A value of `n` short words: enough of them wrap.
fn words(n: usize) -> String {
vec!["word"; n].join(" ")
}
fn lines(field: &TextField<()>) -> f32 {
field.lines_at(W)
}
/// **Given only a most, the box starts at one line** and grows as the value wraps, up
/// to the most, as the reference's `maxLines` does.
#[test]
fn a_box_grows_from_one_line_to_the_most() {
let empty = TextField::<()>::new("").max_lines(4);
assert!(empty.grows());
assert_eq!(lines(&empty), 1.0, "one line, empty");
let short = TextField::<()>::new(words(2)).max_lines(4);
assert_eq!(lines(&short), 1.0);
let wrapped = TextField::<()>::new(words(40)).max_lines(4);
assert_eq!(lines(&wrapped), 4.0, "held at the most");
let some = TextField::<()>::new(words(14)).max_lines(4);
let n = lines(&some);
assert!(n > 1.0 && n < 4.0, "in between: {n}");
let unbounded = TextField::<()>::new(words(160)).max_lines(None);
assert!(lines(&unbounded) > 12.0, "no most: {}", lines(&unbounded));
}
/// **The fewest lines hold the box open**, and the most is never below them.
#[test]
fn the_fewest_lines_hold_the_box_open() {
let held = TextField::<()>::new("").min_lines(2).max_lines(5);
assert_eq!(lines(&held), 2.0);
let either_order = TextField::<()>::new("").max_lines(5).min_lines(2);
assert_eq!(lines(&either_order), 2.0, "said after the most");
let inverted = TextField::<()>::new(words(40)).min_lines(6).max_lines(3);
assert_eq!(
lines(&inverted),
6.0,
"a most below the fewest is the fewest"
);
assert!(!inverted.grows());
let raised = TextField::<()>::new(words(40)).max_lines(3).min_lines(6);
assert_eq!(lines(&raised), 6.0, "the fewest raise a most said first");
assert!(!raised.grows());
}
/// **One line at most is a single-line field**, and `rows` still fixes the box.
#[test]
fn one_line_and_fixed_rows_do_not_grow() {
let single = TextField::<()>::new(words(40)).max_lines(1);
assert!(!single.multiline && !single.grows());
assert_eq!(lines(&single), 1.0);
let fixed = TextField::<()>::new(words(40)).rows(3);
assert!(!fixed.grows());
assert_eq!(lines(&fixed), 3.0);
assert!(Widget::<()>::measure(&fixed, &Theme::default()).is_none());
assert!(matches!(
Widget::<()>::style(&fixed).height,
Dimension::Length(_)
));
}
/// **The layout, the paint and the click agree on the height**: a growing box is
/// measured from its width, painted that tall, and its suffix answers down its whole
/// height.
#[test]
fn the_layout_and_the_paint_agree() {
let field = TextField::<()>::new(words(14))
.max_lines(6)
.label("Notes")
.suffix_icon(crate::Icons::CLOSE)
.on_suffix(());
let style = Widget::<()>::style(&field);
assert_eq!(style.height, Dimension::Auto);
let theme = Theme::default();
let measure = Widget::<()>::measure(&field, &theme).expect("measured");
let size = measure(Some(W), None);
let expected =
frus_core::fits(field.label_block() + field.field_height_at(W) + field.sub_block());
assert_eq!(size.height, expected, "in whole pixels");
assert_eq!(size.height.fract(), 0.0);
assert!(
field.field_height_at(W) > field.field_height(),
"taller than one line"
);
let narrow = measure(Some(200.0), None);
assert!(narrow.height > size.height, "narrower wraps more");
let mut scene = Scene::new();
Widget::<()>::paint(
&field,
Rect::new(0.0, 0.0, W, size.height),
Status::default(),
&theme,
&mut scene,
);
let tallest = scene
.primitives()
.iter()
.filter_map(|p| match p {
frus_core::Primitive::Rect { rect, .. } => Some(rect.height),
_ => None,
})
.fold(0.0, f32::max);
assert_eq!(tallest, field.field_height_at(W), "the box is that tall");
let low = field.label_block() + field.field_height_at(W) - 4.0;
assert!(
field.suffix_hit(W - 10.0, low, W),
"the suffix answers low in the box"
);
let key = |f: &TextField<()>| Widget::<()>::measure_key(f, &theme);
assert_ne!(
key(&TextField::<()>::new(words(14)).max_lines(6).label("Notes")),
key(&TextField::<()>::new(words(30)).max_lines(6).label("Notes")),
"another value, and nothing else, another measurement"
);
assert_ne!(
key(&TextField::<()>::new(words(14)).max_lines(6)),
key(&TextField::<()>::new(words(14))
.max_lines(6)
.prefix_text("$")),
"a prefix narrows the wrap"
);
}
}
/// The caret, the mask and the focus a field asks for (milestone 659).
#[cfg(test)]
mod cursor_tests {
use super::*;
use frus_core::{BorderRadius, Primitive, TargetPlatform};
/// Every rectangle a focused field paints: where, in what colour, how round.
fn rects(field: &TextField<()>, theme: &Theme) -> Vec<(Rect, Color, BorderRadius)> {
let mut scene = Scene::new();
Widget::<()>::paint(
field,
Rect::new(0.0, 0.0, 300.0, 80.0),
Status {
focused: true,
focus_progress: 1.0,
cursor: Some(2),
..Default::default()
},
theme,
&mut scene,
);
scene
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Rect {
rect,
color,
radius,
..
} => Some((*rect, *color, *radius)),
_ => None,
})
.collect()
}
/// The caret: the rectangle in `color`.
fn caret(field: &TextField<()>, theme: &Theme, color: Color) -> Option<(Rect, BorderRadius)> {
rects(field, theme)
.into_iter()
.find(|(_, c, _)| *c == color)
.map(|(r, _, radius)| (r, radius))
}
/// **The caret is `primary`**, as the reference's is, and the error's colour while one
/// shows; the field's colour over the theme's, the field theme's over the text
/// selection's.
#[test]
fn the_caret_takes_the_reference_s_colours() {
let theme = Theme::default();
let field = TextField::<()>::new("ab");
let (rect, _) = caret(&field, &theme, theme.scheme.primary).expect("in primary");
assert_eq!(rect.width, 2.0, "the reference's two pixels");
let errored = TextField::<()>::new("ab").error("Wrong");
assert!(
caret(&errored, &theme, theme.scheme.error).is_some(),
"in error"
);
assert!(caret(&errored, &theme, theme.scheme.primary).is_none());
let red = Color::rgb(1.0, 0.0, 0.0);
let told = TextField::<()>::new("ab").cursor_color(red);
assert!(caret(&told, &theme, red).is_some(), "the field's");
let blue = Color::rgb(0.0, 0.0, 1.0);
let told_error = TextField::<()>::new("ab")
.error("Wrong")
.cursor_error_color(blue);
assert!(
caret(&told_error, &theme, blue).is_some(),
"the field's error colour"
);
let mut selection = Theme::default();
selection.widgets.text_selection.cursor_color = Some(red);
assert!(
caret(&field, &selection, red).is_some(),
"the text selection's"
);
let mut both = selection.clone();
both.widgets.text_field.cursor_color = Some(blue);
assert!(
caret(&field, &both, blue).is_some(),
"the field theme's over it"
);
}
/// **Its shape**: the width and height told, the height centred on the line; rounded on
/// Apple's platforms and square elsewhere unless told; hidden when told.
#[test]
fn the_caret_takes_its_shape() {
let theme = Theme::default().with_platform(TargetPlatform::Android);
let primary = theme.scheme.primary;
let (line, square) = caret(&TextField::new("ab"), &theme, primary).unwrap();
assert_eq!(square, BorderRadius::uniform(0.0), "square on Android");
let shaped = TextField::<()>::new("ab")
.cursor_width(3.0)
.cursor_height(10.0);
let (rect, _) = caret(&shaped, &theme, primary).unwrap();
assert_eq!((rect.width, rect.height), (3.0, 10.0));
let centre = |r: Rect| r.y + r.height / 2.0;
assert!(
(centre(rect) - centre(line)).abs() < 1e-3,
"centred on the line"
);
let ios = Theme::default().with_platform(TargetPlatform::Ios);
let (_, round) = caret(&TextField::new("ab"), &ios, ios.scheme.primary).unwrap();
assert_eq!(round, BorderRadius::uniform(2.0), "rounded on iOS");
let told = TextField::<()>::new("ab").cursor_radius(1.0);
assert_eq!(
caret(&told, &theme, primary).unwrap().1,
BorderRadius::uniform(1.0)
);
let hidden = TextField::<()>::new("ab").show_cursor(false);
assert!(caret(&hidden, &theme, primary).is_none(), "not shown");
}
/// **A masked value shows the character told**, a dot unless told.
#[test]
fn a_masked_value_shows_the_character_told() {
assert_eq!(TextField::<()>::new("abc").obscure(true).display(), "•••");
let starred = TextField::<()>::new("abc")
.obscure(true)
.obscuring_character('*');
assert_eq!(starred.display(), "***");
assert_eq!(
TextField::<()>::new("abc")
.obscuring_character('*')
.display(),
"abc",
"only a masked field"
);
}
/// **A field asks for the focus when told**, and a disabled one never does.
#[test]
fn a_field_asks_for_the_focus_when_told() {
assert!(!Widget::<()>::autofocus(&TextField::new("")));
assert!(Widget::<()>::autofocus(&TextField::new("").autofocus(true)));
assert!(!Widget::<()>::autofocus(
&TextField::new("").autofocus(true).enabled(false)
));
}
}