Skip to main content

gpui_material_components/
menu_appearance.rs

1use gpui::Pixels;
2#[cfg(any(feature = "inputs", feature = "feedback"))]
3use gpui::{Bounds, Div, Hsla, Point, Styled, div, point, px};
4#[cfg(any(feature = "inputs", feature = "feedback"))]
5use gpui_material_foundation::{OverlayMotion, color, elevation_shadows, resolve_edges};
6use gpui_material_theme::{ColorRole, CornerShape, Elevation, LogicalEdges};
7#[cfg(any(feature = "inputs", feature = "feedback"))]
8use gpui_material_theme::{CornerRole, Direction, MaterialTheme};
9
10#[cfg(any(feature = "inputs", feature = "feedback"))]
11pub(crate) fn menu_pivot(menu: Bounds<Pixels>, anchor: Bounds<Pixels>) -> Point<f32> {
12    fn axis(start: Pixels, end: Pixels, anchor_start: Pixels, anchor_end: Pixels) -> f32 {
13        if start >= anchor_end || start == end {
14            0.
15        } else if end <= anchor_start {
16            1.
17        } else {
18            ((start.max(anchor_start) + end.min(anchor_end)) / 2. - start) / (end - start)
19        }
20    }
21    point(
22        axis(menu.left(), menu.right(), anchor.left(), anchor.right()),
23        axis(menu.top(), menu.bottom(), anchor.top(), anchor.bottom()),
24    )
25}
26
27/// Semantic color presets for Material vertical menus.
28#[cfg(feature = "feedback")]
29#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
30pub enum MenuColor {
31    /// Neutral surface container palette (`SurfaceContainer` / `SurfaceContainerLow`).
32    #[default]
33    Standard,
34    /// Expressive tertiary container palette (`TertiaryContainer` / `OnTertiaryContainer`).
35    Vibrant,
36}
37
38/// Per-surface menu styling. Omitted values use defaults appropriate to the surface.
39#[derive(Clone, Copy, Debug, Default)]
40pub struct MenuSurfaceStyle {
41    /// The surface shape in logical corner order.
42    pub shape: Option<CornerShape>,
43    /// Theme color role for the menu container background.
44    pub container: Option<ColorRole>,
45    /// The logical thickness and Material role of the outline.
46    pub border: Option<(Pixels, ColorRole)>,
47    /// Tonal elevation applied when the container role is `ColorRole::Surface`.
48    pub tonal_elevation: Elevation,
49    /// Drop-shadow elevation level. Defaults to `Elevation::Level2` for menus and `Elevation::Level0` for groups.
50    pub shadow_elevation: Option<Elevation>,
51    /// Inner logical padding around menu items. Defaults to `8 dp` vertical for menus and `4 dp` vertical for groups.
52    pub padding: Option<LogicalEdges>,
53    /// Vertical gap between child items or groups. Defaults to `0 px` for menus and `2 px` for groups.
54    pub spacing: Option<Pixels>,
55}
56
57#[cfg(feature = "inputs")]
58impl MenuSurfaceStyle {
59    pub(crate) fn dropdown_surface(self, theme: &MaterialTheme, motion: OverlayMotion) -> Div {
60        let palette = Palette {
61            container: self.container.unwrap_or(ColorRole::SurfaceContainer),
62            ink: ColorRole::OnSurface,
63            #[cfg(feature = "feedback")]
64            muted: ColorRole::OnSurfaceVariant,
65            #[cfg(feature = "feedback")]
66            selected: ColorRole::SecondaryContainer,
67            #[cfg(feature = "feedback")]
68            selected_ink: ColorRole::OnSecondaryContainer,
69        };
70        Paint {
71            theme,
72            motion,
73            direction: theme.layout.direction,
74        }
75        .surface(self, palette, false)
76    }
77
78    pub(crate) fn popup_vertical_insets(self) -> Pixels {
79        let padding = self
80            .padding
81            .unwrap_or(LogicalEdges::symmetric(0., 8.))
82            .sanitize();
83        let length = |value: Pixels| {
84            if f32::from(value).is_finite() {
85                value.max(px(0.))
86            } else {
87                px(0.)
88            }
89        };
90        px(padding.top + padding.bottom)
91            + self.border.map_or(px(0.), |(width, _)| length(width) * 2.)
92    }
93}
94
95/// Per-row overrides. Unset shapes and colors follow the menu palette and layout.
96#[cfg(feature = "feedback")]
97#[derive(Clone, Copy, Debug, Default)]
98pub struct MenuItemStyle {
99    /// Logical corner shape for unselected menu rows.
100    pub shape: Option<CornerShape>,
101    /// Logical corner shape for selected menu rows.
102    pub selected_shape: Option<CornerShape>,
103    /// Inner logical padding of the menu row.
104    pub padding: Option<LogicalEdges>,
105    /// Horizontal gap between leading, label, and trailing slots.
106    pub spacing: Option<Pixels>,
107    /// Background color role for unselected rows.
108    pub container: Option<ColorRole>,
109    /// Primary label and icon color role for unselected rows.
110    pub content: Option<ColorRole>,
111    /// Supporting text and trailing metadata color role.
112    pub supporting: Option<ColorRole>,
113    /// Background color role for selected rows.
114    pub selected_container: Option<ColorRole>,
115    /// Primary label and icon color role for selected rows.
116    pub selected_content: Option<ColorRole>,
117}
118
119#[cfg(any(feature = "inputs", feature = "feedback"))]
120#[derive(Clone, Copy)]
121pub(crate) struct Palette {
122    pub(crate) container: ColorRole,
123    pub(crate) ink: ColorRole,
124    #[cfg(feature = "feedback")]
125    pub(crate) muted: ColorRole,
126    #[cfg(feature = "feedback")]
127    pub(crate) selected: ColorRole,
128    #[cfg(feature = "feedback")]
129    pub(crate) selected_ink: ColorRole,
130}
131
132#[cfg(feature = "feedback")]
133impl MenuColor {
134    pub(crate) fn palette(self, grouped: bool, container: Option<ColorRole>) -> Palette {
135        use ColorRole::*;
136        let (default_container, ink, muted, selected, selected_ink) = match (self, grouped) {
137            (Self::Standard, false) => (
138                SurfaceContainer,
139                OnSurface,
140                OnSurfaceVariant,
141                SecondaryContainer,
142                OnSecondaryContainer,
143            ),
144            (Self::Standard, true) => (
145                SurfaceContainerLow,
146                OnSurface,
147                OnSurfaceVariant,
148                TertiaryContainer,
149                OnTertiaryContainer,
150            ),
151            (Self::Vibrant, _) => (
152                TertiaryContainer,
153                OnTertiaryContainer,
154                OnTertiaryContainer,
155                Tertiary,
156                OnTertiary,
157            ),
158        };
159        Palette {
160            container: container.unwrap_or(default_container),
161            ink,
162            muted,
163            selected,
164            selected_ink,
165        }
166    }
167}
168
169#[cfg(any(feature = "inputs", feature = "feedback"))]
170#[derive(Clone, Copy)]
171pub(crate) struct Paint<'a> {
172    pub(crate) theme: &'a MaterialTheme,
173    pub(crate) motion: OverlayMotion,
174    pub(crate) direction: Direction,
175}
176
177#[cfg(any(feature = "inputs", feature = "feedback"))]
178impl Paint<'_> {
179    pub(crate) fn color(self, role: ColorRole) -> Hsla {
180        color(self.theme.colors.color(role))
181    }
182
183    pub(crate) fn padding<E: Styled>(self, element: E, padding: LogicalEdges) -> E {
184        let edges = resolve_edges(padding, self.direction);
185        element
186            .pt(self.length(edges.top))
187            .pr(self.length(edges.right))
188            .pb(self.length(edges.bottom))
189            .pl(self.length(edges.left))
190    }
191
192    pub(crate) fn length(self, value: Pixels) -> Pixels {
193        let value = f32::from(value);
194        self.motion
195            .px(if value.is_finite() { value.max(0.) } else { 0. })
196    }
197
198    pub(crate) fn shape<E: Styled>(self, element: E, shape: CornerShape) -> E {
199        if shape == CornerShape::Full {
200            return element.rounded_full();
201        }
202        let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, self.direction);
203        element
204            .rounded_tl(self.motion.px(tl))
205            .rounded_tr(self.motion.px(tr))
206            .rounded_br(self.motion.px(br))
207            .rounded_bl(self.motion.px(bl))
208    }
209
210    pub(crate) fn surface(self, style: MenuSurfaceStyle, palette: Palette, group: bool) -> Div {
211        let background = if palette.container == ColorRole::Surface {
212            color(
213                self.theme
214                    .colors
215                    .surface_at_elevation(style.tonal_elevation),
216            )
217        } else {
218            self.color(palette.container)
219        };
220        let shadow = style.shadow_elevation.unwrap_or(if group {
221            Elevation::Level0
222        } else {
223            Elevation::Level2
224        });
225        let surface = div()
226            .flex()
227            .flex_col()
228            .gap(self.length(style.spacing.unwrap_or(if group { px(2.) } else { px(0.) })))
229            .bg(background)
230            .text_color(self.color(palette.ink))
231            .shadow(elevation_shadows(
232                shadow.dp(),
233                self.motion.scale,
234                self.color(ColorRole::Shadow),
235            ));
236        let surface = if let Some((width, role)) = style.border {
237            let mut surface = surface.border_color(self.color(role));
238            let width = Some(self.length(width).into());
239            let borders = &mut surface.style().border_widths;
240            borders.top = width;
241            borders.right = width;
242            borders.bottom = width;
243            borders.left = width;
244            surface
245        } else {
246            surface
247        };
248        let surface = self.shape(
249            surface,
250            style.shape.unwrap_or_else(|| {
251                if group {
252                    CornerRole::Large.shape()
253                } else {
254                    CornerRole::ExtraSmall.shape()
255                }
256            }),
257        );
258        self.padding(
259            surface,
260            style
261                .padding
262                .unwrap_or_else(|| LogicalEdges::symmetric(0., if group { 4. } else { 8. })),
263        )
264    }
265}