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(1200.),
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 maximum width when resizing the column, default is 1200px.
215    ///
216    /// The default protects against oversized columns during resizing. Set a
217    /// larger maximum explicitly when wider columns are needed. It does not
218    /// limit an initial width set afterwards with [`Self::width`].
219    pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self {
220        let max_width = max_width.into();
221        self.max_width = max_width;
222
223        // If the current width is larger than the new maximum,
224        // pull the width down to match the maximum.
225        if self.width > max_width {
226            self.width = max_width;
227        }
228        self
229    }
230}
231
232impl FluentBuilder for Column {}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum ColumnFixed {
236    Left,
237}
238
239/// Used to sort the column runtime info in Table internal.
240#[derive(Debug, Clone)]
241pub(crate) struct ColGroup {
242    pub(crate) column: Column,
243    /// This is the runtime width of the column, we may update it when the column is resized.
244    ///
245    /// Including the width with next columns by col_span.
246    pub(crate) width: Pixels,
247    /// The bounds of the column in the table after it renders.
248    pub(crate) bounds: Bounds<Pixels>,
249}
250
251impl ColGroup {
252    pub(crate) fn is_resizable(&self) -> bool {
253        self.column.resizable
254    }
255}
256
257#[derive(Clone)]
258pub(crate) struct DragColumn {
259    pub(crate) entity_id: EntityId,
260    pub(crate) name: SharedString,
261    pub(crate) width: Pixels,
262    pub(crate) col_ix: usize,
263}
264
265/// The sorting behavior of a column.
266#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
267pub enum ColumnSort {
268    /// No sorting.
269    #[default]
270    Default,
271    /// Sort in ascending order.
272    Ascending,
273    /// Sort in descending order.
274    Descending,
275}
276
277impl Render for DragColumn {
278    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
279        div()
280            .px_4()
281            .py_1()
282            .bg(cx.theme().tokens.table_head)
283            .text_color(cx.theme().muted_foreground)
284            .opacity(0.9)
285            .border_1()
286            .border_color(cx.theme().border)
287            .shadow_md()
288            .w(self.width)
289            .min_w(px(100.))
290            .max_w(px(450.))
291            .child(self.name.clone())
292    }
293}
294
295#[derive(Clone)]
296pub(crate) struct ResizeColumn(pub (EntityId, usize));
297impl Render for ResizeColumn {
298    fn render(&mut self, _window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
299        Empty
300    }
301}