Skip to main content

egui_pop_views/
table.rs

1//! A data table: virtualised rows, a sticky header, columns sorted and
2//! resized, cells drawn by the application.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! It wraps Rerun's `egui_table` (MIT OR Apache-2.0), which draws the
8//! rows in view, the header and the resize handles, and adds what an
9//! egui-pop view has: a selection by key with the keyboard and the
10//! pointer, sorting from the header, and the sort and the widths kept in
11//! the host's value store (declare them once with [`declare`]), every
12//! change a step (`table.select`, `table.sort`, `table.resize`).
13//!
14//! Columns can be selected too ([`DataTable::select_columns`]): a header
15//! click selects its column (Ctrl toggles it, Shift extends), the column
16//! is tinted from its header to its last row, and the sort moves to the
17//! header's context menu, as in a spreadsheet. The column under the
18//! pointer is tinted as well and said in the output
19//! ([`TableOutput::hovered_column`]). A right click on a header opens its
20//! menu: the sort entries, then the application's
21//! ([`DataTable::header_menu`]).
22//!
23//! The application owns the rows: it sorts them as [`TableState::sort`]
24//! (or the store) says and gives them through [`TableRows`]. An order
25//! decided elsewhere (a sort command) is shown with
26//! [`TableState::set_sort`], without a store.
27//!
28//! Enter or a double click on a row activates it ([`Signal::Activate`]);
29//! built with [`DataTable::drag_out`], a drag from a row carries rows out
30//! ([`Signal::DragOut`]).
31//!
32//! ```
33//! use egui_pop_views::table::{Column, DataTable, TableRows, TableState};
34//!
35//! struct Files(Vec<(u64, String, u64)>);
36//!
37//! impl TableRows<u64> for Files {
38//!     fn len(&self) -> usize { self.0.len() }
39//!     fn key(&self, row: usize) -> u64 { self.0[row].0 }
40//!     fn label(&self, row: usize) -> String { self.0[row].1.clone() }
41//!     fn cell(&mut self, ui: &mut egui::Ui, row: usize, column: usize, _selected: bool) {
42//!         match column {
43//!             0 => { ui.label(&self.0[row].1); }
44//!             _ => { ui.label(format!("{} KB", self.0[row].2)); }
45//!         }
46//!     }
47//! }
48//!
49//! fn ui(ui: &mut egui::Ui, state: &mut TableState<u64>, files: &mut Files) {
50//!     let columns = [Column::new("name", "Name").width(200.0), Column::new("size", "Size")];
51//!     let out = DataTable::new("files", &columns).show(ui, state, files);
52//!     if out.sorted {
53//!         // Sort the rows as `state.sort()` says.
54//!     }
55//! }
56//! ```
57
58use crate::app_link::AppHandle;
59use crate::app_link::Outcome;
60use crate::shared::SelectionService;
61use egui::{Id, Response, Role, Sense, Ui, WidgetInfo};
62use egui_pop_core::binding::SharedStore;
63use egui_pop_core::kit::{Kit, KitCx, Part, State};
64use egui_pop_core::strings::{tr, tr_args};
65use egui_pop_core::widgets::SortHeader;
66use egui_pop_model::commands::Origin;
67use egui_pop_model::ids::OwnerId;
68use egui_pop_model::selection::SelectionItem;
69use egui_pop_model::values::{Change, DeclareError, Descriptor, Set, Value};
70use egui_table::{CellInfo, HeaderCellInfo, HeaderRow, PrefetchInfo, TableDelegate};
71use serde_json::{Value as Json, json};
72
73use crate::list;
74/// What happened in a table this pass: the list's signals.
75pub use crate::list::Signal;
76use crate::nav::{self, TypeAhead};
77use crate::rows;
78use crate::select::{Key, Mode, Proposal, Selection};
79use crate::steps::{self, TABLE_RESIZE, TABLE_SELECT, TABLE_SELECT_COLUMNS, TABLE_SORT};
80use crate::strings as s;
81
82/// A column as declared.
83#[derive(Clone, Debug, PartialEq)]
84pub struct Column {
85    /// Its id in steps, signals and the store.
86    pub id: String,
87    pub title: String,
88    /// Its width until resized.
89    pub width: f32,
90    pub min_width: f32,
91    pub sortable: bool,
92    pub resizable: bool,
93}
94
95impl Column {
96    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
97        Self {
98            id: id.into(),
99            title: title.into(),
100            width: 120.0,
101            min_width: 32.0,
102            sortable: true,
103            resizable: true,
104        }
105    }
106
107    pub fn width(mut self, width: f32) -> Self {
108        self.width = width;
109        self
110    }
111
112    pub fn min_width(mut self, width: f32) -> Self {
113        self.min_width = width;
114        self
115    }
116
117    pub fn sortable(mut self, on: bool) -> Self {
118        self.sortable = on;
119        self
120    }
121
122    pub fn resizable(mut self, on: bool) -> Self {
123        self.resizable = on;
124        self
125    }
126}
127
128/// A table's order: by a column, up or down.
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct Sort {
131    pub column: String,
132    pub descending: bool,
133}
134
135impl Sort {
136    /// As the store keeps it: `name`, `-name` (descending), empty
137    /// (unsorted).
138    pub fn encode(sort: Option<&Sort>) -> String {
139        match sort {
140            Some(s) if s.descending => format!("-{}", s.column),
141            Some(s) => s.column.clone(),
142            None => String::new(),
143        }
144    }
145
146    pub fn decode(text: &str) -> Option<Sort> {
147        match text.strip_prefix('-') {
148            _ if text.is_empty() => None,
149            Some(c) => Some(Sort {
150                column: c.into(),
151                descending: true,
152            }),
153            None => Some(Sort {
154                column: text.into(),
155                descending: false,
156            }),
157        }
158    }
159
160    /// What a click on `column`'s header asks for: up, then down, then
161    /// unsorted.
162    pub fn next(current: Option<&Sort>, column: &str) -> Option<Sort> {
163        match current {
164            Some(s) if s.column == column && !s.descending => Some(Sort {
165                column: column.into(),
166                descending: true,
167            }),
168            Some(s) if s.column == column => None,
169            _ => Some(Sort {
170                column: column.into(),
171                descending: false,
172            }),
173        }
174    }
175}
176
177/// Declares a table's values in the store: `<prefix>/sort` (text:
178/// `name`, `-name` or empty) and `<prefix>/widths` (one per column).
179/// Call it once, from the plugin owning the table.
180pub fn declare(
181    store: &SharedStore,
182    owner: &OwnerId,
183    prefix: &str,
184    columns: &[Column],
185) -> Result<(), DeclareError> {
186    let mut s = egui_pop_core::lock(store);
187    s.declare(
188        owner,
189        &format!("{prefix}/sort"),
190        Descriptor::text("Sort", ""),
191    )?;
192    let widths: Vec<f64> = columns.iter().map(|c| f64::from(c.width)).collect();
193    s.declare(
194        owner,
195        &format!("{prefix}/widths"),
196        Descriptor::floats("Column widths", columns.len() as u32, 8.0, 4000.0, &widths),
197    )
198}
199
200/// The rows a table shows; the application owns them, sorted as the
201/// table's sort says.
202pub trait TableRows<K: Key> {
203    fn len(&self) -> usize;
204
205    fn is_empty(&self) -> bool {
206        self.len() == 0
207    }
208
209    /// Row `row`'s key.
210    fn key(&self, row: usize) -> K;
211
212    /// Row `row`'s accessible name, searched by type-ahead.
213    fn label(&self, row: usize) -> String;
214
215    /// Draws a cell (its row's background is drawn). Its `Ui` truncates
216    /// text: a label too long for the cell is elided with "…" and shows
217    /// the full text on hover.
218    fn cell(&mut self, ui: &mut Ui, row: usize, column: usize, selected: bool);
219
220    /// Where row `row` starts, from the top of the first row, rows being
221    /// `row_h` high unless the application says otherwise: rows of
222    /// several heights (a row expanded to several lines) give their
223    /// offsets here, `0.0` for row 0, and [`TableRows::len`] gives the
224    /// height of them all. Called for the rows in view and a binary
225    /// search over the rows, so keep it cheap.
226    fn row_top(&self, row: usize, row_h: f32) -> f32 {
227        row as f32 * row_h
228    }
229}
230
231/// A table's state between passes.
232#[derive(Debug)]
233pub struct TableState<K: Key> {
234    selection: Selection<K>,
235    type_ahead: TypeAhead,
236    sort: Option<Sort>,
237    widths: Vec<f32>,
238    /// The widths last given to `egui_table`.
239    given: Option<Vec<f32>>,
240    reveal: Option<usize>,
241    page: usize,
242    len: Option<usize>,
243    /// The selected columns' ids, in the columns' order.
244    columns: Vec<String>,
245    /// The column a Shift+click extends from.
246    column_anchor: Option<String>,
247    /// The column under the pointer at the last pass, tinted at this one.
248    hovered_column: Option<String>,
249    /// The shared selection's revision last followed (columns).
250    seen: Option<u64>,
251    /// How many rows a drag out carries, while it lasts.
252    carry: Option<usize>,
253}
254
255impl<K: Key> Default for TableState<K> {
256    fn default() -> Self {
257        Self {
258            selection: Selection::default(),
259            type_ahead: TypeAhead::default(),
260            sort: None,
261            widths: Vec::new(),
262            given: None,
263            reveal: None,
264            page: 10,
265            len: None,
266            columns: Vec::new(),
267            column_anchor: None,
268            hovered_column: None,
269            seen: None,
270            carry: None,
271        }
272    }
273}
274
275impl<K: Key> TableState<K> {
276    pub fn new() -> Self {
277        Self::default()
278    }
279
280    pub fn selection(&self) -> &Selection<K> {
281        &self.selection
282    }
283
284    /// Sets the selection without running a step.
285    pub fn set_selection(&mut self, keys: impl IntoIterator<Item = K>, cursor: Option<K>) {
286        self.selection.set(keys, cursor);
287    }
288
289    /// The order the application sorts its rows in.
290    pub fn sort(&self) -> Option<&Sort> {
291        self.sort.as_ref()
292    }
293
294    /// Sets the order shown in the header (its arrow) without running a
295    /// step or writing a store: for an order the application decides
296    /// elsewhere. A table with a store ([`DataTable::store`]) shows the
297    /// store's order instead.
298    pub fn set_sort(&mut self, sort: Option<Sort>) {
299        self.sort = sort;
300    }
301
302    /// The columns' widths as last shown.
303    pub fn widths(&self) -> &[f32] {
304        &self.widths
305    }
306
307    /// Sets the columns' widths, one per column, shown at the next pass
308    /// without running a step or writing a store (widths of another
309    /// count are replaced by the columns' own). A table with a store
310    /// ([`DataTable::store`]) shows the store's widths instead.
311    pub fn set_widths(&mut self, widths: Vec<f32>) {
312        self.widths = widths;
313    }
314
315    /// The selected columns' ids ([`DataTable::select_columns`]).
316    pub fn selected_columns(&self) -> &[String] {
317        &self.columns
318    }
319
320    /// Sets the selected columns without running a step.
321    pub fn set_selected_columns(&mut self, columns: impl IntoIterator<Item = String>) {
322        self.columns = columns.into_iter().collect();
323    }
324
325    /// The column under the pointer at the last pass, over its header or
326    /// one of its cells.
327    pub fn hovered_column(&self) -> Option<&str> {
328        self.hovered_column.as_deref()
329    }
330
331    /// Brings a row into view at the next pass.
332    pub fn reveal(&mut self, row: usize) {
333        self.reveal = Some(row);
334    }
335}
336
337/// What [`DataTable::show`] returns.
338#[derive(Debug)]
339#[non_exhaustive]
340pub struct TableOutput<K> {
341    /// The table as one focusable widget.
342    pub response: Response,
343    /// Selection changes and vetoes.
344    pub signals: Vec<Signal<K>>,
345    /// The sort changed this pass: sort the rows again.
346    pub sorted: bool,
347    /// The widths changed this pass (a resize ended).
348    pub resized: bool,
349    /// The column selection changed this pass
350    /// ([`TableState::selected_columns`]).
351    pub columns_selected: bool,
352    /// The column under the pointer, over its header or one of its cells.
353    pub hovered_column: Option<String>,
354    /// The column whose header was clicked this pass (a primary click).
355    pub header_clicked: Option<String>,
356    /// The rows in view this pass (empty before the table's first pass).
357    pub visible_rows: std::ops::Range<usize>,
358}
359
360/// What a header's context menu adds after the sort entries, given the
361/// menu's `Ui` and the column's id.
362type MenuFn<'a> = dyn FnMut(&mut Ui, &str) + 'a;
363
364/// [`DataTable::header_menu`]'s closure.
365struct HeaderMenu<'a>(Box<MenuFn<'a>>);
366
367impl std::fmt::Debug for HeaderMenu<'_> {
368    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
369        f.write_str("HeaderMenu")
370    }
371}
372
373/// A column's item in the application-wide selection: `column:<id>`.
374pub fn column_item(column: &str) -> SelectionItem {
375    SelectionItem::new(format!("column:{column}"))
376}
377
378/// The data table widget.
379///
380/// Need (data): a table with sortable, resizable columns.
381#[derive(Debug)]
382pub struct DataTable<'a> {
383    id: String,
384    label: Option<String>,
385    columns: &'a [Column],
386    mode: Mode,
387    app: Option<&'a AppHandle>,
388    store: Option<(&'a SharedStore, String)>,
389    height: Option<f32>,
390    row_height: Option<f32>,
391    select_columns: bool,
392    header_menu: Option<HeaderMenu<'a>>,
393    shared_columns: Option<&'a SelectionService>,
394    stick_to_bottom: bool,
395    drag_out: bool,
396    header_icons: Vec<HeaderIcon>,
397}
398
399/// A column header shown as an icon ([`DataTable::header_icon`]).
400#[derive(Clone, Debug)]
401struct HeaderIcon {
402    column: String,
403    icon: String,
404    tip: String,
405}
406
407impl<'a> DataTable<'a> {
408    /// A table named `id` in steps and signals.
409    pub fn new(id: impl Into<String>, columns: &'a [Column]) -> Self {
410        Self {
411            id: id.into(),
412            label: None,
413            columns,
414            mode: Mode::Single,
415            app: None,
416            store: None,
417            height: None,
418            row_height: None,
419            select_columns: false,
420            header_menu: None,
421            shared_columns: None,
422            stick_to_bottom: false,
423            drag_out: false,
424            header_icons: Vec::new(),
425        }
426    }
427
428    /// Shows column `column`'s header as an icon of the icon registry
429    /// (`phosphor:cloud-check`) with a tooltip (`Backed up`), for a narrow
430    /// column of states. The column's title stays its name for assistive
431    /// technology and in the header's menu; a click sorts as before, the
432    /// sort glyph after the icon.
433    ///
434    /// Need (data): a narrow column of states headed by an icon.
435    pub fn header_icon(
436        mut self,
437        column: impl Into<String>,
438        icon: impl Into<String>,
439        tip: impl Into<String>,
440    ) -> Self {
441        self.header_icons.push(HeaderIcon {
442            column: column.into(),
443            icon: icon.into(),
444            tip: tip.into(),
445        });
446        self
447    }
448
449    /// A drag that starts on a row carries rows out (off by default):
450    /// the table signals [`Signal::DragOut`] as it starts, for the
451    /// application to set its payload (`egui::DragAndDrop::set_payload`)
452    /// and its drop targets to take it; while it lasts the cursor shows a
453    /// carry and the pointer how many rows go.
454    pub fn drag_out(mut self, on: bool) -> Self {
455        self.drag_out = on;
456        self
457    }
458
459    /// Keeps the last row in view as rows are added, until the user
460    /// scrolls up; scrolled back to the end, it follows again (a log's
461    /// tail). Off by default.
462    pub fn stick_to_bottom(mut self, on: bool) -> Self {
463        self.stick_to_bottom = on;
464        self
465    }
466
467    /// Lets a header click select its column (Ctrl+click toggles it,
468    /// Shift+click extends from the last one clicked), through the
469    /// `table.select_columns` step; the selected columns are tinted from
470    /// header to last row. The sort is then in the header's context menu
471    /// (a click no longer sorts), as in a spreadsheet. Off by default: a
472    /// click sorts.
473    pub fn select_columns(mut self, on: bool) -> Self {
474        self.select_columns = on;
475        self
476    }
477
478    /// Adds entries to a header's context menu (a right click), after the
479    /// sort entries: `add(ui, column_id)`.
480    pub fn header_menu(mut self, add: impl FnMut(&mut Ui, &str) + 'a) -> Self {
481        self.header_menu = Some(HeaderMenu(Box::new(add)));
482        self
483    }
484
485    /// Binds the column selection to the application-wide selection
486    /// (`egui_pop_api::selection`), its items `column:<id>`
487    /// ([`column_item`]): the columns selected or hovered anywhere are
488    /// tinted, and what is selected here goes there (Ctrl changes only
489    /// this table's columns). Needs [`DataTable::select_columns`] to
490    /// select from the headers.
491    #[cfg(feature = "api")]
492    pub fn shared_columns(mut self, selection: &'a SelectionService) -> Self {
493        self.shared_columns = Some(selection);
494        self
495    }
496
497    /// Its accessible name.
498    pub fn label(mut self, label: impl Into<String>) -> Self {
499        self.label = Some(label.into());
500        self
501    }
502
503    pub fn mode(mut self, mode: Mode) -> Self {
504        self.mode = mode;
505        self
506    }
507
508    /// Runs its moments as steps of this application.
509    #[cfg(feature = "api")]
510    pub fn app(mut self, app: &'a AppHandle) -> Self {
511        self.app = Some(app);
512        self
513    }
514
515    /// Keeps the sort and the widths in `store` under `prefix` (see
516    /// [`declare`]).
517    pub fn store(mut self, store: &'a SharedStore, prefix: impl Into<String>) -> Self {
518        self.store = Some((store, prefix.into()));
519        self
520    }
521
522    /// Its height (default: what is available).
523    pub fn height(mut self, height: f32) -> Self {
524        self.height = Some(height);
525        self
526    }
527
528    /// Each row's height (default: the theme's interactive height).
529    pub fn row_height(mut self, height: f32) -> Self {
530        self.row_height = Some(height);
531        self
532    }
533
534    fn read_store<K: Key>(&self, state: &mut TableState<K>) {
535        let n = self.columns.len();
536        if state.widths.len() != n {
537            state.widths = self.columns.iter().map(|c| c.width).collect();
538        }
539        let Some((store, prefix)) = &self.store else {
540            return;
541        };
542        let s = egui_pop_core::lock(store);
543        if let Some(Value::Text(t)) = s.get(&format!("{prefix}/sort")).map(|e| &e.value) {
544            state.sort = Sort::decode(t);
545        }
546        if let Some(Value::Floats(w)) = s.get(&format!("{prefix}/widths")).map(|e| &e.value)
547            && w.len() == n
548        {
549            state.widths = w.iter().map(|&w| w as f32).collect();
550        }
551    }
552
553    fn write_store(&self, path: &str, value: Value) -> Result<(), String> {
554        let Some((store, prefix)) = &self.store else {
555            return Ok(());
556        };
557        egui_pop_core::lock(store)
558            .set(
559                // A person sorted or resized: the framework writes it.
560                Set::new(&format!("{prefix}/{path}"), Change::To(value), Origin::User)
561                    .by(&OwnerId::FRAMEWORK)
562                    .untracked(),
563            )
564            .map(|_| ())
565            .map_err(|e| format!("{e:?}"))
566    }
567
568    pub fn show<K: Key>(
569        mut self,
570        ui: &mut Ui,
571        state: &mut TableState<K>,
572        rows: &mut dyn TableRows<K>,
573    ) -> TableOutput<K> {
574        let id = Id::unique(("egui_pop_views::table", &self.id));
575        self.read_store(state);
576        state
577            .columns
578            .retain(|c| self.columns.iter().any(|col| &col.id == c));
579        if let Some(service) = self.shared_columns
580            && state.seen != Some(service.revision())
581        {
582            state.seen = Some(service.revision());
583            let items: std::collections::HashSet<SelectionItem> =
584                service.items().into_iter().collect();
585            state.columns = self
586                .columns
587                .iter()
588                .filter(|c| items.contains(&column_item(&c.id)))
589                .map(|c| c.id.clone())
590                .collect();
591        }
592        let shared_hover = self.shared_columns.and_then(|service| {
593            self.columns
594                .iter()
595                .find(|c| service.is_hovered(&column_item(&c.id)))
596                .map(|c| c.id.clone())
597        });
598        let len = rows.len();
599        list::retain(&mut state.selection, &mut state.len, len, &|i| rows.key(i));
600        let row_h = self.row_height.unwrap_or_else(|| rows::height(ui));
601        let focused = ui.memory(|m| m.has_focus(id));
602        let mut proposals = Vec::new();
603        let mut late = Vec::new();
604        if focused {
605            let (p, reveal, activate) = nav::flat(
606                ui,
607                &state.selection,
608                self.mode,
609                len,
610                &|i| rows.key(i),
611                &|i| rows.label(i),
612                state.page,
613                &mut state.type_ahead,
614            );
615            proposals = p;
616            if reveal.is_some() {
617                state.reveal = reveal;
618            }
619            late.extend(activate.map(|key| Signal::Activate { key }));
620        }
621
622        let columns: Vec<egui_table::Column> = self
623            .columns
624            .iter()
625            .zip(&state.widths)
626            .map(|(c, w)| {
627                egui_table::Column::new(*w)
628                    .range(c.min_width..=f32::INFINITY)
629                    .resizable(c.resizable)
630                    .id(Id::unique(("column", &c.id)))
631            })
632            .collect();
633        let mut table = egui_table::Table::new()
634            .id_salt(id)
635            .num_rows(len as u64)
636            .columns(columns.clone())
637            .headers([HeaderRow::new(row_h + 4.0)])
638            .auto_size_mode(egui_table::AutoSizeMode::Never)
639            .stick_to_bottom(self.stick_to_bottom);
640        if let Some(r) = state.reveal.take() {
641            table = table.scroll_to_row(r as u64, None);
642        }
643        // The widths the store holds go to `egui_table`'s own state, when
644        // they changed (not during a resize).
645        let mut delegate = Delegate {
646            rows,
647            columns: self.columns,
648            selection: &state.selection,
649            sort: state.sort.as_ref(),
650            mode: self.mode,
651            len,
652            focused,
653            cursor_row: None,
654            proposals: &mut proposals,
655            late: &mut late,
656            drag_out: self.drag_out,
657            carry: state.carry.take(),
658            sort_to: None,
659            page: state.page,
660            take_focus: false,
661            row_h,
662            kit: Kit::of(ui.ctx()),
663            select_columns: self.select_columns,
664            selected_columns: &state.columns,
665            tinted: state.hovered_column.clone().or(shared_hover),
666            hovered_column: None,
667            header_clicked: None,
668            column_click: None,
669            header_menu: self.header_menu.take(),
670            header_icons: &self.header_icons,
671            visible_rows: 0..0,
672        };
673        let widths = &state.widths;
674        let given = &mut state.given;
675        let draw = |ui: &mut Ui| {
676            // `egui_table` keeps its state under the drawing ui's id.
677            let table_id = table.get_id(ui);
678            if given.as_ref() != Some(widths) {
679                let mut ts = egui_table::TableState::load(ui.ctx(), table_id).unwrap_or_default();
680                for (i, c) in columns.iter().enumerate() {
681                    ts.col_widths.insert(c.id_for(i), widths[i]);
682                }
683                ts.parent_width = Some(ui.available_width());
684                ts.store(ui.ctx(), table_id);
685                *given = Some(widths.clone());
686            }
687            (table.show(ui, &mut delegate), table_id)
688        };
689        let (inner, table_id) = match self.height {
690            Some(h) => {
691                ui.allocate_ui(egui::vec2(ui.available_width(), h), |ui| {
692                    ui.set_min_height(h);
693                    draw(ui)
694                })
695                .inner
696            }
697            None => draw(ui),
698        };
699        // upstream: egui_table says nothing of its scroll area, so what overflows
700        // comes from the sizes it was given.
701        let wide = state.widths.iter().sum::<f32>();
702        let tall = delegate.rows.row_top(len, row_h) + row_h + 4.0;
703        egui_pop_core::ui::contain_wheel_in(
704            ui,
705            inner.rect,
706            [
707                wide > inner.rect.width() + 0.5,
708                tall > inner.rect.height() + 0.5,
709            ],
710        );
711        let take_focus = delegate.take_focus;
712        let sort_to = delegate.sort_to.take();
713        let hovered_column = delegate.hovered_column.take();
714        let header_clicked = delegate.header_clicked.take();
715        let column_click = delegate.column_click.take();
716        let visible_rows = delegate.visible_rows.clone();
717        let page = delegate.page;
718        let cursor_row = delegate.cursor_row;
719        let mut carry = delegate.carry.take();
720        drop(delegate);
721        rows::carry(ui, &mut carry);
722        state.carry = carry;
723        if hovered_column != state.hovered_column {
724            state.hovered_column = hovered_column.clone();
725            ui.ctx().request_repaint();
726        }
727        if let Some(service) = self.shared_columns {
728            service.hover(
729                &self.id,
730                hovered_column.as_deref().map(column_item).as_ref(),
731            );
732        }
733        state.page = page;
734        let label = self
735            .label
736            .clone()
737            .unwrap_or_else(|| tr(ui.ctx(), &s::TABLE));
738        let response = ui.interact(inner.rect, id, Sense::focusable_noninteractive());
739        egui_pop_core::a11y::name(&response, Role::Table, &label);
740        let shape = (len, self.columns.len());
741        ui.ctx().accesskit_node_builder(id, |node| {
742            node.set_row_count(shape.0);
743            node.set_column_count(shape.1);
744        });
745        rows::active_row(ui, id, cursor_row);
746        if response.has_focus() {
747            // Its cursor row shows it.
748            egui_pop_core::focus::own_ring(ui.ctx(), id);
749            ui.memory_mut(|m| {
750                m.set_focus_lock_filter(
751                    id,
752                    egui::EventFilter {
753                        horizontal_arrows: true,
754                        vertical_arrows: true,
755                        ..Default::default()
756                    },
757                )
758            });
759        }
760        if take_focus {
761            response.request_focus();
762        }
763        // upstream: egui_table's resize handles have no name (see
764        // docs/upstream.md).
765        for (i, c) in columns.iter().enumerate() {
766            if let Some(r) = ui
767                .ctx()
768                .read_response(table_id.with(c.id_for(i)).with("resize"))
769            {
770                let name = format!("{} ↔", self.columns[i].title);
771                r.widget_info(move || WidgetInfo::labeled(Role::Splitter, true, &name));
772            }
773        }
774
775        let mut signals = list::run(
776            self.app,
777            &TABLE_SELECT,
778            "table",
779            &self.id,
780            &mut state.selection,
781            proposals,
782        );
783        let mut sorted = false;
784        if let Some(to) = sort_to {
785            let mut done = to.clone();
786            let outcome = steps::run(
787                self.app,
788                &TABLE_SORT,
789                json!({
790                    "table": self.id,
791                    "column": to.as_ref().map(|s| &s.column),
792                    "descending": to.as_ref().is_some_and(|s| s.descending),
793                }),
794                |args| {
795                    done = args["column"].as_str().map(|c| Sort {
796                        column: c.into(),
797                        descending: args["descending"].as_bool().unwrap_or(false),
798                    });
799                    self.write_store("sort", Value::Text(Sort::encode(done.as_ref())))?;
800                    Ok(Json::String(Sort::encode(done.as_ref())))
801                },
802            );
803            match outcome {
804                Outcome::Done(Ok(_)) => {
805                    state.sort = done;
806                    sorted = true;
807                }
808                Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
809                    signals.push(Signal::Vetoed {
810                        step: TABLE_SORT,
811                        reason,
812                    })
813                }
814            }
815        }
816
817        // A resize ends: its widths go through the step to the store.
818        let mut resized = false;
819        let now: Vec<f32> = egui_table::TableState::load(ui.ctx(), table_id)
820            .map(|ts| {
821                columns
822                    .iter()
823                    .enumerate()
824                    .map(|(i, c)| {
825                        ts.col_widths
826                            .get(&c.id_for(i))
827                            .copied()
828                            .unwrap_or(c.current)
829                    })
830                    .collect()
831            })
832            .unwrap_or_else(|| state.widths.clone());
833        let dragging = ui.input(|i| i.pointer.any_down());
834        if !dragging && now != state.widths {
835            let mut done = now.clone();
836            let outcome = steps::run(
837                self.app,
838                &TABLE_RESIZE,
839                json!({ "table": self.id, "widths": now }),
840                |args| {
841                    done = serde_json::from_value(args["widths"].clone())
842                        .map_err(|e| e.to_string())?;
843                    if done.len() != self.columns.len() {
844                        return Err("one width per column".into());
845                    }
846                    self.write_store(
847                        "widths",
848                        Value::Floats(done.iter().map(|&w| f64::from(w)).collect()),
849                    )?;
850                    Ok(json!(done))
851                },
852            );
853            match outcome {
854                Outcome::Done(Ok(_)) => {
855                    state.widths = done;
856                    resized = true;
857                }
858                Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
859                    signals.push(Signal::Vetoed {
860                        step: TABLE_RESIZE,
861                        reason,
862                    })
863                }
864            }
865            // Given again: what was decided, not what was dragged.
866            state.given = None;
867        }
868        // A header click selecting columns.
869        let mut columns_selected = false;
870        if let Some((column, mods)) = column_click {
871            let before = state.columns.clone();
872            let to = column_selection(
873                self.columns,
874                &state.columns,
875                state.column_anchor.as_deref(),
876                &column,
877                mods,
878            );
879            let mut done = to.clone();
880            let outcome = steps::run(
881                self.app,
882                &TABLE_SELECT_COLUMNS,
883                json!({ "table": self.id, "columns": to }),
884                |args| {
885                    done = serde_json::from_value(args["columns"].clone())
886                        .map_err(|e| e.to_string())?;
887                    Ok(json!(done))
888                },
889            );
890            match outcome {
891                Outcome::Done(Ok(_)) => {
892                    if !mods.shift {
893                        state.column_anchor = Some(column);
894                    }
895                    if done != before {
896                        state.columns = done;
897                        columns_selected = true;
898                        if let Some(service) = self.shared_columns {
899                            let item_of = |c: &String| column_item(c);
900                            crate::shared::write(
901                                service,
902                                &self.id,
903                                &before,
904                                &state.columns,
905                                mods.command,
906                                &item_of,
907                            );
908                            state.seen = Some(service.revision());
909                        }
910                    }
911                }
912                Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
913                    signals.push(Signal::Vetoed {
914                        step: TABLE_SELECT_COLUMNS,
915                        reason,
916                    })
917                }
918            }
919        }
920        signals.extend(late);
921        if !signals.is_empty() || sorted || resized || columns_selected {
922            ui.ctx().request_repaint();
923        }
924        TableOutput {
925            response,
926            signals,
927            sorted,
928            resized,
929            columns_selected,
930            hovered_column,
931            header_clicked,
932            visible_rows,
933        }
934    }
935}
936
937/// The columns selected after a header click on `column`: alone, or
938/// toggled with Ctrl, or the run from `anchor` with Shift (added to the
939/// selection with Ctrl too), in the columns' order.
940pub fn column_selection(
941    columns: &[Column],
942    current: &[String],
943    anchor: Option<&str>,
944    column: &str,
945    mods: egui::Modifiers,
946) -> Vec<String> {
947    let index = |id: &str| columns.iter().position(|c| c.id == id);
948    let mut out: Vec<String> = if mods.shift {
949        let to = index(column);
950        let from = anchor.and_then(index).or(to);
951        let mut run = match (from, to) {
952            (Some(a), Some(b)) => columns[a.min(b)..=a.max(b)]
953                .iter()
954                .map(|c| c.id.clone())
955                .collect(),
956            _ => vec![column.to_string()],
957        };
958        if mods.command {
959            run.extend(current.iter().cloned());
960        }
961        run
962    } else if mods.command {
963        let mut v = current.to_vec();
964        match v.iter().position(|c| c == column) {
965            Some(i) => {
966                v.remove(i);
967            }
968            None => v.push(column.to_string()),
969        }
970        v
971    } else {
972        vec![column.to_string()]
973    };
974    // In the columns' order, once each.
975    out.sort_by_key(|c| index(c).unwrap_or(usize::MAX));
976    out.dedup();
977    out
978}
979
980struct Delegate<'a, K: Key> {
981    rows: &'a mut dyn TableRows<K>,
982    columns: &'a [Column],
983    selection: &'a Selection<K>,
984    sort: Option<&'a Sort>,
985    mode: Mode,
986    len: usize,
987    focused: bool,
988    proposals: &'a mut Vec<Proposal<K>>,
989    /// Activations and drags out, after the selection's signals.
990    late: &'a mut Vec<Signal<K>>,
991    drag_out: bool,
992    /// How many rows a drag out carries, while it lasts.
993    carry: Option<usize>,
994    sort_to: Option<Option<Sort>>,
995    page: usize,
996    take_focus: bool,
997    row_h: f32,
998    /// Fetched once per pass, for every row and header.
999    kit: std::sync::Arc<Kit>,
1000    select_columns: bool,
1001    selected_columns: &'a [String],
1002    /// The column tinted as hovered: under the pointer at the last pass,
1003    /// or hovered elsewhere (the shared selection).
1004    tinted: Option<String>,
1005    /// The column under the pointer this pass.
1006    hovered_column: Option<String>,
1007    header_clicked: Option<String>,
1008    /// A header click selecting its column, with the modifiers held.
1009    column_click: Option<(String, egui::Modifiers)>,
1010    header_menu: Option<HeaderMenu<'a>>,
1011    header_icons: &'a [HeaderIcon],
1012    /// The rows in view, as `egui_table` prepared them.
1013    visible_rows: std::ops::Range<usize>,
1014    /// The cursor row's widget, read by a screen reader as the arrows move.
1015    cursor_row: Option<egui::Id>,
1016}
1017
1018impl<K: Key> Delegate<'_, K> {
1019    /// The fill a column's parts take when it is selected or hovered:
1020    /// the table row's in that state (selected wins), `None` otherwise.
1021    fn column_fill(&self, column: &str) -> Option<egui::Color32> {
1022        let state = if self.selected_columns.iter().any(|c| c == column) {
1023            State::SELECTED
1024        } else if self.tinted.as_deref() == Some(column) {
1025            State::HOVER
1026        } else {
1027            return None;
1028        };
1029        Some(self.kit.table_row.style(state).fill)
1030    }
1031
1032    /// Tints a cell of a selected or hovered column, at half strength so
1033    /// a selected row still shows through.
1034    fn tint(&self, ui: &Ui, column: &str, rect: egui::Rect) {
1035        if let Some(fill) = self.column_fill(column) {
1036            ui.painter()
1037                .rect_filled(rect, 0.0, fill.gamma_multiply(0.5));
1038        }
1039    }
1040
1041    /// Marks a selected or hovered column's header with a bar along its
1042    /// bottom, in the full fill, leaving its title as it is.
1043    fn mark_header(&self, ui: &Ui, column: &str, rect: egui::Rect) {
1044        if let Some(fill) = self.column_fill(column) {
1045            let h = (rect.height() * 0.1).clamp(2.0, 4.0);
1046            let bar =
1047                egui::Rect::from_min_max(egui::pos2(rect.left(), rect.bottom() - h), rect.max);
1048            ui.painter().rect_filled(bar, 0.0, fill);
1049        }
1050    }
1051}
1052
1053impl<K: Key> TableDelegate for Delegate<'_, K> {
1054    fn prepare(&mut self, info: &PrefetchInfo) {
1055        // upstream: the range is reversed for a table clipped away, scrolled out
1056        // of a scroll area around it.
1057        let n = info
1058            .visible_rows
1059            .end
1060            .saturating_sub(info.visible_rows.start) as usize;
1061        self.page = n.saturating_sub(2).max(1);
1062        let start = (info.visible_rows.start as usize).min(self.len);
1063        let end = (info.visible_rows.end as usize).clamp(start, self.len);
1064        self.visible_rows = start..end;
1065    }
1066
1067    fn header_cell_ui(&mut self, ui: &mut Ui, cell: &HeaderCellInfo) {
1068        // upstream: called for an empty sticky region too (see
1069        // docs/upstream.md).
1070        if ui.clip_rect().width() <= 0.0 {
1071            return;
1072        }
1073        let Some(c) = self.columns.get(cell.col_range.start) else {
1074            return;
1075        };
1076        let rect = ui.max_rect();
1077        let sorted = self.sort.filter(|s| s.column == c.id);
1078        let name = match sorted {
1079            Some(s) if s.descending => tr_args(ui.ctx(), &s::SORTED_DOWN, &[("column", &c.title)]),
1080            Some(_) => tr_args(ui.ctx(), &s::SORTED_UP, &[("column", &c.title)]),
1081            None => c.title.clone(),
1082        };
1083        let header = SortHeader {
1084            title: &c.title,
1085            name: &name,
1086            descending: sorted.map(|s| s.descending),
1087            // Clickable when a click does something, and for its menu.
1088            sortable: c.sortable || self.select_columns || self.header_menu.is_some(),
1089        };
1090        let id = ui.scope_id().with("sort");
1091        let icon = self.header_icons.iter().find(|h| h.column == c.id);
1092        let r = match icon {
1093            Some(h) => {
1094                let glyph = egui_pop_core::icon::registry::resolve(&h.icon, "table header")
1095                    .unwrap_or(egui_pop_core::icon::PLACEHOLDER);
1096                header
1097                    .show_icon(ui, &self.kit, rect, id, glyph)
1098                    .on_hover_text(&h.tip)
1099            }
1100            None => header.show(ui, &self.kit, rect, id),
1101        };
1102        self.mark_header(ui, &c.id, rect);
1103        if self.select_columns {
1104            let selected = self.selected_columns.contains(&c.id);
1105            r.widget_info(|| WidgetInfo::selected(Role::Button, true, selected, &name));
1106        }
1107        if r.hovered() {
1108            self.hovered_column = Some(c.id.clone());
1109        }
1110        if r.clicked() {
1111            self.header_clicked = Some(c.id.clone());
1112            if self.select_columns {
1113                self.column_click = Some((c.id.clone(), ui.input(|i| i.modifiers)));
1114            } else if c.sortable {
1115                self.sort_to = Some(Sort::next(self.sort, &c.id));
1116            }
1117        }
1118        let current = self.sort.filter(|s| s.column == c.id).cloned();
1119        let menu = &mut self.header_menu;
1120        let mut sort_to = None;
1121        r.context_menu(|ui| {
1122            if c.sortable {
1123                let entry = |ui: &mut Ui, key, to: Option<Sort>| {
1124                    let on = current == to;
1125                    egui_pop_core::widgets::selectable_label(ui, on, tr(ui.ctx(), key))
1126                        .clicked()
1127                        .then_some(to)
1128                };
1129                let up = Some(Sort {
1130                    column: c.id.clone(),
1131                    descending: false,
1132                });
1133                let down = Some(Sort {
1134                    column: c.id.clone(),
1135                    descending: true,
1136                });
1137                for (key, to) in [
1138                    (&s::SORT_ASCENDING, up),
1139                    (&s::SORT_DESCENDING, down),
1140                    (&s::SORT_CLEAR, None),
1141                ] {
1142                    if let Some(to) = entry(ui, key, to) {
1143                        sort_to = Some(to);
1144                        ui.close();
1145                    }
1146                }
1147            }
1148            if let Some(HeaderMenu(add)) = menu {
1149                if c.sortable {
1150                    ui.separator();
1151                }
1152                add(ui, &c.id);
1153            }
1154        });
1155        egui_pop_core::overlay::follow_menu(&r, "column menu");
1156        if let Some(to) = sort_to
1157            && to.as_ref() != self.sort
1158        {
1159            self.sort_to = Some(to);
1160        }
1161    }
1162
1163    fn row_ui(&mut self, ui: &mut Ui, row_nr: u64) {
1164        let row = row_nr as usize;
1165        // upstream: called for an empty sticky region too (see
1166        // docs/upstream.md).
1167        if ui.clip_rect().width() <= 0.0 || row >= self.len {
1168            return;
1169        }
1170        let key = self.rows.key(row);
1171        let rect = ui.max_rect();
1172        let sense = if self.drag_out {
1173            rows::ROW_SENSE
1174        } else {
1175            Sense::CLICK
1176        };
1177        let r = ui.interact(rect, ui.scope_id().with("select"), sense);
1178        let selected = self.selection.contains(&key);
1179        let cursor = self.focused && self.selection.cursor() == Some(&key);
1180        if cursor {
1181            self.cursor_row = Some(r.id);
1182        }
1183        let state = rows::state(
1184            selected,
1185            r.hovered(),
1186            cursor && egui_pop_core::focus::ring_shown(&r.ctx),
1187        );
1188        if row % 2 == 1 && !selected {
1189            self.kit.table_stripe.paint(
1190                &KitCx {
1191                    painter: ui.painter(),
1192                    ppp: ui.ctx().pixels_per_point(),
1193                },
1194                &Part {
1195                    rect,
1196                    room: rect,
1197                    state: State::REST,
1198                    label: None,
1199                },
1200            );
1201        }
1202        rows::paint(ui, &self.kit.table_row, rect, state);
1203        if selected {
1204            ui.visuals_mut().override_text_color =
1205                Some(rows::text_color(&self.kit.table_row, state));
1206        }
1207        let name = self.rows.label(row);
1208        r.widget_info(move || WidgetInfo::selected(Role::Button, true, selected, &name));
1209        if r.double_clicked() {
1210            self.late.push(Signal::Activate { key: key.clone() });
1211        } else if r.clicked() {
1212            self.take_focus = true;
1213            let mods = ui.input(|i| i.modifiers);
1214            let rows = &*self.rows;
1215            self.proposals.push(self.selection.click(
1216                self.mode,
1217                self.len,
1218                &|i| rows.key(i),
1219                row,
1220                mods,
1221            ));
1222        }
1223        if self.drag_out && r.drag_started() {
1224            let keys = rows::carried(self.selection, key);
1225            self.carry = Some(keys.len());
1226            self.late.push(Signal::DragOut { keys });
1227        }
1228    }
1229
1230    fn cell_ui(&mut self, ui: &mut Ui, cell: &CellInfo) {
1231        let row = cell.row_nr as usize;
1232        if row >= self.len {
1233            return;
1234        }
1235        let selected = self.selection.contains(&self.rows.key(row));
1236        if let Some(c) = self.columns.get(cell.col_nr) {
1237            let rect = ui.max_rect();
1238            self.tint(ui, &c.id, rect);
1239            if ui.rect_contains_pointer(rect) {
1240                self.hovered_column = Some(c.id.clone());
1241            }
1242        }
1243        // The row's border, whatever its state, never moves the content:
1244        // the first cell keeps the room of its widest one.
1245        let room = if cell.col_nr == 0 {
1246            self.kit.table_row.border_room(ui.ctx().pixels_per_point())
1247        } else {
1248            0.0
1249        };
1250        ui.add_space(ui.spacing().item_spacing.x + room);
1251        // A text too long for its cell is elided with "…" (an egui label
1252        // then shows the full text on hover), not cut at the cell's edge.
1253        ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
1254        // A selectable label senses clicks and sits above the row: a
1255        // click on a cell's text would select the text instead of the
1256        // row. An elided label still shows its full text on hover.
1257        ui.style_mut().interaction.selectable_labels = false;
1258        self.rows.cell(ui, row, cell.col_nr, selected);
1259    }
1260
1261    fn row_top_offset(&self, _ctx: &egui::Context, _table_id: Id, row_nr: u64) -> f32 {
1262        self.rows.row_top(row_nr as usize, self.row_h)
1263    }
1264
1265    fn default_row_height(&self) -> f32 {
1266        self.row_h
1267    }
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    use super::*;
1273
1274    #[test]
1275    fn a_header_click_sorts_up_then_down_then_not() {
1276        let up = Sort::next(None, "name");
1277        assert_eq!(Sort::encode(up.as_ref()), "name");
1278        let down = Sort::next(up.as_ref(), "name");
1279        assert_eq!(Sort::encode(down.as_ref()), "-name");
1280        assert_eq!(Sort::next(down.as_ref(), "name"), None);
1281        assert_eq!(Sort::next(down.as_ref(), "size"), Sort::decode("size"));
1282        assert_eq!(Sort::decode(""), None);
1283    }
1284
1285    #[test]
1286    fn a_header_click_selects_toggles_or_extends_columns() {
1287        use egui::Modifiers;
1288        let cols: Vec<Column> = ["a", "b", "c", "d"]
1289            .iter()
1290            .map(|id| Column::new(*id, *id))
1291            .collect();
1292        let sel = |current: &[&str], anchor, column, mods| {
1293            let current: Vec<String> = current.iter().map(|s| s.to_string()).collect();
1294            column_selection(&cols, &current, anchor, column, mods)
1295        };
1296        assert_eq!(sel(&["a"], Some("a"), "c", Modifiers::NONE), ["c"]);
1297        assert_eq!(sel(&["c"], Some("c"), "a", Modifiers::COMMAND), ["a", "c"]);
1298        assert_eq!(sel(&["a", "c"], Some("a"), "c", Modifiers::COMMAND), ["a"]);
1299        assert_eq!(
1300            sel(&["b"], Some("b"), "d", Modifiers::SHIFT),
1301            ["b", "c", "d"]
1302        );
1303        assert_eq!(
1304            sel(
1305                &["a"],
1306                Some("c"),
1307                "d",
1308                Modifiers::SHIFT | Modifiers::COMMAND
1309            ),
1310            ["a", "c", "d"]
1311        );
1312        // No anchor yet: the column alone.
1313        assert_eq!(sel(&[], None, "b", Modifiers::SHIFT), ["b"]);
1314        assert_eq!(column_item("size").as_str(), "column:size");
1315    }
1316}