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