Skip to main content

gpui_component/table/
column.rs

1use gpui::{
2    Bounds, Context, Edges, Empty, EntityId, IntoElement, ParentElement as _, Pixels, Render,
3    SharedString, Styled as _, TextAlign, Window, div, prelude::FluentBuilder, px,
4};
5
6use crate::ActiveTheme as _;
7
8/// Represents a column in a table, used for initializing table columns.
9#[derive(Debug, Clone)]
10pub struct Column {
11    /// The unique key of the column.
12    ///
13    /// This is used to identify the column in the table and your data source.
14    ///
15    /// In most cases, it should match the field name in your data source.
16    pub key: SharedString,
17    /// The display name of the column.
18    pub name: SharedString,
19    /// The text alignment of the column.
20    pub align: TextAlign,
21    /// The sorting behavior of the column, if any.
22    ///
23    /// If `None`, the column is not sortable.
24    pub sort: Option<ColumnSort>,
25    /// The padding of the column.
26    pub paddings: Option<Edges<Pixels>>,
27    /// The width of the column.
28    pub width: Pixels,
29    /// Whether the column is fixed, the fixed column will pin at the left side when scrolling horizontally.
30    pub fixed: Option<ColumnFixed>,
31    /// Whether the column is resizable.
32    pub resizable: bool,
33    /// Whether the column is movable.
34    pub movable: bool,
35    /// Whether the column is selectable.
36    ///
37    /// When `true`:
38    /// - In column selection mode: The entire column can be selected
39    /// - In cell selection mode: Individual cells in this column can be selected
40    ///
41    /// When `false`:
42    /// - The column and its cells cannot be selected
43    /// - Useful for action columns (e.g., buttons, checkboxes) that shouldn't participate in selection
44    pub selectable: bool,
45    /// The minimum width of the column.
46    pub min_width: Pixels,
47    /// The maximum width of the column.
48    pub max_width: Pixels,
49}
50
51/// A column group can be used to group multiple columns under a single header.
52#[derive(Debug, Clone)]
53pub struct ColumnGroup {
54    pub label: SharedString,
55    pub span: usize,
56}
57
58impl ColumnGroup {
59    pub fn new(label: impl Into<SharedString>, span: usize) -> Self {
60        Self {
61            label: label.into(),
62            span,
63        }
64    }
65}
66
67impl Default for Column {
68    fn default() -> Self {
69        Self {
70            key: SharedString::new(""),
71            name: SharedString::new(""),
72            align: TextAlign::Left,
73            sort: None,
74            paddings: None,
75            width: px(100.),
76            fixed: None,
77            resizable: true,
78            movable: true,
79            selectable: true,
80            min_width: px(20.0),
81            max_width: px(f32::MAX),
82        }
83    }
84}
85
86impl Column {
87    /// Create a new column with the given key and name.
88    pub fn new(key: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
89        Self {
90            key: key.into(),
91            name: name.into(),
92            ..Default::default()
93        }
94    }
95
96    /// Set the column to be sortable with custom sort function, default is None (not sortable).
97    ///
98    /// See also [`Column::sortable`] to enable sorting with default.
99    pub fn sort(mut self, sort: ColumnSort) -> Self {
100        self.sort = Some(sort);
101        self
102    }
103
104    /// Set whether the column is sortable, default is true.
105    ///
106    /// See also [`Column::sort`].
107    pub fn sortable(mut self) -> Self {
108        self.sort = Some(ColumnSort::Default);
109        self
110    }
111
112    /// Set whether the column is sort with ascending order.
113    pub fn ascending(mut self) -> Self {
114        self.sort = Some(ColumnSort::Ascending);
115        self
116    }
117
118    /// Set whether the column is sort with descending order.
119    pub fn descending(mut self) -> Self {
120        self.sort = Some(ColumnSort::Descending);
121        self
122    }
123
124    /// Set the text alignment of the column to center.
125    pub fn text_center(mut self) -> Self {
126        self.align = TextAlign::Center;
127        self
128    }
129
130    /// Set the alignment of the column text, default is left.
131    ///
132    /// Only `text_left`, `text_right` is supported.
133    pub fn text_right(mut self) -> Self {
134        self.align = TextAlign::Right;
135        self
136    }
137
138    /// Set the padding of the column, default is None.
139    pub fn paddings(mut self, paddings: impl Into<Edges<Pixels>>) -> Self {
140        self.paddings = Some(paddings.into());
141        self
142    }
143
144    /// Set the padding of the column to 0px.
145    pub fn p_0(mut self) -> Self {
146        self.paddings = Some(Edges::all(px(0.)));
147        self
148    }
149
150    /// Set the width of the column, default is 100px.
151    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
152        self.width = width.into();
153        self
154    }
155
156    /// Set whether the column is fixed, default is false.
157    pub fn fixed(mut self, fixed: impl Into<ColumnFixed>) -> Self {
158        self.fixed = Some(fixed.into());
159        self
160    }
161
162    /// Set whether the column is fixed on left side, default is false.
163    pub fn fixed_left(mut self) -> Self {
164        self.fixed = Some(ColumnFixed::Left);
165        self
166    }
167
168    /// Set whether the column is resizable, default is true.
169    pub fn resizable(mut self, resizable: bool) -> Self {
170        self.resizable = resizable;
171        self
172    }
173
174    /// Set whether the column is movable, default is true.
175    pub fn movable(mut self, movable: bool) -> Self {
176        self.movable = movable;
177        self
178    }
179
180    /// Set whether the column is selectable, default is true.
181    ///
182    /// When `false`, this column and its cells will not participate in selection:
183    /// - In column selection mode: The column header cannot be clicked to select
184    /// - In cell selection mode: Cells in this column cannot be selected
185    ///
186    /// This is useful for action columns (e.g., with buttons or checkboxes) that
187    /// should not be part of the selection system.
188    ///
189    /// # Example
190    ///
191    /// ```rust,ignore
192    /// Column::new("actions", "Actions")
193    ///     .width(px(100.))
194    ///     .selectable(false)  // Prevent selection of action buttons
195    /// ```
196    pub fn selectable(mut self, selectable: bool) -> Self {
197        self.selectable = selectable;
198        self
199    }
200
201    /// Set the minimum width of the column, default is 20px
202    pub fn min_width(mut self, min_width: impl Into<Pixels>) -> Self {
203        let min_width = min_width.into();
204        self.min_width = min_width;
205
206        // If the current width is smaller than the new minimum,
207        // bump the width up to match the minimum.
208        if self.width < min_width {
209            self.width = min_width;
210        }
211        self
212    }
213
214    /// Set the minimum width of the column, default is 1200px
215    pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self {
216        let max_width = max_width.into();
217        self.max_width = max_width;
218
219        // If the current width is larger than the new maximum,
220        // pull the width down to match the maximum.
221        if self.width > max_width {
222            self.width = max_width;
223        }
224        self
225    }
226}
227
228impl FluentBuilder for Column {}
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub enum ColumnFixed {
232    Left,
233}
234
235/// Used to sort the column runtime info in Table internal.
236#[derive(Debug, Clone)]
237pub(crate) struct ColGroup {
238    pub(crate) column: Column,
239    /// This is the runtime width of the column, we may update it when the column is resized.
240    ///
241    /// Including the width with next columns by col_span.
242    pub(crate) width: Pixels,
243    /// The bounds of the column in the table after it renders.
244    pub(crate) bounds: Bounds<Pixels>,
245}
246
247impl ColGroup {
248    pub(crate) fn is_resizable(&self) -> bool {
249        self.column.resizable
250    }
251}
252
253#[derive(Clone)]
254pub(crate) struct DragColumn {
255    pub(crate) entity_id: EntityId,
256    pub(crate) name: SharedString,
257    pub(crate) width: Pixels,
258    pub(crate) col_ix: usize,
259}
260
261/// The sorting behavior of a column.
262#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
263pub enum ColumnSort {
264    /// No sorting.
265    #[default]
266    Default,
267    /// Sort in ascending order.
268    Ascending,
269    /// Sort in descending order.
270    Descending,
271}
272
273impl Render for DragColumn {
274    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
275        div()
276            .px_4()
277            .py_1()
278            .bg(cx.theme().tokens.table_head)
279            .text_color(cx.theme().muted_foreground)
280            .opacity(0.9)
281            .border_1()
282            .border_color(cx.theme().border)
283            .shadow_md()
284            .w(self.width)
285            .min_w(px(100.))
286            .max_w(px(450.))
287            .child(self.name.clone())
288    }
289}
290
291#[derive(Clone)]
292pub(crate) struct ResizeColumn(pub (EntityId, usize));
293impl Render for ResizeColumn {
294    fn render(&mut self, _window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
295        Empty
296    }
297}