Skip to main content

gpui_material_components/
card.rs

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