Skip to main content

gpui_table_runtime/
ordering.rs

1//! Ordering application and selection snapshots for generated table delegates.
2
3use gpui_kit::Context;
4use gpui_kit::component::table::{TableDelegate, TableSelection, TableState};
5use gpui_table_core::sort::{SortError, SortOrder};
6
7/// Ordering of the delegate's loaded rows. Backend ordering remains caller-owned.
8pub trait OrderedTableDelegate: TableDelegate {
9    type RowId: Clone + Eq;
10    fn ordering(&self) -> &SortOrder;
11    fn set_ordering(&mut self, ordering: SortOrder) -> Result<(), SortError>;
12    fn visible_row_id(&self, row_ix: usize) -> Option<Self::RowId>;
13    fn visible_row_position(&self, id: &Self::RowId) -> Option<usize>;
14}
15
16/// Capture before changing rows or ordering, then restore by stable row identity.
17pub struct TableRowSelection<Id> {
18    row: Option<Id>,
19    selection: TableSelection,
20}
21
22impl<Id: Clone + Eq> TableRowSelection<Id> {
23    pub fn capture<D: OrderedTableDelegate<RowId = Id>>(table: &TableState<D>) -> Self {
24        let selection = table.selection();
25        let row_ix = match selection {
26            TableSelection::Row(ix) | TableSelection::Cell(ix, _) => Some(ix),
27            _ => None,
28        };
29        Self {
30            row: row_ix.and_then(|ix| table.delegate().visible_row_id(ix)),
31            selection,
32        }
33    }
34
35    pub fn restore<D: OrderedTableDelegate<RowId = Id>>(
36        self,
37        table: &mut TableState<D>,
38        cx: &mut Context<TableState<D>>,
39    ) {
40        let selection = match (self.row, self.selection) {
41            (Some(id), TableSelection::Row(_)) => table
42                .delegate()
43                .visible_row_position(&id)
44                .map(TableSelection::Row)
45                .unwrap_or_default(),
46            (Some(id), TableSelection::Cell(_, col)) => table
47                .delegate()
48                .visible_row_position(&id)
49                .map(|ix| TableSelection::Cell(ix, col))
50                .unwrap_or_default(),
51            (_, selection) => selection,
52        };
53        table.set_selection(selection, cx);
54    }
55}
56
57/// Apply controlled ordering while keeping row/cell selection on the same record.
58/// This sorts loaded rows only; send the same order to a backend for complete-result ordering.
59pub fn set_table_ordering<D: OrderedTableDelegate>(
60    table: &mut TableState<D>,
61    ordering: SortOrder,
62    cx: &mut Context<TableState<D>>,
63) -> Result<(), SortError> {
64    let selected = TableRowSelection::capture(table);
65    table.delegate_mut().set_ordering(ordering)?;
66    table.refresh(cx);
67    selected.restore(table, cx);
68    cx.notify();
69    Ok(())
70}