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
#![allow(dead_code)]
use std::collections::BTreeMap;
use std::sync::Arc;
use egui::{Color32, Key, Pos2, Response, Ui, Vec2, WidgetInfo, WidgetType};
use egui_extras::{Column, TableBuilder};
use serde_json::Value;
use ui_grid_core::{
constants::SortDirection,
display::format_grid_cell_display_value,
edit::{
GridEditSession, GridMoveDirection, begin_grid_edit_session, find_next_grid_cell,
parse_grid_edited_value, stringify_grid_editor_value,
},
export::{
GridExportContext, GridExportPayload, build_csv_export_payload, build_grid_export_context,
header_label,
},
exporter_registry::{
GridExportResult, GridExportScope, GridExporter, GridRegisteredExportContext,
UnknownExportFormat, register_grid_exporter, unregister_grid_exporter,
},
models::{
BuildGridPipelineContext, DisplayItem, GridCellPosition, GridColumnDef,
GridGroupingOptions, GridIcon, GridOptions, GridRow, PipelineResult, RowItem, SortState,
},
pagination::{get_first_row_index_value, get_last_row_index_value, get_total_pages_value},
pinning::{
PinDirection, PinnedColumnState, build_initial_pinned_state, get_column_pin_direction,
is_column_pinnable, pin_column_state,
},
pipeline::build_grid_pipeline,
state::{
BuildGridSavedStateContext, create_grid_restore_mutation_plan,
deserialize_grid_saved_state, deserialize_grid_saved_state_with,
serialize_grid_saved_state, serialize_grid_saved_state_with,
},
utils::get_cell_value,
validate::{get_grid_cell_error_messages, is_grid_cell_invalid, run_grid_cell_validators},
viewmodel::{
can_grid_move_columns, grid_expand_toggle_label_for_row, grid_filter_placeholder,
grid_group_disclosure_icon, grid_group_disclosure_label, grid_grouping_button_icon,
grid_grouping_button_label, grid_pin_left_icon, grid_pin_right_icon, grid_sort_button_icon,
grid_sort_button_label, grid_tree_toggle_icon, grid_tree_toggle_label_for_row,
grid_unpin_icon, is_grid_column_grouped,
},
};
use crate::column_ext::{
EguiColumnExt, EguiHeaderAction, GridCellContext, GridFilterContext, GridHeaderControlsContext,
find_column_ext, find_column_ext_mut,
};
use crate::grid_theme::GridTheme;
fn paint_triangle(painter: &egui::Painter, center: Pos2, half: f32, dir: TriDir, color: Color32) {
let points = match dir {
TriDir::Left => vec![
Pos2::new(center.x + half * 0.5, center.y - half),
Pos2::new(center.x - half * 0.7, center.y),
Pos2::new(center.x + half * 0.5, center.y + half),
],
TriDir::Right => vec![
Pos2::new(center.x - half * 0.5, center.y - half),
Pos2::new(center.x + half * 0.7, center.y),
Pos2::new(center.x - half * 0.5, center.y + half),
],
TriDir::Down => vec![
Pos2::new(center.x - half, center.y - half * 0.5),
Pos2::new(center.x + half, center.y - half * 0.5),
Pos2::new(center.x, center.y + half * 0.7),
],
TriDir::Up => vec![
Pos2::new(center.x - half, center.y + half * 0.5),
Pos2::new(center.x + half, center.y + half * 0.5),
Pos2::new(center.x, center.y - half * 0.7),
],
};
painter.add(egui::Shape::convex_polygon(
points,
color,
egui::Stroke::NONE,
));
}
#[cfg(test)]
mod tests {
use serde_json::json;
use ui_grid_core::models::{
GridColumnDef, GridColumnType, GridOptions, GridRow, GridSavedState,
};
use super::EguiGrid;
use ui_grid_core::pinning::PinDirection;
fn test_columns() -> Vec<GridColumnDef> {
vec![
GridColumnDef {
name: "owner".to_string(),
display_name: Some("Owner".to_string()),
field: Some("owner".to_string()),
r#type: GridColumnType::String,
..GridColumnDef::default()
},
GridColumnDef {
name: "status".to_string(),
display_name: Some("Status".to_string()),
field: Some("status".to_string()),
r#type: GridColumnType::String,
..GridColumnDef::default()
},
]
}
fn test_options() -> GridOptions {
GridOptions {
id: "desk-grid/spec".to_string(),
column_defs: test_columns(),
data: vec![json!({"id": "row-1", "owner": "Alicia", "status": "Activo"})],
enable_pinning: true,
enable_column_moving: true,
..GridOptions::default()
}
}
fn test_row() -> GridRow {
GridRow::new(
"row-1".to_string(),
json!({"id": "row-1", "owner": "Alicia", "status": "Activo"}),
0,
44,
)
}
#[test]
fn egui_grid_exports_visible_rows_without_io() {
let options = test_options();
let columns = test_columns();
let mut grid = EguiGrid::new();
grid.cached_result.visible_rows = vec![test_row()];
let payload = grid.export_csv(&options, &columns);
assert_eq!(payload.filename, "desk-grid_spec.csv");
assert!(payload.contents.contains("Owner,Status"));
assert!(payload.contents.contains("Alicia,Activo"));
let custom = grid.export_with(&options, &columns, |context| {
context
.rows
.iter()
.map(|row| row.id.clone())
.collect::<Vec<_>>()
.join("|")
});
assert_eq!(custom, "row-1");
}
#[test]
fn egui_grid_save_and_restore_state_are_storage_agnostic() {
let mut grid = EguiGrid::new();
grid.column_order = vec!["status".to_string(), "owner".to_string()];
grid.active_filters
.insert("owner".to_string(), "Ali*".to_string());
grid.group_by_columns = vec!["status".to_string()];
grid.current_page = 3;
grid.page_size = 25;
grid.expanded_rows.insert("row-1".to_string(), true);
grid.expanded_tree_rows.insert("tree-1".to_string(), true);
grid.pinned_columns
.insert("owner".to_string(), "left".to_string());
grid.cached_result.total_items = 80;
let saved = grid.save_state();
let json = grid.serialize_state().expect("serialize state");
let custom = grid.serialize_state_with(|state| state.column_order.join("|"));
assert_eq!(custom, "status|owner");
let mut restored = EguiGrid::new();
restored.restore_state(&saved);
assert_eq!(restored.column_order(), ["status", "owner"]);
assert_eq!(restored.group_by_columns(), ["status"]);
assert_eq!(
restored.pinned_columns().get("owner"),
Some(&"left".to_string())
);
let mut restored_from_json = EguiGrid::new();
restored_from_json
.deserialize_state(&json)
.expect("restore json state");
assert_eq!(restored_from_json.column_order(), ["status", "owner"]);
assert_eq!(
restored_from_json.pinned_columns().get("owner"),
Some(&"left".to_string())
);
let mut restored_custom = EguiGrid::new();
restored_custom
.deserialize_state_with("status|owner", |value| {
Ok::<GridSavedState, &'static str>(GridSavedState {
column_order: value.split('|').map(str::to_string).collect(),
..GridSavedState::default()
})
})
.expect("restore custom state");
assert_eq!(restored_custom.column_order(), ["status", "owner"]);
}
#[test]
fn egui_grid_supports_programmatic_pinning_and_reorder() {
let mut grid = EguiGrid::new();
grid.column_order = vec!["owner".to_string(), "status".to_string()];
grid.pin_column("owner", PinDirection::Left);
assert_eq!(
grid.pinned_columns().get("owner"),
Some(&"left".to_string())
);
grid.move_column_before("status", "owner");
assert_eq!(grid.column_order(), ["status", "owner"]);
}
#[test]
fn egui_grid_restore_normalizes_unsafe_state() {
let mut grid = EguiGrid::new();
grid.restore_state(&GridSavedState {
column_order: vec!["owner".to_string(), "__proto__".to_string()],
filters: std::collections::BTreeMap::from([
("owner".to_string(), "Ali*".to_string()),
("constructor".to_string(), "bad".to_string()),
]),
sort: None,
grouping: vec!["status".to_string(), "prototype".to_string()],
pagination: None,
expandable: Default::default(),
tree_view: Default::default(),
pinning: std::collections::BTreeMap::from([
("owner".to_string(), "left".to_string()),
("prototype".to_string(), "right".to_string()),
]),
column_width_overrides: Default::default(),
});
assert_eq!(grid.column_order(), ["owner"]);
assert_eq!(grid.group_by_columns(), ["status"]);
assert_eq!(
grid.pinned_columns().get("owner"),
Some(&"left".to_string())
);
assert!(!grid.pinned_columns().contains_key("prototype"));
}
}
fn paint_hamburger(painter: &egui::Painter, center: Pos2, half: f32, color: Color32) {
for i in [-1.0_f32, 0.0, 1.0] {
let y = center.y + i * half * 0.6;
painter.line_segment(
[Pos2::new(center.x - half, y), Pos2::new(center.x + half, y)],
egui::Stroke::new(1.5, color),
);
}
}
fn paint_grid_icon(painter: &egui::Painter, center: Pos2, half: f32, color: Color32) {
let s = half * 0.45;
let gap = half * 0.2;
for dx in [-1.0_f32, 1.0] {
for dy in [-1.0_f32, 1.0] {
let cx = center.x + dx * (s + gap);
let cy = center.y + dy * (s + gap);
let r = egui::Rect::from_center_size(Pos2::new(cx, cy), Vec2::splat(s * 2.0));
painter.rect_filled(r, 1.0, color);
}
}
}
fn paint_pin_icon(
painter: &egui::Painter,
center: Pos2,
half: f32,
color: Color32,
side: PinDirection,
) {
let stem_top = Pos2::new(center.x, center.y - half * 0.8);
let stem_bottom = Pos2::new(center.x, center.y + half * 0.9);
painter.line_segment([stem_top, stem_bottom], egui::Stroke::new(1.5, color));
let head = [
Pos2::new(center.x - half * 0.7, center.y - half * 0.25),
Pos2::new(center.x + half * 0.7, center.y - half * 0.25),
Pos2::new(center.x, center.y + half * 0.25),
];
painter.add(egui::Shape::convex_polygon(
head.to_vec(),
color,
egui::Stroke::NONE,
));
let guide_x = match side {
PinDirection::Left => center.x - half * 1.35,
PinDirection::Right => center.x + half * 1.35,
PinDirection::None => center.x,
};
painter.line_segment(
[
Pos2::new(guide_x, center.y - half),
Pos2::new(guide_x, center.y + half),
],
egui::Stroke::new(1.5, color),
);
}
fn paint_unpin_icon(painter: &egui::Painter, center: Pos2, half: f32, color: Color32) {
paint_pin_icon(painter, center, half, color, PinDirection::Left);
painter.line_segment(
[
Pos2::new(center.x - half, center.y + half),
Pos2::new(center.x + half, center.y - half),
],
egui::Stroke::new(1.5, color),
);
}
fn paint_sort_icon(painter: &egui::Painter, center: Pos2, half: f32, color: Color32) {
paint_triangle(
painter,
Pos2::new(center.x, center.y - half * 0.4),
half * 0.55,
TriDir::Up,
color,
);
paint_triangle(
painter,
Pos2::new(center.x, center.y + half * 0.45),
half * 0.55,
TriDir::Down,
color,
);
}
fn paint_semantic_icon(painter: &egui::Painter, rect: egui::Rect, icon: &GridIcon, color: Color32) {
let c = rect.center();
let h = 5.0;
match icon {
GridIcon::Grip => paint_hamburger(painter, c, h, color),
GridIcon::Sort => paint_sort_icon(painter, c, h, color),
GridIcon::SortAsc => paint_triangle(painter, c, h, TriDir::Up, color),
GridIcon::SortDesc => paint_triangle(painter, c, h, TriDir::Down, color),
GridIcon::Group => paint_grid_icon(painter, c, h, color),
GridIcon::Ungroup => {
paint_grid_icon(painter, c, h, color);
painter.line_segment(
[Pos2::new(c.x - h, c.y + h), Pos2::new(c.x + h, c.y - h)],
egui::Stroke::new(1.5, color),
);
}
GridIcon::ChevronLeft => paint_triangle(painter, c, h * 0.8, TriDir::Left, color),
GridIcon::ChevronRight => paint_triangle(painter, c, h * 0.8, TriDir::Right, color),
GridIcon::ChevronDown => paint_triangle(painter, c, h * 0.8, TriDir::Down, color),
GridIcon::PinLeft => paint_pin_icon(painter, c, h, color, PinDirection::Left),
GridIcon::PinRight => paint_pin_icon(painter, c, h, color, PinDirection::Right),
GridIcon::Unpin => paint_unpin_icon(painter, c, h, color),
}
}
fn icon_button(
ui: &mut Ui,
icon: &GridIcon,
theme: &GridTheme,
color: Color32,
active: bool,
) -> egui::Response {
let size = Vec2::splat(16.0);
let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click());
if ui.is_rect_visible(rect) {
let background = if active {
Some(theme.control_active_background)
} else if response.hovered() {
Some(theme.control_hover_background)
} else {
None
};
if let Some(background) = background {
ui.painter().rect_filled(rect.expand(2.0), 4.0, background);
}
paint_semantic_icon(ui.painter(), rect, icon, color);
}
response
}
fn icon_button_labeled(
ui: &mut Ui,
icon: &GridIcon,
theme: &GridTheme,
color: Color32,
label: &str,
active: bool,
) -> Response {
let response = icon_button(ui, icon, theme, color, active);
response.widget_info(|| WidgetInfo::labeled(WidgetType::Button, ui.is_enabled(), label));
response.on_hover_text(label)
}
/// Paint an expand/collapse icon without registering interaction.
/// Returns the allocated rect (with padding) so the caller can do hit-testing.
fn expand_icon_passive(ui: &mut Ui, icon: &GridIcon, color: Color32) -> egui::Rect {
let size = Vec2::new(24.0, 24.0);
let (rect, _) = ui.allocate_exact_size(size, egui::Sense::hover());
if ui.is_rect_visible(rect) {
paint_semantic_icon(ui.painter(), rect, icon, color);
}
rect
}
enum TriDir {
Left,
Right,
Down,
Up,
}
struct HeaderRowLayout {
label_id: egui::Id,
controls_left_x: f32,
}
#[derive(Debug, Clone)]
pub struct EguiGridEvent {
pub kind: EguiGridEventKind,
}
/// Modifier keys held during a row click. The grid widget reads these
/// off `egui::InputState::modifiers` and translates them into selection
/// semantics (range-extend on Shift, additive toggle on Cmd/Ctrl).
#[derive(Debug, Clone, Copy, Default)]
struct RowClickModifiers {
shift: bool,
/// `true` when Cmd is held on Mac or Ctrl on other platforms — egui
/// abstracts both as `modifiers.command`.
toggle: bool,
}
/// Context passed to a custom group-row renderer registered via
/// [`EguiGrid::with_group_row_renderer`]. The renderer paints the
/// entire group row in place of the default implementation.
pub struct GridGroupRowContext<'a> {
pub group: &'a ui_grid_core::models::GroupItem,
pub options: &'a GridOptions,
pub columns: &'a [GridColumnDef],
pub theme: &'a GridTheme,
/// `true` when the group is currently collapsed. Mirrors the
/// `collapsed` flag the default renderer reads to flip the
/// disclosure triangle.
pub collapsed: bool,
}
/// Action returned from a group-row renderer. The default renderer
/// returns `Toggle` when the disclosure chevron is clicked; consumer
/// renderers signal the same intent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GridGroupRowAction {
#[default]
None,
Toggle,
}
/// Context passed to a custom expandable-row renderer registered via
/// [`EguiGrid::with_expandable_row_renderer`]. The renderer paints
/// the entire detail row.
pub struct GridExpandableRowContext<'a> {
pub row: &'a ui_grid_core::models::GridRow,
pub options: &'a GridOptions,
pub columns: &'a [GridColumnDef],
pub theme: &'a GridTheme,
}
/// Context passed to a custom empty-state renderer registered via
/// [`EguiGrid::with_empty_state_renderer`]. Painted when the
/// pipeline produces no display items.
pub struct GridEmptyStateContext<'a> {
pub options: &'a GridOptions,
pub theme: &'a GridTheme,
}
/// Context passed to a custom selection-checkbox renderer registered
/// via [`EguiGrid::with_selection_checkbox_renderer`]. The renderer
/// paints a checkbox-equivalent control inside the synthetic
/// `selectionRowHeaderCol` cell. `row` is `None` for the header
/// (select-all) cell and `Some(row)` for per-row cells. Mutating the
/// `&mut bool` (and returning `true`) flips the row's selection (or
/// triggers select-all on the header).
pub struct GridSelectionCheckboxContext<'a> {
pub row: Option<&'a ui_grid_core::models::GridRow>,
pub options: &'a GridOptions,
pub theme: &'a GridTheme,
/// `true` when the cell should accept input. Mirrors the TS
/// disabled-state for rows whose `enable_selection` is `false` or
/// the select-all header when `enable_select_all` is `false`.
pub enabled: bool,
/// `true` when this is the header (select-all) cell. Mutually
/// exclusive with `row.is_some()`; provided for renderer clarity.
pub is_header: bool,
}
type GroupRowRenderer = Box<dyn FnMut(&mut Ui, &GridGroupRowContext<'_>) -> GridGroupRowAction>;
type ExpandableRowRenderer = Box<dyn FnMut(&mut Ui, &GridExpandableRowContext<'_>)>;
type EmptyStateRenderer = Box<dyn FnMut(&mut Ui, &GridEmptyStateContext<'_>)>;
/// Returns `true` when the user toggled the checkbox; the grid then
/// applies the selection mutation. Mirrors the egui idiom of
/// "widget changed".
type SelectionCheckboxRenderer =
Box<dyn FnMut(&mut Ui, &GridSelectionCheckboxContext<'_>, &mut bool) -> bool>;
/// Parse a `"<n>px"` width string into a `f32`. Returns `None` for
/// non-pixel widths (`"50%"`, `"minmax(...)"`, `"auto"`, etc.) — the
/// table-column wiring then falls through to `Column::auto()` or
/// `Column::remainder()` so the column still stretches with the
/// viewport.
fn parse_pixel_width(raw: &str) -> Option<f32> {
let trimmed = raw.trim();
let stripped = trimmed.strip_suffix("px").unwrap_or(trimmed);
stripped.trim().parse::<f32>().ok().filter(|v| *v > 0.0)
}
/// Synthetic column the grid prepends to render the row-selection
/// checkbox. Mirrors the TS `selectionRowHeaderCol` sentinel — the
/// same name is used by `viewmodel::is_grid_primary_column` and the
/// CSV exporter to skip the synthetic column.
pub const SELECTION_ROW_HEADER_COL_NAME: &str = "selectionRowHeaderCol";
/// Compute the synthetic checkbox column's width as 2× the actual
/// rendered checkbox width. egui's empty-label `Checkbox` paints a
/// square `icon_width` × `icon_width` glyph; doubling that gives a
/// column with one checkbox-width of breathing room split evenly on
/// each side, which keeps the checkbox visually centred regardless
/// of theme overrides to `spacing.icon_width`.
fn selection_row_header_col_width(style: &egui::Style) -> f32 {
(style.spacing.icon_width * 2.0).max(24.0)
}
/// Build the synthetic checkbox column. The column is marked pinned-left
/// so it stays anchored to the leading edge regardless of user pin
/// state. Sort / filter / group / pin chrome is suppressed; width is
/// fixed to twice the rendered checkbox width so the column doesn't
/// expand under `Column::auto()` and the checkbox sits centred.
fn build_selection_row_header_column(width_px: f32) -> GridColumnDef {
GridColumnDef {
name: SELECTION_ROW_HEADER_COL_NAME.to_string(),
display_name: Some(String::new()),
sortable: false,
filterable: false,
enable_sorting: false,
enable_filtering: false,
enable_grouping: false,
enable_pinning: false,
pinned_left: true,
width: Some(format!("{}px", width_px.round() as i32)),
..GridColumnDef::default()
}
}
/// True when the grid options enable both row selection and the
/// row-header (checkbox) chrome. The TS contract is that
/// `enable_row_header_selection` defaults to `true`, so a host that
/// merely sets `enable_row_selection` opts in to the chrome.
fn should_show_selection_row_header(options: &GridOptions) -> bool {
options.enable_row_selection.unwrap_or(false)
&& options.enable_row_header_selection.unwrap_or(true)
}
/// Returns the index of the primary data column — the first column
/// that hosts the leading controls (tree indent + expand chevron).
/// Skips the synthetic `selectionRowHeaderCol` so chrome doesn't
/// land on the checkbox cell. Mirrors TS `is_grid_primary_column`.
fn primary_data_column_index(columns: &[GridColumnDef]) -> usize {
columns
.iter()
.position(|col| col.name != SELECTION_ROW_HEADER_COL_NAME)
.unwrap_or(0)
}
#[derive(Debug, Clone)]
pub enum EguiGridEventKind {
SortChanged {
column: String,
direction: SortDirection,
},
FilterChanged {
column: String,
term: String,
},
PageChanged {
page: usize,
},
GroupToggled {
group_id: String,
collapsed: bool,
},
RowExpanded {
row_id: String,
expanded: bool,
},
TreeNodeToggled {
row_id: String,
expanded: bool,
},
CellEdited {
row_id: String,
column: String,
old_value: Value,
new_value: Value,
},
SelectionChanged {
selected_ids: Vec<String>,
},
/// Multi-row selection delta. Emitted when more than one row's
/// selection state changed in a single interaction (Shift-click
/// range, drag-paint, Ctrl+A select-all). Mirrors the TS
/// `rowSelectionChangedBatch` event gated by
/// `options.enableSelectionBatchEvent` (default `true`). Single-row
/// changes still fire `SelectionChanged` as before.
SelectionChangedBatch {
selected_ids: Vec<String>,
},
ColumnPinned {
column: String,
direction: PinDirection,
},
ColumnsReordered {
order: Vec<String>,
},
RenderingComplete {
pipeline_ms: f64,
total_items: usize,
},
/// Emitted when the body scroll position is within
/// `options.infinite_scroll_rows_from_end` rows of the bottom.
/// Mirrors the TS `needLoadMoreData` event consumers wire up to
/// append the next page of data. Hosts that don't enable
/// `enable_infinite_scroll` never see this event.
NeedLoadMoreData,
}
pub struct EguiGrid {
sort_state: SortState,
active_filters: BTreeMap<String, String>,
group_by_columns: Vec<String>,
collapsed_groups: BTreeMap<String, bool>,
expanded_rows: BTreeMap<String, bool>,
expanded_tree_rows: BTreeMap<String, bool>,
current_page: usize,
page_size: usize,
pipeline_dirty: bool,
cached_result: PipelineResult,
events: Vec<EguiGridEvent>,
edit_session: Option<GridEditSession>,
focused_cell: Option<GridCellPosition>,
selected_row_ids: Vec<String>,
last_clicked_row_id: Option<String>,
/// Drag-paint multi-row selection anchor. Set on the row where the
/// pointer was first pressed; cleared on release. Mirrors the TS
/// vanilla `mousedown` → `mousemove` → `mouseup` selection drag.
drag_paint_anchor: Option<String>,
/// Validator registry used to resolve consumer-registered error
/// messages. Built lazily from `options.labels` on first paint and
/// kept around so message-template lookups don't allocate per
/// invalid-cell tooltip.
validator_registry: ui_grid_core::validate::GridValidatorRegistry,
/// Row-edit lifecycle state (dirty / saving / error sets). Lives
/// on the grid because the pipeline rebuild resets the per-row
/// flags every pass; we re-apply them after each rebuild from
/// this state. Hosts mutate it via `mark_row_dirty` /
/// `mark_row_saving` / `mark_row_clean` / `mark_row_error`.
row_edit_state: ui_grid_core::row_edit::GridRowEditState,
/// Per-column width overrides — populated by the auto-fit
/// dblclick handler and any future drag-resize wiring. Mirrors
/// the TS `columnWidthOverrides` map so save / restore round-trips
/// preserve the user's resize state.
column_widths: BTreeMap<String, String>,
/// Last `total_rows` value at which `NeedLoadMoreData` was
/// emitted. Tracking this prevents the event from re-firing on
/// every paint while the viewport hovers near the bottom; the
/// host emits, the host appends, the row count grows, the next
/// near-bottom paint re-emits.
last_load_more_total_rows: Option<usize>,
column_order: Vec<String>,
pinned_columns: PinnedColumnState,
dragged_column: Option<String>,
pinned_scroll_offset_y: f32,
group_row_renderer: Option<GroupRowRenderer>,
expandable_row_renderer: Option<ExpandableRowRenderer>,
empty_state_renderer: Option<EmptyStateRenderer>,
/// Optional override for the synthetic selection-column checkbox.
/// Lives at grid level (not per-column) because the synthetic
/// `selectionRowHeaderCol` has no `EguiColumnExt` entry — the
/// column is injected by the grid itself, so the renderer hook
/// has to live alongside the injection point.
selection_checkbox_renderer: Option<SelectionCheckboxRenderer>,
}
impl Default for EguiGrid {
fn default() -> Self {
Self::new()
}
}
impl EguiGrid {
pub fn new() -> Self {
Self {
sort_state: SortState {
column_name: None,
direction: SortDirection::None,
},
active_filters: BTreeMap::new(),
group_by_columns: Vec::new(),
collapsed_groups: BTreeMap::new(),
expanded_rows: BTreeMap::new(),
expanded_tree_rows: BTreeMap::new(),
current_page: 1,
page_size: 10,
pipeline_dirty: true,
cached_result: PipelineResult::default(),
events: Vec::new(),
edit_session: None,
focused_cell: None,
selected_row_ids: Vec::new(),
last_clicked_row_id: None,
drag_paint_anchor: None,
validator_registry: ui_grid_core::validate::create_grid_validator_registry(
&ui_grid_core::models::GridLabels::default(),
),
row_edit_state: ui_grid_core::row_edit::create_grid_row_edit_state(),
column_widths: BTreeMap::new(),
last_load_more_total_rows: None,
column_order: Vec::new(),
pinned_columns: PinnedColumnState::new(),
dragged_column: None,
pinned_scroll_offset_y: 0.0,
group_row_renderer: None,
expandable_row_renderer: None,
empty_state_renderer: None,
selection_checkbox_renderer: None,
}
}
/// Replace the default group-row renderer. The closure paints the
/// entire row and returns a [`GridGroupRowAction`] indicating
/// whether to toggle the group's collapsed state.
pub fn with_group_row_renderer(
mut self,
renderer: impl FnMut(&mut Ui, &GridGroupRowContext<'_>) -> GridGroupRowAction + 'static,
) -> Self {
self.group_row_renderer = Some(Box::new(renderer));
self
}
/// Replace the default expandable detail-row renderer. The closure
/// paints the entire detail row.
pub fn with_expandable_row_renderer(
mut self,
renderer: impl FnMut(&mut Ui, &GridExpandableRowContext<'_>) + 'static,
) -> Self {
self.expandable_row_renderer = Some(Box::new(renderer));
self
}
/// Replace the default empty-state renderer. Painted when the
/// pipeline produces no display items (no rows, all filtered out).
pub fn with_empty_state_renderer(
mut self,
renderer: impl FnMut(&mut Ui, &GridEmptyStateContext<'_>) + 'static,
) -> Self {
self.empty_state_renderer = Some(Box::new(renderer));
self
}
/// Replace the default selection-checkbox painter for the synthetic
/// `selectionRowHeaderCol`. The closure runs for both per-row cells
/// (`ctx.row = Some(...)`) and the header select-all cell
/// (`ctx.is_header = true`); mutating the `&mut bool` and returning
/// `true` toggles the row's selection (or triggers select-all on
/// the header). Useful for hosts that want a styled checkbox or a
/// non-checkbox selection control (e.g. a star, an icon button).
pub fn with_selection_checkbox_renderer(
mut self,
renderer: impl FnMut(&mut Ui, &GridSelectionCheckboxContext<'_>, &mut bool) -> bool + 'static,
) -> Self {
self.selection_checkbox_renderer = Some(Box::new(renderer));
self
}
pub fn result(&self) -> &PipelineResult {
&self.cached_result
}
/// Read the current selection as a slice of row ids. Useful for
/// hosts that want to display a count or apply bulk operations
/// without subscribing to every `SelectionChanged` event.
pub fn selected_row_ids(&self) -> &[String] {
&self.selected_row_ids
}
/// Read the row-edit lifecycle state. Hosts that want to display
/// a count of pending changes / errors can read this directly.
pub fn row_edit_state(&self) -> &ui_grid_core::row_edit::GridRowEditState {
&self.row_edit_state
}
/// Move a row to the dirty state. Mirrors TS
/// `gridApi.rowEdit.setRowsDirty([rowEntity])` for a single row.
pub fn mark_row_dirty(&mut self, row_id: impl Into<String>) {
let id = row_id.into();
self.row_edit_state.dirty_row_ids.insert(id.clone());
self.row_edit_state.error_row_ids.remove(&id);
self.row_edit_state.saving_row_ids.remove(&id);
self.pipeline_dirty = true;
}
/// Move a row to the saving state. Mirrors TS
/// `gridApi.rowEdit.flushDirtyRows()` per-row transition.
pub fn mark_row_saving(&mut self, row_id: impl Into<String>) {
let id = row_id.into();
self.row_edit_state.saving_row_ids.insert(id.clone());
self.row_edit_state.error_row_ids.remove(&id);
self.pipeline_dirty = true;
}
/// Move a row to the clean state — drops it from every lifecycle
/// set so the dirty / saving / error tints clear on the next
/// pipeline pass. Mirrors TS `setSavePromise(promise.then(clean))`.
pub fn mark_row_clean(&mut self, row_id: &str) {
self.row_edit_state.dirty_row_ids.remove(row_id);
self.row_edit_state.saving_row_ids.remove(row_id);
self.row_edit_state.error_row_ids.remove(row_id);
self.row_edit_state.save_promise_row_ids.remove(row_id);
self.pipeline_dirty = true;
}
/// Move a row to the error state. Mirrors TS save-failure path:
/// the row stays dirty so the user can retry.
pub fn mark_row_error(&mut self, row_id: impl Into<String>) {
let id = row_id.into();
self.row_edit_state.error_row_ids.insert(id.clone());
self.row_edit_state.dirty_row_ids.insert(id.clone());
self.row_edit_state.saving_row_ids.remove(&id);
self.pipeline_dirty = true;
}
/// Read the current per-column width overrides. The map keys are
/// column names; values are CSS-style width strings (e.g.
/// `"180px"`). Hosts can persist this independently of the
/// `save_state` round-trip.
pub fn column_width_overrides(&self) -> &BTreeMap<String, String> {
&self.column_widths
}
/// Set a per-column width override programmatically. Cleared by
/// passing `None`.
pub fn set_column_width_override(&mut self, column_name: &str, width: Option<String>) {
match width {
Some(value) => {
self.column_widths.insert(column_name.to_string(), value);
}
None => {
self.column_widths.remove(column_name);
}
}
}
/// Check whether the cached body scroll position is close enough
/// to the bottom that the host should load more data, and emit a
/// [`EguiGridEventKind::NeedLoadMoreData`] event when so. Mirrors
/// the TS `needLoadMoreData` heuristic. Idempotent within a frame
/// — successive calls without a row count change won't re-emit.
/// `offset_y` is the body's current scroll offset; `viewport_h`
/// is the visible body height; `row_height` is the per-row pixel
/// size; `total_rows` is the number of pipeline-visible rows.
fn maybe_emit_load_more(
&mut self,
options: &GridOptions,
offset_y: f32,
viewport_h: f32,
row_height: f32,
total_rows: usize,
) {
// Only emit when infinite scroll is wired up. `infinite_scroll_down`
// is the TS-equivalent gate (defaults to off when unset).
if !options.infinite_scroll_down.unwrap_or(false) {
return;
}
if total_rows == 0 || row_height <= 0.0 {
return;
}
let from_end = options.infinite_scroll_rows_from_end.unwrap_or(20);
let trigger_band = (from_end as f32) * row_height;
let body_h = total_rows as f32 * row_height;
let bottom_distance = body_h - (offset_y + viewport_h);
if bottom_distance <= trigger_band && self.last_load_more_total_rows != Some(total_rows) {
self.last_load_more_total_rows = Some(total_rows);
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::NeedLoadMoreData,
});
}
}
/// Run a host-agnostic pipeline benchmark against the current
/// options + column state. Mirrors TS `gridApi.core.benchmark`:
/// runs the pipeline `iterations` times and reports total /
/// average / visible-row / rendered-item counts. The default
/// iteration count when callers pass `None` is 25, matching the
/// TS fallback.
pub fn run_benchmark(
&self,
options: &GridOptions,
columns: &[GridColumnDef],
iterations: Option<usize>,
) -> Option<ui_grid_core::benchmark::GridBenchmarkResult> {
let n = iterations.unwrap_or(25);
let context = self.pipeline_context_for_benchmark(options, columns);
ui_grid_core::benchmark::run_grid_benchmark(&context, n)
}
/// Build the same pipeline context `refresh_pipeline` would
/// build, but without mutating cached state. Used by the
/// benchmark probe so it doesn't disturb the rendered grid.
fn pipeline_context_for_benchmark(
&self,
options: &GridOptions,
columns: &[GridColumnDef],
) -> BuildGridPipelineContext {
let grid_options = GridOptions {
grouping: if options.enable_grouping && !self.group_by_columns.is_empty() {
Some(GridGroupingOptions {
group_by: self.group_by_columns.clone(),
start_collapsed: false,
})
} else {
None
},
..options.clone()
};
BuildGridPipelineContext {
options: grid_options,
columns: columns.to_vec(),
active_filters: self.active_filters.clone(),
sort_state: self.sort_state.clone(),
group_by_columns: self.group_by_columns.clone(),
collapsed_groups: self.collapsed_groups.clone(),
expanded_rows: self.expanded_rows.clone(),
expanded_tree_rows: self.expanded_tree_rows.clone(),
hidden_row_reasons: BTreeMap::new(),
current_page: self.current_page,
page_size: self.page_size,
row_size: 44,
}
}
/// Auto-fit a single column to the widest visible cell + header.
/// Mirrors the TS `measureAutoColumnWidth` UX from
/// `vanilla/src/focus.ts` — that path clones the cell DOM and
/// reads `scrollWidth`; egui has no DOM, so we measure each
/// rendered cell's display string + the header label via
/// `egui::Fonts::layout_no_wrap` and pick the widest, then store
/// the result as a `"<px>px"` width override.
///
/// The override is applied via [`column_widths`](Self::column_width_overrides)
/// so save/restore round-trips preserve it. `padding_px` is added
/// on top of the measured width as breathing room (cell padding).
/// Reasonable defaults: ~24px (matching the grid's cell padding).
pub fn auto_fit_column(
&mut self,
ctx: &egui::Context,
columns: &[GridColumnDef],
column_name: &str,
padding_px: f32,
) {
let Some(column) = columns.iter().find(|c| c.name == column_name) else {
return;
};
let header_text = header_label(column);
// Header label width — the visible title.
let header_label_width = ctx.fonts_mut(|fonts| {
fonts
.layout_no_wrap(header_text, egui::FontId::default(), egui::Color32::WHITE)
.size()
.x
});
// Header controls reserve — sort / group / pin chrome sits to
// the right of the label and would clobber the title under
// `Column::auto()` measurement (which only reads the label
// width). Reserve ~28px per visible control + a trailing
// spacer. Mirrors the visual budget the right-to-left
// layout consumes at paint time.
let mut header_controls_reserve = 0.0_f32;
let column_sort_enabled = column.sortable && column.enable_sorting;
if column_sort_enabled {
header_controls_reserve += 28.0;
}
if column.enable_grouping {
header_controls_reserve += 28.0;
}
if column.enable_pinning {
header_controls_reserve += 28.0;
}
let mut max_width = header_label_width + header_controls_reserve;
for row in &self.cached_result.visible_rows {
let text = format_grid_cell_display_value(row, column);
if text.is_empty() {
continue;
}
let width = ctx.fonts_mut(|fonts| {
fonts
.layout_no_wrap(text, egui::FontId::default(), egui::Color32::WHITE)
.size()
.x
});
if width > max_width {
max_width = width;
}
}
let total = (max_width + padding_px).ceil() as i32;
self.column_widths
.insert(column_name.to_string(), format!("{total}px"));
}
pub fn drain_events(&mut self) -> Vec<EguiGridEvent> {
std::mem::take(&mut self.events)
}
pub fn sort_state(&self) -> &SortState {
&self.sort_state
}
pub fn set_page_size(&mut self, size: usize) {
self.page_size = size;
self.current_page = 1;
self.pipeline_dirty = true;
}
pub fn group_by_columns(&self) -> &[String] {
&self.group_by_columns
}
pub fn column_order(&self) -> &[String] {
&self.column_order
}
pub fn pinned_columns(&self) -> &PinnedColumnState {
&self.pinned_columns
}
pub fn pin_column(&mut self, column_name: &str, direction: PinDirection) {
self.set_column_pin_direction(column_name, direction);
}
pub fn move_column_before(&mut self, column_name: &str, target_column_name: &str) {
self.reorder_column_before(column_name, target_column_name);
}
pub fn export_context<'a>(
&'a self,
options: &'a GridOptions,
columns: &'a [GridColumnDef],
) -> GridExportContext<'a> {
build_grid_export_context(&options.id, columns, &self.cached_result.visible_rows)
}
pub fn export_csv(
&self,
options: &GridOptions,
columns: &[GridColumnDef],
) -> GridExportPayload {
build_csv_export_payload(&self.export_context(options, columns))
}
pub fn export_with<'a, T>(
&'a self,
options: &'a GridOptions,
columns: &'a [GridColumnDef],
exporter: impl FnOnce(GridExportContext<'a>) -> T,
) -> T {
exporter(self.export_context(options, columns))
}
/// Register an exporter against the global exporter registry. The
/// registry is process-wide and shared across every `EguiGrid`
/// instance — exporters registered here are reachable from
/// [`EguiGrid::export`] on any grid in the process. Mirrors the TS
/// contract where consumers register exporters once at startup.
pub fn register_exporter(format: impl Into<String>, exporter: Arc<dyn GridExporter>) {
register_grid_exporter(format, exporter);
}
/// Drop a previously-registered exporter. Returns the prior
/// registration when one existed.
pub fn unregister_exporter(format: &str) -> Option<Arc<dyn GridExporter>> {
unregister_grid_exporter(format)
}
/// Run the exporter registered for `format` against the current
/// pipeline result, scoped to `scope`. The default scope is
/// `Visible` (post-filter / post-sort / post-paginate); see
/// [`GridExportScope`] for the others.
pub fn export(
&self,
options: &GridOptions,
columns: &[GridColumnDef],
format: &str,
scope: GridExportScope,
) -> Result<GridExportResult, UnknownExportFormat> {
let rows: Vec<GridRow> = match scope {
GridExportScope::Visible => self.cached_result.visible_rows.clone(),
GridExportScope::All => options
.data
.iter()
.enumerate()
.map(|(index, entity)| {
GridRow::new(
format!("{}-{}", options.id, index),
entity.clone(),
index,
44,
)
})
.collect(),
GridExportScope::Selected => self
.cached_result
.visible_rows
.iter()
.filter(|row| self.selected_row_ids.iter().any(|id| id == &row.id))
.cloned()
.collect(),
};
// Pre-format every cell in row-major order so consumer
// exporters don't have to walk `format_grid_cell_display_value`
// themselves.
let formatted_cells = rows
.iter()
.map(|row| {
columns
.iter()
.map(|column| format_grid_cell_display_value(row, column))
.collect()
})
.collect();
let ctx = GridRegisteredExportContext {
columns,
rows: &rows,
formatted_cells,
options,
scope,
format,
};
ui_grid_core::exporter_registry::export_grid(format, &ctx)
}
pub fn set_group_by(&mut self, columns: Vec<String>) {
self.group_by_columns = columns;
self.pipeline_dirty = true;
}
pub fn save_state(&self) -> ui_grid_core::models::GridSavedState {
ui_grid_core::state::build_grid_saved_state(BuildGridSavedStateContext {
column_order: self.column_order.clone(),
active_filters: self.active_filters.clone(),
sort_state: self.sort_state.clone(),
group_by_columns: self.group_by_columns.clone(),
current_page: self.current_page,
page_size: self.page_size,
total_items: self.cached_result.total_items,
expanded_rows: self.expanded_rows.clone(),
expanded_tree_rows: self.expanded_tree_rows.clone(),
pinned_columns: self.pinned_columns.clone(),
column_width_overrides: self.column_widths.clone(),
})
}
pub fn serialize_state(&self) -> Result<String, serde_json::Error> {
serialize_grid_saved_state(&self.save_state())
}
pub fn serialize_state_with<T>(
&self,
serializer: impl FnOnce(&ui_grid_core::models::GridSavedState) -> T,
) -> T {
serialize_grid_saved_state_with(&self.save_state(), serializer)
}
pub fn restore_state(&mut self, state: &ui_grid_core::models::GridSavedState) {
let plan = create_grid_restore_mutation_plan(state);
if let Some(column_order) = plan.column_order {
self.column_order = column_order;
}
if let Some(filters) = plan.filters {
self.active_filters = filters;
}
if let Some(sort) = plan.sort {
self.sort_state = sort;
}
if let Some(grouping) = plan.grouping {
self.group_by_columns = grouping;
}
if let Some(pagination) = plan.pagination {
self.current_page = pagination.pagination_current_page;
self.page_size = pagination.pagination_page_size;
}
if let Some(expandable) = plan.expandable {
self.expanded_rows = expandable;
}
if let Some(tree_view) = plan.tree_view {
self.expanded_tree_rows = tree_view;
}
if let Some(pinning) = plan.pinning {
self.pinned_columns = pinning;
}
if let Some(widths) = plan.column_width_overrides {
self.column_widths = widths;
}
self.pipeline_dirty = true;
}
pub fn deserialize_state(&mut self, value: &str) -> Result<(), serde_json::Error> {
let state = deserialize_grid_saved_state(value)?;
self.restore_state(&state);
Ok(())
}
pub fn deserialize_state_with<T, E>(
&mut self,
value: T,
deserializer: impl FnOnce(T) -> Result<ui_grid_core::models::GridSavedState, E>,
) -> Result<(), E> {
let state = deserialize_grid_saved_state_with(value, deserializer)?;
self.restore_state(&state);
Ok(())
}
fn sync_column_state(&mut self, columns: &[GridColumnDef]) {
let current_names = columns
.iter()
.map(|column| column.name.clone())
.collect::<Vec<_>>();
self.column_order
.retain(|name| current_names.contains(name));
for name in ¤t_names {
if !self.column_order.contains(name) {
self.column_order.push(name.clone());
}
}
self.pinned_columns
.retain(|name, _| current_names.iter().any(|current| current == name));
for (name, direction) in build_initial_pinned_state(columns) {
self.pinned_columns.entry(name).or_insert(direction);
}
}
fn resolve_columns(&self, columns: &[GridColumnDef]) -> Vec<GridColumnDef> {
let by_name = columns
.iter()
.cloned()
.map(|column| (column.name.clone(), column))
.collect::<BTreeMap<_, _>>();
let mut ordered = Vec::with_capacity(columns.len());
for name in &self.column_order {
if let Some(column) = by_name.get(name) {
ordered.push(column.clone());
}
}
let mut left = Vec::new();
let mut center = Vec::new();
let mut right = Vec::new();
for column in ordered {
match get_column_pin_direction(&self.pinned_columns, &column) {
PinDirection::Left => left.push(column),
PinDirection::Right => right.push(column),
PinDirection::None => center.push(column),
}
}
left.into_iter().chain(center).chain(right).collect()
}
fn cycle_sort_for_column(&mut self, column_name: &str) {
let is_active = self.sort_state.column_name.as_deref() == Some(column_name);
let next_direction = if is_active {
match self.sort_state.direction {
SortDirection::Asc => SortDirection::Desc,
SortDirection::Desc => SortDirection::None,
SortDirection::None => SortDirection::Asc,
}
} else {
SortDirection::Asc
};
self.sort_state = SortState {
column_name: if next_direction == SortDirection::None {
None
} else {
Some(column_name.to_string())
},
direction: next_direction,
};
self.current_page = 1;
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::SortChanged {
column: column_name.to_string(),
direction: next_direction,
},
});
}
fn set_column_pin_direction(&mut self, column_name: &str, direction: PinDirection) {
let previous = self.pinned_columns.clone();
self.pinned_columns = pin_column_state(&self.pinned_columns, column_name, direction);
if self.pinned_columns != previous {
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::ColumnPinned {
column: column_name.to_string(),
direction,
},
});
}
}
fn move_column_relative(&mut self, column_name: &str, delta: isize) {
let Some(index) = self
.column_order
.iter()
.position(|name| name == column_name)
else {
return;
};
let next_index = (index as isize + delta).clamp(0, self.column_order.len() as isize - 1);
let next_index = next_index as usize;
if index == next_index {
return;
}
let column = self.column_order.remove(index);
self.column_order.insert(next_index, column);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::ColumnsReordered {
order: self.column_order.clone(),
},
});
}
fn reorder_column_before(&mut self, dragged: &str, target: &str) {
if dragged == target {
return;
}
let Some(from_index) = self.column_order.iter().position(|name| name == dragged) else {
return;
};
let Some(mut to_index) = self.column_order.iter().position(|name| name == target) else {
return;
};
let column = self.column_order.remove(from_index);
if from_index < to_index {
to_index -= 1;
}
self.column_order.insert(to_index, column);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::ColumnsReordered {
order: self.column_order.clone(),
},
});
}
fn reorder_column_after(&mut self, dragged: &str, target: &str) {
if dragged == target {
return;
}
let Some(from_index) = self.column_order.iter().position(|name| name == dragged) else {
return;
};
let Some(target_index) = self.column_order.iter().position(|name| name == target) else {
return;
};
let column = self.column_order.remove(from_index);
let insert_index = if from_index < target_index {
target_index
} else {
target_index + 1
};
self.column_order.insert(insert_index, column);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::ColumnsReordered {
order: self.column_order.clone(),
},
});
}
pub fn reset(&mut self) {
*self = Self {
page_size: self.page_size,
..Self::new()
};
}
/// Mark the data pipeline as dirty so it re-runs on the next frame.
/// Call this after mutating `GridOptions::data` externally (e.g.
/// live data updates).
///
/// Also clears the rows cache: the cache keys on raw pointer
/// equality of `data` / `options` / hidden / expanded refs, but
/// hosts that reassign `options.data` from a fresh `Vec` may hit
/// stale cache entries when the allocator recycles the same
/// address. Clearing on `mark_dirty` keeps the cache useful for
/// the in-frame benchmark loop without poisoning live-update flows.
pub fn mark_dirty(&mut self) {
self.pipeline_dirty = true;
ui_grid_core::pipeline::clear_grid_pipeline_rows_cache();
}
pub fn show(
&mut self,
ui: &mut Ui,
options: &mut GridOptions,
columns: &[GridColumnDef],
column_ext: &mut [EguiColumnExt],
theme: &GridTheme,
) {
self.sync_column_state(columns);
// Refresh the validator registry from the host's labels so
// tooltip messages pick up consumer overrides. Cheap — the
// registry is just labels + a small extras map.
self.validator_registry =
ui_grid_core::validate::create_grid_validator_registry(&options.labels);
let mut ordered_columns = self.resolve_columns(columns);
// Inject the synthetic selection-row-header column before the
// first user-defined column. Mirrors the TS injection — the
// sentinel name is recognised throughout the core (viewmodel,
// exporter, save-state) so other features handle it correctly
// without further changes.
if should_show_selection_row_header(options)
&& !ordered_columns
.iter()
.any(|column| column.name == SELECTION_ROW_HEADER_COL_NAME)
{
let width = selection_row_header_col_width(ui.style());
ordered_columns.insert(0, build_selection_row_header_column(width));
}
self.handle_keyboard_navigation(ui, options, &ordered_columns);
self.refresh_pipeline(options, &ordered_columns);
if ordered_columns.is_empty() {
ui.label("No columns defined.");
return;
}
// Pre-fit any column that has neither a declared `column.width`
// nor an existing `column_widths` override. egui_extras keeps
// its column widths inside a private per-table `TableState`
// keyed by `id_salt`, so widths measured in the unpinned table
// are lost when a column moves into the pinned (left/right) or
// back to the center table. Carrying the measured width in our
// own shared `column_widths` map keeps every region in sync —
// pin / unpin no longer resets the column to the "scrunched
// narrow" fallback. Mirrors the TS contract where the grid
// measures every column on first paint.
let needs_pre_fit: Vec<String> = ordered_columns
.iter()
.filter(|column| {
column.name != SELECTION_ROW_HEADER_COL_NAME
&& !self.column_widths.contains_key(&column.name)
&& column
.width
.as_deref()
.and_then(parse_pixel_width)
.is_none()
})
.map(|column| column.name.clone())
.collect();
for name in needs_pre_fit {
self.auto_fit_column(
ui.ctx(),
&ordered_columns,
&name,
theme.cell_padding_x * 2.0,
);
}
let total_items = self.cached_result.total_items;
let display_items = std::mem::take(&mut self.cached_result.display_items);
let mut left_columns = Vec::new();
let mut center_columns = Vec::new();
let mut right_columns = Vec::new();
for column in &ordered_columns {
match get_column_pin_direction(&self.pinned_columns, column) {
PinDirection::Left => left_columns.push(column.clone()),
PinDirection::Right => right_columns.push(column.clone()),
PinDirection::None => center_columns.push(column.clone()),
}
}
let has_pinned = !left_columns.is_empty() || !right_columns.is_empty();
// Compute each region's pixel width from the *actual* declared
// column widths (overrides → column.width → fallback). The
// previous `COL_W = 176.0 * count` heuristic over-allocated for
// narrow columns (e.g. the synthetic 30px checkbox column),
// which was previously masked by the center table's
// `Column::remainder()` last column eating the slack. Now that
// pinning doesn't grow the last column, the gap is exposed.
let region_width = |cols: &[GridColumnDef]| -> f32 {
cols.iter()
.map(|column| {
self.column_widths
.get(&column.name)
.and_then(|raw| parse_pixel_width(raw))
.or_else(|| column.width.as_deref().and_then(parse_pixel_width))
.unwrap_or(120.0)
})
.sum()
};
let left_w = region_width(&left_columns);
let right_w = region_width(&right_columns);
let center_declared_w = region_width(¢er_columns);
egui::Frame::new()
.fill(theme.surface)
.stroke(egui::Stroke::new(1.0, theme.border_color))
.corner_radius(theme.radius)
.show(ui, |ui| {
if options.enable_pagination {
egui::Panel::bottom(ui.id().with("grid_pagination"))
.exact_size(36.0)
.show_inside(ui, |ui| {
self.draw_pagination(ui, options, total_items, theme);
});
}
if !has_pinned {
egui::ScrollArea::horizontal()
.auto_shrink([false, false])
.show(ui, |ui| {
// Sum the per-column declared widths; for
// auto-sized columns assume a sensible
// floor (80px). Use the larger of that
// sum and `ui.available_width()` so the
// table grows with the viewport when the
// declared widths are narrower than the
// window.
let declared_sum: f32 = ordered_columns
.iter()
.map(|column| {
self.column_widths
.get(&column.name)
.and_then(|raw| parse_pixel_width(raw))
.or_else(|| {
column.width.as_deref().and_then(parse_pixel_width)
})
.unwrap_or(120.0)
})
.sum();
ui.set_min_width(declared_sum.max(ui.available_width()));
self.draw_table(
ui,
options,
&ordered_columns,
column_ext,
&display_items,
theme,
true,
None,
None,
true,
true,
);
});
return;
}
// Sticky pinned layout: three side-by-side regions, each with its own
// sticky header (via TableBuilder vscroll). Vertical scroll is synchronized
// across all three regions via a shared offset stored on `self`.
let total_w = ui.available_width();
let avail_h = ui.available_height();
let center_w = (total_w - left_w - right_w).max(80.0);
ui.spacing_mut().item_spacing.x = 0.0;
let stored_offset = self.pinned_scroll_offset_y;
let mut new_offset = stored_offset;
ui.horizontal_top(|ui| {
if !left_columns.is_empty() {
ui.allocate_ui_with_layout(
Vec2::new(left_w, avail_h),
egui::Layout::top_down(egui::Align::Min),
|ui| {
ui.set_min_width(left_w);
if let Some(out) = self.draw_table(
ui,
options,
&left_columns,
column_ext,
&display_items,
theme,
true,
Some("grid_left_table"),
Some(stored_offset),
false,
false,
) && (out - stored_offset).abs() > 0.5
{
new_offset = out;
}
},
);
}
if !center_columns.is_empty() {
ui.allocate_ui_with_layout(
Vec2::new(center_w, avail_h),
egui::Layout::top_down(egui::Align::Min),
|ui| {
egui::ScrollArea::horizontal()
.id_salt("grid_center_hscroll")
.auto_shrink([false, false])
.min_scrolled_width(0.0)
.show(ui, |ui| {
let inner_w = center_declared_w.max(center_w);
ui.set_min_width(inner_w);
if let Some(out) = self.draw_table(
ui,
options,
¢er_columns,
column_ext,
&display_items,
theme,
true,
Some("grid_center_table"),
Some(stored_offset),
true,
false,
) && (out - stored_offset).abs() > 0.5
{
new_offset = out;
}
});
},
);
}
if !right_columns.is_empty() {
ui.allocate_ui_with_layout(
Vec2::new(right_w, avail_h),
egui::Layout::top_down(egui::Align::Min),
|ui| {
ui.set_min_width(right_w);
if let Some(out) = self.draw_table(
ui,
options,
&right_columns,
column_ext,
&display_items,
theme,
true,
Some("grid_right_table"),
Some(stored_offset),
false,
false,
) && (out - stored_offset).abs() > 0.5
{
new_offset = out;
}
},
);
}
});
if (new_offset - stored_offset).abs() > 0.5 {
self.pinned_scroll_offset_y = new_offset;
}
});
// Fire `NeedLoadMoreData` if the body is near the bottom and
// infinite-scroll is wired up. Uses the cached scroll offset
// (the pinned variant tracks it; the unpinned variant always
// resets to 0, so no false-fire there).
let row_height = theme.row_height;
let viewport_h = ui.available_height();
self.maybe_emit_load_more(
options,
self.pinned_scroll_offset_y,
viewport_h,
row_height,
self.cached_result.visible_rows.len(),
);
self.cached_result.display_items = display_items;
}
/// True when any `KeyOverrideSpec` declared on `options` matches
/// the supplied key + modifier state. Hosts use this to opt out
/// of built-in keydown handling (Ctrl+A, F2, Home/End, etc.).
fn key_overridden(
options: &GridOptions,
key: &str,
shift: bool,
ctrl: bool,
alt: bool,
meta: bool,
) -> bool {
options
.key_down_overrides
.iter()
.any(|spec| spec.matches(key, shift, ctrl, alt, meta))
}
fn handle_keyboard_navigation(
&mut self,
ui: &mut Ui,
options: &mut GridOptions,
columns: &[GridColumnDef],
) {
let input = ui.input(|i| {
(
i.key_pressed(Key::Tab),
i.key_pressed(Key::Enter),
i.key_pressed(Key::Escape),
i.key_pressed(Key::ArrowUp),
i.key_pressed(Key::ArrowDown),
i.key_pressed(Key::ArrowLeft),
i.key_pressed(Key::ArrowRight),
i.modifiers.shift,
i.key_pressed(Key::Space),
i.modifiers.command && i.key_pressed(Key::A),
)
});
let (tab, enter, escape, up, down, left, right, shift, space, select_all) = input;
let (ctrl_held, alt_held, meta_held) =
ui.input(|i| (i.modifiers.ctrl, i.modifiers.alt, i.modifiers.mac_cmd));
// Additional keys / modifier combos read via a second `ui.input`
// call to keep the upstream tuple within readable bounds.
let (f2, home, end, command_held, first_char) = ui.input(|i| {
// First printable character pressed this frame, if any —
// used to begin an edit pre-seeded with the typed character.
// We deliberately ignore characters reported while a
// modifier (Cmd/Ctrl/Alt) is held so accelerators don't
// accidentally trigger edit mode.
let printable = i.events.iter().find_map(|event| match event {
egui::Event::Text(text) if !text.is_empty() && !i.modifiers.command => {
text.chars().next()
}
_ => None,
});
(
i.key_pressed(Key::F2),
i.key_pressed(Key::Home),
i.key_pressed(Key::End),
i.modifiers.command,
printable,
)
});
// Ctrl+A / Cmd+A — select every selectable row, gated by
// `enable_row_selection` and `enable_select_all` (both default
// off / on respectively to mirror the TS contract). Skips
// entirely while editing so the shortcut doesn't steal text
// selection behaviour from the editor.
if select_all
&& self.edit_session.is_none()
&& !Self::key_overridden(options, "a", shift, ctrl_held, alt_held, meta_held)
{
if options.enable_row_selection.unwrap_or(false)
&& options.enable_select_all.unwrap_or(true)
{
let initial = self.selected_row_ids.clone();
let batch_events = options.enable_selection_batch_event.unwrap_or(true);
self.selected_row_ids = self
.cached_result
.visible_rows
.iter()
.filter(|row| row.enable_selection)
.map(|row| row.id.clone())
.collect();
self.emit_selection_event(&initial, batch_events);
}
return;
}
// Space — toggle the focused row's selection. Mirrors the
// keyboard contract used by the vanilla web component.
if space
&& self.edit_session.is_none()
&& options.enable_row_selection.unwrap_or(false)
&& !Self::key_overridden(options, " ", shift, ctrl_held, alt_held, meta_held)
&& let Some(ref focused) = self.focused_cell
{
let row_id = focused.row_id.clone();
self.handle_row_click(
options,
&row_id,
RowClickModifiers {
shift: false,
toggle: true, // Space is conceptually an additive toggle.
},
);
return;
}
if escape && self.edit_session.is_some() {
self.edit_session = None;
return;
}
if enter && self.edit_session.is_some() {
self.commit_edit(options, columns);
if let Some(ref focused) = self.focused_cell
&& let Some(next) = find_next_grid_cell(
&self.cached_result.visible_rows,
columns,
&focused.row_id,
&focused.column_name,
GridMoveDirection::Down,
None::<fn(&_, &_) -> bool>,
)
{
let position = GridCellPosition {
row_id: next.row.id.clone(),
column_name: next.column.name.clone(),
};
self.begin_edit_at(&position, options, columns);
}
return;
}
if enter && self.edit_session.is_none() {
if let Some(ref focused) = self.focused_cell.clone() {
self.begin_edit_at(focused, options, columns);
}
return;
}
// F2 — alternate begin-edit binding to match the spreadsheet
// convention. Behaves identically to Enter on a focused cell.
if f2
&& self.edit_session.is_none()
&& !Self::key_overridden(options, "F2", shift, ctrl_held, alt_held, meta_held)
&& let Some(ref focused) = self.focused_cell.clone()
{
self.begin_edit_at(focused, options, columns);
return;
}
if tab {
if self.edit_session.is_some() {
self.commit_edit(options, columns);
}
let dir = if shift {
GridMoveDirection::Left
} else {
GridMoveDirection::Right
};
if let Some(ref focused) = self.focused_cell.clone()
&& let Some(next) = find_next_grid_cell(
&self.cached_result.visible_rows,
columns,
&focused.row_id,
&focused.column_name,
dir,
None::<fn(&_, &_) -> bool>,
)
{
let position = GridCellPosition {
row_id: next.row.id.clone(),
column_name: next.column.name.clone(),
};
self.begin_edit_at(&position, options, columns);
}
return;
}
if self.edit_session.is_some() {
return;
}
// Ctrl+Home / Ctrl+End — jump to the first or last visible row
// while keeping the focused column. Mirrors the
// spreadsheet-style binding used by the vanilla web component.
let home_end_key = if home { "Home" } else { "End" };
if command_held
&& (home || end)
&& !Self::key_overridden(options, home_end_key, shift, ctrl_held, alt_held, meta_held)
&& let Some(ref focused) = self.focused_cell.clone()
{
let rows = &self.cached_result.visible_rows;
let target_row = if home { rows.first() } else { rows.last() };
if let Some(target) = target_row {
let position = GridCellPosition {
row_id: target.id.clone(),
column_name: focused.column_name.clone(),
};
self.focused_cell = Some(position.clone());
self.selected_row_ids = vec![position.row_id.clone()];
self.last_clicked_row_id = Some(position.row_id);
}
return;
}
// Home / End — move focus to the first or last column on the
// current row. Honors `enable_cell_navigation` semantics
// implicitly through `find_next_grid_cell`.
if (home || end)
&& !command_held
&& !Self::key_overridden(options, home_end_key, shift, ctrl_held, alt_held, meta_held)
&& let Some(ref focused) = self.focused_cell.clone()
&& let Some(target_column) = (if home {
columns.first()
} else {
columns.last()
})
{
let position = GridCellPosition {
row_id: focused.row_id.clone(),
column_name: target_column.name.clone(),
};
self.focused_cell = Some(position.clone());
self.selected_row_ids = vec![position.row_id.clone()];
self.last_clicked_row_id = Some(position.row_id);
return;
}
// First-character keypress — begin editing the focused cell
// pre-seeded with the typed character. Skipped when no cell
// is focused, when no column is editable, or when a modifier
// (Cmd/Ctrl/Alt) was held (those are handled by the input
// gather above as accelerators).
if let Some(ch) = first_char
&& let Some(ref focused) = self.focused_cell.clone()
{
let column = columns.iter().find(|c| c.name == focused.column_name);
let is_editable =
column.is_some_and(|c| c.enable_cell_edit || options.enable_cell_edit);
if is_editable {
let session =
begin_grid_edit_session(&focused.row_id, &focused.column_name, ch.to_string());
self.edit_session = Some(session);
return;
}
}
let direction = if up {
Some(GridMoveDirection::Up)
} else if down {
Some(GridMoveDirection::Down)
} else if left {
Some(GridMoveDirection::Left)
} else if right {
Some(GridMoveDirection::Right)
} else {
None
};
if let Some(dir) = direction
&& let Some(ref focused) = self.focused_cell.clone()
&& let Some(next) = find_next_grid_cell(
&self.cached_result.visible_rows,
columns,
&focused.row_id,
&focused.column_name,
dir,
None::<fn(&_, &_) -> bool>,
)
{
let position = GridCellPosition {
row_id: next.row.id.clone(),
column_name: next.column.name.clone(),
};
self.focused_cell = Some(position.clone());
self.selected_row_ids = vec![position.row_id.clone()];
self.last_clicked_row_id = Some(position.row_id);
}
}
fn begin_edit_at(
&mut self,
position: &GridCellPosition,
options: &GridOptions,
columns: &[GridColumnDef],
) {
let column = columns.iter().find(|c| c.name == position.column_name);
let is_editable = column.is_some_and(|c| c.enable_cell_edit || options.enable_cell_edit);
if !is_editable {
self.focused_cell = Some(position.clone());
self.selected_row_ids = vec![position.row_id.clone()];
return;
}
let current_value = self
.cached_result
.visible_rows
.iter()
.find(|r| r.id == position.row_id)
.and_then(|row| column.map(|col| get_cell_value(&row.entity, col)))
.unwrap_or(Value::Null);
let session = begin_grid_edit_session(
&position.row_id,
&position.column_name,
stringify_grid_editor_value(¤t_value),
);
self.focused_cell = Some(position.clone());
self.selected_row_ids = vec![position.row_id.clone()];
self.edit_session = Some(session);
}
fn commit_edit(&mut self, options: &mut GridOptions, columns: &[GridColumnDef]) {
let session = match self.edit_session.take() {
Some(s) => s,
None => return,
};
let column = columns
.iter()
.find(|c| c.name == session.editing_cell.column_name);
let column = match column {
Some(c) => c,
None => return,
};
let field = column.field.as_deref().unwrap_or(&column.name);
let old_value = options
.data
.iter()
.find(|r| {
r.get("id")
.and_then(|v| v.as_str())
.is_some_and(|id| id == session.editing_cell.row_id)
})
.and_then(|r| r.get(field).cloned())
.unwrap_or(Value::Null);
let new_value = parse_grid_edited_value(column, &session.editing_value, &old_value);
if new_value != old_value {
if let Some(row) = options.data.iter_mut().find(|r| {
r.get("id")
.and_then(|v| v.as_str())
.is_some_and(|id| id == session.editing_cell.row_id)
}) && let Some(obj) = row.as_object_mut()
{
obj.insert(field.to_string(), new_value.clone());
// Run any validators declared on the column. The
// helper stamps `$$invalid<col>` and per-validator
// error keys directly on the entity, which the cell
// paint path picks up via `is_grid_cell_invalid` and
// the validation chrome (border + tooltip).
if column.validators.is_some() {
let mut entity = serde_json::Value::Object(obj.clone());
let _ = run_grid_cell_validators(
&mut entity,
column,
&new_value,
&old_value,
&self.validator_registry,
);
if let Some(updated) = entity.as_object() {
obj.clone_from(updated);
}
}
}
// Mark the row dirty so the row-edit chrome lights up. The
// pipeline rebuild resets per-row flags every pass; the
// `row_edit_state` set persists the dirty marker across
// rebuilds via `refresh_pipeline`.
self.row_edit_state
.dirty_row_ids
.insert(session.editing_cell.row_id.clone());
self.row_edit_state
.error_row_ids
.remove(&session.editing_cell.row_id);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::CellEdited {
row_id: session.editing_cell.row_id,
column: session.editing_cell.column_name,
old_value,
new_value,
},
});
}
}
#[allow(clippy::too_many_arguments)]
fn draw_table(
&mut self,
ui: &mut Ui,
options: &mut GridOptions,
columns: &[GridColumnDef],
column_ext: &mut [EguiColumnExt],
display_items: &[DisplayItem],
theme: &GridTheme,
vscroll: bool,
id_salt: Option<&str>,
scroll_offset_y: Option<f32>,
scroll_bar_visible: bool,
fill_remainder: bool,
) -> Option<f32> {
let show_filters = options.enable_filtering;
let label_row_h = theme.header_padding_y + 20.0;
let header_height = if show_filters {
label_row_h + theme.filter_padding_y + 22.0 + 4.0
} else {
label_row_h + theme.header_padding_y
};
let resizable = options.enable_column_resizing;
// Double-click on the resize handle auto-fits the column to
// its widest cell + header label (mirrors the TS contract).
// egui_extras 0.34's built-in dblclick detection in
// `TableBuilder::header()` checks `ui.id().with("resize_column")`
// but the actual interact id used to register the resize handle
// response is `state_id.with("resize_column")` (where state_id =
// ui.id().with(id_salt)). The IDs don't match, so the built-in
// path never fires. Re-read the resize-handle response under
// the *correct* id and route to our existing `auto_fit_column`.
let table_state_id = match id_salt {
Some(salt) => ui.id().with(egui::Id::new(salt)),
None => ui.id().with(egui::Id::new("__table_state")),
};
let mut auto_fit_index: Option<usize> = None;
for (i, _) in columns.iter().enumerate() {
let resize_id = table_state_id.with("resize_column").with(i);
if let Some(resp) = ui.ctx().read_response(resize_id)
&& resp.double_clicked()
{
auto_fit_index = Some(i);
break;
}
}
let auto_fit_requested = if let Some(i) = auto_fit_index
&& let Some(column) = columns.get(i)
{
let column_name = column.name.clone();
self.auto_fit_column(ui.ctx(), columns, &column_name, theme.cell_padding_x * 2.0);
true
} else {
false
};
let mut table = TableBuilder::new(ui)
.striped(false)
.vscroll(vscroll)
.resizable(resizable)
.cell_layout(egui::Layout::left_to_right(egui::Align::Center));
if let Some(salt) = id_salt {
table = table.id_salt(salt);
}
if auto_fit_requested {
// Drop egui_extras' persisted column widths so our newly
// written `column_widths` override (translated to
// `Column::initial(effective)` below) actually takes effect
// on this frame. Without this, `TableState::load` keeps the
// prior widths via `Size::exact(prev_width)` and our
// override is ignored until the user otherwise pokes the
// table.
table.reset();
}
if let Some(offset) = scroll_offset_y {
table = table.vertical_scroll_offset(offset);
}
if !scroll_bar_visible {
table =
table.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden);
}
// Column sizing precedence:
// 1. `column_widths` override (set by auto-fit / drag-resize /
// restore-state) — fixed pixel width, resizable.
// 2. `column.width` declared on the model (e.g. "180px") —
// fixed pixel width, resizable.
// 3. `Column::auto()` — sized to content, resizable.
// The last column always uses `remainder()` so the table
// expands to fill the available width when the window is wider
// than the sum of fixed columns. Mirrors the TS contract where
// the body subgrid stretches across the viewport.
//
// The primary data column carries the expand / tree-toggle
// chevron when those features are on. The chevron is drawn
// outside the cell-content path so `Column::auto()` won't
// measure it; bump the column's min-width to reserve space
// for it (24px icon + 12px padding ≈ 36px), so the column
// visibly grows to fit the leading control when toggles are
// active.
let last_index = columns.len().saturating_sub(1);
let primary_index = primary_data_column_index(columns);
let leading_controls_active = options.enable_expandable || options.enable_tree_view;
for (index, column) in columns.iter().enumerate() {
let is_synthetic_selection = column.name == SELECTION_ROW_HEADER_COL_NAME;
let override_px = self
.column_widths
.get(&column.name)
.and_then(|raw| parse_pixel_width(raw));
let column_px = if override_px.is_some() {
override_px
} else {
column.width.as_deref().and_then(parse_pixel_width)
};
// Synthetic selection column wants its declared narrow width
// (≈ 2× checkbox glyph) without the data-column 80px floor.
let primary_min: f32 = if is_synthetic_selection {
0.0
} else if index == primary_index && leading_controls_active {
160.0
} else {
80.0
};
let table_column = if let Some(px) = column_px {
let effective = px.max(primary_min);
let mut col = Column::initial(effective).resizable(resizable).clip(true);
if is_synthetic_selection {
// Lock the synthetic column to its computed width;
// letting the user resize it would defeat the
// checkbox-only sizing contract.
col = col.at_least(effective).at_most(effective).resizable(false);
}
col
} else if index == last_index && fill_remainder {
// Only the unpinned (single-table) layout uses
// `remainder` to fill the viewport. In the pinned 3-table
// layout each region is sized to the sum of its columns,
// so a `remainder` last column would silently grow to
// eat any leftover space when the user pins another
// column elsewhere — that's the "pinning makes the last
// column wider" bug. Fall through to `auto` instead.
Column::remainder()
.at_least(primary_min)
.resizable(resizable)
.clip(true)
} else {
Column::auto()
.at_least(primary_min)
.resizable(resizable)
.clip(true)
};
table = table.column(table_column);
}
let has_mixed_heights = display_items
.iter()
.any(|item| !matches!(item, DisplayItem::Row(_)));
// Captures the actual rendered width of each header cell so we
// can sync drag-resize back into `column_widths`. egui_extras
// owns the live width inside its private `TableState`; without
// this pass the user can drag a column wider but the outer
// scroll-area / pinned-region width math (which reads
// `column_widths`) keeps the prior value, leaving empty
// scrollable space to the right of the table. Synthetic
// selection column is skipped because its width is fixed.
let mut measured_widths: Vec<(String, f32)> = Vec::with_capacity(columns.len());
let body_output = table
.header(header_height, |mut header| {
for col in columns.iter() {
header.col(|ui| {
let rect = ui.max_rect();
if col.name != SELECTION_ROW_HEADER_COL_NAME {
measured_widths.push((col.name.clone(), rect.width()));
}
let pin_direction = get_column_pin_direction(&self.pinned_columns, col);
let header_background = if pin_direction == PinDirection::None {
theme.header_background
} else {
theme.pinned_header_background
};
ui.painter().rect_filled(rect, 0.0, header_background);
let is_sort_active = self.sort_state.column_name.as_ref()
== Some(&col.name)
&& self.sort_state.direction != SortDirection::None;
if is_sort_active {
ui.painter()
.rect_filled(rect, 0.0, theme.header_sort_active_bg());
}
// Bottom border
let bottom = egui::Rect::from_min_size(
egui::pos2(rect.min.x, rect.max.y - 1.0),
Vec2::new(rect.width(), 1.0),
);
ui.painter().rect_filled(bottom, 0.0, theme.border_color);
if pin_direction != PinDirection::None {
let x = if pin_direction == PinDirection::Left {
rect.min.x
} else {
rect.max.x - 3.0
};
let pin_indicator = egui::Rect::from_min_size(
egui::pos2(x, rect.min.y),
Vec2::new(3.0, rect.height()),
);
ui.painter()
.rect_filled(pin_indicator, 0.0, theme.pinned_indicator);
}
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
ui.add_space(theme.header_padding_y * 0.5);
let header_label_id = self.draw_header_row(
ui,
options,
col,
find_column_ext_mut(column_ext, &col.name),
theme,
egui::Rect::from_min_max(
rect.min,
egui::pos2(rect.max.x, rect.min.y + label_row_h),
),
);
if show_filters {
ui.add_space(2.0);
self.draw_filter_input(
ui,
options,
col,
find_column_ext_mut(column_ext, &col.name),
theme,
header_label_id,
);
}
});
});
}
})
.body(|mut body| {
// Empty-state — emit a single full-height row hosting
// the consumer's renderer (or a default heading + body).
// Painted only when the pipeline produced no display
// items at all; non-empty bodies fall through to the
// regular per-row dispatch below.
if display_items.is_empty() && !columns.is_empty() {
body.row(theme.row_height * 4.0, |mut row| {
// Span by drawing the empty-state into the
// first column cell only; the remaining cells
// are left blank so the table layout stays
// intact.
row.col(|ui| {
self.draw_empty_state_row(ui, options, theme);
});
for _ in 1..columns.len() {
row.col(|_| {});
}
});
return;
}
if has_mixed_heights {
let heights = display_items.iter().map(|item| match item {
DisplayItem::Group(_) => theme.group_padding_y * 2.0 + 20.0,
DisplayItem::Row(_) => theme.row_height,
DisplayItem::Expandable(_) => 120.0,
});
body.heterogeneous_rows(heights, |mut row| {
let row_index = row.index();
if let Some(item) = display_items.get(row_index) {
for col_index in 0..columns.len() {
row.col(|ui| {
self.draw_display_item(
ui, options, columns, column_ext, item, col_index,
row_index, theme,
);
});
}
}
});
} else {
body.rows(theme.row_height, display_items.len(), |mut row| {
let row_index = row.index();
if let Some(item) = display_items.get(row_index) {
for col_index in 0..columns.len() {
row.col(|ui| {
self.draw_display_item(
ui, options, columns, column_ext, item, col_index,
row_index, theme,
);
});
}
}
});
}
});
if ui.input(|input| input.pointer.any_released()) {
self.dragged_column = None;
}
// Sync measured header widths back into `column_widths`. Catches
// user drag-resize (egui_extras' built-in handle widens the
// header cell but doesn't touch our map) and the auto-fit
// dblclick path (`Column::initial(effective)` → measured rect
// confirms the new width). 1px tolerance avoids thrash from
// sub-pixel rounding. Skipped during an active resize drag so
// we don't flood the override map with intermediate widths.
let pointer_held = ui.input(|i| i.pointer.any_down());
if !pointer_held {
for (name, width) in measured_widths {
let prior = self
.column_widths
.get(&name)
.and_then(|raw| parse_pixel_width(raw))
.unwrap_or(0.0);
if (prior - width).abs() > 1.0 {
self.column_widths
.insert(name, format!("{}px", width.round() as i32));
}
}
}
if vscroll {
Some(body_output.state.offset.y)
} else {
None
}
}
fn refresh_pipeline(&mut self, options: &GridOptions, columns: &[GridColumnDef]) {
if !self.pipeline_dirty {
return;
}
// Drop the rows cache before every refresh. The cache keys on
// raw-pointer identity, which is unsound for stack-constructed
// contexts and Vecs that reuse freed addresses. Production
// refreshes always need a fresh pipeline run; the cache only
// earns its keep inside the in-frame benchmark loop, where
// the same context is fed N times in succession.
ui_grid_core::pipeline::clear_grid_pipeline_rows_cache();
let grid_options = GridOptions {
grouping: if options.enable_grouping && !self.group_by_columns.is_empty() {
Some(GridGroupingOptions {
group_by: self.group_by_columns.clone(),
start_collapsed: false,
})
} else {
None
},
..options.clone()
};
let context = BuildGridPipelineContext {
options: grid_options,
columns: columns.to_vec(),
active_filters: self.active_filters.clone(),
sort_state: self.sort_state.clone(),
group_by_columns: self.group_by_columns.clone(),
collapsed_groups: self.collapsed_groups.clone(),
expanded_rows: self.expanded_rows.clone(),
expanded_tree_rows: self.expanded_tree_rows.clone(),
hidden_row_reasons: BTreeMap::new(),
current_page: self.current_page,
page_size: self.page_size,
row_size: 44,
};
self.cached_result = build_grid_pipeline(&context);
// Re-apply row-edit lifecycle flags to the freshly-built rows.
// The pipeline resets `is_dirty` / `is_saving` / `is_error` to
// false on every rebuild because they live on `GridRow`, not
// on the source entity. Persisting them in `row_edit_state` and
// re-stamping here is what gives the row-edit chrome its
// session-stable lifetime.
for row in self.cached_result.visible_rows.iter_mut() {
if self.row_edit_state.dirty_row_ids.contains(&row.id) {
row.is_dirty = true;
}
if self.row_edit_state.saving_row_ids.contains(&row.id) {
row.is_saving = true;
}
if self.row_edit_state.error_row_ids.contains(&row.id) {
row.is_error = true;
row.is_dirty = true;
}
}
self.pipeline_dirty = false;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::RenderingComplete {
pipeline_ms: self.cached_result.pipeline_ms,
total_items: self.cached_result.total_items,
},
});
}
fn draw_header_row(
&mut self,
ui: &mut Ui,
options: &GridOptions,
column: &GridColumnDef,
column_ext: Option<&mut EguiColumnExt>,
theme: &GridTheme,
header_row_rect: egui::Rect,
) -> egui::Id {
// The synthetic checkbox column is anchored to the leading
// edge and never participates in drag-reorder — neither as a
// drag source nor as a drop target.
let is_synthetic_selection = column.name == SELECTION_ROW_HEADER_COL_NAME;
let can_move = can_grid_move_columns(options) && !is_synthetic_selection;
// Drop-zone painting / drop handling for THIS column when another column is being dragged.
// We paint the indicator BEFORE the content so children render on top.
let active_payload = egui::DragAndDrop::payload::<String>(ui.ctx());
let pointer_pos = ui.input(|input| input.pointer.hover_pos());
let mut pending_drop: Option<(String, bool)> = None;
if can_move && let Some(payload) = active_payload.as_deref() {
if payload == column.name.as_str() {
ui.painter().rect_stroke(
header_row_rect.shrink2(Vec2::splat(2.0)),
4.0,
egui::Stroke::new(1.0, theme.accent),
egui::StrokeKind::Inside,
);
} else if let Some(pos) = pointer_pos
&& header_row_rect.contains(pos)
{
let drop_after = pos.x >= header_row_rect.center().x;
let drop_zone_rect = header_row_rect.shrink2(Vec2::new(2.0, 3.0));
ui.painter()
.rect_filled(drop_zone_rect, 4.0, theme.control_hover_background);
let marker_x = if drop_after {
header_row_rect.max.x - 2.0
} else {
header_row_rect.min.x
};
let drop_marker = egui::Rect::from_min_size(
egui::pos2(marker_x, header_row_rect.min.y + 4.0),
Vec2::new(2.0, header_row_rect.height() - 8.0),
);
ui.painter().rect_filled(drop_marker, 1.0, theme.accent);
if ui.input(|input| input.pointer.any_released()) {
pending_drop = Some((payload.clone(), drop_after));
}
}
}
let layout = self.draw_header_row_content(ui, options, column, column_ext, theme);
if can_move {
let drag_rect = egui::Rect::from_min_max(
header_row_rect.min,
egui::pos2(
layout
.controls_left_x
.clamp(header_row_rect.min.x + 12.0, header_row_rect.max.x),
header_row_rect.max.y,
),
);
let drag_id = ui.id().with(("header_drag", &column.name));
let dnd_response = ui
.scope_builder(egui::UiBuilder::new().max_rect(drag_rect), |ui| {
ui.dnd_drag_source(drag_id, column.name.clone(), |ui| {
ui.allocate_rect(ui.max_rect(), egui::Sense::hover())
})
})
.inner;
if dnd_response.response.drag_started() {
self.dragged_column = Some(column.name.clone());
}
}
if let Some((dragged, drop_after)) = pending_drop {
// Consume the payload so other columns don't also try to drop.
let _ = egui::DragAndDrop::take_payload::<String>(ui.ctx());
if drop_after {
self.reorder_column_after(&dragged, &column.name);
} else {
self.reorder_column_before(&dragged, &column.name);
}
}
layout.label_id
}
fn draw_header_row_content(
&mut self,
ui: &mut Ui,
options: &GridOptions,
column: &GridColumnDef,
column_ext: Option<&mut EguiColumnExt>,
theme: &GridTheme,
) -> HeaderRowLayout {
// Synthetic checkbox column — render a select-all checkbox in
// place of the usual sort / filter / pin chrome. Mirrors the
// vanilla web component's behaviour for `selectionRowHeaderCol`.
if column.name == SELECTION_ROW_HEADER_COL_NAME {
return self.draw_select_all_header(ui, options, theme);
}
let label_text = header_label(column);
let can_sort = options.enable_sorting && column.sortable && column.enable_sorting;
let can_group = options.enable_grouping && column.enable_grouping;
let can_pin = is_column_pinnable(options, column);
let can_move = can_grid_move_columns(options);
let is_grouped = is_grid_column_grouped(&self.group_by_columns, column);
let pin_direction = get_column_pin_direction(&self.pinned_columns, column);
let sort_direction = if self.sort_state.column_name.as_ref() == Some(&column.name) {
self.sort_state.direction
} else {
SortDirection::None
};
let mut controls_left_x: Option<f32> = None;
// Layout strategy: reserve space for the controls first
// (right-to-left), THEN draw the label into whatever's left
// with truncation so a narrow column shows the title with an
// ellipsis instead of letting the label clobber the controls.
ui.horizontal(|ui| {
// Right-to-left scope draws controls from the trailing
// edge inward. We measure where they end and use that as
// the label's max-width.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.add_space(theme.header_padding_x);
let mut actions = Vec::new();
let context = GridHeaderControlsContext {
column,
labels: &options.labels,
icons: &options.icons,
theme,
is_grouped,
sort_direction,
pin_direction,
can_sort,
can_group,
can_pin,
can_move,
};
let mut handled = false;
if let Some(column_ext) = column_ext
&& let Some(renderer) = column_ext.header_controls_renderer.as_mut()
{
renderer(ui, &context, &mut actions);
handled = true;
}
if !handled {
if can_pin {
match pin_direction {
PinDirection::Left | PinDirection::Right => {
if icon_button_labeled(
ui,
&grid_unpin_icon(&options.icons),
theme,
theme.accent,
&options.labels.unpin,
true,
)
.clicked()
{
actions.push(EguiHeaderAction::Unpin);
}
}
PinDirection::None => {
if icon_button_labeled(
ui,
&grid_pin_right_icon(&options.icons),
theme,
theme.muted_color,
&options.labels.pin_right,
false,
)
.clicked()
{
actions.push(EguiHeaderAction::PinRight);
}
if icon_button_labeled(
ui,
&grid_pin_left_icon(&options.icons),
theme,
theme.muted_color,
&options.labels.pin_left,
false,
)
.clicked()
{
actions.push(EguiHeaderAction::PinLeft);
}
}
}
}
if can_group {
let group_color = if is_grouped {
theme.accent
} else {
theme.muted_color
};
let group_label = grid_grouping_button_label(is_grouped, &options.labels);
if icon_button_labeled(
ui,
&grid_grouping_button_icon(is_grouped, &options.icons),
theme,
group_color,
&group_label,
is_grouped,
)
.clicked()
{
actions.push(EguiHeaderAction::ToggleGrouping);
}
}
if can_sort {
let is_active = self.sort_state.column_name.as_ref() == Some(&column.name);
let (color, direction) = if is_active {
match self.sort_state.direction {
SortDirection::Asc => (theme.accent, SortDirection::Asc),
SortDirection::Desc => (theme.accent, SortDirection::Desc),
SortDirection::None => (theme.muted_color, SortDirection::None),
}
} else {
(theme.muted_color, SortDirection::None)
};
let sort_label = grid_sort_button_label(direction, &options.labels);
if icon_button_labeled(
ui,
&grid_sort_button_icon(direction, &options.icons),
theme,
color,
&sort_label,
is_active,
)
.clicked()
{
actions.push(EguiHeaderAction::CycleSort);
}
}
}
for action in actions {
match action {
EguiHeaderAction::ToggleGrouping => {
if is_grouped {
self.group_by_columns.retain(|name| name != &column.name);
} else {
self.group_by_columns.push(column.name.clone());
}
self.pipeline_dirty = true;
}
EguiHeaderAction::CycleSort => self.cycle_sort_for_column(&column.name),
EguiHeaderAction::PinLeft => {
self.set_column_pin_direction(&column.name, PinDirection::Left)
}
EguiHeaderAction::PinRight => {
self.set_column_pin_direction(&column.name, PinDirection::Right)
}
EguiHeaderAction::Unpin => {
self.set_column_pin_direction(&column.name, PinDirection::None)
}
EguiHeaderAction::MoveLeft => self.move_column_relative(&column.name, -1),
EguiHeaderAction::MoveRight => self.move_column_relative(&column.name, 1),
}
}
controls_left_x = Some(ui.min_rect().min.x);
});
// Now allocate the remaining space (between leading
// padding and the controls' left edge) for the label,
// and draw it with truncation so an overcrowded column
// shows an ellipsis instead of overflowing into the
// controls.
let row_rect = ui.max_rect();
let label_left = row_rect.min.x + theme.header_padding_x;
let label_right = controls_left_x
.map(|x| x - theme.header_padding_x)
.unwrap_or(row_rect.max.x);
let label_rect = egui::Rect::from_min_max(
egui::pos2(label_left, row_rect.min.y),
egui::pos2(label_right.max(label_left), row_rect.max.y),
);
let label_response = ui
.scope_builder(egui::UiBuilder::new().max_rect(label_rect), |ui| {
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.add(
egui::Label::new(
egui::RichText::new(&label_text)
.color(theme.cell_color)
.strong(),
)
.truncate()
.sense(egui::Sense::hover()),
)
})
.inner
})
.inner;
label_response.widget_info(|| {
WidgetInfo::labeled(WidgetType::Label, ui.is_enabled(), &label_text)
});
HeaderRowLayout {
label_id: label_response.id,
controls_left_x: controls_left_x.unwrap_or(label_response.rect.max.x),
}
})
.inner
}
/// Render the per-row selection checkbox shown in the synthetic
/// `selectionRowHeaderCol`. Toggles route through the shared event
/// helper so they emit single vs. batch events consistently with
/// the rest of the selection chrome. Rows with
/// `enable_selection: false` render a disabled checkbox.
fn draw_row_selection_checkbox(
&mut self,
ui: &mut Ui,
options: &GridOptions,
row_item: &RowItem,
theme: &GridTheme,
) {
let rect = ui.max_rect();
let is_selected = self
.selected_row_ids
.iter()
.any(|id| id == &row_item.row.id);
let bg = if is_selected {
theme.row_selected_background
} else {
theme.surface
};
ui.painter().rect_filled(rect, 0.0, bg);
if is_selected {
// Match the data-row leading-edge indicator stripe so the
// selection chrome reads consistently across the synthetic
// checkbox column and the data columns.
let stripe = egui::Rect::from_min_size(
egui::pos2(rect.min.x, rect.min.y),
Vec2::new(3.0, rect.height()),
);
ui.painter()
.rect_filled(stripe, 0.0, theme.row_selected_indicator);
}
let bottom = egui::Rect::from_min_size(
egui::pos2(rect.min.x, rect.max.y - 1.0),
Vec2::new(rect.width(), 1.0),
);
ui.painter().rect_filled(bottom, 0.0, theme.border_color);
let mut state = is_selected;
let toggled = if let Some(renderer) = self.selection_checkbox_renderer.as_mut() {
let context = GridSelectionCheckboxContext {
row: Some(&row_item.row),
options,
theme,
enabled: row_item.row.enable_selection,
is_header: false,
};
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
ui.with_layout(
egui::Layout::centered_and_justified(egui::Direction::TopDown),
|ui| renderer(ui, &context, &mut state),
)
.inner
})
.inner
} else {
// Centre the checkbox in both axes against the cell's full
// rect — `horizontal_centered` only centred vertically, which
// left the checkbox left-aligned even after the column was
// narrowed to its content width.
let response = ui
.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
ui.with_layout(
egui::Layout::centered_and_justified(egui::Direction::TopDown),
|ui| {
ui.add_enabled(
row_item.row.enable_selection,
egui::Checkbox::new(&mut state, ""),
)
},
)
.inner
})
.inner;
response.clicked()
};
if toggled && row_item.row.enable_selection {
let row_id = row_item.row.id.clone();
// Checkbox is conceptually an additive toggle — a click on
// one row's checkbox should never wipe out the rest of the
// selection. The shared handler treats `toggle: true` that
// way regardless of the host modifier state.
self.handle_row_click(
options,
&row_id,
RowClickModifiers {
shift: false,
toggle: true,
},
);
}
}
/// Render the select-all checkbox shown in the header of the
/// synthetic `selectionRowHeaderCol`. Toggling selects every
/// visible (post-filter / post-paginate) selectable row, or clears
/// the selection if every visible row is already selected. Honors
/// `enable_select_all`; when disabled, the checkbox is rendered
/// non-interactive at its current state.
fn draw_select_all_header(
&mut self,
ui: &mut Ui,
options: &GridOptions,
theme: &GridTheme,
) -> HeaderRowLayout {
let selectable: Vec<&str> = self
.cached_result
.visible_rows
.iter()
.filter(|row| row.enable_selection)
.map(|row| row.id.as_str())
.collect();
let all_selected = !selectable.is_empty()
&& selectable
.iter()
.all(|id| self.selected_row_ids.iter().any(|s| s == *id));
let select_all_enabled = options.enable_select_all.unwrap_or(true);
let batch_events = options.enable_selection_batch_event.unwrap_or(true);
// Centre the select-all checkbox horizontally against the
// header cell — matches the per-row checkbox cell so the
// chrome reads as one column.
let header_rect = ui.max_rect();
let mut state = all_selected;
let (toggled, response_id) = if let Some(renderer) =
self.selection_checkbox_renderer.as_mut()
{
let context = GridSelectionCheckboxContext {
row: None,
options,
theme,
enabled: select_all_enabled,
is_header: true,
};
let response_id = ui.id().with("selection_row_header_select_all");
let toggled = ui
.scope_builder(egui::UiBuilder::new().max_rect(header_rect), |ui| {
ui.with_layout(
egui::Layout::centered_and_justified(egui::Direction::TopDown),
|ui| renderer(ui, &context, &mut state),
)
.inner
})
.inner;
(toggled, response_id)
} else {
let response = ui
.scope_builder(egui::UiBuilder::new().max_rect(header_rect), |ui| {
ui.with_layout(
egui::Layout::centered_and_justified(egui::Direction::TopDown),
|ui| {
ui.add_enabled(select_all_enabled, egui::Checkbox::new(&mut state, ""))
},
)
.inner
})
.inner;
(response.clicked(), response.id)
};
if toggled && select_all_enabled {
let initial = self.selected_row_ids.clone();
self.selected_row_ids = if all_selected {
Vec::new()
} else {
selectable.iter().map(|id| (*id).to_string()).collect()
};
self.emit_selection_event(&initial, batch_events);
}
HeaderRowLayout {
label_id: response_id,
controls_left_x: header_rect.max.x,
}
}
fn draw_filter_input(
&mut self,
ui: &mut Ui,
options: &GridOptions,
column: &GridColumnDef,
column_ext: Option<&mut EguiColumnExt>,
theme: &GridTheme,
labelled_by: egui::Id,
) {
if !options.enable_filtering || !column.filterable || !column.enable_filtering {
return;
}
let mut filter_text = self
.active_filters
.get(&column.name)
.cloned()
.unwrap_or_default();
let initial = filter_text.clone();
let custom_changed = if let Some(ext) = column_ext
&& let Some(renderer) = ext.filter_renderer.as_mut()
{
let context = GridFilterContext {
column,
labels: &options.labels,
theme,
};
let mut changed = false;
ui.horizontal(|ui| {
ui.add_space(theme.header_padding_x);
if renderer(ui, &context, &mut filter_text) {
changed = true;
}
});
Some(changed)
} else {
None
};
if custom_changed.is_none() {
ui.horizontal(|ui| {
ui.add_space(theme.header_padding_x);
let trailing = theme.header_padding_x;
let clear_size = if filter_text.is_empty() {
0.0
} else {
// Reserve space for the inline ✕ clear button.
18.0
};
let available = ui.available_width() - trailing - clear_size;
let text_edit = egui::TextEdit::singleline(&mut filter_text)
.hint_text(grid_filter_placeholder(true, &options.labels))
.desired_width(available.max(40.0))
.text_color(theme.cell_color)
.show(ui);
let response =
<Response as Clone>::clone(&text_edit.response).labelled_by(labelled_by);
response.widget_info(|| {
WidgetInfo::labeled(
WidgetType::TextEdit,
ui.is_enabled(),
&options.labels.filter_column,
)
});
// Inline ✕ clear button — visible only when the
// filter has a non-empty term. Mirrors the TS chrome.
if !filter_text.is_empty() {
let clear = ui.add(
egui::Button::new(egui::RichText::new("✕").color(theme.muted_color))
.frame(false),
);
if clear.clicked() {
filter_text.clear();
}
}
});
}
let changed = match custom_changed {
Some(c) => c,
None => filter_text != initial,
};
if changed {
if filter_text.is_empty() {
self.active_filters.remove(&column.name);
} else {
self.active_filters
.insert(column.name.clone(), filter_text.clone());
}
self.current_page = 1;
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::FilterChanged {
column: column.name.clone(),
term: filter_text,
},
});
}
}
#[allow(clippy::too_many_arguments)]
fn draw_display_item(
&mut self,
ui: &mut Ui,
options: &mut GridOptions,
columns: &[GridColumnDef],
column_ext: &mut [EguiColumnExt],
item: &DisplayItem,
col_index: usize,
row_index: usize,
theme: &GridTheme,
) {
match item {
DisplayItem::Group(group) => {
// When a custom group renderer is registered, paint
// the entire row through it (col_index == 0 only —
// remaining cells are intentionally blank so the
// layout stays intact). Otherwise fall through to the
// default renderer which paints across columns.
let custom_action = if col_index == 0 {
if let Some(renderer) = self.group_row_renderer.as_mut() {
let collapsed = self
.collapsed_groups
.get(&group.id)
.copied()
.unwrap_or(false);
let context = GridGroupRowContext {
group,
options,
columns,
theme,
collapsed,
};
Some((renderer(ui, &context), collapsed))
} else {
None
}
} else if self.group_row_renderer.is_some() {
// Custom renderer occupies col 0 only — leave
// remaining columns blank.
Some((GridGroupRowAction::None, false))
} else {
None
};
match custom_action {
Some((GridGroupRowAction::Toggle, collapsed)) => {
let next = !collapsed;
self.collapsed_groups.insert(group.id.clone(), next);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::GroupToggled {
group_id: group.id.clone(),
collapsed: next,
},
});
}
Some(_) => {}
None => self.draw_group_row(ui, options, columns, theme, group, col_index),
}
}
DisplayItem::Row(row_item) => {
self.draw_data_row(
ui, options, columns, column_ext, row_item, col_index, row_index, theme,
);
}
DisplayItem::Expandable(expandable) => {
let rect = ui.max_rect();
ui.painter().rect_filled(rect, 0.0, theme.expandable_bg());
let bottom = egui::Rect::from_min_size(
egui::pos2(rect.min.x, rect.max.y - 1.0),
Vec2::new(rect.width(), 1.0),
);
ui.painter().rect_filled(bottom, 0.0, theme.border_color);
if col_index == 0 {
ui.add_space(theme.cell_padding_x);
if let Some(renderer) = self.expandable_row_renderer.as_mut() {
let context = GridExpandableRowContext {
row: &expandable.row,
options,
columns,
theme,
};
renderer(ui, &context);
} else {
ui.vertical(|ui| {
ui.label(
egui::RichText::new("Detail View")
.strong()
.size(13.0)
.color(theme.accent),
);
for col in columns {
let value = format_grid_cell_display_value(&expandable.row, col);
let label = col.display_name.as_deref().unwrap_or(&col.name);
ui.label(
egui::RichText::new(format!("{}: {}", label, value))
.color(theme.cell_color),
);
}
});
}
}
}
}
}
/// Paint the empty-state body — either the consumer's renderer or
/// a default heading + description from `options.labels`. Called
/// when the pipeline produces no display items.
fn draw_empty_state_row(&mut self, ui: &mut Ui, options: &GridOptions, theme: &GridTheme) {
if let Some(renderer) = self.empty_state_renderer.as_mut() {
let context = GridEmptyStateContext { options, theme };
renderer(ui, &context);
return;
}
ui.add_space(theme.cell_padding_y);
ui.vertical_centered(|ui| {
ui.label(
egui::RichText::new(&options.labels.empty_heading)
.strong()
.color(theme.cell_color),
);
ui.label(
egui::RichText::new(&options.labels.empty_description).color(theme.muted_color),
);
});
}
fn draw_group_row(
&mut self,
ui: &mut Ui,
options: &GridOptions,
_columns: &[GridColumnDef],
theme: &GridTheme,
group: &ui_grid_core::models::GroupItem,
col_index: usize,
) {
let rect = ui.max_rect();
ui.painter().rect_filled(rect, 0.0, theme.group_background);
let bottom = egui::Rect::from_min_size(
egui::pos2(rect.min.x, rect.max.y - 1.0),
Vec2::new(rect.width(), 1.0),
);
ui.painter().rect_filled(bottom, 0.0, theme.border_color);
if col_index == 0 {
let indent = group.depth as f32 * theme.group_indent_per_depth + theme.cell_padding_x;
ui.add_space(indent);
let expand_icon = grid_group_disclosure_icon(group.collapsed, &options.icons);
let tri_response = icon_button(ui, &expand_icon, theme, theme.cell_color, false);
tri_response.widget_info(|| {
WidgetInfo::labeled(
WidgetType::Button,
ui.is_enabled(),
grid_group_disclosure_label(group.collapsed, &options.labels),
)
});
let label = format!("{}: {} ({})", group.field, group.label, group.count);
let rich = egui::RichText::new(&label).color(theme.cell_color).strong();
let text_response = ui.add(egui::Label::new(rich).sense(egui::Sense::click()));
let response = tri_response | text_response;
if response.clicked() {
let collapsed = !group.collapsed;
self.collapsed_groups.insert(group.id.clone(), collapsed);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::GroupToggled {
group_id: group.id.clone(),
collapsed,
},
});
}
}
}
#[allow(clippy::too_many_arguments)]
fn draw_data_row(
&mut self,
ui: &mut Ui,
options: &mut GridOptions,
columns: &[GridColumnDef],
column_ext: &mut [EguiColumnExt],
row_item: &RowItem,
col_index: usize,
row_index: usize,
theme: &GridTheme,
) {
if col_index >= columns.len() {
return;
}
let column = &columns[col_index];
// Synthetic checkbox column — render the per-row checkbox and
// bail before the regular cell-content path. Editing / focus
// chrome is suppressed here; selection toggles flow through the
// shared event helper so the batch / single distinction is
// preserved.
if column.name == SELECTION_ROW_HEADER_COL_NAME {
self.draw_row_selection_checkbox(ui, options, row_item, theme);
return;
}
let rect = ui.max_rect();
let is_selected = self.selected_row_ids.contains(&row_item.row.id);
let pin_direction = get_column_pin_direction(&self.pinned_columns, column);
let bg = if is_selected {
theme.row_selected_background
} else if pin_direction != PinDirection::None {
theme.pinned_row_background
} else if row_index.is_multiple_of(2) {
theme.row_even
} else {
theme.row_odd
};
ui.painter().rect_filled(rect, 0.0, bg);
// Selected-row leading-edge indicator strip — paints a 3px
// accent column on the leading edge so the selected state is
// visible regardless of how subtle the row background tint is.
// Honours the theme-supplied colour so themes can disable the
// stripe by setting it to transparent.
if is_selected {
let stripe = egui::Rect::from_min_size(
egui::pos2(rect.min.x, rect.min.y),
Vec2::new(3.0, rect.height()),
);
ui.painter()
.rect_filled(stripe, 0.0, theme.row_selected_indicator);
}
// Row-edit lifecycle tint. The flags are mutually-exclusive in
// practice (row state machine: clean → dirty → saving → clean
// or → error), but priority is error > saving > dirty so a
// failed save wins the visual. Painted on top of the base row
// bg so selection / pin tints stay visible underneath.
let row_edit_tint = if row_item.row.is_error {
Some(theme.row_error_background)
} else if row_item.row.is_saving {
Some(theme.row_saving_background)
} else if row_item.row.is_dirty {
Some(theme.row_dirty_background)
} else {
None
};
if let Some(tint) = row_edit_tint {
ui.painter().rect_filled(rect, 0.0, tint);
}
let bottom = egui::Rect::from_min_size(
egui::pos2(rect.min.x, rect.max.y - 1.0),
Vec2::new(rect.width(), 1.0),
);
ui.painter().rect_filled(bottom, 0.0, theme.border_color);
// Hover highlight (paint before content so content draws on top)
let pointer_hovering =
ui.input(|i| i.pointer.hover_pos().is_some_and(|pos| rect.contains(pos)));
if !is_selected && pointer_hovering {
let hover_bg = if pin_direction == PinDirection::None {
theme.row_hover
} else {
theme.control_hover_background
};
ui.painter().rect_filled(rect, 0.0, hover_bg);
}
if pin_direction != PinDirection::None {
let x = if pin_direction == PinDirection::Left {
rect.min.x
} else {
rect.max.x - 2.0
};
let pin_indicator =
egui::Rect::from_min_size(egui::pos2(x, rect.min.y), Vec2::new(2.0, rect.height()));
ui.painter()
.rect_filled(pin_indicator, 0.0, theme.pinned_indicator);
}
let is_focused = self
.focused_cell
.as_ref()
.is_some_and(|f| f.row_id == row_item.row.id && f.column_name == column.name);
if is_focused {
ui.painter().rect_stroke(
rect.shrink(1.0),
0.0,
egui::Stroke::new(2.0, theme.accent),
egui::StrokeKind::Inside,
);
}
// Validation chrome — red tint + border around invalid cells.
// The `$$invalid<col>` flag is set on the row entity by the
// validators; reading it here keeps the chrome a presentation
// concern with no extra state on the widget.
let cell_invalid = is_grid_cell_invalid(&row_item.row.entity, column);
if cell_invalid {
ui.painter()
.rect_filled(rect, 0.0, theme.cell_invalid_background);
ui.painter().rect_stroke(
rect.shrink(1.0),
0.0,
egui::Stroke::new(1.5, theme.cell_invalid_border),
egui::StrokeKind::Inside,
);
}
// Render cell content
ui.add_space(theme.cell_padding_x);
// Render leading controls (tree indent + expand chevron) on
// the primary data column. When the synthetic selection-row-
// header column is prepended at index 0 the primary column is
// index 1; otherwise it's 0. Mirrors `is_grid_primary_column`
// in core/viewmodel.rs.
let primary_col_index = primary_data_column_index(columns);
let expand_icon_rect = if col_index == primary_col_index {
self.draw_row_leading_controls(ui, options, row_item, theme)
} else {
None
};
let is_editing = self.edit_session.as_ref().is_some_and(|s| {
s.editing_cell.row_id == row_item.row.id && s.editing_cell.column_name == column.name
});
if is_editing {
self.draw_cell_editor(ui, column, column_ext, theme);
} else {
self.draw_formatted_cell(ui, column, column_ext, row_item, row_index, theme);
}
// Skip the click overlay when this cell is being edited so editor
// widgets (date picker button, etc.) can receive clicks directly.
if !is_editing {
let response = ui.interact(
rect,
ui.id().with(("row_cell", row_index, col_index)),
// Drag-sense enables drag-paint multi-row selection.
egui::Sense::click_and_drag(),
);
// Validation tooltip — show the joined error messages on
// hover when the cell is invalid. Mirrors the TS contract
// wired into vanilla / Angular / React headers.
if cell_invalid {
let messages = get_grid_cell_error_messages(
&row_item.row.entity,
column,
&self.validator_registry,
);
if !messages.is_empty() {
let tooltip = messages.join("\n");
response.clone().on_hover_text(&tooltip);
}
}
// Drag-paint multi-row selection. On drag start the cell
// under the press becomes the anchor. While a press is held
// (any cell — egui only sets `dragged()` on the cell that
// received the press, so we re-check pointer hits on every
// cell every frame), the row whose rect contains the
// pointer becomes the drag-paint endpoint. The selection is
// recomputed as the anchor→endpoint range. Gated on the
// grid's row-selection flag so non-selecting consumers
// never see selection state mutate from a stray drag.
if options.enable_row_selection.unwrap_or(false) {
if response.drag_started() {
self.drag_paint_anchor = Some(row_item.row.id.clone());
let initial = self.selected_row_ids.clone();
let batch_events = options.enable_selection_batch_event.unwrap_or(true);
self.selected_row_ids = vec![row_item.row.id.clone()];
self.last_clicked_row_id = Some(row_item.row.id.clone());
self.emit_selection_event(&initial, batch_events);
} else if let Some(anchor) = self.drag_paint_anchor.clone() {
// Anchor exists ⇒ a drag-paint session is active.
// Treat this row as the endpoint when the pointer
// is over our rect AND the press is still held.
let pointer_held = ui.input(|i| i.pointer.any_down());
let pointer_over =
ui.input(|i| i.pointer.hover_pos().is_some_and(|p| rect.contains(p)));
if pointer_held && pointer_over {
let rows = &self.cached_result.visible_rows;
let start = rows.iter().position(|r| r.id == anchor);
let end = rows.iter().position(|r| r.id == row_item.row.id);
if let (Some(s), Some(e)) = (start, end) {
let (from, to) = if s <= e { (s, e) } else { (e, s) };
let next: Vec<String> = rows[from..=to]
.iter()
.filter(|r| r.enable_selection)
.map(|r| r.id.clone())
.collect();
if next != self.selected_row_ids {
let initial = self.selected_row_ids.clone();
let batch_events =
options.enable_selection_batch_event.unwrap_or(true);
self.selected_row_ids = next;
self.emit_selection_event(&initial, batch_events);
}
}
}
if !pointer_held {
// Pointer was released — clear the anchor so
// subsequent clicks don't re-trigger drag-paint.
self.drag_paint_anchor = None;
}
}
}
if expand_icon_rect.is_some() {
let toggle_label = if options.enable_tree_view {
grid_tree_toggle_label_for_row(
&self.expanded_tree_rows,
&row_item.row,
&options.labels,
)
} else {
grid_expand_toggle_label_for_row(&row_item.row, &options.labels)
};
response.widget_info(|| {
WidgetInfo::labeled(WidgetType::Button, ui.is_enabled(), toggle_label.clone())
});
}
if response.clicked() {
// Check if the click landed on the expand icon
let click_pos = ui.input(|i| i.pointer.interact_pos());
let hit_expand = expand_icon_rect
.is_some_and(|icon_rect| click_pos.is_some_and(|pos| icon_rect.contains(pos)));
if hit_expand {
// Toggle expansion and select the row, but don't focus the cell.
self.toggle_row_expansion(options, row_item);
if options.enable_row_selection.unwrap_or(false) {
let initial = self.selected_row_ids.clone();
let batch_events = options.enable_selection_batch_event.unwrap_or(true);
self.selected_row_ids = vec![row_item.row.id.clone()];
self.last_clicked_row_id = Some(row_item.row.id.clone());
self.emit_selection_event(&initial, batch_events);
}
} else {
// Normal cell click — commit any in-progress edit, select row, focus cell
if self.edit_session.is_some() {
self.commit_edit(options, columns);
}
let modifiers = ui.input(|i| RowClickModifiers {
shift: i.modifiers.shift,
// Treat Ctrl on non-Mac and Cmd on Mac as the
// "additive multi-select" modifier — egui exposes
// `mac_cmd` for Cmd/Super on Mac and `ctrl` for
// the platform-conventional ctrl-key elsewhere.
toggle: i.modifiers.command,
});
self.handle_row_click(options, &row_item.row.id, modifiers);
self.focused_cell = Some(GridCellPosition {
row_id: row_item.row.id.clone(),
column_name: column.name.clone(),
});
}
}
if response.double_clicked() {
// Don't enter edit mode if double-clicking the expand icon
let click_pos = ui.input(|i| i.pointer.interact_pos());
let hit_expand = expand_icon_rect
.is_some_and(|icon_rect| click_pos.is_some_and(|pos| icon_rect.contains(pos)));
if !hit_expand {
if self.edit_session.is_some() {
self.commit_edit(options, columns);
}
let is_editable = column.enable_cell_edit || options.enable_cell_edit;
if is_editable {
self.focused_cell = Some(GridCellPosition {
row_id: row_item.row.id.clone(),
column_name: column.name.clone(),
});
let current_value = get_cell_value(&row_item.row.entity, column);
let session = begin_grid_edit_session(
&row_item.row.id,
&column.name,
stringify_grid_editor_value(¤t_value),
);
self.edit_session = Some(session);
}
}
}
}
}
/// Draws leading controls (tree indent, expand icon) and returns the expand
/// icon rect if one was drawn. The icon is painted passively — click
/// handling is done by the cell overlay in `draw_data_row`.
fn draw_row_leading_controls(
&mut self,
ui: &mut Ui,
options: &GridOptions,
row_item: &RowItem,
theme: &GridTheme,
) -> Option<egui::Rect> {
if options.enable_tree_view && row_item.row.tree_level > 0 {
let indent = row_item.row.tree_level as f32 * theme.tree_indent_per_level;
ui.add_space(indent);
}
if options.enable_tree_view && row_item.row.has_children {
let expanded = self
.expanded_tree_rows
.get(&row_item.row.id)
.copied()
.unwrap_or(false);
let icon = grid_tree_toggle_icon(expanded, &options.icons);
return Some(expand_icon_passive(ui, &icon, theme.accent));
} else if options.enable_tree_view {
ui.add_space(24.0);
}
if options.enable_expandable && !options.enable_tree_view {
let expanded = self
.expanded_rows
.get(&row_item.row.id)
.copied()
.unwrap_or(false);
let icon = if expanded {
options.icons.collapse_detail.clone()
} else {
options.icons.expand_detail.clone()
};
return Some(expand_icon_passive(ui, &icon, theme.accent));
}
None
}
fn draw_formatted_cell(
&self,
ui: &mut Ui,
column: &GridColumnDef,
column_ext: &[EguiColumnExt],
row_item: &RowItem,
row_index: usize,
theme: &GridTheme,
) {
let value = get_cell_value(&row_item.row.entity, column);
if let Some(ext) = find_column_ext(column_ext, &column.name) {
if let Some(ref renderer) = ext.cell_renderer {
let ctx = GridCellContext {
value: &value,
row: &row_item.row,
column,
theme,
row_index,
};
renderer(ui, &ctx);
return;
}
if let Some(ref formatter) = ext.formatter {
let text = formatter(&value, &row_item.row);
ui.label(egui::RichText::new(&text).color(theme.cell_color));
return;
}
}
let text = format_grid_cell_display_value(&row_item.row, column);
ui.label(egui::RichText::new(&text).color(theme.cell_color));
}
fn draw_cell_editor(
&mut self,
ui: &mut Ui,
column: &GridColumnDef,
column_ext: &mut [EguiColumnExt],
theme: &GridTheme,
) {
if let Some(ref mut session) = self.edit_session {
// Consumer-provided editor wins over the built-in choice.
if let Some(ext) = find_column_ext_mut(column_ext, &column.name)
&& let Some(ref mut editor) = ext.cell_editor
{
editor(ui, &mut session.editing_value, theme);
return;
}
// Pick an editor based on the column's declared type. The
// serialized `editing_value` is always `String`, so each
// editor parses / formats around that representation.
match column.r#type {
ui_grid_core::models::GridColumnType::Boolean => {
let mut value = matches!(
session.editing_value.as_str(),
"true" | "True" | "TRUE" | "1"
);
if ui.checkbox(&mut value, "").changed() {
session.editing_value = value.to_string();
}
}
ui_grid_core::models::GridColumnType::Date => {
// Parse the current `YYYY-MM-DD` string into a jiff
// civil date (egui_extras 0.34's DatePickerButton
// works with `jiff::civil::Date`); fall back to
// today's date when parsing fails so the picker
// still opens with a sane initial value.
let mut date =
jiff::civil::Date::strptime("%Y-%m-%d", session.editing_value.trim())
.unwrap_or_else(|_| jiff::Zoned::now().date());
let picker = egui_extras::DatePickerButton::new(&mut date)
.id_salt("ui_grid_egui_cell_editor_date")
.show_icon(true);
let response = ui.add(picker);
if response.changed() {
session.editing_value = date.to_string();
}
}
ui_grid_core::models::GridColumnType::Number => {
// Numeric filter — strip characters that wouldn't
// parse as a JSON number while typing. Mirrors the
// TS contract where `editor_input_type` returns
// `'number'` for these columns.
let response = egui::TextEdit::singleline(&mut session.editing_value)
.desired_width(ui.available_width() - theme.cell_padding_x * 2.0)
.text_color(theme.cell_color)
.show(ui)
.response;
response.request_focus();
if response.changed() {
session.editing_value.retain(|c| {
c.is_ascii_digit() || matches!(c, '-' | '.' | 'e' | 'E' | '+')
});
}
}
_ => {
let response = egui::TextEdit::singleline(&mut session.editing_value)
.desired_width(ui.available_width() - theme.cell_padding_x * 2.0)
.text_color(theme.cell_color)
.show(ui)
.response;
response.request_focus();
}
}
}
}
fn toggle_row_expansion(&mut self, options: &GridOptions, row_item: &RowItem) {
if options.enable_tree_view && row_item.row.has_children {
let expanded = self
.expanded_tree_rows
.get(&row_item.row.id)
.copied()
.unwrap_or(false);
let next = !expanded;
self.expanded_tree_rows
.insert(row_item.row.id.clone(), next);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::TreeNodeToggled {
row_id: row_item.row.id.clone(),
expanded: next,
},
});
} else if options.enable_expandable && !options.enable_tree_view {
let expanded = self
.expanded_rows
.get(&row_item.row.id)
.copied()
.unwrap_or(false);
let next = !expanded;
self.expanded_rows.insert(row_item.row.id.clone(), next);
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::RowExpanded {
row_id: row_item.row.id.clone(),
expanded: next,
},
});
}
}
fn handle_row_click(
&mut self,
options: &GridOptions,
row_id: &str,
modifiers: RowClickModifiers,
) {
// Selection feature flags. Defaults match TS:
// enableRowSelection ? false (off unless opted in)
// modifierKeysToMultiSelect ? false (Shift / Cmd extend by default)
// noUnselect ? false (clicks can deselect)
// enableSelectionBatchEvent ? true (multi-row events emit batch)
if !options.enable_row_selection.unwrap_or(false) {
return;
}
let modifier_keys_to_multi_select = options.modifier_keys_to_multi_select.unwrap_or(false);
let no_unselect = options.no_unselect.unwrap_or(false);
let batch_events = options.enable_selection_batch_event.unwrap_or(true);
// Shift-range extend. When `modifier_keys_to_multi_select` is on
// the user must hold Shift to extend; that's already what the
// condition models, so the gate is consistent in both modes.
let initial = self.selected_row_ids.clone();
if modifiers.shift
&& let Some(ref last) = self.last_clicked_row_id
{
let rows = &self.cached_result.visible_rows;
let start = rows.iter().position(|r| r.id == *last);
let end = rows.iter().position(|r| r.id == row_id);
if let (Some(s), Some(e)) = (start, end) {
let (from, to) = if s <= e { (s, e) } else { (e, s) };
self.selected_row_ids = rows[from..=to].iter().map(|r| r.id.clone()).collect();
self.emit_selection_event(&initial, batch_events);
return;
}
}
// Cmd/Ctrl additive toggle: leave existing selection alone, just
// flip this row. When `modifier_keys_to_multi_select` is on, the
// user MUST hold the modifier to keep multi-row state — without
// it, additive toggles aren't allowed and the click collapses to
// single-select.
let already_selected = self.selected_row_ids.iter().any(|id| id == row_id);
if modifiers.toggle {
if already_selected {
if !no_unselect {
self.selected_row_ids.retain(|id| id != row_id);
}
} else {
self.selected_row_ids.push(row_id.to_string());
}
self.last_clicked_row_id = Some(row_id.to_string());
self.emit_selection_event(&initial, batch_events);
return;
}
// Plain click. With `modifier_keys_to_multi_select` set, every
// unmodified click collapses to single-select. Without it, the
// legacy behaviour persists: clicking a selected row toggles it
// off (unless `noUnselect`), clicking a different row replaces
// the selection with just that row.
if modifier_keys_to_multi_select {
self.selected_row_ids = vec![row_id.to_string()];
} else if already_selected {
if !no_unselect {
self.selected_row_ids.retain(|id| id != row_id);
}
} else {
self.selected_row_ids = vec![row_id.to_string()];
}
self.last_clicked_row_id = Some(row_id.to_string());
self.emit_selection_event(&initial, batch_events);
}
/// Push the selection-changed event, choosing between the single-row
/// and batch variants based on the feature flag and the size of the
/// delta vs. the previous selection. When the change involves more
/// than one row id (typical for shift-range / Ctrl+A) the batch
/// variant fires; single-row toggles stay on the legacy event.
fn emit_selection_event(&mut self, previous: &[String], batch_events: bool) {
let next = &self.selected_row_ids;
let same: bool =
previous.len() == next.len() && previous.iter().all(|id| next.iter().any(|n| n == id));
if same {
return;
}
let symmetric_delta = previous
.iter()
.filter(|id| !next.iter().any(|n| n == *id))
.count()
+ next
.iter()
.filter(|id| !previous.iter().any(|p| p == *id))
.count();
let kind = if batch_events && symmetric_delta > 1 {
EguiGridEventKind::SelectionChangedBatch {
selected_ids: next.clone(),
}
} else {
EguiGridEventKind::SelectionChanged {
selected_ids: next.clone(),
}
};
self.events.push(EguiGridEvent { kind });
}
fn draw_pagination(
&mut self,
ui: &mut Ui,
options: &GridOptions,
total_items: usize,
theme: &GridTheme,
) {
let rect = ui.max_rect();
ui.painter().rect_filled(rect, 0.0, theme.header_background);
let top = egui::Rect::from_min_size(rect.min, Vec2::new(rect.width(), 1.0));
ui.painter().rect_filled(top, 0.0, theme.border_color);
let total_pages = get_total_pages_value(options, total_items, self.page_size);
// Range label "M – N of total" mirrors the vanilla web component's
// pagination footer; uses inclusive 1-based indices.
let first_row =
get_first_row_index_value(options, self.current_page, total_items, self.page_size);
let last_row =
get_last_row_index_value(options, self.current_page, total_items, self.page_size);
let range_label = if total_items == 0 {
format!("0 {} 0", options.labels.pagination_of)
} else {
format!(
"{} \u{2013} {} {} {}",
first_row + 1,
last_row + 1,
options.labels.pagination_of,
total_items,
)
};
let page_label = format!(
"{} {} {} {}",
options.labels.pagination_page,
self.current_page,
options.labels.pagination_of,
total_pages,
);
ui.horizontal(|ui| {
ui.add_space(theme.cell_padding_x);
// Render a button whose text colour goes muted when the
// action is disabled, so prev/next visibly grey out at the
// edges. The disabled flag still no-ops the click.
let btn = |ui: &mut Ui, text: &str, label: &str, enabled: bool| -> egui::Response {
let color = if enabled {
theme.accent
} else {
theme.muted_color
};
let response = ui.add_enabled(
enabled,
egui::Label::new(egui::RichText::new(text).color(color))
.sense(egui::Sense::click()),
);
response.widget_info(|| WidgetInfo::labeled(WidgetType::Button, enabled, label));
response.on_hover_text(label)
};
let can_prev = self.current_page > 1;
let can_next = self.current_page < total_pages;
if btn(
ui,
"\u{00AB} First",
&options.labels.pagination_previous,
can_prev,
)
.clicked()
&& can_prev
{
self.current_page = 1;
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::PageChanged { page: 1 },
});
}
if btn(
ui,
"\u{2039} Prev",
&options.labels.pagination_previous,
can_prev,
)
.clicked()
&& can_prev
{
self.current_page -= 1;
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::PageChanged {
page: self.current_page,
},
});
}
let page_response = ui.label(egui::RichText::new(&page_label).color(theme.cell_color));
page_response.widget_info(|| {
WidgetInfo::labeled(WidgetType::Label, ui.is_enabled(), &page_label)
});
if btn(
ui,
"Next \u{203A}",
&options.labels.pagination_next,
can_next,
)
.clicked()
&& can_next
{
self.current_page += 1;
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::PageChanged {
page: self.current_page,
},
});
}
if btn(
ui,
"Last \u{00BB}",
&options.labels.pagination_next,
can_next,
)
.clicked()
&& can_next
{
self.current_page = total_pages;
self.pipeline_dirty = true;
self.events.push(EguiGridEvent {
kind: EguiGridEventKind::PageChanged {
page: self.current_page,
},
});
}
ui.separator();
let rows_label_response = ui.label(
egui::RichText::new(format!("{}:", options.labels.pagination_rows))
.color(theme.muted_color),
);
let prev_size = self.page_size;
// Read page-size choices from `options.pagination_page_sizes`
// (TS contract); fall back to the legacy default tier when
// the host hasn't supplied any.
let page_sizes: Vec<usize> = if options.pagination_page_sizes.is_empty() {
vec![5, 10, 25, 50, 100]
} else {
options.pagination_page_sizes.clone()
};
let page_size_response = egui::ComboBox::from_id_salt(ui.id().with("page_size"))
.selected_text(
egui::RichText::new(self.page_size.to_string()).color(theme.cell_color),
)
.show_ui(ui, |ui| {
for size in &page_sizes {
ui.selectable_value(&mut self.page_size, *size, size.to_string());
}
});
page_size_response
.response
.labelled_by(rows_label_response.id);
if self.page_size != prev_size {
self.current_page = 1;
self.pipeline_dirty = true;
}
ui.separator();
let range_response =
ui.label(egui::RichText::new(&range_label).color(theme.muted_color));
range_response.widget_info(|| {
WidgetInfo::labeled(WidgetType::Label, ui.is_enabled(), &range_label)
});
});
}
}