Skip to main content

gpui_material_foundation/
overlay.rs

1use std::rc::Rc;
2
3use gpui::{
4    Anchor, App, Div, ElementId, Hsla, InteractiveElement, IntoElement, RenderOnce, Role,
5    ScrollHandle, SharedString, Stateful, StatefulInteractiveElement, Styled, Window,
6    accesskit::Action, div,
7};
8use gpui_material_theme::Direction;
9
10use crate::{current_material_theme, scrim_color};
11
12type ScrimClick = Rc<dyn Fn(&mut Window, &mut App)>;
13
14/// A backdrop that fills its positioned parent. Add it after background content
15/// and before the foreground surface. The caller owns visibility and modal focus.
16#[derive(IntoElement)]
17pub struct Scrim {
18    id: ElementId,
19    color: Option<Hsla>,
20    opacity: f32,
21    accessibility_label: Option<SharedString>,
22    on_click: Option<ScrimClick>,
23}
24
25impl Scrim {
26    const DEFAULT_OPACITY: f32 = 0.32;
27
28    /// Creates a decorative backdrop with the current window's Scrim color role.
29    pub fn new(id: impl Into<ElementId>) -> Self {
30        Self {
31            id: id.into(),
32            color: None,
33            opacity: Self::DEFAULT_OPACITY,
34            accessibility_label: None,
35            on_click: None,
36        }
37    }
38
39    /// Uses a custom tint. The tint's own alpha multiplies the scrim opacity.
40    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
41        self.color = Some(color.into());
42        self
43    }
44
45    /// Sets opacity in the range 0–1, clamping values outside it. NaN uses 0.32.
46    pub fn opacity(mut self, opacity: f32) -> Self {
47        self.opacity = if opacity.is_nan() {
48            Self::DEFAULT_OPACITY
49        } else {
50            opacity.clamp(0., 1.)
51        };
52        self
53    }
54
55    /// Names the clickable scrim for assistive technology. Defaults to “Dismiss overlay.”
56    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
57        self.accessibility_label = Some(label.into());
58        self
59    }
60
61    /// Blocks pointer input behind the scrim and handles click or accessibility activation.
62    /// Keep keyboard dismissal and focus management in the foreground surface.
63    pub fn on_click(mut self, on_click: impl Fn(&mut Window, &mut App) + 'static) -> Self {
64        self.on_click = Some(Rc::new(on_click));
65        self
66    }
67}
68
69impl RenderOnce for Scrim {
70    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
71        let fill = self.color.map_or_else(
72            || scrim_color(&current_material_theme(window, cx), self.opacity),
73            |color| color.opacity(self.opacity),
74        );
75        let backdrop = div().id(self.id).absolute().inset_0().bg(fill);
76        match self.on_click {
77            Some(on_click) => {
78                let on_accessibility_click = on_click.clone();
79                backdrop
80                    .occlude()
81                    .role(Role::Button)
82                    .aria_label(
83                        self.accessibility_label
84                            .unwrap_or_else(|| "Dismiss overlay".into()),
85                    )
86                    // GPUI's default accessibility click targets the center,
87                    // where the foreground surface may cover the scrim.
88                    .on_a11y_action(Action::Click, move |_, window, cx| {
89                        on_accessibility_click(window, cx);
90                    })
91                    .on_click(move |_, window, cx| {
92                        cx.stop_propagation();
93                        on_click(window, cx);
94                    })
95            }
96            None => backdrop,
97        }
98    }
99}
100
101/// Mirrors the horizontal part of an overlay anchor for logical direction.
102/// Base retains placement, fit, focus scope and dismissal.
103pub fn logical_anchor(anchor: Anchor, direction: Direction) -> Anchor {
104    if direction == Direction::Ltr {
105        return anchor;
106    }
107    match anchor {
108        Anchor::TopLeft => Anchor::TopRight,
109        Anchor::TopRight => Anchor::TopLeft,
110        Anchor::BottomLeft => Anchor::BottomRight,
111        Anchor::BottomRight => Anchor::BottomLeft,
112        Anchor::LeftCenter => Anchor::RightCenter,
113        Anchor::RightCenter => Anchor::LeftCenter,
114        Anchor::TopCenter | Anchor::BottomCenter => anchor,
115    }
116}
117
118/// Creates an inner vertical scroll viewport that keeps wheel input from
119/// reaching scroll owners behind it. The caller gives it a bounded height.
120pub fn isolated_scroll(id: impl Into<ElementId>, handle: &ScrollHandle) -> Stateful<Div> {
121    div()
122        .id(id)
123        .min_h_0()
124        .overflow_y_scroll()
125        .occlude()
126        .track_scroll(handle)
127}