Skip to main content

gpui_material_components/
menu_appearance.rs

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