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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Rich text editor and viewer widget.
//!
//! Two construction presets share the same implementation: [`RichTextEditor::editor`]
//! provides a full editing surface (blinking caret, keyboard commands, clipboard,
//! undo/redo, `Role::MultilineTextInput`) and [`RichTextEditor::read_only`] is a
//! view-only surface (hidden caret, mutations rejected, `Role::Document`). Both
//! bind to an external [`TextDocument`]
//! via `on_change` subscriptions, so any number of editors and viewers can share
//! one document and observe each other's edits live.
//!
//! The widget owns a per-widget `RichTextEngine` (typesetter), and drives its own
//! scroll bars independently of `ScrollArea` to avoid the wrap/scrollbar circular
//! measurement dependency. Use [`RichTextEditor::min_lines`] /
//! [`RichTextEditor::max_lines`] to switch from greedy sizing to intrinsic
//! (messenger-composer) sizing. A detachable [`EditorHandle`] lets toolbars and
//! palette panels issue formatting commands from closures that cannot borrow the
//! editor directly.
//!
//! ```ignore
//! use teksilo_text::text_document::TextDocument;
//! let doc = TextDocument::new();
//! let editor = RichTextEditor::editor(doc)
//!     .min_lines(3)
//!     .max_lines(8)
//!     .wrap_mode(WrapMode::Word);
//! ```

pub mod caret_highlight;
mod clipboard;
mod context_menu;
mod find_session;
mod frame_loop;
// `pub(crate)` so the code editor can reuse the hit-test wrapper rather than
// re-deriving pointer-to-offset resolution. Both surfaces ask the same engine
// the same question; the answer should not have two implementations.
pub(crate) mod hit_test;
pub(crate) mod image_cache;
mod keyboard;
mod mouse;
pub(crate) mod paint;
mod policy;
mod state;

#[cfg(test)]
mod tests;
#[cfg(test)]
mod window_tests;

pub use context_menu::{
    INTENT_COPY, INTENT_CUT, INTENT_PASTE, INTENT_PASTE_UNFORMATTED, INTENT_SELECT_ALL,
};
pub use find_session::FindSession;
pub use hit_test::ContextTarget;
pub use policy::{
    AccessibilityRole, CaretPolicy, ClipboardPolicy, CommandFilter, EDITOR_PRESET, EditCommandKind,
    PolicyBundle, READ_ONLY_PRESET,
};

use std::cell::Cell;
use std::rc::Rc;

use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::build_context::BuildContext;
use teksilo_core::color_prop::ColorProp;
use teksilo_core::signal::Signal;
use teksilo_core::styles::{
    RichTextEditorStyle, RichTextEditorStyleConfig, SharedRichTextEditorStyle,
};
use teksilo_core::widget::{CursorIcon, LayoutContext, PaintContext, Widget, WidgetPlacement};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;
use teksilo_text::text_document::{
    Alignment, BlockFormat, CharVerticalAlignment, LinkExtent, ListStyle, MoveMode, ResourceType,
    SelectionType, TextDirection, TextDocument, TextFormat,
};
use teksilo_text::{
    EditorTypographyDefaults, FontRegistrar, RichTextEngine, SharedTypesetter, WrapMode,
};

use self::paint::{PaintParams, paint_frame};
use self::state::{EditorState, SharedState};
use crate::common::scroll::OverscrollBehavior;
use crate::scroll_bar::{ScrollBar, ScrollBarOrientation, ScrollBarVariant};
use crate::styles::RecipeRichTextEditorStyle;

/// Scroll bar visibility policy for [`RichTextEditor`], applied independently per axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScrollPolicy {
    /// Show the scroll bar only when content overflows the visible area (default).
    #[default]
    Auto,
    /// Always show the scroll bar, reserving gutter space even when content fits.
    AlwaysOn,
    /// Never show the scroll bar; useful when embedding the editor inside an outer
    /// `ScrollArea` or in headless tests.
    AlwaysOff,
}

/// How a piece of text reached the document — the **channel**, not the author.
///
/// Deliberately framework-generic, and deliberately small. These are the routes
/// a toolkit can actually observe: which input path the characters came down.
/// What that *means* is the application's to decide, and every application will
/// decide differently — a writing tool cares that dictation is not typing, a
/// code editor cares that a snippet is not either, and a form cares about none
/// of it. Teksilo says what it saw; it does not interpret.
///
/// ⚠ **Not evidence of who wrote anything.** Text typed one character at a time
/// was typed one character at a time, and that is the entire claim. Anything
/// further — who, or whether a person at all — is an inference this cannot make
/// and no consumer of it should pretend to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EditSource {
    /// Typed, one key at a time.
    Keyboard,
    /// The settled result of an IME composition — CJK/Kana candidate selection,
    /// a dead-key accent. Separate from [`Self::Keyboard`] because the
    /// characters that land are not the keys that were pressed.
    Ime,
    /// Pasted, as plain text or as HTML.
    Clipboard,
    /// Arrived through an assistive technology: AccessKit's `SetValue` or
    /// `ReplaceSelectedText`, which is how dictation and a braille display
    /// write.
    ///
    /// **Never folded into [`Self::Keyboard`].** For some people this *is*
    /// typing, and a toolkit that reported it as something else — or as nothing
    /// — would be quietly erasing how they work.
    Accessibility,
    /// Inserted by the application itself rather than by anything the person at
    /// the keyboard did: a template, a substitution, a completion.
    Programmatic,
}

/// The main rich text widget. Construct via [`RichTextEditor::read_only`]
/// (view/select only) or [`RichTextEditor::editor`] (full editing).
pub use self::state::TextAnnotationSpan;

pub struct RichTextEditor {
    state: SharedState,
    v_scroll_policy: ScrollPolicy,
    h_scroll_policy: ScrollPolicy,
    /// Whether to install the built-in context-menu factory during
    /// `build()`. Defaults to `true`. Set `false` via
    /// [`default_context_menu`](Self::default_context_menu) to suppress
    /// the default entirely (right-click then bubbles past the widget;
    /// `context_target_at` stays available for apps that render their
    /// own menu).
    default_context_menu_enabled: bool,
    /// User-supplied context-menu factory (see
    /// [`context_menu`](Self::context_menu)). When set, it takes
    /// precedence over the default factory regardless of
    /// `default_context_menu_enabled`. Taken out (via `Option::take`)
    /// during `build()` because `Box<dyn Fn>` is not `Clone`.
    custom_context_menu: Option<
        Box<
            dyn Fn(
                teksilo_canvas::Point,
                &mut teksilo_core::widget::EventContext,
            ) -> Option<Box<dyn teksilo_core::widget::Widget>>,
        >,
    >,
    /// Minimum visible-text height expressed in lines. When set,
    /// switches `size_that_fits` from greedy (consume the proposal)
    /// to **intrinsic** sizing — see [`min_lines`](Self::min_lines).
    min_lines: Option<u32>,
    /// Maximum visible-text height expressed in lines. Hard-caps
    /// the intrinsic height — see [`max_lines`](Self::max_lines).
    max_lines: Option<u32>,
    /// Per-call style override for the chrome (border, padding, focus
    /// ring). Replaces the theme-wide `style_slots.rich_text_editor`
    /// and the default [`RecipeRichTextEditorStyle`] for just this
    /// editor.
    style_override: Option<SharedRichTextEditorStyle>,
    /// Root of the composed subtree returned by
    /// [`RichTextEditorStyle::make_body`]. Cached so layout queries
    /// route through the chrome without re-running the style call.
    root_child_id: Option<WidgetId>,
    /// Vertical scrollbar child id. `None` when
    /// `v_scroll_policy == ScrollPolicy::AlwaysOff` — in that case
    /// the scrollbar isn't even instantiated.
    v_scrollbar_id: Option<WidgetId>,
    /// Horizontal scrollbar child id. `None` when
    /// `h_scroll_policy == ScrollPolicy::AlwaysOff`.
    h_scrollbar_id: Option<WidgetId>,
    /// Scrollbar window-space bounds, written by `place_children` and
    /// read by the wrapper's `on_pointer_event` handler. Used to bail
    /// out of the drag-select latch when the press lands over an
    /// overlay scrollbar — without this guard the preview-pass pointer
    /// handler on the wrapper runs *before* the scrollbar (its child)
    /// gets the event, sets `drag_state = Selecting` on text under the
    /// overlay, and then steals every subsequent `PointerMove` with
    /// `EventResponse::Handled`, so the scrollbar's gesture arena
    /// never sees the drag.
    v_scrollbar_bounds: Rc<Cell<Rect>>,
    h_scrollbar_bounds: Rc<Cell<Rect>>,
    /// Per-edge `(top, right, bottom, left)` padding between the text
    /// content and the chrome. `None` lets the style apply its own
    /// default (TextInput-style insets for editable, no padding for
    /// read-only). Set via [`content_padding`](Self::content_padding) /
    /// [`content_padding_symmetric`](Self::content_padding_symmetric) /
    /// [`content_padding_each`](Self::content_padding_each).
    content_padding: Option<(f32, f32, f32, f32)>,
    /// Wheel scroll-chaining behavior at the editor's scroll boundary.
    /// [`OverscrollBehavior::Chain`] (the default) declines a wheel event the
    /// editor can no longer absorb so it bubbles to an ancestor scrollable —
    /// the editor embedded in a scrolling form/page hands the leftover scroll
    /// to the page. [`OverscrollBehavior::Contain`] absorbs the event at the
    /// boundary instead. Mirrors the identical knob on `ScrollArea` /
    /// `ListView` / `TableView` / `GridView`. See
    /// [`overscroll_behavior`](Self::overscroll_behavior).
    overscroll_behavior: OverscrollBehavior,
}

impl std::fmt::Debug for RichTextEditor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RichTextEditor")
            .field("policy", &self.state.borrow().policy)
            .finish_non_exhaustive()
    }
}

impl RichTextEditor {
    /// Construct a read-only rich text viewer bound to `document`. The
    /// document can also back an editable `RichTextEditor::editor` in
    /// another part of the UI — both widgets receive document events
    /// independently via `on_change` subscriptions.
    pub fn read_only(document: TextDocument) -> Self {
        // A viewer defaults to *bare*: it can mirror the same shared document
        // as an editor pane, but stays free of the document's search / spell /
        // syntax highlighting (those are authoring affordances). Opt back in
        // with `.show_highlights(true)` — e.g. a read-only code viewer that
        // *wants* syntax coloring.
        Self::construct(document, READ_ONLY_PRESET).show_highlights(false)
    }

    /// Construct an editable rich text editor bound to `document`.
    /// Uses the full editor preset: every command accepted, caret
    /// blinks, `MultilineTextInput` accessibility role, full clipboard
    /// support. Multiple editors on the same document share live edits
    /// via per-widget `on_change` subscriptions.
    pub fn editor(document: TextDocument) -> Self {
        Self::construct(document, EDITOR_PRESET)
    }

    fn construct(document: TextDocument, policy: PolicyBundle) -> Self {
        // Start with a private engine. `build()` swaps it for one that
        // shares the application's `SharedTypesetter` when one is
        // reachable via `ctx.app_state`, so rendered glyphs land in
        // the atlas that teksilo-render actually uploads to the GPU.
        // Outside a windowed teksilo-app (headless tests) the private
        // engine is correct: no renderer is ever invoked.
        let mut engine = RichTextEngine::private_default();
        engine.set_wrap_mode(WrapMode::Word);
        // Prose editor: hyphenate justified paragraphs. Single-line / label
        // widgets (e.g. TextInputField) deliberately don't enable this.
        engine.set_hyphenate_justified(true);
        let state = EditorState::new(document, engine, policy, WrapMode::Word);
        Self {
            state,
            v_scroll_policy: ScrollPolicy::Auto,
            h_scroll_policy: ScrollPolicy::Auto,
            default_context_menu_enabled: true,
            custom_context_menu: None,
            min_lines: None,
            max_lines: None,
            style_override: None,
            root_child_id: None,
            v_scrollbar_id: None,
            h_scrollbar_id: None,
            v_scrollbar_bounds: Rc::new(Cell::new(Rect::ZERO)),
            h_scrollbar_bounds: Rc::new(Cell::new(Rect::ZERO)),
            content_padding: None,
            overscroll_behavior: OverscrollBehavior::default(),
        }
    }

    /// Per-call style override for the editor chrome (border, padding,
    /// focus ring). Replaces the theme-wide
    /// `style_slots.rich_text_editor` and the IntUI default
    /// `RecipeRichTextEditorStyle` for just this editor.
    pub fn style(mut self, style: impl RichTextEditorStyle) -> Self {
        self.style_override = Some(Rc::new(style));
        self
    }

    /// Set a uniform padding (logical pixels) between the text content
    /// and the editor's chrome. Replaces the style's default insets
    /// (TextInput-style for editable, none for read-only). Use
    /// [`content_padding_symmetric`](Self::content_padding_symmetric) or
    /// [`content_padding_each`](Self::content_padding_each) for
    /// per-axis / per-edge control.
    pub fn content_padding(mut self, amount: f32) -> Self {
        self.content_padding = Some((amount, amount, amount, amount));
        self
    }

    /// Set vertical and horizontal padding (logical pixels) between the
    /// text content and the editor's chrome. Replaces the style's
    /// default insets.
    pub fn content_padding_symmetric(mut self, vertical: f32, horizontal: f32) -> Self {
        self.content_padding = Some((vertical, horizontal, vertical, horizontal));
        self
    }

    /// Set per-edge padding `(top, right, bottom, left)` between the
    /// text content and the editor's chrome. Replaces the style's
    /// default insets.
    pub fn content_padding_each(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
        self.content_padding = Some((top, right, bottom, left));
        self
    }

    /// Set just the top inset between the text and the chrome. Leaves
    /// the other edges at their previously-set values, defaulting to
    /// `0.0` for any edge never touched.
    pub fn content_padding_top(mut self, top: f32) -> Self {
        let (_, r, b, l) = self.content_padding.unwrap_or((0.0, 0.0, 0.0, 0.0));
        self.content_padding = Some((top, r, b, l));
        self
    }

    /// Set just the right inset between the text and the chrome.
    pub fn content_padding_right(mut self, right: f32) -> Self {
        let (t, _, b, l) = self.content_padding.unwrap_or((0.0, 0.0, 0.0, 0.0));
        self.content_padding = Some((t, right, b, l));
        self
    }

    /// Set just the bottom inset between the text and the chrome.
    pub fn content_padding_bottom(mut self, bottom: f32) -> Self {
        let (t, r, _, l) = self.content_padding.unwrap_or((0.0, 0.0, 0.0, 0.0));
        self.content_padding = Some((t, r, bottom, l));
        self
    }

    /// Set just the left inset between the text and the chrome.
    pub fn content_padding_left(mut self, left: f32) -> Self {
        let (t, r, b, _) = self.content_padding.unwrap_or((0.0, 0.0, 0.0, 0.0));
        self.content_padding = Some((t, r, b, left));
        self
    }

    // --- Builder methods ------------------------------------------------

    /// Set the line-wrap mode. `WrapMode::Word` (the default) wraps at word
    /// boundaries; `WrapMode::None` allows horizontal overflow — pair with
    /// `.h_scroll_policy(ScrollPolicy::Auto)` to expose a scroll bar.
    pub fn wrap_mode(self, mode: WrapMode) -> Self {
        {
            let mut st = self.state.borrow_mut();
            st.wrap_mode = mode;
            st.engine.set_wrap_mode(mode);
            st.needs_full_layout = true;
        }
        self
    }

    /// Whether this view applies the document's syntax / search / spell
    /// highlighting. `editor` defaults to `true`; `read_only` defaults to
    /// `false` (a bare preview). A highlights-off view pulls a *clean*
    /// snapshot (no highlights at all, even metric ones like keyword bold) and
    /// ignores paint-only highlight events entirely, so it does zero work when
    /// the shared document's search/spell highlights change.
    pub fn show_highlights(self, show: bool) -> Self {
        {
            let mut st = self.state.borrow_mut();
            if st.show_highlights != show {
                st.show_highlights = show;
                // Re-pull the snapshot in the new flavor on the next tick.
                st.needs_full_layout = true;
            }
        }
        self
    }

    /// Declare the annotations (comment threads) covering ranges of this
    /// document, for the **accessibility tree only**.
    ///
    /// Each span becomes a `Role::Comment` node, and every `Role::TextRun` it
    /// covers points at it through AccessKit's `details` relation — the W3C
    /// annotations pattern, and the reason a screen reader can say "has comment"
    /// and let the user navigate in rather than reciting the thread every time the
    /// caret crosses the span.
    ///
    /// Painting is a separate concern: a highlight session draws the underline. A
    /// highlight carries no text and this carries no colour, so neither is
    /// derivable from the other and both are supplied independently.
    pub fn annotation_spans(self, spans: Vec<TextAnnotationSpan>) -> Self {
        self.state.borrow_mut().annotation_spans = spans;
        self
    }

    /// Set which highlight sessions **this view** renders, at runtime.
    ///
    /// [`HighlightMask::all`](teksilo_text::text_document::HighlightMask::all) shows every
    /// session on the document (the default);
    /// [`HighlightMask::only`](teksilo_text::text_document::HighlightMask::only) shows a
    /// chosen set — which is how a per-editor find banner
    /// keeps one pane's find highlighting out of another pane over the same document.
    /// `show_highlights(false)` still overrides this to nothing.
    ///
    /// Forces a re-pull on the next tick so the change is visible immediately.
    pub fn set_highlight_mask(&self, mask: teksilo_text::text_document::HighlightMask) {
        let mut st = self.state.borrow_mut();
        if st.highlight_mask != mask {
            st.highlight_mask = mask;
            st.needs_full_layout = true;
            // A mask change fires no document event, so the AT-cache invalidation the
            // event path does won't run — do it here. Dropping a metric session (syntax
            // bold) out of this view changes what the AT tree should report, and a stale
            // cached tree would keep announcing formatting the pane no longer draws.
            st.invalidate_accessibility_cache();
        }
    }

    /// Set the initial non-destructive default typography (font family / line
    /// height / first-line indent) applied to runs and blocks that carry no
    /// explicit override. Applied before the first layout. These are display
    /// defaults — they never mutate the bound document (no undo entry, no
    /// `modified`); use [`set_typography_defaults`](Self::set_typography_defaults)
    /// or [`EditorHandle::set_typography_defaults`] to change them after mount.
    /// Preferred text size is [`font_size_scale`](Self::font_size_scale).
    pub fn typography_defaults(self, defaults: EditorTypographyDefaults) -> Self {
        {
            let mut st = self.state.borrow_mut();
            st.engine.set_typography_defaults(defaults);
            st.needs_full_layout = true;
        }
        self
    }

    /// Override the editor background fill. Accepts a `Color`, a theme role
    /// (`SurfaceRole::Content`, …), or a `Signal`. Threaded into the active
    /// [`RichTextEditorStyle`]'s `make_body`, so the common case ("give the
    /// editor a surface") needs no custom style. `None` uses the style's
    /// default surface.
    pub fn background(self, color: impl Into<ColorProp>) -> Self {
        self.state.borrow_mut().background_prop = Some(color.into());
        self
    }

    /// Override the selection-highlight color. Accepts a `Color`, theme role,
    /// or `Signal`. Resolved against the active theme on every paint; `None`
    /// uses the engine/theme default.
    pub fn selection_color(self, color: impl Into<ColorProp>) -> Self {
        self.state.borrow_mut().selection_color_prop = Some(color.into());
        self
    }

    /// Override the caret / insertion-point color. Accepts a `Color`, theme
    /// role, or `Signal`. Resolved against the active theme on every paint;
    /// `None` tracks the theme's `editor_caret` role.
    pub fn caret_color(self, color: impl Into<ColorProp>) -> Self {
        self.state.borrow_mut().caret_color_prop = Some(color.into());
        self
    }

    /// Override the default text color. Accepts a `Color`, theme role, or
    /// `Signal`. Resolved against the active theme on every paint; `None`
    /// tracks the theme's `editor_fg` role (so dark / light swaps follow
    /// automatically). A role or `Signal` stays reactive; a bare `Color` pins
    /// it.
    pub fn text_color(self, color: impl Into<ColorProp>) -> Self {
        self.state.borrow_mut().text_color_prop = Some(color.into());
        self
    }

    /// Set the vertical scroll-bar visibility policy.
    pub fn v_scroll_policy(mut self, policy: ScrollPolicy) -> Self {
        self.v_scroll_policy = policy;
        self
    }

    /// Set the horizontal scroll-bar visibility policy.
    pub fn h_scroll_policy(mut self, policy: ScrollPolicy) -> Self {
        self.h_scroll_policy = policy;
        self
    }

    /// Window paint-time culling to the accumulated ancestor clip rather than
    /// this editor's own bounds.
    ///
    /// Enable this **only** for an editor deliberately laid out at its full
    /// document height inside an outer [`ScrollArea`](crate::ScrollArea)
    /// (`v_scroll_policy(ScrollPolicy::AlwaysOff)`, no `max_lines`) — "dubious
    /// mode". Such an editor's own viewport spans the whole document, so the
    /// viewport-derived render cull keeps nothing; this makes it cull to the
    /// visible clip band instead, so a huge document only rasterizes the rows on
    /// screen. Correct under nested ScrollAreas (the clip is the intersection of
    /// all clipping ancestors), and positioning / hit-testing are unaffected.
    ///
    /// A normal self-scrolling editor already culls correctly from its own scroll
    /// offset and doesn't need this — leave it **off** (the default). (The window
    /// is computed relative to the editor's own scroll offset as well, so enabling
    /// it on a self-scroller degrades to a correct-but-redundant cull rather than
    /// rendering the wrong rows.)
    /// Guess this editor's height from its text until something has laid it out.
    ///
    /// `content_height()` is `0` until `layout_full` has run, and that waits for the
    /// editor to have been through a frame on screen. The zero falls through to the
    /// `min_lines` floor, so an editor that has never been shown claims the same few
    /// lines whatever it holds.
    ///
    /// For an editor that **is** on screen that is invisible — it lays out on the
    /// first frame and the floor never shows. Turn this on for one that may not be:
    /// a row of a long column, most of which is below the fold. There the page's
    /// height is the sum of its rows' claims, so the scroll extent starts wrong by an
    /// order of magnitude and settles a row at a time as the reader arrives — and
    /// anything drawing that extent draws the settling.
    ///
    /// Off by default, deliberately. The estimate is crude by construction, and an
    /// editor that lays out immediately gains nothing from it while every consumer of
    /// its first-frame size pays for the guess — including the windowed-render path,
    /// whose culling is derived from the editor's own bounds.
    ///
    /// Never a floor: it goes through the same clamp a real height does, so
    /// `max_lines` still caps it and an over-estimate corrects downwards when the
    /// layout lands.
    pub fn estimate_height_before_layout(self, on: bool) -> Self {
        self.state.borrow_mut().estimate_height_before_layout = on;
        self
    }

    pub fn window_to_clip(self, on: bool) -> Self {
        self.state.borrow_mut().window_to_clip = on;
        self
    }

    /// Set the same scroll-bar visibility policy on both axes.
    pub fn scroll_policy(mut self, policy: ScrollPolicy) -> Self {
        self.v_scroll_policy = policy;
        self.h_scroll_policy = policy;
        self
    }

    /// Whether moving the caret also scrolls any *enclosing* scroll area to
    /// keep the caret on screen — the standard editor "caret stays visible as
    /// you type / navigate" behaviour. **On by default.**
    ///
    /// It fires only on a caret *move*, never on a plain wheel / scrollbar
    /// scroll, so the reader can still scroll freely away from the caret and the
    /// view holds until the caret next moves. This is what makes an editor that
    /// **grows** to its content with its own scroll suppressed (a flowing page
    /// inside an outer `ScrollArea`) track the caret at all — there the editor's
    /// internal caret-visibility is a no-op, so the enclosing-page follow is the
    /// only mechanism that reveals the caret. Pass `false` for the rare layout
    /// where a caret change must never move the surrounding page.
    pub fn follow_caret_in_page(self, follow: bool) -> Self {
        self.state.borrow_mut().follow_caret_in_page = follow;
        self
    }

    /// **Typewriter scrolling**: pin the caret's line at `fraction` of the way
    /// down the enclosing scroll area — `0.0` at the top, `0.5` centred, `1.0`
    /// at the bottom — and let the document scroll under it. `None` (the
    /// default) leaves the ordinary minimal-reveal follow in charge.
    ///
    /// Unlike that follow, which only acts once the caret would leave the
    /// viewport, a pin re-asserts on every caret move, so the line being written
    /// holds a constant height on screen. The classic writing-app feature.
    ///
    /// Three behaviours come with it, each of them the consensus answer among
    /// the editors that ship this well:
    ///
    /// - **The pointer stands the pin down.** A click places the caret without
    ///   scrolling, and that position becomes the new resting place; a
    ///   drag-selection is never interrupted. The next keystroke resumes
    ///   pinning. Editors that re-centre on pointer input instead have open bugs
    ///   about the view fighting the mouse and about drag-selection becoming
    ///   unusable.
    /// - **The rendered row is pinned, not the paragraph.** Under soft wrap a
    ///   long paragraph spans several visual rows; pinning the logical line
    ///   would leave the caret far from the mark.
    /// - **Typing snaps, page jumps glide.** Animating a pin that updates on
    ///   every keystroke is what produces the "screen bouncing" complaint other
    ///   implementations attract.
    ///
    /// Requires [`follow_caret_in_page`](Self::follow_caret_in_page) (on by
    /// default). `fraction` is clamped to `0.0..=1.0`.
    ///
    /// Near the start of the document the pin gives way to the scroll range —
    /// the caret rides above its line until there is room — and near the end it
    /// would do the same, which is usually not what you want: pair this with
    /// `ScrollArea::scroll_past_end(1.0 - fraction)` so the last line can still
    /// reach the pin.
    ///
    /// Takes a plain value, like [`typography_defaults`](Self::typography_defaults);
    /// to follow a setting live, push changes onto the handle with
    /// [`EditorHandle::set_typewriter`].
    pub fn typewriter(self, anchor: Option<f32>) -> Self {
        self.state.borrow_mut().typewriter = anchor.map(|f| f.clamp(0.0, 1.0));
        self
    }

    /// Set the wheel scroll-chaining behavior at the editor's boundary
    /// (default [`OverscrollBehavior::Chain`]). With `Chain`, a wheel event the
    /// editor can no longer absorb (already at the top/bottom, or content that
    /// fits so there is nothing to scroll) is declined so it bubbles to an
    /// ancestor scrollable — an editor embedded in a scrolling form/page lets
    /// the page scroll once the editor reaches its edge.
    /// [`OverscrollBehavior::Contain`] keeps the event at the editor instead.
    /// Mirrors the identical knob on `ScrollArea` / `ListView` / `TableView` /
    /// `GridView`.
    pub fn overscroll_behavior(mut self, behavior: OverscrollBehavior) -> Self {
        self.overscroll_behavior = behavior;
        self
    }

    /// Set a minimum height (in lines of text) for the editor's
    /// **intrinsic** size.
    ///
    /// Setting either `min_lines` or [`max_lines`](Self::max_lines)
    /// switches the editor from greedy sizing (consume the
    /// proposal) to intrinsic sizing: `size_that_fits` returns
    /// `clamp(content_height, min_lines × line_height, max_lines × line_height)`
    /// for the dimension the parent leaves unspecified. A parent
    /// like `VStack` proposes unbounded height to non-Expand
    /// children, so the editor lands at its intrinsic height —
    /// exactly the messenger-composer / chat-input pattern.
    ///
    /// A parent that *forces* the height (e.g. `FixedSize`) wins
    /// regardless. This is intentional and matches Teksilo's
    /// general layout discipline: parents always have the final
    /// say on the dimensions they pin.
    ///
    /// `min_lines` measures the *visible text area*, not the outer
    /// widget — `min_lines(1)` reports a height equal to one line
    /// of text at the typesetter's default font + size, even
    /// before the document has any content.
    pub fn min_lines(mut self, n: u32) -> Self {
        self.min_lines = Some(n);
        self
    }

    /// Set a maximum height (in lines of text) for the editor's
    /// intrinsic size. Past this cap the vertical scroll bar
    /// absorbs further content growth.
    ///
    /// See [`min_lines`](Self::min_lines) for the intrinsic-mode
    /// switch and the parent-proposal interaction. `max_lines`
    /// measures the visible text area, not the outer widget.
    pub fn max_lines(mut self, n: u32) -> Self {
        self.max_lines = Some(n);
        self
    }

    /// Whether this editor's text grows with the global accessibility text
    /// scale (`ctx.text_scale`). Defaults to `true` — like every other text
    /// surface, the editor magnifies when the user raises the app-wide text
    /// size. Pass `false` for an editor whose font sizes are **document
    /// content** (a WYSIWYG / print-layout editor) that must stay at its true
    /// point size regardless of the reader's UI accessibility setting.
    ///
    /// Composed with [`font_size_scale`](Self::font_size_scale):  
    /// `engine.font_scale = (follow ? text_scale : 1.0) × font_size_scale`.
    pub fn follow_text_scale(self, follow: bool) -> Self {
        self.state.borrow_mut().follow_text_scale = follow;
        self
    }

    /// Per-editor logical font-size multiplier (`1.0` = 100 %). Applied
    /// *before* shaping (same channel as accessibility text scale), so text
    /// grows, re-wraps, and stays sharp — the knob for a "Text size"
    /// preference. Composed as
    /// `(follow_text_scale ? ctx.text_scale : 1.0) × font_size_scale`.
    /// Clamped to `[0.1, 10.0]`. Use [`set_font_size_scale`](Self::set_font_size_scale)
    /// after mount.
    pub fn font_size_scale(self, scale: f32) -> Self {
        {
            let mut st = self.state.borrow_mut();
            st.font_size_scale = scale.clamp(0.1, 10.0);
            st.needs_full_layout = true;
            st.content_dirty = true;
        }
        self
    }

    /// Replace the built-in right-click context menu with a
    /// user-provided factory. Same shape as the framework's
    /// [`teksilo_core::widget_builder::ContextMenuFactory`]: the
    /// closure receives the click position (widget-local) and a full
    /// [`EventContext`](teksilo_core::widget::EventContext), and returns
    /// `Some(menu_widget)` to mount or `None` to decline (falling
    /// through to the next ancestor with a factory).
    ///
    /// Taking this branch disables the default menu unconditionally.
    /// The framework's
    /// [`show_context_menu_for`](teksilo_core::widget_tree) handles
    /// the overlay lifecycle (open at pointer, dismiss on
    /// click-outside / Escape, focus-restore on dismiss), so the
    /// factory only needs to build the menu content.
    ///
    /// This is an **inherent method**: it shadows the blanket
    /// [`WidgetBuilder::context_menu`](teksilo_core::widget_builder::WidgetBuilder::context_menu)
    /// trait method so the user can chain it directly on the editor.
    /// Internally, the factory is installed on the editor's arena
    /// node via the same `HandlerSet::context_menu` plumbing.
    pub fn context_menu(
        mut self,
        factory: impl Fn(
            teksilo_canvas::Point,
            &mut teksilo_core::widget::EventContext,
        ) -> Option<Box<dyn teksilo_core::widget::Widget>>
        + 'static,
    ) -> Self {
        self.custom_context_menu = Some(Box::new(factory));
        self
    }

    /// Enable (default) or disable the widget's built-in right-click
    /// context menu (Cut / Copy / Paste / Paste Unformatted / Select
    /// All). When disabled, right-click bubbles past the widget
    /// unhandled and
    /// [`context_target_at`](Self::context_target_at) stays
    /// available for applications that render their own menu.
    ///
    /// Note: if a user factory is installed via
    /// [`context_menu`](Self::context_menu), that factory wins
    /// regardless of this flag — this setter only governs the
    /// *default* menu.
    pub fn default_context_menu(mut self, enabled: bool) -> Self {
        self.default_context_menu_enabled = enabled;
        self
    }

    /// Install a custom font registrar for the fallback private
    /// engine. Only has effect when the editor is built outside a
    /// windowed teksilo-app — once `build()` sees a `SharedTypesetter`
    /// in `app_state`, the private engine is replaced with one that
    /// shares the app's typesetter and this registrar is ignored.
    pub fn font_registrar(self, registrar: &dyn FontRegistrar) -> Self {
        {
            let mut st = self.state.borrow_mut();
            let mut engine = RichTextEngine::private_with_registrar(registrar);
            engine.set_wrap_mode(st.wrap_mode);
            engine.set_hyphenate_justified(true);
            st.engine = engine;
            st.needs_full_layout = true;
        }
        self
    }

    /// Install a callback fired once per batch of genuine **user content
    /// edits** (typing, paste, cut, delete) — and *not* on a programmatic
    /// `set_djot` / `set_markdown` / `set_html` load or a document reset, and
    /// *not* while an IME composition (CJK/Kana candidate preview, dead-key
    /// accent) is still in progress — only the settled result of a commit
    /// fires it. The callback runs on the UI thread during the editor's frame
    /// drain, so it may touch `Signal`s directly — e.g. flip a "dirty" flag or
    /// kick a debounced autosave. Replaces any prior change callback on this
    /// editor.
    ///
    /// For a reactive change *token* (which also bumps on loads/format-only
    /// changes, and on intermediate IME composition steps), observe
    /// [`document_version`](Self::document_version) instead.
    pub fn on_change(self, f: impl Fn() + 'static) -> Self {
        self.state.borrow_mut().on_change = Some(Rc::new(f));
        self
    }

    /// Install a callback fired **at each insertion**, with the
    /// [`EditSource`] the text came through and how many characters it was.
    ///
    /// Additive to [`on_change`](Self::on_change) rather than a replacement for
    /// it, because they answer different questions. `on_change` fires once per
    /// drain batch and says *that* the document changed — the right shape for a
    /// dirty flag and a debounced autosave, and the wrong one for counting: a
    /// batch can carry a typed run and a paste, and after the fact nothing can
    /// tell them apart.
    ///
    /// **Reported where the text is, not derived afterwards.** Every site below
    /// holds the literal `&str` about to be inserted, so the count is what was
    /// actually written rather than a position delta — which is a different
    /// number the moment an insertion replaces a selection.
    ///
    /// Fires for text arriving through:
    ///
    /// - the keyboard, once per batched run of typed characters;
    /// - an IME commit, once for the settled result and never for the
    ///   intermediate composition states;
    /// - a paste, of plain text or HTML;
    /// - an assistive technology, through AccessKit's `SetValue` and
    ///   `ReplaceSelectedText`.
    ///
    /// It does **not** fire for a programmatic `set_djot` / `set_markdown` /
    /// `set_html` load, for undo or redo, or for a format-only change: none of
    /// those is text arriving.
    ///
    /// Replaces any prior callback on this editor. Runs on the UI thread.
    pub fn on_text_inserted(self, f: impl Fn(EditSource, usize) + 'static) -> Self {
        self.state.borrow_mut().on_text_inserted = Some(Rc::new(f));
        self
    }

    // --- Observable signals ---------------------------------------------

    /// Reactive counter that bumps on every document change (content edits,
    /// format changes, load events). Starts at `0`. Use as a change token to
    /// invalidate external caches.
    pub fn document_version(&self) -> Signal<u64> {
        self.state.borrow().document_version.clone()
    }

    /// Current cursor position in the document, in character units.
    /// Exposed for tests and for applications that need to mirror the
    /// caret position externally (status bar, outline panel, etc.).
    pub fn cursor_position(&self) -> usize {
        self.state.borrow().cursor.position()
    }

    /// Current selection anchor (equal to `cursor_position` when there
    /// is no selection).
    pub fn cursor_anchor(&self) -> usize {
        self.state.borrow().cursor.anchor()
    }

    /// `true` while an IME composition (CJK/Kana candidate preview, dead-key
    /// accent) is actively in progress — i.e. [`on_change`](Self::on_change)
    /// is currently suppressed for this editor. Exposed so a caller doing its
    /// own while-typing scanning (e.g. an autocorrect feature) can gate its
    /// own trigger logic the same way, as defense-in-depth alongside
    /// `on_change`'s own gate.
    pub fn is_composing(&self) -> bool {
        self.state.borrow().ime_preedit.is_some()
    }

    /// Reactive cursor position signal. Observers fire whenever the
    /// cursor moves (arrow keys, click, Home/End, …). Useful for
    /// status bars and tests.
    pub fn cursor_position_signal(&self) -> Signal<usize> {
        self.state.borrow().cursor_position.clone()
    }

    /// Reactive selection anchor signal.
    pub fn cursor_anchor_signal(&self) -> Signal<usize> {
        self.state.borrow().cursor_anchor.clone()
    }

    /// Reactive signal — `true` whenever the editor has a non-empty
    /// selection. Updates synchronously after every cursor mutation.
    pub fn has_selection(&self) -> Signal<bool> {
        self.state.borrow().has_selection.clone()
    }

    /// Reactive undo-availability signal, suitable for toolbar button
    /// enable-state. Updated through the frame loop's debounce drain
    /// so toolbars don't flicker during rapid editing.
    pub fn can_undo(&self) -> Signal<bool> {
        self.state.borrow().can_undo.clone()
    }

    /// Reactive redo-availability signal.
    pub fn can_redo(&self) -> Signal<bool> {
        self.state.borrow().can_redo.clone()
    }

    /// Read the current character format at the widget's caret —
    /// the right source for toolbars that mirror bold/italic/underline
    /// state.
    ///
    /// When a selection is active, the format is read from
    /// [`selection_start()`](teksilo_text::text_document::TextCursor::selection_start)
    /// rather than [`position()`](teksilo_text::text_document::TextCursor::position).
    /// Rationale (matches godot-rich-text's `query_char_format`):
    /// `position()` lands at the **end** of the selection and may fall
    /// on a run with different formatting (or past the last character,
    /// on an empty virtual element) — a toolbar observing that value
    /// would flicker or lie. `selection_start()` always points at the
    /// first character of the selected range, so the reading is
    /// stable and matches what a user would expect from "tell me the
    /// format of what I have selected."
    pub fn caret_char_format(&self) -> TextFormat {
        let st = self.state.borrow();
        let probe_pos = if st.cursor.has_selection() {
            st.cursor.selection_start()
        } else {
            st.cursor.position()
        };
        // Read through a fresh cursor so we don't disturb the widget's
        // own cursor (the widget's own cursor has its own position /
        // anchor state that we must not move).
        let probe = st.document.cursor();
        probe.set_position(probe_pos, teksilo_text::text_document::MoveMode::MoveAnchor);
        probe.char_format().unwrap_or_default()
    }

    /// Clone the internal shared state handle for test observation.
    /// Tests take this before `tree.add(editor)` moves the widget
    /// into the arena, so they can read the widget's live cursor,
    /// signal state, and debounce fields through the very same
    /// `Rc<RefCell<EditorState>>` that the arena-stored editor is
    /// mutating.
    #[cfg(test)]
    pub(crate) fn state_handle(&self) -> SharedState {
        self.state.clone()
    }

    /// Reactive vertical scroll offset in logical pixels. Bind to a
    /// scroll bar or observe for scroll-position persistence.
    pub fn scroll_y(&self) -> Signal<f32> {
        self.state.borrow().scroll_y.clone()
    }

    /// Reactive horizontal scroll offset in logical pixels. Non-zero
    /// only when [`wrap_mode`](Self::wrap_mode) is `WrapMode::None`.
    pub fn scroll_x(&self) -> Signal<f32> {
        self.state.borrow().scroll_x.clone()
    }

    // --- Context-menu support (external menus) --------------------------

    /// Classify what is under `point` in the widget's local coordinates
    /// (origin at the widget's top-left, scroll offset handled
    /// internally by the typesetter), for applications building an
    /// external context menu. Returns `None` if the point does not
    /// land on any hit region.
    pub fn context_target_at(&self, point: Point) -> Option<hit_test::ContextTarget> {
        let st = self.state.borrow();
        let hit = hit_test::hit_test_at(&st.engine, point, 0.0, 0.0)?;
        let selection = Some((st.cursor.anchor(), st.cursor.position()));
        Some(hit_test::classify(&hit, selection, &st.document))
    }

    // --- Selection helpers (allowed under both presets) -----------------

    /// Currently selected text, or an empty string if nothing is selected.
    pub fn selected_text(&self) -> String {
        self.state
            .borrow()
            .cursor
            .selected_text()
            .unwrap_or_default()
    }

    /// Select the entire document programmatically. Equivalent to
    /// the final step of the Ctrl+A ladder; resets the ladder state
    /// so a subsequent Ctrl+A starts fresh at level 1.
    pub fn select_all(&self) {
        {
            let mut st = self.state.borrow_mut();
            st.cursor.select(SelectionType::Document);
            st.select_all_level = 0;
            st.select_all_anchor_cell = None;
        }
        sync_cursor_signals(&self.state);
    }

    /// Clear any current selection.
    pub fn deselect(&self) {
        {
            let mut st = self.state.borrow_mut();
            st.cursor.clear_selection();
            st.select_all_level = 0;
            st.select_all_anchor_cell = None;
        }
        sync_cursor_signals(&self.state);
    }

    // --- Cursor mirror API -------------------------------------------------
    //
    // These mirror the corresponding `TextCursor` methods but act on the
    // widget's **internal** cursor (the one tied to caret rendering /
    // blink / focus) rather than a fresh `doc.cursor()`. An application
    // that reaches through `TextDocument::cursor()` gets an independent
    // cursor whose position is decoupled from the widget's caret — any
    // mutation would be invisible to the paint pass. Use these methods
    // when you want programmatic effects to feel like user-typed edits.

    /// Insert plain text at the widget's caret. Replaces any selection.
    pub fn insert_text(&self, text: &str) {
        let st = self.state.borrow();
        let _ = st.cursor.insert_text(text);
        drop(st);
        sync_cursor_signals(&self.state);
    }

    /// Insert a fragment parsed from HTML at the widget's caret.
    /// Replaces any selection. Uses text-document's
    /// [`TextCursor::insert_html`](teksilo_text::text_document::TextCursor::insert_html),
    /// which parses the HTML into a `DocumentFragment` and inserts it.
    pub fn insert_html(&self, html: &str) {
        let st = self.state.borrow();
        let _ = st.cursor.insert_html(html);
        drop(st);
        sync_cursor_signals(&self.state);
    }

    /// Insert a fragment parsed from djot at the widget's caret.
    /// Replaces any selection. Uses text-document's
    /// [`TextCursor::insert_djot`](teksilo_text::text_document::TextCursor::insert_djot),
    /// which parses the djot into a `DocumentFragment` and inserts it — so
    /// unlike [`insert_text`](Self::insert_text), block-level source really
    /// does produce new blocks rather than literal newlines in one paragraph.
    pub fn insert_djot(&self, djot: &str) {
        let st = self.state.borrow();
        let _ = st.cursor.insert_djot(djot);
        drop(st);
        sync_cursor_signals(&self.state);
    }

    /// Split the current block at the widget's caret, as pressing Enter does.
    pub fn insert_block(&self) {
        let st = self.state.borrow();
        let _ = st.cursor.insert_block();
        drop(st);
        sync_cursor_signals(&self.state);
    }

    /// Insert an inline image by logical resource name. `width` and
    /// `height` are in logical pixels.
    ///
    /// `alt` is the image's accessible description and its export representation. It is
    /// passed straight through rather than defaulted here: the caller is the only layer
    /// that knows what the picture shows, and an empty string chosen on its behalf would
    /// be an accessibility decision made silently by a widget wrapper.
    pub fn insert_image(&self, name: &str, alt: &str, width: u32, height: u32) {
        let st = self.state.borrow();
        let _ = st.cursor.insert_image(name, alt, width, height);
        drop(st);
        sync_cursor_signals(&self.state);
    }

    /// Delete the current selection. No-op when nothing is selected.
    pub fn delete_selection(&self) {
        let st = self.state.borrow();
        if st.cursor.has_selection() {
            let _ = st.cursor.remove_selected_text();
        }
        drop(st);
        sync_cursor_signals(&self.state);
    }

    /// Select the word under the widget's caret.
    pub fn select_word(&self) {
        {
            let st = self.state.borrow();
            st.cursor.select(SelectionType::WordUnderCursor);
        }
        sync_cursor_signals(&self.state);
    }

    /// Select the paragraph / block under the widget's caret.
    pub fn select_line(&self) {
        {
            let st = self.state.borrow();
            st.cursor.select(SelectionType::LineUnderCursor);
        }
        sync_cursor_signals(&self.state);
    }

    /// Move the caret to an absolute character position. Collapses any
    /// existing selection (passes [`MoveMode::MoveAnchor`]). Resets
    /// `CursorAffinity` to `Downstream` — programmatic placement
    /// can't know whether the caller wanted the upstream side of a
    /// wrap boundary, so we default to the same placement that
    /// existed before affinity was introduced.
    pub fn set_caret_position(&self, position: usize) {
        {
            let mut st = self.state.borrow_mut();
            st.cursor.set_position(position, MoveMode::MoveAnchor);
            st.cursor_affinity = teksilo_text::CursorAffinity::Downstream;
        }
        sync_cursor_signals(&self.state);
    }

    // --- Search / find-banner support (B3) --------------------------------

    /// Reactive signal — `true` while **this** editor holds keyboard focus.
    ///
    /// A per-editor find banner (Ctrl+F) targets whichever editor is focused, and the split
    /// view has two of them; `focused_side` only names the Primary/Secondary *pane*, not which
    /// editor. This is the per-editor answer, mirroring [`has_selection`](Self::has_selection).
    pub fn focused_signal(&self) -> Signal<bool> {
        self.state.borrow().focus_signal.clone()
    }

    /// Select the character range `[start, end)`, **without** collapsing — unlike
    /// [`set_caret_position`](Self::set_caret_position), which always moves both ends together.
    ///
    /// The anchor lands at `start` and the caret (focus) at `end`, so the standard selection
    /// highlight marks the range and a subsequent replace acts on it. Used to select a search
    /// match. (The non-collapsing two-call shape is the same one the AccessKit
    /// `SetTextSelection` handler uses.)
    pub fn select_range(&self, start: usize, end: usize) {
        {
            let mut st = self.state.borrow_mut();
            st.cursor.set_position(start, MoveMode::MoveAnchor);
            st.cursor.set_position(end, MoveMode::KeepAnchor);
            // The caret sits at `end`; downstream affinity matches placement at a range end.
            st.cursor_affinity = teksilo_text::CursorAffinity::Downstream;
        }
        sync_cursor_signals(&self.state);
    }

    /// Scroll the character range `[start, end)` into view within the enclosing scroll area.
    ///
    /// Reveals an **arbitrary** offset range — the current search match — rather than the live
    /// caret the follow-into-view path tracks, and works whether or not the editor is focused.
    ///
    /// **Returns whether it could.** `false` means this editor has no layout to locate the
    /// range in — never laid out, or parked dormant in a tab that is not on screen — and
    /// nothing was requested. A caller holding several editors over one document (two split
    /// panes; a stream row and that row's own tab) must try the next rather than take the
    /// first as the answer: revealing through a dormant one silently does nothing, which
    /// reads as "the viewport does not follow".
    ///
    /// Under [`typewriter`](Self::typewriter) scrolling the range is *pinned* to
    /// the anchor rather than merely revealed, so a search walks matches to the
    /// same height the caret writes at instead of leaving them wherever they
    /// happened to fall. Because a search jump is a deliberate, screen-sized
    /// move, it glides.
    pub fn reveal_range(
        &self,
        ctx: &mut teksilo_core::widget::EventContext,
        start: usize,
        end: usize,
    ) -> bool {
        reveal_range_impl(&self.state, ctx, start, end)
    }

    // --- Character-format commands ----------------------------------------
    //
    // Each setter writes to `TextCursor::merge_char_format`, which
    // applies to the current selection (or acts as a typing format when
    // there is no selection — see text-document's semantics). Toggle
    // variants (`toggle_bold`, `toggle_italic`, `toggle_underline`,
    // `toggle_strikethrough`) read the current state via
    // [`caret_char_format`](Self::caret_char_format) first and flip,
    // which matches the Ctrl+B / Ctrl+I / Ctrl+U keyboard shortcuts.

    fn apply_char_format(&self, fmt: TextFormat) {
        let st = self.state.borrow();
        let _ = st.cursor.merge_char_format(&fmt);
        // `pending_format_changed` gets set by `drain_events` when the
        // document emits its `FormatChanged` event in response to the
        // cursor mutation, so no manual bookkeeping is needed here.
    }

    /// Apply **bold** to the current selection (or set the typing bold
    /// state when no selection is active). Pairs with
    /// [`is_bold`](Self::is_bold) and [`toggle_bold`](Self::toggle_bold).
    pub fn set_bold(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_bold: Some(enabled),
            ..Default::default()
        });
    }

    /// Apply *italic* to the current selection.
    pub fn set_italic(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_italic: Some(enabled),
            ..Default::default()
        });
    }

    /// Apply underline to the current selection.
    pub fn set_underline(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_underline: Some(enabled),
            ..Default::default()
        });
    }

    /// Apply strikethrough to the current selection.
    pub fn set_strikethrough(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_strikeout: Some(enabled),
            ..Default::default()
        });
    }

    /// Set the font size (in points) for the current selection.
    pub fn set_font_size(&self, size: u32) {
        self.apply_char_format(TextFormat {
            font_point_size: Some(size),
            ..Default::default()
        });
    }

    /// Set the font family for the current selection. `family` must be
    /// a name resolvable by the shared typesetter's font registrar.
    pub fn set_font_family(&self, family: impl Into<String>) {
        self.apply_char_format(TextFormat {
            font_family: Some(family.into()),
            ..Default::default()
        });
    }

    /// Toggle bold on the current selection, reading the current state
    /// via [`caret_char_format`](Self::caret_char_format). Matches the
    /// Ctrl+B keyboard shortcut's behaviour.
    pub fn toggle_bold(&self) {
        let current = self.caret_char_format().font_bold.unwrap_or(false);
        self.set_bold(!current);
    }

    /// Toggle italic; see [`toggle_bold`](Self::toggle_bold).
    pub fn toggle_italic(&self) {
        let current = self.caret_char_format().font_italic.unwrap_or(false);
        self.set_italic(!current);
    }

    /// Toggle underline; see [`toggle_bold`](Self::toggle_bold).
    pub fn toggle_underline(&self) {
        let current = self.caret_char_format().font_underline.unwrap_or(false);
        self.set_underline(!current);
    }

    /// Toggle strikethrough; see [`toggle_bold`](Self::toggle_bold).
    pub fn toggle_strikethrough(&self) {
        let current = self.caret_char_format().font_strikeout.unwrap_or(false);
        self.set_strikethrough(!current);
    }

    // --- Vertical alignment (super / subscript) ---------------------------
    //
    // One property with three meaningful states, surfaced as two independent
    // toggles because that is how a toolbar presents it. Setting one clears
    // the other, since a run cannot be both.

    /// Raise the selection to superscript, or drop it back to the baseline.
    pub fn set_superscript(&self, enabled: bool) {
        self.set_vertical_alignment(if enabled {
            CharVerticalAlignment::SuperScript
        } else {
            CharVerticalAlignment::Normal
        });
    }

    /// Lower the selection to subscript, or drop it back to the baseline.
    pub fn set_subscript(&self, enabled: bool) {
        self.set_vertical_alignment(if enabled {
            CharVerticalAlignment::SubScript
        } else {
            CharVerticalAlignment::Normal
        });
    }

    /// Set the selection's vertical alignment directly. `Normal` is the
    /// baseline; `Middle` exists in the model but has no toolbar affordance.
    pub fn set_vertical_alignment(&self, alignment: CharVerticalAlignment) {
        self.apply_char_format(TextFormat {
            vertical_alignment: Some(alignment),
            ..Default::default()
        });
    }

    /// The caret's vertical alignment, `Normal` when unset.
    pub fn get_vertical_alignment(&self) -> CharVerticalAlignment {
        self.caret_char_format()
            .vertical_alignment
            .unwrap_or(CharVerticalAlignment::Normal)
    }

    /// True while the caret sits in superscript text.
    pub fn is_superscript(&self) -> bool {
        self.get_vertical_alignment() == CharVerticalAlignment::SuperScript
    }

    /// True while the caret sits in subscript text.
    pub fn is_subscript(&self) -> bool {
        self.get_vertical_alignment() == CharVerticalAlignment::SubScript
    }

    /// Flip superscript on the selection. Turning it on replaces subscript.
    pub fn toggle_superscript(&self) {
        self.set_superscript(!self.is_superscript());
    }

    /// Flip subscript on the selection. Turning it on replaces superscript.
    pub fn toggle_subscript(&self) {
        self.set_subscript(!self.is_subscript());
    }

    // --- Block-format commands --------------------------------------------

    /// Set an arbitrary [`BlockFormat`] on the caret's current block.
    /// The higher-level helpers [`set_alignment`](Self::set_alignment)
    /// and [`set_heading_level`](Self::set_heading_level) go through
    /// this method. Exposed so apps that need less common fields
    /// (`indent`, `left_margin`, `line_height`, …) don't have to
    /// reach through `TextDocument::cursor()` and lose the widget's
    /// caret continuity.
    pub fn apply_block_format(&self, fmt: BlockFormat) {
        let st = self.state.borrow();
        let _ = st.cursor.set_block_format(&fmt);
        // See `apply_char_format` — `FormatChanged` propagates
        // through `drain_events` and updates `pending_format_changed`
        // + `format_version` there.
    }

    /// Set an arbitrary [`TextFormat`] on the current selection.
    /// Public counterpart of the private `apply_char_format` helper,
    /// for apps that need fields beyond the dedicated
    /// `set_bold` / `set_italic` / … setters (e.g. `letter_spacing`,
    /// `foreground_color`).
    pub fn apply_text_format(&self, fmt: TextFormat) {
        self.apply_char_format(fmt);
    }

    /// Set the paragraph alignment for the current block (or the block
    /// containing the selection anchor).
    pub fn set_alignment(&self, alignment: Alignment) {
        self.apply_block_format(BlockFormat {
            alignment: Some(alignment),
            ..Default::default()
        });
    }

    /// Unset the block's direction, handing the paragraph back to
    /// automatic detection.
    ///
    /// Not the same as setting left-to-right. An explicit direction
    /// *pins* the paragraph and overrides the bidi algorithm, so
    /// "clearing" a direction by writing `LeftToRight` would force
    /// Arabic and Hebrew prose to lay out backwards. Only an unset
    /// direction lets the text speak for itself.
    pub fn clear_direction(&self) {
        self.apply_block_format(BlockFormat {
            clear_direction: true,
            ..Default::default()
        });
    }

    /// Set the base reading direction of the current block.
    ///
    /// This is the *paragraph* direction, not a character property: it
    /// decides which edge unaligned text sits against and, more
    /// importantly, overrides the bidi algorithm's first-strong-character
    /// guess — which misreads an Arabic paragraph opening with a Latin
    /// acronym as left-to-right.
    pub fn set_direction(&self, direction: TextDirection) {
        self.apply_block_format(BlockFormat {
            direction: Some(direction),
            ..Default::default()
        });
    }

    /// Set the heading level of the current block. `0` = plain
    /// paragraph; `1..=6` follow the HTML `<h1>..<h6>` convention.
    pub fn set_heading_level(&self, level: u8) {
        self.apply_block_format(BlockFormat {
            heading_level: Some(level),
            ..Default::default()
        });
    }

    // --- List commands ----------------------------------------------------

    /// Create a list at the current selection. `ordered = true` uses
    /// decimal numbering; `ordered = false` uses a bullet disc.
    /// Choose a specific style with [`create_list`](Self::create_list).
    pub fn insert_list(&self, ordered: bool) {
        let style = if ordered {
            ListStyle::Decimal
        } else {
            ListStyle::Disc
        };
        self.create_list(style);
    }

    /// Create a list with an explicit [`ListStyle`]. Exposed for
    /// applications that want e.g. lowercase Roman numerals or circle
    /// bullets.
    pub fn create_list(&self, style: ListStyle) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.create_list(style);
        }
        sync_cursor_signals(&self.state);
    }

    /// Increase the nesting depth of the caret's current list item by
    /// one. No-op when the caret is not inside a list. Equivalent to
    /// pressing Tab while the caret is on a list item — same behaviour,
    /// same `nest_current_list_item` codepath, exposed for toolbar
    /// buttons that do not want to synthesise key events.
    pub fn indent(&self) {
        keyboard::indent_current_block(&mut self.state.borrow_mut());
        sync_cursor_signals(&self.state);
    }

    /// Decrease the nesting depth of the caret's current list item by
    /// one. No-op at depth 0 (use `Backspace` at block-start to exit
    /// the list entirely). Toolbar counterpart of Shift+Tab.
    pub fn outdent(&self) {
        keyboard::dedent_current_block(&mut self.state.borrow_mut());
        sync_cursor_signals(&self.state);
    }

    /// Take the caret's block out of its list entirely, leaving a plain
    /// paragraph. No-op when the caret is not inside a list.
    ///
    /// [`outdent`](Self::outdent) deliberately stops at depth 0 — Shift+Tab
    /// should not silently destroy the list — so a toolbar that offers
    /// "remove list formatting" needs this instead. Backspace at block-start
    /// reaches the same codepath from the keyboard.
    pub fn remove_from_list(&self) {
        let _ = self.state.borrow().cursor.remove_current_block_from_list();
        sync_cursor_signals(&self.state);
    }

    // --- Blockquote commands ----------------------------------------------

    /// True iff the caret currently sits inside a blockquote frame at
    /// any nesting depth. Used by the toolbar to drive the toggle
    /// button's pressed state and the context menu's label.
    pub fn is_in_blockquote(&self) -> bool {
        let st = self.state.borrow();
        st.cursor.is_in_blockquote()
    }

    /// True iff the current selection spans more than one frame. The
    /// "Toggle blockquote" affordance is disabled in this case because
    /// wrapping a cross-frame range has no well-defined semantics
    /// (different blocks already belong to different containers).
    pub fn selection_spans_multiple_frames(&self) -> bool {
        let st = self.state.borrow();
        st.cursor.selection_spans_multiple_frames()
    }

    /// Wrap the current block (or selection) in a blockquote, or
    /// unwrap the innermost enclosing blockquote if already inside one.
    /// No-op (returns silently) when the selection spans multiple
    /// frames.
    pub fn toggle_blockquote(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.toggle_blockquote();
        }
        sync_cursor_signals(&self.state);
    }

    /// Equivalent to pressing Tab inside a blockquote — wraps the
    /// current block in a deeper nested quote. No-op when the caret is
    /// not in a quote.
    pub fn increase_blockquote_depth(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.increase_blockquote_depth();
        }
        sync_cursor_signals(&self.state);
    }

    /// Equivalent to pressing Shift+Tab inside a blockquote — pops one
    /// nesting level. At depth 1 unwraps the block to a plain
    /// paragraph. No-op when the caret is not in a quote.
    pub fn decrease_blockquote_depth(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.decrease_blockquote_depth();
        }
        sync_cursor_signals(&self.state);
    }

    // --- Table commands ---------------------------------------------------
    //
    // Each table command drops through `sync_cursor_signals` because
    // the underlying `cursor.*` calls move the caret (insert_table
    // lands past the new table; row/column ops may shift the caret's
    // logical position). Callers observing `cursor_position_signal`
    // see the post-operation position without waiting for the next
    // frame tick.

    /// Insert a fresh `rows × columns` table at the caret. Any
    /// existing selection is replaced.
    pub fn insert_table(&self, rows: usize, columns: usize) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_table(rows, columns);
        }
        sync_cursor_signals(&self.state);
    }

    /// Remove the table containing the caret (if any). No-op when the
    /// caret is not inside a table.
    pub fn remove_current_table(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.remove_current_table();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a row above the caret's current table row. No-op when
    /// outside a table.
    pub fn insert_row_above(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_row_above();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a row below the caret's current table row.
    pub fn insert_row_below(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_row_below();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a column before the caret's current table column.
    pub fn insert_column_before(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_column_before();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a column after the caret's current table column.
    pub fn insert_column_after(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_column_after();
        }
        sync_cursor_signals(&self.state);
    }

    /// Remove the caret's current table row.
    pub fn remove_current_row(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.remove_current_row();
        }
        sync_cursor_signals(&self.state);
    }

    /// Remove the caret's current table column.
    pub fn remove_current_column(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.remove_current_column();
        }
        sync_cursor_signals(&self.state);
    }

    /// Whether the caret is currently inside a table cell.
    pub fn is_in_table(&self) -> bool {
        self.state.borrow().cursor.current_table().is_some()
    }

    // --- Format query methods (toolbar state) -----------------------------
    //
    // Every query goes through [`caret_char_format`](Self::caret_char_format)
    // which honours the selection-start rule — toolbar buttons reflect
    // "the format of what's selected," not "the format after the
    // selection ends."

    /// Whether the current selection / typing position is bold.
    pub fn is_bold(&self) -> bool {
        self.caret_char_format().font_bold.unwrap_or(false)
    }

    /// Whether italic.
    pub fn is_italic(&self) -> bool {
        self.caret_char_format().font_italic.unwrap_or(false)
    }

    // ── Hyperlinks ───────────────────────────────────────────────
    //
    // A link is a character format, not an object: applying one merges a
    // destination onto a range, so any bold or italic already there survives
    // and no markup has to be escaped. What it does not get for free is
    // removal — every field of a merge means "leave this alone" when unset —
    // hence `clear_link` rather than "set the destination to nothing".

    /// Point the selection at `href`.
    ///
    /// Merges, so formatting already on the range is kept. A collapsed
    /// selection formats nothing (as everywhere else), so a caller linking
    /// existing text should select it first — see
    /// [`link_at_caret`](Self::link_at_caret) for the range of a link already
    /// there.
    pub fn set_link(&self, href: &str) {
        self.apply_char_format(TextFormat {
            anchor_href: Some(href.to_string()),
            ..Default::default()
        });
    }

    /// Take the link off the selection, leaving its text.
    pub fn clear_link(&self) {
        self.apply_char_format(TextFormat {
            clear_link: true,
            ..Default::default()
        });
    }

    /// The link the caret is in, and how far it reaches.
    ///
    /// Coalesced across the runs an inner mark splits a link into, so the
    /// range covers the whole link rather than the piece under the caret.
    /// `None` when the caret is not on a link.
    pub fn link_at_caret(&self) -> Option<LinkExtent> {
        self.state.borrow().cursor.link_at_caret()
    }

    /// Whether the caret / selection sits on a link.
    pub fn is_link(&self) -> bool {
        self.caret_char_format().is_anchor.unwrap_or(false)
    }

    /// Whether underline.
    pub fn is_underline(&self) -> bool {
        self.caret_char_format().font_underline.unwrap_or(false)
    }

    /// Whether strikethrough.
    pub fn is_strikethrough(&self) -> bool {
        self.caret_char_format().font_strikeout.unwrap_or(false)
    }

    /// Current heading level (0 = plain paragraph). Reads the caret's
    /// current block format.
    pub fn get_heading_level(&self) -> u8 {
        self.state
            .borrow()
            .cursor
            .block_format()
            .ok()
            .and_then(|f| f.heading_level)
            .unwrap_or(0)
    }

    /// Current block alignment.
    pub fn get_alignment(&self) -> Alignment {
        self.state
            .borrow()
            .cursor
            .block_format()
            .ok()
            .and_then(|f| f.alignment)
            .unwrap_or(Alignment::Left)
    }

    /// The block's explicitly-set reading direction, if it has one.
    /// `None` means the bidi algorithm decides from the text.
    pub fn get_direction(&self) -> Option<TextDirection> {
        self.state
            .borrow()
            .cursor
            .block_format()
            .ok()
            .and_then(|f| f.direction)
    }

    // --- History ---------------------------------------------------------
    //
    // Programmatic Undo / Redo. Failures (e.g. empty undo stack) are
    // silently discarded — toolbars gate the buttons on
    // [`can_undo`](Self::can_undo) / [`can_redo`](Self::can_redo)
    // signals so the error path is unreachable in normal use, and the
    // keyboard handlers at `keyboard.rs:357-366` use the same
    // `let _ =` discipline.

    /// Undo the most recent edit. Mirrors Ctrl+Z. No-op when the undo
    /// stack is empty.
    pub fn undo(&self) {
        let _ = self.state.borrow().document.undo();
        sync_cursor_signals(&self.state);
    }

    /// Close the current undo entry, so the next edit starts a new one.
    ///
    /// Typing coalesces into word-sized undo steps by looking only at the shape
    /// of two edits — adjacent, moments apart. It cannot see that the user did
    /// something else in between, somewhere else in the application, that they
    /// would remember as a dividing line. A host that knows one was crossed says
    /// so here, and the burst before it stops merging with the burst after.
    pub fn break_undo_merge(&self) {
        self.state.borrow().document.break_undo_merge();
    }

    /// Redo the most recently undone edit. Mirrors Ctrl+Y /
    /// Ctrl+Shift+Z. No-op when the redo stack is empty.
    pub fn redo(&self) {
        let _ = self.state.borrow().document.redo();
        sync_cursor_signals(&self.state);
    }

    // --- Edit blocks (composite undo) ------------------------------------
    //
    // Every command on this type is its own transaction, so a caller that
    // composes several of them into one user-visible action — "clear
    // formatting" turning off four marks and flattening a heading — leaves
    // the user pressing Ctrl+Z once per property. Wrapping the sequence in
    // an edit block makes it one entry.
    //
    // The editor already groups this way internally for IME composition
    // (`keyboard.rs`) and for list nesting; these expose the same primitive
    // to external toolbars. Composites nest, so it is safe to wrap calls
    // that open one of their own.

    /// Begin grouping subsequent edits into a single undo entry.
    ///
    /// Must be paired with [`end_edit_block`](Self::end_edit_block). Prefer
    /// [`edit_block`](Self::edit_block), which pairs them for you.
    pub fn begin_edit_block(&self) {
        self.state.borrow().cursor.begin_edit_block();
    }

    /// Close the group opened by [`begin_edit_block`](Self::begin_edit_block).
    pub fn end_edit_block(&self) {
        self.state.borrow().cursor.end_edit_block();
    }

    /// Run `edits` as one undo entry.
    ///
    /// The scoped form of [`begin_edit_block`](Self::begin_edit_block) — the
    /// block is closed even if `edits` returns early, which hand-pairing gets
    /// wrong eventually.
    pub fn edit_block<R>(&self, edits: impl FnOnce() -> R) -> R {
        self.begin_edit_block();
        let result = edits();
        self.end_edit_block();
        result
    }

    /// Set the document-wide default language (ISO 639-1 code, e.g. "en",
    /// "fr", "de"). Blocks that don't set their own language inherit it
    /// for hyphenation. Forces a full re-layout so the change takes effect
    /// on the next frame. No-op-safe if the document rejects the update.
    pub fn set_default_language(&self, language: &str) {
        let _ = self.state.borrow().document.set_default_language(language);
        self.state.borrow_mut().needs_full_layout = true;
    }

    /// The document-wide default language (ISO 639-1 code). Defaults to
    /// `"en"` when never set.
    pub fn default_language(&self) -> String {
        self.state.borrow().document.default_language()
    }

    // --- External handle -------------------------------------------------

    /// Cheap clone-able handle for external toolbars / palettes — see
    /// [`EditorHandle`]. The handle shares the editor's internal
    /// state (same `Rc<RefCell<…>>`), so mutations through the handle
    /// are immediately observable through the editor's reactive
    /// signals (and vice versa).
    ///
    /// Use this when the caller needs to invoke editor commands from
    /// `on_activate_fn` / `ctx.effect` closures that outlive the
    /// borrow of `&editor`: `RichTextEditor` itself is move-only
    /// (the optional context-menu factory holds a `Box<dyn Fn>`,
    /// which prevents `Clone`).
    pub fn handle(&self) -> EditorHandle {
        EditorHandle {
            state: self.state.clone(),
        }
    }

    // --- Clipboard (programmatic) -----------------------------------------
    //
    // Direct programmatic counterparts of Ctrl+C / Ctrl+X / Ctrl+V /
    // Ctrl+Shift+V. The `ctx` argument is the active
    // [`EventContext`](teksilo_core::widget::EventContext) — the clipboard
    // lookup flows through `ctx.app_state::<ClipboardHandle>()` which
    // only has a value during event dispatch. Callers outside that
    // scope (e.g. ambient "restore from file" flows) should operate on
    // the `TextDocument` and the app-level clipboard directly.

    /// Copy the current selection to the system clipboard (plain +
    /// HTML payloads). No-op when there is no selection.
    ///
    /// All clipboard methods take `&EventContext` because they only
    /// need read access — the clipboard handle is looked up via
    /// `ctx.app_state::<ClipboardHandle>()`. A call site that holds
    /// `&mut EventContext` can pass `&ctx` directly; Rust reborrows
    /// automatically.
    pub fn copy(&self, ctx: &teksilo_core::widget::EventContext) {
        let mut st = self.state.borrow_mut();
        clipboard::copy(&mut st, ctx);
    }

    /// Cut the current selection: copy first, then remove.
    pub fn cut(&self, ctx: &teksilo_core::widget::EventContext) {
        {
            let mut st = self.state.borrow_mut();
            clipboard::cut(&mut st, ctx);
        }
        sync_cursor_signals(&self.state);
    }

    /// Paste from the system clipboard. Prefers an in-process fragment
    /// over HTML over plain text — see
    /// `rich_text/clipboard.rs`.
    pub fn paste(&self, ctx: &teksilo_core::widget::EventContext) {
        {
            let mut st = self.state.borrow_mut();
            clipboard::paste(&mut st, ctx);
        }
        sync_cursor_signals(&self.state);
    }

    /// Paste plain text only, stripping any rich payload.
    pub fn paste_unformatted(&self, ctx: &teksilo_core::widget::EventContext) {
        {
            let mut st = self.state.borrow_mut();
            clipboard::paste_unformatted(&mut st, ctx);
        }
        sync_cursor_signals(&self.state);
    }

    /// Whether a paste would insert anything — `true` iff the system
    /// clipboard carries text **or** an HTML payload (the shapes
    /// [`paste`](Self::paste) can consume; an HTML-only clipboard pastes
    /// fine, so probing plain text alone would under-report).
    ///
    /// Clipboard contents are not reactively observable, so this is a
    /// **point-in-time query** rather than a `Signal`: pass the active
    /// [`EventContext`](teksilo_core::widget::EventContext). It probes
    /// the clipboard (an X11 HTML probe can round-trip to the selection
    /// owner), so a menu / toolbar builder should re-query when the menu
    /// opens, not per frame. Returns `false` when no clipboard backend
    /// is installed (headless or feature-off builds) — the same
    /// "silently no-op" degradation the paste path itself uses.
    pub fn can_paste(&self, ctx: &teksilo_core::widget::EventContext) -> bool {
        clipboard::can_paste(ctx)
    }

    /// Set the per-editor logical font-size multiplier (`1.0` = 100 %).
    /// Composed with accessibility text scale at paint; forces relayout.
    /// See [`font_size_scale`](Self::font_size_scale).
    pub fn set_font_size_scale(&self, scale: f32) {
        let mut st = self.state.borrow_mut();
        let scale = scale.clamp(0.1, 10.0);
        if (st.font_size_scale - scale).abs() <= f32::EPSILON {
            return;
        }
        st.font_size_scale = scale;
        // Force the paint pass to re-push engine font_scale (it compares
        // against `last_font_scale` only).
        st.last_font_scale = f32::NAN;
        st.needs_full_layout = true;
        st.content_dirty = true;
        if let Some(handle) = &st.frame_request {
            handle.set(true);
        }
    }

    /// Current per-editor font-size scale (`1.0` = 100 %).
    pub fn get_font_size_scale(&self) -> f32 {
        self.state.borrow().font_size_scale
    }

    /// Set the non-destructive default typography at runtime. Re-lays out and
    /// schedules a repaint. Never mutates the document.
    pub fn set_typography_defaults(&self, defaults: EditorTypographyDefaults) {
        let mut st = self.state.borrow_mut();
        st.engine.set_typography_defaults(defaults);
        st.needs_full_layout = true;
        st.content_dirty = true;
        if let Some(handle) = &st.frame_request {
            handle.set(true);
        }
    }

    /// Current default typography (see [`typography_defaults`](Self::typography_defaults)).
    pub fn get_typography_defaults(&self) -> EditorTypographyDefaults {
        self.state.borrow().engine.typography_defaults().clone()
    }

    /// Set the typewriter-scrolling anchor at runtime — see
    /// [`typewriter`](Self::typewriter). `None` turns pinning off.
    ///
    /// Takes effect on the next caret move rather than scrolling immediately: a
    /// pin is a follow rule, and re-anchoring the page the instant a setting
    /// changes would jump the view under a reader who is not even typing.
    pub fn set_typewriter(&self, anchor: Option<f32>) {
        let mut st = self.state.borrow_mut();
        st.typewriter = anchor.map(|f| f.clamp(0.0, 1.0));
        // Drop the pin's dedup memory: the *next* caret move must re-pin even if
        // it lands where the last chase already was.
        st.last_chase_y = None;
    }

    /// Current typewriter anchor (see [`typewriter`](Self::typewriter)).
    pub fn get_typewriter(&self) -> Option<f32> {
        self.state.borrow().typewriter
    }

    /// Narrow (or restore) what the keyboard may do on this mounted editor.
    ///
    /// The other three policy dimensions — caret, accessibility role, clipboard
    /// surface — describe what *kind* of surface this is and are fixed at
    /// construction; only the command filter is a mode the host can change
    /// while the writer is looking at it. Swapping in
    /// [`CommandFilter::ForwardOnly`] gives a forward-only drafting mode;
    /// [`CommandFilter::All`] restores ordinary editing.
    ///
    /// Every gate reads the filter live — the keyboard dispatch, the default
    /// context menu, and drag-and-drop — so this takes effect on the next
    /// event without rebuilding the widget.
    pub fn set_command_filter(&self, filter: policy::CommandFilter) {
        self.state.borrow_mut().policy.command_filter = filter;
    }

    /// The filter currently in force (see
    /// [`set_command_filter`](Self::set_command_filter)).
    pub fn command_filter(&self) -> policy::CommandFilter {
        self.state.borrow().policy.command_filter
    }

    /// Draw an ambient band behind the sentence — or paragraph — the caret is in.
    ///
    /// `None` (the default) draws nothing and registers no session on the document. The band
    /// shows only while **this** editor has focus, so two panes over one document never band
    /// twice, and it disappears when focus leaves the editor entirely.
    ///
    /// The band is registered below every other highlight layer, so a find match or a spell
    /// squiggle always paints over it. Give it a paint-only `format` — a background colour —
    /// or it will force a reshape on every caret move.
    pub fn set_caret_highlight(&self, highlight: Option<caret_highlight::CaretHighlight>) {
        set_caret_highlight(&self.state, highlight);
    }

    /// What this editor's caret band is currently configured to draw.
    pub fn get_caret_highlight(&self) -> Option<caret_highlight::CaretHighlight> {
        self.state
            .borrow()
            .caret_highlight
            .as_ref()
            .and_then(|s| s.config())
    }

    /// The caret's rectangle in **absolute window (tree) coordinates**, or
    /// `None` when the editor is unfocused or has not been laid out yet.
    ///
    /// The same rect the OS-IME reporting and the caret follow use, exposed for
    /// hosts that need to position something against the caret (and for tests
    /// that need to assert where a pin actually put it).
    pub fn caret_window_rect(&self) -> Option<teksilo_canvas::Rect> {
        self::keyboard::caret_window_rect(&self.state.borrow())
    }

    // --- Observability: reactive version counters -------------------------

    /// Signal that bumps on every format-only document event (bold /
    /// italic / heading / alignment / list style changes …).
    /// Distinct from [`document_version`](Self::document_version),
    /// which also bumps on content changes. Useful for toolbar
    /// observers that want to refresh button state on format changes
    /// without flickering during plain typing.
    pub fn format_version(&self) -> Signal<u64> {
        self.state.borrow().format_version.clone()
    }

    /// Signal that bumps once per document-loaded event (fires when
    /// an async `set_html` / `set_markdown` import completes). Starts
    /// at 0; observers see a new value each time a long import
    /// finishes.
    pub fn document_loaded_count(&self) -> Signal<u64> {
        self.state.borrow().document_loaded_count.clone()
    }

    // --- Link / image click callbacks -------------------------------------
    //
    // Installed via builder methods (below). The widget fires these
    // on a Primary PointerDown whose hit lands on a `HitRegion::Link`
    // or `HitRegion::Image`, before any caret placement.

    /// Install a callback fired when the user Primary-clicks a link
    /// (an element with an anchor `href`). The callback receives the
    /// href string and the active `EventContext`.
    ///
    /// The callback replaces any prior link-click callback on this
    /// builder chain. To stop observing, reconstruct the editor
    /// without the setter.
    pub fn on_link_activated(
        self,
        handler: impl Fn(&str, &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.state.borrow_mut().on_link_activated = Some(std::rc::Rc::new(handler));
        self
    }

    /// Supply an image's bytes on demand, when the document has no resource
    /// under that name.
    ///
    /// An inline image references its pixels by name, and those pixels live on
    /// the *document*. So a name that arrives without them — which is exactly
    /// what pasting an image into a second editor is, since the interchange
    /// format carries the reference and not the bytes — lays out at its full
    /// size and paints nothing.
    ///
    /// Rather than make every host re-scan its document after every edit for
    /// names that have appeared, the editor asks for what it is missing, once,
    /// at the moment it needs it. The bytes are written onto the document, so
    /// the answer is permanent and every later reader (a save, an export, a
    /// second view of the same document) sees them too.
    ///
    /// One hook serves paste, drag-and-drop, and an undo that re-inserts a
    /// deleted image, without any of them knowing it exists.
    pub fn on_image_missing(
        self,
        resolve: impl Fn(&str) -> Option<(String, Vec<u8>)> + 'static,
    ) -> Self {
        self.state.borrow_mut().image_resolver = Some(std::rc::Rc::new(resolve));
        self
    }

    /// Install a callback fired when files are dropped on the editor.
    ///
    /// The editor places the caret at the drop point and then hands the paths
    /// over: what a dropped file *means* — a picture to embed, a link to write,
    /// a document to include — is the host's policy, and a text editor that
    /// guessed would be wrong for every host but one.
    ///
    /// Without this, file drops are declined, and the drag bubbles to whatever
    /// ancestor claims it.
    pub fn on_files_dropped(
        self,
        handler: impl Fn(&[std::path::PathBuf], &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.state.borrow_mut().on_files_dropped = Some(std::rc::Rc::new(handler));
        self
    }

    /// Install a callback fired when the reader finishes dragging one of a
    /// selected image's corner grips.
    ///
    /// The widget does not resize the picture itself. It cannot: an image's
    /// display size lives in the host's own document format (an attribute, a
    /// style, a column of a table), and only the host knows how to write it
    /// there so it survives a save. So the drag reports a size and the host
    /// decides what that means — the same division of labour as
    /// [`on_image_activated`](Self::on_image_activated).
    ///
    /// Fired once, on release. During the drag the widget shows an outline at
    /// the proposed size, which costs no relayout and keeps one gesture to one
    /// entry on the host's undo stack.
    pub fn on_image_resized(
        self,
        handler: impl Fn(&ImageResize, &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.state.borrow_mut().on_image_resized = Some(std::rc::Rc::new(handler));
        self
    }

    /// Install a callback fired when the user Primary-clicks an inline
    /// image. The callback receives the activation (see
    /// [`ImageActivation`]) and the active `EventContext`.
    pub fn on_image_activated(
        self,
        handler: impl Fn(&ImageActivation, &mut teksilo_core::widget::EventContext) + 'static,
    ) -> Self {
        self.state.borrow_mut().on_image_activated = Some(std::rc::Rc::new(handler));
        self
    }
}

// =============================================================================
// EditorHandle — external toolbar / palette handle
// =============================================================================

/// A clone-able, `'static` handle to a [`RichTextEditor`]'s shared
/// state.
///
/// Use this when a toolbar, palette, command panel, or other external
/// widget needs to invoke editor commands from `on_activate_fn` /
/// `ctx.effect` closures that outlive the borrow of `&editor`.
/// [`RichTextEditor`] itself is move-only (the optional
/// `custom_context_menu` factory holds a `Box<dyn Fn>`, which prevents
/// `Clone`), so a closure cannot just capture `editor.clone()`.
/// Obtain a handle via [`RichTextEditor::handle()`] and clone it into
/// each closure that needs to issue commands.
///
/// `EditorHandle` mirrors the toolbar-relevant subset of the editor's
/// public API:
///
/// * Inline character formatting — [`set_bold`](Self::set_bold) /
///   [`toggle_bold`](Self::toggle_bold) / [`is_bold`](Self::is_bold)
///   and the italic / underline / strikethrough variants.
/// * Block-level formatting — [`set_alignment`](Self::set_alignment),
///   [`set_heading_level`](Self::set_heading_level),
///   [`apply_block_format`](Self::apply_block_format),
///   [`insert_list`](Self::insert_list),
///   [`indent`](Self::indent) / [`outdent`](Self::outdent).
/// * Tables — [`insert_table`](Self::insert_table) and the per-row /
///   per-column / remove operations, plus [`is_in_table`](Self::is_in_table)
///   for contextual UI enable state.
/// * History — [`undo`](Self::undo) / [`redo`](Self::redo).
/// * Clipboard — [`copy`](Self::copy) / [`cut`](Self::cut) /
///   [`paste`](Self::paste) /
///   [`paste_unformatted`](Self::paste_unformatted), plus
///   [`can_paste`](Self::can_paste) for Paste enable-state — so a
///   context-menu factory (which can only capture a handle, never the
///   editor that owns it) can rebuild Cut / Copy / Paste /
///   Paste-Unformatted.
/// * Selection — [`select_all`](Self::select_all) /
///   [`delete_selection`](Self::delete_selection).
/// * Reactive signal accessors —
///   [`format_version`](Self::format_version),
///   [`cursor_position_signal`](Self::cursor_position_signal),
///   [`cursor_anchor_signal`](Self::cursor_anchor_signal),
///   [`has_selection`](Self::has_selection),
///   [`can_undo`](Self::can_undo) / [`can_redo`](Self::can_redo) — so
///   callers that hold only an `EditorHandle` can derive bound signals
///   without keeping a separate `RichTextEditor` reference.
///
/// Cloning is cheap (an `Rc` clone). All clones share the same
/// underlying state — mutations through any clone, through other
/// clones, or through the originating `RichTextEditor` are all
/// immediately observable through the same signals.
#[derive(Clone)]
pub struct EditorHandle {
    state: SharedState,
}

impl std::fmt::Debug for EditorHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EditorHandle").finish_non_exhaustive()
    }
}

/// An inline image the user clicked.
///
/// Carries the offset as well as the name because a document may hold the same
/// picture more than once — a name alone cannot say *which* one was clicked, so
/// a host acting on the click (selecting it, editing its size, replacing it)
/// would be guessing. The offset addresses the image's single `U+FFFC`, so
/// `select_range(offset, offset + 1)` selects exactly it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageActivation {
    /// The image's resource name — the `src` the document stores.
    pub name: String,
    /// Character offset of the image within the document.
    pub offset: usize,
}

/// Rich text being dragged out of an editor.
///
/// The typed fast path for editor-to-editor drags: it carries the
/// `DocumentFragment` itself, so formatting, tables and inline images survive a
/// move the way they survive a copy/paste — where the `text/plain` MIME
/// alternative the drag also advertises (for other applications) could only
/// carry the words.
///
/// `source` and `range` are what let the drop tell a *move* from a *copy*:
/// dropped back into the editor it came from, the original has to be removed,
/// and only the source editor can say which range that was.
#[derive(Debug, Clone)]
pub struct EditorTextDrag {
    /// The editor the text was picked up from.
    pub source: teksilo_core::WidgetId,
    /// The dragged range in that editor, as document offsets.
    pub range: (usize, usize),
    /// The dragged content, with its formatting.
    pub fragment: teksilo_text::text_document::DocumentFragment,
    /// The same content as plain text — the drop's fallback, and the bytes
    /// handed to another application when the drag leaves the window.
    pub text: String,
}

/// Whether this payload is one the editor can take.
///
/// Text, files, and an [`EditorTextDrag`] from any editor. Any other typed
/// payload belongs to whichever widget understands that type — a binder row
/// dropped on the prose should still open a document, not paste its debug
/// representation.
///
/// **Optimistic while the drag is still in the air.** On Wayland the concrete
/// `files` / `text` arrive only at drop; during hover the payload carries just
/// the *advertised* formats. Judging by content alone therefore refuses every
/// external drag for its whole flight — the drop is forbidden everywhere right
/// up to the release that would have filled it in. So an advertised
/// `text/uri-list` or text format counts as acceptance, and the real check
/// happens at drop, where there is finally something to check. This is the same
/// rule `DropTarget::accept_external_files` / `accept_external_text` apply.
fn droppable(payload: &teksilo_core::DragPayload) -> bool {
    if payload.get_typed::<EditorTextDrag>().is_some() {
        return true;
    }
    if !payload.files().is_empty() || payload.text().is_some_and(|t| !t.is_empty()) {
        return true;
    }
    payload.formats().iter().any(|f| {
        f.starts_with("text/uri-list")
            || f.starts_with("text/plain")
            || matches!(f.as_str(), "UTF8_STRING" | "STRING" | "TEXT")
    })
}

/// A resize the reader finished dragging.
///
/// Reported once, on release, rather than continuously: the document is the
/// durable record and rewriting it on every pointer move would put a hundred
/// entries on the undo stack for one gesture.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageResize {
    /// The image's resource name.
    pub name: String,
    /// Character offset of its `U+FFFC` — the identity, since a document may
    /// hold one picture in several places.
    pub offset: usize,
    /// The new display size in logical pixels, proportions preserved.
    pub width: u32,
    pub height: u32,
}

impl EditorHandle {
    // --- Search / find-banner support (B3, handle mirror) ------------------
    //
    // These mirror the same-named [`RichTextEditor`] methods (which operate on
    // the same `state`), so a per-editor find banner built *above* the editor
    // can drive selection / scroll-into-view on the current match through the
    // handle it captured — the widget itself is long gone into the tree by then.

    /// This editor's content as Djot.
    ///
    /// The counterpart to [`insert_djot`](Self::insert_djot): a toolbar or command that can
    /// write into an editor it did not build should be able to read it back the same way.
    /// Without this the only route to the text is the host's own document bookkeeping,
    /// which knows about the editors it *mounted* and not about the ones a list or a card
    /// grid created — so a command ends up working on some surfaces and silently doing
    /// nothing on others.
    ///
    /// Empty string on a serialisation error, matching `TextDocument::to_djot`'s own
    /// callers: a command reading an editor has no better answer than "nothing there", and
    /// propagating a `Result` here would push that decision onto every call site.
    pub fn to_djot(&self) -> String {
        self.state.borrow().document.to_djot().unwrap_or_default()
    }

    /// This editor's content as the *addressable* plain text — the view whose
    /// character offsets are the document's own.
    ///
    /// The counterpart to [`to_djot`](Self::to_djot) for a caller that has an
    /// offset (a caret, a selection, a click) and needs to know what is there.
    /// An inline image appears as its `U+FFFC`, so offsets into this string are
    /// offsets into the document, character for character — which the `.txt`
    /// export's view deliberately is not.
    ///
    /// Empty string on error, for the same reason `to_djot` returns one.
    pub fn to_plain_text(&self) -> String {
        self.state
            .borrow()
            .document
            .to_plain_text()
            .unwrap_or_default()
    }

    /// Whether this editor holds no text at all.
    ///
    /// `character_count() == 0`, so a document of one empty paragraph is empty but one
    /// holding only spaces is not — the distinction a caller usually wants is
    /// `to_djot().trim().is_empty()`, and this is the cheap O(1) pre-check.
    pub fn is_empty(&self) -> bool {
        self.state.borrow().document.is_empty()
    }

    /// Reactive signal — `true` while **this** editor holds keyboard focus.
    /// See [`RichTextEditor::focused_signal`].
    pub fn focused_signal(&self) -> Signal<bool> {
        self.state.borrow().focus_signal.clone()
    }

    /// Select the character range `[start, end)` without collapsing (anchor at
    /// `start`, caret at `end`). See [`RichTextEditor::select_range`].
    pub fn select_range(&self, start: usize, end: usize) {
        {
            let mut st = self.state.borrow_mut();
            st.cursor.set_position(start, MoveMode::MoveAnchor);
            st.cursor.set_position(end, MoveMode::KeepAnchor);
            st.cursor_affinity = teksilo_text::CursorAffinity::Downstream;
        }
        sync_cursor_signals(&self.state);
    }

    /// Replace the character range `[start, end)` with `text`, leaving the caret
    /// after the inserted text.
    ///
    /// The counterpart to [`select_range`](Self::select_range) for callers that
    /// must *rewrite* a span rather than merely reveal it — a spell-check
    /// correction picked from a context menu, an autocorrect, a
    /// replace-this-occurrence action. It goes through the widget's **internal**
    /// cursor, so the edit behaves exactly like typed text: it lands on the
    /// editor's undo stack as one entry (the replacement is a single
    /// insert-over-selection), fires the document's change notifications, and
    /// leaves the caret where the user would expect it.
    ///
    /// Offsets are **character** positions, the same space
    /// [`cursor_position`](Self::cursor_position) and `select_range` use. The
    /// inserted text inherits the character format at `start`, so correcting a
    /// word inside italic prose stays italic.
    ///
    /// Reaching through [`TextDocument::cursor`](teksilo_text::text_document::TextDocument::cursor)
    /// instead would mutate the document behind the widget's back, leaving the
    /// caret decoupled from the edit — use this.
    pub fn replace_range(&self, start: usize, end: usize, text: &str) {
        self.replace_range_from(start, end, text, EditSource::Programmatic);
    }

    /// As [`replace_range`](Self::replace_range), saying which channel the text
    /// came through for [`on_text_inserted`](RichTextEditor::on_text_inserted).
    ///
    /// `replace_range` itself reports [`EditSource::Programmatic`], which is
    /// what a handle-driven edit is by default: a toolbar, a menu command, a
    /// substitution the application made. **An application that knows better
    /// should say so here rather than let the default stand.** The distinction
    /// that matters most is an edit which merely puts back what the person
    /// typed — undoing an autocorrect, say. Those characters were typed, they
    /// are being typed again, and reporting them as the application's own work
    /// would credit the application with the writer's words.
    ///
    /// One call rather than an insert plus a separate report, so the two cannot
    /// drift apart at a call site that later grows a second early return.
    pub fn replace_range_from(&self, start: usize, end: usize, text: &str, source: EditSource) {
        // Select, then insert over the selection — each step in its own borrow
        // scope, mirroring `select_range` / `RichTextEditor::insert_text`. The
        // insert must not run while a `borrow_mut` is held: it notifies document
        // observers, which are free to read the state back.
        self.select_range(start, end);
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_text(text);
            st.report_inserted(source, text);
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert plain text at the caret, replacing any selection. The
    /// [`EditorHandle`] counterpart of
    /// [`RichTextEditor::insert_text`](RichTextEditor::insert_text), for callers
    /// that hold only a handle — a toolbar button or a global menu command.
    pub fn insert_text(&self, text: &str) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_text(text);
        }
        sync_cursor_signals(&self.state);
    }

    /// Register an image's bytes on this editor's document, under `name`.
    ///
    /// An inline image stores only a name; the paint pass resolves it to pixels
    /// through the document's resource table. So an image inserted without this
    /// lays out and stays blank — and the name is also what a *reload* resolves
    /// against, which is why a host restoring a document has to register its
    /// images before the first paint rather than at insertion time only.
    ///
    /// On the handle rather than only on the widget because commands operate on
    /// whichever editor has focus, including ones a list or card grid built that
    /// the host never mounted itself.
    pub fn add_image_resource(&self, name: &str, mime_type: &str, bytes: &[u8]) -> bool {
        let st = self.state.borrow();
        st.document
            .add_resource(ResourceType::Image, name, mime_type, bytes)
            .is_ok()
    }

    /// The natural pixel size of a registered image, decoded from its bytes.
    ///
    /// What the file actually is, not what the document asks it to be shown at
    /// — so a host offering "reset to the original size" restores the picture's
    /// own dimensions rather than a number remembered from when it was inserted,
    /// which is wrong the moment the file behind the name is replaced.
    ///
    /// Decodes on call. That is deliberate: this answers an explicit, rare
    /// request, and caching it would mean holding a second copy of every image
    /// in the document for a question almost nobody asks.
    pub fn image_resource_size(&self, name: &str) -> Option<(u32, u32)> {
        let bytes = self.state.borrow().document.resource(name).ok()??;
        let icon = teksilo_canvas::RasterIcon::decode(&bytes).ok()?;
        Some((icon.width(), icon.height()))
    }

    /// Whether this editor's document already has an image under `name`.
    ///
    /// Registering the same name twice appends a second resource row, so a host
    /// re-registering on every paint would grow the document without bound.
    pub fn has_image_resource(&self, name: &str) -> bool {
        let st = self.state.borrow();
        st.document.resource(name).ok().flatten().is_some()
    }

    /// Insert a fragment parsed from djot at the caret, replacing any selection.
    ///
    /// Unlike [`insert_text`](Self::insert_text), which drops its bytes into the
    /// current block verbatim (a `\n` becomes literal content, not a new
    /// paragraph), this parses block-level djot into a `DocumentFragment`, so
    /// inserting a standalone paragraph really does create one.
    pub fn insert_djot(&self, djot: &str) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_djot(djot);
        }
        sync_cursor_signals(&self.state);
    }

    /// Split the current block at the caret, as pressing Enter does.
    pub fn insert_block(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_block();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert `text` as a **paragraph of its own** at the caret: split here, fill
    /// the new block, split again, so whatever followed the caret continues in a
    /// third block.
    ///
    /// Deliberately one call rather than three. Composing
    /// `insert_block` + `insert_text` + `insert_block` from outside re-enters the
    /// widget three times, and an application that rebuilds its editor in
    /// response to the first change notification is left driving a handle that
    /// no longer points at the mounted widget — the split lands and the text
    /// silently does not. Doing the whole edit under a single borrow, with one
    /// signal sync at the end, makes it atomic from the caller's side.
    /// Returns `false` if any step failed, leaving the document as far as it
    /// got. Steps are **not** attempted after a failure: filling and re-splitting
    /// on top of a split that did not happen produces a mangled paragraph rather
    /// than a partial one, and the caller has no way to tell.
    pub fn insert_paragraph(&self, text: &str) -> bool {
        let ok = {
            let st = self.state.borrow();
            st.cursor.insert_block().is_ok()
                && st.cursor.insert_text(text).is_ok()
                && st.cursor.insert_block().is_ok()
        };
        sync_cursor_signals(&self.state);
        ok
    }

    /// The live selection as `(anchor, position)`, unordered — `anchor` is where the
    /// selection started, `position` is where the caret is, so a backwards drag
    /// reports `anchor > position`. Equal values mean no selection.
    ///
    /// Both ends are read under a **single** borrow, so the pair cannot tear. That is
    /// the reason to prefer this over pairing [`cursor_position`](Self::cursor_position)
    /// with [`cursor_anchor_signal`](Self::cursor_anchor_signal): the former is a live
    /// read of the cursor while the latter is a mirror refreshed on sync, so combining
    /// them mixes two different moments in time and can invent — or miss — a selection
    /// if the mirror lags. A caller deciding *"is there a selection, and over what"*
    /// wants one consistent answer.
    pub fn selection(&self) -> (usize, usize) {
        let st = self.state.borrow();
        (st.cursor.anchor(), st.cursor.position())
    }

    /// The selected text, or an empty string when nothing is selected.
    ///
    /// O(selection), not O(document). Pairs with [`selection`](Self::selection)
    /// for a caller that needs the range *and* what is in it — a link dialog
    /// pre-filling its display name from what the writer highlighted, say.
    pub fn selected_text(&self) -> String {
        self.state
            .borrow()
            .cursor
            .selected_text()
            .unwrap_or_default()
    }

    /// The **window-space** rectangle enclosing the character range `[start, end)`.
    ///
    /// The inverse of [`offset_at_point`](Self::offset_at_point): that maps a point
    /// to an offset, this maps offsets back to a point. It is what a decoration
    /// drawn *outside* the editor — a margin annotation, a connector leader, a
    /// bracket spanning a paragraph — needs in order to line itself up with the
    /// text it refers to.
    ///
    /// Coordinates match what the arena stores (`viewport_origin` + engine-local −
    /// scroll), so the result can be compared with any other widget's bounds
    /// directly, and it tracks scrolling for free.
    ///
    /// `None` before the first full layout. Focus is **not** required — a margin
    /// annotation must stay aligned whether or not the writer is typing.
    pub fn range_rect(&self, start: usize, end: usize) -> Option<Rect> {
        let st = self.state.borrow();
        keyboard::range_window_rect(&st, start, end)
    }

    /// The **window-space** caret rectangle at one offset — a zero-width
    /// [`range_rect`](Self::range_rect), and the anchor point for a marker drawn at
    /// one end of a span (the triangle at a comment's tail).
    pub fn offset_rect(&self, offset: usize) -> Option<Rect> {
        self.range_rect(offset, offset)
    }

    /// The **content-space** rectangle enclosing `[start, end)` — y = 0 at the top
    /// of the laid-out text, unaffected by scrolling and by where the editor sits
    /// in the window.
    ///
    /// The scroll-free counterpart to [`range_rect`](Self::range_rect), and the one
    /// to reach for when the question is *what proportion of the document is this*
    /// rather than *where is this on screen*. Divided by
    /// [`content_height`](Self::content_height) it gives a fraction an overview
    /// strip can draw against, for offsets the writer has long scrolled past —
    /// which window space cannot express at all, since it reports those relative to
    /// a viewport they are nowhere near.
    ///
    /// `None` before the first full layout. Focus is not required.
    pub fn range_content_rect(&self, start: usize, end: usize) -> Option<Rect> {
        let st = self.state.borrow();
        keyboard::range_content_rect(&st, start, end)
    }

    /// The **content-space** caret rectangle at one offset — a zero-width
    /// [`range_content_rect`](Self::range_content_rect).
    pub fn offset_content_rect(&self, offset: usize) -> Option<Rect> {
        self.range_content_rect(offset, offset)
    }

    /// Reactive counter that bumps on every document change — the handle mirror of
    /// [`RichTextEditor::document_version`].
    ///
    /// The change token a decoration drawn *outside* the editor binds, so it
    /// re-derives when the text moves under it. Without it such a widget has only
    /// the scroll metrics to go on, and those move on a reflow but not on an edit
    /// that leaves the height alone — which is most edits, and exactly the ones that
    /// shift the offsets a mark is anchored to.
    pub fn document_version(&self) -> Signal<u64> {
        self.state.borrow().document_version.clone()
    }

    /// Height of the laid-out text, in the same space
    /// [`range_content_rect`](Self::range_content_rect) reports.
    ///
    /// The denominator that turns a content rect into a fraction of the document.
    /// `None` before the first full layout — the same gate the rect queries use, so
    /// a caller that has one has the other and the division is never against a
    /// stale height.
    ///
    /// This is the *text's* height, not the widget's: an editor laid out taller
    /// than its content (a short scene in a tall pane) reports the text.
    pub fn content_height(&self) -> Option<f32> {
        let st = self.state.borrow();
        st.engine
            .has_full_layout()
            .then(|| st.engine.content_height())
    }

    /// Hit-test a point — **in window coordinates**, as a
    /// [`context_menu`](RichTextEditor::context_menu) factory receives it — to a
    /// document character offset. `None` when the point resolves to no text
    /// (past the last glyph on an empty line, outside the body, etc.).
    ///
    /// Lets a custom context-menu factory resolve "the word under the pointer"
    /// from the right-click position, since a bare right-click does not move the
    /// caret on its own.
    pub fn offset_at_point(&self, window_point: Point) -> Option<usize> {
        mouse::offset_at_window_point(&self.state, window_point)
    }

    /// Reposition the caret to a right-click point (**window coordinates**)
    /// unless the click lands inside the current selection (then the selection
    /// is preserved). Call this at the top of a custom
    /// [`context_menu`](RichTextEditor::context_menu) factory so the menu's Paste
    /// — and any caret-relative action — operates where the user clicked, exactly
    /// as the built-in menu and the single-line field do.
    pub fn reposition_caret_for_context_menu(&self, window_point: Point) {
        mouse::reposition_caret_for_context_menu(&self.state, window_point);
    }

    /// Scroll the character range `[start, end)` into view, reporting whether this editor
    /// could — it has a layout to locate the range in, and is on screen rather than parked
    /// dormant. See [`RichTextEditor::reveal_range`].
    ///
    /// When it answers `false` because there is no layout yet, the coarser
    /// [`reveal_widget`](Self::reveal_widget) is the way to get one.
    pub fn reveal_range(
        &self,
        ctx: &mut teksilo_core::widget::EventContext,
        start: usize,
        end: usize,
    ) -> bool {
        reveal_range_impl(&self.state, ctx, start, end)
    }

    /// Scroll **the editor itself** into view — the coarse fallback for the one case
    /// [`reveal_range`](Self::reveal_range) cannot serve at all. Reports whether this
    /// editor could: it has been built, so the arena knows a widget to scroll to, and
    /// it is on screen rather than parked dormant.
    ///
    /// A row of a stream that has never been painted has no full layout, so there is
    /// no rect to locate an offset in and `reveal_range` answers `false` — for ever,
    /// because the row only gets a layout when it is painted and it is only painted
    /// when it comes on screen. That is a deadlock a range reveal has no way out of:
    /// a match found in row 31 of a Book leaves the page exactly where it was, with
    /// the counter cheerfully reading `1 of 40`.
    ///
    /// Revealing by *widget* breaks it, because the arena knows where row 31 is laid
    /// out whether or not its text has been shaped. The row comes on screen, the next
    /// paint gives it a layout, and a later `reveal_range` can then put the match
    /// itself where the caller wants it. Coarser on purpose: this reveals the row,
    /// not the offset inside it.
    pub fn reveal_widget(&self, ctx: &mut teksilo_core::widget::EventContext) -> bool {
        let id = {
            let st = self.state.borrow();
            // The same dormancy gate `reveal_range` applies, and for the same reason:
            // a parked editor's bounds are still in the arena, so the walk would
            // happily scroll a container nobody can see and answer `true` — and a
            // caller told `true` stops looking for the editor that is on screen.
            if st.activation.as_ref().is_some_and(|a| !a.get()) {
                return false;
            }
            // `None` only before the editor's first build: nothing is mounted, so
            // there is no widget for the arena to resolve bounds for.
            match st.self_id {
                Some(id) => id,
                None => return false,
            }
        };
        ctx.ensure_widget_visible(id);
        true
    }

    /// Move keyboard focus onto the editor. Lets a control built *above* the
    /// editor — a find banner returning focus to the prose on Escape — put the
    /// caret back where the user expects. A no-op until the editor has built at
    /// least once (its wrapper id is stashed then).
    pub fn focus(&self, ctx: &mut teksilo_core::widget::EventContext) {
        if let Some(id) = self.state.borrow().self_id {
            ctx.request_focus(id);
        }
    }

    // --- Character-format query / apply ------------------------------------

    /// Read the current character format at the caret. When a selection
    /// is active, reads from `selection_start()` rather than
    /// `position()` so toolbar bistate stays stable across selection
    /// extension (same rule as
    /// [`RichTextEditor::caret_char_format`]).
    pub fn caret_char_format(&self) -> TextFormat {
        let st = self.state.borrow();
        let probe_pos = if st.cursor.has_selection() {
            st.cursor.selection_start()
        } else {
            st.cursor.position()
        };
        let probe = st.document.cursor();
        probe.set_position(probe_pos, MoveMode::MoveAnchor);
        probe.char_format().unwrap_or_default()
    }

    fn apply_char_format(&self, fmt: TextFormat) {
        let st = self.state.borrow();
        let _ = st.cursor.merge_char_format(&fmt);
    }

    /// Apply **bold** to the current selection.
    pub fn set_bold(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_bold: Some(enabled),
            ..Default::default()
        });
    }

    /// Apply *italic* to the current selection.
    pub fn set_italic(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_italic: Some(enabled),
            ..Default::default()
        });
    }

    /// Apply underline to the current selection.
    pub fn set_underline(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_underline: Some(enabled),
            ..Default::default()
        });
    }

    /// Apply strikethrough to the current selection.
    pub fn set_strikethrough(&self, enabled: bool) {
        self.apply_char_format(TextFormat {
            font_strikeout: Some(enabled),
            ..Default::default()
        });
    }

    /// Set the font family for the current selection (a character-format
    /// change applied over the selected range). Like the other char-format
    /// setters (`set_bold`, …), this is a **no-op when there is no
    /// selection** — the document model has no typing/pending format, so a
    /// bare caret has no range to format. `family` must be a name resolvable
    /// by the shared typesetter's font registrar — e.g. a value chosen from
    /// a [`FontPicker`](crate::font_picker::FontPicker).
    pub fn set_font_family(&self, family: impl Into<String>) {
        self.apply_char_format(TextFormat {
            font_family: Some(family.into()),
            ..Default::default()
        });
    }

    /// Set the font size (in points) for the current selection.
    pub fn set_font_size(&self, size: u32) {
        self.apply_char_format(TextFormat {
            font_point_size: Some(size),
            ..Default::default()
        });
    }

    // --- Default typography / font size (non-destructive, whole editor) ---

    /// Set the non-destructive default typography (font family / line height /
    /// first-line indent) filled onto runs and blocks with no explicit
    /// override. Unlike [`set_font_family`](Self::set_font_family) /
    /// [`set_font_size`](Self::set_font_size) — which mutate the selected text —
    /// this is a display-time default: it never touches the document, undo
    /// stack, or `modified` flag. Schedules a relayout + repaint.
    pub fn set_typography_defaults(&self, defaults: EditorTypographyDefaults) {
        let mut st = self.state.borrow_mut();
        st.engine.set_typography_defaults(defaults);
        st.needs_full_layout = true;
        st.content_dirty = true;
        if let Some(handle) = &st.frame_request {
            handle.set(true);
        }
    }

    /// Current default typography.
    pub fn get_typography_defaults(&self) -> EditorTypographyDefaults {
        self.state.borrow().engine.typography_defaults().clone()
    }

    /// Set the per-editor logical font-size multiplier. See
    /// [`RichTextEditor::set_font_size_scale`].
    pub fn set_font_size_scale(&self, scale: f32) {
        let mut st = self.state.borrow_mut();
        let scale = scale.clamp(0.1, 10.0);
        if (st.font_size_scale - scale).abs() <= f32::EPSILON {
            return;
        }
        st.font_size_scale = scale;
        st.last_font_scale = f32::NAN;
        st.needs_full_layout = true;
        st.content_dirty = true;
        if let Some(handle) = &st.frame_request {
            handle.set(true);
        }
    }

    /// Current per-editor font-size scale (`1.0` = 100 %).
    pub fn get_font_size_scale(&self) -> f32 {
        self.state.borrow().font_size_scale
    }

    /// Set the typewriter-scrolling anchor — the [`EditorHandle`] counterpart of
    /// [`RichTextEditor::set_typewriter`]. `None` turns pinning off.
    ///
    /// This is the door a host uses to keep the pin following a live setting,
    /// the same way [`set_typography_defaults`](Self::set_typography_defaults)
    /// keeps typography following one.
    pub fn set_typewriter(&self, anchor: Option<f32>) {
        let mut st = self.state.borrow_mut();
        st.typewriter = anchor.map(|f| f.clamp(0.0, 1.0));
        st.last_chase_y = None;
    }

    /// Current typewriter anchor.
    pub fn get_typewriter(&self) -> Option<f32> {
        self.state.borrow().typewriter
    }

    /// Narrow (or restore) what the keyboard may do — the [`EditorHandle`]
    /// counterpart of [`RichTextEditor::set_command_filter`], for hosts that
    /// drive a drafting mode from a settings or session effect after the editor
    /// is mounted.
    pub fn set_command_filter(&self, filter: policy::CommandFilter) {
        self.state.borrow_mut().policy.command_filter = filter;
    }

    /// The filter currently in force on this editor.
    pub fn command_filter(&self) -> policy::CommandFilter {
        self.state.borrow().policy.command_filter
    }

    /// Draw an ambient band behind the caret's sentence or paragraph — the [`EditorHandle`]
    /// counterpart of [`RichTextEditor::set_caret_highlight`], for hosts that re-push it from a
    /// settings or theme effect after the editor is mounted.
    pub fn set_caret_highlight(&self, highlight: Option<caret_highlight::CaretHighlight>) {
        set_caret_highlight(&self.state, highlight);
    }

    /// What this editor's caret band is currently configured to draw.
    pub fn get_caret_highlight(&self) -> Option<caret_highlight::CaretHighlight> {
        self.state
            .borrow()
            .caret_highlight
            .as_ref()
            .and_then(|s| s.config())
    }

    /// The caret's rectangle in **absolute window (tree) coordinates** — the
    /// [`EditorHandle`] counterpart of [`RichTextEditor::caret_window_rect`].
    /// `None` when unfocused or not yet laid out.
    pub fn caret_window_rect(&self) -> Option<teksilo_canvas::Rect> {
        self::keyboard::caret_window_rect(&self.state.borrow())
    }

    /// Apply an arbitrary [`TextFormat`] (escape hatch for fields not
    /// covered by the dedicated setters: `letter_spacing`,
    /// `foreground_color`, …).
    pub fn apply_text_format(&self, fmt: TextFormat) {
        self.apply_char_format(fmt);
    }

    /// Toggle bold on the current selection.
    pub fn toggle_bold(&self) {
        let current = self.caret_char_format().font_bold.unwrap_or(false);
        self.set_bold(!current);
    }

    /// Toggle italic on the current selection.
    pub fn toggle_italic(&self) {
        let current = self.caret_char_format().font_italic.unwrap_or(false);
        self.set_italic(!current);
    }

    /// Toggle underline on the current selection.
    pub fn toggle_underline(&self) {
        let current = self.caret_char_format().font_underline.unwrap_or(false);
        self.set_underline(!current);
    }

    /// Toggle strikethrough on the current selection.
    pub fn toggle_strikethrough(&self) {
        let current = self.caret_char_format().font_strikeout.unwrap_or(false);
        self.set_strikethrough(!current);
    }

    /// Whether the selection / typing position is bold.
    pub fn is_bold(&self) -> bool {
        self.caret_char_format().font_bold.unwrap_or(false)
    }

    /// Whether italic.
    pub fn is_italic(&self) -> bool {
        self.caret_char_format().font_italic.unwrap_or(false)
    }

    // ── Hyperlinks ───────────────────────────────────────────────
    //
    // A link is a character format, not an object: applying one merges a
    // destination onto a range, so any bold or italic already there survives
    // and no markup has to be escaped. What it does not get for free is
    // removal — every field of a merge means "leave this alone" when unset —
    // hence `clear_link` rather than "set the destination to nothing".

    /// Point the selection at `href`.
    ///
    /// Merges, so formatting already on the range is kept. A collapsed
    /// selection formats nothing (as everywhere else), so a caller linking
    /// existing text should select it first — see
    /// [`link_at_caret`](Self::link_at_caret) for the range of a link already
    /// there.
    pub fn set_link(&self, href: &str) {
        self.apply_char_format(TextFormat {
            anchor_href: Some(href.to_string()),
            ..Default::default()
        });
    }

    /// Take the link off the selection, leaving its text.
    pub fn clear_link(&self) {
        self.apply_char_format(TextFormat {
            clear_link: true,
            ..Default::default()
        });
    }

    /// The link the caret is in, and how far it reaches.
    ///
    /// Coalesced across the runs an inner mark splits a link into, so the
    /// range covers the whole link rather than the piece under the caret.
    /// `None` when the caret is not on a link.
    pub fn link_at_caret(&self) -> Option<LinkExtent> {
        self.state.borrow().cursor.link_at_caret()
    }

    /// Whether the caret / selection sits on a link.
    pub fn is_link(&self) -> bool {
        self.caret_char_format().is_anchor.unwrap_or(false)
    }

    /// Whether underline.
    pub fn is_underline(&self) -> bool {
        self.caret_char_format().font_underline.unwrap_or(false)
    }

    /// Whether strikethrough.
    pub fn is_strikethrough(&self) -> bool {
        self.caret_char_format().font_strikeout.unwrap_or(false)
    }

    // --- Vertical alignment (super / subscript) ----------------------------
    //
    // See [`RichTextEditor::set_superscript`]: one tri-state property shown as
    // two toggles, because a run cannot be both raised and lowered.

    /// Raise the selection to superscript, or return it to the baseline.
    pub fn set_superscript(&self, enabled: bool) {
        self.set_vertical_alignment(if enabled {
            CharVerticalAlignment::SuperScript
        } else {
            CharVerticalAlignment::Normal
        });
    }

    /// Lower the selection to subscript, or return it to the baseline.
    pub fn set_subscript(&self, enabled: bool) {
        self.set_vertical_alignment(if enabled {
            CharVerticalAlignment::SubScript
        } else {
            CharVerticalAlignment::Normal
        });
    }

    /// Set the selection's vertical alignment directly.
    pub fn set_vertical_alignment(&self, alignment: CharVerticalAlignment) {
        self.apply_char_format(TextFormat {
            vertical_alignment: Some(alignment),
            ..Default::default()
        });
    }

    /// The caret's vertical alignment, `Normal` when unset.
    pub fn get_vertical_alignment(&self) -> CharVerticalAlignment {
        self.caret_char_format()
            .vertical_alignment
            .unwrap_or(CharVerticalAlignment::Normal)
    }

    /// True while the caret sits in superscript text.
    pub fn is_superscript(&self) -> bool {
        self.get_vertical_alignment() == CharVerticalAlignment::SuperScript
    }

    /// True while the caret sits in subscript text.
    pub fn is_subscript(&self) -> bool {
        self.get_vertical_alignment() == CharVerticalAlignment::SubScript
    }

    /// Flip superscript on the selection. Turning it on replaces subscript.
    pub fn toggle_superscript(&self) {
        self.set_superscript(!self.is_superscript());
    }

    /// Flip subscript on the selection. Turning it on replaces superscript.
    pub fn toggle_subscript(&self) {
        self.set_subscript(!self.is_subscript());
    }

    // --- Block-format query / apply ----------------------------------------

    /// Apply an arbitrary [`BlockFormat`] to the caret's block.
    pub fn apply_block_format(&self, fmt: BlockFormat) {
        let st = self.state.borrow();
        let _ = st.cursor.set_block_format(&fmt);
    }

    /// Set paragraph alignment for the caret's block.
    pub fn set_alignment(&self, alignment: Alignment) {
        self.apply_block_format(BlockFormat {
            alignment: Some(alignment),
            ..Default::default()
        });
    }

    /// Unset the block's direction, handing the paragraph back to
    /// automatic detection.
    ///
    /// Not the same as setting left-to-right. An explicit direction
    /// *pins* the paragraph and overrides the bidi algorithm, so
    /// "clearing" a direction by writing `LeftToRight` would force
    /// Arabic and Hebrew prose to lay out backwards. Only an unset
    /// direction lets the text speak for itself.
    pub fn clear_direction(&self) {
        self.apply_block_format(BlockFormat {
            clear_direction: true,
            ..Default::default()
        });
    }

    /// Set the base reading direction of the caret's block. See
    /// [`RichTextEditor::set_direction`].
    pub fn set_direction(&self, direction: TextDirection) {
        self.apply_block_format(BlockFormat {
            direction: Some(direction),
            ..Default::default()
        });
    }

    /// Set heading level for the caret's block. `0` = plain paragraph,
    /// `1..=6` follow the HTML `<h1>..<h6>` convention.
    pub fn set_heading_level(&self, level: u8) {
        self.apply_block_format(BlockFormat {
            heading_level: Some(level),
            ..Default::default()
        });
    }

    /// Current block alignment.
    pub fn get_alignment(&self) -> Alignment {
        self.state
            .borrow()
            .cursor
            .block_format()
            .ok()
            .and_then(|f| f.alignment)
            .unwrap_or(Alignment::Left)
    }

    /// The block's explicitly-set reading direction, if it has one.
    ///
    /// `None` means the writer never chose — the bidi algorithm decides
    /// from the text. That is a genuinely different state from an
    /// explicit left-to-right, so it is reported rather than defaulted:
    /// a toggle needs to show "auto" as its own setting.
    pub fn get_direction(&self) -> Option<TextDirection> {
        self.state
            .borrow()
            .cursor
            .block_format()
            .ok()
            .and_then(|f| f.direction)
    }

    /// Current heading level (0 = plain paragraph).
    pub fn get_heading_level(&self) -> u8 {
        self.state
            .borrow()
            .cursor
            .block_format()
            .ok()
            .and_then(|f| f.heading_level)
            .unwrap_or(0)
    }

    // --- Lists -------------------------------------------------------------

    /// Wrap the caret's block in a list. `ordered = true` uses decimal
    /// numbering, `false` uses bullet discs.
    pub fn insert_list(&self, ordered: bool) {
        let style = if ordered {
            ListStyle::Decimal
        } else {
            ListStyle::Disc
        };
        self.create_list(style);
    }

    /// Wrap the caret's block in a list with an explicit
    /// [`ListStyle`].
    pub fn create_list(&self, style: ListStyle) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.create_list(style);
        }
        sync_cursor_signals(&self.state);
    }

    /// Indent the caret's current list item by one nesting level.
    /// No-op when the caret is not inside a list. Equivalent to Tab.
    pub fn indent(&self) {
        keyboard::indent_current_block(&mut self.state.borrow_mut());
        sync_cursor_signals(&self.state);
    }

    /// Outdent the caret's current list item by one nesting level.
    /// No-op at depth 0. Equivalent to Shift+Tab.
    pub fn outdent(&self) {
        keyboard::dedent_current_block(&mut self.state.borrow_mut());
        sync_cursor_signals(&self.state);
    }

    /// Take the caret's block out of its list entirely, leaving a plain
    /// paragraph. No-op when the caret is not inside a list.
    ///
    /// See [`RichTextEditor::remove_from_list`] for why this is separate from
    /// [`outdent`](Self::outdent), which stops at depth 0 by design.
    pub fn remove_from_list(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.remove_current_block_from_list();
        }
        sync_cursor_signals(&self.state);
    }

    // --- Blockquotes -------------------------------------------------------

    /// True iff the caret currently sits inside a blockquote frame at
    /// any nesting depth.
    pub fn is_in_blockquote(&self) -> bool {
        let st = self.state.borrow();
        st.cursor.is_in_blockquote()
    }

    /// True iff the selection spans more than one frame — the
    /// "Toggle blockquote" affordance should be disabled in this case.
    pub fn selection_spans_multiple_frames(&self) -> bool {
        let st = self.state.borrow();
        st.cursor.selection_spans_multiple_frames()
    }

    /// Wrap the current block/selection in a blockquote, or unwrap the
    /// innermost enclosing blockquote if already inside one. Toolbar
    /// counterpart for a Ctrl+Shift+Q-style toggle.
    pub fn toggle_blockquote(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.toggle_blockquote();
        }
        sync_cursor_signals(&self.state);
    }

    /// Wrap the current block in a deeper nested quote. Equivalent to
    /// Tab inside a blockquote.
    pub fn increase_blockquote_depth(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.increase_blockquote_depth();
        }
        sync_cursor_signals(&self.state);
    }

    /// Pop the caret out of one blockquote nesting level. Equivalent to
    /// Shift+Tab inside a blockquote.
    pub fn decrease_blockquote_depth(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.decrease_blockquote_depth();
        }
        sync_cursor_signals(&self.state);
    }

    // --- Tables ------------------------------------------------------------

    /// Insert a fresh `rows × columns` table at the caret.
    pub fn insert_table(&self, rows: usize, columns: usize) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_table(rows, columns);
        }
        sync_cursor_signals(&self.state);
    }

    /// Remove the table containing the caret. No-op outside a table.
    pub fn remove_current_table(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.remove_current_table();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a row above the caret's current table row.
    pub fn insert_row_above(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_row_above();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a row below the caret's current table row.
    pub fn insert_row_below(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_row_below();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a column before the caret's current table column.
    pub fn insert_column_before(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_column_before();
        }
        sync_cursor_signals(&self.state);
    }

    /// Insert a column after the caret's current table column.
    pub fn insert_column_after(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.insert_column_after();
        }
        sync_cursor_signals(&self.state);
    }

    /// Remove the caret's current table row.
    pub fn remove_current_row(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.remove_current_row();
        }
        sync_cursor_signals(&self.state);
    }

    /// Remove the caret's current table column.
    pub fn remove_current_column(&self) {
        {
            let st = self.state.borrow();
            let _ = st.cursor.remove_current_column();
        }
        sync_cursor_signals(&self.state);
    }

    /// Whether the caret is currently inside a table cell.
    pub fn is_in_table(&self) -> bool {
        self.state.borrow().cursor.current_table().is_some()
    }

    // --- History -----------------------------------------------------------

    /// Undo the most recent edit. No-op when the undo stack is empty.
    pub fn undo(&self) {
        let _ = self.state.borrow().document.undo();
        sync_cursor_signals(&self.state);
    }

    /// Close the current undo entry, so the next edit starts a new one.
    ///
    /// Typing coalesces into word-sized undo steps by looking only at the shape
    /// of two edits — adjacent, moments apart. It cannot see that the user did
    /// something else in between, somewhere else in the application, that they
    /// would remember as a dividing line. A host that knows one was crossed says
    /// so here, and the burst before it stops merging with the burst after.
    pub fn break_undo_merge(&self) {
        self.state.borrow().document.break_undo_merge();
    }

    /// Redo the most recently undone edit. No-op when the redo stack
    /// is empty.
    pub fn redo(&self) {
        let _ = self.state.borrow().document.redo();
        sync_cursor_signals(&self.state);
    }

    // --- Edit blocks (composite undo) --------------------------------------
    //
    // See [`RichTextEditor::begin_edit_block`] for the rationale: a toolbar
    // action composed of several commands should cost one Ctrl+Z, not one per
    // property it touched.

    /// Begin grouping subsequent edits into a single undo entry. Pair with
    /// [`end_edit_block`](Self::end_edit_block), or prefer the scoped
    /// [`edit_block`](Self::edit_block).
    pub fn begin_edit_block(&self) {
        self.state.borrow().cursor.begin_edit_block();
    }

    /// Close the group opened by [`begin_edit_block`](Self::begin_edit_block).
    pub fn end_edit_block(&self) {
        self.state.borrow().cursor.end_edit_block();
    }

    /// Run `edits` as one undo entry — the pairing-safe form.
    pub fn edit_block<R>(&self, edits: impl FnOnce() -> R) -> R {
        self.begin_edit_block();
        let result = edits();
        self.end_edit_block();
        result
    }

    // --- Clipboard ---------------------------------------------------------
    //
    // Programmatic counterparts of Ctrl+C / Ctrl+X / Ctrl+V /
    // Ctrl+Shift+V, mirroring [`RichTextEditor::copy`] / `cut` / `paste` /
    // `paste_unformatted` body-for-body. Each takes the active
    // [`EventContext`](teksilo_core::widget::EventContext) because the
    // clipboard handle is looked up via `ctx.app_state::<ClipboardHandle>()`,
    // which only has a value during event dispatch — so these are callable
    // from an `on_activate_fn` / context-menu closure that captured just a
    // handle. A call site holding `&mut EventContext` can pass `&ctx`
    // directly; Rust reborrows automatically.

    /// Copy the current selection to the system clipboard (plain + HTML
    /// payloads). No-op when there is no selection. See
    /// [`RichTextEditor::copy`].
    pub fn copy(&self, ctx: &teksilo_core::widget::EventContext) {
        let mut st = self.state.borrow_mut();
        clipboard::copy(&mut st, ctx);
    }

    /// Cut the current selection: copy first, then remove. See
    /// [`RichTextEditor::cut`].
    pub fn cut(&self, ctx: &teksilo_core::widget::EventContext) {
        {
            let mut st = self.state.borrow_mut();
            clipboard::cut(&mut st, ctx);
        }
        sync_cursor_signals(&self.state);
    }

    /// Paste from the system clipboard. Prefers an in-process fragment
    /// over HTML over plain text. See [`RichTextEditor::paste`].
    pub fn paste(&self, ctx: &teksilo_core::widget::EventContext) {
        {
            let mut st = self.state.borrow_mut();
            clipboard::paste(&mut st, ctx);
        }
        sync_cursor_signals(&self.state);
    }

    /// Paste plain text only, stripping any rich payload. See
    /// [`RichTextEditor::paste_unformatted`].
    pub fn paste_unformatted(&self, ctx: &teksilo_core::widget::EventContext) {
        {
            let mut st = self.state.borrow_mut();
            clipboard::paste_unformatted(&mut st, ctx);
        }
        sync_cursor_signals(&self.state);
    }

    /// Whether a paste would insert anything — `true` iff the system
    /// clipboard carries text **or** an HTML payload. A point-in-time
    /// query (clipboard contents are not reactively observable), taking
    /// the active [`EventContext`](teksilo_core::widget::EventContext).
    /// Use it to drive a context-menu / toolbar Paste enable-state,
    /// re-querying on menu-open. Mirrors [`RichTextEditor::can_paste`].
    pub fn can_paste(&self, ctx: &teksilo_core::widget::EventContext) -> bool {
        clipboard::can_paste(ctx)
    }

    // --- Selection ---------------------------------------------------------

    /// Select the entire document programmatically. Resets the Ctrl+A
    /// ladder so a subsequent Ctrl+A starts fresh at level 1. Mirrors
    /// [`RichTextEditor::select_all`].
    pub fn select_all(&self) {
        {
            let mut st = self.state.borrow_mut();
            st.cursor.select(SelectionType::Document);
            st.select_all_level = 0;
            st.select_all_anchor_cell = None;
        }
        sync_cursor_signals(&self.state);
    }

    /// Delete the current selection. No-op when nothing is selected.
    /// Mirrors [`RichTextEditor::delete_selection`].
    pub fn delete_selection(&self) {
        {
            let st = self.state.borrow();
            if st.cursor.has_selection() {
                let _ = st.cursor.remove_selected_text();
            }
        }
        sync_cursor_signals(&self.state);
    }

    // --- Reactive signal accessors -----------------------------------------

    /// Bumps on every format-only document event (bold / italic /
    /// heading / alignment / list-style changes). See
    /// [`RichTextEditor::format_version`].
    pub fn format_version(&self) -> Signal<u64> {
        self.state.borrow().format_version.clone()
    }

    /// The **live** caret offset — reads `cursor.position()` directly, unbatched. Unlike
    /// [`cursor_position_signal`](Self::cursor_position_signal), whose stored value lags one frame
    /// behind a just-typed printable character (the insert is deferred to the frame loop and the
    /// signal is only re-synced on the *next* caret event), this always reflects the true caret —
    /// what a host that recomputes highlights on a frame tick must read. Mirrors
    /// [`RichTextEditor::cursor_position`].
    pub fn cursor_position(&self) -> usize {
        self.state.borrow().cursor.position()
    }

    /// `true` while an IME composition is actively in progress. Mirrors
    /// [`RichTextEditor::is_composing`].
    pub fn is_composing(&self) -> bool {
        self.state.borrow().ime_preedit.is_some()
    }

    /// Reactive caret position signal.
    pub fn cursor_position_signal(&self) -> Signal<usize> {
        self.state.borrow().cursor_position.clone()
    }

    /// Reactive selection anchor signal.
    pub fn cursor_anchor_signal(&self) -> Signal<usize> {
        self.state.borrow().cursor_anchor.clone()
    }

    /// Reactive selection-non-empty signal.
    pub fn has_selection(&self) -> Signal<bool> {
        self.state.borrow().has_selection.clone()
    }

    /// Reactive undo-availability signal (toolbar enable-state source).
    pub fn can_undo(&self) -> Signal<bool> {
        self.state.borrow().can_undo.clone()
    }

    /// Reactive redo-availability signal.
    pub fn can_redo(&self) -> Signal<bool> {
        self.state.borrow().can_redo.clone()
    }
}

/// Private leaf body for [`RichTextEditor`].
///
/// Pure rendering surface: layout (intrinsic / greedy via
/// `min_lines` / `max_lines`), `place_children` (records the
/// viewport on `state`), `paint` (glyph runs, caret, selection),
/// `accessibility` (Role::MultilineTextInput / Role::Document plus
/// the flow-snapshot walk that emits paragraph + text-run children).
///
/// Handlers, focus, the context-menu factory, and per-frame ticking
/// all live on the composing outer [`RichTextEditor`]; the body
/// itself is non-focusable and has no event handlers. The shared
/// `state` is what links them — both widgets hold an `Rc` to the
/// same [`EditorState`], so a key event on the wrapper mutates the
/// state and the body re-paints on the next frame.
pub(crate) struct RichTextEditorBody {
    state: SharedState,
    min_lines: Option<u32>,
    max_lines: Option<u32>,
}

impl std::fmt::Debug for RichTextEditorBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RichTextEditorBody")
            .field("policy", &self.state.borrow().policy)
            .finish_non_exhaustive()
    }
}

/// How tall this text is likely to be, before anything has laid it out.
///
/// See the call site in [`RichTextEditorBody::layout_response`] for why a guess
/// beats the zero it replaces. Two O(1) document reads and some arithmetic; no
/// shaping, no glyph cache, nothing that could be slow enough to matter in a
/// layout pass.
///
/// **The typography is the half that decides whether this is useful.** A first cut
/// counted bare lines at the font's natural height and came out well under the
/// truth for manuscript prose, which is set with a line-height multiplier and space
/// between paragraphs — the estimate was missing a third of the page and the rows it
/// sized still visibly grew when they finally laid out. So:
///
/// * lines are counted at the font's own advance, since that is what decides how
///   many characters fit on one, and
/// * each line is then given the **multiplied** height, and each block the space
///   above and below it that a body paragraph gets.
///
/// The mean advance is taken as half the font's line height. That is roughly right
/// for proportional Latin text at ordinary sizes and roughly wrong for everything
/// else, which is acceptable for a number whose only competition is a constant and
/// whose lifetime is one frame.
/// Mean glyph advance as a fraction of the font's natural line height.
///
/// **Measured, not derived.** Thirty-two real manuscript scenes were laid out in a
/// running window and compared against what this function claimed for each, at a
/// 447 px measure in Literata at 1.6 line height:
///
/// | scene | guess | real | ratio |
/// |---|---|---|---|
/// | 23 443 chars | 19 586 | 17 768 | 1.10 |
/// | 20 798 chars | 17 028 | 15 578 | 1.09 |
/// | 16 493 chars | 13 860 | 12 827 | 1.08 |
///
/// The bias was 1.06–1.12 across a 1.4× range of scene sizes: a scale error, not
/// noise, and 0.37 solved back to 0.335 on every one of them. Two earlier values
/// were reasoned about rather than measured — 0.5 from "half the font size", then
/// 0.37 from dividing that by a nominal line height — and both were wrong by more
/// than this whole correction.
///
/// It is a *typical* value, and it is font-dependent: a wider or narrower face moves
/// it, which is why the accuracy test allows ±25% rather than pretending otherwise.
/// If that stops being good enough, the answer is to learn it from the first real
/// layout the process performs rather than to tune the constant again.
const MEAN_ADVANCE_OVER_LINE_HEIGHT: f32 = 0.335;

fn estimated_content_height(
    document: &teksilo_text::text_document::TextDocument,
    width: f32,
    font_line_h: f32,
    typography: &teksilo_text::EditorTypographyDefaults,
) -> f32 {
    if width <= 0.0 || font_line_h <= 0.0 {
        return 0.0;
    }
    // Characters per line from the **font's** line height: the multiplier below
    // spaces lines further apart, it does not make the glyphs wider.
    let per_line = (width / (font_line_h * MEAN_ADVANCE_OVER_LINE_HEIGHT)).max(1.0);
    let chars = document.character_count() as f32;
    let blocks = document.block_count().max(1) as f32;
    // Wrapped lines, plus **half** a line per block for the ragged last one of each.
    // Half rather than one: a block takes `ceil(chars / per_line)` lines, which
    // averages half a line more than the division, and charging a whole one over-
    // counted a scene of many short paragraphs by more than the wrapping itself.
    // Floored at one line per block, because an empty paragraph still takes a line.
    let lines = (chars / per_line + blocks * 0.5).max(blocks);
    let line_h = font_line_h * typography.line_height.max(0.1);
    let per_block = typography.paragraph_spacing_before + typography.paragraph_spacing_after;
    let h = lines * line_h + blocks * per_block.max(0.0);
    #[cfg(feature = "debug-traces")]
    if height_debug() {
        eprintln!(
            "HEIGHT-EST chars={chars:.0} blocks={blocks:.0} width={width:.1} \
             font_lh={font_line_h:.2} mult={:.2} per_line={per_line:.1} -> {h:.1}",
            typography.line_height
        );
    }
    h
}

/// Whether to print what the height guess and the real layout each came up with.
///
/// `TEKSILO_HEIGHT_DEBUG=1`, and only in a build with the `debug-traces` feature.
/// Read once — this sits in a layout pass, and an environment lookup per
/// measurement would be a real cost for a diagnostic that is off for everyone.
///
/// It earns its place: the guess above was wrong three separate ways before anyone
/// could see it, and the one that mattered most — being asked to measure at 76 px
/// when the text wraps at 447 — was invisible to every test and obvious in one line
/// of this output.
///
/// Behind a feature as well as a variable, and the traces are `#[cfg]` out rather
/// than merely switched off: a runtime `false` still leaves every format string in
/// the binary, which is measurable. A diagnostic nobody can switch on has no
/// business being reachable in a release, and an environment variable is reachable
/// by anyone.
#[cfg(feature = "debug-traces")]
fn height_debug() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var_os("TEKSILO_HEIGHT_DEBUG").is_some())
}

impl Widget for RichTextEditorBody {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Bind `caret_visible` to the framework's repaint tracker so
        // that every toggle in the frame-tick effect marks **this
        // body** widget `needs_paint` — the caret is painted in
        // `RichTextEditorBody::paint`. Skipped for `CaretPolicy::Hidden`.
        {
            let st = self.state.borrow();
            let caret_policy = st.policy.caret_policy;
            let caret_visible = st.caret_visible.clone();
            drop(st);
            if caret_policy != CaretPolicy::Hidden {
                let self_id = ctx.self_id();
                caret_visible.bind_to(
                    self_id,
                    ctx.binding_registry(),
                    teksilo_core::binding::BindingLevel::RepaintOnly,
                );
            }
        }

        // Bind document_version at `BindingLevel::AccessibilityOnly` so
        // text / format edits flip the tree's `a11y_dirty` flag through
        // **this body** — its `accessibility()` is the one that emits
        // the editor's Role::MultilineTextInput / Role::Document and
        // walks the flow snapshot.
        //
        // ALSO bind at `RepaintOnly` so the widget's needs_paint flips
        // on every text / format change. Without this, paint() only
        // ran on caret-blink (the only other RepaintOnly binding), and
        // the post-fix dispatch's `last_relayout_block_id.take()` was
        // consumed on the wrong tick — leaving text edits invisible
        // until a resize forced a full re-layout.
        {
            let st = self.state.borrow();
            let document_version = st.document_version.clone();
            drop(st);
            let self_id = ctx.self_id();
            document_version.bind_to(
                self_id,
                ctx.binding_registry(),
                teksilo_core::binding::BindingLevel::AccessibilityOnly,
            );
            document_version.bind_to(
                self_id,
                ctx.binding_registry(),
                teksilo_core::binding::BindingLevel::RepaintOnly,
            );
        }

        // Bind `scroll_y`, `scroll_x`, `cursor_position`, `cursor_anchor`,
        // and `has_selection` at RepaintOnly so the widget marks
        // needs_paint immediately on scroll, cursor move, and selection
        // change. Without these, paint() only ran on caret-blink and
        // text-version bumps — so scroll/selection changes appeared
        // delayed by up to 500ms (in sync with the next caret toggle).
        //
        // The cursor_only render path inside text-typeset falls back to
        // a full render automatically when scroll drifted since
        // the last full render, so this binding is correctness-safe.
        {
            let st = self.state.borrow();
            let scroll_y = st.scroll_y.clone();
            let scroll_x = st.scroll_x.clone();
            let cursor_position = st.cursor_position.clone();
            let cursor_anchor = st.cursor_anchor.clone();
            let has_selection = st.has_selection.clone();
            drop(st);
            let self_id = ctx.self_id();
            for signal in [&scroll_y, &scroll_x] {
                signal.bind_to(
                    self_id,
                    ctx.binding_registry(),
                    teksilo_core::binding::BindingLevel::RepaintOnly,
                );
            }
            // Caret and anchor are repaint-only for geometry, but they ALSO
            // change what the a11y walk reports via `set_text_selection_to`. A
            // caret-only move (arrow key, click, drag-select) emits no document
            // event, so `document_version` never bumps; without an
            // `AccessibilityOnly` binding here `a11y_dirty` never flips and a
            // screen reader hears the caret frozen at the last edit. Bind both
            // levels — the two-level pattern `document_version` uses. Selecting
            // moves the caret and/or anchor, so `has_selection` (derived from
            // them) needs no separate a11y binding.
            for signal in [&cursor_position, &cursor_anchor] {
                signal.bind_to(
                    self_id,
                    ctx.binding_registry(),
                    teksilo_core::binding::BindingLevel::RepaintOnly,
                );
                signal.bind_to(
                    self_id,
                    ctx.binding_registry(),
                    teksilo_core::binding::BindingLevel::AccessibilityOnly,
                );
            }
            has_selection.bind_to(
                self_id,
                ctx.binding_registry(),
                teksilo_core::binding::BindingLevel::RepaintOnly,
            );
        }

        Vec::new()
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        let w = proposal.width.unwrap_or(200.0).max(0.0);

        // Greedy mode (default, behaviour unchanged): both knobs
        // unset → consume the proposal exactly as before.
        if self.min_lines.is_none() && self.max_lines.is_none() {
            let h = proposal.height.unwrap_or(100.0).max(0.0);
            return (Size::new(w, h)).into();
        }

        // Intrinsic mode: clamp content height to `[min_h, max_h]`
        // where each bound is `n * line_height`. The clamp is a
        // hard cap — we ignore the proposal's height and let the
        // vertical scroll bar take over past `max_lines`.
        // Remember the widest measure anything has asked for, before reading the
        // state below — see where it is used for why the widest and not this pass's.
        {
            let mut st = self.state.borrow_mut();
            if let Some(w) = proposal.width
                && w > st.widest_measured_width
            {
                st.widest_measured_width = w;
            }
        }
        let st = self.state.borrow();
        // `default_line_height()` is the *unscaled* line height (its standalone
        // shaper path uses font_scale = 1.0), but `content_height()` carries the
        // engine's font_scale. Scale the per-line bound to match, or a
        // text-scaled editor would clip at `max_lines` / under-size at
        // `min_lines`.
        let line_scale = st.effective_font_scale(ctx.text_scale);
        let line_h = st.engine.default_line_height() * line_scale;
        // **An estimate rather than a zero before the text has been laid out.**
        //
        // `content_height()` is `0` until `layout_full` has run, and that does not
        // happen until the editor has been through a frame on screen. A zero then
        // falls through to the `min_lines` floor below, so *every* unlaid-out editor
        // claims the same ten lines whatever it holds — a three-thousand-word scene
        // and an empty one measure identically.
        //
        // On a single editor that is invisible: it is on screen, so it lays out.
        // Down a **stream** it is not. A Full Book is a column of editors, most of
        // them below the fold, and the page's height is the sum of their claims —
        // so the scroll extent is wrong by an order of magnitude and settles, a row
        // at a time, as the writer reads. Anything drawing that extent draws the
        // settling: a margin lane gives each row a slice to match the claim, then
        // watches it grow tenfold the moment the row is reached.
        //
        // The estimate is deliberately crude — a mean advance of half the line
        // height, one extra line per block for the ragged last line of each — and
        // being crude is the point. It is thrown away the instant a real layout
        // exists, so its only job is to be closer than a constant, which is not a
        // demanding standard. It is **not** a floor: an over-estimate corrects
        // downwards when the layout lands, where a too-large `min_lines` would
        // leave blank space under short text for the life of the widget.
        //
        // ⚠ **Only when the width is actually known.** `w` above falls back to 200
        // for a proposal that carries none, which is fine for a width but ruinous
        // for a line count: `CenterColumnFlowing` measures its child width-only, and
        // estimating against the fallback made a scene wrap at a quarter of its real
        // measure and claim nearly twice its real height. An unbounded measure gets
        // the old answer — the floor — because without a measure there is genuinely
        // no way to know how many lines the text takes.
        let content_h = match (st.engine.has_full_layout(), proposal.width) {
            (true, _) => st.engine.content_height(),
            // **At the width the text will actually wrap at**, which is the viewport
            // the body was last *placed* at — not the width of whichever measurement
            // pass happens to be asking.
            //
            // Measured in a real window those are not the same number, and the
            // difference is not small: a stream row was asked to measure at 76 px
            // during an early pass, estimated eight characters to a line and so six
            // times its true height, while the layout that followed wrapped it at
            // 447. A guess taken at the wrong measure is worse than no guess — it is
            // the same jump it was meant to remove, pointing the other way.
            //
            // Zero before the body has ever been placed, and then the proposal is the
            // only thing on offer; after the first placement the viewport is the
            // truth. `w` above is deliberately not reused: its 200 px fallback is a
            // sane default for a width and a ruinous one for a line count.
            (false, _) if st.estimate_height_before_layout => {
                // The viewport if this body has been placed, else the **widest**
                // width anything has asked it to measure at.
                //
                // Not the width of the pass that happens to be asking: a real window
                // proposes 76 px to a stream row whose text wraps at 447, and
                // guessing against that claimed six times the true height. Nor the
                // viewport alone, which was tried and is worse — a stream's rows are
                // rebuilt often enough that it is almost always still zero, so the
                // guess simply never ran and every row fell back to the floor it was
                // meant to replace.
                let width = st.viewport_width.max(st.widest_measured_width);
                if width > 0.0 {
                    estimated_content_height(
                        &st.document,
                        width,
                        line_h,
                        st.engine.typography_defaults(),
                    )
                } else {
                    0.0
                }
            }
            (false, _) => 0.0,
        };
        drop(st);

        let min_h = self.min_lines.map(|n| n as f32 * line_h).unwrap_or(0.0);
        let max_h = self
            .max_lines
            .map(|n| n as f32 * line_h)
            .unwrap_or(f32::INFINITY);
        let intrinsic_h = content_h.clamp(min_h, max_h);
        Size::new(w, intrinsic_h.max(0.0)).into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        _children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        // The body is a leaf, but the layout walker hands every widget its final
        // bounds here — and layout runs before paint, so this is the earliest
        // (hence authoritative) point at which the viewport can be adopted.
        // `sync_viewport` owns the whole handoff, including `engine.set_viewport`
        // and the relayout flag; paint calls it again as an idempotent echo. See
        // its docs for why the writes must not be split.
        self.state.borrow_mut().sync_viewport(bounds);
    }

    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
        let mut st = self.state.borrow_mut();

        // Sync the engine's default text color with the active theme
        // so dark / light mode swaps reach the rendered glyphs. The
        // engine reads `text_color` fresh on every `render()` and
        // does not bake it into a glyph cache, so a per-paint write
        // is cheap. Skipped when the app pinned a color via
        // `RichTextEditor::text_color(...)`.
        //
        // The render frame DOES cache colors baked into glyph quads,
        // though — the cursor-only and block-only render paths reuse
        // those cached quads. So when the theme colour actually
        // changes, we must dispatch a full render this frame, or the
        // visible glyphs keep painting in the old colour until the
        // next typing / scroll event happens to bump up to a Full
        // path on its own.
        // An app-set `text_color` (Color / role / Signal) is resolved against
        // the active theme each paint; otherwise track the theme's `editor_fg`.
        {
            let new_color = match &st.text_color_prop {
                Some(prop) => prop.resolve(ctx.theme, true).to_array(),
                None => ctx.theme.colors.editor_fg.to_array(),
            };
            st.engine.set_text_color(new_color);
            if st.last_text_color != Some(new_color) {
                st.last_text_color = Some(new_color);
                st.pending_full_render = true;
            }
        }

        // Caret colour: app override resolved each paint, else the theme's
        // `editor_caret` role. The engine defaults the cursor to opaque black,
        // so without this the blinking caret stays black under a dark theme.
        // Cursor decorations are regenerated on every render (the cursor-only
        // path included), so a colour change only needs a render this frame —
        // force one so a swap doesn't wait for the next blink toggle.
        {
            let new_caret = match &st.caret_color_prop {
                Some(prop) => prop.resolve(ctx.theme, true).to_array(),
                None => ctx.theme.colors.editor_caret.to_array(),
            };
            st.engine.set_cursor_color(new_caret);
            if st.last_cursor_color != Some(new_caret) {
                st.last_cursor_color = Some(new_caret);
                st.pending_full_render = true;
            }
        }

        // Selection highlight. A custom colour (set via `.selection_color`) is
        // used as-is and is NOT auto-desaturated when the window goes inactive
        // — matching macOS, where an explicit selection colour opts out of
        // system management. Otherwise the theme drives it, window-aware: the
        // vivid `editor_selection_bg` while the window is active, the muted
        // `selection_bg_inactive` while it is not. Resolved each paint and
        // cached, so a change (theme, custom colour, or window-active flip)
        // just needs a render this frame.
        let new_sel = if let Some(prop) = st.selection_color_prop.as_ref() {
            prop.resolve(ctx.theme, true).to_array()
        } else if ctx.window_active {
            ctx.theme.colors.editor_selection_bg.to_array()
        } else {
            ctx.theme.colors.selection_bg_inactive.to_array()
        };
        if st.last_selection_color != Some(new_sel) {
            st.engine.set_selection_color(new_sel);
            st.last_selection_color = Some(new_sel);
            st.pending_full_render = true;
        }

        // Code block surface colours come from the same theme path
        // (`editor_code_block_bg` / `editor_code_block_fg`). Unlike
        // `text_color`, these are baked into the converted
        // `BlockLayoutParams` at `layout_full` / `relayout_block`
        // time, so the typesetter does NOT pick them up on a render
        // pass — we need a full re-layout when they change. Setting
        // `needs_full_layout = true` schedules that for the same
        // frame; `pending_full_render` covers the render side.
        let new_code_bg = ctx.theme.colors.editor_code_block_bg.to_array();
        let new_code_fg = Some(ctx.theme.colors.editor_code_block_fg.to_array());
        st.engine.set_code_block_background(new_code_bg);
        st.engine.set_code_block_foreground(new_code_fg);
        if st.last_code_block_bg != Some(new_code_bg) || st.last_code_block_fg != new_code_fg {
            st.last_code_block_bg = Some(new_code_bg);
            st.last_code_block_fg = new_code_fg;
            st.needs_full_layout = true;
            st.pending_full_render = true;
        }

        // Link colour rides the same path, and for the same reason: it is
        // baked into the shaped runs at layout time, so a theme swap needs a
        // full re-layout rather than a repaint. Sharing `TextRole::Link` with
        // every other link in the app is the point — a hyperlink in prose and
        // one in a panel should not be two different blues.
        let new_link_fg = Some(ctx.theme.colors.text_link.to_array());
        st.engine.set_link_foreground(new_link_fg);
        if st.last_link_fg != new_link_fg {
            st.last_link_fg = new_link_fg;
            st.needs_full_layout = true;
            st.pending_full_render = true;
        }

        // The engine reads the HiDPI display scale factor from the
        // shared `TypesetterBridge` on every `layout_full`, exactly
        // like `TextWidget` does internally. No widget-side plumbing
        // — this is a render-pipeline concern, invisible to the
        // widget author.

        // Logical font scale: a11y text scale (if followed) × per-editor
        // `font_size_scale`. Baked at `layout_full`, so a change forces a
        // relayout + render this frame.
        {
            let target = st.effective_font_scale(ctx.text_scale);
            if st.last_font_scale.is_nan() || (st.last_font_scale - target).abs() > f32::EPSILON {
                st.last_font_scale = target;
                st.engine.set_font_scale(target);
                st.needs_full_layout = true;
                st.pending_full_render = true;
            }
        }

        // Idempotent echo — `place_children` already adopted these exact bounds
        // during layout, so this is normally a no-op. It stays so that any path
        // which paints without a preceding layout still sizes the engine.
        st.sync_viewport(bounds);

        // First-frame guard + viewport-change guard: (re)run the
        // full layout so the render call produces glyphs sized
        // for the current bounds. With per-widget `DocumentFlow`
        // state inside the engine, `has_full_layout()` only
        // reports `false` when this widget has never laid out
        // or when the shared service's HiDPI scale factor has
        // changed since the last layout — there is no
        // cross-widget trampling left to guard against.
        //
        // `did_full_layout` is true on this paint iff we just ran
        // `layout_full` above — which means the render frame must
        // be rebuilt from scratch via `with_render_frame`. The
        // incremental render paths (`with_render_block_only`,
        // `with_render_cursor_only`) assume a valid prior full
        // render exists.
        let did_full_layout = st.needs_full_layout || !st.engine.has_full_layout();
        if did_full_layout {
            let flow = st.flow_snapshot();
            st.engine.layout_full(&flow);
            st.needs_full_layout = false;
            st.content_dirty = true;
            #[cfg(feature = "debug-traces")]
            if height_debug() {
                eprintln!(
                    "HEIGHT-REAL chars={} blocks={} width={:.1} -> {:.1}",
                    st.document.character_count(),
                    st.document.block_count(),
                    st.engine.layout_width(),
                    st.engine.content_height()
                );
            }
        }

        // Update the cursor display every paint so selection
        // highlights follow the caret without needing a frame tick.
        // The caret is suppressed in an inactive window for every policy — the
        // authoritative final gate, covering the one frame between a
        // window-active flip and the build-time effect running.
        let caret_on_now = if st.drop_caret && st.policy.caret_policy != CaretPolicy::Hidden {
            // A drag is overhead: show where it would land. Focus is still
            // wherever the drag started — often another editor entirely — so
            // the focus gate below would hide precisely the caret the writer
            // is aiming with. Steady, not blinking, and never in a read-only
            // editor (`Hidden`), which takes no drop anyway.
            st.window_active
        } else {
            match st.policy.caret_policy {
                CaretPolicy::Hidden => false,
                CaretPolicy::StaticVisible => st.has_focus && st.window_active,
                CaretPolicy::Blinking => st.caret_visible.get() && st.has_focus && st.window_active,
            }
        };
        let cursor_display = teksilo_text::CursorDisplay {
            position: st.cursor.position(),
            anchor: st.cursor.anchor(),
            affinity: st.cursor_affinity,
            visible: caret_on_now,
            selected_cells: Vec::new(),
        };
        st.engine.set_cursor(&cursor_display);

        // Forward the widget's scroll state to the typesetter so
        // viewport culling knows where the visible window is. text-
        // typeset's `render()` only emits glyphs whose flow Y falls
        // inside `[scroll_offset, scroll_offset + viewport_height]`,
        // and the emitted screen coordinates already have
        // `scroll_offset` subtracted — so the paint walker doesn't
        // apply any further offset beyond the widget origin.
        let scroll_y_logical = st.scroll_y.get();
        st.engine.set_scroll_offset(scroll_y_logical);

        // Window the render to the visible clip when opted in (dubious mode).
        // The editor is laid out at its full document height inside an outer
        // ScrollArea, so its own viewport spans the whole document and the
        // viewport-derived cull keeps everything. `ctx.clip_bounds` is the
        // accumulated ancestor clip — the intersection of every clipping
        // ancestor, so this is correct under nested ScrollAreas — mapped into
        // the editor's content space to the band actually on screen. A
        // half-viewport margin each side pre-renders content just off-screen so
        // scrolling never flashes a blank edge. Positioning and hit-testing are
        // untouched: `set_render_window` overrides culling only, and
        // `scroll_offset` stays as set above.
        let render_window = if st.window_to_clip {
            ctx.clip_bounds.map(|clip| {
                // `clip` and `bounds` are screen-space; the render cull works in
                // content space. The visible band's top is the editor's own scroll
                // offset plus however far its top sits above the clip: in dubious
                // mode `scroll_offset` is pinned to 0, but including it keeps the
                // window correct (rather than mis-culling) even for a self-scrolling
                // editor, so this can't silently render the wrong rows.
                let vis_top = (scroll_y_logical + (clip.y - bounds.y)).max(0.0);
                let vis_h = clip.height.max(0.0);
                let margin = vis_h * 0.5;
                ((vis_top - margin).max(0.0), vis_h + 2.0 * margin)
            })
        } else {
            None
        };
        st.engine.set_render_window(render_window);

        // Captured before the split-borrow below (which holds `st` mutably
        // for the rest of the method) so the preedit underline pass can
        // still see them. `cursor_affinity` matches what `caret_rect`
        // queries elsewhere.
        let scroll_x_logical = st.scroll_x.get();
        let ime_preedit_range = st.ime_preedit_range.clone();
        let ime_affinity = st.cursor_affinity;

        // Clip to bounds so overflowing glyphs don't bleed into siblings.
        canvas.set_clip(bounds);

        // Choose the cheapest render path that produces a correct
        // frame for this paint:
        // - Full render: we just rebuilt the layout (no prior frame
        //   to incrementally update), so emit everything from scratch.
        // - Block-only: the frame_loop relayed out exactly one block
        //   since the last paint (single-block edit). Reuse cached
        //   glyphs for the other N-1 blocks.
        // - Cursor-only: nothing structural changed since last
        //   paint — only the cursor blink or selection updated.
        //   Reuses every cached glyph and just refreshes cursor /
        //   selection decorations. Falls back to full render
        //   internally if scroll drifted.
        //
        // Pre-fix, paint() unconditionally called `with_render_frame`,
        // which walked every block on every paint — visible as a
        // ~17% chunk in `rasterize_glyph` / `render_run_glyphs` on
        // the flamegraph because caret blinks and signal updates
        // were forcing a full re-render at ~60 Hz.
        let block_relayout = st.last_relayout_block_id.take();
        let pending_full = std::mem::replace(&mut st.pending_full_render, false);
        enum RenderChoice {
            Full,
            Block(usize),
            CursorOnly,
        }
        // `pending_full` covers the case where `frame_loop::tick`
        // already ran `layout_full` this frame (e.g. on FormatChanged
        // or FlowElementsInserted events from a list-indent edit or
        // Enter key) but cleared `needs_full_layout` before paint ran.
        // Without it, paint would fall through to CursorOnly and the
        // new layout wouldn't render until something else forced a
        // Full pass (resize, scroll out and back into view).
        let choice = if did_full_layout || pending_full {
            RenderChoice::Full
        } else if let Some(bid) = block_relayout {
            RenderChoice::Block(bid)
        } else {
            RenderChoice::CursorOnly
        };

        // Split-borrow the state fields so the paint walker can hold
        // `&engine.with_render_frame(...)`, `&document`, and
        // `&mut image_cache` simultaneously.
        let state_ref: &mut EditorState = &mut st;
        // Read before the split borrow below, which reborrows `state_ref`
        // field by field.
        let selection_range = {
            let (s, e) = (
                state_ref.cursor.selection_start(),
                state_ref.cursor.selection_end(),
            );
            (s != e).then_some((s, e))
        };
        let EditorState {
            ref mut engine,
            ref document,
            ref mut image_cache,
            ref image_resolver,
            ref selected_image,
            ref resize_preview,
            ..
        } = *state_ref;
        let image_resolver = image_resolver.as_ref();
        let resize_preview_rect = resize_preview.get();
        let paint_closure = |frame: &teksilo_text::RenderFrame| {
            paint_frame(
                canvas,
                PaintParams {
                    frame,
                    origin: Point::new(bounds.x, bounds.y),
                    document,
                    image_cache,
                    image_resolver,
                    selection: selection_range,
                    // The same colour the typesetter drew underneath, resolved
                    // above for `engine.set_selection_color`.
                    selection_color: new_sel,
                    // The paint pass is the one place that has both the image
                    // rects and the selection, so it is what tells the pointer
                    // handler where the grips are.
                    selected_image_out: Some(selected_image),
                    resize_preview: resize_preview_rect,
                    draw_caret: caret_on_now,
                },
            );
        };
        match choice {
            RenderChoice::Full => engine.with_render_frame(paint_closure),
            RenderChoice::Block(bid) => engine.with_render_block_only(bid, paint_closure),
            RenderChoice::CursorOnly => engine.with_render_cursor_only(paint_closure),
        };

        // IME preedit underline. Walk the composing range char-by-char,
        // emitting one underline segment per visual line so a wrapped
        // composition underlines correctly. Engine coords are content-
        // space; screen = bounds + content − scroll (matches the glyphs).
        // On a read-only viewer there is never a preedit, so this is inert.
        if let Some(range) = ime_preedit_range
            && engine.has_full_layout()
            && range.start < range.end
        {
            let color = ctx.theme.colors.text_primary;
            let underline = |canvas: &mut Canvas, x0: f32, x1: f32, y: f32, h: f32| {
                let uy = y + h - 1.0;
                canvas.draw_line(
                    Point::new(x0, uy),
                    Point::new(x1, uy),
                    color,
                    teksilo_canvas::StrokeStyle::solid(1.0),
                );
            };
            let mut seg_x0: Option<f32> = None;
            let (mut seg_y, mut seg_h, mut last_x) = (0.0_f32, 0.0_f32, 0.0_f32);
            for p in range.start..=range.end {
                let c = engine.caret_rect(p, ime_affinity);
                let x = bounds.x + c[0] - scroll_x_logical;
                let y = bounds.y + c[1] - scroll_y_logical;
                match seg_x0 {
                    None => {
                        seg_x0 = Some(x);
                        seg_y = y;
                        seg_h = c[3];
                        last_x = x;
                    }
                    Some(x0) => {
                        if (y - seg_y).abs() > 0.5 {
                            underline(canvas, x0, last_x, seg_y, seg_h);
                            seg_x0 = Some(x);
                            seg_y = y;
                            seg_h = c[3];
                        }
                        last_x = x;
                    }
                }
            }
            if let Some(x0) = seg_x0 {
                underline(canvas, x0, last_x, seg_y, seg_h);
            }
        }

        canvas.clear_clip();
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        use self::policy::AccessibilityRole;
        use self::state::SyntheticElementRef;
        use teksilo_core::accesskit::{Action, NodeId, Role};
        use teksilo_text::text_document::{FlowElementSnapshot, FragmentContent};

        let st = self.state.borrow();

        let role = match st.policy.access_role {
            AccessibilityRole::Editor => Role::MultilineTextInput,
            AccessibilityRole::Document => Role::Document,
        };
        builder.set_role(role);
        if st.policy.is_read_only() {
            builder.set_read_only();
        }

        // Walk the cached flow snapshot (or rebuild it if the last
        // edit cleared the cache). For each block we emit a
        // Role::Paragraph child (or Role::Heading when the block's
        // heading_level is set), then for each text fragment we
        // emit a Role::TextRun child carrying value,
        // character_lengths, word_starts, and per-character
        // geometry from text-typeset. Widget-local
        // synthetic_to_element map is populated so the on-access
        // handler can convert AccessKit TextSelection back into
        // document-absolute cursor positions.
        let snap = {
            let mut cache = st.accessibility_flow_snapshot.borrow_mut();
            if cache.is_none() {
                // A bare view (show_highlights=false) builds its AT tree from a
                // clean snapshot too, so screen readers never hear highlight-
                // driven formatting that no sighted user sees. The paint-only
                // overlay is skipped: the AT walk reads fragments, never the
                // overlay, so computing a paint span per spell/find range here
                // would be pure waste (it dominated the a11y rebuild on a large
                // spell-checked document).
                *cache = Some(st.flow_snapshot_for_a11y());
            }
            cache.as_ref().cloned()
        };

        // While composing (IME preedit active), expose the composition as
        // the AT selection so screen readers / braille track the tentative
        // text — the composing characters are already in the runs / value.
        // Falls back to the live cursor/selection otherwise.
        let (user_anchor, user_pos) = match st.ime_preedit_range.clone() {
            Some(range) => (range.start, range.end),
            None => (st.cursor.anchor(), st.cursor.position()),
        };
        let mut caret_pair: Option<(NodeId, usize)> = None;
        let mut anchor_pair: Option<(NodeId, usize)> = None;
        let mut syn_map: std::collections::HashMap<NodeId, SyntheticElementRef> =
            std::collections::HashMap::new();

        if let Some(snap) = snap {
            for elem in &snap.elements {
                if let FlowElementSnapshot::Block(block) = elem {
                    let para_id = builder.push_paragraph_child(block.block_id as u64);
                    if let Some(level) = block.block_format.heading_level {
                        builder.set_paragraph_as_heading(para_id, level);
                    }
                    for frag in &block.fragments {
                        if let FragmentContent::Text {
                            text,
                            offset,
                            length,
                            element_id,
                            word_starts,
                            format,
                            ..
                        } = frag
                        {
                            // Text attributes for AT (WCAG 1.3.1 / EN 301 549
                            // 11.5.2.9): bold / italic / underline / strikethrough
                            // per formatting run. AccessKit has no bold flag, so
                            // an explicit weight wins, else bold folds to 700.
                            let attrs = teksilo_core::accessibility::TextRunAttributes {
                                font_weight: format.font_weight.map(|w| w as u16),
                                bold: format.font_bold.unwrap_or(false),
                                italic: format.font_italic.unwrap_or(false),
                                underline: format.font_underline.unwrap_or(false),
                                strikethrough: format.font_strikeout.unwrap_or(false),
                            };
                            // character_lengths: UTF-8 byte length of each char.
                            // AccessKit indexes by char, each entry is byte count.
                            let char_lengths: Vec<u8> =
                                text.chars().map(|c| c.len_utf8() as u8).collect();

                            // Per-character geometry from text-typeset. char_start
                            // / char_end are block-relative character offsets
                            // (matches LayoutLine::char_range's coordinate space).
                            let char_start = *offset;
                            let char_end = char_start + *length;
                            let geom =
                                st.engine
                                    .character_geometry(block.block_id, char_start, char_end);
                            let char_positions: Vec<f32> =
                                geom.iter().map(|g| g.position).collect();
                            let char_widths: Vec<f32> = geom.iter().map(|g| g.width).collect();

                            let node_id = builder.push_text_run_child(
                                para_id,
                                *element_id,
                                *offset,
                                text.clone(),
                                char_lengths,
                                Some(word_starts.clone()),
                                if char_positions.is_empty() {
                                    None
                                } else {
                                    Some(char_positions)
                                },
                                if char_widths.is_empty() {
                                    None
                                } else {
                                    Some(char_widths)
                                },
                                attrs,
                            );

                            // Annotations covering this run: one Role::Comment
                            // node each, linked from the run through `details`.
                            // Emitted per run rather than once per span because a
                            // span can cross runs (a bold word inside a commented
                            // sentence splits it), and every covered run must
                            // carry the relation or the announcement drops out
                            // halfway through the phrase.
                            let run_start = block.position + *offset;
                            let run_end = run_start + *length;
                            for span in &st.annotation_spans {
                                if span.start < run_end && span.end > run_start {
                                    let detail = builder
                                        .push_annotation_child(span.group_id, span.summary.clone());
                                    builder.push_detail_on_child(node_id, detail);
                                }
                            }

                            // Remember where this run lives in the document so
                            // the on-access handler can resolve
                            // SetTextSelection(TextRun NodeId, char_index).
                            let absolute_start = block.position + *offset;
                            syn_map.insert(
                                node_id,
                                SyntheticElementRef {
                                    element_id: *element_id,
                                    absolute_start,
                                    text: text.clone(),
                                },
                            );

                            // Resolve user cursor / anchor to this run if they
                            // fall within its absolute character range
                            // [absolute_start, absolute_start + length].
                            let absolute_end = absolute_start + *length;
                            if user_pos >= absolute_start && user_pos <= absolute_end {
                                let char_idx = char_index_in_text(text, user_pos - absolute_start);
                                caret_pair = Some((node_id, char_idx));
                            }
                            if user_anchor >= absolute_start && user_anchor <= absolute_end {
                                let char_idx =
                                    char_index_in_text(text, user_anchor - absolute_start);
                                anchor_pair = Some((node_id, char_idx));
                            }
                        }

                        // Inline objects: one document character each, rendered
                        // as something a reader sees but cannot read out of the
                        // text — an image, or a footnote's marker.
                        //
                        // Announced as a single-character text run whose value
                        // is that description. `character_lengths` is one entry
                        // spanning the whole string on purpose: the object *is*
                        // one character of the document, however many letters
                        // stand in for it, and telling AccessKit otherwise would
                        // put every caret offset after it out by the difference.
                        //
                        // Images were reaching no assistive technology at all
                        // until now — their `alt` was carried the whole way
                        // through the pipeline and then dropped here, at the
                        // last step, because this loop only ever matched `Text`.
                        let object_run = match frag {
                            FragmentContent::Image {
                                alt,
                                offset,
                                element_id,
                                format,
                                ..
                            } => Some((alt.clone(), *offset, *element_id, format)),
                            FragmentContent::FootnoteReference {
                                marker,
                                offset,
                                element_id,
                                format,
                                ..
                            } => Some((marker.clone(), *offset, *element_id, format)),
                            FragmentContent::Text { .. } => None,
                        };

                        if let Some((value, offset, element_id, format)) = object_run {
                            let attrs = teksilo_core::accessibility::TextRunAttributes {
                                font_weight: format.font_weight.map(|w| w as u16),
                                bold: format.font_bold.unwrap_or(false),
                                italic: format.font_italic.unwrap_or(false),
                                underline: format.font_underline.unwrap_or(false),
                                strikethrough: format.font_strikeout.unwrap_or(false),
                            };
                            // An empty description would announce nothing at
                            // all, which is indistinguishable from a rendering
                            // fault. A single space is at least a spoken pause.
                            let value = if value.is_empty() {
                                " ".to_string()
                            } else {
                                value
                            };
                            let geom =
                                st.engine
                                    .character_geometry(block.block_id, offset, offset + 1);
                            let node_id = builder.push_text_run_child(
                                para_id,
                                element_id,
                                offset,
                                value.clone(),
                                vec![value.len().min(u8::MAX as usize) as u8],
                                None,
                                if geom.is_empty() {
                                    None
                                } else {
                                    Some(geom.iter().map(|g| g.position).collect())
                                },
                                if geom.is_empty() {
                                    None
                                } else {
                                    Some(geom.iter().map(|g| g.width).collect())
                                },
                                attrs,
                            );

                            let absolute_start = block.position + offset;
                            syn_map.insert(
                                node_id,
                                SyntheticElementRef {
                                    element_id,
                                    absolute_start,
                                    text: value,
                                },
                            );
                            if user_pos >= absolute_start && user_pos <= absolute_start + 1 {
                                caret_pair = Some((node_id, user_pos - absolute_start));
                            }
                            if user_anchor >= absolute_start && user_anchor <= absolute_start + 1 {
                                anchor_pair = Some((node_id, user_anchor - absolute_start));
                            }
                        }
                    }
                }
            }
        }

        // Attach the text selection on the editor itself, referencing
        // the appropriate TextRun children. If we couldn't resolve
        // either endpoint (empty document, cursor in no fragment),
        // fall back to a self-targeted selection so screen readers
        // still see *something*.
        if let (Some(a), Some(c)) = (anchor_pair, caret_pair) {
            builder.set_text_selection_to(a, c);
        } else {
            builder.set_text_selection_on_self(user_anchor, user_pos);
        }

        *st.synthetic_to_element.borrow_mut() = syn_map;

        builder.add_action(Action::Focus);
        builder.add_action(Action::ScrollIntoView);
        builder.add_action(Action::SetTextSelection);
        if matches!(st.policy.access_role, AccessibilityRole::Editor) {
            builder.add_action(Action::SetValue);
            builder.add_action(Action::ReplaceSelectedText);
        }
    }

    fn clips_children(&self) -> bool {
        true
    }
}

impl Widget for RichTextEditor {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Tell the framework this widget edits text.
        //
        // What it buys: an application may take `Ctrl+Z`, `Ctrl+C` and friends
        // for itself — a single Undo command over the whole app has to — and
        // registered shortcuts resolve before any widget sees the raw key. This
        // is how the host can tell that the caret is *here*, and either drive
        // this surface or step aside so it keeps its own keys. Without it, an
        // application that routes those chords silently breaks every text
        // widget it does not personally know about. See
        // `teksilo_core::text_surface`.
        ctx.register_text_surface(std::rc::Rc::new(self.handle()));
        // Engine swap: replace the private fallback with one sharing
        // the application's `SharedTypesetter` so rendered glyphs end
        // up in the atlas teksilo-render uploads to the GPU. Headless
        // tests without a `SharedTypesetter` keep the private engine
        // untouched. Lives on the wrapper because state mutation
        // doesn't depend on `ctx.self_id()`.
        if let Some(shared) = ctx.app_state::<SharedTypesetter>() {
            let mut st = self.state.borrow_mut();
            let wrap = st.wrap_mode;
            // Carry over builder-set engine config that the swap would otherwise
            // drop — `.typography_defaults()`, `.echo_char()` are set on the
            // private engine before mount, and this runs on every rebuild.
            // (Theme colours / font-scale re-derive themselves in `paint()`.)
            let typography = st.engine.typography_defaults().clone();
            let echo = st.engine.echo_char();
            let mut engine = RichTextEngine::from_shared(shared.clone());
            engine.set_wrap_mode(wrap);
            engine.set_hyphenate_justified(true);
            engine.set_typography_defaults(typography);
            engine.set_echo_char(echo);
            st.engine = engine;
            st.needs_full_layout = true;
        }

        // Stash the tree's frame-request handle on the state so the
        // frame-tick effect can self-chain (caret blink, drag
        // auto-scroll) without mutable access to the tree.
        {
            let mut st = self.state.borrow_mut();
            st.frame_request = Some(ctx.frame_request_handle());
            st.frame_wake_at = Some(ctx.wake_at_handle());
            // Remember this build's wrapper id — the `.focusable(true)` node — so a
            // held handle can request focus back onto the editor.
            st.self_id = Some(ctx.self_id());
        }

        // Kick off the first frame so the initial layout/paint runs
        // through the tick path and populates max_scroll / content
        // metrics. Gated by activation: a tab content pane parked in a
        // non-selected `Switcher` branch must not keep the event loop
        // awake just because it was built (TabWidget pre-mounts every
        // open tab).
        let activation = ctx.activation_signal(ctx.self_id());
        // Stash it too: `reveal_range` has no other way to tell an on-screen
        // editor from one parked dormant, because the engine's layout survives
        // the parking. Taken from the signal rather than set by the dormancy
        // effect below, which fires only on a *transition* — an editor built
        // dormant (a TabWidget pre-mounts every open tab) never transitions.
        self.state.borrow_mut().activation = Some(activation.clone());
        if activation.get() {
            ctx.request_frame();
        }

        // When this editor is parked dormant (tab switch, collapsed
        // pane, …) clear local focus state synchronously. The tree may
        // also dispatch FocusLost via revalidate, but a race between
        // selection change and pointer focus — or a programmatic
        // selection change that never moves focus — used to leave
        // `has_focus = true` on every visited tab. Each stuck editor
        // kept scheduling caret `wake_at`s, and every open tab's
        // frame-tick effect still ran on those wakes (observers are
        // not dormancy-gated). Rapid tab switching made CPU climb.
        {
            let state = self.state.clone();
            ctx.effect(&activation, move |&active| {
                if active {
                    // **Re-activated** — re-arm the frame loop.
                    //
                    // The dormant branch below deliberately does not re-arm
                    // `frame_request`, and the frame-tick effect is skipped
                    // entirely while dormant, so nothing restarts the tick 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 shows
                    // **no caret at all** and reads as a broken surface.
                    //
                    // The in-tree modal path hits this on every open: it builds
                    // the content, marks it dormant, mounts it, activates it and
                    // *then* moves focus in (`present_in_tree_modal_request`). A
                    // tab switch and a collapsed pane take the same route back.
                    //
                    // Cheap and self-limiting: one frame request, after which the
                    // ordinary tick loop re-arms itself only while it has work.
                    let st = state.borrow();
                    if let Some(handle) = &st.frame_request {
                        handle.set(true);
                    }
                    return;
                }
                let mut st = state.borrow_mut();
                if st.has_focus {
                    st.has_focus = false;
                    st.focus_signal.set(false);
                }
                if st.caret_visible.get() {
                    st.caret_visible.set(false);
                }
                st.blink.reset();
                // Retire the caret band here too. Only `frame_loop::tick` pushes the band's
                // focus state through to the document, and the tick effect below is skipped
                // entirely while dormant — so a parked editor would keep its last band
                // registered on a document its siblings are still showing, and a split pane
                // over the same document would show two. Clearing `has_focus` above is not
                // enough; nothing would ever act on it.
                if let Some(band) = &st.caret_highlight {
                    band.set_active(false);
                }
                st.caret_highlight_active = false;
                // Do not re-arm frame_request here: a dormant editor has
                // nothing to paint, and re-arming is exactly the leak
                // this gate exists to stop.
            });
        }

        // Frame-tick effect — drains document events, blinks the
        // caret, runs drag auto-scroll. Re-arms the tree's
        // frame-request flag while there's still pending work.
        // Skipped entirely while dormant so a multi-tab TabWidget does
        // not pay O(open tabs) per wake for editors nobody can see.
        {
            let state = self.state.clone();
            let active = activation.clone();
            let tick_signal = ctx.frame_tick();
            ctx.effect(&tick_signal, move |delta| {
                if !active.get() {
                    return;
                }
                let mut st = state.borrow_mut();
                let more = frame_loop::tick(&mut st, *delta);
                // Signal::set is unconditional (clones+invokes every
                // observer even when value unchanged), so only call it
                // when the bool actually flipped. Avoids per-tick fanout
                // to chrome widgets that watch the selection state.
                let new_has_selection = st.cursor.has_selection();
                if st.has_selection.get() != new_has_selection {
                    st.has_selection.set(new_has_selection);
                }
                if more && let Some(handle) = &st.frame_request {
                    handle.set(true);
                }
                drop(st);
            });
        }

        // Window-active effect — mirror the tree's window-active state onto the
        // editor state so the frame loop (which has no context) can gate the
        // caret. The frame loop may not tick while the window is inactive (the
        // animation scheduler is parked), so on deactivation we hide the caret
        // *synchronously* here rather than waiting for a tick, and request a
        // frame so the change reaches a paint pass — but only while this
        // editor is itself active. A dormant tab must not re-arm the frame
        // loop just because the host window blinked.
        {
            let state = self.state.clone();
            let active = activation.clone();
            let wa_signal = ctx.window_active_signal();
            ctx.effect(&wa_signal, move |&window_active| {
                let mut st = state.borrow_mut();
                st.window_active = window_active;
                if window_active {
                    // Reactivated: if the editor still holds focus, show the
                    // caret immediately (restart the blink phase) rather than
                    // waiting up to one blink interval. `Hidden` policy stays
                    // hidden — the paint gate suppresses it anyway.
                    let show =
                        st.has_focus && !matches!(st.policy.caret_policy, CaretPolicy::Hidden);
                    if show && !st.caret_visible.get() {
                        st.caret_visible.set(true);
                    }
                    st.blink.reset();
                } else {
                    // Deactivated: hide the caret synchronously (the frame loop
                    // may not tick while the window is inactive).
                    if st.caret_visible.get() {
                        st.caret_visible.set(false);
                    }
                    st.blink.reset();
                }
                if active.get()
                    && let Some(handle) = &st.frame_request
                {
                    handle.set(true);
                }
                drop(st);
            });
        }

        // Attach handlers on the WRAPPER — making the composing
        // widget itself the focus + event target. The body is a
        // pure leaf so users can wrap it in arbitrary chrome via
        // `RichTextEditorStyle::make_body` without losing focus
        // semantics.
        let mut handlers = HandlerSet::new();
        // Editable editors are text-input surfaces — enable the OS IME
        // while focused. Read-only viewers stay focusable for selection but
        // accept no text input, so they leave the IME descriptor unset.
        if !self.state.borrow().policy.is_read_only() {
            handlers = handlers.ime_input(teksilo_core::ime::ImeContext::text());
        }
        handlers = handlers
            // Text and files dropped onto the editor land at the caret, and the
            // caret follows the drag so the writer can see where that is. An
            // editor with no drop handling at all is not merely inert: the drag
            // bubbles to whatever ancestor claims it, and the pane's own
            // `DropTarget` paints a reject tint across the whole surface, which
            // reads as the editor refusing the drop rather than never being
            // offered it.
            .on_drag_hover({
                let state = self.state.clone();
                move |payload, pos, ctx| {
                    // Read the policy live rather than snapshotting it here: the
                    // command filter is swappable on a mounted editor
                    // (`set_command_filter`), and a value captured at build time
                    // would keep promising a drop the drop handler then refuses.
                    let read_only = state.borrow().policy.is_read_only();
                    if read_only || !droppable(payload) {
                        // `NoFeedback` rather than a reject visual: the drag
                        // must keep bubbling so an ancestor that does want this
                        // payload — a binder row dropped on the editor pane —
                        // still gets it.
                        return teksilo_core::DropFeedback::NoFeedback;
                    }
                    if !self::mouse::move_caret_for_drag(&state, pos) {
                        self::mouse::clear_drop_caret(&state);
                        return teksilo_core::DropFeedback::NoFeedback;
                    }
                    ctx.request_frame();
                    // The caret IS the feedback — a framework insertion line
                    // would draw a second, differently-placed promise about
                    // where the drop lands.
                    teksilo_core::DropFeedback::Accept
                }
            })
            // The drag moved off this editor (or was cancelled over it): stop
            // promising a landing place. Without this the drop caret is left
            // burnt into an editor the drag has already left.
            .on_drag_leave({
                let state = self.state.clone();
                move |ctx| {
                    self::mouse::clear_drop_caret(&state);
                    ctx.request_frame();
                }
            })
            .on_drop({
                let state = self.state.clone();
                move |payload, pos, ctx| {
                    self::mouse::clear_drop_caret(&state);
                    // Live, for the same reason as `on_drag_hover` above.
                    let read_only = state.borrow().policy.is_read_only();
                    if read_only || !droppable(&payload) {
                        return false;
                    }
                    // Place the caret one last time: a drop can arrive without a
                    // final hover at the same point (a fast release, or a
                    // backend that only fills the payload at drop time).
                    self::mouse::move_caret_for_drag(&state, pos);
                    // Text dragged out of an editor. Dropped back into the one
                    // it came from it is a *move* — the original goes away —
                    // and dropped into any other editor it is a copy, which is
                    // what a writer means by carrying a phrase to a second
                    // document rather than emptying it out of the first.
                    if let Some(drag) = payload.get_typed::<EditorTextDrag>() {
                        let same_editor = state.borrow().self_id == Some(drag.source);
                        let moved = self::mouse::apply_text_drop(&state, drag, same_editor);
                        if moved {
                            sync_cursor_signals(&state);
                            state.borrow_mut().pending_text_changed = true;
                            // Take the caret with the text. Focus is still in
                            // the editor the drag *started* in, so without this
                            // the writer is left looking at text they just
                            // placed here while typing into somewhere else.
                            let self_id = state.borrow().self_id;
                            if let Some(id) = self_id {
                                ctx.request_focus(id);
                            }
                            ctx.request_frame();
                        }
                        return moved;
                    }
                    let files: Vec<std::path::PathBuf> = payload.files().to_vec();
                    if !files.is_empty() {
                        // Files mean nothing to a text editor on their own —
                        // whether a path becomes a picture, a link, or an
                        // include is the host's policy. Hand them over.
                        let cb = state.borrow().on_files_dropped.clone();
                        let Some(cb) = cb else { return false };
                        cb(&files, ctx);
                        ctx.request_frame();
                        return true;
                    }
                    // Advertised but delivered nothing: decline, so the drag
                    // bubbles rather than being silently eaten.
                    let Some(text) = payload.text().filter(|t| !t.is_empty()) else {
                        return false;
                    };
                    {
                        let st = state.borrow();
                        let _ = st.cursor.insert_text(text);
                    }
                    sync_cursor_signals(&state);
                    state.borrow_mut().pending_text_changed = true;
                    ctx.request_frame();
                    true
                }
            })
            .focusable(true)
            .cursor(CursorIcon::Text)
            .on_focus({
                let state = self.state.clone();
                move |gained, ctx| {
                    let mut st = state.borrow_mut();
                    st.has_focus = gained;
                    // Mirror onto the reactive signal so chrome
                    // installed by `RichTextEditorStyle::make_body`
                    // (focus-aware border / ring) re-renders.
                    st.focus_signal.set(gained);
                    if gained && matches!(st.policy.caret_policy, CaretPolicy::Blinking) {
                        st.blink.restart();
                        st.caret_visible.set(true);
                    }
                    drop(st);
                    if gained {
                        // Seed the OS IME candidate area at the caret.
                        self::keyboard::report_ime_cursor_area(&state, ctx);
                    } else {
                        // Abandon any in-progress composition on blur, and drop
                        // the IME-area / caret-chase caches. The OS IME candidate
                        // area is a single *per-window* resource a sibling field
                        // may have re-pointed while we were unfocused; clearing
                        // `last_ime_area` forces the next focus-gain report to
                        // re-seed it (the dedup must not swallow that re-seed).
                        // Clearing `last_chase_pos` lets a refocus re-reveal the
                        // caret even if it has not moved since we lost focus.
                        self::keyboard::clear_ime_preedit(&state);
                        let mut st = state.borrow_mut();
                        st.last_ime_area = None;
                        st.last_chase_pos = None;
                    }
                    ctx.request_frame();
                }
            })
            .on_pointer_event({
                let state = self.state.clone();
                let v_sb = self.v_scrollbar_bounds.clone();
                let h_sb = self.h_scrollbar_bounds.clone();
                move |event, ctx| {
                    self::mouse::handle_pointer_event(&state, &v_sb, &h_sb, event, ctx)
                }
            })
            .on_scroll({
                let state = self.state.clone();
                let overscroll = self.overscroll_behavior;
                move |event, ctx| self::mouse::handle_scroll(&state, overscroll, event, ctx)
            })
            .on_key({
                let state = self.state.clone();
                move |event, ctx| self::keyboard::handle_key(&state, event, ctx)
            })
            .on_double_tap({
                let state = self.state.clone();
                move |event, ctx| self::mouse::handle_double_tap(&state, event.position, ctx)
            })
            .on_triple_tap({
                let state = self.state.clone();
                move |event, ctx| self::mouse::handle_triple_tap(&state, event.position, ctx)
            })
            .on_access_action_request({
                let state = self.state.clone();
                move |action, target_node, data, ctx| {
                    handle_access_action_request(&state, action, target_node, data, ctx)
                }
            });

        // Context-menu factory — same shape as before, just hosted on
        // the wrapper. The factory reads the policy from the shared state on
        // each right-click, so a filter swapped in after mount is honoured.
        if let Some(factory) = context_menu::resolve_factory(
            self.custom_context_menu.take(),
            self.default_context_menu_enabled,
            self.state.clone(),
        ) {
            handlers = handlers.context_menu(move |pos, ctx| factory(pos, ctx));
        }

        ctx.apply_self_handlers(handlers);

        // Build the pure-paint leaf body. The body carries
        // layout/paint/accessibility (using its own `self_id()` for
        // `caret_visible` + `document_version` bindings); the shared
        // `state` propagates handler-driven mutations into it.
        let body = RichTextEditorBody {
            state: self.state.clone(),
            min_lines: self.min_lines,
            max_lines: self.max_lines,
        };
        let viewport_id = ctx.add(body);

        // Reactive colour overrides: a signal/role-bound `ColorProp` must
        // repaint the body (the leaf that resolves + applies them in `paint`)
        // when it changes. Bind to `viewport_id`, not the wrapper — the painter
        // owns its prop bindings (the `RectWidget` pattern). Theme-role changes
        // already dirty every node via the reactive theme; this covers
        // `Signal`-bound props. The background prop is reactive through the
        // `RectWidget` the style builds, so it isn't registered here.
        {
            let props = {
                let st = self.state.borrow();
                [
                    st.text_color_prop.clone(),
                    st.caret_color_prop.clone(),
                    st.selection_color_prop.clone(),
                ]
            };
            let registry = ctx.binding_registry();
            for prop in props.iter().flatten() {
                prop.register_if_bound(
                    viewport_id,
                    registry,
                    teksilo_core::binding::BindingLevel::RepaintOnly,
                );
            }
        }

        // Snapshot focus + read-only state for the chrome. `is_focused`
        // is the reactive mirror updated by `on_focus`; `is_read_only`
        // is sampled from the policy bundle.
        let (is_focused, is_read_only) = {
            let st = self.state.borrow();
            (st.focus_signal.clone(), st.policy.is_read_only())
        };

        let style: SharedRichTextEditorStyle = self
            .style_override
            .clone()
            .or_else(|| ctx.theme().style_slots.rich_text_editor.clone())
            .unwrap_or_else(|| Rc::new(RecipeRichTextEditorStyle));
        let cfg = RichTextEditorStyleConfig {
            viewport: viewport_id,
            is_focused,
            is_read_only,
            content_padding: self.content_padding,
            background: self.state.borrow().background_prop.clone(),
        };
        let root = style.make_body(&cfg, ctx);
        self.root_child_id = Some(root);

        // Overlay scrollbars — floated on top of the chrome at the
        // right / bottom edges. Driven by the same signals the frame
        // loop publishes (`scroll_*`, `max_scroll_*`, `viewport_ratio_*`).
        // ScrollPolicy::AlwaysOff suppresses the widget entirely so it
        // doesn't sit in the children list as a zero-sized stub.
        let (scroll_x, scroll_y, max_scroll_x, max_scroll_y, vr_x, vr_y) = {
            let st = self.state.borrow();
            (
                st.scroll_x.clone(),
                st.scroll_y.clone(),
                st.max_scroll_x.clone(),
                st.max_scroll_y.clone(),
                st.viewport_ratio_x.clone(),
                st.viewport_ratio_y.clone(),
            )
        };

        let mut children = vec![root];
        if self.v_scroll_policy != ScrollPolicy::AlwaysOff {
            let v_sb = ScrollBar::new(
                ScrollBarOrientation::Vertical,
                scroll_y,
                max_scroll_y.clone(),
                vr_y,
            )
            .visual(ScrollBarVariant::Overlay);
            let v_id = ctx.add(v_sb);
            self.v_scrollbar_id = Some(v_id);
            children.push(v_id);
        }
        if self.h_scroll_policy != ScrollPolicy::AlwaysOff {
            let h_sb = ScrollBar::new(
                ScrollBarOrientation::Horizontal,
                scroll_x,
                max_scroll_x.clone(),
                vr_x,
            )
            .visual(ScrollBarVariant::Overlay);
            let h_id = ctx.add(h_sb);
            self.h_scrollbar_id = Some(h_id);
            children.push(h_id);
        }

        // `place_children` reads `max_scroll_y` / `max_scroll_x`
        // synchronously to decide whether to give the overlay
        // scrollbars a non-zero rect under `ScrollPolicy::Auto`. The
        // frame loop publishes those values from `Step 7` on every
        // tick — without a Relayout binding the wrapper wouldn't
        // re-place its children when the values cross zero, so the
        // bars would stay sized 0×0 until something else (scroll
        // wheel, resize) forced a layout pass.
        let self_id = ctx.self_id();
        let registry = ctx.binding_registry();
        max_scroll_y.bind_to(
            self_id,
            registry,
            teksilo_core::binding::BindingLevel::Relayout,
        );
        max_scroll_x.bind_to(
            self_id,
            registry,
            teksilo_core::binding::BindingLevel::Relayout,
        );

        children
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        self.root_child_id
            .and_then(|id| ctx.child_size(id, proposal))
            .unwrap_or_else(|| proposal.resolve(0.0, 0.0))
            .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        // Chrome (first child) fills the entire bounds. Overlay
        // scrollbars float on top at the right (vertical) and
        // bottom (horizontal) edges — collapsed to zero when the
        // axis policy is `Auto` and there's nothing to scroll.
        let sb_thickness = self::frame_loop::SCROLLBAR_THICKNESS;
        {
            // Record the wrapper node's window-space origin so the pointer
            // handlers can reconstruct window coords from the now
            // wrapper-node-local positions (see `State::node_origin`).
            let mut st = self.state.borrow_mut();
            st.node_origin = teksilo_canvas::Point::new(bounds.x, bounds.y);
        }
        let st = self.state.borrow();
        let max_y = st.max_scroll_y.get();
        let max_x = st.max_scroll_x.get();
        drop(st);
        let show_v = match self.v_scroll_policy {
            ScrollPolicy::AlwaysOn => true,
            ScrollPolicy::Auto => max_y > 0.0,
            ScrollPolicy::AlwaysOff => false,
        };
        let show_h = match self.h_scroll_policy {
            ScrollPolicy::AlwaysOn => true,
            ScrollPolicy::Auto => max_x > 0.0,
            ScrollPolicy::AlwaysOff => false,
        };
        let mut v_rect = Rect::ZERO;
        let mut h_rect = Rect::ZERO;
        for (idx, child) in children.iter_mut().enumerate() {
            if idx == 0 {
                child.origin = teksilo_canvas::Point::new(bounds.x, bounds.y);
                child.size = Size::new(bounds.width, bounds.height);
            } else if Some(child.id) == self.v_scrollbar_id {
                if show_v {
                    let h = if show_h {
                        (bounds.height - sb_thickness).max(0.0)
                    } else {
                        bounds.height
                    };
                    child.origin = teksilo_canvas::Point::new(
                        bounds.x + bounds.width - sb_thickness,
                        bounds.y,
                    );
                    child.size = Size::new(sb_thickness, h);
                    // Widget-local: pointer events arrive widget-local, so
                    // the published bounds the press-bypass test compares
                    // against must be local too (subtract the widget origin).
                    v_rect = Rect::new(
                        child.origin.x - bounds.x,
                        child.origin.y - bounds.y,
                        sb_thickness,
                        h,
                    );
                } else {
                    child.origin = teksilo_canvas::Point::new(bounds.x, bounds.y);
                    child.size = Size::ZERO;
                }
            } else if Some(child.id) == self.h_scrollbar_id {
                if show_h {
                    let w = if show_v {
                        (bounds.width - sb_thickness).max(0.0)
                    } else {
                        bounds.width
                    };
                    child.origin = teksilo_canvas::Point::new(
                        bounds.x,
                        bounds.y + bounds.height - sb_thickness,
                    );
                    child.size = Size::new(w, sb_thickness);
                    // Widget-local (see the v_scrollbar branch).
                    h_rect = Rect::new(
                        child.origin.x - bounds.x,
                        child.origin.y - bounds.y,
                        w,
                        sb_thickness,
                    );
                } else {
                    child.origin = teksilo_canvas::Point::new(bounds.x, bounds.y);
                    child.size = Size::ZERO;
                }
            }
        }
        // Published to the wrapper's `on_pointer_event` so a press over
        // an overlay scrollbar bypasses the drag-select latch — see
        // [`v_scrollbar_bounds`](Self::v_scrollbar_bounds).
        self.v_scrollbar_bounds.set(v_rect);
        self.h_scrollbar_bounds.set(h_rect);
    }

    fn children(&self) -> Vec<WidgetId> {
        let mut ids = Vec::with_capacity(3);
        if let Some(id) = self.root_child_id {
            ids.push(id);
        }
        if let Some(id) = self.v_scrollbar_id {
            ids.push(id);
        }
        if let Some(id) = self.h_scrollbar_id {
            ids.push(id);
        }
        ids
    }

    fn clips_children(&self) -> bool {
        // Mirror the body's clipping so chrome around the editor
        // doesn't leak the body's overflow.
        true
    }

    fn focus_reveal_rect(&self, _bounds: Rect) -> Option<Rect> {
        // On focus gain the framework reveals the focused widget into any
        // enclosing ScrollArea. Reveal the caret *line*, not the (potentially
        // page-tall, own-scroll-suppressed) whole editor: a click that only
        // placed the caret near the top must not jump the page to the editor's
        // bottom. Returns the exact absolute caret rect the in-page caret-follow
        // uses (viewport_origin + caret − scroll); `scroll_rect_into_view`
        // excludes the editor itself, so this targets the enclosing ScrollArea
        // with no double-scroll. `None` (→ reveal whole bounds) before the first
        // layout or while unfocused.
        self::keyboard::caret_window_rect(&self.state.borrow())
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        // Transparent container in the AT tree — the inner
        // `RichTextEditorBody` carries the real role
        // (`MultilineTextInput` / `Document`) plus the paragraph and
        // text-run children. Without this method the wrapper would
        // emit a `Role::Unknown` node (the `AccessNodeBuilder`
        // default), which screen readers can't classify. Same
        // pattern as [`TextInput`](crate::TextInput), which also
        // wraps a focusable inner field.
        builder.set_role(teksilo_core::accesskit::Role::GenericContainer);
    }
}

// ---------------------------------------------------------------------------
// Event handlers — take `&SharedState` so they can be boxed into handler
// closures without borrowing `self`.
// ---------------------------------------------------------------------------

/// Shared body of [`RichTextEditor::reveal_range`] and its
/// [`EditorHandle`] twin — one implementation so the two can never drift on the
/// typewriter-pin rule.
///
/// The pin applies here even though the range is not the caret: with typewriter
/// scrolling on, walking search hits should bring each one to the same height
/// the writer works at. Unlike the caret chase, a pointer anchor does *not*
/// suppress it — the user asked for this jump explicitly by pressing Find Next,
/// so there is no gesture to fight.
fn reveal_range_impl(
    state: &SharedState,
    ctx: &mut teksilo_core::widget::EventContext,
    start: usize,
    end: usize,
) -> bool {
    // **Named as the rect's owner**, so the scroll walk climbs the *editor's*
    // ancestors and not the handler's. The two are the same widget when the editor
    // reveals its own caret, and different every time something built beside it asks
    // — a find banner's Next button, a mention counter's chevron. Those sit outside
    // the scrolling page, so a walk from them leaves through the strip and never
    // meets the scroll container: the match was selected, the counter moved, and the
    // viewport stayed exactly where it was. `self_id` is `None` only before the
    // editor's first build, and there is nothing laid out to reveal then anyway.
    let (area, pin, owner) = {
        let st = state.borrow();
        // **Dormant is "no layout to do it in"**, even though the engine still holds
        // one: `has_full_layout` is set at the first full layout and never cleared, and
        // parking an editor clears its focus, caret and band but not its layout. So the
        // rect below resolves perfectly for a tab nobody can see, the ancestor walk
        // finds a scroll container that is not on screen, and the answer `true` tells a
        // caller holding several editors over one document to stop looking — while the
        // visible one, never asked, stays exactly where it was.
        if st.activation.as_ref().is_some_and(|a| !a.get()) {
            return false;
        }
        match self::keyboard::range_window_rect(&st, start, end) {
            Some(a) => (a, st.typewriter, st.self_id),
            None => return false,
        }
    };
    match (pin, owner) {
        (Some(fraction), Some(owner)) => ctx.ensure_visible_aligned_from(
            owner,
            area,
            fraction,
            teksilo_core::event::ScrollMotion::Smooth,
        ),
        (Some(fraction), None) => {
            ctx.ensure_visible_aligned(area, fraction, teksilo_core::event::ScrollMotion::Smooth)
        }
        (None, Some(owner)) => ctx.ensure_visible_from(owner, area),
        (None, None) => ctx.ensure_visible(area),
    }
    true
}

/// Set (or clear) an editor's ambient caret band. Shared by
/// [`RichTextEditor::set_caret_highlight`] and its [`EditorHandle`] mirror.
///
/// The session is created on first use and torn down when the band is cleared, so an editor
/// that never asks for one registers nothing on the document at all — which matters, since
/// every read-only preview pane shares the documents the writing panes are editing.
fn set_caret_highlight(state: &SharedState, highlight: Option<caret_highlight::CaretHighlight>) {
    let mut st = state.borrow_mut();
    match (&st.caret_highlight, &highlight) {
        (None, None) => return,
        (None, Some(_)) => {
            let session = caret_highlight::CaretHighlightSession::new(&st.document);
            session.set_config(highlight);
            // The frame loop hands it the focus state and the caret on the next tick, so a band
            // switched on mid-session appears without the editor having to be touched.
            let active = st.has_focus && !st.cursor.has_selection();
            session.set_active(active);
            st.caret_highlight_active = active;
            st.caret_highlight = Some(session);
        }
        (Some(_), None) => {
            // Dropping the session retires its highlight layer.
            st.caret_highlight = None;
            st.caret_highlight_active = false;
        }
        (Some(session), Some(_)) => {
            session.set_config(highlight);
        }
    }
    // A band that appeared, vanished or changed colour needs a frame to draw it — and the
    // resolve-and-push itself only happens in `frame_loop::tick`, so without waking the tree an
    // idle editor stays configured-but-unbanded until some unrelated interaction pumps a frame.
    // Same poke `set_typography_defaults` / `set_font_size_scale` make, for the same reason:
    // these are the ctx-less setters a host calls from a settings or theme effect.
    st.content_dirty = true;
    if let Some(handle) = &st.frame_request {
        handle.set(true);
    }
}

/// Push the current cursor position / anchor / selection flag into
/// the state's reactive signals. Called after every cursor mutation
/// so external observers (status bars, tests) see the change on the
/// next signal propagation. Exported to `keyboard` and `mouse`
/// because every event handler ends with a signal publish.
pub(super) fn sync_cursor_signals(state: &SharedState) {
    let mut st = state.borrow_mut();
    let pos = st.cursor.position();
    let anc = st.cursor.anchor();
    let has_sel = st.cursor.has_selection();
    let pos_sig = st.cursor_position.clone();
    let anc_sig = st.cursor_anchor.clone();
    let sel_sig = st.has_selection.clone();
    let caret_vis_sig = st.caret_visible.clone();
    // Restart the blink phase on every cursor mutation: a steady-visible
    // caret while typing or holding an arrow key, blinking only
    // resumes after the user stops moving. Mirrors focus-gain behavior
    // (see the FocusChanged handler around rich_text.rs:2041). The frame
    // loop only toggles once a full interval has elapsed since the phase
    // start, so restarting here delays the next toggle by a full interval.
    let blink_reset = st.has_focus && matches!(st.policy.caret_policy, CaretPolicy::Blinking);
    if blink_reset {
        st.blink.restart();
    }
    drop(st);
    pos_sig.set(pos);
    anc_sig.set(anc);
    sel_sig.set(has_sel);
    if blink_reset && !caret_vis_sig.get() {
        caret_vis_sig.set(true);
    }
}

/// Dispatch an AccessKit `ActionRequest` payload for the rich text
/// editor. Handles `SetTextSelection` (screen-reader-initiated
/// caret moves), `SetValue` (programmatic text replacement), and
/// `ScrollIntoView` (scroll so the caret is visible).
fn handle_access_action_request(
    state: &SharedState,
    action: teksilo_core::accesskit::Action,
    _target_node: teksilo_core::accesskit::NodeId,
    data: Option<teksilo_core::accesskit::ActionData>,
    ctx: &mut teksilo_core::widget::EventContext,
) -> teksilo_core::event::EventResponse {
    use self::policy::EditCommandKind;
    use teksilo_core::accesskit::{Action, ActionData};
    use teksilo_core::event::EventResponse;
    use teksilo_text::text_document::{MoveMode, SelectionType};

    match (action, data) {
        (Action::SetTextSelection, Some(ActionData::SetTextSelection(sel))) => {
            let filter = state.borrow().policy.command_filter;
            // Screen-reader-initiated caret moves are "navigation",
            // filtered under the same rule as arrow keys.
            if !filter.accepts(EditCommandKind::MoveLeft) {
                return EventResponse::Ignored;
            }
            let resolve = |pos: teksilo_core::accesskit::TextPosition| -> Option<usize> {
                let st = state.borrow();
                let map = st.synthetic_to_element.borrow();
                let er = map.get(&pos.node)?.clone();
                // Convert character_index (char units within the run)
                // to a byte offset within the run's text, then add
                // absolute_start to get the document position.
                let byte_off = er
                    .text
                    .char_indices()
                    .nth(pos.character_index)
                    .map(|(i, _)| i)
                    .unwrap_or(er.text.len());
                Some(er.absolute_start + byte_off)
            };
            if let (Some(a), Some(f)) = (resolve(sel.anchor), resolve(sel.focus)) {
                let st = state.borrow();
                st.cursor.set_position(a, MoveMode::MoveAnchor);
                st.cursor.set_position(f, MoveMode::KeepAnchor);
                drop(st);
                sync_cursor_signals(state);
                ctx.request_frame();
                EventResponse::Handled
            } else {
                EventResponse::Ignored
            }
        }
        (Action::SetValue, Some(ActionData::Value(value))) => {
            let filter = state.borrow().policy.command_filter;
            // `SetValue` swaps the *whole document* for the supplied string, so
            // accepting `InsertChar` is not enough on its own: under a
            // forward-only filter this is the single most destructive edit
            // available, however additive the incoming text looks. Dictation
            // that wants to add rather than replace arrives as
            // `ReplaceSelectedText` below.
            if !filter.accepts(EditCommandKind::InsertChar)
                || !filter.allows_wholesale_replacement()
            {
                return EventResponse::Ignored;
            }
            let st = state.borrow();
            st.cursor.select(SelectionType::Document);
            let _ = st.cursor.insert_text(value.as_ref());
            // For some people this **is** typing — dictation, a braille display —
            // and it is reported as itself rather than as `Keyboard` or as
            // nothing at all. A toolkit that folded it into typing would erase
            // how they work; one that reported nothing would leave anything
            // counting arrivals silently short for exactly those writers.
            st.report_inserted(EditSource::Accessibility, value.as_ref());
            drop(st);
            sync_cursor_signals(state);
            ctx.request_frame();
            EventResponse::Handled
        }
        (Action::ReplaceSelectedText, Some(ActionData::Value(value))) => {
            // Insert at the caret, replacing the active selection (if
            // any) — NOT the whole document like `SetValue`. The AT-SPI
            // (Linux) / UIA (Windows) braille-keyboard & dictation
            // insertion path; macOS routes insertion through `SetValue`.
            // We advertise the action in `accessibility()`, so service it.
            let filter = state.borrow().policy.command_filter;
            if !filter.accepts(EditCommandKind::InsertChar) {
                return EventResponse::Ignored;
            }
            let st = state.borrow();
            self::keyboard::collapse_selection_before_insert(&st);
            let _ = st.cursor.insert_text(value.as_ref());
            // The AT-SPI / UIA insertion path, which is how a braille keyboard
            // and most dictation write. Same reason as `SetValue` above.
            st.report_inserted(EditSource::Accessibility, value.as_ref());
            drop(st);
            sync_cursor_signals(state);
            ctx.request_frame();
            EventResponse::Handled
        }
        (Action::ScrollIntoView, _) => {
            let mut st = state.borrow_mut();
            if let Some(new_y) = st.engine.ensure_caret_visible() {
                st.scroll_y.set(new_y);
            }
            drop(st);
            ctx.request_frame();
            EventResponse::Handled
        }
        _ => EventResponse::Ignored,
    }
}

/// Convert an intra-fragment byte offset into a character index.
/// Used by `accessibility()` to map the user's document-absolute
/// cursor position into AccessKit's `TextPosition.character_index`
/// (which indexes into the target TextRun's `character_lengths`,
/// i.e., one entry per Rust `char`).
fn char_index_in_text(text: &str, byte_offset: usize) -> usize {
    // Walk char_indices until we pass byte_offset; the count at
    // that point is the character index. Fall back to the char
    // count when byte_offset >= text.len().
    if byte_offset >= text.len() {
        return text.chars().count();
    }
    let mut count = 0usize;
    for (i, _) in text.char_indices() {
        if i >= byte_offset {
            return count;
        }
        count += 1;
    }
    count
}

// ── The framework's uniform view of a text-editing widget ────────────────────

impl teksilo_core::text_surface::TextSurface for EditorHandle {
    fn can_undo(&self) -> bool {
        EditorHandle::can_undo(self).get()
    }

    fn can_redo(&self) -> bool {
        EditorHandle::can_redo(self).get()
    }

    fn undo(&self) {
        EditorHandle::undo(self);
    }

    fn redo(&self) {
        EditorHandle::redo(self);
    }

    /// The editor's own [`CommandFilter`]
    /// is the authority: a host that has imposed `ForwardOnly` or `ReadOnly` on
    /// this editor must not be able to route around it from a menu.
    fn history_frozen(&self) -> bool {
        !self.command_filter().accepts(EditCommandKind::Undo)
    }

    fn has_selection(&self) -> bool {
        EditorHandle::has_selection(self).get()
    }

    fn is_read_only(&self) -> bool {
        !self.command_filter().accepts(EditCommandKind::InsertChar)
    }

    fn allows_copy(&self) -> bool {
        self.command_filter().accepts(EditCommandKind::Copy)
    }

    fn cut(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        EditorHandle::cut(self, ctx);
    }

    fn copy(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        EditorHandle::copy(self, ctx);
    }

    fn paste(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        EditorHandle::paste(self, ctx);
    }

    fn paste_plain(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        EditorHandle::paste_unformatted(self, ctx);
    }

    fn select_all(&self) {
        EditorHandle::select_all(self);
    }
}