Skip to main content

gpui_material_foundation/
surface.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, ElementId, Entity, FocusHandle, Hsla, IntoElement,
5    ParentElement, Pixels, RenderOnce, Rgba, Role, SharedString, StatefulInteractiveElement,
6    StyleRefinement, Styled, Toggled, Window, canvas, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button, StyledExt};
9use gpui_material_theme::{Argb, ColorRole, CornerShape, Direction, Elevation, MaterialTheme};
10
11use crate::{
12    InteractionFeedback, InteractionSource, Shape,
13    control_feedback::{activate_feedback, feedback_target, ripple_state},
14    window_material_theme,
15};
16
17/// Converts Material's packed sRGB color and preserves its alpha channel.
18pub fn color(argb: Argb) -> Hsla {
19    let [a, r, g, b] = argb.channels().map(|channel| f32::from(channel) / 255.);
20    Rgba { r, g, b, a }.into()
21}
22
23/// Resolves the Material scrim color for an overlay that owns dismissal and focus.
24pub fn scrim_color(theme: &MaterialTheme, opacity: f32) -> Hsla {
25    color(theme.colors.color(ColorRole::Scrim)).opacity(opacity.clamp(0., 1.))
26}
27
28/// Desktop shadow projection shared by surfaces and custom-painted controls.
29/// `elevation` is in Material logical units; `scale` follows the component geometry.
30/// Compose delegates shadows to its platform renderer; GPUI uses these two layers.
31pub fn elevation_shadows(elevation: f32, scale: f32, shadow: Hsla) -> Vec<gpui::BoxShadow> {
32    let dp = elevation * scale;
33    if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
34        return Vec::new();
35    }
36    vec![
37        gpui_base::box_shadow(0., dp * 0.4, dp, 0., shadow.opacity(0.18)),
38        gpui_base::box_shadow(0., scale, dp * 0.5, 0., shadow.opacity(0.13)),
39    ]
40}
41
42/// An outline in logical pixels, drawn around the surface's shape.
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct SurfaceBorder {
45    pub width: Pixels,
46    pub color: Hsla,
47}
48
49/// Customizes the Material feedback painted by one interactive surface.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct SurfaceFeedback {
52    pub state_layer: bool,
53    pub ripple: bool,
54    pub focus_ring: bool,
55    pub ink: Option<Hsla>,
56    pub focus_color: Option<Hsla>,
57}
58
59impl Default for SurfaceFeedback {
60    fn default() -> Self {
61        Self {
62            state_layer: true,
63            ripple: true,
64            focus_ring: true,
65            ink: None,
66            focus_color: None,
67        }
68    }
69}
70
71#[derive(Clone, Copy)]
72enum SurfaceAction {
73    Activate,
74    Select(bool),
75    Check(bool),
76}
77
78type Activate = Rc<dyn Fn(&mut Window, &mut App)>;
79
80struct Control {
81    id: ElementId,
82    label: SharedString,
83    action: SurfaceAction,
84    activate: Option<Activate>,
85}
86
87/// A passive Material background or an interactive surface with arbitrary children.
88#[derive(IntoElement)]
89pub struct Surface {
90    style: StyleRefinement,
91    children: Vec<AnyElement>,
92    role: ColorRole,
93    container_color: Option<Hsla>,
94    content_color: Option<Hsla>,
95    inherit_content_color: bool,
96    shape: Option<CornerShape>,
97    border: Option<SurfaceBorder>,
98    tonal_elevation: Elevation,
99    shadow_elevation: Elevation,
100    shadow_scale: f32,
101    theme: Option<MaterialTheme>,
102    control: Option<Control>,
103    disabled: bool,
104    focus: Option<FocusHandle>,
105    feedback: SurfaceFeedback,
106    interaction_source: Option<Entity<InteractionSource>>,
107}
108
109impl Surface {
110    pub fn new(role: ColorRole) -> Self {
111        Self {
112            style: StyleRefinement::default(),
113            children: Vec::new(),
114            role,
115            container_color: None,
116            content_color: None,
117            inherit_content_color: false,
118            shape: None,
119            border: None,
120            tonal_elevation: Elevation::Level0,
121            shadow_elevation: Elevation::Level0,
122            shadow_scale: 1.,
123            theme: None,
124            control: None,
125            disabled: false,
126            focus: None,
127            feedback: SurfaceFeedback::default(),
128            interaction_source: None,
129        }
130    }
131
132    pub fn clickable(
133        id: impl Into<ElementId>,
134        label: impl Into<SharedString>,
135        role: ColorRole,
136    ) -> Self {
137        Self::interactive(id, label, role, SurfaceAction::Activate)
138    }
139
140    /// Renders the caller's selection and requests activation through on_activate.
141    pub fn selectable(
142        id: impl Into<ElementId>,
143        label: impl Into<SharedString>,
144        role: ColorRole,
145        selected: bool,
146    ) -> Self {
147        Self::interactive(id, label, role, SurfaceAction::Select(selected))
148    }
149
150    /// Renders the caller's check state and requests the next value through on_checked_change.
151    pub fn toggleable(
152        id: impl Into<ElementId>,
153        label: impl Into<SharedString>,
154        role: ColorRole,
155        checked: bool,
156    ) -> Self {
157        Self::interactive(id, label, role, SurfaceAction::Check(checked))
158    }
159
160    fn interactive(
161        id: impl Into<ElementId>,
162        label: impl Into<SharedString>,
163        role: ColorRole,
164        action: SurfaceAction,
165    ) -> Self {
166        Self {
167            control: Some(Control {
168                id: id.into(),
169                label: label.into(),
170                action,
171                activate: None,
172            }),
173            ..Self::new(role)
174        }
175    }
176
177    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
178        if let Some(control) = &mut self.control {
179            control.activate = Some(Rc::new(handler));
180        }
181        self
182    }
183
184    pub fn on_checked_change(
185        mut self,
186        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
187    ) -> Self {
188        if let Some(control) = &mut self.control
189            && let SurfaceAction::Check(checked) = control.action
190        {
191            control.activate = Some(Rc::new(move |window, cx| handler(!checked, window, cx)));
192        }
193        self
194    }
195
196    pub fn disabled(mut self, disabled: bool) -> Self {
197        self.disabled = disabled;
198        self
199    }
200
201    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
202        self.focus = Some(focus.clone());
203        self
204    }
205
206    pub fn feedback(mut self, feedback: SurfaceFeedback) -> Self {
207        self.feedback = feedback;
208        self
209    }
210
211    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
212        self.interaction_source = Some(source.clone());
213        self
214    }
215
216    /// Uses an explicit fill and inherits the foreground unless one is supplied.
217    pub fn container_color(mut self, color: Hsla) -> Self {
218        self.container_color = Some(color);
219        self
220    }
221
222    /// Sets the inherited foreground for this surface's children.
223    pub fn content_color(mut self, color: Hsla) -> Self {
224        self.content_color = Some(color);
225        self
226    }
227
228    /// Uses the ancestor text color unless this surface supplies an explicit foreground.
229    pub fn inherit_content_color(mut self, inherit: bool) -> Self {
230        self.inherit_content_color = inherit;
231        self
232    }
233
234    pub fn shape(mut self, shape: CornerShape) -> Self {
235        self.shape = Some(shape);
236        self
237    }
238
239    pub fn border(mut self, border: SurfaceBorder) -> Self {
240        self.border = Some(border);
241        self
242    }
243
244    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
245        self.tonal_elevation = elevation;
246        self
247    }
248
249    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
250        self.shadow_elevation = elevation;
251        self
252    }
253
254    /// Scales the offset and blur radius with an animated surface.
255    pub fn shadow_scale(mut self, scale: f32) -> Self {
256        self.shadow_scale = scale;
257        self
258    }
259
260    /// Uses an explicit window or subtree theme for this surface.
261    pub fn with_theme(mut self, theme: MaterialTheme) -> Self {
262        self.theme = Some(theme);
263        self
264    }
265}
266
267impl ParentElement for Surface {
268    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
269        self.children.extend(elements);
270    }
271}
272
273impl Styled for Surface {
274    fn style(&mut self) -> &mut StyleRefinement {
275        &mut self.style
276    }
277}
278
279impl RenderOnce for Surface {
280    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
281        let theme = self
282            .theme
283            .as_ref()
284            .unwrap_or_else(|| window_material_theme(window, cx));
285        let scheme = &theme.colors;
286        let default_focus = color(scheme.color(ColorRole::Secondary));
287        let background = if self.role == ColorRole::Surface {
288            scheme.surface_at_elevation(self.tonal_elevation)
289        } else {
290            scheme.color(self.role)
291        };
292        let direction = theme.layout.direction;
293        let background = self.container_color.unwrap_or_else(|| color(background));
294        let foreground = self.content_color.or_else(|| {
295            if self.inherit_content_color || self.container_color.is_some() {
296                return None;
297            }
298            scheme.pair(self.role).map(|pair| color(pair.foreground))
299        });
300        self.style.background = Some(background.into());
301        if let Some(foreground) = foreground {
302            self.style.text.color = Some(foreground);
303        }
304        let shadows = elevation_shadows(
305            self.shadow_elevation.dp(),
306            self.shadow_scale,
307            color(scheme.color(ColorRole::Shadow)),
308        );
309        if !shadows.is_empty() {
310            self.style.box_shadow = Some(shadows);
311        }
312        if let Some(shape) = self.shape {
313            if shape == CornerShape::Full {
314                self = self.rounded_full();
315            } else {
316                let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
317                self = self
318                    .rounded_tl(px(tl))
319                    .rounded_tr(px(tr))
320                    .rounded_br(px(br))
321                    .rounded_bl(px(bl));
322            }
323        }
324        if let Some(border) = self.border {
325            let border_width = if f32::from(border.width).is_finite() {
326                border.width.max(px(0.))
327            } else {
328                px(0.)
329            };
330            let width = Some(border_width.into());
331            self.style.border_widths.top = width;
332            self.style.border_widths.right = width;
333            self.style.border_widths.bottom = width;
334            self.style.border_widths.left = width;
335            self.style.border_color = Some(if border_width > px(0.) {
336                border.color
337            } else {
338                gpui::transparent_black()
339            });
340        }
341        let Some(control) = self.control.take() else {
342            return div()
343                .refine_style(&self.style)
344                .children(self.children)
345                .into_any_element();
346        };
347        self.render_control(control, direction, default_focus, window, cx)
348    }
349}
350
351impl Surface {
352    fn render_control(
353        self,
354        control: Control,
355        direction: Direction,
356        default_focus: Hsla,
357        window: &mut Window,
358        cx: &mut App,
359    ) -> AnyElement {
360        let focus = self.focus.unwrap_or_else(|| {
361            window
362                .use_keyed_state((control.id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
363                .read(cx)
364                .clone()
365        });
366        let state = ripple_state(&control.id, !self.disabled, window, cx);
367        let tracker = self
368            .interaction_source
369            .as_ref()
370            .map(|source| InteractionSource::track(source, &control.id, window, cx));
371        let interaction = state
372            .borrow_mut()
373            .track(!self.disabled, &focus, tracker, window, cx);
374        let (shape, shape_direction) = if let Some(shape) = self.shape {
375            (shape, direction)
376        } else {
377            let radii = &self.style.corner_radii;
378            let radius = |value: Option<gpui::AbsoluteLength>| {
379                value.map_or(0., |value| value.to_pixels(window.rem_size()).into())
380            };
381            (
382                CornerShape::Radii([
383                    radius(radii.top_left),
384                    radius(radii.top_right),
385                    radius(radii.bottom_right),
386                    radius(radii.bottom_left),
387                ]),
388                Direction::Ltr,
389            )
390        };
391        let appearance = self.feedback;
392        let ink = appearance
393            .ink
394            .or(self.style.text.color)
395            .unwrap_or_else(|| window.text_style().color);
396        let ring = if appearance.focus_ring {
397            appearance.focus_color.unwrap_or(default_focus)
398        } else {
399            gpui::transparent_black()
400        };
401        let geometry = state.clone();
402        let paint = state.clone();
403        let visual = canvas(
404            move |bounds, window, _| {
405                geometry
406                    .borrow_mut()
407                    .set_shape(Shape::rounded(bounds, shape, shape_direction), window);
408            },
409            move |_, _, window, cx| {
410                let state = paint.borrow();
411                if let Some(shape) = &state.shape {
412                    let reduced = cx.reduce_motion();
413                    let ripple = state.ripple.as_ref().filter(|_| appearance.ripple);
414                    let layer = interaction
415                        .layer_with_ripple(reduced || !appearance.ripple)
416                        .filter(|_| appearance.state_layer)
417                        .map_or(0., |layer| layer.opacity());
418                    InteractionFeedback::new(interaction, ink, ring).paint_with_opacity(
419                        shape,
420                        ripple,
421                        layer,
422                        cx.background_executor().now(),
423                        reduced,
424                        window,
425                    );
426                }
427            },
428        )
429        .absolute()
430        .inset_0();
431        let button = Button::new(control.id)
432            .block()
433            .items_stretch()
434            .justify_start()
435            .line_height(window.text_style().line_height)
436            .refine_style(&self.style)
437            .accessibility_label(control.label)
438            .track_focus(&focus)
439            .disabled(self.disabled);
440        let button = match control.action {
441            SurfaceAction::Activate => button,
442            SurfaceAction::Select(value) => button.role(Role::ListBoxOption).aria_selected(value),
443            SurfaceAction::Check(value) => button.role(Role::CheckBox).aria_toggled(if value {
444                Toggled::True
445            } else {
446                Toggled::False
447            }),
448        };
449        let button = if let Some(activate) = control.activate.filter(|_| !self.disabled) {
450            let accessible = activate.clone();
451            let feedback = state.clone();
452            button
453                .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
454                    accessible(window, cx);
455                })
456                .on_click(move |event, window, cx| {
457                    cx.stop_propagation();
458                    if !feedback.borrow().blocks_activation(event) {
459                        activate_feedback(event, &feedback, window, cx);
460                        activate(window, cx);
461                    }
462                })
463        } else {
464            button
465        };
466        button
467            .when(!self.disabled, |button| {
468                feedback_target(button, state, true, Some(focus))
469            })
470            .children(self.children)
471            .child(visual)
472            .into_any_element()
473    }
474}