teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Headless integration tests for the read-only `RichTextEditor`.
//!
//! These tests drive the widget through its public surface: add it to a
//! `WidgetTree`, poke a shared `TextDocument`, advance the simulated
//! clock, and verify that the widget produced layout, ran the frame
//! loop, and dispatched events correctly.

use std::cell::Cell;
use std::rc::Rc;
use teksilo_canvas::{Point, SizeProposal};
use teksilo_core::widget_tree::WidgetTree;
use teksilo_i18n::lit;
use teksilo_text::text_document::TextDocument;

use super::RichTextEditor;

fn tree_with_layout() -> WidgetTree {
    let mut tree = WidgetTree::new();
    tree.layout(SizeProposal::exact(400.0, 300.0));
    tree
}

fn tick_once(tree: &mut WidgetTree) {
    tree.request_frame();
    tree.tick_animations(std::time::Duration::from_millis(16));
    tree.layout(SizeProposal::exact(400.0, 300.0));
}

#[test]
fn read_only_constructs_and_exposes_version_signal() {
    let doc = TextDocument::new();
    doc.set_plain_text("Hello, world!").unwrap();
    let editor = RichTextEditor::read_only(doc);
    let version = editor.document_version();
    assert_eq!(
        version.get(),
        0,
        "freshly built editor reports version 0 until it drains events"
    );
}

#[test]
fn read_only_widget_places_into_tree_and_lays_out() {
    let doc = TextDocument::new();
    doc.set_plain_text("First paragraph.\n\nSecond paragraph with more text.")
        .unwrap();

    let mut tree = WidgetTree::new();
    let _id = tree.add(RichTextEditor::read_only(doc.clone()));

    // `build()` calls `ctx.request_frame()` so the tree reports the
    // editor wants to pump.
    tree.layout(SizeProposal::exact(400.0, 300.0));
    assert!(
        tree.frame_requested() || tree.needs_redraw(),
        "the editor must request a frame during build so its frame loop kicks in"
    );

    // Drive a handful of frames so the widget has a chance to drain
    // the `on_change` burst triggered by the initial `set_plain_text`
    // call, run its layout, and settle.
    for _ in 0..3 {
        tick_once(&mut tree);
    }
}

#[test]
fn shared_document_between_two_editors_delivers_events_independently() {
    // Two editors on one document both receive `on_change` callbacks
    // and update independently. This is the critical test that
    // justifies the `on_change`-based routing instead of
    // `poll_events`.
    let doc = TextDocument::new();
    doc.set_plain_text("initial").unwrap();

    let a = RichTextEditor::read_only(doc.clone());
    let b = RichTextEditor::read_only(doc.clone());
    let version_a = a.document_version();
    let version_b = b.document_version();

    let mut tree = WidgetTree::new();
    let _ia = tree.add(a);
    let _ib = tree.add(b);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // Initial drain: both editors receive the first burst of events
    // from `set_plain_text` that was queued on the document before the
    // editors subscribed. After subscription, another `set_plain_text`
    // fires events into *both* subscriptions.
    let before_a = version_a.get();
    let before_b = version_b.get();

    doc.set_plain_text("updated by external mutation").unwrap();

    // Pump one frame so each editor's frame loop drains its queue.
    tick_once(&mut tree);

    assert!(
        version_a.get() > before_a,
        "editor A must see the external mutation (version was {}, now {})",
        before_a,
        version_a.get()
    );
    assert!(
        version_b.get() > before_b,
        "editor B must see the external mutation (version was {}, now {})",
        before_b,
        version_b.get()
    );
}

#[test]
fn select_all_updates_has_selection_signal() {
    let doc = TextDocument::new();
    doc.set_plain_text("some text").unwrap();
    let editor = RichTextEditor::read_only(doc);
    let has_sel = editor.has_selection();

    assert!(!has_sel.get(), "initial state: nothing selected");
    editor.select_all();
    assert!(
        has_sel.get(),
        "select_all must flip the has_selection signal"
    );
    assert!(!editor.selected_text().is_empty());

    editor.deselect();
    assert!(
        !has_sel.get(),
        "deselect must flip has_selection back to false"
    );
}

#[test]
fn context_target_reports_plain_text_for_empty_document() {
    let doc = TextDocument::new();
    doc.set_plain_text("line").unwrap();
    let editor = RichTextEditor::read_only(doc);

    // Context target on a freshly constructed widget (no layout yet)
    // may return None because the typesetter has not run a layout
    // pass. That's a valid response — the test only asserts the call
    // does not panic.
    let _ = editor.context_target_at(Point::new(5.0, 5.0));
}

#[test]
fn idle_read_only_editor_does_not_pump_frames_after_events_drain() {
    // This is the draw-when-needed contract for rich-text widgets.
    // An editor with no pending events, no drag, no focus must not
    // keep `needs_redraw()` stuck at true.
    let doc = TextDocument::new();
    doc.set_plain_text("steady").unwrap();

    let mut tree = WidgetTree::new();
    let _ = tree.add(RichTextEditor::read_only(doc));
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // Pump a few frames to drain the startup burst.
    for _ in 0..5 {
        tick_once(&mut tree);
    }

    // Now the editor should be idle: no more frame requests.
    assert!(
        !tree.frame_requested(),
        "an idle read-only editor must stop requesting frames"
    );
}

#[test]
fn read_only_editor_arrow_keys_move_caret_and_preserve_selection() {
    // Full end-to-end navigation check: focus the widget, press a
    // sequence of arrow / Home / End / Ctrl+A keys, assert that the
    // cursor position and selection state track the key input.
    // Observes through the `cursor_position_signal` + `has_selection`
    // so the test never has to downcast through the arena.
    use teksilo_canvas::Point;
    use teksilo_core::event::{Key, Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::read_only(doc);
    let caret = editor.cursor_position_signal();
    let has_sel = editor.has_selection();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // Click near the start of the widget to place the caret.
    // Pump a render so the engine actually lays out the document.
    // Without this, `hit_test()` has nothing to hit, and the click
    // silently falls on the "no region" branch — the click returns
    // Ignored, no cursor placement, and later arrow keys operate on
    // a never-placed caret. Real apps never see this because their
    // render loop paints on every layout pass; the test has to do
    // it explicitly.
    let _ = tree.render();

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(1.0, 8.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
    let focused = tree.focused();
    assert!(
        focused.is_some_and(|f| f == id || tree.is_descendant_of(f, id)),
        "click must focus editor (focus={:?})",
        focused,
    );
    let after_click = caret.get();

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::ArrowRight,
        modifiers: Modifiers::NONE,
        text: None,
    });
    assert_eq!(
        caret.get(),
        after_click + 1,
        "ArrowRight must advance caret by 1 (was {}, now {})",
        after_click,
        caret.get()
    );

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::ArrowRight,
        modifiers: Modifiers::SHIFT,
        text: None,
    });
    assert_eq!(caret.get(), after_click + 2);
    assert!(has_sel.get(), "Shift+ArrowRight must flip has_selection");

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::End,
        modifiers: Modifiers::NONE,
        text: None,
    });
    assert_eq!(
        caret.get(),
        "Hello world".chars().count(),
        "End must move to block end"
    );
    assert!(
        !has_sel.get(),
        "End without shift must collapse the selection"
    );

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::Home,
        modifiers: Modifiers::NONE,
        text: None,
    });
    assert_eq!(caret.get(), 0, "Home must move to block start");

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::A,
        modifiers: Modifiers::CTRL,
        text: None,
    });
    assert!(has_sel.get(), "Ctrl+A must set has_selection");
}

#[test]
fn read_only_editor_end_key_does_not_escalate_past_block() {
    // Regression for the "End jumps into the next block on second
    // press" bug. text-document's `get_block_at_position` returns
    // the **next** block when queried at a block boundary, so a
    // naive `MoveOperation::EndOfBlock` from an already-at-end
    // cursor would land on the end of the next paragraph. The
    // widget guards the call with `at_block_end()`.
    use teksilo_canvas::Point;
    use teksilo_core::event::{Key, Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("first block\nsecond block").unwrap();
    let editor = RichTextEditor::read_only(doc);
    let caret = editor.cursor_position_signal();

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(1.0, 8.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::End,
        modifiers: Modifiers::NONE,
        text: None,
    });
    let after_first_end = caret.get();
    assert!(after_first_end > 0, "first End must move caret");

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::End,
        modifiers: Modifiers::NONE,
        text: None,
    });
    let after_second_end = caret.get();
    assert_eq!(
        after_second_end, after_first_end,
        "second End must stay at end of current block (was {}, now {})",
        after_first_end, after_second_end
    );
}

#[test]
fn read_only_editor_blink_policy_stays_off_when_unfocused() {
    // The read-only preset uses `CaretPolicy::Hidden`, so `blinking_active`
    // is always false in the frame loop. Even if we tried to focus it,
    // no blink pump should kick in — verifying here that an unfocused
    // editor is idle is the easier case.
    let doc = TextDocument::new();
    doc.set_plain_text("quiet").unwrap();

    let mut tree = WidgetTree::new();
    let _ = tree.add(RichTextEditor::read_only(doc));
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    // Drain the build-time frame request so the assertion reflects
    // the steady state, not the initial tick.
    tree.request_frame();
    tree.tick_animations(std::time::Duration::from_millis(16));
    tree.request_frame();
    tree.tick_animations(std::time::Duration::from_millis(16));

    assert!(
        !tree.frame_requested(),
        "an unfocused read-only editor must not chain-request frames"
    );
}

#[test]
fn read_only_editor_is_focusable_and_dispatches_key_events() {
    // Regression guard for "arrow keys don't move the caret" — the
    // widget must be marked focusable (so click-to-focus finds it)
    // and it must actually receive KeyDown events on its on_key
    // handler after gaining focus.
    use teksilo_canvas::Point;
    use teksilo_core::event::{Key, Modifiers, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("abcdef").unwrap();
    let editor = RichTextEditor::read_only(doc);
    let version = editor.document_version();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // Simulate a primary click on the middle of the widget to focus it.
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(100.0, 20.0),
        button: teksilo_core::event::PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
    let focused = tree.focused();
    assert!(
        focused.is_some_and(|f| f == id || tree.is_descendant_of(f, id)),
        "clicking the editor must focus it (focus={:?})",
        focused,
    );

    // Capture the cursor position before key dispatch.
    let version_before = version.get();
    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::ArrowRight,
        modifiers: Modifiers::NONE,
        text: None,
    });
    // The on_key handler should run, move the cursor, and bump the
    // document version signal (via has_selection mirror in paint or
    // via the frame-tick chain). More directly: the key handler
    // calls `ctx.request_frame()` which sets the frame-request flag,
    // proving the handler was invoked.
    let _ = version_before; // unused in this minimal assertion
    assert!(
        tree.frame_requested(),
        "on_key must call ctx.request_frame() when an arrow key is handled"
    );
}

#[test]
fn read_only_editor_with_shared_typesetter_also_renders_glyphs() {
    // Mirrors the teksilo-app configuration: a `SharedTypesetter` is
    // installed in `app_state`, and the editor's `build()` swaps its
    // private engine for one that shares the app's typesetter. This
    // is the only path that produces GPU-uploadable glyphs when run
    // through teksilo-app, so it must be exercised by a regression
    // test.
    use std::any::TypeId;
    use std::collections::HashMap;
    use teksilo_text::SharedTypesetter;

    let doc = TextDocument::new();
    doc.set_plain_text("Alpha Beta Gamma").unwrap();

    let mut tree = WidgetTree::new();
    let shared = SharedTypesetter::new_with_default_font();
    tree = tree.with_text_backend(shared.as_text_backend());

    // Install the shared typesetter into app_state so the widget
    // picks it up in build(), matching teksilo-app's wiring.
    let mut registry: HashMap<TypeId, Box<dyn std::any::Any>> = HashMap::new();
    registry.insert(TypeId::of::<SharedTypesetter>(), Box::new(shared));
    let ctx = teksilo_core::event_source::TreeAppContext::empty().with_app_state(registry);
    tree.set_app_context(std::rc::Rc::new(ctx));

    let _ = tree.add(RichTextEditor::read_only(doc));
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let frame = tree.render();
    assert!(
        !frame.glyphs.is_empty(),
        "shared-typesetter editor must emit glyphs, got {}",
        frame.glyphs.len()
    );
}

#[test]
fn read_only_editor_emits_glyphs_into_final_render_frame() {
    // Regression guard for the "blank viewer" bug.  Two related
    // defects caused the widget to render no text:
    //   1. `place_children` is never called for leaf widgets, so
    //      `viewport_width/height` on the editor state stayed at 0
    //      and layout produced a degenerate flow.
    //   2. `frame_loop::tick` ran during `tree.layout()` and called
    //      `engine.set_cursor(...)` *before* any `layout_full` had
    //      happened, poisoning text-typeset's render state so every
    //      subsequent `render()` returned zero glyphs even after a
    //      correct layout pass.
    // Both are now fixed: `paint()` wires the viewport from bounds
    // and runs layout, and `frame_loop::tick` gates `set_cursor` /
    // `ensure_caret_visible` behind `engine.has_full_layout()`.
    let doc = TextDocument::new();
    doc.set_plain_text("Alpha Beta Gamma Delta Epsilon")
        .unwrap();

    let mut tree = WidgetTree::new();
    let id = tree.add(RichTextEditor::read_only(doc));

    tree.layout(SizeProposal::exact(400.0, 300.0));
    let bounds = tree.bounds(id);
    assert!(bounds.width > 0.0 && bounds.height > 0.0);

    let frame = tree.render();
    assert!(
        !frame.glyphs.is_empty(),
        "expected the read-only editor to emit glyph quads into the rendered frame, got {} glyphs",
        frame.glyphs.len()
    );
    assert!(
        frame
            .glyphs
            .iter()
            .any(|g| g.screen[0] < 400.0 && g.screen[1] < 300.0),
        "glyph coordinates must land inside the widget viewport"
    );
}

// ---------------------------------------------------------------------------
// M8b editor preset tests.
// ---------------------------------------------------------------------------

/// Advance the tree through one frame-tick with a chosen delta,
/// long enough to cross the 150 ms debounce window when needed.
/// A plain `tick_once` uses 16 ms which is deliberately below the
/// debounce window for idle-loop tests; editor tests that need
/// debounced signals to publish should call this instead.
fn tick_past_debounce(tree: &mut WidgetTree) {
    tree.request_frame();
    tree.tick_animations(std::time::Duration::from_millis(200));
    tree.layout(SizeProposal::exact(400.0, 300.0));
}

fn press_key(
    tree: &mut WidgetTree,
    key: teksilo_core::event::Key,
    mods: teksilo_core::event::Modifiers,
) {
    use teksilo_core::event::WidgetEvent;
    tree.dispatch_event(WidgetEvent::KeyDown {
        key,
        modifiers: mods,
        text: None,
    });
}

fn press_char(tree: &mut WidgetTree, ch: char) {
    use teksilo_core::event::{Key, Modifiers, WidgetEvent};
    // Emulate a winit KeyDown carrying the printable character in
    // `text`. The editor path uses the `text` field, not the `key`
    // variant, to avoid coupling to a specific layout mapping.
    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::A, // placeholder; not read when `text` is present
        modifiers: Modifiers::NONE,
        text: Some(ch.to_string()),
    });
    let _ = (tree, ch);
}

fn focus_editor(tree: &mut WidgetTree, id: teksilo_core::widget_id::WidgetId) {
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};
    let _ = tree.render();
    // Click well inside the body so the chrome padding (editable
    // mode wraps the viewport in TextInput-style padding) doesn't
    // swallow the click. The body is the focusable inner leaf; the
    // wrapper composes chrome around it through
    // `RichTextEditorStyle::make_body`.
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(20.0, 20.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
    let focused = tree.focused();
    assert!(
        focused.is_some_and(|f| f == id || tree.is_descendant_of(f, id)),
        "focus_editor helper: click did not focus editor (focus={:?}, expected {:?} or a descendant)",
        focused,
        id,
    );
}

#[test]
fn editor_inserts_typed_characters_via_pending_chars_batch() {
    let doc = TextDocument::new();
    doc.set_plain_text("abc").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Cursor landed somewhere in "abc". Move to end via Ctrl+End
    // so the inserts append deterministically regardless of where
    // the click happened to land.
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );

    // Type " def" as a burst — 4 characters, all within one frame.
    for ch in [' ', 'd', 'e', 'f'] {
        press_char(&mut tree, ch);
    }
    // Pending_chars flushes at the next frame-loop tick.
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    let plain = doc.to_plain_text().unwrap_or_default();
    assert_eq!(
        plain, "abc def",
        "pending_chars batch must flush to a single insert — got {:?}",
        plain
    );
}

#[test]
fn editor_backspace_and_delete_remove_characters() {
    let doc = TextDocument::new();
    doc.set_plain_text("ABCDE").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );

    // Backspace twice → "ABC"
    press_key(
        &mut tree,
        teksilo_core::event::Key::Backspace,
        teksilo_core::event::Modifiers::NONE,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::Backspace,
        teksilo_core::event::Modifiers::NONE,
    );
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "ABC");

    // Home, then Delete → "BC"
    press_key(
        &mut tree,
        teksilo_core::event::Key::Home,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::Delete,
        teksilo_core::event::Modifiers::NONE,
    );
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "BC");
}

#[test]
fn editor_enter_inserts_a_new_block() {
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::Enter,
        teksilo_core::event::Modifiers::NONE,
    );
    for ch in ['s', 'e', 'c', 'o', 'n', 'd'] {
        press_char(&mut tree, ch);
    }
    for _ in 0..3 {
        tick_once(&mut tree);
    }
    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("first") && plain.contains("second") && plain.len() > "firstsecond".len(),
        "Enter must insert a block boundary between 'first' and 'second', got {:?}",
        plain
    );
}

#[test]
fn editor_undo_redo_round_trip_restores_can_undo_signal() {
    let doc = TextDocument::new();
    doc.set_plain_text("base").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let can_undo = editor.can_undo();
    let can_redo = editor.can_redo();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    for ch in ['!', '!'] {
        press_char(&mut tree, ch);
    }
    // Flush pending_chars (tick 1) and advance past the 150 ms
    // debounce window so can_undo/can_redo publish (tick 2).
    tick_past_debounce(&mut tree);
    tick_past_debounce(&mut tree);
    let after_insert = doc.to_plain_text().unwrap_or_default();
    assert_eq!(after_insert, "base!!");
    assert!(
        can_undo.get(),
        "after insert can_undo must be true (published through debounce drain)"
    );

    press_key(
        &mut tree,
        teksilo_core::event::Key::Z,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "base",
        "Ctrl+Z must revert the insert"
    );
    assert!(
        can_redo.get(),
        "after undo can_redo must be true — signal published via debounce"
    );

    press_key(
        &mut tree,
        teksilo_core::event::Key::Y,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "base!!",
        "Ctrl+Y must reapply the insert"
    );
}

#[test]
fn editor_bold_toggle_applies_to_selection() {
    // `TextCursor::merge_char_format` operates on the selection range
    // `[anchor, position]`. With no selection the range is empty and
    // no character is touched — that matches the godot reference,
    // where Ctrl+B only takes visible effect when there's a
    // selection. This test selects "text" and confirms Ctrl+B bolds
    // the whole run.
    let doc = TextDocument::new();
    doc.set_plain_text("text").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Select the whole document.
    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );

    press_key(
        &mut tree,
        teksilo_core::event::Key::B,
        teksilo_core::event::Modifiers::CTRL,
    );

    // Read format at the document start via an independent cursor
    // parked at position 1 (inside the selection range). Because
    // `char_format()` inspects the underlying inline element rather
    // than any transient cursor state, both the widget's cursor and
    // a freshly-created one see the updated format.
    let probe = state.borrow().document.cursor();
    probe.set_position(1, teksilo_text::text_document::MoveMode::MoveAnchor);
    let after = probe.char_format().unwrap_or_default();
    assert_eq!(
        after.font_bold,
        Some(true),
        "Ctrl+B on selection must bold the selected range — got {:?}",
        after.font_bold
    );

    // Re-select (Ctrl+A collapsed nothing, but the first Ctrl+B
    // cleared preferred_x; re-select is necessary because Ctrl+B
    // itself doesn't preserve the selection in this path) and
    // toggle off.
    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::B,
        teksilo_core::event::Modifiers::CTRL,
    );

    probe.set_position(1, teksilo_text::text_document::MoveMode::MoveAnchor);
    let after_off = probe.char_format().unwrap_or_default();
    assert_eq!(
        after_off.font_bold,
        Some(false),
        "Ctrl+B again must toggle the selection back to non-bold"
    );
}

#[test]
fn read_only_preset_emits_no_cursor_decoration() {
    // After the Hidden flip, the paint pass must never emit a cursor
    // quad for the read-only preset, regardless of focus or blink.
    let doc = TextDocument::new();
    doc.set_plain_text("quiet").unwrap();

    let mut tree = WidgetTree::new();
    let id = tree.add(RichTextEditor::read_only(doc));
    tree.layout(SizeProposal::exact(400.0, 300.0));
    // Click to focus — would normally kick off a blink for
    // CaretPolicy::Blinking, but READ_ONLY_PRESET is Hidden now.
    focus_editor(&mut tree, id);
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    let frame = tree.render();
    use teksilo_canvas::DecorationKind;
    assert!(
        !frame
            .decorations
            .iter()
            .any(|d| matches!(d.kind, DecorationKind::Cursor)),
        "Hidden caret policy must not emit any DecorationKind::Cursor rects"
    );
}

#[test]
fn caret_hidden_when_window_inactive() {
    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    tick_once(&mut tree);

    // Focused editor in an active window: caret on (on_focus set it; the blink
    // interval hasn't elapsed). `caret_visible` is the value the paint gate
    // (`caret_visible && has_focus && window_active`) reads.
    assert!(state.borrow().has_focus, "editor took focus");
    assert!(state.borrow().window_active);
    assert!(
        state.borrow().caret_visible.get(),
        "caret visible when focused in an active window"
    );

    // Window blur: the window-active effect hides the caret synchronously,
    // without waiting for a frame tick.
    tree.set_window_active(false);
    assert!(!state.borrow().window_active);
    assert!(
        !state.borrow().caret_visible.get(),
        "caret_visible cleared on window blur"
    );

    // Reactivate: the caret returns immediately (the editor still holds focus).
    tree.set_window_active(true);
    assert!(state.borrow().window_active);
    assert!(
        state.borrow().caret_visible.get(),
        "caret restored on window reactivate"
    );
}

#[test]
fn selection_color_desaturates_when_window_inactive() {
    let theme = teksilo_core::presets::intui::light();
    let active_color = theme.colors.editor_selection_bg.to_array();
    let inactive_color = theme.colors.selection_bg_inactive.to_array();
    assert_ne!(active_color, inactive_color);

    let doc = TextDocument::new();
    doc.set_plain_text("hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new().with_theme(theme);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    let _ = tree.render();

    // Active window: the vivid theme selection colour is pushed to the engine.
    assert_eq!(
        state.borrow().last_selection_color,
        Some(active_color),
        "active window uses the vivid editor selection colour"
    );

    // Inactive: it desaturates to the muted inactive selection colour.
    tree.set_window_active(false);
    let _ = tree.render();
    assert_eq!(
        state.borrow().last_selection_color,
        Some(inactive_color),
        "inactive window desaturates the selection"
    );

    // Reactivate: the vivid colour returns.
    tree.set_window_active(true);
    let _ = tree.render();
    assert_eq!(
        state.borrow().last_selection_color,
        Some(active_color),
        "reactivating restores the vivid selection"
    );
}

#[test]
fn a_reactivated_editor_re_arms_its_frame_loop() {
    // Regression: an editor that goes dormant and comes back must restart its
    // frame tick. The dormant branch of the activation effect deliberately does
    // not re-arm `frame_request` (a parked editor has nothing to paint) and the
    // tick effect is skipped entirely while dormant — so without an explicit
    // re-arm on the way back, the editor paints once and then goes quiet.
    //
    // The caret is what makes that visible: `on_focus` restarts the blink, but
    // only the tick pushes the cursor through to the engine, so a re-activated
    // editor that is then focused draws no caret at all. The in-tree modal path
    // takes exactly this route on every open — build, `set_dormant`, mount,
    // `activate`, then focus.
    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    // Park it, then bring it back — the modal presenter's exact sequence.
    tree.set_dormant(id);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    // Clear whatever the parking left armed, so the assertion below can only be
    // satisfied by the re-activation itself.
    state.borrow().frame_request.as_ref().unwrap().set(false);

    tree.activate(id);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    assert!(
        state.borrow().frame_request.as_ref().unwrap().get(),
        "a re-activated editor must re-arm its frame loop, or its caret never \
         blinks again and a modal opens caretless"
    );
}

#[test]
fn custom_selection_color_is_not_desaturated_when_inactive() {
    use teksilo_tokens::Color;
    let custom = Color::from_hex("#FF00FF");
    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();
    let editor = RichTextEditor::editor(doc).selection_color(custom);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    let _ = tree.render();
    assert_eq!(state.borrow().last_selection_color, Some(custom.to_array()));

    // An app-set selection colour opts out of auto-desaturation (macOS
    // semantics): it stays fixed when the window goes inactive.
    tree.set_window_active(false);
    let _ = tree.render();
    assert_eq!(
        state.borrow().last_selection_color,
        Some(custom.to_array()),
        "custom selection colour stays fixed while the window is inactive"
    );
}

#[test]
fn caret_color_follows_theme_in_dark_mode() {
    // Regression: the typesetter defaults the caret to opaque black, so
    // the editor must push the theme's `editor_caret` role into the
    // engine each paint. Without it the blinking caret stays black under
    // a dark theme — invisible against the dark editor background.
    use teksilo_text::{CursorAffinity, CursorDisplay, TypesetterDecorationKind as DecorationKind};

    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();

    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::dark());
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    // Paint runs here, syncing the engine's cursor colour from the theme.
    let _ = tree.render();

    let expected = teksilo_core::presets::intui::dark()
        .colors
        .editor_caret
        .to_array();
    assert_ne!(
        expected,
        [0.0, 0.0, 0.0, 1.0],
        "dark theme's editor_caret must not be black, or this test proves nothing"
    );

    // Force a visible caret so the cursor-only render path emits a
    // DecorationKind::Cursor rect regardless of the current blink phase.
    let mut st = state.borrow_mut();
    st.engine.set_cursor(&CursorDisplay {
        position: 0,
        anchor: 0,
        affinity: CursorAffinity::Downstream,
        visible: true,
        selected_cells: Vec::new(),
    });
    let caret_color = st.engine.with_render_cursor_only(|frame| {
        frame
            .decorations
            .iter()
            .find(|d| matches!(d.kind, DecorationKind::Cursor))
            .map(|d| d.color)
    });

    assert_eq!(
        caret_color,
        Some(expected),
        "caret must paint in the theme's editor_caret colour, not the engine's black default"
    );
}

// ---------------------------------------------------------------------------
// Phase B tests — clipboard, double/triple tap, drag-select, Ctrl+A ladder.
// ---------------------------------------------------------------------------

fn ctx_with_memory_clipboard(
    tree: &mut WidgetTree,
) -> teksilo_platform::clipboard::ClipboardHandle {
    use std::any::TypeId;
    use std::collections::HashMap;
    use teksilo_core::event_source::TreeAppContext;
    use teksilo_platform::clipboard::{ClipboardHandle, MemoryClipboard};
    let handle = ClipboardHandle::new(MemoryClipboard::new());
    let mut registry: HashMap<TypeId, Box<dyn std::any::Any>> = HashMap::new();
    registry.insert(TypeId::of::<ClipboardHandle>(), Box::new(handle.clone()));
    let ctx = TreeAppContext::empty().with_app_state(registry);
    tree.set_app_context(std::rc::Rc::new(ctx));
    handle
}

fn synth_pointer_down(tree: &mut WidgetTree, x: f32, y: f32) {
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(x, y),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
}

fn synth_pointer_up(tree: &mut WidgetTree, x: f32, y: f32) {
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};
    tree.dispatch_event(WidgetEvent::PointerUp {
        position: Point::new(x, y),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
}

fn synth_pointer_move(tree: &mut WidgetTree, x: f32, y: f32) {
    use teksilo_core::event::WidgetEvent;
    tree.dispatch_event(WidgetEvent::PointerMove {
        position: Point::new(x, y),
    });
}

#[test]
fn editor_copy_sets_system_clipboard_plain_text() {
    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Select everything, copy.
    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::C,
        teksilo_core::event::Modifiers::CTRL,
    );

    assert_eq!(
        clipboard.get_text().unwrap_or_default(),
        "Hello world",
        "Ctrl+C must push the selection's plain text into the clipboard"
    );
}

#[test]
fn editor_cut_removes_selection_and_fills_clipboard() {
    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::X,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        clipboard.get_text().unwrap_or_default(),
        "Hello world",
        "Ctrl+X must copy the selection before removing"
    );
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "",
        "Ctrl+X must remove the selection from the document"
    );
}

#[test]
fn editor_paste_inserts_system_clipboard_text() {
    let doc = TextDocument::new();
    doc.set_plain_text("start ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard.set_text("pasted").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(doc.to_plain_text().unwrap_or_default(), "start pasted");
}

#[test]
fn editor_copy_paste_round_trip_uses_stored_fragment() {
    // Copy a selection, then paste at a different position. The
    // paste path uses the stored fragment because the system
    // clipboard's plain text matches. Phase B's in-process rich
    // preservation guarantee.
    let doc = TextDocument::new();
    doc.set_plain_text("one two three").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let _ = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Select "one" via Shift+Right.
    press_key(
        &mut tree,
        teksilo_core::event::Key::Home,
        teksilo_core::event::Modifiers::CTRL,
    );
    for _ in 0..3 {
        press_key(
            &mut tree,
            teksilo_core::event::Key::ArrowRight,
            teksilo_core::event::Modifiers::SHIFT,
        );
    }
    press_key(
        &mut tree,
        teksilo_core::event::Key::C,
        teksilo_core::event::Modifiers::CTRL,
    );

    // After copy the stored fragment is set.
    {
        let st = state.borrow();
        assert!(
            st.rich_clipboard_fragment.is_some(),
            "Ctrl+C must stash the rich fragment"
        );
        assert!(
            st.rich_clipboard_marker.is_some(),
            "Ctrl+C must stash the marker that identifies the payload as ours"
        );
        assert_eq!(
            st.rich_clipboard_plain, None,
            "this backend carries the marker, so the plain-text identity — the \
             fallback for backends that cannot — must stay unset: another \
             application's identical text would otherwise pick up our fragment"
        );
    }

    // Move to end, paste. The paste path finds its own marker in the system
    // clipboard's HTML payload and reinserts the fragment.
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "one two threeone",
        "paste must append 'one' at end via the stored fragment"
    );
}

#[test]
fn double_click_selects_word() {
    // The editor wires `on_double_tap` to select the word under the
    // pointer. The gesture recognizer fires on the second press
    // within 300 ms / 10 px, and the handler calls
    // `cursor.select(SelectionType::WordUnderCursor)`.
    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo charlie").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    // Two presses in close succession — the arena's DoubleTapRecognizer
    // fires the second one.
    synth_pointer_down(&mut tree, 50.0, 8.0);
    synth_pointer_up(&mut tree, 50.0, 8.0);
    synth_pointer_down(&mut tree, 50.0, 8.0);
    synth_pointer_up(&mut tree, 50.0, 8.0);

    let selected = state.borrow().cursor.selected_text().unwrap_or_default();
    assert!(
        !selected.is_empty() && "alpha bravo charlie".contains(selected.as_str()),
        "double-click must select a word, got {:?}",
        selected
    );
    assert!(
        !selected.contains(' '),
        "double-click must select a single word, not a span with whitespace"
    );
}

#[test]
fn triple_click_selects_block() {
    // Three consecutive clicks within the window. The arena's
    // cooperative recognizer plumbing lets both double-tap and
    // triple-tap observe the full sequence; the editor's
    // `on_triple_tap` handler calls
    // `cursor.select(SelectionType::BlockUnderCursor)`.
    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo charlie").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    for _ in 0..3 {
        synth_pointer_down(&mut tree, 50.0, 8.0);
        synth_pointer_up(&mut tree, 50.0, 8.0);
    }

    let selected = state.borrow().cursor.selected_text().unwrap_or_default();
    assert_eq!(
        selected, "alpha bravo charlie",
        "triple-click must select the whole block, got {:?}",
        selected
    );
}

#[test]
fn click_after_double_click_does_not_block_arena() {
    // Regression guard for the "on_pointer_event returns Handled and
    // consumes the event before the gesture arena sees it" bug.
    // After Phase B, `on_pointer_event::PointerDown` returns
    // `Ignored` so the arena still runs — both `on_double_tap` and
    // the caret-placement side effect must fire.
    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo charlie").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    // Click 1: the caret lands somewhere via on_pointer_event; the
    // double-tap recognizer is pending.
    synth_pointer_down(&mut tree, 50.0, 8.0);
    synth_pointer_up(&mut tree, 50.0, 8.0);
    let after_click_1 = state.borrow().cursor.selected_text().unwrap_or_default();
    assert!(
        after_click_1.is_empty(),
        "click 1 must not produce a selection (got {:?})",
        after_click_1
    );

    // Click 2 within the window: the arena fires on_double_tap →
    // the word becomes selected. If on_pointer_event had returned
    // Handled, the arena wouldn't have seen click 2 and this would
    // still be empty.
    synth_pointer_down(&mut tree, 50.0, 8.0);
    synth_pointer_up(&mut tree, 50.0, 8.0);
    let after_click_2 = state.borrow().cursor.selected_text().unwrap_or_default();
    assert!(
        !after_click_2.is_empty(),
        "click 2 must fire on_double_tap and select a word"
    );
}

#[test]
fn drag_select_extends_selection() {
    // Simulate PointerDown at x=1, PointerMove to x=80, check the
    // cursor anchors at the press position and extends to the move
    // position. Uses PointerMove (not PointerDown) for the second
    // event so the editor's drag-state machine handles it.
    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo charlie delta echo")
        .unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    synth_pointer_down(&mut tree, 1.0, 8.0);
    let anchor_before = state.borrow().cursor.anchor();
    synth_pointer_move(&mut tree, 120.0, 8.0);

    let st = state.borrow();
    assert!(
        st.cursor.has_selection(),
        "drag must extend a selection from the press position"
    );
    assert_eq!(
        st.cursor.anchor(),
        anchor_before,
        "anchor must stay at the press position during drag"
    );
}

#[test]
fn ctrl_a_outside_table_is_single_shot_document() {
    // Outside a table, Ctrl+A is single-shot `SelectionType::Document`.
    // A second Ctrl+A leaves the selection unchanged (still the
    // whole document), and the level stays at 0.
    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo charlie").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    let first = state.borrow().cursor.selected_text().unwrap_or_default();
    let first_level = state.borrow().select_all_level;
    assert_eq!(first, "alpha bravo charlie");
    assert_eq!(
        first_level, 0,
        "non-table Ctrl+A stays at level 0 (single-shot Document)"
    );

    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    let second = state.borrow().cursor.selected_text().unwrap_or_default();
    assert_eq!(second, "alpha bravo charlie");
    assert_eq!(state.borrow().select_all_level, 0);
}

#[test]
fn ctrl_a_reset_on_other_key() {
    // Ctrl+A at level 1, then ArrowRight (level resets to 0), then
    // Ctrl+A again must be level 1 (Document because no table).
    // This locks the reset rule at the top of `on_key`.
    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo").unwrap();
    let editor = RichTextEditor::editor(doc);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::ArrowRight,
        teksilo_core::event::Modifiers::NONE,
    );
    assert_eq!(
        state.borrow().select_all_level,
        0,
        "any non-SelectAll key resets select_all_level to 0"
    );

    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    assert_eq!(state.borrow().select_all_level, 0);
    assert_eq!(
        state.borrow().cursor.selected_text().unwrap_or_default(),
        "alpha bravo"
    );
}

// The old `accessibility_text_cache` was removed as part of the
// AccessKit TextRun overhaul — `accessibility()` now walks the
// document flow to emit per-paragraph / per-run children instead
// of stuffing the whole document into one `set_value` call. The
// replacement tests live below under the "AccessKit TextRun
// emission" section and cover flow snapshot caching, signal-
// driven a11y_dirty propagation, TextRun node emission, and
// AccessKit action handling.

// ---------------------------------------------------------------------------
// HTML rich-clipboard round-trip tests
// ---------------------------------------------------------------------------

#[test]
fn editor_copy_writes_both_plain_text_and_html() {
    // After Ctrl+C on a selection the system clipboard carries both
    // payloads so external apps that prefer HTML can get rich content
    // while plain-text surfaces (Notepad, terminal) still see text.
    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::C,
        teksilo_core::event::Modifiers::CTRL,
    );

    assert_eq!(
        clipboard.get_text().unwrap_or_default(),
        "Hello world",
        "plain-text payload must be present"
    );
    assert!(
        clipboard.has_html(),
        "copy must also write an HTML payload via DocumentFragment::to_html"
    );
    let html = clipboard
        .get_html()
        .expect("HTML payload must be readable after copy");
    assert!(
        html.contains("Hello world"),
        "serialised HTML must carry the copied text, got {:?}",
        html
    );
}

#[test]
fn editor_paste_prefers_self_round_trip_over_html() {
    // The paste path checks the stashed rich fragment *before* the
    // HTML branch. This guarantees lossless intra-editor round-trip:
    // even if the HTML serialisation is lossy for some element (say,
    // an obscure format flag), copy+paste in the same editor reuses
    // the original fragment bit-exact.
    let doc = TextDocument::new();
    doc.set_plain_text("one two three").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let _ = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Select "one" at the start and copy — this stashes the rich
    // fragment on state and writes HTML+plain to the clipboard.
    press_key(
        &mut tree,
        teksilo_core::event::Key::Home,
        teksilo_core::event::Modifiers::CTRL,
    );
    for _ in 0..3 {
        press_key(
            &mut tree,
            teksilo_core::event::Key::ArrowRight,
            teksilo_core::event::Modifiers::SHIFT,
        );
    }
    press_key(
        &mut tree,
        teksilo_core::event::Key::C,
        teksilo_core::event::Modifiers::CTRL,
    );

    // State now holds the fragment.
    assert!(
        state.borrow().rich_clipboard_fragment.is_some(),
        "copy stashes the fragment"
    );

    // Paste at end — plain-text match kicks in the self-round-trip
    // arm before the HTML arm even gets a chance.
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "one two threeone",
        "self-round-trip fragment must land intact after Ctrl+C / Ctrl+V"
    );
}

#[test]
fn editor_paste_from_external_html_inserts_rich_content() {
    // Simulates pasting from another application: the clipboard
    // carries HTML + plain text with no matching stashed fragment
    // (the `rich_clipboard_fragment` stash is empty). The paste path
    // falls through to the HTML branch, parses the payload via
    // text-document's `TextCursor::insert_html`, and applies the
    // formatting to the document.
    let doc = TextDocument::new();
    doc.set_plain_text("before ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    // Seed the clipboard as if another app had copied a bold word.
    // Plain text and HTML both present — the paste path prefers HTML
    // because the stashed fragment is None (no self-round-trip).
    clipboard.set_html("<p><b>BOLD</b></p>", "BOLD").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("BOLD"),
        "HTML paste must insert the content's text ({:?})",
        plain
    );

    // Confirm the bold format landed on the inserted text by reading
    // `char_format` at the BOLD word. Use `find` on plain text to
    // locate the first B, then position a probe cursor there.
    let b_pos = plain.find("BOLD").expect("BOLD substring");
    let probe = doc.cursor();
    probe.set_position(b_pos, teksilo_text::text_document::MoveMode::MoveAnchor);
    let fmt = probe.char_format().unwrap_or_default();
    assert_eq!(
        fmt.font_bold,
        Some(true),
        "HTML <b> tag must translate to TextFormat.font_bold = true, got {:?}",
        fmt.font_bold
    );
}

#[test]
fn editor_paste_falls_back_to_plain_when_html_unsupported() {
    // A backend that does not override set_html / get_html must still
    // round-trip a plain-text paste. Regression guard for the
    // default-trait-body contract.
    use std::any::TypeId;
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;
    use teksilo_core::event_source::TreeAppContext;
    use teksilo_platform::clipboard::{ClipboardBackend, ClipboardHandle};

    struct PlainOnly(Rc<RefCell<String>>);
    impl ClipboardBackend for PlainOnly {
        fn get_text(&mut self) -> Result<String, String> {
            Ok(self.0.borrow().clone())
        }
        fn set_text(&mut self, text: &str) -> Result<(), String> {
            *self.0.borrow_mut() = text.to_string();
            Ok(())
        }
    }
    let text = Rc::new(RefCell::new("pasted".to_string()));
    let handle = ClipboardHandle::new(PlainOnly(text.clone()));

    let doc = TextDocument::new();
    doc.set_plain_text("start ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let mut registry: HashMap<TypeId, Box<dyn std::any::Any>> = HashMap::new();
    registry.insert(TypeId::of::<ClipboardHandle>(), Box::new(handle.clone()));
    let ctx = TreeAppContext::empty().with_app_state(registry);
    tree.set_app_context(std::rc::Rc::new(ctx));

    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "start pasted",
        "paste must still work when the backend lacks HTML support"
    );
    assert!(!handle.has_html(), "plain-only backend never reports HTML");
}

#[test]
fn editor_paste_unformatted_strips_html_to_plain() {
    // Ctrl+Shift+V must bypass both the rich-fragment stash and the
    // HTML branch and insert only the plain text. External apps that
    // generate rich HTML (Firefox's "Copy" of a formatted paragraph)
    // should still paste as plain text when the user explicitly
    // requests it.
    let doc = TextDocument::new();
    doc.set_plain_text("before ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard.set_html("<p><b>BOLD</b></p>", "BOLD").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL | teksilo_core::event::Modifiers::SHIFT,
    );
    tick_past_debounce(&mut tree);

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("BOLD"),
        "plain text must be inserted verbatim, got {:?}",
        plain
    );

    // Confirm no bold format was applied — Ctrl+Shift+V is
    // explicitly plain-only.
    let b_pos = plain.find("BOLD").expect("BOLD substring");
    let probe = doc.cursor();
    probe.set_position(b_pos, teksilo_text::text_document::MoveMode::MoveAnchor);
    let fmt = probe.char_format().unwrap_or_default();
    assert!(
        !matches!(fmt.font_bold, Some(true)),
        "Paste Unformatted must not apply bold formatting — got font_bold = {:?}",
        fmt.font_bold
    );
}

// ---------------------------------------------------------------------------
// EditorHandle clipboard + selection — the detached-handle counterparts of
// the editor-owned methods above. A context-menu factory can only capture an
// `EditorHandle` (never the move-only `RichTextEditor` that owns it), so
// these must work purely through the shared state. Each mirrors the
// `RichTextEditor` body and is exercised end-to-end through a handle.
// ---------------------------------------------------------------------------

#[test]
fn handle_copy_sets_system_clipboard_plain_text() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // Select everything, then copy through the handle.
    handle.select_all();
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| handle.copy(ctx));

    assert_eq!(
        clipboard.get_text().unwrap_or_default(),
        "Hello world",
        "EditorHandle::copy must push the selection's plain text into the clipboard"
    );
}

#[test]
fn handle_copy_without_selection_is_noop() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // No selection: copy must capture nothing (mirrors the editor / Ctrl+C
    // "stay silent on an empty selection" convention).
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| handle.copy(ctx));

    assert!(
        clipboard.get_text().unwrap_or_default().is_empty(),
        "EditorHandle::copy with no selection must not write the clipboard"
    );
}

#[test]
fn handle_cut_removes_selection_and_fills_clipboard() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    handle.select_all();
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| handle.cut(ctx));
    tick_past_debounce(&mut tree);

    assert_eq!(
        clipboard.get_text().unwrap_or_default(),
        "Hello world",
        "EditorHandle::cut must copy the selection before removing"
    );
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "",
        "EditorHandle::cut must remove the selection from the document"
    );
}

#[test]
fn handle_paste_inserts_system_clipboard_text() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("start ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard.set_text("pasted").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Deterministically place the caret at the document end, then paste
    // through the handle.
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| handle.paste(ctx));
    tick_past_debounce(&mut tree);

    assert_eq!(doc.to_plain_text().unwrap_or_default(), "start pasted");
}

#[test]
fn handle_paste_unformatted_strips_html_to_plain() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("before ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard.set_html("<p><b>BOLD</b></p>", "BOLD").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| handle.paste_unformatted(ctx));
    tick_past_debounce(&mut tree);

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("BOLD"),
        "EditorHandle::paste_unformatted must insert the plain text verbatim, got {:?}",
        plain
    );
    // The rich payload must be dropped — no bold format applied.
    let b_pos = plain.find("BOLD").expect("BOLD substring");
    let probe = doc.cursor();
    probe.set_position(b_pos, teksilo_text::text_document::MoveMode::MoveAnchor);
    let fmt = probe.char_format().unwrap_or_default();
    assert!(
        !matches!(fmt.font_bold, Some(true)),
        "EditorHandle::paste_unformatted must not apply bold formatting — got font_bold = {:?}",
        fmt.font_bold
    );
}

#[test]
fn handle_select_all_then_delete_selection_empties_document() {
    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    assert!(
        !handle.has_selection().get(),
        "a freshly built editor must start with no selection"
    );

    handle.select_all();
    assert!(
        handle.has_selection().get(),
        "EditorHandle::select_all must produce a non-empty selection"
    );

    handle.delete_selection();
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "",
        "EditorHandle::delete_selection must remove the selected range"
    );
    assert!(
        !handle.has_selection().get(),
        "the selection must be cleared once the range is deleted"
    );
}

#[test]
fn handle_delete_selection_without_selection_is_noop() {
    let doc = TextDocument::new();
    doc.set_plain_text("Hello").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // No selection active — must leave the document untouched.
    handle.delete_selection();
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "Hello",
        "EditorHandle::delete_selection with no selection must be a no-op"
    );
}

#[test]
fn handle_can_paste_reflects_clipboard_contents() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("x").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // Empty clipboard → nothing to paste.
    let empty = std::cell::Cell::new(true);
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| empty.set(handle.can_paste(ctx)));
    assert!(
        !empty.get(),
        "can_paste must be false while the clipboard is empty"
    );

    // Populate the clipboard → paste becomes available.
    clipboard.set_text("something").unwrap();
    let filled = std::cell::Cell::new(false);
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| filled.set(handle.can_paste(ctx)));
    assert!(
        filled.get(),
        "can_paste must be true once the clipboard holds text"
    );
}

#[test]
fn handle_can_paste_true_for_html_only_clipboard() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("x").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    // An HTML-only clipboard: `text/html` with NO `text/plain` companion
    // (the empty plain fallback leaves has_text() false while has_html()
    // is true). `paste()` inserts this via its external-HTML branch, so
    // `can_paste` must report it as pasteable — probing has_text() alone
    // would wrongly grey out the Paste command.
    clipboard.set_html("<p><b>rich</b></p>", "").unwrap();
    assert!(
        !clipboard.has_text(),
        "precondition: the HTML-only clipboard must have no plain text"
    );
    assert!(clipboard.has_html(), "precondition: HTML payload present");
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    let can = std::cell::Cell::new(false);
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| can.set(handle.can_paste(ctx)));
    assert!(
        can.get(),
        "can_paste must be true for an HTML-only clipboard — paste() would insert the HTML"
    );
}

#[test]
fn handle_can_paste_false_without_clipboard_backend() {
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("x").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    // No `ctx_with_memory_clipboard` — the tree has no ClipboardHandle in
    // app-state, exactly like a headless / feature-off build.
    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    let can = std::cell::Cell::new(true);
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| can.set(handle.can_paste(ctx)));
    assert!(
        !can.get(),
        "can_paste must degrade to false when no clipboard backend is installed"
    );
}

#[test]
fn editor_ime_composition_then_commit_inserts_finalised_text() {
    // A CJK-style composition: two intermediate compositions before
    // the final commit. The document must reflect the current preedit
    // at each step, and the final state must contain only the committed
    // string (no duplicate preedit fragments).
    use teksilo_core::event::WidgetEvent;

    let doc = TextDocument::new();
    doc.set_plain_text("").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let _ = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    tree.dispatch_event(WidgetEvent::ImeComposition {
        text: "n".to_string(),
        cursor: None,
    });
    tree.tick_animations(std::time::Duration::from_millis(16));
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "n");

    tree.dispatch_event(WidgetEvent::ImeComposition {
        text: "ni".to_string(),
        cursor: None,
    });
    tree.tick_animations(std::time::Duration::from_millis(16));
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "ni");

    tree.dispatch_event(WidgetEvent::ImeCommit {
        text: "".to_string(),
    });
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "",
        "commit must replace the preedit with the final character"
    );
}

#[test]
fn editor_ime_composition_cancelled_leaves_document_clean() {
    // Composition cancelled mid-sequence (empty composition event).
    // The tentative preedit must be removed entirely.
    use teksilo_core::event::WidgetEvent;

    let doc = TextDocument::new();
    doc.set_plain_text("before ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let _ = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );

    tree.dispatch_event(WidgetEvent::ImeComposition {
        text: "abc".to_string(),
        cursor: None,
    });
    tree.tick_animations(std::time::Duration::from_millis(16));
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "before abc");

    // Cancel: empty composition.
    tree.dispatch_event(WidgetEvent::ImeComposition {
        text: String::new(),
        cursor: None,
    });
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "before ",
        "cancelled composition must leave no residue"
    );
}

#[test]
fn editor_paste_external_identical_plain_does_not_reuse_stale_fragment() {
    // Regression: previously the self-round-trip check compared plain
    // text only, so after an internal copy of "foo" (bold), an external
    // copy of "foo" (plain) with identical text would re-insert the
    // bold fragment. The marker-based check must distinguish them.
    let doc = TextDocument::new();
    doc.set_plain_text("foo").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Step 1: select "foo" and make it bold, then copy internally.
    press_key(
        &mut tree,
        teksilo_core::event::Key::Home,
        teksilo_core::event::Modifiers::CTRL,
    );
    for _ in 0..3 {
        press_key(
            &mut tree,
            teksilo_core::event::Key::ArrowRight,
            teksilo_core::event::Modifiers::SHIFT,
        );
    }
    press_key(
        &mut tree,
        teksilo_core::event::Key::B,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::C,
        teksilo_core::event::Modifiers::CTRL,
    );

    // Step 2: simulate another app overwriting the clipboard with the
    // same plain text but **no HTML** — the marker check should miss.
    clipboard.set_text("foo").unwrap();

    // Reset document so we can verify what gets pasted afresh.
    doc.set_plain_text("").unwrap();
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    // Paste must land as plain text (no bold) because the clipboard
    // no longer carries our marker.
    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("foo"),
        "plain paste must succeed, got {plain:?}"
    );
    let probe = doc.cursor();
    probe.set_position(
        plain.find("foo").unwrap(),
        teksilo_text::text_document::MoveMode::MoveAnchor,
    );
    let fmt = probe.char_format().unwrap_or_default();
    assert!(
        !matches!(fmt.font_bold, Some(true)),
        "external plain paste must NOT reuse stale bold fragment — got {:?}",
        fmt.font_bold
    );
}

#[test]
fn editor_paste_plain_text_with_newlines_splits_into_blocks() {
    // A multi-line plain clipboard payload (e.g. copied from a
    // terminal or a text file) must produce separate blocks per
    // line — text-document's `insert_text` stores `\n` as a
    // literal scalar, so the clipboard path has to split.
    let doc = TextDocument::new();
    doc.set_plain_text("").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard
        .set_text("line one\nline two\nline three")
        .unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.block_count(),
        3,
        "multi-line paste must split into 3 blocks, got {} with plain {:?}",
        doc.block_count(),
        doc.to_plain_text().unwrap_or_default()
    );
}

#[test]
fn editor_paste_plain_normalises_crlf() {
    // Windows clipboards deliver `\r\n`; classic Mac apps deliver
    // `\r`. Both must collapse to a single block boundary.
    let doc = TextDocument::new();
    doc.set_plain_text("").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard.set_text("a\r\nb\rc").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(doc.block_count(), 3, "CRLF and CR must split like LF");
}

// ---------------------------------------------------------------------------
// Default right-click context menu
// ---------------------------------------------------------------------------

#[test]
fn editor_right_click_opens_default_context_menu() {
    // `RichTextEditor::editor(...)` installs the default menu
    // factory. Framework intercepts Secondary PointerDown and calls
    // the factory via `show_context_menu_for`, which shows the
    // returned MenuList as an overlay.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let before = tree.active_overlays().len();
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(50.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));

    assert!(
        tree.active_overlays().len() > before,
        "right-click on an editor with default_context_menu enabled must open an overlay \
         (before: {}, after: {})",
        before,
        tree.active_overlays().len()
    );
}

#[test]
fn editor_right_click_suppressed_when_default_context_menu_disabled() {
    // `default_context_menu(false)` opts out. Right-click bubbles
    // past the widget unhandled; the framework's
    // `show_context_menu_for` walks up the parent chain and — with
    // no ancestor claiming a factory — returns false. No overlay.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("alpha bravo").unwrap();
    let editor = RichTextEditor::editor(doc).default_context_menu(false);

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let before = tree.active_overlays().len();
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(50.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));
    assert_eq!(
        tree.active_overlays().len(),
        before,
        "default_context_menu(false) must not show any overlay on right-click"
    );
}

#[test]
fn editor_context_menu_copy_item_copies_selection_to_clipboard() {
    // End-to-end: Ctrl+A to select, right-click to open the menu,
    // synthetic-click on Copy → clipboard ends up with the plain
    // text. Because menu items call `rt_clipboard::copy` directly
    // via their on_activate_fn closure, there is no dependency on
    // the Action/Intent dispatch ordering.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Select everything so Copy has non-empty content. Also sync
    // cursor signals so the menu factory sees `has_selection=true`
    // when it runs at the right-click.
    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );

    // Open the context menu via right-click. Two layout passes so
    // the overlay's widgets get real bounds — `tree.click` reads
    // `arena.bounds` to compute click center.
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(30.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    tree.layout(SizeProposal::exact(400.0, 300.0));

    // Locate the Copy MenuItem via the a11y tree — nothing else
    // exposes labels, and the menu's internal widget ids aren't
    // public.
    let update = tree.sync_accessibility();
    let copy_node_id = update
        .nodes
        .iter()
        .find(|(_, n)| {
            n.role() == teksilo_core::accesskit::Role::MenuItem && n.label() == Some("Copy")
        })
        .map(|(id, _)| *id)
        .expect("Copy menu item must appear in the a11y tree after right-click");
    let copy_widget_id = teksilo_core::accessibility::node_id_to_widget_id_maybe(copy_node_id)
        .expect("MenuItem NodeId maps back to a concrete WidgetId");

    // Sanity-check bounds so a failure here says "overlay didn't
    // lay out" rather than the downstream clipboard assertion.
    let bounds = tree.bounds(copy_widget_id);
    assert!(
        bounds.width > 0.0 && bounds.height > 0.0,
        "Copy menu item must have non-zero bounds after overlay layout — got {:?}",
        bounds
    );

    tree.click(copy_widget_id);
    tick_past_debounce(&mut tree);

    assert_eq!(
        clipboard.get_text().unwrap_or_default(),
        "Hello world",
        "clicking Copy in the context menu must write the selected plain text to the clipboard"
    );
    assert!(
        clipboard.has_html(),
        "clicking Copy must also write the HTML payload via DocumentFragment::to_html"
    );
}

#[test]
fn editor_context_menu_paste_unformatted_item_strips_formatting() {
    // The Paste Unformatted item's closure calls
    // `rt_clipboard::paste_unformatted` directly, which inserts
    // plain text verbatim regardless of any HTML payload on the
    // clipboard.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("before ").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard.set_html("<b>BOLD</b>", "BOLD").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    // Move caret to end so the insert appends.
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(30.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    tree.layout(SizeProposal::exact(400.0, 300.0));

    let update = tree.sync_accessibility();
    let pu_node_id = update
        .nodes
        .iter()
        .find(|(_, n)| {
            n.role() == teksilo_core::accesskit::Role::MenuItem
                && n.label() == Some("Paste Unformatted")
        })
        .map(|(id, _)| *id)
        .expect("Paste Unformatted menu item must appear");
    let pu_widget_id = teksilo_core::accessibility::node_id_to_widget_id_maybe(pu_node_id)
        .expect("MenuItem NodeId maps back to WidgetId");

    tree.click(pu_widget_id);
    tick_past_debounce(&mut tree);

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("BOLD"),
        "plain text must be inserted verbatim, got {:?}",
        plain
    );
    // No bold formatting because this is the plain-text path.
    let b_pos = plain.find("BOLD").expect("BOLD substring");
    let probe = doc.cursor();
    probe.set_position(b_pos, teksilo_text::text_document::MoveMode::MoveAnchor);
    let fmt = probe.char_format().unwrap_or_default();
    assert!(
        !matches!(fmt.font_bold, Some(true)),
        "Paste Unformatted must not apply bold; got font_bold = {:?}",
        fmt.font_bold
    );
}

#[test]
fn editor_context_menu_copy_item_disabled_without_selection() {
    // The factory reads `cursor.has_selection()` at right-click
    // time. Without a selection, the Copy MenuItem is built with
    // `.enabled(false)` — the a11y node reports disabled, and its
    // tap handler short-circuits.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(30.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));

    let update = tree.sync_accessibility();
    let copy_node = update
        .nodes
        .iter()
        .find(|(_, n)| {
            n.role() == teksilo_core::accesskit::Role::MenuItem && n.label() == Some("Copy")
        })
        .expect("Copy menu item must appear in the a11y tree");
    assert!(
        copy_node.1.is_disabled(),
        "Copy must be disabled when there is no selection"
    );
}

#[test]
fn read_only_editor_context_menu_shape_hides_cut_and_paste() {
    // The read-only preset's `ClipboardPolicy::CopyAndSelectAllOnly`
    // filters out Cut, Paste, and Paste Unformatted entirely — the
    // rendered menu has only Copy + Select All.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("quiet").unwrap();
    let editor = RichTextEditor::read_only(doc);

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(20.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));

    let update = tree.sync_accessibility();
    let labels: Vec<Option<&str>> = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == teksilo_core::accesskit::Role::MenuItem)
        .map(|(_, n)| n.label())
        .collect();
    assert!(
        labels.contains(&Some("Copy")),
        "read-only menu must include Copy, got labels {:?}",
        labels
    );
    assert!(
        labels.contains(&Some("Select All")),
        "read-only menu must include Select All, got labels {:?}",
        labels
    );
    assert!(
        !labels.contains(&Some("Cut")),
        "read-only menu must NOT include Cut, got labels {:?}",
        labels
    );
    assert!(
        !labels.contains(&Some("Paste")),
        "read-only menu must NOT include Paste, got labels {:?}",
        labels
    );
    assert!(
        !labels.contains(&Some("Paste Unformatted")),
        "read-only menu must NOT include Paste Unformatted, got labels {:?}",
        labels
    );
}

#[test]
fn editor_context_menu_slot_replaces_default_entirely() {
    // A user-supplied factory takes precedence. The default's
    // Cut/Copy/Paste/… items must not appear; only the user's
    // items are visible.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("content").unwrap();
    let editor = RichTextEditor::editor(doc).context_menu(|_pos, _ctx| {
        Some(Box::new(
            crate::menu_list::MenuList::new()
                .item(
                    crate::menu_item::MenuItem::new(lit!("Custom Action A")).on_activate_fn(|_| ()),
                )
                .item(
                    crate::menu_item::MenuItem::new(lit!("Custom Action B")).on_activate_fn(|_| ()),
                ),
        ))
    });

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(20.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));

    let update = tree.sync_accessibility();
    let labels: Vec<Option<&str>> = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == teksilo_core::accesskit::Role::MenuItem)
        .map(|(_, n)| n.label())
        .collect();

    assert!(
        labels.contains(&Some("Custom Action A")),
        "custom factory's items must appear, got {:?}",
        labels
    );
    assert!(
        !labels.contains(&Some("Copy")),
        "default Copy item must NOT appear when a custom factory is installed, got {:?}",
        labels
    );
}

#[test]
fn editor_right_click_does_not_collapse_selection() {
    // Right-click *inside* a live selection must leave it intact so the menu's
    // Cut/Copy can act on it. Here the whole document is selected (Ctrl+A), so
    // any click lands inside the selection — the context-menu factory's caret
    // reposition sees `hit ∈ [selection]` and preserves it. (A right-click
    // *outside* the selection instead collapses the caret to the click point —
    // see `editor_right_click_outside_selection_repositions_caret`.)
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let has_sel = editor.has_selection();

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    assert!(has_sel.get(), "Ctrl+A must flip has_selection");

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(30.0, 10.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));

    assert!(
        has_sel.get(),
        "right-click must preserve the existing selection"
    );
}

#[test]
fn editor_right_click_outside_selection_repositions_caret() {
    // A right-click *outside* the current selection collapses the caret to the
    // click point — the platform convention that makes the menu's Paste (and
    // "add word under cursor") act where the user clicked. This is the
    // mechanism behind the paste-under-cursor fix: paste always inserts at the
    // caret, so moving the caret to the click point is what makes paste land
    // there.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let has_sel = editor.has_selection();
    let caret = editor.cursor_position_signal();
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    focus_editor(&mut tree, id);

    // Select "world" (offsets 6..11), caret at the end.
    handle.select_range(6, 11);
    assert!(has_sel.get(), "precondition: a selection exists");

    // Right-click at the far left — resolves to the very start, outside [6, 11].
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(1.0, 8.0),
        button: PointerButton::Secondary,
        modifiers: Modifiers::NONE,
    });
    tree.layout(SizeProposal::exact(400.0, 300.0));

    assert!(
        !has_sel.get(),
        "right-click outside the selection must collapse it"
    );
    assert!(
        caret.get() < 6,
        "caret must move to the click point (got {})",
        caret.get()
    );
}

#[test]
fn editor_offset_at_point_hit_tests_window_coordinates() {
    // `EditorHandle::offset_at_point` maps a window-space point (as a
    // context-menu factory receives it) to a document offset. A click at the
    // far left lands near the start; a click far to the right lands near the
    // end of the (single-line) content.
    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let len = "Hello world".chars().count();
    let left = handle.offset_at_point(Point::new(2.0, 8.0));
    let right = handle.offset_at_point(Point::new(60.0, 8.0));
    assert!(
        matches!(left, Some(n) if n <= len),
        "a left-side click resolves to an in-bounds offset (got {left:?})"
    );
    assert!(
        matches!(right, Some(n) if n <= len),
        "a right-side click resolves to an in-bounds offset (got {right:?})"
    );
    if let (Some(l), Some(r)) = (left, right) {
        assert!(r >= l, "offset grows left→right ({l} → {r})");
    }
}

#[test]
fn editor_replace_range_rewrites_the_span_and_leaves_the_caret_after_it() {
    // `EditorHandle::replace_range` rewrites an arbitrary span (a spell-check
    // correction picked from a context menu) as a typed-style edit: the text is
    // replaced, the caret lands after the insertion, and it is one undo entry.
    let doc = TextDocument::new();
    doc.set_plain_text("Hello wrld today").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let caret = editor.cursor_position_signal();
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Replace "wrld" (offsets 6..10) with "world".
    handle.replace_range(6, 10, "world");
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "Hello world today",
        "the span is rewritten, the surrounding text untouched"
    );
    assert_eq!(
        caret.get(),
        11,
        "the caret sits just after the inserted text"
    );

    // One undo entry — the replacement is a single insert-over-selection, so a
    // single Ctrl+Z restores the original word (not a half-deleted one).
    handle.undo();
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "Hello wrld today",
        "one undo restores the original span"
    );
}

#[test]
fn editor_selection_reports_both_ends_from_one_read() {
    // `EditorHandle::selection` answers "is there a selection, and over what" from a
    // single borrow — the pair a caller would otherwise have to assemble from a live
    // `cursor_position()` and the lagging `cursor_anchor_signal()` mirror.
    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // A collapsed caret: both ends agree, which is how a caller detects "no selection".
    handle.select_range(3, 3);
    assert_eq!(
        handle.selection(),
        (3, 3),
        "no selection ⇒ anchor == position"
    );

    // A forward selection: anchor at the start, caret at the end.
    handle.select_range(6, 11);
    assert_eq!(handle.selection(), (6, 11));

    // A backwards drag is reported unordered, exactly as the cursor holds it — the
    // caller decides whether to sort. Losing this would hide right-to-left selections.
    handle.select_range(11, 6);
    assert_eq!(handle.selection(), (11, 6), "anchor may trail the caret");
}

#[test]
fn editor_replace_range_uses_char_offsets_not_bytes() {
    // Offsets are character positions, the same space `cursor_position` and
    // `select_range` use. "café" is 4 chars but 5 bytes: a byte-indexed
    // implementation would cut the accented word apart here.
    let doc = TextDocument::new();
    doc.set_plain_text("café wrld").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _cb = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // "wrld" is at char offsets 5..9 (byte offsets would be 6..10).
    handle.replace_range(5, 9, "world");
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "café world",
        "char offsets survive a multi-byte character earlier in the line"
    );
}

#[test]
fn read_only_editor_arrow_keys_survive_default_context_menu() {
    // Regression guard: installing the default context menu factory
    // must not disturb the read-only editor's navigation behaviour.
    // This is the test that broke the earlier arena-parenting
    // approach — we keep it to catch similar regressions if the
    // context-menu wiring changes again.
    use teksilo_core::event::{Key, Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    // Default context menu is ENABLED by default for read_only too
    // (it shows Copy + Select All). Crucially, the End key must
    // still move to block end.
    let editor = RichTextEditor::read_only(doc);
    let caret = editor.cursor_position_signal();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(1.0, 8.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
    let focused = tree.focused();
    assert!(
        focused.is_some_and(|f| f == id || tree.is_descendant_of(f, id)),
        "click must focus editor (focus={:?})",
        focused,
    );

    tree.dispatch_event(WidgetEvent::KeyDown {
        key: Key::End,
        modifiers: Modifiers::NONE,
        text: None,
    });
    assert_eq!(
        caret.get(),
        "Hello world".chars().count(),
        "End must move caret to block end even with default context menu installed"
    );
}

#[test]
fn read_only_editor_paste_unformatted_rejected_by_command_filter() {
    // The CommandFilter rejects PasteUnformatted (it mutates the
    // document) on the read-only preset. Pressing Ctrl+Shift+V must
    // not modify the document.
    let doc = TextDocument::new();
    doc.set_plain_text("immutable").unwrap();
    let editor = RichTextEditor::read_only(doc.clone());

    let mut tree = WidgetTree::new();
    let clipboard = ctx_with_memory_clipboard(&mut tree);
    clipboard.set_text("new content").unwrap();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::V,
        teksilo_core::event::Modifiers::CTRL | teksilo_core::event::Modifiers::SHIFT,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "immutable",
        "read-only editor must reject Ctrl+Shift+V"
    );
}

// ---------------------------------------------------------------------------
// AccessKit TextRun emission tests
// ---------------------------------------------------------------------------

#[test]
fn accessibility_emits_paragraph_and_text_run_children() {
    // The rewritten `accessibility()` walks `document.snapshot_flow()`
    // and emits one `Role::Paragraph` per block with one
    // `Role::TextRun` per fragment. This test dispatches
    // `tree.sync_accessibility()` and asserts the resulting
    // `TreeUpdate` contains at least one paragraph node and one
    // text-run node attached to the editor.
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("hello world").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let update = tree.sync_accessibility();
    let has_paragraph = update
        .nodes
        .iter()
        .any(|(_, n)| n.role() == Role::Paragraph);
    let has_text_run = update.nodes.iter().any(|(_, n)| n.role() == Role::TextRun);
    assert!(
        has_paragraph,
        "editor must emit at least one Paragraph child"
    );
    assert!(has_text_run, "editor must emit at least one TextRun child");
}

/// Pull the reported caret (the selection focus) out of a `TreeUpdate` as an
/// opaque `(node, char index)` pair — enough to tell whether it moved between
/// two walks, without depending on the run-id derivation.
fn reported_caret(
    update: &teksilo_core::accesskit::TreeUpdate,
) -> Option<(teksilo_core::accesskit::NodeId, usize)> {
    update.nodes.iter().find_map(|(_, n)| {
        n.text_selection()
            .map(|s| (s.focus.node, s.focus.character_index))
    })
}

/// A caret-only move (no edit) must re-walk the accessibility tree so the
/// reported selection tracks the caret. The walk reads the *live* cursor, so
/// this regresses only at the binding level: without an `AccessibilityOnly`
/// binding on the caret signals, `a11y_dirty` never flips on a plain arrow key,
/// `sync_accessibility` returns the stale cached tree, and a screen reader hears
/// the caret frozen at the last edit.
#[test]
fn a_caret_move_alone_rewalks_the_accessibility_selection() {
    use teksilo_core::event::{Key, Modifiers};

    let doc = TextDocument::new();
    doc.set_plain_text("hello world").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Anchor the caret at the line start, then take the baseline walk that fills
    // the cached AT tree.
    press_key(&mut tree, Key::Home, Modifiers::NONE);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let base = reported_caret(&tree.sync_accessibility());
    assert!(
        base.is_some(),
        "a focused editor must report a text selection"
    );

    // One arrow right — a pure caret move, no edit.
    press_key(&mut tree, Key::ArrowRight, Modifiers::NONE);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let after = reported_caret(&tree.sync_accessibility());

    assert!(
        after.is_some() && after != base,
        "the AT selection must follow a caret-only move (before {base:?}, after \
         {after:?} — equal means the walk returned the stale cached tree)"
    );
}

#[test]
fn accessibility_text_run_carries_value_and_character_lengths() {
    // The TextRun for plain ASCII "foo" must carry `value = "foo"`
    // and `character_lengths = [1, 1, 1]`. Locks the UTF-8
    // byte-length contract.
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("foo").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let update = tree.sync_accessibility();
    let text_run = update
        .nodes
        .iter()
        .find(|(_, n)| n.role() == Role::TextRun)
        .expect("at least one TextRun emitted");
    assert_eq!(text_run.1.value(), Some("foo"));
    assert_eq!(text_run.1.character_lengths(), &[1u8, 1, 1]);
}

#[test]
fn accessibility_multibyte_character_lengths_are_byte_counts() {
    // "café" has a multi-byte final character (é = 2 UTF-8 bytes).
    // AccessKit's `character_lengths` is one u8 per char, giving
    // the byte count — so the expected slice is [1, 1, 1, 2].
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("café").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let update = tree.sync_accessibility();
    let text_run = update
        .nodes
        .iter()
        .find(|(_, n)| n.role() == Role::TextRun && n.value() == Some("café"))
        .expect("'café' text run emitted");
    assert_eq!(text_run.1.character_lengths(), &[1u8, 1, 1, 2]);
}

#[test]
fn accessibility_text_run_carries_character_positions() {
    // The rewrite populates `character_positions` from
    // text-typeset's `character_geometry` so screen readers /
    // magnifiers can track the caret at character granularity.
    // This test just asserts the property is set and has the
    // right length — the actual layout math lives in text-typeset.
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("abc").unwrap();
    let editor = RichTextEditor::editor(doc);

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let update = tree.sync_accessibility();
    let text_run = update
        .nodes
        .iter()
        .find(|(_, n)| n.role() == Role::TextRun && n.value() == Some("abc"))
        .expect("'abc' text run emitted");
    // character_positions length matches character_lengths (one
    // entry per char). May be empty if the test harness doesn't
    // fully exercise text-typeset layout, in which case the field
    // is None and the accessibility pass deliberately skips it.
    if let Some(positions) = text_run.1.character_positions() {
        assert_eq!(positions.len(), 3);
    }
}

#[test]
fn accessibility_signal_driven_rebuild_on_text_edit() {
    // Previously, text edits didn't mark `a11y_dirty`.
    // Now the document_version signal
    // is bound at `BindingLevel::AccessibilityOnly` and every
    // edit flips `a11y_dirty` through `process_state_changes`.
    // This test types a character, ticks past debounce, and
    // asserts that `sync_accessibility()` sees different content
    // than the pre-edit tree.
    let doc = TextDocument::new();
    doc.set_plain_text("before").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    // Baseline: initial a11y tree contains "before".
    let first = tree.sync_accessibility();
    let initial_has_before = first.nodes.iter().any(|(_, n)| n.value() == Some("before"));
    assert!(initial_has_before, "initial tree must contain 'before'");

    // Type "X" at end. The document_version bump during
    // drain_events propagates through AccessibilityOnly binding
    // and flips a11y_dirty in process_state_changes.
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_char(&mut tree, 'X');
    tick_past_debounce(&mut tree);
    tick_past_debounce(&mut tree);

    let second = tree.sync_accessibility();
    let has_before_x = second
        .nodes
        .iter()
        .any(|(_, n)| n.value() == Some("beforeX"));
    assert!(
        has_before_x,
        "a11y rebuild after text edit must surface new content"
    );
}

// ---------------------------------------------------------------------------
// godot-parity ports: Tab, list indent/dedent, Ctrl+Enter, link/image clicks,
// horizontal caret visibility, widget formatting + query API, cell selection
// ---------------------------------------------------------------------------

#[test]
fn caret_char_format_uses_selection_start_when_selection_spans_formatted_runs() {
    // godot's query_char_format uses selection_start when a selection
    // is active — `cursor.position()` lands at the end of the
    // selection and may fall on a different run.
    // Build a document with plain "A" then bold "B". Select "AB".
    // caret_char_format() should report the START (plain "A"), which
    // is what a toolbar showing the selection's format should see.
    use teksilo_text::text_document::TextFormat;

    let doc = TextDocument::new();
    doc.set_plain_text("AB").unwrap();
    // Bold only the second char.
    let probe = doc.cursor();
    probe.set_position(1, teksilo_text::text_document::MoveMode::MoveAnchor);
    probe.move_position(
        teksilo_text::text_document::MoveOperation::Right,
        teksilo_text::text_document::MoveMode::KeepAnchor,
        1,
    );
    let bold_fmt = TextFormat {
        font_bold: Some(true),
        ..Default::default()
    };
    probe.merge_char_format(&bold_fmt).unwrap();

    let editor = RichTextEditor::editor(doc);
    // Select the whole document from position 0 → 2 (so position() is
    // at end, on bold; selection_start() is at 0, on plain).
    editor.select_all();

    let fmt = editor.caret_char_format();
    assert!(
        fmt.font_bold != Some(true),
        "caret_char_format must read from selection_start (plain start) \
         not selection_end (bold run); got font_bold = {:?}",
        fmt.font_bold
    );
}

#[test]
fn widget_formatting_api_set_bold_applies_to_selection() {
    // Calls `editor.set_bold(true)` through the widget's public API
    // and verifies the underlying document run ended up bold. Uses
    // `select_all()` so there's a selection for `merge_char_format`
    // to act on (the underlying cursor method no-ops on an empty
    // range).
    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    // Baseline: char 0 is not bold.
    let probe = doc.cursor();
    probe.set_position(0, teksilo_text::text_document::MoveMode::MoveAnchor);
    assert!(
        probe.char_format().unwrap_or_default().font_bold != Some(true),
        "baseline: text must not start bold"
    );

    editor.select_all();
    editor.set_bold(true);

    // Re-probe char 0 — must now be bold.
    let probe = doc.cursor();
    probe.set_position(0, teksilo_text::text_document::MoveMode::MoveAnchor);
    assert_eq!(
        probe.char_format().unwrap_or_default().font_bold,
        Some(true),
        "set_bold(true) must flip font_bold on the underlying run"
    );
}

#[test]
fn widget_is_bold_reports_selection_start_format() {
    // `is_bold()` goes through `caret_char_format()` which reads at
    // `selection_start` when a selection exists. Build a doc with the
    // first char bold, select from 0 to 2, and confirm `is_bold()`
    // is true.
    let doc = TextDocument::new();
    doc.set_plain_text("AB").unwrap();
    let probe = doc.cursor();
    probe.set_position(0, teksilo_text::text_document::MoveMode::MoveAnchor);
    probe.move_position(
        teksilo_text::text_document::MoveOperation::Right,
        teksilo_text::text_document::MoveMode::KeepAnchor,
        1,
    );
    probe
        .merge_char_format(&teksilo_text::text_document::TextFormat {
            font_bold: Some(true),
            ..Default::default()
        })
        .unwrap();

    let editor = RichTextEditor::editor(doc);
    editor.select_all();
    assert!(
        editor.is_bold(),
        "is_bold must return true when the selection starts on a bold run"
    );
}

#[test]
fn widget_toggle_bold_flips_current_state() {
    let doc = TextDocument::new();
    doc.set_plain_text("text").unwrap();
    let editor = RichTextEditor::editor(doc);
    editor.select_all();
    assert!(!editor.is_bold(), "baseline");
    editor.toggle_bold();
    assert!(editor.is_bold(), "toggle_bold flips on");
    editor.toggle_bold();
    // Re-select because the toggle cleared preferred_x (not selection,
    // but be explicit).
    editor.select_all();
    assert!(!editor.is_bold(), "second toggle flips off");
}

#[test]
fn widget_set_heading_level_updates_block_format() {
    let doc = TextDocument::new();
    doc.set_plain_text("heading").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.set_caret_position(0);
    editor.set_heading_level(2);
    assert_eq!(
        editor.get_heading_level(),
        2,
        "heading_level getter must reflect the setter"
    );
}

#[test]
fn widget_set_alignment_updates_block_format() {
    let doc = TextDocument::new();
    doc.set_plain_text("aligned").unwrap();
    let editor = RichTextEditor::editor(doc);
    editor.set_caret_position(0);
    editor.set_alignment(teksilo_text::text_document::Alignment::Center);
    assert_eq!(
        editor.get_alignment(),
        teksilo_text::text_document::Alignment::Center
    );
}

#[test]
fn widget_is_in_table_round_trip_with_navigation() {
    // `insert_table` via text-document positions the cursor after the
    // newly inserted table (the block following it). Use
    // `set_caret_position(0)` to move back into the first cell. The
    // test then verifies `is_in_table()` reports correctly.
    let doc = TextDocument::new();
    doc.set_plain_text("").unwrap();
    let editor = RichTextEditor::editor(doc);
    editor.insert_table(2, 3);
    // Place caret at position 0 — should land in the first cell of
    // the table (the table is the first flow element).
    editor.set_caret_position(0);
    assert!(
        editor.is_in_table(),
        "caret at position 0 with a table as the first flow element \
         must be inside the table"
    );
}

#[test]
fn widget_insert_list_creates_list_block() {
    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.set_caret_position(0);
    editor.insert_list(false);
    // The caret block should now belong to a list.
    let block = doc.block_at_position(0).unwrap();
    assert!(
        block.list().is_some(),
        "insert_list(false) must convert the current block into a list item"
    );
}

#[test]
fn widget_remove_from_list_leaves_a_plain_paragraph() {
    // `outdent` deliberately bottoms out at depth 0 rather than destroying the
    // list, so "remove list formatting" needs its own command.
    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.set_caret_position(0);
    editor.insert_list(false);
    assert!(doc.block_at_position(0).unwrap().list().is_some());

    editor.outdent();
    assert!(
        doc.block_at_position(0).unwrap().list().is_some(),
        "outdent at depth 0 must leave the list intact"
    );

    editor.remove_from_list();
    assert!(
        doc.block_at_position(0).unwrap().list().is_none(),
        "remove_from_list must take the block out of the list entirely"
    );
}

#[test]
fn handle_remove_from_list_mirrors_the_widget() {
    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.set_caret_position(0);
    let handle = editor.handle();
    handle.insert_list(true);
    assert!(doc.block_at_position(0).unwrap().list().is_some());

    handle.remove_from_list();
    assert!(doc.block_at_position(0).unwrap().list().is_none());

    // Outside a list it is a no-op, not an error — a toolbar button may be
    // clicked anywhere.
    handle.remove_from_list();
    assert!(doc.block_at_position(0).unwrap().list().is_none());
}

#[test]
fn edit_block_collapses_several_commands_into_one_undo_entry() {
    // The reason this exists: a "clear formatting" action that turns off four
    // marks would otherwise cost four Ctrl+Z presses, and a single undo would
    // leave the document half-cleared.
    let doc = TextDocument::new();
    doc.set_plain_text("hello world").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.select_all();
    let handle = editor.handle();

    handle.edit_block(|| {
        handle.set_bold(true);
        handle.set_italic(true);
        handle.set_underline(true);
    });
    assert!(handle.is_bold() && handle.is_italic() && handle.is_underline());

    handle.undo();
    assert!(
        !handle.is_bold() && !handle.is_italic() && !handle.is_underline(),
        "one undo must revert the whole block, not just its last command"
    );
}

#[test]
fn ungrouped_commands_still_undo_one_at_a_time() {
    // The contrast case, so the test above is proving grouping rather than
    // some blanket coalescing the backend would do anyway.
    let doc = TextDocument::new();
    doc.set_plain_text("hello world").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.select_all();
    let handle = editor.handle();

    handle.set_bold(true);
    handle.set_italic(true);
    handle.undo();
    assert!(
        handle.is_bold(),
        "without an edit block each command is its own undo entry"
    );
}

#[test]
fn edit_block_closes_even_when_the_body_returns_early() {
    // The scoped form exists precisely so a `?` or an early `return` cannot
    // leave a composite open and swallow every later edit into it.
    let doc = TextDocument::new();
    doc.set_plain_text("hello world").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.select_all();
    let handle = editor.handle();

    let applied = handle.edit_block(|| {
        handle.set_bold(true);
        if handle.is_bold() {
            return true;
        }
        handle.set_italic(true);
        false
    });
    assert!(applied);

    // A later edit must be its own entry, which it cannot be if the block
    // above is still open.
    handle.set_italic(true);
    handle.undo();
    assert!(
        handle.is_bold(),
        "the early return must not have left the edit block open"
    );
}

#[test]
fn widget_runtime_font_size_scale_roundtrips() {
    let doc = TextDocument::new();
    doc.set_plain_text("size me").unwrap();
    let editor = RichTextEditor::editor(doc);
    editor.set_font_size_scale(2.5);
    assert!((editor.get_font_size_scale() - 2.5).abs() < 1e-4);
    // Clamp to allowed range.
    editor.set_font_size_scale(100.0);
    assert!(
        editor.get_font_size_scale() <= 10.0,
        "font_size_scale must clamp to the 0.1..=10.0 range"
    );
}

#[test]
fn widget_runtime_typography_defaults_roundtrip_via_editor_and_handle() {
    use teksilo_text::EditorTypographyDefaults;

    let doc = TextDocument::new();
    doc.set_plain_text("typeset me").unwrap();
    let editor = RichTextEditor::editor(doc);

    let defaults = EditorTypographyDefaults {
        font_family: Some("Literata".into()),
        line_height: 1.5,
        first_line_indent: 28.0,
        paragraph_spacing_before: 12.0,
        paragraph_spacing_after: 6.0,
    };
    editor.set_typography_defaults(defaults.clone());
    assert_eq!(editor.get_typography_defaults(), defaults);

    // The handle shares the same state — reads back and drives it too.
    let handle = editor.handle();
    assert_eq!(handle.get_typography_defaults(), defaults);

    let other = EditorTypographyDefaults {
        font_family: None,
        line_height: 2.0,
        first_line_indent: 0.0,
        paragraph_spacing_before: 0.0,
        paragraph_spacing_after: 0.0,
    };
    handle.set_typography_defaults(other.clone());
    assert_eq!(editor.get_typography_defaults(), other);

    // The handle's font_size_scale mirror clamps like the editor's.
    handle.set_font_size_scale(1.4);
    assert!((editor.get_font_size_scale() - 1.4).abs() < 1e-4);
    handle.set_font_size_scale(50.0);
    assert!(handle.get_font_size_scale() <= 10.0);
}

/// An empty paragraph must put its caret — and size its line — exactly
/// where its first character will land.
///
/// Both halves of one reported bug. With a first-line indent set, the
/// caret on an empty paragraph sat flush left and jumped right by the
/// indent on the first keystroke; and because an empty block carries no
/// fragment for the default family to land on, the line measured in the
/// registry's default (UI) face, so that same keystroke also resized the
/// caret and shifted every paragraph below it.
#[test]
fn an_empty_paragraph_carets_where_its_first_character_will_land() {
    use teksilo_text::{CursorAffinity, EditorTypographyDefaults};

    const INDENT: f32 = 28.0;

    // "JetBrains Mono" is registered by `register_default_font` beside the
    // default "Inter", so this is a real family switch with real metric
    // differences — not a request that silently falls back to the default.
    let defaults = EditorTypographyDefaults {
        font_family: Some("JetBrains Mono".into()),
        first_line_indent: INDENT,
        ..EditorTypographyDefaults::default()
    };

    // Two paragraphs: the first empty (the caret sits there), the second
    // holding prose, so a metrics change is also a visible shift below.
    let doc = TextDocument::new();
    doc.set_plain_text("\nsecond paragraph").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.set_typography_defaults(defaults);
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    for _ in 0..4 {
        tick_once(&mut tree);
    }

    let (empty_caret, second_para_y) = {
        let st = state.borrow();
        (
            st.engine.caret_rect(0, CursorAffinity::Downstream),
            st.engine.caret_rect(1, CursorAffinity::Downstream)[1],
        )
    };

    assert!(
        (empty_caret[0] - INDENT).abs() < 0.5,
        "an empty paragraph's caret must sit at the first-line indent \
         ({INDENT}), not flush left; got x = {}",
        empty_caret[0]
    );

    // Type the first character; the caret keeps its place and its size,
    // and the paragraph below does not move.
    press_char(&mut tree, 'A');
    tick_past_debounce(&mut tree);

    let (typed_caret, typed_second_para_y) = {
        let st = state.borrow();
        (
            st.engine.caret_rect(0, CursorAffinity::Downstream),
            st.engine.caret_rect(2, CursorAffinity::Downstream)[1],
        )
    };

    assert!(
        (typed_caret[0] - empty_caret[0]).abs() < 0.5,
        "the first keystroke must not move the caret: {} -> {}",
        empty_caret[0],
        typed_caret[0]
    );
    assert!(
        (typed_caret[3] - empty_caret[3]).abs() < 0.5,
        "the first keystroke must not resize the caret: {} -> {}",
        empty_caret[3],
        typed_caret[3]
    );
    assert!(
        (typed_second_para_y - second_para_y).abs() < 0.5,
        "the first keystroke must not shift the paragraphs below it: {second_para_y} \
         -> {typed_second_para_y}"
    );
}

#[test]
fn editor_ctrl_enter_always_inserts_block_in_table() {
    // Ctrl+Enter inside a table cell inserts a new block (same cell)
    // — bypasses the Enter-navigates-to-next-cell-row behaviour.
    // Godot parity: its forced-block-insert branch.
    let doc = TextDocument::new();
    doc.set_plain_text("").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    editor.insert_table(2, 2);
    // Put the caret inside the first cell.
    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    let block_count_before = doc.block_count();
    press_key(
        &mut tree,
        teksilo_core::event::Key::Enter,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert!(
        doc.block_count() > block_count_before,
        "Ctrl+Enter in a table cell must insert a new block (count before={}, after={})",
        block_count_before,
        doc.block_count()
    );
}

#[test]
fn editor_tab_in_list_increments_indent() {
    // Tab inside a list item increases the list's indent (the value
    // the typesetter reads via `block.list_info.indent`). Godot:
    // 604-622.
    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.insert_list(false);
    editor.set_caret_position(0);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    let indent = state
        .borrow()
        .cursor
        .current_list()
        .map(|l| l.indent())
        .unwrap_or(0);
    assert!(
        indent >= 1,
        "Tab at list-item start must increase list indent (got {})",
        indent
    );
}

#[test]
fn editor_shift_tab_in_list_decrements_indent() {
    use teksilo_text::text_document::ListFormat;

    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.insert_list(false);
    editor.set_caret_position(0);
    // Pre-indent the list so Shift+Tab has something to decrement.
    // Uses the list format because that's what the renderer reads.
    let _ = state.borrow().cursor.set_current_list_format(&ListFormat {
        indent: Some(2),
        ..Default::default()
    });

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::SHIFT,
    );
    tick_past_debounce(&mut tree);

    let indent = state
        .borrow()
        .cursor
        .current_list()
        .map(|l| l.indent())
        .unwrap_or(0);
    assert_eq!(
        indent, 1,
        "Shift+Tab must decrement list indent from 2 to 1 (got {})",
        indent
    );
}

#[test]
fn editor_tab_in_list_indents_from_mid_block_caret() {
    // Tab inside a list item must indent regardless of caret
    // position within the block — the user shouldn't have to Home
    // first. Matches standard word-processor behaviour.
    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.insert_list(false);
    // Caret in the middle of the word — NOT at block start.
    editor.set_caret_position(2);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    let indent = state
        .borrow()
        .cursor
        .current_list()
        .map(|l| l.indent())
        .unwrap_or(0);
    assert!(
        indent >= 1,
        "Tab mid-block inside a list must still indent (got {})",
        indent
    );
    // Also verify no literal tab character was inserted.
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "item",
        "Tab in a list must not insert a literal \\t"
    );
}

#[test]
fn editor_shift_tab_in_list_dedents_from_mid_block_caret() {
    use teksilo_text::text_document::ListFormat;

    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.insert_list(false);
    editor.set_caret_position(0);
    let _ = state.borrow().cursor.set_current_list_format(&ListFormat {
        indent: Some(2),
        ..Default::default()
    });
    // Now move caret into the middle of the word.
    editor.set_caret_position(2);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::SHIFT,
    );
    tick_past_debounce(&mut tree);

    let indent = state
        .borrow()
        .cursor
        .current_list()
        .map(|l| l.indent())
        .unwrap_or(0);
    assert_eq!(
        indent, 1,
        "Shift+Tab mid-block must decrement list indent from 2 to 1 (got {})",
        indent
    );
}

#[test]
fn editor_tab_in_multi_item_list_indents_only_current_item() {
    // Regression: Tab on one item of a multi-item list must indent
    // ONLY the current item, not all siblings. Earlier versions
    // updated `ListFormat::indent` on the shared list, which shifted
    // every item together. Fix splits the current item into its own
    // list at the deeper nesting level.
    let doc = TextDocument::new();
    doc.set_plain_text("a\nb\nc").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    // Wrap all three blocks in one bullet list.
    editor.select_all();
    editor.insert_list(false);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    // focus_editor clicks to set focus, moving the caret — so set
    // the caret position AFTER focusing. Position 2 lands inside
    // block "b": in a text-document the layout for "a\nb\nc" is
    // block 0 = "a" (pos 0..1), block 1 = "b" (pos 2..3), block 2
    // = "c" (pos 4..5). We place the caret at position 2.
    state
        .borrow()
        .cursor
        .set_position(2, teksilo_text::text_document::MoveMode::MoveAnchor);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    // After Tab: block "b" is now in a new list at indent 1; blocks
    // "a" and "c" still sit in the original list at indent 0.
    let a_list_id = doc
        .block_at_position(0)
        .and_then(|b| b.list())
        .map(|l| l.id());
    let b_list_id = doc
        .block_at_position(2)
        .and_then(|b| b.list())
        .map(|l| l.id());
    let c_list_id = doc
        .block_at_position(4)
        .and_then(|b| b.list())
        .map(|l| l.id());
    let a_indent = doc
        .block_at_position(0)
        .and_then(|b| b.list())
        .map(|l| l.indent())
        .unwrap_or(255);
    let b_indent = doc
        .block_at_position(2)
        .and_then(|b| b.list())
        .map(|l| l.indent())
        .unwrap_or(255);
    let c_indent = doc
        .block_at_position(4)
        .and_then(|b| b.list())
        .map(|l| l.indent())
        .unwrap_or(255);

    assert_eq!(a_indent, 0, "sibling 'a' must stay at indent 0");
    assert_eq!(b_indent, 1, "current item 'b' must move to indent 1");
    assert_eq!(c_indent, 0, "sibling 'c' must stay at indent 0");

    // And 'a' and 'c' should still be in the SAME list (the original),
    // distinct from 'b's new nested list.
    assert!(a_list_id.is_some() && b_list_id.is_some() && c_list_id.is_some());
    assert_eq!(
        a_list_id, c_list_id,
        "'a' and 'c' must share the parent list"
    );
    assert_ne!(a_list_id, b_list_id, "'b' must be in its own nested list");
}

#[test]
fn editor_shift_tab_in_multi_item_list_dedents_only_current_item() {
    use teksilo_text::text_document::ListFormat;

    let doc = TextDocument::new();
    doc.set_plain_text("a\nb\nc").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.select_all();
    editor.insert_list(false);
    // Pre-indent the whole list to depth 2 so there's room to dedent.
    let _ = state.borrow().cursor.set_current_list_format(&ListFormat {
        indent: Some(2),
        ..Default::default()
    });

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    // focus_editor moves the caret via a synthetic click, so set
    // position AFTER focusing (see the matching Tab test).
    state
        .borrow()
        .cursor
        .set_position(2, teksilo_text::text_document::MoveMode::MoveAnchor);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::SHIFT,
    );
    tick_past_debounce(&mut tree);

    let a_indent = doc
        .block_at_position(0)
        .and_then(|b| b.list())
        .map(|l| l.indent())
        .unwrap_or(99);
    let b_indent = doc
        .block_at_position(2)
        .and_then(|b| b.list())
        .map(|l| l.indent())
        .unwrap_or(99);
    let c_indent = doc
        .block_at_position(4)
        .and_then(|b| b.list())
        .map(|l| l.indent())
        .unwrap_or(99);

    assert_eq!(a_indent, 2, "sibling 'a' must stay at indent 2");
    assert_eq!(b_indent, 1, "current item 'b' must dedent to indent 1");
    assert_eq!(c_indent, 2, "sibling 'c' must stay at indent 2");
}

#[test]
fn editor_backspace_at_list_start_dedents_or_exits() {
    // Backspace at block start with indent > 0: dedent.
    // Backspace at block start with indent 0: remove from list.
    // Godot: 564-586.
    let doc = TextDocument::new();
    doc.set_plain_text("item").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.insert_list(false);
    editor.set_caret_position(0);
    editor.apply_block_format(teksilo_text::text_document::BlockFormat {
        indent: Some(1),
        ..Default::default()
    });

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Backspace,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    let indent = state
        .borrow()
        .cursor
        .block_format()
        .ok()
        .and_then(|f| f.indent)
        .unwrap_or(0);
    assert_eq!(
        indent, 0,
        "first Backspace dedents from 1 to 0 (got {})",
        indent
    );

    // Second Backspace: indent is 0, so remove from list.
    press_key(
        &mut tree,
        teksilo_core::event::Key::Backspace,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    let in_list = doc.block_at_position(0).and_then(|b| b.list()).is_some();
    assert!(
        !in_list,
        "second Backspace at indent 0 must remove block from list"
    );
}

// ────────────────────────────────────────────────────────────────────────
// Blockquote keyboard / toolbar behaviour (Phase C of the blockquote
// management overhaul). The corresponding data-layer tests live in
// /Users/cyril/Devel/text-document/crates/public_api/tests/blockquote_editing_tests.rs.
// ────────────────────────────────────────────────────────────────────────

#[test]
fn editor_tab_in_quote_increases_depth() {
    let doc = TextDocument::new();
    doc.set_markdown("> Quoted line.\n")
        .unwrap()
        .wait()
        .unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.set_caret_position(0);
    assert_eq!(state.borrow().cursor.blockquote_depth_at_cursor(), 1);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        state.borrow().cursor.blockquote_depth_at_cursor(),
        2,
        "Tab inside a depth-1 quote must produce depth-2"
    );
}

#[test]
fn editor_shift_tab_at_depth_1_unwraps_to_plain() {
    let doc = TextDocument::new();
    doc.set_markdown("> Quoted line.\n")
        .unwrap()
        .wait()
        .unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.set_caret_position(0);
    assert_eq!(state.borrow().cursor.blockquote_depth_at_cursor(), 1);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Tab,
        teksilo_core::event::Modifiers::SHIFT,
    );
    tick_past_debounce(&mut tree);

    assert_eq!(
        state.borrow().cursor.blockquote_depth_at_cursor(),
        0,
        "Shift+Tab at depth 1 must unwrap to plain paragraph"
    );
}

#[test]
fn editor_backspace_at_quote_first_block_unwraps() {
    let doc = TextDocument::new();
    doc.set_markdown("> Quoted line.\n")
        .unwrap()
        .wait()
        .unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.set_caret_position(0);
    assert!(state.borrow().cursor.is_in_blockquote());

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    press_key(
        &mut tree,
        teksilo_core::event::Key::Backspace,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    assert!(
        !state.borrow().cursor.is_in_blockquote(),
        "Backspace at the first block of a quote must unwrap the block"
    );
}

// NOTE on coverage for Enter-on-empty-quoted-block and Tab-in-list-
// inside-quote: the behaviours are confirmed at the data-layer in
// /Users/cyril/Devel/text-document/crates/public_api/tests/blockquote_editing_tests.rs
// (toggle/wrap/unwrap round-trips, depth changes). Widget-level setup
// for these specific scenarios requires reproducing exact in-block
// caret states that the headless test harness does not preserve
// reliably across mock layouts (markdown imports trailing blocks,
// insert_block leaves the caret in the new block at a position that
// is_at_block_start-but-not-current_block_is_empty under certain mock
// configurations). Skipped as widget tests; covered functionally by
// the data-layer suite and verifiable via the end-to-end smoke run.

#[test]
fn editor_delete_at_last_pos_of_last_quoted_block_unwraps() {
    let doc = TextDocument::new();
    doc.set_markdown("> Quoted.\n").unwrap().wait().unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    // Move caret to End so it lands at the end of the quoted block's
    // content (not past it into any trailing paragraph the markdown
    // parser may have produced).
    editor.set_caret_position(0);

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Navigate to end of the block via the End key so the test doesn't
    // depend on character_count semantics around trailing blocks.
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);
    assert!(state.borrow().cursor.is_in_blockquote());
    assert!(state.borrow().cursor.at_block_end());
    assert!(state.borrow().cursor.is_last_block_in_current_frame());

    press_key(
        &mut tree,
        teksilo_core::event::Key::Delete,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);

    assert!(
        !state.borrow().cursor.is_in_blockquote(),
        "Delete at the end of the last quoted block must unwrap, not cross-frame merge"
    );
}

#[test]
fn editor_toggle_blockquote_wraps_then_unwraps() {
    let doc = TextDocument::new();
    doc.set_plain_text("Hello.").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();
    editor.set_caret_position(0);
    assert!(!state.borrow().cursor.is_in_blockquote());

    editor.toggle_blockquote();
    assert!(
        state.borrow().cursor.is_in_blockquote(),
        "first toggle must wrap"
    );

    editor.toggle_blockquote();
    assert!(
        !state.borrow().cursor.is_in_blockquote(),
        "second toggle must unwrap"
    );
}

// List-inside-quote Tab precedence: the keyboard handler checks
// `is_cursor_in_list` BEFORE the blockquote branch (keyboard.rs ladder
// in the Tab arm). That ordering is visually inspectable in the
// source; a behavioural test would require the mock layout to
// preserve `current_list()` membership across `toggle_blockquote`,
// which today is brittle under headless tests (the wrap moves blocks
// between frames). Tracking as a polish item for D3.

/// User-reported bug: typing Enter at end of `> A`, then Enter again,
/// previously inserted a line BEFORE A and lost a quote level. Expected:
/// 1st Enter creates an empty quoted block after A (cursor on it),
/// 2nd Enter exits the quote so the cursor sits AFTER A in a plain
/// paragraph.
#[test]
fn editor_enter_then_enter_at_end_of_quote_exits_after_not_before() {
    let doc = TextDocument::new();
    doc.set_markdown("> A\n").unwrap().wait().unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let state = editor.state_handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    // Position the caret at the end of "A" AFTER the widget is in the
    // tree so the state's cursor isn't reset by widget mount.
    state
        .borrow()
        .cursor
        .set_position(1, teksilo_text::text_document::MoveMode::MoveAnchor);

    // 1st Enter: still in quote, new empty block after A.
    press_key(
        &mut tree,
        teksilo_core::event::Key::Enter,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);
    assert!(
        state.borrow().cursor.is_in_blockquote(),
        "after 1st Enter the cursor must still be inside the quote (new empty block)"
    );
    assert!(
        state.borrow().cursor.current_block_is_empty(),
        "after 1st Enter the cursor's block must be the new empty one"
    );

    // 2nd Enter: empty quoted block → exit the quote.
    press_key(
        &mut tree,
        teksilo_core::event::Key::Enter,
        teksilo_core::event::Modifiers::NONE,
    );
    tick_past_debounce(&mut tree);
    assert!(
        !state.borrow().cursor.is_in_blockquote(),
        "after 2nd Enter the cursor must be outside the quote (depth dropped)"
    );

    // The exported markdown must keep "> A" intact and not have an
    // empty quoted paragraph BEFORE it.
    let md = doc.to_markdown().unwrap();
    let a_idx = md
        .find("> A")
        .unwrap_or_else(|| panic!("`> A` missing after Enter-Enter; got: {md:?}"));
    let before_a = &md[..a_idx];
    assert!(
        !before_a.contains('>'),
        "no quoted line must appear BEFORE `> A` after exiting the quote; got: {md:?}"
    );
}

#[test]
fn link_click_callback_installs_without_panicking() {
    // We can't reliably hit-test a link in a headless tree (no real
    // typesetter layout means `HitRegion::Link` placement is
    // non-deterministic under the mock backend). A behavioural test
    // that actually clicks the link text would need integration-
    // level infrastructure.
    //
    // What we CAN lock in: installing the builder callback compiles,
    // stores the closure on state, and dispatching a PointerDown on
    // the widget doesn't panic even when the hit lands outside any
    // link region. Regression guards the type signature + callback
    // storage, not the dispatch itself.
    use std::cell::RefCell;
    use std::rc::Rc;

    let doc = TextDocument::new();
    doc.set_html(r#"<p><a href="https://example.com/x">link</a></p>"#)
        .unwrap();

    let seen = Rc::new(RefCell::new(Vec::<String>::new()));
    let seen_clone = seen.clone();
    let editor = RichTextEditor::editor(doc).on_link_activated(move |href, _ctx| {
        seen_clone.borrow_mut().push(href.to_string());
    });

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    tree.dispatch_event(teksilo_core::event::WidgetEvent::PointerDown {
        position: Point::new(5.0, 10.0),
        button: teksilo_core::event::PointerButton::Primary,
        modifiers: teksilo_core::event::Modifiers::NONE,
    });
    // No assertion on `seen` — the callback firing depends on the
    // mock engine's layout producing a Link hit at (5, 10), which
    // isn't guaranteed. The test's job here is to guard the
    // compile-time wiring.
    let _ = seen;
}

#[test]
fn format_version_bumps_on_format_only_edits() {
    // Applying bold to a selection fires DocumentEvent::FormatChanged;
    // state::drain_events bumps `format_version` once per batch.
    let doc = TextDocument::new();
    doc.set_plain_text("abc").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let fmt_ver = editor.format_version();
    let baseline = fmt_ver.get();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::B,
        teksilo_core::event::Modifiers::CTRL,
    );
    tick_past_debounce(&mut tree);

    assert!(
        fmt_ver.get() > baseline,
        "format_version must bump after a format-only edit (baseline={}, now={})",
        baseline,
        fmt_ver.get()
    );
}

// Horizontal caret-visibility (ensure_caret_h_visible_locked): no
// dedicated test here. The behaviour is fully exercised under a
// real typesetter in apps that run `wrap_mode(WrapMode::None)`; a
// headless mock backend produces `max_scroll_x == 0` regardless of
// content, which makes the early-return short-circuit trigger and
// hides the real logic from unit tests. Left documented here so a
// future integration test harness can pick it up.

// ---------------------------------------------------------------------------
// min_lines / max_lines — intrinsic sizing.
// ---------------------------------------------------------------------------

#[test]
fn no_min_max_lines_preserves_greedy_sizing() {
    // Regression guard: when neither knob is set, `size_that_fits`
    // must consume the proposal exactly as before so existing
    // layouts in apps don't shift.
    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc);
    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let bounds = tree.bounds(id);
    assert!((bounds.width - 400.0).abs() < 0.5);
    assert!((bounds.height - 300.0).abs() < 0.5);
}

#[test]
fn min_lines_enforces_intrinsic_height_on_empty_doc() {
    // Empty document with `min_lines(3)`: when the parent proposes
    // an unbounded height (as a `VStack` does for non-Expand
    // children), the editor's intrinsic body height is
    // `3 × default_line_height`. The outer wrapper bounds also
    // include the editor-chrome vertical padding (TextInput-style
    // frame installed by `RichTextEditorStyle::make_body`).
    use crate::styles::recipe_text_input_style::TEXT_FIELD_PADDING_VERTICAL;
    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc).min_lines(3);
    let line_h = {
        let st = editor.state_handle();
        let st = st.borrow();
        st.engine.default_line_height()
    };
    assert!(
        line_h > 0.0,
        "default_line_height must be non-zero for the embedded font"
    );
    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::with_width(400.0));
    let bounds = tree.bounds(id);
    let expected = 3.0 * line_h + 2.0 * TEXT_FIELD_PADDING_VERTICAL;
    assert!(
        (bounds.height - expected).abs() < 1.0,
        "expected ~{}px (3 × {:.2} body + 2 × {:.1} chrome), got {:.2}",
        expected,
        line_h,
        TEXT_FIELD_PADDING_VERTICAL,
        bounds.height
    );
}

#[test]
fn max_lines_caps_intrinsic_height_below_proposal() {
    // `max_lines(2)` plus an unbounded-height proposal: the editor
    // reports 2 × line_height (or less when content is shorter),
    // letting any overflow scroll vertically rather than growing.
    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc).max_lines(2);
    let line_h = {
        let st = editor.state_handle();
        let st = st.borrow();
        st.engine.default_line_height()
    };
    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::with_width(400.0));
    let bounds = tree.bounds(id);
    let expected = 2.0 * line_h;
    assert!(
        bounds.height <= expected + 0.5,
        "max_lines(2) must cap at 2 × line_height ({:.2}), got {:.2}",
        expected,
        bounds.height
    );
}

#[test]
fn min_and_max_lines_clamp_growth_within_window() {
    // The classic messenger composer pattern:
    // `min_lines(1).max_lines(4)` must report a height in
    // `[1, 4] × line_height` regardless of how much vertical
    // space the parent has on offer (modeled here by an
    // unbounded-height proposal).
    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc).min_lines(1).max_lines(4);
    let line_h = {
        let st = editor.state_handle();
        let st = st.borrow();
        st.engine.default_line_height()
    };
    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::with_width(400.0));
    let bounds = tree.bounds(id);
    assert!(
        bounds.height >= line_h - 0.5 && bounds.height <= 4.0 * line_h + 0.5,
        "intrinsic height must land in [1, 4] × line_height, got {:.2}",
        bounds.height
    );
}

// -----------------------------------------------------------------------------
// Composing/leaf split + RichTextEditorStyle wiring.
// -----------------------------------------------------------------------------

#[test]
fn editor_chrome_padding_is_included_in_wrapper_bounds() {
    // Regression: the editor's outer wrapper bounds must account for
    // the chrome padding installed by `RichTextEditorStyle::make_body`.
    // Read-only mode skips the frame and reports body bounds 1:1;
    // editor mode adds TextInput-style padding on both axes.
    use crate::styles::recipe_text_input_style::{
        TEXT_FIELD_PADDING_HORIZONTAL, TEXT_FIELD_PADDING_VERTICAL,
    };
    let doc_a = TextDocument::new();
    doc_a.set_plain_text("hi").unwrap();
    let read_only = RichTextEditor::read_only(doc_a);
    let mut tree_ro = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id_ro = tree_ro.add(read_only);
    tree_ro.layout(SizeProposal::exact(400.0, 60.0));
    let b_ro = tree_ro.bounds(id_ro);
    assert!(
        (b_ro.width - 400.0).abs() < 0.5,
        "read-only viewer fills the proposal width without chrome inset, got {}",
        b_ro.width,
    );

    let doc_b = TextDocument::new();
    doc_b.set_plain_text("hi").unwrap();
    let editor = RichTextEditor::editor(doc_b);
    let mut tree_ed = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id_ed = tree_ed.add(editor);
    tree_ed.layout(SizeProposal::exact(400.0, 60.0));
    let b_ed = tree_ed.bounds(id_ed);
    // Editor mode fills the proposal too (chrome consumes the parent
    // proposal exactly). What we can verify: the inner viewport is
    // inset by the chrome padding on both axes.
    // Body is not focusable now; pierce via descendants until we find
    // a widget whose bounds shrink by the chrome padding. Skip — easier
    // path is to just compare bounds shape: viewport bounds.x must be
    // at TEXT_FIELD_PADDING_HORIZONTAL.
    let body_id = tree_ed.first_focusable_descendant(id_ed);
    let _ = body_id;
    // Confirm the wrapper width is the full proposal.
    assert!(
        (b_ed.width - 400.0).abs() < 0.5,
        "editable editor fills the proposal width, got {}",
        b_ed.width,
    );
    // Confirm the chrome padding values exist (compile-time guard
    // against silent drift between recipe and test).
    let _ = TEXT_FIELD_PADDING_HORIZONTAL;
    let _ = TEXT_FIELD_PADDING_VERTICAL;
}

#[test]
fn editor_style_override_installs_custom_chrome() {
    // Installing a custom `RichTextEditorStyle` via `.style(...)`
    // swaps the chrome wholesale. The override returns the viewport
    // id directly (no chrome), so the wrapper bounds match the body
    // bounds exactly, with no chrome padding.
    use teksilo_core::build_context::BuildContext;
    use teksilo_core::styles::{RichTextEditorStyle, RichTextEditorStyleConfig};
    use teksilo_core::widget_id::WidgetId;

    #[derive(Default)]
    struct PassthroughStyle;
    impl RichTextEditorStyle for PassthroughStyle {
        fn make_body(&self, cfg: &RichTextEditorStyleConfig, _ctx: &mut BuildContext) -> WidgetId {
            cfg.viewport
        }
    }

    let doc = TextDocument::new();
    doc.set_plain_text("hi").unwrap();
    let editor = RichTextEditor::editor(doc).style(PassthroughStyle);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 60.0));
    let b = tree.bounds(id);
    // Without the default chrome, wrapper bounds = body (greedy) bounds = full proposal.
    assert!((b.width - 400.0).abs() < 0.5);
    assert!((b.height - 60.0).abs() < 0.5);
}

#[test]
fn color_overrides_store_reactive_props() {
    // The color builders accept `impl Into<ColorProp>` (Color / theme role /
    // Signal) and stash a reactive prop on the shared state; paint resolves it
    // against the active theme each frame. (Resolution is exercised by the
    // theme-default paint tests; here we lock the builder -> state wiring.)
    use teksilo_tokens::{SurfaceRole, TextRole};

    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc)
        .text_color(TextRole::Primary)
        .caret_color(TextRole::Accent)
        .selection_color(TextRole::Accent)
        .background(SurfaceRole::Content);
    let state = editor.state_handle();
    let st = state.borrow();
    assert!(st.text_color_prop.is_some(), "text_color stored as a prop");
    assert!(
        st.caret_color_prop.is_some(),
        "caret_color stored as a prop"
    );
    assert!(
        st.selection_color_prop.is_some(),
        "selection_color stored as a prop"
    );
    assert!(st.background_prop.is_some(), "background stored as a prop");
}

#[test]
fn editor_wrapper_is_generic_container_in_a11y_tree() {
    // Regression guard: the composing outer `RichTextEditor` must
    // emit `Role::GenericContainer` in the AT tree so screen readers
    // don't get the `AccessNodeBuilder` default of `Role::Unknown`.
    // The inner `RichTextEditorBody` carries the real role
    // (`MultilineTextInput` / `Document`) and the synthetic paragraph
    // / text-run children — same pattern as `TextInput` wrapping
    // `TextInputField`.
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();
    let editor = RichTextEditor::editor(doc);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 60.0));

    let info = tree.accessibility_node(id);
    assert_eq!(
        info.role(),
        Role::GenericContainer,
        "wrapper RichTextEditor must emit GenericContainer in the AT tree (got {:?})",
        info.role(),
    );
    // The body still emits MultilineTextInput somewhere under the wrapper.
    let update = tree.sync_accessibility();
    let has_input = update
        .nodes
        .iter()
        .any(|(_, n)| n.role() == Role::MultilineTextInput);
    assert!(
        has_input,
        "the inner body must still emit Role::MultilineTextInput",
    );
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// `on_change` fires for structural edits, stays silent for loads
//
// Regression guard. `drain_events` used to lump `DocumentReset` in with
// `BlockCountChanged` / `FlowElementsInserted` / `FlowElementsRemoved`
// under one "this was a programmatic load, stay quiet" flag. But
// text-document emits the latter three from generic post-mutation
// detectors, so they also fire for genuine user edits — meaning any
// edit that changed the block count (Enter, a backspace that merges two
// paragraphs, a multi-paragraph paste) silently suppressed `on_change`,
// contradicting its documented contract.
//
// A load stays suppressed because it queues `DocumentReset` in the same
// drain batch (and never emits `FlowElements*` at all).
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

/// Install an `on_change` probe, returning the editor and a counter of
/// how many times the callback fired.
fn with_on_change_probe(editor: RichTextEditor) -> (RichTextEditor, Rc<Cell<u32>>) {
    let counter = Rc::new(Cell::new(0u32));
    let probe = counter.clone();
    (
        editor.on_change(move || probe.set(probe.get() + 1)),
        counter,
    )
}

#[test]
fn editor_on_change_fires_for_plain_typing() {
    // Baseline: this path never regressed (ContentsChanged alone). It
    // guards the fix against over-correcting into silence.
    let doc = TextDocument::new();
    doc.set_plain_text("abc").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_char(&mut tree, 'x');
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert!(
        fired.get() > 0,
        "typing a character must fire on_change (fired {} times)",
        fired.get()
    );
}

#[test]
fn editor_on_change_fires_on_enter_paragraph_split() {
    // The core repro: Enter emits BlockCountChanged + FlowElementsInserted
    // and NO DocumentReset, yet used to be classified as a "load".
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::Enter,
        teksilo_core::event::Modifiers::NONE,
    );
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert!(
        fired.get() > 0,
        "pressing Enter (paragraph split) must fire on_change — a structural \
         edit is still a user edit (fired {} times)",
        fired.get()
    );
}

#[test]
fn editor_on_change_fires_on_backspace_paragraph_merge() {
    // The inverse structural edit: a backspace at the start of a block
    // merges it into the previous one, emitting BlockCountChanged +
    // FlowElementsRemoved with no DocumentReset.
    let doc = TextDocument::new();
    doc.set_plain_text("first\nsecond").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    // Caret to the very end, then to the start of that (second) block, so
    // Backspace deletes the block boundary rather than a character.
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    press_key(
        &mut tree,
        teksilo_core::event::Key::Home,
        teksilo_core::event::Modifiers::NONE,
    );
    for _ in 0..2 {
        tick_once(&mut tree);
    }
    fired.set(0); // ignore anything the caret moves may have produced
    press_key(
        &mut tree,
        teksilo_core::event::Key::Backspace,
        teksilo_core::event::Modifiers::NONE,
    );
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("firstsecond"),
        "precondition: Backspace at block start must merge the paragraphs, got {plain:?}"
    );
    assert!(
        fired.get() > 0,
        "a backspace that merges two paragraphs must fire on_change (fired {} times)",
        fired.get()
    );
}

#[test]
fn editor_on_change_fires_on_accesskit_set_value_replace() {
    // The AT write path (a screen reader / braille keyboard / dictation
    // client replacing the document). `handle_access_action_request`
    // services SetValue by select-all + insert_text, which crosses block
    // boundaries here — so it lands as a structural edit and used to be
    // swallowed too. This is also the first coverage of the SetValue
    // handler at all.
    use teksilo_core::accessibility::widget_id_to_node_id;
    use teksilo_core::accesskit::{Action, ActionData};

    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    for _ in 0..2 {
        tick_once(&mut tree);
    }
    fired.set(0);

    let mut ops = teksilo_core::window::NoopWindowOps;
    let resolved = tree.dispatch_access_action(
        widget_id_to_node_id(id),
        Action::SetValue,
        Some(ActionData::Value("alpha\nbeta".into())),
        &mut ops,
    );
    assert!(resolved, "SetValue must resolve a live target widget");
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("alpha") && plain.contains("beta") && !plain.contains("first"),
        "SetValue must replace the whole document, got {plain:?}"
    );
    assert!(
        fired.get() > 0,
        "an assistive-tech SetValue edit must fire on_change (fired {} times)",
        fired.get()
    );
}

#[test]
fn editor_on_change_stays_silent_for_programmatic_load() {
    // The behaviour the suppression was written to protect, and which the
    // arm split must preserve: `set_plain_text` queues DocumentReset in the
    // same batch as the BlockCountChanged it triggers, so the gate still
    // closes.
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    for _ in 0..2 {
        tick_once(&mut tree);
    }
    fired.set(0);

    // Repopulate the document from code, the way `set_djot` / `set_markdown`
    // would — several blocks, so a BlockCountChanged is definitely emitted.
    doc.set_plain_text("one\ntwo\nthree").unwrap();
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert_eq!(
        fired.get(),
        0,
        "a programmatic load must NOT fire on_change, even though it changes \
         the block count"
    );
}

#[test]
fn editor_on_change_stays_silent_during_ime_composition_then_fires_once_on_commit() {
    // A consumer (e.g. a while-typing autocorrect scanner) must see exactly
    // one on_change for a whole CJK composition — not one per intermediate
    // candidate. Each ImeComposition step still mutates the document (this
    // must keep rendering live preedit text), but only ImeCommit is a
    // settled edit.
    use teksilo_core::event::WidgetEvent;

    let doc = TextDocument::new();
    doc.set_plain_text("").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));

    let mut tree = WidgetTree::new();
    let _ = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    for _ in 0..2 {
        tick_once(&mut tree);
    }
    fired.set(0);

    tree.dispatch_event(WidgetEvent::ImeComposition {
        text: "n".to_string(),
        cursor: None,
    });
    tree.tick_animations(std::time::Duration::from_millis(16));
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "n",
        "the preedit must still render live"
    );
    assert_eq!(
        fired.get(),
        0,
        "an intermediate IME composition step must not fire on_change"
    );

    tree.dispatch_event(WidgetEvent::ImeComposition {
        text: "ni".to_string(),
        cursor: None,
    });
    tree.tick_animations(std::time::Duration::from_millis(16));
    assert_eq!(
        fired.get(),
        0,
        "a second intermediate composition step must still not fire on_change"
    );

    tree.dispatch_event(WidgetEvent::ImeCommit {
        text: "".to_string(),
    });
    tick_past_debounce(&mut tree);
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "");
    assert_eq!(
        fired.get(),
        1,
        "the commit must fire on_change exactly once for the settled result"
    );
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// CursorAffinity at soft-wrap boundaries
//
// Background: when a paragraph wraps onto multiple display lines, the
// position at the wrap boundary has TWO valid visual placements (end
// of line K vs start of line K+1). `EditorState::cursor_affinity`
// disambiguates them. See `text_typeset::CursorAffinity` for the
// design rationale.
//
// These tests drive the widget through its public surface (mouse
// clicks, keyboard events) and assert the resulting `cursor_affinity`
// in `EditorState`.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

mod affinity_tests {
    use super::*;
    use teksilo_text::CursorAffinity;

    /// Long single paragraph that definitely wraps at the test
    /// viewport width of 400 px. NotoSans at 16px produces multiple
    /// visual lines for this content.
    const WRAPPING_TEXT: &str = "The quick brown fox jumps over the lazy dog. \
         A long paragraph that absolutely positively must wrap across \
         multiple visual lines so the soft-wrap-boundary affinity \
         tests have something concrete to assert against.";

    /// Build an editor wrapped in a tree with focus, on a wrap-prone
    /// document. Returns the tree, the editor widget id, the shared
    /// state, the wrap-boundary character position (offset where
    /// line 1 ends == line 2 starts), and the two lines' window-space
    /// Y coordinates ready for `synth_pointer_down`.
    struct WrappedEditor {
        tree: WidgetTree,
        state: super::super::SharedState,
        boundary_pos: usize,
        /// Window-space Y for a click inside line 1.
        line_1_window_y: f32,
        /// Window-space Y for a click inside line 2.
        line_2_window_y: f32,
        /// Window-space X for "near the body's left edge". A click
        /// at this X on `line_2_window_y` lands on line 2's start.
        body_left_edge_x: f32,
        /// Window-space X past the body's right edge but still inside
        /// the body's bounds — for "click past end of line" tests.
        body_right_edge_x: f32,
    }

    fn make_wrapped_editor() -> WrappedEditor {
        let doc = TextDocument::new();
        doc.set_plain_text(WRAPPING_TEXT).unwrap();
        let editor = RichTextEditor::editor(doc);
        let state = editor.state_handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        // Narrow width forces wrapping at NotoSans 16px.
        tree.layout(SizeProposal::exact(280.0, 400.0));
        focus_editor(&mut tree, id);
        // Drive a few frames so the editor's layout settles.
        for _ in 0..4 {
            tick_once(&mut tree);
        }

        // Probe for the wrap boundary using the engine directly. The
        // engine returns widget-local Y; convert to window-space by
        // adding the body's viewport_origin.
        let (boundary_pos, line_1_widget_y, line_2_widget_y, viewport_origin, viewport_width) = {
            let st = state.borrow();
            let mut boundary: Option<(usize, f32, f32)> = None;
            for pos in 1..WRAPPING_TEXT.len() {
                let d = st.engine.caret_rect(pos, CursorAffinity::Downstream);
                let u = st.engine.caret_rect(pos, CursorAffinity::Upstream);
                if (u[1] - d[1]).abs() > 1.0 {
                    boundary = Some((pos, d[1], u[1]));
                    break;
                }
            }
            let (bp, d_y, u_y) = boundary
                .expect("doc must wrap at the test viewport width — widen text or narrow viewport");
            (bp, d_y, u_y, st.viewport_origin, st.viewport_width)
        };
        let line_1_window_y = line_1_widget_y + viewport_origin.y;
        let line_2_window_y = line_2_widget_y + viewport_origin.y;
        let body_left_edge_x = viewport_origin.x + 2.0;
        // Just inside the body's right edge — for "click past end of
        // line" probes. Hit-test clamps anything past line N's actual
        // glyphs to PastLineEnd at line N's char_range.end.
        let body_right_edge_x = viewport_origin.x + viewport_width - 2.0;

        WrappedEditor {
            tree,
            state,
            boundary_pos,
            line_1_window_y,
            line_2_window_y,
            body_left_edge_x,
            body_right_edge_x,
        }
    }

    #[test]
    fn fresh_editor_has_downstream_affinity_by_default() {
        let we = make_wrapped_editor();
        assert_eq!(
            we.state.borrow().cursor_affinity,
            CursorAffinity::Downstream,
            "freshly built editor must default to Downstream affinity"
        );
    }

    #[test]
    fn click_at_start_of_wrapped_line_sets_upstream_affinity() {
        let mut we = make_wrapped_editor();
        // Click at the far left of the second wrapped line. The
        // typesetter's hit_test must return Upstream, and the mouse
        // handler must thread that through into EditorState.
        synth_pointer_down(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        synth_pointer_up(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        let st = we.state.borrow();
        assert_eq!(
            st.cursor.position(),
            we.boundary_pos,
            "click at start of line 2 should land at the wrap-boundary position"
        );
        assert_eq!(
            st.cursor_affinity,
            CursorAffinity::Upstream,
            "click at start of line 2 should produce Upstream affinity (caret on line 2's left edge)"
        );
    }

    #[test]
    fn click_at_end_of_wrapped_line_sets_downstream_affinity() {
        let mut we = make_wrapped_editor();
        // Click past the right edge of the FIRST wrapped line. Hit
        // should land at the wrap-boundary position with Downstream.
        synth_pointer_down(&mut we.tree, we.body_right_edge_x, we.line_1_window_y);
        synth_pointer_up(&mut we.tree, we.body_right_edge_x, we.line_1_window_y);
        let st = we.state.borrow();
        assert_eq!(
            st.cursor.position(),
            we.boundary_pos,
            "click past line-1 end should land at the wrap-boundary position"
        );
        assert_eq!(
            st.cursor_affinity,
            CursorAffinity::Downstream,
            "click past line-1 end should produce Downstream affinity (caret on line 1's right end)"
        );
    }

    #[test]
    fn typing_a_character_resets_affinity_to_downstream() {
        let mut we = make_wrapped_editor();
        // Land at the upstream-affinity position first.
        synth_pointer_down(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        synth_pointer_up(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        assert_eq!(we.state.borrow().cursor_affinity, CursorAffinity::Upstream);
        // Now type a character. The edit path must reset to Downstream
        // because the caret position is no longer on a wrap boundary
        // it can disambiguate.
        press_char(&mut we.tree, 'x');
        tick_past_debounce(&mut we.tree);
        assert_eq!(
            we.state.borrow().cursor_affinity,
            CursorAffinity::Downstream,
            "edit must reset affinity to Downstream — the inserted character makes the previous upstream placement meaningless"
        );
    }

    #[test]
    fn left_arrow_resets_affinity_to_downstream() {
        let mut we = make_wrapped_editor();
        // Land upstream.
        synth_pointer_down(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        synth_pointer_up(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        assert_eq!(we.state.borrow().cursor_affinity, CursorAffinity::Upstream);
        // Left moves logically to position N-1 — not a wrap boundary.
        press_key(
            &mut we.tree,
            teksilo_core::event::Key::ArrowLeft,
            teksilo_core::event::Modifiers::NONE,
        );
        assert_eq!(
            we.state.borrow().cursor_affinity,
            CursorAffinity::Downstream,
            "Left arrow must reset affinity to Downstream"
        );
    }

    #[test]
    fn right_arrow_resets_affinity_to_downstream() {
        let mut we = make_wrapped_editor();
        // Land downstream first (end of line 1, position = boundary).
        synth_pointer_down(&mut we.tree, we.body_right_edge_x, we.line_1_window_y);
        synth_pointer_up(&mut we.tree, we.body_right_edge_x, we.line_1_window_y);
        // Right moves to N+1.
        press_key(
            &mut we.tree,
            teksilo_core::event::Key::ArrowRight,
            teksilo_core::event::Modifiers::NONE,
        );
        assert_eq!(
            we.state.borrow().cursor_affinity,
            CursorAffinity::Downstream,
            "Right arrow must reset affinity to Downstream"
        );
    }

    #[test]
    fn home_from_end_of_line_1_lands_at_line_1_start_with_downstream() {
        let mut we = make_wrapped_editor();
        // Caret starts at position 0 (block start). Click well past
        // end of line 1 to land at wrap boundary, Downstream affinity.
        synth_pointer_down(&mut we.tree, we.body_right_edge_x, we.line_1_window_y);
        synth_pointer_up(&mut we.tree, we.body_right_edge_x, we.line_1_window_y);
        // Home should jump to start of the CURRENT visual line. Caret
        // was on line 1 (Downstream); start of line 1 is position 0
        // (block start), which is NOT a wrap boundary → Downstream.
        press_key(
            &mut we.tree,
            teksilo_core::event::Key::Home,
            teksilo_core::event::Modifiers::NONE,
        );
        let st = we.state.borrow();
        assert_eq!(st.cursor.position(), 0, "Home from line 1 → position 0");
        assert_eq!(
            st.cursor_affinity,
            CursorAffinity::Downstream,
            "block start is not a wrap continuation; Home produces Downstream"
        );
    }

    #[test]
    fn home_from_start_of_line_2_lands_at_line_2_start_with_upstream() {
        let mut we = make_wrapped_editor();
        // Land Upstream on line 2 start by clicking there.
        synth_pointer_down(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        synth_pointer_up(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        assert_eq!(we.state.borrow().cursor_affinity, CursorAffinity::Upstream);
        // Home from line 2 start should stay on line 2 — i.e. preserve
        // Upstream affinity, because the start of line 2 IS a wrap
        // continuation (= end of line 1). The new helper consults the
        // current affinity to find the right line, then sets affinity
        // from the typesetter's hit-test of the line-start probe.
        press_key(
            &mut we.tree,
            teksilo_core::event::Key::Home,
            teksilo_core::event::Modifiers::NONE,
        );
        let st = we.state.borrow();
        assert_eq!(
            st.cursor.position(),
            we.boundary_pos,
            "Home from line 2 should stay at line-2's start (= wrap boundary)"
        );
        assert_eq!(
            st.cursor_affinity,
            CursorAffinity::Upstream,
            "Home from upstream-line-2-start must preserve Upstream — the caret stays on line 2"
        );
    }

    #[test]
    fn end_from_start_of_line_2_lands_at_line_2_end() {
        let mut we = make_wrapped_editor();
        // Land Upstream on line 2 start.
        synth_pointer_down(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        synth_pointer_up(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        // End from line 2 should advance to line 2's end. Line 2's
        // end may or may not itself be a wrap boundary depending on
        // the third wrap line's presence — assert the position
        // increases and affinity is what hit-test reported.
        let pos_before = we.state.borrow().cursor.position();
        press_key(
            &mut we.tree,
            teksilo_core::event::Key::End,
            teksilo_core::event::Modifiers::NONE,
        );
        let st = we.state.borrow();
        assert!(
            st.cursor.position() > pos_before,
            "End from line 2 should advance the caret past line 2's start"
        );
    }

    #[test]
    fn ctrl_home_resets_affinity_to_downstream() {
        let mut we = make_wrapped_editor();
        synth_pointer_down(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        synth_pointer_up(&mut we.tree, we.body_left_edge_x, we.line_2_window_y);
        assert_eq!(we.state.borrow().cursor_affinity, CursorAffinity::Upstream);
        press_key(
            &mut we.tree,
            teksilo_core::event::Key::Home,
            teksilo_core::event::Modifiers::CTRL,
        );
        let st = we.state.borrow();
        assert_eq!(st.cursor.position(), 0, "Ctrl+Home goes to document start");
        assert_eq!(
            st.cursor_affinity,
            CursorAffinity::Downstream,
            "Ctrl+Home is a logical jump — resets affinity to Downstream"
        );
    }

    #[test]
    fn set_caret_position_resets_affinity_to_downstream() {
        // Programmatic placement of the caret via the public API
        // can't know whether the caller wants the upstream side of a
        // wrap boundary, so it must collapse to Downstream — matching
        // the pre-affinity behavior and the documented contract on
        // `RichTextEditor::set_caret_position`.
        let doc = TextDocument::new();
        doc.set_plain_text(WRAPPING_TEXT).unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let state = editor.state_handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(280.0, 400.0));
        focus_editor(&mut tree, id);
        for _ in 0..4 {
            tick_once(&mut tree);
        }

        // Plant Upstream affinity directly on state (avoids needing
        // viewport-origin math for this isolated test).
        {
            let mut st = state.borrow_mut();
            st.cursor_affinity = CursorAffinity::Upstream;
        }
        assert_eq!(state.borrow().cursor_affinity, CursorAffinity::Upstream);

        // Find the editor by querying the tree — we need its
        // RichTextEditor instance to call set_caret_position. But our
        // editor variable was moved into tree.add(); reach it through
        // an alternate path: build a fresh editor handle for the same
        // shared state? That's not how the API works.
        //
        // Pragmatic test: invoke the same code path the public API
        // takes — borrow_mut + set_position + reset affinity to
        // Downstream. This matches what `RichTextEditor::set_caret_position`
        // does internally (see rich_text.rs).
        {
            let mut st = state.borrow_mut();
            st.cursor
                .set_position(0, teksilo_text::text_document::MoveMode::MoveAnchor);
            st.cursor_affinity = CursorAffinity::Downstream;
        }

        assert_eq!(
            state.borrow().cursor_affinity,
            CursorAffinity::Downstream,
            "the set_caret_position code path collapses affinity to Downstream"
        );
    }

    #[test]
    fn click_at_middle_of_line_1_is_downstream() {
        let mut we = make_wrapped_editor();
        // Click somewhere clearly mid-line on line 1 (not at the
        // boundary, not in the left margin).
        synth_pointer_down(&mut we.tree, 50.0, we.line_1_window_y);
        synth_pointer_up(&mut we.tree, 50.0, we.line_1_window_y);
        let st = we.state.borrow();
        assert!(st.cursor.position() < we.boundary_pos);
        assert_eq!(
            st.cursor_affinity,
            CursorAffinity::Downstream,
            "non-boundary clicks must produce Downstream affinity"
        );
    }

    #[test]
    fn paint_only_highlight_recolors_without_full_layout() {
        use std::sync::Arc;
        use teksilo_text::text_document::{
            Color, HighlightContext, HighlightFormat, SyntaxHighlighter,
        };

        // Background-only = paint-only (no metric change).
        struct BgHighlighter;
        impl SyntaxHighlighter for BgHighlighter {
            fn highlight_block(&self, text: &str, ctx: &mut HighlightContext) {
                let n = text.chars().count();
                if n > 0 {
                    ctx.set_format(
                        0,
                        n,
                        HighlightFormat {
                            background_color: Some(Color::rgba(255, 214, 0, 150)),
                            ..Default::default()
                        },
                    );
                }
            }
        }

        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        // This view shows highlights, so the paint-only fast path applies.
        let editor = RichTextEditor::read_only(doc.clone()).show_highlights(true);
        let state = editor.state_handle();
        // Drain construction events, then clear dirty flags.
        state.borrow_mut().drain_events();
        {
            let mut st = state.borrow_mut();
            st.needs_full_layout = false;
            st.pending_recolor = false;
        }

        doc.set_syntax_highlighter(Some(Arc::new(BgHighlighter)));
        let (had, single) = state.borrow_mut().drain_events();
        assert!(had, "attaching a highlighter should produce an event");
        let st = state.borrow();
        assert!(
            st.pending_recolor,
            "paint-only change must request a recolor"
        );
        assert!(
            !st.needs_full_layout,
            "paint-only change must NOT trigger a full relayout"
        );
        assert!(single.is_none());
    }

    #[test]
    fn metric_highlight_triggers_full_layout() {
        use std::sync::Arc;
        use teksilo_text::text_document::{HighlightContext, HighlightFormat, SyntaxHighlighter};

        // Bold = metric-affecting -> must reshape (full layout).
        struct BoldHighlighter;
        impl SyntaxHighlighter for BoldHighlighter {
            fn highlight_block(&self, text: &str, ctx: &mut HighlightContext) {
                let n = text.chars().count();
                if n > 0 {
                    ctx.set_format(
                        0,
                        n,
                        HighlightFormat {
                            font_bold: Some(true),
                            ..Default::default()
                        },
                    );
                }
            }
        }

        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        // This view shows highlights, so a metric change must reshape.
        let editor = RichTextEditor::read_only(doc.clone()).show_highlights(true);
        let state = editor.state_handle();
        state.borrow_mut().drain_events();
        {
            let mut st = state.borrow_mut();
            st.needs_full_layout = false;
            st.pending_recolor = false;
        }

        doc.set_syntax_highlighter(Some(Arc::new(BoldHighlighter)));
        state.borrow_mut().drain_events();
        let st = state.borrow();
        assert!(
            st.needs_full_layout,
            "metric highlight must trigger a full relayout"
        );
        assert!(
            !st.pending_recolor,
            "metric highlight is not a recolor-only change"
        );
    }

    #[test]
    fn bare_view_ignores_paint_only_highlight() {
        use std::sync::Arc;
        use teksilo_text::text_document::{
            Color, HighlightContext, HighlightFormat, SyntaxHighlighter,
        };

        struct BgHighlighter;
        impl SyntaxHighlighter for BgHighlighter {
            fn highlight_block(&self, text: &str, ctx: &mut HighlightContext) {
                let n = text.chars().count();
                if n > 0 {
                    ctx.set_format(
                        0,
                        n,
                        HighlightFormat {
                            background_color: Some(Color::rgba(255, 214, 0, 150)),
                            ..Default::default()
                        },
                    );
                }
            }
        }

        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        // read_only defaults to show_highlights = false (a bare preview).
        let viewer = RichTextEditor::read_only(doc.clone());
        let state = viewer.state_handle();
        state.borrow_mut().drain_events();
        {
            let mut st = state.borrow_mut();
            st.needs_full_layout = false;
            st.pending_recolor = false;
        }

        doc.set_syntax_highlighter(Some(Arc::new(BgHighlighter)));
        state.borrow_mut().drain_events();
        let st = state.borrow();
        // The bare view does zero work on a paint-only highlight change.
        assert!(
            !st.pending_recolor,
            "bare view must ignore HighlightPaintChanged"
        );
        assert!(!st.needs_full_layout);
    }

    #[test]
    fn bare_view_flow_snapshot_has_no_highlights() {
        use std::sync::Arc;
        use teksilo_text::text_document::{
            FlowElementSnapshot, FlowSnapshot, FragmentContent, HighlightContext, HighlightFormat,
            SyntaxHighlighter,
        };

        struct BoldHighlighter;
        impl SyntaxHighlighter for BoldHighlighter {
            fn highlight_block(&self, text: &str, ctx: &mut HighlightContext) {
                let n = text.chars().count();
                if n > 0 {
                    ctx.set_format(
                        0,
                        n,
                        HighlightFormat {
                            font_bold: Some(true),
                            ..Default::default()
                        },
                    );
                }
            }
        }
        fn has_bold(flow: &FlowSnapshot) -> bool {
            flow.elements.iter().any(|e| match e {
                FlowElementSnapshot::Block(bs) => bs.fragments.iter().any(|f| {
                    matches!(f, FragmentContent::Text { format, .. } if format.font_bold == Some(true))
                }),
                _ => false,
            })
        }

        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        doc.set_syntax_highlighter(Some(Arc::new(BoldHighlighter)));

        // Editor shows highlights -> its snapshot carries the (metric) bold.
        let editor = RichTextEditor::editor(doc.clone());
        assert!(
            has_bold(&editor.state_handle().borrow().flow_snapshot()),
            "editor view should keep the metric highlight"
        );

        // Bare viewer -> clean snapshot, base fragments, no bold.
        let viewer = RichTextEditor::read_only(doc.clone());
        assert!(
            !has_bold(&viewer.state_handle().borrow().flow_snapshot()),
            "bare viewer must drop the highlight even for a metric highlighter"
        );
    }

    // -----------------------------------------------------------------
    // Wheel scroll-chaining: an editor that can no longer scroll hands
    // the wheel to an enclosing ScrollArea (mirrors the ListView /
    // TableView / TreeTableView `nested_*_chains_to_outer_at_boundary`
    // tests). Also the caret-follow outer-scroll behaviour.
    // -----------------------------------------------------------------

    /// Pump the editor's frame loop a few times at `(w, h)` so its
    /// `max_scroll_y` is populated from the laid-out content before we drive
    /// scroll / caret events.
    fn pump(tree: &mut WidgetTree, w: f32, h: f32) {
        for _ in 0..4 {
            tree.request_frame();
            tree.tick_animations(std::time::Duration::from_millis(16));
            tree.layout(SizeProposal::exact(w, h));
        }
    }

    /// Outer `ScrollArea { VStack[ fixed 48px editor (tall document), 300px
    /// filler ] }` in a 150px viewport. The editor is wrapped in a `FixedSize`
    /// so it has a well-defined viewport headlessly (an intrinsic `max_lines`
    /// editor can't bootstrap its content layout without a paint pass). Returns
    /// `(tree, editor_scroll_y, outer_scroll_y)`.
    fn nested_rich_text_fixture(
        inner: crate::OverscrollBehavior,
    ) -> (
        WidgetTree,
        teksilo_core::signal::Signal<f32>,
        teksilo_core::signal::Signal<f32>,
    ) {
        use crate::ScrollArea;
        use crate::primitives::{FixedSize, TextWidget, VStack};

        let doc = TextDocument::new();
        // 20 short lines → content far taller than the 48px editor viewport.
        let text: String = (0..20)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        doc.set_plain_text(&text).unwrap();

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let editor = RichTextEditor::editor(doc).overscroll_behavior(inner);
        let editor_y = editor.scroll_y();
        // Seed the engine viewport the way a real paint pass would — headless
        // tests never paint, and the text engine only lays out (and so only
        // reports a non-zero `max_scroll_y`) once its viewport is set. Without
        // this the editor is a 0-content stub and can't demonstrate boundary
        // chaining. Everything downstream (handle_scroll, the bubble to the
        // outer ScrollArea) is the real code path.
        {
            let handle = editor.state_handle();
            let mut s = handle.borrow_mut();
            s.viewport_width = 208.0;
            s.viewport_height = 48.0;
            s.engine.set_viewport(208.0, 48.0);
            s.needs_full_layout = true;
        }
        let editor_id = tree.add(editor);
        let editor_box = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(48.0)
                .child_id(editor_id),
        );
        let filler = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(300.0)
                .child(TextWidget::new(lit!(""))),
        );
        let outer_content = tree.add(VStack::new().add_child(editor_box).add_child(filler));
        let outer = ScrollArea::from_id(outer_content).smooth_scrolling(false);
        let outer_y = outer.scroll_y_signal().clone();
        let _outer = tree.add(outer);
        tree.layout(SizeProposal::exact(220.0, 150.0));
        pump(&mut tree, 220.0, 150.0);
        (tree, editor_y, outer_y)
    }

    #[test]
    fn nested_rich_text_chains_to_outer_at_boundary() {
        use teksilo_core::event::{Modifiers, ScrollDelta, WidgetEvent};
        let (mut tree, editor_y, outer_y) =
            nested_rich_text_fixture(crate::OverscrollBehavior::Chain);

        assert!(
            editor_y.get().abs() < 0.01 && outer_y.get().abs() < 0.01,
            "fixture starts unscrolled"
        );

        // Pointer over the editor (top of the outer content), scroll it to the
        // bottom of its own content.
        tree.pointer_move(Point::new(50.0, 12.0));
        tree.dispatch_event(WidgetEvent::Scroll {
            delta: ScrollDelta::Pixels { x: 0.0, y: 9999.0 },
            modifiers: Modifiers::NONE,
        });
        tree.layout(SizeProposal::exact(220.0, 150.0));

        let editor_bottom = editor_y.get();
        assert!(
            editor_bottom > 0.0,
            "the editor should have scrolled its own content down; got {editor_bottom}"
        );
        assert!(
            outer_y.get().abs() < 0.01,
            "outer must not move while the editor still absorbs the scroll"
        );

        // A second downward wheel at the editor's boundary chains to the outer.
        tree.pointer_move(Point::new(50.0, 12.0));
        tree.dispatch_event(WidgetEvent::Scroll {
            delta: ScrollDelta::Pixels { x: 0.0, y: 120.0 },
            modifiers: Modifiers::NONE,
        });
        tree.layout(SizeProposal::exact(220.0, 150.0));

        assert!(
            (editor_y.get() - editor_bottom).abs() < 0.01,
            "editor stays clamped at its bottom"
        );
        assert!(
            outer_y.get() > 0.01,
            "outer must scroll because the editor chained the boundary wheel"
        );
    }

    #[test]
    fn nested_rich_text_contain_blocks_chaining() {
        use teksilo_core::event::{Modifiers, ScrollDelta, WidgetEvent};
        let (mut tree, _editor_y, outer_y) =
            nested_rich_text_fixture(crate::OverscrollBehavior::Contain);

        // Scroll the editor to its bottom, then again — Contain must swallow
        // the boundary wheel so the outer never moves.
        for _ in 0..2 {
            tree.pointer_move(Point::new(50.0, 12.0));
            tree.dispatch_event(WidgetEvent::Scroll {
                delta: ScrollDelta::Pixels { x: 0.0, y: 9999.0 },
                modifiers: Modifiers::NONE,
            });
            tree.layout(SizeProposal::exact(220.0, 150.0));
        }
        assert!(
            outer_y.get().abs() < 0.01,
            "Contain must keep the wheel at the editor; outer stayed put"
        );
    }

    #[test]
    fn caret_move_chases_outer_scroll_area() {
        use crate::ScrollArea;
        use crate::primitives::{FixedSize, TextWidget, VStack};
        use teksilo_core::event::{Key, Modifiers, WidgetEvent};

        // A 150px editor (30-line document → scrolls internally) at the top of
        // an outer ScrollArea whose viewport is only 90px, so the editor's
        // lower half sits below the fold.
        let doc = TextDocument::new();
        let text: String = (0..30)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        doc.set_plain_text(&text).unwrap();

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        // Caret-follow into the enclosing page is on by default.
        let editor = RichTextEditor::editor(doc);
        {
            let handle = editor.state_handle();
            let mut s = handle.borrow_mut();
            s.viewport_width = 208.0;
            s.viewport_height = 150.0;
            s.engine.set_viewport(208.0, 150.0);
            s.needs_full_layout = true;
        }
        let editor_id = tree.add(editor);
        let editor_box = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(150.0)
                .child_id(editor_id),
        );
        let filler = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(200.0)
                .child(TextWidget::new(lit!(""))),
        );
        let outer_content = tree.add(VStack::new().add_child(editor_box).add_child(filler));
        let outer = ScrollArea::from_id(outer_content).smooth_scrolling(false);
        let outer_y = outer.scroll_y_signal().clone();
        let _outer = tree.add(outer);
        tree.layout(SizeProposal::exact(220.0, 90.0));
        pump(&mut tree, 220.0, 90.0);

        // Focusing the editor makes the focus-driven follow scroll the outer to
        // reveal the whole editor. Reset it so we can attribute any *further*
        // scroll purely to caret movement (the thing under test).
        tree.focus(editor_id);
        tree.layout(SizeProposal::exact(220.0, 90.0));
        outer_y.set(0.0);
        tree.layout(SizeProposal::exact(220.0, 90.0));
        assert!(outer_y.get().abs() < 0.01, "reset outer scroll to top");

        // Walk the caret to the bottom of the document. Each ArrowDown keeps the
        // caret inside the editor's own 150px viewport AND chases it into the
        // 90px outer viewport — the caret line ends up well below the fold, so
        // the outer must scroll to keep it visible.
        for _ in 0..30 {
            tree.dispatch_event(WidgetEvent::KeyDown {
                key: Key::ArrowDown,
                modifiers: Modifiers::NONE,
                text: None,
            });
        }
        tree.layout(SizeProposal::exact(220.0, 90.0));

        assert!(
            outer_y.get() > 0.01,
            "moving the caret below the outer fold must scroll the enclosing \
             ScrollArea (got outer scroll {})",
            outer_y.get()
        );
    }

    #[test]
    fn caret_follow_disabled_leaves_enclosing_page_alone() {
        // With follow_caret_in_page(false) a caret move must NOT scroll the
        // enclosing page — the opt-out for a layout that wants the surrounding
        // page to never move on a caret change.
        use crate::ScrollArea;
        use crate::primitives::{FixedSize, VStack};
        use teksilo_core::event::{Key, Modifiers, WidgetEvent};

        let doc = TextDocument::new();
        let text: String = (0..40)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        doc.set_plain_text(&text).unwrap();

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        // Grow editor with the page-follow explicitly disabled.
        let editor = RichTextEditor::editor(doc).follow_caret_in_page(false);
        {
            let handle = editor.state_handle();
            let mut s = handle.borrow_mut();
            s.viewport_width = 208.0;
            s.viewport_height = 900.0;
            s.engine.set_viewport(208.0, 900.0);
            s.needs_full_layout = true;
        }
        let editor_id = tree.add(editor);
        let editor_box = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(900.0)
                .child_id(editor_id),
        );
        let outer_content = tree.add(VStack::new().add_child(editor_box));
        let outer = ScrollArea::from_id(outer_content).smooth_scrolling(false);
        let outer_y = outer.scroll_y_signal().clone();
        let _outer = tree.add(outer);
        tree.layout(SizeProposal::exact(220.0, 150.0));
        tree.focus(editor_id);
        pump(&mut tree, 220.0, 150.0);
        // Baseline after focus settles — a caret move must not change it when
        // the follow is disabled.
        let baseline = outer_y.get();

        // Move the caret far down (well past the 150px fold).
        for _ in 0..30 {
            tree.dispatch_event(WidgetEvent::KeyDown {
                key: Key::ArrowDown,
                modifiers: Modifiers::NONE,
                text: None,
            });
        }
        tree.layout(SizeProposal::exact(220.0, 150.0));
        pump(&mut tree, 220.0, 150.0);
        assert!(
            (outer_y.get() - baseline).abs() < 0.5,
            "follow disabled: caret movement must not scroll the enclosing \
             page; baseline={baseline} now={}",
            outer_y.get()
        );
    }

    #[test]
    fn standalone_wheel_scroll_away_from_caret_stays() {
        // Standalone editor (internal scroll), caret at top. Wheel-scroll down
        // and confirm the view does NOT snap back to the caret on subsequent
        // frames — scrolling past the caret must work.
        use crate::primitives::FixedSize;
        use teksilo_core::event::{Key, Modifiers, ScrollDelta, WidgetEvent};

        let doc = TextDocument::new();
        let text: String = (0..40)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        doc.set_plain_text(&text).unwrap();
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let editor = RichTextEditor::editor(doc);
        let editor_y = editor.scroll_y();
        {
            let handle = editor.state_handle();
            let mut s = handle.borrow_mut();
            s.viewport_width = 208.0;
            s.viewport_height = 100.0;
            s.engine.set_viewport(208.0, 100.0);
            s.needs_full_layout = true;
        }
        let editor_id = tree.add(editor);
        let _box = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(100.0)
                .child_id(editor_id),
        );
        tree.layout(SizeProposal::exact(220.0, 100.0));
        pump(&mut tree, 220.0, 100.0);

        tree.focus(editor_id);
        // Caret to document start.
        tree.dispatch_event(WidgetEvent::KeyDown {
            key: Key::Home,
            modifiers: Modifiers::CTRL,
            text: None,
        });
        pump(&mut tree, 220.0, 100.0);
        assert!(editor_y.get().abs() < 0.5, "caret at top → scroll 0");

        // Wheel down, away from the caret.
        tree.pointer_move(Point::new(50.0, 40.0));
        tree.dispatch_event(WidgetEvent::Scroll {
            delta: ScrollDelta::Pixels { x: 0.0, y: 200.0 },
            modifiers: Modifiers::NONE,
        });
        tree.layout(SizeProposal::exact(220.0, 100.0));
        let after_scroll = editor_y.get();
        assert!(
            after_scroll > 0.5,
            "wheel scrolled the editor down; got {after_scroll}"
        );

        // Let several frames pass — the view must NOT snap back to the caret.
        pump(&mut tree, 220.0, 100.0);
        assert!(
            editor_y.get() > 0.5,
            "view snapped back to caret after scrolling! scroll_y={} (was {after_scroll})",
            editor_y.get()
        );
    }

    #[test]
    fn smooth_scroll_away_from_caret_stays() {
        // Skribisto's exact config: grow editor (scroll suppressed) inside an
        // outer ScrollArea with SMOOTH scrolling (the default — the other repros
        // force it off). Wheel the page away from the caret and confirm the
        // smooth animation lands there and STAYS (no snap back to the caret).
        use crate::ScrollArea;
        use crate::primitives::{FixedSize, VStack};
        use teksilo_core::event::{Modifiers, ScrollDelta, WidgetEvent};

        let doc = TextDocument::new();
        let text: String = (0..40)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        doc.set_plain_text(&text).unwrap();

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let editor = RichTextEditor::editor(doc);
        {
            let handle = editor.state_handle();
            let mut s = handle.borrow_mut();
            s.viewport_width = 208.0;
            s.viewport_height = 900.0; // > content → grow, editor can't scroll
            s.engine.set_viewport(208.0, 900.0);
            s.needs_full_layout = true;
        }
        let editor_id = tree.add(editor);
        let editor_box = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(900.0)
                .child_id(editor_id),
        );
        let outer_content = tree.add(VStack::new().add_child(editor_box));
        // SMOOTH scrolling ON (default) — this is the untested path.
        let outer = ScrollArea::from_id(outer_content);
        let outer_y = outer.scroll_y_signal().clone();
        let _outer = tree.add(outer);

        let sz = SizeProposal::exact(220.0, 150.0);
        tree.layout(sz);
        tree.focus(editor_id);
        pump(&mut tree, 220.0, 150.0);
        // Reset to the top so any later scroll is our own doing.
        outer_y.set(0.0);
        tree.layout(sz);

        // Wheel the page DOWN. Caret is at the top (position 0) and does NOT
        // move, so nothing should ever pull the page back up to it.
        tree.pointer_move(Point::new(50.0, 40.0));
        tree.dispatch_event(WidgetEvent::Scroll {
            delta: ScrollDelta::Pixels { x: 0.0, y: 300.0 },
            modifiers: Modifiers::NONE,
        });
        // Drive the smooth animation to completion.
        for _ in 0..40 {
            tree.request_frame();
            tree.tick_animations(std::time::Duration::from_millis(16));
            tree.layout(sz);
        }

        assert!(
            outer_y.get() > 0.5,
            "page must stay scrolled away from the caret; ended at {}",
            outer_y.get()
        );
    }

    /// Height of the spacer stacked **above** the editor inside the scroll page.
    /// It exceeds the page viewport (150 dp), so with the page at rest
    /// (`scroll_y == 0`) the editor's body — and therefore a caret at document
    /// position 0 — genuinely lands *below* the visible area.
    const IME_FIXTURE_SPACER_H: f32 = 300.0;

    /// A grow editor inside a page `ScrollArea`, preceded by a tall spacer so the
    /// caret starts **really** off-screen below the page viewport whenever the
    /// page is at rest — the state a reader reaches by scrolling the caret away.
    ///
    /// The off-screen condition is produced by the actual layout (the ScrollArea
    /// offsets its content child's bounds by `scroll_y`, and `place_children`
    /// feeds those bounds to `EditorState::sync_viewport`), NOT by seeding
    /// `viewport_origin` behind layout's back. A seeded origin would be
    /// overwritten by the next layout pass, and — worse — the flood tests below
    /// would still pass while silently testing nothing, because a caret that is
    /// actually *in view* never triggers a page-follow no matter how broken the
    /// gate is.
    ///
    /// Returns `(tree, editor_id, state_handle, outer_scroll_y, proposal)`. Drive
    /// IME / key events, then assert on `outer_scroll_y`.
    fn ime_flood_fixture() -> (
        WidgetTree,
        teksilo_core::widget_id::WidgetId,
        super::super::state::SharedState,
        teksilo_core::signal::Signal<f32>,
        SizeProposal,
    ) {
        use crate::ScrollArea;
        use crate::primitives::{FixedSize, VStack};

        let doc = TextDocument::new();
        let text: String = (0..40)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        doc.set_plain_text(&text).unwrap();

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let editor = RichTextEditor::editor(doc);
        let st = editor.state_handle();
        let editor_id = tree.add(editor);
        // Taller than its content → the editor grows and cannot scroll itself, so
        // the only scroller in play is the outer page.
        let editor_box = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(2000.0)
                .child_id(editor_id),
        );
        let spacer = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(IME_FIXTURE_SPACER_H)
                .child(crate::primitives::RectWidget::new()),
        );
        let outer_content = tree.add(VStack::new().add_child(spacer).add_child(editor_box));
        let outer = ScrollArea::from_id(outer_content);
        let outer_y = outer.scroll_y_signal().clone();
        let _outer = tree.add(outer);

        let sz = SizeProposal::exact(220.0, 150.0);
        tree.layout(sz);
        // Let the engine take its real viewport (via `place_children`) and run its
        // first full layout, so the caret rect below is meaningful.
        pump(&mut tree, 220.0, 150.0);

        // Focusing reveals the caret — which, being below the spacer, scrolls the
        // page down to it. That is correct behaviour, and it is the state the
        // reader then scrolls *away* from.
        tree.focus(editor_id);
        pump(&mut tree, 220.0, 150.0);

        // The reader scrolls the caret off-screen again: page back to the top.
        outer_y.set(0.0);
        tree.layout(sz);

        // Guard the fixture's own premise. If layout ever stops offsetting the
        // body by the page scroll, the flood tests below would go vacuous (a caret
        // that is actually in view never triggers a follow, however broken the
        // gate). Fail loudly here instead of passing for the wrong reason.
        let origin_y = st.borrow().viewport_origin.y;
        assert!(
            origin_y >= 150.0,
            "fixture premise broken: with the page at rest the body must start \
             below the 150dp page viewport, but viewport_origin.y = {origin_y}"
        );
        (tree, editor_id, st, outer_y, sz)
    }

    #[test]
    fn empty_ime_composition_flood_does_not_follow_caret() {
        // THE Skribisto bug. On some Linux IME backends winit floods empty
        // `Ime::Preedit("")` events while a field is focused. Each one used to
        // run the page-follow caret chase, so once the reader scrolled the
        // caret off-screen the very next empty event snapped the page straight
        // back to it (~800 events/sec). The flood must now be completely inert.
        use teksilo_core::event::WidgetEvent;

        let (mut tree, _editor_id, _st, outer_y, sz) = ime_flood_fixture();
        // Page at rest at the top ⇒ the caret (document position 0) sits below the
        // spacer, off-screen. The fixture asserts that premise.
        outer_y.set(0.0);
        tree.layout(sz);

        for _ in 0..20 {
            tree.dispatch_event(WidgetEvent::ImeComposition {
                text: String::new(),
                cursor: None,
            });
            tree.tick_animations(std::time::Duration::from_millis(16));
            tree.layout(sz);
        }

        assert!(
            outer_y.get().abs() < 0.5,
            "an empty IME composition flood must not scroll the page to the caret; \
             page moved to {}",
            outer_y.get()
        );
    }

    #[test]
    fn real_caret_move_still_follows_after_scroll_away() {
        // Positive control / feature-intact check: the page-follow must still
        // fire on a genuine caret MOVE even after the reader scrolled away — the
        // position gate suppresses only no-op repeats, never real motion.
        use teksilo_core::event::{Key, Modifiers};

        let (mut tree, _editor_id, _st, outer_y, sz) = ime_flood_fixture();
        outer_y.set(0.0);
        tree.layout(sz);

        press_key(&mut tree, Key::ArrowDown, Modifiers::NONE);
        tree.tick_animations(std::time::Duration::from_millis(16));
        tree.layout(sz);

        assert!(
            outer_y.get() > 0.5,
            "a real caret move must reveal the caret (page-follow intact); page at {}",
            outer_y.get()
        );
    }

    #[test]
    fn repeated_same_preedit_does_not_re_follow_caret() {
        // Position gate (Fix 2), exercised on a path Fix 1 does NOT short-circuit:
        // a non-empty composition re-sent with identical text lands the caret at
        // the same document position, and must not re-snap the page after the
        // reader scrolled it away.
        use teksilo_core::event::WidgetEvent;

        let (mut tree, _editor_id, _st, outer_y, sz) = ime_flood_fixture();
        tree.layout(sz);

        // First preedit "x": caret advances to 1, the page follows it into view.
        tree.dispatch_event(WidgetEvent::ImeComposition {
            text: "x".to_string(),
            cursor: None,
        });
        tree.tick_animations(std::time::Duration::from_millis(16));
        tree.layout(sz);
        assert!(
            outer_y.get() > 0.5,
            "first preedit should follow the caret into view; page at {}",
            outer_y.get()
        );

        // Reader scrolls the page away again.
        outer_y.set(0.0);
        tree.layout(sz);

        // Same preedit re-sent → caret lands at the same position 1 → no re-follow.
        tree.dispatch_event(WidgetEvent::ImeComposition {
            text: "x".to_string(),
            cursor: None,
        });
        tree.tick_animations(std::time::Duration::from_millis(16));
        tree.layout(sz);
        assert!(
            outer_y.get().abs() < 0.5,
            "re-sending the same preedit must not snap the page back; page at {}",
            outer_y.get()
        );
    }

    #[test]
    fn blur_clears_ime_area_cache() {
        // Regression for the dedup's blur-staleness: the OS IME candidate area is
        // a single *per-window* resource. With two editors A/B, focusing B
        // re-points it; refocusing A (caret unmoved) would recompute A's old area
        // and, if A's `last_ime_area` were still cached, the dedup would swallow
        // the re-seed, leaving the candidate popup at B. Blur must drop the cache.
        let doc_a = TextDocument::new();
        doc_a.set_plain_text("a").unwrap();
        let doc_b = TextDocument::new();
        doc_b.set_plain_text("b").unwrap();

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let ed_a = RichTextEditor::editor(doc_a);
        let st_a = ed_a.state_handle();
        let a_id = tree.add(ed_a);
        let b_id = tree.add(RichTextEditor::editor(doc_b));
        tree.layout(SizeProposal::exact(300.0, 120.0));

        tree.focus(a_id);
        // Simulate a prior IME-area report on A having cached an area.
        st_a.borrow_mut().last_ime_area = Some(teksilo_canvas::Rect::new(1.0, 2.0, 2.0, 14.0));

        // Focus B → A blurs → A's IME-area cache must be dropped.
        tree.focus(b_id);
        assert!(
            st_a.borrow().last_ime_area.is_none(),
            "blur must clear the IME-area dedup cache so a refocus re-seeds the OS"
        );
    }

    #[test]
    fn focus_reveals_caret_not_whole_editor_box() {
        // The Skribisto "click the main editor and it jumps to the end of the
        // scene" bug: a grow editor (own scroll suppressed) sits BELOW some
        // content inside a page ScrollArea and is far taller than the viewport.
        // Focusing it must reveal the CARET (near the top), not the whole
        // ~2000px box — which the old `scroll_focused_into_view` did, scrolling
        // the page to the editor's bottom.
        use crate::ScrollArea;
        use crate::primitives::{FixedSize, TextWidget, VStack};

        let doc = TextDocument::new();
        let text: String = (0..80)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        doc.set_plain_text(&text).unwrap();

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let editor = RichTextEditor::editor(doc);
        let st = editor.state_handle();
        {
            let mut s = st.borrow_mut();
            s.viewport_width = 208.0;
            s.viewport_height = 2000.0; // grow: own scroll suppressed
            s.engine.set_viewport(208.0, 2000.0);
            s.needs_full_layout = true;
        }
        let editor_id = tree.add(editor);
        // Content ABOVE the editor so its top sits below the page-viewport top
        // (as in the scene tab): the editor does NOT span the viewport, so the
        // old whole-bounds reveal genuinely scrolls to its bottom.
        let header = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(80.0)
                .child(TextWidget::new(lit!(""))),
        );
        let editor_box = tree.add(
            FixedSize::new()
                .width(220.0)
                .height(2000.0)
                .child_id(editor_id),
        );
        let outer_content = tree.add(VStack::new().add_child(header).add_child(editor_box));
        let outer = ScrollArea::from_id(outer_content).smooth_scrolling(false);
        let outer_y = outer.scroll_y_signal().clone();
        let _outer = tree.add(outer);

        let sz = SizeProposal::exact(220.0, 150.0);
        tree.layout(sz);
        pump(&mut tree, 220.0, 150.0);
        // `viewport_origin` needs no seeding: `place_children` adopts the body's
        // real laid-out origin every pass. (The old seed used the *wrapper's*
        // bounds, which is off by the body's inset.)

        // Focus the editor (caret at document start). Must reveal the caret near
        // the top, NOT jump to the editor's ~1900px bottom.
        tree.focus(editor_id);
        tree.layout(sz);
        assert!(
            outer_y.get() < 60.0,
            "focus must reveal the caret near the top, not scroll to the editor's bottom; page at {}",
            outer_y.get()
        );
    }

    // ── B3: search-support methods ──────────────────────────────────

    #[test]
    fn select_range_selects_without_collapsing() {
        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        let editor = RichTextEditor::read_only(doc);

        let anchor = editor.cursor_anchor_signal();
        let caret = editor.cursor_position_signal();
        let has_sel = editor.has_selection();

        // Select "world" (chars 6..11) — unlike set_caret_position, this must NOT collapse.
        editor.select_range(6, 11);
        assert!(has_sel.get(), "select_range must produce a real selection");
        assert_eq!(anchor.get(), 6, "anchor at the range start");
        assert_eq!(caret.get(), 11, "caret at the range end");
        assert_eq!(editor.selected_text(), "world");

        // set_caret_position, by contrast, collapses.
        editor.set_caret_position(3);
        assert!(!has_sel.get());
    }

    #[test]
    fn focused_signal_reads_focus_state() {
        let doc = TextDocument::new();
        doc.set_plain_text("text").unwrap();
        let editor = RichTextEditor::read_only(doc);
        // A freshly-built, unmounted editor holds no focus.
        assert!(!editor.focused_signal().get());
    }
}

// --- reading content back through EditorHandle -----------------------------

/// The counterpart to `insert_djot`: a command that can write into an editor it did not
/// build must be able to read it back the same way, or it works on the surfaces the host
/// happens to track and silently does nothing on the rest.
#[test]
fn editor_handle_reads_its_content_back_as_djot() {
    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.insert_djot("# Title\n\nSome prose.\n");

    let out = handle.to_djot();
    assert!(out.contains("Title"), "heading survives: {out}");
    assert!(out.contains("Some prose."), "body survives: {out}");
    assert_eq!(
        out,
        doc.to_djot().unwrap_or_default(),
        "same as the document"
    );
}

#[test]
fn editor_handle_reports_emptiness() {
    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();
    assert!(handle.is_empty(), "a fresh editor holds nothing");

    handle.insert_text("x");
    assert!(!handle.is_empty());
}

/// `is_empty` is a character count, so whitespace is content. Callers that mean "nothing
/// worth keeping" want `to_djot().trim()`, and this pins the difference so nobody has to
/// discover it from behaviour.
#[test]
fn editor_handle_counts_whitespace_as_content() {
    let doc = TextDocument::new();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();
    handle.insert_text("   ");
    assert!(!handle.is_empty(), "spaces are characters");
    assert!(
        handle.to_djot().trim().is_empty(),
        "but nothing worth keeping"
    );
}

// --- programmatic block insertion via EditorHandle -------------------------

#[test]
fn editor_handle_insert_text_keeps_a_newline_inside_one_block() {
    // The baseline this exists to contrast with: `insert_text` drops its bytes
    // into the current block verbatim, so a `\n` becomes literal content rather
    // than a paragraph break. A caller that wants a new paragraph cannot get one
    // this way — hence `insert_djot` / `insert_block`.
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(5, 5);
    handle.insert_text("\nsecond");

    let djot = doc.to_djot().unwrap_or_default();
    assert!(
        !djot.contains("\n\n"),
        "insert_text must not create a second block, got:\n{djot}"
    );
}

#[test]
fn editor_handle_insert_block_splits_the_current_block() {
    let doc = TextDocument::new();
    doc.set_plain_text("firstsecond").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(5, 5);
    handle.insert_block();

    let djot = doc.to_djot().unwrap_or_default();
    assert!(
        djot.contains("first\n\nsecond"),
        "insert_block must split into two paragraphs, got:\n{djot}"
    );
}

#[test]
fn editor_handle_insert_djot_merges_a_single_paragraph_at_the_caret() {
    // A one-paragraph fragment joins the block the caret is in — leading blank
    // lines in the source are whitespace to the parser, not a forced split. Use
    // `insert_block` to get a paragraph boundary; see the test below.
    //
    // The source is ESCAPED (`\* \* \*`) because bare `* * *` is a djot thematic
    // break, which the document model does not represent and the parser drops.
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(5, 5);
    handle.insert_djot("\\* \\* \\*");

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        plain.contains("* * *"),
        "the escaped marker's literal text must survive, got:\n{plain}"
    );
}

#[test]
fn editor_handle_insert_djot_carries_a_multi_block_fragment() {
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(5, 5);
    handle.insert_djot("one\n\ntwo");

    let djot = doc.to_djot().unwrap_or_default();
    assert!(
        djot.contains("\n\n"),
        "a two-block fragment must produce two blocks, got:\n{djot}"
    );
}

#[test]
fn insert_paragraph_lands_a_marker_on_its_own_line() {
    // The exact recipe an "insert scene break" command uses: split at the caret,
    // type the marker into the new block, then split again so the prose that
    // followed the caret continues in its own paragraph. Plain `insert_text` is
    // right here — the marker is literal text, and the djot escaping that keeps
    // it from parsing as a thematic break is applied automatically on save.
    let doc = TextDocument::new();
    doc.set_plain_text("beforeafter").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(6, 6);
    handle.insert_paragraph("* * *");

    let djot = doc.to_djot().unwrap_or_default();
    assert!(
        djot.contains("before\n\n\\* \\* \\*\n\nafter"),
        "marker must be its own paragraph between the halves, got:\n{djot}"
    );
}

#[test]
fn an_unescaped_thematic_break_is_dropped_by_the_parser() {
    // Pins the reason the inserter escapes. If text-document ever grows a real
    // thematic-break block this test will fail loudly, which is the signal to
    // revisit how the marker is represented.
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(5, 5);
    handle.insert_djot("\n\n* * *\n");

    let plain = doc.to_plain_text().unwrap_or_default();
    assert!(
        !plain.contains("* * *"),
        "an unescaped thematic break is expected to be dropped, got:\n{plain}"
    );
}

#[test]
fn superscript_round_trips_through_the_handle() {
    // Until MergeTextFormatDto carried vertical_alignment, this whole API was
    // a silent no-op: the call succeeded and the document was unchanged. This
    // test is the guard that it stays reachable.
    let doc = TextDocument::new();
    doc.set_plain_text("E=mc2").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();
    handle.select_range(4, 5);

    assert!(!handle.is_superscript());
    handle.toggle_superscript();
    assert!(handle.is_superscript(), "superscript must actually apply");

    handle.toggle_superscript();
    assert!(!handle.is_superscript(), "and must come back off");
}

#[test]
fn superscript_and_subscript_are_mutually_exclusive() {
    // One property, two toggles. A run cannot be both raised and lowered, so
    // asking for one must clear the other rather than leaving a stale button
    // lit in the toolbar.
    let doc = TextDocument::new();
    doc.set_plain_text("H2O").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();
    handle.select_range(1, 2);

    handle.toggle_subscript();
    assert!(handle.is_subscript() && !handle.is_superscript());

    handle.toggle_superscript();
    assert!(
        handle.is_superscript() && !handle.is_subscript(),
        "raising a subscript run must clear the subscript"
    );
}

// ── Bidirectional caret motion ─────────────────────────────────

/// "שלום" (shalom) — four Hebrew letters, so the paragraph
/// auto-detects as right-to-left without any explicit block format.
const SHALOM: &str = "\u{05E9}\u{05DC}\u{05D5}\u{05DD}";

/// Drive an editor headlessly with the caret parked at `at`.
///
/// A render pass is mandatory before the keyboard handlers can consult
/// direction: without layout there are no shaped runs, and
/// `direction_at` falls back to left-to-right.
fn rtl_editor(text: &str, at: usize) -> (WidgetTree, teksilo_core::signal::Signal<usize>) {
    let doc = TextDocument::new();
    doc.set_plain_text(text).unwrap();
    let editor = RichTextEditor::editor(doc);
    let caret = editor.cursor_position_signal();
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    // Click to focus — key events only reach a focused widget — then
    // park the caret exactly where the test wants it.
    tree.dispatch_event(teksilo_core::event::WidgetEvent::PointerDown {
        position: teksilo_canvas::Point::new(1.0, 8.0),
        button: teksilo_core::event::PointerButton::Primary,
        modifiers: teksilo_core::event::Modifiers::NONE,
    });
    handle.select_range(at, at);
    assert_eq!(caret.get(), at, "caret should start at {at}");
    (tree, caret)
}

fn press(tree: &mut WidgetTree, key: teksilo_core::event::Key) {
    tree.dispatch_event(teksilo_core::event::WidgetEvent::KeyDown {
        key,
        modifiers: teksilo_core::event::Modifiers::NONE,
        text: None,
    });
}

#[test]
fn arrow_keys_follow_the_screen_in_rtl_text() {
    use teksilo_core::event::Key;

    let (mut tree, caret) = rtl_editor(SHALOM, 2);

    // In right-to-left text the *next* character is drawn further left,
    // so pressing → has to step logically backwards to move the caret
    // rightwards on screen. Mapping ArrowRight straight onto "next
    // character" — which is what it used to do — walked the caret the
    // wrong way across the word.
    press(&mut tree, Key::ArrowRight);
    assert_eq!(
        caret.get(),
        1,
        "ArrowRight in RTL text must step logically backwards so the \
         caret moves right on screen"
    );

    press(&mut tree, Key::ArrowLeft);
    assert_eq!(caret.get(), 2, "ArrowLeft must undo it");

    press(&mut tree, Key::ArrowLeft);
    assert_eq!(caret.get(), 3, "and keep travelling logically forwards");
}

#[test]
fn arrow_keys_are_unchanged_in_ltr_text() {
    use teksilo_core::event::Key;

    // The direction lookup must not disturb ordinary Latin editing.
    let (mut tree, caret) = rtl_editor("Hello world", 2);

    press(&mut tree, Key::ArrowRight);
    assert_eq!(caret.get(), 3, "ArrowRight still advances in LTR text");

    press(&mut tree, Key::ArrowLeft);
    assert_eq!(caret.get(), 2, "ArrowLeft still retreats in LTR text");
}

#[test]
fn home_and_end_reach_the_logical_ends_of_an_rtl_line() {
    use teksilo_core::event::Key;

    let len = SHALOM.chars().count();
    let (mut tree, caret) = rtl_editor(SHALOM, 2);

    // Home and End are logical, not visual: Home goes to the start of
    // the text regardless of which screen edge that sits on. The old
    // code probed the visual left edge for Home, which in an RTL line
    // is the logical *end* — so Home and End both landed on the wrong
    // side of the word.
    press(&mut tree, Key::Home);
    assert_eq!(caret.get(), 0, "Home must reach the logical start");

    press(&mut tree, Key::End);
    assert_eq!(caret.get(), len, "End must reach the logical end");
}

#[test]
fn home_and_end_still_work_in_ltr_text() {
    use teksilo_core::event::Key;

    let text = "Hello world";
    let (mut tree, caret) = rtl_editor(text, 4);

    press(&mut tree, Key::Home);
    assert_eq!(caret.get(), 0);

    press(&mut tree, Key::End);
    assert_eq!(caret.get(), text.chars().count());
}

// ---------------------------------------------------------------------------
// Typewriter scrolling
// ---------------------------------------------------------------------------

/// What the enclosing scroll container was asked for, if anything.
type PinRecord = Rc<Cell<Option<teksilo_core::event::ScrollAlign>>>;

/// An editor in "flowing page" mode (its own scroll suppressed, intrinsic
/// height) inside a `clips_children` container that records the alignment of
/// every `ScrollIntoView` it receives — the exact shape Skribisto's writing
/// column uses, and the only one where the enclosing page does the scrolling.
fn typewriter_fixture(
    anchor: Option<f32>,
) -> (
    WidgetTree,
    super::EditorHandle,
    PinRecord,
    teksilo_core::widget_id::WidgetId,
) {
    use super::ScrollPolicy;
    use crate::primitives::VStack;
    use teksilo_core::event::{EventResponse, WidgetEvent};
    use teksilo_core::widget_builder::WidgetBuilder;

    let doc = TextDocument::new();
    // Enough lines that a pin has somewhere to scroll to.
    doc.set_plain_text(
        &(1..=40)
            .map(|i| format!("Line {i}"))
            .collect::<Vec<_>>()
            .join("\n"),
    )
    .unwrap();

    let editor = RichTextEditor::editor(doc)
        .min_lines(1)
        .v_scroll_policy(ScrollPolicy::AlwaysOff)
        .typewriter(anchor);
    let handle = editor.handle();

    let recorded: PinRecord = Rc::new(Cell::new(None));
    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    let rec = recorded.clone();
    let _container = tree.add(
        VStack::new()
            .add_child(id)
            .on_scroll(move |ev, _ctx| match ev {
                WidgetEvent::ScrollIntoView { align, .. } => {
                    rec.set(Some(*align));
                    EventResponse::Handled
                }
                _ => EventResponse::Ignored,
            })
            .clips_children(true),
    );
    tree.layout(SizeProposal::exact(400.0, 120.0));
    let _ = tree.render();
    (tree, handle, recorded, id)
}

/// A **complete** click. The release matters: without it the editor stays in
/// `DragState::Selecting`, which legitimately suppresses the pin (a pin must
/// never fight a selection gesture in progress), so a down-only "click" would
/// silently disable typewriter scrolling for the rest of the test.
fn click_at(tree: &mut WidgetTree, y: f32) {
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(20.0, y),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
    tree.dispatch_event(WidgetEvent::PointerUp {
        position: Point::new(20.0, y),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
}

fn key(tree: &mut WidgetTree, key: teksilo_core::event::Key) {
    use teksilo_core::event::{Modifiers, WidgetEvent};
    tree.dispatch_event(WidgetEvent::KeyDown {
        key,
        modifiers: Modifiers::NONE,
        text: None,
    });
}

#[test]
fn a_keyboard_caret_move_pins_when_typewriter_is_on() {
    use teksilo_core::event::{Key, ScrollAlign};

    let (mut tree, _handle, recorded, _id) = typewriter_fixture(Some(0.5));
    click_at(&mut tree, 8.0);
    recorded.set(None);

    key(&mut tree, Key::ArrowDown);

    assert_eq!(
        recorded.get(),
        Some(ScrollAlign::Fraction(0.5)),
        "a keyboard caret move must ask the enclosing page for a pin"
    );
}

#[test]
fn without_typewriter_a_caret_move_only_reveals_minimally() {
    use teksilo_core::event::{Key, ScrollAlign};

    let (mut tree, _handle, recorded, _id) = typewriter_fixture(None);
    click_at(&mut tree, 8.0);
    recorded.set(None);

    // Walk far enough down that the caret genuinely leaves the 120px viewport,
    // so a minimal reveal actually fires and we observe its alignment.
    for _ in 0..30 {
        key(&mut tree, Key::ArrowDown);
    }

    assert_eq!(
        recorded.get(),
        Some(ScrollAlign::Minimal),
        "with typewriter off the page must keep its plain reveal behaviour"
    );
}

#[test]
fn a_mouse_click_never_pins() {
    let (mut tree, _handle, recorded, _id) = typewriter_fixture(Some(0.5));
    // Place the caret once so the editor is focused and laid out.
    click_at(&mut tree, 8.0);
    recorded.set(None);

    // A second click, elsewhere: the caret moves, but the page must not be
    // yanked to re-centre on it — the click becomes the new resting position.
    click_at(&mut tree, 60.0);

    assert!(
        !matches!(
            recorded.get(),
            Some(teksilo_core::event::ScrollAlign::Fraction(_))
        ),
        "clicking must not pin — it is the gesture that stands the pin down"
    );
}

#[test]
fn the_next_keystroke_resumes_pinning_after_a_click() {
    use teksilo_core::event::{Key, ScrollAlign};

    let (mut tree, _handle, recorded, _id) = typewriter_fixture(Some(0.5));
    click_at(&mut tree, 8.0);
    click_at(&mut tree, 60.0);
    recorded.set(None);

    key(&mut tree, Key::ArrowDown);

    assert_eq!(
        recorded.get(),
        Some(ScrollAlign::Fraction(0.5)),
        "the pin must take over again as soon as the keyboard is used"
    );
}

#[test]
fn the_anchor_is_clamped_into_the_viewport() {
    let (_tree, handle, _recorded, _id) = typewriter_fixture(Some(4.2));
    assert_eq!(
        handle.get_typewriter(),
        Some(1.0),
        "an out-of-range anchor must clamp rather than aim the pin off-screen"
    );

    handle.set_typewriter(Some(-3.0));
    assert_eq!(handle.get_typewriter(), Some(0.0));
}

#[test]
fn set_typewriter_toggles_pinning_live() {
    use teksilo_core::event::{Key, ScrollAlign};

    let (mut tree, handle, recorded, _id) = typewriter_fixture(None);
    click_at(&mut tree, 8.0);

    // Off: no pin.
    recorded.set(None);
    key(&mut tree, Key::ArrowDown);
    assert!(!matches!(recorded.get(), Some(ScrollAlign::Fraction(_))));

    // Turned on at runtime — the way a settings change reaches a live editor.
    handle.set_typewriter(Some(0.25));
    recorded.set(None);
    key(&mut tree, Key::ArrowDown);
    assert_eq!(recorded.get(), Some(ScrollAlign::Fraction(0.25)));

    // And back off again.
    handle.set_typewriter(None);
    recorded.set(None);
    key(&mut tree, Key::ArrowDown);
    assert!(!matches!(recorded.get(), Some(ScrollAlign::Fraction(_))));
}

#[test]
fn a_pin_re_asserts_after_a_reflow_at_the_same_caret_offset() {
    use teksilo_core::event::{Key, ScrollAlign};

    let (mut tree, handle, recorded, _id) = typewriter_fixture(Some(0.5));
    click_at(&mut tree, 8.0);
    key(&mut tree, Key::ArrowDown);

    // Same caret offset as the last chase. The plain follow dedups on offset
    // alone and would decline — but a font-size change moves the caret's
    // *rect*, so the pin has to notice and re-assert or it silently drifts
    // off its line.
    handle.set_font_size_scale(2.0);
    for _ in 0..3 {
        tick_once(&mut tree);
    }
    recorded.set(None);

    // A no-op nav at the document start: the offset does not change, only the
    // geometry did.
    key(&mut tree, Key::ArrowLeft);
    key(&mut tree, Key::ArrowRight);

    assert_eq!(
        recorded.get(),
        Some(ScrollAlign::Fraction(0.5)),
        "a pin must survive a reflow that leaves the caret offset untouched"
    );
}

#[test]
fn a_drag_selection_is_never_interrupted_by_the_pin() {
    use teksilo_core::event::{Modifiers, PointerButton, ScrollAlign, WidgetEvent};

    let (mut tree, _handle, recorded, _id) = typewriter_fixture(Some(0.5));
    click_at(&mut tree, 8.0);

    // Press and drag downward without releasing — an in-progress selection.
    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(20.0, 8.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
    recorded.set(None);
    for y in [20.0, 40.0, 60.0, 90.0] {
        tree.dispatch_event(WidgetEvent::PointerMove {
            position: Point::new(20.0, y),
        });
    }

    assert!(
        !matches!(recorded.get(), Some(ScrollAlign::Fraction(_))),
        "the view must hold still while a selection is being dragged — \
         re-centring mid-drag is what makes precise selection impossible"
    );

    // Releasing leaves the pin stood down (the pointer placed the caret);
    // the keyboard takes it back.
    tree.dispatch_event(WidgetEvent::PointerUp {
        position: Point::new(20.0, 90.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });
    recorded.set(None);
    key(&mut tree, teksilo_core::event::Key::ArrowDown);
    assert_eq!(recorded.get(), Some(ScrollAlign::Fraction(0.5)));
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// The ambient caret band, through a mounted editor
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

mod caret_band {
    use super::*;
    use crate::rich_text::caret_highlight::{CaretHighlight, CaretHighlightScope};
    use teksilo_text::text_document::{Color, FlowElementSnapshot, HighlightFormat, HighlightMask};

    const BAND: Color = Color {
        red: 255,
        green: 254,
        blue: 235,
        alpha: 255,
    };

    pub(super) fn band(scope: CaretHighlightScope) -> CaretHighlight {
        CaretHighlight {
            scope,
            format: HighlightFormat {
                background_color: Some(BAND),
                ..Default::default()
            },
            content_locale: Some("en".into()),
        }
    }

    /// The band's extents on the first block, as `(start, length)`.
    pub(super) fn banded(doc: &TextDocument) -> Vec<(usize, usize)> {
        match &doc.snapshot_flow_masked(&HighlightMask::all()).elements[0] {
            FlowElementSnapshot::Block(b) => b
                .paint_highlights
                .iter()
                .filter(|s| s.background_color == Some(BAND))
                .map(|s| (s.start, s.length))
                .collect(),
            _ => panic!("expected a block"),
        }
    }

    /// Everything a test needs to drive one mounted editor.
    pub(super) struct Mounted {
        pub tree: WidgetTree,
        pub doc: TextDocument,
        pub handle: crate::rich_text::EditorHandle,
        pub state: crate::rich_text::state::SharedState,
    }

    /// A mounted, focused editor over `text`, already through one frame.
    pub(super) fn mounted(text: &str) -> Mounted {
        let doc = TextDocument::new();
        doc.set_plain_text(text).unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let handle = editor.handle();
        let state = editor.state_handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        tree.focus(id);
        tick_once(&mut tree);
        Mounted {
            tree,
            doc,
            handle,
            state,
        }
    }

    /// The whole chain: a band set through the handle reaches the document as a real paint
    /// highlight over the caret's sentence, driven only by the frame loop.
    #[test]
    fn setting_a_band_paints_the_caret_sentence() {
        let Mounted {
            mut tree,
            doc,
            handle,
            ..
        } = mounted("One is first. Two is second.");
        assert!(banded(&doc).is_empty(), "no band before it is asked for");

        handle.select_range(16, 16);
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        tick_once(&mut tree);

        assert_eq!(banded(&doc), [(14, 14)], "\"Two is second.\" is banded");
    }

    #[test]
    fn the_band_follows_the_caret_and_the_scope() {
        let Mounted {
            mut tree,
            doc,
            handle,
            ..
        } = mounted("One is first. Two is second.");
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        handle.select_range(2, 2);
        tick_once(&mut tree);
        assert_eq!(banded(&doc), [(0, 13)]);

        handle.select_range(16, 16);
        tick_once(&mut tree);
        assert_eq!(banded(&doc), [(14, 14)], "it followed the caret");

        handle.set_caret_highlight(Some(band(CaretHighlightScope::Paragraph)));
        tick_once(&mut tree);
        assert_eq!(banded(&doc), [(0, 28)], "and widened with the scope");
    }

    #[test]
    fn clearing_the_band_removes_it_from_the_document() {
        let Mounted {
            mut tree,
            doc,
            handle,
            ..
        } = mounted("One is first.");
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        tick_once(&mut tree);
        assert!(!banded(&doc).is_empty());

        handle.set_caret_highlight(None);
        tick_once(&mut tree);
        assert!(banded(&doc).is_empty(), "and its session is gone");
        assert_eq!(handle.get_caret_highlight(), None);
    }

    /// **Why an unfocused view clears its band.** Two panes over one shared document each own a
    /// session, and both are configured. Only the focused one may draw, or the writer would see
    /// a second band sitting wherever the other pane's caret happens to rest — and no
    /// `HighlightMask` is needed to arrange it.
    #[test]
    fn only_the_focused_pane_of_a_split_bands() {
        let doc = TextDocument::new();
        doc.set_plain_text("One is first. Two is second.").unwrap();

        let left = RichTextEditor::editor(doc.clone());
        let left_handle = left.handle();
        let right = RichTextEditor::editor(doc.clone());
        let right_handle = right.handle();

        let mut tree = WidgetTree::new();
        let left_id = tree.add(left);
        let right_id = tree.add(right);
        tree.layout(SizeProposal::exact(400.0, 300.0));

        left_handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        right_handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        left_handle.select_range(2, 2);
        right_handle.select_range(16, 16);

        tree.focus(left_id);
        tick_once(&mut tree);
        assert_eq!(
            banded(&doc),
            [(0, 13)],
            "exactly one band, at the focused pane's caret"
        );

        tree.focus(right_id);
        tick_once(&mut tree);
        tick_once(&mut tree);
        assert_eq!(
            banded(&doc),
            [(14, 14)],
            "still exactly one band, now at the other pane's caret"
        );
    }

    /// **The performance contract.** A band move must recolor, never reshape: no full layout,
    /// and the recolor must take the block-scoped path rather than re-snapshotting the document.
    #[test]
    fn moving_the_band_recolors_one_block_and_never_relayouts() {
        let Mounted {
            mut tree,
            handle,
            state,
            ..
        } = mounted("One is first. Two is second.\nA second paragraph.");
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        tick_once(&mut tree);

        {
            let mut st = state.borrow_mut();
            st.needs_full_layout = false;
            st.pending_recolor = false;
            st.pending_recolor_range = None;
        }

        handle.select_range(16, 16);
        // Drain the caret move into the session without running the recolor, so the accumulated
        // extent can be inspected before `tick` consumes it.
        {
            let mut st = state.borrow_mut();
            let caret = st.cursor.position();
            let changed = st
                .caret_highlight
                .as_ref()
                .expect("a band was set")
                .refresh(caret);
            assert!(changed, "the caret moved to another sentence");
            st.drain_events();
        }

        let st = state.borrow();
        assert!(st.pending_recolor, "a band move asks for a recolor");
        assert!(
            !st.needs_full_layout,
            "a band move must never force a reshape"
        );
        let (start, length) = st
            .pending_recolor_range
            .expect("the extent must be known, or the fast path cannot fire");
        assert!(
            length > 0 && start + length <= 28,
            "the extent must stay inside the first block; got {start}..{}",
            start + length
        );
    }

    /// A read-only view keeps highlights off, so the band is inert there without special-casing.
    #[test]
    fn a_read_only_view_paints_no_band() {
        let doc = TextDocument::new();
        doc.set_plain_text("One is first.").unwrap();
        let editor = RichTextEditor::read_only(doc.clone());
        let handle = editor.handle();
        let state = editor.state_handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        tree.focus(id);
        tick_once(&mut tree);

        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        tick_once(&mut tree);

        assert!(
            !state.borrow().show_highlights,
            "read_only defaults highlights off"
        );
        assert!(
            !state.borrow().pending_recolor,
            "so a band change is a pure no-op for this view"
        );
    }
}

/// What the band does while text is selected.
#[cfg(test)]
mod caret_band_selection {
    use super::caret_band::*;
    use super::*;
    use crate::rich_text::caret_highlight::CaretHighlightScope;

    /// **A selection replaces the band.**
    ///
    /// The band answers "where am I writing". A selection answers that better, and more
    /// precisely — so while one exists the band is noise. Worse than noise, in fact: it is
    /// resolved from the caret, which during a selection is the *moving end*, so it jumped from
    /// sentence to sentence underneath the selection as it grew.
    #[test]
    fn a_selection_hides_the_band() {
        let Mounted {
            mut tree,
            doc,
            handle,
            ..
        } = mounted("One is first. Two is second. Three is third.");
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        handle.select_range(2, 2);
        tick_once(&mut tree);
        assert_eq!(banded(&doc), [(0, 13)], "a collapsed caret bands");

        // Select across into the second sentence.
        handle.select_range(2, 20);
        tick_once(&mut tree);
        assert!(
            banded(&doc).is_empty(),
            "no band while a selection is up; got {:?}",
            banded(&doc)
        );

        // Collapsing the selection brings it back.
        handle.select_range(20, 20);
        tick_once(&mut tree);
        assert_eq!(banded(&doc), [(14, 14)], "and it returns on collapse");
    }

    /// Growing a selection must not make the band flicker through the sentences it crosses —
    /// the "wild" part. Every step of the drag stays bandless.
    #[test]
    fn growing_a_selection_never_flickers_the_band() {
        let Mounted {
            mut tree,
            doc,
            handle,
            ..
        } = mounted("One is first. Two is second. Three is third.");
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        handle.select_range(2, 2);
        tick_once(&mut tree);

        for head in 3..=42 {
            handle.select_range(2, head);
            tick_once(&mut tree);
            assert!(
                banded(&doc).is_empty(),
                "band reappeared mid-drag at head {head}: {:?}",
                banded(&doc)
            );
        }
    }

    /// A backwards selection is still a selection.
    #[test]
    fn a_backwards_selection_hides_the_band_too() {
        let Mounted {
            mut tree,
            doc,
            handle,
            ..
        } = mounted("One is first. Two is second.");
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        handle.select_range(25, 5);
        tick_once(&mut tree);
        assert!(banded(&doc).is_empty(), "got {:?}", banded(&doc));
    }
}

/// Regressions for two ways the band escaped its own rules, both found in review.
#[cfg(test)]
mod caret_band_regressions {
    use super::caret_band::*;
    use super::*;
    use crate::rich_text::caret_highlight::CaretHighlightScope;

    /// **A parked editor must drop its band.**
    ///
    /// Only `frame_loop::tick` pushes focus through to the session, and the tick effect is
    /// skipped entirely while dormant — so clearing `has_focus` in the dormancy effect was not
    /// enough: nothing ever acted on it. A tab parked with a band left it registered on the
    /// shared document forever, and a split pane over that document showed two bands.
    #[test]
    fn parking_an_editor_retires_its_band() {
        let doc = TextDocument::new();
        doc.set_plain_text("One is first. Two is second.").unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let handle = editor.handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        tree.focus(id);
        tick_once(&mut tree);

        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        tick_once(&mut tree);
        assert!(!banded(&doc).is_empty(), "banded while live and focused");

        // Park it, exactly as a TabWidget does when its tab stops being the visible one.
        tree.set_dormant(id);
        tree.layout(SizeProposal::exact(400.0, 300.0));

        assert!(
            banded(&doc).is_empty(),
            "a dormant editor must leave no band on a document its siblings still show"
        );
    }

    /// **A band change must survive a full layout in the same tick.**
    ///
    /// The band used to be resolved *after* the layout step, so on any edit that forced a full
    /// layout (Enter, a multi-paragraph paste, undo) `layout_full` baked the PREVIOUS band and
    /// the recolor step then discarded the correction as redundant — leaving the band on the
    /// old extent until something unrelated pumped another recolor.
    #[test]
    fn a_band_move_survives_a_full_layout_in_the_same_tick() {
        let Mounted {
            mut tree,
            doc,
            handle,
            state,
        } = mounted("One is first. Two is second.");
        handle.set_caret_highlight(Some(band(CaretHighlightScope::Sentence)));
        handle.select_range(2, 2);
        // Render between ticks: only `paint()` consumes `pending_full_render`, and the recolor
        // step skips while it is set — so a tick-only loop never exercises the paint path at all.
        tick_once(&mut tree);
        let _ = tree.render();
        tick_once(&mut tree);
        let _ = tree.render();
        assert_eq!(banded(&doc), [(0, 13)], "banding the first sentence");

        // The band the LAYOUT actually carries, as x-extents of its background rects. Asserting
        // on the document's session ranges would not catch this bug: those were always updated
        // correctly — it was the baked layout that kept the stale colours.
        let painted = |state: &crate::rich_text::state::SharedState| -> Vec<(i64, i64)> {
            state.borrow_mut().engine.with_render_frame(|frame| {
                let mut v: Vec<(i64, i64)> = frame
                    .decorations
                    .iter()
                    .filter(|d| d.kind == teksilo_text::TypesetterDecorationKind::TextBackground)
                    .map(|d| {
                        (
                            d.rect[0].round() as i64,
                            (d.rect[0] + d.rect[2]).round() as i64,
                        )
                    })
                    .collect();
                v.sort();
                v
            })
        };
        let first = painted(&state);
        assert!(!first.is_empty(), "the first sentence is painted");

        // Force the full-layout branch, and move the caret into the second sentence, in one go.
        state.borrow_mut().needs_full_layout = true;
        handle.select_range(16, 16);
        tick_once(&mut tree);
        let _ = tree.render();

        assert_eq!(
            banded(&doc),
            [(14, 14)],
            "the document carries the new extent (this part was never broken)"
        );
        let second = painted(&state);
        assert!(!second.is_empty(), "the second sentence is painted");
        assert_ne!(
            first, second,
            "the PAINTED band must move too — it used to keep the pre-edit extent, because \
             layout_full baked the old band and the recolor step then dropped the correction"
        );
    }
}

#[cfg(test)]
mod vertical_movement {
    use super::*;
    use teksilo_core::{Key, Modifiers, WidgetEvent};
    use teksilo_text::EditorTypographyDefaults;

    /// An editor whose paragraphs set `line_height`, the way prose does.
    fn editor_with_line_height(line_height: f32) -> (crate::rich_text::EditorHandle, WidgetTree) {
        let doc = TextDocument::new();
        doc.set_plain_text("Line one here.\nLine two here.\nLine three here.\nLine four here.")
            .unwrap();
        let editor = RichTextEditor::editor(doc).typography_defaults(EditorTypographyDefaults {
            line_height,
            ..Default::default()
        });
        let handle = editor.handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        tree.focus(id);
        tick_once(&mut tree);
        let _ = tree.render();
        (handle, tree)
    }

    fn press(tree: &mut WidgetTree, key: Key) {
        tree.dispatch_event(WidgetEvent::KeyDown {
            key,
            modifiers: Modifiers::NONE,
            text: None,
        });
        tick_once(tree);
    }

    /// **ArrowDown must cross to the next line whatever the line spacing.**
    ///
    /// The step used to be the caret's own height — ascent plus descent — while the distance to
    /// the next line is the line's advance, which is larger for any spacing above 1.0. Stepping
    /// by the caret height from the top of a line landed inside that same line, so Down did
    /// nothing at all. `1.0` is the case that always worked; the rest are what prose uses.
    #[test]
    fn arrow_down_crosses_a_line_at_every_line_height() {
        for line_height in [1.0f32, 1.2, 1.5, 1.6, 2.0] {
            let (handle, mut tree) = editor_with_line_height(line_height);
            handle.select_range(2, 2);
            tick_once(&mut tree);
            let _ = tree.render();

            press(&mut tree, Key::ArrowDown);
            let after = handle.cursor_position();
            assert!(
                after >= 15,
                "line_height {line_height}: ArrowDown must reach the second line, got {after}"
            );
        }
    }

    /// Up kept working through the bug, by luck. Pin it so the fix cannot break it.
    #[test]
    fn arrow_up_crosses_a_line_at_every_line_height() {
        for line_height in [1.0f32, 1.6, 2.0] {
            let (handle, mut tree) = editor_with_line_height(line_height);
            handle.select_range(20, 20); // on the second line
            tick_once(&mut tree);
            let _ = tree.render();

            press(&mut tree, Key::ArrowUp);
            let after = handle.cursor_position();
            assert!(
                after < 15,
                "line_height {line_height}: ArrowUp must reach the first line, got {after}"
            );
        }
    }

    /// Down and Up must compose back to where they started, at any spacing.
    #[test]
    fn down_then_up_returns_to_the_starting_line() {
        for line_height in [1.0f32, 1.6] {
            let (handle, mut tree) = editor_with_line_height(line_height);
            handle.select_range(2, 2);
            tick_once(&mut tree);
            let _ = tree.render();

            press(&mut tree, Key::ArrowDown);
            let middle = handle.cursor_position();
            press(&mut tree, Key::ArrowUp);
            let back = handle.cursor_position();
            assert!(middle > 2, "line_height {line_height}: down moved");
            assert_eq!(back, 2, "line_height {line_height}: and up came back");
        }
    }

    /// At the top and bottom edges the caret must simply stay put.
    #[test]
    fn vertical_movement_stops_at_the_document_edges() {
        let (handle, mut tree) = editor_with_line_height(1.6);
        handle.select_range(0, 0);
        tick_once(&mut tree);
        let _ = tree.render();
        press(&mut tree, Key::ArrowUp);
        assert_eq!(handle.cursor_position(), 0, "no running off the top");

        let end = 60;
        handle.select_range(end, end);
        tick_once(&mut tree);
        let _ = tree.render();
        for _ in 0..5 {
            press(&mut tree, Key::ArrowDown);
        }
        assert!(handle.cursor_position() <= 61, "no running off the bottom");
    }
}

// ---------------------------------------------------------------------------
// AccessKit annotation (comment) emission — the W3C annotations pattern
// ---------------------------------------------------------------------------

#[allow(unused_imports)]
use crate::rich_text::TextAnnotationSpan;

/// An annotated range must produce a `Role::Comment` body node, and the
/// `Role::TextRun` covering it must point at that node through `details`
/// (AccessKit's `aria-details`).
///
/// That relation is the whole feature: without it a screen reader has no way to
/// know the prose is annotated, and the underline a sighted user sees has no
/// accessible counterpart at all.
#[test]
fn an_annotated_range_emits_a_comment_node_linked_by_details() {
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("The lamp guttered").unwrap();
    let editor = RichTextEditor::editor(doc).annotation_spans(vec![TextAnnotationSpan {
        start: 4,
        end: 8,
        group_id: 77,
        summary: "Jane: is this too on-the-nose?".into(),
    }]);

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    let update = tree.sync_accessibility();

    let comment = update
        .nodes
        .iter()
        .find(|(_, n)| n.role() == Role::Comment)
        .expect("an annotated range must emit a Role::Comment body node");
    assert_eq!(
        comment.1.value(),
        Some("Jane: is this too on-the-nose?"),
        "the body carries the text to announce — the marked span must not, since \
         role=mark forbids an accessible name"
    );

    let linked = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == Role::TextRun)
        .any(|(_, n)| n.details().contains(&comment.0));
    assert!(
        linked,
        "the TextRun covering the annotation must point at the comment via details"
    );
}

/// No annotations, no comment nodes — the feature must cost nothing on an
/// ordinary document.
#[test]
fn an_unannotated_document_emits_no_comment_nodes() {
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("The lamp guttered").unwrap();
    let mut tree = WidgetTree::new();
    let _id = tree.add(RichTextEditor::editor(doc));
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let update = tree.sync_accessibility();
    assert!(
        !update.nodes.iter().any(|(_, n)| n.role() == Role::Comment),
        "an unannotated document must emit no annotation bodies"
    );
}

/// Two overlapping annotations both reach the reader: `details` is a list, so the
/// covered run points at both bodies. Overlap is normal in review, and a design
/// that kept only one would silently hide a thread.
#[test]
fn overlapping_annotations_each_get_their_own_body_node() {
    use teksilo_core::accesskit::Role;

    let doc = TextDocument::new();
    doc.set_plain_text("The lamp guttered").unwrap();
    let editor = RichTextEditor::editor(doc).annotation_spans(vec![
        TextAnnotationSpan {
            start: 0,
            end: 8,
            group_id: 1,
            summary: "first".into(),
        },
        TextAnnotationSpan {
            start: 4,
            end: 17,
            group_id: 2,
            summary: "second".into(),
        },
    ]);

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    let update = tree.sync_accessibility();

    let bodies: Vec<&str> = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == Role::Comment)
        .filter_map(|(_, n)| n.value())
        .collect();
    assert!(bodies.contains(&"first"), "got {bodies:?}");
    assert!(bodies.contains(&"second"), "got {bodies:?}");
}

// ---------------------------------------------------------------------------
// EditorHandle::range_rect — geometry for decorations drawn outside the editor
// ---------------------------------------------------------------------------

/// A laid-out range must report a rectangle that is inside the editor, non-empty,
/// and ordered left-to-right / top-to-bottom.
///
/// This is the primitive a margin annotation lines itself up with, so a wrong
/// answer here misplaces every connector and bracket drawn from it.
#[test]
fn range_rect_reports_a_plausible_box_for_a_laid_out_span() {
    let doc = TextDocument::new();
    doc.set_plain_text("The lamp guttered, and then it did not.")
        .unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    let r = handle
        .range_rect(4, 8)
        .expect("a laid-out editor must report a rect for a real range");
    assert!(r.width > 0.0, "a four-character span has width: {r:?}");
    assert!(r.height > 0.0, "and a line's height: {r:?}");
}

/// A later range sits further right on the same line — the ordering a leader line
/// depends on when it decides which end of the span to leave from.
#[test]
fn range_rect_advances_along_the_line() {
    let doc = TextDocument::new();
    doc.set_plain_text("aaaa bbbb cccc").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(600.0, 300.0));
    let _ = tree.render();

    let first = handle.range_rect(0, 4).expect("first word");
    let last = handle.range_rect(10, 14).expect("last word");
    assert!(
        last.x > first.x,
        "a later span must start further right: {first:?} then {last:?}"
    );
}

/// Before layout there is no geometry to report, and the answer is `None` rather
/// than a zero rect a caller would happily draw at the origin.
#[test]
fn range_rect_is_none_before_layout() {
    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();
    assert!(handle.range_rect(0, 5).is_none());
}

// ---------------------------------------------------------------------------
// Intrinsic height before the text has been laid out
// ---------------------------------------------------------------------------

/// The **body**'s height, which is what intrinsic sizing decides. The outer
/// editor takes the proposal it is handed; the body is the part that measures
/// to its text.
fn body_height(tree: &WidgetTree, id: teksilo_core::widget_id::WidgetId) -> f32 {
    fn walk(
        tree: &WidgetTree,
        id: teksilo_core::widget_id::WidgetId,
    ) -> Option<teksilo_core::widget_id::WidgetId> {
        if tree
            .widget_type_name(id)
            .is_some_and(|n| n.ends_with("RichTextEditorBody"))
        {
            return Some(id);
        }
        tree.children(id).into_iter().find_map(|c| walk(tree, c))
    }
    walk(tree, id).map(|b| tree.bounds(b).height).unwrap_or(0.0)
}

/// **A long document must not measure the same as an empty one** before either has
/// been laid out.
///
/// `content_height()` is `0` until `layout_full` has run, and that waits for a frame
/// on screen. The zero fell through to the `min_lines` floor, so every unlaid-out
/// editor claimed exactly ten lines whatever it held. On one editor that is
/// invisible; down a stream of them it makes the page's height wrong by an order of
/// magnitude, and anything drawing that extent — a scroll bar, a margin lane —
/// draws it settling a row at a time as the reader arrives.
#[test]
fn an_unlaid_out_editor_estimates_its_height_from_its_text() {
    fn measured(text: &str) -> f32 {
        let doc = TextDocument::new();
        doc.set_plain_text(text).unwrap();
        let editor = RichTextEditor::editor(doc)
            .min_lines(10)
            .estimate_height_before_layout(true);
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        // Laid out but never rendered: exactly the state a row below the fold is in.
        // **Twice.** The guess is made at the width the body was last *placed* at,
        // so the first pass has no measure to guess against and reports the floor;
        // the pass after it is the one that estimates. That is the contract, not a
        // quirk of the harness: guessing against whatever proposal happens to be
        // asking was measured claiming six times a scene's true height.
        tree.layout(SizeProposal::exact(400.0, 3000.0));
        tree.layout(SizeProposal::exact(400.0, 3001.0));
        body_height(&tree, id)
    }

    let empty = measured("");
    let short = measured("One line.");
    let long = measured(&"The ferry left before the light did. ".repeat(200));

    assert!(
        (empty - short).abs() < 1.0,
        "nothing and almost nothing both sit on the floor: {empty} against {short}"
    );
    assert!(
        long > short * 4.0,
        "a document forty times longer must not measure the same: {long} against {short}"
    );
}

/// **The estimate uses the measure it was given**, not a constant.
///
/// `layout_response`'s `w` falls back to 200 for a proposal carrying no width, which
/// is a reasonable default for a *width* and ruinous for a line count: the same text
/// wraps to four times as many lines at a quarter of the measure. Estimating against
/// that fallback made a scene claim nearly twice its real height, which pushed the
/// editor below it clean off the page — where it then never laid out at all, and the
/// margin lane beside it had no geometry to place a single mark against. A consumer
/// test in the Skribisto tree caught that; this says the same thing here.
#[test]
fn a_narrower_measure_estimates_a_taller_block_of_text() {
    fn at(width: f32) -> f32 {
        let doc = TextDocument::new();
        doc.set_plain_text(&"The ferry left before the light did. ".repeat(200))
            .unwrap();
        let editor = RichTextEditor::editor(doc)
            .min_lines(1)
            .estimate_height_before_layout(true);
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(width, 3000.0));
        tree.layout(SizeProposal::exact(width, 3001.0));
        body_height(&tree, id)
    }

    let wide = at(800.0);
    let narrow = at(200.0);
    assert!(
        narrow > wide * 2.0,
        "a quarter of the measure is roughly four times the lines: {narrow} at 200 px \
         against {wide} at 800 px"
    );
}

/// **Manuscript typography has to be in the guess**, or it is not worth making.
///
/// Prose is set with a line-height multiplier and space between paragraphs. A first
/// cut counted bare lines at the font's natural height, came out well under the
/// truth, and the rows it sized still visibly grew when they finally laid out —
/// which is the whole thing the estimate exists to stop.
#[test]
fn the_estimate_counts_the_line_height_and_the_paragraph_spacing() {
    fn at(defaults: teksilo_text::EditorTypographyDefaults) -> f32 {
        let doc = TextDocument::new();
        doc.set_plain_text(&"The ferry left before the light did.\n\n".repeat(30))
            .unwrap();
        let editor = RichTextEditor::editor(doc)
            .min_lines(1)
            .typography_defaults(defaults)
            .estimate_height_before_layout(true);
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 6000.0));
        tree.layout(SizeProposal::exact(400.0, 6001.0));
        body_height(&tree, id)
    }

    let plain = at(teksilo_text::EditorTypographyDefaults::default());
    let spaced = at(teksilo_text::EditorTypographyDefaults {
        line_height: 1.6,
        ..Default::default()
    });
    let gapped = at(teksilo_text::EditorTypographyDefaults {
        paragraph_spacing_before: 6.0,
        paragraph_spacing_after: 6.0,
        ..Default::default()
    });

    assert!(
        spaced > plain * 1.4,
        "a 1.6 line-height multiplier must show: {spaced} against {plain}"
    );
    assert!(
        gapped > plain,
        "twelve pixels between each of thirty paragraphs is real page: {gapped} against {plain}"
    );
}

/// The estimate has to be **close**, and it has to be **content rather than a
/// bound**.
///
/// Close, because its whole job is to be nearer the truth than the constant it
/// replaced; a wild guess would trade one wrong page height for another, and the
/// row would visibly jump either way when the real layout landed. Content, because a
/// `min_lines` big enough to cover a long scene would leave blank space under a
/// short one for the life of the widget — so the number goes through the same clamp
/// a real height does, and `max_lines` still caps it.
///
/// The tolerance is deliberately tight. Two loose ones shipped before it: the first
/// guess ignored the line-height multiplier and came out 60% under for manuscript
/// prose, the second over-counted lines by a third, and both were inside a
/// `0.4..=2.5` band that let them through. What a reader sees is the *correction*,
/// so the size of the correction is the thing to pin.
///
/// What this cannot show is the settling itself: adopting the real height is driven
/// by the frame loop, which a bare `layout`/`render` pair does not stand in for.
/// `scripts/automation_margin_lane.py` in the Skribisto tree watches that in a window.
#[test]
fn the_estimate_is_close_to_the_truth_and_is_not_a_floor() {
    /// Guessed height over real height, for one shape of text at one measure.
    fn ratio(text: &str, typography: teksilo_text::EditorTypographyDefaults) -> f32 {
        let doc = TextDocument::new();
        doc.set_plain_text(text).unwrap();
        let editor = RichTextEditor::editor(doc)
            .min_lines(10)
            .typography_defaults(typography)
            .estimate_height_before_layout(true);
        let handle = editor.handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);

        tree.layout(SizeProposal::exact(400.0, 6000.0));
        tree.layout(SizeProposal::exact(400.0, 6001.0));
        let guessed = body_height(&tree, id);
        assert!(handle.content_height().is_none(), "nothing laid out yet");
        let _ = tree.render();
        guessed / handle.content_height().expect("laid out now")
    }

    let manuscript = teksilo_text::EditorTypographyDefaults {
        line_height: 1.6,
        ..Default::default()
    };
    // Three shapes, because the error is not the same for all of them: long wrapped
    // paragraphs are dominated by the advance estimate, many short ones by the
    // per-block allowance.
    for (name, text, typo) in [
        (
            "one long paragraph",
            "The ferry left before the light did. ".repeat(200),
            Default::default(),
        ),
        (
            "many short paragraphs",
            "The ferry left.\n\n".repeat(120),
            Default::default(),
        ),
        (
            "manuscript line height",
            "The ferry left before the light did. ".repeat(200),
            manuscript,
        ),
    ] {
        let r = ratio(&text, typo);
        assert!(
            (0.75..=1.35).contains(&r),
            "{name}: the guess was a factor of {r} off, which a reader would see correct itself"
        );
    }

    // Capped like any content height. A floor could not be capped, which is the
    // structural half of "this is not a `min_lines`".
    let doc = TextDocument::new();
    doc.set_plain_text(&"The ferry left before the light did. ".repeat(200))
        .unwrap();
    let capped = RichTextEditor::editor(doc)
        .min_lines(2)
        .max_lines(4)
        .estimate_height_before_layout(true);
    let mut tree = WidgetTree::new();
    let id = tree.add(capped);
    tree.layout(SizeProposal::exact(400.0, 6000.0));
    tree.layout(SizeProposal::exact(400.0, 6001.0));
    let h = body_height(&tree, id);
    assert!(
        h < 200.0,
        "`max_lines` must cap the estimate as it caps a real height: got {h}"
    );
}

// ---------------------------------------------------------------------------
// EditorHandle content space — the scroll-free geometry an overview strip maps
// ---------------------------------------------------------------------------

/// A tall document in a short viewport, laid out and rendered once.
#[cfg(test)]
fn tall_editor() -> (
    RichTextEditor,
    crate::rich_text::EditorHandle,
    teksilo_core::signal::Signal<f32>,
) {
    let doc = TextDocument::new();
    let mut text = String::new();
    for i in 0..60 {
        text.push_str(&format!(
            "Paragraph {i}: the ferry left before the light did.\n"
        ));
    }
    doc.set_plain_text(&text).unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();
    let scroll = editor.scroll_y();
    (editor, handle, scroll)
}

/// **The property the whole content-space API exists for.**
///
/// Scrolling moves what is on screen and moves nothing about the document. A lane
/// that mapped window coordinates would slide every mark up the strip as the writer
/// scrolled down, which is precisely backwards: the marks are supposed to be the
/// fixed thing the viewport moves over.
#[test]
fn content_rect_ignores_scrolling_where_the_window_rect_follows_it() {
    let (editor, handle, scroll) = tall_editor();
    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 200.0));
    let _ = tree.render();

    let window_before = handle.range_rect(100, 110).expect("laid out");
    let content_before = handle.range_content_rect(100, 110).expect("laid out");

    scroll.set(300.0);

    let window_after = handle.range_rect(100, 110).expect("still laid out");
    let content_after = handle.range_content_rect(100, 110).expect("still laid out");

    assert!(
        (window_before.y - window_after.y).abs() > 100.0,
        "the window rect must follow the scroll: {window_before:?} then {window_after:?}"
    );
    assert!(
        (content_before.y - content_after.y).abs() < 0.01,
        "the content rect must not: {content_before:?} then {content_after:?}"
    );
}

/// The division a lane actually performs: an offset's content y over the content
/// height is a fraction of the document, monotone in the offset and inside `0..=1`.
#[test]
fn content_rect_over_content_height_is_a_monotone_document_fraction() {
    let (editor, handle, _scroll) = tall_editor();
    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 200.0));
    let _ = tree.render();

    let height = handle.content_height().expect("laid out");
    assert!(
        height > 200.0,
        "the document is taller than its viewport: {height}"
    );

    let fraction = |offset: usize| handle.offset_content_rect(offset).unwrap().y / height;

    let first = fraction(0);
    let middle = fraction(1500);
    let last = fraction(3000);

    assert!(
        (0.0..=1.0).contains(&first) && (0.0..=1.0).contains(&last),
        "fractions stay inside the document: {first} .. {last}"
    );
    assert!(
        first < middle && middle < last,
        "and rise with the offset: {first}, {middle}, {last}"
    );
}

/// The same gate as the window queries, so a caller holding one holds the other and
/// never divides a real y by a stale or absent height.
#[test]
fn content_geometry_is_absent_together_before_layout() {
    let doc = TextDocument::new();
    doc.set_plain_text("hello").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();
    assert!(handle.range_content_rect(0, 5).is_none());
    assert!(handle.offset_content_rect(0).is_none());
    assert!(handle.content_height().is_none());
}

// ---------------------------------------------------------------------------
// External (OS) drag hover
// ---------------------------------------------------------------------------

/// An external drag must reach the editor's own `on_drag_hover` and move the
/// caret under the pointer, so the writer can see where the drop will land.
///
/// The payload shape here is the one Wayland actually delivers on hover: the
/// bytes are only readable at drop time (they arrive over a pipe), so `files`
/// / `text` / `uris` are all empty and only the advertised MIME `formats` are
/// populated. A target that validates on `files()`/`text()` sees an empty
/// payload, returns `NoFeedback`, and the drag bubbles to an ancestor that
/// paints a reject tint — which reads as "drops are forbidden everywhere",
/// with a caret that never follows the drag.
#[test]
fn external_drag_hover_moves_caret_from_formats_only_payload() {
    use teksilo_core::ExternalDropData;
    use teksilo_core::window::NoopWindowOps;

    let doc = TextDocument::new();
    doc.set_plain_text("Hello world").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();

    handle.select_range(0, 0);
    let before = handle.cursor_position();

    let mut noop = NoopWindowOps;
    tree.begin_external_drag(
        Point::new(300.0, 8.0),
        ExternalDropData {
            formats: vec!["text/uri-list".to_string()],
            ..Default::default()
        },
        &mut noop,
    );

    assert_ne!(
        before,
        handle.cursor_position(),
        "the caret must follow an external drag whose payload carries only MIME \
         formats (the Wayland hover shape)"
    );
}

// ---------------------------------------------------------------------------
// Dragging a selection out of the editor
// ---------------------------------------------------------------------------

/// Build an editor holding `text`, return it with its state and handle.
fn drag_fixture(text: &str) -> (super::state::SharedState, super::EditorHandle, WidgetTree) {
    let doc = TextDocument::new();
    doc.set_plain_text(text).unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();
    let state = editor.state.clone();

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    (state, handle, tree)
}

/// Capture `range` as a drag payload, then park the caret at `drop_at`.
fn drag_of(
    state: &super::state::SharedState,
    handle: &super::EditorHandle,
    range: (usize, usize),
    drop_at: usize,
) -> super::EditorTextDrag {
    handle.select_range(range.0, range.1);
    let fragment = state.borrow().cursor.selection();
    let text = fragment.to_plain_text().to_string();
    handle.select_range(drop_at, drop_at);
    super::EditorTextDrag {
        source: teksilo_core::WidgetId::default(),
        range,
        fragment,
        text,
    }
}

/// Dropped back into the editor it came from, dragged text *moves*: the original
/// goes away. The drop offset was measured before the removal, so it has to be
/// re-based by the removed length or the text lands that many characters right.
#[test]
fn text_dropped_into_its_own_editor_moves() {
    let (state, handle, _tree) = drag_fixture("Hello world");
    let drag = drag_of(&state, &handle, (0, 5), 11);

    assert!(super::mouse::apply_text_drop(&state, &drag, true));
    assert_eq!(
        handle.to_plain_text(),
        " worldHello",
        "the original must be removed and the drop re-based past it"
    );
}

/// Dropped into a *different* editor it is a copy — carrying a phrase into a
/// second document must not empty it out of the first.
#[test]
fn text_dropped_into_another_editor_copies() {
    let (state, handle, _tree) = drag_fixture("Hello world");
    let drag = drag_of(&state, &handle, (0, 5), 11);

    assert!(super::mouse::apply_text_drop(&state, &drag, false));
    assert_eq!(
        handle.to_plain_text(),
        "Hello worldHello",
        "a cross-editor drop copies, leaving the source text standing"
    );
}

/// Dropping a selection back inside itself is a no-op, not a self-destruct:
/// removing the range would delete the very text being carried.
#[test]
fn text_dropped_inside_itself_changes_nothing() {
    let (state, handle, _tree) = drag_fixture("Hello world");
    let drag = drag_of(&state, &handle, (0, 5), 3);

    assert!(super::mouse::apply_text_drop(&state, &drag, true));
    assert_eq!(handle.to_plain_text(), "Hello world");
}

/// A drop *before* the dragged range needs no re-basing — the removal happens
/// entirely after it.
#[test]
fn text_dropped_before_its_own_range_lands_at_the_caret() {
    let (state, handle, _tree) = drag_fixture("Hello world");
    let drag = drag_of(&state, &handle, (6, 11), 0);

    assert!(super::mouse::apply_text_drop(&state, &drag, true));
    assert_eq!(handle.to_plain_text(), "worldHello ");
}

/// Pressing inside a selection must not collapse it. The press cannot yet know
/// whether it is a click or the start of a drag of that text, and collapsing
/// eagerly is what makes a selection impossible to pick up — the text is gone
/// from the selection before the drag could carry it.
#[test]
fn press_inside_the_selection_keeps_it() {
    let (state, handle, mut tree) = drag_fixture("Hello world, and a good long line of prose.");
    handle.select_range(0, 20);

    let rect = handle.range_rect(4, 6).expect("geometry for the selection");
    synth_pointer_down(
        &mut tree,
        rect.x + rect.width / 2.0,
        rect.y + rect.height / 2.0,
    );

    assert!(
        state.borrow().cursor.has_selection(),
        "a press inside the selection must leave it standing"
    );
    assert!(
        matches!(
            state.borrow().drag_state,
            super::state::DragState::PendingTextDrag { .. }
        ),
        "and arm a possible drag of it"
    );
}

/// Releasing without travelling resolves the same press the other way: it was
/// an ordinary click, so the selection collapses onto it after all.
#[test]
fn press_inside_the_selection_then_release_collapses_it() {
    let (state, handle, mut tree) = drag_fixture("Hello world, and a good long line of prose.");
    handle.select_range(0, 20);

    let rect = handle.range_rect(4, 6).expect("geometry for the selection");
    let (x, y) = (rect.x + rect.width / 2.0, rect.y + rect.height / 2.0);
    synth_pointer_down(&mut tree, x, y);
    synth_pointer_up(&mut tree, x, y);

    assert!(
        !state.borrow().cursor.has_selection(),
        "a click that never travelled must collapse the selection"
    );
    assert!(matches!(
        state.borrow().drag_state,
        super::state::DragState::Idle
    ));
}

/// The caret that shows where a drag will land must appear in an editor that
/// does **not** have focus — the focus stays wherever the drag began, so gating
/// this caret on focus hides the one the writer is aiming with.
#[test]
fn drop_caret_shows_without_focus() {
    let (state, handle, _tree) = drag_fixture("Hello world, and a good long line of prose.");
    assert!(
        !state.borrow().has_focus,
        "fixture precondition: the editor is unfocused"
    );

    let rect = handle.range_rect(6, 11).expect("geometry for a word");
    let landed = super::mouse::move_caret_for_drag(
        &state,
        Point::new(rect.x + rect.width / 2.0, rect.y + rect.height / 2.0),
    );

    assert!(landed, "the drag is over text");
    assert!(
        state.borrow().drop_caret,
        "an unfocused editor under a drag must still show where the drop lands"
    );

    super::mouse::clear_drop_caret(&state);
    assert!(
        !state.borrow().drop_caret,
        "and stop showing it once the drag leaves, rather than burning it in"
    );
}

// ── Forward-only drafting (CommandFilter::ForwardOnly) ───────────────
//
// The behavioural half of the filter. `policy.rs`'s unit tests pin which
// commands are accepted; these drive a mounted editor to prove the two ways
// prose can leave a document *without* passing a command filter — type-over and
// a same-editor drag-move — are closed as well.

/// Mount an editor over `text`, focus it, and swap in the forward-only filter
/// the way a host does at runtime.
fn forward_only_editor(text: &str) -> (TextDocument, crate::rich_text::EditorHandle, WidgetTree) {
    let doc = TextDocument::new();
    doc.set_plain_text(text).unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();
    let mut tree = WidgetTree::new();
    let _ = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    handle.set_command_filter(super::policy::CommandFilter::ForwardOnly);
    (doc, handle, tree)
}

#[test]
fn forward_only_swallows_backspace_and_delete() {
    use teksilo_core::event::{Key, Modifiers};
    let (doc, handle, mut tree) = forward_only_editor("Hemingway");
    handle.select_range(9, 9);

    press_key(&mut tree, Key::Backspace, Modifiers::NONE);
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "Hemingway",
        "backspace must not remove a character"
    );

    handle.select_range(0, 0);
    press_key(&mut tree, Key::Delete, Modifiers::NONE);
    tick_past_debounce(&mut tree);
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "Hemingway");

    // Word-scale deletion is the same command family through a modifier.
    handle.select_range(9, 9);
    press_key(&mut tree, Key::Backspace, Modifiers::CTRL);
    tick_past_debounce(&mut tree);
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "Hemingway");
}

#[test]
fn forward_only_typing_over_a_selection_appends_instead_of_replacing() {
    // The trap the command filter alone cannot close: `insert_text` removes the
    // selected range *inside* text-document, so accepting InsertChar while
    // rejecting DeletePrev would still let a writer select everything and type
    // over it. The keystroke must land — after the selection, not instead of it.
    let (doc, handle, mut tree) = forward_only_editor("keep this");
    handle.select_range(0, 9);
    assert!(
        handle.has_selection().get(),
        "precondition: the whole line is selected"
    );

    press_char(&mut tree, '!');
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "keep this!",
        "the selected passage survives and the typed character is appended after it"
    );
}

#[test]
fn ordinary_editing_still_types_over_a_selection() {
    // The counterpart: the collapse is scoped to the forward-only filter and
    // must not change how a normal editor behaves.
    let doc = TextDocument::new();
    doc.set_plain_text("keep this").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();
    let mut tree = WidgetTree::new();
    let _ = ctx_with_memory_clipboard(&mut tree);
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    handle.select_range(0, 9);
    press_char(&mut tree, '!');
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "!",
        "an unrestricted editor replaces the selection, as every editor does"
    );
}

#[test]
fn forward_only_ime_composition_does_not_eat_a_selection() {
    // Dead keys and CJK candidates arrive on a path that never reaches the key
    // match, so the collapse has to be installed there too.
    use teksilo_core::event::WidgetEvent;
    let (doc, handle, mut tree) = forward_only_editor("garder");
    handle.select_range(0, 6);

    tree.dispatch_event(WidgetEvent::ImeComposition {
        text: "n".to_string(),
        cursor: None,
    });
    tree.tick_animations(std::time::Duration::from_millis(16));
    tree.dispatch_event(WidgetEvent::ImeCommit {
        text: "".to_string(),
    });
    tick_past_debounce(&mut tree);

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "garder你",
        "composition appends after the selection instead of replacing it"
    );
}

#[test]
fn forward_only_undo_is_blocked_but_history_survives_the_mode() {
    // Blocking Ctrl+Z must not *discard* history: everything written during a
    // forward-only session is undoable again the moment the mode ends.
    use teksilo_core::event::{Key, Modifiers};
    let (doc, handle, mut tree) = forward_only_editor("start");
    handle.select_range(5, 5);
    press_char(&mut tree, '!');
    tick_past_debounce(&mut tree);
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "start!");

    press_key(&mut tree, Key::Z, Modifiers::CTRL);
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "start!",
        "undo is refused while the mode is on"
    );

    handle.set_command_filter(super::policy::CommandFilter::All);
    press_key(&mut tree, Key::Z, Modifiers::CTRL);
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "start",
        "and works again as soon as it is off — the history was kept, not dropped"
    );
}

#[test]
fn the_filter_swap_takes_effect_without_rebuilding_the_widget() {
    use teksilo_core::event::{Key, Modifiers};
    let (doc, handle, mut tree) = forward_only_editor("abc");
    handle.select_range(3, 3);

    press_key(&mut tree, Key::Backspace, Modifiers::NONE);
    tick_past_debounce(&mut tree);
    assert_eq!(doc.to_plain_text().unwrap_or_default(), "abc");

    handle.set_command_filter(super::policy::CommandFilter::All);
    press_key(&mut tree, Key::Backspace, Modifiers::NONE);
    tick_past_debounce(&mut tree);
    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "ab",
        "the same mounted editor honours the new filter on the very next key"
    );
}

// ── Hyperlinks ──────────────────────────────────────────────────
//
// A link is a character format, so applying one goes through the same
// `merge_char_format` path bold does. What is specific to links is the
// *extent* query (a link is a stretch of runs, not an object) and the click
// rule (a writer must be able to get a caret inside their own link).

#[test]
fn setting_a_link_over_a_selection_lands_on_the_run() {
    let doc = TextDocument::new();
    doc.set_plain_text("Read the manual").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(9, 15);
    handle.set_link("https://example.com");

    handle.select_range(9, 15);
    assert_eq!(
        handle.caret_char_format().anchor_href.as_deref(),
        Some("https://example.com")
    );
    assert!(handle.is_link());
}

#[test]
fn a_link_survives_being_written_out_as_djot() {
    // The whole point of applying a link as a format: it reaches the file in
    // the format the document is actually saved in.
    let doc = TextDocument::new();
    doc.set_plain_text("Read the manual").unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(9, 15);
    handle.set_link("https://example.com");

    assert_eq!(
        handle.to_djot().trim(),
        "Read the [manual](https://example.com)"
    );
}

#[test]
fn clearing_a_link_leaves_its_text_behind() {
    let doc = TextDocument::new();
    doc.set_djot("Read the [manual](https://example.com)")
        .unwrap()
        .wait()
        .unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(11, 11);
    let extent = handle
        .link_at_caret()
        .expect("the caret is inside the link");
    handle.select_range(extent.start, extent.end);
    handle.clear_link();

    assert_eq!(handle.to_djot().trim(), "Read the manual");
}

#[test]
fn link_at_caret_reports_the_whole_link_not_the_run_under_the_caret() {
    // An inner mark splits the link into several runs. Reporting only the one
    // under the caret would make "Edit link" rewrite a fragment of the
    // writer's text and leave the rest still linked.
    let doc = TextDocument::new();
    doc.set_djot("[a _stormy_ night](https://example.com)")
        .unwrap()
        .wait()
        .unwrap();
    let editor = RichTextEditor::editor(doc.clone());
    let handle = editor.handle();

    handle.select_range(5, 5);
    let extent = handle.link_at_caret().expect("caret is inside the link");
    assert_eq!(extent.start, 0);
    assert_eq!(extent.end, 14);
    assert_eq!(extent.href, "https://example.com");
}

#[test]
fn a_plain_click_on_a_link_places_the_caret_and_does_not_follow_it() {
    // The behaviour that made links unusable in an editor: every click was
    // swallowed, so the text inside a link could not be reached by pointer at
    // all. A writer clicking their own link is usually trying to edit it.
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_djot("[a fairly long link label](https://example.com)")
        .unwrap()
        .wait()
        .unwrap();
    let followed = Rc::new(Cell::new(0u32));
    let probe = followed.clone();
    let editor = RichTextEditor::editor(doc.clone())
        .on_link_activated(move |_href, _ctx| probe.set(probe.get() + 1));
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    focus_editor(&mut tree, id);

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(60.0, 20.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::NONE,
    });

    assert_eq!(followed.get(), 0, "a plain click must not follow the link");
    assert!(
        handle.cursor_position() > 0,
        "a plain click must put the caret in the link's text"
    );
}

#[test]
fn ctrl_click_on_a_link_follows_it() {
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};

    let doc = TextDocument::new();
    doc.set_djot("[a fairly long link label](https://example.com)")
        .unwrap()
        .wait()
        .unwrap();
    let seen = Rc::new(std::cell::RefCell::new(String::new()));
    let probe = seen.clone();
    let editor = RichTextEditor::editor(doc.clone())
        .on_link_activated(move |href, _ctx| *probe.borrow_mut() = href.to_string());

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    focus_editor(&mut tree, id);

    tree.dispatch_event(WidgetEvent::PointerDown {
        position: Point::new(60.0, 20.0),
        button: PointerButton::Primary,
        modifiers: Modifiers::CTRL,
    });

    assert_eq!(seen.borrow().as_str(), "https://example.com");
}

#[test]
fn editor_on_change_fires_for_a_format_only_edit() {
    // The bug this guards: `on_change` is what a host wires "unsaved changes"
    // to, and a formatting edit never reached it. Bolding a word and closing
    // the app lost the bold with no prompt.
    let doc = TextDocument::new();
    doc.set_plain_text("abc").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    for _ in 0..2 {
        tick_once(&mut tree);
    }
    fired.set(0);

    handle.select_range(0, 3);
    handle.set_bold(true);
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert!(
        fired.get() > 0,
        "a formatting edit is the writer's work and must count as a change"
    );
}

#[test]
fn editor_on_change_stays_silent_for_a_load_that_carries_formatting() {
    // The risk the fix has to not introduce. A load applies formatting as it
    // parses, so widening the gate to formatting could have made every
    // `set_djot` look like an edit — which would mark a freshly-opened
    // project dirty before the writer touched it.
    let doc = TextDocument::new();
    doc.set_plain_text("first").unwrap();
    let (editor, fired) = with_on_change_probe(RichTextEditor::editor(doc.clone()));

    let mut tree = WidgetTree::new();
    let _id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    for _ in 0..2 {
        tick_once(&mut tree);
    }
    fired.set(0);

    doc.set_djot("a *bold* word and [a link](https://example.com)")
        .unwrap()
        .wait()
        .unwrap();
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert_eq!(
        fired.get(),
        0,
        "loading a formatted document must not look like an edit"
    );
}

use super::EditSource;

// ── Where text came from ────────────────────────────────────────────────────
//
// `on_text_inserted` reports the channel and the character count at each
// insertion. What matters in every test below is that the count is of what was
// *written*, not of how far the caret moved — those are different numbers the
// moment an insertion replaces a selection, and the second is the one a caller
// counting arrivals is never asking for.

/// Collects everything an editor reports, for assertions.
#[derive(Clone, Default)]
struct Arrivals(std::rc::Rc<std::cell::RefCell<Vec<(EditSource, usize)>>>);

impl Arrivals {
    fn seen(&self) -> Vec<(EditSource, usize)> {
        self.0.borrow().clone()
    }

    fn chars_from(&self, source: EditSource) -> usize {
        self.0
            .borrow()
            .iter()
            .filter(|(s, _)| *s == source)
            .map(|(_, n)| n)
            .sum()
    }
}

#[test]
fn typing_reports_the_characters_that_were_typed() {
    let doc = TextDocument::new();
    doc.set_plain_text("abc").unwrap();
    let arrivals = Arrivals::default();
    let editor = RichTextEditor::editor(doc.clone()).on_text_inserted({
        let arrivals = arrivals.clone();
        move |source, chars| arrivals.0.borrow_mut().push((source, chars))
    });

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );

    for ch in [' ', 'd', 'e', 'f'] {
        press_char(&mut tree, ch);
    }
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert_eq!(
        arrivals.seen(),
        vec![(EditSource::Keyboard, 4)],
        "one report per flushed batch, counting the characters in it"
    );
}

/// **The count is of what was written, not of how far the caret moved.** Typing
/// over a selection removes it first, so a position delta would report four
/// characters as one — or as a negative, if the selection were longer.
#[test]
fn typing_over_a_selection_counts_what_was_typed_not_the_net_change() {
    let doc = TextDocument::new();
    doc.set_plain_text("abcdefghij").unwrap();
    let arrivals = Arrivals::default();
    let editor = RichTextEditor::editor(doc.clone()).on_text_inserted({
        let arrivals = arrivals.clone();
        move |source, chars| arrivals.0.borrow_mut().push((source, chars))
    });

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::A,
        teksilo_core::event::Modifiers::CTRL,
    );

    for ch in ['h', 'i'] {
        press_char(&mut tree, ch);
    }
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert_eq!(
        doc.to_plain_text().unwrap_or_default(),
        "hi",
        "ten characters were replaced by two"
    );
    assert_eq!(
        arrivals.chars_from(EditSource::Keyboard),
        2,
        "two characters were written; the document is eight shorter, which is a \
         different question and not the one being asked"
    );
}

/// Nothing is reported for a programmatic load, for undo, or for a format-only
/// change: none of them is text arriving.
#[test]
fn a_programmatic_load_reports_nothing() {
    let doc = TextDocument::new();
    let arrivals = Arrivals::default();
    let editor = RichTextEditor::editor(doc.clone()).on_text_inserted({
        let arrivals = arrivals.clone();
        move |source, chars| arrivals.0.borrow_mut().push((source, chars))
    });

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);

    doc.set_plain_text("a whole manuscript, loaded from a file")
        .unwrap();
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert!(
        arrivals.seen().is_empty(),
        "opening a document is not somebody writing in it: {:?}",
        arrivals.seen()
    );
}

/// An editor nobody asked is an editor that counts nothing — the callback is
/// what turns the measuring on, so a build with no consumer pays nothing.
#[test]
fn an_editor_with_no_callback_is_undisturbed() {
    let doc = TextDocument::new();
    doc.set_plain_text("abc").unwrap();
    let editor = RichTextEditor::editor(doc.clone());

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    focus_editor(&mut tree, id);
    press_key(
        &mut tree,
        teksilo_core::event::Key::End,
        teksilo_core::event::Modifiers::CTRL,
    );
    for ch in ['d', 'e', 'f'] {
        press_char(&mut tree, ch);
    }
    for _ in 0..3 {
        tick_once(&mut tree);
    }

    assert_eq!(doc.to_plain_text().unwrap_or_default(), "abcdef");
}

// ── Following a link: a viewer takes a plain click, an editor asks for Ctrl ──
//
// The two surfaces disagree on purpose (see `mouse.rs`'s press arm). These
// four tests pin both halves, because getting either one wrong is invisible
// until a user complains: a viewer whose links need Ctrl reads as broken, and
// an editor that follows links on a plain click makes the text inside a link
// unreachable by pointer.

/// A document whose entire first line is one link, plus the click position
/// that lands inside it. `(2, 2)` is inside the first glyph run under the
/// mock text backend, which lays out deterministically.
fn link_only_doc() -> TextDocument {
    let doc = TextDocument::new();
    doc.set_html(r#"<p><a href="https://example.com/x">linklinklink</a></p>"#)
        .unwrap();
    doc
}

/// Click once inside the link with `modifiers` on a tree holding `editor`, and
/// report every href the widget dispatched.
///
/// `content_padding(0.0)` is not cosmetic here: the editor preset carries
/// TextInput-style insets and the read-only one carries none, so without it the
/// same click lands on text in one surface and in the padding of the other —
/// and the editor tests would pass by missing the link entirely rather than by
/// declining to follow it.
fn hrefs_after_click(
    editor: RichTextEditor,
    modifiers: teksilo_core::event::Modifiers,
) -> Vec<String> {
    use std::cell::RefCell;
    use std::rc::Rc;

    let seen = Rc::new(RefCell::new(Vec::<String>::new()));
    let seen_clone = seen.clone();
    let editor = editor
        .content_padding(0.0)
        .on_link_activated(move |href, _ctx| {
            seen_clone.borrow_mut().push(href.to_string());
        });

    let mut tree = WidgetTree::new();
    let _ = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    tree.dispatch_event(teksilo_core::event::WidgetEvent::PointerDown {
        position: Point::new(2.0, 2.0),
        button: teksilo_core::event::PointerButton::Primary,
        modifiers,
    });

    seen.borrow().clone()
}

#[test]
fn read_only_follows_a_link_on_a_plain_click() {
    let hrefs = hrefs_after_click(
        RichTextEditor::read_only(link_only_doc()),
        teksilo_core::event::Modifiers::NONE,
    );
    assert_eq!(
        hrefs,
        vec!["https://example.com/x".to_string()],
        "a read-only viewer must follow a link on an ordinary click — there is no caret to place, \
         so a link that ignores a plain click reads as broken"
    );
}

#[test]
fn an_editor_ignores_a_plain_click_on_a_link() {
    let hrefs = hrefs_after_click(
        RichTextEditor::editor(link_only_doc()),
        teksilo_core::event::Modifiers::NONE,
    );
    assert!(
        hrefs.is_empty(),
        "an editable surface must NOT follow a link on a plain click: that click places the caret, \
         and intercepting it leaves the text inside a link unreachable by pointer — got {hrefs:?}"
    );
}

#[test]
fn an_editor_follows_a_link_on_ctrl_click() {
    let hrefs = hrefs_after_click(
        RichTextEditor::editor(link_only_doc()),
        teksilo_core::event::Modifiers::CTRL,
    );
    assert_eq!(
        hrefs,
        vec!["https://example.com/x".to_string()],
        "Ctrl(Cmd)+click remains the editor's way to follow a link"
    );
}

#[test]
fn read_only_still_follows_a_link_on_ctrl_click() {
    // The viewer's plain-click rule *widens* the gate; it must not replace it.
    // A reader who has learned Ctrl+click elsewhere should not find it dead here.
    let hrefs = hrefs_after_click(
        RichTextEditor::read_only(link_only_doc()),
        teksilo_core::event::Modifiers::CTRL,
    );
    assert_eq!(
        hrefs,
        vec!["https://example.com/x".to_string()],
        "the read-only rule must widen the gate, not replace it"
    );
}

// ===========================================================================
// Regressions — RichTextEditor vertical caret motion & clipboard.
//
// Each test here pins one defect that shipped, and its doc comment says what
// the code used to do. They are grouped rather than scattered because they
// share two root causes: the engine answers caret geometry in two coordinate
// spaces at once, and the clipboard path had three places where a payload
// shape nobody had in front of them silently did nothing.
// ===========================================================================

/// Vertical caret motion: `move_cursor_vertical`'s range guard compares a
/// **screen-space** y against a **document-space** height.
#[cfg(test)]
mod regression_vertical {
    use super::*;
    use teksilo_core::event::{Key, Modifiers, WidgetEvent};

    const W: f32 = 400.0;
    const H: f32 = 130.0;

    fn settle(tree: &mut WidgetTree) {
        for _ in 0..3 {
            tree.request_frame();
            tree.tick_animations(std::time::Duration::from_millis(16));
            tree.layout(SizeProposal::exact(W, H));
        }
        let _ = tree.render();
    }

    fn press(tree: &mut WidgetTree, key: Key) {
        tree.dispatch_event(WidgetEvent::KeyDown {
            key,
            modifiers: Modifiers::NONE,
            text: None,
        });
        settle(tree);
    }

    struct Fixture {
        tree: WidgetTree,
        handle: crate::rich_text::EditorHandle,
        state: crate::rich_text::SharedState,
        scroll_y: teksilo_core::signal::Signal<f32>,
    }

    /// A self-scrolling editor: 120 px viewport over a document many times
    /// taller — the shape the `rich_text_editor` demo puts the editor in
    /// (a `Splitter` pane, no enclosing `ScrollArea`).
    fn fixture(text: &str) -> Fixture {
        let doc = TextDocument::new();
        doc.set_plain_text(text).unwrap();
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let editor = RichTextEditor::editor(doc);
        let handle = editor.handle();
        let state = editor.state_handle();
        let scroll_y = state.borrow().scroll_y.clone();
        {
            let mut s = state.borrow_mut();
            s.viewport_width = 380.0;
            s.viewport_height = 120.0;
            s.engine.set_viewport(380.0, 120.0);
            s.needs_full_layout = true;
        }
        let editor_id = tree.add(editor);
        let _box_id = tree.add(
            crate::primitives::FixedSize::new()
                .width(380.0)
                .height(120.0)
                .child_id(editor_id),
        );
        tree.layout(SizeProposal::exact(W, H));
        tree.focus(editor_id);
        settle(&mut tree);
        Fixture {
            tree,
            handle,
            state,
            scroll_y,
        }
    }

    fn numbered(n: usize) -> String {
        (0..n)
            .map(|i| format!("line {i:02} aaa"))
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// **ArrowUp stalls on every second press once the editor has scrolled.**
    ///
    /// `move_cursor_vertical` guards with
    /// `if target_y < 0.0 || target_y > st.engine.content_height() { return; }`.
    /// `target_y` comes from `engine.caret_rect`, which text-typeset documents
    /// as *screen-space* — `render/hit_test.rs::caret_rect_in_block` computes
    /// `caret_y = ... - scroll_offset`. `content_height()` is the document's
    /// total height, scroll-free. So once the editor is scrolled, the line
    /// above the caret has a **negative** screen y and the guard rejects a
    /// perfectly legal move.
    ///
    /// Trace (position, scroll_y) for successive ArrowUp presses:
    /// `408,582 → 408,565 → 396,565 → 396,549 → 384,549 …` — the caret only
    /// advances on alternate presses.
    #[test]
    fn arrow_up_advances_on_every_press_in_a_scrolled_editor() {
        let mut f = fixture(&numbered(60));
        f.handle.select_range(0, 0);
        settle(&mut f.tree);
        for _ in 0..40 {
            press(&mut f.tree, Key::ArrowDown);
        }
        let mut trace = Vec::new();
        for _ in 0..40 {
            press(&mut f.tree, Key::ArrowUp);
            trace.push(f.handle.cursor_position());
        }
        let stalls: Vec<usize> = trace
            .windows(2)
            .enumerate()
            .filter(|(_, w)| w[0] == w[1])
            .map(|(i, _)| i)
            .collect();
        assert!(
            stalls.is_empty(),
            "ArrowUp stalled at steps {stalls:?}; trace = {trace:?}"
        );
        assert_eq!(
            f.handle.cursor_position(),
            0,
            "40 downs then 40 ups must return to the top (scroll_y = {})",
            f.scroll_y.get()
        );
    }

    /// **The first ArrowDown after wheel-scrolling the caret out of view is
    /// swallowed.** Same guard, same coordinate-space mix-up: with the caret
    /// scrolled above the viewport its screen y is negative, so `target_y`
    /// (one line further down, still negative) trips `target_y < 0.0`.
    ///
    /// User-visible as "the down arrow doesn't move the caret".
    #[test]
    fn arrow_down_works_after_scrolling_the_caret_out_of_view() {
        let mut f = fixture(&numbered(60));
        f.handle.select_range(0, 0);
        settle(&mut f.tree);
        // Exactly what `mouse::handle_scroll` does for a wheel event.
        f.scroll_y.set(600.0);
        settle(&mut f.tree);
        let before = f.handle.cursor_position();
        press(&mut f.tree, Key::ArrowDown);
        assert!(
            f.handle.cursor_position() > before,
            "ArrowDown must move the caret even when the caret has been \
             scrolled out of view (stayed at {before})"
        );
    }

    /// **`caret_window_rect` subtracts the scroll offset twice.**
    ///
    /// `engine.caret_rect` already returns screen space, but
    /// `keyboard::caret_window_rect` does `viewport_origin.y + caret[1] -
    /// scroll_y`. Its own doc comment asserts the opposite ("`caret_rect`
    /// returns engine/content-local coordinates"). The rect feeds the OS IME
    /// candidate window, `chase_caret_into_view` (the enclosing-ScrollArea
    /// follow) and the typewriter pin — all off by `scroll_y`.
    ///
    /// Measured: `scroll_y = 400`, raw caret y = `-400`, reported window y =
    /// `-796`, actual painted y = `-396`.
    #[test]
    fn caret_window_rect_matches_the_painted_caret() {
        let mut f = fixture(&numbered(60));
        f.handle.select_range(0, 0);
        settle(&mut f.tree);
        f.scroll_y.set(400.0);
        settle(&mut f.tree);

        let st = f.state.borrow();
        let win = crate::rich_text::keyboard::caret_window_rect(&st).expect("focused, laid out");
        // The caret sits at document y = 0, so it paints at
        // `viewport_origin.y - scroll_y`.
        let expected = st.viewport_origin.y - f.scroll_y.get();
        assert!(
            (win.y - expected).abs() < 1.0,
            "caret_window_rect reported y = {} but the caret paints at {} \
             (scroll_y = {})",
            win.y,
            expected,
            f.scroll_y.get()
        );
    }

    /// **The scroll-follow is computed from a one-keystroke-old caret.**
    ///
    /// `ensure_caret_visible` → `DocumentFlow::ensure_caret_visible` reads
    /// `self.cursors[0].position`, a cache written only by
    /// `DocumentFlow::set_cursor`. The widget calls `engine.set_cursor` in
    /// exactly two places — `frame_loop.rs` `tick()` and `rich_text.rs`
    /// `paint()` — and neither runs inside the key handler, so the correction
    /// keeps the *previous* caret in view and leaves the new one outside it.
    /// The frame loop deliberately does not re-run the follow, so the caret
    /// stays out of view until the next keystroke.
    ///
    /// Walking down a 120 px viewport with 16.9 px lines: press 6 puts the
    /// caret on line 7 (screen y 118.6, bottom 135.5 — below the fold) while
    /// `scroll_y` is still 0; press 7 finally scrolls, and by 23.5 px — the
    /// correction for **line 7**, not for the line 8 the caret is now on.
    #[test]
    fn arrow_down_keeps_the_caret_inside_the_viewport_on_every_press() {
        let mut f = fixture(&numbered(60));
        f.handle.select_range(0, 0);
        settle(&mut f.tree);

        for step in 0..12 {
            press(&mut f.tree, Key::ArrowDown);
            let (caret, vh, scroll) = {
                let st = f.state.borrow();
                (
                    st.engine
                        .caret_rect(st.cursor.position(), st.cursor_affinity),
                    st.viewport_height,
                    f.scroll_y.get(),
                )
            };
            assert!(
                caret[1] >= 0.0 && caret[1] + caret[3] <= vh + 0.5,
                "press {step}: after ArrowDown the caret spans screen y \
                 {}..{} but the viewport is 0..{vh} (scroll_y = {scroll}) — \
                 the scroll correction is a keystroke behind",
                caret[1],
                caret[1] + caret[3]
            );
        }
    }

    /// **`range_content_rect` is documented as scroll-free and is not.**
    ///
    /// `RichTextEditor::range_content_rect` promises "y = 0 at the top of the
    /// laid-out text, unaffected by scrolling", and its doc names the use case:
    /// divide by `content_height()` to get the fraction an overview strip
    /// draws against. But `keyboard::range_content_rect` builds the rect from
    /// `engine.caret_rect`, which has the scroll offset already subtracted — so
    /// the fraction moves as the reader scrolls.
    ///
    /// (`range_rect` / `offset_rect` have the mirror-image defect: they
    /// subtract the scroll a *second* time — see
    /// [`caret_window_rect_matches_the_painted_caret`].)
    #[test]
    fn range_content_rect_does_not_move_when_the_editor_scrolls() {
        let mut f = fixture(&numbered(60));
        settle(&mut f.tree);

        let at_top = {
            let st = f.state.borrow();
            crate::rich_text::keyboard::range_content_rect(&st, 0, 5).expect("laid out")
        };
        f.scroll_y.set(400.0);
        settle(&mut f.tree);
        let scrolled = {
            let st = f.state.borrow();
            crate::rich_text::keyboard::range_content_rect(&st, 0, 5).expect("laid out")
        };
        assert!(
            (at_top.y - scrolled.y).abs() < 0.5,
            "content-space y for offsets 0..5 moved from {} to {} when the \
             editor scrolled — an overview strip would draw the mark in the \
             wrong place",
            at_top.y,
            scrolled.y
        );
    }
}

/// Clipboard: internal (intra-app) copy / cut / paste.
#[cfg(test)]
mod regression_clipboard_internal {
    use super::*;
    use teksilo_core::event::{Key, Modifiers};
    use teksilo_text::text_document::{MoveMode, TextFormat};

    /// A backend with no HTML support — the trait's default bodies, which
    /// `teksilo-platform/src/clipboard.rs` documents as a supported degrade.
    #[derive(Default)]
    struct PlainOnly(std::rc::Rc<std::cell::RefCell<String>>);
    impl teksilo_platform::clipboard::ClipboardBackend for PlainOnly {
        fn get_text(&mut self) -> Result<String, String> {
            Ok(self.0.borrow().clone())
        }
        fn set_text(&mut self, text: &str) -> Result<(), String> {
            *self.0.borrow_mut() = text.to_string();
            Ok(())
        }
    }

    fn install<B: teksilo_platform::clipboard::ClipboardBackend + 'static>(
        tree: &mut WidgetTree,
        backend: B,
    ) {
        use std::any::TypeId;
        use std::collections::HashMap;
        use teksilo_core::event_source::TreeAppContext;
        use teksilo_platform::clipboard::ClipboardHandle;
        let mut registry: HashMap<TypeId, Box<dyn std::any::Any>> = HashMap::new();
        registry.insert(
            TypeId::of::<ClipboardHandle>(),
            Box::new(ClipboardHandle::new(backend)),
        );
        tree.set_app_context(std::rc::Rc::new(
            TreeAppContext::empty().with_app_state(registry),
        ));
    }

    fn is_bold_at(doc: &TextDocument, pos: usize) -> Option<bool> {
        let probe = doc.cursor();
        probe.set_position(pos, MoveMode::MoveAnchor);
        probe.char_format().unwrap_or_default().font_bold
    }

    /// **A multi-line paste is N undo steps, not one.**
    ///
    /// `insert_multiline_plain` issues one `insert_text` per line with an
    /// `insert_block` between them and never wraps the run in
    /// `begin_edit_block()` / `end_edit_block()` — unlike
    /// `nest_current_list_item` in `keyboard.rs`, which does. Pasting four
    /// lines therefore takes four Ctrl+Z presses to undo.
    #[test]
    fn a_multiline_paste_undoes_in_one_step() {
        let doc = TextDocument::new();
        doc.set_plain_text("").unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let mut tree = WidgetTree::new();
        let cb = ctx_with_memory_clipboard(&mut tree);
        cb.set_text("a\nb\nc\nd").unwrap();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        focus_editor(&mut tree, id);

        press_key(&mut tree, Key::V, Modifiers::CTRL);
        tick_past_debounce(&mut tree);
        assert_eq!(doc.to_plain_text().unwrap_or_default(), "a\nb\nc\nd");

        press_key(&mut tree, Key::Z, Modifiers::CTRL);
        tick_past_debounce(&mut tree);
        assert_eq!(
            doc.to_plain_text().unwrap_or_default().trim(),
            "",
            "one undo must remove the whole pasted block"
        );
    }

    /// **An intra-app copy/paste loses its formatting on a clipboard backend
    /// with no HTML support.**
    ///
    /// `paste()`'s self-round-trip branch is gated on `cb.has_html()`, so the
    /// bit-exact `DocumentFragment` sitting in `state.rich_clipboard_fragment`
    /// is never consulted. `state.rich_clipboard_plain` — written on every
    /// copy, read by no production code — exists for exactly the fallback
    /// `paste()`'s own doc comment describes ("if the system clipboard's
    /// plain text matches what this editor last copied") and which was never
    /// implemented.
    #[test]
    fn a_self_paste_keeps_formatting_without_an_html_payload() {
        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        let c = doc.cursor();
        c.set_position(0, MoveMode::MoveAnchor);
        c.set_position(5, MoveMode::KeepAnchor);
        let _ = c.set_char_format(&TextFormat {
            font_bold: Some(true),
            ..Default::default()
        });

        let editor = RichTextEditor::editor(doc.clone());
        let handle = editor.handle();
        let mut tree = WidgetTree::new();
        install(&mut tree, PlainOnly::default());
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        focus_editor(&mut tree, id);

        handle.select_range(0, 5);
        press_key(&mut tree, Key::C, Modifiers::CTRL);
        press_key(&mut tree, Key::End, Modifiers::CTRL);
        press_key(&mut tree, Key::V, Modifiers::CTRL);
        tick_past_debounce(&mut tree);

        let plain = doc.to_plain_text().unwrap_or_default();
        let pasted = plain.rfind("hello").expect("the pasted copy");
        assert_eq!(
            is_bold_at(&doc, pasted),
            Some(true),
            "an intra-app copy/paste must keep its formatting; got {plain:?}"
        );
    }

    /// **Paste-unformatted does nothing on an HTML-only clipboard.**
    ///
    /// `paste_unformatted` reads only `get_text()`; `can_paste()` reports
    /// `has_text() || has_html()`, so the command is offered and then no-ops.
    #[test]
    fn paste_unformatted_falls_back_to_the_html_payload() {
        let doc = TextDocument::new();
        doc.set_plain_text("").unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let mut tree = WidgetTree::new();
        let cb = ctx_with_memory_clipboard(&mut tree);
        cb.set_html("<p>rich</p>", "").unwrap();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        focus_editor(&mut tree, id);

        press_key(&mut tree, Key::V, Modifiers::CTRL | Modifiers::SHIFT);
        tick_past_debounce(&mut tree);
        assert!(
            !doc.to_plain_text().unwrap_or_default().is_empty(),
            "paste-unformatted inserted nothing from an html-only clipboard, \
             yet can_paste() reports true"
        );
    }
}

/// Clipboard: external interop — payloads as real applications publish them.
#[cfg(test)]
mod regression_clipboard_external {
    use super::*;
    use teksilo_core::event::{Key, Modifiers};

    fn paste_html(html: &str, plain: &str) -> TextDocument {
        let doc = TextDocument::new();
        doc.set_plain_text("").unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let mut tree = WidgetTree::new();
        let clipboard = ctx_with_memory_clipboard(&mut tree);
        clipboard.set_html(html, plain).unwrap();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        focus_editor(&mut tree, id);
        press_key(&mut tree, Key::V, Modifiers::CTRL);
        tick_past_debounce(&mut tree);
        doc
    }

    /// **A `<style>` block pastes as visible body text.**
    ///
    /// Word, Google Docs and Chrome all publish `text/html` as a full
    /// document with a `<style>` element. text-document's HTML walker
    /// (`common/src/parser_tools/content_parser.rs`) has no case for
    /// `head` / `style` / `script` / `title`, so they fall through the
    /// "inline element or unknown: recurse" arm and their raw text children
    /// become paragraphs.
    ///
    /// Got: `"Hello\nWorld\np.c1 { color: #ff0000; font-weight: 700 }\np.c2 { margin: 0 }"`.
    #[test]
    fn a_style_block_does_not_paste_as_body_text() {
        let doc = paste_html(
            "<html><head><meta charset=\"utf-8\"><style type=\"text/css\">\
             p.c1 { color: #ff0000; font-weight: 700 }\np.c2 { margin: 0 }\
             </style></head><body><!--StartFragment--><p class=\"c1\">Hello</p>\
             <p class=\"c2\">World</p><!--EndFragment--></body></html>",
            "Hello\nWorld",
        );
        let got = doc.to_plain_text().unwrap_or_default();
        assert!(got.contains("Hello") && got.contains("World"), "{got:?}");
        assert!(
            !got.contains("color:") && !got.contains("font-weight"),
            "the <style> CSS was inserted as literal text: {got:?}"
        );
    }

    /// **The self-round-trip marker survives a platform that wraps the payload.**
    ///
    /// `arboard`'s macOS backend puts everything handed to `set_html` inside
    /// `<html><head><meta …></head><body>…</body></html>` and returns the
    /// wrapper verbatim on read (`platform/osx.rs`). `payload_marker` used to
    /// be a strict `strip_prefix` at byte 0, so it never matched there and
    /// every intra-editor copy/paste on macOS silently fell through to
    /// re-parsing its own HTML — losing everything `to_html` cannot say.
    ///
    /// Font size is one such thing, which is what makes it the probe here: the
    /// fragment carries it, the HTML does not.
    ///
    /// (X11 and Wayland round-trip verbatim; Windows' CF_HTML reader slices to
    /// `StartFragment`, which lands exactly on the marker. Only macOS wraps.)
    #[test]
    fn the_self_copy_marker_survives_the_macos_pasteboard_wrapping() {
        use teksilo_text::text_document::{MoveMode, TextFormat};

        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        let sized = doc.cursor();
        sized.set_position(0, MoveMode::MoveAnchor);
        sized.set_position(5, MoveMode::KeepAnchor);
        let _ = sized.set_char_format(&TextFormat {
            font_point_size: Some(33),
            ..Default::default()
        });

        let editor = RichTextEditor::editor(doc.clone());
        let handle = editor.handle();
        let mut tree = WidgetTree::new();
        let clipboard = ctx_with_memory_clipboard(&mut tree);
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        focus_editor(&mut tree, id);

        handle.select_range(0, 5);
        press_key(&mut tree, Key::C, Modifiers::CTRL);

        // Re-publish exactly what NSPasteboard would hand back on macOS.
        let written = clipboard.get_html().expect("copy wrote an html payload");
        clipboard
            .set_html(
                &format!(
                    "<html><head><meta http-equiv=\"content-type\" \
                     content=\"text/html; charset=utf-8\"></head><body>{written}</body></html>"
                ),
                "hello",
            )
            .unwrap();

        press_key(&mut tree, Key::End, Modifiers::CTRL);
        press_key(&mut tree, Key::V, Modifiers::CTRL);
        tick_past_debounce(&mut tree);

        let plain = doc.to_plain_text().unwrap_or_default();
        let pasted = plain.rfind("hello").expect("the pasted copy");
        let probe = doc.cursor();
        probe.set_position(pasted, MoveMode::MoveAnchor);
        assert_eq!(
            probe.char_format().unwrap_or_default().font_point_size,
            Some(33),
            "the wrapped payload must still be recognised as this editor's own \
             copy, so the stored fragment is reinserted rather than the HTML \
             re-parsed; got {plain:?}"
        );
    }

    /// **Superscript and subscript do not survive HTML.**
    ///
    /// Neither direction handles them: `push_inline_html`
    /// (`text-document/crates/public_api/src/fragment.rs`) never emits
    /// `<sup>`/`<sub>` for `fmt_vertical_alignment`, and the HTML walker
    /// hard-codes `superscript: false` at every `ParsedSpan` site. So a
    /// formula copied out arrives flat, and one pasted in stays flat.
    #[test]
    fn superscript_survives_an_html_paste() {
        use teksilo_text::text_document::MoveMode;
        let doc = paste_html("<p>x<sup>2</sup></p>", "x2");
        let plain = doc.to_plain_text().unwrap_or_default();
        let two = plain.rfind('2').expect("the exponent");
        let probe = doc.cursor();
        probe.set_position(two, MoveMode::MoveAnchor);
        let fmt = probe.char_format().unwrap_or_default();
        assert_ne!(
            fmt.vertical_alignment,
            Some(teksilo_text::text_document::CharVerticalAlignment::Normal),
            "<sup> must import as superscript, got {:?}",
            fmt.vertical_alignment
        );
        assert!(
            fmt.vertical_alignment.is_some(),
            "<sup> must import as superscript, got None"
        );
    }
}

/// Two edits in one frame used to leave the document and the typesetter
/// disagreeing about where every later block starts.
#[cfg(test)]
mod regression_block_position_desync {
    use super::*;
    use teksilo_text::text_document::MoveMode;

    /// Click the far-left edge of every block's first line and report each one
    /// whose hit-test disagrees with the block's true start. A disagreement
    /// means the laid-out `position` has drifted from the document's, which is
    /// what makes a click land on the wrong character and a selection paint in
    /// the wrong place.
    ///
    /// The far-left edge specifically, not the block's own reported x: a block
    /// whose position has drifted reports a caret rect for its first character
    /// several characters into the line — so hit-testing *there* asks the two
    /// broken mappings to agree with each other, which they always do. Only an
    /// absolute coordinate catches the drift.
    ///
    /// Which is why table cells are skipped rather than probed: a cell has its
    /// own left origin (column 1 sits at x = 200), so the document's left edge
    /// lands in column 0 and the probe would report a drift that is entirely
    /// its own doing.
    fn desynced_blocks(doc: &TextDocument, state: &crate::rich_text::SharedState) -> Vec<String> {
        let st = state.borrow();
        let mut bad = Vec::new();
        for b in doc.blocks() {
            if st.engine.is_block_in_table(b.id()) {
                continue;
            }
            let pos = b.position();
            let r = st
                .engine
                .caret_rect(pos, teksilo_text::CursorAffinity::Downstream);
            let hit = st
                .engine
                .hit_test(0.5, r[1] + r[3] * 0.5)
                .map(|h| h.position);
            if hit != Some(pos) {
                bad.push(format!(
                    "{:?} starts at {pos} but its left edge hit-tests to {hit:?}",
                    b.text().chars().take(20).collect::<String>()
                ));
            }
        }
        bad
    }

    fn editor_with(text: &str) -> (TextDocument, WidgetTree, crate::rich_text::SharedState) {
        let doc = TextDocument::new();
        doc.set_plain_text(text).unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let state = editor.state_handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(420.0, 400.0));
        focus_editor(&mut tree, id);
        tick_past_debounce(&mut tree);
        let _ = tree.render();
        (doc, tree, state)
    }

    fn insert_at(doc: &TextDocument, at: usize, text: &str) {
        let c = doc.cursor_at(at);
        c.set_position(at, MoveMode::MoveAnchor);
        let _ = c.insert_text(text);
    }

    /// **Two single-block edits arriving in one frame.**
    ///
    /// `drain_events` reports at most one block position for the incremental
    /// relayout, and it used to keep whichever `ContentsChanged` arrived last.
    /// The other edit was then never laid out — and the character-position
    /// shift that runs after a relayout, which moves every following block's
    /// `position` by the edit's length, never ran for it either. From then on
    /// the typesetter placed every later block N characters earlier than the
    /// document did.
    ///
    /// What that looks like to a writer, with N = 4: the first four characters
    /// of the next paragraph cannot be clicked (the caret lands on the fourth),
    /// selecting the word just typed paints a phantom highlight of the same
    /// width at the start of the paragraph below, and selections in that
    /// paragraph are drawn four characters to the left of the words they cover.
    #[test]
    fn two_edits_in_one_frame_keep_the_layout_and_the_document_agreeing() {
        let (doc, mut tree, state) =
            editor_with("Premier paragraphe ici.\nDeuxieme paragraphe ici.\nTroisieme ici.");
        assert!(
            desynced_blocks(&doc, &state).is_empty(),
            "precondition: a freshly laid-out document agrees with itself"
        );

        let blocks = doc.blocks();
        let (first, third) = (blocks[0].position(), blocks[2].position());
        // No tick between them, so both events land in one drain.
        insert_at(&doc, first, "AAAA");
        insert_at(&doc, third + 4, "BB");
        tick_past_debounce(&mut tree);
        let _ = tree.render();

        let bad = desynced_blocks(&doc, &state);
        assert!(bad.is_empty(), "after two edits in one frame: {bad:?}");
    }

    /// Two edits at the *same* position still take the incremental path — they
    /// describe one block, and one relayout from the final document is exactly
    /// right. Pinned so the fix above cannot quietly become "any second event
    /// forces a full layout", which would put a whole-document relayout on the
    /// typing path.
    #[test]
    fn two_edits_at_one_position_still_relayout_incrementally() {
        let (doc, mut tree, state) =
            editor_with("Premier paragraphe ici.\nDeuxieme paragraphe ici.");
        let at = doc.blocks()[0].position();
        insert_at(&doc, at, "AA");
        insert_at(&doc, at, "BB");
        tick_past_debounce(&mut tree);
        let _ = tree.render();

        assert_eq!(
            doc.to_plain_text().unwrap(),
            "BBAAPremier paragraphe ici.\nDeuxieme paragraphe ici."
        );
        assert!(
            !state.borrow().needs_full_layout,
            "one block, one relayout — no full layout on the typing path"
        );
        let bad = desynced_blocks(&doc, &state);
        assert!(bad.is_empty(), "{bad:?}");
    }

    /// A table in the document disqualifies the rope fast path that resolves an
    /// edit position to its block, so typing near a paragraph boundary takes a
    /// different lookup. Probe it too.
    #[test]
    fn typing_after_a_table_keeps_the_following_paragraphs_clickable() {
        let (doc, mut tree, state) =
            editor_with("Avant le tableau.\nApres le tableau.\nEncore un paragraphe.");
        {
            let c = doc.cursor_at(0);
            c.set_position(0, MoveMode::MoveAnchor);
            let _ = c.insert_table(2, 2);
        }
        tick_past_debounce(&mut tree);
        let _ = tree.render();
        let bad = desynced_blocks(&doc, &state);
        assert!(
            bad.is_empty(),
            "precondition after inserting a table: {bad:?}"
        );

        let plain = doc.to_plain_text().unwrap();
        let at = plain.find("Apres le tableau.").expect("second paragraph")
            + "Apres le tableau.".chars().count();
        insert_at(&doc, at, "test");
        tick_past_debounce(&mut tree);
        let _ = tree.render();

        let bad = desynced_blocks(&doc, &state);
        assert!(
            bad.is_empty(),
            "after typing at a paragraph end past a table: {bad:?}"
        );
    }

    /// The ordinary path the writer takes: type a word at the end of a
    /// paragraph and click into the next one. This always worked; it is here so
    /// the fix is not mistaken for the whole story.
    #[test]
    fn typing_a_word_at_a_paragraph_end_leaves_the_next_paragraph_clickable() {
        let long = "Elle avait longtemps vecu dans une petite ville tranquille pres \
                    du fleuve, loin de tout, quelque part au Canada.";
        let (doc, mut tree, state) = editor_with(&format!(
            "{long}\nQuelqu'un s'approcha d'elle par derriere."
        ));
        let end_of_first = long.chars().count();
        insert_at(&doc, end_of_first, "test");
        tick_past_debounce(&mut tree);
        let _ = tree.render();

        let bad = desynced_blocks(&doc, &state);
        assert!(bad.is_empty(), "{bad:?}");
    }
}

/// The bug as reported: type a word at the end of one paragraph, then click into
/// the next one.
#[cfg(test)]
mod regression_recolor_reverts_block_position {
    use super::*;
    use teksilo_text::text_document::{BlockFormat, MoveMode};

    const P1: &str = "Elle avait longtemps vecu dans une petite ville tranquille pres du \
                      fleuve, loin de tout, quelque part au Canada.";
    const P2: &str = "Quelqu'un s'approcha d'elle par derriere et lui tapota l'epaule. \
                      Surprise, Claire se detendit en reconnaissant sa soeur, Marie.";
    const P3: &str = "Le lendemain, elles repartirent ensemble vers le nord.";

    fn build(
        indent: Option<i32>,
    ) -> (
        TextDocument,
        WidgetTree,
        crate::rich_text::SharedState,
        crate::rich_text::EditorHandle,
    ) {
        let doc = TextDocument::new();
        doc.set_plain_text(&format!("{P1}\n{P2}\n{P3}")).unwrap();
        if let Some(px) = indent {
            for b in doc.blocks() {
                let c = doc.cursor_at(b.position());
                c.set_position(b.position(), MoveMode::MoveAnchor);
                let _ = c.set_block_format(&BlockFormat {
                    text_indent: Some(px),
                    ..Default::default()
                });
            }
        }
        let editor = RichTextEditor::editor(doc.clone());
        let state = editor.state_handle();
        let handle = editor.handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(430.0, 400.0));
        focus_editor(&mut tree, id);
        tick_past_debounce(&mut tree);
        let _ = tree.render();
        (doc, tree, state, handle)
    }

    /// Leftmost glyph x, and the mid-y, of the FIRST line of `block_index`,
    /// read straight off the painted frame — the ground truth for "where the
    /// writer sees this paragraph start".
    fn first_line_of_block(
        doc: &TextDocument,
        state: &crate::rich_text::SharedState,
        block_index: usize,
    ) -> (f32, f32) {
        let mut st = state.borrow_mut();
        let bid = doc.blocks()[block_index].id();
        let info = st.engine.block_visual_info(bid).expect("laid out");
        st.engine.with_render_frame(|frame| {
            let mut in_block: Vec<&teksilo_text::TypesetterGlyphQuad> = frame
                .glyphs
                .iter()
                .filter(|g| g.screen[1] >= info.y - 1.0 && g.screen[1] < info.y + info.height)
                .collect();
            in_block.sort_by(|a, b| a.screen[1].partial_cmp(&b.screen[1]).unwrap());
            let top_y = in_block.first().map(|g| g.screen[1]).unwrap_or(info.y);
            let first_line: Vec<_> = in_block
                .iter()
                .filter(|g| (g.screen[1] - top_y).abs() < 2.0)
                .collect();
            let min_x = first_line
                .iter()
                .map(|g| g.screen[0])
                .fold(f32::INFINITY, f32::min);
            let h = first_line.first().map(|g| g.screen[3]).unwrap_or(12.0);
            (min_x, top_y + h * 0.5)
        })
    }

    /// **The reported bug, end to end.**
    ///
    /// Type a word at the end of paragraph 1, then click into paragraph 2 — with
    /// the ambient caret band on, which is what a writing app has on. The click
    /// retargets the band to paragraph 2, which recolours just that block; the
    /// recolour used to re-derive it wholesale from a base captured before the
    /// typing, putting its document position back where it was. From then on
    /// clicking paragraph 2 landed N characters early.
    #[test]
    fn typing_then_clicking_the_next_paragraph_with_the_band_on() {
        let doc = TextDocument::new();
        doc.set_plain_text(&format!("{P1}\n{P2}\n{P3}")).unwrap();
        let editor = RichTextEditor::editor(doc.clone());
        let state = editor.state_handle();
        let handle = editor.handle();
        let mut tree = WidgetTree::new();
        let id = tree.add(editor);
        tree.layout(SizeProposal::exact(430.0, 400.0));
        focus_editor(&mut tree, id);
        handle.set_caret_highlight(Some(super::caret_band::band(
            crate::rich_text::caret_highlight::CaretHighlightScope::Paragraph,
        )));
        tick_past_debounce(&mut tree);
        let _ = tree.render();

        // 1. Type "test" at the end of paragraph 1.
        let end_p1 = P1.chars().count();
        handle.select_range(end_p1, end_p1);
        tick_past_debounce(&mut tree);
        for ch in "test".chars() {
            press_char(&mut tree, ch);
        }
        tick_past_debounce(&mut tree);
        let _ = tree.render();

        let plain = doc.to_plain_text().unwrap();
        let p2 = plain.find("Quelqu").expect("second paragraph");

        // 2. Click into paragraph 2 — this is what retargets the band.
        let (x, y) = first_line_of_block(&doc, &state, 1);
        synth_pointer_down(&mut tree, x + 20.0, y);
        synth_pointer_up(&mut tree, x + 20.0, y);
        tick_past_debounce(&mut tree);
        let _ = tree.render();

        // 3. Now clicking paragraph 2's first character must land on it.
        let hit = state
            .borrow()
            .engine
            .hit_test(x + 0.5, y)
            .map(|h| h.position);
        assert_eq!(
            hit,
            Some(p2),
            "after typing above it and clicking into it, paragraph 2's first \
             character must still be reachable (p2 starts at {p2})"
        );
    }
}

/// A standing check that the typesetter's idea of where each block starts never
/// drifts from the document's, under long runs of ordinary editing.
///
/// Written to hunt a reported drift rather than to pin a known one, and it
/// earned its keep: with the `drain_events` fix reverted it finds the fault in
/// seed 0. Both faults it guards reached the writer the same way — a click
/// landing on the wrong character, a selection painted off the words it covers.
#[cfg(test)]
mod invariant_fuzz {
    use super::*;
    use teksilo_core::event::{Key, Modifiers};

    /// For every top-level block: clicking the far-left edge of its first line
    /// must return that block's own start offset. When it does not, the
    /// typesetter and the document disagree about where the block begins —
    /// which is what puts the caret on the wrong character and paints
    /// selections in the wrong place.
    fn invariant_violations(
        doc: &TextDocument,
        state: &crate::rich_text::SharedState,
    ) -> Vec<String> {
        let st = state.borrow();
        if !st.engine.has_full_layout() {
            return Vec::new();
        }
        let mut bad = Vec::new();
        for b in doc.blocks() {
            if st.engine.is_block_in_table(b.id()) {
                continue;
            }
            let pos = b.position();
            let r = st
                .engine
                .caret_rect(pos, teksilo_text::CursorAffinity::Downstream);
            if r[3] <= 0.0 {
                continue;
            }
            let hit = st
                .engine
                .hit_test(0.5, r[1] + r[3] * 0.5)
                .map(|h| h.position);
            if hit != Some(pos) {
                bad.push(format!(
                    "block {pos} {:?} -> left-edge hit {hit:?}",
                    b.text().chars().take(16).collect::<String>()
                ));
            }
        }
        bad
    }

    /// Select a range that lies wholly inside one block, and check that every
    /// painted Selection rect lands inside THAT block's vertical band.
    ///
    /// This is the half the hit-test probe cannot see: a highlight painted in
    /// the paragraph *below* the selected text is a paint-side mapping fault,
    /// and the reported bug shows exactly that — selecting a word paints a
    /// phantom band of the same width at the start of the next paragraph.
    fn stray_selection_rects(
        doc: &TextDocument,
        state: &crate::rich_text::SharedState,
        tree: &mut WidgetTree,
        handle: &crate::rich_text::EditorHandle,
    ) -> Vec<String> {
        let mut bad = Vec::new();
        let blocks = doc.blocks();
        for b in &blocks {
            let len = b.text().chars().count();
            if len < 6 {
                continue;
            }
            let (bid, pos) = (b.id(), b.position());
            let band = {
                let st = state.borrow();
                if st.engine.is_block_in_table(bid) {
                    continue;
                }
                // `block_visual_info` answers in content space; decoration rects
                // are screen space, with the scroll already taken off. Compare
                // like with like.
                let off = st.engine.scroll_offset();
                match st.engine.block_visual_info(bid) {
                    Some(i) => (i.y - off, i.y + i.height - off),
                    None => continue,
                }
            };
            handle.select_range(pos + 1, pos + 5);
            for _ in 0..3 {
                tree.request_frame();
                tree.tick_animations(std::time::Duration::from_millis(16));
                tree.layout(SizeProposal::exact(430.0, 160.0));
            }
            let _ = tree.render();
            let (strays, left_of_text) = state.borrow_mut().engine.with_render_frame(|frame| {
                let sel: Vec<&teksilo_text::DecorationRect> = frame
                    .decorations
                    .iter()
                    .filter(|d| {
                        d.kind == teksilo_text::TypesetterDecorationKind::Selection
                            && d.rect[3] > 0.0
                            && d.rect[2] > 0.0
                    })
                    .collect();
                let strays: Vec<(i64, i64)> = sel
                    .iter()
                    .filter(|d| {
                        d.rect[1] + d.rect[3] * 0.5 < band.0 - 1.0
                            || d.rect[1] + d.rect[3] * 0.5 > band.1 + 1.0
                    })
                    .map(|d| (d.rect[0].round() as i64, d.rect[1].round() as i64))
                    .collect();
                // Ground truth for "where the text is": the glyphs on the
                // same visual line as the highlight. A highlight that starts
                // left of the leftmost glyph on its own line is drawn off the
                // text it claims to cover.
                let mut left_of_text = Vec::new();
                for d in &sel {
                    let mid = d.rect[1] + d.rect[3] * 0.5;
                    let line_min_x = frame
                        .glyphs
                        .iter()
                        .filter(|g| mid >= g.screen[1] && mid <= g.screen[1] + g.screen[3])
                        .map(|g| g.screen[0])
                        .fold(f32::INFINITY, f32::min);
                    // 10 px of slack: a highlight legitimately starts at the
                    // pen position while the glyph's ink starts after its left
                    // side bearing, which is a few pixels. The fault being
                    // hunted is a whole-character shift (~34 px for four
                    // characters at this size), well clear of that.
                    if line_min_x.is_finite() && d.rect[0] < line_min_x - 10.0 {
                        left_of_text.push((d.rect[0].round() as i64, line_min_x.round() as i64));
                    }
                }
                (strays, left_of_text)
            });
            if !strays.is_empty() {
                bad.push(format!(
                    "selecting {}..{} (block band {:.0}..{:.0}) painted outside it at {strays:?}",
                    pos + 1,
                    pos + 5,
                    band.0,
                    band.1
                ));
            }
            if !left_of_text.is_empty() {
                bad.push(format!(
                    "selecting {}..{} painted left of the text on its own line \
                     (rect x, first glyph x): {left_of_text:?}",
                    pos + 1,
                    pos + 5
                ));
            }
        }
        bad
    }

    struct Lcg(u64);
    impl Lcg {
        fn next(&mut self, n: usize) -> usize {
            self.0 = self
                .0
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((self.0 >> 33) as usize) % n.max(1)
        }
    }

    #[test]
    fn editing_never_drifts_the_layout_from_the_document() {
        for seed in 0..8u64 {
            // A document long enough to scroll inside a small viewport, with a
            // first-line indent on every block — the shape in the report.
            let doc = TextDocument::new();
            // Every other seed uses an imported document with a blockquote (a
            // frame) and a list, which `set_plain_text` cannot build — those
            // take different branches in the incremental relayout.
            if seed % 2 == 1 {
                doc.set_plain_text("").unwrap();
                let c = doc.cursor_at(0);
                c.set_position(0, teksilo_text::text_document::MoveMode::MoveAnchor);
                let mut html = String::new();
                for i in 0..6 {
                    html.push_str(&format!(
                        "<p>Paragraphe {i}. Elle avait longtemps vecu dans une petite ville \
                         tranquille pres du fleuve, quelque part au Canada.</p>"
                    ));
                    if i == 2 {
                        html.push_str(
                            "<blockquote><p>Une citation, dans un cadre, qui occupe \
                             deux lignes au moins.</p></blockquote>",
                        );
                        html.push_str("<ul><li>premier</li><li>deuxieme</li></ul>");
                    }
                }
                let _ = c.insert_html(&html);
            } else {
                let body: String = (0..14)
                    .map(|i| {
                        format!(
                            "Paragraphe {i}. Elle avait longtemps vecu dans une petite ville \
                         tranquille pres du fleuve, loin de tout, quelque part au Canada."
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("\n");
                doc.set_plain_text(&body).unwrap();
                for b in doc.blocks() {
                    let c = doc.cursor_at(b.position());
                    c.set_position(
                        b.position(),
                        teksilo_text::text_document::MoveMode::MoveAnchor,
                    );
                    let _ = c.set_block_format(&teksilo_text::text_document::BlockFormat {
                        text_indent: Some(32),
                        ..Default::default()
                    });
                }
            }
            let editor = RichTextEditor::editor(doc.clone());
            let state = editor.state_handle();
            let handle = editor.handle();
            let scroll_y = state.borrow().scroll_y.clone();
            {
                let mut st = state.borrow_mut();
                st.viewport_width = 410.0;
                st.viewport_height = 140.0;
                st.engine.set_viewport(410.0, 140.0);
                st.needs_full_layout = true;
            }
            let mut tree = WidgetTree::new();
            let id = tree.add(editor);
            let _box = tree.add(
                crate::primitives::FixedSize::new()
                    .width(410.0)
                    .height(140.0)
                    .child_id(id),
            );
            tree.layout(SizeProposal::exact(430.0, 160.0));
            focus_editor(&mut tree, id);
            tick_past_debounce(&mut tree);
            let _ = tree.render();

            let mut rng = Lcg(seed.wrapping_mul(0x9E3779B97F4A7C15).wrapping_add(12345));
            let mut log: Vec<String> = Vec::new();
            for step in 0..30 {
                let len = doc.to_plain_text().unwrap().chars().count().max(1);
                let op = rng.next(10);
                let desc = match op {
                    0 => {
                        let at = rng.next(len);
                        handle.select_range(at, at);
                        for ch in "test".chars() {
                            press_char(&mut tree, ch);
                        }
                        format!("type \"test\" at {at}")
                    }
                    1 => {
                        // Type, then click WITHOUT letting the batch flush.
                        let at = rng.next(len);
                        handle.select_range(at, at);
                        for ch in "abcd".chars() {
                            press_char(&mut tree, ch);
                        }
                        let y = (rng.next(6) * 17) as f32 + 4.0;
                        synth_pointer_down(&mut tree, 3.0, y);
                        synth_pointer_up(&mut tree, 3.0, y);
                        format!("type \"abcd\" at {at} then click y={y} before the flush")
                    }
                    2 => {
                        let y = (rng.next(6) * 17) as f32 + 4.0;
                        let x = (rng.next(20) * 12) as f32;
                        synth_pointer_down(&mut tree, x, y);
                        synth_pointer_up(&mut tree, x, y);
                        format!("click ({x},{y})")
                    }
                    3 => {
                        let at = rng.next(len);
                        handle.select_range(at, at);
                        press_key(&mut tree, Key::Enter, Modifiers::NONE);
                        format!("Enter at {at}")
                    }
                    4 => {
                        let at = rng.next(len);
                        handle.select_range(at, at);
                        press_key(&mut tree, Key::Backspace, Modifiers::NONE);
                        format!("Backspace at {at}")
                    }
                    5 => {
                        press_key(&mut tree, Key::Z, Modifiers::CTRL);
                        "undo".to_string()
                    }
                    6 => {
                        let a = rng.next(len);
                        let b = (a + 1 + rng.next(12)).min(len);
                        handle.select_range(a, b);
                        press_key(&mut tree, Key::Delete, Modifiers::NONE);
                        format!("delete range {a}..{b}")
                    }
                    7 => {
                        let at = rng.next(len);
                        handle.select_range(at, at);
                        press_key(&mut tree, Key::ArrowDown, Modifiers::NONE);
                        format!("ArrowDown from {at}")
                    }
                    9 => {
                        let to = (rng.next(12) * 40) as f32;
                        scroll_y.set(to);
                        format!("scroll to {to}")
                    }
                    _ => {
                        // Two programmatic edits with no tick between them.
                        let a = rng.next(len);
                        let b = rng.next(len);
                        for at in [a, b] {
                            let c = doc.cursor_at(at);
                            c.set_position(at, teksilo_text::text_document::MoveMode::MoveAnchor);
                            let _ = c.insert_text("Z");
                        }
                        format!("two raw inserts at {a} and {b}")
                    }
                };
                log.push(desc.clone());
                for _ in 0..3 {
                    tree.request_frame();
                    tree.tick_animations(std::time::Duration::from_millis(16));
                    tree.layout(SizeProposal::exact(430.0, 160.0));
                }
                let _ = tree.render();

                let mut bad = invariant_violations(&doc, &state);
                // The painted-selection probe re-selects and re-renders once per
                // block, so it costs far more than the hit-test one. Every third
                // step keeps it cheap without losing it.
                if step % 3 == 0 {
                    bad.extend(stray_selection_rects(&doc, &state, &mut tree, &handle));
                }
                if !bad.is_empty() {
                    eprintln!("seed {seed}: VIOLATION at step {step} after: {desc}");
                    eprintln!("  history: {log:?}");
                    eprintln!("  violations: {bad:?}");
                    eprintln!("  text: {:?}", doc.to_plain_text().unwrap());
                    panic!("invariant broken");
                }
            }
        }
        eprintln!("no violations across 8 seeds x 30 steps");
    }
}

// ---------------------------------------------------------------------------
// reveal_range — the answer a caller holding several editors relies on.
// ---------------------------------------------------------------------------

/// Ask an editor to reveal `[0, 5)` through its handle, and report what it
/// answered. `run_with_event_context` returns nothing, so the answer comes back
/// through a cell.
fn reveal_answer(tree: &mut WidgetTree, handle: &super::EditorHandle) -> bool {
    use teksilo_core::window::NoopWindowOps;
    let answer = Rc::new(Cell::new(false));
    let sink = answer.clone();
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| {
        sink.set(handle.reveal_range(ctx, 0, 5));
    });
    answer.get()
}

#[test]
fn reveal_range_answers_false_for_a_dormant_editor() {
    // `reveal_range` promises that `false` means nothing was requested, and a
    // caller holding several editors over one document — two split panes, a
    // stream row and that row's own tab — stops at the first `true`. A parked
    // editor keeps the layout it had (`has_full_layout` is set once and never
    // cleared; parking clears focus, caret and band and nothing else), so it
    // used to locate the offset happily and answer `true` from behind a tab
    // nobody can see. The match was selected, the counter moved, and the
    // visible editor was never asked: "the viewport does not follow".
    let doc = TextDocument::new();
    doc.set_plain_text("Alpha Beta Gamma Delta Epsilon")
        .unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    // The paint pass is what runs the full layout the reveal needs.
    let _ = tree.render();

    assert!(
        reveal_answer(&mut tree, &handle),
        "on screen and laid out, the editor must report that it revealed the \
         range — without this the dormant assertion below could pass on an \
         editor that simply never laid out"
    );

    tree.set_dormant(id);
    tree.layout(SizeProposal::exact(400.0, 300.0));

    assert!(
        !reveal_answer(&mut tree, &handle),
        "parked dormant, the editor must answer false: it still holds a layout, \
         but nothing it scrolls is on screen, and a caller told `true` stops \
         looking for the editor that is"
    );

    // And it must come back. A dormancy answer that never clears would strand
    // every match in a tab the reader returns to.
    tree.activate(id);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let _ = tree.render();
    assert!(
        reveal_answer(&mut tree, &handle),
        "a re-activated editor must reveal again"
    );
}

/// Ask an editor to reveal *itself* through its handle, and report what it
/// answered.
fn reveal_widget_answer(tree: &mut WidgetTree, handle: &super::EditorHandle) -> bool {
    use teksilo_core::window::NoopWindowOps;
    let answer = Rc::new(Cell::new(false));
    let sink = answer.clone();
    tree.run_with_event_context(&mut NoopWindowOps, |ctx| {
        sink.set(handle.reveal_widget(ctx));
    });
    answer.get()
}

#[test]
fn reveal_widget_scrolls_a_row_that_has_never_been_painted() {
    // The stream deadlock: a Book is one scrolling page of one editor per row, and a
    // row below the fold is never painted, so its engine never runs a full layout.
    // `reveal_range` needs that layout to locate the match, so it answers `false` —
    // and it will answer `false` for ever, because the row is only painted once it is
    // on screen and it only comes on screen if something scrolls to it. Ctrl+F found
    // the match, the counter said "1 of 40", and the page did not move.
    //
    // `reveal_widget` is the way out: the arena knows where the row is laid out
    // whether or not its text has been shaped.
    use crate::ScrollArea;
    use crate::primitives::{FixedSize, TextWidget, VStack};

    let doc = TextDocument::new();
    doc.set_plain_text("Alpha Beta Gamma Delta Epsilon")
        .unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let editor_id = tree.add(editor);
    // 2000 px of other rows above it, so the row starts far below a 150 px viewport.
    let header = tree.add(
        FixedSize::new()
            .width(220.0)
            .height(2000.0)
            .child(TextWidget::new(lit!(""))),
    );
    let row = tree.add(
        FixedSize::new()
            .width(220.0)
            .height(300.0)
            .child_id(editor_id),
    );
    let content = tree.add(VStack::new().add_child(header).add_child(row));
    let page = ScrollArea::from_id(content).smooth_scrolling(false);
    let page_y = page.scroll_y_signal().clone();
    let _page = tree.add(page);

    let sz = SizeProposal::exact(220.0, 150.0);
    tree.layout(sz);
    // Deliberately no `render`: the paint pass is what runs the full layout, and the
    // whole point of this row is that it has never had one.

    assert!(
        !reveal_answer(&mut tree, &handle),
        "fixture sanity: an unpainted row must have no layout to reveal a range in — \
         without this the assertion below would be testing nothing"
    );
    assert_eq!(
        page_y.get(),
        0.0,
        "fixture sanity: the page must start at the top"
    );

    assert!(
        reveal_widget_answer(&mut tree, &handle),
        "a built, on-screen-eligible editor must accept a widget reveal even with no \
         text layout — that is the only thing that can bring the row on screen"
    );
    tree.layout(sz);

    assert!(
        page_y.get() > 0.0,
        "the page must have scrolled down to the row; still at {}",
        page_y.get()
    );
}

#[test]
fn reveal_widget_refuses_from_a_dormant_editor_and_before_the_first_build() {
    // The two answers a caller walking several editors over one document relies on.
    // A parked tab's editor still has bounds in the arena, so an ungated widget
    // reveal would scroll a container nobody can see and report success — and the
    // caller, told the row was revealed, stops looking for the editor that is on
    // screen. An editor that has never built has no widget at all.
    let doc = TextDocument::new();
    doc.set_plain_text("Alpha Beta Gamma").unwrap();
    let editor = RichTextEditor::editor(doc);
    let handle = editor.handle();

    let mut tree = WidgetTree::new();
    assert!(
        !reveal_widget_answer(&mut tree, &handle),
        "before its first build the editor is not mounted, so there is nothing to \
         scroll to"
    );

    let id = tree.add(editor);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    assert!(
        reveal_widget_answer(&mut tree, &handle),
        "fixture sanity: built and active, the editor must accept"
    );

    tree.set_dormant(id);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    assert!(
        !reveal_widget_answer(&mut tree, &handle),
        "parked dormant, the editor must refuse: nothing it is inside is on screen"
    );

    tree.activate(id);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    assert!(
        reveal_widget_answer(&mut tree, &handle),
        "and it must come back when the tab does"
    );
}