Skip to main content

fc_ui/capabilities/data/
data_table.rs

1//! DataTable - High-performance table component with virtual scrolling and sorting.
2
3use crate::capabilities::controls::input::{Input, InputSize, InputState};
4use crate::capabilities::controls::select::{Select, SelectEvent, SelectOption};
5use crate::capabilities::foundation::theme::use_theme;
6use crate::capabilities::primitives::icon_source::IconSource;
7use crate::capabilities::scroll::uniform_virtual_list::vlist_uniform_view;
8use gpui::{prelude::FluentBuilder as _, *};
9use std::collections::{HashMap, HashSet};
10use std::ops::Range;
11use std::rc::Rc;
12
13pub type RowActionCallback = Rc<dyn Fn(usize, &mut Window, &mut App)>;
14type LoadMoreCallback<T> = Box<dyn Fn(&mut Window, &mut Context<T>) + 'static>;
15type CellEditCallback<T> =
16    Box<dyn Fn(usize, SharedString, SharedString, SharedString, &mut Context<T>) + 'static>;
17type CellDoubleClickCallback<T> =
18    Box<dyn Fn(&T, SharedString, SharedString, &mut Window, &mut Context<DataTable<T>>) + 'static>;
19type FetchPageCallback<T> = Box<dyn Fn(usize, usize, &mut Window, &mut Context<T>) + 'static>;
20type RowClickCallback<T> =
21    Box<dyn Fn(usize, &T, &mut Window, &mut Context<DataTable<T>>) + 'static>;
22type SelectionChangeCallback<T> = Box<dyn Fn(&[usize], &mut Window, &mut Context<T>) + 'static>;
23type SortChangeCallback<T> =
24    Box<dyn Fn(SharedString, SortDirection, &mut Window, &mut Context<T>) + 'static>;
25
26#[derive(Clone)]
27pub struct RowAction {
28    pub id: SharedString,
29    pub label: SharedString,
30    pub icon: Option<IconSource>,
31    pub destructive: bool,
32    pub on_click: RowActionCallback,
33}
34
35impl RowAction {
36    pub fn new<S: Into<SharedString>, F: Fn(usize, &mut Window, &mut App) + 'static>(
37        id: S,
38        label: S,
39        handler: F,
40    ) -> Self {
41        Self {
42            id: id.into(),
43            label: label.into(),
44            icon: None,
45            destructive: false,
46            on_click: Rc::new(handler),
47        }
48    }
49
50    pub fn icon(mut self, icon: impl Into<IconSource>) -> Self {
51        self.icon = Some(icon.into());
52        self
53    }
54
55    pub fn destructive(mut self) -> Self {
56        self.destructive = true;
57        self
58    }
59}
60
61#[derive(Copy, Clone, Debug, PartialEq, Eq)]
62pub enum SortDirection {
63    Ascending,
64    Descending,
65}
66
67#[derive(Debug, Clone)]
68struct ViewportState {
69    viewport_height: f32,
70    row_height: f32,
71}
72
73impl ViewportState {
74    fn new(row_height: f32, viewport_height: f32) -> Self {
75        Self {
76            viewport_height,
77            row_height,
78        }
79    }
80}
81
82struct VirtualScroller {
83    viewport: ViewportState,
84    total_items: usize,
85}
86
87impl VirtualScroller {
88    fn new(total_items: usize, viewport: ViewportState) -> Self {
89        Self {
90            viewport,
91            total_items,
92        }
93    }
94
95    fn set_total_items(&mut self, count: usize) {
96        self.total_items = count;
97    }
98}
99
100pub struct ColumnDef<T: 'static> {
101    pub id: SharedString,
102    pub header: SharedString,
103    pub accessor: Rc<dyn Fn(&T) -> SharedString>,
104    pub width: Pixels,
105    pub min_width: Pixels,
106    pub resizable: bool,
107    pub sortable: bool,
108    pub editable: bool,
109}
110
111impl<T: 'static> ColumnDef<T> {
112    pub fn new<S: Into<SharedString>, F: Fn(&T) -> SharedString + 'static>(
113        id: S,
114        header: S,
115        accessor: F,
116    ) -> Self {
117        let id_string: SharedString = id.into();
118        let header_string: SharedString = header.into();
119
120        Self {
121            id: id_string,
122            header: header_string,
123            accessor: Rc::new(accessor),
124            width: px(150.0),
125            min_width: px(80.0),
126            resizable: true,
127            sortable: true,
128            editable: false,
129        }
130    }
131
132    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
133        self.width = width.into();
134        self
135    }
136
137    pub fn min_width(mut self, width: impl Into<Pixels>) -> Self {
138        self.min_width = width.into();
139        self
140    }
141
142    pub fn resizable(mut self, resizable: bool) -> Self {
143        self.resizable = resizable;
144        self
145    }
146
147    pub fn sortable(mut self, sortable: bool) -> Self {
148        self.sortable = sortable;
149        self
150    }
151
152    pub fn editable(mut self, editable: bool) -> Self {
153        self.editable = editable;
154        self
155    }
156}
157
158enum DataBacking<T: Clone + 'static> {
159    InMemory {
160        data: Vec<T>,
161    },
162    Virtual {
163        total_items: usize,
164        cache: HashMap<usize, T>,
165        in_flight_pages: HashSet<usize>,
166        page_size: usize,
167    },
168}
169
170pub struct DataTableState<T: Clone + 'static> {
171    columns: Vec<ColumnDef<T>>,
172    column_widths: Vec<Pixels>,
173    sort_column: Option<usize>,
174    sort_direction: SortDirection,
175    scroller: VirtualScroller,
176    selected_rows: Vec<usize>,
177    backing: DataBacking<T>,
178}
179
180impl<T: Clone + 'static> DataTableState<T> {
181    pub fn new(data: Vec<T>, columns: Vec<ColumnDef<T>>) -> Self {
182        let column_widths = columns
183            .iter()
184            .map(|col| col.width.max(col.min_width))
185            .collect();
186        let total_items = data.len();
187        let viewport = ViewportState::new(48.0, 600.0);
188
189        Self {
190            column_widths,
191            columns,
192            sort_column: None,
193            sort_direction: SortDirection::Ascending,
194            scroller: VirtualScroller::new(total_items, viewport),
195            selected_rows: Vec::new(),
196            backing: DataBacking::InMemory { data },
197        }
198    }
199
200    fn row_height(&self) -> f32 {
201        self.scroller.viewport.row_height
202    }
203
204    fn viewport_height(&self) -> f32 {
205        self.scroller.viewport.viewport_height
206    }
207
208    fn total_items(&self) -> usize {
209        match &self.backing {
210            DataBacking::InMemory { data } => data.len(),
211            DataBacking::Virtual { total_items, .. } => *total_items,
212        }
213    }
214
215    fn get_row(&self, index: usize) -> Option<&T> {
216        match &self.backing {
217            DataBacking::InMemory { data } => data.get(index),
218            DataBacking::Virtual { cache, .. } => cache.get(&index),
219        }
220    }
221
222    fn replace_in_memory_data(&mut self, data: Vec<T>) {
223        let mut data = data;
224        self.sort_in_memory_data(&mut data);
225        let count = data.len();
226        self.backing = DataBacking::InMemory { data };
227        self.scroller.set_total_items(count);
228    }
229
230    fn sort_in_memory_data(&self, data: &mut Vec<T>) {
231        let Some(column_index) = self.sort_column else {
232            return;
233        };
234        let Some(column) = self.columns.get(column_index) else {
235            return;
236        };
237        Self::sort_rows(data, column.accessor.clone(), self.sort_direction);
238    }
239
240    fn resort_current_in_memory_data(&mut self) {
241        let Some(column_index) = self.sort_column else {
242            return;
243        };
244        let Some(column) = self.columns.get(column_index) else {
245            return;
246        };
247        let accessor = column.accessor.clone();
248        let direction = self.sort_direction;
249        if let DataBacking::InMemory { data } = &mut self.backing {
250            Self::sort_rows(data, accessor, direction);
251        }
252    }
253
254    fn append_in_memory_data(&mut self, mut new_data: Vec<T>) -> bool {
255        if let DataBacking::InMemory { data } = &mut self.backing {
256            data.append(&mut new_data);
257        } else {
258            return false;
259        }
260        self.resort_current_in_memory_data();
261        true
262    }
263
264    fn sort_rows(
265        data: &mut Vec<T>,
266        accessor: Rc<dyn Fn(&T) -> SharedString>,
267        direction: SortDirection,
268    ) {
269        let mut indexed_values: Vec<(usize, String)> = data
270            .iter()
271            .enumerate()
272            .map(|(idx, row)| (idx, accessor(row).to_string()))
273            .collect();
274
275        indexed_values.sort_by(|(_, a), (_, b)| {
276            let ordering = match (a.parse::<f64>(), b.parse::<f64>()) {
277                (Ok(number_a), Ok(number_b)) => number_a
278                    .partial_cmp(&number_b)
279                    .unwrap_or(std::cmp::Ordering::Equal),
280                _ => a.cmp(b),
281            };
282            match direction {
283                SortDirection::Ascending => ordering,
284                SortDirection::Descending => ordering.reverse(),
285            }
286        });
287
288        *data = indexed_values
289            .into_iter()
290            .filter_map(|(idx, _)| data.get(idx).cloned())
291            .collect();
292    }
293
294    fn virtual_reset(&mut self, total_items: usize, page_size: Option<usize>) {
295        match &mut self.backing {
296            DataBacking::Virtual {
297                total_items: t,
298                cache,
299                in_flight_pages,
300                page_size: ps,
301            } => {
302                *t = total_items;
303                cache.clear();
304                in_flight_pages.clear();
305                if let Some(s) = page_size {
306                    *ps = s.max(1);
307                }
308            }
309            DataBacking::InMemory { .. } => {
310                self.backing = DataBacking::Virtual {
311                    total_items,
312                    cache: HashMap::new(),
313                    in_flight_pages: HashSet::new(),
314                    page_size: page_size.unwrap_or(200).max(1),
315                };
316            }
317        }
318        // Virtual pages arrive in source order and cannot be reordered locally.
319        // Clear the indicator so it never claims an order that the cache does
320        // not actually provide.
321        self.sort_column = None;
322        self.sort_direction = SortDirection::Ascending;
323        self.scroller.set_total_items(total_items);
324        self.selected_rows.clear();
325    }
326
327    fn virtual_set_page(&mut self, page_start: usize, rows: Vec<T>) {
328        if let DataBacking::Virtual {
329            total_items,
330            cache,
331            in_flight_pages,
332            ..
333        } = &mut self.backing
334        {
335            for (i, row) in rows.into_iter().enumerate() {
336                let Some(index) = page_start.checked_add(i) else {
337                    break;
338                };
339                if index >= *total_items {
340                    break;
341                }
342                cache.insert(index, row);
343            }
344            in_flight_pages.remove(&page_start);
345        }
346    }
347
348    pub fn sort_by_column(&mut self, column_index: usize, direction: SortDirection) {
349        let Some(column) = self.columns.get(column_index) else {
350            return;
351        };
352        if !column.sortable {
353            return;
354        }
355
356        // Sorting is only implemented for in-memory rows. A virtual table's
357        // pages are owned by its fetch callback, which currently receives no
358        // sort parameters, so advertising a local sort would make the header
359        // disagree with the rendered order.
360        if !matches!(&self.backing, DataBacking::InMemory { .. }) {
361            return;
362        }
363
364        self.sort_column = Some(column_index);
365        self.sort_direction = direction;
366
367        if let DataBacking::InMemory { data } = &mut self.backing {
368            Self::sort_rows(data, column.accessor.clone(), direction);
369            self.selected_rows.clear();
370        }
371    }
372
373    pub fn toggle_row(&mut self, row_index: usize) {
374        if let Some(pos) = self.selected_rows.iter().position(|&i| i == row_index) {
375            self.selected_rows.remove(pos);
376        } else {
377            self.selected_rows.push(row_index);
378        }
379    }
380
381    pub fn is_row_selected(&self, row_index: usize) -> bool {
382        self.selected_rows.contains(&row_index)
383    }
384
385    fn clear_selection(&mut self) {
386        self.selected_rows.clear();
387    }
388
389    pub fn resize_column(&mut self, column_index: usize, new_width: Pixels) {
390        if let (Some(width), Some(column)) = (
391            self.column_widths.get_mut(column_index),
392            self.columns.get(column_index),
393        ) {
394            *width = new_width.max(column.min_width);
395        }
396    }
397}
398
399pub struct DataTable<T: Clone + 'static> {
400    state: DataTableState<T>,
401    resizing_column: Option<usize>,
402    resize_start_x: f32,
403    resize_start_width: Pixels,
404    on_load_more: Option<LoadMoreCallback<Self>>,
405    load_more_threshold: f32,
406    load_more_triggered: bool,
407    scroll_handle: ScrollHandle,
408    editing_cell: Option<(usize, usize)>,
409    edit_input: Option<Entity<InputState>>,
410    edit_column_id: SharedString,
411    edit_old_value: SharedString,
412    use_edit_dialog: bool,
413    on_cell_edit: Option<CellEditCallback<Self>>,
414    on_cell_double_click: Option<CellDoubleClickCallback<T>>,
415    on_fetch_page: Option<FetchPageCallback<Self>>,
416    on_row_click: Option<RowClickCallback<T>>,
417    on_sort_change: Option<SortChangeCallback<Self>>,
418    search_query: String,
419    search_column: Option<usize>,
420    show_search: bool,
421    search_column_select: Entity<Select<usize>>,
422    search_input: Entity<InputState>,
423    show_selection: bool,
424    on_selection_change: Option<SelectionChangeCallback<Self>>,
425    row_actions: Vec<RowAction>,
426    context_menu: Option<(usize, Point<Pixels>)>,
427    style: StyleRefinement,
428}
429
430impl<T: Clone + 'static> DataTable<T> {
431    pub fn new(data: Vec<T>, columns: Vec<ColumnDef<T>>, cx: &mut Context<Self>) -> Self {
432        Self::from_state(DataTableState::new(data, columns), cx)
433    }
434
435    fn from_state(state: DataTableState<T>, cx: &mut Context<Self>) -> Self {
436        let (search_column_select, search_input) = Self::create_search_controls(&state.columns, cx);
437
438        Self {
439            state,
440            resizing_column: None,
441            resize_start_x: 0.0,
442            resize_start_width: px(0.0),
443            on_load_more: None,
444            load_more_threshold: 0.7,
445            load_more_triggered: false,
446            scroll_handle: ScrollHandle::new(),
447            editing_cell: None,
448            edit_input: None,
449            edit_column_id: SharedString::from(""),
450            edit_old_value: SharedString::from(""),
451            use_edit_dialog: false,
452            on_cell_edit: None,
453            on_cell_double_click: None,
454            on_fetch_page: None,
455            on_row_click: None,
456            on_sort_change: None,
457            search_query: String::new(),
458            search_column: None,
459            show_search: true,
460            search_column_select,
461            search_input,
462            show_selection: false,
463            on_selection_change: None,
464            row_actions: Vec::new(),
465            context_menu: None,
466            style: StyleRefinement::default(),
467        }
468    }
469
470    fn create_search_controls(
471        columns: &[ColumnDef<T>],
472        cx: &mut Context<Self>,
473    ) -> (Entity<Select<usize>>, Entity<InputState>) {
474        let mut select_options = vec![SelectOption::new(usize::MAX, "All Columns")];
475        select_options.extend(
476            columns
477                .iter()
478                .enumerate()
479                .map(|(idx, column)| SelectOption::new(idx, column.header.clone())),
480        );
481
482        let search_column_select = cx.new(|cx| {
483            Select::new(cx)
484                .options(select_options)
485                .selected_index(Some(0))
486                .placeholder("Select column...")
487        });
488
489        cx.subscribe(
490            &search_column_select,
491            |this, _select, event: &SelectEvent, cx| match event {
492                SelectEvent::Change => {
493                    let selected = this.search_column_select.read(cx).selected_value().copied();
494                    this.search_column =
495                        (selected != Some(usize::MAX)).then_some(selected).flatten();
496                    cx.notify();
497                }
498            },
499        )
500        .detach();
501
502        (search_column_select, cx.new(InputState::new))
503    }
504
505    #[deprecated(note = "DataTable keeps its header outside the virtualized body; use the default")]
506    pub fn sticky_header(self, _sticky: bool) -> Self {
507        self
508    }
509
510    pub fn show_selection(mut self, show: bool) -> Self {
511        self.show_selection = show;
512        self
513    }
514
515    pub fn on_selection_change<F>(mut self, callback: F) -> Self
516    where
517        F: Fn(&[usize], &mut Window, &mut Context<Self>) + 'static,
518    {
519        self.on_selection_change = Some(Box::new(callback));
520        self
521    }
522
523    pub fn new_virtual(
524        total_items: usize,
525        columns: Vec<ColumnDef<T>>,
526        page_size: usize,
527        cx: &mut Context<Self>,
528    ) -> Self {
529        let mut state = DataTableState::new(Vec::new(), columns);
530        state.virtual_reset(total_items, Some(page_size));
531        Self::from_state(state, cx)
532    }
533
534    /// Set callback for when user scrolls near the end
535    ///
536    /// This is useful for infinite scrolling / pagination - load more data when needed
537    pub fn on_load_more<F>(mut self, callback: F) -> Self
538    where
539        F: Fn(&mut Window, &mut Context<Self>) + 'static,
540    {
541        self.on_load_more = Some(Box::new(callback));
542        self
543    }
544
545    /// Set the threshold (0.0-1.0) for when to trigger load_more
546    ///
547    /// Default is 0.7 (70%) - callback fires when user scrolls past 70% of loaded data
548    pub fn load_more_threshold(mut self, threshold: f32) -> Self {
549        self.load_more_threshold = threshold.clamp(0.0, 1.0);
550        self
551    }
552
553    pub fn on_fetch_page<F>(mut self, callback: F) -> Self
554    where
555        F: Fn(usize, usize, &mut Window, &mut Context<Self>) + 'static,
556    {
557        self.on_fetch_page = Some(Box::new(callback));
558        self
559    }
560
561    /// Set the callback used to request remote sorting for virtual tables.
562    ///
563    /// In-memory tables sort locally. Virtual tables do not reorder cached
564    /// pages, so this callback must request sorted data from the backing
565    /// source and refresh the table when the result arrives.
566    pub fn on_sort_change<F>(mut self, callback: F) -> Self
567    where
568        F: Fn(SharedString, SortDirection, &mut Window, &mut Context<Self>) + 'static,
569    {
570        self.on_sort_change = Some(Box::new(callback));
571        self
572    }
573
574    /// Set callback for when a cell is edited
575    ///
576    /// The callback receives: (row_index, column_id, old_value, new_value, context)
577    pub fn on_cell_edit<F>(mut self, callback: F) -> Self
578    where
579        F: Fn(usize, SharedString, SharedString, SharedString, &mut Context<Self>) + 'static,
580    {
581        self.on_cell_edit = Some(Box::new(callback));
582        self
583    }
584
585    /// Set callback for cell double-click: (row_data, column_id, cell_value)
586    pub fn on_cell_double_click<F>(mut self, callback: F) -> Self
587    where
588        F: Fn(&T, SharedString, SharedString, &mut Window, &mut Context<Self>) + 'static,
589    {
590        self.on_cell_double_click = Some(Box::new(callback));
591        self
592    }
593
594    /// Set whether losing focus keeps the in-progress cell edit
595    ///
596    /// No confirmation dialog is rendered; the flag only controls blur behavior.
597    /// - `false` (default): losing focus saves the edit (Enter always saves)
598    /// - `true`: losing focus discards the edit
599    pub fn use_edit_dialog(mut self, use_dialog: bool) -> Self {
600        self.use_edit_dialog = use_dialog;
601        self
602    }
603
604    /// Set callback for when a row is clicked
605    ///
606    pub fn on_row_click<F>(mut self, callback: F) -> Self
607    where
608        F: Fn(usize, &T, &mut Window, &mut Context<Self>) + 'static,
609    {
610        self.on_row_click = Some(Box::new(callback));
611        self
612    }
613
614    pub fn show_search(mut self, show: bool) -> Self {
615        self.show_search = show;
616        self
617    }
618
619    pub fn row_actions(mut self, actions: Vec<RowAction>) -> Self {
620        self.row_actions = actions;
621        self
622    }
623
624    pub fn set_search(&mut self, query: String, cx: &mut Context<Self>) {
625        self.search_query = query;
626        cx.notify();
627    }
628
629    pub fn set_search_column(&mut self, column_index: Option<usize>, cx: &mut Context<Self>) {
630        self.search_column = column_index;
631        cx.notify();
632    }
633
634    fn sort_from_header(
635        &mut self,
636        column_index: usize,
637        direction: SortDirection,
638        window: &mut Window,
639        cx: &mut Context<Self>,
640    ) {
641        if !matches!(&self.state.backing, DataBacking::Virtual { .. }) {
642            self.state.sort_by_column(column_index, direction);
643            return;
644        }
645
646        let Some(callback) = self.on_sort_change.as_ref() else {
647            return;
648        };
649        let Some(column) = self.state.columns.get(column_index) else {
650            return;
651        };
652
653        self.state.sort_column = Some(column_index);
654        self.state.sort_direction = direction;
655        self.state.selected_rows.clear();
656        callback(column.id.clone(), direction, window, cx);
657    }
658
659    fn row_matches_search(&self, row: &T, query_lower: &str) -> bool {
660        if query_lower.is_empty() {
661            return true;
662        }
663
664        if let Some(col_idx) = self.search_column {
665            if let Some(column) = self.state.columns.get(col_idx) {
666                let cell_value = (column.accessor)(row);
667                cell_value.to_string().to_lowercase().contains(query_lower)
668            } else {
669                false
670            }
671        } else {
672            self.state.columns.iter().any(|column| {
673                let cell_value = (column.accessor)(row);
674                cell_value.to_string().to_lowercase().contains(query_lower)
675            })
676        }
677    }
678
679    fn get_filtered_indices(&self) -> Vec<usize> {
680        if let DataBacking::InMemory { data } = &self.state.backing {
681            let query_lower = self.search_query.to_lowercase();
682            data.iter()
683                .enumerate()
684                .filter(|(_, row)| self.row_matches_search(row, &query_lower))
685                .map(|(idx, _)| idx)
686                .collect()
687        } else {
688            (0..self.state.total_items()).collect()
689        }
690    }
691
692    pub fn set_data(&mut self, data: Vec<T>, cx: &mut Context<Self>) {
693        // Replacing rows invalidates the editing index (and the input entity)
694        // even when the new data has the same length.
695        self.cancel_edit(cx);
696        self.state.replace_in_memory_data(data);
697        self.state.clear_selection();
698        self.load_more_triggered = false;
699        cx.notify();
700    }
701
702    /// Replace in-memory data and notify selection observers when the old
703    /// index-based selection is cleared. Use this variant from an event
704    /// handler that has a window context.
705    pub fn set_data_with_window(
706        &mut self,
707        data: Vec<T>,
708        window: &mut Window,
709        cx: &mut Context<Self>,
710    ) {
711        let had_selection = !self.state.selected_rows.is_empty();
712        self.cancel_edit(cx);
713        self.state.replace_in_memory_data(data);
714        self.state.clear_selection();
715        self.load_more_triggered = false;
716        if had_selection {
717            if let Some(ref callback) = self.on_selection_change {
718                callback(&self.state.selected_rows, window, cx);
719            }
720        }
721        cx.notify();
722    }
723
724    pub fn append_data(&mut self, new_data: Vec<T>, cx: &mut Context<Self>) {
725        // Appending under an active sort can reorder existing rows, so discard
726        // the positional edit before changing the backing data.
727        self.cancel_edit(cx);
728        let was_sorted = self.state.sort_column.is_some();
729        if !self.state.append_in_memory_data(new_data) {
730            return;
731        }
732        if was_sorted {
733            // Selection is represented by row indices. Reordering can make an
734            // existing index refer to a different row, so clear it explicitly.
735            self.state.clear_selection();
736        }
737        let new_count = self.state.total_items();
738        self.state.scroller.set_total_items(new_count);
739        self.load_more_triggered = false;
740        cx.notify();
741    }
742
743    pub fn virtual_reset(
744        &mut self,
745        total_items: usize,
746        page_size: Option<usize>,
747        cx: &mut Context<Self>,
748    ) {
749        self.cancel_edit(cx);
750        self.state.virtual_reset(total_items, page_size);
751        self.state.clear_selection();
752        self.load_more_triggered = false;
753        cx.notify();
754    }
755
756    /// Reset virtual data and notify selection observers when stale row
757    /// indices are discarded.
758    pub fn virtual_reset_with_window(
759        &mut self,
760        total_items: usize,
761        page_size: Option<usize>,
762        window: &mut Window,
763        cx: &mut Context<Self>,
764    ) {
765        let had_selection = !self.state.selected_rows.is_empty();
766        self.cancel_edit(cx);
767        self.state.virtual_reset(total_items, page_size);
768        self.load_more_triggered = false;
769        if had_selection {
770            if let Some(ref callback) = self.on_selection_change {
771                callback(&self.state.selected_rows, window, cx);
772            }
773        }
774        cx.notify();
775    }
776
777    pub fn set_page_data(&mut self, page_start: usize, rows: Vec<T>, cx: &mut Context<Self>) {
778        // A page refresh may replace the row currently being edited. The
779        // virtual backing has no stable row identity, so drop the positional
780        // editor before installing new cache entries.
781        self.cancel_edit(cx);
782        self.state.virtual_set_page(page_start, rows);
783        self.load_more_triggered = false;
784        cx.notify();
785    }
786
787    pub fn data(&self) -> &[T] {
788        match &self.state.backing {
789            DataBacking::InMemory { data } => data,
790            _ => &[],
791        }
792    }
793
794    pub fn data_count(&self) -> usize {
795        self.state.total_items()
796    }
797
798    pub fn selected_rows(&self) -> &[usize] {
799        &self.state.selected_rows
800    }
801
802    pub fn toggle_row_selection(
803        &mut self,
804        row_index: usize,
805        window: &mut Window,
806        cx: &mut Context<Self>,
807    ) {
808        self.state.toggle_row(row_index);
809
810        if let Some(ref callback) = self.on_selection_change {
811            callback(&self.state.selected_rows, window, cx);
812        }
813
814        cx.notify();
815    }
816
817    pub fn select_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
818        let total = self.state.total_items();
819        self.state.selected_rows = (0..total).collect();
820
821        if let Some(ref callback) = self.on_selection_change {
822            callback(&self.state.selected_rows, window, cx);
823        }
824
825        cx.notify();
826    }
827
828    pub fn clear_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
829        self.state.selected_rows.clear();
830
831        if let Some(ref callback) = self.on_selection_change {
832            callback(&self.state.selected_rows, window, cx);
833        }
834
835        cx.notify();
836    }
837
838    fn is_all_selected(&self) -> bool {
839        let total = self.state.total_items();
840        total > 0 && self.state.selected_rows.len() == total
841    }
842
843    fn cancel_edit(&mut self, cx: &mut Context<Self>) {
844        if self.editing_cell.is_none() {
845            return;
846        }
847
848        self.editing_cell = None;
849        self.edit_input = None;
850        self.edit_column_id = SharedString::default();
851        self.edit_old_value = SharedString::default();
852        cx.notify();
853    }
854
855    fn total_table_width(&self) -> Pixels {
856        let mut total: f32 = self
857            .state
858            .column_widths
859            .iter()
860            .map(|w| {
861                let w_f32: f32 = (*w).into();
862                w_f32
863            })
864            .sum();
865
866        if self.show_selection {
867            total += 50.0;
868        }
869
870        px(total)
871    }
872
873    fn save_edit(&mut self, cx: &mut Context<Self>) {
874        if let Some((row_idx, _col_idx)) = self.editing_cell {
875            let new_value_string: String = if let Some(ref input) = self.edit_input {
876                input.read(cx).content().to_string()
877            } else {
878                String::new()
879            };
880
881            let row_idx_copy = row_idx;
882            let column_id = self.edit_column_id.clone();
883            let old_value = self.edit_old_value.clone();
884
885            self.editing_cell = None;
886            self.edit_input = None;
887
888            if let Some(ref callback) = self.on_cell_edit {
889                callback(
890                    row_idx_copy,
891                    column_id,
892                    old_value,
893                    new_value_string.into(),
894                    cx,
895                );
896            }
897
898            cx.notify();
899        }
900    }
901
902    fn render_search_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
903        let theme = use_theme(cx);
904
905        div()
906            .flex()
907            .items_center()
908            .gap(px(12.0))
909            .px(px(16.0))
910            .py(px(12.0))
911            .border_b_1()
912            .border_color(theme.tokens.border)
913            .bg(theme.tokens.muted.opacity(0.3))
914            .child(
915                div()
916                    .flex()
917                    .items_center()
918                    .gap(px(8.0))
919                    .child(
920                        div()
921                            .text_size(px(13.0))
922                            .text_color(theme.tokens.muted_foreground)
923                            .child("Search in:"),
924                    )
925                    .child(div().w(px(200.0)).child(self.search_column_select.clone())),
926            )
927            .child(
928                div().w(px(300.0)).child(
929                    Input::new(&self.search_input)
930                        .size(InputSize::Sm)
931                        .placeholder("Type to search...")
932                        .on_change({
933                            let entity = cx.entity();
934                            move |value: SharedString, cx| {
935                                entity.update(cx, |this, cx| {
936                                    this.search_query = value.to_string();
937                                    cx.notify();
938                                });
939                            }
940                        }),
941                ),
942            )
943    }
944
945    fn render_header(&self, cx: &mut Context<Self>) -> impl IntoElement {
946        let theme = use_theme(cx);
947
948        let total_width = self.total_table_width();
949        let mut header_row = div().flex().w(total_width).min_w(total_width);
950
951        if self.show_selection {
952            let all_selected = self.is_all_selected();
953
954            header_row = header_row.child(
955                div()
956                    .flex()
957                    .items_center()
958                    .justify_center()
959                    .w(px(50.0))
960                    .px(px(16.0))
961                    .py(px(12.0))
962                    .text_size(px(13.0))
963                    .font_weight(FontWeight::SEMIBOLD)
964                    .text_color(theme.tokens.muted_foreground)
965                    .border_b_1()
966                    .border_r_1()
967                    .border_color(theme.tokens.border)
968                    .bg(theme.tokens.muted.opacity(0.5))
969                    .cursor(CursorStyle::PointingHand)
970                    .hover(|style| style.bg(theme.tokens.muted.opacity(0.7)))
971                    .on_mouse_down(
972                        MouseButton::Left,
973                        cx.listener(|this, _event, window, cx| {
974                            if this.is_all_selected() {
975                                this.clear_selection(window, cx);
976                            } else {
977                                this.select_all(window, cx);
978                            }
979                        }),
980                    )
981                    .child(
982                        div()
983                            .w(px(16.0))
984                            .h(px(16.0))
985                            .rounded(px(3.0))
986                            .border_1()
987                            .border_color(if all_selected {
988                                theme.tokens.primary
989                            } else {
990                                theme.tokens.border
991                            })
992                            .bg(if all_selected {
993                                theme.tokens.primary
994                            } else {
995                                theme.tokens.background
996                            }),
997                    ),
998            );
999        }
1000
1001        let header_cells = self
1002            .state
1003            .columns
1004            .iter()
1005            .enumerate()
1006            .map(|(col_idx, column)| {
1007                let width = self.state.column_widths[col_idx];
1008                let is_sorted = self.state.sort_column == Some(col_idx);
1009                let sortable = column.sortable;
1010
1011                let mut header_cell = div()
1012                    .flex()
1013                    .items_center()
1014                    .justify_between()
1015                    .px(px(16.0))
1016                    .py(px(12.0))
1017                    .w(width)
1018                    .text_size(px(13.0))
1019                    .font_weight(FontWeight::SEMIBOLD)
1020                    .text_color(theme.tokens.muted_foreground)
1021                    .border_b_1()
1022                    .border_r_1()
1023                    .border_color(theme.tokens.border)
1024                    .bg(theme.tokens.muted.opacity(0.5))
1025                    .hover(|style| {
1026                        if sortable {
1027                            style
1028                                .bg(theme.tokens.muted.opacity(0.7))
1029                                .cursor(CursorStyle::PointingHand)
1030                        } else {
1031                            style
1032                        }
1033                    })
1034                    .child(
1035                        div()
1036                            .flex()
1037                            .items_center()
1038                            .gap(px(8.0))
1039                            .child(column.header.clone())
1040                            .when(is_sorted, |el| {
1041                                el.child(div().text_size(px(10.0)).child(
1042                                    match self.state.sort_direction {
1043                                        SortDirection::Ascending => "â–²",
1044                                        SortDirection::Descending => "â–¼",
1045                                    },
1046                                ))
1047                            }),
1048                    );
1049
1050                if sortable {
1051                    header_cell = header_cell.on_mouse_down(
1052                        MouseButton::Left,
1053                        cx.listener(move |this, _event, window, cx| {
1054                            let new_direction = if this.state.sort_column == Some(col_idx) {
1055                                match this.state.sort_direction {
1056                                    SortDirection::Ascending => SortDirection::Descending,
1057                                    SortDirection::Descending => SortDirection::Ascending,
1058                                }
1059                            } else {
1060                                SortDirection::Ascending
1061                            };
1062
1063                            if this.editing_cell.is_some() {
1064                                if this.use_edit_dialog {
1065                                    this.cancel_edit(cx);
1066                                } else {
1067                                    this.save_edit(cx);
1068                                }
1069                            }
1070                            let had_selection = !this.state.selected_rows.is_empty();
1071                            this.sort_from_header(col_idx, new_direction, window, cx);
1072                            if had_selection {
1073                                if let Some(ref callback) = this.on_selection_change {
1074                                    callback(&this.state.selected_rows, window, cx);
1075                                }
1076                            }
1077                            cx.notify();
1078                        }),
1079                    );
1080                }
1081
1082                header_cell = header_cell.when(column.resizable, |el| {
1083                    el.child(
1084                        div()
1085                            .w(px(4.0))
1086                            .h_full()
1087                            .absolute()
1088                            .right(px(0.0))
1089                            .top(px(0.0))
1090                            .cursor(CursorStyle::ResizeLeftRight)
1091                            .bg(gpui::transparent_black())
1092                            .hover(|style| style.bg(theme.tokens.primary.opacity(0.5)))
1093                            .on_mouse_down(
1094                                MouseButton::Left,
1095                                cx.listener(move |this, event: &MouseDownEvent, _window, cx| {
1096                                    cx.stop_propagation();
1097                                    this.resizing_column = Some(col_idx);
1098                                    this.resize_start_x = event.position.x.into();
1099                                    this.resize_start_width = this.state.column_widths[col_idx];
1100                                    cx.notify();
1101                                }),
1102                            ),
1103                    )
1104                });
1105
1106                header_cell
1107            });
1108
1109        header_row.children(header_cells)
1110    }
1111}
1112
1113impl<T: Clone + 'static> Styled for DataTable<T> {
1114    fn style(&mut self) -> &mut StyleRefinement {
1115        &mut self.style
1116    }
1117}
1118
1119impl<T: Clone + 'static> Render for DataTable<T> {
1120    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1121        let theme = use_theme(cx);
1122
1123        let user_style = self.style.clone();
1124
1125        let viewport_height = self.state.viewport_height();
1126
1127        let (total_items, filtered_indices): (usize, Option<Rc<Vec<usize>>>) =
1128            match &self.state.backing {
1129                DataBacking::InMemory { .. } => {
1130                    let indices = Rc::new(self.get_filtered_indices());
1131                    (indices.len(), Some(indices))
1132                }
1133                DataBacking::Virtual { .. } => (self.state.total_items(), None),
1134            };
1135        let row_extent = px(self.state.row_height());
1136        let total_width = self.total_table_width();
1137
1138        let view_entity = cx.entity().clone();
1139        let filtered_indices_for_render = filtered_indices.clone();
1140        let renderer = move |this: &mut DataTable<T>,
1141                             range: Range<usize>,
1142                             _window: &mut Window,
1143                             cx: &mut Context<DataTable<T>>| {
1144            let theme = use_theme(cx);
1145            range
1146                .map(|row_idx| {
1147                    let actual_idx = if let Some(ref map) = filtered_indices_for_render {
1148                        map.get(row_idx).copied().unwrap_or(row_idx)
1149                    } else {
1150                        row_idx
1151                    };
1152
1153                    if let Some(row_data) = this.state.get_row(actual_idx) {
1154                        let is_selected = this.state.is_row_selected(actual_idx);
1155
1156                        let mut row_div = div()
1157                            .flex()
1158                            .w(total_width)
1159                            .min_w(total_width)
1160                            .h(row_extent)
1161                            .bg(if is_selected {
1162                                theme.tokens.accent.opacity(0.2)
1163                            } else if row_idx % 2 == 0 {
1164                                theme.tokens.background
1165                            } else {
1166                                theme.tokens.muted.opacity(0.3)
1167                            })
1168                            .hover(|style| style.bg(theme.tokens.accent.opacity(0.1)));
1169
1170                        if !this.row_actions.is_empty() {
1171                            row_div = row_div.on_mouse_down(
1172                                MouseButton::Right,
1173                                cx.listener(move |this, event: &MouseDownEvent, _window, cx| {
1174                                    this.context_menu = Some((actual_idx, event.position));
1175                                    cx.notify();
1176                                }),
1177                            );
1178                        }
1179
1180                        if this.on_row_click.is_some() {
1181                            row_div = row_div.on_mouse_down(
1182                                MouseButton::Left,
1183                                cx.listener(move |this, event: &MouseDownEvent, window, cx| {
1184                                    if event.click_count > 1 {
1185                                        return;
1186                                    }
1187                                    if let Some(row) = this.state.get_row(actual_idx) {
1188                                        if let Some(ref cb) = this.on_row_click {
1189                                            (cb)(actual_idx, row, window, cx);
1190                                        }
1191                                    }
1192                                }),
1193                            );
1194                        }
1195
1196                        if this.show_selection {
1197                            row_div = row_div.child(
1198                                div()
1199                                    .flex()
1200                                    .items_center()
1201                                    .justify_center()
1202                                    .w(px(50.0))
1203                                    .px(px(16.0))
1204                                    .py(px(12.0))
1205                                    .border_b_1()
1206                                    .border_r_1()
1207                                    .border_color(theme.tokens.border.opacity(0.5))
1208                                    .cursor(CursorStyle::PointingHand)
1209                                    .on_mouse_down(
1210                                        MouseButton::Left,
1211                                        cx.listener(move |this, _event, window, cx| {
1212                                            this.toggle_row_selection(actual_idx, window, cx);
1213                                        }),
1214                                    )
1215                                    .child(
1216                                        div()
1217                                            .w(px(16.0))
1218                                            .h(px(16.0))
1219                                            .rounded(px(3.0))
1220                                            .border_1()
1221                                            .border_color(if is_selected {
1222                                                theme.tokens.primary
1223                                            } else {
1224                                                theme.tokens.border
1225                                            })
1226                                            .bg(if is_selected {
1227                                                theme.tokens.primary
1228                                            } else {
1229                                                theme.tokens.background
1230                                            }),
1231                                    ),
1232                            );
1233                        }
1234
1235                        let cells =
1236                            this.state
1237                                .columns
1238                                .iter()
1239                                .enumerate()
1240                                .map(|(col_idx, column)| {
1241                                    let width = this.state.column_widths[col_idx];
1242                                    let cell_value = (column.accessor)(row_data);
1243                                    let is_editable = column.editable;
1244                                    let is_editing =
1245                                        this.editing_cell == Some((actual_idx, col_idx));
1246
1247                                    let mut cell_div = div()
1248                                        .flex()
1249                                        .items_center()
1250                                        .px(px(16.0))
1251                                        .py(px(12.0))
1252                                        .w(width)
1253                                        .text_size(px(13.0))
1254                                        .text_color(theme.tokens.foreground)
1255                                        .border_b_1()
1256                                        .border_r_1()
1257                                        .border_color(theme.tokens.border.opacity(0.5))
1258                                        .overflow_hidden()
1259                                        .text_ellipsis();
1260
1261                                    if is_editable && !is_editing {
1262                                        let cell_value_for_closure = cell_value.clone();
1263                                        let column_id = column.id.clone();
1264                                        let row_data_clone = row_data.clone();
1265                                        cell_div = cell_div
1266                                            .cursor(CursorStyle::IBeam)
1267                                            .on_mouse_down(
1268                                            MouseButton::Left,
1269                                            cx.listener(
1270                                                move |this, event: &MouseDownEvent, window, cx| {
1271                                                    if event.click_count < 2 {
1272                                                        return;
1273                                                    }
1274
1275                                                    if this.on_cell_double_click.is_some() {
1276                                                        if let Some(ref cb) =
1277                                                            this.on_cell_double_click
1278                                                        {
1279                                                            (cb)(
1280                                                                &row_data_clone,
1281                                                                column_id.clone(),
1282                                                                cell_value_for_closure.clone(),
1283                                                                window,
1284                                                                cx,
1285                                                            );
1286                                                        }
1287                                                        return;
1288                                                    }
1289
1290                                                    let input_state = cx.new(|cx| {
1291                                                        let mut state = InputState::new(cx);
1292                                                        state.set_value(
1293                                                            cell_value_for_closure.clone(),
1294                                                            window,
1295                                                            cx,
1296                                                        );
1297                                                        state
1298                                                    });
1299                                                    use crate::capabilities::controls::input::InputEvent;
1300                                                    cx.subscribe(
1301                                                        &input_state,
1302                                                        |this, _, event: &InputEvent, cx| {
1303                                                            match event {
1304                                                                InputEvent::Enter => {
1305                                                                    this.save_edit(cx)
1306                                                                }
1307                                                                InputEvent::Blur => {
1308                                                                    if !this.use_edit_dialog {
1309                                                                        this.save_edit(cx);
1310                                                                    } else {
1311                                                                        this.cancel_edit(cx);
1312                                                                    }
1313                                                                }
1314                                                                _ => {}
1315                                                            }
1316                                                        },
1317                                                    )
1318                                                    .detach();
1319                                                    this.editing_cell = Some((actual_idx, col_idx));
1320                                                    this.edit_input = Some(input_state);
1321                                                    this.edit_column_id = column_id.clone();
1322                                                    this.edit_old_value =
1323                                                        cell_value_for_closure.clone();
1324                                                    if let Some(ref input) = this.edit_input {
1325                                                        window.focus(
1326                                                            &input.read(cx).focus_handle(cx),
1327                                                        );
1328                                                    }
1329                                                    cx.notify();
1330                                                },
1331                                            ),
1332                                        );
1333                                    }
1334
1335                                    if is_editing {
1336                                        if let Some(ref input_state) = this.edit_input {
1337                                            cell_div
1338                                                .child(Input::new(input_state).size(InputSize::Sm))
1339                                        } else {
1340                                            cell_div.child(cell_value)
1341                                        }
1342                                    } else {
1343                                        cell_div.child(cell_value)
1344                                    }
1345                                });
1346
1347                        row_div.children(cells)
1348                    } else {
1349                        let mut skeleton_row = div()
1350                            .flex()
1351                            .w(total_width)
1352                            .min_w(total_width)
1353                            .h(row_extent)
1354                            .bg(if row_idx % 2 == 0 {
1355                                theme.tokens.background
1356                            } else {
1357                                theme.tokens.muted.opacity(0.3)
1358                            });
1359                        if this.show_selection {
1360                            skeleton_row = skeleton_row.child(
1361                                div()
1362                                    .flex()
1363                                    .items_center()
1364                                    .justify_center()
1365                                    .w(px(50.0))
1366                                    .px(px(16.0))
1367                                    .py(px(12.0))
1368                                    .border_b_1()
1369                                    .border_r_1()
1370                                    .border_color(theme.tokens.border.opacity(0.5)),
1371                            );
1372                        }
1373                        let cells = this.state.columns.iter().enumerate().map(|(col_idx, _)| {
1374                            let width = this.state.column_widths[col_idx];
1375                            div()
1376                                .flex()
1377                                .items_center()
1378                                .px(px(16.0))
1379                                .py(px(12.0))
1380                                .w(width)
1381                                .border_b_1()
1382                                .border_r_1()
1383                                .border_color(theme.tokens.border.opacity(0.5))
1384                                .child(
1385                                    div()
1386                                        .w(px(96.0))
1387                                        .h(px(12.0))
1388                                        .rounded(px(4.0))
1389                                        .bg(theme.tokens.muted.opacity(0.6)),
1390                                )
1391                        });
1392                        skeleton_row.children(cells)
1393                    }
1394                })
1395                .collect::<Vec<_>>()
1396        };
1397
1398        let view_for_visible = view_entity.clone();
1399        let view_for_near_end = view_entity.clone();
1400        let body_scroll = vlist_uniform_view(
1401            view_entity,
1402            "data-table-body",
1403            total_items,
1404            row_extent,
1405            renderer,
1406        )
1407        .track_scroll(&self.scroll_handle)
1408        .overscan(8)
1409        .h(px(viewport_height))
1410        .on_visible_range(move |range, window, app| {
1411            let start = range.start;
1412            let end = range.end;
1413            let _ = window;
1414            view_for_visible.update(app, |this: &mut DataTable<T>, cx| {
1415                let total_items = match &this.state.backing {
1416                    DataBacking::InMemory { .. } => this.get_filtered_indices().len(),
1417                    DataBacking::Virtual { .. } => this.state.total_items(),
1418                };
1419                if total_items > 0 && !this.load_more_triggered {
1420                    let progress = end as f32 / total_items as f32;
1421                    if progress >= this.load_more_threshold {
1422                        if let Some(ref callback) = this.on_load_more {
1423                            this.load_more_triggered = true;
1424                            callback(window, cx);
1425                        }
1426                    }
1427                }
1428
1429                if let DataBacking::Virtual {
1430                    page_size,
1431                    in_flight_pages,
1432                    cache,
1433                    ..
1434                } = &mut this.state.backing
1435                {
1436                    if let Some(ref fetch_cb) = this.on_fetch_page {
1437                        let first_page_start = (start / *page_size) * *page_size;
1438                        let last_index = end.saturating_sub(1);
1439                        let last_page_start = (last_index / *page_size) * *page_size;
1440                        let mut page = first_page_start;
1441                        while page <= last_page_start {
1442                            let mut needs_fetch = false;
1443                            let page_end = page.saturating_add(*page_size).min(total_items);
1444                            for i in page..page_end {
1445                                if !cache.contains_key(&i) {
1446                                    needs_fetch = true;
1447                                    break;
1448                                }
1449                            }
1450                            if needs_fetch && !in_flight_pages.contains(&page) {
1451                                in_flight_pages.insert(page);
1452                                fetch_cb(page, *page_size, window, cx);
1453                            }
1454                            let Some(next_page) = page.checked_add(*page_size) else {
1455                                break;
1456                            };
1457                            page = next_page;
1458                        }
1459                    }
1460                }
1461            });
1462        })
1463        .on_near_end(self.load_more_threshold, move |window, app| {
1464            view_for_near_end.update(app, |this: &mut DataTable<T>, cx| {
1465                if !this.load_more_triggered {
1466                    if let Some(ref callback) = this.on_load_more {
1467                        this.load_more_triggered = true;
1468                        callback(window, cx);
1469                    }
1470                }
1471            });
1472        });
1473
1474        let body_container = div()
1475            .id("data-table-body-container")
1476            .h(px(viewport_height))
1477            .on_scroll_wheel(
1478                cx.listener(|_view, _event: &ScrollWheelEvent, _window, cx| {
1479                    cx.stop_propagation();
1480                    cx.notify();
1481                }),
1482            )
1483            .child(body_scroll);
1484
1485        let scrollable_content = div()
1486            .id("data-table-content")
1487            .flex()
1488            .flex_col()
1489            .overflow_x_scroll()
1490            .w_full()
1491            .cursor(CursorStyle::PointingHand)
1492            .child(
1493                div()
1494                    .flex()
1495                    .flex_col()
1496                    .w(total_width)
1497                    .min_w(total_width)
1498                    .child(self.render_header(cx))
1499                    .child(body_container),
1500            );
1501
1502        let table_div = div()
1503            .flex()
1504            .flex_col()
1505            .w_full()
1506            .border_1()
1507            .border_color(theme.tokens.border)
1508            .rounded(theme.tokens.radius_lg)
1509            .overflow_hidden()
1510            .bg(theme.tokens.card)
1511            .shadow_sm()
1512            .when(self.show_search, |div| {
1513                div.child(self.render_search_bar(cx))
1514            })
1515            .child(scrollable_content)
1516            .map(|mut this| {
1517                this.style().refine(&user_style);
1518                this
1519            });
1520
1521        let context_menu_elem = self
1522            .context_menu
1523            .map(|(row_idx, position)| self.render_context_menu(row_idx, position, cx));
1524
1525        div()
1526            .relative()
1527            .w_full()
1528            .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _window, cx| {
1529                if let Some(col_idx) = this.resizing_column {
1530                    let current_x: f32 = event.position.x.into();
1531                    let delta_x = current_x - this.resize_start_x;
1532                    let new_width_f32: f32 = this.resize_start_width.into();
1533                    let new_width = px(new_width_f32 + delta_x);
1534
1535                    let min_width = this.state.columns[col_idx].min_width;
1536                    let final_width = if new_width > min_width {
1537                        new_width
1538                    } else {
1539                        min_width
1540                    };
1541
1542                    this.state.resize_column(col_idx, final_width);
1543                    cx.notify();
1544                }
1545            }))
1546            .on_mouse_up(
1547                MouseButton::Left,
1548                cx.listener(|this, _event, _window, cx| {
1549                    if this.resizing_column.is_some() {
1550                        this.resizing_column = None;
1551                        cx.notify();
1552                    }
1553                }),
1554            )
1555            .child(table_div)
1556            .children(context_menu_elem)
1557    }
1558}
1559
1560impl<T: Clone + 'static> DataTable<T> {
1561    fn render_context_menu(
1562        &self,
1563        row_idx: usize,
1564        position: Point<Pixels>,
1565        cx: &mut Context<Self>,
1566    ) -> impl IntoElement {
1567        let theme = use_theme(cx);
1568
1569        deferred(
1570            anchored()
1571                .position(position)
1572                .snap_to_window_with_margin(px(8.))
1573                .anchor(Corner::TopLeft)
1574                .child(
1575                    div()
1576                        .occlude()
1577                        .min_w(px(200.0))
1578                        .bg(theme.tokens.popover)
1579                        .border_1()
1580                        .border_color(theme.tokens.border)
1581                        .rounded(theme.tokens.radius_md)
1582                        .shadow_xl()
1583                        .p(px(4.0))
1584                        .on_mouse_down_out(cx.listener(|this, _, _, cx| {
1585                            this.context_menu = None;
1586                            cx.notify();
1587                        }))
1588                        .children(self.row_actions.iter().map(|action| {
1589                            let action = action.clone();
1590                            div()
1591                                .flex()
1592                                .items_center()
1593                                .gap(px(8.0))
1594                                .px(px(12.0))
1595                                .py(px(8.0))
1596                                .rounded(theme.tokens.radius_sm)
1597                                .cursor(CursorStyle::PointingHand)
1598                                .hover(|style| style.bg(theme.tokens.accent))
1599                                .text_size(px(14.0))
1600                                .text_color(if action.destructive {
1601                                    theme.tokens.destructive
1602                                } else {
1603                                    theme.tokens.popover_foreground
1604                                })
1605                                .on_mouse_down(
1606                                    MouseButton::Left,
1607                                    cx.listener(move |this, _event, window, cx| {
1608                                        (action.on_click)(row_idx, window, cx);
1609                                        this.context_menu = None;
1610                                        cx.notify();
1611                                    }),
1612                                )
1613                                .when_some(action.icon, |div, icon| {
1614                                    div.child(
1615                                        crate::capabilities::primitives::icon::Icon::new(icon)
1616                                            .size(px(16.0))
1617                                            .color(if action.destructive {
1618                                                theme.tokens.destructive
1619                                            } else {
1620                                                theme.tokens.popover_foreground
1621                                            }),
1622                                    )
1623                                })
1624                                .child(action.label)
1625                                .into_any_element()
1626                        })),
1627                ),
1628        )
1629    }
1630}
1631
1632#[cfg(test)]
1633mod tests {
1634    use super::*;
1635    use std::cell::{Cell, RefCell};
1636    use std::rc::Rc;
1637
1638    #[derive(Clone)]
1639    struct Row {
1640        value: String,
1641    }
1642
1643    fn columns() -> Vec<ColumnDef<Row>> {
1644        vec![ColumnDef::new("value", "Value", |row: &Row| {
1645            row.value.clone().into()
1646        })]
1647    }
1648
1649    #[::core::prelude::v1::test]
1650    fn numeric_sort_uses_numeric_order_and_clears_selection() {
1651        let mut state = DataTableState::new(
1652            vec![
1653                Row { value: "10".into() },
1654                Row { value: "2".into() },
1655                Row { value: "1".into() },
1656            ],
1657            columns(),
1658        );
1659        state.toggle_row(1);
1660        state.sort_by_column(0, SortDirection::Ascending);
1661
1662        let DataBacking::InMemory { data } = &state.backing else {
1663            panic!("expected in-memory data");
1664        };
1665        assert_eq!(
1666            data.iter()
1667                .map(|row| row.value.as_str())
1668                .collect::<Vec<_>>(),
1669            vec!["1", "2", "10"]
1670        );
1671        assert!(state.selected_rows.is_empty());
1672    }
1673
1674    #[::core::prelude::v1::test]
1675    fn replacing_data_reapplies_the_active_sort() {
1676        let mut state = DataTableState::new(
1677            vec![Row { value: "2".into() }, Row { value: "1".into() }],
1678            columns(),
1679        );
1680        state.sort_by_column(0, SortDirection::Ascending);
1681        state.replace_in_memory_data(vec![Row { value: "10".into() }, Row { value: "3".into() }]);
1682
1683        let DataBacking::InMemory { data } = &state.backing else {
1684            panic!("expected in-memory data");
1685        };
1686        assert_eq!(
1687            data.iter()
1688                .map(|row| row.value.as_str())
1689                .collect::<Vec<_>>(),
1690            vec!["3", "10"]
1691        );
1692    }
1693
1694    #[::core::prelude::v1::test]
1695    fn appending_data_reapplies_the_active_sort() {
1696        let mut state = DataTableState::new(
1697            vec![Row { value: "1".into() }, Row { value: "3".into() }],
1698            columns(),
1699        );
1700        state.sort_by_column(0, SortDirection::Descending);
1701        assert!(state.append_in_memory_data(vec![Row { value: "10".into() }]));
1702
1703        let DataBacking::InMemory { data } = &state.backing else {
1704            panic!("expected in-memory data");
1705        };
1706        assert_eq!(
1707            data.iter()
1708                .map(|row| row.value.as_str())
1709                .collect::<Vec<_>>(),
1710            vec!["10", "3", "1"]
1711        );
1712    }
1713
1714    #[::core::prelude::v1::test]
1715    fn virtual_sort_does_not_claim_a_local_order() {
1716        let mut state = DataTableState::new(Vec::<Row>::new(), columns());
1717        state.virtual_reset(10, Some(2));
1718        state.sort_by_column(0, SortDirection::Ascending);
1719
1720        assert!(state.sort_column.is_none());
1721    }
1722
1723    #[gpui::test]
1724    fn virtual_sort_dispatches_remote_sort_request() {
1725        let mut app = TestApp::new();
1726        let requests = Rc::new(RefCell::new(Vec::new()));
1727        let requests_for_callback = requests.clone();
1728        let table = app.update(|cx| {
1729            cx.new(|cx| {
1730                DataTable::new_virtual(10, columns(), 2, cx).on_sort_change(
1731                    move |column, direction, _, _| {
1732                        requests_for_callback
1733                            .borrow_mut()
1734                            .push((column.to_string(), direction));
1735                    },
1736                )
1737            })
1738        });
1739        let mut window = app.open_window(|_, _| gpui::Empty);
1740
1741        window.update(|_, window, cx| {
1742            table.update(cx, |table, cx| {
1743                table.sort_from_header(0, SortDirection::Descending, window, cx);
1744            });
1745        });
1746
1747        assert_eq!(
1748            requests.borrow().as_slice(),
1749            &[("value".to_string(), SortDirection::Descending)]
1750        );
1751    }
1752
1753    #[::core::prelude::v1::test]
1754    fn virtual_reset_clears_index_based_selection() {
1755        let mut state = DataTableState::new(Vec::<Row>::new(), columns());
1756        state.virtual_reset(10, Some(2));
1757        state.toggle_row(7);
1758        state.virtual_reset(3, Some(2));
1759        assert!(state.selected_rows.is_empty());
1760    }
1761
1762    #[gpui::test]
1763    fn window_aware_data_reset_notifies_selection_observers() {
1764        let mut app = TestApp::new();
1765        let calls = Rc::new(Cell::new(0));
1766        let calls_for_callback = calls.clone();
1767        let table = app.update(|cx| {
1768            cx.new(|cx| {
1769                DataTable::new(
1770                    vec![Row {
1771                        value: "one".into(),
1772                    }],
1773                    columns(),
1774                    cx,
1775                )
1776                .on_selection_change(move |selected, _, _| {
1777                    if selected.is_empty() {
1778                        calls_for_callback.set(calls_for_callback.get() + 1);
1779                    }
1780                })
1781            })
1782        });
1783        let mut window = app.open_window(|_, _| gpui::Empty);
1784
1785        window.update(|_, window, cx| {
1786            table.update(cx, |table, _cx| table.state.toggle_row(0));
1787            table.update(cx, |table, cx| {
1788                table.set_data_with_window(
1789                    vec![Row {
1790                        value: "two".into(),
1791                    }],
1792                    window,
1793                    cx,
1794                );
1795            });
1796        });
1797
1798        assert_eq!(calls.get(), 1);
1799    }
1800}