Skip to main content

egui_selectable_table/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3mod auto_reload;
4mod auto_scroll;
5mod row_modification;
6mod row_selection;
7
8#[cfg(feature = "fuzzy-matching")]
9#[cfg_attr(docsrs, doc(cfg(feature = "fuzzy-matching")))]
10mod fuzzy_matcher;
11
12use ahash::{HashMap, HashMapExt, HashSet, HashSetExt};
13use auto_reload::AutoReload;
14pub use auto_scroll::AutoScroll;
15use egui::{Event, Key, Label, Response, ScrollArea, Sense, Ui};
16use egui_extras::{Column, TableBuilder, TableRow};
17use std::cmp::Ordering;
18use std::hash::Hash;
19
20#[cfg(feature = "fuzzy-matching")]
21use nucleo_matcher::Matcher;
22
23/// Enum representing the possible sort orders for table columns.
24#[derive(Default, Clone, Copy)]
25pub enum SortOrder {
26    /// Sorts in ascending order (e.g., A to Z or 1 to 10).
27    #[default]
28    Ascending,
29    /// Sorts in descending order (e.g., Z to A or 10 to 1).
30    Descending,
31}
32
33/// Trait for defining how to order rows based on a specific column.
34///
35/// This trait should be implemented by users to specify how rows should be
36/// compared for sorting purposes. The implementation can vary depending on
37/// the type of column. For instance, string comparisons or numeric comparisons
38/// can be handled differently depending on the column. Should only be implemented for Ascending
39/// ordering, in case of Descending, it is handled internally.
40///
41/// # Example
42/// Suppose you have a struct `MyRow` with fields like `user_id`, `name`, and `username`.
43/// You could implement this trait for each column to specify how rows should be compared.
44///
45/// ```rust,ignore
46/// impl ColumnOrdering<MyRow> for ColumnName {
47///     fn order_by(&self, row_1: &MyRow, row_2: &MyRow) -> Ordering {
48///         match self {
49///             ColumnName::UserID => row_1.user_id.cmp(&row_2.user_id),
50///             ColumnName::Name => row_1.name.cmp(&row_2.name),
51///             ColumnName::Username => row_1.username.cmp(&row_2.username),
52///         }
53///     }
54/// }
55/// ```
56pub trait ColumnOrdering<Row>
57where
58    Row: Clone + Send + Sync,
59{
60    /// Compare two rows and return the ordering result (`Ordering`).
61    ///
62    /// This function defines how to order two rows based on the specific column.
63    /// It returns `Ordering::Less`, `Ordering::Equal`, or `Ordering::Greater`
64    /// to indicate whether `row_1` should be placed before, after, or at the same
65    /// position as `row_2` when sorting. Should only be implemented for ascending ordering, in
66    /// case of Descending, it is handled internally.
67    ///
68    /// # Arguments
69    /// * `row_1` - The first row for comparison.
70    /// * `row_2` - The second row for comparison.
71    ///
72    /// # Returns
73    /// * `Ordering` - Indicates the relative order between the two rows.
74    fn order_by(&self, row_1: &Row, row_2: &Row) -> Ordering;
75}
76
77/// Trait for defining column-specific operations in a table UI.
78///
79/// This trait allows users to define how each column should behave within a table.
80/// This includes how headers should be displayed, how each row in the table should be rendered,
81/// and how to extract column-specific text.
82///
83/// # Type Parameters:
84/// * `Row` - The type representing each row in the table.
85/// * `F` - A type that identifies columns, usually an enum or a field type.
86/// * `Conf` - Configuration type for the table, useful for passing additional settings.
87///
88/// # Requirements:
89/// You must implement this trait to specify the behavior of each column within
90/// the context of your table UI.
91pub trait ColumnOperations<Row, F, Conf>
92where
93    Row: Clone + Send + Sync,
94    F: Eq
95        + Hash
96        + Clone
97        + Ord
98        + Send
99        + Sync
100        + Default
101        + ColumnOperations<Row, F, Conf>
102        + ColumnOrdering<Row>,
103    Conf: Default,
104{
105    /// Create the header UI for this column.
106    ///
107    /// This function is responsible for creating the visual representation of the column header.
108    /// The `sort_order` argument indicates whether the column is currently used for sorting and, if so, in which
109    /// direction (ascending or descending). You can customize the header appearance based on
110    /// this information, for example by adding icons or text. Return `None` for no header.
111    ///
112    /// # Arguments
113    /// * `ui` - A mutable reference to the UI context.
114    /// * `sort_order` - An optional `SortOrder` representing the current sort state of the column.
115    /// * `table` - A mutable reference to the `SelectableTable`, allowing you to interact with the table state.
116    ///
117    /// # Returns
118    /// * `Option<Response>` - An optional response representing interaction with the UI.
119    fn create_header(
120        &self,
121        ui: &mut Ui,
122        sort_order: Option<SortOrder>,
123        table: &mut SelectableTable<Row, F, Conf>,
124    ) -> Option<Response>;
125
126    /// Create the UI for a specific row in this column.
127    ///
128    /// This function is responsible for rendering the content of this column for a given row.
129    /// It should handle user interactions like clicking or selection as necessary. Mutable table
130    /// access is provided for modifyiing other rows as necessary.
131    ///
132    /// # Arguments
133    /// * `ui` - A mutable reference to the UI context.
134    /// * `row` - A reference to the current `SelectableRow` for this table.
135    /// * `column_selected` - A boolean indicating whether this column is selected.
136    /// * `table` - A mutable reference to the `SelectableTable` for modifying table data
137    ///
138    /// # Returns
139    /// * `Response` - The result of the UI interaction for this row.
140    fn create_table_row(
141        &self,
142        ui: &mut Ui,
143        row: &SelectableRow<Row, F>,
144        column_selected: bool,
145        table: &mut SelectableTable<Row, F, Conf>,
146    ) -> Response;
147
148    /// Extract the text representation of the column for the given row.
149    ///
150    /// This function should return the appropriate text representation of this column
151    /// for the given row. It can be used to display the data in a simplified form, such
152    /// as for debugging or plain text rendering.
153    ///
154    /// # Arguments
155    /// * `row` - A reference to the row from which to extract the column text.
156    ///
157    /// # Returns
158    /// * `String` - The text representation of this column for the row.
159    fn column_text(&self, row: &Row) -> String;
160}
161
162/// Represents a row in a table with selectable columns.
163///
164/// This struct is used to store the data of a row along with its unique identifier (`id`)
165/// and the set of selected columns for this row.
166///
167/// # Type Parameters:
168/// * `Row` - The type representing the data stored in each row.
169/// * `F` - The type used to identify each column, typically an enum or a type with unique values.
170///
171/// # Fields:
172/// * `row_data` - The actual data stored in the row.
173/// * `id` - A unique identifier for the row.
174/// * `selected_columns` - A set of columns that are selected in this row.
175#[derive(Clone)]
176pub struct SelectableRow<Row, F>
177where
178    Row: Clone + Send + Sync,
179    F: Eq + Hash + Clone + Ord + Send + Sync + Default,
180{
181    pub row_data: Row,
182    pub id: i64,
183    pub selected_columns: HashSet<F>,
184}
185
186/// A table structure that hold data for performing selection on drag, sorting, and displaying rows and more.
187///
188/// # Type Parameters
189/// * `Row` - The type representing each row in the table.
190/// * `F` - A type used to identify columns, often an enum or field type.
191/// * `Conf` - Configuration type for additional table settings passed by the user. This is made available anytime when creating or modifying rows
192pub struct SelectableTable<Row, F, Conf>
193where
194    Row: Clone + Send + Sync,
195    F: Eq
196        + Hash
197        + Clone
198        + Ord
199        + Send
200        + Sync
201        + Default
202        + ColumnOperations<Row, F, Conf>
203        + ColumnOrdering<Row>,
204    Conf: Default,
205{
206    /// List of all columns available in the table.
207    all_columns: Vec<F>,
208    /// Maps each column to its index in the table for quick lookup.
209    column_number: HashMap<F, usize>,
210    /// Stores all rows in the table, keyed by their unique ID.
211    rows: HashMap<i64, SelectableRow<Row, F>>,
212    /// The current set of formatted rows for display.
213    formatted_rows: Vec<SelectableRow<Row, F>>,
214    /// The column currently being used to sort the table.
215    sorted_by: F,
216    /// The current sort order (ascending or descending).
217    sort_order: SortOrder,
218    /// Tracks where a drag operation started in the table, if any.
219    drag_started_on: Option<(i64, F)>,
220    /// The columns that have at least 1 row with the column as selected
221    active_columns: HashSet<F>,
222    /// The rows that have at least 1 column as selected
223    active_rows: HashSet<i64>,
224    /// The last row where the pointer was
225    last_active_row: Option<i64>,
226    /// The last column where the pointer was
227    last_active_column: Option<F>,
228    /// Whether the pointer moved from the dragged point at least once
229    beyond_drag_point: bool,
230    /// Map of the row IDs to the indices of `formatted_rows`
231    indexed_ids: HashMap<i64, usize>,
232    /// The last ID that was used for a new row in the table.
233    last_id_used: i64,
234    /// Handles auto scroll operation when dragging
235    auto_scroll: AutoScroll,
236    /// Handles auto recreating the displayed rows with the latest data
237    auto_reload: AutoReload,
238    /// Whether to select the entire row when dragging and selecting instead of a single cell
239    select_full_row: bool,
240    /// Whether to add a horizontal scrollbar
241    horizontal_scroll: bool,
242    /// Additional Parameters passed by you, available when creating new rows or header. Can
243    /// contain anything implementing the `Default` trait
244    pub config: Conf,
245    /// Whether to add the row serial column to the table
246    add_serial_column: bool,
247    /// The row height for the table, defaults to 25.0
248    row_height: f32,
249    /// The header height for the table, defaults to 20.0
250    header_height: f32,
251
252    /// The matcher used for fuzzy searching
253    #[cfg(feature = "fuzzy-matching")]
254    matcher: Matcher,
255    /// Whether to capture Ctrl+A for selecting all rows
256    no_ctrl_a_capture: bool,
257    /// Row count above which rayon is used for parallel processing
258    #[cfg(feature = "rayon")]
259    rayon_threshold: usize,
260}
261
262impl<Row, F, Conf> SelectableTable<Row, F, Conf>
263where
264    Row: Clone + Send + Sync,
265    F: Eq
266        + Hash
267        + Clone
268        + Ord
269        + Send
270        + Sync
271        + Default
272        + ColumnOperations<Row, F, Conf>
273        + ColumnOrdering<Row>,
274    Conf: Default,
275{
276    /// Creates a new `SelectableTable` with the provided columns in a specified order.
277    ///
278    /// # Parameters:
279    /// - `columns`: A `Vec<F>` representing the columns. Columns must be passed in the correct order (e.g., 1 to 10).
280    ///
281    /// # Returns:
282    /// - A new instance of `SelectableTable`.
283    ///
284    /// # Example:
285    /// ```rust,ignore
286    /// let table = SelectableTable::new(vec![col1, col2, col3]);
287    /// ```
288    #[must_use]
289    pub fn new(columns: Vec<F>) -> Self {
290        let all_columns = columns.clone();
291        let mut column_number = HashMap::new();
292
293        for (index, col) in columns.into_iter().enumerate() {
294            column_number.insert(col, index);
295        }
296        Self {
297            all_columns,
298            column_number,
299            last_id_used: 0,
300            rows: HashMap::new(),
301            formatted_rows: Vec::new(),
302            sorted_by: F::default(),
303            sort_order: SortOrder::default(),
304            drag_started_on: None,
305            active_columns: HashSet::new(),
306            active_rows: HashSet::new(),
307            last_active_row: None,
308            last_active_column: None,
309            beyond_drag_point: false,
310            indexed_ids: HashMap::new(),
311            auto_scroll: AutoScroll::default(),
312            auto_reload: AutoReload::default(),
313            select_full_row: false,
314            horizontal_scroll: false,
315            config: Conf::default(),
316            add_serial_column: false,
317            row_height: 25.0,
318            header_height: 20.0,
319            #[cfg(feature = "fuzzy-matching")]
320            matcher: Matcher::default(),
321            no_ctrl_a_capture: false,
322            #[cfg(feature = "rayon")]
323            rayon_threshold: 5000,
324        }
325    }
326
327    /// Updates the table's configuration with the given `conf`.
328    ///
329    /// # Parameters:
330    /// - `conf`: The new configuration of type `Conf`, which is user-defined and allows
331    ///   passing data to help with row/table modification.
332    ///
333    /// # Example:
334    /// ```rust,ignore
335    /// table.set_config(my_config);
336    /// ```
337    pub fn set_config(&mut self, conf: Conf) {
338        self.config = conf;
339    }
340
341    /// Sets a configuration in a builder-style pattern.
342    ///
343    /// # Parameters:
344    /// - `conf`: A configuration of type `Conf`. The user can pass any data to help with row creation or modification.
345    ///
346    /// # Returns:
347    /// - The updated `SelectableTable` with the new configuration applied.
348    ///
349    /// # Example:
350    /// ```rust,ignore
351    /// let table = SelectableTable::new(vec![col1, col2, col3]).config(my_config);
352    /// ```
353    #[must_use]
354    pub fn config(mut self, conf: Conf) -> Self {
355        self.config = conf;
356        self
357    }
358
359    /// Clears all rows from the table, including the displayed ones. No need for any additional
360    /// call to update the UI.
361    ///
362    /// # Example:
363    /// ```rust,ignore
364    /// table.clear_all_rows();
365    /// ```
366    pub fn clear_all_rows(&mut self) {
367        self.rows.clear();
368        self.formatted_rows.clear();
369        self.active_rows.clear();
370        self.active_columns.clear();
371        self.last_id_used = 0;
372    }
373
374    /// Displays the UI for the table and uses the provided `TableBuilder` for creating the table UI.
375    ///
376    /// # Parameters:
377    /// - `ui`: The UI context where the table will be rendered.
378    /// - A closure that provides and allows modification of `TableBuilder`. Build your own table
379    ///   and return it.
380    ///
381    /// # Example:
382    /// ```rust,ignore
383    /// table.show_ui(ui, |builder| builder.column(column1));
384    /// ```
385    pub fn show_ui<Fn>(&mut self, ui: &mut Ui, table_builder: Fn)
386    where
387        Fn: FnOnce(TableBuilder) -> TableBuilder,
388    {
389        let is_ctrl_pressed = ui.ctx().input(|i| i.modifiers.ctrl);
390        let key_a_pressed = ui.ctx().input(|i| i.key_pressed(Key::A));
391        let copy_initiated = ui.ctx().input(|i| i.events.contains(&Event::Copy));
392        let ctx = ui.ctx().clone();
393
394        if copy_initiated {
395            self.copy_selected_cells(ui);
396        }
397        if is_ctrl_pressed && key_a_pressed && !self.no_ctrl_a_capture {
398            self.select_all();
399        }
400
401        let pointer = ui.input(|i| i.pointer.hover_pos());
402        let max_rect = ui.max_rect();
403
404        if self.horizontal_scroll {
405            ScrollArea::horizontal().show(ui, |ui| {
406                let mut table = TableBuilder::new(ui);
407
408                if self.add_serial_column {
409                    table = table.column(Column::initial(25.0).clip(true));
410                }
411
412                table = table_builder(table);
413
414                if self.drag_started_on.is_some()
415                    && let Some(offset) = self.auto_scroll.start_scroll(max_rect, pointer)
416                {
417                    table = table.vertical_scroll_offset(offset);
418                    ctx.request_repaint();
419                }
420
421                let output = table
422                    .header(self.header_height, |header| {
423                        self.build_head(header);
424                    })
425                    .body(|body| {
426                        body.rows(self.row_height, self.formatted_rows.len(), |row| {
427                            let index = row.index();
428                            self.build_body(row, index);
429                        });
430                    });
431
432                let scroll_offset = output.state.unclamped_offset().y;
433                self.update_scroll_offset(scroll_offset);
434            });
435        } else {
436            let mut table = TableBuilder::new(ui);
437
438            if self.add_serial_column {
439                table = table.column(Column::initial(25.0).clip(true));
440            }
441
442            table = table_builder(table);
443
444            if self.drag_started_on.is_some()
445                && let Some(offset) = self.auto_scroll.start_scroll(max_rect, pointer)
446            {
447                table = table.vertical_scroll_offset(offset);
448                ctx.request_repaint();
449            }
450
451            let output = table
452                .header(self.header_height, |header| {
453                    self.build_head(header);
454                })
455                .body(|body| {
456                    body.rows(self.row_height, self.formatted_rows.len(), |row| {
457                        let index = row.index();
458                        self.build_body(row, index);
459                    });
460                });
461            let scroll_offset = output.state.unclamped_offset().y;
462            self.update_scroll_offset(scroll_offset);
463        }
464    }
465
466    fn build_head(&mut self, mut header: TableRow) {
467        if self.add_serial_column {
468            header.col(|ui| {
469                ui.add_sized(ui.available_size(), Label::new(""));
470            });
471        }
472        for column_name in &self.all_columns.clone() {
473            header.col(|ui| {
474                let sort_order = if &self.sorted_by == column_name {
475                    Some(self.sort_order)
476                } else {
477                    None
478                };
479
480                let Some(resp) = column_name.create_header(ui, sort_order, self) else {
481                    return;
482                };
483
484                // Response click sense is not forced. So if a header should not be used
485                // for sorting, without click there won't be any actions.
486
487                if resp.clicked() {
488                    let is_selected = &self.sorted_by == column_name;
489                    if is_selected {
490                        self.change_sort_order();
491                    } else {
492                        self.change_sorted_by(column_name);
493                    }
494                    self.recreate_rows();
495                }
496            });
497        }
498    }
499
500    fn build_body(&mut self, mut row: TableRow, index: usize) {
501        let row_data = self.formatted_rows[index].clone();
502
503        if self.add_serial_column {
504            row.col(|ui| {
505                ui.add_sized(ui.available_size(), Label::new(format!("{}", index + 1)));
506            });
507        }
508        self.handle_table_body(row, &row_data);
509    }
510
511    /// Change the current sort order from ascending to descending and vice versa. Will unselect
512    /// all selected rows
513    fn change_sort_order(&mut self) {
514        self.unselect_all();
515        if matches!(self.sort_order, SortOrder::Ascending) {
516            self.sort_order = SortOrder::Descending;
517        } else {
518            self.sort_order = SortOrder::Ascending;
519        }
520    }
521
522    /// Change the column that is currently being used for sorting. Will unselect all rows
523    fn change_sorted_by(&mut self, sort_by: &F) {
524        self.unselect_all();
525        self.sorted_by = sort_by.clone();
526        self.sort_order = SortOrder::default();
527    }
528
529    /// Recreates the rows shown in the UI for the next frame load.
530    ///
531    /// # Important:
532    /// - Any direct modifications made using [`modify_shown_row`](#method.modify_shown_row)
533    ///   will be **cleared** when this is called.
534    ///   To preserve changes, use [`add_modify_row`](#method.add_modify_row) to update row data instead.
535    ///
536    /// # Performance:
537    /// - Should be used sparingly for large datasets, as frequent calls can lead to performance issues.
538    /// - Consider calling after every X number of row updates, depending on update frequency,
539    ///   or use [`auto_reload`](#method.auto_reload) for automatic reload.
540    ///
541    /// # Example:
542    /// ```rust,ignore
543    /// table.recreate_rows();
544    /// ```
545    pub fn recreate_rows(&mut self) {
546        self.formatted_rows.clear();
547        self.active_rows.clear();
548        self.active_columns.clear();
549        self.sort_rows();
550    }
551
552    /// Recreates the rows shown in the UI for the next frame load.
553    ///
554    /// This function refreshes the internal row state by clearing and re-sorting the rows
555    /// similar to [`recreate_rows`](#method.recreate_rows), but it **preserves** the currently
556    /// selected rows and re-applies the active column selection to them.
557    ///
558    /// Useful when the UI needs to be refreshed without resetting user interaction state.
559    ///
560    /// # Important:
561    /// - Any direct modifications made to `formatted_rows` using [`modify_shown_row`](#method.modify_shown_row)
562    ///   will be **cleared** when this is called.
563    ///   To preserve changes, use [`add_modify_row`](#method.add_modify_row) to update row data instead.
564    ///
565    /// # Performance:
566    /// - Should be used sparingly for large datasets, as frequent calls can lead to performance issues.
567    /// - Consider calling after every X number of row updates, depending on update frequency,
568    ///   or use [`auto_reload`](#method.auto_reload) for automatic reload.
569    ///
570    /// # Example:
571    /// ```rust,ignore
572    /// table.recreate_rows_no_unselect();
573    /// ```
574    pub fn recreate_rows_no_unselect(&mut self) {
575        self.formatted_rows.clear();
576        self.sort_rows();
577
578        for row in &self.active_rows {
579            let Some(target_index) = self.indexed_ids.get(row) else {
580                continue;
581            };
582            self.formatted_rows[*target_index]
583                .selected_columns
584                .clone_from(&self.active_columns);
585        }
586    }
587
588    /// The first column that was passed by the user
589    fn first_column(&self) -> F {
590        self.all_columns[0].clone()
591    }
592
593    /// The last column that was passed by the user
594    fn last_column(&self) -> F {
595        self.all_columns[self.all_columns.len() - 1].clone()
596    }
597
598    /// Returns the row ID to use as the anchor for shift+click range selection.
599    /// Uses the first selected row (by display order) if any, otherwise the first visible row.
600    fn anchor_row_id(&self) -> i64 {
601        if self.active_rows.is_empty() || self.formatted_rows.is_empty() {
602            return 0;
603        }
604        let mut min_idx = usize::MAX;
605        let mut anchor = 0;
606        for id in &self.active_rows {
607            if let Some(idx) = self.indexed_ids.get(id)
608                && *idx < min_idx
609            {
610                min_idx = *idx;
611                anchor = *id;
612            }
613        }
614        anchor
615    }
616
617    /// Returns the column to use as the anchor for shift+click range selection.
618    /// Uses the first column in `active_columns` (by configured order) if any,
619    /// otherwise the first column in the table.
620    fn anchor_column(&self) -> &F {
621        if self.active_columns.is_empty() {
622            return &self.all_columns[0];
623        }
624        for col in &self.all_columns {
625            if self.active_columns.contains(col) {
626                return col;
627            }
628        }
629        &self.all_columns[0]
630    }
631
632    /// Convert a number to a column value
633    fn column_to_num(&self, column: &F) -> usize {
634        *self
635            .column_number
636            .get(column)
637            .expect("Not in the column list")
638    }
639
640    /// Get the next column of the provided column
641    fn next_column(&self, column: &F) -> F {
642        let current_column_num = self.column_to_num(column);
643        if current_column_num == self.all_columns.len() - 1 {
644            self.all_columns[0].clone()
645        } else {
646            self.all_columns[current_column_num + 1].clone()
647        }
648    }
649
650    /// Builds the table's Body section
651    fn handle_table_body(&mut self, mut row: TableRow, row_data: &SelectableRow<Row, F>) {
652        for column_name in &self.all_columns.clone() {
653            row.col(|ui| {
654                let selected = row_data.selected_columns.contains(column_name);
655                let mut resp = column_name.create_table_row(ui, row_data, selected, self);
656
657                // Drag sense is forced otherwise there is no point of this library.
658                resp = resp.interact(Sense::drag());
659
660                if resp.drag_started() {
661                    // If CTRL is not pressed down and the mouse right click is not pressed, unselect all cells
662                    // Right click for context menu
663                    if !ui.ctx().input(|i| i.modifiers.ctrl)
664                        && !ui.ctx().input(|i| i.pointer.secondary_clicked())
665                    {
666                        self.unselect_all();
667                    }
668                    self.drag_started_on = Some((row_data.id, column_name.clone()));
669                }
670
671                let pointer_released = ui.input(|a| a.pointer.primary_released());
672
673                if pointer_released {
674                    self.last_active_row = None;
675                    self.last_active_column = None;
676                    self.drag_started_on = None;
677                    self.beyond_drag_point = false;
678                }
679
680                if resp.clicked() {
681                    let shift = ui.ctx().input(|i| i.modifiers.shift);
682                    let ctrl = ui.ctx().input(|i| i.modifiers.ctrl);
683                    let secondary = ui.ctx().input(|i| i.pointer.secondary_clicked());
684
685                    if shift {
686                        let anchor_id = self.anchor_row_id();
687                        let anchor_col = self.anchor_column().clone();
688                        if !ctrl && !secondary {
689                            self.unselect_all();
690                        }
691                        self.select_rectangle(
692                            anchor_id,
693                            &anchor_col,
694                            row_data.id,
695                            column_name,
696                            ctrl,
697                        );
698                    } else {
699                        // If CTRL is not pressed down and the mouse right click is not pressed, unselect all cells
700                        // Right click for context menu
701                        if !ctrl && !secondary {
702                            self.unselect_all();
703                        }
704                        self.select_single_row_cell(row_data.id, column_name);
705                    }
706                }
707
708                if ui.ui_contains_pointer()
709                    && self.drag_started_on.is_some()
710                    && let Some(drag_start) = self.drag_started_on.as_ref()
711                {
712                    // Only call drag either when not on the starting drag row/column or went beyond the
713                    // drag point at least once. Otherwise normal click would be considered as drag
714                    if drag_start.0 != row_data.id
715                        || &drag_start.1 != column_name
716                        || self.beyond_drag_point
717                    {
718                        let is_ctrl_pressed = ui.ctx().input(|i| i.modifiers.ctrl);
719                        self.select_dragged_row_cell(row_data.id, column_name, is_ctrl_pressed);
720                    }
721                }
722            });
723        }
724    }
725
726    /// Returns the total number of rows currently being displayed in the UI.
727    ///
728    /// # Returns:
729    /// - `usize`: The number of rows that are formatted and ready for display.
730    pub const fn total_displayed_rows(&self) -> usize {
731        self.formatted_rows.len()
732    }
733
734    /// Returns the total number of rows in the table (both displayed and non-displayed).
735    ///
736    /// # Returns:
737    /// - `usize`: The total number of rows stored in the table, regardless of whether they are being displayed or not.
738    pub fn total_rows(&self) -> usize {
739        self.rows.len()
740    }
741
742    /// Provides a reference to the rows currently being displayed in the UI.
743    ///
744    /// # Returns:
745    /// - `&Vec<SelectableRow<Row, F>>`: A reference to the vector of formatted rows ready for display.
746    pub const fn get_displayed_rows(&self) -> &Vec<SelectableRow<Row, F>> {
747        &self.formatted_rows
748    }
749
750    /// Provides a reference to all rows in the table, regardless of whether they are displayed.
751    ///
752    /// # Returns:
753    /// - `&HashMap<i64, SelectableRow<Row, F>>`: A reference to the entire collection of rows in the table.
754    pub const fn get_all_rows(&self) -> &HashMap<i64, SelectableRow<Row, F>> {
755        &self.rows
756    }
757
758    /// Adds a serial column UI to the table.
759    ///
760    /// The serial column UI is automatically generated and displayed at the very left of the table.
761    /// It shows the row number (starting from 1) for each row.
762    ///
763    /// # Returns:
764    /// - `Self`: The modified table with the serial column enabled.
765    ///
766    /// # Example:
767    /// ```rust,ignore
768    /// let table = SelectableTable::new(vec![col1, col2, col3])
769    ///     .config(my_config).serial_column();
770    /// ```
771    #[must_use]
772    pub const fn serial_column(mut self) -> Self {
773        self.add_serial_column = true;
774        self
775    }
776
777    /// Add a horizontal scrollbar to the table
778    ///
779    /// # Returns:
780    /// - `Self`: The modified table with the horizontal scrollbar enabled.
781    ///
782    /// # Example:
783    /// ```rust,ignore
784    /// let table = SelectableTable::new(vec![col1, col2, col3])
785    ///     .horizontal_scroll();
786    /// ```
787    #[must_use]
788    pub const fn horizontal_scroll(mut self) -> Self {
789        self.horizontal_scroll = true;
790        self
791    }
792
793    /// Sets the number of rows above which rayon is used for sorting and other bulk operations.
794    /// Smaller tables are processed sequentially since thread overhead outweighs the gain.
795    /// Defaults to 5000.
796    ///
797    /// Rayon is slower than sequential processing on small tables and starts to pay off
798    /// somewhere around 3,000-5,000 rows. See the README for benchmark numbers.
799    ///
800    /// # Example:
801    /// ```rust,ignore
802    /// let table = SelectableTable::new(columns)
803    ///     .rayon_threshold(5000);
804    /// ```
805    #[cfg(feature = "rayon")]
806    #[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
807    #[must_use]
808    pub const fn rayon_threshold(mut self, threshold: usize) -> Self {
809        self.rayon_threshold = threshold;
810        self
811    }
812
813    /// Sets the height of the rows in the table. Defaults to 25.0.
814    ///
815    /// # Parameters:
816    /// - `height`: The desired height for each row in logical points.
817    ///
818    /// # Returns:
819    /// - `Self`: The modified table with the specified row height applied.
820    ///
821    /// # Example:
822    /// ```rust,ignore
823    /// let table = SelectableTable::new(vec![col1, col2, col3])
824    ///     .row_height(24.0);
825    /// ```
826    #[must_use]
827    pub const fn row_height(mut self, height: f32) -> Self {
828        self.row_height = height;
829        self
830    }
831
832    /// Sets the height of the header in the table. Defaults to 20.0.
833    ///
834    /// # Parameters:
835    /// - `height`: The desired height for the header
836    ///
837    /// # Returns:
838    /// - `Self`: The modified table with the specified header height applied.
839    ///
840    /// # Example:
841    /// ```rust,ignore
842    /// let table = SelectableTable::new(vec![col1, col2, col3])
843    ///     .header_height(24.0);
844    /// ```
845    #[must_use]
846    pub const fn header_height(mut self, height: f32) -> Self {
847        self.header_height = height;
848        self
849    }
850
851    /// Disables Ctrl+A keyboard shortcut capturing for selecting all rows
852    ///
853    /// # Returns:
854    /// - `Self`: The modified table with Ctrl+A capturing disabled.
855    ///
856    /// # Example:
857    /// ```rust,ignore
858    /// let table = SelectableTable::new(columns)
859    ///     .no_ctrl_a_capture();
860    /// ```
861    #[must_use]
862    pub const fn no_ctrl_a_capture(mut self) -> Self {
863        self.no_ctrl_a_capture = true;
864        self
865    }
866
867    /// Enables or disables Ctrl+A keyboard shortcut capturing dynamically for selecting all rows.
868    ///
869    /// # Parameters:
870    /// - `status`: `true` to disable Ctrl+A capture, `false` to enable it.
871    ///
872    /// # Example:
873    /// ```rust,ignore
874    /// table.set_no_ctrl_a_capture(true); // Disable Ctrl+A capture
875    /// ```
876    pub const fn set_no_ctrl_a_capture(&mut self, status: bool) {
877        self.no_ctrl_a_capture = status;
878    }
879}