Skip to main content

gpui_material_components/
display.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Axis, ElementId, FocusHandle, InteractiveElement,
5    IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
6    StatefulInteractiveElement, Styled, Window, canvas, div, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{animate, color, move_roving_focus, window_material_theme};
10use gpui_material_theme::{
11    ColorRole, CornerRole, Direction, Elevation, MotionKind, MotionSpeed, StateLayer, TypeRole,
12};
13
14use crate::{
15    Text,
16    action::{Activate, ripple_ink, ripple_state, ripple_target},
17};
18
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub enum CardVariant {
21    Elevated,
22    #[default]
23    Filled,
24    Outlined,
25}
26
27/// A static surface or a keyboard-operable action with independent child controls.
28#[derive(IntoElement)]
29pub struct Card {
30    id: ElementId,
31    variant: CardVariant,
32    children: Vec<AnyElement>,
33    activation: Option<(SharedString, Activate)>,
34    disabled: bool,
35}
36
37impl Card {
38    pub fn new(id: impl Into<ElementId>) -> Self {
39        Self {
40            id: id.into(),
41            variant: CardVariant::default(),
42            children: Vec::new(),
43            activation: None,
44            disabled: false,
45        }
46    }
47
48    pub fn variant(mut self, variant: CardVariant) -> Self {
49        self.variant = variant;
50        self
51    }
52
53    pub fn disabled(mut self, disabled: bool) -> Self {
54        self.disabled = disabled;
55        self
56    }
57
58    pub fn on_activate(
59        mut self,
60        name: impl Into<SharedString>,
61        handler: impl Fn(&mut Window, &mut App) + 'static,
62    ) -> Self {
63        self.activation = Some((name.into(), Rc::new(handler)));
64        self
65    }
66}
67
68impl ParentElement for Card {
69    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
70        self.children.extend(elements);
71    }
72}
73
74impl RenderOnce for Card {
75    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
76        let (background, shadow, outline) = match self.variant {
77            CardVariant::Elevated => (ColorRole::SurfaceContainerLow, Elevation::Level1, false),
78            CardVariant::Filled => (ColorRole::SurfaceContainerHighest, Elevation::Level0, false),
79            CardVariant::Outlined => (ColorRole::Surface, Elevation::Level0, true),
80        };
81        let border = if self.disabled {
82            tone(ColorRole::SurfaceContainerLow, window, cx)
83                .blend(tone(ColorRole::Outline, window, cx).opacity(0.12))
84        } else {
85            tone(ColorRole::OutlineVariant, window, cx)
86        };
87        let focus = tone(ColorRole::Secondary, window, cx);
88        let background = if self.disabled {
89            match self.variant {
90                CardVariant::Filled => tone(background, window, cx)
91                    .blend(tone(ColorRole::SurfaceVariant, window, cx).opacity(0.38)),
92                _ => tone(ColorRole::Surface, window, cx),
93            }
94        } else {
95            tone(background, window, cx)
96        };
97        let foreground = tone(ColorRole::OnSurface, window, cx);
98        let (feedback, opacity) = surface_feedback(
99            &self.id,
100            self.activation.is_some() && !self.disabled,
101            window,
102            cx,
103        );
104        let hover_elevation = match self.variant {
105            CardVariant::Elevated => Elevation::Level2,
106            CardVariant::Filled => Elevation::Level1,
107            // CardDefaults.outlinedCardElevation keeps the surface flat on hover.
108            CardVariant::Outlined => Elevation::Level0,
109        };
110        let elevation = animate(
111            (self.id.clone(), "card-shadow"),
112            if self.disabled {
113                shadow.dp()
114            } else if feedback.get() == Some(StateLayer::Hover) {
115                hover_elevation.dp()
116            } else {
117                shadow.dp()
118            },
119            window_material_theme(window, cx).motion.spec(
120                MotionKind::Spatial,
121                MotionSpeed::Fast,
122                cx.reduce_motion(),
123            ),
124            window,
125            cx,
126        )
127        .max(0.);
128        let interactive = self.activation.is_some() && !self.disabled;
129        let ripple = ripple_state(&self.id, interactive, window, cx);
130        let direction = window_material_theme(window, cx).layout.direction;
131        let surface = div()
132            .id("card-surface")
133            .relative()
134            .rounded(px(12.))
135            .bg(background.blend(foreground.opacity(opacity)))
136            .text_color(foreground)
137            .when(elevation > 0., |surface| {
138                let shadow = tone(ColorRole::Shadow, window, cx);
139                surface.shadow(gpui_material_foundation::elevation_shadows(
140                    elevation, 1., shadow,
141                ))
142            })
143            .border_1()
144            .border_color(if outline {
145                border
146            } else {
147                gpui::transparent_black()
148            })
149            .w_full()
150            .p(px(16.))
151            .flex()
152            .flex_col()
153            .gap(px(8.))
154            .when(interactive, |surface| {
155                surface.child(ripple_ink(
156                    ripple.clone(),
157                    foreground,
158                    gpui_material_theme::CornerShape::Radii([12.; 4]),
159                    direction,
160                ))
161            })
162            .child(
163                div()
164                    .flex()
165                    .flex_col()
166                    .gap(px(8.))
167                    .when(self.disabled, |content| {
168                        content.text_color(foreground.opacity(0.38))
169                    })
170                    .children(self.children),
171            )
172            .when(interactive, |surface| ripple_target(surface, ripple));
173        match self.activation {
174            Some((name, activate)) => {
175                let invoke = activate.clone();
176                gpui_base::Button::new(self.id)
177                    .when(!self.disabled, |button| monitor_surface(button, feedback))
178                    .w_full()
179                    .accessibility_label(name)
180                    .disabled(self.disabled)
181                    .rounded(px(12.))
182                    .border_2()
183                    .border_color(gpui::transparent_black())
184                    .focus_visible(move |style| style.border_color(focus))
185                    .when(!self.disabled, |control| {
186                        control.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
187                            invoke(window, cx)
188                        })
189                    })
190                    .on_click(move |_, window, cx| {
191                        cx.stop_propagation();
192                        activate(window, cx);
193                    })
194                    .child(surface)
195                    .into_any_element()
196            }
197            None => div().id(self.id).child(surface).into_any_element(),
198        }
199    }
200}
201
202#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
203pub enum ListVariant {
204    #[default]
205    Standard,
206    Segmented,
207}
208
209/// A row with a stable domain ID, text and optional leading/trailing slots.
210#[derive(IntoElement)]
211pub struct ListItem {
212    id: ElementId,
213    label: SharedString,
214    supporting: Option<SharedString>,
215    overline: Option<SharedString>,
216    leading: Option<AnyElement>,
217    trailing: Option<AnyElement>,
218    activation: Option<Activate>,
219    selected: bool,
220    disabled: bool,
221    focus: Option<(FocusHandle, bool)>,
222}
223
224impl ListItem {
225    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
226        Self {
227            id: id.into(),
228            label: label.into(),
229            supporting: None,
230            overline: None,
231            leading: None,
232            trailing: None,
233            activation: None,
234            selected: false,
235            disabled: false,
236            focus: None,
237        }
238    }
239
240    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
241        self.supporting = Some(text.into());
242        self
243    }
244
245    pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
246        self.overline = Some(text.into());
247        self
248    }
249
250    pub fn leading(mut self, leading: impl IntoElement) -> Self {
251        self.leading = Some(leading.into_any_element());
252        self
253    }
254
255    pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
256        self.trailing = Some(trailing.into_any_element());
257        self
258    }
259
260    pub fn selected(mut self, selected: bool) -> Self {
261        self.selected = selected;
262        self
263    }
264
265    pub fn disabled(mut self, disabled: bool) -> Self {
266        self.disabled = disabled;
267        self
268    }
269
270    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
271        self.activation = Some(Rc::new(handler));
272        self
273    }
274
275    /// Uses a retained focus handle and roving tab stop supplied by a virtual
276    /// collection. The collection owns navigation across unrendered rows.
277    pub fn track_focus(mut self, focus: &FocusHandle, tab_stop: bool) -> Self {
278        self.focus = Some((focus.clone(), tab_stop));
279        self
280    }
281
282    fn row(
283        self,
284        corners: [f32; 4],
285        focus: Option<(&FocusHandle, bool)>,
286        window: &mut Window,
287        cx: &mut App,
288    ) -> AnyElement {
289        let motion = window_material_theme(window, cx).motion;
290        let reduced = cx.reduce_motion();
291        let effects = motion.spec(MotionKind::Effects, MotionSpeed::Default, reduced);
292        let spatial = motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
293        let selection = animate(
294            (self.id.clone(), "list-selection"),
295            f32::from(self.selected),
296            effects,
297            window,
298            cx,
299        )
300        .clamp(0., 1.);
301        let corners = std::array::from_fn::<_, 4, _>(|idx| {
302            let id = gpui::ElementId::from((self.id.clone(), "list-corners"));
303            animate(
304                gpui::ElementId::NamedChild(id.into(), ["tl", "tr", "br", "bl"][idx].into()),
305                corners[idx],
306                spatial,
307                window,
308                cx,
309            )
310            .max(0.)
311        });
312        let background = crate::motion::mix(
313            tone(ColorRole::Surface, window, cx),
314            if self.disabled {
315                tone(ColorRole::OnSurface, window, cx).opacity(0.38)
316            } else {
317                tone(ColorRole::SecondaryContainer, window, cx)
318            },
319            selection,
320        );
321        let foreground = if self.selected && !self.disabled {
322            ColorRole::OnSecondaryContainer
323        } else {
324            ColorRole::OnSurface
325        };
326        let secondary = if self.disabled {
327            ColorRole::OnSurface
328        } else if self.selected {
329            ColorRole::OnSecondaryContainer
330        } else {
331            ColorRole::OnSurfaceVariant
332        };
333        let text_height = window
334            .use_keyed_state((self.id.clone(), "list-text-height"), cx, |_, _| {
335                Rc::new(Cell::new(px(0.)))
336            })
337            .read(cx)
338            .clone();
339        let measure = text_height.clone();
340        let three_lines = self.overline.is_some() && self.supporting.is_some()
341            || self
342                .supporting
343                .as_ref()
344                .is_some_and(|text| text.contains('\n'))
345            || text_height.get() > px(44.);
346        let height = match (self.overline.is_some(), self.supporting.is_some()) {
347            _ if three_lines => 88.,
348            (false, false) => 56.,
349            _ => 72.,
350        };
351        let content = div()
352            .relative()
353            .flex()
354            .flex_col()
355            .flex_1()
356            .min_w_0()
357            .overflow_hidden()
358            .children(self.overline.map(|text| {
359                Text::new(text)
360                    .id("overline")
361                    .role(TypeRole::LabelSmall)
362                    .color(secondary)
363            }))
364            .child(Text::new(self.label.clone()).id("label").color(foreground))
365            .children(self.supporting.map(|text| {
366                Text::new(text)
367                    .id("supporting")
368                    .role(TypeRole::BodyMedium)
369                    .color(secondary)
370                    .wrap()
371            }))
372            .child(
373                canvas(
374                    move |bounds, window, _| {
375                        if measure.replace(bounds.size.height) != bounds.size.height {
376                            window.refresh();
377                        }
378                    },
379                    |_, _, _, _| {},
380                )
381                .absolute()
382                .inset_0(),
383            );
384        let state_layer = tone(foreground, window, cx);
385        let focus_ring = tone(ColorRole::Secondary, window, cx);
386        let (feedback, opacity) = surface_feedback(
387            &self.id,
388            self.activation.is_some() && !self.disabled,
389            window,
390            cx,
391        );
392        let interactive = self.activation.is_some() && !self.disabled;
393        let ripple = ripple_state(&self.id, interactive, window, cx);
394        let direction = window_material_theme(window, cx).layout.direction;
395        let row = div()
396            .id("list-surface")
397            .relative()
398            .min_h(px(height))
399            .w_full()
400            .flex()
401            .when_else(three_lines, Styled::items_start, Styled::items_center)
402            .gap(px(12.))
403            .px(px(16.))
404            .py(px(if three_lines { 12. } else { 10. }))
405            .when(
406                window_material_theme(window, cx).layout.direction == Direction::Rtl,
407                Styled::flex_row_reverse,
408            )
409            .rounded_tl(px(corners[0]))
410            .rounded_tr(px(corners[1]))
411            .rounded_br(px(corners[2]))
412            .rounded_bl(px(corners[3]))
413            .bg(background.blend(state_layer.opacity(opacity)))
414            .when(interactive, |row| {
415                row.child(ripple_ink(
416                    ripple.clone(),
417                    state_layer,
418                    gpui_material_theme::CornerShape::Radii(corners),
419                    direction,
420                ))
421            })
422            .when(interactive, |row| ripple_target(row, ripple))
423            .children(self.leading.map(|leading| {
424                div()
425                    .when(self.disabled, |part| {
426                        part.text_color(tone(ColorRole::OnSurface, window, cx).opacity(0.38))
427                    })
428                    .child(leading)
429            }))
430            .child(content.when(self.disabled, |content| content.opacity(0.38)))
431            .children(self.trailing.map(|trailing| {
432                div()
433                    .when(self.disabled, |part| {
434                        part.text_color(tone(ColorRole::OnSurface, window, cx).opacity(0.38))
435                    })
436                    .child(trailing)
437            }));
438        let row = match self.activation {
439            Some(activate) => {
440                let invoke = activate.clone();
441                gpui_base::Button::new((self.id.clone(), "activate"))
442                    .when_some(focus, |button, (focus, tab_stop)| {
443                        button.track_focus(focus).tab_stop(tab_stop)
444                    })
445                    .when(!self.disabled, |button| monitor_surface(button, feedback))
446                    .w_full()
447                    .accessibility_label(self.label)
448                    .disabled(self.disabled)
449                    .selected(self.selected)
450                    .border_2()
451                    .border_color(gpui::transparent_black())
452                    .rounded_md()
453                    .focus_visible(move |style| style.border_color(focus_ring))
454                    .when(!self.disabled, |control| {
455                        control.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
456                            invoke(window, cx)
457                        })
458                    })
459                    .on_click(move |_, window, cx| {
460                        cx.stop_propagation();
461                        activate(window, cx);
462                    })
463                    .child(row)
464                    .into_any_element()
465            }
466            None => row.into_any_element(),
467        };
468        div()
469            .id(self.id)
470            .role(Role::ListItem)
471            .test_support()
472            .aria_selected(self.selected)
473            .child(row)
474            .into_any_element()
475    }
476}
477
478impl RenderOnce for ListItem {
479    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
480        let focus = self.focus.clone();
481        self.row(
482            [0.; 4],
483            focus.as_ref().map(|(handle, tab)| (handle, *tab)),
484            window,
485            cx,
486        )
487    }
488}
489
490/// A list of identified rows. Applications can supply a visible window of rows
491/// from their own virtualized collection.
492#[derive(IntoElement)]
493pub struct List {
494    id: ElementId,
495    items: Vec<ListItem>,
496    variant: ListVariant,
497}
498
499impl List {
500    pub fn new(id: impl Into<ElementId>) -> Self {
501        Self {
502            id: id.into(),
503            items: Vec::new(),
504            variant: ListVariant::default(),
505        }
506    }
507
508    pub fn variant(mut self, variant: ListVariant) -> Self {
509        self.variant = variant;
510        self
511    }
512
513    pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
514        self.items.extend(items);
515        self
516    }
517}
518
519impl RenderOnce for List {
520    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
521        let last = self.items.len().saturating_sub(1);
522        let direction = window_material_theme(window, cx).layout.direction;
523        let focus: Vec<_> = self
524            .items
525            .iter()
526            .map(|item| {
527                window.with_id((self.id.clone(), "list-focus"), |window| {
528                    window
529                        .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
530                        .read(cx)
531                        .clone()
532                })
533            })
534            .collect();
535        let enabled: Vec<_> = self
536            .items
537            .iter()
538            .map(|item| !item.disabled && item.activation.is_some())
539            .collect();
540        let tab_stop = focus
541            .iter()
542            .enumerate()
543            .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
544            .or_else(|| {
545                self.items
546                    .iter()
547                    .enumerate()
548                    .position(|(ix, item)| enabled[ix] && item.selected)
549            })
550            .or_else(|| enabled.iter().position(|enabled| *enabled));
551        let navigation = focus.clone();
552        div()
553            .id(self.id)
554            .role(Role::List)
555            .flex()
556            .flex_col()
557            .w_full()
558            .on_key_down(move |event, window, cx| {
559                // Nested controls keep their own arrow-key behavior.
560                if !navigation.iter().any(|focus| focus.is_focused(window)) {
561                    return;
562                }
563                let items: Vec<_> = navigation
564                    .iter()
565                    .zip(&enabled)
566                    .map(|(focus, enabled)| (focus, *enabled))
567                    .collect();
568                if move_roving_focus(
569                    &items,
570                    &event.keystroke.key,
571                    Axis::Vertical,
572                    direction,
573                    window,
574                    cx,
575                )
576                .is_some()
577                {
578                    cx.stop_propagation();
579                    window.refresh();
580                }
581            })
582            .when(self.variant == ListVariant::Segmented, |list| {
583                list.gap(px(2.))
584            })
585            .children(self.items.into_iter().enumerate().map(|(ix, item)| {
586                let corners = if self.variant == ListVariant::Standard {
587                    [0.; 4]
588                } else if item.selected {
589                    CornerRole::Large.shape().radii(100., 100., Direction::Ltr)
590                } else {
591                    let top = if ix == 0 { 16. } else { 4. };
592                    let bottom = if ix == last { 16. } else { 4. };
593                    [top, top, bottom, bottom]
594                };
595                item.row(
596                    corners,
597                    Some((&focus[ix], Some(ix) == tab_stop)),
598                    window,
599                    cx,
600                )
601            }))
602    }
603}
604
605/// Decorative Material divider, with logical start and end insets.
606#[derive(IntoElement)]
607pub struct Divider {
608    axis: Axis,
609    start: gpui::Pixels,
610    end: gpui::Pixels,
611}
612
613impl Divider {
614    pub fn horizontal() -> Self {
615        Self {
616            axis: Axis::Horizontal,
617            start: px(0.),
618            end: px(0.),
619        }
620    }
621
622    pub fn vertical() -> Self {
623        Self {
624            axis: Axis::Vertical,
625            ..Self::horizontal()
626        }
627    }
628
629    pub fn inset(mut self, start: gpui::Pixels, end: gpui::Pixels) -> Self {
630        self.start = start.max(px(0.));
631        self.end = end.max(px(0.));
632        self
633    }
634}
635
636impl RenderOnce for Divider {
637    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
638        let fill = tone(ColorRole::OutlineVariant, window, cx);
639        let (left, right) = window_material_theme(window, cx)
640            .layout
641            .horizontal(self.start, self.end);
642        if self.axis == Axis::Vertical {
643            div()
644                .w(px(1.))
645                .h_full()
646                .pt(self.start)
647                .pb(self.end)
648                .child(div().size_full().bg(fill))
649        } else {
650            div()
651                .w_full()
652                .h(px(1.))
653                .pl(left)
654                .pr(right)
655                .child(div().size_full().bg(fill))
656        }
657    }
658}
659
660/// An anchored badge. Pass its accessible name to the host control so the host
661/// announces the count once and keeps a single focus stop.
662#[derive(IntoElement)]
663pub struct Badge {
664    host: AnyElement,
665    text: Option<SharedString>,
666}
667
668impl Badge {
669    pub fn dot(host: impl IntoElement) -> Self {
670        Self {
671            host: host.into_any_element(),
672            text: None,
673        }
674    }
675
676    pub fn label(host: impl IntoElement, text: impl Into<SharedString>) -> Self {
677        Self {
678            host: host.into_any_element(),
679            text: Some(text.into()),
680        }
681    }
682
683    pub fn count(host: impl IntoElement, count: usize, maximum: usize) -> Self {
684        Self::label(
685            host,
686            if count > maximum {
687                format!("{maximum}+")
688            } else {
689                count.to_string()
690            },
691        )
692    }
693}
694
695impl RenderOnce for Badge {
696    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
697        let large = self.text.is_some();
698        let side = px(if large { 16. } else { 6. });
699        let overlap = if large { px(12.) } else { px(6.) };
700        let mark = div()
701            .absolute()
702            .top(if large { px(-2.) } else { px(0.) })
703            .min_w(side)
704            .h(side)
705            .rounded_full()
706            .when_else(
707                window_material_theme(window, cx).layout.direction == Direction::Rtl,
708                |badge| badge.right(gpui::relative(1.)).mr(-overlap),
709                |badge| badge.left(gpui::relative(1.)).ml(-overlap),
710            )
711            .when(large, |badge| badge.px(px(4.)))
712            .bg(tone(ColorRole::Error, window, cx))
713            .text_color(tone(ColorRole::OnError, window, cx))
714            .flex()
715            .items_center()
716            .justify_center()
717            .children(self.text.map(|text| {
718                crate::text::single_line(
719                    text,
720                    TypeRole::LabelSmall.style(gpui_material_theme::TypographyEmphasis::Baseline),
721                    1.,
722                    tone(ColorRole::OnError, window, cx),
723                    (None, 1., 1.),
724                    window,
725                    cx,
726                )
727            }));
728        div().relative().child(self.host).child(mark)
729    }
730}
731
732fn tone(role: ColorRole, window: &Window, cx: &App) -> gpui::Hsla {
733    color(window_material_theme(window, cx).colors.color(role))
734}
735
736fn surface_feedback(
737    id: &ElementId,
738    enabled: bool,
739    window: &mut Window,
740    cx: &mut App,
741) -> (Rc<Cell<Option<StateLayer>>>, f32) {
742    let state = window
743        .use_keyed_state((id.clone(), "surface-interaction"), cx, |_, _| {
744            Rc::new(Cell::new(None::<StateLayer>))
745        })
746        .read(cx)
747        .clone();
748    if !enabled || !window.is_window_active() {
749        state.set(None);
750    }
751    let alpha = animate(
752        (id.clone(), "surface-opacity"),
753        state.get().map_or(0., StateLayer::opacity),
754        window_material_theme(window, cx).motion.spec(
755            MotionKind::Effects,
756            MotionSpeed::Fast,
757            cx.reduce_motion() || !enabled,
758        ),
759        window,
760        cx,
761    )
762    .clamp(0., 1.);
763    (state, alpha)
764}
765
766fn monitor_surface(
767    button: gpui_base::Button,
768    state: Rc<Cell<Option<StateLayer>>>,
769) -> gpui_base::Button {
770    let hover = state.clone();
771    let down = state.clone();
772    let up = state.clone();
773    button
774        .on_hover(move |hovering, window, _| {
775            hover.set(hovering.then_some(StateLayer::Hover));
776            window.refresh();
777        })
778        .on_mouse_down(MouseButton::Left, move |_, window, _| {
779            down.set(Some(StateLayer::Pressed));
780            window.refresh();
781        })
782        .on_mouse_up(MouseButton::Left, move |_, window, _| {
783            up.set(Some(StateLayer::Hover));
784            window.refresh();
785        })
786        .on_mouse_up_out(MouseButton::Left, move |_, window, _| {
787            state.set(None);
788            window.refresh();
789        })
790}