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
//! Table management actions and toolbar operations frameworks.

use std::{borrow::Cow, collections::HashSet};

use compact_str::{CompactString, ToCompactString as _};
use fluent_zero::t;
use roaring::RoaringBitmap;

use super::{error::TableError, filter::Filter, state::TableState};

/// Represents cell data, providing the primary text and an optional tooltip/hover override.
pub type TableCell<'a> = (Cow<'a, str>, Option<Cow<'a, str>>);

/// Owned counterpart of [`TableCell`] with a `'static` lifetime, used when a row's
/// data must outlive the provider borrow (e.g. when caching visible rows for rendering).
pub type TableCellOwned = (CompactString, Option<CompactString>);

/// A fully-owned row snapshot, cacheable across frames and usable anywhere a
/// [`Row`] is expected.
#[derive(Default, Clone, Debug)]
pub struct OwnedRow {
    /// Owned cell values, indexed by column offset.
    pub cells: Vec<TableCellOwned>,
}

impl Row for OwnedRow {
    fn cell(&self, col_index: usize) -> Option<TableCell<'_>> {
        self.cells.get(col_index).map(|(val, hover)| {
            (
                Cow::Borrowed(val.as_str()),
                hover.as_ref().map(|h| Cow::Borrowed(h.as_str())),
            )
        })
    }
    fn column_count(&self) -> usize {
        self.cells.len()
    }
}

/// A row element that resolves display text properties at specific column offsets.
pub trait Row {
    fn cell(&self, col_index: usize) -> Option<TableCell<'_>>;
    fn column_count(&self) -> usize;

    /// Snapshots every column of this row into an [`OwnedRow`], detaching it from
    /// the provider's borrow lifetime so it can be cached.
    fn to_owned_row(&self) -> OwnedRow {
        let mut cells = Vec::with_capacity(self.column_count());
        for i in 0..self.column_count() {
            if let Some((val, hover)) = self.cell(i) {
                cells.push((
                    val.to_compact_string(),
                    hover.map(|h| h.to_compact_string()),
                ));
            }
        }
        OwnedRow { cells }
    }
}

impl Row for [TableCell<'_>] {
    fn cell(&self, col_index: usize) -> Option<TableCell<'_>> {
        self.get(col_index).map(|(val, hover)| {
            (
                Cow::Borrowed(val.as_ref()),
                hover.as_ref().map(|h| Cow::Borrowed(h.as_ref())),
            )
        })
    }
    fn column_count(&self) -> usize {
        self.len()
    }
}

/// The callback signature used to process streamed row data.
/// - `'b` represents the lifetime of any local variables captured by the closure.
pub type RowCallback<'b> = dyn FnMut(&dyn Row) -> Result<(), TableError> + 'b;

/// Structural nesting parameters for tree hierarchy nodes.
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)]
pub struct RowHierarchy {
    pub indent_level: usize,
    pub has_children: bool,
    pub is_expanded: bool,
}

/// Zero-allocation lazy headers iterator.
pub struct HeaderIter<'a> {
    provider: &'a dyn TableProvider,
    index: usize,
    count: usize,
}

impl<'a> HeaderIter<'a> {
    pub fn new(provider: &'a dyn TableProvider) -> Self {
        Self {
            provider,
            index: 0,
            count: provider.column_count(),
        }
    }
}

impl<'a> Iterator for HeaderIter<'a> {
    type Item = Cow<'a, str>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.count {
            let res = self.provider.header(self.index);
            self.index += 1;
            res
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.count.saturating_sub(self.index);
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for HeaderIter<'_> {
    fn len(&self) -> usize {
        self.count.saturating_sub(self.index)
    }
}

/// A zero-allocation row wrapper that references cell data directly from a provider.
#[derive(Copy, Clone)]
pub struct BorrowedRow<'a> {
    pub provider: &'a dyn TableProvider,
    pub row_index: usize,
}

impl Row for BorrowedRow<'_> {
    fn cell(&self, col_index: usize) -> Option<TableCell<'_>> {
        self.provider
            .cell_at(self.row_index, col_index)
            .ok()
            .flatten()
    }

    fn column_count(&self) -> usize {
        self.provider.column_count()
    }
}

/// Trait implemented by datasets to back the interactive table system.
pub trait TableProvider {
    fn column_count(&self) -> usize;
    fn header(&self, index: usize) -> Option<Cow<'_, str>>;

    fn headers(&self) -> HeaderIter<'_>;

    fn row_count(&self) -> usize;

    /// Direct cellular random-access method.
    ///
    /// Override this in your custom collections to achieve O(1) performance
    /// and completely bypass heap-allocation pathways during rendering.
    fn cell_at(
        &self,
        row_index: usize,
        col_index: usize,
    ) -> Result<Option<TableCell<'_>>, TableError> {
        // Fallback default: Query row_at and copy values to satisfy lifetimes
        if let Some(owned_row) = self.row_at(row_index)?
            && let Some((val, hover)) = owned_row.cells.get(col_index)
        {
            return Ok(Some((
                Cow::Owned(val.to_string()),
                hover.as_ref().map(|h| Cow::Owned(h.to_string())),
            )));
        }
        Ok(None)
    }

    /// Processes a single row by index. Override this for O(1) random access.
    fn for_row_at(&self, index: usize, f: &mut RowCallback<'_>) -> Result<(), TableError> {
        let mut idx = 0;
        self.for_all_rows(&mut |row| {
            if idx == index {
                f(row)?;
            }
            idx += 1;
            Ok(())
        })
    }

    /// Randomly fetches a single row as an [`OwnedRow`]. This is the access path used
    /// by the rendering delegate for visible rows.
    ///
    /// The default implementation walks the dataset sequentially (O(N)) and should be
    /// overridden for true O(1) random access whenever the backing store supports it.
    fn row_at(&self, index: usize) -> Result<Option<OwnedRow>, TableError> {
        if index >= self.row_count() {
            return Ok(None);
        }
        let mut out: Option<OwnedRow> = None;
        let mut idx = 0usize;
        self.for_all_rows(&mut |row| {
            if idx == index {
                out = Some(row.to_owned_row());
            }
            idx += 1;
            Ok(())
        })?;
        Ok(out)
    }

    /// Sequentially processes each selected row with the provided callback.
    fn for_selected_rows(
        &self,
        state: &TableState,
        f: &mut RowCallback<'_>,
    ) -> Result<(), TableError>;

    /// Sequentially processes every row in the dataset.
    fn for_all_rows(&self, f: &mut RowCallback<'_>) -> Result<(), TableError>;

    /// Sorts the active row indices by the specified column.
    /// Uses a generic string-based fallback sorting implementation, but can be overridden.
    fn sort_active_rows(
        &self,
        active_rows: &mut Vec<usize>,
        col_index: usize,
        ascending: bool,
    ) -> Result<(), TableError> {
        if active_rows.len() <= 1 {
            return Ok(());
        }

        let active_set: RoaringBitmap = active_rows.iter().map(|&i| i as u32).collect();
        let mut sort_keys = Vec::with_capacity(active_rows.len());

        let mut idx = 0usize;
        self.for_all_rows(&mut |row| {
            if active_set.contains(idx as u32) {
                let val = row
                    .cell(col_index)
                    .map(|(v, _)| v.to_compact_string())
                    .unwrap_or_default();
                sort_keys.push((idx, val));
            }
            idx += 1;
            Ok(())
        })?;

        if ascending {
            sort_keys.sort_by(|a, b| a.1.cmp(&b.1));
        } else {
            sort_keys.sort_by(|a, b| b.1.cmp(&a.1));
        }

        *active_rows = sort_keys.into_iter().map(|(idx, _)| idx).collect();
        Ok(())
    }

    /// Filters all rows sequentially. Override this to implement custom parallel filtering (e.g. Rayon).
    fn filter_rows(
        &self,
        state: &TableState,
        filters: &[(usize, Filter)],
    ) -> Result<Vec<usize>, TableError> {
        if filters.is_empty() {
            return Ok((0..self.row_count()).collect());
        }

        let initial_capacity = self.row_count().min(2048);
        let mut passing_indices = Vec::with_capacity(initial_capacity);
        let mut row_idx = 0;

        self.for_all_rows(&mut |row| {
            let highlight = state.highlights.get_usize(row_idx);
            let mut matches = true;

            for &(col_idx, ref filter) in filters {
                if let Some(cell) = row.cell(col_idx) {
                    if !filter.matches(&cell.0, highlight) {
                        matches = false;
                        break;
                    }
                } else {
                    matches = false;
                    break;
                }
            }

            if matches {
                passing_indices.push(row_idx);
            }
            row_idx += 1;
            Ok(())
        })?;

        Ok(passing_indices)
    }

    /// Returns tree nesting parameters for a given row.
    /// Evaluates to `None` by default (representing traditional non-hierarchical flat tables).
    fn row_hierarchy(&self, _state: &TableState, _row_index: usize) -> Option<RowHierarchy> {
        None
    }

    /// Returns whether this provider represents a hierarchical tree table.
    /// Returns `false` by default.
    fn is_tree(&self) -> bool {
        false
    }

    /// Returns the active parent row index for a given row (if any).
    fn row_parent(&self, _row_index: usize) -> Option<usize> {
        None
    }

    /// Returns the child row indices nested immediately under the specified row.
    fn row_children(&self, _row_index: usize) -> Vec<usize> {
        Vec::new()
    }

    /// Returns whether an individual row matches the currently active column filters.
    fn row_matches(
        &self,
        _state: &TableState,
        _row_index: usize,
        _filters: &[(usize, Filter)],
        _highlight: Option<u8>,
    ) -> bool {
        true
    }
}

impl dyn TableProvider + '_ {
    /// Maps over each selected row with a closure and collects the results into a flat Vector.
    pub fn map_selected_rows<T, F>(
        &self,
        state: &TableState,
        mut f: F,
    ) -> Result<Vec<T>, TableError>
    where
        F: FnMut(&dyn Row) -> Result<T, TableError>,
    {
        let mut results = Vec::with_capacity(state.selected_rows.len() as usize);
        self.for_selected_rows(state, &mut |row| {
            results.push(f(row)?);
            Ok(())
        })?;
        Ok(results)
    }

    /// Maps only the first selected row (if any) and returns the result, stopping iteration immediately.
    pub fn map_first_selected_row<T, F>(
        &self,
        state: &TableState,
        f: F,
    ) -> Result<Option<T>, TableError>
    where
        F: FnOnce(&dyn Row) -> Result<T, TableError>,
    {
        let mut result = None;
        let mut f_opt = Some(f);

        self.for_selected_rows(state, &mut |row| {
            if let Some(f_once) = f_opt.take() {
                result = Some(f_once(row)?);
            }
            Ok(())
        })?;

        Ok(result)
    }
}

/// Helper trait to parse, extract, or fall back between primary text and hover text in rows.
pub trait RowSliceExt {
    /// Extracts the primary text at the specified column index.
    fn get_primary(&self, col_index: usize) -> Result<Cow<'_, str>, TableError>;

    /// Extracts the hover/alternate text at the specified column index.
    fn get_hover(&self, col_index: usize) -> Result<Cow<'_, str>, TableError>;

    /// Parses the primary text at the specified column index into type `T`.
    fn parse_primary<T>(&self, col_index: usize) -> Result<T, TableError>
    where
        T: std::str::FromStr,
        <T as std::str::FromStr>::Err: std::fmt::Display;

    /// Parses the hover text at the specified column index into type `T`.
    fn parse_hover<T>(&self, col_index: usize) -> Result<T, TableError>
    where
        T: std::str::FromStr,
        <T as std::str::FromStr>::Err: std::fmt::Display;
}

impl RowSliceExt for dyn Row + '_ {
    fn get_primary(&self, col_index: usize) -> Result<Cow<'_, str>, TableError> {
        self.cell(col_index)
            .map(|(val, _)| val)
            .ok_or(TableError::CorruptedState)
    }

    fn get_hover(&self, col_index: usize) -> Result<Cow<'_, str>, TableError> {
        self.cell(col_index)
            .and_then(|(_, hover)| hover)
            .ok_or(TableError::CorruptedState)
    }

    fn parse_primary<T>(&self, col_index: usize) -> Result<T, TableError>
    where
        T: std::str::FromStr,
        <T as std::str::FromStr>::Err: std::fmt::Display,
    {
        T::from_str(self.get_primary(col_index)?.as_ref())
            .map_err(|e| TableError::Generic(e.to_string()))
    }

    fn parse_hover<T>(&self, col_index: usize) -> Result<T, TableError>
    where
        T: std::str::FromStr,
        <T as std::str::FromStr>::Err: std::fmt::Display,
    {
        T::from_str(self.get_hover(col_index)?.as_ref())
            .map_err(|e| TableError::Generic(e.to_string()))
    }
}

/// Evaluation context supplied to active toolbar operations during executions.
pub struct OperationContext<'a, 'b> {
    pub ui: &'a mut egui::Ui,
    pub data: &'a mut TableState,
    pub provider: &'b dyn TableProvider,
}

/// Coordinates grouped sequences of toolbar actions, polling systems, and error dialogs.
#[derive(Debug, Default)]
pub struct TableOperations {
    pub groups: Vec<Vec<Box<dyn TableOperation>>>,
    pub pending_tracker: HashSet<(usize, usize), ahash::RandomState>,
    pub last_tick: u64,
}

impl TableOperations {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn with_group(mut self, group: Vec<Box<dyn TableOperation>>) -> Self {
        self.groups.push(group);
        self
    }

    #[must_use]
    pub fn with_operation(mut self, op: impl TableOperation + 'static) -> Self {
        if let Some(group) = self.groups.last_mut() {
            group.push(Box::new(op));
        } else {
            self.groups.push(vec![Box::new(op)]);
        }
        self
    }

    /// Evaluates state transitions exactly once per unique frame tick.
    /// Returns `true` if any completed operation requested a view refresh.
    pub fn update(&mut self, ctx: &egui::Context) -> bool {
        let mut refresh = false;
        let current_tick = ctx.cumulative_frame_nr();
        if self.last_tick != current_tick {
            self.last_tick = current_tick;

            for (g_idx, op_group) in self.groups.iter_mut().enumerate() {
                for (op_idx, op) in op_group.iter_mut().enumerate() {
                    let key = (g_idx, op_idx);
                    let pending = op.is_pending();
                    let was_pending = self.pending_tracker.contains(&key);

                    if was_pending && !pending {
                        self.pending_tracker.remove(&key);
                        let success = op.error().is_none();
                        op.on_completed(success);
                        if op.refresh_on_completion() {
                            refresh = true;
                        }
                    } else if !was_pending && pending {
                        self.pending_tracker.insert(key);
                    }
                }
            }
        }
        refresh
    }

    /// Renders standard table operation buttons with default look.
    pub fn gui(
        &mut self,
        ui: &mut egui::Ui,
        provider: &dyn TableProvider,
        data: &mut TableState,
        context_menu: bool,
    ) -> Result<bool, TableError> {
        self.gui_custom(
            ui,
            provider,
            data,
            context_menu,
            |ui, op, enabled, reason, context_menu| {
                ui.add_enabled_ui(enabled, |ui| {
                    let mut button = ui
                        .button(op.get_name(context_menu).as_ref())
                        .on_hover_text(op.name());
                    if !enabled {
                        button = button.on_disabled_hover_text(format!("{}\n{reason}", op.name()));
                    }
                    button
                })
                .inner
            },
        )
    }

    /// Renders table operations using a custom button builder callback.
    ///
    /// This handles all the state machine details (polling, execution, pending modes, group separation)
    /// but allows full control over the visual presentation of each button.
    pub fn gui_custom<F>(
        &mut self,
        ui: &mut egui::Ui,
        provider: &dyn TableProvider,
        data: &mut TableState,
        context_menu: bool,
        mut button_renderer: F,
    ) -> Result<bool, TableError>
    where
        F: FnMut(
            &mut egui::Ui,
            &mut Box<dyn TableOperation>,
            bool, // enabled
            &str, // localized disabled reason
            bool, // context_menu
        ) -> egui::Response,
    {
        let refresh = self.update(ui.ctx());
        let mut any_clicked = false;
        let num_groups = self.groups.len();

        // Render operations and process interactions
        for (g_idx, op_group) in self.groups.iter_mut().enumerate() {
            for op in op_group {
                let is_pending = op.is_pending();

                if op.pollable() {
                    op.poll(ui, data)?;
                }
                let (enabled, reason) = if is_pending {
                    (false, t!("operation-pending"))
                } else {
                    op.evaluate_enablement(data)
                };
                if !context_menu {
                    op.extra_ui(ui, data)?;
                }
                let response = button_renderer(ui, op, enabled, reason.as_ref(), context_menu);
                if response.clicked() {
                    any_clicked = true;
                    let mut ctx = OperationContext { ui, data, provider };
                    op.exec(&mut ctx)?;
                }
            }
            // Draw group separators in standard layouts and menus alike
            if g_idx + 1 < num_groups {
                ui.separator();
            }
        }
        if any_clicked && context_menu {
            ui.close_kind(egui::UiKind::Menu);
        }
        Ok(refresh)
    }

    /// Renders all operations in a specific group.
    /// This is useful for building custom caller layouts, submenus, and advanced structural separations.
    pub fn show_group<F>(
        &mut self,
        ui: &mut egui::Ui,
        provider: &dyn TableProvider,
        data: &mut TableState,
        group_idx: usize,
        context_menu: bool,
        mut button_renderer: F,
    ) -> Result<bool, TableError>
    where
        F: FnMut(
            &mut egui::Ui,
            &mut Box<dyn TableOperation>,
            bool, // enabled
            &str, // localized disabled reason
        ) -> egui::Response,
    {
        if group_idx >= self.groups.len() {
            return Ok(false);
        }

        let refresh = self.update(ui.ctx());
        let mut any_clicked = false;

        let op_group = &mut self.groups[group_idx];
        for op in op_group {
            let is_pending = op.is_pending();

            if op.pollable() {
                op.poll(ui, data)?;
            }
            let (enabled, reason) = if is_pending {
                (false, t!("operation-pending"))
            } else {
                op.evaluate_enablement(data)
            };

            if !context_menu {
                op.extra_ui(ui, data)?;
            }

            let response = button_renderer(ui, op, enabled, reason.as_ref());
            if response.clicked() {
                any_clicked = true;
                let mut ctx = OperationContext { ui, data, provider };
                op.exec(&mut ctx)?;
            }
        }

        if any_clicked && context_menu {
            ui.close_kind(egui::UiKind::Menu);
        }

        Ok(refresh)
    }

    /// Renders a single operation directly at a specific group and operation index.
    /// Gives the caller total control over fine-grained placement and visual arrangement.
    pub fn show_operation<F>(
        &mut self,
        ui: &mut egui::Ui,
        provider: &dyn TableProvider,
        data: &mut TableState,
        group_idx: usize,
        op_idx: usize,
        context_menu: bool,
        button_renderer: F,
    ) -> Result<bool, TableError>
    where
        F: FnOnce(
            &mut egui::Ui,
            &mut Box<dyn TableOperation>,
            bool, // enabled
            &str, // localized disabled reason
        ) -> egui::Response,
    {
        if group_idx >= self.groups.len() || op_idx >= self.groups[group_idx].len() {
            return Ok(false);
        }

        let refresh = self.update(ui.ctx());

        let op = &mut self.groups[group_idx][op_idx];
        let is_pending = op.is_pending();

        if op.pollable() {
            op.poll(ui, data)?;
        }
        let (enabled, reason) = if is_pending {
            (false, t!("operation-pending"))
        } else {
            op.evaluate_enablement(data)
        };

        if !context_menu {
            op.extra_ui(ui, data)?;
        }

        let response = button_renderer(ui, op, enabled, reason.as_ref());
        if response.clicked() {
            let mut ctx = OperationContext { ui, data, provider };
            op.exec(&mut ctx)?;
            if context_menu {
                ui.close_kind(egui::UiKind::Menu);
            }
        }

        Ok(refresh)
    }
}

/// Triggers for when table actions can execute.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TableOperationEnablement {
    #[default]
    Always,
    AtLeastOneFiltered,
    AtLeastOneSelected,
    OneSelected,
}

/// Trait defining a single modular table operation.
pub trait TableOperation: std::any::Any + std::fmt::Debug + Send + Sync {
    fn name(&self) -> Cow<'_, str>;
    fn icon(&self) -> &'static str {
        "X"
    }
    fn get_name(&self, full: bool) -> Cow<'_, str> {
        if full {
            Cow::Owned(format!("{} {}", self.name(), self.icon()))
        } else {
            Cow::Borrowed(self.icon())
        }
    }
    fn refresh_on_completion(&self) -> bool {
        false
    }
    fn pollable(&self) -> bool {
        false
    }
    fn is_first_page(&self) -> bool {
        true
    }
    fn is_last_page(&self) -> bool {
        true
    }
    fn enabled(&self) -> TableOperationEnablement;
    fn exec(&mut self, ctx: &mut OperationContext<'_, '_>) -> Result<(), TableError>;
    fn extra_ui(&mut self, _ui: &mut egui::Ui, _data: &mut TableState) -> Result<(), TableError> {
        Ok(())
    }
    fn is_pending(&mut self) -> bool {
        false
    }

    /// Event hook called exactly once when the operation transitions from pending to completed.
    fn on_completed(&mut self, _success: bool) {}

    /// Routine tick loop, natively fired if `pollable()` evaluates to true.
    fn poll(&mut self, _ui: &mut egui::Ui, _data: &mut TableState) -> Result<(), TableError> {
        Ok(())
    }
    fn consume(&mut self) -> Result<(), TableError> {
        Ok(())
    }
    fn error(&self) -> Option<&str> {
        None
    }
    fn clear_error(&mut self) {}
    fn is_modal_open(&self) -> bool {
        false
    }
    fn set_modal_open(&mut self, _open: bool) {}
    fn reset(&mut self) {}

    /// Spawns an input form dialog, pausing interactions while polling.
    fn pollable_modal(
        &mut self,
        ui: &mut egui::Ui,
        centered: bool,
        action: Cow<'_, str>,
        action_progressive: Cow<'_, str>,
        input_ui: impl FnOnce(&mut egui::Ui, &mut Self) -> Result<(), TableError>,
    ) -> Result<(), TableError>
    where
        Self: Sized,
    {
        if self.is_modal_open() {
            egui::Modal::new(ui.id().with("pollable_modal"))
                .show(ui.ctx(), |ui| {
                    ui.scope_builder(
                        egui::UiBuilder::new().layout(egui::Layout::top_down(if centered {
                            egui::Align::Center
                        } else {
                            egui::Align::Min
                        })),
                        |ui| {
                            ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
                            ui.heading(
                                egui::RichText::new(format!("{} {}", self.name(), self.icon()))
                                    .strong(),
                            );
                            ui.separator();
                            ui.spacing_mut().item_spacing.y = 5.0;

                            let is_pending = self.is_pending();
                            ui.add_enabled_ui(!is_pending, |ui| input_ui(ui, self))
                                .inner?;
                            ui.add_space(10.0);

                            if let Some(error) = self.error() {
                                ui.colored_label(egui::Color32::RED, t!("error"));
                                ui.colored_label(egui::Color32::RED, error);
                            }

                            if is_pending {
                                ui.label(action_progressive);
                                ui.add_space(5.0);
                                ui.spinner();
                            } else {
                                if self.is_last_page() {
                                    let is_allowed = self.poll_allow_execution();
                                    if ui
                                        .add_enabled(is_allowed, egui::Button::new(action))
                                        .clicked()
                                    {
                                        self.clear_error();
                                        self.consume()?;
                                    }
                                }
                                if self.is_first_page() && ui.button(t!("cancel")).clicked() {
                                    self.reset();
                                }
                            }
                            Ok(())
                        },
                    )
                    .inner
                })
                .inner
        } else {
            Ok(())
        }
    }

    /// Spawns a progress information dialog.
    fn polled_modal(
        &mut self,
        ui: &mut egui::Ui,
        heading: Cow<'_, str>,
        action_progressive: Cow<'_, str>,
        input_ui: impl FnOnce(&mut egui::Ui, &mut Self) -> Result<(), TableError>,
    ) -> Result<(), TableError>
    where
        Self: Sized,
    {
        if self.is_modal_open() {
            egui::Modal::new(ui.id().with("polled_modal"))
                .show(ui.ctx(), |ui| {
                    ui.vertical_centered(|ui| {
                        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
                        ui.heading(heading);
                        ui.separator();
                        ui.spacing_mut().item_spacing.y = 5.0;

                        if self.is_pending() {
                            ui.label(action_progressive);
                            ui.add_space(5.0);
                            ui.spinner();
                        } else if let Some(error) = self.error() {
                            ui.colored_label(egui::Color32::RED, t!("error"));
                            ui.colored_label(egui::Color32::RED, error);
                        } else {
                            input_ui(ui, self)?;
                        }

                        ui.add_space(10.0);
                        if ui.button(t!("close")).clicked() {
                            self.reset();
                        }
                        Ok::<_, TableError>(())
                    })
                })
                .inner
                .inner?;
        }
        Ok(())
    }

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

    /// Evaluates if the operation is enabled based on the current `TableState`,
    /// returning a tuple of `(is_enabled, localized_disabled_reason)`.
    fn evaluate_enablement(&self, state: &TableState) -> (bool, Cow<'static, str>) {
        match self.enabled() {
            TableOperationEnablement::Always => (true, Cow::Borrowed("")),
            TableOperationEnablement::AtLeastOneSelected => (
                !state.selected_rows.is_empty(),
                t!("operation-at-least-one"),
            ),
            TableOperationEnablement::OneSelected => {
                (state.selected_rows.len() == 1, t!("operation-one"))
            }
            TableOperationEnablement::AtLeastOneFiltered => (
                !state.active_rows.is_empty(),
                t!("operation-at-least-one-filtered"),
            ),
        }
    }
}

// Default Operations

#[derive(Debug, Default)]
pub struct CopyRows {
    pub prioritize_hovers: bool,
}

impl TableOperation for CopyRows {
    fn name(&self) -> Cow<'_, str> {
        if self.prioritize_hovers {
            t!("copy-hovered-rows")
        } else {
            t!("copy-rows")
        }
    }
    fn icon(&self) -> &'static str {
        if self.prioritize_hovers {
            "📁"
        } else {
            "📋"
        }
    }
    fn enabled(&self) -> TableOperationEnablement {
        TableOperationEnablement::AtLeastOneSelected
    }
    fn exec(&mut self, ctx: &mut OperationContext<'_, '_>) -> Result<(), TableError> {
        // Pre-allocate a default chunk size to minimize system allocator pressure
        let mut output = String::with_capacity(2048);

        ctx.provider.for_selected_rows(ctx.data, &mut |row| {
            if !output.is_empty() {
                output.push('\n');
            }
            for i in 0..row.column_count() {
                if i > 0 {
                    output.push(',');
                }
                if let Some((val, hover)) = row.cell(i) {
                    let cell_text = if self.prioritize_hovers {
                        hover.as_ref().map_or_else(|| val.as_ref(), |h| h.as_ref())
                    } else {
                        val.as_ref()
                    };
                    output.push_str(cell_text);
                }
            }
            Ok(())
        })?;

        ctx.ui.ctx().copy_text(output);
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct CopyHeadersRows {
    pub prioritize_hovers: bool,
}

impl TableOperation for CopyHeadersRows {
    fn name(&self) -> Cow<'_, str> {
        if self.prioritize_hovers {
            t!("copy-hovered-rows-with-headers")
        } else {
            t!("copy-rows-with-headers")
        }
    }
    fn icon(&self) -> &'static str {
        if self.prioritize_hovers {
            "🗄"
        } else {
            "📜"
        }
    }
    fn enabled(&self) -> TableOperationEnablement {
        TableOperationEnablement::AtLeastOneSelected
    }

    fn exec(&mut self, ctx: &mut OperationContext<'_, '_>) -> Result<(), TableError> {
        // Pre-allocate a reasonable capacity for headers and initial rows
        let mut output = String::with_capacity(2048);

        // 1. Write the headers directly into the buffer (replacing headers.join(","))
        for (i, header) in ctx.provider.headers().enumerate() {
            if i > 0 {
                output.push(',');
            }
            output.push_str(&header);
        }

        // 2. Stream the selected rows sequentially into the same buffer
        ctx.provider.for_selected_rows(ctx.data, &mut |row| {
            output.push('\n');
            for i in 0..row.column_count() {
                if i > 0 {
                    output.push(',');
                }
                if let Some((val, hover)) = row.cell(i) {
                    let cell_text = if self.prioritize_hovers {
                        hover.as_ref().map_or_else(|| val.as_ref(), |h| h.as_ref())
                    } else {
                        val.as_ref()
                    };
                    output.push_str(cell_text);
                }
            }
            Ok(())
        })?;

        // 3. Send the single allocated string to the clipboard
        ctx.ui.ctx().copy_text(output);
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct FilterSelectAll;

impl TableOperation for FilterSelectAll {
    fn name(&self) -> Cow<'_, str> {
        t!("select-filtered")
    }
    fn icon(&self) -> &'static str {
        ""
    }
    fn enabled(&self) -> TableOperationEnablement {
        TableOperationEnablement::Always
    }
    fn exec(&mut self, ctx: &mut OperationContext<'_, '_>) -> Result<(), TableError> {
        let active_u32_iter = ctx.data.active_rows.iter().map(|&row| row as u32);
        ctx.data.selected_rows.extend(active_u32_iter);
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct FilterDeSelectAll;

impl TableOperation for FilterDeSelectAll {
    fn name(&self) -> Cow<'_, str> {
        t!("deselect-filtered")
    }
    fn icon(&self) -> &'static str {
        ""
    }
    fn enabled(&self) -> TableOperationEnablement {
        TableOperationEnablement::Always
    }
    fn exec(&mut self, ctx: &mut OperationContext<'_, '_>) -> Result<(), TableError> {
        ctx.data.active_rows.iter().for_each(|row| {
            ctx.data.selected_rows.remove(*row as u32);
        });
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct SelectAll;

impl TableOperation for SelectAll {
    fn name(&self) -> Cow<'_, str> {
        t!("select-all")
    }
    fn icon(&self) -> &'static str {
        ""
    }
    fn enabled(&self) -> TableOperationEnablement {
        TableOperationEnablement::Always
    }
    fn exec(&mut self, ctx: &mut OperationContext<'_, '_>) -> Result<(), TableError> {
        ctx.data.selected_rows.clear();
        ctx.data
            .selected_rows
            .insert_range(0..ctx.provider.row_count() as u32);
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct DeSelectAll;

impl TableOperation for DeSelectAll {
    fn name(&self) -> Cow<'_, str> {
        t!("deselect-all")
    }
    fn icon(&self) -> &'static str {
        ""
    }
    fn enabled(&self) -> TableOperationEnablement {
        TableOperationEnablement::Always
    }
    fn exec(&mut self, ctx: &mut OperationContext<'_, '_>) -> Result<(), TableError> {
        ctx.data.selected_rows.clear();
        Ok(())
    }
}