1use crate::{
2 ActiveTheme, Sizable, Size, ThemeStyled as _,
3 actions::{
4 Cancel, SelectDown, SelectFirst, SelectLast, SelectNextColumn, SelectPageDown,
5 SelectPageUp, SelectPrevColumn, SelectUp,
6 },
7 scroll::ScrollbarMode,
8 table::{TableDelegate, TableState},
9};
10use gpui::{
11 App, Edges, Entity, Focusable, InteractiveElement, IntoElement, KeyBinding, ParentElement,
12 Pixels, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, div,
13 prelude::FluentBuilder,
14};
15use gpui_base::TestSupportExt as _;
16
17const CONTEXT: &'static str = "DataTable";
18pub(super) fn init(cx: &mut App) {
19 cx.bind_keys([
20 KeyBinding::new("escape", Cancel, Some(CONTEXT)),
21 KeyBinding::new("up", SelectUp, Some(CONTEXT)),
22 KeyBinding::new("down", SelectDown, Some(CONTEXT)),
23 KeyBinding::new("left", SelectPrevColumn, Some(CONTEXT)),
24 KeyBinding::new("right", SelectNextColumn, Some(CONTEXT)),
25 KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
26 KeyBinding::new("end", SelectLast, Some(CONTEXT)),
27 KeyBinding::new("pageup", SelectPageUp, Some(CONTEXT)),
28 KeyBinding::new("pagedown", SelectPageDown, Some(CONTEXT)),
29 ]);
30}
31
32pub(super) struct TableOptions {
33 pub(super) scroll_bounce: Option<bool>,
34 pub(super) scrollbar_visible: Edges<bool>,
35 pub(super) scrollbar_mode: Option<ScrollbarMode>,
36 pub(super) stripe: bool,
38 pub(super) bordered: bool,
40 pub(super) fixed_cols_border: bool,
42 pub(super) size: Size,
44 pub(super) header_row_height: Option<Pixels>,
46}
47
48impl Default for TableOptions {
49 fn default() -> Self {
50 Self {
51 scroll_bounce: None,
52 scrollbar_visible: Edges::all(true),
53 scrollbar_mode: None,
54 stripe: false,
55 bordered: true,
56 fixed_cols_border: true,
57 size: Size::default(),
58 header_row_height: None,
59 }
60 }
61}
62
63#[derive(IntoElement)]
101pub struct DataTable<D: TableDelegate> {
102 state: Entity<TableState<D>>,
103 options: TableOptions,
104 focus_ring_enabled: bool,
105 accessibility_label: Option<SharedString>,
106}
107
108impl<D> DataTable<D>
109where
110 D: TableDelegate,
111{
112 pub fn new(state: &Entity<TableState<D>>) -> Self {
114 Self {
115 state: state.clone(),
116 options: TableOptions::default(),
117 focus_ring_enabled: true,
118 accessibility_label: None,
119 }
120 }
121
122 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
124 self.accessibility_label = Some(label.into());
125 self
126 }
127
128 pub fn stripe(mut self, stripe: bool) -> Self {
130 self.options.stripe = stripe;
131 self
132 }
133
134 pub fn scroll_bounce(mut self, enabled: bool) -> Self {
138 self.options.scroll_bounce = Some(enabled);
139 self
140 }
141
142 pub fn bordered(mut self, bordered: bool) -> Self {
144 self.options.bordered = bordered;
145 self
146 }
147
148 pub fn header_row_height(mut self, height: impl Into<Pixels>) -> Self {
155 self.options.header_row_height = Some(height.into());
156 self
157 }
158
159 pub fn fixed_cols_border(mut self, fixed_cols_border: bool) -> Self {
166 self.options.fixed_cols_border = fixed_cols_border;
167 self
168 }
169
170 pub fn scrollbar_visible(mut self, vertical: bool, horizontal: bool) -> Self {
172 self.options.scrollbar_visible = Edges {
173 right: vertical,
174 bottom: horizontal,
175 ..Default::default()
176 };
177 self
178 }
179
180 pub fn scrollbar_mode(mut self, mode: ScrollbarMode) -> Self {
186 self.options.scrollbar_mode = Some(mode);
187 self
188 }
189}
190
191impl<D> Sizable for DataTable<D>
192where
193 D: TableDelegate,
194{
195 fn with_size(mut self, size: impl Into<Size>) -> Self {
196 self.options.size = size.into();
197 self
198 }
199}
200
201impl<D> crate::FocusableExt for DataTable<D>
202where
203 D: TableDelegate,
204{
205 fn focus_ring(mut self, enabled: bool) -> Self {
206 self.focus_ring_enabled = enabled;
207 self
208 }
209
210 fn is_focus_ring_enabled(&self) -> bool {
211 self.focus_ring_enabled
212 }
213}
214
215impl<D> RenderOnce for DataTable<D>
216where
217 D: TableDelegate,
218{
219 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
220 let bordered = self.options.bordered;
221 let focus_ring_enabled = self.focus_ring_enabled;
222 let focus_handle = self.state.focus_handle(cx);
223 let (role, rows_count, columns_count) = self.state.update(cx, |state, cx| {
224 state.options = self.options;
225 let role = if state.row_selectable || state.cell_selectable {
227 gpui::Role::Grid
228 } else {
229 gpui::Role::Table
230 };
231 let delegate = state.delegate();
232 (role, delegate.rows_count(cx), delegate.columns_count(cx))
233 });
234
235 div()
239 .id("table")
240 .test_support()
241 .role(role)
242 .when_some(self.accessibility_label, |this, label| {
243 this.aria_label(label)
244 })
245 .aria_row_count(rows_count + 1)
248 .aria_column_count(columns_count)
249 .size_full()
250 .key_context(CONTEXT)
251 .track_focus(&focus_handle)
252 .on_action(window.listener_for(&self.state, TableState::action_cancel))
253 .on_action(window.listener_for(&self.state, TableState::action_select_next))
254 .on_action(window.listener_for(&self.state, TableState::action_select_prev))
255 .on_action(window.listener_for(&self.state, TableState::action_select_next_col))
256 .on_action(window.listener_for(&self.state, TableState::action_select_prev_col))
257 .on_action(window.listener_for(&self.state, TableState::action_select_first_column))
258 .on_action(window.listener_for(&self.state, TableState::action_select_last_column))
259 .on_action(window.listener_for(&self.state, TableState::action_select_page_up))
260 .on_action(window.listener_for(&self.state, TableState::action_select_page_down))
261 .bg(cx.theme().tokens.table)
262 .when(bordered, |this| {
263 this.rounded(cx.theme().radius)
264 .border_1()
265 .border_color(cx.theme().border)
266 })
267 .child(self.state)
268 .when(
271 focus_ring_enabled
272 && focus_handle.is_focused(window)
273 && window.last_input_was_keyboard(),
274 |this| this.focus_ring_style(window, cx),
275 )
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use gpui::{
282 AppContext as _, Context, Entity, Render, TestAppContext, VisualTestContext, Window, div,
283 px,
284 };
285
286 use super::*;
287 use crate::{
288 FocusableExt as _,
289 table::{Column, TableState},
290 };
291
292 struct RowsDelegate;
293
294 impl TableDelegate for RowsDelegate {
295 fn columns_count(&self, _: &App) -> usize {
296 1
297 }
298 fn rows_count(&self, _: &App) -> usize {
299 3
300 }
301 fn column(&self, _: usize, _: &App) -> Column {
302 Column::new("name", "Name")
303 }
304 fn render_td(
305 &mut self,
306 row: usize,
307 _: usize,
308 _: &mut Window,
309 _: &mut Context<TableState<Self>>,
310 ) -> impl IntoElement {
311 div().child(row.to_string())
312 }
313 }
314
315 struct FocusRingHarness {
316 state: Entity<TableState<RowsDelegate>>,
317 focus_ring: bool,
318 }
319
320 impl Render for FocusRingHarness {
321 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
322 div()
323 .w(px(240.))
324 .h(px(160.))
325 .child(DataTable::new(&self.state).focus_ring(self.focus_ring))
326 }
327 }
328
329 fn keyboard_focused_table(cx: &mut TestAppContext, focus_ring: bool) -> &mut VisualTestContext {
332 cx.update(crate::init);
333 let (view, cx) = cx.add_window_view(move |window, cx| FocusRingHarness {
334 state: cx.new(|cx| TableState::new(RowsDelegate, window, cx)),
335 focus_ring,
336 });
337 let state = view.read_with(cx, |view, _| view.state.clone());
338 cx.update(|window, cx| {
339 let handle = state.focus_handle(cx);
340 window.focus(&handle, cx);
341 });
342 cx.simulate_keystrokes("down");
343 cx.update(|window, cx| window.draw(cx).clear(cx));
344 cx
345 }
346
347 #[gpui::test]
348 fn test_data_table_builder(cx: &mut TestAppContext) {
349 cx.update(crate::init);
350 let (view, cx) = cx.add_window_view(|window, cx| FocusRingHarness {
351 state: cx.new(|cx| TableState::new(RowsDelegate, window, cx)),
352 focus_ring: true,
353 });
354 let state = view.read_with(cx, |view, _| view.state.clone());
355 assert!(DataTable::new(&state).is_focus_ring_enabled());
356
357 let table = DataTable::new(&state)
358 .stripe(true)
359 .bordered(false)
360 .scroll_bounce(false)
361 .header_row_height(px(32.))
362 .fixed_cols_border(false)
363 .scrollbar_visible(false, true)
364 .scrollbar_mode(ScrollbarMode::Always)
365 .with_size(Size::Small)
366 .focus_ring(false);
367 assert!(table.options.stripe);
368 assert!(!table.options.bordered);
369 assert_eq!(table.options.scroll_bounce, Some(false));
370 assert_eq!(table.options.header_row_height, Some(px(32.)));
371 assert!(!table.options.fixed_cols_border);
372 assert!(!table.options.scrollbar_visible.right);
373 assert!(table.options.scrollbar_visible.bottom);
374 assert_eq!(table.options.scrollbar_mode, Some(ScrollbarMode::Always));
375 assert_eq!(table.options.size, Size::Small);
376 assert!(!table.is_focus_ring_enabled());
377 assert!(table.focus_ring(true).is_focus_ring_enabled());
378 }
379
380 #[gpui::test]
381 fn data_table_draws_the_focus_ring_by_default(cx: &mut TestAppContext) {
382 let cx = keyboard_focused_table(cx, true);
383 assert!(
384 cx.debug_bounds("focus-ring").is_some(),
385 "a keyboard-focused table draws its focus ring"
386 );
387 }
388
389 #[gpui::test]
390 fn data_table_focus_ring_can_be_turned_off(cx: &mut TestAppContext) {
391 let cx = keyboard_focused_table(cx, false);
392 assert!(
393 cx.debug_bounds("focus-ring").is_none(),
394 "`focus_ring(false)` must not draw a ring"
395 );
396 }
397}