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, FontWeight, Length,
  6    ListHorizontalSizingBehavior, ListSizingBehavior, MouseButton, Stateful, Task,
  7    UniformListScrollHandle, WeakEntity, transparent_black, 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    // fn listener(this: Entity<Self>, fn: F) ->
159
160    pub fn listener<E: ?Sized>(
161        this: &Entity<Self>,
162        f: impl Fn(&mut Self, &E, &mut Window, &mut Context<Self>) + 'static,
163    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
164        let view = this.downgrade();
165        move |e: &E, window: &mut Window, cx: &mut App| {
166            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
167        }
168    }
169
170    fn render_vertical_scrollbar_track(
171        this: &Entity<Self>,
172        parent: Div,
173        scroll_track_size: Pixels,
174        cx: &mut App,
175    ) -> Div {
176        if !this.read(cx).vertical_scrollbar.show_track {
177            return parent;
178        }
179        let child = v_flex()
180            .h_full()
181            .flex_none()
182            .w(scroll_track_size)
183            .bg(cx.theme().colors().background)
184            .child(
185                div()
186                    .size_full()
187                    .flex_1()
188                    .border_l_1()
189                    .border_color(cx.theme().colors().border),
190            );
191        parent.child(child)
192    }
193
194    fn render_vertical_scrollbar(this: &Entity<Self>, parent: Div, cx: &mut App) -> Div {
195        if !this.read(cx).vertical_scrollbar.show_scrollbar {
196            return parent;
197        }
198        let child = div()
199            .id("keymap-editor-vertical-scroll")
200            .occlude()
201            .flex_none()
202            .h_full()
203            .cursor_default()
204            .absolute()
205            .right_0()
206            .top_0()
207            .bottom_0()
208            .w(px(12.))
209            .on_mouse_move(Self::listener(this, |_, _, _, cx| {
210                cx.notify();
211                cx.stop_propagation()
212            }))
213            .on_hover(|_, _, cx| {
214                cx.stop_propagation();
215            })
216            .on_mouse_up(
217                MouseButton::Left,
218                Self::listener(this, |this, _, window, cx| {
219                    if !this.vertical_scrollbar.state.is_dragging()
220                        && !this.focus_handle.contains_focused(window, cx)
221                    {
222                        this.vertical_scrollbar.hide(window, cx);
223                        cx.notify();
224                    }
225
226                    cx.stop_propagation();
227                }),
228            )
229            .on_any_mouse_down(|_, _, cx| {
230                cx.stop_propagation();
231            })
232            .on_scroll_wheel(Self::listener(&this, |_, _, _, cx| {
233                cx.notify();
234            }))
235            .children(Scrollbar::vertical(
236                this.read(cx).vertical_scrollbar.state.clone(),
237            ));
238        parent.child(child)
239    }
240
241    /// Renders the horizontal scrollbar.
242    ///
243    /// The right offset is used to determine how far to the right the
244    /// scrollbar should extend to, useful for ensuring it doesn't collide
245    /// with the vertical scrollbar when visible.
246    fn render_horizontal_scrollbar(
247        this: &Entity<Self>,
248        parent: Stateful<Div>,
249        right_offset: Pixels,
250        cx: &mut App,
251    ) -> Stateful<Div> {
252        if !this.read(cx).horizontal_scrollbar.show_scrollbar {
253            return parent;
254        }
255        let child = div()
256            .id("keymap-editor-horizontal-scroll")
257            .occlude()
258            .flex_none()
259            .w_full()
260            .cursor_default()
261            .absolute()
262            .bottom_neg_px()
263            .left_0()
264            .right_0()
265            .pr(right_offset)
266            .on_mouse_move(Self::listener(this, |_, _, _, cx| {
267                cx.notify();
268                cx.stop_propagation()
269            }))
270            .on_hover(|_, _, cx| {
271                cx.stop_propagation();
272            })
273            .on_any_mouse_down(|_, _, cx| {
274                cx.stop_propagation();
275            })
276            .on_mouse_up(
277                MouseButton::Left,
278                Self::listener(this, |this, _, window, cx| {
279                    if !this.horizontal_scrollbar.state.is_dragging()
280                        && !this.focus_handle.contains_focused(window, cx)
281                    {
282                        this.horizontal_scrollbar.hide(window, cx);
283                        cx.notify();
284                    }
285
286                    cx.stop_propagation();
287                }),
288            )
289            .on_scroll_wheel(Self::listener(this, |_, _, _, cx| {
290                cx.notify();
291            }))
292            .children(Scrollbar::horizontal(
293                // percentage as f32..end_offset as f32,
294                this.read(cx).horizontal_scrollbar.state.clone(),
295            ));
296        parent.child(child)
297    }
298
299    fn render_horizantal_scrollbar_track(
300        this: &Entity<Self>,
301        parent: Stateful<Div>,
302        scroll_track_size: Pixels,
303        cx: &mut App,
304    ) -> Stateful<Div> {
305        if !this.read(cx).horizontal_scrollbar.show_track {
306            return parent;
307        }
308        let child = h_flex()
309            .w_full()
310            .h(scroll_track_size)
311            .flex_none()
312            .relative()
313            .child(
314                div()
315                    .w_full()
316                    .flex_1()
317                    // for some reason the horizontal scrollbar is 1px
318                    // taller than the vertical scrollbar??
319                    .h(scroll_track_size - px(1.))
320                    .bg(cx.theme().colors().background)
321                    .border_t_1()
322                    .border_color(cx.theme().colors().border),
323            )
324            .when(this.read(cx).vertical_scrollbar.show_track, |parent| {
325                parent
326                    .child(
327                        div()
328                            .flex_none()
329                            // -1px prevents a missing pixel between the two container borders
330                            .w(scroll_track_size - px(1.))
331                            .h_full(),
332                    )
333                    .child(
334                        // HACK: Fill the missing 1px 🥲
335                        div()
336                            .absolute()
337                            .right(scroll_track_size - px(1.))
338                            .bottom(scroll_track_size - px(1.))
339                            .size_px()
340                            .bg(cx.theme().colors().border),
341                    )
342            });
343
344        parent.child(child)
345    }
346}
347
348/// A table component
349#[derive(RegisterComponent, IntoElement)]
350pub struct Table<const COLS: usize = 3> {
351    striped: bool,
352    width: Length,
353    headers: Option<[AnyElement; COLS]>,
354    rows: TableContents<COLS>,
355    interaction_state: Option<WeakEntity<TableInteractionState>>,
356    selected_item_index: Option<usize>,
357    column_widths: Option<[Length; COLS]>,
358    on_click_row: Option<Rc<dyn Fn(usize, &mut Window, &mut App)>>,
359}
360
361impl<const COLS: usize> Table<COLS> {
362    /// number of headers provided.
363    pub fn new() -> Self {
364        Table {
365            striped: false,
366            width: Length::Auto,
367            headers: None,
368            rows: TableContents::Vec(Vec::new()),
369            interaction_state: None,
370            selected_item_index: None,
371            column_widths: None,
372            on_click_row: None,
373        }
374    }
375
376    /// Enables uniform list rendering.
377    /// The provided function will be passed directly to the `uniform_list` element.
378    /// Therefore, if this method is called, any calls to [`Table::row`] before or after
379    /// this method is called will be ignored.
380    pub fn uniform_list(
381        mut self,
382        id: impl Into<ElementId>,
383        row_count: usize,
384        render_item_fn: impl Fn(Range<usize>, &mut Window, &mut App) -> Vec<[AnyElement; COLS]>
385        + 'static,
386    ) -> Self {
387        self.rows = TableContents::UniformList(UniformListData {
388            element_id: id.into(),
389            row_count: row_count,
390            render_item_fn: Box::new(render_item_fn),
391        });
392        self
393    }
394
395    /// Enables row striping.
396    pub fn striped(mut self) -> Self {
397        self.striped = true;
398        self
399    }
400
401    /// Sets the width of the table.
402    pub fn width(mut self, width: impl Into<Length>) -> Self {
403        self.width = width.into();
404        self
405    }
406
407    pub fn interactable(mut self, interaction_state: &Entity<TableInteractionState>) -> Self {
408        self.interaction_state = Some(interaction_state.downgrade());
409        self
410    }
411
412    pub fn selected_item_index(mut self, selected_item_index: Option<usize>) -> Self {
413        self.selected_item_index = selected_item_index;
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 on_click_row(
435        mut self,
436        callback: impl Fn(usize, &mut Window, &mut App) + 'static,
437    ) -> Self {
438        self.on_click_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    cx: &App,
460) -> AnyElement {
461    let is_striped = table_context.striped;
462    let is_last = row_index == table_context.total_row_count - 1;
463    let bg = if row_index % 2 == 1 && is_striped {
464        Some(cx.theme().colors().text.opacity(0.05))
465    } else {
466        None
467    };
468    let column_widths = table_context
469        .column_widths
470        .map_or([None; COLS], |widths| widths.map(|width| Some(width)));
471    let is_selected = table_context.selected_item_index == Some(row_index);
472
473    let row = div()
474        .w_full()
475        .border_2()
476        .border_color(transparent_black())
477        .when(is_selected, |row| {
478            row.border_color(cx.theme().colors().panel_focused_border)
479        })
480        .child(
481            div()
482                .w_full()
483                .flex()
484                .flex_row()
485                .items_center()
486                .justify_between()
487                .px_1p5()
488                .py_1()
489                .when_some(bg, |row, bg| row.bg(bg))
490                .when(!is_striped, |row| {
491                    row.border_b_1()
492                        .border_color(transparent_black())
493                        .when(!is_last, |row| row.border_color(cx.theme().colors().border))
494                })
495                .children(
496                    items
497                        .map(IntoElement::into_any_element)
498                        .into_iter()
499                        .zip(column_widths)
500                        .map(|(cell, width)| base_cell_style(width, cx).child(cell)),
501                ),
502        );
503
504    if let Some(on_click) = table_context.on_click_row {
505        row.id(ElementId::named_usize("table-row", row_index))
506            .on_click(move |_, window, cx| on_click(row_index, window, cx))
507            .into_any_element()
508    } else {
509        row.into_any_element()
510    }
511}
512
513pub fn render_header<const COLS: usize>(
514    headers: [impl IntoElement; COLS],
515    table_context: TableRenderContext<COLS>,
516    cx: &mut App,
517) -> impl IntoElement {
518    let column_widths = table_context
519        .column_widths
520        .map_or([None; COLS], |widths| widths.map(|width| Some(width)));
521    div()
522        .flex()
523        .flex_row()
524        .items_center()
525        .justify_between()
526        .w_full()
527        .p_2()
528        .border_b_1()
529        .border_color(cx.theme().colors().border)
530        .children(headers.into_iter().zip(column_widths).map(|(h, width)| {
531            base_cell_style(width, cx)
532                .font_weight(FontWeight::SEMIBOLD)
533                .child(h)
534        }))
535}
536
537#[derive(Clone)]
538pub struct TableRenderContext<const COLS: usize> {
539    pub striped: bool,
540    pub total_row_count: usize,
541    pub selected_item_index: Option<usize>,
542    pub column_widths: Option<[Length; COLS]>,
543    pub on_click_row: Option<Rc<dyn Fn(usize, &mut Window, &mut App)>>,
544}
545
546impl<const COLS: usize> TableRenderContext<COLS> {
547    fn new(table: &Table<COLS>) -> Self {
548        Self {
549            striped: table.striped,
550            total_row_count: table.rows.len(),
551            column_widths: table.column_widths,
552            selected_item_index: table.selected_item_index.clone(),
553            on_click_row: table.on_click_row.clone(),
554        }
555    }
556}
557
558impl<const COLS: usize> RenderOnce for Table<COLS> {
559    fn render(mut self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
560        // match self.ro
561        let table_context = TableRenderContext::new(&self);
562        let interaction_state = self.interaction_state.and_then(|state| state.upgrade());
563
564        let scroll_track_size = px(16.);
565        let h_scroll_offset = if interaction_state
566            .as_ref()
567            .is_some_and(|state| state.read(cx).vertical_scrollbar.show_scrollbar)
568        {
569            // magic number
570            px(3.)
571        } else {
572            px(0.)
573        };
574
575        div()
576            .id("todo! how to have id")
577            .w(self.width)
578            .h_full()
579            .v_flex()
580            .when_some(interaction_state.as_ref(), |this, interaction_state| {
581                this.track_focus(&interaction_state.read(cx).focus_handle)
582                    .on_hover({
583                        let interaction_state = interaction_state.downgrade();
584                        move |hovered, window, cx| {
585                            interaction_state
586                                .update(cx, |interaction_state, cx| {
587                                    if *hovered {
588                                        interaction_state.horizontal_scrollbar.show(cx);
589                                        interaction_state.vertical_scrollbar.show(cx);
590                                        cx.notify();
591                                    } else if !interaction_state
592                                        .focus_handle
593                                        .contains_focused(window, cx)
594                                    {
595                                        interaction_state.hide_scrollbars(window, cx);
596                                    }
597                                })
598                                .ok(); // todo! handle error?
599                        }
600                    })
601            })
602            .when_some(self.headers.take(), |this, headers| {
603                this.child(render_header(headers, table_context.clone(), cx))
604            })
605            .child(
606                div()
607                    .flex_grow()
608                    .w_full()
609                    .relative()
610                    .overflow_hidden()
611                    .map(|parent| match self.rows {
612                        TableContents::Vec(items) => {
613                            parent.children(items.into_iter().enumerate().map(|(index, row)| {
614                                render_row(index, row, table_context.clone(), cx)
615                            }))
616                        }
617                        TableContents::UniformList(uniform_list_data) => parent.child(
618                            uniform_list(
619                                uniform_list_data.element_id,
620                                uniform_list_data.row_count,
621                                {
622                                    let render_item_fn = uniform_list_data.render_item_fn;
623                                    move |range: Range<usize>, window, cx| {
624                                        let elements = render_item_fn(range.clone(), window, cx);
625                                        elements
626                                            .into_iter()
627                                            .zip(range)
628                                            .map(|(row, row_index)| {
629                                                render_row(
630                                                    row_index,
631                                                    row,
632                                                    table_context.clone(),
633                                                    cx,
634                                                )
635                                            })
636                                            .collect()
637                                    }
638                                },
639                            )
640                            .size_full()
641                            .flex_grow()
642                            .with_sizing_behavior(ListSizingBehavior::Auto)
643                            .with_horizontal_sizing_behavior(
644                                ListHorizontalSizingBehavior::Unconstrained,
645                            )
646                            .when_some(
647                                interaction_state.as_ref(),
648                                |this, state| {
649                                    this.track_scroll(
650                                        state.read_with(cx, |s, _| s.scroll_handle.clone()),
651                                    )
652                                },
653                            ),
654                        ),
655                    })
656                    .when_some(interaction_state.as_ref(), |this, interaction_state| {
657                        this.map(|this| {
658                            TableInteractionState::render_vertical_scrollbar_track(
659                                interaction_state,
660                                this,
661                                scroll_track_size,
662                                cx,
663                            )
664                        })
665                        .map(|this| {
666                            TableInteractionState::render_vertical_scrollbar(
667                                interaction_state,
668                                this,
669                                cx,
670                            )
671                        })
672                    }),
673            )
674            .when_some(interaction_state.as_ref(), |this, interaction_state| {
675                this.map(|this| {
676                    TableInteractionState::render_horizantal_scrollbar_track(
677                        interaction_state,
678                        this,
679                        scroll_track_size,
680                        cx,
681                    )
682                })
683                .map(|this| {
684                    TableInteractionState::render_horizontal_scrollbar(
685                        interaction_state,
686                        this,
687                        h_scroll_offset,
688                        cx,
689                    )
690                })
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}