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, _, _| {
278                geometry.borrow_mut().shape = if enabled && (actionable || dragged) {
279                    Shape::rounded(bounds, shape, direction)
280                } else {
281                    None
282                };
283                let [top_left, top_right, bottom_right, bottom_left] = shape
284                    .radii(
285                        f32::from(bounds.size.width),
286                        f32::from(bounds.size.height),
287                        direction,
288                    )
289                    .map(px);
290                Corners {
291                    top_left,
292                    top_right,
293                    bottom_right,
294                    bottom_left,
295                }
296            },
297            move |bounds, corners, window, cx| {
298                if elevation > 0. {
299                    window.paint_drop_shadows(
300                        bounds,
301                        corners,
302                        &elevation_shadows(elevation, 1., shadow),
303                    );
304                }
305                window.paint_quad(quad(
306                    bounds,
307                    corners,
308                    background,
309                    border_width,
310                    border_color,
311                    BorderStyle::Solid,
312                ));
313                let feedback = paint_feedback.borrow();
314                if let Some(shape) = &feedback.shape {
315                    InteractionFeedback::new(interaction, foreground, ring).paint_with_opacity(
316                        shape,
317                        feedback.ripple.as_ref(),
318                        layer,
319                        cx.background_executor().now(),
320                        reduced,
321                        window,
322                    );
323                }
324            },
325        )
326        .absolute()
327        .inset_0()
328        .size_full();
329        let surface = div()
330            .id("card-surface")
331            .relative()
332            .text_color(foreground)
333            .w_full()
334            .p(px(16.) + border_width)
335            .flex()
336            .flex_col()
337            .gap(px(8.))
338            .child(visual)
339            .children(self.children);
340        match self.activation {
341            Some((name, activate)) => {
342                let invoke = activate.clone();
343                let press = feedback.clone();
344                gpui_base::Button::new(self.id)
345                    .track_focus(&focus)
346                    .tab_stop(true)
347                    .disabled(self.disabled)
348                    .w_full()
349                    .border_2()
350                    .border_color(gpui::transparent_black())
351                    .accessibility_label(name)
352                    .when(enabled && !dragged, |control| {
353                        feedback_target(control, feedback, true, Some(focus))
354                    })
355                    .when(enabled, |control| {
356                        control
357                            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
358                                if !dragged {
359                                    invoke(window, cx);
360                                }
361                            })
362                            .on_click(move |event, window, cx| {
363                                cx.stop_propagation();
364                                let native_drag =
365                                    matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag();
366                                if !native_drag && !press.borrow().blocks_activation(event) {
367                                    activate_feedback(event, &press, window, cx);
368                                    activate(window, cx);
369                                }
370                            })
371                    })
372                    .child(surface)
373                    .into_any_element()
374            }
375            None => div()
376                .id(self.id)
377                .test_support()
378                .role(Role::Group)
379                .child(surface)
380                .into_any_element(),
381        }
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use Elevation::*;
389
390    #[test]
391    fn elevation_overrides_resolve_each_state_and_precedence() {
392        let levels = CardElevations {
393            resting: Some(Level0),
394            hovered: Some(Level1),
395            focused: Some(Level2),
396            pressed: Some(Level3),
397            dragged: Some(Level4),
398            disabled: Some(Level5),
399        };
400        for variant in [
401            CardVariant::Elevated,
402            CardVariant::Filled,
403            CardVariant::Outlined,
404        ] {
405            let mut state = InteractionState::default();
406            assert_eq!(levels.resolve(variant, state), Level0);
407            state.hovered = true;
408            assert_eq!(levels.resolve(variant, state), Level1);
409            state.focus_visible = true;
410            assert_eq!(levels.resolve(variant, state), Level2);
411            state.pressed = true;
412            assert_eq!(levels.resolve(variant, state), Level3);
413            state.dragged = true;
414            assert_eq!(levels.resolve(variant, state), Level4);
415            state.disabled = true;
416            assert_eq!(levels.resolve(variant, state), Level5);
417        }
418    }
419
420    #[test]
421    fn omitted_elevations_keep_the_pinned_variant_values() {
422        let levels = CardElevations::default();
423        for (variant, resting, hovered, dragged) in [
424            (CardVariant::Elevated, Level1, Level2, Level4),
425            (CardVariant::Filled, Level0, Level1, Level3),
426            (CardVariant::Outlined, Level0, Level0, Level3),
427        ] {
428            let mut state = InteractionState::default();
429            assert_eq!(levels.resolve(variant, state), resting);
430            state.hovered = true;
431            assert_eq!(levels.resolve(variant, state), hovered);
432            state.focus_visible = true;
433            assert_eq!(levels.resolve(variant, state), resting);
434            state.pressed = true;
435            assert_eq!(levels.resolve(variant, state), resting);
436            state.dragged = true;
437            assert_eq!(levels.resolve(variant, state), dragged);
438            state.disabled = true;
439            assert_eq!(levels.resolve(variant, state), resting);
440        }
441    }
442}