egui-table-kit 0.5.2

An extension for `egui` that brings batteries-included, filtering, highlighting, tree structures, and an action dispatch to your tables.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
use std::{
    collections::{BTreeMap, btree_map::Entry},
    ops::{Range, RangeInclusive},
};

use egui::{
    Align, Context, Id, IdMap, IdSalt, Layout, NumExt as _, Rangef, Rect, Response, Ui, UiBuilder,
    Vec2, Vec2b, vec2,
};

use super::{
    SplitScroll, SplitScrollDelegate,
    columns::{Column, ColumnFlags},
};

// TODO: fix the functionality of this
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub enum AutoSizeMode {
    /// Never auto-size the columns.
    #[default]
    Never,

    /// Always auto-size the columns
    Always,

    /// Auto-size the columns if the parents' width changes
    OnParentResize,
}

#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct TableState {
    // Maps columns ids to their widths.
    pub col_widths: IdMap<f32>,

    pub parent_width: Option<f32>,
}

impl TableState {
    #[must_use]
    pub fn load(ctx: &egui::Context, id: Id) -> Option<Self> {
        ctx.data_mut(|d| d.get_persisted(id))
    }

    pub fn store(self, ctx: &egui::Context, id: Id) {
        ctx.data_mut(|d| d.insert_persisted(id, self));
    }

    #[must_use]
    pub fn id(ui: &Ui, id_salt: IdSalt) -> Id {
        ui.make_persistent_id(id_salt)
    }

    pub fn reset(ctx: &egui::Context, id: Id) {
        ctx.data_mut(|d| {
            d.remove::<Self>(id);
        });
    }
}

/// Describes one of potentially many header rows.
///
/// Each header row has a fixed height.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct HeaderRow {
    pub height: f32,

    /// If empty, it is ignored.
    ///
    /// Contains non-overlapping ranges of column indices to group together.
    /// For instance: `vec![(0..3), (3..5), (5..6)]`.
    pub groups: Vec<Range<usize>>,
}

impl HeaderRow {
    #[must_use]
    pub const fn new(height: f32) -> Self {
        Self {
            height,
            groups: Vec::new(),
        }
    }
}

/// A table viewer.
///
/// Designed to be fast when there are millions of rows, but only hundreds of columns.
///
/// ## Sticky columns and rows
/// You can designate a certain number of column and rows as being "sticky".
/// These won't scroll with the rest of the table.
///
/// The sticky rows are always the first ones at the top, and are usually used for the column headers.
/// The sticky columns are always the first ones on the left, useful for special columns like
/// table row number or similar.
/// A sticky column is sometimes called a "gutter".
///
/// ## Batteries not included
/// * You need to specify the `Table` size beforehand
/// * Does not add any margins to cells. Add it yourself with [`egui::Frame`].
/// * Does not wrap cells in scroll areas. Do that yourself.
/// * Doesn't paint any guide-lines for the rows. Paint them yourself.
pub struct Table {
    /// The columns of the table.
    columns: Vec<Column>,

    /// Salt added to the parent [`Ui::id`] to produce an [`Id`] that is unique
    /// within the parent [`Ui`].
    ///
    /// You need to set this to something unique if you have multiple tables in the same ui.
    id_salt: IdSalt,

    /// Which columns are sticky (non-scrolling)?
    num_sticky_cols: usize,

    /// The count and parameters of the sticky (non-scrolling) header rows.
    headers: Vec<HeaderRow>,

    /// Total number of rows (sticky + non-sticky).
    num_rows: u64,

    /// How to do auto-sizing of columns, if at all.
    auto_size_mode: AutoSizeMode,

    scroll_to_columns: Option<(RangeInclusive<usize>, Option<Align>)>,
    scroll_to_rows: Option<(RangeInclusive<u64>, Option<Align>)>,

    /// If true, the vertical scrollbar will stick to the bottom as the content grows.
    ///
    /// Useful for log views or terminal emulation.
    stick_to_bottom: bool,
    max_height: Option<f32>,
    max_rows: Option<u64>,
}

impl Default for Table {
    fn default() -> Self {
        Self {
            columns: vec![],
            id_salt: IdSalt::new("table"),
            num_sticky_cols: 0,
            headers: vec![HeaderRow::new(16.0)],
            num_rows: 0,
            auto_size_mode: AutoSizeMode::default(),
            scroll_to_columns: None,
            scroll_to_rows: None,
            stick_to_bottom: false,
            max_height: None,
            max_rows: None,
        }
    }
}

#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct CellInfo {
    pub col_nr: usize,

    pub row_nr: u64,

    /// The unique [`Id`] of this table.
    pub table_id: Id,

    /// Is the row hovered?
    pub row_hovered: bool,
}

#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct HeaderCellInfo {
    pub group_index: usize,

    pub col_range: Range<usize>,

    /// Header row
    pub row_nr: usize,

    /// The unique [`Id`] of this table.
    pub table_id: Id,
}

/// Data given to the delegate containing information about what is about to be rendered.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[non_exhaustive]
pub struct PrefetchInfo {
    /// The sticky columns are always visible.
    pub num_sticky_columns: usize,

    /// This range of columns are currently visible, in addition to the sticky ones.
    pub visible_columns: Range<usize>,

    /// These rows are currently visible.
    pub visible_rows: Range<u64>,

    /// The unique [`Id`] of this table.
    pub table_id: Id,
}

/// The interface that the user needs to implement to display a table.
///
/// The [`Table`] calls functions on the delegate to render the table.
pub trait TableDelegate {
    /// Called before any call to [`Self::cell_ui`] to communicate the range of visible columns and rows.
    ///
    /// You can use this to only load the data required to be viewed.
    fn prepare(&mut self, _info: &PrefetchInfo) {}

    /// The contents of a header cell in the table.
    ///
    /// The [`CellInfo::row_nr`] is which header row (usually 0).
    fn header_cell_ui(&mut self, ui: &mut Ui, cell: &HeaderCellInfo);

    /// The contents of a row.
    ///
    /// Individual cell [`Ui`]s will be children of the ui passed to this fn, so you can e.g. use
    /// [`Ui::style_mut`] to style the whole row.
    ///
    /// This might be called multiple times per row (e.g. for sticky and non-sticky columns).
    fn row_ui(&mut self, _ui: &mut Ui, _row_nr: u64) {}

    /// The contents of a cell in the table.
    ///
    /// The [`CellInfo::row_nr`] is ignoring header rows.
    fn cell_ui(&mut self, ui: &mut Ui, cell: &CellInfo);

    /// Compute the offset for the top of the given row.
    ///
    /// Implement this for arbitrary row heights. The default implementation uses
    /// [`Self::default_row_height`].
    ///
    /// Note: must always return 0.0 for `row_nr = 0`.
    #[allow(clippy::cast_precision_loss)]
    fn row_top_offset(&self, _ctx: &Context, _table_id: Id, row_nr: u64) -> f32 {
        row_nr as f32 * self.default_row_height()
    }

    /// Default row height.
    ///
    /// This is used by the default implementation of [`Self::row_top_offset`].
    fn default_row_height(&self) -> f32 {
        20.0
    }

    fn uniform_row_height(&self) -> Option<f32> {
        Some(self.default_row_height())
    }
}

impl Table {
    /// Create a new table, with no columns and no headers, and zero rows.
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Salt added to the parent [`Ui::id`] to produce an [`Id`] that is unique
    /// within the parent [`Ui`].
    ///
    /// You need to set this to something unique if you have multiple tables in the same ui.
    #[must_use]
    #[inline]
    pub fn id_salt(mut self, id_salt: impl egui::AsIdSalt) -> Self {
        self.id_salt = IdSalt::new(id_salt);
        self
    }

    #[must_use]
    #[inline]
    pub const fn max_rows(mut self, max_rows: u64) -> Self {
        self.max_rows = Some(max_rows);
        self
    }

    /// Total number of rows (sticky + non-sticky).
    #[must_use]
    #[inline]
    pub const fn num_rows(mut self, num_rows: u64) -> Self {
        self.num_rows = num_rows;
        self
    }

    /// The columns of the table.
    #[must_use]
    #[inline]
    pub fn columns(mut self, columns: impl Into<Vec<Column>>) -> Self {
        self.columns = columns.into();
        self
    }

    /// How many columns are sticky (non-scrolling)?
    ///
    /// Default is 0.
    #[must_use]
    #[inline]
    pub const fn num_sticky_cols(mut self, num_sticky_cols: usize) -> Self {
        self.num_sticky_cols = num_sticky_cols;
        self
    }

    /// The count and parameters of the sticky (non-scrolling) header rows.
    #[must_use]
    #[inline]
    pub fn headers(mut self, headers: impl Into<Vec<HeaderRow>>) -> Self {
        self.headers = headers.into();
        self
    }

    /// How to do auto-sizing of columns, if at all.
    #[must_use]
    #[inline]
    pub const fn auto_size_mode(mut self, auto_size_mode: AutoSizeMode) -> Self {
        self.auto_size_mode = auto_size_mode;
        self
    }

    #[must_use]
    #[inline]
    pub const fn max_height(mut self, max_height: f32) -> Self {
        self.max_height = Some(max_height);
        self
    }

    /// The scroll handle will stick to the bottom position even while the content size
    /// changes dynamically.
    ///
    /// This can be useful to simulate terminal UIs or log/info scrollers.
    /// The scroll handle remains stuck until user manually changes position. Once "unstuck"
    /// it will remain focused on whatever content viewport the user left it on.
    #[must_use]
    #[inline]
    pub const fn stick_to_bottom(mut self, stick: bool) -> Self {
        self.stick_to_bottom = stick;
        self
    }

    /// Read the globally unique id, based on the current [`Self::id_salt`]
    /// and the parent id.
    #[must_use]
    #[inline]
    pub fn get_id(&self, ui: &Ui) -> Id {
        TableState::id(ui, self.id_salt)
    }

    /// Set a row to scroll to.
    ///
    /// `align` specifies if the row should be positioned in the top, center, or bottom of the view
    /// (using [`Align::TOP`], [`Align::Center`] or [`Align::BOTTOM`]).
    /// If `align` is `None`, the table will scroll just enough to bring the cursor into view.
    ///
    /// See also: [`Self::scroll_to_column`].
    #[must_use]
    #[inline]
    pub const fn scroll_to_row(self, row: u64, align: Option<Align>) -> Self {
        self.scroll_to_rows(row..=row, align)
    }

    /// Scroll to a range of rows.
    ///
    /// See [`Self::scroll_to_row`] for details.
    #[must_use]
    #[inline]
    pub const fn scroll_to_rows(mut self, rows: RangeInclusive<u64>, align: Option<Align>) -> Self {
        self.scroll_to_rows = Some((rows, align));
        self
    }

    /// Set a column to scroll to.
    ///
    /// `align` specifies if the column should be positioned in the left, center, or right of the view
    /// (using [`Align::LEFT`], [`Align::Center`] or [`Align::RIGHT`]).
    /// If `align` is `None`, the table will scroll just enough to bring the cursor into view.
    ///
    /// See also: [`Self::scroll_to_row`].
    #[must_use]
    #[inline]
    pub const fn scroll_to_column(self, column: usize, align: Option<Align>) -> Self {
        self.scroll_to_columns(column..=column, align)
    }

    /// Scroll to a range of columns.
    ///
    /// See [`Self::scroll_to_column`] for details.
    #[must_use]
    #[inline]
    pub const fn scroll_to_columns(
        mut self,
        columns: RangeInclusive<usize>,
        align: Option<Align>,
    ) -> Self {
        self.scroll_to_columns = Some((columns, align));
        self
    }

    /// The top y coordinate offset of a specific row nr.
    ///
    /// `get_row_top_offset(0)` should always return 0.0.
    #[expect(clippy::unused_self)] // for uniformity
    fn get_row_top_offset(
        &self,
        ctx: &Context,
        table_id: Id,
        table_delegate: &dyn TableDelegate,
        row_nr: u64,
    ) -> f32 {
        table_delegate.row_top_offset(ctx, table_id, row_nr)
    }

    /// Which row contains the given y offset (from the top)?
    fn get_row_nr_at_y_offset(
        &self,
        ctx: &Context,
        table_id: Id,
        table_delegate: &dyn TableDelegate,
        y_offset: f32,
    ) -> u64 {
        if let Some(height) = table_delegate.uniform_row_height()
            && height > 0.0
        {
            return ((y_offset / height) as u64).at_most(self.num_rows.saturating_sub(1));
        }

        // Fall back to binary search for variable heights
        partition_point(0..=self.num_rows, |row_nr| {
            y_offset <= self.get_row_top_offset(ctx, table_id, table_delegate, row_nr)
        })
        .saturating_sub(1)
    }

    pub fn show(mut self, ui: &mut Ui, table_delegate: &mut dyn TableDelegate) -> Response {
        self.num_sticky_cols = self.num_sticky_cols.at_most(self.columns.len());

        let id = TableState::id(ui, self.id_salt);
        let state = TableState::load(ui, id);
        let is_new = state.is_none();
        let mut state = state.unwrap_or_default();

        for (i, column) in self.columns.iter_mut().enumerate() {
            let column_id = column.id_for(i);
            let cached_width = state.col_widths.get(&column_id).copied();
            if let Some(existing_width) = cached_width {
                column.current = existing_width;
            } else {
                // If it is a new column and configured for auto-fitting, trigger sizing pass
                if column.is_auto_fit() {
                    column.flags.set(ColumnFlags::AUTO_SIZE_THIS_FRAME, true);
                }
            }
            column.current = column.range.clamp(column.current);

            // Only run the initial sizing pass on columns configured for auto-fitting
            if is_new && column.is_auto_fit() {
                column.flags.set(ColumnFlags::AUTO_SIZE_THIS_FRAME, true);
            }
        }

        // Only do full sizing pass if there are any columns that actually need to be auto-fitted
        let do_full_sizing_pass = is_new
            && self
                .columns
                .iter()
                .any(super::columns::Column::is_auto_size_this_frame);

        let parent_width = ui.available_width();
        let auto_size = match self.auto_size_mode {
            AutoSizeMode::Never => false,
            AutoSizeMode::Always => true,
            AutoSizeMode::OnParentResize => state.parent_width != Some(parent_width),
        };
        if auto_size {
            Column::auto_size(&mut self.columns, parent_width);
        }
        state.parent_width = Some(parent_width);

        let col_x = {
            let mut x = ui.cursor().min.x;
            let mut col_x = Vec::with_capacity(self.columns.len() + 1);
            col_x.push(x);
            for column in &self.columns {
                x += column.current;
                col_x.push(x);
            }
            col_x
        };

        let header_row_y = {
            let mut y = ui.cursor().min.y;
            let mut sticky_row_y = Vec::with_capacity(self.headers.len() + 1);
            sticky_row_y.push(y);
            for header in &self.headers {
                y += header.height;
                sticky_row_y.push(y);
            }
            sticky_row_y
        };

        let sticky_size = Vec2::new(
            self.columns[..self.num_sticky_cols]
                .iter()
                .map(|c| c.current)
                .sum(),
            self.headers.iter().map(|h| h.height).sum(),
        );

        let mut ui_builder = UiBuilder::new().layout(Layout::top_down(Align::Min));
        if do_full_sizing_pass {
            ui_builder = ui_builder.sizing_pass().invisible();
            ui.request_discard("Full egui_table sizing");
        }
        let response = ui
            .scope_builder(ui_builder, |ui| {
                // Don't wrap text in the table cells.
                ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);

                let num_columns = self.columns.len();

                for (col_nr, column) in self.columns.iter_mut().enumerate() {
                    if column.is_resizable() {
                        let column_resize_id = id.with(column.id_for(col_nr)).with("resize");
                        if let Some(response) = ui.read_response(column_resize_id)
                            && response.double_clicked()
                        {
                            column.flags.set(ColumnFlags::AUTO_SIZE_THIS_FRAME, true);
                        }
                    }
                    if column.is_auto_size_this_frame() {
                        ui.request_discard("egui_table column sizing");
                    }
                }

                SplitScroll {
                    scroll_enabled: Vec2b::new(true, true),
                    fixed_size: sticky_size,
                    scroll_outer_size: {
                        // Calculate the combined height of the headers and rows
                        let total_rows_height =
                            self.get_row_top_offset(ui, id, table_delegate, self.num_rows);
                        let total_content_height = sticky_size.y + total_rows_height;

                        // Ensure a minimum height of up to 10 rows (or self.num_rows if smaller)
                        // to prevent collapsing to header-only height during animations/sizing passes.
                        let min_rows = self.num_rows.min(10);
                        let min_rows_height =
                            self.get_row_top_offset(ui, id, table_delegate, min_rows);
                        let min_table_height = sticky_size.y + min_rows_height;

                        // Calculate the maximum allowed height based on row limits, max pixel limits, or the visible clip rect.
                        let max_height_limit = if let Some(max_r) = self.max_rows {
                            let max_rows_height =
                                self.get_row_top_offset(ui, id, table_delegate, max_r);
                            sticky_size.y + max_rows_height
                        } else {
                            self.max_height.unwrap_or_else(|| ui.clip_rect().height())
                        };

                        let available_height = ui
                            .available_height()
                            .at_most(max_height_limit)
                            .max(min_table_height);

                        let allocated_height = total_content_height.min(available_height);

                        Vec2::new(
                            (ui.available_width() - sticky_size.x).max(0.0),
                            (allocated_height - sticky_size.y).max(0.0),
                        )
                    },
                    scroll_content_size: Vec2::new(
                        self.columns[self.num_sticky_cols..]
                            .iter()
                            .map(|c| c.current)
                            .sum(),
                        self.get_row_top_offset(ui, id, table_delegate, self.num_rows),
                    ),
                    stick_to_bottom: self.stick_to_bottom,
                }
                .show(
                    ui,
                    &mut TableSplitScrollDelegate {
                        id,
                        table_delegate,
                        state: &mut state,
                        table: &mut self,
                        col_x,
                        header_row_y,
                        max_column_widths: vec![0.0; num_columns],
                        visible_column_lines: BTreeMap::default(),
                        do_full_sizing_pass,
                        has_prefetched: false,
                        egui_ctx: ui.clone(),
                        col_interaction: BTreeMap::default(),
                        dragging_col: None,
                    },
                );
            })
            .response;

        state.store(ui, id);
        response
    }
}

#[derive(Clone, Copy, Debug)]
struct ColumnResizer {
    scroll_offset: Vec2,

    top: f32,
}

fn update(map: &mut BTreeMap<usize, ColumnResizer>, key: usize, value: ColumnResizer) {
    match map.entry(key) {
        Entry::Vacant(entry) => {
            entry.insert(value);
        }
        Entry::Occupied(mut entry) => {
            entry.get_mut().top = entry.get_mut().top.min(value.top);
        }
    }
}

struct TableSplitScrollDelegate<'a> {
    id: Id,
    table_delegate: &'a mut dyn TableDelegate,
    table: &'a mut Table,
    state: &'a mut TableState,

    /// The x coordinate for the start of each column, plus the end of the last column.
    col_x: Vec<f32>,

    /// The y coordinate for the start of each header row, plus the end of the last header row.
    header_row_y: Vec<f32>,

    /// Actual width of the widest element in each column
    max_column_widths: Vec<f32>,

    /// Key is column number. The resizer is to the right of the column.
    visible_column_lines: BTreeMap<usize, ColumnResizer>,

    do_full_sizing_pass: bool,

    has_prefetched: bool,

    egui_ctx: Context,

    col_interaction: BTreeMap<usize, (bool, bool)>,
    dragging_col: Option<usize>,
}

impl TableSplitScrollDelegate<'_> {
    /// Helper wrapper around [`Table::get_row_top_offset`].
    fn get_row_top_offset(&self, row_nr: u64) -> f32 {
        self.table
            .get_row_top_offset(&self.egui_ctx, self.id, self.table_delegate, row_nr)
    }

    /// Helper wrapper around [`Table::get_row_nr_at_y_offset`].
    fn get_row_nr_at_y_offset(&self, y_offset: f32) -> u64 {
        self.table
            .get_row_nr_at_y_offset(&self.egui_ctx, self.id, self.table_delegate, y_offset)
    }

    fn header_ui(&mut self, ui: &mut Ui, scroll_offset: Vec2) {
        // Compute the visible column range for the current quadrant viewport
        let viewport = ui.clip_rect().translate(scroll_offset);

        #[allow(clippy::float_cmp)]
        let col_range = if self.table.columns.is_empty() || viewport.left() == viewport.right() {
            0..0
        } else if self.do_full_sizing_pass {
            // Render all columns during a sizing pass to measure layout constraints
            0..self.table.columns.len()
        } else {
            let col_idx_at = |x: f32| -> usize {
                self.col_x
                    .partition_point(|&col_x| col_x < x)
                    .saturating_sub(1)
                    .at_most(self.table.columns.len() - 1)
            };

            col_idx_at(viewport.min.x)..col_idx_at(viewport.max.x) + 1
        };

        let last_header_row_y = self.header_row_y.last().copied().unwrap_or(0.0);

        for (row_nr, header_row) in self.table.headers.iter().enumerate() {
            let groups = if header_row.groups.is_empty() {
                (0..self.table.columns.len()).map(|i| i..i + 1).collect()
            } else {
                header_row.groups.clone()
            };

            let y_range = Rangef::new(self.header_row_y[row_nr], self.header_row_y[row_nr + 1]);

            for (group_index, col_range_group) in groups.into_iter().enumerate() {
                let start = col_range_group.start;
                let end = col_range_group.end;

                // Skip processing and rendering if this group is outside the quadrant's visible column span
                if end <= col_range.start || start >= col_range.end {
                    continue;
                }

                let mut header_rect =
                    Rect::from_x_y_ranges(self.col_x[start]..=self.col_x[end], y_range)
                        .translate(-scroll_offset);

                if 0 < start
                    && self.table.columns[start - 1].is_resizable()
                    && ui.clip_rect().x_range().contains(header_rect.left())
                {
                    // The previous column is resizable, so make sure the resize line goes to above this heading:
                    update(
                        &mut self.visible_column_lines,
                        start - 1,
                        ColumnResizer {
                            scroll_offset,
                            top: header_rect.top(),
                        },
                    );
                }

                let clip_rect = header_rect;

                let last_column = &self.table.columns[end - 1];
                let auto_size_this_frame = last_column.is_auto_size_this_frame();

                if auto_size_this_frame {
                    header_rect.max.x = header_rect.min.x
                        + self.table.columns[start..end]
                            .iter()
                            .map(|column| column.range.min)
                            .sum::<f32>();
                }

                let mut ui_builder = UiBuilder::new()
                    .max_rect(header_rect)
                    .id_salt(("header", row_nr, group_index))
                    .layout(egui::Layout::left_to_right(egui::Align::Center));
                if auto_size_this_frame {
                    ui_builder = ui_builder.sizing_pass();
                }
                let mut cell_ui = ui.new_child(ui_builder);
                cell_ui.shrink_clip_rect(clip_rect);

                self.table_delegate.header_cell_ui(
                    &mut cell_ui,
                    &HeaderCellInfo {
                        group_index,
                        col_range: col_range_group,
                        row_nr,
                        table_id: self.id,
                    },
                );

                if start + 1 == end {
                    // normal single-column group
                    let col_nr = start;
                    let column = &self.table.columns[start];
                    let width = &mut self.max_column_widths[col_nr];
                    *width = width.max(cell_ui.min_size().x);

                    // Save column lines for later interaction:
                    if column.is_resizable()
                        && ui.clip_rect().x_range().contains(header_rect.right())
                    {
                        update(
                            &mut self.visible_column_lines,
                            col_nr,
                            ColumnResizer {
                                scroll_offset,
                                top: header_rect.top(),
                            },
                        );
                    }
                }
            }
        }

        // Repaint separator lines over the headers so they aren't covered by header backgrounds.
        for (col_nr, ColumnResizer { scroll_offset, top }) in &self.visible_column_lines {
            let col_nr = *col_nr;
            let Some(column) = self.table.columns.get(col_nr) else {
                continue;
            };
            if !column.is_resizable() {
                continue;
            }

            let column_id = column.id_for(col_nr);
            let new_width = self
                .state
                .col_widths
                .get(&column_id)
                .copied()
                .unwrap_or(column.current);
            let old_width = column.current;

            let x = self.col_x[col_nr + 1] - scroll_offset.x + (new_width - old_width);
            let yrange = Rangef::new(*top, last_header_row_y);

            let (hovered, dragged) = self
                .col_interaction
                .get(&col_nr)
                .copied()
                .unwrap_or((false, false));
            let stroke = if dragged {
                ui.style().visuals.widgets.active.bg_stroke
            } else if hovered {
                ui.style().visuals.widgets.hovered.bg_stroke
            } else {
                ui.visuals().widgets.noninteractive.bg_stroke
            };

            ui.painter().vline(x, yrange, stroke);
        }
    }

    fn region_ui(&mut self, ui: &mut Ui, scroll_offset: Vec2, do_prefetch: bool) {
        // Used to find the visible range of columns and rows:
        let viewport = ui.clip_rect().translate(scroll_offset);
        let last_header_row_y = self.header_row_y.last().copied().unwrap_or(0.0);

        #[allow(clippy::float_cmp)]
        let col_range = if self.table.columns.is_empty() || viewport.left() == viewport.right() {
            0..0
        } else if self.do_full_sizing_pass {
            // We do the UI for all columns during a sizing pass, so we can auto-size ALL columns
            0..self.table.columns.len()
        } else {
            // Only paint the visible columns:
            let col_idx_at = |x: f32| -> usize {
                self.col_x
                    .partition_point(|&col_x| col_x < x)
                    .saturating_sub(1)
                    .at_most(self.table.columns.len() - 1)
            };

            col_idx_at(viewport.min.x)..col_idx_at(viewport.max.x) + 1
        };

        #[allow(clippy::float_cmp)]
        let row_range = if self.table.num_rows == 0 || viewport.top() == viewport.bottom() {
            0..0
        } else {
            // Only paint the visible rows:
            let row_idx_at = |y: f32| -> u64 {
                let row_nr = self.get_row_nr_at_y_offset(y - last_header_row_y);
                row_nr.at_most(self.table.num_rows.saturating_sub(1))
            };

            let margin = if do_prefetch {
                1.0 // Handle possible rounding errors in the syncing of the scroll offsets
            } else {
                0.0
            };

            row_idx_at(viewport.min.y - margin)..row_idx_at(viewport.max.y + margin) + 1
        };

        if do_prefetch {
            self.table_delegate.prepare(&PrefetchInfo {
                num_sticky_columns: self.table.num_sticky_cols,
                visible_columns: col_range.clone(),
                visible_rows: row_range.clone(),
                table_id: self.id,
            });
            self.has_prefetched = true;
        } else {
            debug_assert!(
                self.has_prefetched,
                "SplitScroll delegate methods called in unexpected order"
            );
        }

        let pointer_pos = ui.ctx().pointer_latest_pos();
        let current_frame = ui.ctx().cumulative_frame_nr();
        let hovered_row_id = self.id.with("hovered_row");

        for row_nr in row_range {
            let y_range = Rangef::new(
                last_header_row_y + self.get_row_top_offset(row_nr),
                last_header_row_y + self.get_row_top_offset(row_nr + 1),
            );

            let row_x_range = self.col_x[0]..=self.col_x[self.col_x.len() - 1];
            let row_rect = Rect::from_x_y_ranges(row_x_range, y_range).translate(-scroll_offset);

            // Check if the cursor is hovering over the visible portion of this row
            if let Some(pos) = pointer_pos {
                let visible_row_rect = row_rect.intersect(ui.clip_rect());

                // Exclusive check on bottom and right edges to prevent multi-row highlights
                let contains_exclusive = visible_row_rect.min.x <= pos.x
                    && pos.x < visible_row_rect.max.x
                    && visible_row_rect.min.y <= pos.y
                    && pos.y < visible_row_rect.max.y;

                if contains_exclusive {
                    ui.ctx()
                        .data_mut(|d| d.insert_temp(hovered_row_id, (current_frame, row_nr)));
                }
            }

            // Determine if the current row was hovered on this frame or the previous one
            let row_hovered = if let Some((frame, hovered_row)) =
                ui.ctx().data(|d| d.get_temp::<(u64, u64)>(hovered_row_id))
            {
                hovered_row == row_nr
                    && (frame == current_frame || frame == current_frame.saturating_sub(1))
            } else {
                false
            };

            let mut row_ui = ui.new_child(
                UiBuilder::new()
                    .max_rect(row_rect)
                    .id_salt(("row", row_nr))
                    .layout(egui::Layout::left_to_right(egui::Align::Center)),
            );
            row_ui.set_min_size(row_rect.size());

            self.table_delegate.row_ui(&mut row_ui, row_nr);

            for col_nr in col_range.clone() {
                let column = &self.table.columns[col_nr];
                let mut cell_rect =
                    Rect::from_x_y_ranges(self.col_x[col_nr]..=self.col_x[col_nr + 1], y_range)
                        .translate(-scroll_offset);
                let clip_rect = cell_rect;
                let auto_size_this_frame = column.is_auto_size_this_frame();
                if auto_size_this_frame {
                    cell_rect.max.x = cell_rect.min.x + column.range.min;
                }

                let mut ui_builder = UiBuilder::new()
                    .max_rect(cell_rect)
                    .id_salt((row_nr, col_nr))
                    .layout(egui::Layout::left_to_right(egui::Align::Center));
                if auto_size_this_frame {
                    ui_builder = ui_builder.sizing_pass();
                }
                let mut cell_ui = row_ui.new_child(ui_builder);
                cell_ui.shrink_clip_rect(clip_rect);

                self.table_delegate.cell_ui(
                    &mut cell_ui,
                    &CellInfo {
                        col_nr,
                        row_nr,
                        table_id: self.id,
                        row_hovered,
                    },
                );

                let width = &mut self.max_column_widths[col_nr];
                *width = width.max(cell_ui.min_size().x);
            }
        }

        // Save column lines for later interaction:
        for col_nr in col_range {
            let column = &self.table.columns[col_nr];
            if column.is_resizable() {
                update(
                    &mut self.visible_column_lines,
                    col_nr,
                    ColumnResizer {
                        scroll_offset,
                        top: last_header_row_y,
                    },
                );
            }
        }
    }
}

impl SplitScrollDelegate for TableSplitScrollDelegate<'_> {
    // First to be called
    fn right_bottom_ui(&mut self, ui: &mut Ui, scroll_offset: Vec2) {
        if self.table.scroll_to_columns.is_some() || self.table.scroll_to_rows.is_some() {
            let mut target_rect = ui.clip_rect(); // no scrolling
            let mut target_align = None;

            if let Some((column_range, align)) = &self.table.scroll_to_columns {
                // Use the first scrollable column as the base, so that offsets start
                // at 0 for the first non-sticky column — mirroring how row_top_offset
                // starts at 0 for the first data row.
                let scrollable_col_x_base = self.col_x[self.table.num_sticky_cols];
                let x_from_column_nr = |col_nr: usize| -> f32 {
                    ui.min_rect().left() + (self.col_x[col_nr] - scrollable_col_x_base)
                };

                let sticky_width = scrollable_col_x_base - self.col_x[0];

                // Subtract sticky_width from the left of the target rect so that when
                // scroll_to_rect aligns the left of the target to the viewport left, the
                // actual column lands just right of the sticky columns (not behind them).
                target_rect.min.x = x_from_column_nr(*column_range.start()) - sticky_width;
                target_rect.max.x = x_from_column_nr(*column_range.end() + 1);
                target_align = target_align.or(*align);
            }

            if let Some((row_range, align)) = &self.table.scroll_to_rows {
                let y_from_row_nr =
                    |row_nr: u64| -> f32 { ui.min_rect().top() + self.get_row_top_offset(row_nr) };

                let last_header_row_y = self.header_row_y.last().copied().unwrap_or(0.0);
                let sticky_height = last_header_row_y - self.header_row_y[0];

                // Subtract sticky_height from the top of the target rect so that when
                // scroll_to_rect aligns the top of the target to the viewport top, the
                // actual row lands just below the sticky header (not behind it).
                target_rect.min.y = y_from_row_nr(*row_range.start()) - sticky_height;
                target_rect.max.y = y_from_row_nr(*row_range.end() + 1);
                target_align = target_align.or(*align);
            }

            ui.scroll_to_rect(target_rect, target_align);
        }

        self.region_ui(ui, scroll_offset, true);
    }

    fn left_top_ui(&mut self, ui: &mut Ui) {
        self.header_ui(ui, Vec2::ZERO);
    }

    fn right_top_ui(&mut self, ui: &mut Ui, scroll_offset: Vec2) {
        let horizontal_scroll_offset = vec2(scroll_offset.x, 0.0);
        self.header_ui(ui, horizontal_scroll_offset);
    }

    fn left_bottom_ui(&mut self, ui: &mut Ui, scroll_offset: Vec2) {
        let vertical_scroll_offset = vec2(0.0, scroll_offset.y);
        self.region_ui(ui, vertical_scroll_offset, false);
    }

    fn paint_overlays(&mut self, ui: &mut Ui) {
        let total_rows_height = self.get_row_top_offset(self.table.num_rows);
        let header_top = self.header_row_y[0];
        let header_bottom = self.header_row_y.last().copied().unwrap_or(0.0);
        let clip_bottom = ui.clip_rect().bottom();

        // 1. Pre-interaction pass: interact with all visible lines exactly once.
        // visible_column_lines contains right-body from this frame, and left-body/headers from the previous frame.
        for (
            col_nr,
            ColumnResizer {
                scroll_offset,
                top: _,
            },
        ) in &self.visible_column_lines
        {
            let col_nr = *col_nr;
            if self.col_interaction.contains_key(&col_nr) {
                continue; // Already interacted this frame
            }

            let Some(column) = self.table.columns.get(col_nr) else {
                continue;
            };
            if !column.is_resizable() {
                continue;
            }

            let column_id = column.id_for(col_nr);
            let range = column.range;
            let current = column.current;
            let column_width = self
                .state
                .col_widths
                .get(&column_id)
                .copied()
                .unwrap_or(current);

            let x = self.col_x[col_nr + 1] - scroll_offset.x + (column_width - current);
            let content_bottom = header_bottom + total_rows_height - scroll_offset.y;
            let line_bottom = clip_bottom.min(content_bottom);

            // Use the full line rect for interaction so dragging works seamlessly
            let line_rect = egui::Rect::from_x_y_ranges(x..=x, header_top..=line_bottom)
                .expand(ui.style().interaction.resize_grab_radius_side);

            let column_resize_id = self.id.with(column_id).with("resize");
            let resize_response =
                ui.interact(line_rect, column_resize_id, egui::Sense::click_and_drag());

            let hovered = resize_response.hovered();
            let dragged = resize_response.dragged();

            if dragged && let Some(pointer) = ui.pointer_latest_pos() {
                let new_width = column_width + pointer.x - x;
                let clamped_width = range.clamp(new_width);
                self.state.col_widths.insert(column_id, clamped_width);
                self.dragging_col = Some(col_nr);
            }

            self.col_interaction.insert(col_nr, (hovered, dragged));
        }

        // 2. Paint the body lines for this quadrant
        for (col_nr, ColumnResizer { scroll_offset, top }) in &self.visible_column_lines {
            let col_nr = *col_nr;
            let Some(column) = self.table.columns.get(col_nr) else {
                continue;
            };
            if !column.is_resizable() {
                continue;
            }

            let column_id = column.id_for(col_nr);
            let current = column.current;
            let column_width = self
                .state
                .col_widths
                .get(&column_id)
                .copied()
                .unwrap_or(current);
            let x = self.col_x[col_nr + 1] - scroll_offset.x + (column_width - current);

            let content_bottom = header_bottom + total_rows_height - scroll_offset.y;
            let line_bottom = clip_bottom.min(content_bottom);
            let yrange = Rangef::new(*top, line_bottom);

            let (hovered, dragged) = self
                .col_interaction
                .get(&col_nr)
                .copied()
                .unwrap_or((false, false));

            if hovered || dragged {
                ui.set_cursor_icon(egui::CursorIcon::ResizeColumn);
            }

            let stroke = if dragged {
                ui.style().visuals.widgets.active.bg_stroke
            } else if hovered {
                ui.style().visuals.widgets.hovered.bg_stroke
            } else {
                ui.visuals().widgets.noninteractive.bg_stroke
            };

            ui.painter().vline(x, yrange, stroke);
        }
    }

    fn update_col_widths(&mut self, ui: &mut Ui) {
        for col_nr in 0..self.table.columns.len() {
            // Skip auto-sizing if the user is actively dragging this column
            if self.dragging_col == Some(col_nr) {
                continue;
            }

            let column = self.table.columns.get(col_nr);
            let Some(column) = column else {
                continue;
            };
            if !column.is_resizable() {
                continue;
            }

            let column_id = column.id_for(col_nr);
            let used_width = column.range.clamp(self.max_column_widths[col_nr]);
            let old_width = self
                .state
                .col_widths
                .get(&column_id)
                .copied()
                .unwrap_or(column.current);

            // Copy flags to avoid borrow checker issues
            let auto_size_this_frame = column.is_auto_size_this_frame();
            let auto_fit = column.is_auto_fit();

            if auto_size_this_frame {
                self.table.columns[col_nr]
                    .flags
                    .set(ColumnFlags::AUTO_SIZE_THIS_FRAME, false);
            }

            let mut new_width = old_width;
            if auto_size_this_frame || (ui.is_sizing_pass() && auto_fit) {
                new_width = used_width;
            } else if auto_fit {
                new_width = old_width.max(used_width);
            }

            self.state.col_widths.insert(column_id, new_width);
        }

        // Clear the interaction state for the next frame
        self.col_interaction.clear();

        // Clear the drag state when the mouse button is released
        if !ui.input(|i| i.pointer.primary_down()) {
            self.dragging_col = None;
        }
    }
}

/// Returns the index of the first element that returns `true` using binary search.
fn partition_point(range: RangeInclusive<u64>, second_partition: impl Fn(u64) -> bool) -> u64 {
    let mut min = *range.start();
    let mut max = *range.end();

    debug_assert!(min < max, "Bad call to partition_point");

    while min < max {
        let mid = min + (max - min) / 2;

        if second_partition(mid) {
            max = mid;
        } else {
            min = mid + 1;
        }
    }

    min
}

#[cfg(test)]
mod tests {
    use super::partition_point;

    #[test]
    fn test_partition_point() {
        assert_eq!(partition_point(0..=17, |i| 8 <= i), 8);
        assert_eq!(partition_point(0..=17, |i| 9 <= i), 9);
        assert_eq!(partition_point(10..=17, |_| true), 10);
        assert_eq!(partition_point(10..=17, |_| false), 17);
    }
}