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
//! [`Text`]: a widget that displays a line of text.
use std::any::Any;
use std::cell::{Cell, OnceCell};
use frus_core::{
fits, Color, FontWeight, MaskShader, Point, Rect, ResolvedTextStyle, Scene, ShaderMask,
TextAlign, TextBlock, TextOverflow, TextStyle,
};
use frus_layout::{Dimension, Style};
use frus_text::TextLayout;
use crate::interaction::{Key, Status};
use crate::runtime::Edit;
use crate::selectiontoolbar::{SelectionToolbar, ToolbarContext, ToolbarItem};
use crate::textinput::{
handle_at, handles_in, move_caret, paint_handle, paint_handles, selection_box_in, word_range,
ToolbarBuild,
};
use crate::theme::Theme;
use crate::widget::Widget;
use crate::widgettheme::DefaultTextStyle;
/// A single-line text widget.
///
/// Its layout size comes from a **styled** measurement (`frus-text`, weight and
/// italic included); it pushes a text primitive into the scene when painting. The
/// [`TextStyle`]'s color is inherited from the theme when absent.
pub struct Text {
content: String,
style: TextStyle,
/// Whether the text wraps at the width it is given. Unset, **on**, as in the
/// reference: a piece of prose put in a box narrower than itself is a paragraph.
wrap: Option<bool>,
/// What becomes of text that does not fit its box. Unset, clipped.
overflow: Option<TextOverflow>,
/// At most this many lines; the rest is dropped and `overflow` decides how the last
/// one ends.
max_lines: Option<usize>,
/// Where the lines sit inside the box. Unset, at the start.
align: Option<TextAlign>,
/// Whether this text is a **heading** — a landmark a screen reader's user can jump
/// to, rather than one more piece of prose. It changes nothing that is drawn.
heading: bool,
/// Whether this text is willing to be given **less than it asked for**.
///
/// It is not the same question as what happens when it overflows, and conflating the
/// two would change every text in the framework: a flex item's automatic minimum size
/// is its content, so a plain text refuses to shrink and its siblings are pushed out
/// instead. Saying what to do on overflow is what says it may be squeezed — and an
/// **inherited** limit says it just as much as a called one, which is why this is
/// derived at resolution rather than stored.
shrinkable: bool,
/// What makes the text **selectable** — see [`Text::selectable`]. Boxed, and absent for
/// the vast majority of texts, which are read and nothing more: the widget that is built
/// by the thousand does not carry a selection's state around.
selection: Option<Box<Selection>>,
/// The typography this text was **last laid out and painted with**, which is what a hit,
/// a highlight and a handle have to be measured against.
///
/// A hit test is asked for outside a frame, with no theme and no reader's font setting in
/// force — and a text's size may be handed down by a subtree and scaled by that setting,
/// neither of which the widget can see from where it is asked. So layout and paint write
/// down what they resolved, and the questions read it back.
shaping: Cell<Option<Shaping>>,
/// The reader's font-size setting when the text was built, for a question asked before
/// any layout has: the best guess there is, and the right one for a text that sets its
/// own size.
scale: f32,
/// The bars this text shows when a [`SelectionArea`](crate::SelectionArea)'s selection is
/// placed against it, one per context, built the first time each is asked for. A pointer
/// until then: a text is built by the thousand and very few ever carry a bar.
area_bars: OnceCell<Box<AreaBars>>,
}
/// One bar per [`ToolbarContext`], each an `Option<Box<dyn Widget<Msg>>>` behind `dyn Any`.
type AreaBars = [OnceCell<Box<dyn Any>>; ToolbarContext::VARIANTS as usize];
/// The state of a text that can be selected and copied.
struct Selection {
/// Whether the text is selectable at all. [`Text::selection_toolbar`] may have made
/// the state before [`Text::selectable`] is called, in either order.
on: bool,
/// The application's say over the bar shown above a selection: a
/// [`ToolbarBuild`] of the application's message type, kept as `dyn Any` because a
/// `Text` is not generic over it.
toolbar_build: Option<Box<dyn Any>>,
/// The bar for each context, built the first time it is asked for and kept: the walk
/// borrows it for a frame, so it must live as long as the text does. Each holds an
/// `Option<Box<dyn Widget<Msg>>>`.
toolbars: [OnceCell<Box<dyn Any>>; ToolbarContext::VARIANTS as usize],
}
/// What a selection is measured against: the typography a text resolved, and whether it
/// wraps at the width it is given.
#[derive(Copy, Clone)]
struct Shaping {
style: ResolvedTextStyle,
wrap: bool,
}
/// A [`Text`]'s questions, all answered: what the caller said where they said it, what the
/// subtree's [`DefaultTextStyle`](crate::DefaultTextStyle) said where they did not, and
/// the framework's own default where neither did.
///
/// Everything the widget does — the width it asks for, the words it keeps, the glyphs it
/// draws — reads from one of these, and every hook builds it the same way. That is not
/// tidiness: a size resolved one way for the measurement and another way for the paint is
/// a layout that is wrong everywhere at once, with nothing in the picture to say which of
/// the two numbers was the mistake.
pub(crate) struct Resolved {
pub style: ResolvedTextStyle,
pub align: TextAlign,
pub wrap: bool,
pub overflow: TextOverflow,
pub max_lines: Option<usize>,
/// Whether this text is willing to be given less than it asked for — which an
/// inherited overflow or line limit says just as much as a called one.
pub shrinkable: bool,
}
/// The ellipsis a cut line ends in.
pub(crate) const ELLIPSIS: &str = "…";
/// The longest prefix of `content` that fits in `max_width`, ending in an ellipsis when
/// anything was cut. Returns `content` untouched when it already fits.
///
/// A box with **no room at all** gets an ellipsis and nothing else. It used to get the
/// whole string, on the reasoning that a zero width meant "the layout has not run yet"
/// rather than "there is no room" — inherited from the app bar, which cannot produce a
/// zero anyway (its title room has a floor of 64 px). What the exception actually did was
/// let a genuinely collapsed box draw its whole label, over whatever was beside it, which
/// is the one thing ellipsising exists to prevent.
///
/// Character by character from the end: the strings this is used on are a line, not a
/// document, and a binary search over char boundaries would buy nothing at that length.
pub(crate) fn truncate(content: &str, style: &ResolvedTextStyle, max_width: f32) -> String {
let measure = |text: &str| frus_text::measure_resolved(text, style).width;
if measure(content) <= max_width {
return content.to_string();
}
let mut chars: Vec<char> = content.chars().collect();
while !chars.is_empty() {
chars.pop();
let kept: String = chars.iter().collect();
let candidate = format!("{}{ELLIPSIS}", kept.trim_end());
if measure(&candidate) <= max_width {
return candidate;
}
}
ELLIPSIS.to_string()
}
/// `line` cut so that it and an ellipsis together fit `max_width` — **always** ending in
/// one, where [`truncate`] leaves a line that already fits alone.
///
/// The difference is which question is being asked. `truncate` asks whether this line
/// fits; this asks how to end a line that is being cut because the *next* one was
/// dropped, and there the line usually does fit and still has to say so.
pub(crate) fn ellipsise(line: &str, style: &ResolvedTextStyle, max_width: f32) -> String {
let measure = |text: &str| frus_text::measure_resolved(text, style).width;
let mut chars: Vec<char> = line.trim_end().chars().collect();
loop {
let kept: String = chars.iter().collect();
let candidate = format!("{}{ELLIPSIS}", kept.trim_end());
if chars.is_empty() || max_width <= 0.0 || measure(&candidate) <= max_width {
return candidate;
}
chars.pop();
}
}
/// What a text came to after being fitted to its box: what to draw, and which way it ran
/// over — the two are different questions, and a fade needs to know which.
pub(crate) struct Fitted {
/// The text to draw, with the dropped lines gone and any ellipsis already in it.
pub text: String,
/// The last line is wider than the box.
pub too_wide: bool,
/// Lines were dropped off the bottom.
pub too_tall: bool,
}
impl Fitted {
/// Whether anything ran over at all.
fn over(&self) -> bool {
self.too_wide || self.too_tall
}
}
impl Text {
/// Creates a text that has **chosen nothing**: it takes its size, weight and colour
/// from whatever subtree it is put in, and the framework's own where nothing says
/// otherwise (16 px, regular, the theme's `on_surface`).
///
/// It used to be written as a 16 px style, which read the same and meant something
/// else: a style that *answered* 16, so an app bar or a section could not dress it.
pub fn new(content: impl Into<String>) -> Self {
Self {
content: content.into(),
..Self::defaults()
}
}
/// Creates a text from a full [`TextStyle`] — typically one step of the theme's
/// scale (`Text::styled("Title", theme.text.title_large)`).
/// The style is taken **exactly as written**: whatever it names it answers, and
/// whatever it leaves open stays open to a subtree.
///
/// So `Text::styled(s, theme.text.title_medium)` wears that step of the scale and
/// still picks up a colour from the section it sits in, while
/// `Text::styled(s, TextStyle::new(20.0))` fixes the size alone and inherits the rest.
pub fn styled(content: impl Into<String>, style: TextStyle) -> Self {
Self {
content: content.into(),
style,
..Self::defaults()
}
}
/// The settings every constructor starts from, so that adding one does not mean
/// touching each of them.
fn defaults() -> Self {
Self {
content: String::new(),
style: TextStyle::NONE,
wrap: None,
overflow: None,
max_lines: None,
align: None,
heading: false,
shrinkable: false,
selection: None,
shaping: Cell::new(None),
scale: frus_core::text_scale(),
area_bars: OnceCell::new(),
}
}
/// Makes this text **selectable**: a press, a drag, a double click or a long press
/// selects words in it, and Ctrl+C, or the bar that opens over the selection, copies
/// them. Ordinary text is not — it is drawn, and there is nothing under the pointer to
/// select — and choosing which of an application's texts a reader may copy from is
/// the application's business: an order number, an address, a code, an error message.
///
/// A selectable text can take focus, so Tab reaches it and a screen reader announces
/// it as it does any text; it does **not** open the software keyboard, which is for
/// text that can be typed into. Its selection shows the highlight
/// ([`Theme::selection`]) and, when made with a finger, the handles.
///
/// ```
/// use frus_widgets::Text;
///
/// let code = Text::new("ORDER-4417").selectable();
/// # let _ = code;
/// ```
///
/// **Limits.** What is selected is what is drawn from the start of each line: a text
/// aligned to the centre or the end, or one that a line limit or an ellipsis cuts short,
/// is highlighted as if it were not. Up and Down move focus rather than the caret.
/// A selectable text inside something that takes a tap — a button, a list tile — takes
/// the press instead of it: make selectable the texts that are not the button's label.
pub fn selectable(mut self) -> Self {
self.selection_mut().on = true;
self
}
/// Changes what the bar over a selectable text's selection offers — the application's
/// say, as [`TextField::selection_toolbar`](crate::TextField::selection_toolbar) is for a
/// field. `build` is given the context and the default list (Copy when something is
/// selected, Select all unless everything is) and answers with the list to show; an
/// empty one shows no bar.
///
/// Only for a text that is [`selectable`](Self::selectable). The bar carries the
/// application's messages, so `Msg` is the message type of the view the text is in.
pub fn selection_toolbar<Msg: 'static>(
mut self,
build: impl Fn(&ToolbarContext, Vec<ToolbarItem<Msg>>) -> Vec<ToolbarItem<Msg>> + 'static,
) -> Self {
let build: ToolbarBuild<Msg> = Box::new(build);
let selection = self.selection_mut();
selection.toolbar_build = Some(Box::new(build));
// Whatever was built for the old answer is not the answer any more.
selection.toolbars = Default::default();
self
}
/// The state of the selection, made when first asked for.
fn selection_mut(&mut self) -> &mut Selection {
self.selection.get_or_insert_with(|| {
Box::new(Selection {
on: false,
toolbar_build: None,
toolbars: Default::default(),
})
})
}
/// The selection state, if this text is selectable.
fn selecting(&self) -> Option<&Selection> {
self.selection.as_deref().filter(|selection| selection.on)
}
/// The layout of this text as it was drawn, at `width`: what a hit, a highlight, a
/// handle or the bar's anchor is worked out from. `None` for a text that is not
/// selectable.
fn selection_layout(&self, width: f32) -> Option<TextLayout> {
self.selecting()?;
Some(self.text_layout(width))
}
/// The layout of this text as it was drawn, at `width` — for any text, selectable or
/// not: a [`SelectionArea`](crate::SelectionArea) selects in texts that never asked to be.
fn text_layout(&self, width: f32) -> TextLayout {
let shaping = self.shaping.get().unwrap_or_else(|| {
let resolved = frus_core::with_text_scale(self.scale, || self.resolved(None));
Shaping {
style: resolved.style,
wrap: resolved.wrap,
}
});
TextLayout::resolved(&self.content, &shaping.style, shaping.wrap.then_some(width))
}
/// Writes down what this text resolved, for the questions a selection is asked later.
fn remember(&self, r: &Resolved) {
self.shaping.set(Some(Shaping {
style: r.style,
wrap: r.wrap,
}));
}
/// Wraps at the width the parent offers. This is the default, and the call is kept
/// because saying so at the call site is not redundant when it is the whole point of
/// the widget being there.
/// Marks this text as a **heading**: a landmark assistive technology can jump
/// between, instead of one more run of prose.
///
/// It changes nothing that is drawn. A screen reader's user moves through a screen by
/// its headings, and a title announced as a label gives them nothing to move between
/// — which is what an app bar's title was until milestone 397. The reference says the
/// same thing with `SemanticsProperties(header: true)` around its title.
pub fn heading(mut self) -> Self {
self.heading = true;
self
}
/// Wraps the text at the width it is given: [`soft_wrap(true)`](Self::soft_wrap). It is
/// what an unset text does already; this says so, and undoes a
/// [`no_wrap`](Self::no_wrap) further up a chain.
pub fn wrap(mut self) -> Self {
self.wrap = Some(true);
self
}
/// Keeps the text on **one line**, explicit newlines aside. It then runs past its box
/// rather than folding, and [`Text::overflow`] decides what becomes of the part that
/// hangs over.
pub fn no_wrap(mut self) -> Self {
self.wrap = Some(false);
self
}
/// Whether the text wraps at the width it is given. `wrap()` is `soft_wrap(true)`.
///
/// Off, the text stays on one line — explicit newlines aside — and runs past its box
/// or is cut, according to [`Text::overflow`].
pub fn soft_wrap(mut self, soft_wrap: bool) -> Self {
self.wrap = Some(soft_wrap);
self
}
/// Where the lines sit **inside the box** the text was given.
///
/// It does nothing to a text that shrink-wraps, and that is not a limitation of this
/// implementation: a box exactly as wide as its text has nowhere to align it to. It
/// takes effect once something has made the box wider — a stretched column, an
/// [`crate::Expanded`], a width.
pub fn align(mut self, align: TextAlign) -> Self {
self.align = Some(align);
self
}
/// At most `max_lines` lines; what is past them is dropped, and [`Text::overflow`]
/// decides how the last one ends.
///
/// Asking for a limit also tells the layout this text may be given **less width than
/// it asked for** — a limit is only meaningful for a text expected to be squeezed.
pub fn max_lines(mut self, max_lines: usize) -> Self {
self.max_lines = Some(max_lines.max(1));
self.shrinkable = true;
self
}
/// What becomes of text that does not fit: cut, cut with an ellipsis, faded out, or
/// drawn past the box.
///
/// Saying so also tells the layout this text may be given **less than it asked for**.
pub fn overflow(mut self, overflow: TextOverflow) -> Self {
self.overflow = Some(overflow);
self.shrinkable = true;
self
}
/// Keeps the text on **one line and inside its box**, cut with an ellipsis when it
/// does not fit — the reference's `TextOverflow.ellipsis`.
///
/// This is two things, and the second is the one that matters. The obvious half is the
/// cut. The other is that an ellipsising text tells the layout it may be given *less
/// than it asked for*: a flex item's automatic minimum size is its content, so a plain
/// `Text` in a row refuses to shrink and pushes its siblings out of the box instead —
/// which is how a long task name evicted its own delete button, off the card and out of
/// the hit registry, on a device (milestone 333). `min_width: 0` is what lets flexbox
/// do its job, and it is the same fix the web has needed for the same reason forever.
///
/// Mutually exclusive with [`Text::wrap`], which is the other answer to the same
/// question: wrap grows downwards, this one cuts. The last one called wins.
pub fn ellipsis(mut self) -> Self {
self.wrap = Some(false);
self.overflow = Some(TextOverflow::Ellipsis);
self.shrinkable = true;
self
}
/// Sets the font size, in pixels.
pub fn size(mut self, size: f32) -> Self {
self.style.size = Some(size);
self
}
/// Sets the weight.
pub fn weight(mut self, weight: FontWeight) -> Self {
self.style.weight = Some(weight);
self
}
/// Switches to italic.
pub fn italic(mut self) -> Self {
self.style.italic = Some(true);
self
}
/// Sets the **font family** — the reference's
/// [`fontFamily`](frus_core::TextStyle::family).
///
/// `Text::new("fn main()").family(FontFamily::Monospace)` for code;
/// `FontFamily::Named("Inter")` for a face registered with `frus_text::add_font`.
/// Unset, the application's default.
///
/// **A run containing Arabic keeps the registered Arabic face** whatever is named
/// here, because a family without Arabic coverage renders nothing at all on Android
/// rather than falling back — see [`frus_core::TextStyle::family`].
pub fn family(mut self, family: frus_core::FontFamily) -> Self {
self.style.family = Some(family);
self
}
/// Sets the line height as a **multiple of the font size** — the reference's
/// [`TextStyle::height`](frus_core::TextStyle::height).
///
/// `1.0` packs the lines to exactly the type's size, `1.6` opens a paragraph up.
/// Unset, the line height is whatever a surrounding [`crate::DefaultTextStyle`] said,
/// or [`DEFAULT_LINE_HEIGHT`](frus_core::DEFAULT_LINE_HEIGHT) at the end of the chain.
///
/// A ratio and not a length, so the leading grows with the letters when a reader turns
/// the type up instead of staying where it was set.
pub fn height(mut self, height: f32) -> Self {
self.style.height = Some(height);
self
}
/// Sets the text color (otherwise the theme's).
pub fn color(mut self, color: Color) -> Self {
self.style.color = Some(color);
self
}
/// Underlines the text.
pub fn underline(mut self) -> Self {
self.style = self.style.underline();
self
}
/// Strikes the text through.
pub fn strikethrough(mut self) -> Self {
self.style = self.style.strikethrough();
self
}
/// Sets the decoration lines (freely combined).
pub fn decoration(mut self, decoration: frus_core::TextDecoration) -> Self {
self.style.decoration = Some(decoration);
self
}
/// Sets the decoration color (otherwise the text's).
pub fn decoration_color(mut self, color: Color) -> Self {
self.style.decoration_color = Some(color);
self
}
}
impl Text {
/// Every question this text asks of itself, answered once: **what the caller said ??
/// what the subtree handed down ?? what the framework ships**.
///
/// `theme` is an `Option` because [`Widget::style`] has no theme to give — a widget
/// asked for its style outside a walk. `None` means nothing was handed down, which is
/// exactly what a fresh theme carries, so the two agree and the unthemed case costs
/// nothing.
///
/// The typography is one `merge` and one `resolved`, and it was fourteen lines of
/// bookkeeping until [`TextStyle`]'s fields could each say *unset*. A style that never
/// named a size does not outrank a subtree that did; one that named it keeps it. The
/// same rule as before, now expressed by the type instead of shadowed by a flag.
pub(crate) fn resolved(&self, theme: Option<&Theme>) -> Resolved {
let handed = theme.map_or(DefaultTextStyle::NONE, |t| t.widgets.text);
Resolved {
style: handed.style.merge(self.style).resolved(),
align: self.align.or(handed.align).unwrap_or(TextAlign::Start),
wrap: self.wrap.or(handed.soft_wrap).unwrap_or(true),
overflow: self
.overflow
.or(handed.overflow)
.unwrap_or(TextOverflow::Clip),
max_lines: self.max_lines.or(handed.max_lines),
// An **inherited** overflow or line limit says the same thing a called one
// does: this text may be given less than it asked for. Leaving it out would
// ship a subtree that ellipsises its texts and never gets the chance to,
// because each of them still refuses to be squeezed.
shrinkable: self.shrinkable
|| (self.overflow.is_none() && handed.overflow.is_some())
|| (self.max_lines.is_none() && handed.max_lines.is_some()),
}
}
/// The text that actually fits `width`, and which way it ran over.
///
/// Everything the box does to the words happens here: dropping the lines past the
/// limit, cutting the last one, deciding whether a line ran past the edge. The paint
/// draws what comes back, and the overflow mode decides how.
pub(crate) fn fitted(&self, width: f32, r: &Resolved) -> Fitted {
// Only a line **limit** makes the words the widget's business. Left alone, the
// text goes to the renderer whole and is broken there.
//
// And what goes over is a **prefix**, cut at a break the shaper chose — never a
// list of lines glued back together. Lines glued back together are a paragraph
// *per line*, and rules that span a paragraph stop working: a justified block can
// only leave its last line ragged if it knows which line is the last.
let mut text = self.content.clone();
let mut too_tall = false;
if let Some(max) = r.max_lines {
// Under the whole style — its line height, family and letter spacing break
// the lines as the renderer will (milestone 623).
let spans =
frus_text::line_spans_resolved(&self.content, &r.style, Some(width), r.wrap);
if spans.len() > max {
too_tall = true;
let cut = spans[max].start;
let last = spans[max - 1].start;
text = if r.overflow == TextOverflow::Ellipsis {
let ended = ellipsise(&self.content[last..cut], &r.style, width);
format!("{}{ended}", &self.content[..last])
} else {
self.content[..cut].to_string()
};
}
}
// A line can only be wider than the box when nothing may push it onto the next
// one. Where the text wraps, every line fits by construction.
let too_wide = !r.wrap && frus_text::measure_resolved(&text, &r.style).width > width + 0.5;
if too_wide && !too_tall && r.overflow == TextOverflow::Ellipsis {
text = ellipsise(&text, &r.style, width);
}
Fitted {
text,
too_wide,
too_tall,
}
}
/// Whether this text needs the **whole width it is offered** rather than its own.
///
/// Alignment is the only thing that does. A box exactly as wide as its text has
/// nowhere to align it to, so a text asked to centre itself and then given its own
/// width would be centred and look untouched — the setting would appear to do nothing
/// and there would be nothing to see. Left alone, a text still shrink-wraps.
fn fills(r: &Resolved) -> bool {
r.align != TextAlign::Start
}
/// A line limit is a **height** cap and nothing else: the words break where they
/// broke, and the ones past the limit are not drawn.
fn capped(height: f32, r: &Resolved) -> f32 {
match r.max_lines {
Some(max) => height.min(r.style.line_height() * max as f32),
None => height,
}
}
/// The fade that ends a cut text: opaque until the last stretch of the box, then out
/// to nothing at the edge it ran past.
/// The two handles of a touch selection, hanging below their ends of it. Drawn last,
/// over the words, and outside the text's own clip: they hang past its last line.
fn paint_grips(&self, bounds: Rect, status: &Status, theme: &Theme, scene: &mut Scene) {
// The handles of a selection area's touch selection that hang from this text.
let (start, end) = status.region_grips;
if start.is_some() || end.is_some() {
let layout = self.text_layout(bounds.width);
let color = theme
.widgets
.text_selection
.handle_color_in(theme)
.fade(status.opacity);
let offset = Point::new(bounds.x, bounds.y);
let origin = Point::new(0.0, 0.0);
for (index, is_start) in [(start, true), (end, false)] {
if let Some(index) = index {
let handle = handle_at(&layout, origin, index, is_start);
paint_handle(scene, handle, offset, color, is_start);
}
}
}
if !(status.focused && status.handles) {
return;
}
let Some((start, end)) = status.selection else {
return;
};
let Some(layout) = self.selection_layout(bounds.width) else {
return;
};
let edit = Edit {
cursor: end,
anchor: Some(start),
composing: None,
};
let len = self.content.chars().count();
if let Some(handles) = handles_in(&layout, Point::new(0.0, 0.0), len, &edit) {
let color = theme
.widgets
.text_selection
.handle_color_in(theme)
.fade(status.opacity);
paint_handles(scene, handles, Point::new(bounds.x, bounds.y), color);
}
}
fn fade(bounds: Rect, horizontal: bool, r: &Resolved) -> ShaderMask {
// A fifth of the box, and never more than three line heights of it. Over a long
// line a proportional fade would start halfway through words that are perfectly
// legible; over a short one an absolute fade would swallow the lot.
let extent = if horizontal {
bounds.width
} else {
bounds.height
};
let run = (extent * 0.2).min(r.style.line_height() * 3.0);
let (from, to) = if horizontal {
(
Point::new(bounds.x + bounds.width - run, bounds.y),
Point::new(bounds.x + bounds.width, bounds.y),
)
} else {
(
Point::new(bounds.x, bounds.y + bounds.height - run),
Point::new(bounds.x, bounds.y + bounds.height),
)
};
ShaderMask::new(MaskShader::Linear {
from,
to,
from_color: Color::WHITE,
to_color: Color::WHITE.fade(0.0),
})
}
}
impl Text {
/// The box this text asks for, once every question has been answered.
///
/// Split out from the two style hooks rather than duplicated across them: they differ
/// only in whether a theme was there to be asked, and a second copy of this reasoning
/// is a second place for the themed and the unthemed answers to drift apart.
fn boxed(&self, r: &Resolved) -> Style {
// A flex item's automatic minimum size is its content, so a plain text refuses to
// shrink and pushes its siblings out instead. One that has said what to do when it
// overflows may be given less; the paint fits the words to whatever it gets.
let min_width = if r.shrinkable {
Dimension::Length(0.0)
} else {
Dimension::Auto
};
// A paragraph, or a text that has to know how wide its box is: free dimensions,
// and the size comes from `measure` — the only way a box can be *given* a width
// and answer with a height.
if r.wrap || Self::fills(r) {
return Style {
min_width,
..Default::default()
};
}
// A single line is a box of a known size, and saying so is what keeps it from
// being folded: a measured leaf reports its narrowest useful width as its
// minimum content, and a row would take that as leave to squeeze it there.
let measured = frus_text::measure_resolved(&self.content, &r.style);
Style {
width: Dimension::Length(measured.width.ceil()),
height: Dimension::Length(Self::capped(measured.height, r).ceil()),
min_width,
// A text that has said what to do when it overflows is **clamped to its
// parent**, which is what the reference does to every one of them: a
// paragraph is laid out at `constraints.constrain(its own size)`. Without it a
// text declares the width it wants, a narrower box does not take it away, and
// the overflow mode never fires — the words simply draw past the edge, which
// is the behaviour it was set to prevent.
max_width: if r.shrinkable {
Dimension::Percent(1.0)
} else {
Dimension::Auto
},
..Default::default()
}
}
}
impl<Msg: Clone + 'static> Widget<Msg> for Text {
fn style(&self) -> Style {
self.boxed(&self.resolved(None))
}
/// A subtree can hand down a size, a weight and a line limit, and every one of those
/// is a **box**, not a colour. Resolving them here rather than at paint is what lets
/// an app bar make the words inside it smaller and have them take less room, instead
/// of the same room with smaller writing in it.
fn style_themed(&self, theme: &Theme) -> Style {
let r = self.resolved(Some(theme));
self.remember(&r);
self.boxed(&r)
}
/// A text will not be **squeezed along a row**: it runs past the end of one rather
/// than being folded into a column of single words, which is the reference's rule and
/// was, until now, the only thing a declared width was doing here.
///
/// A text that has said what to do when it overflows has already said the opposite,
/// and is left alone.
fn main_axis_floor(&self, theme: &Theme) -> Option<f32> {
let r = self.resolved(Some(theme));
// A single line already carries its width in its style; only a text measured
// under constraints needs to be told where to stop giving way.
if r.shrinkable || !(r.wrap || Self::fills(&r)) {
return None;
}
Some(
frus_text::measure_resolved(&self.content, &r.style)
.width
.ceil(),
)
}
/// The line this text sits on, measured from the top of its box. A `Text` is the
/// widget that actually *has* a baseline; every alignment that talks about one is
/// ultimately asking one of these.
fn text_baseline(&self, theme: &Theme) -> Option<f32> {
let r = self.resolved(Some(theme));
Some(frus_text::baseline(
r.style.size,
r.style.weight,
r.style.italic,
))
}
fn measure(&self, theme: &Theme) -> Option<frus_layout::MeasureFn<'_>> {
let r = self.resolved(Some(theme));
if !r.wrap && !Self::fills(&r) {
return None;
}
let content = self.content.clone();
let style = r.style;
let max_lines = r.max_lines;
let wrap = r.wrap;
Some(Box::new(move |max_width, _| {
// Under the whole style, as the renderer draws it: its line height, its family
// and its letter spacing (milestone 623). Measured by size, weight and slant
// alone, a text with a family or a line height of its own was measured in
// another face, at another height, than it was drawn.
let mut size = frus_text::measure_wrapped_resolved(
&content,
&style,
// A text that only wanted the width to align inside is still one line:
// the constraint tells it where its box ends, not where to break.
if wrap { max_width } else { None },
);
if let Some(max) = max_lines {
// **Rounded up, like the measurement it clamps** (issue #54): a line
// height is a fraction of a size, so two allowed lines come to 28.8, and
// a box rounded to 28 is one the second line no longer fits in. The
// clamp says *how many lines*; the pixels those lines occupy are still
// pixels a layout will round.
size.height = size.height.min(fits(style.line_height() * max as f32));
}
size
}))
}
fn measure_key(&self, theme: &Theme) -> Option<u64> {
let r = self.resolved(Some(theme));
if !r.wrap && !Self::fills(&r) {
return None;
}
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
self.content.hash(&mut hasher);
// The **resolved** style, not the written one: an inherited size changes the
// measurement, and a key that ignored it would hand back the geometry the text had
// before the subtree said anything.
r.style.size.to_bits().hash(&mut hasher);
r.style.weight.to_u16().hash(&mut hasher);
r.style.italic.hash(&mut hasher);
// The leading and the face, which milestones 409 and 410 put into the measurement
// and *not* into this key: two paragraphs alike but for their line height wrapped
// to the same box, and the second kept the first's geometry.
r.style.height.map(f32::to_bits).hash(&mut hasher);
r.style.family.hash(&mut hasher);
r.max_lines.hash(&mut hasher);
r.wrap.hash(&mut hasher);
Some(hasher.finish())
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&[]
}
/// An aligned text takes the width its parent offers: a box exactly as wide as its
/// text has nowhere to align it to. It is the same request a [`crate::Row`] makes,
/// and it is answered by the same walk.
fn fill_axes(&self, theme: &Theme) -> crate::widget::FillAxes {
if Self::fills(&self.resolved(Some(theme))) {
crate::widget::FillAxes::WIDTH
} else {
crate::widget::FillAxes::NONE
}
}
fn paint(&self, bounds: Rect, status: Status, theme: &Theme, scene: &mut Scene) {
let r = self.resolved(Some(theme));
self.remember(&r);
let color = r
.style
.color
.unwrap_or(theme.on_surface)
.fade(status.opacity);
let fitted = self.fitted(bounds.width, &r);
// The selection: the highlight below the words (the handles of a touch selection are
// drawn after them). A selection area's covers this text whether or not it is focused;
// a selectable text's own only while it is.
let own = status
.selection
.filter(|_| status.focused && self.selecting().is_some());
if let Some((start, end)) = status.region.or(own) {
let highlight = theme
.widgets
.text_selection
.selection_color_in(theme)
.fade(status.opacity);
{
let layout = self.text_layout(bounds.width);
let len = self.content.chars().count();
for rect in layout.selection_rects(start.min(len), end.min(len)) {
scene.fill_rect(
Rect::new(
bounds.x + rect.x,
bounds.y + rect.y,
rect.width,
rect.height,
),
highlight,
);
}
}
}
let block = TextBlock {
// A width is handed over only when something is going to use it. Giving the
// renderer one it did not have changes where right-to-left text lands, which
// is a bug this codebase has already had once.
width: (r.wrap || r.align != TextAlign::Start).then_some(bounds.width),
soft_wrap: r.wrap,
align: r.align,
};
let draw = |scene: &mut Scene| {
scene.text_block(
Point::new(bounds.x, bounds.y),
fitted.text.clone(),
&r.style,
color,
block,
);
};
// Nothing hanging over the edge, or already cut to size, or told to spill: the
// three cases where the mode has nothing left to do.
if !fitted.over()
|| r.overflow == TextOverflow::Visible
|| r.overflow == TextOverflow::Ellipsis
{
draw(scene);
self.paint_grips(bounds, &status, theme, scene);
return;
}
// Only where it genuinely does not fit: a clip around every text would put a hard
// edge through the antialiasing of every one that does.
let outer = scene.current_clip();
scene.set_clip(outer.intersect(bounds));
match r.overflow {
TextOverflow::Fade => {
let horizontal = fitted.too_wide && !fitted.too_tall;
scene.masked(Self::fade(bounds, horizontal, &r), draw);
}
_ => draw(scene),
}
scene.set_clip(outer);
self.paint_grips(bounds, &status, theme, scene);
}
fn on_click(&self) -> Option<Msg> {
None
}
// What follows is a **selectable** text's: a read-only text field, in effect. None of it
// answers for a text that is not.
fn focusable(&self) -> bool {
self.selecting().is_some()
}
/// A selectable text's words, so that the shell treats it as the text field it is
/// for the caret's sake: the arrows move the caret, Ctrl+A selects, the context-menu
/// key opens the bar. Not for the keyboard's — see [`Widget::takes_typing`].
fn text_value(&self) -> Option<&str> {
self.selecting().map(|_| self.content.as_str())
}
fn takes_typing(&self) -> bool {
false
}
/// The words, for a selection that spans texts: any text with something to select.
fn selection_text(&self) -> Option<&str> {
(!self.content.is_empty()).then_some(self.content.as_str())
}
/// Copy, and Select all unless everything is selected — against the box of the part of the
/// selection that lies in this text.
fn region_toolbar(
&self,
context: ToolbarContext,
width: f32,
range: (usize, usize),
) -> Option<(Rect, &dyn Widget<Msg>)> {
let layout = self.text_layout(width);
let len = self.content.chars().count();
let edit = Edit {
cursor: range.1,
anchor: Some(range.0),
composing: None,
};
let anchor = selection_box_in(&layout, Point::new(0.0, 0.0), len, &edit);
let bars = self.area_bars.get_or_init(Box::default);
let bar = bars[usize::from(context.variant())]
.get_or_init(|| {
let mut items: Vec<ToolbarItem<Msg>> = Vec::new();
if context.has_selection {
items.push(ToolbarItem::copy());
}
if !context.all_selected {
items.push(ToolbarItem::select_all());
}
let bar: Option<Box<dyn Widget<Msg>>> = (!items.is_empty())
.then(|| Box::new(SelectionToolbar::new(items)) as Box<dyn Widget<Msg>>);
Box::new(bar) as Box<dyn Any>
})
.downcast_ref::<Option<Box<dyn Widget<Msg>>>>()?
.as_deref()?;
Some((anchor, bar))
}
fn selection_grip(
&self,
width: f32,
index: usize,
start: bool,
) -> Option<crate::SelectionHandle> {
let len = self.content.chars().count();
Some(handle_at(
&self.text_layout(width),
Point::new(0.0, 0.0),
index.min(len),
start,
))
}
fn selection_hit(&self, local_x: f32, local_y: f32, width: f32) -> Option<usize> {
if self.content.is_empty() {
return None;
}
Some(
self.text_layout(width)
.hit_test(Point::new(local_x, local_y)),
)
}
fn cursor_at(
&self,
local_x: f32,
local_y: f32,
width: f32,
_scroll_cursor: usize,
) -> Option<usize> {
let layout = self.selection_layout(width)?;
Some(layout.hit_test(Point::new(local_x, local_y)))
}
fn word_at(&self, index: usize) -> Option<(usize, usize)> {
self.selecting()?;
let chars: Vec<char> = self.content.chars().collect();
word_range(&chars, index)
}
fn selected_text(&self, edit: &Edit) -> Option<String> {
self.selecting()?;
let chars: Vec<char> = self.content.chars().collect();
let len = chars.len();
let (start, end) = edit.selection_range()?;
let (start, end) = (start.min(len), end.min(len));
(start < end).then(|| chars[start..end].iter().collect())
}
/// The caret's keys — the arrows, home and end — and nothing else: a text that cannot
/// be typed into takes no other key, and answers no message.
fn on_edit(&self, edit: &mut Edit, key: &Key) -> Option<Msg> {
self.selecting()?;
let chars: Vec<char> = self.content.chars().collect();
let len = chars.len();
let mut cursor = edit.cursor.min(len);
let mut anchor = edit.anchor.map(|anchor| anchor.min(len));
if move_caret(&chars, &mut cursor, &mut anchor, key) {
edit.cursor = cursor;
edit.anchor = anchor;
}
None
}
fn selection_handles(
&self,
width: f32,
edit: &Edit,
_scroll_y: f32,
) -> Option<[crate::SelectionHandle; 2]> {
let layout = self.selection_layout(width)?;
let len = self.content.chars().count();
handles_in(&layout, Point::new(0.0, 0.0), len, edit)
}
fn selection_anchor(&self, width: f32, edit: &Edit, _scroll_y: f32) -> Option<Rect> {
let layout = self.selection_layout(width)?;
let len = self.content.chars().count();
Some(selection_box_in(&layout, Point::new(0.0, 0.0), len, edit))
}
/// Copy, when something is selected, and Select all, unless everything is: a text
/// cannot be cut from or pasted into, so those are not offered.
fn selection_toolbar(&self, context: ToolbarContext) -> Option<&dyn Widget<Msg>> {
let selection = self.selecting()?;
selection.toolbars[usize::from(context.variant())]
.get_or_init(|| {
let mut items = Vec::new();
if context.has_selection {
items.push(ToolbarItem::copy());
}
if !context.all_selected {
items.push(ToolbarItem::select_all());
}
let build = selection
.toolbar_build
.as_ref()
.and_then(|build| build.downcast_ref::<ToolbarBuild<Msg>>());
let items = match build {
Some(build) => build(&context, items),
None => items,
};
let bar: Option<Box<dyn Widget<Msg>>> = (!items.is_empty())
.then(|| Box::new(SelectionToolbar::new(items)) as Box<dyn Widget<Msg>>);
Box::new(bar) as Box<dyn Any>
})
.downcast_ref::<Option<Box<dyn Widget<Msg>>>>()?
.as_deref()
}
fn semantics(&self) -> Option<frus_core::SemanticsProperties> {
// A text carries its content as its accessible label — or as a **heading**, which
// is a landmark rather than a label and is what a screen reader's user navigates by.
let role = if self.heading {
frus_core::Role::Heading
} else {
frus_core::Role::Label
};
Some(frus_core::SemanticsProperties::new(role).label(self.content.clone()))
}
}
#[cfg(test)]
mod tests {
/// An ellipsising text is **cut to the box it is given** instead of drawing past it.
///
/// It also tells the layout it may be given less than it asked for (`min_width: 0`),
/// which is half of what a row needs to keep its trailing widget intact. The other
/// half arrived in milestone 349: a widget that did not ask to give way is not
/// squeezed, so the trailing button keeps its width without saying anything.
#[test]
fn an_ellipsising_text_is_cut_to_its_box() {
let long = "A task name that is really rather long indeed and keeps going";
let style = TextStyle::new(18.0);
let full = frus_text::measure_style(long, style).width;
assert!(full > 300.0, "the fixture has to overflow: {full}");
let cut = truncate(long, &style.resolved(), 150.0);
assert!(cut.ends_with(ELLIPSIS), "cut with an ellipsis: {cut}");
let cut_width = frus_text::measure_style(&cut, style).width;
assert!(cut_width <= 150.0, "and it fits: {cut_width}");
assert!(cut.len() > 4, "without cutting everything: {cut}");
// A width it already fits in leaves it alone, ellipsis and all.
assert_eq!(truncate("Short", &style.resolved(), 500.0), "Short");
// A box with no room at all draws an ellipsis and nothing else. It used to draw
// the whole string, which is the one thing ellipsising exists to prevent.
assert_eq!(truncate(long, &style.resolved(), 0.0), ELLIPSIS);
}
/// The layout half: an ellipsising text accepts less width than it asked for, a plain
/// one does not.
#[test]
fn an_ellipsising_text_lets_the_layout_shrink_it() {
use frus_layout::Dimension;
let plain =
Widget::<()>::style(&Text::new("A rather long label indeed").size(18.0).no_wrap());
let cut = Widget::<()>::style(
&Text::new("A rather long label indeed")
.size(18.0)
.ellipsis(),
);
assert_eq!(plain.min_width, Dimension::Auto, "content is its own floor");
assert_eq!(
cut.min_width,
Dimension::Length(0.0),
"and this one has none"
);
assert_eq!(plain.width, cut.width, "both still ask for the same width");
}
use super::*;
use frus_core::Primitive;
use frus_core::{MaskShader, TextAlign, TextOverflow};
/// A paragraph **sized to fit** — centred on a column's cross axis, so it gets
/// its natural width rather than the whole row — must be given a box the text
/// still fits in, and the thing below it must clear the lines it really has.
///
/// This failed on a device before the measurement was rounded up: the natural
/// width came back as a fraction, the layout rounded the box down below it, the
/// text wrapped onto a second line when painted, and the label underneath sat on
/// top of that line — the layout having reserved the height of one.
#[test]
fn a_paragraph_sized_to_fit_is_not_squeezed_into_wrapping() {
use crate::{build_ui, Container, Flex, Runtime, Size};
use frus_core::FontWeight;
use frus_layout::Align;
const MARK: Color = Color {
r: 1.0,
g: 0.0,
b: 1.0,
a: 1.0,
};
// Two labels: one that fits on a line at its natural width, one that cannot
// fit the box at all and must reserve every line it wraps onto.
for (label, lines) in [
("Write code", 1.0_f32),
("A rather long task name that certainly wraps", 2.0),
] {
let tree = Container::<()>::new().width(400.0).height(600.0).child(
Flex::column()
.width(376.0)
.align(Align::Center)
.gap(18.0)
.child(Text::new(label).size(24.0).weight(FontWeight::Bold).wrap())
.child(Container::new().height(20.0).color(MARK)),
);
let ui = build_ui(
&tree,
Size::new(400.0, 600.0),
&Runtime::default(),
&Theme::default(),
);
let paragraph = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Text {
position,
max_width,
..
} => Some((*position, max_width.unwrap_or(f32::MAX))),
_ => None,
})
.expect("the paragraph is painted");
let below = ui
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if *color == MARK => Some(*rect),
_ => None,
})
.expect("the label under it is painted");
// What the box it was given really costs, shaped at that width.
let painted =
frus_text::measure_wrapped(label, 24.0, FontWeight::Bold, false, Some(paragraph.1));
// Against the **whole** height those lines occupy, which is what a
// measurement reports since milestone 497: a height of `lines × line_height`
// is fractional and would be shaved by the layout's rounding, so it is
// rounded up before it leaves. Dividing the rounded height back by the line
// height gives 2.014 lines, which is arithmetic rather than a wrap.
let want = frus_core::fits(lines * frus_text::line_height(24.0));
assert!(
(painted.height - want).abs() < 0.01,
"{label:?} wrapped onto {} lines in a box of {}",
painted.height / frus_text::line_height(24.0),
paragraph.1
);
assert!(
below.y >= paragraph.0.y + painted.height - 0.01,
"{label:?}: the label underneath overlaps the paragraph ({below:?} vs {painted:?})"
);
}
}
/// A line limit drops what is past it and, asked for an ellipsis, says so on the
/// last line it kept.
#[test]
fn a_line_limit_cuts_the_paragraph_and_marks_the_cut() {
let long = "one two three four five six seven eight nine ten eleven twelve";
let text = Text::new(long)
.size(14.0)
.wrap()
.max_lines(2)
.overflow(TextOverflow::Ellipsis);
let fitted = text.fitted(90.0, &text.resolved(None));
// What comes back is a **prefix**, not a list of lines: it wraps into two when the
// renderer breaks it, which is where the breaking belongs.
assert!(
fitted.text.lines().count() == 1,
"one string, no newlines in it: {:?}",
fitted.text
);
let lines = frus_text::line_spans(
&fitted.text,
14.0,
FontWeight::Regular,
false,
Some(90.0),
true,
);
assert_eq!(lines.len(), 2, "and it breaks into two: {:?}", fitted.text);
assert!(fitted.too_tall, "and there was more");
assert!(
fitted.text.ends_with(ELLIPSIS),
"ending in an ellipsis: {:?}",
fitted.text
);
}
/// The same paragraph with room for every line is left exactly as it was written.
#[test]
fn a_limit_it_does_not_reach_changes_nothing() {
let text = Text::new("one two").size(14.0).wrap().max_lines(4);
let fitted = text.fitted(400.0, &text.resolved(None));
assert_eq!(fitted.text, "one two");
assert!(!fitted.too_tall && !fitted.too_wide);
}
/// A limit is a height cap: the words still wrap where they wrapped, and the box
/// stops at the line it was allowed.
#[test]
fn a_limit_caps_the_measured_height() {
let long = "one two three four five six seven eight nine ten eleven twelve";
let free = Text::new(long).size(14.0).wrap();
let capped = Text::new(long).size(14.0).wrap().max_lines(2);
let at = |t: &Text| {
Widget::<()>::measure(t, &Theme::default()).expect("measure")(Some(90.0), None).height
};
assert!(at(&free) > at(&capped), "the limit is doing something");
assert!(
(at(&capped) - frus_text::line_height(14.0) * 2.0).abs() < 0.5,
"two lines exactly: {}",
at(&capped)
);
}
/// **A line limit counts the lines the style asked for**, not lines of a default
/// height.
///
/// Milestone 409 gave a style a `height` and threaded it through the measurement and
/// the paint; it left twenty-four places computing `line_height(style.size)` — the
/// 1.2 default — while holding a style that said otherwise. A cap is one of them, and
/// it is the one a test can see: two lines of a doubled leading is twice the box, and
/// before this it was capped as though the leading had never been named (milestone
/// 412).
#[test]
fn a_limit_counts_lines_of_the_height_that_was_asked_for() {
let long = "one two three four five six seven eight nine ten eleven twelve";
let plain = Text::new(long).size(14.0).wrap().max_lines(2);
let open = Text::new(long).size(14.0).height(2.4).wrap().max_lines(2);
let at = |t: &Text| {
Widget::<()>::measure(t, &Theme::default()).expect("measure")(Some(90.0), None).height
};
let ratio = at(&open) / at(&plain);
assert!(
(ratio - 2.0).abs() < 0.02,
"a doubled leading doubles the two-line cap: {ratio}"
);
}
/// `Visible` draws past the box; `Clip` puts the box in the primitive's clip so the
/// renderer stops at the edge. Both draw the whole string — the difference is the
/// clip, not the text.
#[test]
fn clip_and_visible_differ_by_the_clip_and_not_the_words() {
let long = "a label far too long for the box it was given";
let paint = |overflow: TextOverflow| {
let text = Text::new(long).size(16.0).no_wrap().overflow(overflow);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 60.0, 20.0),
Status::default(),
&Theme::default(),
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text { text, clip, .. } => (text.clone(), *clip),
other => panic!("a text, not {other:?}"),
}
};
let (visible_text, visible_clip) = paint(TextOverflow::Visible);
let (clipped_text, clipped_clip) = paint(TextOverflow::Clip);
assert_eq!(visible_text, long, "nothing is cut");
assert_eq!(clipped_text, long, "nothing is cut here either");
assert_eq!(visible_clip, Rect::UNBOUNDED, "and nothing stops it");
assert_eq!(
clipped_clip,
Rect::new(0.0, 0.0, 60.0, 20.0),
"this one stops"
);
}
/// A **subtree** can hand a text its size, and a text that never chose one takes it.
///
/// The half that matters is where it is taken: the size has to reach the **box**, not
/// only the glyphs. A text drawn at 24 px inside a box measured for 16 leaves every
/// row on the screen the wrong height, and nothing in the picture says which of the
/// two numbers was the mistake.
#[test]
fn a_subtree_hands_a_text_its_size() {
let mut theme = Theme::default();
theme.widgets.text.style.size = Some(30.0);
// One line, so the box it asks for is a number this test can read.
let text = Text::new("Handed down").no_wrap();
let alone = Widget::<()>::style(&text);
let handed = Widget::<()>::style_themed(&text, &theme);
let (Dimension::Length(alone_w), Dimension::Length(handed_w)) = (alone.width, handed.width)
else {
panic!("a single line is a box of a known size");
};
assert!(
handed_w > alone_w * 1.5,
"the box grew with the type: {alone_w} → {handed_w}"
);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, handed_w, 40.0),
Status::default(),
&theme,
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text { size, .. } => assert_eq!(
*size, 30.0,
"and the glyphs agree with the box they were measured into"
),
other => panic!("a text, not {other:?}"),
}
}
/// A size the **caller** chose is not overruled — and a default nobody chose is.
///
/// The two halves are the whole rule, and either alone would be wrong: without the
/// first, a subtree silently resizes the one text that had asked to be different;
/// without the second, the feature does nothing at all, because every `Text` already
/// holds a size and a number cannot say whether anybody picked it.
#[test]
fn a_chosen_size_outranks_a_handed_one() {
let mut theme = Theme::default();
theme.widgets.text.style.size = Some(30.0);
let width = |text: &Text| match Widget::<()>::style_themed(text, &theme).width {
Dimension::Length(w) => w,
other => panic!("a known width, not {other:?}"),
};
// The same 16 px, once as a default and once as an answer.
let untouched = width(&Text::new("Handed down").no_wrap());
let chosen = width(&Text::new("Handed down").no_wrap().size(16.0));
assert!(
untouched > chosen,
"the one that chose kept its size: {untouched} vs {chosen}"
);
assert_eq!(
chosen,
width(&Text::new("Handed down").no_wrap().size(16.0)),
"and it keeps it however often it is asked"
);
}
/// The merge is **field by field**: a subtree that sets a colour and nothing else
/// leaves every size alone.
///
/// A whole-style handover would be the easy implementation and the wrong one — an app
/// bar recolouring its words would flatten the type scale of everything inside it.
#[test]
fn handing_down_a_colour_leaves_the_sizes_alone() {
let red = Color::rgb(1.0, 0.0, 0.0);
let mut theme = Theme::default();
theme.widgets.text.style.color = Some(red);
let text = Text::new("Words").no_wrap().size(22.0);
assert_eq!(
Widget::<()>::style_themed(&text, &theme).width,
Widget::<()>::style(&text).width,
"the box did not move"
);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 300.0, 40.0),
Status::default(),
&theme,
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text { size, color, .. } => {
assert_eq!(*color, red, "the colour came down");
assert_eq!(*size, 22.0, "the size stayed put");
}
other => panic!("a text, not {other:?}"),
}
}
/// A handed-down line limit also says the text **may be squeezed**.
///
/// It is the easy half to leave out, and leaving it out ships a subtree that
/// ellipsises its texts and never gets the chance to: a flex item's automatic minimum
/// size is its content, so each of them still refuses to give way and the mode never
/// fires. Saying what to do on overflow is what says it may be squeezed — however the
/// text was told.
#[test]
fn a_handed_down_limit_lets_the_text_give_way() {
let mut theme = Theme::default();
theme.widgets.text.max_lines = Some(1);
theme.widgets.text.overflow = Some(TextOverflow::Ellipsis);
let text = Text::new("a label far too long for the box it will be given");
assert_eq!(
Widget::<()>::style(&text).min_width,
Dimension::Auto,
"left alone it refuses to shrink"
);
assert_eq!(
Widget::<()>::style_themed(&text, &theme).min_width,
Dimension::Length(0.0),
"handed a limit, it gives way"
);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 80.0, 20.0),
Status::default(),
&theme,
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text { text, .. } => {
assert!(text.ends_with(ELLIPSIS), "and it was cut: {text:?}")
}
other => panic!("a text, not {other:?}"),
}
}
/// A handed-down **alignment** also makes the text ask for its parent's width.
///
/// Alignment is the one style setting that is also a *request*: a box exactly as wide
/// as its own text has nowhere to centre it in, so a text told to centre asks to fill
/// the line first. That request is made by `fill_axes`, which is why that hook
/// had to see the theme too — without it, the one setting that arrives by inheritance
/// would resolve correctly everywhere except where it takes effect, and centring a
/// subtree's texts would silently do nothing.
#[test]
fn a_handed_down_alignment_still_asks_for_the_width() {
let mut theme = Theme::default();
theme.widgets.text.align = Some(TextAlign::Center);
let text = Text::new("Centred").no_wrap();
assert_eq!(
Widget::<()>::fill_axes(&text, &Theme::default()),
crate::widget::FillAxes::NONE,
"left alone it hugs its words"
);
assert_eq!(
Widget::<()>::fill_axes(&text, &theme),
crate::widget::FillAxes::WIDTH,
"handed a centring, it asks for the line"
);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 300.0, 20.0),
Status::default(),
&theme,
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text {
align, max_width, ..
} => {
assert_eq!(*align, TextAlign::Center);
assert_eq!(*max_width, Some(300.0), "and it was given a box to sit in");
}
other => panic!("a text, not {other:?}"),
}
}
/// **Two nested wrappers each setting one field leave a text wearing both.**
///
/// This is what makes the merge worth its complexity. A whole-style handover would
/// look identical in a single-wrapper test and be wrong here: the inner wrapper would
/// replace the outer one's colour with nothing at all, and a section that set a size
/// inside a screen that set a colour would silently drop the colour.
#[test]
fn nested_wrappers_compose_field_by_field() {
use crate::{build_ui, Runtime, Size};
let muted = Color::rgb(0.4, 0.4, 0.45);
let outer = crate::DefaultTextStyle::from_text_style(TextStyle::NONE.color(muted));
let inner = crate::DefaultTextStyle::from_text_style(TextStyle::new(9.0));
let root: Box<dyn Widget<()>> =
Box::new(outer.around(inner.around(Text::new("Both").no_wrap())));
let ui = build_ui(
root.as_ref(),
Size::new(300.0, 100.0),
&Runtime::default(),
&Theme::default(),
);
let found = ui.scene().primitives().iter().find_map(|p| match p {
Primitive::Text { size, color, .. } => Some((*size, *color)),
_ => None,
});
assert_eq!(
found,
Some((9.0, muted)),
"the size came from the inner wrapper and the colour from the outer"
);
}
/// **A style may name a size and leave the weight to the subtree** — the thing this
/// framework could not express until `TextStyle`'s fields could each say *unset*.
///
/// `Text::styled(s, TextStyle::new(20.0))` used to answer a size, a weight *and* a
/// slant, because the type had nowhere to put "not said". So a caller who wanted one
/// step of the scale at a different size had to restate the weight, and a section that
/// set a weight for its labels could not reach a single one of them.
#[test]
fn a_style_may_fix_the_size_and_still_inherit_the_weight() {
let mut theme = Theme::default();
theme.widgets.text.style.weight = Some(FontWeight::Bold);
let text = Text::styled("Words", TextStyle::new(20.0)).no_wrap();
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 300.0, 40.0),
Status::default(),
&theme,
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text { size, weight, .. } => {
assert_eq!(*size, 20.0, "the size it named");
assert_eq!(*weight, FontWeight::Bold, "the weight it did not");
}
other => panic!("a text, not {other:?}"),
}
// And the box was measured at the same pair, not at one of each.
let bold_20 = frus_text::measure_styled("Words", 20.0, FontWeight::Bold, false).width;
match Widget::<()>::style_themed(&text, &theme).width {
Dimension::Length(w) => assert!(
(w - bold_20.ceil()).abs() < 0.01,
"measured {w}, drawn at {bold_20}"
),
other => panic!("a known width, not {other:?}"),
}
}
/// **The box grows with the reader's font size, and the glyphs agree with the box.**
///
/// The second half is the whole risk of this feature and the reason it is resolved at
/// one place rather than applied by each widget. Text measured at 16 and drawn at 24
/// leaves every row on the screen the wrong height at once, and nothing in the picture
/// says which of the two numbers was the mistake. So this asserts the pair, not the
/// paint: what the layout reserved is what the renderer was asked to draw.
#[test]
fn a_reader_who_asked_for_larger_text_gets_a_larger_box_too() {
use crate::{build_ui, MediaQuery, Runtime, Size};
let drawn = |scaler: f32| {
MediaQuery::new(Size::new(400.0, 200.0))
.with_text_scaler(scaler)
.scope(|| {
let text: Box<dyn Widget<()>> = Box::new(Text::new("Readable").no_wrap());
let ui = build_ui(
text.as_ref(),
Size::new(400.0, 200.0),
&Runtime::default(),
&Theme::default(),
);
let rect = ui.scene().primitives().iter().find_map(|p| match p {
Primitive::Text { size, bounds, .. } => Some((*size, *bounds)),
_ => None,
});
rect.expect("the text is drawn")
})
};
let (plain_size, plain_box) = drawn(1.0);
let (big_size, big_box) = drawn(1.5);
assert_eq!(plain_size, 16.0, "the framework's own, unscaled");
assert_eq!(big_size, 24.0, "and the reader's 1.5 of it");
assert!(
big_box.width > plain_box.width * 1.4,
"the box grew with the glyphs: {} → {}",
plain_box.width,
big_box.width
);
// The pair, which is the thing that must never come apart: the box the layout gave
// this text is the box its own drawn size measures to.
let measured = frus_text::measure_styled("Readable", big_size, FontWeight::Regular, false);
assert!(
(big_box.width - measured.width.ceil()).abs() < 0.51,
"reserved {} for glyphs measuring {}",
big_box.width,
measured.width
);
}
/// Outside a described surface **nothing scales**, which is what every test in this
/// file and every golden depends on: they build widgets with no `MediaQuery` around
/// them, and a framework that scaled by default would move all of them at once.
#[test]
fn with_no_surface_described_nothing_is_scaled() {
assert_eq!(
Text::new("x").resolved(None).style.size,
frus_core::DEFAULT_TEXT_SIZE
);
}
/// A text that fits is never clipped, whatever it asked for: a clip on every text
/// would put a hard edge through the antialiasing of every one of them.
#[test]
fn a_text_that_fits_is_not_clipped() {
let text = Text::new("short")
.size(16.0)
.no_wrap()
.overflow(TextOverflow::Clip);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 300.0, 20.0),
Status::default(),
&Theme::default(),
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text { clip, .. } => assert_eq!(*clip, Rect::UNBOUNDED),
other => panic!("a text, not {other:?}"),
}
}
/// `Fade` wraps the text in a masked group — the fade has to be a group, or the two
/// halves of an overlapping glyph would fade against the background separately.
#[test]
fn fade_wraps_the_text_in_a_masked_group() {
let text = Text::new("a label far too long for the box it was given")
.size(16.0)
.no_wrap()
.overflow(TextOverflow::Fade);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 60.0, 20.0),
Status::default(),
&Theme::default(),
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Layer {
primitives, filter, ..
} => {
assert_eq!(primitives.len(), 1, "the text, and only the text");
let mask = filter.mask.expect("a mask");
match mask.shader {
// The fade runs to the right edge of the box, horizontally, because
// that is the edge the line ran past.
MaskShader::Linear { from, to, .. } => {
assert!(
to.x > from.x && (to.x - 60.0).abs() < 0.01,
"{from:?} {to:?}"
);
assert!((to.y - from.y).abs() < 0.01, "horizontal");
}
other => panic!("a linear fade, not {other:?}"),
}
}
other => panic!("a masked layer, not {other:?}"),
}
}
/// Alignment reaches the primitive, and with it the width it aligns inside — which a
/// start-aligned text is deliberately not given.
#[test]
fn alignment_hands_the_renderer_a_width_and_start_does_not() {
let painted = |align: TextAlign| {
let text = Text::new("x").size(16.0).no_wrap().align(align);
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 200.0, 20.0),
Status::default(),
&Theme::default(),
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text {
align, max_width, ..
} => (*align, *max_width),
other => panic!("a text, not {other:?}"),
}
};
assert_eq!(painted(TextAlign::Center), (TextAlign::Center, Some(200.0)));
assert_eq!(painted(TextAlign::Start), (TextAlign::Start, None));
}
/// Saying what to do on overflow is what tells the layout the text may be squeezed;
/// a plain one still refuses, which is what keeps a row from losing its last widget.
#[test]
fn an_overflow_mode_is_what_makes_a_text_shrinkable() {
use frus_layout::Dimension;
let plain = Widget::<()>::style(&Text::new("a long enough label"));
let clipped =
Widget::<()>::style(&Text::new("a long enough label").overflow(TextOverflow::Clip));
assert_eq!(plain.min_width, Dimension::Auto);
assert_eq!(clipped.min_width, Dimension::Length(0.0));
}
#[test]
fn text_paints_a_text_primitive() {
let text = Text::new("Salut")
.size(20.0)
.no_wrap()
.color(Color::rgb(1.0, 0.0, 0.0));
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(5.0, 6.0, 100.0, 24.0),
Status::default(),
&Theme::default(),
&mut scene,
);
assert_eq!(scene.primitives().len(), 1);
assert_eq!(
scene.primitives()[0],
Primitive::Text {
position: Point::new(5.0, 6.0),
text: "Salut".to_string(),
size: 20.0,
color: Color::rgb(1.0, 0.0, 0.0),
weight: FontWeight::Regular,
italic: false,
max_width: None,
soft_wrap: false,
align: TextAlign::Start,
decoration: frus_core::TextDecoration::NONE,
decoration_color: None,
height: None,
family: None,
clip: Rect::UNBOUNDED,
// Painted directly rather than through the widget walk, so no box was
// declared: unknown, which the renderer reads as "covers everything".
bounds: Rect::UNBOUNDED,
owner: 0,
letter_spacing: 0.0,
}
);
}
#[test]
fn wrapped_text_measures_to_the_offered_width() {
let long = "a paragraph long enough to wrap onto several lines";
let text = Text::new(long).wrap();
// Measuring under constraints wraps: taller at 120 px than when free.
let measure = Widget::<()>::measure(&text, &Theme::default()).expect("measure closure");
let free = measure(None, None);
let narrow = measure(Some(120.0), None);
assert!(narrow.width <= 120.0);
assert!(narrow.height > free.height, "wrapped → taller");
// And the measure key changes with the content (the cache fix).
let other = Text::new("short").wrap();
assert_ne!(
Widget::<()>::measure_key(&text, &Theme::default()),
Widget::<()>::measure_key(&other, &Theme::default())
);
// A text that does not wrap is a box of a known size, and says so in its style
// rather than through a measurement: a measured leaf reports its narrowest useful
// width as its minimum content, and a row would take that as leave to fold it.
let plain = Text::new(long).no_wrap();
assert!(Widget::<()>::measure(&plain, &Theme::default()).is_none());
assert!(Widget::<()>::measure_key(&plain, &Theme::default()).is_none());
}
#[test]
fn styled_text_carries_weight_and_italic() {
let theme = Theme::default();
// One step of the theme's scale (title_medium = 16 px, medium weight).
let text = Text::styled("Title", theme.text.title_medium).italic();
let mut scene = Scene::new();
Widget::<()>::paint(
&text,
Rect::new(0.0, 0.0, 100.0, 24.0),
Status::default(),
&theme,
&mut scene,
);
match &scene.primitives()[0] {
Primitive::Text {
size,
weight,
italic,
color,
..
} => {
assert_eq!(*size, 16.0);
assert_eq!(*weight, FontWeight::Medium);
assert!(*italic);
// Color inherited from the theme (the style did not set one).
assert_eq!(*color, theme.on_surface);
}
_ => panic!("expected text"),
}
}
#[test]
fn bold_text_lays_out_wider() {
let w = |text: &Text| {
Widget::<()>::measure(text, &Theme::default()).expect("measure")(None, None).width
};
assert!(
w(&Text::new("Width").weight(FontWeight::Bold)) > w(&Text::new("Width")),
"bold must be wider"
);
}
/// The default is the reference's: prose put in a box narrower than itself is a
/// paragraph. Along a **row** it is not — a text runs past the end of one rather than
/// folding into a column of single words — and that is the floor the parent applies.
#[test]
fn text_wraps_down_a_column_and_runs_on_along_a_row() {
use crate::{build_ui, Container, Flex, Runtime, Size};
let long = "one two three four five six seven eight nine ten eleven twelve";
// The painted box, read from the scene: the text primitive carries the box it
// was laid out in, which is the number this is about.
let painted = |root: &dyn Widget<()>| {
let rt = Runtime::default();
let theme = Theme::default();
let ui = build_ui(root, Size::new(120.0, 300.0), &rt, &theme);
ui.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Text { bounds, .. } => Some(*bounds),
_ => None,
})
.expect("the text")
};
let column: Container<()> = Container::new()
.width(120.0)
.child(Flex::column().child(Text::new(long).size(12.0)));
// Two children, because a box with a single child is handing a width down rather
// than dividing a line up — and there a paragraph does wrap.
let row: Container<()> = Container::new().width(120.0).child(
Flex::row()
.child(Text::new(long).size(12.0))
.child(Container::new().width(10.0).height(10.0)),
);
let tall = painted(&column);
let wide = painted(&row);
assert!(
tall.width <= 120.5,
"the column gave it 120: {}",
tall.width
);
assert!(tall.height > 20.0, "so it wrapped: {}", tall.height);
assert!(wide.width > 120.0, "the row did not: {}", wide.width);
}
}
#[cfg(test)]
mod reader_font_size {
use frus_core::{Primitive, Size};
use crate::theme::Theme;
use crate::{build_ui_inspected, MediaQuery, Runtime, Widget};
type W = Box<dyn Widget<()>>;
type Case = (&'static str, fn() -> W);
/// Every glyph a widget paints, and the size it was drawn at.
fn glyphs(make: fn() -> W, scale: f32) -> Vec<(String, f32)> {
let root = make();
MediaQuery::new(Size::new(400.0, 300.0))
.with_text_scaler(scale)
.scope(|| {
let (ui, _) = build_ui_inspected(
root.as_ref(),
Size::new(400.0, 300.0),
&Runtime::default(),
&Theme::default(),
);
ui.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Text { text, size, .. } => Some((text.clone(), *size)),
_ => None,
})
.collect()
})
}
fn cases() -> Vec<Case> {
vec![
("Chip", || Box::new(crate::Chip::<()>::new("Filter"))),
("Button", || Box::new(crate::Button::<()>::new("Save"))),
("ListTile", || {
Box::new(crate::ListTile::<()>::new().title("A row"))
}),
("SnackBar", || Box::new(crate::SnackBar::<()>::new("Saved"))),
("Kbd", || Box::new(crate::Kbd::new("Ctrl"))),
("DropdownButton", || {
Box::new(crate::DropdownButton::new("Pick", ()))
}),
("Text", || Box::new(crate::Text::new("A line"))),
("TextField", || {
Box::new(crate::TextField::<()>::new("typed"))
}),
("Table", || {
Box::new(crate::Table::<()>::new(2).row(&["one", "two"]))
}),
("Tree", || {
Box::new(crate::Tree::new(|_| ()).node(1, 0, "a branch", false, false))
}),
]
}
/// **The reader's font size reaches the text a widget paints itself.**
///
/// `TextStyle::resolved` is the single place the setting is applied (milestone 403),
/// and forty-seven paint sites went around it: they named an `f32` and handed it
/// straight to the scene, so their text was the one size a reader could not change.
/// Nothing failed and nothing was reported — the widget simply ignored the request.
///
/// The door is shut now: [`frus_core::Scene::text`] takes a
/// [`frus_core::ResolvedTextStyle`], so a bare number does not compile. This test is
/// what keeps it shut, because a new widget can still reach for
/// [`frus_core::ResolvedTextStyle::exact`] — which is right for an icon and wrong for
/// a word.
#[test]
fn the_text_a_widget_paints_follows_the_readers_font_size() {
for (name, make) in cases() {
let plain = glyphs(make, 1.0);
let doubled = glyphs(make, 2.0);
assert!(!plain.is_empty(), "{name} paints no text at all");
assert_eq!(
plain.len(),
doubled.len(),
"{name}: a different number of runs at twice the size"
);
let grew = plain
.iter()
.zip(&doubled)
.any(|((_, a), (_, b))| *b > *a + 0.01);
assert!(
grew,
"{name}: not one glyph followed the reader — sizes {plain:?}"
);
}
}
/// **And the box grows to hold it.** A default height is a *floor*, as it is in the
/// reference — `max(_targetTileHeight, contentHeight)` — not a ceiling. A chip whose
/// height was a constant needed 34 px of glyphs inside 32 px and cut them.
#[test]
fn a_box_that_holds_text_grows_with_it() {
for (name, make) in cases() {
let root = make();
MediaQuery::new(Size::new(400.0, 300.0))
.with_text_scaler(2.0)
.scope(|| {
let (ui, _) = build_ui_inspected(
root.as_ref(),
Size::new(400.0, 300.0),
&Runtime::default(),
&Theme::default(),
);
let mut checked = 0;
for p in ui.scene().primitives() {
if let Primitive::Text {
text, size, bounds, ..
} = p
{
// The box the text was **laid out in**, not the widget's outermost
// rect: a table's outer box is enormous and would pass whatever its
// rows did. Checking the emitting box is what caught the table.
if bounds.height <= 0.0 {
continue;
}
// What the **shaper** gives back, not the nominal `line_height`:
// a face's real line box can be a fraction under the metric, and a
// box sized to the smaller number clips nothing.
let style = frus_core::ResolvedTextStyle::exact(*size);
let needed = frus_text::measure_resolved(text, &style).height;
checked += 1;
assert!(
needed <= bounds.height + 0.51,
"{name}: {text:?} needs {needed:.1} px in a box of {:.1}",
bounds.height
);
}
}
assert!(checked > 0, "{name}: no text was checked at all");
});
}
}
/// **Chrome caps the type instead of growing**, which is the reference's other answer
/// and the reason both exist. An app bar keeps its height — a toolbar that grew would
/// push every screen down — so it clamps the title's scaler to 1.34 rather than let
/// the reader out. Below that cap it follows like anything else.
#[test]
fn an_app_bar_caps_its_title_rather_than_growing() {
let title_size = |scale: f32| {
let bar = crate::AppBar::<()>::new().title(crate::Text::new("A title"));
MediaQuery::new(Size::new(400.0, 300.0))
.with_text_scaler(scale)
.scope(|| {
let root = bar.build();
let (ui, _) = build_ui_inspected(
root.as_ref(),
Size::new(400.0, 300.0),
&Runtime::default(),
&Theme::default(),
);
ui.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Text { text, size, .. } if text == "A title" => Some(*size),
_ => None,
})
.expect("the bar paints its title")
})
};
let plain = title_size(1.0);
assert!(
(title_size(1.2) - plain * 1.2).abs() < 0.1,
"under the cap the title follows the reader"
);
let capped = plain * crate::APP_BAR_MAX_TITLE_SCALE;
for scale in [1.5, 2.0, 4.0] {
assert!(
(title_size(scale) - capped).abs() < 0.1,
"at x{scale} the title is {} rather than the capped {capped}",
title_size(scale)
);
}
}
}
#[cfg(test)]
mod selectable_tests {
use super::*;
use crate::{build_ui, EditAction, Flex, Runtime, Size};
use frus_core::Primitive;
const WORDS: &str = "one two three four five six seven eight nine ten";
fn hit(text: &Text, x: f32, y: f32, width: f32) -> Option<usize> {
Widget::<()>::cursor_at(text, x, y, width, 0)
}
fn selected(cursor: usize, anchor: Option<usize>) -> Edit {
Edit {
cursor,
anchor,
composing: None,
}
}
/// The width of `prefix` in the framework's default text style.
fn width_of(prefix: &str) -> f32 {
frus_text::measure_resolved(prefix, &TextStyle::NONE.resolved()).width
}
/// The actions on the bar a context gets, in order.
fn bar_for(text: &Text, context: ToolbarContext) -> Option<Vec<EditAction>> {
let bar = Widget::<()>::selection_toolbar(text, context)?;
Some(
bar.children()
.iter()
.map(|button| button.edit_action().expect("a built-in action"))
.collect(),
)
}
/// **An ordinary text is not selectable**, and nothing about it changes: it takes no
/// focus, answers no hit test, and has no bar. Selectable is opted into, per text.
#[test]
fn an_ordinary_text_is_not_selectable() {
let text = Text::new("ORDER-4417");
assert!(!Widget::<()>::focusable(&text));
assert_eq!(Widget::<()>::text_value(&text), None);
assert_eq!(hit(&text, 10.0, 5.0, 200.0), None);
assert_eq!(Widget::<()>::word_at(&text, 2), None);
assert_eq!(
Widget::<()>::selected_text(&text, &selected(5, Some(0))),
None
);
assert!(Widget::<()>::selection_toolbar(&text, ToolbarContext::default()).is_none());
// A bar configured for a text that is not selectable changes nothing about it.
let configured = Text::new("x").selection_toolbar::<()>(|_, items| items);
assert!(!Widget::<()>::focusable(&configured));
assert_eq!(Widget::<()>::text_value(&configured), None);
}
/// **A selectable text takes focus and is a text field for the caret's sake, and not
/// for the keyboard's**: the arrows are its own, and the soft keyboard is not asked for.
#[test]
fn a_selectable_text_takes_focus_but_no_typing() {
let text = Text::new("ORDER-4417").selectable();
assert!(Widget::<()>::focusable(&text));
assert_eq!(Widget::<()>::text_value(&text), Some("ORDER-4417"));
assert!(!Widget::<()>::takes_typing(&text));
}
/// **A press lands on the character it is over**: at the start, between two letters, and
/// past the end.
#[test]
fn a_press_lands_between_the_letters_it_is_over() {
let text = Text::new("hello world").selectable();
assert_eq!(hit(&text, 0.0, 5.0, 400.0), Some(0));
assert_eq!(hit(&text, width_of("hello"), 5.0, 400.0), Some(5));
assert_eq!(hit(&text, width_of("hello w"), 5.0, 400.0), Some(7));
assert_eq!(hit(&text, 1000.0, 5.0, 400.0), Some(11));
}
/// **A wrapped paragraph is hit line by line**: the second line's first letter is the
/// first character after the break, not one on the first line at the same `x`.
#[test]
fn a_wrapped_paragraph_is_hit_line_by_line() {
let text = Text::new(WORDS).selectable();
let style = TextStyle::NONE.resolved();
let spans = frus_text::line_spans(
WORDS,
style.size,
style.weight,
style.italic,
Some(90.0),
true,
);
assert!(spans.len() >= 3, "the fixture wraps: {spans:?}");
let line = style.line_height();
for (index, span) in spans.iter().enumerate().take(3) {
let y = line * index as f32 + line * 0.5;
assert_eq!(
hit(&text, 0.0, y, 90.0),
Some(span.start),
"the start of line {index}"
);
}
}
/// **The layout follows the paragraph's leading**: a text set at twice the line height
/// has its second line twice as far down, and a hit test that assumed the default would
/// find the third line where the second is drawn.
#[test]
fn a_hit_follows_the_leading_the_paragraph_is_drawn_with() {
let text = Text::styled(WORDS, TextStyle::new(16.0).height(2.0)).selectable();
let spans =
frus_text::line_spans(WORDS, 16.0, FontWeight::Regular, false, Some(90.0), true);
assert!(spans.len() >= 3, "the fixture wraps: {spans:?}");
// 32 px a line: 48 is the middle of the second, which is the third at 19.2 a line.
assert_eq!(hit(&text, 0.0, 48.0, 90.0), Some(spans[1].start));
}
/// **A size handed down by a subtree is the size a press is measured at.** The hooks are
/// asked outside a frame, with no theme in reach, so the text writes down what its layout
/// resolved; answering from the framework's own default would put every press of a text in
/// a large-type section a few letters from where it was made.
#[test]
fn a_hit_follows_the_size_a_subtree_handed_down() {
let mut theme = Theme::default();
theme.widgets.text.style.size = Some(30.0);
let text = Text::new("hello world").selectable().no_wrap();
// Laid out and painted, as any tree on its way to the screen is.
let _ = build_ui::<()>(&text, Size::new(400.0, 100.0), &Runtime::default(), &theme);
let big = frus_text::measure_resolved("hello", &TextStyle::new(30.0).resolved()).width;
assert!(big > width_of("hello") * 1.5, "the fixture: {big}");
assert_eq!(hit(&text, big, 10.0, 400.0), Some(5));
}
/// **And the reader's font-size setting**, which is installed while a view is built and
/// not while a press is handled: the text remembers the one it was built under.
#[test]
fn a_hit_follows_the_readers_font_setting() {
let text =
frus_core::with_text_scale(2.0, || Text::new("hello world").selectable().no_wrap());
let doubled = frus_text::measure_resolved(
"hello",
&frus_core::with_text_scale(2.0, || TextStyle::NONE.resolved()),
)
.width;
assert!(doubled > width_of("hello") * 1.9, "the fixture: {doubled}");
assert_eq!(hit(&text, doubled, 10.0, 600.0), Some(5));
}
/// **What is copied is what is selected**, by character and not by byte, and in whichever
/// direction it was dragged.
#[test]
fn the_selected_text_is_the_characters_between_the_ends() {
let text = Text::new("héllo wörld").selectable();
let copy = |edit| Widget::<()>::selected_text(&text, &edit);
assert_eq!(copy(selected(4, Some(1))).as_deref(), Some("éll"));
assert_eq!(copy(selected(1, Some(4))).as_deref(), Some("éll"));
assert_eq!(copy(selected(3, Some(3))), None, "a caret selects nothing");
assert_eq!(copy(selected(3, None)), None);
assert_eq!(
copy(selected(usize::MAX, Some(0))).as_deref(),
Some("héllo wörld"),
"the end of everything, as Select all asks for it"
);
}
#[test]
fn a_double_click_selects_the_word() {
let text = Text::new("hello wörld_2!").selectable();
assert_eq!(Widget::<()>::word_at(&text, 8), Some((6, 13)));
assert_eq!(
Widget::<()>::word_at(&text, 13),
Some((13, 14)),
"a separator"
);
}
/// **The caret's keys move the caret, and no other key does anything** — a text that
/// cannot be typed into does not change, and answers no message.
#[test]
fn the_arrows_move_the_caret_and_typing_does_nothing() {
let text = Text::new("hello world").selectable();
let press = |edit: &mut Edit, key: Key| Widget::<()>::on_edit(&text, edit, &key);
let mut edit = selected(2, None);
let right = Key::Right {
shift: false,
word: false,
};
assert_eq!(press(&mut edit, right), None);
assert_eq!((edit.cursor, edit.anchor), (3, None));
let shift_right = Key::Right {
shift: true,
word: false,
};
press(&mut edit, shift_right);
assert_eq!(edit.selection_range(), Some((3, 4)), "Shift extends");
let word_left = Key::Left {
shift: false,
word: true,
};
press(&mut edit, word_left);
assert_eq!((edit.cursor, edit.anchor), (0, None), "a word to the left");
let select_to_end = Key::End {
shift: true,
doc: true,
};
press(&mut edit, select_to_end);
assert_eq!(edit.selection_range(), Some((0, 11)));
let before = edit;
for key in [
Key::Text("x".into()),
Key::Backspace,
Key::Delete,
Key::Enter,
Key::Escape,
] {
assert_eq!(press(&mut edit, key.clone()), None);
assert_eq!(edit, before, "{key:?} changed nothing");
}
}
fn paint(text: &Text, status: Status) -> Vec<Primitive> {
let mut scene = Scene::new();
Widget::<()>::paint(
text,
Rect::new(10.0, 20.0, 300.0, 40.0),
status,
&Theme::default(),
&mut scene,
);
scene.primitives().to_vec()
}
fn highlights(primitives: &[Primitive]) -> Vec<Rect> {
let selection = Theme::default().selection;
primitives
.iter()
.filter_map(|p| match p {
Primitive::Rect { rect, color, .. } if *color == selection => Some(*rect),
_ => None,
})
.collect()
}
/// **A focused selection is highlighted, under the words** — over the letters it
/// covers, in the theme's selection colour, and only while the text has the focus.
#[test]
fn a_selection_is_highlighted_under_the_words() {
let text = Text::new("hello world").selectable().no_wrap();
let focused = Status {
focused: true,
selection: Some((0, 5)),
..Status::default()
};
let primitives = paint(&text, focused);
let boxes = highlights(&primitives);
assert_eq!(boxes.len(), 1, "one line, one box: {boxes:?}");
assert!(
(boxes[0].x - 10.0).abs() < 0.5,
"from the text's left: {:?}",
boxes[0]
);
assert!(
(boxes[0].width - width_of("hello")).abs() < 1.0,
"as wide as the word: {:?}",
boxes[0]
);
assert_eq!(boxes[0].y, 20.0, "on the text's line");
let rect = primitives
.iter()
.position(|p| matches!(p, Primitive::Rect { .. }));
let words = primitives
.iter()
.position(|p| matches!(p, Primitive::Text { .. }));
assert!(rect < words, "below the words, so they stay readable");
let unfocused = Status {
selection: Some((0, 5)),
..Status::default()
};
assert!(
highlights(&paint(&text, unfocused)).is_empty(),
"not focused"
);
// And a text that is not selectable paints exactly what it always has.
assert!(highlights(&paint(&Text::new("hello world"), focused)).is_empty());
}
/// **A touch selection has its two handles**, hanging below the ends of it, and where
/// they are painted is where a finger is told to look for them.
#[test]
fn a_touch_selection_has_handles_where_they_are_painted() {
let text = Text::new("hello world").selectable().no_wrap();
let touched = Status {
focused: true,
handles: true,
selection: Some((0, 5)),
..Status::default()
};
let paths = |primitives: &[Primitive]| {
primitives
.iter()
.filter(|p| matches!(p, Primitive::Path { .. }))
.count()
};
assert_eq!(paths(&paint(&text, touched)), 2, "two handles");
let no_handles = Status {
handles: false,
..touched
};
assert_eq!(paths(&paint(&text, no_handles)), 0);
let [start, end] =
Widget::<()>::selection_handles(&text, 300.0, &selected(5, Some(0)), 0.0)
.expect("the handles of a selection");
assert!(
(end.line_center.x - start.line_center.x - width_of("hello")).abs() < 1.0,
"{start:?} {end:?}"
);
assert!(
start.rect.y > start.line_center.y,
"they hang below their line"
);
assert!(
Widget::<()>::selection_handles(&text, 300.0, &selected(5, None), 0.0).is_none(),
"a caret has none"
);
}
/// **The bar is placed against the selection's own box.**
#[test]
fn the_bar_is_anchored_on_the_selection() {
let text = Text::new("hello world").selectable().no_wrap();
let anchor = Widget::<()>::selection_anchor(&text, 300.0, &selected(5, Some(0)), 0.0)
.expect("an anchor");
assert!(anchor.x.abs() < 0.5, "{anchor:?}");
assert!((anchor.width - width_of("hello")).abs() < 1.0, "{anchor:?}");
}
/// **The bar offers what a text can do**: Copy of what is selected and Select all — no
/// Cut, and no Paste, for text that cannot be changed.
#[test]
fn the_bar_offers_copy_and_select_all_only() {
use EditAction::{Copy, SelectAll};
let text = Text::new("hello world").selectable();
let context = |has_selection, can_paste, all_selected| ToolbarContext {
has_selection,
can_paste,
all_selected,
};
assert_eq!(
bar_for(&text, context(true, true, false)),
Some(vec![Copy, SelectAll])
);
assert_eq!(bar_for(&text, context(true, false, true)), Some(vec![Copy]));
assert_eq!(
bar_for(&text, context(false, true, false)),
Some(vec![SelectAll])
);
assert_eq!(
bar_for(&text, context(false, false, true)),
None,
"nothing to offer"
);
}
/// **The application has its say over the bar**, as it has over a field's.
#[test]
fn the_application_can_change_the_bar() {
let context = ToolbarContext {
has_selection: true,
can_paste: false,
all_selected: false,
};
let more = Text::new("hello")
.selectable()
.selection_toolbar::<()>(|_, mut items| {
items.push(ToolbarItem::custom("Share", ()));
items
});
let bar = Widget::<()>::selection_toolbar(&more, context).expect("a bar");
assert_eq!(
bar.children().len(),
3,
"Copy, Select all and the application's"
);
let none = Text::new("hello")
.selection_toolbar::<()>(|_, _| Vec::new())
.selectable();
assert!(
Widget::<()>::selection_toolbar(&none, context).is_none(),
"an empty list shows no bar, whichever order the calls were made in"
);
}
/// **In a tree, a press on a selectable text finds it** — the widget the shell gives the
/// focus to and asks where the caret goes — and a text that is not selectable is not found.
#[test]
fn a_selectable_text_is_a_target_in_a_tree() {
let found = |selectable: bool| {
let text = if selectable {
Text::new("ORDER-4417").selectable()
} else {
Text::new("ORDER-4417")
};
let tree = Flex::column().width(300.0).height(100.0).child(text);
let ui = build_ui::<()>(
&tree,
Size::new(300.0, 100.0),
&Runtime::default(),
&Theme::default(),
);
ui.focus_hit(Point::new(5.0, 5.0)).is_some()
};
assert!(found(true));
assert!(!found(false));
}
}