table.rs

  1use std::{ops::Range, rc::Rc, time::Duration};
  2
  3use editor::{EditorSettings, ShowScrollbar, scroll::ScrollbarAutoHide};
  4use gpui::{
  5    AppContext, Axis, Context, Entity, FocusHandle, Length, ListHorizontalSizingBehavior,
  6    ListSizingBehavior, MouseButton, Task, UniformListScrollHandle, WeakEntity, transparent_black,
  7    uniform_list,
  8};
  9use settings::Settings as _;
 10use ui::{
 11    ActiveTheme as _, AnyElement, App, Button, ButtonCommon as _, ButtonStyle, Color, Component,
 12    ComponentScope, Div, ElementId, FixedWidth as _, FluentBuilder as _, Indicator,
 13    InteractiveElement as _, IntoElement, ParentElement, Pixels, RegisterComponent, RenderOnce,
 14    Scrollbar, ScrollbarState, StatefulInteractiveElement as _, Styled, StyledExt as _,
 15    StyledTypography, Window, div, example_group_with_title, h_flex, px, single_example, v_flex,
 16};
 17
 18struct UniformListData<const COLS: usize> {
 19    render_item_fn: Box<dyn Fn(Range<usize>, &mut Window, &mut App) -> Vec<[AnyElement; COLS]>>,
 20    element_id: ElementId,
 21    row_count: usize,
 22}
 23
 24enum TableContents<const COLS: usize> {
 25    Vec(Vec<[AnyElement; COLS]>),
 26    UniformList(UniformListData<COLS>),
 27}
 28
 29impl<const COLS: usize> TableContents<COLS> {
 30    fn rows_mut(&mut self) -> Option<&mut Vec<[AnyElement; COLS]>> {
 31        match self {
 32            TableContents::Vec(rows) => Some(rows),
 33            TableContents::UniformList(_) => None,
 34        }
 35    }
 36
 37    fn len(&self) -> usize {
 38        match self {
 39            TableContents::Vec(rows) => rows.len(),
 40            TableContents::UniformList(data) => data.row_count,
 41        }
 42    }
 43}
 44
 45pub struct TableInteractionState {
 46    pub focus_handle: FocusHandle,
 47    pub scroll_handle: UniformListScrollHandle,
 48    pub horizontal_scrollbar: ScrollbarProperties,
 49    pub vertical_scrollbar: ScrollbarProperties,
 50}
 51
 52impl TableInteractionState {
 53    pub fn new(window: &mut Window, cx: &mut App) -> Entity<Self> {
 54        cx.new(|cx| {
 55            let focus_handle = cx.focus_handle();
 56
 57            cx.on_focus_out(&focus_handle, window, |this: &mut Self, _, window, cx| {
 58                this.hide_scrollbars(window, cx);
 59            })
 60            .detach();
 61
 62            let scroll_handle = UniformListScrollHandle::new();
 63            let vertical_scrollbar = ScrollbarProperties {
 64                axis: Axis::Vertical,
 65                state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
 66                show_scrollbar: false,
 67                show_track: false,
 68                auto_hide: false,
 69                hide_task: None,
 70            };
 71
 72            let horizontal_scrollbar = ScrollbarProperties {
 73                axis: Axis::Horizontal,
 74                state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
 75                show_scrollbar: false,
 76                show_track: false,
 77                auto_hide: false,
 78                hide_task: None,
 79            };
 80
 81            let mut this = Self {
 82                focus_handle,
 83                scroll_handle,
 84                horizontal_scrollbar,
 85                vertical_scrollbar,
 86            };
 87
 88            this.update_scrollbar_visibility(cx);
 89            this
 90        })
 91    }
 92
 93    fn update_scrollbar_visibility(&mut self, cx: &mut Context<Self>) {
 94        let show_setting = EditorSettings::get_global(cx).scrollbar.show;
 95
 96        let scroll_handle = self.scroll_handle.0.borrow();
 97
 98        let autohide = |show: ShowScrollbar, cx: &mut Context<Self>| match show {
 99            ShowScrollbar::Auto => true,
100            ShowScrollbar::System => cx
101                .try_global::<ScrollbarAutoHide>()
102                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
103            ShowScrollbar::Always => false,
104            ShowScrollbar::Never => false,
105        };
106
107        let longest_item_width = scroll_handle.last_item_size.and_then(|size| {
108            (size.contents.width > size.item.width).then_some(size.contents.width)
109        });
110
111        // is there an item long enough that we should show a horizontal scrollbar?
112        let item_wider_than_container = if let Some(longest_item_width) = longest_item_width {
113            longest_item_width > px(scroll_handle.base_handle.bounds().size.width.0)
114        } else {
115            true
116        };
117
118        let show_scrollbar = match show_setting {
119            ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always => true,
120            ShowScrollbar::Never => false,
121        };
122        let show_vertical = show_scrollbar;
123
124        let show_horizontal = item_wider_than_container && show_scrollbar;
125
126        let show_horizontal_track =
127            show_horizontal && matches!(show_setting, ShowScrollbar::Always);
128
129        // TODO: we probably should hide the scroll track when the list doesn't need to scroll
130        let show_vertical_track = show_vertical && matches!(show_setting, ShowScrollbar::Always);
131
132        self.vertical_scrollbar = ScrollbarProperties {
133            axis: self.vertical_scrollbar.axis,
134            state: self.vertical_scrollbar.state.clone(),
135            show_scrollbar: show_vertical,
136            show_track: show_vertical_track,
137            auto_hide: autohide(show_setting, cx),
138            hide_task: None,
139        };
140
141        self.horizontal_scrollbar = ScrollbarProperties {
142            axis: self.horizontal_scrollbar.axis,
143            state: self.horizontal_scrollbar.state.clone(),
144            show_scrollbar: show_horizontal,
145            show_track: show_horizontal_track,
146            auto_hide: autohide(show_setting, cx),
147            hide_task: None,
148        };
149
150        cx.notify();
151    }
152
153    fn hide_scrollbars(&mut self, window: &mut Window, cx: &mut Context<Self>) {
154        self.horizontal_scrollbar.hide(window, cx);
155        self.vertical_scrollbar.hide(window, cx);
156    }
157
158    pub fn listener<E: ?Sized>(
159        this: &Entity<Self>,
160        f: impl Fn(&mut Self, &E, &mut Window, &mut Context<Self>) + 'static,
161    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
162        let view = this.downgrade();
163        move |e: &E, window: &mut Window, cx: &mut App| {
164            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
165        }
166    }
167
168    fn render_vertical_scrollbar_track(
169        this: &Entity<Self>,
170        parent: Div,
171        scroll_track_size: Pixels,
172        cx: &mut App,
173    ) -> Div {
174        if !this.read(cx).vertical_scrollbar.show_track {
175            return parent;
176        }
177        let child = v_flex()
178            .h_full()
179            .flex_none()
180            .w(scroll_track_size)
181            .bg(cx.theme().colors().background)
182            .child(
183                div()
184                    .size_full()
185                    .flex_1()
186                    .border_l_1()
187                    .border_color(cx.theme().colors().border),
188            );
189        parent.child(child)
190    }
191
192    fn render_vertical_scrollbar(this: &Entity<Self>, parent: Div, cx: &mut App) -> Div {
193        if !this.read(cx).vertical_scrollbar.show_scrollbar {
194            return parent;
195        }
196        let child = div()
197            .id(("table-vertical-scrollbar", this.entity_id()))
198            .occlude()
199            .flex_none()
200            .h_full()
201            .cursor_default()
202            .absolute()
203            .right_0()
204            .top_0()
205            .bottom_0()
206            .w(px(12.))
207            .on_mouse_move(Self::listener(this, |_, _, _, cx| {
208                cx.notify();
209                cx.stop_propagation()
210            }))
211            .on_hover(|_, _, cx| {
212                cx.stop_propagation();
213            })
214            .on_mouse_up(
215                MouseButton::Left,
216                Self::listener(this, |this, _, window, cx| {
217                    if !this.vertical_scrollbar.state.is_dragging()
218                        && !this.focus_handle.contains_focused(window, cx)
219                    {
220                        this.vertical_scrollbar.hide(window, cx);
221                        cx.notify();
222                    }
223
224                    cx.stop_propagation();
225                }),
226            )
227            .on_any_mouse_down(|_, _, cx| {
228                cx.stop_propagation();
229            })
230            .on_scroll_wheel(Self::listener(&this, |_, _, _, cx| {
231                cx.notify();
232            }))
233            .children(Scrollbar::vertical(
234                this.read(cx).vertical_scrollbar.state.clone(),
235            ));
236        parent.child(child)
237    }
238
239    /// Renders the horizontal scrollbar.
240    ///
241    /// The right offset is used to determine how far to the right the
242    /// scrollbar should extend to, useful for ensuring it doesn't collide
243    /// with the vertical scrollbar when visible.
244    fn render_horizontal_scrollbar(
245        this: &Entity<Self>,
246        parent: Div,
247        right_offset: Pixels,
248        cx: &mut App,
249    ) -> Div {
250        if !this.read(cx).horizontal_scrollbar.show_scrollbar {
251            return parent;
252        }
253        let child = div()
254            .id(("table-horizontal-scrollbar", this.entity_id()))
255            .occlude()
256            .flex_none()
257            .w_full()
258            .cursor_default()
259            .absolute()
260            .bottom_neg_px()
261            .left_0()
262            .right_0()
263            .pr(right_offset)
264            .on_mouse_move(Self::listener(this, |_, _, _, cx| {
265                cx.notify();
266                cx.stop_propagation()
267            }))
268            .on_hover(|_, _, cx| {
269                cx.stop_propagation();
270            })
271            .on_any_mouse_down(|_, _, cx| {
272                cx.stop_propagation();
273            })
274            .on_mouse_up(
275                MouseButton::Left,
276                Self::listener(this, |this, _, window, cx| {
277                    if !this.horizontal_scrollbar.state.is_dragging()
278                        && !this.focus_handle.contains_focused(window, cx)
279                    {
280                        this.horizontal_scrollbar.hide(window, cx);
281                        cx.notify();
282                    }
283
284                    cx.stop_propagation();
285                }),
286            )
287            .on_scroll_wheel(Self::listener(this, |_, _, _, cx| {
288                cx.notify();
289            }))
290            .children(Scrollbar::horizontal(
291                // percentage as f32..end_offset as f32,
292                this.read(cx).horizontal_scrollbar.state.clone(),
293            ));
294        parent.child(child)
295    }
296
297    fn render_horizontal_scrollbar_track(
298        this: &Entity<Self>,
299        parent: Div,
300        scroll_track_size: Pixels,
301        cx: &mut App,
302    ) -> Div {
303        if !this.read(cx).horizontal_scrollbar.show_track {
304            return parent;
305        }
306        let child = h_flex()
307            .w_full()
308            .h(scroll_track_size)
309            .flex_none()
310            .relative()
311            .child(
312                div()
313                    .w_full()
314                    .flex_1()
315                    // for some reason the horizontal scrollbar is 1px
316                    // taller than the vertical scrollbar??
317                    .h(scroll_track_size - px(1.))
318                    .bg(cx.theme().colors().background)
319                    .border_t_1()
320                    .border_color(cx.theme().colors().border),
321            )
322            .when(this.read(cx).vertical_scrollbar.show_track, |parent| {
323                parent
324                    .child(
325                        div()
326                            .flex_none()
327                            // -1px prevents a missing pixel between the two container borders
328                            .w(scroll_track_size - px(1.))
329                            .h_full(),
330                    )
331                    .child(
332                        // HACK: Fill the missing 1px 🥲
333                        div()
334                            .absolute()
335                            .right(scroll_track_size - px(1.))
336                            .bottom(scroll_track_size - px(1.))
337                            .size_px()
338                            .bg(cx.theme().colors().border),
339                    )
340            });
341
342        parent.child(child)
343    }
344}
345
346/// A table component
347#[derive(RegisterComponent, IntoElement)]
348pub struct Table<const COLS: usize = 3> {
349    striped: bool,
350    width: Option<Length>,
351    headers: Option<[AnyElement; COLS]>,
352    rows: TableContents<COLS>,
353    interaction_state: Option<WeakEntity<TableInteractionState>>,
354    column_widths: Option<[Length; COLS]>,
355    map_row: Option<Rc<dyn Fn((usize, Div), &mut Window, &mut App) -> AnyElement>>,
356}
357
358impl<const COLS: usize> Table<COLS> {
359    /// number of headers provided.
360    pub fn new() -> Self {
361        Table {
362            striped: false,
363            width: None,
364            headers: None,
365            rows: TableContents::Vec(Vec::new()),
366            interaction_state: None,
367            column_widths: None,
368            map_row: None,
369        }
370    }
371
372    /// Enables uniform list rendering.
373    /// The provided function will be passed directly to the `uniform_list` element.
374    /// Therefore, if this method is called, any calls to [`Table::row`] before or after
375    /// this method is called will be ignored.
376    pub fn uniform_list(
377        mut self,
378        id: impl Into<ElementId>,
379        row_count: usize,
380        render_item_fn: impl Fn(Range<usize>, &mut Window, &mut App) -> Vec<[AnyElement; COLS]>
381        + 'static,
382    ) -> Self {
383        self.rows = TableContents::UniformList(UniformListData {
384            element_id: id.into(),
385            row_count: row_count,
386            render_item_fn: Box::new(render_item_fn),
387        });
388        self
389    }
390
391    /// Enables row striping.
392    pub fn striped(mut self) -> Self {
393        self.striped = true;
394        self
395    }
396
397    /// Sets the width of the table.
398    /// Will enable horizontal scrolling if [`Self::interactable`] is also called.
399    pub fn width(mut self, width: impl Into<Length>) -> Self {
400        self.width = Some(width.into());
401        self
402    }
403
404    /// Enables interaction (primarily scrolling) with the table.
405    ///
406    /// Vertical scrolling will be enabled by default if the table is taller than its container.
407    ///
408    /// Horizontal scrolling will only be enabled if [`Self::width`] is also called, otherwise
409    /// the list will always shrink the table columns to fit their contents I.e. If [`Self::uniform_list`]
410    /// is used without a width and with [`Self::interactable`], the [`ListHorizontalSizingBehavior`] will
411    /// be set to [`ListHorizontalSizingBehavior::FitList`].
412    pub fn interactable(mut self, interaction_state: &Entity<TableInteractionState>) -> Self {
413        self.interaction_state = Some(interaction_state.downgrade());
414        self
415    }
416
417    pub fn header(mut self, headers: [impl IntoElement; COLS]) -> Self {
418        self.headers = Some(headers.map(IntoElement::into_any_element));
419        self
420    }
421
422    pub fn row(mut self, items: [impl IntoElement; COLS]) -> Self {
423        if let Some(rows) = self.rows.rows_mut() {
424            rows.push(items.map(IntoElement::into_any_element));
425        }
426        self
427    }
428
429    pub fn column_widths(mut self, widths: [impl Into<Length>; COLS]) -> Self {
430        self.column_widths = Some(widths.map(Into::into));
431        self
432    }
433
434    pub fn map_row(
435        mut self,
436        callback: impl Fn((usize, Div), &mut Window, &mut App) -> AnyElement + 'static,
437    ) -> Self {
438        self.map_row = Some(Rc::new(callback));
439        self
440    }
441}
442
443fn base_cell_style(width: Option<Length>, cx: &App) -> Div {
444    div()
445        .px_1p5()
446        .when_some(width, |this, width| this.w(width))
447        .when(width.is_none(), |this| this.flex_1())
448        .justify_start()
449        .text_ui(cx)
450        .whitespace_nowrap()
451        .text_ellipsis()
452        .overflow_hidden()
453}
454
455pub fn render_row<const COLS: usize>(
456    row_index: usize,
457    items: [impl IntoElement; COLS],
458    table_context: TableRenderContext<COLS>,
459    window: &mut Window,
460    cx: &mut App,
461) -> AnyElement {
462    let is_striped = table_context.striped;
463    let is_last = row_index == table_context.total_row_count - 1;
464    let bg = if row_index % 2 == 1 && is_striped {
465        Some(cx.theme().colors().text.opacity(0.05))
466    } else {
467        None
468    };
469    let column_widths = table_context
470        .column_widths
471        .map_or([None; COLS], |widths| widths.map(Some));
472
473    let row = div().w_full().child(
474        h_flex()
475            .id("table_row")
476            .w_full()
477            .justify_between()
478            .px_1p5()
479            .py_1()
480            .when_some(bg, |row, bg| row.bg(bg))
481            .when(!is_striped, |row| {
482                row.border_b_1()
483                    .border_color(transparent_black())
484                    .when(!is_last, |row| row.border_color(cx.theme().colors().border))
485            })
486            .children(
487                items
488                    .map(IntoElement::into_any_element)
489                    .into_iter()
490                    .zip(column_widths)
491                    .map(|(cell, width)| base_cell_style(width, cx).child(cell)),
492            ),
493    );
494
495    if let Some(map_row) = table_context.map_row {
496        map_row((row_index, row), window, cx)
497    } else {
498        row.into_any_element()
499    }
500}
501
502pub fn render_header<const COLS: usize>(
503    headers: [impl IntoElement; COLS],
504    table_context: TableRenderContext<COLS>,
505    cx: &mut App,
506) -> impl IntoElement {
507    let column_widths = table_context
508        .column_widths
509        .map_or([None; COLS], |widths| widths.map(Some));
510    div()
511        .flex()
512        .flex_row()
513        .items_center()
514        .justify_between()
515        .w_full()
516        .p_2()
517        .border_b_1()
518        .border_color(cx.theme().colors().border)
519        .children(
520            headers
521                .into_iter()
522                .zip(column_widths)
523                .map(|(h, width)| base_cell_style(width, cx).child(h)),
524        )
525}
526
527#[derive(Clone)]
528pub struct TableRenderContext<const COLS: usize> {
529    pub striped: bool,
530    pub total_row_count: usize,
531    pub column_widths: Option<[Length; COLS]>,
532    pub map_row: Option<Rc<dyn Fn((usize, Div), &mut Window, &mut App) -> AnyElement>>,
533}
534
535impl<const COLS: usize> TableRenderContext<COLS> {
536    fn new(table: &Table<COLS>) -> Self {
537        Self {
538            striped: table.striped,
539            total_row_count: table.rows.len(),
540            column_widths: table.column_widths,
541            map_row: table.map_row.clone(),
542        }
543    }
544}
545
546impl<const COLS: usize> RenderOnce for Table<COLS> {
547    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
548        let table_context = TableRenderContext::new(&self);
549        let interaction_state = self.interaction_state.and_then(|state| state.upgrade());
550
551        let scroll_track_size = px(16.);
552        let h_scroll_offset = if interaction_state
553            .as_ref()
554            .is_some_and(|state| state.read(cx).vertical_scrollbar.show_scrollbar)
555        {
556            // magic number
557            px(3.)
558        } else {
559            px(0.)
560        };
561
562        let width = self.width;
563
564        let table = div()
565            .when_some(width, |this, width| this.w(width))
566            .h_full()
567            .v_flex()
568            .when_some(self.headers.take(), |this, headers| {
569                this.child(render_header(headers, table_context.clone(), cx))
570            })
571            .child(
572                div()
573                    .flex_grow()
574                    .w_full()
575                    .relative()
576                    .overflow_hidden()
577                    .map(|parent| match self.rows {
578                        TableContents::Vec(items) => {
579                            parent.children(items.into_iter().enumerate().map(|(index, row)| {
580                                render_row(index, row, table_context.clone(), window, cx)
581                            }))
582                        }
583                        TableContents::UniformList(uniform_list_data) => parent.child(
584                            uniform_list(
585                                uniform_list_data.element_id,
586                                uniform_list_data.row_count,
587                                {
588                                    let render_item_fn = uniform_list_data.render_item_fn;
589                                    move |range: Range<usize>, window, cx| {
590                                        let elements = render_item_fn(range.clone(), window, cx);
591                                        elements
592                                            .into_iter()
593                                            .zip(range)
594                                            .map(|(row, row_index)| {
595                                                render_row(
596                                                    row_index,
597                                                    row,
598                                                    table_context.clone(),
599                                                    window,
600                                                    cx,
601                                                )
602                                            })
603                                            .collect()
604                                    }
605                                },
606                            )
607                            .size_full()
608                            .flex_grow()
609                            .with_sizing_behavior(ListSizingBehavior::Auto)
610                            .with_horizontal_sizing_behavior(if width.is_some() {
611                                ListHorizontalSizingBehavior::Unconstrained
612                            } else {
613                                ListHorizontalSizingBehavior::FitList
614                            })
615                            .when_some(
616                                interaction_state.as_ref(),
617                                |this, state| {
618                                    this.track_scroll(
619                                        state.read_with(cx, |s, _| s.scroll_handle.clone()),
620                                    )
621                                },
622                            ),
623                        ),
624                    })
625                    .when_some(interaction_state.as_ref(), |this, interaction_state| {
626                        this.map(|this| {
627                            TableInteractionState::render_vertical_scrollbar_track(
628                                interaction_state,
629                                this,
630                                scroll_track_size,
631                                cx,
632                            )
633                        })
634                        .map(|this| {
635                            TableInteractionState::render_vertical_scrollbar(
636                                interaction_state,
637                                this,
638                                cx,
639                            )
640                        })
641                    }),
642            )
643            .when_some(
644                width.and(interaction_state.as_ref()),
645                |this, interaction_state| {
646                    this.map(|this| {
647                        TableInteractionState::render_horizontal_scrollbar_track(
648                            interaction_state,
649                            this,
650                            scroll_track_size,
651                            cx,
652                        )
653                    })
654                    .map(|this| {
655                        TableInteractionState::render_horizontal_scrollbar(
656                            interaction_state,
657                            this,
658                            h_scroll_offset,
659                            cx,
660                        )
661                    })
662                },
663            );
664
665        if let Some(interaction_state) = interaction_state.as_ref() {
666            table
667                .track_focus(&interaction_state.read(cx).focus_handle)
668                .id(("table", interaction_state.entity_id()))
669                .on_hover({
670                    let interaction_state = interaction_state.downgrade();
671                    move |hovered, window, cx| {
672                        interaction_state
673                            .update(cx, |interaction_state, cx| {
674                                if *hovered {
675                                    interaction_state.horizontal_scrollbar.show(cx);
676                                    interaction_state.vertical_scrollbar.show(cx);
677                                    cx.notify();
678                                } else if !interaction_state
679                                    .focus_handle
680                                    .contains_focused(window, cx)
681                                {
682                                    interaction_state.hide_scrollbars(window, cx);
683                                }
684                            })
685                            .ok();
686                    }
687                })
688                .into_any_element()
689        } else {
690            table.into_any_element()
691        }
692    }
693}
694
695// computed state related to how to render scrollbars
696// one per axis
697// on render we just read this off the keymap editor
698// we update it when
699// - settings change
700// - on focus in, on focus out, on hover, etc.
701#[derive(Debug)]
702pub struct ScrollbarProperties {
703    axis: Axis,
704    show_scrollbar: bool,
705    show_track: bool,
706    auto_hide: bool,
707    hide_task: Option<Task<()>>,
708    state: ScrollbarState,
709}
710
711impl ScrollbarProperties {
712    // Shows the scrollbar and cancels any pending hide task
713    fn show(&mut self, cx: &mut Context<TableInteractionState>) {
714        if !self.auto_hide {
715            return;
716        }
717        self.show_scrollbar = true;
718        self.hide_task.take();
719        cx.notify();
720    }
721
722    fn hide(&mut self, window: &mut Window, cx: &mut Context<TableInteractionState>) {
723        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
724
725        if !self.auto_hide {
726            return;
727        }
728
729        let axis = self.axis;
730        self.hide_task = Some(cx.spawn_in(window, async move |keymap_editor, cx| {
731            cx.background_executor()
732                .timer(SCROLLBAR_SHOW_INTERVAL)
733                .await;
734
735            if let Some(keymap_editor) = keymap_editor.upgrade() {
736                keymap_editor
737                    .update(cx, |keymap_editor, cx| {
738                        match axis {
739                            Axis::Vertical => {
740                                keymap_editor.vertical_scrollbar.show_scrollbar = false
741                            }
742                            Axis::Horizontal => {
743                                keymap_editor.horizontal_scrollbar.show_scrollbar = false
744                            }
745                        }
746                        cx.notify();
747                    })
748                    .ok();
749            }
750        }));
751    }
752}
753
754impl Component for Table<3> {
755    fn scope() -> ComponentScope {
756        ComponentScope::Layout
757    }
758
759    fn description() -> Option<&'static str> {
760        Some("A table component for displaying data in rows and columns with optional styling.")
761    }
762
763    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
764        Some(
765            v_flex()
766                .gap_6()
767                .children(vec![
768                    example_group_with_title(
769                        "Basic Tables",
770                        vec![
771                            single_example(
772                                "Simple Table",
773                                Table::new()
774                                    .width(px(400.))
775                                    .header(["Name", "Age", "City"])
776                                    .row(["Alice", "28", "New York"])
777                                    .row(["Bob", "32", "San Francisco"])
778                                    .row(["Charlie", "25", "London"])
779                                    .into_any_element(),
780                            ),
781                            single_example(
782                                "Two Column Table",
783                                Table::new()
784                                    .header(["Category", "Value"])
785                                    .width(px(300.))
786                                    .row(["Revenue", "$100,000"])
787                                    .row(["Expenses", "$75,000"])
788                                    .row(["Profit", "$25,000"])
789                                    .into_any_element(),
790                            ),
791                        ],
792                    ),
793                    example_group_with_title(
794                        "Styled Tables",
795                        vec![
796                            single_example(
797                                "Default",
798                                Table::new()
799                                    .width(px(400.))
800                                    .header(["Product", "Price", "Stock"])
801                                    .row(["Laptop", "$999", "In Stock"])
802                                    .row(["Phone", "$599", "Low Stock"])
803                                    .row(["Tablet", "$399", "Out of Stock"])
804                                    .into_any_element(),
805                            ),
806                            single_example(
807                                "Striped",
808                                Table::new()
809                                    .width(px(400.))
810                                    .striped()
811                                    .header(["Product", "Price", "Stock"])
812                                    .row(["Laptop", "$999", "In Stock"])
813                                    .row(["Phone", "$599", "Low Stock"])
814                                    .row(["Tablet", "$399", "Out of Stock"])
815                                    .row(["Headphones", "$199", "In Stock"])
816                                    .into_any_element(),
817                            ),
818                        ],
819                    ),
820                    example_group_with_title(
821                        "Mixed Content Table",
822                        vec![single_example(
823                            "Table with Elements",
824                            Table::new()
825                                .width(px(840.))
826                                .header(["Status", "Name", "Priority", "Deadline", "Action"])
827                                .row([
828                                    Indicator::dot().color(Color::Success).into_any_element(),
829                                    "Project A".into_any_element(),
830                                    "High".into_any_element(),
831                                    "2023-12-31".into_any_element(),
832                                    Button::new("view_a", "View")
833                                        .style(ButtonStyle::Filled)
834                                        .full_width()
835                                        .into_any_element(),
836                                ])
837                                .row([
838                                    Indicator::dot().color(Color::Warning).into_any_element(),
839                                    "Project B".into_any_element(),
840                                    "Medium".into_any_element(),
841                                    "2024-03-15".into_any_element(),
842                                    Button::new("view_b", "View")
843                                        .style(ButtonStyle::Filled)
844                                        .full_width()
845                                        .into_any_element(),
846                                ])
847                                .row([
848                                    Indicator::dot().color(Color::Error).into_any_element(),
849                                    "Project C".into_any_element(),
850                                    "Low".into_any_element(),
851                                    "2024-06-30".into_any_element(),
852                                    Button::new("view_c", "View")
853                                        .style(ButtonStyle::Filled)
854                                        .full_width()
855                                        .into_any_element(),
856                                ])
857                                .into_any_element(),
858                        )],
859                    ),
860                ])
861                .into_any_element(),
862        )
863    }
864}