Skip to main content

gpui_table_runtime/
selection.rs

1//! Delegate-owned multiple selection composed with the public GPUI Kit table.
2use crate::OrderedTableDelegate;
3use gpui_kit::component::{
4    ActiveTheme as _,
5    table::{TableSelection, TableState},
6};
7use gpui_kit::{
8    App, Context, Div, Entity, Focusable as _, InteractiveElement as _, Modifiers, Stateful,
9    StatefulInteractiveElement as _, Styled as _, Window, div, prelude::FluentBuilder as _,
10};
11
12#[derive(Clone, Default)]
13pub struct RowSelectionState {
14    enabled: bool,
15    rows: Vec<usize>,
16    cursor: Option<usize>,
17    anchor: Option<usize>,
18    revision: u64,
19    preserve_unavailable: bool,
20}
21
22pub fn new_multi_row_table<D: OrderedTableDelegate>(
23    mut delegate: D,
24    window: &mut Window,
25    cx: &mut Context<TableState<D>>,
26) -> TableState<D> {
27    if let Some(selection) = delegate.row_selection_mut() {
28        selection.enabled = true;
29    }
30    TableState::new(delegate, window, cx).select_on_modifier_click(false)
31}
32
33pub fn enable_row_selection<D: OrderedTableDelegate>(table: &mut TableState<D>) {
34    if let Some(state) = table.delegate_mut().row_selection_mut() {
35        state.enabled = true;
36    }
37}
38
39pub fn selected_rows<D: OrderedTableDelegate>(table: &TableState<D>) -> Vec<usize> {
40    if let Some(state) = table
41        .delegate()
42        .row_selection()
43        .filter(|state| state.enabled)
44    {
45        return state.rows.clone();
46    }
47    table.selected_row().into_iter().collect()
48}
49pub fn selection_revision<D: OrderedTableDelegate>(table: &TableState<D>) -> u64 {
50    table
51        .delegate()
52        .row_selection()
53        .map_or(0, |state| state.revision)
54}
55pub fn preserves_unavailable_rows<D: OrderedTableDelegate>(table: &TableState<D>) -> bool {
56    table
57        .delegate()
58        .row_selection()
59        .is_some_and(|state| state.preserve_unavailable)
60}
61pub fn row_selection_cursor<D: OrderedTableDelegate>(table: &TableState<D>) -> Option<usize> {
62    table
63        .delegate()
64        .row_selection()
65        .filter(|state| state.enabled)
66        .and_then(|state| state.cursor)
67        .or(table.selected_row())
68}
69pub fn row_selection_anchor<D: OrderedTableDelegate>(table: &TableState<D>) -> Option<usize> {
70    table
71        .delegate()
72        .row_selection()
73        .filter(|state| state.enabled)
74        .and_then(|state| state.anchor)
75        .or(table.selected_row())
76}
77
78pub fn restore_rows<D: OrderedTableDelegate>(
79    table: &mut TableState<D>,
80    mut rows: Vec<usize>,
81    cursor: Option<usize>,
82    anchor: Option<usize>,
83    cx: &mut Context<TableState<D>>,
84) {
85    let count = table.delegate().rows_count(cx);
86    rows.retain(|row| *row < count);
87    rows.sort_unstable();
88    rows.dedup();
89    let cursor = cursor
90        .filter(|row| *row < count)
91        .or_else(|| rows.first().copied());
92    let primary = cursor
93        .filter(|row| rows.contains(row))
94        .or_else(|| rows.first().copied());
95    if let Some(state) = table.delegate_mut().row_selection_mut() {
96        state.rows = rows;
97        state.cursor = cursor;
98        state.anchor = anchor.filter(|row| *row < count).or(cursor);
99    }
100    match primary {
101        Some(row) => table.set_selected_row(row, cx),
102        None => table.clear_selection(cx),
103    }
104    cx.notify();
105}
106
107pub fn select_row<D: OrderedTableDelegate>(
108    table: &mut TableState<D>,
109    row: usize,
110    modifiers: Modifiers,
111    cx: &mut Context<TableState<D>>,
112) {
113    if !table.row_selectable || row >= table.delegate().rows_count(cx) {
114        return;
115    }
116    let enabled = table
117        .delegate()
118        .row_selection()
119        .is_some_and(|state| state.enabled);
120    let additive = enabled && modifiers.secondary(cx);
121    let anchor = if enabled && modifiers.shift {
122        row_selection_anchor(table)
123            .or(row_selection_cursor(table))
124            .unwrap_or(row)
125    } else {
126        row
127    };
128    let mut rows = if additive {
129        selected_rows(table)
130    } else {
131        Vec::new()
132    };
133    if enabled && modifiers.shift {
134        rows.extend(anchor.min(row)..=anchor.max(row));
135    } else if additive && rows.contains(&row) {
136        rows.retain(|selected| *selected != row);
137    } else {
138        rows.push(row);
139    }
140    if let Some(state) = table.delegate_mut().row_selection_mut() {
141        state.revision = state.revision.wrapping_add(1);
142        state.preserve_unavailable = additive;
143    }
144    restore_rows(table, rows, Some(row), Some(anchor), cx);
145}
146
147pub fn clear_selection<D: OrderedTableDelegate>(
148    table: &mut TableState<D>,
149    cx: &mut Context<TableState<D>>,
150) {
151    if let Some(state) = table.delegate_mut().row_selection_mut() {
152        state.revision = state.revision.wrapping_add(1);
153        state.preserve_unavailable = false;
154    }
155    restore_rows(table, Vec::new(), None, None, cx);
156}
157
158pub fn decorate_row<D: OrderedTableDelegate>(
159    row: Stateful<Div>,
160    index: usize,
161    selection: &RowSelectionState,
162    window: &mut Window,
163    cx: &mut Context<TableState<D>>,
164) -> Stateful<Div> {
165    if !selection.enabled {
166        return row;
167    }
168    let selected = selection.rows.contains(&index);
169    row.when(selected, |row| row.bg(cx.theme().table_active))
170        .on_click(window.listener_for(
171            &cx.entity(),
172            move |table, event: &gpui_kit::ClickEvent, window, cx| {
173                table.focus_handle(cx).focus(window, cx);
174                select_row(table, index, event.modifiers(), cx);
175                cx.stop_propagation();
176            },
177        ))
178}
179
180/// Wrap tables or alternate card/grid presentations sharing the delegate.
181pub fn selection_container<D: OrderedTableDelegate>(
182    table: &Entity<TableState<D>>,
183    window: &mut Window,
184    cx: &App,
185) -> Stateful<Div> {
186    selection_scope(table, window, cx)
187        .key_context("DataTable")
188        .track_focus(&table.focus_handle(cx))
189}
190
191/// Captures selection commands above an existing native table focus owner.
192pub fn selection_scope<D: OrderedTableDelegate>(
193    table: &Entity<TableState<D>>,
194    window: &mut Window,
195    cx: &App,
196) -> Stateful<Div> {
197    let focus = table.focus_handle(cx);
198    div()
199        .id("table-selection")
200        .capture_action(window.listener_for(
201            table,
202            |table, _: &gpui_kit::base::actions::Cancel, window, cx| {
203                if !handle_navigation(table, "escape", window.modifiers(), window, cx) {
204                    cx.propagate();
205                }
206            },
207        ))
208        .capture_action(window.listener_for(
209            table,
210            |table, _: &gpui_kit::base::actions::SelectUp, window, cx| {
211                if !handle_navigation(table, "up", window.modifiers(), window, cx) {
212                    cx.propagate();
213                }
214            },
215        ))
216        .capture_action(window.listener_for(
217            table,
218            |table, _: &gpui_kit::base::actions::SelectDown, window, cx| {
219                if !handle_navigation(table, "down", window.modifiers(), window, cx) {
220                    cx.propagate();
221                }
222            },
223        ))
224        .capture_action(window.listener_for(
225            table,
226            |table, _: &gpui_kit::base::actions::SelectFirst, window, cx| {
227                if !handle_navigation(table, "home", window.modifiers(), window, cx) {
228                    cx.propagate();
229                }
230            },
231        ))
232        .capture_action(window.listener_for(
233            table,
234            |table, _: &gpui_kit::base::actions::SelectLast, window, cx| {
235                if !handle_navigation(table, "end", window.modifiers(), window, cx) {
236                    cx.propagate();
237                }
238            },
239        ))
240        .capture_action(window.listener_for(
241            table,
242            |table, _: &gpui_kit::base::actions::SelectPageUp, window, cx| {
243                if !handle_navigation(table, "pageup", window.modifiers(), window, cx) {
244                    cx.propagate();
245                }
246            },
247        ))
248        .capture_action(window.listener_for(
249            table,
250            |table, _: &gpui_kit::base::actions::SelectPageDown, window, cx| {
251                if !handle_navigation(table, "pagedown", window.modifiers(), window, cx) {
252                    cx.propagate();
253                }
254            },
255        ))
256        .capture_key_down(window.listener_for(
257            table,
258            move |table, event: &gpui_kit::KeyDownEvent, window, cx| {
259                if focus.is_focused(window) {
260                    handle_navigation(
261                        table,
262                        &event.keystroke.key,
263                        event.keystroke.modifiers,
264                        window,
265                        cx,
266                    );
267                }
268            },
269        ))
270}
271
272fn handle_navigation<D: OrderedTableDelegate>(
273    table: &mut TableState<D>,
274    key: &str,
275    modifiers: Modifiers,
276    window: &mut Window,
277    cx: &mut Context<TableState<D>>,
278) -> bool {
279    if !table.focus_handle(cx).is_focused(window)
280        || !table
281            .delegate()
282            .row_selection()
283            .is_some_and(|state| state.enabled)
284        || matches!(
285            table.selection(),
286            TableSelection::Cell(..) | TableSelection::Column(..)
287        )
288    {
289        return false;
290    }
291    let count = table.delegate().rows_count(cx);
292    if key == "escape" {
293        clear_selection(table, cx);
294    } else if key == "a" && modifiers.secondary(cx) {
295        if let Some(state) = table.delegate_mut().row_selection_mut() {
296            state.revision = state.revision.wrapping_add(1);
297            state.preserve_unavailable = false;
298        }
299        restore_rows(
300            table,
301            (0..count).collect(),
302            row_selection_cursor(table).or((count > 0).then_some(0)),
303            row_selection_anchor(table),
304            cx,
305        );
306    } else if count > 0 {
307        let cursor = row_selection_cursor(table);
308        let row = match key {
309            "down" => cursor.map_or(0, |row| (row + 1).min(count - 1)),
310            "up" => cursor.map_or(count - 1, |row| row.saturating_sub(1)),
311            "home" => 0,
312            "end" => count - 1,
313            "pageup" => cursor.unwrap_or(0).saturating_sub(10),
314            "pagedown" => cursor.unwrap_or(0).saturating_add(10).min(count - 1),
315            _ => return false,
316        };
317        select_row(table, row, modifiers, cx);
318    } else {
319        return false;
320    }
321    cx.stop_propagation();
322    true
323}