Skip to main content

gpui_material_components/
card.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, BorderStyle, ClickEvent, Corners, Edges, ElementId, Entity,
5    FocusHandle, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, Role,
6    SharedString, StatefulInteractiveElement, Styled, Window, canvas, div, prelude::FluentBuilder,
7    px, quad,
8};
9use gpui_base::TestSupportExt as _;
10use gpui_material_foundation::{
11    InteractionFeedback, InteractionSource, InteractionState, ThemeScope, animate, color,
12    current_material_theme, elevation_shadow_pair,
13};
14use gpui_material_theme::{
15    ColorRole, CornerRole, CornerShape, Direction, Elevation, MotionKind, MotionSpec, MotionSpeed,
16};
17
18use crate::{
19    action::{Activate, activate_feedback, feedback_target, ripple_state},
20    button_style::finite_length,
21};
22
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24pub enum CardVariant {
25    Elevated,
26    #[default]
27    Filled,
28    Outlined,
29}
30
31/// The card's stroke. A zero-width border removes the stroke.
32#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct CardBorder {
34    pub width: Pixels,
35    pub color: Hsla,
36}
37
38/// Per-instance colors. Omitted fields keep their variant and window defaults.
39#[derive(Clone, Copy, Debug, Default, PartialEq)]
40pub struct CardColors {
41    pub container: Option<Hsla>,
42    pub content: Option<Hsla>,
43    pub disabled_container: Option<Hsla>,
44    pub disabled_content: Option<Hsla>,
45}
46
47/// Shadow levels. Each omitted field keeps the variant default for its state.
48#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
49pub struct CardElevations {
50    pub resting: Option<Elevation>,
51    pub pressed: Option<Elevation>,
52    pub focused: Option<Elevation>,
53    pub hovered: Option<Elevation>,
54    pub dragged: Option<Elevation>,
55    pub disabled: Option<Elevation>,
56}
57
58impl CardElevations {
59    fn resolve(self, variant: CardVariant, state: InteractionState) -> Elevation {
60        let (resting, hovered, dragged) = match variant {
61            CardVariant::Elevated => (Elevation::Level1, Elevation::Level2, Elevation::Level4),
62            CardVariant::Filled => (Elevation::Level0, Elevation::Level1, Elevation::Level3),
63            CardVariant::Outlined => (Elevation::Level0, Elevation::Level0, Elevation::Level3),
64        };
65        if state.disabled {
66            self.disabled.unwrap_or(resting)
67        } else if state.dragged {
68            self.dragged.unwrap_or(dragged)
69        } else if state.pressed {
70            self.pressed.unwrap_or(resting)
71        } else if state.focus_visible {
72            self.focused.unwrap_or(resting)
73        } else if state.hovered {
74            self.hovered.unwrap_or(hovered)
75        } else {
76            self.resting.unwrap_or(resting)
77        }
78    }
79}
80
81/// A static surface or a keyboard-operable action with independent child controls.
82#[derive(IntoElement)]
83pub struct Card {
84    id: ElementId,
85    variant: CardVariant,
86    children: Vec<AnyElement>,
87    activation: Option<(SharedString, Activate)>,
88    accessible_label: Option<SharedString>,
89    disabled: bool,
90    dragged: bool,
91    shape: CornerShape,
92    border: Option<CardBorder>,
93    colors: CardColors,
94    elevations: CardElevations,
95    content_padding: Edges<Pixels>,
96    gap: Pixels,
97    focus: Option<FocusHandle>,
98    source: Option<Entity<InteractionSource>>,
99}
100
101impl Card {
102    pub fn new(id: impl Into<ElementId>) -> Self {
103        Self {
104            id: id.into(),
105            variant: CardVariant::default(),
106            children: Vec::new(),
107            activation: None,
108            accessible_label: None,
109            disabled: false,
110            dragged: false,
111            shape: CornerRole::Medium.shape(),
112            border: None,
113            colors: CardColors::default(),
114            elevations: CardElevations::default(),
115            content_padding: Edges::all(px(16.)),
116            gap: px(8.),
117            focus: None,
118            source: None,
119        }
120    }
121
122    /// Creates an Elevated card.
123    pub fn elevated(id: impl Into<ElementId>) -> Self {
124        Self::new(id).variant(CardVariant::Elevated)
125    }
126
127    /// Creates a Filled card.
128    pub fn filled(id: impl Into<ElementId>) -> Self {
129        Self::new(id).variant(CardVariant::Filled)
130    }
131
132    /// Creates an Outlined card.
133    pub fn outlined(id: impl Into<ElementId>) -> Self {
134        Self::new(id).variant(CardVariant::Outlined)
135    }
136
137    pub fn variant(mut self, variant: CardVariant) -> Self {
138        self.variant = variant;
139        self
140    }
141
142    pub fn disabled(mut self, disabled: bool) -> Self {
143        self.disabled = disabled;
144        self
145    }
146
147    pub fn on_activate(
148        mut self,
149        name: impl Into<SharedString>,
150        handler: impl Fn(&mut Window, &mut App) + 'static,
151    ) -> Self {
152        self.activation = Some((name.into(), Rc::new(handler)));
153        self
154    }
155
156    pub fn shape(mut self, shape: CornerShape) -> Self {
157        self.shape = shape;
158        self
159    }
160
161    pub fn border(mut self, border: CardBorder) -> Self {
162        self.border = Some(border);
163        self
164    }
165
166    pub fn colors(mut self, colors: CardColors) -> Self {
167        self.colors = colors;
168        self
169    }
170
171    pub fn elevations(mut self, elevations: CardElevations) -> Self {
172        self.elevations = elevations;
173        self
174    }
175
176    /// Sets the card's inner padding in logical pixels. Defaults to 16 dp on all sides.
177    pub fn content_padding(mut self, padding: Edges<Pixels>) -> Self {
178        self.content_padding = Edges {
179            top: finite_length(padding.top),
180            right: finite_length(padding.right),
181            bottom: finite_length(padding.bottom),
182            left: finite_length(padding.left),
183        };
184        self
185    }
186
187    /// Sets the vertical gap between child elements. Defaults to 8 dp.
188    pub fn gap(mut self, gap: Pixels) -> Self {
189        self.gap = if f32::from(gap).is_finite() && gap >= px(0.) {
190            gap
191        } else {
192            px(8.)
193        };
194        self
195    }
196
197    /// Names a static (`Role::Group`) card for assistive technology.
198    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
199        self.accessible_label = Some(label.into());
200        self
201    }
202
203    /// Displays a caller-owned drag. Clear the flag after drop or cancellation.
204    pub fn dragged(mut self, dragged: bool) -> Self {
205        self.dragged = dragged;
206        self
207    }
208
209    /// Uses the caller's focus handle when the card is actionable.
210    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
211        self.focus = Some(focus.clone());
212        self
213    }
214
215    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
216        self.source = Some(source.clone());
217        self
218    }
219}
220
221impl ParentElement for Card {
222    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
223        self.children.extend(elements);
224    }
225}
226
227impl RenderOnce for Card {
228    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
229        let actionable = self.activation.is_some();
230        let enabled = !self.disabled;
231        let dragged = enabled && self.dragged;
232        let feedback = ripple_state(&self.id, actionable && enabled, window, cx);
233        let focus = self.focus.filter(|_| actionable).unwrap_or_else(|| {
234            window
235                .use_keyed_state((self.id.clone(), "card-focus"), cx, |_, cx| {
236                    cx.focus_handle()
237                })
238                .read(cx)
239                .clone()
240        });
241        let tracker = self
242            .source
243            .as_ref()
244            .map(|source| InteractionSource::track(source, &self.id, window, cx));
245        let interaction = {
246            let mut feedback = feedback.borrow_mut();
247            feedback.set_dragged(dragged);
248            feedback.track(enabled, &focus, tracker, window, cx)
249        };
250
251        let theme = current_material_theme(window, cx);
252        let direction = theme.layout.direction;
253        let reduced = cx.reduce_motion();
254        let tone = |role| color(theme.colors.color(role));
255        let container = match self.variant {
256            CardVariant::Elevated => ColorRole::SurfaceContainerLow,
257            CardVariant::Filled => ColorRole::SurfaceContainerHighest,
258            CardVariant::Outlined => ColorRole::Surface,
259        };
260        let background = if self.disabled {
261            self.colors
262                .disabled_container
263                .unwrap_or_else(|| match self.variant {
264                    CardVariant::Filled => {
265                        tone(container).blend(tone(ColorRole::SurfaceVariant).opacity(0.38))
266                    }
267                    _ => tone(ColorRole::Surface),
268                })
269        } else {
270            self.colors.container.unwrap_or_else(|| tone(container))
271        };
272        let foreground = if self.disabled {
273            self.colors
274                .disabled_content
275                .unwrap_or_else(|| tone(ColorRole::OnSurface).opacity(0.38))
276        } else {
277            self.colors
278                .content
279                .unwrap_or_else(|| tone(ColorRole::OnSurface))
280        };
281        let border = self.border.unwrap_or_else(|| CardBorder {
282            // Keep the default card content inset across variants.
283            width: px(1.),
284            color: if self.variant != CardVariant::Outlined {
285                gpui::transparent_black()
286            } else if self.disabled {
287                tone(ColorRole::SurfaceContainerLow).blend(tone(ColorRole::Outline).opacity(0.12))
288            } else {
289                tone(ColorRole::OutlineVariant)
290            },
291        });
292        let border_width = finite_length(border.width);
293        let border_color = if border_width > px(0.) {
294            border.color
295        } else {
296            gpui::transparent_black()
297        };
298        let ring = tone(ColorRole::Secondary);
299        let shadow = tone(ColorRole::Shadow);
300        let elevation_motion = theme
301            .motion
302            .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
303        let layer_motion = theme
304            .motion
305            .spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
306        let elevation = animate(
307            (self.id.clone(), "card-shadow"),
308            self.elevations.resolve(self.variant, interaction).dp(),
309            if enabled {
310                elevation_motion
311            } else {
312                MotionSpec::Instant
313            },
314            window,
315            cx,
316        )
317        .max(0.);
318        let layer = animate(
319            (self.id.clone(), "card-state-layer"),
320            interaction
321                .layer_with_ripple(reduced)
322                .map_or(0., |layer| layer.opacity()),
323            if enabled {
324                layer_motion
325            } else {
326                MotionSpec::Instant
327            },
328            window,
329            cx,
330        )
331        .clamp(0., 1.);
332        let geometry = feedback.clone();
333        let paint_feedback = feedback.clone();
334        let shape = self.shape;
335        let visual = canvas(
336            move |bounds, window, _| {
337                if enabled && (actionable || dragged) {
338                    geometry
339                        .borrow_mut()
340                        .set_rounded_shape(bounds, shape, direction, window);
341                } else {
342                    geometry.borrow_mut().set_shape(None, window);
343                }
344                let [top_left, top_right, bottom_right, bottom_left] = shape
345                    .radii(
346                        f32::from(bounds.size.width),
347                        f32::from(bounds.size.height),
348                        direction,
349                    )
350                    .map(px);
351                Corners {
352                    top_left,
353                    top_right,
354                    bottom_right,
355                    bottom_left,
356                }
357            },
358            move |bounds, corners, window, cx| {
359                if let Some(shadows) = elevation_shadow_pair(elevation, 1., shadow) {
360                    window.paint_drop_shadows(bounds, corners, &shadows);
361                }
362                window.paint_quad(quad(
363                    bounds,
364                    corners,
365                    background,
366                    border_width,
367                    border_color,
368                    BorderStyle::Solid,
369                ));
370                let feedback = paint_feedback.borrow();
371                if let Some(shape) = &feedback.shape {
372                    InteractionFeedback::new(interaction, foreground, ring).paint_with_opacity(
373                        shape,
374                        feedback.ripple.as_ref(),
375                        layer,
376                        cx.background_executor().now(),
377                        reduced,
378                        window,
379                    );
380                }
381            },
382        )
383        .absolute()
384        .inset_0()
385        .size_full();
386        let content = apply_corner_shape(
387            div()
388                .relative()
389                .w_full()
390                .overflow_hidden()
391                .text_color(foreground)
392                .pt(self.content_padding.top + border_width)
393                .pr(self.content_padding.right + border_width)
394                .pb(self.content_padding.bottom + border_width)
395                .pl(self.content_padding.left + border_width)
396                .flex()
397                .flex_col()
398                .gap(self.gap),
399            self.shape,
400            direction,
401        )
402        .children(self.children);
403        let surface = div()
404            .id("card-surface")
405            .relative()
406            .w_full()
407            .child(visual)
408            .child(content);
409        match self.activation {
410            Some((name, activate)) => {
411                let activate = Rc::new(ThemeScope::bind_action(
412                    move |window, cx| activate(window, cx),
413                    window,
414                    cx,
415                ));
416                let invoke = activate.clone();
417                let press = feedback.clone();
418                gpui_base::Button::new(self.id)
419                    .track_focus(&focus)
420                    .tab_stop(true)
421                    .disabled(self.disabled)
422                    .w_full()
423                    .border_2()
424                    .border_color(gpui::transparent_black())
425                    .accessibility_label(name)
426                    .when(enabled && !dragged, |control| {
427                        feedback_target(control, feedback, true, Some(focus))
428                    })
429                    .when(enabled, |control| {
430                        control
431                            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
432                                if !dragged {
433                                    invoke(window, cx);
434                                }
435                            })
436                            .on_click(move |event, window, cx| {
437                                cx.stop_propagation();
438                                let native_drag =
439                                    matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag();
440                                if !native_drag && !press.borrow().blocks_activation(event) {
441                                    activate_feedback(event, &press, window, cx);
442                                    activate(window, cx);
443                                }
444                            })
445                    })
446                    .child(surface)
447                    .into_any_element()
448            }
449            None => div()
450                .id(self.id)
451                .test_support()
452                .role(Role::Group)
453                .when_some(self.accessible_label, |card, label| card.aria_label(label))
454                .child(surface)
455                .into_any_element(),
456        }
457    }
458}
459
460fn apply_corner_shape<E: Styled>(element: E, shape: CornerShape, direction: Direction) -> E {
461    if shape == CornerShape::Full {
462        element.rounded_full()
463    } else {
464        let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
465        element
466            .rounded_tl(px(tl))
467            .rounded_tr(px(tr))
468            .rounded_br(px(br))
469            .rounded_bl(px(bl))
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use Elevation::*;
477
478    #[test]
479    fn elevation_overrides_resolve_each_state_and_precedence() {
480        let levels = CardElevations {
481            resting: Some(Level0),
482            hovered: Some(Level1),
483            focused: Some(Level2),
484            pressed: Some(Level3),
485            dragged: Some(Level4),
486            disabled: Some(Level5),
487        };
488        for variant in [
489            CardVariant::Elevated,
490            CardVariant::Filled,
491            CardVariant::Outlined,
492        ] {
493            let mut state = InteractionState::default();
494            assert_eq!(levels.resolve(variant, state), Level0);
495            state.hovered = true;
496            assert_eq!(levels.resolve(variant, state), Level1);
497            state.focus_visible = true;
498            assert_eq!(levels.resolve(variant, state), Level2);
499            state.pressed = true;
500            assert_eq!(levels.resolve(variant, state), Level3);
501            state.dragged = true;
502            assert_eq!(levels.resolve(variant, state), Level4);
503            state.disabled = true;
504            assert_eq!(levels.resolve(variant, state), Level5);
505        }
506    }
507
508    #[test]
509    fn omitted_elevations_keep_the_pinned_variant_values() {
510        let levels = CardElevations::default();
511        for (variant, resting, hovered, dragged) in [
512            (CardVariant::Elevated, Level1, Level2, Level4),
513            (CardVariant::Filled, Level0, Level1, Level3),
514            (CardVariant::Outlined, Level0, Level0, Level3),
515        ] {
516            let mut state = InteractionState::default();
517            assert_eq!(levels.resolve(variant, state), resting);
518            state.hovered = true;
519            assert_eq!(levels.resolve(variant, state), hovered);
520            state.focus_visible = true;
521            assert_eq!(levels.resolve(variant, state), resting);
522            state.pressed = true;
523            assert_eq!(levels.resolve(variant, state), resting);
524            state.dragged = true;
525            assert_eq!(levels.resolve(variant, state), dragged);
526            state.disabled = true;
527            assert_eq!(levels.resolve(variant, state), resting);
528        }
529    }
530
531    #[test]
532    fn card_variant_shorthands_set_expected_variants() {
533        assert_eq!(Card::elevated("c1").variant, CardVariant::Elevated);
534        assert_eq!(Card::filled("c2").variant, CardVariant::Filled);
535        assert_eq!(Card::outlined("c3").variant, CardVariant::Outlined);
536    }
537}