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