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, ThemeScope, animate, color,
12    current_material_theme, elevation_shadow_pair,
13};
14use gpui_material_theme::{
15    ColorRole, CornerRole, CornerShape, 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    disabled: bool,
89    dragged: bool,
90    shape: CornerShape,
91    border: Option<CardBorder>,
92    colors: CardColors,
93    elevations: CardElevations,
94    focus: Option<FocusHandle>,
95    source: Option<Entity<InteractionSource>>,
96}
97
98impl Card {
99    pub fn new(id: impl Into<ElementId>) -> Self {
100        Self {
101            id: id.into(),
102            variant: CardVariant::default(),
103            children: Vec::new(),
104            activation: None,
105            disabled: false,
106            dragged: false,
107            shape: CornerRole::Medium.shape(),
108            border: None,
109            colors: CardColors::default(),
110            elevations: CardElevations::default(),
111            focus: None,
112            source: None,
113        }
114    }
115
116    /// Creates an Elevated card.
117    pub fn elevated(id: impl Into<ElementId>) -> Self {
118        Self::new(id).variant(CardVariant::Elevated)
119    }
120
121    /// Creates a Filled card.
122    pub fn filled(id: impl Into<ElementId>) -> Self {
123        Self::new(id).variant(CardVariant::Filled)
124    }
125
126    /// Creates an Outlined card.
127    pub fn outlined(id: impl Into<ElementId>) -> Self {
128        Self::new(id).variant(CardVariant::Outlined)
129    }
130
131    pub fn variant(mut self, variant: CardVariant) -> Self {
132        self.variant = variant;
133        self
134    }
135
136    pub fn disabled(mut self, disabled: bool) -> Self {
137        self.disabled = disabled;
138        self
139    }
140
141    pub fn on_activate(
142        mut self,
143        name: impl Into<SharedString>,
144        handler: impl Fn(&mut Window, &mut App) + 'static,
145    ) -> Self {
146        self.activation = Some((name.into(), Rc::new(handler)));
147        self
148    }
149
150    pub fn shape(mut self, shape: CornerShape) -> Self {
151        self.shape = shape;
152        self
153    }
154
155    pub fn border(mut self, border: CardBorder) -> Self {
156        self.border = Some(border);
157        self
158    }
159
160    pub fn colors(mut self, colors: CardColors) -> Self {
161        self.colors = colors;
162        self
163    }
164
165    pub fn elevations(mut self, elevations: CardElevations) -> Self {
166        self.elevations = elevations;
167        self
168    }
169
170    /// Displays a caller-owned drag. Clear the flag after drop or cancellation.
171    pub fn dragged(mut self, dragged: bool) -> Self {
172        self.dragged = dragged;
173        self
174    }
175
176    /// Uses the caller's focus handle when the card is actionable.
177    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
178        self.focus = Some(focus.clone());
179        self
180    }
181
182    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
183        self.source = Some(source.clone());
184        self
185    }
186}
187
188impl ParentElement for Card {
189    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
190        self.children.extend(elements);
191    }
192}
193
194impl RenderOnce for Card {
195    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
196        let actionable = self.activation.is_some();
197        let enabled = !self.disabled;
198        let dragged = enabled && self.dragged;
199        let feedback = ripple_state(&self.id, actionable && enabled, window, cx);
200        let focus = self.focus.filter(|_| actionable).unwrap_or_else(|| {
201            window
202                .use_keyed_state((self.id.clone(), "card-focus"), cx, |_, cx| {
203                    cx.focus_handle()
204                })
205                .read(cx)
206                .clone()
207        });
208        let tracker = self
209            .source
210            .as_ref()
211            .map(|source| InteractionSource::track(source, &self.id, window, cx));
212        let interaction = {
213            let mut feedback = feedback.borrow_mut();
214            feedback.set_dragged(dragged);
215            feedback.track(enabled, &focus, tracker, window, cx)
216        };
217
218        let theme = current_material_theme(window, cx);
219        let direction = theme.layout.direction;
220        let reduced = cx.reduce_motion();
221        let tone = |role| color(theme.colors.color(role));
222        let container = match self.variant {
223            CardVariant::Elevated => ColorRole::SurfaceContainerLow,
224            CardVariant::Filled => ColorRole::SurfaceContainerHighest,
225            CardVariant::Outlined => ColorRole::Surface,
226        };
227        let background = if self.disabled {
228            self.colors
229                .disabled_container
230                .unwrap_or_else(|| match self.variant {
231                    CardVariant::Filled => {
232                        tone(container).blend(tone(ColorRole::SurfaceVariant).opacity(0.38))
233                    }
234                    _ => tone(ColorRole::Surface),
235                })
236        } else {
237            self.colors.container.unwrap_or_else(|| tone(container))
238        };
239        let foreground = if self.disabled {
240            self.colors
241                .disabled_content
242                .unwrap_or_else(|| tone(ColorRole::OnSurface).opacity(0.38))
243        } else {
244            self.colors
245                .content
246                .unwrap_or_else(|| tone(ColorRole::OnSurface))
247        };
248        let border = self.border.unwrap_or_else(|| CardBorder {
249            // Keep the default card content inset across variants.
250            width: px(1.),
251            color: if self.variant != CardVariant::Outlined {
252                gpui::transparent_black()
253            } else if self.disabled {
254                tone(ColorRole::SurfaceContainerLow).blend(tone(ColorRole::Outline).opacity(0.12))
255            } else {
256                tone(ColorRole::OutlineVariant)
257            },
258        });
259        let border_width = finite_length(border.width);
260        let border_color = if border_width > px(0.) {
261            border.color
262        } else {
263            gpui::transparent_black()
264        };
265        let ring = tone(ColorRole::Secondary);
266        let shadow = tone(ColorRole::Shadow);
267        let elevation_motion = theme
268            .motion
269            .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
270        let layer_motion = theme
271            .motion
272            .spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
273        let elevation = animate(
274            (self.id.clone(), "card-shadow"),
275            self.elevations.resolve(self.variant, interaction).dp(),
276            if enabled {
277                elevation_motion
278            } else {
279                MotionSpec::Instant
280            },
281            window,
282            cx,
283        )
284        .max(0.);
285        let layer = animate(
286            (self.id.clone(), "card-state-layer"),
287            interaction
288                .layer_with_ripple(reduced)
289                .map_or(0., |layer| layer.opacity()),
290            if enabled {
291                layer_motion
292            } else {
293                MotionSpec::Instant
294            },
295            window,
296            cx,
297        )
298        .clamp(0., 1.);
299        let geometry = feedback.clone();
300        let paint_feedback = feedback.clone();
301        let shape = self.shape;
302        let visual = canvas(
303            move |bounds, window, _| {
304                if enabled && (actionable || dragged) {
305                    geometry
306                        .borrow_mut()
307                        .set_rounded_shape(bounds, shape, direction, window);
308                } else {
309                    geometry.borrow_mut().set_shape(None, window);
310                }
311                let [top_left, top_right, bottom_right, bottom_left] = shape
312                    .radii(
313                        f32::from(bounds.size.width),
314                        f32::from(bounds.size.height),
315                        direction,
316                    )
317                    .map(px);
318                Corners {
319                    top_left,
320                    top_right,
321                    bottom_right,
322                    bottom_left,
323                }
324            },
325            move |bounds, corners, window, cx| {
326                if let Some(shadows) = elevation_shadow_pair(elevation, 1., shadow) {
327                    window.paint_drop_shadows(bounds, corners, &shadows);
328                }
329                window.paint_quad(quad(
330                    bounds,
331                    corners,
332                    background,
333                    border_width,
334                    border_color,
335                    BorderStyle::Solid,
336                ));
337                let feedback = paint_feedback.borrow();
338                if let Some(shape) = &feedback.shape {
339                    InteractionFeedback::new(interaction, foreground, ring).paint_with_opacity(
340                        shape,
341                        feedback.ripple.as_ref(),
342                        layer,
343                        cx.background_executor().now(),
344                        reduced,
345                        window,
346                    );
347                }
348            },
349        )
350        .absolute()
351        .inset_0()
352        .size_full();
353        let surface = div()
354            .id("card-surface")
355            .relative()
356            .text_color(foreground)
357            .w_full()
358            .p(px(16.) + border_width)
359            .flex()
360            .flex_col()
361            .gap(px(8.))
362            .child(visual)
363            .children(self.children);
364        match self.activation {
365            Some((name, activate)) => {
366                let activate = Rc::new(ThemeScope::bind_action(
367                    move |window, cx| activate(window, cx),
368                    window,
369                    cx,
370                ));
371                let invoke = activate.clone();
372                let press = feedback.clone();
373                gpui_base::Button::new(self.id)
374                    .track_focus(&focus)
375                    .tab_stop(true)
376                    .disabled(self.disabled)
377                    .w_full()
378                    .border_2()
379                    .border_color(gpui::transparent_black())
380                    .accessibility_label(name)
381                    .when(enabled && !dragged, |control| {
382                        feedback_target(control, feedback, true, Some(focus))
383                    })
384                    .when(enabled, |control| {
385                        control
386                            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
387                                if !dragged {
388                                    invoke(window, cx);
389                                }
390                            })
391                            .on_click(move |event, window, cx| {
392                                cx.stop_propagation();
393                                let native_drag =
394                                    matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag();
395                                if !native_drag && !press.borrow().blocks_activation(event) {
396                                    activate_feedback(event, &press, window, cx);
397                                    activate(window, cx);
398                                }
399                            })
400                    })
401                    .child(surface)
402                    .into_any_element()
403            }
404            None => div()
405                .id(self.id)
406                .test_support()
407                .role(Role::Group)
408                .child(surface)
409                .into_any_element(),
410        }
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use Elevation::*;
418
419    #[test]
420    fn elevation_overrides_resolve_each_state_and_precedence() {
421        let levels = CardElevations {
422            resting: Some(Level0),
423            hovered: Some(Level1),
424            focused: Some(Level2),
425            pressed: Some(Level3),
426            dragged: Some(Level4),
427            disabled: Some(Level5),
428        };
429        for variant in [
430            CardVariant::Elevated,
431            CardVariant::Filled,
432            CardVariant::Outlined,
433        ] {
434            let mut state = InteractionState::default();
435            assert_eq!(levels.resolve(variant, state), Level0);
436            state.hovered = true;
437            assert_eq!(levels.resolve(variant, state), Level1);
438            state.focus_visible = true;
439            assert_eq!(levels.resolve(variant, state), Level2);
440            state.pressed = true;
441            assert_eq!(levels.resolve(variant, state), Level3);
442            state.dragged = true;
443            assert_eq!(levels.resolve(variant, state), Level4);
444            state.disabled = true;
445            assert_eq!(levels.resolve(variant, state), Level5);
446        }
447    }
448
449    #[test]
450    fn omitted_elevations_keep_the_pinned_variant_values() {
451        let levels = CardElevations::default();
452        for (variant, resting, hovered, dragged) in [
453            (CardVariant::Elevated, Level1, Level2, Level4),
454            (CardVariant::Filled, Level0, Level1, Level3),
455            (CardVariant::Outlined, Level0, Level0, Level3),
456        ] {
457            let mut state = InteractionState::default();
458            assert_eq!(levels.resolve(variant, state), resting);
459            state.hovered = true;
460            assert_eq!(levels.resolve(variant, state), hovered);
461            state.focus_visible = true;
462            assert_eq!(levels.resolve(variant, state), resting);
463            state.pressed = true;
464            assert_eq!(levels.resolve(variant, state), resting);
465            state.dragged = true;
466            assert_eq!(levels.resolve(variant, state), dragged);
467            state.disabled = true;
468            assert_eq!(levels.resolve(variant, state), resting);
469        }
470    }
471
472    #[test]
473    fn card_variant_shorthands_set_expected_variants() {
474        assert_eq!(Card::elevated("c1").variant, CardVariant::Elevated);
475        assert_eq!(Card::filled("c2").variant, CardVariant::Filled);
476        assert_eq!(Card::outlined("c3").variant, CardVariant::Outlined);
477    }
478}